feat: replace the ssr/client data blocks with apis blocks
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -378,14 +378,13 @@ function clientCalledApiNames(ast: PageAst): Set<string> {
|
||||
* never does either.
|
||||
*/
|
||||
function assertNoDynamicApiAccess(ast: PageAst): void {
|
||||
// Only pages with a mode "any" block have anything at stake here: those
|
||||
// Only pages with a sectioned api block have anything at stake here: those
|
||||
// blocks are emitted solely because usage detection saw `api.<name>`, so a
|
||||
// dynamic reference this scan can't see is the one that silently drops a
|
||||
// block from the bundle. Mode "client" blocks always ship regardless of
|
||||
// usage, and a page with no api blocks at all may still declare an
|
||||
// ordinary `state api` (see the B5 regression test) where a bare "api"
|
||||
// block from the bundle. A page with no api blocks at all may still declare
|
||||
// an ordinary `state api` (see the B5 regression test) where a bare "api"
|
||||
// identifier is just that state, not a missed block reference.
|
||||
if (!ast.dataApis.some((block) => block.mode === "any" && block.sections)) return;
|
||||
if (!ast.dataApis.some((block) => block.sections)) return;
|
||||
|
||||
for (const fn of ast.runtimeFunctions.filter((fn) => ["client", "shared"].includes(fn.runtime))) {
|
||||
const masked = maskStringsAndComments(fn.body);
|
||||
@@ -403,16 +402,13 @@ function assertNoDynamicApiAccess(ast: PageAst): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* A block is emitted into the browser module when it is authored as
|
||||
* client-only, or when it is mode "any" and a client function actually calls
|
||||
* it. `hasClientApi` below must use this exact predicate so the `api`
|
||||
* reserved-binding exclusion and the emitted object can never disagree.
|
||||
* A block is emitted into the browser module when it declares typed sections
|
||||
* and a client function actually calls it. `hasClientApi` below must use this
|
||||
* exact predicate so the `api` reserved-binding exclusion and the emitted
|
||||
* object can never disagree.
|
||||
*/
|
||||
function isClientEmittedApiBlock(block: PageAst["dataApis"][number], called: Set<string>): boolean {
|
||||
return (
|
||||
Boolean(block.sections) &&
|
||||
(block.mode === "client" || (block.mode === "any" && called.has(block.name)))
|
||||
);
|
||||
return Boolean(block.sections) && called.has(block.name);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -567,29 +567,6 @@ function compileIfExpr(node: IfNode): string {
|
||||
return "${" + expr + "}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect every server-control expression in a view (recursively): `{#each}` list
|
||||
* expressions and `{#if}` conditions. Used to wrn up raw SSR data consts.
|
||||
*/
|
||||
function collectControlExprs(nodes: ViewNode[], out: string[] = []): string[] {
|
||||
for (const node of nodes) {
|
||||
if (node.type === "text") continue;
|
||||
if (node.type === "each") {
|
||||
out.push(node.list);
|
||||
collectControlExprs(node.body, out);
|
||||
collectControlExprs(node.empty, out);
|
||||
} else if (node.type === "if") {
|
||||
for (const b of node.branches) {
|
||||
if (b.cond) out.push(b.cond);
|
||||
collectControlExprs(b.body, out);
|
||||
}
|
||||
} else if (node.type === "element") {
|
||||
collectControlExprs(node.children, out);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function renderNode(
|
||||
node: ViewNode,
|
||||
ssrBindings: SsrBinding[],
|
||||
@@ -741,39 +718,32 @@ function renderNode(
|
||||
const csrText = attrValue(node.attrs, "csrText");
|
||||
|
||||
const csrId =
|
||||
apiBinding?.mode === "client"
|
||||
? csrMarker(csrBindings, renderBinding(apiBinding))
|
||||
: csrGet && csrText
|
||||
? csrMarker(csrBindings, {
|
||||
method: "GET",
|
||||
path: apiRoutePath(csrGet),
|
||||
body: expressionBody(csrText),
|
||||
helpers: "",
|
||||
})
|
||||
: undefined;
|
||||
csrGet && csrText
|
||||
? csrMarker(csrBindings, {
|
||||
method: "GET",
|
||||
path: apiRoutePath(csrGet),
|
||||
body: expressionBody(csrText),
|
||||
helpers: "",
|
||||
})
|
||||
: undefined;
|
||||
|
||||
// Void elements (<br>, <img>, …) have no closing tag and no children.
|
||||
if (VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
||||
}
|
||||
|
||||
const inner =
|
||||
apiBinding?.mode === "ssr"
|
||||
? ssrMarker(ssrBindings, renderBinding(apiBinding))
|
||||
: apiBinding?.mode === "any"
|
||||
? apiCallMarker(loops, parsedApi!.name, parsedApi!.args)
|
||||
: ssrGet && ssrText
|
||||
? ssrMarker(ssrBindings, {
|
||||
method: "GET",
|
||||
path: apiRoutePath(ssrGet),
|
||||
body: expressionBody(ssrText),
|
||||
helpers: "",
|
||||
})
|
||||
: node.children
|
||||
.map((child) =>
|
||||
renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive),
|
||||
)
|
||||
.join("");
|
||||
const inner = apiBinding
|
||||
? apiCallMarker(loops, parsedApi!.name, parsedApi!.args)
|
||||
: ssrGet && ssrText
|
||||
? ssrMarker(ssrBindings, {
|
||||
method: "GET",
|
||||
path: apiRoutePath(ssrGet),
|
||||
body: expressionBody(ssrText),
|
||||
helpers: "",
|
||||
})
|
||||
: node.children
|
||||
.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive))
|
||||
.join("");
|
||||
|
||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>${inner}</${node.tag}>`;
|
||||
}
|
||||
@@ -912,16 +882,6 @@ function csrMarker(bindings: CsrBinding[], binding: RenderBinding): string {
|
||||
return id;
|
||||
}
|
||||
|
||||
function renderBinding(binding: NamedDataBinding): RenderBinding {
|
||||
return {
|
||||
method: binding.method,
|
||||
path: binding.path,
|
||||
body: binding.body,
|
||||
helpers: binding.helpers,
|
||||
...(binding.errorBody ? { errorBody: binding.errorBody } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function hasClientBehavior(nodes: ViewNode[]): boolean {
|
||||
return nodes.some((node) => {
|
||||
// `{t:key}` is i18n sugar resolved server-side — not client reactivity.
|
||||
@@ -963,18 +923,6 @@ function dataBody(source: string): string {
|
||||
return /\breturn\b/.test(trimmed) ? trimmed : expressionBody(trimmed);
|
||||
}
|
||||
|
||||
function modeHelpers(ast: PageAst, mode: DataMode, sharedHelpers: string): string {
|
||||
return [
|
||||
sharedHelpers,
|
||||
...ast.modeFunctions
|
||||
.filter((block) => block.mode === mode)
|
||||
.map((block) => block.body.trim())
|
||||
.filter(Boolean),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
function apiBindingMap(ast: PageAst, sharedHelpers: string): Map<string, NamedDataBinding> {
|
||||
const bindings = new Map<string, NamedDataBinding>();
|
||||
|
||||
@@ -997,7 +945,7 @@ function apiBindingMap(ast: PageAst, sharedHelpers: string): Map<string, NamedDa
|
||||
// legacy blocks and sectioned blocks without `error` keep failures
|
||||
// propagating exactly as before.
|
||||
...(errorSection ? { errorBody: errorSection } : {}),
|
||||
helpers: modeHelpers(ast, block.mode, sharedHelpers),
|
||||
helpers: sharedHelpers,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1664,22 +1612,7 @@ function generateInner(ast: PageAst): string {
|
||||
}
|
||||
}
|
||||
|
||||
// Server loops iterate raw SSR data. Declare a named const for every `ssr` data
|
||||
// binding a loop references, so `{#each <name> as …}` can iterate the real value.
|
||||
const loopConsts: string[] = [];
|
||||
if (loops.length > 0) {
|
||||
const lists = collectControlExprs(ast.view);
|
||||
for (const [name, binding] of apiBindings) {
|
||||
if (binding.mode !== "ssr") continue;
|
||||
if (!lists.some((expr) => new RegExp(`\\b${name}\\b`).test(expr))) continue;
|
||||
const errorBodyProp = binding.errorBody
|
||||
? `, errorBody: ${JSON.stringify(binding.errorBody)}`
|
||||
: "";
|
||||
loopConsts.push(
|
||||
` const ${name} = await __wrnexusResolveApiBinding({ path: ${JSON.stringify(binding.path)}, method: ${JSON.stringify(binding.method)}, body: ${JSON.stringify(binding.body)}, helpers: ${JSON.stringify(binding.helpers)}${errorBodyProp} }, ctx);`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const needsSsrRuntime = ssrBindings.length > 0 || loops.length > 0 || runtimeStateNames.size > 0;
|
||||
const needsRuntimeHelpers = needsSsrRuntime || hasServerApis;
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
|
||||
function browserModule(inner: string): string {
|
||||
return generateTargets(
|
||||
parse(`page Repro {
|
||||
client {
|
||||
${inner}
|
||||
}
|
||||
|
||||
functions {
|
||||
client async function run(): Promise<void> {
|
||||
const users = await api.searchUsers({ name: "Ajay" })
|
||||
console.log(users)
|
||||
}
|
||||
}
|
||||
|
||||
view { <main><button @click="run()">go</button></main> }
|
||||
}
|
||||
`),
|
||||
).browser;
|
||||
}
|
||||
|
||||
const BLOCK = ` api searchUsers POST /api/users {
|
||||
request {
|
||||
body {
|
||||
name?: string
|
||||
age?: number
|
||||
}
|
||||
}
|
||||
|
||||
response {
|
||||
return data.users
|
||||
}
|
||||
|
||||
error {
|
||||
return []
|
||||
}
|
||||
}`;
|
||||
|
||||
test("emits an api member that calls the transport with the block's path and method", () => {
|
||||
const generated = browserModule(BLOCK);
|
||||
|
||||
expect(generated).toContain("const api =");
|
||||
expect(generated).toContain("searchUsers");
|
||||
expect(generated).toContain('"/api/users"');
|
||||
expect(generated).toContain('"POST"');
|
||||
});
|
||||
|
||||
test("declared field types never reach the browser module", () => {
|
||||
// The artifact is written as .mjs and parsed as JavaScript.
|
||||
const generated = browserModule(BLOCK);
|
||||
|
||||
expect(generated).not.toContain("name?: string");
|
||||
expect(generated).not.toContain("age?: number");
|
||||
});
|
||||
|
||||
test("the emitted module is valid JavaScript", () => {
|
||||
const generated = browserModule(BLOCK);
|
||||
|
||||
expect(() => {
|
||||
new Function(generated.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
test("a block without an error section still emits its response body", () => {
|
||||
const generated = browserModule(` api plainUsers GET /api/users {
|
||||
request {
|
||||
parameters {
|
||||
team: string
|
||||
}
|
||||
}
|
||||
|
||||
response {
|
||||
return data.users
|
||||
}
|
||||
}`);
|
||||
|
||||
expect(generated).toContain("plainUsers");
|
||||
expect(generated).toContain("data.users");
|
||||
});
|
||||
|
||||
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 ~line 288 and ~371, 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 generated = browserModule(` api 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)
|
||||
}
|
||||
}`);
|
||||
|
||||
expect(generated).not.toContain("list: string[]");
|
||||
expect(generated).not.toContain("): string[] {");
|
||||
expect(generated).not.toContain("e: unknown");
|
||||
expect(generated).not.toContain("): string {");
|
||||
expect(() => {
|
||||
new Function(generated.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
test("a page with state api and no client api blocks still reads that state (B5)", () => {
|
||||
// "api" is normally excluded from state/prop destructuring because the
|
||||
// emitted `const api = {...}` binding would shadow it -- but that binding
|
||||
// only exists when the page has client-mode api blocks. Without one, the
|
||||
// exclusion left `api` completely undeclared: a ReferenceError.
|
||||
const generated = generateTargets(
|
||||
parse(`page Repro {
|
||||
state {
|
||||
api = "hello"
|
||||
}
|
||||
|
||||
functions {
|
||||
client function run(): void {
|
||||
console.log(api)
|
||||
}
|
||||
}
|
||||
|
||||
view { <main><button @click="run()">go</button></main> }
|
||||
}
|
||||
`),
|
||||
).browser;
|
||||
|
||||
expect(generated).toContain("context.state");
|
||||
expect(() => {
|
||||
new Function(generated.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
/**
|
||||
* Builds a browser module whose `run()` function calls api.searchUsers and
|
||||
* reports the outcome through `output.report(...)` so the test can observe
|
||||
* whether the call resolved or rejected without reaching into codegen
|
||||
* internals.
|
||||
*/
|
||||
function reportingBrowserModule(apiBlock: string): string {
|
||||
return generateTargets(
|
||||
parse(`page Repro {
|
||||
client {
|
||||
${apiBlock}
|
||||
}
|
||||
|
||||
outputs {
|
||||
report(payload: any)
|
||||
}
|
||||
|
||||
functions {
|
||||
client async function run(): Promise<void> {
|
||||
try {
|
||||
const users = await api.searchUsers({ name: "Ajay" })
|
||||
output.report({ ok: true, users })
|
||||
} catch (e) {
|
||||
output.report({ ok: false, message: String(e && e.message || e) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main><button @click="run()">go</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(` api 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.run(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(` api 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.run(context);
|
||||
|
||||
expect(reports).toEqual([{ ok: true, users: ["fallback"] }]);
|
||||
});
|
||||
|
||||
test("a state field named api does not collide with the emitted api object", () => {
|
||||
const generated = generateTargets(
|
||||
parse(`page Repro {
|
||||
state {
|
||||
api = ""
|
||||
}
|
||||
|
||||
client {
|
||||
${BLOCK}
|
||||
}
|
||||
|
||||
functions {
|
||||
client async function run(): Promise<void> {
|
||||
const users = await api.searchUsers({ name: "Ajay" })
|
||||
console.log(users)
|
||||
}
|
||||
}
|
||||
|
||||
view { <main><button @click="run()">go</button></main> }
|
||||
}
|
||||
`),
|
||||
).browser;
|
||||
|
||||
expect(() => {
|
||||
new Function(generated.replace(/^\s*import[^\n]*$/gm, "").replace(/\bexport\s+/g, ""));
|
||||
}).not.toThrow();
|
||||
});
|
||||
@@ -1,305 +0,0 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parse } from "@wrnexus/syntax";
|
||||
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 (observed: it rejected `ignoreDeprecations: "6.0"` and couldn't
|
||||
// find the `bun` type-definition entry point), 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 `__wrnexusSsrBindings` annotation (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-ssr-tsc-"));
|
||||
roots.push(root);
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, source);
|
||||
// Reuse the repo's own tsconfig (paths, lib, types, jsx, ...) so this only
|
||||
// checks the one file we care about instead of hand-duplicating the whole
|
||||
// compiler configuration (and drifting from it over time).
|
||||
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 };
|
||||
}
|
||||
|
||||
function serverModule(inner: string): string {
|
||||
return generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
${inner}
|
||||
}
|
||||
|
||||
view { <main><p api="ssrUsers">loading</p></main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
}
|
||||
|
||||
test("a sectioned ssr block binds the payload to data", () => {
|
||||
const generated = serverModule(` api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.length
|
||||
}
|
||||
}`);
|
||||
|
||||
expect(generated).toContain("data.users.length");
|
||||
});
|
||||
|
||||
test("a legacy ssr block is unchanged", () => {
|
||||
const generated = serverModule(` api ssrUsers GET /api/users {
|
||||
return users.length
|
||||
}`);
|
||||
|
||||
expect(generated).toContain("users.length");
|
||||
});
|
||||
|
||||
test("an ssr block with an error section emits the error body and binds status/message/data", () => {
|
||||
const generated = serverModule(` api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.length
|
||||
}
|
||||
error {
|
||||
return message + status + data
|
||||
}
|
||||
}`);
|
||||
|
||||
expect(generated).toContain('"errorBody"');
|
||||
expect(generated).toContain("return message + status + data");
|
||||
expect(generated).toContain("const status = $status");
|
||||
expect(generated).toContain("const message = $message");
|
||||
expect(generated).toContain("const data = $data");
|
||||
expect(generated).toContain("__wrnexusEvalError");
|
||||
});
|
||||
|
||||
test("an ssr block without an error section emits no catch entry for that binding", () => {
|
||||
const generated = serverModule(` api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.length
|
||||
}
|
||||
}`);
|
||||
|
||||
expect(generated).not.toContain('"errorBody"');
|
||||
});
|
||||
|
||||
test("tsc: a sectioned ssr block's generated module has no diagnostics", () => {
|
||||
const generated = serverModule(` api 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);
|
||||
});
|
||||
|
||||
test("an ssr block used in {#each} with an error section runs the error body on failure", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-each-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
linkWorkspaceCore(root);
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
const html = await mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
});
|
||||
|
||||
expect(html).toContain("fallback");
|
||||
});
|
||||
|
||||
test("an ssr block's response body error is not swallowed by the error section", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.missing.length
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-response-throws-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
linkWorkspaceCore(root);
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
|
||||
await expect(
|
||||
mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => ({ users: [] }),
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("an ssr block still runs the error body on a genuine transport failure", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.length
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-transport-fails-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
linkWorkspaceCore(root);
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
const html = await mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
});
|
||||
|
||||
expect(html).toContain("fallback");
|
||||
});
|
||||
|
||||
test("an ssr block used in {#each} without an error section still propagates a failure", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-each-propagate-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
linkWorkspaceCore(root);
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
|
||||
await expect(
|
||||
mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("boom");
|
||||
});
|
||||
Reference in New Issue
Block a user