clarusjs 0.14.0 → 0.15.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 (45) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +106 -5
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.js +2 -2
  9. package/dist/compiler/components.d.ts +32 -0
  10. package/dist/compiler/components.js +63 -0
  11. package/dist/compiler/emit-client.js +18 -3
  12. package/dist/compiler/emit-server.js +11 -8
  13. package/dist/compiler/html-expr.d.ts +2 -1
  14. package/dist/compiler/html-expr.js +15 -9
  15. package/dist/compiler/index.d.ts +13 -1
  16. package/dist/compiler/index.js +54 -1
  17. package/dist/compiler/ir.d.ts +20 -0
  18. package/dist/compiler/ir.js +78 -11
  19. package/dist/compiler/parse.d.ts +20 -0
  20. package/dist/compiler/parse.js +27 -10
  21. package/dist/compiler/script.d.ts +11 -0
  22. package/dist/compiler/script.js +41 -0
  23. package/dist/compiler/shared.d.ts +6 -0
  24. package/dist/compiler/shared.js +14 -0
  25. package/dist/forms/index.js +15 -3
  26. package/dist/runtime/attrs.d.ts +6 -0
  27. package/dist/runtime/attrs.js +16 -0
  28. package/dist/runtime/dom.d.ts +33 -1
  29. package/dist/runtime/dom.js +128 -23
  30. package/dist/runtime/html.d.ts +6 -0
  31. package/dist/runtime/html.js +12 -0
  32. package/dist/runtime/index.d.ts +1 -1
  33. package/dist/runtime/index.js +1 -1
  34. package/dist/runtime/loader.js +32 -6
  35. package/dist/runtime/router.d.ts +6 -1
  36. package/dist/runtime/router.js +1 -1
  37. package/dist/runtime/server.d.ts +8 -2
  38. package/dist/runtime/server.js +14 -7
  39. package/dist/server/handler.d.ts +28 -1
  40. package/dist/server/handler.js +44 -1
  41. package/dist/server/modes.d.ts +2 -0
  42. package/dist/server/modes.js +5 -1
  43. package/dist/vite/plugin.d.ts +19 -0
  44. package/dist/vite/plugin.js +46 -12
  45. package/package.json +1 -1
@@ -1,17 +1,24 @@
1
1
  import { emitClient } from './emit-client.js';
2
2
  import { ClarusError } from './errors.js';
3
3
  import { emitServer } from './emit-server.js';
4
- import { lower } from './ir.js';
4
+ import { lower, SPREAD_REFUSED } from './ir.js';
5
+ import { autoImport } from './components.js';
5
6
  import { awaitLists, parse } from './parse.js';
6
7
  export { ClarusError } from './errors.js';
7
8
  export { parse } from './parse.js';
9
+ export { componentIndex, COMPONENT_DIRS } from './components.js';
8
10
  import { foldClass } from './class-style.js';
9
11
  export { checkIcons } from './icon.js';
10
12
  export { lint, lintRules } from './lint.js';
11
13
  export function compile(source, options) {
12
14
  const parsed = parse(source, options.file);
15
+ if (options.components)
16
+ autoImport(parsed, options.components, options.file, source);
17
+ if (options.layouts?.length && parsed.layout !== 'none')
18
+ wrapInLayouts(parsed, options.layouts, options.file, source);
13
19
  const warnings = [];
14
20
  const id = options.scope ?? scopeId(options.file);
21
+ fallThrough(parsed);
15
22
  foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
16
23
  markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
17
24
  let css = '';
@@ -76,6 +83,36 @@ function markSlotContent(nodes, cls, components) {
76
83
  }
77
84
  }
78
85
  }
