clarusjs 0.1.0 → 0.3.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.
@@ -1,4 +1,5 @@
1
- // Island loader: finds <cl-island> elements, loads each one's chunk, calls attach(). Browser only, ~20 lines.
1
+ // Island loader: finds <cl-island> elements, loads each one's chunk when its attach mode says so, calls attach(),
2
+ // and replays what the visitor did before that. Browser only.
2
3
  var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
4
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
4
5
  return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
@@ -7,36 +8,132 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
8
  }
8
9
  return path;
9
10
  };
10
- // Islands whose chunk is being fetched. `data-cl-ready` is set only after attach() succeeds.
11
+ import { parse } from './serialize.js';
12
+ // Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
11
13
  const loading = new WeakSet();
12
- export async function attachAll(root = document, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src))) {
13
- const islands = [...root.querySelectorAll('cl-island:not([data-cl-ready]):not([data-cl-error])')].filter((el) => !loading.has(el));
14
- const pending = islands.map(async (el) => {
15
- loading.add(el);
16
- let mod;
17
- let props;
18
- try {
19
- mod = await load(el.getAttribute('src'));
20
- props = JSON.parse(el.getAttribute('p') ?? '{}');
21
- }
22
- catch (err) {
23
- loading.delete(el); // network or parse failure: the next attachAll() retries
24
- console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
14
+ let lastLoad = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src));
15
+ // Events recorded until an island attaches, then replayed. Clicks and submits are held back (no navigation, no
16
+ // form post) so the island can handle them once it is ready.
17
+ const REPLAY = ['click', 'submit', 'input', 'change', 'keydown'];
18
+ const HOLD = new Set(['click', 'submit']);
19
+ // What counts as using an island, for attach="interaction".
20
+ const INTERACTION = ['pointerdown', 'keydown', 'focusin', 'input', 'click', 'submit'];
21
+ /** Record events aimed at this island (not at an island nested in it) until stop() is called. */
22
+ function record(el) {
23
+ const events = [];
24
+ const listener = (e) => {
25
+ const target = e.target;
26
+ if (!target || target.closest?.('cl-island') !== el)
25
27
  return;
28
+ if (HOLD.has(e.type))
29
+ e.preventDefault();
30
+ events.push({ type: e.type, target, key: e.key });
31
+ };
32
+ for (const type of REPLAY)
33
+ el.addEventListener(type, listener, true);
34
+ return { events, stop: () => { for (const type of REPLAY)
35
+ el.removeEventListener(type, listener, true); } };
36
+ }
37
+ /** Do again what the visitor did before the island attached, now that its handlers are listening. */
38
+ function replay(events) {
39
+ for (const { type, target, key } of events) {
40
+ if (!target.isConnected)
41
+ continue;
42
+ if (type === 'click')
43
+ target.click?.();
44
+ else if (type === 'submit') {
45
+ const form = target;
46
+ if (typeof form.requestSubmit === 'function')
47
+ form.requestSubmit();
48
+ else
49
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
26
50
  }
27
- try {
28
- mod.attach(el, props);
29
- el.setAttribute('data-cl-ready', '');
30
- }
31
- catch (err) {
32
- el.setAttribute('data-cl-error', ''); // attach may have wired some listeners already: never retry
33
- console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to attach`, err);
34
- }
35
- finally {
36
- loading.delete(el);
37
- }
38
- });
39
- await Promise.all(pending);
51
+ else if (type === 'keydown')
52
+ target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
53
+ else
54
+ target.dispatchEvent(new Event(type, { bubbles: true }));
55
+ }
56
+ }
57
+ /** Run `go` when the island's attach mode (`a` attribute) says: now, when idle, when visible, or on first use. */
58
+ function schedule(el, go) {
59
+ const mode = el.getAttribute('a') ?? 'load';
60
+ if (mode === 'idle') {
61
+ const idle = globalThis.requestIdleCallback;
62
+ if (idle)
63
+ idle(go);
64
+ else
65
+ setTimeout(go, 200);
66
+ }
67
+ else if (mode === 'visible' && typeof IntersectionObserver === 'function') {
68
+ const io = new IntersectionObserver((entries) => {
69
+ if (entries.some((entry) => entry.isIntersecting)) {
70
+ io.disconnect();
71
+ go();
72
+ }
73
+ });
74
+ io.observe(el);
75
+ }
76
+ else if (mode === 'interaction') {
77
+ const start = () => { for (const type of INTERACTION)
78
+ el.removeEventListener(type, start, true); go(); };
79
+ for (const type of INTERACTION)
80
+ el.addEventListener(type, start, true);
81
+ }
82
+ else {
83
+ go();
84
+ }
85
+ }
86
+ async function attachOne(el, load, recorded) {
87
+ let mod;
88
+ let props;
89
+ let state;
90
+ try {
91
+ mod = await load(el.getAttribute('src'));
92
+ props = parse(el.getAttribute('p') ?? '{}');
93
+ const s = el.getAttribute('s');
94
+ state = s === null ? undefined : parse(s);
95
+ }
96
+ catch (err) {
97
+ recorded.stop();
98
+ loading.delete(el); // network or parse failure: the next attachAll() retries
99
+ console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
100
+ return;
101
+ }
102
+ try {
103
+ mod.attach(el, props, state);
104
+ el.setAttribute('data-cl-ready', '');
105
+ }
106
+ catch (err) {
107
+ el.setAttribute('data-cl-error', ''); // attach may have wired some listeners already: never retry
108
+ console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to attach`, err);
109
+ }
110
+ finally {
111
+ loading.delete(el);
112
+ }
113
+ recorded.stop();
114
+ if (el.hasAttribute('data-cl-ready'))
115
+ replay(recorded.events);
116
+ }
117
+ /**
118
+ * Attach every island under `root` that isn't attached yet. Resolves once the islands that attach right away
119
+ * (the default, attach="load") are done; idle, visible and interaction islands attach later on their own.
120
+ */
121
+ export async function attachAll(root = document, load = lastLoad) {
122
+ lastLoad = load;
123
+ const islands = [...root.querySelectorAll('cl-island:not([data-cl-ready]):not([data-cl-error])')].filter((el) => !loading.has(el));
124
+ const now = [];
125
+ for (const el of islands) {
126
+ loading.add(el);
127
+ const recorded = record(el);
128
+ if ((el.getAttribute('a') ?? 'load') === 'load')
129
+ now.push(attachOne(el, load, recorded));
130
+ else
131
+ schedule(el, () => void attachOne(el, load, recorded));
132
+ }
133
+ await Promise.all(now);
40
134
  }
135
+ // Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook.
136
+ ;
137
+ globalThis.__clAttach = (root) => void attachAll(root);
41
138
  if (typeof document !== 'undefined')
42
139
  attachAll();
@@ -0,0 +1,8 @@
1
+ /**
2
+ * JSON plus Date, Map, Set, undefined, NaN, ±Infinity, -0 and BigInt. Objects that themselves have a `$cl` key are
3
+ * wrapped so data is never mistaken for a tag. Functions, symbols, class instances and cycles are rejected with the
4
+ * path to the bad value.
5
+ */
6
+ export declare function stringify(value: unknown): string;
7
+ /** The inverse of stringify(). */
8
+ export declare function parse(text: string): unknown;
@@ -0,0 +1,93 @@
1
+ // Island props and state go from server HTML to the browser as JSON, with tags for what JSON can't hold.
2
+ // Shared by the server (stringify) and the browser (parse).
3
+ const TAG = '$cl';
4
+ /**
5
+ * JSON plus Date, Map, Set, undefined, NaN, ±Infinity, -0 and BigInt. Objects that themselves have a `$cl` key are
6
+ * wrapped so data is never mistaken for a tag. Functions, symbols, class instances and cycles are rejected with the
7
+ * path to the bad value.
8
+ */
9
+ export function stringify(value) {
10
+ return JSON.stringify(encode(value, '', new Set()));
11
+ }
12
+ function encode(value, path, seen) {
13
+ const at = (key) => (path ? `${path}.${key}` : String(key));
14
+ const fail = (what) => {
15
+ throw new TypeError(`[clarusjs] cannot send ${path || 'the value'} to the browser: ${what}`);
16
+ };
17
+ switch (typeof value) {
18
+ case 'undefined':
19
+ return { [TAG]: 'u' };
20
+ case 'number':
21
+ if (Number.isFinite(value) && !Object.is(value, -0))
22
+ return value;
23
+ return { [TAG]: 'n', v: Object.is(value, -0) ? '-0' : String(value) };
24
+ case 'bigint':
25
+ return { [TAG]: 'b', v: value.toString() };
26
+ case 'function':
27
+ case 'symbol':
28
+ return fail(`it is a ${typeof value}`);
29
+ case 'object': {
30
+ if (value === null)
31
+ return null;
32
+ if (seen.has(value))
33
+ return fail('circular reference');
34
+ seen.add(value);
35
+ try {
36
+ if (Array.isArray(value)) {
37
+ const out = [];
38
+ for (let i = 0; i < value.length; i++)
39
+ out.push(encode(value[i], at(i), seen));
40
+ return out;
41
+ }
42
+ if (value instanceof Date)
43
+ return { [TAG]: 'd', v: Number.isNaN(value.getTime()) ? null : value.toISOString() };
44
+ if (value instanceof Map)
45
+ return { [TAG]: 'm', v: [...value].map(([k, v], i) => [encode(k, at(`key${i}`), seen), encode(v, at(i), seen)]) };
46
+ if (value instanceof Set)
47
+ return { [TAG]: 's', v: [...value].map((v, i) => encode(v, at(i), seen)) };
48
+ const proto = Object.getPrototypeOf(value);
49
+ if (proto !== Object.prototype && proto !== null) {
50
+ return fail(`it is a ${proto?.constructor?.name ?? 'class instance'}; only plain objects, arrays, Date, Map and Set can be sent`);
51
+ }
52
+ const out = {};
53
+ for (const [k, v] of Object.entries(value))
54
+ out[k] = encode(v, at(k), seen);
55
+ return TAG in out ? { [TAG]: 'o', v: out } : out;
56
+ }
57
+ finally {
58
+ seen.delete(value);
59
+ }
60
+ }
61
+ default:
62
+ return value; // string, boolean
63
+ }
64
+ }
65
+ /** The inverse of stringify(). */
66
+ export function parse(text) {
67
+ return decode(JSON.parse(text));
68
+ }
69
+ function decode(value) {
70
+ if (Array.isArray(value))
71
+ return value.map(decode);
72
+ if (value === null || typeof value !== 'object')
73
+ return value;
74
+ if (TAG in value) {
75
+ const { [TAG]: tag, v } = value;
76
+ switch (tag) {
77
+ case 'u': return undefined;
78
+ case 'n': return v === '-0' ? -0 : Number(v);
79
+ case 'b': return BigInt(v);
80
+ case 'd': return new Date(v === null ? NaN : v);
81
+ case 'm': return new Map(v.map(([k, x]) => [decode(k), decode(x)]));
82
+ case 's': return new Set(v.map(decode));
83
+ case 'o': return decodeObject(v);
84
+ }
85
+ }
86
+ return decodeObject(value);
87
+ }
88
+ function decodeObject(value) {
89
+ const out = {};
90
+ for (const [k, v] of Object.entries(value))
91
+ out[k] = decode(v);
92
+ return out;
93
+ }
@@ -1,4 +1,9 @@
1
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
2
- export declare function escape(value: unknown): string;
3
- /** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
4
- export declare function island(name: string, src: string, props: Record<string, unknown>, html: string): string;
1
+ import { attrHtml } from './html.ts';
2
+ export { escape, blockHtml, forHtml, regionHtml } from './html.ts';
3
+ /**
4
+ * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
5
+ * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
6
+ */
7
+ export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string): string;
8
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
9
+ export declare const attr: typeof attrHtml;
@@ -1,26 +1,15 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
- const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
3
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
4
- export function escape(value) {
5
- if (value == null)
6
- return '';
7
- return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
8
- }
9
- function assertSerializable(value, path) {
10
- const t = typeof value;
11
- if (t === 'function' || t === 'symbol' || t === 'bigint') {
12
- throw new TypeError(`[clarusjs] island prop "${path}" is a ${t}; island props must be JSON-serializable`);
13
- }
14
- if (t === 'number' && !Number.isFinite(value)) {
15
- throw new TypeError(`[clarusjs] island prop "${path}" is ${value}; island props must be JSON-serializable`);
16
- }
17
- if (value && t === 'object') {
18
- for (const [k, v] of Object.entries(value))
19
- assertSerializable(v, path ? `${path}.${k}` : k);
20
- }
21
- }
22
- /** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
23
- export function island(name, src, props, html) {
24
- assertSerializable(props, '');
25
- return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(JSON.stringify(props))}">${html}</cl-island>`;
2
+ import { attrHtml, escape } from './html.js';
3
+ import { stringify } from './serialize.js';
4
+ export { escape, blockHtml, forHtml, regionHtml } from './html.js';
5
+ /**
6
+ * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
7
+ * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
8
+ */
9
+ export function island(name, src, props, html, state, attach) {
10
+ const s = state === undefined ? '' : ` s="${escape(stringify(state))}"`;
11
+ const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
12
+ return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(stringify(props))}"${s}${a}>${html}</cl-island>`;
26
13
  }
