clarusjs 0.13.0 → 0.14.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/dist/check/generate.js +42 -8
- package/dist/compiler/class-style.d.ts +1 -1
- package/dist/compiler/class-style.js +4 -0
- package/dist/compiler/emit-client.js +15 -1
- package/dist/compiler/emit-server.js +11 -4
- package/dist/compiler/html-expr.d.ts +10 -2
- package/dist/compiler/html-expr.js +28 -16
- package/dist/compiler/icon.d.ts +1 -1
- package/dist/compiler/icon.js +4 -0
- package/dist/compiler/index.js +10 -1
- package/dist/compiler/ir.d.ts +19 -0
- package/dist/compiler/ir.js +27 -1
- package/dist/compiler/lint.js +12 -1
- package/dist/compiler/parse.d.ts +24 -0
- package/dist/compiler/parse.js +66 -0
- package/dist/compiler/script.d.ts +10 -1
- package/dist/compiler/script.js +17 -3
- package/dist/fetch/index.d.ts +157 -3
- package/dist/fetch/index.js +135 -14
- package/dist/runtime/dom.d.ts +9 -0
- package/dist/runtime/dom.js +24 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/server.d.ts +12 -0
- package/dist/runtime/server.js +34 -1
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +5 -2
- package/dist/server/views.d.ts +1 -1
- package/dist/server/views.js +1 -1
- package/dist/vite/plugin.js +15 -2
- package/package.json +1 -1
package/dist/check/generate.js
CHANGED
|
@@ -48,6 +48,13 @@ export function generateTs(source, file, options = {}) {
|
|
|
48
48
|
emit('\n');
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
|
+
const serverScript = parsed.serverScript ? splitImports(parsed.serverScript.code, file, source, parsed.serverScript.start, true) : null;
|
|
52
|
+
if (parsed.serverScript && serverScript) {
|
|
53
|
+
for (const imp of serverScript.imports) {
|
|
54
|
+
copy(imp.text, parsed.serverScript.start + imp.start);
|
|
55
|
+
emit('\n');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
51
58
|
for (const t of parsed.types) {
|
|
52
59
|
emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
|
|
53
60
|
copy(t.type, t.typeStart);
|
|
@@ -76,7 +83,8 @@ export function generateTs(source, file, options = {}) {
|
|
|
76
83
|
emit('\n');
|
|
77
84
|
}
|
|
78
85
|
emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
|
|
79
|
-
|
|
86
|
+
const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
|
|
87
|
+
emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
|
|
80
88
|
for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
|
|
81
89
|
if (!list.length)
|
|
82
90
|
continue;
|
|
@@ -93,23 +101,27 @@ export function generateTs(source, file, options = {}) {
|
|
|
93
101
|
emit(' } = __cl_props\n');
|
|
94
102
|
emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
|
|
95
103
|
}
|
|
96
|
-
|
|
97
|
-
const body =
|
|
104
|
+
const copyScript = (from, split) => {
|
|
105
|
+
const body = split.body;
|
|
98
106
|
const cuts = [
|
|
99
|
-
...
|
|
100
|
-
...untypedParams(
|
|
107
|
+
...split.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
|
|
108
|
+
...untypedParams(from.code).map((e) => ({ ...e, end: e.at })),
|
|
101
109
|
].sort((a, b) => a.at - b.at);
|
|
102
110
|
let pos = 0;
|
|
103
111
|
for (const cut of cuts) {
|
|
104
112
|
if (cut.at > pos)
|
|
105
|
-
copy(body.slice(pos, cut.at),
|
|
113
|
+
copy(body.slice(pos, cut.at), from.start + pos);
|
|
106
114
|
emit(cut.text);
|
|
107
115
|
pos = Math.max(pos, cut.end);
|
|
108
116
|
}
|
|
109
117
|
if (body.length > pos)
|
|
110
|
-
copy(body.slice(pos),
|
|
118
|
+
copy(body.slice(pos), from.start + pos);
|
|
111
119
|
emit('\n;\n');
|
|
112
|
-
}
|
|
120
|
+
};
|
|
121
|
+
if (parsed.serverScript && serverScript)
|
|
122
|
+
copyScript(parsed.serverScript, serverScript);
|
|
123
|
+
if (parsed.script && script)
|
|
124
|
+
copyScript(parsed.script, script);
|
|
113
125
|
const use = (expr, start) => {
|
|
114
126
|
emit(' __cl_use((');
|
|
115
127
|
copy(expr, at(expr, start));
|
|
@@ -159,6 +171,28 @@ export function generateTs(source, file, options = {}) {
|
|
|
159
171
|
emit(' }\n');
|
|
160
172
|
});
|
|
161
173
|
return;
|
|
174
|
+
case 'await': {
|
|
175
|
+
emit(' { const __cl_aw = (');
|
|
176
|
+
copy(node.expr, at(node.expr, node.exprStart));
|
|
177
|
+
emit(');\n');
|
|
178
|
+
emit(' {\n');
|
|
179
|
+
node.pending.forEach(visit);
|
|
180
|
+
emit(' }\n');
|
|
181
|
+
for (const [b, type] of [[node.then, 'Awaited<typeof __cl_aw>'], [node.catch, 'any']]) {
|
|
182
|
+
if (!b)
|
|
183
|
+
continue;
|
|
184
|
+
emit(' { const ');
|
|
185
|
+
copy(b.name, b.nameStart);
|
|
186
|
+
emit(`: ${type} = null!; __cl_use(${b.name})\n`);
|
|
187
|
+
const outer = guards.splice(0);
|
|
188
|
+
guards.push(...outer.filter((g) => !referencesNames(g, new Set([b.name]))));
|
|
189
|
+
b.children.forEach(visit);
|
|
190
|
+
guards.splice(0, guards.length, ...outer);
|
|
191
|
+
emit(' }\n');
|
|
192
|
+
}
|
|
193
|
+
emit(' }\n');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
162
196
|
case 'for': {
|
|
163
197
|
emit(' for (const ');
|
|
164
198
|
copy(node.item, node.itemStart);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type TemplateNode } from './parse.ts';
|
|
2
2
|
export declare function foldClass(nodes: TemplateNode[], components: Set<string>): void;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { awaitLists } from './parse.js';
|
|
1
2
|
const spreadOf = (node) => node.attrs.find((a) => a.kind === 'prop' && a.name === '...')?.expr;
|
|
2
3
|
const isSource = (a, name) => a.name === name && a.kind !== 'event';
|
|
3
4
|
function part(a) {
|
|
@@ -45,5 +46,8 @@ export function foldClass(nodes, components) {
|
|
|
45
46
|
}
|
|
46
47
|
else if (node.type === 'fill')
|
|
47
48
|
foldClass(node.children, components);
|
|
49
|
+
else if (node.type === 'await')
|
|
50
|
+
for (const kids of awaitLists(node))
|
|
51
|
+
foldClass(kids, components);
|
|
48
52
|
}
|
|
49
53
|
}
|
|
@@ -8,7 +8,7 @@ export function emitClient(ir, hot) {
|
|
|
8
8
|
const kinds = new Set(ir.signals.values());
|
|
9
9
|
const all = walk(ir.nodes);
|
|
10
10
|
const hasHoles = all.some((n) => n.kind === 'hole' && n.reactive);
|
|
11
|
-
const hasBlocks = all.some((n) => n.kind === 'if' && n.block >= 0);
|
|
11
|
+
const hasBlocks = all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0);
|
|
12
12
|
const hasFors = all.some((n) => n.kind === 'for' && n.block >= 0);
|
|
13
13
|
const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
|
|
14
14
|
const rendersHtml = hasBlocks || hasFors || hasRegions;
|
|
@@ -22,6 +22,7 @@ export function emitClient(ir, hot) {
|
|
|
22
22
|
all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
|
|
23
23
|
all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
|
|
24
24
|
hasBlocks && 'block as __cl_block',
|
|
25
|
+
all.some((n) => n.kind === 'await' && n.block >= 0) && 'awaited as __cl_awaited',
|
|
25
26
|
hasFors && 'forBlock as __cl_for',
|
|
26
27
|
all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
|
|
27
28
|
hasRegions && 'region as __cl_region',
|
|
@@ -114,6 +115,19 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
114
115
|
const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
|
|
115
116
|
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
|
|
116
117
|
}
|
|
118
|
+
if (n.kind === 'await' && n.block >= 0) {
|
|
119
|
+
const a = `__cl_a${n.block}`;
|
|
120
|
+
lines.push(`const ${a} = __cl_awaited(() => ${wrapExpr(rw.expr(n.expr))})`);
|
|
121
|
+
const named = (b, k) => {
|
|
122
|
+
if (!b)
|
|
123
|
+
return ` { html: () => "", wire: () => {} },`;
|
|
124
|
+
const plain = rw.without([b.name]);
|
|
125
|
+
const wire = wiring(ir, b.nodes, `${n.block}.${k}`, ctx, new Map([...signals].filter(([name]) => name !== b.name)), depth);
|
|
126
|
+
return ` { html: () => ((${b.name}) => ${htmlExpr(b.nodes, plain)})(${a}.v()), wire: ${fn('', wire.length ? [`const ${b.name} = ${a}.v()`, ...wire] : [])} },`;
|
|
127
|
+
};
|
|
128
|
+
const branches = [` { html: () => ${htmlExpr(n.pending, rw)}, wire: ${fn('', wiring(ir, n.pending, `${n.block}.0`, ctx, signals, depth))} },`, named(n.then, 1), named(n.catch, 2)];
|
|
129
|
+
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${a}.k(), [\n${branches.join('\n')}\n ])`);
|
|
130
|
+
}
|
|
117
131
|
if (n.kind === 'for' && n.block >= 0) {
|
|
118
132
|
const rowCtx = `__cl_c${depth + 1}`;
|
|
119
133
|
const names = rowNames(n, ir.events);
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { htmlExpr, walk } from './html-expr.js';
|
|
1
|
+
import { asWritten, htmlExpr, walk } from './html-expr.js';
|
|
2
2
|
import { rewriteServer } from './script.js';
|
|
3
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
4
|
export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
5
5
|
const all = walk(ir.nodes);
|
|
6
|
+
const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null });
|
|
6
7
|
const runtime = [
|
|
7
8
|
'escape as __cl_escape',
|
|
8
9
|
all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
|
|
@@ -11,10 +12,13 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
|
11
12
|
all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
|
|
12
13
|
all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
|
|
13
14
|
all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
|
|
14
|
-
all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
15
|
+
all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
16
|
+
all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
|
|
15
17
|
all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
|
|
16
18
|
all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
|
|
17
19
|
loader && 'loaded as __cl_loaded',
|
|
20
|
+
html.includes('__cl_join(') && 'join as __cl_join',
|
|
21
|
+
html.includes('__cl_sync(') && 'sync as __cl_sync',
|
|
18
22
|
].filter(Boolean).join(', ');
|
|
19
23
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
20
24
|
for (const imp of ir.imports)
|
|
@@ -23,9 +27,10 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
|
23
27
|
out += `import ${d.clause} from '${d.from}'\n`;
|
|
24
28
|
for (const line of ir.scriptImports)
|
|
25
29
|
out += `${line}\n`;
|
|
26
|
-
const
|
|
30
|
+
for (const line of ir.server?.imports ?? [])
|
|
31
|
+
out += `${line}\n`;
|
|
27
32
|
const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
|
|
28
|
-
out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
|
|
33
|
+
out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
|
|
29
34
|
if (ir.stateful)
|
|
30
35
|
out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
31
36
|
else {
|
|
@@ -38,6 +43,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
|
38
43
|
out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
|
|
39
44
|
if (ir.script)
|
|
40
45
|
out += indentScript(rewriteServer(ir.script));
|
|
46
|
+
if (ir.server)
|
|
47
|
+
out += indentScript(ir.server.body);
|
|
41
48
|
out += ir.stateful
|
|
42
49
|
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach, __cl_opts?.paths)\n`
|
|
43
50
|
: ` return ${html}\n`;
|
|
@@ -8,11 +8,19 @@ export type Rewriter = {
|
|
|
8
8
|
without(names: string[]): Rewriter;
|
|
9
9
|
};
|
|
10
10
|
export declare const asWritten: Rewriter;
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Server output only (#430): `island` is the component's name when it's an island, null when it isn't. Outside
|
|
13
|
+
* islands, a level that calls a component or places a slot joins its parts with __cl_join (a string, or a promise
|
|
14
|
+
* when an awaiting component is in it); inside an island, a component call is checked not to be a promise.
|
|
15
|
+
*/
|
|
16
|
+
export type ServerCtx = {
|
|
17
|
+
island: string | null;
|
|
18
|
+
};
|
|
19
|
+
export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter, ctx?: ServerCtx): string;
|
|
12
20
|
/** `render_child({ props }, { slots })` for a component node. */
|
|
13
21
|
export declare function componentCall(n: Extract<IRNode, {
|
|
14
22
|
kind: 'component';
|
|
15
|
-
}>, rw: Rewriter): string;
|
|
23
|
+
}>, rw: Rewriter, ctx?: ServerCtx): string;
|
|
16
24
|
/** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
|
|
17
25
|
export declare function whichExpr(n: Extract<IRNode, {
|
|
18
26
|
kind: 'if';
|
|
@@ -2,12 +2,13 @@ import { FOR_IMPLICIT } from './parse.js';
|
|
|
2
2
|
import { renderName } from './shared.js';
|
|
3
3
|
import { wrapExpr } from './script.js';
|
|
4
4
|
export const asWritten = { expr: (e) => e, without: () => asWritten };
|
|
5
|
-
|
|
5
|
+
const mayWait = (nodes) => walk(nodes).some((n) => n.kind === 'component' || n.kind === 'slot' || (n.kind === 'await' && n.block < 0));
|
|
6
|
+
export function htmlExpr(nodes, rw = asWritten, ctx) {
|
|
6
7
|
const parts = nodes.map((n) => {
|
|
7
8
|
if (n.kind === 'static')
|
|
8
9
|
return JSON.stringify(n.html);
|
|
9
10
|
if (n.kind === 'slot')
|
|
10
|
-
return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
|
|
11
|
+
return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw, ctx)})` : '""'})`;
|
|
11
12
|
if (n.kind === 'connect')
|
|
12
13
|
return '""';
|
|
13
14
|
if (n.kind === 'attr' && n.name === '...')
|
|
@@ -17,25 +18,33 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
17
18
|
if (n.kind === 'if') {
|
|
18
19
|
if (n.block === -1) {
|
|
19
20
|
const last = n.branches[n.branches.length - 1];
|
|
20
|
-
let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw)})` : '""';
|
|
21
|
+
let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw, ctx)})` : '""';
|
|
21
22
|
const conditional = last.cond === null ? n.branches.slice(0, -1) : n.branches;
|
|
22
23
|
for (const b of [...conditional].reverse())
|
|
23
|
-
expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw)}) : ${expr})`;
|
|
24
|
+
expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw, ctx)}) : ${expr})`;
|
|
24
25
|
return expr;
|
|
25
26
|
}
|
|
26
|
-
const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw)}`).join(', ');
|
|
27
|
+
const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw, ctx)}`).join(', ');
|
|
27
28
|
return `__cl_blockHtml(${n.block}, ${whichExpr(n, rw)}, [${branches}])`;
|
|
28
29
|
}
|
|
30
|
+
if (n.kind === 'await') {
|
|
31
|
+
if (n.block >= 0)
|
|
32
|
+
return `__cl_blockHtml(${n.block}, 0, [() => ${htmlExpr(n.pending, rw, ctx)}])`;
|
|
33
|
+
const branch = (b) => (b ? `(${b.name}) => ${htmlExpr(b.nodes, rw.without([b.name]), ctx)}` : 'null');
|
|
34
|
+
return `__cl_awaitHtml(${wrapExpr(rw.expr(n.expr))}, ${branch(n.then)}, ${branch(n.catch)})`;
|
|
35
|
+
}
|
|
29
36
|
if (n.kind === 'for') {
|
|
30
37
|
const list = wrapExpr(rw.expr(n.list));
|
|
31
|
-
const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
|
|
32
|
-
const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
|
|
38
|
+
const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
|
|
39
|
+
const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
|
|
33
40
|
if (n.block >= 0)
|
|
34
41
|
return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
|
|
35
|
-
|
|
42
|
+
const rows = ctx && !ctx.island && mayWait(n.nodes) ? `__cl_join(__cl_l.map(${row}))` : `__cl_l.map(${row}).join("")`;
|
|
43
|
+
return `((__cl_l) => __cl_l.length ? ${rows} : ${n.empty ? `(${htmlExpr(n.empty, rw, ctx)})` : '""'})([...(${list} ?? [])])`;
|
|
36
44
|
}
|
|
37
45
|
if (n.kind === 'component') {
|
|
38
|
-
const
|
|
46
|
+
const plain = componentCall(n, rw, ctx);
|
|
47
|
+
const call = ctx?.island ? `__cl_sync(${plain}, ${JSON.stringify(n.name)}, ${JSON.stringify(ctx.island)})` : plain;
|
|
39
48
|
return n.region >= 0 ? `__cl_regionHtml(${n.region}, () => ${call})` : call;
|
|
40
49
|
}
|
|
41
50
|
if (n.json)
|
|
@@ -43,13 +52,15 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
43
52
|
const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
|
|
44
53
|
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
45
54
|
});
|
|
55
|
+
if (ctx && !ctx.island && mayWait(nodes))
|
|
56
|
+
return `__cl_join([${parts.join(', ')}])`;
|
|
46
57
|
return parts.length ? parts.join(' + ') : '""';
|
|
47
58
|
}
|
|
48
|
-
export function componentCall(n, rw) {
|
|
59
|
+
export function componentCall(n, rw, ctx) {
|
|
49
60
|
const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${p.name}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
|
|
50
61
|
const slots = [
|
|
51
|
-
...(n.children.length ? [`"default": ${htmlExpr(n.children, rw)}`] : []),
|
|
52
|
-
...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
|
|
62
|
+
...(n.children.length ? [`"default": ${htmlExpr(n.children, rw, ctx)}`] : []),
|
|
63
|
+
...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw, ctx)}`),
|
|
53
64
|
];
|
|
54
65
|
const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
|
|
55
66
|
const opts = [...(n.attach ? [`attach: ${JSON.stringify(n.attach)}`] : []), ...(n.class ? [`class: ${JSON.stringify(n.class)}`] : []), ...(n.paths ? [`paths: { ${n.paths.map((p) => `${JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }`] : [])];
|
|
@@ -78,10 +89,11 @@ export function walk(nodes) {
|
|
|
78
89
|
return nodes.flatMap((n) => [
|
|
79
90
|
n,
|
|
80
91
|
...(n.kind === 'if' ? n.branches.flatMap((b) => walk(b.nodes))
|
|
81
|
-
: n.kind === '
|
|
82
|
-
: n.kind === '
|
|
83
|
-
: n.kind === '
|
|
84
|
-
:
|
|
92
|
+
: n.kind === 'await' ? [...walk(n.pending), ...walk(n.then?.nodes ?? []), ...walk(n.catch?.nodes ?? [])]
|
|
93
|
+
: n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
|
|
94
|
+
: n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
|
|
95
|
+
: n.kind === 'slot' ? walk(n.fallback)
|
|
96
|
+
: []),
|
|
85
97
|
]);
|
|
86
98
|
}
|
|
87
99
|
const DERIVED = {
|
package/dist/compiler/icon.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { IconLookup } from '../icons.ts';
|
|
2
2
|
import { ClarusError } from './errors.ts';
|
|
3
|
-
import type
|
|
3
|
+
import { type ParsedFile, type TemplateNode } from './parse.ts';
|
|
4
4
|
/**
|
|
5
5
|
* Finds an icon by `set:name` for `<icon>`: `resolveIcon` from clarusjs/icons, bound to the file being compiled.
|
|
6
6
|
* @see https://clarusjs.com/guide/icons
|
package/dist/compiler/icon.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClarusError } from './errors.js';
|
|
2
|
+
import { awaitLists } from './parse.js';
|
|
2
3
|
const LABELS = new Set(['aria-label', 'aria-labelledby']);
|
|
3
4
|
export function iconElement(node, file, source, icon) {
|
|
4
5
|
const fail = (text) => { throw new ClarusError(text, file, source, node.start); };
|
|
@@ -72,6 +73,9 @@ export function checkIcons(parsed, file, source, icon) {
|
|
|
72
73
|
}
|
|
73
74
|
else if (node.type === 'fill')
|
|
74
75
|
walk(node.children);
|
|
76
|
+
else if (node.type === 'await')
|
|
77
|
+
for (const kids of awaitLists(node))
|
|
78
|
+
walk(kids);
|
|
75
79
|
}
|
|
76
80
|
};
|
|
77
81
|
walk(parsed.nodes);
|
package/dist/compiler/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { emitClient } from './emit-client.js';
|
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
3
|
import { emitServer } from './emit-server.js';
|
|
4
4
|
import { lower } from './ir.js';
|
|
5
|
-
import { parse } from './parse.js';
|
|
5
|
+
import { awaitLists, parse } from './parse.js';
|
|
6
6
|
export { ClarusError } from './errors.js';
|
|
7
7
|
export { parse } from './parse.js';
|
|
8
8
|
import { foldClass } from './class-style.js';
|
|
@@ -27,6 +27,8 @@ export function compile(source, options) {
|
|
|
27
27
|
const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
|
|
28
28
|
css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
|
|
29
29
|
}
|
|
30
|
+
if (options.renderImports && parsed.serverScript)
|
|
31
|
+
throw new ClarusError('<script server> runs on the server only, and this component renders in the browser (a client route, or a child of an island, which re-renders it): make the route static or server, or render the component outside the island', options.file, source, parsed.serverScript.tag);
|
|
30
32
|
const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
|
|
31
33
|
warnings.push(...ir.warnings);
|
|
32
34
|
if (options.target === 'client')
|
|
@@ -55,6 +57,9 @@ function markSlotContent(nodes, cls, components) {
|
|
|
55
57
|
if (node.empty)
|
|
56
58
|
markSlotContent(node.empty, cls, components);
|
|
57
59
|
}
|
|
60
|
+
else if (node.type === 'await')
|
|
61
|
+
for (const kids of awaitLists(node))
|
|
62
|
+
markSlotContent(kids, cls, components);
|
|
58
63
|
else if (node.type === 'element' && components.has(node.tag))
|
|
59
64
|
markSlotContent(node.children, cls, components);
|
|
60
65
|
else if (node.type === 'element' && !UNMARKED.has(node.tag)) {
|
|
@@ -99,5 +104,9 @@ function markRoots(nodes, cls, components, slots = false) {
|
|
|
99
104
|
if (node.empty)
|
|
100
105
|
markRoots(node.empty, cls, components, slots);
|
|
101
106
|
}
|
|
107
|
+
else if (node.type === 'await') {
|
|
108
|
+
for (const kids of awaitLists(node))
|
|
109
|
+
markRoots(kids, cls, components, slots);
|
|
110
|
+
}
|
|
102
111
|
}
|
|
103
112
|
}
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -64,6 +64,19 @@ export type IRNode = {
|
|
|
64
64
|
nodes: IRNode[];
|
|
65
65
|
}[];
|
|
66
66
|
block: number;
|
|
67
|
+
} | {
|
|
68
|
+
kind: 'await';
|
|
69
|
+
expr: string;
|
|
70
|
+
pending: IRNode[];
|
|
71
|
+
then: {
|
|
72
|
+
name: string;
|
|
73
|
+
nodes: IRNode[];
|
|
74
|
+
} | null;
|
|
75
|
+
catch: {
|
|
76
|
+
name: string;
|
|
77
|
+
nodes: IRNode[];
|
|
78
|
+
} | null;
|
|
79
|
+
block: number;
|
|
67
80
|
} | {
|
|
68
81
|
kind: 'for';
|
|
69
82
|
item: string;
|
|
@@ -86,6 +99,12 @@ export type ComponentIR = {
|
|
|
86
99
|
imports: ImportDecl[];
|
|
87
100
|
script?: string;
|
|
88
101
|
scriptImports: string[];
|
|
102
|
+
/** <script server> (#430): its hoisted imports, its body (run at the top of render), and whether it awaits. */
|
|
103
|
+
server?: {
|
|
104
|
+
imports: string[];
|
|
105
|
+
body: string;
|
|
106
|
+
awaits: boolean;
|
|
107
|
+
};
|
|
89
108
|
dataImports: DataImport[];
|
|
90
109
|
signals: Signals;
|
|
91
110
|
stateful: boolean;
|
package/dist/compiler/ir.js
CHANGED
|
@@ -2,7 +2,7 @@ import { parseExpressionAt } from 'acorn';
|
|
|
2
2
|
import { iconElement } from './icon.js';
|
|
3
3
|
import { ClarusError } from './errors.js';
|
|
4
4
|
import { FOR_IMPLICIT, importNames } from './parse.js';
|
|
5
|
-
import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
5
|
+
import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
|
|
6
6
|
const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
|
|
7
7
|
const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
|
|
8
8
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
@@ -11,6 +11,10 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
11
11
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
12
12
|
const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
|
|
13
13
|
const warnings = [];
|
|
14
|
+
const ss = parsed.serverScript;
|
|
15
|
+
if (ss && stateful)
|
|
16
|
+
fail('<script server> runs on the server only, and this component is an island (it has a <script> or a @model input): load the data in a parent, or in a page\'s <script server>, and pass it to the island as props', ss.tag);
|
|
17
|
+
const server = ss ? serverScriptParts(ss.code, file, source, ss.start) : undefined;
|
|
14
18
|
const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
|
|
15
19
|
const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
|
|
16
20
|
const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
|
|
@@ -125,6 +129,27 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
125
129
|
out.push({ kind: 'if', branches, block });
|
|
126
130
|
return;
|
|
127
131
|
}
|
|
132
|
+
if (node.type === 'await') {
|
|
133
|
+
checkExpr(node.expr, file, source, node.exprStart);
|
|
134
|
+
const block = stateful ? blockCount++ : -1;
|
|
135
|
+
const parent = out;
|
|
136
|
+
const parentScope = scopeKey;
|
|
137
|
+
const lowerBranch = (children, k) => {
|
|
138
|
+
const list = [];
|
|
139
|
+
out = list;
|
|
140
|
+
if (stateful)
|
|
141
|
+
scopeKey = `${block}.${k}`;
|
|
142
|
+
children.forEach((child) => visit(child, rawText));
|
|
143
|
+
return list;
|
|
144
|
+
};
|
|
145
|
+
const pending = lowerBranch(node.pending, 0);
|
|
146
|
+
const then = node.then ? { name: node.then.name, nodes: lowerBranch(node.then.children, 1) } : null;
|
|
147
|
+
const caught = node.catch ? { name: node.catch.name, nodes: lowerBranch(node.catch.children, 2) } : null;
|
|
148
|
+
out = parent;
|
|
149
|
+
scopeKey = parentScope;
|
|
150
|
+
out.push({ kind: 'await', expr: node.expr, pending, then, catch: caught, block });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
128
153
|
if (node.type === 'for') {
|
|
129
154
|
checkExpr(node.list, file, source, node.listStart);
|
|
130
155
|
if (node.track !== null)
|
|
@@ -445,6 +470,7 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
445
470
|
imports: parsed.imports,
|
|
446
471
|
script: parsed.script ? split.body : undefined,
|
|
447
472
|
scriptImports: split.imports.map((imp) => imp.text),
|
|
473
|
+
...(server ? { server } : {}),
|
|
448
474
|
dataImports: parsed.dataImports,
|
|
449
475
|
signals,
|
|
450
476
|
stateful,
|
package/dist/compiler/lint.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ClarusError } from './errors.js';
|
|
2
|
-
import { importNames, parse } from './parse.js';
|
|
2
|
+
import { awaitLists, importNames, parse } from './parse.js';
|
|
3
3
|
const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
|
|
4
4
|
const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
|
|
5
5
|
function* elements(nodes) {
|
|
@@ -18,6 +18,9 @@ function* elements(nodes) {
|
|
|
18
18
|
}
|
|
19
19
|
else if (n.type === 'fill')
|
|
20
20
|
yield* elements(n.children);
|
|
21
|
+
else if (n.type === 'await')
|
|
22
|
+
for (const kids of awaitLists(n))
|
|
23
|
+
yield* elements(kids);
|
|
21
24
|
}
|
|
22
25
|
}
|
|
23
26
|
function* expressions(nodes) {
|
|
@@ -52,6 +55,11 @@ function* expressions(nodes) {
|
|
|
52
55
|
}
|
|
53
56
|
else if (n.type === 'fill')
|
|
54
57
|
yield* expressions(n.children);
|
|
58
|
+
else if (n.type === 'await') {
|
|
59
|
+
yield n.expr;
|
|
60
|
+
for (const kids of awaitLists(n))
|
|
61
|
+
yield* expressions(kids);
|
|
62
|
+
}
|
|
55
63
|
}
|
|
56
64
|
}
|
|
57
65
|
const has = (el, name) => el.attrs.some((a) => a.name === name);
|
|
@@ -66,6 +74,8 @@ function named(nodes, components) {
|
|
|
66
74
|
return n.branches.some((b) => named(b.children, components));
|
|
67
75
|
if (n.type === 'for')
|
|
68
76
|
return named(n.children, components);
|
|
77
|
+
if (n.type === 'await')
|
|
78
|
+
return awaitLists(n).some((kids) => named(kids, components));
|
|
69
79
|
if (n.type !== 'element')
|
|
70
80
|
return false;
|
|
71
81
|
if (components.has(n.tag) || n.tag === 'slot' || n.tag === 'title' || labelled(n))
|
|
@@ -135,6 +145,7 @@ export function lint(source, file, config = {}, extra = []) {
|
|
|
135
145
|
const corpus = [
|
|
136
146
|
...expressions(parsed.nodes),
|
|
137
147
|
parsed.script?.code ?? '',
|
|
148
|
+
parsed.serverScript?.code ?? '',
|
|
138
149
|
...parsed.inputs.flatMap((i) => [i.type, i.default ?? '']),
|
|
139
150
|
...parsed.types.map((t) => t.type),
|
|
140
151
|
].join('\n');
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -32,6 +32,16 @@ export type Attr = {
|
|
|
32
32
|
})[];
|
|
33
33
|
start: number;
|
|
34
34
|
};
|
|
35
|
+
/** An @await's lists of children: pending, then @then's and @catch's (those it has). */
|
|
36
|
+
export declare const awaitLists: (n: Extract<TemplateNode, {
|
|
37
|
+
type: 'await';
|
|
38
|
+
}>) => TemplateNode[][];
|
|
39
|
+
/** An @await's @then or @catch: the name it binds, and its content. */
|
|
40
|
+
export type AwaitBranch = {
|
|
41
|
+
name: string;
|
|
42
|
+
nameStart: number;
|
|
43
|
+
children: TemplateNode[];
|
|
44
|
+
};
|
|
35
45
|
/**
|
|
36
46
|
* A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
|
|
37
47
|
* @see https://clarusjs.com/reference/compiler#parse
|
|
@@ -63,6 +73,14 @@ export type TemplateNode = {
|
|
|
63
73
|
children: TemplateNode[];
|
|
64
74
|
}[];
|
|
65
75
|
start: number;
|
|
76
|
+
} | {
|
|
77
|
+
type: 'await';
|
|
78
|
+
expr: string;
|
|
79
|
+
exprStart: number;
|
|
80
|
+
pending: TemplateNode[];
|
|
81
|
+
then: AwaitBranch | null;
|
|
82
|
+
catch: AwaitBranch | null;
|
|
83
|
+
start: number;
|
|
66
84
|
} | {
|
|
67
85
|
type: 'fill';
|
|
68
86
|
name: string;
|
|
@@ -139,6 +157,12 @@ export type ParsedFile = {
|
|
|
139
157
|
code: string;
|
|
140
158
|
start: number;
|
|
141
159
|
};
|
|
160
|
+
/** <script server> (#430): runs at render on the server only. `tag` = offset of `<script`. */
|
|
161
|
+
serverScript?: {
|
|
162
|
+
code: string;
|
|
163
|
+
start: number;
|
|
164
|
+
tag: number;
|
|
165
|
+
};
|
|
142
166
|
styles: {
|
|
143
167
|
css: string;
|
|
144
168
|
mode: 'scoped' | 'global' | 'plain';
|
package/dist/compiler/parse.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClarusError } from './errors.js';
|
|
2
|
+
export const awaitLists = (n) => [n.pending, ...(n.then ? [n.then.children] : []), ...(n.catch ? [n.catch.children] : [])];
|
|
2
3
|
export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
|
|
3
4
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
4
5
|
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
@@ -285,6 +286,49 @@ export function parse(source, file) {
|
|
|
285
286
|
}
|
|
286
287
|
return fail(`unclosed ( after ${keyword}`, open);
|
|
287
288
|
}
|
|
289
|
+
function awaitBlock() {
|
|
290
|
+
const start = i;
|
|
291
|
+
i += 6;
|
|
292
|
+
const { cond: expr, condStart: exprStart } = condition('@await');
|
|
293
|
+
const open = () => {
|
|
294
|
+
while (/\s/.test(source[i] ?? ''))
|
|
295
|
+
i++;
|
|
296
|
+
if (source[i] !== '{')
|
|
297
|
+
fail('expected { to open the block', i);
|
|
298
|
+
i++;
|
|
299
|
+
};
|
|
300
|
+
open();
|
|
301
|
+
const pending = children({ tag: '@await', start, block: true });
|
|
302
|
+
let then = null;
|
|
303
|
+
let caught = null;
|
|
304
|
+
for (;;) {
|
|
305
|
+
const save = i;
|
|
306
|
+
while (/\s/.test(source[i] ?? ''))
|
|
307
|
+
i++;
|
|
308
|
+
const kw = /^@(then|catch)[\s(]/.exec(source.slice(i, i + 7))?.[1];
|
|
309
|
+
if (!kw) {
|
|
310
|
+
i = save;
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
const at = i;
|
|
314
|
+
if (kw === 'then' && caught)
|
|
315
|
+
fail('@then comes before @catch', at);
|
|
316
|
+
if ((kw === 'then' && then) || (kw === 'catch' && caught))
|
|
317
|
+
fail(`only one @${kw} per @await`, at);
|
|
318
|
+
i += kw.length + 1;
|
|
319
|
+
const { cond: name, condStart: nameStart } = condition(`@${kw}`);
|
|
320
|
+
const what = kw === 'then' ? 'value' : 'error';
|
|
321
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name))
|
|
322
|
+
fail(`@${kw} takes a name for the ${what}: @${kw} (${what})`, nameStart);
|
|
323
|
+
open();
|
|
324
|
+
const branch = { name, nameStart, children: children({ tag: `@${kw}`, start: at, block: true }) };
|
|
325
|
+
if (kw === 'then')
|
|
326
|
+
then = branch;
|
|
327
|
+
else
|
|
328
|
+
caught = branch;
|
|
329
|
+
}
|
|
330
|
+
return { type: 'await', expr, exprStart, pending, then, catch: caught, start };
|
|
331
|
+
}
|
|
288
332
|
function ifBlock() {
|
|
289
333
|
const start = i;
|
|
290
334
|
i += 3;
|
|
@@ -447,6 +491,14 @@ export function parse(source, file) {
|
|
|
447
491
|
nodes.push(ifBlock());
|
|
448
492
|
textStart = i;
|
|
449
493
|
}
|
|
494
|
+
else if (/^@await[\s(]/.test(source.slice(i, i + 7))) {
|
|
495
|
+
flush();
|
|
496
|
+
nodes.push(awaitBlock());
|
|
497
|
+
textStart = i;
|
|
498
|
+
}
|
|
499
|
+
else if (/^@(then|catch)[\s(]/.test(source.slice(i, i + 7))) {
|
|
500
|
+
fail(`${/^@\w+/.exec(source.slice(i))[0]} without @await before it`, i);
|
|
501
|
+
}
|
|
450
502
|
else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
|
|
451
503
|
flush();
|
|
452
504
|
nodes.push(forBlock());
|
|
@@ -525,6 +577,20 @@ export function parse(source, file) {
|
|
|
525
577
|
nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
|
|
526
578
|
i = selfClosing ? i : end + '</script>'.length;
|
|
527
579
|
}
|
|
580
|
+
else if (tag === 'script' && list.some((a) => a.name === 'server')) {
|
|
581
|
+
if (parent)
|
|
582
|
+
fail('<script server> must be at the top level (it runs once per render, before the template)', start);
|
|
583
|
+
if (out.serverScript)
|
|
584
|
+
fail('only one <script server> block is allowed', start);
|
|
585
|
+
const other = list.find((a) => a.name !== 'server');
|
|
586
|
+
if (other)
|
|
587
|
+
fail('<script server> takes no other attributes', other.start);
|
|
588
|
+
const end = source.indexOf('</script>', i);
|
|
589
|
+
if (end === -1)
|
|
590
|
+
fail('unclosed <script server>', start);
|
|
591
|
+
out.serverScript = { code: source.slice(i, end), start: i, tag: start };
|
|
592
|
+
i = end + '</script>'.length;
|
|
593
|
+
}
|
|
528
594
|
else if (tag === 'script') {
|
|
529
595
|
if (parent)
|
|
530
596
|
fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
|