86
+ const ID_LISTS = ['aria-describedby', 'aria-labelledby', 'aria-controls', 'aria-owns'];
87
+ function fallThrough(parsed) {
88
+ const meaningful = parsed.nodes.filter((n) => !(n.type === 'text' && !n.value.trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
89
+ const root = meaningful[0];
90
+ if (meaningful.length !== 1 || root?.type !== 'element' || SPREAD_REFUSED.has(root.tag.toLowerCase()))
91
+ return;
92
+ if (root.attrs.some((a) => a.kind === 'prop' && a.name === '...'))
93
+ return;
94
+ const island = !!parsed.script || parsed.inputs.some((i) => i.model);
95
+ if (island && parsed.imports.some((i) => i.name === root.tag))
96
+ return;
97
+ root.attrs.push({ kind: 'prop', name: '...', expr: '__cl_attrs', start: root.start });
98
+ for (const [i, a] of root.attrs.entries()) {
99
+ if (a.kind !== 'static' || typeof a.value !== 'string' || !ID_LISTS.includes(a.name.toLowerCase()))
100
+ continue;
101
+ const more = `__cl_attrs[${JSON.stringify(a.name)}] == null ? "" : " " + __cl_attrs[${JSON.stringify(a.name)}]`;
102
+ root.attrs[i] = { kind: 'interp', name: a.name, parts: [a.value, { expr: more, start: a.start }], start: a.start };
103
+ }
104
+ if (parsed.imports.some((i) => i.name === root.tag))
105
+ return;
106
+ if (root.attrs.some((a) => (a.name === 'style' || a.name.startsWith('style.')) && a.kind !== 'event' && a.kind !== 'static'))
107
+ return;
108
+ const style = root.attrs.findIndex((a) => a.name === 'style' && a.kind !== 'event');
109
+ const ownStyle = root.attrs[style];
110
+ if (ownStyle?.kind === 'static' && typeof ownStyle.value === 'string') {
111
+ root.attrs[style] = { kind: 'interp', name: 'style', parts: [ownStyle.value, { expr: '__cl_attrs.style == null ? "" : "; " + __cl_attrs.style', start: ownStyle.start }], start: ownStyle.start };
112
+ }
113
+ else if (!ownStyle)
114
+ root.attrs.push({ kind: 'prop', name: 'style', expr: '__cl_attrs.style', start: root.start });
115
+ }
79
116
  function markRoots(nodes, cls, components, slots = false) {
80
117
  for (const node of nodes) {
81
118
  if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
@@ -110,3 +147,19 @@ function markRoots(nodes, cls, components, slots = false) {
110
147
  }
111
148
  }
112
149
  }
150
+ function wrapInLayouts(parsed, layouts, file, source) {
151
+ if (parsed.script || parsed.inputs.some((i) => i.model)) {
152
+ throw new ClarusError('this page is an island (it has a <script> or a @model input), and folder or config layouts can\'t wrap an island yet: move the script into a component the page uses, or add @layout none', file, source, 0);
153
+ }
154
+ let nodes = parsed.nodes;
155
+ for (let k = layouts.length - 1; k >= 0; k--) {
156
+ const name = `__cl_layout_${k}`;
157
+ parsed.imports.push({ name, from: layouts[k], start: 0 });
158
+ const attrs = [
159
+ { kind: 'prop', name: 'path', expr: "__cl_opts?.route?.path ?? ''", start: 0 },
160
+ { kind: 'prop', name: 'params', expr: '__cl_opts?.route?.params ?? {}', start: 0 },
161
+ ];
162
+ nodes = [{ type: 'element', tag: name, attrs, children: nodes, start: 0 }];
163
+ }
164
+ parsed.nodes = nodes;
165
+ }
@@ -22,9 +22,14 @@ export type IRNode = {
22
22
  name: string;
23
23
  set: string;
24
24
  }[];
25
+ listens?: {
26
+ name: string;
27
+ handler: string;
28
+ }[];
25
29
  children: IRNode[];
26
30
  fills: {
27
31
  name: string;
32
+ params?: string;
28
33
  nodes: IRNode[];
29
34
  }[];
30
35
  region: number;
@@ -37,6 +42,10 @@ export type IRNode = {
37
42
  } | {
38
43
  kind: 'slot';
39
44
  name: string;
45
+ props: {
46
+ name: string;
47
+ expr: string;
48
+ }[];
40
49
  fallback: IRNode[];
41
50
  } | {
42
51
  kind: 'attr';
@@ -57,6 +66,10 @@ export type IRNode = {
57
66
  kind: 'connect';
58
67
  expr: string;
59
68
  index: number;
69
+ } | {
70
+ kind: 'use';
71
+ expr: string;
72
+ index: number;
60
73
  } | {
61
74
  kind: 'if';
62
75
  branches: {
@@ -110,9 +123,16 @@ export type ComponentIR = {
110
123
  stateful: boolean;
111
124
  nodes: IRNode[];
112
125
  events: IREvent[];
126
+ /** The component sends events to its parent (@event, #442): its script gets emit(). */
127
+ sends: boolean;
128
+ /** @context declarations (#465): values read from the components around this one. */
129
+ contexts: InputDecl[];
130
+ /** The script calls provide() (#465): this component adds to the context its children render with. */
131
+ provides: boolean;
113
132
  /** Things that compile but likely aren't meant (located, not thrown). */
114
133
  warnings: ClarusError[];
115
134
  };
135
+ export declare const SPREAD_REFUSED: Set<string>;
116
136
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
117
137
  collapseWhitespace?: boolean;
118
138
  icon?: IconResolver;
@@ -2,14 +2,21 @@ import { parseExpressionAt } from 'acorn';
2
2
  import { iconElement } from './icon.js';
3
3
  import { ClarusError } from './errors.js';
4
4
  import { FOR_IMPLICIT, importNames } from './parse.js';
5
- import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
5
+ import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
6
6
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
7
- const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
7
+ export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
8
8
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
9
9
  const iconBodies = new WeakMap();
10
10
  export function lower(parsed, file, source, options = {}) {
11
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
12
  const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
13
+ if (parsed.events.length && !parsed.script)
14
+ fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
15
+ if (parsed.contexts.length && stateful)
16
+ 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);
17
+ for (const c of parsed.contexts)
18
+ if (parsed.inputs.some((i) => i.name === c.name))
19
+ fail(`"${c.name}" is already an @input`, c.nameStart);
13
20
  const warnings = [];
14
21
  const ss = parsed.serverScript;
15
22
  if (ss && stateful)
@@ -18,6 +25,7 @@ export function lower(parsed, file, source, options = {}) {
18
25
  const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
19
26
  const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
20
27
  const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
28
+ const provides = parsed.script ? providesIn(split, file, source, parsed.script.start) : false;
21
29
  const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
22
30
  const inputNames = new Set(stateful ? parsed.inputs.filter((i) => !i.model).map((i) => i.name).filter((name) => !signals.has(name)) : []);
23
31
  for (const name of inputNames) {
@@ -75,6 +83,7 @@ export function lower(parsed, file, source, options = {}) {
75
83
  let eventElementCount = 0;
76
84
  let attrElementCount = 0;
77
85
  let formCount = 0;
86
+ let useCount = 0;
78
87
  let selectModel;
79
88
  let engineScope = null;
80
89
  const sameRoot = (path, at) => {
@@ -206,9 +215,12 @@ export function lower(parsed, file, source, options = {}) {
206
215
  let attach;
207
216
  let cls;
208
217
  const paths = [];
218
+ const listens = [];
209
219
  for (const a of node.attrs) {
210
220
  if (/^(class|style)\./.test(a.name))
211
221
  fail(`a component takes a static class="…" only: [${a.name}] is for elements`, a.start);
222
+ if (a.kind === 'prop' && a.name === 'use')
223
+ fail('[use] is for elements: put it on an element inside the component', a.start);
212
224
  if (a.kind === 'prop' && a.name === '...') {
213
225
  if (props.some((p) => p.name === '...'))
214
226
  fail('one [...] per element', a.start);
@@ -235,17 +247,32 @@ export function lower(parsed, file, source, options = {}) {
235
247
  paths.push({ name: a.name, expr: modelPath(a.expr, modelNames) });
236
248
  models.push({ name: a.name, set });
237
249
  }
250
+ else if (a.kind === 'event') {
251
+ if (!stateful)
252
+ fail('event bindings need a <script> with state; this component is static', a.start);
253
+ checkHandler(a.expr, file, source, a.start);
254
+ listens.push({ name: a.name, handler: a.expr });
255
+ }
256
+ else if (a.kind === 'interp') {
257
+ for (const p of a.parts)
258
+ if (typeof p !== 'string')
259
+ checkExpr(p.expr, file, source, p.start);
260
+ props.push({ name: a.name, expr: `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')` });
261
+ }
262
+ else if (a.kind === 'static' && a.name !== 'attach') {
263
+ props.push({ name: a.name, expr: JSON.stringify(a.value) });
264
+ }
238
265
  else if (a.kind === 'static' && a.name === 'attach') {
239
266
  if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
240
267
  fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
241
268
  attach = a.value;
242
269
  }
243
270
  else
244
- fail(`component <${node.tag}> only takes [prop] and [(prop)] bindings and attach="…"`, a.start);
271
+ fail(`component <${node.tag}> only takes [prop], [(prop)] and (event) bindings and attach="…"`, a.start);
245
272
  }
246
273
  const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
247
274
  const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
248
- const region = stateful && (hasContent || readsState || models.length > 0) ? regionCount++ : -1;
275
+ const region = stateful && (hasContent || readsState || models.length > 0 || listens.length > 0 || provides) ? regionCount++ : -1;
249
276
  const parentScope = scopeKey;
250
277
  if (region >= 0)
251
278
  scopeKey = `c${region}`;
@@ -263,30 +290,46 @@ export function lower(parsed, file, source, options = {}) {
263
290
  continue;
264
291
  if (fills.some((f) => f.name === child.name))
265
292
  fail(`slot "${child.name}" is filled twice`, child.start);
266
- fills.push({ name: child.name, nodes: lowerList(child.children) });
293
+ if (child.params !== undefined) {
294
+ if (stateful)
295
+ 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);
296
+ slotParamsCheck(child.params, file, source, child.paramsStart);
297
+ }
298
+ fills.push({ name: child.name, ...(child.params !== undefined ? { params: child.params } : {}), nodes: lowerList(child.children) });
267
299
  }
268
300
  const rest = node.children.filter((c) => c.type !== 'fill');
269
301
  const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
302
+ if (children.length && fills.some((f) => f.name === 'default'))
303
+ fail('the default slot is filled twice: by @slot(\'default\') and by content outside any @slot', node.start);
270
304
  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 } : {}) });
305
+ 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
306
  return;
273
307
  }
274
308
  if (node.tag === 'slot') {
275
- if (stateful)
276
- fail('<slot /> is only supported in components without <script>', node.start);
309
+ if (stateful && scopeKey !== undefined)
310
+ 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
311
  let name = 'default';
312
+ const props = [];
278
313
  for (const a of node.attrs) {
279
314
  if (a.kind === 'static' && a.name === 'name' && typeof a.value === 'string' && a.value)
280
315
  name = a.value;
316
+ else if (a.kind === 'prop' && /^[A-Za-z_$][\w$]*$/.test(a.name)) {
317
+ checkExpr(a.expr, file, source, a.start + a.name.length + 4);
318
+ props.push({ name: a.name, expr: a.expr });
319
+ }
281
320
  else
282
- fail('<slot> only takes name="…"', a.start);
321
+ fail('<slot> only takes name="…", and the data it passes to its fill as [name]="expression"', a.start);
283
322
  }
284
323
  const fallback = [];
285
324
  const parent = out;
286
325
  out = fallback;
287
326
  node.children.forEach((child) => visit(child, rawText));
288
327
  out = parent;
289
- out.push({ kind: 'slot', name, fallback });
328
+ if (stateful && props.length)
329
+ fail('in an island, a slot passes no data: render the component outside the island to use [name]="…" on <slot>', node.start);
330
+ if (stateful && fallback.length)
331
+ fail('in an island, a slot has no fallback content', node.start);
332
+ out.push({ kind: 'slot', name, props, fallback });
290
333
  return;
291
334
  }
292
335
  const outerSelect = selectModel;
@@ -397,11 +440,19 @@ export function lower(parsed, file, source, options = {}) {
397
440
  const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
398
441
  const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
399
442
  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}` };
443
+ 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
444
  if (reactive)
402
445
  dynamic.push(node_);
403
446
  out.push(node_);
404
447
  }
448
+ else if (a.kind === 'prop' && a.name === 'use') {
449
+ if (!stateful)
450
+ fail('[use] needs a <script> (an island): behaviours run in the browser', a.start);
451
+ checkExpr(a.expr, file, source, a.start);
452
+ const index = useCount++;
453
+ emitStatic(` data-cl-u="${index}"`);
454
+ out.push({ kind: 'use', expr: a.expr, index });
455
+ }
405
456
  else if (a.kind === 'prop' && a.name === 'engine') {
406
457
  if (!stateful)
407
458
  fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
@@ -476,9 +527,25 @@ export function lower(parsed, file, source, options = {}) {
476
527
  stateful,
477
528
  nodes,
478
529
  events,
530
+ sends: parsed.events.length > 0,
531
+ contexts: parsed.contexts,
532
+ provides,
479
533
  warnings,
480
534
  };
481
535
  }
536
+ function slotParamsCheck(params, file, source, at) {
537
+ 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); };
538
+ try {
539
+ const node = parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' });
540
+ if (node.type !== 'ArrowFunctionExpression' || node.params?.length !== 1 || node.end !== params.length + 7)
541
+ bad();
542
+ }
543
+ catch (err) {
544
+ if (err instanceof ClarusError)
545
+ throw err;
546
+ bad();
547
+ }
548
+ }
482
549
  function pathSegments(path) {
483
550
  const root = /^[A-Za-z_$][\w$]*/.exec(path)?.[0];
484
551
  if (!root)
@@ -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,6 +190,9 @@ 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;
176
196
  nodes: TemplateNode[];
177
197
  };
178
198
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
@@ -8,7 +8,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
10
  export function parse(source, file) {
11
- const out = { inputs: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
11
+ const out = { inputs: [], events: [], contexts: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
12
12
  let i = 0;
13
13
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
14
14
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
@@ -17,8 +17,8 @@ export function parse(source, file) {
17
17
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
18
18
  const line = source.slice(i, end).trim();
19
19
  let m;
20
- if (/^@(input|model)\s/.test(line)) {
21
- return inputDecl(lineStart, line.startsWith('@model'));
20
+ if (/^@(input|model|context)\s/.test(line)) {
21
+ return inputDecl(lineStart, line.startsWith('@model'), line.startsWith('@context'));
22
22
  }
23
23
  else if (/^@(type|interface)\s/.test(line)) {
24
24
  return typeDecl(lineStart);
@@ -40,6 +40,20 @@ export function parse(source, file) {
40
40
  fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
41
41
  out.cssImports.push({ from: m[2], start: i });
42
42
  }
43
+ else if (/^@event(\s|$)/.test(line)) {
44
+ const d = /^@event\s+([A-Za-z_$][\w$-]*)\s*(?::\s*(\S[\s\S]*?))?\s*$/.exec(line);
45
+ if (!d)
46
+ fail('@event takes a name and the type of its value: @event change: string (or @event close for none)', i);
47
+ const nameStart = lineStart + line.indexOf(d[1], 6);
48
+ const typeStart = d[2] ? lineStart + line.lastIndexOf(d[2]) : nameStart;
49
+ out.events.push({ name: d[1], type: d[2] ?? 'void', start: i, nameStart, typeStart });
50
+ }
51
+ else if ((m = /^@layout(?:\s+(\S+))?\s*$/.exec(line))) {
52
+ if (m[1] !== 'none')
53
+ fail('@layout only takes none: @layout none renders the page without its folder and config layouts', i);
54
+ out.layout = 'none';
55
+ out.layoutStart = i;
56
+ }
43
57
  else
44
58
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
45
59
  i = end;
@@ -65,8 +79,8 @@ export function parse(source, file) {
65
79
  }
66
80
  return source.length;
67
81
  }
68
- function inputDecl(lineStart, model) {
69
- const directive = model ? '@model' : '@input';
82
+ function inputDecl(lineStart, model, context = false) {
83
+ const directive = context ? '@context' : model ? '@model' : '@input';
70
84
  const malformed = () => fail(`unknown or malformed directive "${directive}"`, i);
71
85
  let pos = lineStart + directive.length;
72
86
  while (source[pos] === ' ' || source[pos] === '\t')
@@ -117,7 +131,8 @@ export function parse(source, file) {
117
131
  malformed();
118
132
  fallback = { default: value, defaultStart: at };
119
133
  }
120
- out.inputs.push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
134
+ ;
135
+ (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
121
136
  i = end;
122
137
  }
123
138
  function typeDecl(lineStart) {
@@ -450,16 +465,18 @@ export function parse(source, file) {
450
465
  function fillBlock() {
451
466
  const start = i;
452
467
  i += 5;
453
- const { cond } = condition('@slot');
454
- const m = /^(['"])([\w-]+)\1$/.exec(cond);
468
+ const { cond, condStart } = condition('@slot');
469
+ const m = /^(['"])([\w-]+)\1\s*(?:,\s*([\s\S]*\S))?\s*$/.exec(cond);
455
470
  if (!m)
456
- fail(`@slot needs a quoted name, like @slot('aside')`, start);
471
+ fail(`@slot needs a quoted name, like @slot('aside'), or @slot('row', { item }) for a slot that passes data`, start);
472
+ const params = m[3];
473
+ const paramsStart = params === undefined ? undefined : condStart + cond.indexOf(params, m[1].length * 2 + m[2].length);
457
474
  while (/\s/.test(source[i] ?? ''))
458
475
  i++;
459
476
  if (source[i] !== '{')
460
477
  fail('expected { to open the block', i);
461
478
  i++;
462
- return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
479
+ return { type: 'fill', name: m[2], ...(params !== undefined ? { params, paramsStart } : {}), children: children({ tag: '@slot', start, block: true }), start };
463
480
  }
464
481
  function children(parent) {
465
482
  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
+ }
@@ -1,5 +1,5 @@
1
1
  import { effect, onDispose, state, untrack } from '../runtime/index.js';
2
- import { marked } from '../runtime/dom.js';
2
+ import { marked, openSlots, owner } from '../runtime/dom.js';
3
3
  import { browser } from '../runtime/env.js';
4
4
  const CONTAINERS = 'label, [data-cl-field], fieldset, cl-island';
5
5
  const FIELDS = 'input[data-cl-path],select[data-cl-path],textarea[data-cl-path]';
@@ -9,16 +9,28 @@ const read = (value, path) => path.split('.').reduce((v, k) => (v == null ? v :
9
9
  const dotted = (path = []) => path.map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
10
10
  function pathOf(field, root) {
11
11
  const parts = [];
12
+ let through = 0;
12
13
  for (let el = field; el && el !== root.parentElement; el = el.parentElement) {
13
14
  const here = el;
15
+ if (through && here.localName === 'cl-island') {
16
+ through--;
17
+ through += openSlots(here);
18
+ continue;
19
+ }
20
+ if (through) {
21
+ through += openSlots(here);
22
+ continue;
23
+ }
24
+ through += openSlots(here);
14
25
  let part = here.getAttribute('data-cl-path');
15
26
  if (part?.startsWith('@')) {
16
27
  const [model, ...rest] = part.slice(1).split('.');
17
- const island = here.parentElement?.closest(`[data-cl-path-${model}]`);
18
- if (!island)
28
+ const island = owner(here);
29
+ if (!island?.hasAttribute(`data-cl-path-${model}`))
19
30
  return '';
20
31
  part = [island.getAttribute(`data-cl-path-${model}`), ...rest].filter(Boolean).join('.');
21
32
  el = island;
33
+ through = openSlots(island);
22
34
  }
23
35
  if (part)
24
36
  parts.unshift(part);
@@ -30,3 +30,9 @@ export declare function spreadAttrs(obj: unknown, skip: readonly string[], tag?:
30
30
  set: [string, string | true | null][];
31
31
  dropped: [string, string][];
32
32
  };
33
+ /**
34
+ * The attributes a parent passed to a component (#463): its props with an attribute-like name that it doesn't declare
35
+ * as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
36
+ * @internal Compiled components call this.
37
+ */
38
+ export declare function passed(props: Record<string, unknown>, inputs: readonly string[]): Record<string, unknown>;
@@ -128,3 +128,19 @@ export function spreadAttrs(obj, skip, tag) {
128
128
  }
129
129
  return { set, dropped };
130
130
  }
131
+ // What a parent's attributes may set on a component's root (#463): attribute-like names only, so a page's load() data or
132
+ // a layout's path never become attributes.
133
+ const PASSED = /^(id|role|tabindex|hidden|lang|dir|style|(data|aria)-[\w:.-]+)$/;
134
+ /**
135
+ * The attributes a parent passed to a component (#463): its props with an attribute-like name that it doesn't declare
136
+ * as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
137
+ * @internal Compiled components call this.
138
+ */
139
+ export function passed(props, inputs) {
140
+ const out = {};
141
+ // Never clarusjs's own markers (data-cl-e, data-cl-u, data-cl-path…): passed data must not spoof the runtime's wiring.
142
+ for (const k in props)
143
+ if (PASSED.test(k) && !/^data-cl-/i.test(k) && !inputs.includes(k))
144
+ out[k] = props[k];
145
+ return out;
146
+ }