test: restore executed and real-tsc coverage lost when the old api-block tests were deleted

Fix round 1: the deleted api-block-*.test.ts files were not fully superseded
by the apis-* siblings as claimed. Ports back, using apis {} fixtures:
- brace-inside-a-string-literal response-section scanner regression test
- type erasure of response/error bodies before browser emission
- client-side response-error-not-swallowed / transport-failure-fallback,
  executed via dynamic import of a generated browser module
- the full SSR execution suite: response payload binding, error section
  status/message/data binding, {#each} failure propagation, all executed
  via dynamic import + a real load/api call chain (not string checks)
- the four real-tsc enforcement tests (matching/wrong-type/extra-field/
  missing-field), plus the B1 cross-page collision guard and the B6
  export-for-noUnusedLocals guard

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-20 08:14:16 +05:30
co-authored by Claude Opus 5
parent 890d6106b3
commit 0ed8351828
4 changed files with 737 additions and 2 deletions
+240
View File
@@ -46,3 +46,243 @@ test("a block with no declared fields gets no assertion", () => {
expect(generated).not.toContain("listAll");
});
test("emits the ApiInput, ApiOutput and AssertAssignable helpers", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string; age?: number } }
response { return data.users }
}`);
generateApplicationTypes(root);
const generated = readFileSync(join(root, "app/types/wrnexus.generated.d.ts"), "utf8");
expect(generated).toContain("type AssertAssignable<");
expect(generated).toContain('type ApiInput<P extends ApiRoute, M> = ApiContracts[P][M]["input"]');
expect(generated).toContain(
'type ApiOutput<P extends ApiRoute, M> = ApiContracts[P][M]["output"]',
);
});
// The per-block assertions live in a plain .ts file, not the .d.ts: `skipLibCheck: true`
// (set repo-wide) exempts .d.ts *contents* from being checked at all, so a `.d.ts` can
// never actually enforce anything here. A real .ts file under app/ is compiled and
// checked normally.
test("emits one assertion per sectioned block, naming its route and method", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string; age?: number } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
expect(checks).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
expect(checks).toContain('WRNexusGenerated.ApiInput<"/api/users", "POST">');
expect(checks).toContain("name?: string");
expect(checks).toContain("age?: number");
});
test("the api-checks file has no runtime code and is a module", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
expect(checks).toContain("AUTO-GENERATED");
expect(checks.trim().endsWith("export {};")).toBe(true);
});
test("B1: two pages each declaring a block with the same name do not collide", () => {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-types-collide-"));
roots.push(root);
mkdirSync(join(root, "app/pages"), { recursive: true });
mkdirSync(join(root, "app/api"), { recursive: true });
writeFileSync(
join(root, "app/api/users.ts"),
`export const POST = async () => Response.json({ users: [] });\n`,
);
const block = ` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`;
writeFileSync(
join(root, "app/pages/one.wrn"),
`page One {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
writeFileSync(
join(root, "app/pages/two.wrn"),
`page Two {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const names = [...checks.matchAll(/__wrn_api_check_\S+(?=\s*=)/g)].map((m) => m[0]);
expect(names.length).toBe(2);
expect(new Set(names).size).toBe(2);
});
test("B6: each emitted assertion is exported, so noUnusedLocals cannot flag it", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const assertionLine = checks
.split(/\r?\n/)
.find((line) => line.includes("__wrn_api_check_") && line.includes("="));
expect(assertionLine).toBeDefined();
expect(assertionLine).toMatch(/^export type __wrn_api_check_/);
});
// --- Real-compiler enforcement tests ---------------------------------------------
//
// Everything above only asserts on the emitted *text*. That proves nothing about
// whether the assertions actually make `tsc` fail — a build that reverted to the
// original inert `never`-based design, or one where `AssertAssignable` is merely
// one-directional (so it misses an *extra* declared field), would pass every test
// above unchanged. These tests instead run the real TypeScript compiler over the
// generated output and assert on its diagnostics.
//
// The fixture endpoint takes a second (body) parameter so `ApiContract`'s fallback
// branch infers a real input type (`{ name: string; email: string }`) instead of
// `unknown` — with `unknown`, `AssertAssignable`'s untyped-route bypass means nothing
// could ever fail, which would make these tests meaningless.
function typedFixture(block: string): string {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-types-tsc-"));
roots.push(root);
mkdirSync(join(root, "app/pages"), { recursive: true });
mkdirSync(join(root, "app/api"), { recursive: true });
writeFileSync(
join(root, "app/api/users.ts"),
`export const POST = async (ctx: unknown, body: { name: string; email: string }) => Response.json(body);\n`,
);
writeFileSync(
join(root, "app/pages/search.wrn"),
`page Search {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
return root;
}
/**
* Compiles the two generated files (and whatever they reference on disk) with the
* real TypeScript compiler and returns its stdout plus whether it reported any
* diagnostics.
*/
function typecheckGenerated(root: string): { ok: boolean; output: string } {
const dts = join(root, "app/types/wrnexus.generated.d.ts");
const checks = join(root, "app/types/wrnexus.generated.api-checks.ts");
const result = Bun.spawnSync(
[
"bunx",
"tsc",
"--noEmit",
"--strict",
"--skipLibCheck",
"--moduleResolution",
"bundler",
"--target",
"ES2022",
"--module",
"ESNext",
dts,
checks,
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
const output = `${result.stdout?.toString() ?? ""}${result.stderr?.toString() ?? ""}`;
return { ok: result.exitCode === 0, output };
}
const MATCHING_BLOCK = ` searchUsers POST /api/users {
request {
body {
name: string
email: string
}
}
response {
return data
}
}`;
test("tsc: a block whose fields match the contract has no diagnostics", () => {
const root = typedFixture(MATCHING_BLOCK);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(output.trim()).toBe("");
expect(ok).toBe(true);
});
test("tsc: a field with the wrong type fails, naming the block's assertion", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: number
email: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});
test("tsc: an extra field the contract does not accept fails (Finding A regression guard)", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: string
email: string
extra: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});
test("tsc: a missing required field fails", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});
+188 -1
View File
@@ -1,7 +1,15 @@
import { expect, test } from "bun:test";
import { afterEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse } from "@wrnexus/syntax";
import { generateTargets } from "../src/targets.ts";
const roots: string[] = [];
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
const withCalls = (calls: string) => `page Probe {
apis {
used POST /api/used {
@@ -98,3 +106,182 @@ test("the word 'api' inside a comment or string literal does not trigger the dyn
),
).not.toThrow();
});
test("type annotations in response/error bodies are erased before emission (B4)", () => {
// Every other browser-bound body in the repo passes through eraseFunctionTypes
// (see the fn.body call sites in client-codegen.ts and store-codegen.ts);
// response/error bodies must too, for the same reason: eraseFunctionTypes
// strips function-signature annotations (params, return type, typed catch
// clauses) so a locally-declared helper function inside a response/error
// body no longer ships raw TypeScript into the .mjs artifact.
const browser = generateTargets(
parse(`page Probe {
apis {
searchUsers POST /api/users {
request { body { name?: string } }
response {
function pick(list: string[]): string[] { return list }
return pick(data.users)
}
error {
function describe(e: unknown): string { return String(e) }
return describe(error)
}
}
}
functions {
client async function go(): Promise<void> {
await api.searchUsers({ name: "a" })
}
}
view { <main><button @click="go()">x</button></main> }
}
`),
).browser;
expect(browser).not.toContain("list: string[]");
expect(browser).not.toContain("): string[] {");
expect(browser).not.toContain("e: unknown");
expect(browser).not.toContain("): string {");
expect(() => {
new Function(browser.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
}).not.toThrow();
});
test("a state field named api does not collide with the emitted api object", () => {
const browser = generateTargets(
parse(`page Probe {
state {
api = ""
}
apis {
used POST /api/used {
request { body { name?: string } }
response { return data.users }
}
}
functions {
client async function go(): Promise<void> {
const users = await api.used({ name: "a" })
console.log(users)
}
}
view { <main><button @click="go()">x</button></main> }
}
`),
).browser;
expect(() => {
new Function(browser.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
}).not.toThrow();
});
/**
* Builds a browser module whose `go()` function calls api.searchUsers and
* reports the outcome through `output.report(...)` so a test can observe
* whether the call resolved or rejected without reaching into codegen
* internals.
*/
function reportingBrowserModule(apiBlock: string): string {
return generateTargets(
parse(`page Probe {
apis {
${apiBlock}
}
outputs {
report(payload: any)
}
functions {
client async function go(): Promise<void> {
try {
const users = await api.searchUsers({ name: "a" })
output.report({ ok: true, users })
} catch (e) {
output.report({ ok: false, message: String(e && e.message || e) })
}
}
}
view { <main><button @click="go()">x</button></main> }
}
`),
).browser;
}
async function importBrowserModule(source: string): Promise<any> {
const root = mkdtempSync(join(tmpdir(), "wrnexus-client-exec-"));
roots.push(root);
mkdirSync(root, { recursive: true });
const file = join(root, "page.mjs");
writeFileSync(file, source);
return import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
}
test("a response body error is not swallowed by the error section (client)", async () => {
const mod = await importBrowserModule(
reportingBrowserModule(` searchUsers GET /api/users {
request { parameters { name: string } }
response {
return data.users.missing.length
}
error {
return []
}
}`),
);
const reports: unknown[] = [];
const context = {
state: {},
props: {},
output: { report: (value: unknown) => reports.push(value) },
server: {},
refs: {},
callApi: async () => ({ users: [] }),
};
await mod.__wrnexusClientFunctions.go(context);
expect(reports).toEqual([{ ok: false, message: expect.any(String) }]);
// The error section's own fallback ("[]" / an empty array) must not have
// been what the caller observed -- a bug in the response body is a
// rejection, not a silently-returned fallback value.
expect(reports[0]).not.toEqual({ ok: true, users: [] });
});
test("a genuine transport failure still runs the error section's fallback (client)", async () => {
const mod = await importBrowserModule(
reportingBrowserModule(` searchUsers GET /api/users {
request { parameters { name: string } }
response {
return data.users
}
error {
return ["fallback"]
}
}`),
);
const reports: unknown[] = [];
const context = {
state: {},
props: {},
output: { report: (value: unknown) => reports.push(value) },
server: {},
refs: {},
callApi: async () => {
throw Object.assign(new Error("transport failed"), { status: 500 });
},
};
await mod.__wrnexusClientFunctions.go(context);
expect(reports).toEqual([{ ok: true, users: ["fallback"] }]);
});
+285 -1
View File
@@ -1,7 +1,111 @@
import { expect, test } from "bun:test";
import { afterEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse } from "@wrnexus/syntax";
import { runWithRequestContext } from "@wrnexus/core";
import { generate } from "../src/codegen.ts";
// The generated module dynamically imported below is written to an OS
// tmpdir with no node_modules of its own, so Node's bare-specifier
// resolution for "@wrnexus/core" would otherwise walk up to whatever
// (possibly stale, globally-installed) copy happens to sit outside the
// workspace. Symlink the workspace package in so it resolves to the real,
// currently-built `@wrnexus/core` — the same one every other package in
// this repo gets via its own `node_modules/@wrnexus/core` symlink.
const WORKSPACE_CORE = join(import.meta.dir, "../../core");
function linkWorkspaceCore(root: string): void {
const scopeDir = join(root, "node_modules", "@wrnexus");
mkdirSync(scopeDir, { recursive: true });
symlinkSync(
WORKSPACE_CORE,
join(scopeDir, "core"),
process.platform === "win32" ? "junction" : "dir",
);
}
const ROOT_TSCONFIG = join(import.meta.dir, "../../../tsconfig.json").replace(/\\/g, "/");
// The repo's own tsc, not a `bunx`-fetched one — `bunx tsc` can resolve an
// unrelated TypeScript version that doesn't understand this repo's tsconfig
// options, unlike `bun run typecheck`, which uses this same local binary.
const LOCAL_TSC = join(import.meta.dir, "../../../node_modules/.bin/tsc").replace(/\\/g, "/");
// `types`/`typeRoots` in an extended tsconfig resolve relative to the config
// file that's actually invoked (our temp one), not the base file — so the
// ambient `bun` types need an explicit path back to the repo's node_modules.
const TYPE_ROOTS = join(import.meta.dir, "../../../node_modules/@types").replace(/\\/g, "/");
const roots: string[] = [];
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
/**
* Runs the real TypeScript compiler over a generated server module. Proves
* the emitted server `api` object (and everything else in the module)
* actually type-checks — string-containment assertions alone can't catch a
* declared type that omits a field every emitted object literal has.
*/
function typecheckGenerated(source: string): { ok: boolean; output: string } {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-server-tsc-"));
roots.push(root);
const file = join(root, "page.ts");
writeFileSync(file, source);
writeFileSync(
join(root, "tsconfig.json"),
JSON.stringify({
extends: ROOT_TSCONFIG,
compilerOptions: { noEmit: true, typeRoots: [TYPE_ROOTS] },
include: ["page.ts"],
}),
);
const result = Bun.spawnSync([LOCAL_TSC, "--project", join(root, "tsconfig.json")], {
cwd: root,
stdout: "pipe",
stderr: "pipe",
});
const output = `${result.stdout?.toString() ?? ""}${result.stderr?.toString() ?? ""}`;
return { ok: result.exitCode === 0, output };
}
async function importServerModule(source: string): Promise<any> {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-server-exec-"));
roots.push(root);
mkdirSync(root, { recursive: true });
linkWorkspaceCore(root);
const file = join(root, "page.ts");
writeFileSync(file, source);
return import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
}
/**
* Renders a page module the way the dev-server runtime does: runs the
* generated `__wrnexusLoad` export (if any) and merges its result onto ctx
* before calling the default render export. `callApi` fakes the transport
* that the generated server `api` object's members call out to. The same
* ctx object must be both the AsyncLocalStorage store (so the api member's
* `requireRequestContext` call finds it) and the ctx passed to load/render,
* or the fake transport is never reached.
*/
function renderPage(
mod: any,
callApi: (path: string, method: string, input?: unknown) => Promise<unknown>,
): Promise<string> {
const ctx: any = {
req: { url: "http://localhost/", headers: new Headers() },
cookies: {},
session: {},
__wrnexusCallApi: callApi,
};
return runWithRequestContext(ctx, async () => {
if (typeof mod.__wrnexusLoad === "function") {
const data = await mod.__wrnexusLoad(ctx);
if (data && typeof data === "object") Object.assign(ctx, data);
}
return mod.default(ctx);
});
}
const SOURCE = `page Probe {
apis {
searchUsers POST /api/users {
@@ -44,3 +148,183 @@ test("a block with no error section rethrows rather than resolving undefined", (
expect(generated).toContain("throw");
});
// --- Execution tests --------------------------------------------------------
//
// Everything above only asserts on emitted *text*. These instead run the real
// TypeScript compiler and dynamically import + execute the generated module,
// proving the response/error sections actually run with the right bindings —
// a string-containment check cannot prove that.
function renderModule(inner: string): string {
return generate(
parse(`page Repro {
apis {
${inner}
}
view { <main><p api="ssrUsers">loading</p></main> }
}
`),
);
}
test("a sectioned block's response body binds the payload to data", async () => {
const mod = await importServerModule(
renderModule(` ssrUsers GET /api/users {
response {
return data.users.length
}
}`),
);
const html = await renderPage(mod, async () => ({ users: [1, 2, 3] }));
expect(html).toContain("3");
});
test("an error section emits the error body and binds status/message/data", async () => {
const mod = await importServerModule(
renderModule(` ssrUsers GET /api/users {
response {
return data.users.length
}
error {
return message + ":" + status + ":" + data
}
}`),
);
const html = await renderPage(mod, async () => {
throw Object.assign(new Error("boom"), { status: 500, data: "extra" });
});
expect(html).toContain("boom:500:extra");
});
test("a block without an error section still propagates a genuine transport failure", async () => {
const mod = await importServerModule(
renderModule(` ssrUsers GET /api/users {
response {
return data.users.length
}
}`),
);
await expect(
renderPage(mod, async () => {
throw new Error("boom");
}),
).rejects.toThrow("boom");
});
test("a response body error is not swallowed by the error section", async () => {
const mod = await importServerModule(
renderModule(` ssrUsers GET /api/users {
response {
return data.users.missing.length
}
error {
return "fallback"
}
}`),
);
// The transport call itself succeeds; the bug is in the response body. That
// must surface as a rejection, not be swallowed by the error section's own
// fallback -- a bug in response handling is not a transport failure.
await expect(renderPage(mod, async () => ({ users: [] }))).rejects.toThrow();
});
test("a genuine transport failure still runs the error section's fallback", async () => {
const mod = await importServerModule(
renderModule(` ssrUsers GET /api/users {
response {
return data.users.length
}
error {
return "fallback"
}
}`),
);
const html = await renderPage(mod, async () => {
throw new Error("boom");
});
expect(html).toContain("fallback");
});
test("tsc: a sectioned block's generated server module has no diagnostics", () => {
const generated = renderModule(` ssrUsers GET /api/users {
response {
return data.users.length
}
error {
return message + status + data
}
}`);
const { ok, output } = typecheckGenerated(generated);
expect(output.trim()).toBe("");
expect(ok).toBe(true);
});
// {#each} iterates a plain, already-resolved value — an `await` inside the
// list expression itself is not supported (the list expression runs outside
// an async boundary). A `load server` block is the idiomatic way to resolve
// an api call before the view iterates it, and it goes through the exact
// same server `api` member (and thus the same response/error handling) as
// every other apis {} call site.
function eachModule(inner: string): string {
return generate(
parse(`page Repro {
apis {
${inner}
}
load server users {
return await api.ssrUsers()
}
view { <main>{#each users as u}<p>{u}</p>{/each}</main> }
}
`),
);
}
test("an api block used in {#each} with an error section runs the error body on failure", async () => {
const mod = await importServerModule(
eachModule(` ssrUsers GET /api/users {
response {
return data.users
}
error {
return ["fallback"]
}
}`),
);
const html = await renderPage(mod, async () => {
throw new Error("boom");
});
expect(html).toContain("fallback");
});
test("an api block used in {#each} without an error section still propagates a failure", async () => {
const mod = await importServerModule(
eachModule(` ssrUsers GET /api/users {
response {
return data.users
}
}`),
);
await expect(
renderPage(mod, async () => {
throw new Error("boom");
}),
).rejects.toThrow("boom");
});
+24
View File
@@ -97,3 +97,27 @@ test("an explicit empty response section is accepted, unlike a bare body", () =>
expect(block.name).toBe("empty");
expect(block.sections?.response.trim()).toBe("");
});
test("a brace inside a string literal in the response body does not truncate the section", () => {
const ast = parse(
page(` searchUsers POST /api/users {
request {
body {
name?: string
}
}
response {
return "a } weird string"
}
error {
return []
}
}`),
);
const block = ast.dataApis[0]!;
expect(block.sections?.response.trim()).toBe('return "a } weird string"');
expect(block.sections?.error.trim()).toBe("return []");
});