clarusjs 0.9.0 → 0.10.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 +15 -8
- package/dist/compiler/emit-client.js +10 -5
- package/dist/compiler/errors.d.ts +14 -1
- package/dist/compiler/html-expr.d.ts +21 -0
- package/dist/compiler/html-expr.js +24 -1
- package/dist/compiler/index.d.ts +20 -2
- package/dist/compiler/index.js +2 -1
- package/dist/compiler/ir.d.ts +6 -1
- package/dist/compiler/ir.js +104 -4
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +11 -0
- package/dist/compiler/script.js +27 -0
- package/dist/fetch/index.d.ts +149 -0
- package/dist/fetch/index.js +312 -0
- package/dist/forms/index.d.ts +21 -2
- package/dist/forms/types.d.ts +20 -3
- package/dist/runtime/attrs.js +10 -2
- package/dist/runtime/dom.d.ts +15 -7
- package/dist/runtime/dom.js +33 -13
- package/dist/runtime/env.d.ts +8 -1
- package/dist/runtime/env.js +8 -1
- package/dist/runtime/html.d.ts +9 -7
- package/dist/runtime/html.js +12 -7
- package/dist/runtime/navigate.d.ts +5 -0
- package/dist/runtime/navigation.d.ts +85 -13
- package/dist/runtime/navigation.js +77 -11
- package/dist/runtime/serialize.d.ts +1 -1
- package/dist/runtime/serialize.js +1 -1
- package/dist/runtime/server.d.ts +8 -1
- package/dist/runtime/server.js +20 -4
- package/dist/runtime/signals.d.ts +97 -4
- package/dist/runtime/signals.js +88 -4
- package/dist/server/handler.d.ts +14 -1
- package/dist/server/handler.js +2 -2
- package/dist/server/head.d.ts +4 -1
- package/dist/server/manifest.d.ts +14 -1
- package/dist/server/views.d.ts +64 -6
- package/dist/server/views.js +46 -0
- package/dist/vite/build.d.ts +1 -1
- package/dist/vite/manifest.d.ts +12 -0
- package/dist/vite/plugin.d.ts +30 -2
- package/dist/vite/plugin.js +2 -1
- package/dist/vite/sitemap.d.ts +1 -0
- package/package.json +5 -1
package/dist/check/generate.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { routeFromFile } from '../server/handler.js';
|
|
2
2
|
import { ClarusError } from '../compiler/errors.js';
|
|
3
|
-
import { parse } from '../compiler/parse.js';
|
|
3
|
+
import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
|
|
4
4
|
import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
|
|
5
5
|
const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
|
|
6
6
|
const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
|
|
@@ -19,6 +19,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
19
19
|
emit('declare function derived<T>(fn: () => T): T\n');
|
|
20
20
|
emit('declare function shared<T>(store: { get(): T }): T\n');
|
|
21
21
|
emit('declare function __cl_use(value: unknown): void\n');
|
|
22
|
+
emit('declare const __cl_bool: boolean\n');
|
|
22
23
|
const text = 'string | number | boolean | null | undefined';
|
|
23
24
|
emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
|
|
24
25
|
emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
|
|
@@ -118,13 +119,16 @@ export function generateTs(source, file, options = {}) {
|
|
|
118
119
|
if (guards.length)
|
|
119
120
|
emit(`\n // @ts-ignore\n if (${guards.join(' && ')})\n `);
|
|
120
121
|
};
|
|
121
|
-
const writable = (a) => {
|
|
122
|
+
const writable = (a, value) => {
|
|
122
123
|
emit(' ;(() => { ');
|
|
123
124
|
guarded();
|
|
124
|
-
emit('(');
|
|
125
|
-
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
126
|
-
emit(') = (');
|
|
125
|
+
emit(value === undefined ? '(' : '');
|
|
127
126
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
127
|
+
emit(value === undefined ? ') = (' : ' = (');
|
|
128
|
+
if (value === undefined)
|
|
129
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
130
|
+
else
|
|
131
|
+
emit(value);
|
|
128
132
|
emit(') });\n');
|
|
129
133
|
};
|
|
130
134
|
function visit(node) {
|
|
@@ -158,11 +162,11 @@ export function generateTs(source, file, options = {}) {
|
|
|
158
162
|
copy(node.item, node.itemStart);
|
|
159
163
|
emit(' of ');
|
|
160
164
|
copy(node.list, node.listStart);
|
|
161
|
-
emit(') {\n const $index: number = 0; __cl_use($index)\n');
|
|
165
|
+
emit(') {\n const $index: number = 0, $count: number = 0, $first = __cl_bool, $last = __cl_bool, $even = __cl_bool, $odd = __cl_bool; __cl_use([$index, $count, $first, $last, $even, $odd])\n');
|
|
162
166
|
if (node.track !== null)
|
|
163
167
|
use(node.track, node.trackStart);
|
|
164
168
|
const outer = guards.splice(0);
|
|
165
|
-
guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item,
|
|
169
|
+
guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT]))));
|
|
166
170
|
node.children.forEach(visit);
|
|
167
171
|
guards.splice(0, guards.length, ...outer);
|
|
168
172
|
emit(' }\n');
|
|
@@ -205,7 +209,10 @@ export function generateTs(source, file, options = {}) {
|
|
|
205
209
|
for (const a of node.attrs) {
|
|
206
210
|
if (a.kind === 'model') {
|
|
207
211
|
use(a.expr, attrValueStart(a));
|
|
208
|
-
|
|
212
|
+
const type = node.attrs.find((x) => x.kind === 'static' && x.name === 'type');
|
|
213
|
+
const own = node.attrs.find((x) => x.kind === 'static' && x.name === 'value');
|
|
214
|
+
const radio = node.tag === 'input' && a.name === 'value' && type?.kind === 'static' && String(type.value).toLowerCase() === 'radio' && own?.kind === 'static';
|
|
215
|
+
writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
|
|
209
216
|
}
|
|
210
217
|
else if (a.kind === 'prop' && a.name === 'engine') {
|
|
211
218
|
emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { FOR_IMPLICIT } from './parse.js';
|
|
2
|
+
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
|
|
2
3
|
import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
3
4
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
5
|
export function emitClient(ir) {
|
|
@@ -21,6 +22,7 @@ export function emitClient(ir) {
|
|
|
21
22
|
all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
|
|
22
23
|
hasBlocks && 'block as __cl_block',
|
|
23
24
|
hasFors && 'forBlock as __cl_for',
|
|
25
|
+
all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
|
|
24
26
|
hasRegions && 'region as __cl_region',
|
|
25
27
|
all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
|
|
26
28
|
kinds.has('model') && 'modelInput as __cl_modelInput',
|
|
@@ -101,11 +103,14 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
101
103
|
}
|
|
102
104
|
if (n.kind === 'for' && n.block >= 0) {
|
|
103
105
|
const rowCtx = `__cl_c${depth + 1}`;
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
const
|
|
106
|
+
const names = rowNames(n, ir.events);
|
|
107
|
+
const derivedNames = names.filter((x) => x !== '$count');
|
|
108
|
+
const loop = [n.item, '$index', ...(names.length ? ['$count'] : [])];
|
|
109
|
+
const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived'])]);
|
|
110
|
+
const plain = rw.without([n.item, ...FOR_IMPLICIT]);
|
|
107
111
|
const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
|
|
108
|
-
const
|
|
112
|
+
const wire = [...rowDerived(n, ir.events), ...wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1)];
|
|
113
|
+
const row = `{\n html: (${rowParams(n)}) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${loop.join(', ')}`, wire)},\n }`;
|
|
109
114
|
const empty = n.empty
|
|
110
115
|
? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
|
|
111
116
|
: 'null';
|
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based), with the
|
|
3
|
+
* parts as `file`, `line` and `column`. `compile()` and `parse()` throw it; `compile()`'s warnings are ones too.
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* try {
|
|
7
|
+
* compile(source, { file, target: 'server' })
|
|
8
|
+
* } catch (err) {
|
|
9
|
+
* if (err instanceof ClarusError) report(err.file, err.line, err.column, err.message)
|
|
10
|
+
* else throw err
|
|
11
|
+
* }
|
|
12
|
+
* ```
|
|
13
|
+
* @see https://clarusjs.com/reference/compiler#claruserror
|
|
14
|
+
*/
|
|
2
15
|
export declare class ClarusError extends Error {
|
|
3
16
|
file: string;
|
|
4
17
|
line: number;
|
|
@@ -27,3 +27,24 @@ export declare function tagArg(n: Extract<IRNode, {
|
|
|
27
27
|
}>): string;
|
|
28
28
|
/** Every node, including those inside @if branches, @for bodies and component children. */
|
|
29
29
|
export declare function walk(nodes: IRNode[]): IRNode[];
|
|
30
|
+
/** The @for implicit names a row's template uses, besides `$index`: `$count` and those derived from it. */
|
|
31
|
+
export declare function rowNames(n: Extract<IRNode, {
|
|
32
|
+
kind: 'for';
|
|
33
|
+
}>, events?: {
|
|
34
|
+
handler: string;
|
|
35
|
+
scope?: string;
|
|
36
|
+
}[]): string[];
|
|
37
|
+
/**
|
|
38
|
+
* A row's parameters: the item and `$index`, then (when used) the list, `$count` and the names derived from them as
|
|
39
|
+
* default values, so every caller passes (item, index, list) and a plain Array.map works too.
|
|
40
|
+
*/
|
|
41
|
+
export declare function rowParams(n: Extract<IRNode, {
|
|
42
|
+
kind: 'for';
|
|
43
|
+
}>): string;
|
|
44
|
+
/** In a row's wiring: the derived names, from the row's $index and the list's $count signals. */
|
|
45
|
+
export declare function rowDerived(n: Extract<IRNode, {
|
|
46
|
+
kind: 'for';
|
|
47
|
+
}>, events?: {
|
|
48
|
+
handler: string;
|
|
49
|
+
scope?: string;
|
|
50
|
+
}[]): string[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FOR_IMPLICIT } from './parse.js';
|
|
1
2
|
import { renderName } from './shared.js';
|
|
2
3
|
import { wrapExpr } from './script.js';
|
|
3
4
|
export const asWritten = { expr: (e) => e, without: () => asWritten };
|
|
@@ -25,7 +26,7 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
25
26
|
}
|
|
26
27
|
if (n.kind === 'for') {
|
|
27
28
|
const list = wrapExpr(rw.expr(n.list));
|
|
28
|
-
const row = `(${n
|
|
29
|
+
const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
|
|
29
30
|
const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
|
|
30
31
|
if (n.block >= 0)
|
|
31
32
|
return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
|
|
@@ -81,3 +82,25 @@ export function walk(nodes) {
|
|
|
81
82
|
: []),
|
|
82
83
|
]);
|
|
83
84
|
}
|
|
85
|
+
const DERIVED = {
|
|
86
|
+
$first: '$index === 0',
|
|
87
|
+
$last: '$index === $count - 1',
|
|
88
|
+
$even: '$index % 2 === 0',
|
|
89
|
+
$odd: '$index % 2 === 1',
|
|
90
|
+
};
|
|
91
|
+
export function rowNames(n, events = []) {
|
|
92
|
+
const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
|
|
93
|
+
const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
|
|
94
|
+
const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
|
|
95
|
+
const used = Object.keys(DERIVED).filter(has);
|
|
96
|
+
return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
|
|
97
|
+
}
|
|
98
|
+
export function rowParams(n) {
|
|
99
|
+
const names = rowNames(n);
|
|
100
|
+
if (!names.length)
|
|
101
|
+
return `${n.item}, $index`;
|
|
102
|
+
return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`)].join(', ');
|
|
103
|
+
}
|
|
104
|
+
export function rowDerived(n, events = []) {
|
|
105
|
+
return rowNames(n, events).filter((x) => x !== '$count').map((x) => `const ${x} = __cl_derived(() => ${DERIVED[x].replace(/\$index/g, '$index.get()').replace(/\$count/g, '$count.get()')})`);
|
|
106
|
+
}
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -6,17 +6,24 @@ export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './pa
|
|
|
6
6
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
7
7
|
* browser (a client route's page, or a component re-rendered inside an island).
|
|
8
8
|
*/
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* `compile()`'s options: the file (for errors and the style scope), the target (`'server'` renders HTML, `'client'`
|
|
11
|
+
* attaches an island), and for the server target the island's client URL.
|
|
12
|
+
* `scope`: the id that scopes this component's styles (default: from the file name).
|
|
13
|
+
* @see https://clarusjs.com/reference/compiler#compile
|
|
14
|
+
*/
|
|
10
15
|
export type CompileOptions = {
|
|
11
16
|
file: string;
|
|
12
17
|
target: 'server' | 'client';
|
|
13
18
|
clientUrl?: string;
|
|
14
19
|
renderImports?: boolean;
|
|
15
20
|
scope?: string;
|
|
21
|
+
collapseWhitespace?: boolean;
|
|
16
22
|
};
|
|
17
23
|
/**
|
|
18
24
|
* `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
|
|
19
25
|
* <style>. `warnings`: things that compile but likely aren't meant (each a located ClarusError, not thrown).
|
|
26
|
+
* @see https://clarusjs.com/reference/compiler#compile
|
|
20
27
|
*/
|
|
21
28
|
export type CompileResult = {
|
|
22
29
|
code: string;
|
|
@@ -24,6 +31,17 @@ export type CompileResult = {
|
|
|
24
31
|
css: string;
|
|
25
32
|
warnings: ClarusError[];
|
|
26
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Compile a `.tscl` component: for the server, a module whose `render(props)` returns its HTML; for the client, an
|
|
36
|
+
* island's `attach(root, props)` (or `export {}` when it has no script). Pure: strings in, strings out. Throws a
|
|
37
|
+
* located `ClarusError` for a template it can't compile.
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { compile } from 'clarusjs/compiler'
|
|
41
|
+
* const { code, css, stateful, warnings } = compile(source, { file: 'src/components/card.tscl', target: 'server', clientUrl: '/card.js' })
|
|
42
|
+
* ```
|
|
43
|
+
* @see https://clarusjs.com/reference/compiler#compile
|
|
44
|
+
*/
|
|
27
45
|
export declare function compile(source: string, options: CompileOptions): CompileResult;
|
|
28
|
-
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
46
|
+
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. @internal */
|
|
29
47
|
export declare function scopeId(file: string): string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -23,7 +23,8 @@ export function compile(source, options) {
|
|
|
23
23
|
const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
|
|
24
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
|
-
const ir = lower(parsed, options.file, source);
|
|
26
|
+
const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
|
|
27
|
+
warnings.push(...ir.warnings);
|
|
27
28
|
if (options.target === 'client')
|
|
28
29
|
return { code: emitClient(ir), stateful: ir.stateful, css, warnings };
|
|
29
30
|
if (ir.stateful && !options.clientUrl)
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ClarusError } from './errors.ts';
|
|
1
2
|
import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
|
|
2
3
|
import { type Signals } from './script.ts';
|
|
3
4
|
export type IRNode = {
|
|
@@ -87,5 +88,9 @@ export type ComponentIR = {
|
|
|
87
88
|
stateful: boolean;
|
|
88
89
|
nodes: IRNode[];
|
|
89
90
|
events: IREvent[];
|
|
91
|
+
/** Things that compile but likely aren't meant (located, not thrown). */
|
|
92
|
+
warnings: ClarusError[];
|
|
90
93
|
};
|
|
91
|
-
export declare function lower(parsed: ParsedFile, file: string, source: string
|
|
94
|
+
export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
|
|
95
|
+
collapseWhitespace?: boolean;
|
|
96
|
+
}): ComponentIR;
|
package/dist/compiler/ir.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { parseExpressionAt } from 'acorn';
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
|
-
import { importNames } from './parse.js';
|
|
3
|
+
import { FOR_IMPLICIT, importNames } from './parse.js';
|
|
4
4
|
import { analyzeScript, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
5
5
|
const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
|
|
6
6
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
7
|
-
export function lower(parsed, file, source) {
|
|
7
|
+
export function lower(parsed, file, source, options = {}) {
|
|
8
8
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
9
9
|
const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
|
|
10
|
+
const warnings = [];
|
|
10
11
|
const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
|
|
11
12
|
const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
|
|
12
13
|
const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
|
|
@@ -63,6 +64,7 @@ export function lower(parsed, file, source) {
|
|
|
63
64
|
let eventElementCount = 0;
|
|
64
65
|
let attrElementCount = 0;
|
|
65
66
|
let formCount = 0;
|
|
67
|
+
let selectModel;
|
|
66
68
|
let engineScope = null;
|
|
67
69
|
const sameRoot = (path, at) => {
|
|
68
70
|
const root = pathSegments(path)?.root;
|
|
@@ -89,9 +91,12 @@ export function lower(parsed, file, source) {
|
|
|
89
91
|
if (input.default !== undefined)
|
|
90
92
|
checkExpr(input.default, file, source, input.start);
|
|
91
93
|
const RAW_TEXT = new Set(['textarea', 'title', 'style']);
|
|
94
|
+
const KEEP_WHITESPACE = new Set(['pre', 'textarea', 'script', 'style']);
|
|
95
|
+
let keep = 0;
|
|
96
|
+
const text = (value) => options.collapseWhitespace && !keep ? value.replace(/[ \t\n\f\r]+/g, (run) => (run.includes('\n') ? '\n' : ' ')) : value;
|
|
92
97
|
function visit(node, rawText) {
|
|
93
98
|
if (node.type === 'text')
|
|
94
|
-
return emitStatic(node.value);
|
|
99
|
+
return emitStatic(text(node.value));
|
|
95
100
|
if (node.type === 'fill')
|
|
96
101
|
return fail('@slot only works directly inside a component tag', node.start);
|
|
97
102
|
if (node.type === 'if') {
|
|
@@ -130,7 +135,11 @@ export function lower(parsed, file, source) {
|
|
|
130
135
|
children.forEach((child) => visit(child, rawText));
|
|
131
136
|
return list;
|
|
132
137
|
};
|
|
133
|
-
|
|
138
|
+
if (node.track !== null && referencesNames(node.track, new Set(FOR_IMPLICIT.filter((x) => x !== '$index'))))
|
|
139
|
+
fail('track can use the item and $index, not $count, $first, $last, $even or $odd (a key must not change when the list grows)', node.trackStart);
|
|
140
|
+
if (block >= 0 && node.track === null)
|
|
141
|
+
warnings.push(new ClarusError('@for without track: rows are matched by position, so a row\'s state moves to another item when the list changes order; add track item.id (or another unique key)', file, source, node.start));
|
|
142
|
+
const nodes = lowerInto(node.children, `f${block}`, new Set([...parentLoop, node.item, ...FOR_IMPLICIT]));
|
|
134
143
|
const empty = node.empty ? lowerInto(node.empty, `f${block}e`, parentLoop) : null;
|
|
135
144
|
out = parent;
|
|
136
145
|
scopeKey = parentScope;
|
|
@@ -234,6 +243,7 @@ export function lower(parsed, file, source) {
|
|
|
234
243
|
out.push({ kind: 'slot', name, fallback });
|
|
235
244
|
return;
|
|
236
245
|
}
|
|
246
|
+
const outerSelect = selectModel;
|
|
237
247
|
const tag = node.tag;
|
|
238
248
|
const attrs = node.attrs.flatMap((a) => {
|
|
239
249
|
if (a.kind !== 'model')
|
|
@@ -243,9 +253,68 @@ export function lower(parsed, file, source) {
|
|
|
243
253
|
fail(`[(${a.name})] on <${tag}>: an element binds two ways only with [(value)] (input, select, textarea) or [(checked)]`, a.start);
|
|
244
254
|
const type = a.name === 'checked' || tag === 'select' ? 'change' : 'input';
|
|
245
255
|
sameRoot(a.expr, a.start);
|
|
256
|
+
const typeAttr = node.attrs.find((x) => x.kind === 'static' && x.name === 'type');
|
|
257
|
+
const inputType = typeAttr?.kind === 'static' && typeof typeAttr.value === 'string' ? typeAttr.value.toLowerCase() : 'text';
|
|
258
|
+
const path = { kind: 'prop', name: 'data-cl-path', expr: modelPath(a.expr, modelNames), start: a.start };
|
|
259
|
+
if (a.name === 'value' && tag === 'input' && inputType === 'checkbox') {
|
|
260
|
+
const own = node.attrs.find((x) => x.name === 'value' && (x.kind === 'static' || x.kind === 'prop'));
|
|
261
|
+
if (!own)
|
|
262
|
+
return fail("a checkbox bound with [(value)] needs a value (value=\"…\" or [value]): it's what goes into the array; for a boolean, use [(checked)]", a.start);
|
|
263
|
+
const mine = own.kind === 'static' ? JSON.stringify(own.value === true ? '' : own.value) : `(${own.expr})`;
|
|
264
|
+
const next = `($event.target.checked ? [...((${a.expr}) ?? []), ${mine}] : ((${a.expr}) ?? []).filter((__cl_x) => __cl_x !== ${mine}))`;
|
|
265
|
+
return [
|
|
266
|
+
{ kind: 'prop', name: 'checked', expr: `((${a.expr}) ?? []).includes(${mine})`, start: a.start },
|
|
267
|
+
{ kind: 'event', name: 'change', expr: writeBack(a.expr, next, a.name, a.start), start: a.start },
|
|
268
|
+
path,
|
|
269
|
+
];
|
|
270
|
+
}
|
|
271
|
+
if (a.name === 'value' && tag === 'select') {
|
|
272
|
+
selectModel = a.expr;
|
|
273
|
+
return [
|
|
274
|
+
{ kind: 'prop', name: a.name, expr: a.expr, start: a.start },
|
|
275
|
+
{ kind: 'event', name: 'change', expr: writeBack(a.expr, '($event.target.multiple ? Array.from($event.target.selectedOptions, (__cl_o) => __cl_o.value) : $event.target.value)', a.name, a.start), start: a.start },
|
|
276
|
+
path,
|
|
277
|
+
];
|
|
278
|
+
}
|
|
279
|
+
if (a.name === 'value' && tag === 'input' && (inputType === 'number' || inputType === 'range')) {
|
|
280
|
+
return [
|
|
281
|
+
{ kind: 'prop', name: a.name, expr: a.expr, start: a.start },
|
|
282
|
+
{ kind: 'event', name: type, expr: writeBack(a.expr, '((__cl_v) => (isNaN(parseFloat(__cl_v)) ? __cl_v : parseFloat(__cl_v)))($event.target.value)', a.name, a.start), start: a.start },
|
|
283
|
+
path,
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
if (type === 'input' && !(tag === 'input' && inputType === 'radio')) {
|
|
287
|
+
const write = writeBack(a.expr, `$event.target.${a.name}`, a.name, a.start);
|
|
288
|
+
return [
|
|
289
|
+
{ kind: 'prop', name: a.name, expr: a.expr, start: a.start },
|
|
290
|
+
{ kind: 'event', name: 'input', expr: `if (!$event.isComposing) { ${write} }`, start: a.start },
|
|
291
|
+
{ kind: 'event', name: 'compositionend', expr: write, start: a.start },
|
|
292
|
+
path,
|
|
293
|
+
];
|
|
294
|
+
}
|
|
295
|
+
if (a.name === 'value' && tag === 'input' && inputType === 'radio') {
|
|
296
|
+
const own = node.attrs.find((x) => x.name === 'value' && (x.kind === 'static' || x.kind === 'prop'));
|
|
297
|
+
if (!own)
|
|
298
|
+
return fail("a radio bound with [(value)] needs a value (value=\"…\" or [value]): it's what the radio writes when picked", a.start);
|
|
299
|
+
const mine = own.kind === 'static' ? JSON.stringify(own.value === true ? '' : own.value) : `(${own.expr})`;
|
|
300
|
+
return [
|
|
301
|
+
{ kind: 'prop', name: 'checked', expr: `(${a.expr}) === ${mine}`, start: a.start },
|
|
302
|
+
{ kind: 'event', name: 'change', expr: writeBack(a.expr, mine, a.name, a.start), start: a.start },
|
|
303
|
+
{ kind: 'prop', name: 'data-cl-path', expr: modelPath(a.expr, modelNames), start: a.start },
|
|
304
|
+
];
|
|
305
|
+
}
|
|
246
306
|
const event = { kind: 'event', name: type, expr: writeBack(a.expr, `$event.target.${a.name}`, a.name, a.start), start: a.start };
|
|
247
307
|
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
308
|
});
|
|
309
|
+
const late = (x) => x.kind !== 'event' && (x.name === 'value' || x.name === 'checked');
|
|
310
|
+
attrs.sort((x, y) => Number(late(x)) - Number(late(y)));
|
|
311
|
+
if (tag === 'option' && selectModel !== undefined) {
|
|
312
|
+
const own = node.attrs.find((x) => x.name === 'value' && (x.kind === 'static' || x.kind === 'prop'));
|
|
313
|
+
if (own) {
|
|
314
|
+
const mine = own.kind === 'static' ? JSON.stringify(own.value === true ? '' : own.value) : `(${own.expr})`;
|
|
315
|
+
attrs.push({ kind: 'prop', name: 'selected', expr: `((__cl_s, __cl_v) => (Array.isArray(__cl_s) ? __cl_s.map(String).includes(String(__cl_v)) : String(__cl_s) === String(__cl_v)))(${selectModel}, ${mine})`, start: own.start });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
249
318
|
emitStatic(`<${node.tag}`);
|
|
250
319
|
const elementEvents = attrs.filter((a) => a.kind === 'event');
|
|
251
320
|
const dynamic = [];
|
|
@@ -278,6 +347,9 @@ export function lower(parsed, file, source) {
|
|
|
278
347
|
fail(`use (${a.name.slice(2).toLowerCase()}) for events, not an ${a.name} attribute`, a.start);
|
|
279
348
|
if (a.name.toLowerCase() === 'srcdoc')
|
|
280
349
|
fail('srcdoc cannot be bound; write it as a static attribute', a.start);
|
|
350
|
+
const loads = loadingUrl(node.tag, a.name, node.attrs);
|
|
351
|
+
if (loads)
|
|
352
|
+
fail(`${a.name} on <${node.tag}> ${loads}, so it can't come from data: write it as a static attribute`, a.start);
|
|
281
353
|
const exprs = a.kind === 'prop' ? [{ expr: a.expr, start: a.start }] : a.parts.filter((p) => typeof p !== 'string');
|
|
282
354
|
for (const e of exprs)
|
|
283
355
|
checkExpr(e.expr, file, source, e.start);
|
|
@@ -305,8 +377,16 @@ export function lower(parsed, file, source) {
|
|
|
305
377
|
const outer = engineScope;
|
|
306
378
|
if (engine)
|
|
307
379
|
engineScope = { root: null };
|
|
380
|
+
if (tag !== 'select' || !node.attrs.some((x) => x.kind === 'model'))
|
|
381
|
+
selectModel = tag === 'optgroup' || tag === 'option' ? selectModel : undefined;
|
|
382
|
+
const keeps = KEEP_WHITESPACE.has(node.tag);
|
|
383
|
+
if (keeps)
|
|
384
|
+
keep++;
|
|
308
385
|
node.children.forEach((child) => visit(child, RAW_TEXT.has(node.tag) ? node.tag : rawText));
|
|
386
|
+
if (keeps)
|
|
387
|
+
keep--;
|
|
309
388
|
engineScope = outer;
|
|
389
|
+
selectModel = outerSelect;
|
|
310
390
|
if (!VOID.has(node.tag))
|
|
311
391
|
emitStatic(`</${node.tag}>`);
|
|
312
392
|
}
|
|
@@ -323,6 +403,7 @@ export function lower(parsed, file, source) {
|
|
|
323
403
|
stateful,
|
|
324
404
|
nodes,
|
|
325
405
|
events,
|
|
406
|
+
warnings,
|
|
326
407
|
};
|
|
327
408
|
}
|
|
328
409
|
function pathSegments(path) {
|
|
@@ -375,3 +456,22 @@ function modelPath(path, models = new Set()) {
|
|
|
375
456
|
return '""';
|
|
376
457
|
return parts.map((p, i) => (i ? `"." + ${p}` : p)).join(' + ');
|
|
377
458
|
}
|
|
459
|
+
const LOADS = {
|
|
460
|
+
iframe: { src: 'loads a page into this one', sandbox: 'sets what the iframe may do', allow: 'sets what the iframe may do', referrerpolicy: 'sets what the iframe sends' },
|
|
461
|
+
frame: { src: 'loads a page into this one' },
|
|
462
|
+
embed: { src: 'loads a plugin or page into this one' },
|
|
463
|
+
object: { data: 'loads a plugin or page into this one', codebase: 'sets where a plugin loads from' },
|
|
464
|
+
base: { href: 'sets where every relative URL on the page points' },
|
|
465
|
+
};
|
|
466
|
+
const SAFE_RELS = new Set(['canonical', 'alternate', 'prev', 'next', 'author', 'license', 'help', 'search', 'me', 'bookmark', 'external', 'nofollow', 'noopener', 'noreferrer', 'tag', 'privacy-policy', 'terms-of-service']);
|
|
467
|
+
function loadingUrl(tag, attr, attrs) {
|
|
468
|
+
const t = tag.toLowerCase();
|
|
469
|
+
const name = attr.toLowerCase();
|
|
470
|
+
if (t === 'link' && name === 'href') {
|
|
471
|
+
const relAttrs = attrs.filter((x) => x.name.toLowerCase() === 'rel');
|
|
472
|
+
const rel = relAttrs.length === 1 ? relAttrs[0] : undefined;
|
|
473
|
+
const rels = rel?.kind === 'static' && typeof rel.value === 'string' ? rel.value.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
474
|
+
return rels.length && rels.every((r) => SAFE_RELS.has(r)) ? undefined : 'can load a stylesheet, icon or script (only rel="canonical", "alternate" and other rels that load nothing take an href from data)';
|
|
475
|
+
}
|
|
476
|
+
return LOADS[t]?.[name];
|
|
477
|
+
}
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An attribute in the syntax tree: static, an event `(x)`, a prop `[x]`, a two-way binding `[(x)]`, or a value with
|
|
3
|
+
* `{{ }}` holes. `start`: its offset in the source.
|
|
4
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
5
|
+
*/
|
|
1
6
|
export type Attr = {
|
|
2
7
|
kind: 'static';
|
|
3
8
|
name: string;
|
|
@@ -27,6 +32,10 @@ export type Attr = {
|
|
|
27
32
|
})[];
|
|
28
33
|
start: number;
|
|
29
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
|
|
37
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
38
|
+
*/
|
|
30
39
|
export type TemplateNode = {
|
|
31
40
|
type: 'element';
|
|
32
41
|
tag: string;
|
|
@@ -72,6 +81,10 @@ export type TemplateNode = {
|
|
|
72
81
|
empty: TemplateNode[] | null;
|
|
73
82
|
start: number;
|
|
74
83
|
};
|
|
84
|
+
/**
|
|
85
|
+
* An `@input` (or `@model`) declaration: its name, type text, default, and offsets.
|
|
86
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
87
|
+
*/
|
|
75
88
|
export type InputDecl = {
|
|
76
89
|
name: string;
|
|
77
90
|
type: string;
|
|
@@ -94,6 +107,10 @@ export type DataImport = {
|
|
|
94
107
|
start: number;
|
|
95
108
|
clauseStart: number;
|
|
96
109
|
};
|
|
110
|
+
/**
|
|
111
|
+
* A component `@import`: the name it's used by in the template, and where it comes from.
|
|
112
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
113
|
+
*/
|
|
97
114
|
export type ImportDecl = {
|
|
98
115
|
name: string;
|
|
99
116
|
from: string;
|
|
@@ -108,6 +125,10 @@ export type TypeDecl = {
|
|
|
108
125
|
nameStart: number;
|
|
109
126
|
typeStart: number;
|
|
110
127
|
};
|
|
128
|
+
/**
|
|
129
|
+
* A `.tscl` file's syntax tree, as `parse()` gives it: inputs, imports, the script, styles and template nodes.
|
|
130
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
131
|
+
*/
|
|
111
132
|
export type ParsedFile = {
|
|
112
133
|
inputs: InputDecl[];
|
|
113
134
|
imports: ImportDecl[];
|
|
@@ -130,6 +151,19 @@ export type ParsedFile = {
|
|
|
130
151
|
}[];
|
|
131
152
|
nodes: TemplateNode[];
|
|
132
153
|
};
|
|
154
|
+
/** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
|
|
155
|
+
export declare const FOR_IMPLICIT: string[];
|
|
156
|
+
/**
|
|
157
|
+
* Parse a `.tscl` file into its syntax tree, without compiling it: for tools (an editor, a linter, a docs
|
|
158
|
+
* generator). Throws a located `ClarusError` for a syntax error.
|
|
159
|
+
* @example
|
|
160
|
+
* ```ts
|
|
161
|
+
* import { parse } from 'clarusjs/compiler'
|
|
162
|
+
* const { inputs, imports } = parse(source, 'src/components/card.tscl')
|
|
163
|
+
* console.log(inputs.map((i) => `${i.name}: ${i.type}`))
|
|
164
|
+
* ```
|
|
165
|
+
* @see https://clarusjs.com/reference/compiler#parse
|
|
166
|
+
*/
|
|
133
167
|
export declare function parse(source: string, file: string): ParsedFile;
|
|
134
168
|
/** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
|
|
135
169
|
export declare function importNames(clause: string): string[];
|
package/dist/compiler/parse.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClarusError } from './errors.js';
|
|
2
|
+
export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
|
|
2
3
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
3
4
|
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
4
5
|
const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
@@ -359,6 +360,8 @@ export function parse(source, file) {
|
|
|
359
360
|
if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
|
|
360
361
|
fail('the @for item must be a simple name', headStart);
|
|
361
362
|
const itemStart = at + first.start + m.indices[1][0];
|
|
363
|
+
if (FOR_IMPLICIT.includes(m[1].trim()))
|
|
364
|
+
fail(`"${m[1].trim()}" is an implicit @for variable: name the item something else`, itemStart);
|
|
362
365
|
const listStart = at + first.start + m.indices[2][0];
|
|
363
366
|
let track = null;
|
|
364
367
|
let trackStart = -1;
|
|
@@ -366,6 +369,8 @@ export function parse(source, file) {
|
|
|
366
369
|
const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
|
|
367
370
|
if (!t)
|
|
368
371
|
fail(`unknown @for clause "${clause.text}"`, headStart);
|
|
372
|
+
if (track !== null)
|
|
373
|
+
fail('only one track per @for', at + clause.start);
|
|
369
374
|
track = t[1].trim();
|
|
370
375
|
trackStart = at + clause.start + t.indices[1][0];
|
|
371
376
|
}
|
|
@@ -387,6 +392,12 @@ export function parse(source, file) {
|
|
|
387
392
|
fail('expected { to open the block', i);
|
|
388
393
|
i++;
|
|
389
394
|
empty = children({ tag: '@empty', start, block: true });
|
|
395
|
+
const after = i;
|
|
396
|
+
while (/\s/.test(source[i] ?? ''))
|
|
397
|
+
i++;
|
|
398
|
+
if (/^@empty[\s{]/.test(source.slice(i, i + 7)))
|
|
399
|
+
fail('only one @empty per @for', i);
|
|
400
|
+
i = after;
|
|
390
401
|
}
|
|
391
402
|
else
|
|
392
403
|
i = save;
|
package/dist/compiler/script.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parse as acornParse, parseExpressionAt } from 'acorn';
|
|
2
|
+
import { FOR_IMPLICIT } from './parse.js';
|
|
2
3
|
import { ClarusError } from './errors.js';
|
|
3
4
|
const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
|
|
4
5
|
function isNode(v) {
|
|
@@ -244,6 +245,16 @@ export function analyzeScript(code, file, source, offset) {
|
|
|
244
245
|
}
|
|
245
246
|
return undefined;
|
|
246
247
|
});
|
|
248
|
+
for (const stmt of ast.body) {
|
|
249
|
+
const ids = stmt.type === 'VariableDeclaration' ? stmt.declarations.map((d) => d.id) : stmt.type === 'FunctionDeclaration' && stmt.id ? [stmt.id] : [];
|
|
250
|
+
for (const id of ids) {
|
|
251
|
+
if (id.type === 'Identifier' && FOR_IMPLICIT.includes(id.name))
|
|
252
|
+
throw new ClarusError(`"${id.name}" is a @for row name: name it something else`, file, source, offset + id.start);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const tla = topLevelAwait(ast);
|
|
256
|
+
if (tla)
|
|
257
|
+
throw new ClarusError("top-level await isn't supported in a <script> (rendering is synchronous): await inside a function, such as a resource's fetcher or an event handler", file, source, offset + tla.start);
|
|
247
258
|
for (const stmt of ast.body) {
|
|
248
259
|
if (stmt.type.startsWith('Export')) {
|
|
249
260
|
throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
|
|
@@ -393,3 +404,19 @@ export function referencesNames(expr, names) {
|
|
|
393
404
|
});
|
|
394
405
|
return found;
|
|
395
406
|
}
|
|
407
|
+
function topLevelAwait(node) {
|
|
408
|
+
if (/Function/.test(node.type))
|
|
409
|
+
return undefined;
|
|
410
|
+
if (node.type === 'AwaitExpression' || (node.type === 'ForOfStatement' && node.await))
|
|
411
|
+
return node;
|
|
412
|
+
for (const value of Object.values(node)) {
|
|
413
|
+
for (const child of Array.isArray(value) ? value : [value]) {
|
|
414
|
+
if (child && typeof child === 'object' && typeof child.type === 'string') {
|
|
415
|
+
const found = topLevelAwait(child);
|
|
416
|
+
if (found)
|
|
417
|
+
return found;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return undefined;
|
|
422
|
+
}
|