14
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
15
+ export const attr = attrHtml;
@@ -1,10 +1,22 @@
1
1
  export type Signal<T> = {
2
2
  get(): T;
3
3
  set(v: T): void;
4
+ readonly initial: T;
4
5
  };
5
6
  export type ReadSignal<T> = {
6
7
  get(): T;
7
8
  };
9
+ /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
10
+ export declare function scope(fn: () => void): () => void;
11
+ /** Register a cleanup with the enclosing scope (no-op outside one). */
12
+ export declare function onDispose(fn: () => void): void;
13
+ /** Read signals without subscribing the running effect to them. */
14
+ export declare function untrack<T>(fn: () => T): T;
8
15
  export declare function state<T>(initial: T): Signal<T>;
9
16
  export declare function effect(fn: () => void): () => void;
10
17
  export declare function derived<T>(fn: () => T): ReadSignal<T>;
18
+ /**
19
+ * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
20
+ * store, so every island using it stays in sync. On the server it renders the store's initial value.
21
+ */
22
+ export declare function shared<T>(store: Signal<T>): Signal<T>;
@@ -1,9 +1,43 @@
1
1
  // Fine-grained reactivity used by compiled attach() functions. Browser only.
2
2
  let current = null;
3
+ // Cleanups registered while a scope() is running: effect stops, event listener removals, child scopes.
4
+ let currentScope = null;
5
+ /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
6
+ export function scope(fn) {
7
+ const prev = currentScope;
8
+ const cleanups = [];
9
+ currentScope = cleanups;
10
+ try {
11
+ fn();
12
+ }
13
+ finally {
14
+ currentScope = prev;
15
+ }
16
+ const dispose = () => { for (const c of cleanups.splice(0).reverse())
17
+ c(); };
18
+ onDispose(dispose);
19
+ return dispose;
20
+ }
21
+ /** Register a cleanup with the enclosing scope (no-op outside one). */
22
+ export function onDispose(fn) {
23
+ currentScope?.push(fn);
24
+ }
25
+ /** Read signals without subscribing the running effect to them. */
26
+ export function untrack(fn) {
27
+ const prev = current;
28
+ current = null;
29
+ try {
30
+ return fn();
31
+ }
32
+ finally {
33
+ current = prev;
34
+ }
35
+ }
3
36
  export function state(initial) {
4
37
  let value = initial;
5
38
  const subs = new Set();
6
39
  return {
40
+ initial, // what the server renders for a shared store: never a value another request set
7
41
  get() {
8
42
  if (current?.active) {
9
43
  subs.add(current);
@@ -42,8 +76,10 @@ export function effect(fn) {
42
76
  },
43
77
  };
44
78
  e.run();
45
- return () => { e.active = false; for (const subs of e.deps)
79
+ const stop = () => { e.active = false; for (const subs of e.deps)
46
80
  subs.delete(e); e.deps.clear(); };
81
+ onDispose(stop);
82
+ return stop;
47
83
  }
48
84
  // ponytail: eager derived, may compute twice on diamond graphs; switch to push-pull (alien-signals style) when nested derived lands
49
85
  export function derived(fn) {
@@ -51,3 +87,10 @@ export function derived(fn) {
51
87
  effect(() => s.set(fn()));
52
88
  return { get: s.get };
53
89
  }
90
+ /**
91
+ * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
92
+ * store, so every island using it stays in sync. On the server it renders the store's initial value.
93
+ */
94
+ export function shared(store) {
95
+ return store;
96
+ }
@@ -3,7 +3,10 @@ type PageModule = {
3
3
  };
4
4
  /** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
5
5
  export declare function routeFromFile(file: string): string;
6
- export declare function createHandler(pages: Record<string, () => Promise<PageModule>>): {
6
+ export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
7
+ loaderUrl?: string;
8
+ }): {
7
9
  fetch(request: Request): Promise<Response>;
10
+ routes: string[];
8
11
  };
9
12
  export {};
@@ -4,23 +4,48 @@ export function routeFromFile(file) {
4
4
  const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.clarus$/, '').replace(/\/index$/, '');
5
5
  return path || '/';
6
6
  }
7
- export function createHandler(pages) {
7
+ export function createHandler(pages, options = {}) {
8
8
  const routes = new Map(Object.entries(pages).map(([file, load]) => [routeFromFile(file), load]));
9
+ const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
9
10
  return {
11
+ routes: [...routes.keys()].sort(),
10
12
  async fetch(request) {
11
13
  if (request.method !== 'GET' && request.method !== 'HEAD')
12
14
  return new Response('Method Not Allowed', { status: 405 });
13
- const load = routes.get(new URL(request.url).pathname);
15
+ const pathname = new URL(request.url).pathname;
16
+ // '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
17
+ const load = routes.get(pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname);
14
18
  const head = request.method === 'HEAD';
15
19
  if (!load)
16
20
  return new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
17
21
  const html = (await load()).render({});
22
+ const visible = maskComments(html);
23
+ const hasIslands = visible.includes('<cl-island ');
18
24
  // Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
19
- const hasIslands = html.replace(/<!--[\s\S]*?-->/g, '').includes('<cl-island ');
20
- const scripts = hasIslands ? '<script type="module" src="/cl-loader.js"></script>' : '';
21
25
  const style = hasIslands ? '<style>cl-island{display:contents}</style>' : ''; // islands never affect layout
22
- const body = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${scripts}</body></html>`;
26
+ const script = hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
27
+ const body = /<html[\s>]/i.test(visible)
28
+ ? fullDocument(html, style, script)
29
+ : `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${script}</body></html>`;
23
30
  return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
24
31
  },
25
32
  };
26
33
  }
34
+ /** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
35
+ function maskComments(html) {
36
+ return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
37
+ }
38
+ /** A page whose layout renders the whole document: add the doctype if missing, and put style/script in place. */
39
+ function fullDocument(html, style, script) {
40
+ let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
41
+ if (style) {
42
+ const head = maskComments(out).search(/<\/head>/i);
43
+ out = head === -1 ? out + style : out.slice(0, head) + style + out.slice(head);
44
+ }
45
+ if (script) {
46
+ const bodies = [...maskComments(out).matchAll(/<\/body>/gi)];
47
+ const body = bodies.length ? bodies[bodies.length - 1].index : -1;
48
+ out = body === -1 ? out + script : out.slice(0, body) + script + out.slice(body);
49
+ }
50
+ return out;
51
+ }
@@ -0,0 +1,9 @@
1
+ /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
2
+ export declare function findClarusFiles(srcDir: string): string[];
3
+ /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
4
+ export declare function routeToFile(route: string): string;
5
+ /**
6
+ * Call the built handler for every route and write the HTML into `outDir`. Any failure fails the build.
7
+ * Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache.
8
+ */
9
+ export declare function prerender(serverEntry: string, outDir: string): Promise<string[]>;
@@ -0,0 +1,55 @@
1
+ // Build-time helpers for the Vite plugin: find components, and prerender every route to static HTML.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { readdirSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
6
+ export function findClarusFiles(srcDir) {
7
+ let entries;
8
+ try {
9
+ entries = readdirSync(srcDir, { recursive: true });
10
+ }
11
+ catch {
12
+ return [];
13
+ }
14
+ return entries.filter((f) => f.endsWith('.clarus')).map((f) => resolve(srcDir, f)).sort();
15
+ }
16
+ /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
17
+ export function routeToFile(route) {
18
+ const path = route.replace(/^\/+|\/+$/g, '');
19
+ return path ? `${path}/index.html` : 'index.html';
20
+ }
21
+ /**
22
+ * Call the built handler for every route and write the HTML into `outDir`. Any failure fails the build.
23
+ * Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache.
24
+ */
25
+ export async function prerender(serverEntry, outDir) {
26
+ const script = `
27
+ import { mkdirSync, writeFileSync } from 'node:fs'
28
+ import { dirname, resolve } from 'node:path'
29
+ import { pathToFileURL } from 'node:url'
30
+ const routeToFile = ${routeToFile.toString()}
31
+ const [entry, outDir] = process.argv.slice(1)
32
+ const { default: handler } = await import(pathToFileURL(entry).href)
33
+ for (const route of handler.routes) {
34
+ let response
35
+ try {
36
+ response = await handler.fetch(new Request('http://localhost' + route))
37
+ } catch (err) {
38
+ process.stderr.write('prerender ' + route + ': ' + (err && err.message || err))
39
+ process.exit(1)
40
+ }
41
+ if (response.status !== 200) {
42
+ process.stderr.write('prerender ' + route + ': status ' + response.status)
43
+ process.exit(1)
44
+ }
45
+ const file = resolve(outDir, routeToFile(route))
46
+ mkdirSync(dirname(file), { recursive: true })
47
+ writeFileSync(file, await response.text())
48
+ }
49
+ process.stdout.write(JSON.stringify(handler.routes))
50
+ `;
51
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, serverEntry, outDir], { encoding: 'utf8' });
52
+ if (result.status !== 0)
53
+ throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
54
+ return JSON.parse(result.stdout);
55
+ }