clarusjs 0.0.1 → 0.2.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/LICENSE +21 -0
- package/README.md +68 -4
- package/dist/compiler/emit-client.d.ts +2 -0
- package/dist/compiler/emit-client.js +34 -0
- package/dist/compiler/emit-server.d.ts +2 -0
- package/dist/compiler/emit-server.js +41 -0
- package/dist/compiler/errors.d.ts +7 -0
- package/dist/compiler/errors.js +16 -0
- package/dist/compiler/index.d.ts +11 -0
- package/dist/compiler/index.js +14 -0
- package/dist/compiler/ir.d.ts +38 -0
- package/dist/compiler/ir.js +110 -0
- package/dist/compiler/parse.d.ts +52 -0
- package/dist/compiler/parse.js +189 -0
- package/dist/compiler/script.d.ts +18 -0
- package/dist/compiler/script.js +287 -0
- package/dist/compiler/shared.d.ts +6 -0
- package/dist/compiler/shared.js +26 -0
- package/dist/runtime/dom.d.ts +14 -0
- package/dist/runtime/dom.js +70 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.js +3 -0
- package/dist/runtime/loader.d.ts +5 -0
- package/dist/runtime/loader.js +42 -0
- package/dist/runtime/server.d.ts +4 -0
- package/dist/runtime/server.js +26 -0
- package/dist/runtime/signals.d.ts +10 -0
- package/dist/runtime/signals.js +53 -0
- package/dist/server/handler.d.ts +12 -0
- package/dist/server/handler.js +51 -0
- package/dist/vite/build.d.ts +9 -0
- package/dist/vite/build.js +55 -0
- package/dist/vite/node.d.ts +3 -0
- package/dist/vite/node.js +15 -0
- package/dist/vite/plugin.d.ts +4 -0
- package/dist/vite/plugin.js +169 -0
- package/package.json +78 -8
- package/index.js +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Felix Orinda
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,7 +1,71 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo: a clear cut crystal with one bright facet">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">clarusjs</h1>
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
<p align="center"><strong>Clear, compiled views.</strong></p>
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
|
|
10
|
+
only for the parts that are interactive. Static sites, server rendering and client apps share one component model,
|
|
11
|
+
and you can always see where each line runs.
|
|
12
|
+
|
|
13
|
+
> Status: early (`0.x`). The API will change between minor versions.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add clarusjs
|
|
19
|
+
pnpm add -D vite
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Use
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// vite.config.ts
|
|
26
|
+
import { defineConfig } from 'vite'
|
|
27
|
+
import clarusjs from 'clarusjs/vite'
|
|
28
|
+
|
|
29
|
+
export default defineConfig({ plugins: [clarusjs()] })
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```clarus
|
|
33
|
+
{{-- src/components/counter.clarus --}}
|
|
34
|
+
@input start: number = 0
|
|
35
|
+
|
|
36
|
+
<script>
|
|
37
|
+
let count = state(start)
|
|
38
|
+
function add() { count++ }
|
|
39
|
+
</script>
|
|
40
|
+
|
|
41
|
+
<button (click)="add()">Clicked {{ count }} times</button>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```clarus
|
|
45
|
+
{{-- src/pages/index.clarus --}}
|
|
46
|
+
@import counter from '../components/counter.clarus'
|
|
47
|
+
|
|
48
|
+
<h1>Hello</h1>
|
|
49
|
+
<counter [start]="1" />
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `vite` serves `src/pages/**/*.clarus` as routes, rendered on the server.
|
|
53
|
+
- `vite build` writes a static site to `dist/client/`: one HTML file per page, plus JavaScript only for components
|
|
54
|
+
with a `<script>` (the counter above). The `<h1>` ships no JavaScript at all.
|
|
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
|
+
## Links
|
|
67
|
+
|
|
68
|
+
- Repository and design: [github.com/forinda/clarusjs](https://github.com/forinda/clarusjs)
|
|
69
|
+
- Contributing: [CONTRIBUTING.md](https://github.com/forinda/clarusjs/blob/main/CONTRIBUTING.md)
|
|
70
|
+
- Security: [SECURITY.md](https://github.com/forinda/clarusjs/blob/main/SECURITY.md)
|
|
71
|
+
- License: MIT
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
2
|
+
import { indentScript, inputsLine } from './shared.js';
|
|
3
|
+
export function emitClient(ir) {
|
|
4
|
+
if (!ir.stateful)
|
|
5
|
+
return 'export {}\n';
|
|
6
|
+
const kinds = new Set(ir.signals.values());
|
|
7
|
+
const reactive = ir.nodes.filter((n) => n.kind === 'hole' && n.reactive);
|
|
8
|
+
const used = [
|
|
9
|
+
kinds.has('state') && 'state',
|
|
10
|
+
kinds.has('derived') && 'derived',
|
|
11
|
+
reactive.length > 0 && 'holes as __cl_holes',
|
|
12
|
+
reactive.length > 0 && 'text as __cl_text',
|
|
13
|
+
ir.events.length > 0 && 'on as __cl_on',
|
|
14
|
+
].filter(Boolean);
|
|
15
|
+
let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
|
|
16
|
+
out += `\nexport function attach(__cl_root, __cl_props = {}) {\n`;
|
|
17
|
+
out += inputsLine(ir);
|
|
18
|
+
if (ir.script)
|
|
19
|
+
out += indentScript(rewriteClient(ir.script, ir.signals));
|
|
20
|
+
const wiring = [];
|
|
21
|
+
if (reactive.length)
|
|
22
|
+
wiring.push('const __cl_h = __cl_holes(__cl_root)');
|
|
23
|
+
for (const h of [...reactive].sort((a, b) => a.index - b.index)) {
|
|
24
|
+
wiring.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rewriteClientExpr(h.expr, ir.signals))})`);
|
|
25
|
+
}
|
|
26
|
+
for (const e of ir.events) {
|
|
27
|
+
const body = rewriteClient(e.handler, ir.signals).trim();
|
|
28
|
+
const end = body.includes('//') ? '\n ' : ' '; // a trailing line comment must not swallow the closing `})`
|
|
29
|
+
wiring.push(`__cl_on(__cl_root, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
|
|
30
|
+
}
|
|
31
|
+
if (wiring.length)
|
|
32
|
+
out += '\n' + wiring.map((l) => ` ${l}\n`).join('');
|
|
33
|
+
return out + '}\n';
|
|
34
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { rewriteServer, wrapExpr } from './script.js';
|
|
2
|
+
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
3
|
+
export function emitServer(ir, clientUrl) {
|
|
4
|
+
const runtime = ir.stateful ? 'escape as __cl_escape, island as __cl_island' : 'escape as __cl_escape';
|
|
5
|
+
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
6
|
+
for (const imp of ir.imports)
|
|
7
|
+
out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
|
|
8
|
+
const html = htmlExpr(ir.nodes);
|
|
9
|
+
const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }`.replace('{ }', '{}');
|
|
10
|
+
out += `\nexport function render(__cl_props = {}, __cl_slot) {\n`;
|
|
11
|
+
if (ir.stateful)
|
|
12
|
+
out += ` if (__cl_slot !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
13
|
+
else if (!hasSlot(ir.nodes))
|
|
14
|
+
out += ` if (__cl_slot !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <slot /> for the content passed to it`)})\n`;
|
|
15
|
+
out += inputsLine(ir);
|
|
16
|
+
if (ir.script)
|
|
17
|
+
out += indentScript(rewriteServer(ir.script));
|
|
18
|
+
out += ir.stateful
|
|
19
|
+
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html})\n`
|
|
20
|
+
: ` return ${html}\n`;
|
|
21
|
+
return out + '}\n';
|
|
22
|
+
}
|
|
23
|
+
/** One JS string expression for a list of IR nodes. Component children become the child's slot argument. */
|
|
24
|
+
function htmlExpr(nodes) {
|
|
25
|
+
const parts = nodes.map((n) => {
|
|
26
|
+
if (n.kind === 'static')
|
|
27
|
+
return JSON.stringify(n.html);
|
|
28
|
+
if (n.kind === 'slot')
|
|
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
|
+
}
|
|
39
|
+
function hasSlot(nodes) {
|
|
40
|
+
return nodes.some((n) => n.kind === 'slot' || (n.kind === 'component' && hasSlot(n.children)));
|
|
41
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
|
|
2
|
+
export declare class ClarusError extends Error {
|
|
3
|
+
file: string;
|
|
4
|
+
line: number;
|
|
5
|
+
column: number;
|
|
6
|
+
constructor(text: string, file: string, source: string, offset: number);
|
|
7
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
|
|
2
|
+
export class ClarusError extends Error {
|
|
3
|
+
file;
|
|
4
|
+
line;
|
|
5
|
+
column;
|
|
6
|
+
constructor(text, file, source, offset) {
|
|
7
|
+
const before = source.slice(0, offset);
|
|
8
|
+
const line = before.split('\n').length;
|
|
9
|
+
const column = offset - (before.lastIndexOf('\n') + 1) + 1;
|
|
10
|
+
super(`${file}:${line}:${column} ${text}`);
|
|
11
|
+
this.name = 'ClarusError';
|
|
12
|
+
this.file = file;
|
|
13
|
+
this.line = line;
|
|
14
|
+
this.column = column;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { ClarusError } from './errors.ts';
|
|
2
|
+
export type CompileOptions = {
|
|
3
|
+
file: string;
|
|
4
|
+
target: 'server' | 'client';
|
|
5
|
+
clientUrl?: string;
|
|
6
|
+
};
|
|
7
|
+
export type CompileResult = {
|
|
8
|
+
code: string;
|
|
9
|
+
stateful: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function compile(source: string, options: CompileOptions): CompileResult;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Public compiler entry. Pure: string in, string out.
|
|
2
|
+
import { emitClient } from './emit-client.js';
|
|
3
|
+
import { emitServer } from './emit-server.js';
|
|
4
|
+
import { lower } from './ir.js';
|
|
5
|
+
import { parse } from './parse.js';
|
|
6
|
+
export { ClarusError } from './errors.js';
|
|
7
|
+
export function compile(source, options) {
|
|
8
|
+
const ir = lower(parse(source, options.file), options.file, source);
|
|
9
|
+
if (options.target === 'client')
|
|
10
|
+
return { code: emitClient(ir), stateful: ir.stateful };
|
|
11
|
+
if (ir.stateful && !options.clientUrl)
|
|
12
|
+
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
13
|
+
return { code: emitServer(ir, options.clientUrl ?? ''), stateful: ir.stateful };
|
|
14
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { ImportDecl, InputDecl, ParsedFile } from './parse.ts';
|
|
2
|
+
import { type Signals } from './script.ts';
|
|
3
|
+
export type IRNode = {
|
|
4
|
+
kind: 'static';
|
|
5
|
+
html: string;
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'hole';
|
|
8
|
+
expr: string;
|
|
9
|
+
reactive: boolean;
|
|
10
|
+
index: number;
|
|
11
|
+
} | {
|
|
12
|
+
kind: 'component';
|
|
13
|
+
name: string;
|
|
14
|
+
props: {
|
|
15
|
+
name: string;
|
|
16
|
+
expr: string;
|
|
17
|
+
}[];
|
|
18
|
+
children: IRNode[];
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'slot';
|
|
21
|
+
};
|
|
22
|
+
export type IREvent = {
|
|
23
|
+
index: number;
|
|
24
|
+
type: string;
|
|
25
|
+
handler: string;
|
|
26
|
+
};
|
|
27
|
+
export type ComponentIR = {
|
|
28
|
+
file: string;
|
|
29
|
+
name: string;
|
|
30
|
+
inputs: InputDecl[];
|
|
31
|
+
imports: ImportDecl[];
|
|
32
|
+
script?: string;
|
|
33
|
+
signals: Signals;
|
|
34
|
+
stateful: boolean;
|
|
35
|
+
nodes: IRNode[];
|
|
36
|
+
events: IREvent[];
|
|
37
|
+
};
|
|
38
|
+
export declare function lower(parsed: ParsedFile, file: string, source: string): ComponentIR;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Syntax tree → IR: static HTML chunks, holes (reactive or not), child components, events. Build-time checks live here.
|
|
2
|
+
import { ClarusError } from './errors.js';
|
|
3
|
+
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames } from './script.js';
|
|
4
|
+
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
5
|
+
export function lower(parsed, file, source) {
|
|
6
|
+
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
7
|
+
const stateful = !!parsed.script;
|
|
8
|
+
const signals = parsed.script ? analyzeScript(parsed.script.code, file, source, parsed.script.start) : new Map();
|
|
9
|
+
// A hole is reactive if it reads anything the script declares: a signal directly, or a function/value that may read one.
|
|
10
|
+
// text()'s effect tracks the real dependencies, so over-marking only costs a pair of comment markers.
|
|
11
|
+
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
12
|
+
const components = new Set(parsed.imports.map((i) => i.name));
|
|
13
|
+
const nodes = [];
|
|
14
|
+
let out = nodes; // where lowering writes; switched while lowering a component's children
|
|
15
|
+
let slotCount = 0;
|
|
16
|
+
const events = [];
|
|
17
|
+
let holeCount = 0;
|
|
18
|
+
let eventElementCount = 0;
|
|
19
|
+
const emitStatic = (html) => {
|
|
20
|
+
const last = out[out.length - 1];
|
|
21
|
+
if (last?.kind === 'static')
|
|
22
|
+
last.html += html;
|
|
23
|
+
else
|
|
24
|
+
out.push({ kind: 'static', html });
|
|
25
|
+
};
|
|
26
|
+
for (const input of parsed.inputs)
|
|
27
|
+
if (input.default !== undefined)
|
|
28
|
+
checkExpr(input.default, file, source, input.start);
|
|
29
|
+
// Elements whose content is raw text: comment markers inside them would be literal text, not Comment nodes.
|
|
30
|
+
const RAW_TEXT = new Set(['textarea', 'title', 'style']);
|
|
31
|
+
function visit(node, rawText) {
|
|
32
|
+
if (node.type === 'text')
|
|
33
|
+
return emitStatic(node.value);
|
|
34
|
+
if (node.type === 'expr') {
|
|
35
|
+
checkExpr(node.expr, file, source, node.start);
|
|
36
|
+
const reactive = referencesNames(node.expr, scriptScope);
|
|
37
|
+
if (reactive && rawText)
|
|
38
|
+
fail(`reactive {{ }} inside <${rawText}> is not supported yet (it cannot hold update markers)`, node.start);
|
|
39
|
+
out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (components.has(node.tag)) {
|
|
43
|
+
if (stateful)
|
|
44
|
+
fail('components inside a stateful component are not supported yet', node.start);
|
|
45
|
+
const props = [];
|
|
46
|
+
for (const a of node.attrs) {
|
|
47
|
+
if (a.kind === 'prop') {
|
|
48
|
+
checkExpr(a.expr, file, source, a.start);
|
|
49
|
+
props.push({ name: a.name, expr: a.expr });
|
|
50
|
+
}
|
|
51
|
+
else
|
|
52
|
+
fail(`component <${node.tag}> only takes [prop] bindings`, a.start);
|
|
53
|
+
}
|
|
54
|
+
// The wrapped content is rendered here, in this component's scope, and handed to the child as its slot.
|
|
55
|
+
const children = [];
|
|
56
|
+
const parent = out;
|
|
57
|
+
out = children;
|
|
58
|
+
node.children.forEach((child) => visit(child, rawText));
|
|
59
|
+
out = parent;
|
|
60
|
+
out.push({ kind: 'component', name: node.tag, props, children });
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (node.tag === 'slot') {
|
|
64
|
+
if (stateful)
|
|
65
|
+
fail('<slot /> is only supported in components without <script>', node.start);
|
|
66
|
+
if (node.attrs.some((a) => a.name === 'name'))
|
|
67
|
+
fail('named slots are not supported yet', node.start);
|
|
68
|
+
if (node.children.length)
|
|
69
|
+
fail('<slot /> takes no children', node.start);
|
|
70
|
+
if (slotCount++)
|
|
71
|
+
fail('only one <slot /> per component', node.start);
|
|
72
|
+
out.push({ kind: 'slot' });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
let open = `<${node.tag}`;
|
|
76
|
+
const elementEvents = node.attrs.filter((a) => a.kind === 'event');
|
|
77
|
+
for (const a of node.attrs) {
|
|
78
|
+
if (a.kind === 'static')
|
|
79
|
+
open += a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`;
|
|
80
|
+
else if (a.kind === 'prop')
|
|
81
|
+
fail('[prop] bindings on HTML elements are not supported yet', a.start);
|
|
82
|
+
else if (!stateful)
|
|
83
|
+
fail('event bindings need a <script> with state; this component is static', a.start);
|
|
84
|
+
else
|
|
85
|
+
checkHandler(a.expr, file, source, a.start);
|
|
86
|
+
}
|
|
87
|
+
if (elementEvents.length) {
|
|
88
|
+
const index = eventElementCount++;
|
|
89
|
+
open += ` data-cl-e="${index}"`;
|
|
90
|
+
for (const a of elementEvents)
|
|
91
|
+
events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '' });
|
|
92
|
+
}
|
|
93
|
+
emitStatic(open + '>');
|
|
94
|
+
node.children.forEach((child) => visit(child, RAW_TEXT.has(node.tag) ? node.tag : rawText));
|
|
95
|
+
if (!VOID.has(node.tag))
|
|
96
|
+
emitStatic(`</${node.tag}>`);
|
|
97
|
+
}
|
|
98
|
+
parsed.nodes.forEach((n) => visit(n));
|
|
99
|
+
return {
|
|
100
|
+
file,
|
|
101
|
+
name: file.split('/').pop().replace(/\.clarus$/, ''),
|
|
102
|
+
inputs: parsed.inputs,
|
|
103
|
+
imports: parsed.imports,
|
|
104
|
+
script: parsed.script?.code,
|
|
105
|
+
signals,
|
|
106
|
+
stateful,
|
|
107
|
+
nodes,
|
|
108
|
+
events,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export type Attr = {
|
|
2
|
+
kind: 'static';
|
|
3
|
+
name: string;
|
|
4
|
+
value: string | true;
|
|
5
|
+
start: number;
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'event';
|
|
8
|
+
name: string;
|
|
9
|
+
expr: string;
|
|
10
|
+
start: number;
|
|
11
|
+
} | {
|
|
12
|
+
kind: 'prop';
|
|
13
|
+
name: string;
|
|
14
|
+
expr: string;
|
|
15
|
+
start: number;
|
|
16
|
+
};
|
|
17
|
+
export type TemplateNode = {
|
|
18
|
+
type: 'element';
|
|
19
|
+
tag: string;
|
|
20
|
+
attrs: Attr[];
|
|
21
|
+
children: TemplateNode[];
|
|
22
|
+
start: number;
|
|
23
|
+
} | {
|
|
24
|
+
type: 'text';
|
|
25
|
+
value: string;
|
|
26
|
+
start: number;
|
|
27
|
+
} | {
|
|
28
|
+
type: 'expr';
|
|
29
|
+
expr: string;
|
|
30
|
+
start: number;
|
|
31
|
+
};
|
|
32
|
+
export type InputDecl = {
|
|
33
|
+
name: string;
|
|
34
|
+
type: string;
|
|
35
|
+
default?: string;
|
|
36
|
+
start: number;
|
|
37
|
+
};
|
|
38
|
+
export type ImportDecl = {
|
|
39
|
+
name: string;
|
|
40
|
+
from: string;
|
|
41
|
+
start: number;
|
|
42
|
+
};
|
|
43
|
+
export type ParsedFile = {
|
|
44
|
+
inputs: InputDecl[];
|
|
45
|
+
imports: ImportDecl[];
|
|
46
|
+
script?: {
|
|
47
|
+
code: string;
|
|
48
|
+
start: number;
|
|
49
|
+
};
|
|
50
|
+
nodes: TemplateNode[];
|
|
51
|
+
};
|
|
52
|
+
export declare function parse(source: string, file: string): ParsedFile;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// .clarus source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
|
|
2
|
+
import { ClarusError } from './errors.js';
|
|
3
|
+
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
4
|
+
const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/;
|
|
5
|
+
const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
|
|
6
|
+
export function parse(source, file) {
|
|
7
|
+
const out = { inputs: [], imports: [], nodes: [] };
|
|
8
|
+
let i = 0;
|
|
9
|
+
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
10
|
+
const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
|
|
11
|
+
function directive() {
|
|
12
|
+
const end = source.indexOf('\n', i) === -1 ? source.length : source.indexOf('\n', i);
|
|
13
|
+
const line = source.slice(i, end).trim();
|
|
14
|
+
let m;
|
|
15
|
+
if ((m = line.match(INPUT_RE)))
|
|
16
|
+
out.inputs.push({ name: m[1], type: m[2].trim(), default: m[3], start: i });
|
|
17
|
+
else if ((m = line.match(IMPORT_RE)))
|
|
18
|
+
out.imports.push({ name: m[1], from: m[3], start: i });
|
|
19
|
+
else
|
|
20
|
+
fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
|
|
21
|
+
i = end;
|
|
22
|
+
}
|
|
23
|
+
function attrs() {
|
|
24
|
+
const list = [];
|
|
25
|
+
for (;;) {
|
|
26
|
+
while (/\s/.test(source[i] ?? ''))
|
|
27
|
+
i++;
|
|
28
|
+
if (i >= source.length)
|
|
29
|
+
return list;
|
|
30
|
+
if (source[i] === '>' || source.startsWith('/>', i))
|
|
31
|
+
return list;
|
|
32
|
+
const start = i;
|
|
33
|
+
const name = source.slice(i).match(/^[^\s=/>"']+/)?.[0] ?? fail('expected an attribute name', i);
|
|
34
|
+
i += name.length;
|
|
35
|
+
let value = true;
|
|
36
|
+
if (source[i] === '=') {
|
|
37
|
+
if (source[i + 1] !== '"')
|
|
38
|
+
fail('attribute values must be double-quoted', i + 1);
|
|
39
|
+
const close = source.indexOf('"', i + 2);
|
|
40
|
+
if (close === -1)
|
|
41
|
+
fail('unclosed attribute value', i + 1);
|
|
42
|
+
value = source.slice(i + 2, close);
|
|
43
|
+
i = close + 1;
|
|
44
|
+
}
|
|
45
|
+
if (name.startsWith('(') && name.endsWith(')')) {
|
|
46
|
+
if (value === true)
|
|
47
|
+
fail(`event binding ${name} needs a handler`, start);
|
|
48
|
+
list.push({ kind: 'event', name: name.slice(1, -1), expr: value.trim(), start });
|
|
49
|
+
}
|
|
50
|
+
else if (name.startsWith('[') && name.endsWith(']')) {
|
|
51
|
+
if (value === true)
|
|
52
|
+
fail(`binding ${name} needs an expression`, start);
|
|
53
|
+
list.push({ kind: 'prop', name: name.slice(1, -1), expr: value.trim(), start });
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
if (typeof value === 'string' && value.includes('{{'))
|
|
57
|
+
fail('interpolation in attributes is not supported yet; use a literal value', start);
|
|
58
|
+
list.push({ kind: 'static', name, value, start });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Find the `}}` that closes a hole, skipping strings, template literals and nested brackets.
|
|
63
|
+
// ponytail: regex literals containing quotes or braces are not recognised; tokenise with acorn if that ever bites
|
|
64
|
+
function holeEnd(from) {
|
|
65
|
+
const stack = [];
|
|
66
|
+
for (let j = from; j < source.length; j++) {
|
|
67
|
+
const c = source[j];
|
|
68
|
+
const top = stack[stack.length - 1];
|
|
69
|
+
if (top === '`') {
|
|
70
|
+
if (c === '\\')
|
|
71
|
+
j++;
|
|
72
|
+
else if (c === '`')
|
|
73
|
+
stack.pop();
|
|
74
|
+
else if (c === '$' && source[j + 1] === '{') {
|
|
75
|
+
stack.push('${');
|
|
76
|
+
j++;
|
|
77
|
+
}
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (c === '"' || c === "'") {
|
|
81
|
+
for (j++; j < source.length && source[j] !== c; j++)
|
|
82
|
+
if (source[j] === '\\')
|
|
83
|
+
j++;
|
|
84
|
+
}
|
|
85
|
+
else if (c === '`')
|
|
86
|
+
stack.push('`');
|
|
87
|
+
else if (c === '(' || c === '[' || c === '{')
|
|
88
|
+
stack.push(c);
|
|
89
|
+
else if (c === ')' || c === ']')
|
|
90
|
+
stack.pop();
|
|
91
|
+
else if (c === '}') {
|
|
92
|
+
if (!stack.length && source[j + 1] === '}')
|
|
93
|
+
return j;
|
|
94
|
+
stack.pop();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return -1;
|
|
98
|
+
}
|
|
99
|
+
// Parse children until `</parent>` (or end of input at top level).
|
|
100
|
+
function children(parent) {
|
|
101
|
+
const nodes = [];
|
|
102
|
+
let text = '';
|
|
103
|
+
let textStart = i;
|
|
104
|
+
const flush = () => {
|
|
105
|
+
if (text && (parent || text.trim()))
|
|
106
|
+
nodes.push({ type: 'text', value: text, start: textStart });
|
|
107
|
+
text = '';
|
|
108
|
+
};
|
|
109
|
+
while (i < source.length) {
|
|
110
|
+
if (source.startsWith('{{--', i)) {
|
|
111
|
+
const end = source.indexOf('--}}', i);
|
|
112
|
+
if (end === -1)
|
|
113
|
+
fail('unclosed {{-- comment', i);
|
|
114
|
+
flush();
|
|
115
|
+
i = end + 4;
|
|
116
|
+
textStart = i;
|
|
117
|
+
}
|
|
118
|
+
else if (source.startsWith('<!--', i)) {
|
|
119
|
+
const end = source.indexOf('-->', i + 4);
|
|
120
|
+
if (end === -1)
|
|
121
|
+
fail('unclosed <!-- comment', i);
|
|
122
|
+
text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
|
|
123
|
+
i = end + 3;
|
|
124
|
+
}
|
|
125
|
+
else if (!parent && source[i] === '@' && atLineStart(i)) {
|
|
126
|
+
flush();
|
|
127
|
+
directive();
|
|
128
|
+
textStart = i;
|
|
129
|
+
}
|
|
130
|
+
else if (source.startsWith('{{', i)) {
|
|
131
|
+
const end = holeEnd(i + 2);
|
|
132
|
+
if (end === -1)
|
|
133
|
+
fail('unclosed {{', i);
|
|
134
|
+
flush();
|
|
135
|
+
nodes.push({ type: 'expr', expr: source.slice(i + 2, end).trim(), start: i });
|
|
136
|
+
i = end + 2;
|
|
137
|
+
textStart = i;
|
|
138
|
+
}
|
|
139
|
+
else if (source.startsWith('</', i)) {
|
|
140
|
+
const start = i;
|
|
141
|
+
const tag = source.slice(i + 2).match(/^[\w-]+/)?.[0] ?? '';
|
|
142
|
+
if (!parent || tag !== parent.tag)
|
|
143
|
+
fail(`unexpected closing tag </${tag}>`, start);
|
|
144
|
+
const gt = source.indexOf('>', i);
|
|
145
|
+
if (gt === -1)
|
|
146
|
+
fail(`unclosed </${tag}>`, start);
|
|
147
|
+
flush();
|
|
148
|
+
i = gt + 1;
|
|
149
|
+
return nodes;
|
|
150
|
+
}
|
|
151
|
+
else if (source[i] === '<' && /[A-Za-z]/.test(source[i + 1] ?? '')) {
|
|
152
|
+
flush();
|
|
153
|
+
const start = i;
|
|
154
|
+
const tag = source.slice(i + 1).match(/^[\w-]+/)[0];
|
|
155
|
+
i += 1 + tag.length;
|
|
156
|
+
const list = attrs();
|
|
157
|
+
if (i >= source.length)
|
|
158
|
+
fail(`unclosed <${tag}>`, start);
|
|
159
|
+
const selfClosing = source.startsWith('/>', i);
|
|
160
|
+
i += selfClosing ? 2 : 1;
|
|
161
|
+
if (tag === 'script') {
|
|
162
|
+
if (parent)
|
|
163
|
+
fail('<script> must be at the top level', start);
|
|
164
|
+
if (out.script)
|
|
165
|
+
fail('only one <script> block is allowed', start);
|
|
166
|
+
const end = source.indexOf('</script>', i);
|
|
167
|
+
if (end === -1)
|
|
168
|
+
fail('unclosed <script>', start);
|
|
169
|
+
out.script = { code: source.slice(i, end), start: i };
|
|
170
|
+
i = end + '</script>'.length;
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const kids = selfClosing || VOID.has(tag) ? [] : children({ tag, start });
|
|
174
|
+
nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
|
|
175
|
+
}
|
|
176
|
+
textStart = i;
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
text += source[i++];
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (parent)
|
|
183
|
+
fail(`unclosed <${parent.tag}>`, parent.start);
|
|
184
|
+
flush();
|
|
185
|
+
return nodes;
|
|
186
|
+
}
|
|
187
|
+
out.nodes = children();
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type Signals = Map<string, 'state' | 'derived'>;
|
|
2
|
+
/** Throw a located ClarusError unless `expr` is exactly one JS expression. */
|
|
3
|
+
export declare function checkExpr(expr: string, file: string, source: string, offset: number): void;
|
|
4
|
+
/** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
|
|
5
|
+
export declare function checkHandler(code: string, file: string, source: string, offset: number): void;
|
|
6
|
+
/** [start, end] ranges of template literals in `code`, so formatting never touches their contents. */
|
|
7
|
+
export declare function templateRanges(code: string): [number, number][];
|
|
8
|
+
/** Parenthesize expressions whose meaning changes when inlined as an argument or arrow body (`a, b`, `{ … }`). */
|
|
9
|
+
export declare function wrapExpr(expr: string): string;
|
|
10
|
+
/** Names declared at the top level of <script>: variables, functions, classes. */
|
|
11
|
+
export declare function scriptNames(code: string): Set<string>;
|
|
12
|
+
export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
|
|
13
|
+
export declare function rewriteClient(code: string, signals: Signals): string;
|
|
14
|
+
export declare function rewriteClientExpr(expr: string, signals: Signals): string;
|
|
15
|
+
export declare function rewriteServer(code: string): string;
|
|
16
|
+
export declare function referencesSignal(expr: string, signals: Signals): boolean;
|
|
17
|
+
/** Does `expr` read any of `names`? */
|
|
18
|
+
export declare function referencesNames(expr: string, names: Set<string>): boolean;
|