import test from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { mkdtempSync, readdirSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, extname, join, relative } from "node:path"; import { createHttpServer, repoRootFrom } from "../src/gateway/http.js"; const ROOT = repoRootFrom(import.meta.url); const CLIENT_SRC = join(ROOT, "client", "src"); const PLAY_ENTRY = "/src/play/main.js"; const EDITOR_ENTRY = "/src/editor/main.js"; test("client modules do not re-export unbound names", () => { const offenders = []; for (const file of listJsFiles(CLIENT_SRC)) { const source = readFileSync(file, "utf8"); for (const name of unboundReexportLocals(source)) { offenders.push(`${relative(ROOT, file)}: export { ${name} } is not defined in module`); } } assert.deepEqual(offenders, []); }); test("client modules do not declare duplicate import bindings", () => { const offenders = []; for (const file of listJsFiles(CLIENT_SRC)) { const source = readFileSync(file, "utf8"); for (const name of duplicateImportBindings(source)) { offenders.push(`${relative(ROOT, file)}: duplicate import binding '${name}'`); } } assert.deepEqual(offenders, []); }); test("HTTP smoke: play, editor, and module graph resolve", async () => { const server = createHttpServer(ROOT); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const { port } = server.address(); const base = `http://127.0.0.1:${port}`; try { assert.equal((await fetch(`${base}/`)).status, 200); assert.equal((await fetch(`${base}/editor`)).status, 200); assert.equal((await fetch(`${base}/framework/framework.js`)).status, 200); assert.equal((await fetch(`${base}/assets/catalog.json`)).status, 200); const playHtml = await (await fetch(`${base}/`)).text(); assert.match(playHtml, /src="\/src\/play\/main\.js"/); const editorHtml = await (await fetch(`${base}/editor`)).text(); assert.match(editorHtml, /src="\/src\/editor\/main\.js"/); const seen = new Set(); await crawlModuleGraph(base, PLAY_ENTRY, seen); await crawlModuleGraph(base, EDITOR_ENTRY, seen); assert.ok(seen.has(PLAY_ENTRY)); assert.ok(seen.has(EDITOR_ENTRY)); assert.ok(seen.size > 20, `expected a substantial module graph, got ${seen.size}`); } finally { await new Promise((resolve) => server.close(resolve)); } }); test("server process boots and serves play + editor", async () => { const dataDir = mkdtempSync(join(tmpdir(), "questward-smoke-")); const port = await freePort(); const child = spawn( process.execPath, ["--experimental-sqlite", join(ROOT, "server", "src", "index.js")], { cwd: ROOT, env: { ...process.env, PORT: String(port), QUESTWARD_DATA_DIR: dataDir, QUESTWARD_DEPLOY_SCHEDULER: "0", QUESTWARD_AUTH_STUB: "1", SIMULATION_WORKERS: "1", SIMULATION_WORKER_MODE: "inprocess" }, stdio: ["ignore", "pipe", "pipe"] } ); let stdout = ""; let stderr = ""; child.stdout.on("data", (chunk) => { stdout += chunk; }); child.stderr.on("data", (chunk) => { stderr += chunk; }); let exitCode = null; child.on("exit", (code) => { exitCode = code; }); try { await waitFor( () => /Questward listening/.test(stdout + stderr), () => { if (exitCode != null) { throw new Error( `Server exited early (${exitCode}). Output:\n${stdout}\n${stderr}` ); } }, 20_000 ); const base = `http://127.0.0.1:${port}`; assert.equal((await fetch(`${base}/`)).status, 200); assert.equal((await fetch(`${base}/editor`)).status, 200); assert.equal((await fetch(`${base}${PLAY_ENTRY}`)).status, 200); assert.equal((await fetch(`${base}${EDITOR_ENTRY}`)).status, 200); } finally { if (exitCode == null) { child.kill("SIGTERM"); await new Promise((resolve) => { const timer = setTimeout(() => { child.kill("SIGKILL"); resolve(); }, 5_000); child.on("exit", () => { clearTimeout(timer); resolve(); }); }); } } assert.doesNotMatch(stderr, /SyntaxError|Export '.*' is not defined/); assert.doesNotMatch(stdout, /SyntaxError|Export '.*' is not defined/); }); async function crawlModuleGraph (base, urlPath, seen) { if (seen.has(urlPath)) { return; } seen.add(urlPath); const res = await fetch(`${base}${urlPath}`); assert.equal(res.status, 200, `missing module ${urlPath}`); const type = res.headers.get("content-type") ?? ""; assert.match(type, /javascript|ecmascript/, `${urlPath} content-type ${type}`); const source = await res.text(); for (const name of unboundReexportLocals(source)) { assert.fail(`${urlPath}: export { ${name} } is not defined in module`); } for (const name of duplicateImportBindings(source)) { assert.fail(`${urlPath}: duplicate import binding '${name}'`); } for (const spec of staticImportSpecifiers(source)) { const next = resolveBrowserSpecifier(urlPath, spec); if (!next) { continue; } await crawlModuleGraph(base, next, seen); } } function resolveBrowserSpecifier (fromPath, spec) { if (spec.startsWith("/")) { return spec.split("?")[0]; } if (!spec.startsWith(".")) { return null; } const fromDir = dirname(fromPath); const parts = [...fromDir.split("/").filter(Boolean)]; for (const part of spec.split("/")) { if (part === "." || part === "") { continue; } if (part === "..") { parts.pop(); } else { parts.push(part); } } return `/${parts.join("/")}`; } function staticImportSpecifiers (source) { const specs = []; const cleaned = stripComments(source); for (const match of cleaned.matchAll(/\b(?:import|export)\s+(?:[^'";]*?\s+from\s+)?["']([^"']+)["']/g)) { specs.push(match[1]); } for (const match of cleaned.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g)) { specs.push(match[1]); } return specs; } function unboundReexportLocals (source) { const cleaned = stripComments(source); const defined = new Set([ ...importedBindings(cleaned), ...localBindings(cleaned) ]); const missing = []; for (const match of cleaned.matchAll(/\bexport\s*\{([^}]+)\}(\s*from\s*["'][^"']+["'])?/g)) { if (match[2]) { continue; } for (const part of match[1].split(",")) { const trimmed = part.trim(); if (!trimmed) { continue; } const local = trimmed.split(/\s+as\s+/)[0].trim(); if (!local || local === "default") { continue; } if (!defined.has(local)) { missing.push(local); } } } return missing; } /** Local names imported more than once in the same module (SyntaxError in browsers). */ function duplicateImportBindings (source) { const cleaned = stripComments(source); const counts = new Map(); const note = (name) => { if (!name || name === "default") { return; } counts.set(name, (counts.get(name) ?? 0) + 1); }; for (const match of cleaned.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g)) { for (const part of match[1].split(",")) { const trimmed = part.trim(); if (!trimmed) { continue; } const bits = trimmed.split(/\s+as\s+/); note(bits[bits.length - 1].trim()); } } for (const match of cleaned.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s*from\s*["']/g)) { note(match[1]); for (const part of match[2].split(",")) { const trimmed = part.trim(); if (!trimmed) { continue; } const bits = trimmed.split(/\s+as\s+/); note(bits[bits.length - 1].trim()); } } for (const match of cleaned.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) { note(match[1]); } for (const match of cleaned.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) { note(match[1]); } return [...counts.entries()] .filter(([, count]) => count > 1) .map(([name]) => name); } function importedBindings (source) { const names = new Set(); for (const match of source.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g)) { for (const part of match[1].split(",")) { const trimmed = part.trim(); if (!trimmed) { continue; } const bits = trimmed.split(/\s+as\s+/); names.add(bits[bits.length - 1].trim()); } } for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{/g)) { names.add(match[1]); } for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) { names.add(match[1]); } for (const match of source.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) { names.add(match[1]); } return names; } function localBindings (source) { const names = new Set(); for (const match of source.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g)) { names.add(match[1]); } for (const match of source.matchAll(/\bclass\s+([A-Za-z_$][\w$]*)/g)) { names.add(match[1]); } for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g)) { names.add(match[1]); } return names; } function stripComments (source) { return source .replace(/\/\*[\s\S]*?\*\//g, "") .replace(/(^|[^:])\/\/.*$/gm, "$1"); } function listJsFiles (dir) { const out = []; for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name); if (entry.isDirectory()) { out.push(...listJsFiles(path)); } else if (extname(entry.name) === ".js") { out.push(path); } } return out; } function freePort () { return new Promise((resolve, reject) => { const server = createHttpServer(ROOT); server.listen(0, "127.0.0.1", () => { const { port } = server.address(); server.close((error) => (error ? reject(error) : resolve(port))); }); }); } function waitFor (isReady, onTick, timeoutMs) { const started = Date.now(); return new Promise((resolve, reject) => { const tick = () => { try { onTick?.(); } catch (error) { reject(error); return; } if (isReady()) { resolve(); return; } if (Date.now() - started > timeoutMs) { reject(new Error(`Timed out after ${timeoutMs}ms`)); return; } setTimeout(tick, 50); }; tick(); }); }