clarusjs 0.8.0 → 0.9.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.d.ts +26 -4
- package/dist/check/generate.js +160 -21
- package/dist/cli/check.d.ts +13 -0
- package/dist/cli/check.js +76 -19
- package/dist/cli/index.js +9 -3
- package/dist/cli/mapper.d.ts +25 -0
- package/dist/cli/mapper.js +65 -0
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +21 -0
- package/dist/compiler/emit-client.js +23 -4
- package/dist/compiler/emit-server.js +3 -2
- package/dist/compiler/html-expr.js +5 -2
- package/dist/compiler/index.d.ts +8 -1
- package/dist/compiler/index.js +34 -23
- package/dist/compiler/ir.d.ts +13 -0
- package/dist/compiler/ir.js +157 -7
- package/dist/compiler/parse.d.ts +18 -1
- package/dist/compiler/parse.js +134 -6
- package/dist/compiler/script.d.ts +22 -1
- package/dist/compiler/script.js +81 -5
- package/dist/forms/index.d.ts +7 -0
- package/dist/forms/index.js +374 -0
- package/dist/forms/types.d.ts +94 -0
- package/dist/forms/types.js +1 -0
- package/dist/runtime/dom.d.ts +12 -5
- package/dist/runtime/dom.js +76 -5
- package/dist/runtime/env.d.ts +7 -0
- package/dist/runtime/env.js +7 -0
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -35
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +3 -2
- package/dist/runtime/loader.d.ts +1 -1
- package/dist/runtime/loader.js +38 -5
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +38 -40
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +4 -2
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +25 -3
- package/dist/server/handler.d.ts +8 -0
- package/dist/server/handler.js +36 -9
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +3 -2
- package/dist/vite/plugin.d.ts +6 -0
- package/dist/vite/plugin.js +82 -20
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/package.json +29 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
async function flatten(plugins) {
|
|
3
|
+
const value = await plugins;
|
|
4
|
+
if (Array.isArray(value))
|
|
5
|
+
return (await Promise.all(value.map(flatten))).flat();
|
|
6
|
+
return value && typeof value === 'object' ? [value] : [];
|
|
7
|
+
}
|
|
8
|
+
export async function loadProject(root) {
|
|
9
|
+
let vite;
|
|
10
|
+
try {
|
|
11
|
+
vite = await import('vite');
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return { sources: [], viteAliases: undefined };
|
|
15
|
+
}
|
|
16
|
+
const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, resolve(root), 'silent');
|
|
17
|
+
if (!loaded)
|
|
18
|
+
return { sources: [], viteAliases: undefined };
|
|
19
|
+
const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
|
|
20
|
+
return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias };
|
|
21
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr } from './html-expr.js';
|
|
2
|
-
import { rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
2
|
+
import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
3
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
4
|
export function emitClient(ir) {
|
|
5
5
|
if (!ir.stateful)
|
|
@@ -12,7 +12,7 @@ export function emitClient(ir) {
|
|
|
12
12
|
const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
|
|
13
13
|
const rendersHtml = hasBlocks || hasFors || hasRegions;
|
|
14
14
|
const used = [
|
|
15
|
-
kinds.has('state') && 'state',
|
|
15
|
+
(kinds.has('state') || kinds.has('input')) && 'state',
|
|
16
16
|
kinds.has('derived') && 'derived',
|
|
17
17
|
kinds.has('shared') && 'shared',
|
|
18
18
|
hasHoles && 'holes as __cl_holes',
|
|
@@ -22,6 +22,9 @@ export function emitClient(ir) {
|
|
|
22
22
|
hasBlocks && 'block as __cl_block',
|
|
23
23
|
hasFors && 'forBlock as __cl_for',
|
|
24
24
|
hasRegions && 'region as __cl_region',
|
|
25
|
+
all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
|
|
26
|
+
kinds.has('model') && 'modelInput as __cl_modelInput',
|
|
27
|
+
ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
|
|
25
28
|
rendersHtml && 'escape as __cl_escape',
|
|
26
29
|
rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
|
|
27
30
|
rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
|
|
@@ -36,15 +39,27 @@ export function emitClient(ir) {
|
|
|
36
39
|
}
|
|
37
40
|
for (const d of ir.dataImports)
|
|
38
41
|
out += `import ${d.clause} from '${d.from}'\n`;
|
|
42
|
+
if (all.some((n) => n.kind === 'connect'))
|
|
43
|
+
out += `import { connect as __cl_connect } from 'clarusjs/forms'\n`;
|
|
39
44
|
for (const line of ir.scriptImports)
|
|
40
45
|
out += `${line}\n`;
|
|
41
46
|
out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
|
|
42
|
-
out +=
|
|
47
|
+
out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
|
|
48
|
+
const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
|
|
49
|
+
const value = (i, from) => i.default === undefined ? `${from}.${i.name}` : `${from}.${i.name} === undefined ? (${rewriteClientExpr(i.default, ir.signals)}) : ${from}.${i.name}`;
|
|
50
|
+
for (const i of inputs) {
|
|
51
|
+
out += i.model
|
|
52
|
+
? ` const ${i.name} = __cl_modelInput(__cl_root, ${JSON.stringify(i.name)}, ${value(i, '__cl_props')})\n`
|
|
53
|
+
: ` const ${i.name} = state(${value(i, '__cl_props')})\n`;
|
|
54
|
+
}
|
|
55
|
+
out += inputsLine({ ...ir, inputs: ir.inputs.filter((i) => !inputs.includes(i)) });
|
|
43
56
|
if (ir.script)
|
|
44
|
-
out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true }));
|
|
57
|
+
out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true, forms: formName(ir.scriptImports) }));
|
|
45
58
|
const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
|
|
46
59
|
if (lines.length)
|
|
47
60
|
out += '\n' + lines.map((l) => ` ${l}\n`).join('');
|
|
61
|
+
if (inputs.length)
|
|
62
|
+
out += ` return (__cl_p) => __cl_batch(() => {\n${inputs.map((i) => ` ${i.name}.${i.model ? 'own' : 'set'}(${value(i, '__cl_p')})\n`).join('')} })\n`;
|
|
48
63
|
return out + '}\n';
|
|
49
64
|
}
|
|
50
65
|
function rewriter(signals) {
|
|
@@ -64,6 +79,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
64
79
|
for (const a of nodes) {
|
|
65
80
|
if (a.kind === 'attr' && a.reactive)
|
|
66
81
|
lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
|
|
82
|
+
if (a.kind === 'connect')
|
|
83
|
+
lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
|
|
67
84
|
}
|
|
68
85
|
for (const e of ir.events.filter((ev) => ev.scope === scope)) {
|
|
69
86
|
const body = rewriteClient(e.handler, signals).trim();
|
|
@@ -75,6 +92,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
75
92
|
if (n.kind === 'component' && n.region >= 0) {
|
|
76
93
|
const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
|
|
77
94
|
lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
|
|
95
|
+
for (const m of n.models ?? [])
|
|
96
|
+
lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
|
|
78
97
|
}
|
|
79
98
|
if (n.kind === 'if' && n.block >= 0) {
|
|
80
99
|
const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
|
|
@@ -20,7 +20,7 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
20
20
|
for (const line of ir.scriptImports)
|
|
21
21
|
out += `${line}\n`;
|
|
22
22
|
const html = htmlExpr(ir.nodes);
|
|
23
|
-
const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }
|
|
23
|
+
const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
|
|
24
24
|
out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
|
|
25
25
|
if (ir.stateful)
|
|
26
26
|
out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
@@ -29,10 +29,11 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
29
29
|
out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
|
|
30
30
|
}
|
|
31
31
|
out += inputsLine(ir);
|
|
32
|
+
out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
|
|
32
33
|
if (ir.script)
|
|
33
34
|
out += indentScript(rewriteServer(ir.script));
|
|
34
35
|
out += ir.stateful
|
|
35
|
-
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach)\n`
|
|
36
|
+
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach, __cl_opts?.paths)\n`
|
|
36
37
|
: ` return ${html}\n`;
|
|
37
38
|
return out + '}\n';
|
|
38
39
|
}
|
|
@@ -7,6 +7,8 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
7
7
|
return JSON.stringify(n.html);
|
|
8
8
|
if (n.kind === 'slot')
|
|
9
9
|
return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
|
|
10
|
+
if (n.kind === 'connect')
|
|
11
|
+
return '""';
|
|
10
12
|
if (n.kind === 'attr')
|
|
11
13
|
return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
|
|
12
14
|
if (n.kind === 'if') {
|
|
@@ -47,8 +49,9 @@ export function componentCall(n, rw) {
|
|
|
47
49
|
...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
|
|
48
50
|
];
|
|
49
51
|
const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
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(', ')} }`] : [])];
|
|
53
|
+
if (opts.length)
|
|
54
|
+
return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { ${opts.join(', ')} })`;
|
|
52
55
|
return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
|
|
53
56
|
}
|
|
54
57
|
export function whichExpr(n, rw) {
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { ClarusError } from './errors.ts';
|
|
1
2
|
export { ClarusError } from './errors.ts';
|
|
3
|
+
export { parse } from './parse.ts';
|
|
4
|
+
export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
|
|
2
5
|
/**
|
|
3
6
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
4
7
|
* browser (a client route's page, or a component re-rendered inside an island).
|
|
@@ -11,11 +14,15 @@ export type CompileOptions = {
|
|
|
11
14
|
renderImports?: boolean;
|
|
12
15
|
scope?: string;
|
|
13
16
|
};
|
|
14
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
|
|
19
|
+
* <style>. `warnings`: things that compile but likely aren't meant (each a located ClarusError, not thrown).
|
|
20
|
+
*/
|
|
15
21
|
export type CompileResult = {
|
|
16
22
|
code: string;
|
|
17
23
|
stateful: boolean;
|
|
18
24
|
css: string;
|
|
25
|
+
warnings: ClarusError[];
|
|
19
26
|
};
|
|
20
27
|
export declare function compile(source: string, options: CompileOptions): CompileResult;
|
|
21
28
|
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
package/dist/compiler/index.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
1
|
import { emitClient } from './emit-client.js';
|
|
2
|
+
import { ClarusError } from './errors.js';
|
|
2
3
|
import { emitServer } from './emit-server.js';
|
|
3
4
|
import { lower } from './ir.js';
|
|
4
5
|
import { parse } from './parse.js';
|
|
5
6
|
export { ClarusError } from './errors.js';
|
|
7
|
+
export { parse } from './parse.js';
|
|
6
8
|
export function compile(source, options) {
|
|
7
9
|
const parsed = parse(source, options.file);
|
|
10
|
+
const warnings = [];
|
|
11
|
+
const id = options.scope ?? scopeId(options.file);
|
|
12
|
+
markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)));
|
|
8
13
|
let css = '';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
markRoots(parsed.nodes, id, components);
|
|
13
|
-
for (const s of parsed.styles) {
|
|
14
|
-
if (s.global) {
|
|
15
|
-
css += s.css;
|
|
16
|
-
continue;
|
|
17
|
-
}
|
|
18
|
-
const head = /^(?:\s*@(?:reference|import)\b[^;{]*;)+/.exec(s.css)?.[0] ?? '';
|
|
19
|
-
const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
|
|
20
|
-
css += `${statements}@scope ([data-cl-c="${id}"]) to ([data-cl-c]) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
|
|
14
|
+
for (const s of parsed.styles) {
|
|
15
|
+
if (s.mode === 'plain') {
|
|
16
|
+
warnings.push(new ClarusError('a plain <style> is global: add `scoped` to scope it to this component (it used to be scoped by default), or `global` to keep it global without this warning', options.file, source, s.tag));
|
|
21
17
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
18
|
+
if (s.mode !== 'scoped') {
|
|
19
|
+
css += s.css;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const head = /^(?:\s*@(?:reference|import)\b[^;{]*;)+/.exec(s.css)?.[0] ?? '';
|
|
23
|
+
const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
|
|
24
|
+
css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
|
|
25
25
|
}
|
|
26
26
|
const ir = lower(parsed, options.file, source);
|
|
27
27
|
if (options.target === 'client')
|
|
28
|
-
return { code: emitClient(ir), stateful: ir.stateful, css };
|
|
28
|
+
return { code: emitClient(ir), stateful: ir.stateful, css, warnings };
|
|
29
29
|
if (ir.stateful && !options.clientUrl)
|
|
30
30
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
31
|
-
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css };
|
|
31
|
+
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css, warnings };
|
|
32
32
|
}
|
|
33
33
|
export function scopeId(file) {
|
|
34
34
|
let h = 0x811c9dc5;
|
|
@@ -37,19 +37,30 @@ export function scopeId(file) {
|
|
|
37
37
|
const name = (file.split(/[\\/]/).pop() ?? 'c').replace(/\.tscl$/, '').replace(/[^\w-]/g, '') || 'c';
|
|
38
38
|
return `${name}-${(h >>> 0).toString(36)}`;
|
|
39
39
|
}
|
|
40
|
-
|
|
40
|
+
const UNMARKED = new Set(['slot', 'cl-head', 'script', 'style', 'html', 'title', 'meta', 'link', 'base']);
|
|
41
|
+
function markRoots(nodes, cls, components) {
|
|
41
42
|
for (const node of nodes) {
|
|
42
|
-
if (node.type === 'element' && !components.has(node.tag) && node.tag
|
|
43
|
-
node.attrs.
|
|
43
|
+
if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
|
|
44
|
+
const at = node.attrs.findIndex((a) => a.name === 'class');
|
|
45
|
+
const own = node.attrs[at];
|
|
46
|
+
const passed = { expr: '__cl_class', start: node.start };
|
|
47
|
+
if (!own)
|
|
48
|
+
node.attrs.push({ kind: 'interp', name: 'class', parts: [cls, passed], start: node.start });
|
|
49
|
+
else if (own.kind === 'static')
|
|
50
|
+
node.attrs[at] = { kind: 'interp', name: 'class', parts: [own.value === true || !own.value ? cls : `${own.value} ${cls}`, passed], start: own.start };
|
|
51
|
+
else if (own.kind === 'interp')
|
|
52
|
+
own.parts.push(` ${cls}`, passed);
|
|
53
|
+
else if (own.kind === 'prop')
|
|
54
|
+
node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr, start: own.start }, ` ${cls}`, passed], start: own.start };
|
|
44
55
|
}
|
|
45
56
|
else if (node.type === 'if') {
|
|
46
57
|
for (const b of node.branches)
|
|
47
|
-
markRoots(b.children,
|
|
58
|
+
markRoots(b.children, cls, components);
|
|
48
59
|
}
|
|
49
60
|
else if (node.type === 'for') {
|
|
50
|
-
markRoots(node.children,
|
|
61
|
+
markRoots(node.children, cls, components);
|
|
51
62
|
if (node.empty)
|
|
52
|
-
markRoots(node.empty,
|
|
63
|
+
markRoots(node.empty, cls, components);
|
|
53
64
|
}
|
|
54
65
|
}
|
|
55
66
|
}
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -16,6 +16,10 @@ export type IRNode = {
|
|
|
16
16
|
name: string;
|
|
17
17
|
expr: string;
|
|
18
18
|
}[];
|
|
19
|
+
models?: {
|
|
20
|
+
name: string;
|
|
21
|
+
set: string;
|
|
22
|
+
}[];
|
|
19
23
|
children: IRNode[];
|
|
20
24
|
fills: {
|
|
21
25
|
name: string;
|
|
@@ -23,6 +27,11 @@ export type IRNode = {
|
|
|
23
27
|
}[];
|
|
24
28
|
region: number;
|
|
25
29
|
attach?: string;
|
|
30
|
+
paths?: {
|
|
31
|
+
name: string;
|
|
32
|
+
expr: string;
|
|
33
|
+
}[];
|
|
34
|
+
class?: string;
|
|
26
35
|
} | {
|
|
27
36
|
kind: 'slot';
|
|
28
37
|
name: string;
|
|
@@ -40,6 +49,10 @@ export type IRNode = {
|
|
|
40
49
|
reactive: boolean;
|
|
41
50
|
index: number;
|
|
42
51
|
tag: string;
|
|
52
|
+
} | {
|
|
53
|
+
kind: 'connect';
|
|
54
|
+
expr: string;
|
|
55
|
+
index: number;
|
|
43
56
|
} | {
|
|
44
57
|
kind: 'if';
|
|
45
58
|
branches: {
|
package/dist/compiler/ir.js
CHANGED
|
@@ -1,14 +1,53 @@
|
|
|
1
|
+
import { parseExpressionAt } from 'acorn';
|
|
1
2
|
import { ClarusError } from './errors.js';
|
|
2
3
|
import { importNames } from './parse.js';
|
|
3
|
-
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
4
|
+
import { analyzeScript, writesTo, 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']);
|
|
6
7
|
export function lower(parsed, file, source) {
|
|
7
8
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
8
|
-
const stateful = !!parsed.script;
|
|
9
|
+
const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
|
|
10
|
+
const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
|
|
9
11
|
const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
|
|
10
12
|
const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
|
|
11
13
|
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
14
|
+
const inputNames = new Set(stateful ? parsed.inputs.filter((i) => !i.model).map((i) => i.name).filter((name) => !signals.has(name)) : []);
|
|
15
|
+
for (const name of inputNames) {
|
|
16
|
+
signals.set(name, 'input');
|
|
17
|
+
scriptScope.add(name);
|
|
18
|
+
}
|
|
19
|
+
for (const i of stateful ? parsed.inputs.filter((x) => x.model && !signals.has(x.name)) : []) {
|
|
20
|
+
signals.set(i.name, 'model');
|
|
21
|
+
scriptScope.add(i.name);
|
|
22
|
+
}
|
|
23
|
+
const writeBack = (path, value, name, at) => {
|
|
24
|
+
if (!stateful)
|
|
25
|
+
fail(`[(${name})] needs a <script> with state to write back to`, at);
|
|
26
|
+
const invalid = () => fail(`[(${name})] needs a variable or a property path (form.name, rows[$index].name) to write back to, not "${path}"`, at);
|
|
27
|
+
const parsed = pathSegments(path) ?? invalid();
|
|
28
|
+
const { root, segments } = parsed;
|
|
29
|
+
if (loopNames.has(root))
|
|
30
|
+
fail(`[(${name})] can't write back to the row variable "${root}": bind the list by index, like [(${name})]="rows[$index].${path.slice(root.length).replace(/^\./, '') || 'name'}"`, at);
|
|
31
|
+
const bases = [root];
|
|
32
|
+
for (const seg of segments)
|
|
33
|
+
bases.push('key' in seg ? `${bases.at(-1)}.${seg.key}` : `${bases.at(-1)}[${seg.index}]`);
|
|
34
|
+
let next = value;
|
|
35
|
+
for (let k = segments.length - 1; k >= 0; k--) {
|
|
36
|
+
const seg = segments[k];
|
|
37
|
+
const parent = bases[k];
|
|
38
|
+
next = 'key' in seg
|
|
39
|
+
? `{ ...${parent}, ${seg.key}: ${next} }`
|
|
40
|
+
: `(Array.isArray(${parent}) ? ${parent}.map((__cl_x, __cl_i) => __cl_i === (${seg.index}) ? ${next} : __cl_x) : { ...${parent}, [${seg.index}]: ${next} })`;
|
|
41
|
+
}
|
|
42
|
+
const statement = `${root} = ${next}`;
|
|
43
|
+
for (const w of writesTo(statement, inputNames))
|
|
44
|
+
readOnly(w.name, at);
|
|
45
|
+
return statement;
|
|
46
|
+
};
|
|
47
|
+
const readOnly = (name, at) => fail(`@input ${name} is read-only: inputs belong to the parent. Copy it to change it here: let local = state(${name})`, at);
|
|
48
|
+
if (parsed.script && inputNames.size)
|
|
49
|
+
for (const w of writesTo(parsed.script.code, inputNames))
|
|
50
|
+
readOnly(w.name, parsed.script.start + w.start);
|
|
12
51
|
for (const d of parsed.dataImports) {
|
|
13
52
|
if (stateful && d.from.startsWith('node:'))
|
|
14
53
|
fail(`\`${d.from}\` can't be imported in an island: its imports are bundled for the browser`, d.start);
|
|
@@ -23,6 +62,17 @@ export function lower(parsed, file, source) {
|
|
|
23
62
|
let holeCount = 0;
|
|
24
63
|
let eventElementCount = 0;
|
|
25
64
|
let attrElementCount = 0;
|
|
65
|
+
let formCount = 0;
|
|
66
|
+
let engineScope = null;
|
|
67
|
+
const sameRoot = (path, at) => {
|
|
68
|
+
const root = pathSegments(path)?.root;
|
|
69
|
+
if (!engineScope || !root)
|
|
70
|
+
return;
|
|
71
|
+
if (engineScope.root === null)
|
|
72
|
+
engineScope.root = root;
|
|
73
|
+
else if (engineScope.root !== root)
|
|
74
|
+
fail(`fields under [engine] bind one object: found ${engineScope.root} and ${root}`, at);
|
|
75
|
+
};
|
|
26
76
|
let blockCount = 0;
|
|
27
77
|
let forCount = 0;
|
|
28
78
|
let regionCount = 0;
|
|
@@ -106,23 +156,41 @@ export function lower(parsed, file, source) {
|
|
|
106
156
|
}
|
|
107
157
|
if (components.has(node.tag)) {
|
|
108
158
|
const props = [];
|
|
159
|
+
const models = [];
|
|
109
160
|
let attach;
|
|
161
|
+
let cls;
|
|
162
|
+
const paths = [];
|
|
110
163
|
for (const a of node.attrs) {
|
|
164
|
+
if (a.name === 'class') {
|
|
165
|
+
if (a.kind !== 'static' || typeof a.value !== 'string')
|
|
166
|
+
fail('a component takes a static class="…" only ([class] and {{ }} in it aren\'t supported on a component yet)', a.start);
|
|
167
|
+
else
|
|
168
|
+
cls = a.value;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
111
171
|
if (a.kind === 'prop') {
|
|
112
172
|
checkExpr(a.expr, file, source, a.start);
|
|
113
173
|
props.push({ name: a.name, expr: a.expr });
|
|
114
174
|
}
|
|
175
|
+
else if (a.kind === 'model') {
|
|
176
|
+
const set = writeBack(a.expr, '__cl_v', a.name, a.start);
|
|
177
|
+
checkExpr(a.expr, file, source, a.start);
|
|
178
|
+
props.push({ name: a.name, expr: a.expr });
|
|
179
|
+
sameRoot(a.expr, a.start);
|
|
180
|
+
paths.push({ name: a.name, expr: modelPath(a.expr, modelNames) });
|
|
181
|
+
models.push({ name: a.name, set });
|
|
182
|
+
}
|
|
115
183
|
else if (a.kind === 'static' && a.name === 'attach') {
|
|
116
184
|
if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
|
|
117
185
|
fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
|
|
118
186
|
attach = a.value;
|
|
119
187
|
}
|
|
120
188
|
else
|
|
121
|
-
fail(`component <${node.tag}> only takes [prop] bindings and attach="…"`, a.start);
|
|
189
|
+
fail(`component <${node.tag}> only takes [prop] and [(prop)] bindings and attach="…"`, a.start);
|
|
122
190
|
}
|
|
123
191
|
const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
|
|
124
192
|
const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
|
|
125
|
-
const region = stateful && (hasContent || readsState) ? regionCount++ : -1;
|
|
193
|
+
const region = stateful && (hasContent || readsState || models.length > 0) ? regionCount++ : -1;
|
|
126
194
|
const parentScope = scopeKey;
|
|
127
195
|
if (region >= 0)
|
|
128
196
|
scopeKey = `c${region}`;
|
|
@@ -145,7 +213,7 @@ export function lower(parsed, file, source) {
|
|
|
145
213
|
const rest = node.children.filter((c) => c.type !== 'fill');
|
|
146
214
|
const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
|
|
147
215
|
scopeKey = parentScope;
|
|
148
|
-
out.push({ kind: 'component', name: node.tag, props, children, fills, region, ...(attach ? { attach } : {}) });
|
|
216
|
+
out.push({ kind: 'component', name: node.tag, props, ...(models.length ? { models } : {}), children, fills, region, ...(attach ? { attach } : {}), ...(paths.length ? { paths } : {}), ...(cls ? { class: cls } : {}) });
|
|
149
217
|
return;
|
|
150
218
|
}
|
|
151
219
|
if (node.tag === 'slot') {
|
|
@@ -166,16 +234,44 @@ export function lower(parsed, file, source) {
|
|
|
166
234
|
out.push({ kind: 'slot', name, fallback });
|
|
167
235
|
return;
|
|
168
236
|
}
|
|
237
|
+
const tag = node.tag;
|
|
238
|
+
const attrs = node.attrs.flatMap((a) => {
|
|
239
|
+
if (a.kind !== 'model')
|
|
240
|
+
return [a];
|
|
241
|
+
const bindable = (a.name === 'value' && ['input', 'select', 'textarea'].includes(tag)) || (a.name === 'checked' && tag === 'input');
|
|
242
|
+
if (!bindable)
|
|
243
|
+
fail(`[(${a.name})] on <${tag}>: an element binds two ways only with [(value)] (input, select, textarea) or [(checked)]`, a.start);
|
|
244
|
+
const type = a.name === 'checked' || tag === 'select' ? 'change' : 'input';
|
|
245
|
+
sameRoot(a.expr, a.start);
|
|
246
|
+
const event = { kind: 'event', name: type, expr: writeBack(a.expr, `$event.target.${a.name}`, a.name, a.start), start: a.start };
|
|
247
|
+
return [{ kind: 'prop', name: a.name, expr: a.expr, start: a.start }, event, { kind: 'prop', name: 'data-cl-path', expr: modelPath(a.expr, modelNames), start: a.start }];
|
|
248
|
+
});
|
|
169
249
|
emitStatic(`<${node.tag}`);
|
|
170
|
-
const elementEvents =
|
|
250
|
+
const elementEvents = attrs.filter((a) => a.kind === 'event');
|
|
171
251
|
const dynamic = [];
|
|
172
|
-
|
|
252
|
+
let engine = false;
|
|
253
|
+
for (const a of attrs) {
|
|
173
254
|
if (a.kind === 'static')
|
|
174
255
|
emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`);
|
|
175
256
|
else if (a.kind === 'event') {
|
|
176
257
|
if (!stateful)
|
|
177
258
|
fail('event bindings need a <script> with state; this component is static', a.start);
|
|
178
259
|
checkHandler(a.expr, file, source, a.start);
|
|
260
|
+
if (inputNames.size) {
|
|
261
|
+
const found = source.indexOf(a.expr, a.start);
|
|
262
|
+
const exprStart = found === -1 ? a.start : found;
|
|
263
|
+
for (const w of writesTo(a.expr, inputNames))
|
|
264
|
+
readOnly(w.name, exprStart + w.start);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
else if (a.kind === 'prop' && a.name === 'engine') {
|
|
268
|
+
if (!stateful)
|
|
269
|
+
fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
|
|
270
|
+
checkExpr(a.expr, file, source, a.start);
|
|
271
|
+
const index = formCount++;
|
|
272
|
+
emitStatic(` data-cl-form="${index}"`);
|
|
273
|
+
out.push({ kind: 'connect', expr: a.expr, index });
|
|
274
|
+
engine = true;
|
|
179
275
|
}
|
|
180
276
|
else {
|
|
181
277
|
if (/^on/i.test(a.name))
|
|
@@ -206,7 +302,11 @@ export function lower(parsed, file, source) {
|
|
|
206
302
|
events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
|
|
207
303
|
}
|
|
208
304
|
emitStatic('>');
|
|
305
|
+
const outer = engineScope;
|
|
306
|
+
if (engine)
|
|
307
|
+
engineScope = { root: null };
|
|
209
308
|
node.children.forEach((child) => visit(child, RAW_TEXT.has(node.tag) ? node.tag : rawText));
|
|
309
|
+
engineScope = outer;
|
|
210
310
|
if (!VOID.has(node.tag))
|
|
211
311
|
emitStatic(`</${node.tag}>`);
|
|
212
312
|
}
|
|
@@ -225,3 +325,53 @@ export function lower(parsed, file, source) {
|
|
|
225
325
|
events,
|
|
226
326
|
};
|
|
227
327
|
}
|
|
328
|
+
function pathSegments(path) {
|
|
329
|
+
const root = /^[A-Za-z_$][\w$]*/.exec(path)?.[0];
|
|
330
|
+
if (!root)
|
|
331
|
+
return null;
|
|
332
|
+
const segments = [];
|
|
333
|
+
for (let rest = path.slice(root.length); rest;) {
|
|
334
|
+
const key = /^\.([A-Za-z_$][\w$]*)/.exec(rest);
|
|
335
|
+
if (key) {
|
|
336
|
+
segments.push({ key: key[1] });
|
|
337
|
+
rest = rest.slice(key[0].length);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (rest[0] !== '[')
|
|
341
|
+
return null;
|
|
342
|
+
let depth = 0;
|
|
343
|
+
let close = 0;
|
|
344
|
+
for (; close < rest.length; close++) {
|
|
345
|
+
if (rest[close] === '[')
|
|
346
|
+
depth++;
|
|
347
|
+
else if (rest[close] === ']' && --depth === 0)
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
const index = rest.slice(1, close).trim();
|
|
351
|
+
if (close >= rest.length || !index)
|
|
352
|
+
return null;
|
|
353
|
+
segments.push({ index });
|
|
354
|
+
rest = rest.slice(close + 1);
|
|
355
|
+
}
|
|
356
|
+
return { root, segments };
|
|
357
|
+
}
|
|
358
|
+
function modelPath(path, models = new Set()) {
|
|
359
|
+
const parsed = pathSegments(path);
|
|
360
|
+
const parts = (parsed?.segments ?? []).map((seg) => {
|
|
361
|
+
if ('key' in seg)
|
|
362
|
+
return JSON.stringify(seg.key);
|
|
363
|
+
let literal;
|
|
364
|
+
try {
|
|
365
|
+
const node = parseExpressionAt(seg.index, 0, { ecmaVersion: 'latest' });
|
|
366
|
+
if (node.type === 'Literal' && node.end === seg.index.length && (typeof node.value === 'string' || typeof node.value === 'number'))
|
|
367
|
+
literal = node.value;
|
|
368
|
+
}
|
|
369
|
+
catch { }
|
|
370
|
+
return literal !== undefined ? JSON.stringify(String(literal)) : `(${seg.index})`;
|
|
371
|
+
});
|
|
372
|
+
if (parsed && models.has(parsed.root))
|
|
373
|
+
parts.unshift(JSON.stringify(`@${parsed.root}`));
|
|
374
|
+
if (!parts.length)
|
|
375
|
+
return '""';
|
|
376
|
+
return parts.map((p, i) => (i ? `"." + ${p}` : p)).join(' + ');
|
|
377
|
+
}
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -13,6 +13,11 @@ export type Attr = {
|
|
|
13
13
|
name: string;
|
|
14
14
|
expr: string;
|
|
15
15
|
start: number;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'model';
|
|
18
|
+
name: string;
|
|
19
|
+
expr: string;
|
|
20
|
+
start: number;
|
|
16
21
|
} | {
|
|
17
22
|
kind: 'interp';
|
|
18
23
|
name: string;
|
|
@@ -75,6 +80,7 @@ export type InputDecl = {
|
|
|
75
80
|
nameStart: number;
|
|
76
81
|
typeStart: number;
|
|
77
82
|
defaultStart?: number;
|
|
83
|
+
model?: true;
|
|
78
84
|
};
|
|
79
85
|
export type TypeImport = {
|
|
80
86
|
clause: string;
|
|
@@ -93,10 +99,20 @@ export type ImportDecl = {
|
|
|
93
99
|
from: string;
|
|
94
100
|
start: number;
|
|
95
101
|
};
|
|
102
|
+
export type TypeDecl = {
|
|
103
|
+
kind: 'type' | 'interface';
|
|
104
|
+
name: string;
|
|
105
|
+
params?: string;
|
|
106
|
+
type: string;
|
|
107
|
+
start: number;
|
|
108
|
+
nameStart: number;
|
|
109
|
+
typeStart: number;
|
|
110
|
+
};
|
|
96
111
|
export type ParsedFile = {
|
|
97
112
|
inputs: InputDecl[];
|
|
98
113
|
imports: ImportDecl[];
|
|
99
114
|
typeImports: TypeImport[];
|
|
115
|
+
types: TypeDecl[];
|
|
100
116
|
dataImports: DataImport[];
|
|
101
117
|
script?: {
|
|
102
118
|
code: string;
|
|
@@ -104,8 +120,9 @@ export type ParsedFile = {
|
|
|
104
120
|
};
|
|
105
121
|
styles: {
|
|
106
122
|
css: string;
|
|
107
|
-
|
|
123
|
+
mode: 'scoped' | 'global' | 'plain';
|
|
108
124
|
start: number;
|
|
125
|
+
tag: number;
|
|
109
126
|
}[];
|
|
110
127
|
cssImports: {
|
|
111
128
|
from: string;
|