clarusjs 0.14.0 → 0.16.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.
Files changed (54) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +119 -5
  3. package/dist/cli/check.d.ts +10 -2
  4. package/dist/cli/check.js +38 -12
  5. package/dist/cli/index.js +4 -1
  6. package/dist/cli/mapper.js +24 -1
  7. package/dist/cli/project.d.ts +6 -0
  8. package/dist/cli/project.js +1 -1
  9. package/dist/compiler/class-style.js +2 -2
  10. package/dist/compiler/components.d.ts +61 -0
  11. package/dist/compiler/components.js +81 -0
  12. package/dist/compiler/element-attrs.d.ts +7 -0
  13. package/dist/compiler/element-attrs.js +32 -0
  14. package/dist/compiler/emit-client.js +23 -3
  15. package/dist/compiler/emit-server.js +11 -8
  16. package/dist/compiler/html-expr.d.ts +2 -1
  17. package/dist/compiler/html-expr.js +15 -9
  18. package/dist/compiler/index.d.ts +14 -2
  19. package/dist/compiler/index.js +143 -3
  20. package/dist/compiler/ir.d.ts +24 -0
  21. package/dist/compiler/ir.js +81 -11
  22. package/dist/compiler/lint.d.ts +26 -2
  23. package/dist/compiler/lint.js +64 -4
  24. package/dist/compiler/parse.d.ts +37 -0
  25. package/dist/compiler/parse.js +42 -10
  26. package/dist/compiler/script.d.ts +11 -0
  27. package/dist/compiler/script.js +41 -0
  28. package/dist/compiler/shared.d.ts +6 -0
  29. package/dist/compiler/shared.js +14 -0
  30. package/dist/forms/index.js +15 -3
  31. package/dist/runtime/attrs.d.ts +6 -0
  32. package/dist/runtime/attrs.js +22 -3
  33. package/dist/runtime/dom.d.ts +39 -1
  34. package/dist/runtime/dom.js +159 -23
  35. package/dist/runtime/html.d.ts +6 -0
  36. package/dist/runtime/html.js +12 -0
  37. package/dist/runtime/index.d.ts +1 -1
  38. package/dist/runtime/index.js +1 -1
  39. package/dist/runtime/loader.js +53 -7
  40. package/dist/runtime/router.d.ts +6 -1
  41. package/dist/runtime/router.js +1 -1
  42. package/dist/runtime/server.d.ts +8 -2
  43. package/dist/runtime/server.js +14 -7
  44. package/dist/server/handler.d.ts +28 -1
  45. package/dist/server/handler.js +44 -1
  46. package/dist/server/modes.d.ts +2 -0
  47. package/dist/server/modes.js +5 -1
  48. package/dist/vite/build.d.ts +9 -2
  49. package/dist/vite/build.js +20 -5
  50. package/dist/vite/libraries.d.ts +32 -0
  51. package/dist/vite/libraries.js +77 -0
  52. package/dist/vite/plugin.d.ts +23 -0
  53. package/dist/vite/plugin.js +52 -24
  54. package/package.json +1 -1
@@ -1,15 +1,23 @@
1
+ import { extendedAttrs } from './element-attrs.js';
1
2
  import { parseExpressionAt } from 'acorn';
2
3
  import { iconElement } from './icon.js';
3
4
  import { ClarusError } from './errors.js';
4
5
  import { FOR_IMPLICIT, importNames } from './parse.js';
5
- import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
6
+ import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
6
7
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
7
- const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
8
+ export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
8
9
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
9
10
  const iconBodies = new WeakMap();
