feat: replace the ssr/client data blocks with apis blocks
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+35
-140
@@ -1,6 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
// Generated by scripts/build-editor-compiler.mjs. Do not edit directly.
|
// Generated by scripts/build-editor-compiler.mjs. Do not edit directly.
|
||||||
// WRN editor compiler source hash: 9203410b358f7f7f824f49e1e793d2281403faab7097d2664761d5dbe3b8e957
|
// WRN editor compiler source hash: 653a88ea2a34e9c446fc55b268f3ba9c5d27f9e114fc6aa9228ef560e1fd616d
|
||||||
// WRN editor compiler generator hash: a54ca847c758bc98d8e353ad6d70088df31de1820f6cf9d1c3462505f563e6b8
|
// WRN editor compiler generator hash: a54ca847c758bc98d8e353ad6d70088df31de1820f6cf9d1c3462505f563e6b8
|
||||||
// Generated with TypeScript: 6.0.3
|
// Generated with TypeScript: 6.0.3
|
||||||
const __nodeRequire = require;
|
const __nodeRequire = require;
|
||||||
@@ -779,14 +779,13 @@ function clientCalledApiNames(ast) {
|
|||||||
* never does either.
|
* never does either.
|
||||||
*/
|
*/
|
||||||
function assertNoDynamicApiAccess(ast) {
|
function assertNoDynamicApiAccess(ast) {
|
||||||
// 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
|
// 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
|
// 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
|
// block from the bundle. A page with no api blocks at all may still declare
|
||||||
// usage, and a page with no api blocks at all may still declare an
|
// an ordinary `state api` (see the B5 regression test) where a bare "api"
|
||||||
// ordinary `state api` (see the B5 regression test) where a bare "api"
|
|
||||||
// identifier is just that state, not a missed block reference.
|
// identifier is just that state, not a missed block reference.
|
||||||
if (!ast.dataApis.some((block) => block.mode === "any" && block.sections))
|
if (!ast.dataApis.some((block) => block.sections))
|
||||||
return;
|
return;
|
||||||
for (const fn of ast.runtimeFunctions.filter((fn) => ["client", "shared"].includes(fn.runtime))) {
|
for (const fn of ast.runtimeFunctions.filter((fn) => ["client", "shared"].includes(fn.runtime))) {
|
||||||
const masked = maskStringsAndComments(fn.body);
|
const masked = maskStringsAndComments(fn.body);
|
||||||
@@ -799,14 +798,13 @@ function assertNoDynamicApiAccess(ast) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* A block is emitted into the browser module when it is authored as
|
* A block is emitted into the browser module when it declares typed sections
|
||||||
* client-only, or when it is mode "any" and a client function actually calls
|
* and a client function actually calls it. `hasClientApi` below must use this
|
||||||
* it. `hasClientApi` below must use this exact predicate so the `api`
|
* exact predicate so the `api` reserved-binding exclusion and the emitted
|
||||||
* reserved-binding exclusion and the emitted object can never disagree.
|
* object can never disagree.
|
||||||
*/
|
*/
|
||||||
function isClientEmittedApiBlock(block, called) {
|
function isClientEmittedApiBlock(block, called) {
|
||||||
return (Boolean(block.sections) &&
|
return Boolean(block.sections) && called.has(block.name);
|
||||||
(block.mode === "client" || (block.mode === "any" && called.has(block.name))));
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Client-mode and client-called any-mode api blocks become members of an
|
* Client-mode and client-called any-mode api blocks become members of an
|
||||||
@@ -1385,32 +1383,6 @@ function compileIfExpr(node) {
|
|||||||
}
|
}
|
||||||
return "${" + expr + "}";
|
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, out = []) {
|
|
||||||
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, ssrBindings, csrBindings, apiBindings, loops, reactive = null) {
|
function renderNode(node, ssrBindings, csrBindings, apiBindings, loops, reactive = null) {
|
||||||
if (node.type === "text")
|
if (node.type === "text")
|
||||||
return substituteReactiveText(node.value, reactive, loops); // {t:key} + state baking
|
return substituteReactiveText(node.value, reactive, loops); // {t:key} + state baking
|
||||||
@@ -1518,34 +1490,30 @@ function renderNode(node, ssrBindings, csrBindings, apiBindings, loops, reactive
|
|||||||
const ssrText = attrValue(node.attrs, "ssrText");
|
const ssrText = attrValue(node.attrs, "ssrText");
|
||||||
const csrGet = attrValue(node.attrs, "csrGet");
|
const csrGet = attrValue(node.attrs, "csrGet");
|
||||||
const csrText = attrValue(node.attrs, "csrText");
|
const csrText = attrValue(node.attrs, "csrText");
|
||||||
const csrId = apiBinding?.mode === "client"
|
const csrId = csrGet && csrText
|
||||||
? csrMarker(csrBindings, renderBinding(apiBinding))
|
? csrMarker(csrBindings, {
|
||||||
: csrGet && csrText
|
method: "GET",
|
||||||
? csrMarker(csrBindings, {
|
path: apiRoutePath(csrGet),
|
||||||
method: "GET",
|
body: expressionBody(csrText),
|
||||||
path: apiRoutePath(csrGet),
|
helpers: "",
|
||||||
body: expressionBody(csrText),
|
})
|
||||||
helpers: "",
|
: undefined;
|
||||||
})
|
|
||||||
: undefined;
|
|
||||||
// Void elements (<br>, <img>, …) have no closing tag and no children.
|
// Void elements (<br>, <img>, …) have no closing tag and no children.
|
||||||
if (syntax_1.VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
if (syntax_1.VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
||||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
||||||
}
|
}
|
||||||
const inner = apiBinding?.mode === "ssr"
|
const inner = apiBinding
|
||||||
? ssrMarker(ssrBindings, renderBinding(apiBinding))
|
? apiCallMarker(loops, parsedApi.name, parsedApi.args)
|
||||||
: apiBinding?.mode === "any"
|
: ssrGet && ssrText
|
||||||
? apiCallMarker(loops, parsedApi.name, parsedApi.args)
|
? ssrMarker(ssrBindings, {
|
||||||
: ssrGet && ssrText
|
method: "GET",
|
||||||
? ssrMarker(ssrBindings, {
|
path: apiRoutePath(ssrGet),
|
||||||
method: "GET",
|
body: expressionBody(ssrText),
|
||||||
path: apiRoutePath(ssrGet),
|
helpers: "",
|
||||||
body: expressionBody(ssrText),
|
})
|
||||||
helpers: "",
|
: node.children
|
||||||
})
|
.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive))
|
||||||
: node.children
|
.join("");
|
||||||
.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive))
|
|
||||||
.join("");
|
|
||||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>${inner}</${node.tag}>`;
|
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>${inner}</${node.tag}>`;
|
||||||
}
|
}
|
||||||
function renderPageComponentInvocation(node, ssrBindings, csrBindings, apiBindings, loops, reactive) {
|
function renderPageComponentInvocation(node, ssrBindings, csrBindings, apiBindings, loops, reactive) {
|
||||||
@@ -1645,15 +1613,6 @@ function csrMarker(bindings, binding) {
|
|||||||
bindings.push({ id, ...binding });
|
bindings.push({ id, ...binding });
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
function renderBinding(binding) {
|
|
||||||
return {
|
|
||||||
method: binding.method,
|
|
||||||
path: binding.path,
|
|
||||||
body: binding.body,
|
|
||||||
helpers: binding.helpers,
|
|
||||||
...(binding.errorBody ? { errorBody: binding.errorBody } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function hasClientBehavior(nodes) {
|
function hasClientBehavior(nodes) {
|
||||||
return nodes.some((node) => {
|
return nodes.some((node) => {
|
||||||
// `{t:key}` is i18n sugar resolved server-side — not client reactivity.
|
// `{t:key}` is i18n sugar resolved server-side — not client reactivity.
|
||||||
@@ -1691,17 +1650,6 @@ function dataBody(source) {
|
|||||||
return "return undefined;";
|
return "return undefined;";
|
||||||
return /\breturn\b/.test(trimmed) ? trimmed : expressionBody(trimmed);
|
return /\breturn\b/.test(trimmed) ? trimmed : expressionBody(trimmed);
|
||||||
}
|
}
|
||||||
function modeHelpers(ast, mode, sharedHelpers) {
|
|
||||||
return [
|
|
||||||
sharedHelpers,
|
|
||||||
...ast.modeFunctions
|
|
||||||
.filter((block) => block.mode === mode)
|
|
||||||
.map((block) => block.body.trim())
|
|
||||||
.filter(Boolean),
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join("\n\n");
|
|
||||||
}
|
|
||||||
function apiBindingMap(ast, sharedHelpers) {
|
function apiBindingMap(ast, sharedHelpers) {
|
||||||
const bindings = new Map();
|
const bindings = new Map();
|
||||||
for (const block of ast.dataApis) {
|
for (const block of ast.dataApis) {
|
||||||
@@ -1723,7 +1671,7 @@ function apiBindingMap(ast, sharedHelpers) {
|
|||||||
// legacy blocks and sectioned blocks without `error` keep failures
|
// legacy blocks and sectioned blocks without `error` keep failures
|
||||||
// propagating exactly as before.
|
// propagating exactly as before.
|
||||||
...(errorSection ? { errorBody: errorSection } : {}),
|
...(errorSection ? { errorBody: errorSection } : {}),
|
||||||
helpers: modeHelpers(ast, block.mode, sharedHelpers),
|
helpers: sharedHelpers,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return bindings;
|
return bindings;
|
||||||
@@ -2303,22 +2251,7 @@ function generateInner(ast) {
|
|||||||
staticShellBody = staticShellBody.replaceAll(`\x00WRNEACH${idx}\x00`, code);
|
staticShellBody = staticShellBody.replaceAll(`\x00WRNEACH${idx}\x00`, code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 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 = [];
|
const loopConsts = [];
|
||||||
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 needsSsrRuntime = ssrBindings.length > 0 || loops.length > 0 || runtimeStateNames.size > 0;
|
||||||
const needsRuntimeHelpers = needsSsrRuntime || hasServerApis;
|
const needsRuntimeHelpers = needsSsrRuntime || hasServerApis;
|
||||||
if (needsRuntimeHelpers) {
|
if (needsRuntimeHelpers) {
|
||||||
@@ -6813,7 +6746,6 @@ function parse(source) {
|
|||||||
case "client":
|
case "client":
|
||||||
case "server": {
|
case "server": {
|
||||||
const rawMode = kw.value;
|
const rawMode = kw.value;
|
||||||
const mode = rawMode === "client" ? "client" : "ssr";
|
|
||||||
lx.next();
|
lx.next();
|
||||||
if ((rawMode === "client" || rawMode === "server") &&
|
if ((rawMode === "client" || rawMode === "server") &&
|
||||||
lx.peek().type === "ident" &&
|
lx.peek().type === "ident" &&
|
||||||
@@ -6824,52 +6756,15 @@ function parse(source) {
|
|||||||
states.push(...(0, v060_ts_1.parseStateDeclarations)(lx.readBalancedBraces(), rawMode));
|
states.push(...(0, v060_ts_1.parseStateDeclarations)(lx.readBalancedBraces(), rawMode));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (mode === "client" && lx.peek().type === "eq") {
|
if (rawMode === "client" && lx.peek().type === "eq") {
|
||||||
lx.next();
|
lx.next();
|
||||||
hydrate = expect("string").value;
|
hydrate = expect("string").value;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
expect("lbrace");
|
if (lx.peek().type === "lbrace") {
|
||||||
while (lx.peek().type !== "rbrace") {
|
throw new ParseError(`"${rawMode} { … }" data blocks were removed. Declare API calls in a page-level "apis { }" block, and move mode-scoped helpers into "functions { shared function … }".`);
|
||||||
const member = lx.peek();
|
|
||||||
if (member.type === "eof") {
|
|
||||||
throw new ParseError(`Unexpected end of input inside ${mode} block`);
|
|
||||||
}
|
|
||||||
if (member.type !== "ident") {
|
|
||||||
throw new ParseError(`Expected a ${mode} member keyword at offset ${member.pos}`);
|
|
||||||
}
|
|
||||||
switch (member.value) {
|
|
||||||
case "api": {
|
|
||||||
lx.next();
|
|
||||||
const name = expect("ident").value;
|
|
||||||
const method = expect("ident").value.toUpperCase();
|
|
||||||
const path = lx.readPath();
|
|
||||||
const body = lx.readBalancedBraces();
|
|
||||||
const sections = (0, api_sections_ts_1.parseApiSections)(body);
|
|
||||||
if (sections && mode !== "client" && (0, api_sections_ts_1.hasRequestSection)(body)) {
|
|
||||||
throw new ParseError(`An ssr api block cannot declare "request": there is no caller at render time to supply it. Use a client block, or a server function.`);
|
|
||||||
}
|
|
||||||
dataApis.push({
|
|
||||||
mode,
|
|
||||||
name,
|
|
||||||
method,
|
|
||||||
path,
|
|
||||||
body: sections ? "" : body,
|
|
||||||
...(sections ? { sections } : {}),
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "functions": {
|
|
||||||
lx.next();
|
|
||||||
modeFunctions.push({ mode, body: lx.readBalancedBraces() });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new ParseError(`Unknown ${mode} member '${member.value}' at offset ${member.pos}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
expect("rbrace");
|
throw new ParseError(`Expected a ${rawMode} state block or hydrate assignment`);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
case "shared": {
|
case "shared": {
|
||||||
lx.next();
|
lx.next();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// WRN editor extension source hash: 0da6296bd5dd1b84aece4ad5aed742c81deefefc4189ead29706be24c22d1cf9
|
// WRN editor extension source hash: feecaeb59a41771bd1a35be172bf89cec8451468a4bf817f176cc54de3d8267a
|
||||||
// WRN editor extension generator hash: 456d1d614e44e5fb1f19b784176c09cf2ade9b64ef73a17934c2698150b62728
|
// WRN editor extension generator hash: 456d1d614e44e5fb1f19b784176c09cf2ade9b64ef73a17934c2698150b62728
|
||||||
"use strict";
|
"use strict";
|
||||||
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// WRN editor language server source hash: 9614834cb7909e77f707aa31a8cc87ec6193ad642a81ee52870fd6872785fa4e
|
// WRN editor language server source hash: 613d98d8154714b7e5799b02a27e16cd707a50bc2b5ae7d9fbb3f0834b9251e6
|
||||||
// WRN editor language server generator hash: f593a44aaf05495b789ce7a3086bee1eebb951b884d41c0e017bbcfe5f547e72
|
// WRN editor language server generator hash: f593a44aaf05495b789ce7a3086bee1eebb951b884d41c0e017bbcfe5f547e72
|
||||||
// @bun @bun-cjs
|
// @bun @bun-cjs
|
||||||
(function(exports, require, module, __filename, __dirname) {var __create = Object.create;
|
(function(exports, require, module, __filename, __dirname) {var __create = Object.create;
|
||||||
@@ -170866,9 +170866,6 @@ function parseApiSections(source) {
|
|||||||
error: top.get("error")?.text ?? ""
|
error: top.get("error")?.text ?? ""
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function hasRequestSection(source) {
|
|
||||||
return scanTopLevelBlocks(source, SECTION_NAMES).has("request");
|
|
||||||
}
|
|
||||||
function parseApiEntries(source) {
|
function parseApiEntries(source) {
|
||||||
const entries = [];
|
const entries = [];
|
||||||
const lx = new Lexer(source);
|
const lx = new Lexer(source);
|
||||||
@@ -171749,7 +171746,6 @@ function parse(source) {
|
|||||||
case "client":
|
case "client":
|
||||||
case "server": {
|
case "server": {
|
||||||
const rawMode = kw.value;
|
const rawMode = kw.value;
|
||||||
const mode = rawMode === "client" ? "client" : "ssr";
|
|
||||||
lx.next();
|
lx.next();
|
||||||
if ((rawMode === "client" || rawMode === "server") && lx.peek().type === "ident" && lx.peek().value === "state") {
|
if ((rawMode === "client" || rawMode === "server") && lx.peek().type === "ident" && lx.peek().value === "state") {
|
||||||
lx.next();
|
lx.next();
|
||||||
@@ -171758,52 +171754,15 @@ function parse(source) {
|
|||||||
states.push(...parseStateDeclarations(lx.readBalancedBraces(), rawMode));
|
states.push(...parseStateDeclarations(lx.readBalancedBraces(), rawMode));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (mode === "client" && lx.peek().type === "eq") {
|
if (rawMode === "client" && lx.peek().type === "eq") {
|
||||||
lx.next();
|
lx.next();
|
||||||
hydrate = expect("string").value;
|
hydrate = expect("string").value;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
expect("lbrace");
|
if (lx.peek().type === "lbrace") {
|
||||||
while (lx.peek().type !== "rbrace") {
|
throw new ParseError(`"${rawMode} { … }" data blocks were removed. Declare API calls in a page-level "apis { }" block, and move mode-scoped helpers into "functions { shared function … }".`);
|
||||||
const member = lx.peek();
|
|
||||||
if (member.type === "eof") {
|
|
||||||
throw new ParseError(`Unexpected end of input inside ${mode} block`);
|
|
||||||
}
|
|
||||||
if (member.type !== "ident") {
|
|
||||||
throw new ParseError(`Expected a ${mode} member keyword at offset ${member.pos}`);
|
|
||||||
}
|
|
||||||
switch (member.value) {
|
|
||||||
case "api": {
|
|
||||||
lx.next();
|
|
||||||
const name2 = expect("ident").value;
|
|
||||||
const method = expect("ident").value.toUpperCase();
|
|
||||||
const path = lx.readPath();
|
|
||||||
const body = lx.readBalancedBraces();
|
|
||||||
const sections = parseApiSections(body);
|
|
||||||
if (sections && mode !== "client" && hasRequestSection(body)) {
|
|
||||||
throw new ParseError(`An ssr api block cannot declare "request": there is no caller at render time to supply it. Use a client block, or a server function.`);
|
|
||||||
}
|
|
||||||
dataApis.push({
|
|
||||||
mode,
|
|
||||||
name: name2,
|
|
||||||
method,
|
|
||||||
path,
|
|
||||||
body: sections ? "" : body,
|
|
||||||
...sections ? { sections } : {}
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "functions": {
|
|
||||||
lx.next();
|
|
||||||
modeFunctions.push({ mode, body: lx.readBalancedBraces() });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new ParseError(`Unknown ${mode} member '${member.value}' at offset ${member.pos}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
expect("rbrace");
|
throw new ParseError(`Expected a ${rawMode} state block or hydrate assignment`);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
case "shared": {
|
case "shared": {
|
||||||
lx.next();
|
lx.next();
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ page ApiBlockDemo {
|
|||||||
state found = ""
|
state found = ""
|
||||||
state failed = ""
|
state failed = ""
|
||||||
|
|
||||||
client {
|
apis {
|
||||||
api searchDirectory POST /api/directory {
|
searchDirectory POST /api/directory {
|
||||||
request {
|
request {
|
||||||
body {
|
body {
|
||||||
name?: string
|
name?: string
|
||||||
|
|||||||
@@ -18,37 +18,32 @@ page Hello {
|
|||||||
canonical = "/hello"
|
canonical = "/hello"
|
||||||
}
|
}
|
||||||
|
|
||||||
// SSR data bindings run on the server before the HTML is sent.
|
// API calls used by this page. `ssrUsers` is bound in the initial render
|
||||||
// The API itself lives in app/api/users/ssr.ts; this block only calls it
|
// (its endpoint lives in app/api/users/ssr.ts); `csrUsers` is bound after
|
||||||
// and renders the response into HTML.
|
// hydration in the browser (app/api/users/csr.ts). Both just call the same
|
||||||
ssr {
|
// users endpoint shape, so the response handling looks the same.
|
||||||
functions {
|
apis {
|
||||||
function userNames(users) {
|
ssrUsers GET /api/users/ssr {
|
||||||
return users.map((user) => user.name).join(", ")
|
response {
|
||||||
|
const visits = Number(cookies.get("hello_visits") ?? "0") + 1
|
||||||
|
cookies.set("hello_visits", String(visits), { sameSite: "Lax" })
|
||||||
|
session.set("lastHelloVisit", visits)
|
||||||
|
return `${userNames(data.users)} - visit ${visits}`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
api ssrUsers GET /api/users/ssr {
|
csrUsers GET /api/users/csr {
|
||||||
const visits = Number(cookies.get("hello_visits") ?? "0") + 1
|
response {
|
||||||
cookies.set("hello_visits", String(visits), { sameSite: "Lax" })
|
const label = localStorage.get("wrnexus.label") ?? "browser"
|
||||||
session.set("lastHelloVisit", visits)
|
session.set("lastClientLabel", label)
|
||||||
return `${userNames(users)} - visit ${visits}`
|
return `${userNames(data.users)} - ${label}`
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Client data bindings hydrate after the first paint. The browser only sees
|
functions {
|
||||||
// an opaque data-wrnexus-csr id; WrNexus calls app/api/users/csr.ts on the server.
|
shared function userNames(users) {
|
||||||
client {
|
return users.map((user) => user.name).join(", ")
|
||||||
functions {
|
|
||||||
function userNames(users) {
|
|
||||||
return users.map((user) => user.name).join(", ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
api csrUsers GET /api/users/csr {
|
|
||||||
const label = localStorage.get("wrnexus.label") ?? "browser"
|
|
||||||
session.set("lastClientLabel", label)
|
|
||||||
return `${userNames(users)} - ${label}`
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,309 +0,0 @@
|
|||||||
import { afterEach, expect, test } from "bun:test";
|
|
||||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { generateApplicationTypes } from "../src/types.ts";
|
|
||||||
|
|
||||||
const roots: string[] = [];
|
|
||||||
afterEach(() => {
|
|
||||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
/** Minimal app with one typed endpoint and one page that calls it. */
|
|
||||||
function fixture(block: string): string {
|
|
||||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-api-types-"));
|
|
||||||
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`,
|
|
||||||
);
|
|
||||||
writeFileSync(
|
|
||||||
join(root, "app/pages/search.wrn"),
|
|
||||||
`page Search {\n client {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
|
|
||||||
);
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BLOCK = ` api searchUsers POST /api/users {
|
|
||||||
request {
|
|
||||||
body {
|
|
||||||
name?: string
|
|
||||||
age?: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response {
|
|
||||||
return data.users
|
|
||||||
}
|
|
||||||
}`;
|
|
||||||
|
|
||||||
test("emits the ApiInput, ApiOutput and AssertAssignable helpers", () => {
|
|
||||||
const root = fixture(BLOCK);
|
|
||||||
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(BLOCK);
|
|
||||||
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("a legacy bare-body block produces no assertion", () => {
|
|
||||||
const root = fixture(` api legacyUsers GET /api/users {
|
|
||||||
return users.length
|
|
||||||
}`);
|
|
||||||
generateApplicationTypes(root);
|
|
||||||
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
|
|
||||||
|
|
||||||
expect(checks).not.toContain("__wrn_api_check_legacyUsers");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the api-checks file has no runtime code and is a module", () => {
|
|
||||||
const root = fixture(BLOCK);
|
|
||||||
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-api-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`,
|
|
||||||
);
|
|
||||||
writeFileSync(
|
|
||||||
join(root, "app/pages/one.wrn"),
|
|
||||||
`page One {\n client {\n${BLOCK}\n }\n\n view { <main>x</main> }\n}\n`,
|
|
||||||
);
|
|
||||||
writeFileSync(
|
|
||||||
join(root, "app/pages/two.wrn"),
|
|
||||||
`page Two {\n client {\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("B2: an ssr sectioned block emits no assertion (it can never declare a request)", () => {
|
|
||||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-api-types-ssr-"));
|
|
||||||
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 GET = async () => Response.json({ users: [] });\n`,
|
|
||||||
);
|
|
||||||
writeFileSync(
|
|
||||||
join(root, "app/pages/ssr.wrn"),
|
|
||||||
`page Ssr {\n ssr {\n api loadUsers GET /api/users {\n response {\n return data.users\n }\n }\n }\n\n view { <main>x</main> }\n}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
generateApplicationTypes(root);
|
|
||||||
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
|
|
||||||
|
|
||||||
expect(checks).not.toContain("__wrn_api_check");
|
|
||||||
expect(checks).not.toContain("loadUsers");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("B2: a client block with an empty request emits no assertion", () => {
|
|
||||||
const root = fixture(` api pingServer GET /api/users {
|
|
||||||
response {
|
|
||||||
return data.users
|
|
||||||
}
|
|
||||||
}`);
|
|
||||||
|
|
||||||
generateApplicationTypes(root);
|
|
||||||
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
|
|
||||||
|
|
||||||
expect(checks).not.toContain("__wrn_api_check");
|
|
||||||
expect(checks).not.toContain("pingServer");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("B6: each emitted assertion is exported, so noUnusedLocals cannot flag it", () => {
|
|
||||||
const root = fixture(BLOCK);
|
|
||||||
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-api-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 client {\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 = ` api 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(` api 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(` api 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(` api 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/);
|
|
||||||
});
|
|
||||||
@@ -378,14 +378,13 @@ function clientCalledApiNames(ast: PageAst): Set<string> {
|
|||||||
* never does either.
|
* never does either.
|
||||||
*/
|
*/
|
||||||
function assertNoDynamicApiAccess(ast: PageAst): void {
|
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
|
// 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
|
// 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
|
// block from the bundle. A page with no api blocks at all may still declare
|
||||||
// usage, and a page with no api blocks at all may still declare an
|
// an ordinary `state api` (see the B5 regression test) where a bare "api"
|
||||||
// ordinary `state api` (see the B5 regression test) where a bare "api"
|
|
||||||
// identifier is just that state, not a missed block reference.
|
// 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))) {
|
for (const fn of ast.runtimeFunctions.filter((fn) => ["client", "shared"].includes(fn.runtime))) {
|
||||||
const masked = maskStringsAndComments(fn.body);
|
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
|
* A block is emitted into the browser module when it declares typed sections
|
||||||
* client-only, or when it is mode "any" and a client function actually calls
|
* and a client function actually calls it. `hasClientApi` below must use this
|
||||||
* it. `hasClientApi` below must use this exact predicate so the `api`
|
* exact predicate so the `api` reserved-binding exclusion and the emitted
|
||||||
* reserved-binding exclusion and the emitted object can never disagree.
|
* object can never disagree.
|
||||||
*/
|
*/
|
||||||
function isClientEmittedApiBlock(block: PageAst["dataApis"][number], called: Set<string>): boolean {
|
function isClientEmittedApiBlock(block: PageAst["dataApis"][number], called: Set<string>): boolean {
|
||||||
return (
|
return Boolean(block.sections) && called.has(block.name);
|
||||||
Boolean(block.sections) &&
|
|
||||||
(block.mode === "client" || (block.mode === "any" && called.has(block.name)))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -567,29 +567,6 @@ function compileIfExpr(node: IfNode): string {
|
|||||||
return "${" + expr + "}";
|
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(
|
function renderNode(
|
||||||
node: ViewNode,
|
node: ViewNode,
|
||||||
ssrBindings: SsrBinding[],
|
ssrBindings: SsrBinding[],
|
||||||
@@ -741,39 +718,32 @@ function renderNode(
|
|||||||
const csrText = attrValue(node.attrs, "csrText");
|
const csrText = attrValue(node.attrs, "csrText");
|
||||||
|
|
||||||
const csrId =
|
const csrId =
|
||||||
apiBinding?.mode === "client"
|
csrGet && csrText
|
||||||
? csrMarker(csrBindings, renderBinding(apiBinding))
|
? csrMarker(csrBindings, {
|
||||||
: csrGet && csrText
|
method: "GET",
|
||||||
? csrMarker(csrBindings, {
|
path: apiRoutePath(csrGet),
|
||||||
method: "GET",
|
body: expressionBody(csrText),
|
||||||
path: apiRoutePath(csrGet),
|
helpers: "",
|
||||||
body: expressionBody(csrText),
|
})
|
||||||
helpers: "",
|
: undefined;
|
||||||
})
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
// Void elements (<br>, <img>, …) have no closing tag and no children.
|
// Void elements (<br>, <img>, …) have no closing tag and no children.
|
||||||
if (VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
if (VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
||||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const inner =
|
const inner = apiBinding
|
||||||
apiBinding?.mode === "ssr"
|
? apiCallMarker(loops, parsedApi!.name, parsedApi!.args)
|
||||||
? ssrMarker(ssrBindings, renderBinding(apiBinding))
|
: ssrGet && ssrText
|
||||||
: apiBinding?.mode === "any"
|
? ssrMarker(ssrBindings, {
|
||||||
? apiCallMarker(loops, parsedApi!.name, parsedApi!.args)
|
method: "GET",
|
||||||
: ssrGet && ssrText
|
path: apiRoutePath(ssrGet),
|
||||||
? ssrMarker(ssrBindings, {
|
body: expressionBody(ssrText),
|
||||||
method: "GET",
|
helpers: "",
|
||||||
path: apiRoutePath(ssrGet),
|
})
|
||||||
body: expressionBody(ssrText),
|
: node.children
|
||||||
helpers: "",
|
.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive))
|
||||||
})
|
.join("");
|
||||||
: node.children
|
|
||||||
.map((child) =>
|
|
||||||
renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive),
|
|
||||||
)
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>${inner}</${node.tag}>`;
|
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;
|
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 {
|
function hasClientBehavior(nodes: ViewNode[]): boolean {
|
||||||
return nodes.some((node) => {
|
return nodes.some((node) => {
|
||||||
// `{t:key}` is i18n sugar resolved server-side — not client reactivity.
|
// `{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);
|
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> {
|
function apiBindingMap(ast: PageAst, sharedHelpers: string): Map<string, NamedDataBinding> {
|
||||||
const bindings = new 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
|
// legacy blocks and sectioned blocks without `error` keep failures
|
||||||
// propagating exactly as before.
|
// propagating exactly as before.
|
||||||
...(errorSection ? { errorBody: errorSection } : {}),
|
...(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[] = [];
|
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 needsSsrRuntime = ssrBindings.length > 0 || loops.length > 0 || runtimeStateNames.size > 0;
|
||||||
const needsRuntimeHelpers = needsSsrRuntime || hasServerApis;
|
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");
|
|
||||||
});
|
|
||||||
@@ -1,10 +1,5 @@
|
|||||||
import { WRN_RUNTIME_TARGETS } from "./spec.ts";
|
import { WRN_RUNTIME_TARGETS } from "./spec.ts";
|
||||||
import {
|
import { parseApiEntries, type ApiSections } from "./api-sections.ts";
|
||||||
parseApiSections,
|
|
||||||
parseApiEntries,
|
|
||||||
hasRequestSection,
|
|
||||||
type ApiSections,
|
|
||||||
} from "./api-sections.ts";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recursive-descent parser for `.wrn`, producing a small AST.
|
* Recursive-descent parser for `.wrn`, producing a small AST.
|
||||||
@@ -147,7 +142,7 @@ export interface ApiBlock {
|
|||||||
|
|
||||||
export type SeoBlock = Record<string, string>;
|
export type SeoBlock = Record<string, string>;
|
||||||
|
|
||||||
export type DataMode = "ssr" | "client" | "any";
|
export type DataMode = "any";
|
||||||
|
|
||||||
export interface DataApiBlock {
|
export interface DataApiBlock {
|
||||||
mode: DataMode;
|
mode: DataMode;
|
||||||
@@ -669,7 +664,6 @@ export function parse(source: string): PageAst {
|
|||||||
case "client":
|
case "client":
|
||||||
case "server": {
|
case "server": {
|
||||||
const rawMode = kw.value;
|
const rawMode = kw.value;
|
||||||
const mode: DataMode = rawMode === "client" ? "client" : "ssr";
|
|
||||||
lx.next();
|
lx.next();
|
||||||
if (
|
if (
|
||||||
(rawMode === "client" || rawMode === "server") &&
|
(rawMode === "client" || rawMode === "server") &&
|
||||||
@@ -684,56 +678,17 @@ export function parse(source: string): PageAst {
|
|||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (mode === "client" && lx.peek().type === "eq") {
|
if (rawMode === "client" && lx.peek().type === "eq") {
|
||||||
lx.next();
|
lx.next();
|
||||||
hydrate = expect("string").value;
|
hydrate = expect("string").value;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
expect("lbrace");
|
if (lx.peek().type === "lbrace") {
|
||||||
while (lx.peek().type !== "rbrace") {
|
throw new ParseError(
|
||||||
const member = lx.peek();
|
`"${rawMode} { … }" data blocks were removed. Declare API calls in a page-level "apis { }" block, and move mode-scoped helpers into "functions { shared function … }".`,
|
||||||
if (member.type === "eof") {
|
);
|
||||||
throw new ParseError(`Unexpected end of input inside ${mode} block`);
|
|
||||||
}
|
|
||||||
if (member.type !== "ident") {
|
|
||||||
throw new ParseError(`Expected a ${mode} member keyword at offset ${member.pos}`);
|
|
||||||
}
|
|
||||||
switch (member.value) {
|
|
||||||
case "api": {
|
|
||||||
lx.next();
|
|
||||||
const name = expect("ident").value;
|
|
||||||
const method = expect("ident").value.toUpperCase();
|
|
||||||
const path = lx.readPath();
|
|
||||||
const body = lx.readBalancedBraces();
|
|
||||||
const sections = parseApiSections(body);
|
|
||||||
if (sections && mode !== "client" && hasRequestSection(body)) {
|
|
||||||
throw new ParseError(
|
|
||||||
`An ssr api block cannot declare "request": there is no caller at render time to supply it. Use a client block, or a server function.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
dataApis.push({
|
|
||||||
mode,
|
|
||||||
name,
|
|
||||||
method,
|
|
||||||
path,
|
|
||||||
body: sections ? "" : body,
|
|
||||||
...(sections ? { sections } : {}),
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "functions": {
|
|
||||||
lx.next();
|
|
||||||
modeFunctions.push({ mode, body: lx.readBalancedBraces() });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new ParseError(
|
|
||||||
`Unknown ${mode} member '${member.value}' at offset ${member.pos}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
expect("rbrace");
|
throw new ParseError(`Expected a ${rawMode} state block or hydrate assignment`);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
case "shared": {
|
case "shared": {
|
||||||
lx.next();
|
lx.next();
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
import { expect, test } from "bun:test";
|
|
||||||
import { parse } from "../src/index.ts";
|
|
||||||
|
|
||||||
const page = (inner: string) => `page Repro {
|
|
||||||
client {
|
|
||||||
${inner}
|
|
||||||
}
|
|
||||||
|
|
||||||
view { <main>x</main> }
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
|
|
||||||
test("parses a sectioned api block into request, response and error", () => {
|
|
||||||
const ast = parse(
|
|
||||||
page(` api searchUsers POST /api/users {
|
|
||||||
request {
|
|
||||||
body {
|
|
||||||
name?: string
|
|
||||||
age?: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response {
|
|
||||||
return data.users
|
|
||||||
}
|
|
||||||
|
|
||||||
error {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}`),
|
|
||||||
);
|
|
||||||
|
|
||||||
const block = ast.dataApis[0]!;
|
|
||||||
expect(block.name).toBe("searchUsers");
|
|
||||||
expect(block.method).toBe("POST");
|
|
||||||
expect(block.path).toBe("/api/users");
|
|
||||||
expect(block.sections?.body).toEqual([
|
|
||||||
{ name: "name", optional: true, type: "string" },
|
|
||||||
{ name: "age", optional: true, type: "number" },
|
|
||||||
]);
|
|
||||||
expect(block.sections?.response.trim()).toBe("return data.users");
|
|
||||||
expect(block.sections?.error.trim()).toBe("return []");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a bare body still parses as the legacy response body", () => {
|
|
||||||
const ast = parse(
|
|
||||||
page(` api legacyUsers GET /api/users {
|
|
||||||
return users.length
|
|
||||||
}`),
|
|
||||||
);
|
|
||||||
|
|
||||||
const block = ast.dataApis[0]!;
|
|
||||||
expect(block.sections).toBeUndefined();
|
|
||||||
expect(block.body.trim()).toBe("return users.length");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("GET parameters are parsed as required when not marked optional", () => {
|
|
||||||
const ast = parse(
|
|
||||||
page(` api listUsers GET /api/users {
|
|
||||||
request {
|
|
||||||
parameters {
|
|
||||||
team: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response {
|
|
||||||
return data.users
|
|
||||||
}
|
|
||||||
}`),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(ast.dataApis[0]!.sections?.parameters).toEqual([
|
|
||||||
{ name: "team", optional: false, type: "string" },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("request inside an ssr block is rejected with a message naming the restriction", () => {
|
|
||||||
const source = `page Repro {
|
|
||||||
ssr {
|
|
||||||
api ssrUsers GET /api/users {
|
|
||||||
request {
|
|
||||||
parameters {
|
|
||||||
team: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
response {
|
|
||||||
return data.users
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
view { <main>x</main> }
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
|
|
||||||
expect(() => parse(source)).toThrow(/ssr[\s\S]*request/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a brace inside a string literal in the response body does not truncate the section", () => {
|
|
||||||
const ast = parse(
|
|
||||||
page(` api 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 []");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a legacy block whose comment or string mentions a section keyword stays legacy", () => {
|
|
||||||
const ast = parse(
|
|
||||||
page(` api legacyUsers GET /api/users {
|
|
||||||
// fall back to a manual request { } if this fails
|
|
||||||
return "response { not a section }"
|
|
||||||
}`),
|
|
||||||
);
|
|
||||||
|
|
||||||
const block = ast.dataApis[0]!;
|
|
||||||
expect(block.sections).toBeUndefined();
|
|
||||||
expect(block.body.trim()).toBe(
|
|
||||||
'// fall back to a manual request { } if this fails\n return "response { not a section }"',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -74,28 +74,12 @@ test("a bare body inside apis {} is a parse error naming response", () => {
|
|||||||
expect(() => parse(page(` bare GET /api/z { return data }`))).toThrow(/response/i);
|
expect(() => parse(page(` bare GET /api/z { return data }`))).toThrow(/response/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("apis entry followed by an ssr api of the same name is rejected", () => {
|
test("two apis entries of the same name across separate blocks are rejected", () => {
|
||||||
const src = `page Repro {
|
const src = `page Repro {
|
||||||
apis {
|
apis {
|
||||||
foo GET /api/foo { response { return data } }
|
foo GET /api/foo { response { return data } }
|
||||||
}
|
}
|
||||||
|
|
||||||
ssr {
|
|
||||||
api foo GET /api/foo { return data }
|
|
||||||
}
|
|
||||||
|
|
||||||
view { <main>x</main> }
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
expect(() => parse(src)).toThrow(/duplicate/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ssr api followed by an apis entry of the same name is rejected", () => {
|
|
||||||
const src = `page Repro {
|
|
||||||
ssr {
|
|
||||||
api foo GET /api/foo { return data }
|
|
||||||
}
|
|
||||||
|
|
||||||
apis {
|
apis {
|
||||||
foo GET /api/foo { response { return data } }
|
foo GET /api/foo { response { return data } }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { expect, test } from "bun:test";
|
||||||
|
import { parse } from "../src/index.ts";
|
||||||
|
|
||||||
|
test("an ssr data block is rejected and names the replacement", () => {
|
||||||
|
expect(() =>
|
||||||
|
parse(`page P {
|
||||||
|
ssr { api x GET /api/x { return users } }
|
||||||
|
view { <main>x</main> }
|
||||||
|
}
|
||||||
|
`),
|
||||||
|
).toThrow(/apis/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a client data block is rejected and names the replacement", () => {
|
||||||
|
expect(() =>
|
||||||
|
parse(`page P {
|
||||||
|
client { api x GET /api/x { return users } }
|
||||||
|
view { <main>x</main> }
|
||||||
|
}
|
||||||
|
`),
|
||||||
|
).toThrow(/apis/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("client state is unaffected", () => {
|
||||||
|
// Different construct sharing the keyword. It must keep working.
|
||||||
|
const ast = parse(`page P {
|
||||||
|
client state { count = 0 }
|
||||||
|
view { <main>x</main> }
|
||||||
|
}
|
||||||
|
`);
|
||||||
|
|
||||||
|
expect(ast.states.some((state) => state.name === "count")).toBe(true);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user