clarusjs 0.2.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 +5 -15
- package/dist/check/generate.d.ts +11 -0
- package/dist/check/generate.js +164 -0
- package/dist/cli/check.d.ts +17 -0
- package/dist/cli/check.js +91 -0
- package/dist/cli/explain.d.ts +9 -0
- package/dist/cli/explain.js +46 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +38 -0
- package/dist/compiler/emit-client.js +90 -17
- package/dist/compiler/emit-server.js +32 -24
- package/dist/compiler/errors.d.ts +1 -1
- package/dist/compiler/errors.js +1 -1
- package/dist/compiler/html-expr.d.ts +29 -0
- package/dist/compiler/html-expr.js +85 -0
- package/dist/compiler/ir.d.ts +40 -1
- package/dist/compiler/ir.js +155 -33
- package/dist/compiler/parse.d.ts +56 -0
- package/dist/compiler/parse.js +244 -11
- package/dist/compiler/script.d.ts +21 -2
- package/dist/compiler/script.js +67 -6
- package/dist/runtime/attrs.d.ts +5 -0
- package/dist/runtime/attrs.js +56 -0
- package/dist/runtime/dom.d.ts +61 -5
- package/dist/runtime/dom.js +257 -17
- package/dist/runtime/html.d.ts +10 -0
- package/dist/runtime/html.js +30 -0
- package/dist/runtime/index.d.ts +4 -2
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/loader.d.ts +7 -2
- package/dist/runtime/loader.js +125 -28
- package/dist/runtime/serialize.d.ts +8 -0
- package/dist/runtime/serialize.js +93 -0
- package/dist/runtime/server.d.ts +9 -4
- package/dist/runtime/server.js +13 -24
- package/dist/runtime/signals.d.ts +12 -0
- package/dist/runtime/signals.js +44 -1
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +2 -2
- package/dist/server/manifest.d.ts +4 -0
- package/dist/server/manifest.js +17 -0
- package/dist/vite/build.d.ts +8 -4
- package/dist/vite/build.js +16 -9
- package/dist/vite/manifest.d.ts +38 -0
- package/dist/vite/manifest.js +69 -0
- package/dist/vite/plugin.js +49 -10
- package/package.json +10 -2
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
|
|
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.
|
|
33
|
+
{{-- src/components/counter.tscl --}}
|
|
34
34
|
@input start: number = 0
|
|
35
35
|
|
|
36
36
|
<script>
|
|
@@ -42,27 +42,17 @@ export default defineConfig({ plugins: [clarusjs()] })
|
|
|
42
42
|
```
|
|
43
43
|
|
|
44
44
|
```clarus
|
|
45
|
-
{{-- src/pages/index.
|
|
46
|
-
@import counter from '../components/counter.
|
|
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/**/*.
|
|
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
|
|
|
56
|
-
## Exports
|
|
57
|
-
|
|
58
|
-
| Import | What |
|
|
59
|
-
|---|---|
|
|
60
|
-
| `clarusjs/vite` | the Vite plugin |
|
|
61
|
-
| `clarusjs/compiler` | `compile()`, for tools |
|
|
62
|
-
| `clarusjs/runtime` | browser runtime used by compiled components (signals, attach) |
|
|
63
|
-
| `clarusjs/runtime/server` | server helpers used by compiled components |
|
|
64
|
-
| `clarusjs/server` | `createHandler()`, the `fetch(Request)` handler |
|
|
65
|
-
|
|
66
56
|
## Links
|
|
67
57
|
|
|
68
58
|
- Repository and design: [github.com/forinda/clarusjs](https://github.com/forinda/clarusjs)
|
|
@@ -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,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,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();
|
|
@@ -1,34 +1,107 @@
|
|
|
1
|
+
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr } from './html-expr.js';
|
|
1
2
|
import { rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
2
|
-
import { indentScript, inputsLine } from './shared.js';
|
|
3
|
+
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
3
4
|
export function emitClient(ir) {
|
|
4
5
|
if (!ir.stateful)
|
|
5
6
|
return 'export {}\n';
|
|
6
7
|
const kinds = new Set(ir.signals.values());
|
|
7
|
-
const
|
|
8
|
+
const all = walk(ir.nodes);
|
|
9
|
+
const hasHoles = all.some((n) => n.kind === 'hole' && n.reactive);
|
|
10
|
+
const hasBlocks = all.some((n) => n.kind === 'if' && n.block >= 0);
|
|
11
|
+
const hasFors = all.some((n) => n.kind === 'for' && n.block >= 0);
|
|
12
|
+
const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
|
|
13
|
+
const rendersHtml = hasBlocks || hasFors || hasRegions;
|
|
8
14
|
const used = [
|
|
9
15
|
kinds.has('state') && 'state',
|
|
10
16
|
kinds.has('derived') && 'derived',
|
|
11
|
-
|
|
12
|
-
|
|
17
|
+
kinds.has('shared') && 'shared',
|
|
18
|
+
hasHoles && 'holes as __cl_holes',
|
|
19
|
+
hasHoles && 'text as __cl_text',
|
|
13
20
|
ir.events.length > 0 && 'on as __cl_on',
|
|
21
|
+
all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
|
|
22
|
+
hasBlocks && 'block as __cl_block',
|
|
23
|
+
hasFors && 'forBlock as __cl_for',
|
|
24
|
+
hasRegions && 'region as __cl_region',
|
|
25
|
+
// Branch and row HTML is rendered in the browser with the same helpers as on the server.
|
|
26
|
+
rendersHtml && 'escape as __cl_escape',
|
|
27
|
+
rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
|
|
28
|
+
rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
|
|
29
|
+
rendersHtml && hasFors && 'forHtml as __cl_forHtml',
|
|
30
|
+
hasRegions && 'regionHtml as __cl_regionHtml',
|
|
14
31
|
].filter(Boolean);
|
|
15
32
|
let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
|
|
16
|
-
|
|
33
|
+
// Child components render in the browser too (in branches, rows and regions): import their server render
|
|
34
|
+
// functions through the plugin's ?render query.
|
|
35
|
+
const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
|
|
36
|
+
for (const imp of ir.imports) {
|
|
37
|
+
if (usedComponents.has(imp.name))
|
|
38
|
+
out += `import { render as ${renderName(imp.name)} } from '${imp.from}?render'\n`;
|
|
39
|
+
}
|
|
40
|
+
for (const d of ir.dataImports)
|
|
41
|
+
out += `import ${d.clause} from '${d.from}'\n`;
|
|
42
|
+
for (const line of ir.scriptImports)
|
|
43
|
+
out += `${line}\n`;
|
|
44
|
+
out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
|
|
17
45
|
out += inputsLine(ir);
|
|
18
46
|
if (ir.script)
|
|
19
|
-
out += indentScript(rewriteClient(ir.script, ir.signals));
|
|
20
|
-
const
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
47
|
+
out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true }));
|
|
48
|
+
const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
|
|
49
|
+
if (lines.length)
|
|
50
|
+
out += '\n' + lines.map((l) => ` ${l}\n`).join('');
|
|
51
|
+
return out + '}\n';
|
|
52
|
+
}
|
|
53
|
+
/** Rewrites expressions for the browser: reads of `signals` become `.get()`. */
|
|
54
|
+
function rewriter(signals) {
|
|
55
|
+
return {
|
|
56
|
+
expr: (e) => rewriteClientExpr(e, signals),
|
|
57
|
+
without: (names) => rewriter(new Map([...signals].filter(([name]) => !names.includes(name)))),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Code that wires one scope: the top level, an @if branch, a @for row or @empty content. Holes, attributes and
|
|
62
|
+
* events directly in `nodes` are wired here; nested blocks and lists get their own calls, whose branches and rows
|
|
63
|
+
* wire themselves. `ctx` names the island (top level) or the row range the scope's markers are looked up in.
|
|
64
|
+
*/
|
|
65
|
+
function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
66
|
+
const rw = rewriter(signals);
|
|
67
|
+
const lines = [];
|
|
68
|
+
const holes = nodes.filter((n) => n.kind === 'hole' && n.reactive);
|
|
69
|
+
if (holes.length)
|
|
70
|
+
lines.push(`const __cl_h = __cl_holes(${ctx})`);
|
|
71
|
+
for (const h of [...holes].sort((a, b) => a.index - b.index))
|
|
72
|
+
lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
|
|
73
|
+
for (const a of nodes) {
|
|
74
|
+
if (a.kind === 'attr' && a.reactive)
|
|
75
|
+
lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
|
|
25
76
|
}
|
|
26
|
-
for (const e of ir.events) {
|
|
27
|
-
const body = rewriteClient(e.handler,
|
|
77
|
+
for (const e of ir.events.filter((ev) => ev.scope === scope)) {
|
|
78
|
+
const body = rewriteClient(e.handler, signals).trim();
|
|
28
79
|
const end = body.includes('//') ? '\n ' : ' '; // a trailing line comment must not swallow the closing `})`
|
|
29
|
-
|
|
80
|
+
lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
|
|
30
81
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
82
|
+
const fn = (args, inner) => inner.length ? `(${args}) => {\n${inner.map((l) => ` ${l}`).join('\n')}\n }` : `(${args}) => {}`;
|
|
83
|
+
for (const n of nodes) {
|
|
84
|
+
if (n.kind === 'component' && n.region >= 0) {
|
|
85
|
+
const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
|
|
86
|
+
lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
|
|
87
|
+
}
|
|
88
|
+
if (n.kind === 'if' && n.block >= 0) {
|
|
89
|
+
const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
|
|
90
|
+
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
|
|
91
|
+
}
|
|
92
|
+
if (n.kind === 'for' && n.block >= 0) {
|
|
93
|
+
// In row HTML `item` and `$index` are plain values; while wiring a row they are that row's signals.
|
|
94
|
+
const rowCtx = `__cl_c${depth + 1}`;
|
|
95
|
+
const loop = [n.item, '$index'];
|
|
96
|
+
const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state'])]);
|
|
97
|
+
const plain = rw.without(loop);
|
|
98
|
+
const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
|
|
99
|
+
const row = `{\n html: (${n.item}, $index) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${n.item}, $index`, wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1))},\n }`;
|
|
100
|
+
const empty = n.empty
|
|
101
|
+
? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
|
|
102
|
+
: 'null';
|
|
103
|
+
lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${n.item}, $index) => ${key}, ${row}, ${empty})`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return lines;
|
|
34
107
|
}
|
|
@@ -1,41 +1,49 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { htmlExpr, walk } from './html-expr.js';
|
|
2
|
+
import { rewriteServer } from './script.js';
|
|
2
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
3
4
|
export function emitServer(ir, clientUrl) {
|
|
4
|
-
const
|
|
5
|
+
const all = walk(ir.nodes);
|
|
6
|
+
const runtime = [
|
|
7
|
+
'escape as __cl_escape',
|
|
8
|
+
ir.stateful && 'island as __cl_island',
|
|
9
|
+
all.some((n) => n.kind === 'attr') && 'attr as __cl_attrHtml',
|
|
10
|
+
all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
11
|
+
all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
|
|
12
|
+
all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
|
|
13
|
+
].filter(Boolean).join(', ');
|
|
5
14
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
6
15
|
for (const imp of ir.imports)
|
|
7
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`;
|
|
19
|
+
for (const line of ir.scriptImports)
|
|
20
|
+
out += `${line}\n`;
|
|
8
21
|
const html = htmlExpr(ir.nodes);
|
|
9
22
|
const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }`.replace('{ }', '{}');
|
|
10
|
-
out += `\nexport function render(__cl_props = {},
|
|
23
|
+
out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
|
|
11
24
|
if (ir.stateful)
|
|
12
|
-
out += ` if (
|
|
13
|
-
else
|
|
14
|
-
out +=
|
|
25
|
+
out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
26
|
+
else {
|
|
27
|
+
out += unknownSlotCheck(ir);
|
|
28
|
+
out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
|
|
29
|
+
}
|
|
15
30
|
out += inputsLine(ir);
|
|
16
31
|
if (ir.script)
|
|
17
32
|
out += indentScript(rewriteServer(ir.script));
|
|
18
33
|
out += ir.stateful
|
|
19
|
-
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html})\n`
|
|
34
|
+
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach)\n`
|
|
20
35
|
: ` return ${html}\n`;
|
|
21
36
|
return out + '}\n';
|
|
22
37
|
}
|
|
23
|
-
/**
|
|
24
|
-
function
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
return '(__cl_slot ?? "")';
|
|
30
|
-
if (n.kind === 'component') {
|
|
31
|
-
const props = n.props.map((p) => `${p.name}: ${wrapExpr(p.expr)}`).join(', ');
|
|
32
|
-
return n.children.length ? `${renderName(n.name)}({ ${props} }, ${htmlExpr(n.children)})` : `${renderName(n.name)}({ ${props} })`;
|
|
33
|
-
}
|
|
34
|
-
const value = `__cl_escape(${wrapExpr(n.expr)})`;
|
|
35
|
-
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
36
|
-
});
|
|
37
|
-
return parts.length ? parts.join(' + ') : '""';
|
|
38
|
+
/** Content for a slot this component doesn't have is an error (at render, so a build fails naming it). */
|
|
39
|
+
function unknownSlotCheck(ir) {
|
|
40
|
+
const known = [...new Set(walk(ir.nodes).flatMap((n) => (n.kind === 'slot' ? [n.name] : [])))];
|
|
41
|
+
const noDefault = JSON.stringify(`[clarusjs] <${ir.name}> has no <slot /> for the content passed to it`);
|
|
42
|
+
const noNamed = JSON.stringify(`[clarusjs] <${ir.name}> has no slot "`);
|
|
43
|
+
return ` for (const __cl_k in __cl_slots) if (!${JSON.stringify(known)}.includes(__cl_k)) throw new Error(__cl_k === "default" ? ${noDefault} : ${noNamed} + __cl_k + '"')\n`;
|
|
38
44
|
}
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
/** The component's state() values after its script ran: the island's starting point in the browser. */
|
|
46
|
+
function stateArg(ir) {
|
|
47
|
+
const names = [...ir.signals].filter(([, kind]) => kind === 'state').map(([name]) => name);
|
|
48
|
+
return names.length ? `{ ${names.join(', ')} }` : 'undefined';
|
|
41
49
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** A compile error pointing at a place in a .
|
|
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;
|
package/dist/compiler/errors.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** A compile error pointing at a place in a .
|
|
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;
|