10
11
  export function lower(parsed, file, source, options = {}) {
11
12
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
13
  const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
14
+ if (parsed.events.length && !parsed.script)
15
+ fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
16
+ if (parsed.contexts.length && stateful)
17
+ fail('@context is only for components without <script> or @model for now: an island has no context in the browser. Read it in a component without a script, or pass it in as a prop', parsed.contexts[0].start);
18
+ for (const c of parsed.contexts)
19
+ if (parsed.inputs.some((i) => i.name === c.name))
20
+ fail(`"${c.name}" is already an @input`, c.nameStart);
13
21
  const warnings = [];
14
22
  const ss = parsed.serverScript;
15
23
  if (ss && stateful)
@@ -18,6 +26,7 @@ export function lower(parsed, file, source, options = {}) {
18
26
  const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
19
27
  const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
20
28
  const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
29
+ const provides = parsed.script ? providesIn(split, file, source, parsed.script.start) : false;
21
30
  const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
22
31
  const inputNames = new Set(stateful ? parsed.inputs.filter((i) => !i.model).map((i) => i.name).filter((name) => !signals.has(name)) : []);
23
32
  for (const name of inputNames) {
@@ -75,6 +84,7 @@ export function lower(parsed, file, source, options = {}) {
75
84
  let eventElementCount = 0;
76
85
  let attrElementCount = 0;
77
86
  let formCount = 0;
87
+ let useCount = 0;
78
88
  let selectModel;
79
89
  let engineScope = null;
80
90
  const sameRoot = (path, at) => {
@@ -206,9 +216,12 @@ export function lower(parsed, file, source, options = {}) {
206
216
  let attach;
207
217
  let cls;
208
218
  const paths = [];
219
+ const listens = [];
209
220
  for (const a of node.attrs) {
210
221
  if (/^(class|style)\./.test(a.name))
211
222
  fail(`a component takes a static class="…" only: [${a.name}] is for elements`, a.start);
223
+ if (a.kind === 'prop' && a.name === 'use')
224
+ fail('[use] is for elements: put it on an element inside the component', a.start);
212
225
  if (a.kind === 'prop' && a.name === '...') {
213
226
  if (props.some((p) => p.name === '...'))
214
227
  fail('one [...] per element', a.start);
@@ -235,17 +248,32 @@ export function lower(parsed, file, source, options = {}) {
235
248
  paths.push({ name: a.name, expr: modelPath(a.expr, modelNames) });
236
249
  models.push({ name: a.name, set });
237
250
  }
251
+ else if (a.kind === 'event') {
252
+ if (!stateful)
253
+ fail('event bindings need a <script> with state; this component is static', a.start);
254
+ checkHandler(a.expr, file, source, a.start);
255
+ listens.push({ name: a.name, handler: a.expr });
256
+ }
257
+ else if (a.kind === 'interp') {
258
+ for (const p of a.parts)
259
+ if (typeof p !== 'string')
260
+ checkExpr(p.expr, file, source, p.start);
261
+ props.push({ name: a.name, expr: `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')` });
262
+ }
263
+ else if (a.kind === 'static' && a.name !== 'attach') {
264
+ props.push({ name: a.name, expr: JSON.stringify(a.value) });
265
+ }
238
266
  else if (a.kind === 'static' && a.name === 'attach') {
239
267
  if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
240
268
  fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
241
269
  attach = a.value;
242
270
  }
243
271
  else
244
- fail(`component <${node.tag}> only takes [prop] and [(prop)] bindings and attach="…"`, a.start);
272
+ fail(`component <${node.tag}> only takes [prop], [(prop)] and (event) bindings and attach="…"`, a.start);
245
273
  }
246
274
  const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
247
275
  const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
248
- const region = stateful && (hasContent || readsState || models.length > 0) ? regionCount++ : -1;
276
+ const region = stateful && (hasContent || readsState || models.length > 0 || listens.length > 0 || provides) ? regionCount++ : -1;
249
277
  const parentScope = scopeKey;
250
278
  if (region >= 0)
251
279
  scopeKey = `c${region}`;
@@ -263,30 +291,46 @@ export function lower(parsed, file, source, options = {}) {
263
291
  continue;
264
292
  if (fills.some((f) => f.name === child.name))
265
293
  fail(`slot "${child.name}" is filled twice`, child.start);
266
- fills.push({ name: child.name, nodes: lowerList(child.children) });
294
+ if (child.params !== undefined) {
295
+ if (stateful)
296
+ fail(`@slot('${child.name}', …) receives data from the slot, which isn't supported inside an island yet: render this component outside the island, or pass the data as props`, child.start);
297
+ slotParamsCheck(child.params, file, source, child.paramsStart);
298
+ }
299
+ fills.push({ name: child.name, ...(child.params !== undefined ? { params: child.params } : {}), nodes: lowerList(child.children) });
267
300
  }
268
301
  const rest = node.children.filter((c) => c.type !== 'fill');
269
302
  const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
303
+ if (children.length && fills.some((f) => f.name === 'default'))
304
+ fail('the default slot is filled twice: by @slot(\'default\') and by content outside any @slot', node.start);
270
305
  scopeKey = parentScope;
271
- out.push({ kind: 'component', name: node.tag, props, ...(models.length ? { models } : {}), children, fills, region, ...(attach ? { attach } : {}), ...(paths.length ? { paths } : {}), ...(cls ? { class: cls } : {}) });
306
+ out.push({ kind: 'component', name: node.tag, props, ...(models.length ? { models } : {}), ...(listens.length ? { listens } : {}), children, fills, region, ...(attach ? { attach } : {}), ...(paths.length ? { paths } : {}), ...(cls ? { class: cls } : {}) });
272
307
  return;
273
308
  }
274
309
  if (node.tag === 'slot') {
275
- if (stateful)
276
- fail('<slot /> is only supported in components without <script>', node.start);
310
+ if (stateful && scopeKey !== undefined)
311
+ fail('in an island, <slot /> goes outside @if, @for and @await blocks and component content: the browser re-renders those, and slot content only exists on the server', node.start);
277
312
  let name = 'default';
313
+ const props = [];
278
314
  for (const a of node.attrs) {
279
315
  if (a.kind === 'static' && a.name === 'name' && typeof a.value === 'string' && a.value)
280
316
  name = a.value;
317
+ else if (a.kind === 'prop' && /^[A-Za-z_$][\w$]*$/.test(a.name)) {
318
+ checkExpr(a.expr, file, source, a.start + a.name.length + 4);
319
+ props.push({ name: a.name, expr: a.expr });
320
+ }
281
321
  else
282
- fail('<slot> only takes name="…"', a.start);
322
+ fail('<slot> only takes name="…", and the data it passes to its fill as [name]="expression"', a.start);
283
323
  }
284
324
  const fallback = [];
285
325
  const parent = out;
286
326
  out = fallback;
287
327
  node.children.forEach((child) => visit(child, rawText));
288
328
  out = parent;
289
- out.push({ kind: 'slot', name, fallback });
329
+ if (stateful && props.length)
330
+ fail('in an island, a slot passes no data: render the component outside the island to use [name]="…" on <slot>', node.start);
331
+ if (stateful && fallback.length)
332
+ fail('in an island, a slot has no fallback content', node.start);
333
+ out.push({ kind: 'slot', name, props, fallback });
290
334
  return;
291
335
  }
292
336
  const outerSelect = selectModel;
@@ -397,11 +441,19 @@ export function lower(parsed, file, source, options = {}) {
397
441
  const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
398
442
  const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
399
443
  const at = new ClarusError('', file, source, a.start);
400
- const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, where: `${file}:${at.line}:${at.column}` };
444
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }) };
401
445
  if (reactive)
402
446
  dynamic.push(node_);
403
447
  out.push(node_);
404
448
  }
449
+ else if (a.kind === 'prop' && a.name === 'use') {
450
+ if (!stateful)
451
+ fail('[use] needs a <script> (an island): behaviours run in the browser', a.start);
452
+ checkExpr(a.expr, file, source, a.start);
453
+ const index = useCount++;
454
+ emitStatic(` data-cl-u="${index}"`);
455
+ out.push({ kind: 'use', expr: a.expr, index });
456
+ }
405
457
  else if (a.kind === 'prop' && a.name === 'engine') {
406
458
  if (!stateful)
407
459
  fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
@@ -467,6 +519,7 @@ export function lower(parsed, file, source, options = {}) {
467
519
  file,
468
520
  name: file.split('/').pop().replace(/\.tscl$/, ''),
469
521
  inputs: parsed.inputs,
522
+ ...(parsed.extends ? { extends: Object.keys(extendedAttrs(parsed.extends.tag)) } : {}),
470
523
  imports: parsed.imports,
471
524
  script: parsed.script ? split.body : undefined,
472
525
  scriptImports: split.imports.map((imp) => imp.text),
@@ -476,9 +529,26 @@ export function lower(parsed, file, source, options = {}) {
476
529
  stateful,
477
530
  nodes,
478
531
  events,
532
+ sends: parsed.events.length > 0,
533
+ sendNames: parsed.events.map((e) => e.name),
534
+ contexts: parsed.contexts,
535
+ provides,
479
536
  warnings,
480
537
  };
481
538
  }
539
+ function slotParamsCheck(params, file, source, at) {
540
+ const bad = () => { throw new ClarusError('a fill names what its slot passes like a function parameter: @slot(\'row\', { item }) or @slot(\'row\', props)', file, source, at); };
541
+ try {
542
+ const node = parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' });
543
+ if (node.type !== 'ArrowFunctionExpression' || node.params?.length !== 1 || node.end !== params.length + 7)
544
+ bad();
545
+ }
546
+ catch (err) {
547
+ if (err instanceof ClarusError)
548
+ throw err;
549
+ bad();
550
+ }
551
+ }
482
552
  function pathSegments(path) {
483
553
  const root = /^[A-Za-z_$][\w$]*/.exec(path)?.[0];
484
554
  if (!root)
@@ -3,7 +3,7 @@ import { type ParsedFile, type TemplateNode } from './parse.ts';
3
3
  * The built-in rules' names.
4
4
  * @see https://clarusjs.com/guide/lint#rules
5
5
  */
6
- export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name';
6
+ export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name' | 'one-root';
7
7
  /**
8
8
  * Each rule's level, built-in or a project's, keyed by rule name.
9
9
  * @see https://clarusjs.com/guide/lint#warnings-and-errors
@@ -26,6 +26,18 @@ export type LintMessage = {
26
26
  line: number;
27
27
  column: number;
28
28
  start: number;
29
+ fix?: LintFix;
30
+ };
31
+ /**
32
+ * An edit that fixes a finding: the source from `start` to `end` (offsets) becomes `text`. `clarusjs check --fix` and
33
+ * the ESLint plugin apply them.
34
+ * @since 0.16.0
35
+ * @see https://clarusjs.com/guide/lint#fixes
36
+ */
37
+ export type LintFix = {
38
+ start: number;
39
+ end: number;
40
+ text: string;
29
41
  };
30
42
  /**
31
43
  * A template element, as `parse` returns it.
@@ -49,7 +61,7 @@ export type LintContext = {
49
61
  /** Whether the template, the script, or an input's type or default reads `name`. */
50
62
  reads(name: string): boolean;
51
63
  /** 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;
64
+ report(start: number, message: string, fix?: LintFix): void;
53
65
  };
54
66
  /**
55
67
  * A lint rule: a name (used in levels and ignore comments) and a check over one file.
@@ -80,3 +92,15 @@ export declare const lintRules: LintRuleDef[];
80
92
  * @see https://clarusjs.com/reference/compiler#lint
81
93
  */
82
94
  export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[]): LintMessage[];
95
+ /**
96
+ * The source with the findings' fixes applied. Overlapping fixes: the first one (by position) wins; run lint again for
97
+ * the rest.
98
+ * @example
99
+ * ```ts
100
+ * import { applyFixes, lint } from 'clarusjs/compiler'
101
+ * const fixed = applyFixes(source, lint(source, 'src/components/card.tscl'))
102
+ * ```
103
+ * @since 0.16.0
104
+ * @see https://clarusjs.com/reference/compiler#applyfixes
105
+ */
106
+ export declare function applyFixes(source: string, messages: readonly LintMessage[]): string;
@@ -1,5 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { awaitLists, importNames, parse } from './parse.js';
2
+ import { awaitLists, importNames, parse, rootNodes } from './parse.js';
3
3
  const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
4
4
  const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
5
5
  function* elements(nodes) {
@@ -86,6 +86,58 @@ function named(nodes, components) {
86
86
  });
87
87
  }
88
88
  export const lintRules = [
89
+ {
90
+ name: 'one-root',
91
+ check({ file, source, parsed, report }) {
92
+ if (/(^|[\\/])(pages|layouts)[\\/]/.test(file))
93
+ return;
94
+ const top = rootNodes;
95
+ const nodes = top(parsed.nodes);
96
+ if (nodes.some((n) => n.type === 'element' && n.tag === 'html'))
97
+ return;
98
+ const element = (list) => list.length === 1 && list[0].type === 'element';
99
+ if (element(nodes))
100
+ return;
101
+ const one = (list) => element(list) && list[0].tag !== 'fragment';
102
+ const [first] = nodes;
103
+ if (nodes.length === 1 && first.type === 'if' && first.branches.at(-1).cond === null && first.branches.every((b) => one(top(b.children))))
104
+ return;
105
+ const at = nodes.length > 1 && (first.type === 'element') ? nodes[1] : first;
106
+ if (!at)
107
+ return;
108
+ const last = nodes.at(-1);
109
+ const blocks = [...parsed.styles.map((st) => st.tag), parsed.serverScript?.tag ?? -1, parsed.script ? source.lastIndexOf('<script', parsed.script.start) : -1];
110
+ const after = [...parsed.nodes.map((n) => n.start), ...blocks].filter((x) => x > last.start);
111
+ const rawEnd = after.length ? Math.min(...after) : source.length;
112
+ const end = source.slice(0, rawEnd).trimEnd().length;
113
+ const declared = Object.entries(parsed).flatMap(([key, value]) => {
114
+ if (['nodes', 'script', 'serverScript', 'styles'].includes(key))
115
+ return [];
116
+ if (typeof value === 'number')
117
+ return [value];
118
+ const items = Array.isArray(value) ? value : [value];
119
+ return items.flatMap((d) => (d && typeof d === 'object' && typeof d.start === 'number' ? [d.start] : []));
120
+ });
121
+ const inside = (x) => x > first.start && x < end;
122
+ const moving = new Set([...blocks, ...declared].filter(inside));
123
+ const cuts = [...new Set([first.start, ...parsed.nodes.map((n) => n.start).filter(inside), ...moving])].sort((a, b) => a - b);
124
+ const pieces = cuts.map((c, i) => ({ c, text: source.slice(c, cuts[i + 1] ?? end) }));
125
+ const nl = source.includes('\r\n') ? '\r\n' : '\n';
126
+ const moved = pieces.filter((p) => moving.has(p.c)).map((p) => p.text.trimEnd() + nl).join('');
127
+ const typeAt = new Map(parsed.nodes.map((n) => [n.start, n.type]));
128
+ const stay = pieces.filter((p) => !moving.has(p.c));
129
+ const kept = stay.map((p, i) => {
130
+ const next = stay[i + 1];
131
+ if (!next || next.c === pieces[pieces.indexOf(p) + 1]?.c || typeAt.get(p.c) === 'text')
132
+ return p.text;
133
+ const text = p.text.trimEnd();
134
+ return typeAt.get(p.c) !== 'text' && typeAt.get(next.c) !== 'text' ? text + nl : text;
135
+ }).join('').trimEnd();
136
+ const close = last.type !== 'text' || source.slice(end, rawEnd).includes('\n') ? nl : '';
137
+ const fix = { start: first.start, end, text: `${moved}<fragment>${nl}${kept}${close}</fragment>` };
138
+ report(at.start, 'a component renders one root element, for what a parent passes it (attributes, class, events) to land on: wrap these in an element, or in <fragment> if no element is wanted', fix);
139
+ },
140
+ },
89
141
  {
90
142
  name: 'unused-input',
91
143
  check({ parsed, reads, report }) {
@@ -166,19 +218,19 @@ export function lint(source, file, config = {}, extra = []) {
166
218
  reads: (name) => new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
167
219
  };
168
220
  const out = [];
169
- const add = (rule, severity, start, message) => {
221
+ const add = (rule, severity, start, message, fix) => {
170
222
  const { line, column } = new ClarusError(message, file, source, start);
171
223
  const skip = ignored.get(line);
172
224
  if (skip === 'all' || skip?.has(rule))
173
225
  return;
174
- out.push({ rule, severity, message, file, line, column, start });
226
+ out.push({ rule, severity, message, file, line, column, start, ...(fix ? { fix } : {}) });
175
227
  };
176
228
  for (const rule of [...lintRules, ...extra]) {
177
229
  const level = config[rule.name] ?? 'warn';
178
230
  if (level === 'off')
179
231
  continue;
180
232
  try {
181
- rule.check({ ...base, report: (start, message) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message) });
233
+ rule.check({ ...base, report: (start, message, fix) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message, fix) });
182
234
  }
183
235
  catch (err) {
184
236
  add(rule.name, 'error', 0, `the rule failed: ${err.message}`);
@@ -186,3 +238,11 @@ export function lint(source, file, config = {}, extra = []) {
186
238
  }
187
239
  return out.sort((a, b) => a.start - b.start);
188
240
  }
241
+ export function applyFixes(source, messages) {
242
+ const fixes = messages.flatMap((m) => (m.fix ? [m.fix] : [])).sort((a, b) => a.start - b.start);
243
+ const kept = [];
244
+ for (const f of fixes)
245
+ if (!kept.length || f.start >= kept.at(-1).end)
246
+ kept.push(f);
247
+ return kept.reduceRight((text, f) => text.slice(0, f.start) + f.text + text.slice(f.end), source);
248
+ }
@@ -84,6 +84,8 @@ export type TemplateNode = {
84
84
  } | {
85
85
  type: 'fill';
86
86
  name: string;
87
+ params?: string;
88
+ paramsStart?: number;
87
89
  children: TemplateNode[];
88
90
  start: number;
89
91
  } | {
@@ -134,6 +136,17 @@ export type ImportDecl = {
134
136
  from: string;
135
137
  start: number;
136
138
  };
139
+ /**
140
+ * An `@event` declaration (#442): the event's name and the type of the value it sends, with their offsets.
141
+ * @see https://clarusjs.com/guide/events#from-a-child-island-to-its-parent
142
+ */
143
+ export type EventDecl = {
144
+ name: string;
145
+ type: string;
146
+ start: number;
147
+ nameStart: number;
148
+ typeStart: number;
149
+ };
137
150
  export type TypeDecl = {
138
151
  kind: 'type' | 'interface';
139
152
  name: string;
@@ -149,6 +162,10 @@ export type TypeDecl = {
149
162
  */
150
163
  export type ParsedFile = {
151
164
  inputs: InputDecl[];
165
+ /** `@event change: string` (#442): what the component sends its parent, and its value's type ('void' when none). */
166
+ events: EventDecl[];
167
+ /** `@context tabs: Type` (#465): values a component around this one provides; same shape as an @input. */
168
+ contexts: InputDecl[];
152
169
  imports: ImportDecl[];
153
170
  typeImports: TypeImport[];
154
171
  types: TypeDecl[];
@@ -173,10 +190,30 @@ export type ParsedFile = {
173
190
  from: string;
174
191
  start: number;
175
192
  }[];
193
+ /** `@layout none` (#456): the page renders without its folder and config layouts. `layoutStart`: where it is. */
194
+ layout?: 'none';
195
+ layoutStart?: number;
196
+ /** `@extends button`: the native element this component stands for; it takes all of that element's attributes. */
197
+ extends?: {
198
+ tag: string;
199
+ start: number;
200
+ };
176
201
  nodes: TemplateNode[];
177
202
  };
178
203
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
179
204
  export declare const FOR_IMPLICIT: string[];
205
+ /**
206
+ * A template's top-level nodes that render: no whitespace or comments, no <cl-head>, <script> or <style>. What one-root, @extends,
207
+ * fragment roots and check all look at.
208
+ * @internal
209
+ */
210
+ export declare function rootNodes(nodes: TemplateNode[]): TemplateNode[];
211
+ /**
212
+ * Whether a component's root is (or may be) a <fragment>: one at the top, or in a branch of a top-level @if. It
213
+ * renders no single element, so a parent's attributes and events have nowhere to land.
214
+ * @internal
215
+ */
216
+ export declare function fragmentRoot(nodes: TemplateNode[]): boolean;
180
217
  /**
181
218
  * Parse a `.tscl` file into its syntax tree, without compiling it: for tools (an editor, a linter, a docs
182
219
  * generator). Throws a located `ClarusError` for a syntax error.
@@ -7,8 +7,16 @@ const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+
7
7
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
8
8
  const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
9
9
  const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim()];
10
+ export function rootNodes(nodes) {
11
+ return nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && ['cl-head', 'script', 'style'].includes(n.tag)));
12
+ }
13
+ export function fragmentRoot(nodes) {
14
+ const top = rootNodes(nodes);
15
+ const frag = (list) => list.length === 1 && list[0].type === 'element' && list[0].tag === 'fragment';
16
+ return frag(top) || (top.length === 1 && top[0].type === 'if' && top[0].branches.some((b) => frag(rootNodes(b.children))));
17
+ }
10
18
  export function parse(source, file) {
11
- const out = { inputs: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
19
+ const out = { inputs: [], events: [], contexts: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
12
20
  let i = 0;
13
21
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
14
22
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
@@ -17,8 +25,8 @@ export function parse(source, file) {
17
25
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
18
26
  const line = source.slice(i, end).trim();
19
27
  let m;
20
- if (/^@(input|model)\s/.test(line)) {
21
- return inputDecl(lineStart, line.startsWith('@model'));
28
+ if (/^@(input|model|context)\s/.test(line)) {
29
+ return inputDecl(lineStart, line.startsWith('@model'), line.startsWith('@context'));
22
30
  }
23
31
  else if (/^@(type|interface)\s/.test(line)) {
24
32
  return typeDecl(lineStart);
@@ -40,6 +48,27 @@ export function parse(source, file) {
40
48
  fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
41
49
  out.cssImports.push({ from: m[2], start: i });
42
50
  }
51
+ else if (/^@event(\s|$)/.test(line)) {
52
+ const d = /^@event\s+([A-Za-z_$][\w$-]*)\s*(?::\s*(\S[\s\S]*?))?\s*$/.exec(line);
53
+ if (!d)
54
+ fail('@event takes a name and the type of its value: @event change: string (or @event close for none)', i);
55
+ const nameStart = lineStart + line.indexOf(d[1], 6);
56
+ const typeStart = d[2] ? lineStart + line.lastIndexOf(d[2]) : nameStart;
57
+ out.events.push({ name: d[1], type: d[2] ?? 'void', start: i, nameStart, typeStart });
58
+ }
59
+ else if ((m = /^@extends(?:\s+(\S+))?\s*$/.exec(line))) {
60
+ if (out.extends)
61
+ fail('a component has one @extends', i);
62
+ if (!m[1])
63
+ fail('@extends takes an element name: @extends button', i);
64
+ out.extends = { tag: m[1], start: i };
65
+ }
66
+ else if ((m = /^@layout(?:\s+(\S+))?\s*$/.exec(line))) {
67
+ if (m[1] !== 'none')
68
+ fail('@layout only takes none: @layout none renders the page without its folder and config layouts', i);
69
+ out.layout = 'none';
70
+ out.layoutStart = i;
71
+ }
43
72
  else
44
73
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
45
74
  i = end;
@@ -65,8 +94,8 @@ export function parse(source, file) {
65
94
  }
66
95
  return source.length;
67
96
  }
68
- function inputDecl(lineStart, model) {
69
- const directive = model ? '@model' : '@input';
97
+ function inputDecl(lineStart, model, context = false) {
98
+ const directive = context ? '@context' : model ? '@model' : '@input';
70
99
  const malformed = () => fail(`unknown or malformed directive "${directive}"`, i);
71
100
  let pos = lineStart + directive.length;
72
101
  while (source[pos] === ' ' || source[pos] === '\t')
@@ -117,7 +146,8 @@ export function parse(source, file) {
117
146
  malformed();
118
147
  fallback = { default: value, defaultStart: at };
119
148
  }
120
- out.inputs.push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
149
+ ;
150
+ (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
121
151
  i = end;
122
152
  }
123
153
  function typeDecl(lineStart) {
@@ -450,16 +480,18 @@ export function parse(source, file) {
450
480
  function fillBlock() {
451
481
  const start = i;
452
482
  i += 5;
453
- const { cond } = condition('@slot');
454
- const m = /^(['"])([\w-]+)\1$/.exec(cond);
483
+ const { cond, condStart } = condition('@slot');
484
+ const m = /^(['"])([\w-]+)\1\s*(?:,\s*([\s\S]*\S))?\s*$/.exec(cond);
455
485
  if (!m)
456
- fail(`@slot needs a quoted name, like @slot('aside')`, start);
486
+ fail(`@slot needs a quoted name, like @slot('aside'), or @slot('row', { item }) for a slot that passes data`, start);
487
+ const params = m[3];
488
+ const paramsStart = params === undefined ? undefined : condStart + cond.indexOf(params, m[1].length * 2 + m[2].length);
457
489
  while (/\s/.test(source[i] ?? ''))
458
490
  i++;
459
491
  if (source[i] !== '{')
460
492
  fail('expected { to open the block', i);
461
493
  i++;
462
- return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
494
+ return { type: 'fill', name: m[2], ...(params !== undefined ? { params, paramsStart } : {}), children: children({ tag: '@slot', start, block: true }), start };
463
495
  }
464
496
  function children(parent) {
465
497
  const nodes = [];
@@ -53,6 +53,17 @@ export declare function rewriteClient(code: string, signals: Signals, options?:
53
53
  forms?: string;
54
54
  }): string;
55
55
  export declare function rewriteClientExpr(expr: string, signals: Signals): string;
56
+ /**
57
+ * provide(key, value) calls (#465): the key must be a string literal naming a value; provide itself is reserved (a
58
+ * script may not declare or import its own). True when the script provides anything. Shared by build and check.
59
+ */
60
+ export declare function providesIn(split: {
61
+ imports: {
62
+ text: string;
63
+ start: number;
64
+ }[];
65
+ body: string;
66
+ }, file: string, source: string, offset: number): boolean;
56
67
  export declare function rewriteServer(code: string): string;
57
68
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
58
69
  /**
@@ -313,6 +313,9 @@ function clientHook(code, signals, entered = new WeakSet(), forms) {
313
313
  const [first, ...rest] = node.arguments;
314
314
  return `${forms}(${first.name}${rest.map((a) => `, ${rec(a)}`).join('')})`;
315
315
  }
316
+ const provided = provideCall(node, rec);
317
+ if (provided)
318
+ return provided;
316
319
  if (node.type === 'UpdateExpression' && isSignal(node.argument)) {
317
320
  const name = node.argument.name;
318
321
  const op = node.operator[0];
@@ -361,11 +364,49 @@ export function rewriteClientExpr(expr, signals) {
361
364
  const ast = parseExpr(expr);
362
365
  return expr.slice(0, ast.start) + print(ast, expr, clientHook(expr, signals)) + expr.slice(ast.end);
363
366
  }
367
+ export function providesIn(split, file, source, offset) {
368
+ for (const imp of split.imports) {
369
+ if (parseScript(imp.text).body[0].specifiers.some((x) => x.local.name === 'provide'))
370
+ throw new ClarusError('provide is reserved for context: rename this import (import { provide as other } …)', file, source, offset + imp.start);
371
+ }
372
+ const code = split.body;
373
+ let found = false;
374
+ const usage = "provide is called with a string key and a value: provide('tabs', { value })";
375
+ const hook = (node, parent, key) => {
376
+ if (node.type === 'Identifier' && node.name === 'provide' && !(parent?.type === 'CallExpression' && key === 'callee') && (!isBinding(parent, key) || parent?.shorthand)) {
377
+ throw new ClarusError(usage, file, source, offset + node.start);
378
+ }
379
+ const declared = (node.type === 'FunctionDeclaration' || node.type === 'VariableDeclarator' || node.type === 'ClassDeclaration') && node.id?.type === 'Identifier' && node.id.name === 'provide';
380
+ if (declared)
381
+ throw new ClarusError('provide is reserved for context: give this function another name', file, source, offset + node.start);
382
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'provide') {
383
+ found = true;
384
+ const key = node.arguments[0];
385
+ if (!key || key.type !== 'Literal' || typeof key.value !== 'string' || node.arguments.length !== 2) {
386
+ throw new ClarusError(usage, file, source, offset + node.start);
387
+ }
388
+ if (!/^[A-Za-z_$][\w$]*$/.test(key.value))
389
+ throw new ClarusError(`provide's key "${key.value}" isn't a name @context can read: use letters, digits, _ or $, like 'tabs'`, file, source, offset + node.start);
390
+ }
391
+ return undefined;
392
+ };
393
+ print(parseScript(code, file, source, offset), code, hook);
394
+ return found;
395
+ }
396
+ function provideCall(node, rec) {
397
+ if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || node.callee.name !== 'provide' || node.arguments.length !== 2)
398
+ return undefined;
399
+ const [key, value] = node.arguments;
400
+ return `provide(${rec(key)}, () => (${rec(value)}))`;
401
+ }
364
402
  export function rewriteServer(code) {
365
403
  const ast = parseScript(code);
366
404
  const hook = (node) => {
367
405
  if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier')
368
406
  return undefined;
407
+ const provided = provideCall(node, (n) => print(n, code, hook));
408
+ if (provided)
409
+ return provided;
369
410
  const arg = node.arguments[0];
370
411
  const inner = arg ? print(arg, code, hook) : 'undefined';
371
412
  if (node.callee.name === 'state')
@@ -4,3 +4,9 @@ export declare function inputsLine(ir: ComponentIR): string;
4
4
  /** Dedent a script block and indent it by two spaces, one statement line per line. */
5
5
  export declare function indentScript(code: string): string;
6
6
  export declare const renderName: (name: string) => string;
7
+ /**
8
+ * The context a component renders its children with (#465): what it was given (render option cx), plus what its
9
+ * script provides. provide(key, get) adds a getter, so a child reads the value current when it renders. Only when
10
+ * the component calls components, places slots, reads context or provides.
11
+ */
12
+ export declare function contextLines(ir: ComponentIR, incoming: string): string;
@@ -1,4 +1,5 @@
1
1
  import { templateRanges } from './script.js';
2
+ import { walk } from './html-expr.js';
2
3
  export function inputsLine(ir) {
3
4
  if (!ir.inputs.length)
4
5
  return '';
@@ -19,3 +20,16 @@ export function indentScript(code) {
19
20
  return lines.map((l) => (l.literal ? l.text : ' ' + l.text.slice(indent))).join('\n') + '\n';
20
21
  }
21
22
  export const renderName = (name) => '__cl_render_' + name.replace(/-/g, '$');
23
+ export function contextLines(ir, incoming) {
24
+ const all = walk(ir.nodes);
25
+ if (!ir.provides && !ir.contexts.length && !all.some((n) => n.kind === 'component' || n.kind === 'slot'))
26
+ return '';
27
+ let out = ir.provides
28
+ ? ` const __cl_cx = { ...${incoming} }\n const provide = (k, get) => { Object.defineProperty(__cl_cx, k, { get, enumerable: true, configurable: true }) }\n`
29
+ : ` const __cl_cx = ${incoming}\n`;
30
+ for (const c of ir.contexts) {
31
+ const missing = `throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> reads context "${c.name}", which no component around it provides`)})`;
32
+ out += ` const ${c.name} = __cl_cx && {}.hasOwnProperty.call(__cl_cx, ${JSON.stringify(c.name)}) ? __cl_cx.${c.name} : ${c.default !== undefined ? `(${c.default})` : `(() => { ${missing} })()`}\n`;
33
+ }
34
+ return out;
35
+ }