clarusjs 0.9.0 → 0.11.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/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +19 -7
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- 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 +23 -2
- package/dist/compiler/index.js +5 -3
- package/dist/compiler/ir.d.ts +6 -1
- package/dist/compiler/ir.js +104 -4
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- 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/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- 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 +18 -1
- package/dist/runtime/server.js +42 -4
- package/dist/runtime/signals.d.ts +97 -4
- package/dist/runtime/signals.js +88 -4
- package/dist/server/handler.d.ts +115 -5
- package/dist/server/handler.js +233 -10
- 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/aliases.js +3 -3
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +15 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +47 -3
- package/dist/vite/plugin.js +197 -106
- package/dist/vite/sitemap.d.ts +1 -0
- package/package.json +5 -1
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
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type ParsedFile, type TemplateNode } from './parse.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The built-in rules' names.
|
|
4
|
+
* @see https://clarusjs.com/guide/lint#rules
|
|
5
|
+
*/
|
|
6
|
+
export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name';
|
|
7
|
+
/**
|
|
8
|
+
* Each rule's level, built-in or a project's, keyed by rule name.
|
|
9
|
+
* @see https://clarusjs.com/guide/lint#warnings-and-errors
|
|
10
|
+
*/
|
|
11
|
+
export type LintConfig = Partial<Record<LintRule, LintLevel>> & Record<string, LintLevel>;
|
|
12
|
+
/**
|
|
13
|
+
* A rule's level: 'warn' (the default), 'error', or 'off'.
|
|
14
|
+
* @see https://clarusjs.com/guide/lint#warnings-and-errors
|
|
15
|
+
*/
|
|
16
|
+
export type LintLevel = 'off' | 'warn' | 'error';
|
|
17
|
+
/**
|
|
18
|
+
* A finding, at its 1-based line and column (`start`: its offset in the source).
|
|
19
|
+
* @see https://clarusjs.com/reference/compiler#lint
|
|
20
|
+
*/
|
|
21
|
+
export type LintMessage = {
|
|
22
|
+
rule: string;
|
|
23
|
+
severity: 'warning' | 'error';
|
|
24
|
+
message: string;
|
|
25
|
+
file: string;
|
|
26
|
+
line: number;
|
|
27
|
+
column: number;
|
|
28
|
+
start: number;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* A template element, as `parse` returns it.
|
|
32
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
33
|
+
*/
|
|
34
|
+
export type LintElement = Extract<TemplateNode, {
|
|
35
|
+
type: 'element';
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* What a rule's check() gets: the file, its syntax tree, every element in it, and report().
|
|
39
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
40
|
+
*/
|
|
41
|
+
export type LintContext = {
|
|
42
|
+
file: string;
|
|
43
|
+
source: string;
|
|
44
|
+
parsed: ParsedFile;
|
|
45
|
+
/** Every element, in branches, rows, empty content and slot fills too, in source order. */
|
|
46
|
+
elements: LintElement[];
|
|
47
|
+
/** The names of the components this file imports (their tags). */
|
|
48
|
+
components: Set<string>;
|
|
49
|
+
/** Whether the template, the script, or an input's type or default reads `name`. */
|
|
50
|
+
reads(name: string): boolean;
|
|
51
|
+
/** A finding at `start`, an offset in the source (an element's, an attribute's, an @input's). */
|
|
52
|
+
report(start: number, message: string): void;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* A lint rule: a name (used in levels and ignore comments) and a check over one file.
|
|
56
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
57
|
+
*/
|
|
58
|
+
export type LintRuleDef = {
|
|
59
|
+
name: string;
|
|
60
|
+
check(context: LintContext): void;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* The built-in rules, each written as a project's own would be.
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { lintRules } from 'clarusjs/compiler'
|
|
67
|
+
* console.log(lintRules.map((r) => r.name)) // ['unused-input', 'unused-import', …]
|
|
68
|
+
* ```
|
|
69
|
+
* @see https://clarusjs.com/guide/lint#rules
|
|
70
|
+
*/
|
|
71
|
+
export declare const lintRules: LintRuleDef[];
|
|
72
|
+
/**
|
|
73
|
+
* Lint a `.tscl` file's template with the built-in rules and `extra` ones, at the levels in `config`. Throws a
|
|
74
|
+
* located `ClarusError` for a syntax error, as `parse` does.
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* import { lint } from 'clarusjs/compiler'
|
|
78
|
+
* for (const m of lint(source, 'src/components/card.tscl')) console.log(`${m.line}:${m.column} ${m.rule}: ${m.message}`)
|
|
79
|
+
* ```
|
|
80
|
+
* @see https://clarusjs.com/reference/compiler#lint
|
|
81
|
+
*/
|
|
82
|
+
export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[]): LintMessage[];
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { ClarusError } from './errors.js';
|
|
2
|
+
import { importNames, parse } from './parse.js';
|
|
3
|
+
const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
|
|
4
|
+
const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
|
|
5
|
+
function* elements(nodes) {
|
|
6
|
+
for (const n of nodes) {
|
|
7
|
+
if (n.type === 'element') {
|
|
8
|
+
yield n;
|
|
9
|
+
yield* elements(n.children);
|
|
10
|
+
}
|
|
11
|
+
else if (n.type === 'if')
|
|
12
|
+
for (const b of n.branches)
|
|
13
|
+
yield* elements(b.children);
|
|
14
|
+
else if (n.type === 'for') {
|
|
15
|
+
yield* elements(n.children);
|
|
16
|
+
if (n.empty)
|
|
17
|
+
yield* elements(n.empty);
|
|
18
|
+
}
|
|
19
|
+
else if (n.type === 'fill')
|
|
20
|
+
yield* elements(n.children);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function* expressions(nodes) {
|
|
24
|
+
for (const n of nodes) {
|
|
25
|
+
if (n.type === 'expr')
|
|
26
|
+
yield n.expr;
|
|
27
|
+
else if (n.type === 'element') {
|
|
28
|
+
for (const a of n.attrs) {
|
|
29
|
+
if (a.kind === 'interp')
|
|
30
|
+
for (const p of a.parts) {
|
|
31
|
+
if (typeof p !== 'string')
|
|
32
|
+
yield p.expr;
|
|
33
|
+
}
|
|
34
|
+
else if (a.kind !== 'static')
|
|
35
|
+
yield a.expr;
|
|
36
|
+
}
|
|
37
|
+
yield* expressions(n.children);
|
|
38
|
+
}
|
|
39
|
+
else if (n.type === 'if')
|
|
40
|
+
for (const b of n.branches) {
|
|
41
|
+
if (b.cond)
|
|
42
|
+
yield b.cond;
|
|
43
|
+
yield* expressions(b.children);
|
|
44
|
+
}
|
|
45
|
+
else if (n.type === 'for') {
|
|
46
|
+
yield n.list;
|
|
47
|
+
if (n.track)
|
|
48
|
+
yield n.track;
|
|
49
|
+
yield* expressions(n.children);
|
|
50
|
+
if (n.empty)
|
|
51
|
+
yield* expressions(n.empty);
|
|
52
|
+
}
|
|
53
|
+
else if (n.type === 'fill')
|
|
54
|
+
yield* expressions(n.children);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const has = (el, name) => el.attrs.some((a) => a.name === name);
|
|
58
|
+
const labelled = (el) => has(el, 'aria-label') || has(el, 'aria-labelledby') || has(el, 'title');
|
|
59
|
+
function named(nodes, components) {
|
|
60
|
+
return nodes.some((n) => {
|
|
61
|
+
if (n.type === 'text')
|
|
62
|
+
return n.value.trim() !== '';
|
|
63
|
+
if (n.type === 'expr' || n.type === 'raw')
|
|
64
|
+
return true;
|
|
65
|
+
if (n.type === 'if')
|
|
66
|
+
return n.branches.some((b) => named(b.children, components));
|
|
67
|
+
if (n.type === 'for')
|
|
68
|
+
return named(n.children, components);
|
|
69
|
+
if (n.type !== 'element')
|
|
70
|
+
return false;
|
|
71
|
+
if (components.has(n.tag) || n.tag === 'slot' || n.tag === 'title' || labelled(n))
|
|
72
|
+
return true;
|
|
73
|
+
if (n.tag === 'img')
|
|
74
|
+
return n.attrs.some((a) => a.name === 'alt' && !(a.kind === 'static' && (a.value === true || a.value.trim() === '')));
|
|
75
|
+
return named(n.children, components);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export const lintRules = [
|
|
79
|
+
{
|
|
80
|
+
name: 'unused-input',
|
|
81
|
+
check({ parsed, reads, report }) {
|
|
82
|
+
for (const i of parsed.inputs)
|
|
83
|
+
if (!reads(i.name))
|
|
84
|
+
report(i.start, `@${i.model ? 'model' : 'input'} ${i.name} is never used`);
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
name: 'unused-import',
|
|
89
|
+
check({ parsed, elements, reads, report }) {
|
|
90
|
+
const tags = new Set(elements.map((e) => e.tag));
|
|
91
|
+
for (const i of parsed.imports)
|
|
92
|
+
if (!tags.has(i.name) && !reads(i.name))
|
|
93
|
+
report(i.start, `'${i.name}' is imported but never used as <${i.name}>`);
|
|
94
|
+
for (const d of parsed.dataImports) {
|
|
95
|
+
const unused = importNames(d.clause).filter((name) => !reads(name));
|
|
96
|
+
if (unused.length)
|
|
97
|
+
report(d.start, `${unused.map((n) => `'${n}'`).join(', ')} ${unused.length === 1 ? 'is' : 'are'} imported but never used`);
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: 'img-alt',
|
|
103
|
+
check({ elements, report }) {
|
|
104
|
+
for (const el of elements)
|
|
105
|
+
if (el.tag === 'img' && !has(el, 'alt'))
|
|
106
|
+
report(el.start, '<img> without alt: describe the image, or use alt="" when it is decoration');
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
name: 'label-field',
|
|
111
|
+
check({ elements: all, components, report }) {
|
|
112
|
+
for (const el of all) {
|
|
113
|
+
if (el.tag !== 'label' || has(el, 'for'))
|
|
114
|
+
continue;
|
|
115
|
+
if (![...elements(el.children)].some((e) => FIELDS.has(e.tag) || components.has(e.tag) || e.tag === 'slot')) {
|
|
116
|
+
report(el.start, '<label> names no field: put the field inside it, or point to one with for="id"');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
name: 'accessible-name',
|
|
123
|
+
check({ elements, components, report }) {
|
|
124
|
+
for (const el of elements) {
|
|
125
|
+
if (el.tag !== 'button' && !(el.tag === 'a' && has(el, 'href')))
|
|
126
|
+
continue;
|
|
127
|
+
if (!labelled(el) && !named(el.children, components))
|
|
128
|
+
report(el.start, `<${el.tag}> has no accessible name: give it text, aria-label or title`);
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
];
|
|
133
|
+
export function lint(source, file, config = {}, extra = []) {
|
|
134
|
+
const parsed = parse(source, file);
|
|
135
|
+
const corpus = [
|
|
136
|
+
...expressions(parsed.nodes),
|
|
137
|
+
parsed.script?.code ?? '',
|
|
138
|
+
...parsed.inputs.flatMap((i) => [i.type, i.default ?? '']),
|
|
139
|
+
...parsed.types.map((t) => t.type),
|
|
140
|
+
].join('\n');
|
|
141
|
+
const lineOf = (offset) => source.slice(0, offset).split('\n').length;
|
|
142
|
+
const ignored = new Map();
|
|
143
|
+
for (const m of source.matchAll(IGNORE_RE)) {
|
|
144
|
+
const names = m[1].split(/[\s,]+/).filter(Boolean);
|
|
145
|
+
const line = lineOf(m.index + m[0].length);
|
|
146
|
+
for (const l of [line, line + 1])
|
|
147
|
+
ignored.set(l, names.length ? new Set(names) : 'all');
|
|
148
|
+
}
|
|
149
|
+
const base = {
|
|
150
|
+
file,
|
|
151
|
+
source,
|
|
152
|
+
parsed,
|
|
153
|
+
elements: [...elements(parsed.nodes)],
|
|
154
|
+
components: new Set(parsed.imports.map((i) => i.name)),
|
|
155
|
+
reads: (name) => new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
|
|
156
|
+
};
|
|
157
|
+
const out = [];
|
|
158
|
+
const add = (rule, severity, start, message) => {
|
|
159
|
+
const { line, column } = new ClarusError(message, file, source, start);
|
|
160
|
+
const skip = ignored.get(line);
|
|
161
|
+
if (skip === 'all' || skip?.has(rule))
|
|
162
|
+
return;
|
|
163
|
+
out.push({ rule, severity, message, file, line, column, start });
|
|
164
|
+
};
|
|
165
|
+
for (const rule of [...lintRules, ...extra]) {
|
|
166
|
+
const level = config[rule.name] ?? 'warn';
|
|
167
|
+
if (level === 'off')
|
|
168
|
+
continue;
|
|
169
|
+
try {
|
|
170
|
+
rule.check({ ...base, report: (start, message) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message) });
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
add(rule.name, 'error', 0, `the rule failed: ${err.message}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return out.sort((a, b) => a.start - b.start);
|
|
177
|
+
}
|
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
|
+
}
|