clarusjs 0.3.0 → 0.4.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 CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo: a clear cut crystal with one bright facet">
2
+ <img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo: a cut crystal flat along a T, struck by an S-shaped lightning bolt, with C and L down the stem">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">clarusjs</h1>
@@ -30,7 +30,7 @@ export default defineConfig({ plugins: [clarusjs()] })
30
30
  ```
31
31
 
32
32
  ```clarus
33
- {{-- src/components/counter.clarus --}}
33
+ {{-- src/components/counter.tscl --}}
34
34
  @input start: number = 0
35
35
 
36
36
  <script>
@@ -42,14 +42,14 @@ export default defineConfig({ plugins: [clarusjs()] })
42
42
  ```
43
43
 
44
44
  ```clarus
45
- {{-- src/pages/index.clarus --}}
46
- @import counter from '../components/counter.clarus'
45
+ {{-- src/pages/index.tscl --}}
46
+ @import counter from '../components/counter.tscl'
47
47
 
48
48
  <h1>Hello</h1>
49
49
  <counter [start]="1" />
50
50
  ```
51
51
 
52
- - `vite` serves `src/pages/**/*.clarus` as routes, rendered on the server.
52
+ - `vite` serves `src/pages/**/*.tscl` as routes, rendered on the server.
53
53
  - `vite build` writes a static site to `dist/client/`: one HTML file per page, plus JavaScript only for components
54
54
  with a `<script>` (the counter above). The `<h1>` ships no JavaScript at all.
55
55
 
@@ -0,0 +1,11 @@
1
+ /**
2
+ * [virtual offset, length, source offset, exact]. Exact spans are verbatim copies (offsets map one to one); other
3
+ * spans stand for a whole template construct and map to its start.
4
+ */
5
+ export type Mapping = [number, number, number, boolean];
6
+ export declare function generateTs(source: string, file: string): {
7
+ code: string;
8
+ mappings: Mapping[];
9
+ };
10
+ /** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
11
+ export declare function toSourceOffset(mappings: Mapping[], virtualOffset: number): number | null;
@@ -0,0 +1,164 @@
1
+ // .tscl → virtual TypeScript for type checking (it never runs). Template expressions are copied verbatim inside
2
+ // TypeScript that has the same meaning (@if → if, @for → for…of, a component → an object typed as its Inputs), and
3
+ // every copied span is recorded so tsc's errors can be mapped back to the template. Pure: string in, string out.
4
+ import { parse } from '../compiler/parse.js';
5
+ import { splitImports } from '../compiler/script.js';
6
+ export function generateTs(source, file) {
7
+ const parsed = parse(source, file);
8
+ const mappings = [];
9
+ let code = '';
10
+ const emit = (text) => { code += text; };
11
+ const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
12
+ const point = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, false]); code += text; };
13
+ // Where a trimmed expression starts in the source, searching from `from`.
14
+ const at = (text, from) => source.indexOf(text, from);
15
+ const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
16
+ const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
17
+ emit('// Generated by clarusjs for type checking. It never runs.\n');
18
+ emit('declare function state<T>(value: T): T\n');
19
+ emit('declare function derived<T>(fn: () => T): T\n');
20
+ emit('declare function shared<T>(store: { get(): T }): T\n');
21
+ emit('declare function __cl_use(value: unknown): void\n');
22
+ emit('type __cl_Event<K extends string> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : Event) & { target: any; currentTarget: any }\n');
23
+ for (const t of parsed.typeImports) {
24
+ emit('import type ');
25
+ copy(t.clause, t.clauseStart);
26
+ emit(` from ${JSON.stringify(t.from)}\n`);
27
+ }
28
+ for (const imp of parsed.imports)
29
+ emit(`import type { Inputs as ${alias(imp.name)} } from ${JSON.stringify(`${imp.from}.ts`)}\n`);
30
+ for (const d of parsed.dataImports) {
31
+ emit('import ');
32
+ copy(d.clause, d.clauseStart);
33
+ emit(` from ${JSON.stringify(d.from)}\n`);
34
+ }
35
+ const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
36
+ if (parsed.script && script) {
37
+ for (const imp of script.imports) {
38
+ copy(imp.text, parsed.script.start + imp.start);
39
+ emit('\n');
40
+ }
41
+ }
42
+ emit('\nexport interface Inputs {\n');
43
+ for (const input of parsed.inputs) {
44
+ emit(' ');
45
+ copy(input.name, input.nameStart);
46
+ emit(input.default !== undefined ? '?: ' : ': ');
47
+ copy(input.type, input.typeStart);
48
+ emit('\n');
49
+ }
50
+ emit('}\n\nexport default function __cl_check(__cl_props: Inputs) {\n');
51
+ if (parsed.inputs.length) {
52
+ emit(' const { ');
53
+ parsed.inputs.forEach((input, i) => {
54
+ if (i)
55
+ emit(', ');
56
+ copy(input.name, input.nameStart);
57
+ if (input.default !== undefined && input.defaultStart !== undefined) {
58
+ emit(' = ');
59
+ copy(input.default, input.defaultStart);
60
+ }
61
+ });
62
+ emit(' } = __cl_props\n');
63
+ }
64
+ if (parsed.script && script) {
65
+ copy(script.body, parsed.script.start);
66
+ emit('\n;\n'); // the script may end without a semicolon; what follows must not continue its last statement
67
+ }
68
+ const use = (expr, start) => {
69
+ emit(' __cl_use((');
70
+ copy(expr, at(expr, start));
71
+ emit('));\n');
72
+ };
73
+ const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : 4);
74
+ function visit(node) {
75
+ switch (node.type) {
76
+ case 'text':
77
+ case 'raw':
78
+ return;
79
+ case 'expr':
80
+ return use(node.expr, node.start + 2);
81
+ case 'fill':
82
+ node.children.forEach(visit);
83
+ return;
84
+ case 'if':
85
+ node.branches.forEach((b, i) => {
86
+ if (b.cond === null)
87
+ emit(' else {\n');
88
+ else {
89
+ emit(i === 0 ? ' if ((' : ' else if ((');
90
+ copy(b.cond, at(b.cond, b.condStart));
91
+ emit(')) {\n');
92
+ }
93
+ b.children.forEach(visit);
94
+ emit(' }\n');
95
+ });
96
+ return;
97
+ case 'for': {
98
+ emit(' for (const ');
99
+ copy(node.item, node.itemStart);
100
+ emit(' of ');
101
+ copy(node.list, node.listStart);
102
+ emit(') {\n const $index: number = 0\n');
103
+ if (node.track !== null)
104
+ use(node.track, node.trackStart);
105
+ node.children.forEach(visit);
106
+ emit(' }\n');
107
+ if (node.empty) {
108
+ emit(' {\n');
109
+ node.empty.forEach(visit);
110
+ emit(' }\n');
111
+ }
112
+ return;
113
+ }
114
+ case 'element': {
115
+ const component = components.get(node.tag);
116
+ if (component) {
117
+ // An object literal typed as the child's Inputs: unknown props are excess properties, missing ones are
118
+ // reported on the variable, which maps to the tag.
119
+ emit(' { const ');
120
+ point('__cl_p', node.start);
121
+ emit(`: ${alias(node.tag)} = { `);
122
+ for (const a of node.attrs) {
123
+ if (a.kind !== 'prop')
124
+ continue;
125
+ copy(a.name, a.start + 1);
126
+ emit(': (');
127
+ copy(a.expr, at(a.expr, attrValueStart(a)));
128
+ emit('), ');
129
+ }
130
+ emit('}; __cl_use(__cl_p) }\n');
131
+ node.children.forEach(visit);
132
+ return;
133
+ }
134
+ for (const a of node.attrs) {
135
+ if (a.kind === 'prop')
136
+ use(a.expr, attrValueStart(a));
137
+ else if (a.kind === 'interp') {
138
+ for (const p of a.parts)
139
+ if (typeof p !== 'string')
140
+ use(p.expr, p.start + 2);
141
+ }
142
+ else if (a.kind === 'event') {
143
+ emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}>) => { `);
144
+ copy(a.expr, at(a.expr, attrValueStart(a)));
145
+ emit(' });\n');
146
+ }
147
+ }
148
+ node.children.forEach(visit);
149
+ return;
150
+ }
151
+ }
152
+ }
153
+ parsed.nodes.forEach(visit);
154
+ emit('}\n');
155
+ return { code, mappings };
156
+ }
157
+ /** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
158
+ export function toSourceOffset(mappings, virtualOffset) {
159
+ for (const [v, length, s, exact] of mappings) {
160
+ if (virtualOffset >= v && virtualOffset < v + Math.max(length, 1))
161
+ return exact ? s + (virtualOffset - v) : s;
162
+ }
163
+ return null;
164
+ }
@@ -0,0 +1,17 @@
1
+ export type Diagnostic = {
2
+ file: string;
3
+ line: number;
4
+ column: number;
5
+ code: string;
6
+ message: string;
7
+ };
8
+ export type CheckResult = {
9
+ diagnostics: Diagnostic[];
10
+ exitCode: 0 | 1;
11
+ text: string;
12
+ json: string;
13
+ };
14
+ export declare function check(options: {
15
+ root: string;
16
+ typescript?: string;
17
+ }): CheckResult;
@@ -0,0 +1,91 @@
1
+ // `clarusjs check`: type-check every .tscl file in a project (and the .ts it uses) with the project's TypeScript,
2
+ // reporting each error at file.tscl:line:col.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, relative, resolve, sep } from 'node:path';
7
+ import { ClarusError } from '../compiler/errors.js';
8
+ import { generateTs, toSourceOffset } from '../check/generate.js';
9
+ import { findClarusFiles } from '../vite/build.js';
10
+ const VIRTUAL = '.clarusjs/virtual';
11
+ const posix = (path) => path.split(sep).join('/');
12
+ /** Line and column (1-based) of an offset in `text`. */
13
+ function position(text, offset) {
14
+ const before = text.slice(0, offset);
15
+ return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
16
+ }
17
+ /** Where the project's TypeScript lives (overridable for tests and monorepos). */
18
+ function typescriptDir(root, override) {
19
+ if (override)
20
+ return override;
21
+ return dirname(createRequire(resolve(root, 'package.json')).resolve('typescript/package.json'));
22
+ }
23
+ export function check(options) {
24
+ const root = resolve(options.root);
25
+ const virtualRoot = resolve(root, VIRTUAL);
26
+ rmSync(virtualRoot, { recursive: true, force: true });
27
+ const diagnostics = [];
28
+ const generated = new Map();
29
+ for (const path of findClarusFiles(resolve(root, 'src'))) {
30
+ const file = posix(relative(root, path));
31
+ const source = readFileSync(path, 'utf8');
32
+ try {
33
+ const { code, mappings } = generateTs(source, file);
34
+ const vpath = resolve(virtualRoot, `${file}.ts`);
35
+ mkdirSync(dirname(vpath), { recursive: true });
36
+ writeFileSync(vpath, code);
37
+ generated.set(vpath, { file, source, code, mappings });
38
+ }
39
+ catch (err) {
40
+ if (!(err instanceof ClarusError))
41
+ throw err;
42
+ const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
43
+ diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
44
+ }
45
+ }
46
+ // The project's own settings, plus what checking templates needs. Scripts are JavaScript, so untyped parameters
47
+ // are expected (noImplicitAny off). rootDirs lets virtual files and real sources import each other.
48
+ const hasConfig = existsSync(resolve(root, 'tsconfig.json'));
49
+ const config = {
50
+ ...(hasConfig ? { extends: '../tsconfig.json' } : {}),
51
+ compilerOptions: {
52
+ ...(hasConfig ? {} : { strict: true, target: 'ES2023', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2023', 'DOM', 'DOM.Iterable'] }),
53
+ noEmit: true,
54
+ allowImportingTsExtensions: true,
55
+ noImplicitAny: false,
56
+ skipLibCheck: true,
57
+ rootDirs: ['..', './virtual'],
58
+ },
59
+ include: ['../src', './virtual'],
60
+ };
61
+ const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
62
+ mkdirSync(dirname(configPath), { recursive: true });
63
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
64
+ const tsDir = typescriptDir(root, options.typescript);
65
+ const bin = JSON.parse(readFileSync(resolve(tsDir, 'package.json'), 'utf8')).bin;
66
+ const tsc = resolve(tsDir, typeof bin === 'string' ? bin : bin.tsc);
67
+ const run = spawnSync(process.execPath, [tsc, '-p', configPath, '--pretty', 'false'], { cwd: root, encoding: 'utf8' });
68
+ for (const line of `${run.stdout}\n${run.stderr}`.split('\n')) {
69
+ const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line.trim());
70
+ if (!m)
71
+ continue;
72
+ const path = resolve(root, m[1]);
73
+ const g = generated.get(path);
74
+ if (!g) {
75
+ diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
76
+ continue;
77
+ }
78
+ const lines = g.code.split('\n');
79
+ const offset = lines.slice(0, Number(m[2]) - 1).reduce((n, l) => n + l.length + 1, 0) + Number(m[3]) - 1;
80
+ const source = toSourceOffset(g.mappings, offset);
81
+ const at = source === null ? { line: 1, column: 1 } : position(g.source, source);
82
+ diagnostics.push({ file: g.file, ...at, code: m[4], message: source === null ? `${m[5]} (in generated code)` : m[5] });
83
+ }
84
+ diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
85
+ return {
86
+ diagnostics,
87
+ exitCode: diagnostics.length ? 1 : 0,
88
+ text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} error ${d.code}: ${d.message}`).join('\n'),
89
+ json: JSON.stringify(diagnostics, null, 2),
90
+ };
91
+ }
@@ -0,0 +1,9 @@
1
+ export type ExplainResult = {
2
+ exitCode: 0 | 1;
3
+ text: string;
4
+ json: string;
5
+ };
6
+ export declare function explain(options: {
7
+ root: string;
8
+ route?: string;
9
+ }): ExplainResult;
@@ -0,0 +1,46 @@
1
+ // `clarusjs explain [route]`: where each part of a built route runs, in plain words, from dist/clarusjs-manifest.json.
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ const WHEN = {
5
+ load: 'on page load',
6
+ idle: 'when the browser is idle',
7
+ visible: 'when scrolled into view',
8
+ interaction: 'on first interaction',
9
+ };
10
+ const kb = (bytes) => (bytes ? `${(bytes / 1024).toFixed(1)} KB` : '0 KB');
11
+ const row = (label, lines) => lines.map((l, i) => ` ${(i ? '' : label).padEnd(12)}${l}`);
12
+ function describe(path, r) {
13
+ const islands = r.islands.map((i) => `${i.component}${i.count > 1 ? ` ×${i.count}` : ''} (${kb(i.gzip)}, ${WHEN[i.attach]})`);
14
+ return [
15
+ path,
16
+ ...row('Rendered', [`at build time, to dist/client/${r.html}`]),
17
+ ...row('Data', [r.loader ?? 'no loader']),
18
+ ...row('Islands', islands.length ? islands : ['none']),
19
+ ...row('JavaScript', [r.js.files.length ? `${kb(r.js.initialGzip)} on page load, ${kb(r.js.gzip)} in all (gzip, ${r.js.files.length} files)` : 'none']),
20
+ ...row('CSS', [r.css.length ? r.css.join(', ') : 'none']),
21
+ ].join('\n');
22
+ }
23
+ function table(routes) {
24
+ const width = Math.max(5, ...Object.keys(routes).map((r) => r.length)) + 2;
25
+ const line = (cells) => cells[0].padEnd(width) + cells[1].padEnd(9) + cells[2].padEnd(12) + cells[3];
26
+ return [
27
+ line(['Route', 'Islands', 'JS on load', 'JS in all']),
28
+ ...Object.entries(routes).map(([path, r]) => line([path, String(r.islands.reduce((n, i) => n + i.count, 0)), kb(r.js.initialGzip), kb(r.js.gzip)])),
29
+ ].join('\n');
30
+ }
31
+ export function explain(options) {
32
+ let manifest;
33
+ try {
34
+ manifest = JSON.parse(readFileSync(resolve(options.root, 'dist/clarusjs-manifest.json'), 'utf8'));
35
+ }
36
+ catch {
37
+ return { exitCode: 1, text: 'No dist/clarusjs-manifest.json: run vite build first, then explain the built site.', json: '{}' };
38
+ }
39
+ if (options.route === undefined)
40
+ return { exitCode: 0, text: table(manifest.routes), json: JSON.stringify(manifest.routes, null, 2) };
41
+ const path = options.route.replace(/(.)\/+$/, '$1');
42
+ const route = manifest.routes[path];
43
+ if (!route)
44
+ return { exitCode: 1, text: `No route ${path}. Routes: ${Object.keys(manifest.routes).join(', ')}`, json: '{}' };
45
+ return { exitCode: 0, text: describe(path, route), json: JSON.stringify({ route: path, ...route }, null, 2) };
46
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // The clarusjs command line. Node only: nothing here is reachable from a browser bundle.
3
+ import { Command } from 'commander';
4
+ import { check } from './check.js';
5
+ import { explain } from './explain.js';
6
+ const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
7
+ program
8
+ .command('check')
9
+ .description('type-check every .tscl file under src/ and report errors at file.tscl:line:col')
10
+ .argument('[dir]', 'project folder', '.')
11
+ .option('--json', 'print diagnostics as JSON')
12
+ .action((dir, options) => {
13
+ const result = check({ root: dir });
14
+ if (options.json)
15
+ console.log(result.json);
16
+ else if (result.diagnostics.length) {
17
+ console.log(result.text);
18
+ console.log(`\n${result.diagnostics.length} error${result.diagnostics.length === 1 ? '' : 's'}`);
19
+ }
20
+ else
21
+ console.log('No errors.');
22
+ process.exitCode = result.exitCode;
23
+ });
24
+ program
25
+ .command('explain')
26
+ .description('explain where each part of a built route runs: rendering, data, islands, JavaScript and CSS')
27
+ .argument('[route]', 'a route such as /guide/intro; without one, every route is listed')
28
+ .option('--root <dir>', 'project folder', '.')
29
+ .option('--json', 'print the route manifest entry as JSON')
30
+ .action((route, options) => {
31
+ const result = explain({ root: options.root, route });
32
+ if (result.exitCode)
33
+ console.error(result.text);
34
+ else
35
+ console.log(options.json ? result.json : result.text);
36
+ process.exitCode = result.exitCode;
37
+ });
38
+ program.parse();
@@ -37,6 +37,8 @@ export function emitClient(ir) {
37
37
  if (usedComponents.has(imp.name))
38
38
  out += `import { render as ${renderName(imp.name)} } from '${imp.from}?render'\n`;
39
39
  }
40
+ for (const d of ir.dataImports)
41
+ out += `import ${d.clause} from '${d.from}'\n`;
40
42
  for (const line of ir.scriptImports)
41
43
  out += `${line}\n`;
42
44
  out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
@@ -14,6 +14,8 @@ export function emitServer(ir, clientUrl) {
14
14
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
15
15
  for (const imp of ir.imports)
16
16
  out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
17
+ for (const d of ir.dataImports)
18
+ out += `import ${d.clause} from '${d.from}'\n`;
17
19
  for (const line of ir.scriptImports)
18
20
  out += `${line}\n`;
19
21
  const html = htmlExpr(ir.nodes);
@@ -1,4 +1,4 @@
1
- /** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
1
+ /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
2
2
  export declare class ClarusError extends Error {
3
3
  file: string;
4
4
  line: number;
@@ -1,4 +1,4 @@
1
- /** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
1
+ /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
2
2
  export class ClarusError extends Error {
3
3
  file;
4
4
  line;
@@ -1,4 +1,4 @@
1
- import type { ImportDecl, InputDecl, ParsedFile } from './parse.ts';
1
+ import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
2
2
  import { type Signals } from './script.ts';
3
3
  export type IRNode = {
4
4
  kind: 'static';
@@ -68,6 +68,7 @@ export type ComponentIR = {
68
68
  imports: ImportDecl[];
69
69
  script?: string;
70
70
  scriptImports: string[];
71
+ dataImports: DataImport[];
71
72
  signals: Signals;
72
73
  stateful: boolean;
73
74
  nodes: IRNode[];
@@ -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.headStart);
72
+ checkExpr(node.list, file, source, node.listStart);
64
73
  if (node.track !== null)
65
- checkExpr(node.track, file, source, node.headStart);
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(/\.clarus$/, ''),
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,
@@ -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[];
@@ -1,21 +1,37 @@
1
- // .clarus source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
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 = line.match(INPUT_RE)))
16
- out.inputs.push({ name: m[1], type: m[2].trim(), default: m[3], start: i });
17
- else if ((m = line.match(IMPORT_RE)))
18
- out.imports.push({ name: m[1], from: m[3], start: i });
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
- parts.push(text.slice(from, j));
218
+ push(from, j);
197
219
  from = j + 1;
198
220
  }
199
221
  }
200
- return [...parts, text.slice(from)].map((p) => p.trim()).filter(Boolean);
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
- const [first = '', ...rest] = splitClauses(head);
208
- const m = /^([\s\S]+?)\s+of\s+([\s\S]+)$/.exec(first);
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]+)$/.exec(clause);
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: string[];
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;
@@ -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 };
@@ -1,7 +1,7 @@
1
1
  type PageModule = {
2
2
  render(props?: object): string;
3
3
  };
4
- /** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
4
+ /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
5
5
  export declare function routeFromFile(file: string): string;
6
6
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
7
7
  loaderUrl?: string;
@@ -1,7 +1,7 @@
1
1
  // The fetch handler: Request → Response. Same function for dev, per-request SSR and (later) build-time prerender.
2
- /** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
2
+ /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
3
3
  export function routeFromFile(file) {
4
- const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.clarus$/, '').replace(/\/index$/, '');
4
+ const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
5
5
  return path || '/';
6
6
  }
7
7
  export function createHandler(pages, options = {}) {
@@ -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
+ }
@@ -1,9 +1,13 @@
1
- /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
1
+ /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
2
2
  export declare function findClarusFiles(srcDir: string): string[];
3
3
  /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
4
4
  export declare function routeToFile(route: string): string;
5
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.
6
+ * Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
7
+ * build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
8
+ * routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
8
9
  */
9
- export declare function prerender(serverEntry: string, outDir: string): Promise<string[]>;
10
+ export declare function prerender(serverEntry: string, outDir: string, manifestFile: string, only?: string[]): Promise<{
11
+ routes: string[];
12
+ readers: string[];
13
+ }>;
@@ -2,7 +2,7 @@
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { readdirSync } from 'node:fs';
4
4
  import { resolve } from 'node:path';
5
- /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
5
+ /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
6
6
  export function findClarusFiles(srcDir) {
7
7
  let entries;
8
8
  try {
@@ -11,7 +11,7 @@ export function findClarusFiles(srcDir) {
11
11
  catch {
12
12
  return [];
13
13
  }
14
- return entries.filter((f) => f.endsWith('.clarus')).map((f) => resolve(srcDir, f)).sort();
14
+ return entries.filter((f) => f.endsWith('.tscl')).map((f) => resolve(srcDir, f)).sort();
15
15
  }
16
16
  /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
17
17
  export function routeToFile(route) {
@@ -19,18 +19,22 @@ export function routeToFile(route) {
19
19
  return path ? `${path}/index.html` : 'index.html';
20
20
  }
21
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.
22
+ * Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
23
+ * build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
24
+ * routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
24
25
  */
25
- export async function prerender(serverEntry, outDir) {
26
+ export async function prerender(serverEntry, outDir, manifestFile, only) {
26
27
  const script = `
27
28
  import { mkdirSync, writeFileSync } from 'node:fs'
28
29
  import { dirname, resolve } from 'node:path'
29
30
  import { pathToFileURL } from 'node:url'
30
31
  const routeToFile = ${routeToFile.toString()}
31
- const [entry, outDir] = process.argv.slice(1)
32
+ const [entry, outDir, only] = process.argv.slice(1)
32
33
  const { default: handler } = await import(pathToFileURL(entry).href)
33
- for (const route of handler.routes) {
34
+ const routes = only ? JSON.parse(only) : handler.routes
35
+ const readers = []
36
+ for (const route of routes) {
37
+ globalThis.__clManifestRead = false
34
38
  let response
35
39
  try {
36
40
  response = await handler.fetch(new Request('http://localhost' + route))
@@ -45,10 +49,13 @@ export async function prerender(serverEntry, outDir) {
45
49
  const file = resolve(outDir, routeToFile(route))
46
50
  mkdirSync(dirname(file), { recursive: true })
47
51
  writeFileSync(file, await response.text())
52
+ if (globalThis.__clManifestRead) readers.push(route)
48
53
  }
49
- process.stdout.write(JSON.stringify(handler.routes))
54
+ process.stdout.write(JSON.stringify({ routes, readers }))
50
55
  `;
51
- const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, serverEntry, outDir], { encoding: 'utf8' });
56
+ const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
57
+ const env = { ...process.env, CLARUS_MANIFEST: manifestFile };
58
+ const result = spawnSync(process.execPath, args, { encoding: 'utf8', env });
52
59
  if (result.status !== 0)
53
60
  throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
54
61
  return JSON.parse(result.stdout);
@@ -0,0 +1,38 @@
1
+ export type Attach = 'load' | 'idle' | 'visible' | 'interaction';
2
+ export type IslandInfo = {
3
+ component: string;
4
+ src: string;
5
+ attach: Attach;
6
+ count: number;
7
+ gzip: number;
8
+ };
9
+ export type RouteInfo = {
10
+ mode: 'static';
11
+ html: string;
12
+ loader: null;
13
+ islands: IslandInfo[];
14
+ /** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
15
+ js: {
16
+ files: string[];
17
+ gzip: number;
18
+ initialGzip: number;
19
+ };
20
+ css: string[];
21
+ };
22
+ export type Manifest = {
23
+ version: 1;
24
+ routes: Record<string, RouteInfo>;
25
+ };
26
+ /** Vite's client manifest (dist/client/.vite/manifest.json). */
27
+ export type ChunkGraph = Record<string, {
28
+ file: string;
29
+ imports?: string[];
30
+ }>;
31
+ /** What one prerendered page ships. `size` returns a built file's gzip size. */
32
+ export declare function describeRoute(route: string, html: string, opts: {
33
+ base: string;
34
+ chunks: ChunkGraph;
35
+ size(file: string): number;
36
+ }): RouteInfo;
37
+ /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
38
+ export declare function writeManifest(distDir: string, routes: string[], base: string): Manifest;
@@ -0,0 +1,69 @@
1
+ // The route manifest: after `vite build`, what each page ships, read back from its prerendered HTML.
2
+ // dist/clarusjs-manifest.json is what `clarusjs explain` prints. Written outside dist/client, so it isn't served.
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { gzipSync } from 'node:zlib';
6
+ import { routeToFile } from './build.js';
7
+ const attrsOf = (tag) => {
8
+ const out = {};
9
+ for (const m of tag.matchAll(/([\w-]+)="([^"]*)"/g))
10
+ out[m[1]] = m[2].replace(/&amp;/g, '&');
11
+ return out;
12
+ };
13
+ /** What one prerendered page ships. `size` returns a built file's gzip size. */
14
+ export function describeRoute(route, html, opts) {
15
+ const local = (url) => (url.startsWith(opts.base) ? url.slice(opts.base.length) : url.replace(/^\//, ''));
16
+ const byFile = new Map(Object.values(opts.chunks).map((c) => [c.file, c]));
17
+ const keyFile = new Map(Object.entries(opts.chunks).map(([k, c]) => [k, c.file]));
18
+ // A chunk and everything it imports, in load order.
19
+ const closure = (file, into) => {
20
+ if (into.includes(file))
21
+ return;
22
+ into.push(file);
23
+ for (const imp of byFile.get(file)?.imports ?? [])
24
+ closure(keyFile.get(imp) ?? imp, into);
25
+ };
26
+ const islands = [];
27
+ for (const m of html.matchAll(/<cl-island\b([^>]*)>/g)) {
28
+ const a = attrsOf(m[1]);
29
+ const attach = (a.a ?? 'load');
30
+ const src = local(a.src ?? '');
31
+ const same = islands.find((i) => i.component === a.c && i.attach === attach);
32
+ if (same)
33
+ same.count++;
34
+ else
35
+ islands.push({ component: a.c ?? '', src, attach, count: 1, gzip: opts.size(src) });
36
+ }
37
+ const all = [];
38
+ const initial = [];
39
+ for (const m of html.matchAll(/<script type="module" src="([^"]+)"><\/script>/g)) {
40
+ closure(local(m[1]), all);
41
+ closure(local(m[1]), initial);
42
+ }
43
+ for (const island of islands) {
44
+ closure(island.src, all);
45
+ if (island.attach === 'load')
46
+ closure(island.src, initial);
47
+ }
48
+ const sum = (files) => files.reduce((n, f) => n + opts.size(f), 0);
49
+ const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
50
+ // ponytail: every route is prerendered with no data loader; mode and loader become real with routing (#28).
51
+ return { mode: 'static', html: routeToFile(route), loader: null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
52
+ }
53
+ /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
54
+ export function writeManifest(distDir, routes, base) {
55
+ const client = resolve(distDir, 'client');
56
+ const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
57
+ const sizes = new Map();
58
+ const size = (file) => {
59
+ if (!sizes.has(file))
60
+ sizes.set(file, gzipSync(readFileSync(resolve(client, file)), { level: 9 }).length);
61
+ return sizes.get(file);
62
+ };
63
+ const manifest = { version: 1, routes: {} };
64
+ for (const route of routes) {
65
+ manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size });
66
+ }
67
+ writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
68
+ return manifest;
69
+ }
@@ -1,11 +1,12 @@
1
1
  // The clarusjs Vite plugin: a thin adapter around the compiler.
2
2
  // Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
3
- import { existsSync, readFileSync } from 'node:fs';
4
- import { isAbsolute, relative, resolve } from 'node:path';
3
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
4
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { isRunnableDevEnvironment } from 'vite';
7
7
  import { compile, ClarusError } from '../compiler/index.js';
8
8
  import { findClarusFiles, prerender } from './build.js';
9
+ import { writeManifest } from './manifest.js';
9
10
  import { sendResponse, toRequest } from './node.js';
10
11
  // From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
11
12
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
@@ -21,7 +22,7 @@ const CLIENT_OUT = 'dist/client';
21
22
  // Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
22
23
  const CHUNK_TOKEN = '__CLARUS_CHUNK__';
23
24
  const SERVER_OUT = 'dist/server';
24
- const entryName = (root, file) => relative(root, file).replace(/\.clarus$/, '');
25
+ const entryName = (root, file) => relative(root, file).replace(/\.tscl$/, '');
25
26
  export default function clarusjs() {
26
27
  let root = process.cwd();
27
28
  let command = 'serve';
@@ -98,7 +99,7 @@ export default function clarusjs() {
98
99
  out.code = out.code.replace(/__CLARUS_CHUNK__\[(.+?)\]__/g, (_, name) => {
99
100
  const url = byName.get(name);
100
101
  if (!url)
101
- this.error(`clarusjs: no client chunk for ${name}.clarus (stateful components must be under src/)`);
102
+ this.error(`clarusjs: no client chunk for ${name}.tscl (stateful components must be under src/)`);
102
103
  return url;
103
104
  });
104
105
  }
@@ -115,7 +116,18 @@ export default function clarusjs() {
115
116
  return;
116
117
  await builder.build(client);
117
118
  await builder.build(ssr);
118
- await prerender(resolve(builder.config.root, SERVER_OUT, 'index.mjs'), resolve(builder.config.root, CLIENT_OUT));
119
+ const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
120
+ const out = resolve(builder.config.root, CLIENT_OUT);
121
+ const dist = dirname(out);
122
+ const manifestFile = resolve(dist, 'clarusjs-manifest.json');
123
+ rmSync(manifestFile, { force: true }); // a page reading the manifest must never see the previous build's
124
+ const { routes, readers } = await prerender(entry, out, manifestFile);
125
+ writeManifest(dist, routes, builder.config.base);
126
+ // Pages that read the manifest saw none on the first pass: render them again now that it exists.
127
+ if (readers.length) {
128
+ await prerender(entry, out, manifestFile, readers);
129
+ writeManifest(dist, routes, builder.config.base);
130
+ }
119
131
  },
120
132
  resolveId(id) {
121
133
  if (id === '/cl-loader.js')
@@ -128,15 +140,15 @@ export default function clarusjs() {
128
140
  return;
129
141
  const loaderUrl = builtUrls()?.get(LOADER_ENTRY) ?? '/cl-loader.js';
130
142
  return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
131
- `export default createHandler(import.meta.glob('/src/pages/**/*.clarus'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
143
+ `export default createHandler(import.meta.glob('/src/pages/**/*.tscl'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
132
144
  },
133
145
  transform: {
134
- filter: { id: /\.clarus(\?|$)/ },
146
+ filter: { id: /\.tscl(\?|$)/ },
135
147
  handler(code, id) {
136
148
  const file = id.replace(/\?.*$/, '');
137
149
  // ?render: a component's server render function, used in the browser to render children of islands.
138
150
  const target = this.environment.config.consumer === 'server' || /[?&]render\b/.test(id) ? 'server' : 'client';
139
- // ponytail: ?import makes Vite's dev transform middleware serve .clarus as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
151
+ // ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
140
152
  const consumer = this.environment.config.consumer;
141
153
  // Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
142
154
  // exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -48,8 +48,15 @@
48
48
  "./vite": {
49
49
  "types": "./dist/vite/plugin.d.ts",
50
50
  "default": "./dist/vite/plugin.js"
51
+ },
52
+ "./manifest": {
53
+ "types": "./dist/server/manifest.d.ts",
54
+ "default": "./dist/server/manifest.js"
51
55
  }
52
56
  },
57
+ "bin": {
58
+ "clarusjs": "./dist/cli/index.js"
59
+ },
53
60
  "files": [
54
61
  "dist",
55
62
  "LICENSE",
@@ -59,7 +66,8 @@
59
66
  "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
60
67
  },
61
68
  "dependencies": {
62
- "acorn": "^8.19.0"
69
+ "acorn": "^8.19.0",
70
+ "commander": "^15.1.0"
63
71
  },
64
72
  "peerDependencies": {
65
73
  "vite": "^8.0.0"