clarusjs 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/check/generate.d.ts +27 -0
- package/dist/check/generate.js +234 -0
- package/dist/cli/check.d.ts +17 -0
- package/dist/cli/check.js +101 -0
- package/dist/cli/explain.d.ts +9 -0
- package/dist/cli/explain.js +56 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +38 -0
- package/dist/compiler/emit-client.js +2 -0
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -2
- package/dist/compiler/errors.d.ts +1 -1
- package/dist/compiler/errors.js +1 -1
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +1 -1
- package/dist/compiler/ir.d.ts +2 -1
- package/dist/compiler/ir.js +14 -4
- package/dist/compiler/parse.d.ts +22 -0
- package/dist/compiler/parse.js +52 -14
- package/dist/compiler/script.d.ts +5 -1
- package/dist/compiler/script.js +2 -1
- package/dist/runtime/router.d.ts +15 -0
- package/dist/runtime/router.js +101 -0
- package/dist/server/handler.d.ts +25 -1
- package/dist/server/handler.js +170 -9
- package/dist/server/manifest.d.ts +4 -0
- package/dist/server/manifest.js +17 -0
- package/dist/server/modes.d.ts +6 -0
- package/dist/server/modes.js +28 -0
- package/dist/server/views.d.ts +17 -0
- package/dist/server/views.js +23 -0
- package/dist/vite/build.d.ts +18 -5
- package/dist/vite/build.js +49 -12
- package/dist/vite/manifest.d.ts +49 -0
- package/dist/vite/manifest.js +86 -0
- package/dist/vite/netlify.d.ts +4 -0
- package/dist/vite/netlify.js +46 -0
- package/dist/vite/plugin.d.ts +8 -1
- package/dist/vite/plugin.js +134 -20
- package/package.json +14 -2
package/dist/compiler/ir.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Syntax tree → IR: static HTML chunks, holes (reactive or not), child components, events. Build-time checks live here.
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
|
+
import { importNames } from './parse.js';
|
|
3
4
|
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
4
5
|
const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
|
|
5
6
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
@@ -11,6 +12,14 @@ export function lower(parsed, file, source) {
|
|
|
11
12
|
// A hole is reactive if it reads anything the script declares: a signal directly, or a function/value that may read one.
|
|
12
13
|
// text()'s effect tracks the real dependencies, so over-marking only costs a pair of comment markers.
|
|
13
14
|
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
15
|
+
for (const d of parsed.dataImports) {
|
|
16
|
+
// In an island the import is bundled for the browser, like a script import.
|
|
17
|
+
if (stateful && d.from.startsWith('node:'))
|
|
18
|
+
fail(`\`${d.from}\` can't be imported in an island: its imports are bundled for the browser`, d.start);
|
|
19
|
+
if (stateful)
|
|
20
|
+
for (const name of importNames(d.clause))
|
|
21
|
+
scriptScope.add(name);
|
|
22
|
+
}
|
|
14
23
|
const components = new Set(parsed.imports.map((i) => i.name));
|
|
15
24
|
const nodes = [];
|
|
16
25
|
let out = nodes; // where lowering writes; switched while lowering a component's children
|
|
@@ -60,9 +69,9 @@ export function lower(parsed, file, source) {
|
|
|
60
69
|
return;
|
|
61
70
|
}
|
|
62
71
|
if (node.type === 'for') {
|
|
63
|
-
checkExpr(node.list, file, source, node.
|
|
72
|
+
checkExpr(node.list, file, source, node.listStart);
|
|
64
73
|
if (node.track !== null)
|
|
65
|
-
checkExpr(node.track, file, source, node.
|
|
74
|
+
checkExpr(node.track, file, source, node.trackStart);
|
|
66
75
|
const block = stateful ? forCount++ : -1;
|
|
67
76
|
const parent = out;
|
|
68
77
|
const parentScope = scopeKey;
|
|
@@ -209,11 +218,12 @@ export function lower(parsed, file, source) {
|
|
|
209
218
|
parsed.nodes.forEach((n) => visit(n));
|
|
210
219
|
return {
|
|
211
220
|
file,
|
|
212
|
-
name: file.split('/').pop().replace(/\.
|
|
221
|
+
name: file.split('/').pop().replace(/\.tscl$/, ''),
|
|
213
222
|
inputs: parsed.inputs,
|
|
214
223
|
imports: parsed.imports,
|
|
215
224
|
script: parsed.script ? split.body : undefined,
|
|
216
|
-
scriptImports: split.imports,
|
|
225
|
+
scriptImports: split.imports.map((imp) => imp.text),
|
|
226
|
+
dataImports: parsed.dataImports,
|
|
217
227
|
signals,
|
|
218
228
|
stateful,
|
|
219
229
|
nodes,
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -59,6 +59,9 @@ export type TemplateNode = {
|
|
|
59
59
|
list: string;
|
|
60
60
|
track: string | null;
|
|
61
61
|
headStart: number;
|
|
62
|
+
itemStart: number;
|
|
63
|
+
listStart: number;
|
|
64
|
+
trackStart: number;
|
|
62
65
|
children: TemplateNode[];
|
|
63
66
|
empty: TemplateNode[] | null;
|
|
64
67
|
start: number;
|
|
@@ -68,6 +71,21 @@ export type InputDecl = {
|
|
|
68
71
|
type: string;
|
|
69
72
|
default?: string;
|
|
70
73
|
start: number;
|
|
74
|
+
nameStart: number;
|
|
75
|
+
typeStart: number;
|
|
76
|
+
defaultStart?: number;
|
|
77
|
+
};
|
|
78
|
+
export type TypeImport = {
|
|
79
|
+
clause: string;
|
|
80
|
+
from: string;
|
|
81
|
+
start: number;
|
|
82
|
+
clauseStart: number;
|
|
83
|
+
};
|
|
84
|
+
export type DataImport = {
|
|
85
|
+
clause: string;
|
|
86
|
+
from: string;
|
|
87
|
+
start: number;
|
|
88
|
+
clauseStart: number;
|
|
71
89
|
};
|
|
72
90
|
export type ImportDecl = {
|
|
73
91
|
name: string;
|
|
@@ -77,6 +95,8 @@ export type ImportDecl = {
|
|
|
77
95
|
export type ParsedFile = {
|
|
78
96
|
inputs: InputDecl[];
|
|
79
97
|
imports: ImportDecl[];
|
|
98
|
+
typeImports: TypeImport[];
|
|
99
|
+
dataImports: DataImport[];
|
|
80
100
|
script?: {
|
|
81
101
|
code: string;
|
|
82
102
|
start: number;
|
|
@@ -84,3 +104,5 @@ export type ParsedFile = {
|
|
|
84
104
|
nodes: TemplateNode[];
|
|
85
105
|
};
|
|
86
106
|
export declare function parse(source: string, file: string): ParsedFile;
|
|
107
|
+
/** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
|
|
108
|
+
export declare function importNames(clause: string): string[];
|
package/dist/compiler/parse.js
CHANGED
|
@@ -1,21 +1,37 @@
|
|
|
1
|
-
// .
|
|
1
|
+
// .tscl source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
3
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
4
|
-
const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s
|
|
4
|
+
const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/d;
|
|
5
|
+
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
6
|
+
const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
5
7
|
const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
|
|
6
8
|
export function parse(source, file) {
|
|
7
|
-
const out = { inputs: [], imports: [], nodes: [] };
|
|
9
|
+
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], nodes: [] };
|
|
8
10
|
let i = 0;
|
|
9
11
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
10
12
|
const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
|
|
11
13
|
function directive() {
|
|
12
14
|
const end = source.indexOf('\n', i) === -1 ? source.length : source.indexOf('\n', i);
|
|
15
|
+
const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
|
|
13
16
|
const line = source.slice(i, end).trim();
|
|
14
17
|
let m;
|
|
15
|
-
if ((m =
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
if ((m = INPUT_RE.exec(line))) {
|
|
19
|
+
const at = (group) => lineStart + m.indices[group][0];
|
|
20
|
+
out.inputs.push({ name: m[1], type: m[2].trim(), default: m[3], start: i, nameStart: at(1), typeStart: at(2), ...(m[3] ? { defaultStart: at(3) } : {}) });
|
|
21
|
+
}
|
|
22
|
+
else if ((m = IMPORT_TYPE_RE.exec(line))) {
|
|
23
|
+
out.typeImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
|
|
24
|
+
}
|
|
25
|
+
else if ((m = DATA_IMPORT_RE.exec(line))) {
|
|
26
|
+
out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
|
|
27
|
+
}
|
|
28
|
+
else if ((m = line.match(IMPORT_RE))) {
|
|
29
|
+
// A default import of a .tscl file is a component; of anything else, data.
|
|
30
|
+
if (m[3].endsWith('.tscl'))
|
|
31
|
+
out.imports.push({ name: m[1], from: m[3], start: i });
|
|
32
|
+
else
|
|
33
|
+
out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + line.indexOf(m[1], 7) });
|
|
34
|
+
}
|
|
19
35
|
else
|
|
20
36
|
fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
|
|
21
37
|
i = end;
|
|
@@ -177,8 +193,14 @@ export function parse(source, file) {
|
|
|
177
193
|
return { type: 'if', branches, start };
|
|
178
194
|
}
|
|
179
195
|
// Split at top-level ';' (outside strings and brackets).
|
|
196
|
+
/** Top-level `;` clauses, trimmed, each with its offset in `text`. */
|
|
180
197
|
function splitClauses(text) {
|
|
181
198
|
const parts = [];
|
|
199
|
+
const push = (from, to) => {
|
|
200
|
+
const raw = text.slice(from, to);
|
|
201
|
+
if (raw.trim())
|
|
202
|
+
parts.push({ text: raw.trim(), start: from + raw.length - raw.trimStart().length });
|
|
203
|
+
};
|
|
182
204
|
let depth = 0;
|
|
183
205
|
let from = 0;
|
|
184
206
|
for (let j = 0; j < text.length; j++) {
|
|
@@ -193,29 +215,38 @@ export function parse(source, file) {
|
|
|
193
215
|
else if (')]}'.includes(c))
|
|
194
216
|
depth--;
|
|
195
217
|
else if (c === ';' && depth === 0) {
|
|
196
|
-
|
|
218
|
+
push(from, j);
|
|
197
219
|
from = j + 1;
|
|
198
220
|
}
|
|
199
221
|
}
|
|
200
|
-
|
|
222
|
+
push(from, text.length);
|
|
223
|
+
return parts;
|
|
201
224
|
}
|
|
202
225
|
// @for (item of list; track key) { … } @empty { … }
|
|
203
226
|
function forBlock() {
|
|
204
227
|
const start = i;
|
|
205
228
|
i += 4;
|
|
206
229
|
const { cond: head, condStart: headStart } = condition('@for');
|
|
207
|
-
|
|
208
|
-
|
|
230
|
+
// Where `head` (trimmed) starts in the source, so every part below gets its exact offset.
|
|
231
|
+
let at = headStart;
|
|
232
|
+
while (/\s/.test(source[at] ?? ''))
|
|
233
|
+
at++;
|
|
234
|
+
const [first = { text: '', start: 0 }, ...rest] = splitClauses(head);
|
|
235
|
+
const m = /^([\s\S]+?)\s+of\s+([\s\S]+)$/d.exec(first.text);
|
|
209
236
|
if (!m)
|
|
210
237
|
fail('expected "item of list" in @for', headStart);
|
|
211
238
|
if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
|
|
212
239
|
fail('the @for item must be a simple name', headStart);
|
|
240
|
+
const itemStart = at + first.start + m.indices[1][0];
|
|
241
|
+
const listStart = at + first.start + m.indices[2][0];
|
|
213
242
|
let track = null;
|
|
243
|
+
let trackStart = -1;
|
|
214
244
|
for (const clause of rest) {
|
|
215
|
-
const t = /^track\s+([\s\S]+)
|
|
245
|
+
const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
|
|
216
246
|
if (!t)
|
|
217
|
-
fail(`unknown @for clause "${clause}"`, headStart);
|
|
247
|
+
fail(`unknown @for clause "${clause.text}"`, headStart);
|
|
218
248
|
track = t[1].trim();
|
|
249
|
+
trackStart = at + clause.start + t.indices[1][0];
|
|
219
250
|
}
|
|
220
251
|
while (/\s/.test(source[i] ?? ''))
|
|
221
252
|
i++;
|
|
@@ -238,7 +269,7 @@ export function parse(source, file) {
|
|
|
238
269
|
}
|
|
239
270
|
else
|
|
240
271
|
i = save;
|
|
241
|
-
return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, children: body, empty, start };
|
|
272
|
+
return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
|
|
242
273
|
}
|
|
243
274
|
// @slot('name') { … }: content for a component's named slot.
|
|
244
275
|
function fillBlock() {
|
|
@@ -382,3 +413,10 @@ export function parse(source, file) {
|
|
|
382
413
|
out.nodes = children();
|
|
383
414
|
return out;
|
|
384
415
|
}
|
|
416
|
+
/** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
|
|
417
|
+
export function importNames(clause) {
|
|
418
|
+
if (!clause.startsWith('{'))
|
|
419
|
+
return [clause];
|
|
420
|
+
return clause.slice(1, -1).split(',').map((p) => p.trim()).filter((p) => p && !p.startsWith('type '))
|
|
421
|
+
.map((p) => p.split(/\s+as\s+/).pop().trim());
|
|
422
|
+
}
|
|
@@ -14,8 +14,12 @@ export declare function scriptNames(code: string): Set<string>;
|
|
|
14
14
|
* blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
|
|
15
15
|
* Island scripts are bundled for the browser, so `node:` imports are a build error.
|
|
16
16
|
*/
|
|
17
|
+
/** Import statements (text and offset in `code`), and the body with them blanked out. */
|
|
17
18
|
export declare function splitImports(code: string, file: string, source: string, offset: number): {
|
|
18
|
-
imports:
|
|
19
|
+
imports: {
|
|
20
|
+
text: string;
|
|
21
|
+
start: number;
|
|
22
|
+
}[];
|
|
19
23
|
body: string;
|
|
20
24
|
};
|
|
21
25
|
export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
|
package/dist/compiler/script.js
CHANGED
|
@@ -199,6 +199,7 @@ function signalCall(init) {
|
|
|
199
199
|
* blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
|
|
200
200
|
* Island scripts are bundled for the browser, so `node:` imports are a build error.
|
|
201
201
|
*/
|
|
202
|
+
/** Import statements (text and offset in `code`), and the body with them blanked out. */
|
|
202
203
|
export function splitImports(code, file, source, offset) {
|
|
203
204
|
const imports = [];
|
|
204
205
|
let body = code;
|
|
@@ -209,7 +210,7 @@ export function splitImports(code, file, source, offset) {
|
|
|
209
210
|
if (from.startsWith('node:')) {
|
|
210
211
|
throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
|
|
211
212
|
}
|
|
212
|
-
imports.push(code.slice(stmt.start, stmt.end));
|
|
213
|
+
imports.push({ text: code.slice(stmt.start, stmt.end), start: stmt.start });
|
|
213
214
|
body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
|
|
214
215
|
}
|
|
215
216
|
return { imports, body };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Entry = {
|
|
2
|
+
p: string;
|
|
3
|
+
r: string;
|
|
4
|
+
};
|
|
5
|
+
type Page = {
|
|
6
|
+
render(props: object): string;
|
|
7
|
+
};
|
|
8
|
+
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
9
|
+
export declare function matchRoute(table: Entry[], pathname: string): {
|
|
10
|
+
r: string;
|
|
11
|
+
params: Record<string, string>;
|
|
12
|
+
} | null;
|
|
13
|
+
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
14
|
+
export declare function show(url: URL, table: Entry[], load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<boolean>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
// Client router: renders client-mode routes in the browser. Browser only. The server sends a shell with the client
|
|
10
|
+
// route table; the router loads the page's render module and its <path>/__data.json, swaps the document, and lets
|
|
11
|
+
// the island loader attach. Later navigations between client routes are intercepted with the Navigation API;
|
|
12
|
+
// browsers without it simply load pages normally.
|
|
13
|
+
import { parse } from './serialize.js';
|
|
14
|
+
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
15
|
+
export function matchRoute(table, pathname) {
|
|
16
|
+
const got = pathname.replace(/(.)\/+$/, '$1').split('/');
|
|
17
|
+
try {
|
|
18
|
+
for (const { p, r } of table) {
|
|
19
|
+
const want = p.split('/');
|
|
20
|
+
const params = {};
|
|
21
|
+
// Segment by segment: a [param] takes any one non-empty segment, anything else must be equal.
|
|
22
|
+
const hit = want.length === got.length && want.every((w, i) => {
|
|
23
|
+
const key = /^\[([A-Za-z_$][\w$]*)\]$/.exec(w)?.[1];
|
|
24
|
+
if (key === undefined)
|
|
25
|
+
return w === got[i];
|
|
26
|
+
params[key] = decodeURIComponent(got[i]);
|
|
27
|
+
return got[i] !== '';
|
|
28
|
+
});
|
|
29
|
+
if (hit)
|
|
30
|
+
return { r, params };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch { } // a malformed %-escape names no page
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
37
|
+
export async function show(url, table, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch,
|
|
38
|
+
// False once a newer navigation has started: then this one must not touch the document.
|
|
39
|
+
isCurrent = () => true) {
|
|
40
|
+
const found = matchRoute(table, url.pathname);
|
|
41
|
+
if (!found)
|
|
42
|
+
return false;
|
|
43
|
+
const data = `${url.pathname.replace(/\/+$/, '')}/__data.json`;
|
|
44
|
+
const [page, props] = await Promise.all([
|
|
45
|
+
load(found.r),
|
|
46
|
+
get(data).then(async (res) => {
|
|
47
|
+
if (!res.ok)
|
|
48
|
+
throw new Error(`${res.status === 404 ? 'not found' : res.status}: ${data}`);
|
|
49
|
+
return parse(await res.text());
|
|
50
|
+
}),
|
|
51
|
+
]);
|
|
52
|
+
if (!isCurrent())
|
|
53
|
+
return false;
|
|
54
|
+
const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
|
|
55
|
+
const style = doc.createElement('style');
|
|
56
|
+
style.textContent = 'cl-island{display:contents}'; // islands never affect layout
|
|
57
|
+
doc.head.append(style);
|
|
58
|
+
// The page's <title> comes with its head; its own <html> attributes (lang, dir, …) replace the previous page's.
|
|
59
|
+
const root = document.documentElement;
|
|
60
|
+
for (const { name } of [...root.attributes])
|
|
61
|
+
root.removeAttribute(name);
|
|
62
|
+
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
|
+
root.setAttribute(name, value);
|
|
64
|
+
document.head.replaceWith(doc.head);
|
|
65
|
+
document.body.replaceWith(doc.body);
|
|
66
|
+
globalThis.__clAttach?.(document.body);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
const routes = typeof document !== 'undefined' ? document.getElementById('cl-routes') : null;
|
|
70
|
+
if (routes) {
|
|
71
|
+
const table = JSON.parse(routes.textContent ?? '[]');
|
|
72
|
+
// Each navigation gets a number; only the latest may change the document or fall back.
|
|
73
|
+
let latest = 1; // the first render is navigation 1
|
|
74
|
+
show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
|
|
75
|
+
if (latest !== 1)
|
|
76
|
+
return;
|
|
77
|
+
document.body.textContent = err.message.startsWith('not found') ? 'Page not found.' : 'Could not load this page.';
|
|
78
|
+
});
|
|
79
|
+
// A URL that failed to render is loaded normally, never intercepted again (no retry loop). canIntercept is
|
|
80
|
+
// only true for same-origin navigations, so no origin check is needed.
|
|
81
|
+
let fallback = '';
|
|
82
|
+
const navigation = globalThis.navigation;
|
|
83
|
+
navigation?.addEventListener('navigate', (event) => {
|
|
84
|
+
const e = event;
|
|
85
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
|
|
86
|
+
return;
|
|
87
|
+
const url = new URL(e.destination.url);
|
|
88
|
+
if (url.href === fallback || !matchRoute(table, url.pathname))
|
|
89
|
+
return;
|
|
90
|
+
const id = ++latest;
|
|
91
|
+
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
92
|
+
e.intercept({
|
|
93
|
+
handler: () => show(url, table, undefined, undefined, isCurrent).then(() => { }, () => {
|
|
94
|
+
if (!isCurrent())
|
|
95
|
+
return;
|
|
96
|
+
fallback = url.href;
|
|
97
|
+
location.assign(url.href);
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -1,12 +1,36 @@
|
|
|
1
|
+
import { type ModeTable } from './modes.ts';
|
|
1
2
|
type PageModule = {
|
|
2
3
|
render(props?: object): string;
|
|
3
4
|
};
|
|
4
|
-
|
|
5
|
+
type Params = Record<string, string>;
|
|
6
|
+
/**
|
|
7
|
+
* `[page].load.ts`: data for a route, server only. entries() lists a dynamic route's pages to prerender; load()
|
|
8
|
+
* returns the page's inputs and runs per request on the server, or once per page at build.
|
|
9
|
+
*/
|
|
10
|
+
type DataModule = {
|
|
11
|
+
entries?(): Params[] | Promise<Params[]>;
|
|
12
|
+
load?(context: {
|
|
13
|
+
params: Params;
|
|
14
|
+
request: Request;
|
|
15
|
+
}): object | Promise<object>;
|
|
16
|
+
};
|
|
17
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
|
|
5
18
|
export declare function routeFromFile(file: string): string;
|
|
6
19
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
7
20
|
loaderUrl?: string;
|
|
21
|
+
data?: Record<string, () => Promise<DataModule>>;
|
|
22
|
+
modes?: ModeTable;
|
|
23
|
+
/** Client routes (as their files name them) → URL of the page's browser render module. */
|
|
24
|
+
client?: Record<string, string>;
|
|
25
|
+
routerUrl?: string;
|
|
26
|
+
/** Vite's base ('/' or '/docs/'): client routes are listed at their browser paths, under it. */
|
|
27
|
+
base?: string;
|
|
8
28
|
}): {
|
|
9
29
|
fetch(request: Request): Promise<Response>;
|
|
10
30
|
routes: string[];
|
|
31
|
+
serverRoutes: string[];
|
|
32
|
+
paths(): Promise<string[]>;
|
|
33
|
+
hasLoader(route: string): Promise<boolean>;
|
|
34
|
+
isServerPath(pathname: string): boolean;
|
|
11
35
|
};
|
|
12
36
|
export {};
|
package/dist/server/handler.js
CHANGED
|
@@ -1,24 +1,180 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { modeFor } from './modes.js';
|
|
2
|
+
import { stringify } from '../runtime/serialize.js';
|
|
3
|
+
const DATA = '__data.json';
|
|
4
|
+
/** JSON that is safe inside a <script> element and in any HTML context: '<' never appears raw. */
|
|
5
|
+
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
6
|
+
/** A whole path segment that is a parameter: [id], [$id]. Anything else, like v[2], is literal text. */
|
|
7
|
+
const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
|
|
8
|
+
/** '/users/[id]' → keys ['id'] and a RegExp that captures each segment. */
|
|
9
|
+
function compile(path) {
|
|
10
|
+
const keys = [];
|
|
11
|
+
const source = path.split('/').map((seg) => {
|
|
12
|
+
const m = PARAM.exec(seg);
|
|
13
|
+
if (!m)
|
|
14
|
+
return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
15
|
+
keys.push(m[1]);
|
|
16
|
+
return '([^/]+)';
|
|
17
|
+
}).join('/');
|
|
18
|
+
return { keys, regex: new RegExp(`^${source}$`) };
|
|
19
|
+
}
|
|
20
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
|
|
3
21
|
export function routeFromFile(file) {
|
|
4
|
-
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.
|
|
22
|
+
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
|
|
5
23
|
return path || '/';
|
|
6
24
|
}
|
|
7
25
|
export function createHandler(pages, options = {}) {
|
|
8
|
-
|
|
26
|
+
// Static routes first, then dynamic ones with more fixed segments first: /users/new beats /users/[id].
|
|
27
|
+
const routes = Object.entries(pages)
|
|
28
|
+
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
29
|
+
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
30
|
+
const data = options.data ?? {};
|
|
31
|
+
const modes = options.modes ?? {};
|
|
9
32
|
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
33
|
+
function match(pathname) {
|
|
34
|
+
for (const route of routes) {
|
|
35
|
+
const m = route.regex.exec(pathname);
|
|
36
|
+
if (!m)
|
|
37
|
+
continue;
|
|
38
|
+
const params = {};
|
|
39
|
+
try {
|
|
40
|
+
route.keys.forEach((key, i) => { params[key] = decodeURIComponent(m[i + 1]); });
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null; // a malformed %-escape names no page
|
|
44
|
+
}
|
|
45
|
+
return { route, params };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
50
|
+
const entriesCache = new Map();
|
|
51
|
+
function entriesOf(route) {
|
|
52
|
+
if (!entriesCache.has(route)) {
|
|
53
|
+
const file = `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
54
|
+
entriesCache.set(route, (async () => {
|
|
55
|
+
const mod = data[file] ? await data[file]() : undefined;
|
|
56
|
+
return mod?.entries ? await mod.entries() : null;
|
|
57
|
+
})());
|
|
58
|
+
}
|
|
59
|
+
return entriesCache.get(route);
|
|
60
|
+
}
|
|
61
|
+
// Without entries() a route isn't restricted here (the build reports it).
|
|
62
|
+
async function listed(route, params) {
|
|
63
|
+
const list = await entriesOf(route);
|
|
64
|
+
return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
|
|
65
|
+
}
|
|
10
66
|
return {
|
|
11
|
-
routes:
|
|
67
|
+
routes: routes.map((r) => r.path).sort(),
|
|
68
|
+
/** Routes rendered per request ('server' mode), as their files name them. */
|
|
69
|
+
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
70
|
+
/** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
|
|
71
|
+
isServerPath(pathname) {
|
|
72
|
+
const found = match(pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname);
|
|
73
|
+
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
74
|
+
},
|
|
75
|
+
/** Whether a route (as its file names it) has a load(). */
|
|
76
|
+
async hasLoader(path) {
|
|
77
|
+
const route = routes.find((r) => r.path === path);
|
|
78
|
+
const file = route && `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
79
|
+
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
80
|
+
},
|
|
81
|
+
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
82
|
+
async paths() {
|
|
83
|
+
const out = [];
|
|
84
|
+
for (const route of routes) {
|
|
85
|
+
const mode = modeFor(route.path, modes);
|
|
86
|
+
if (mode === 'server')
|
|
87
|
+
continue;
|
|
88
|
+
const add = (path) => {
|
|
89
|
+
out.push(path);
|
|
90
|
+
// A client page's data, fetched by the router: written next to its shell.
|
|
91
|
+
if (mode === 'client')
|
|
92
|
+
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
93
|
+
};
|
|
94
|
+
if (!route.keys.length) {
|
|
95
|
+
add(route.path);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const dataFile = route.file.replace(/\.tscl$/, '.load.ts');
|
|
99
|
+
const list = await entriesOf(route);
|
|
100
|
+
if (!list)
|
|
101
|
+
throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
|
|
102
|
+
for (const params of list) {
|
|
103
|
+
add(route.path.split('/').map((seg) => {
|
|
104
|
+
const key = PARAM.exec(seg)?.[1];
|
|
105
|
+
if (key === undefined)
|
|
106
|
+
return seg;
|
|
107
|
+
const value = params[key];
|
|
108
|
+
// Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
|
|
109
|
+
// Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
|
|
110
|
+
// __data.json is a client route's data file, so it can't also name a page.
|
|
111
|
+
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || /[/\\\0]/.test(value)) {
|
|
112
|
+
throw new Error(`${dataFile}: entries() gave ${JSON.stringify(value)} for "${key}"; each value must be a non-empty string without "/" or "\\", and not ".", ".." or "${DATA}"`);
|
|
113
|
+
}
|
|
114
|
+
return encodeURIComponent(value);
|
|
115
|
+
}).join('/'));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return out.sort();
|
|
119
|
+
},
|
|
12
120
|
async fetch(request) {
|
|
13
121
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
14
122
|
return new Response('Method Not Allowed', { status: 405 });
|
|
15
123
|
const pathname = new URL(request.url).pathname;
|
|
16
124
|
// '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
|
|
17
|
-
const
|
|
125
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
126
|
+
// <client route>/__data.json is that page's props, for the router. Only for a client route: anywhere else the
|
|
127
|
+
// path is an ordinary page path (a server route may well have an [id] of "__data.json").
|
|
128
|
+
let found = match(trim(pathname));
|
|
129
|
+
let wantsData = false;
|
|
130
|
+
if (pathname.endsWith(`/${DATA}`)) {
|
|
131
|
+
const owner = match(trim(pathname.slice(0, -DATA.length - 1) || '/'));
|
|
132
|
+
if (owner && modeFor(owner.route.path, modes) === 'client') {
|
|
133
|
+
found = owner;
|
|
134
|
+
wantsData = true;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
18
137
|
const head = request.method === 'HEAD';
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
138
|
+
const notFound = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
139
|
+
const mode = found && modeFor(found.route.path, modes);
|
|
140
|
+
if (!found)
|
|
141
|
+
return notFound();
|
|
142
|
+
// A prerendered dynamic route only has the pages its entries() lists, as on a static host.
|
|
143
|
+
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
144
|
+
return notFound();
|
|
145
|
+
if (mode === 'client' && !wantsData) {
|
|
146
|
+
// In matching order (static before dynamic, as on the server): the router takes the first match.
|
|
147
|
+
const client = options.client ?? {};
|
|
148
|
+
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
149
|
+
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
150
|
+
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
151
|
+
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
152
|
+
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
153
|
+
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
154
|
+
return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
155
|
+
}
|
|
156
|
+
let props = found.params;
|
|
157
|
+
const dataFile = found.route.file.replace(/\.tscl$/, '.load.ts');
|
|
158
|
+
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
159
|
+
if (mod?.load) {
|
|
160
|
+
let loaded;
|
|
161
|
+
try {
|
|
162
|
+
loaded = await mod.load({ params: found.params, request });
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
return failure(`${dataFile}: load() failed: ${err?.message ?? err}`);
|
|
166
|
+
}
|
|
167
|
+
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
168
|
+
return failure(`${dataFile}: load() must return an object of page inputs, got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
169
|
+
}
|
|
170
|
+
;
|
|
171
|
+
globalThis.__clLoaderRan = true; // recorded by prerender for the manifest
|
|
172
|
+
props = { ...found.params, ...loaded };
|
|
173
|
+
}
|
|
174
|
+
if (wantsData) {
|
|
175
|
+
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
176
|
+
}
|
|
177
|
+
const html = (await found.route.load()).render(props);
|
|
22
178
|
const visible = maskComments(html);
|
|
23
179
|
const hasIslands = visible.includes('<cl-island ');
|
|
24
180
|
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
@@ -31,6 +187,11 @@ export function createHandler(pages, options = {}) {
|
|
|
31
187
|
},
|
|
32
188
|
};
|
|
33
189
|
}
|
|
190
|
+
/** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
|
|
191
|
+
function failure(message) {
|
|
192
|
+
console.error(`[clarusjs] ${message}`);
|
|
193
|
+
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
194
|
+
}
|
|
34
195
|
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
35
196
|
function maskComments(html) {
|
|
36
197
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Manifest } from '../vite/manifest.ts';
|
|
2
|
+
export type { Manifest, RouteInfo, IslandInfo } from '../vite/manifest.ts';
|
|
3
|
+
/** The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. */
|
|
4
|
+
export declare function readManifest(): Manifest | null;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Read the route manifest while pages are prerendered. Server only (Node): a page that calls readManifest() during
|
|
2
|
+
// `vite build` is rendered again once the manifest is written, so it can show what the built site ships.
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
/** The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. */
|
|
5
|
+
export function readManifest() {
|
|
6
|
+
;
|
|
7
|
+
globalThis.__clManifestRead = true;
|
|
8
|
+
const file = process.env.CLARUS_MANIFEST;
|
|
9
|
+
if (!file)
|
|
10
|
+
return null;
|
|
11
|
+
try {
|
|
12
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type Mode = 'static' | 'server' | 'client';
|
|
2
|
+
export type ModeTable = Record<string, string>;
|
|
3
|
+
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
4
|
+
export declare function checkModes(table: ModeTable): void;
|
|
5
|
+
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
6
|
+
export declare function modeFor(route: string, table: ModeTable): Mode;
|