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
@@ -28,6 +28,17 @@ export type Ctx = Element | {
28
28
  start: Comment;
29
29
  end: Comment;
30
30
  };
31
+ /**
32
+ * The island that owns `node` (#465): its nearest <cl-island>, except that each slot range (`<!--[s-->…<!--]s-->`) it
33
+ * sits inside moves ownership one island outward, so content an island passes to another stays its own. Null when
34
+ * no island owns it. An [s the parser left without its ]s runs to the end of its parent.
35
+ * @internal
36
+ */
37
+ export declare function owner(node: Node): Element | null;
38
+ /** @internal An island's provide()s, for content another island re-renders inside it. */
39
+ export declare function provideOn(root: Element, cx: object): void;
40
+ /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
41
+ export declare function openSlots(n: Node): number;
31
42
  /** Hole markers in `ctx`, by index. @internal */
32
43
  export declare function holes(ctx: Ctx): Hole[];
33
44
  /** @if block markers in `ctx`, by index. @internal */
@@ -51,7 +62,7 @@ export declare function awaited(fn: () => unknown): {
51
62
  v(): unknown;
52
63
  };
53
64
  /** @internal Compiled components call this; apps don't. */
54
- export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
65
+ export declare function region(ctx: Ctx, index: number, html: (cx?: object) => string, wire: () => void, cx?: object): void;
55
66
  /**
56
67
  * A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
57
68
  * kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
@@ -76,6 +87,12 @@ export declare function text(hole: Hole, fn: () => unknown): void;
76
87
  * @internal Compiled components call this; apps don't.
77
88
  */
78
89
  export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
90
+ /**
91
+ * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
92
+ * function it returns runs when the branch, row or island goes.
93
+ * @internal Compiled components call this.
94
+ */
95
+ export declare function use(ctx: Ctx, index: number, get: () => unknown): void;
79
96
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
80
97
  export declare function marked(ctx: Ctx, selector: string): Element | undefined;
81
98
  /**
@@ -95,6 +112,21 @@ export declare function attr(ctx: Ctx, index: number, name: string, fn: () => un
95
112
  export declare function modelInput<T>(root: Element, name: string, initial: T): Signal<T> & {
96
113
  own(value: T): void;
97
114
  };
115
+ /**
116
+ * emit() in a component that declares @event (#442): a cancelable cl:event from the island to its parent's listener.
117
+ * False when the parent cancelled it ($info.cancel()).
118
+ * @internal Compiled components call this; apps don't.
119
+ */
120
+ export declare function emit(root: Element, name: string, value: unknown, info?: {
121
+ reason?: string;
122
+ event?: Event;
123
+ }): boolean;
124
+ /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
125
+ export declare function listen(ctx: Ctx, index: number, name: string, handler: (value: unknown, info: {
126
+ reason?: string;
127
+ event?: Event;
128
+ cancel(): void;
129
+ }) => void): void;
98
130
  /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
99
131
  export declare function model(ctx: Ctx, index: number, name: string, set: (value: unknown) => void): void;
100
132
  export {};
@@ -10,6 +10,57 @@ function inside(ctx, node) {
10
10
  return !!(ctx.start.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) &&
11
11
  !!(ctx.end.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_PRECEDING);
12
12
  }
13
+ /**
14
+ * The island that owns `node` (#465): its nearest <cl-island>, except that each slot range (`<!--[s-->…<!--]s-->`) it
15
+ * sits inside moves ownership one island outward, so content an island passes to another stays its own. Null when
16
+ * no island owns it. An [s the parser left without its ]s runs to the end of its parent.
17
+ * @internal
18
+ */
19
+ export function owner(node) {
20
+ let out = 0;
21
+ for (let n = node; n; n = n.parentNode) {
22
+ if (n !== node && n.localName === 'cl-island') {
23
+ if (!out)
24
+ return n;
25
+ out--;
26
+ }
27
+ out += openSlots(n);
28
+ }
29
+ return null;
30
+ }
31
+ // What each island provides (#465), for the components it holds that another island re-renders.
32
+ const provided = new WeakMap();
33
+ /** @internal An island's provide()s, for content another island re-renders inside it. */
34
+ export function provideOn(root, cx) { provided.set(root, cx); }
35
+ /**
36
+ * The context a region renders with: its island's own, plus what each island holding the region (it sits in their
37
+ * slot ranges, between them and `root`) provides, inner ones first. Spreading (Object.assign drops a __proto__ key)
38
+ * reads the getters now, so the region follows the values it read.
39
+ */
40
+ function contextAt(node, root, own) {
41
+ let cx;
42
+ for (let n = node.parentNode; n && n !== root; n = n.parentNode)
43
+ if (n.localName === 'cl-island')
44
+ cx = { ...provided.get(n), ...cx };
45
+ return cx ? { ...own, ...cx } : own;
46
+ }
47
+ /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
48
+ export function openSlots(n) {
49
+ let open = 0;
50
+ let closed = 0;
51
+ for (let s = n.previousSibling; s; s = s.previousSibling) {
52
+ if (s.nodeType !== 8)
53
+ continue;
54
+ const d = s.data;
55
+ if (d === ']s')
56
+ closed++;
57
+ else if (d === '[s')
58
+ closed ? closed-- : open++;
59
+ }
60
+ return open;
61
+ }
62
+ /** The island a context's root stands for: itself when it is one, else the island it is in (null: none). */
63
+ const islandOf = (root) => (root.localName === 'cl-island' ? root : owner(root));
13
64
  /**
14
65
  * Find every marker in `ctx`, skipping nested islands:
15
66
  * holes `<!--[N-->`, @if blocks `<!--[bN:K-->`, @for lists `<!--[fN-->` with rows `<!--[r-->` and `<!--[e-->`,
@@ -22,15 +73,7 @@ function scan(ctx) {
22
73
  const fors = [];
23
74
  const regions = [];
24
75
  const open = [];
25
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT, {
26
- acceptNode: (n) => n.nodeType === 8 ? NodeFilter.FILTER_ACCEPT
27
- : n !== root && n.localName === 'cl-island' ? NodeFilter.FILTER_REJECT
28
- : NodeFilter.FILTER_SKIP,
29
- });
30
- for (let n = walker.nextNode(); n; n = walker.nextNode()) {
31
- if (!inside(ctx, n))
32
- continue;
33
- const c = n;
76
+ const take = (c) => {
34
77
  const data = c.data;
35
78
  let m;
36
79
  const push = (kind, index = 0, k = 0) => open.push({ kind, index, k, start: c, rows: [], empty: null });
@@ -64,7 +107,31 @@ function scan(ctx) {
64
107
  parent.empty = { start: o.start, end: c };
65
108
  }
66
109
  }
67
- }
110
+ };
111
+ // One pass (#465): `level` counts the islands entered below this one, minus the slot ranges entered (each moves its
112
+ // content one island out), so the island's own comments are at 0 and nothing below 0 is (as owner() says, linearly).
113
+ const visit = (parent, level) => {
114
+ let ranges = 0;
115
+ for (let n = parent.firstChild; n; n = n.nextSibling) {
116
+ if (n.nodeType === 1)
117
+ level < 0 || visit(n, level + (n.localName === 'cl-island' ? 1 : 0));
118
+ else if (n.nodeType !== 8)
119
+ continue;
120
+ else if (n.data === '[s') {
121
+ ranges++;
122
+ level--;
123
+ }
124
+ else if (n.data === ']s') {
125
+ if (ranges) {
126
+ ranges--;
127
+ level++;
128
+ }
129
+ }
130
+ else if (!level && inside(ctx, n))
131
+ take(n);
132
+ }
133
+ };
134
+ visit(root, 0);
68
135
  return { holes, blocks, fors, regions };
69
136
  }
70
137
  /** Hole markers in `ctx`, by index. @internal */
@@ -164,7 +231,7 @@ export function awaited(fn) {
164
231
  return { k: () => k.get(), v: () => v };
165
232
  }
166
233
  /** @internal Compiled components call this; apps don't. */
167
- export function region(ctx, index, html, wire) {
234
+ export function region(ctx, index, html, wire, cx) {
168
235
  const r = scan(ctx).regions[index];
169
236
  if (!r)
170
237
  return;
@@ -172,7 +239,7 @@ export function region(ctx, index, html, wire) {
172
239
  let first = true;
173
240
  onDispose(() => dispose?.());
174
241
  effect(() => {
175
- const next = html();
242
+ const next = html(contextAt(r.start, rootOf(ctx), cx));
176
243
  untrack(() => {
177
244
  if (!first) {
178
245
  // A nested island with new props is updated in place (DOM and state kept), not replaced.
@@ -328,7 +395,7 @@ export function on(ctx, index, type, fn) {
328
395
  // An event that doesn't bubble (mouseenter, focus) is its target's alone, not its ancestors'.
329
396
  for (let el = e.target; el && el !== root.parentElement; el = e.bubbles ? el.parentElement : null) {
330
397
  const i = el.getAttribute?.('data-cl-e');
331
- if (i === null || i === undefined || el.closest('cl-island') !== root)
398
+ if (i === null || i === undefined || owner(el) !== root)
332
399
  continue;
333
400
  for (const h of [...(own.get(Number(i)) ?? [])])
334
401
  if (inside(h.ctx, el))
@@ -346,11 +413,28 @@ export function on(ctx, index, type, fn) {
346
413
  onDispose(() => { const at = list.indexOf(handler); if (at !== -1)
347
414
  list.splice(at, 1); }); // a removed branch or row stops listening
348
415
  }
416
+ /**
417
+ * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
418
+ * function it returns runs when the branch, row or island goes.
419
+ * @internal Compiled components call this.
420
+ */
421
+ export function use(ctx, index, get) {
422
+ const el = marked(ctx, `[data-cl-u="${index}"]`);
423
+ if (!el)
424
+ return;
425
+ for (const fn of [untrack(get)].flat()) {
426
+ if (typeof fn !== 'function')
427
+ continue;
428
+ const dispose = fn(el);
429
+ if (typeof dispose === 'function')
430
+ onDispose(dispose);
431
+ }
432
+ }
349
433
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
350
434
  export function marked(ctx, selector) {
351
435
  const root = rootOf(ctx);
352
- const island = root.closest('cl-island');
353
- return [...root.querySelectorAll(selector)].find((e) => e.closest('cl-island') === island && inside(ctx, e));
436
+ const island = islandOf(root);
437
+ return [...root.querySelectorAll(selector)].find((e) => owner(e) === island && inside(ctx, e));
354
438
  }
355
439
  /**
356
440
  * A reactive spread (#405): sets the attributes the object has, removes the ones it no longer has (only those it set:
@@ -426,8 +510,23 @@ export function modelInput(root, name, initial) {
426
510
  },
427
511
  };
428
512
  }
429
- /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
430
- export function model(ctx, index, name, set) {
513
+ /**
514
+ * emit() in a component that declares @event (#442): a cancelable cl:event from the island to its parent's listener.
515
+ * False when the parent cancelled it ($info.cancel()).
516
+ * @internal Compiled components call this; apps don't.
517
+ */
518
+ export function emit(root, name, value, info = {}) {
519
+ return root.dispatchEvent(new CustomEvent('cl:event', { detail: { name, value, ...info }, bubbles: true, cancelable: true }));
520
+ }
521
+ /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
522
+ export function listen(ctx, index, name, handler) {
523
+ fromChild(ctx, index, 'cl:event', name, (event, detail) => {
524
+ const { value, reason, event: cause } = detail;
525
+ handler(value, { reason, event: cause, cancel: () => event.preventDefault() });
526
+ });
527
+ }
528
+ /** Listen for `type` from the child island bound in region `index` only (not one nested in it), named `name`. */
529
+ function fromChild(ctx, index, type, name, take) {
431
530
  const r = scan(ctx).regions[index];
432
531
  if (!r)
433
532
  return;
@@ -438,13 +537,19 @@ export function model(ctx, index, name, set) {
438
537
  // Only from inside this region: 4 = the target follows the start marker, 2 = it precedes the end marker.
439
538
  if (detail.name !== name || !(r.start.compareDocumentPosition(from) & 4) || !(r.end.compareDocumentPosition(from) & 2))
440
539
  return;
441
- // Only the child island this region binds: an island nested in it, which nobody bound, keeps its own value.
442
- if (from.parentElement?.closest('cl-island') !== rootOf(ctx))
540
+ // Only the child island this region binds: an island nested in it, which nobody bound, keeps its own.
541
+ if (owner(from) !== rootOf(ctx))
443
542
  return;
444
- event.preventDefault();
445
543
  event.stopPropagation();
446
- set(detail.value);
544
+ take(event, detail);
447
545
  };
448
- host.addEventListener('cl:model', listen);
449
- onDispose(() => host.removeEventListener('cl:model', listen));
546
+ host.addEventListener(type, listen);
547
+ onDispose(() => host.removeEventListener(type, listen));
548
+ }
549
+ /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
550
+ export function model(ctx, index, name, set) {
551
+ fromChild(ctx, index, 'cl:model', name, (event, detail) => {
552
+ event.preventDefault(); // taken: the child's value follows the parent's state
553
+ set(detail.value);
554
+ });
450
555
  }
@@ -10,6 +10,12 @@ export declare function json(value: unknown): string;
10
10
  * @internal
11
11
  */
12
12
  export declare function spreadHtml(obj: unknown, skip: readonly string[], tag?: string, where?: string): string;
13
+ /**
14
+ * The attributes a parent passed to a component (#463), on its root: each through attrHtml, except the names the root
15
+ * writes itself (`skip`) and style (merged on its own). No spread checks needed: passed() keeps only attribute-like names.
16
+ * @internal
17
+ */
18
+ export declare function passedHtml(attrs: Record<string, unknown>, skip: readonly string[]): string;
13
19
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
14
20
  export declare function attrHtml(name: string, value: unknown, tag?: string): string;
15
21
  /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. @internal */
@@ -34,6 +34,18 @@ export function spreadHtml(obj, skip, tag, where) {
34
34
  }
35
35
  return set.map(([name, v]) => (v === null ? '' : v === true ? ` ${name}` : ` ${name}="${escape(v)}"`)).join('');
36
36
  }
37
+ /**
38
+ * The attributes a parent passed to a component (#463), on its root: each through attrHtml, except the names the root
39
+ * writes itself (`skip`) and style (merged on its own). No spread checks needed: passed() keeps only attribute-like names.
40
+ * @internal
41
+ */
42
+ export function passedHtml(attrs, skip) {
43
+ let out = '';
44
+ for (const k in attrs)
45
+ if (k !== 'style' && !skip.includes(k.toLowerCase()))
46
+ out += attrHtml(k, attrs[k]);
47
+ return out;
48
+ }
37
49
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
38
50
  export function attrHtml(name, value, tag) {
39
51
  const v = attrValue(name, value, tag);
@@ -1,5 +1,5 @@
1
1
  export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
2
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
5
  export { classValue, styleValue } from './attrs.ts';
@@ -1,6 +1,6 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
2
  export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput } from './dom.js';
3
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
6
  export { classValue, styleValue } from './attrs.js';
@@ -17,10 +17,21 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
17
17
  }
18
18
  return path;
19
19
  };
20
+ import { owner } from './dom.js';
20
21
  import { parse } from './serialize.js';
21
22
  import { scope } from './signals.js';
22
23
  // Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
23
24
  const loading = new WeakSet();
25
+ // Islands attaching now (attach="load"), so an island holding them waits for them (#465): content it re-renders
26
+ // inside them reads what they provide.
27
+ const pending = new WeakMap();
28
+ /** Does `inner` hold content of `el` in one of its slot ranges? */
29
+ function holds(inner, el) {
30
+ const walker = document.createTreeWalker(inner, 128); // comments
31
+ for (let n; (n = walker.nextNode());)
32
+ if (n.data === '[s' && owner(n.nextSibling) === el)
33
+ return true;
34
+ }
24
35
  const updates = new WeakMap();
25
36
  // Each attached island's disposer: everything its attach() wired (effects, listeners) is released by it.
26
37
  const attached = new Map();
@@ -36,7 +47,7 @@ function record(el) {
36
47
  const events = [];
37
48
  const listener = (e) => {
38
49
  const target = e.target;
39
- if (!target || target.closest?.('cl-island') !== el)
50
+ if (!target || owner(target) !== el)
40
51
  return;
41
52
  if (HOLD.has(e.type))
42
53
  e.preventDefault();
@@ -105,10 +116,20 @@ async function attachOne(el, load, recorded) {
105
116
  props = parse(el.getAttribute('p') ?? '{}');
106
117
  const s = el.getAttribute('s');
107
118
  state = s === null ? undefined : parse(s);
119
+ // Islands in it holding its content attach first (#465): content it re-renders there reads what they provide. One
120
+ // failing to load fails this one too (both retry). ponytail: later ones (idle, visible, interaction) aren't waited for.
121
+ for (const inner of el.querySelectorAll('cl-island')) {
122
+ if (!pending.has(inner) || !holds(inner, el))
123
+ continue;
124
+ await pending.get(inner);
125
+ if (!pending.has(inner))
126
+ throw 0;
127
+ }
108
128
  }
109
129
  catch (err) {
110
130
  recorded.stop();
111
131
  loading.delete(el); // network or parse failure: the next attachAll() retries
132
+ pending.delete(el);
112
133
  console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
113
134
  return;
114
135
  }
@@ -151,8 +172,11 @@ export async function attachAll(root = document, load = lastLoad) {
151
172
  for (const el of islands) {
152
173
  loading.add(el);
153
174
  const recorded = record(el);
154
- if ((el.getAttribute('a') ?? 'load') === 'load')
155
- now.push(attachOne(el, load, recorded));
175
+ if ((el.getAttribute('a') ?? 'load') === 'load') {
176
+ const p = attachOne(el, load, recorded);
177
+ pending.set(el, p);
178
+ now.push(p);
179
+ }
156
180
  else
157
181
  schedule(el, () => void attachOne(el, load, recorded));
158
182
  }
@@ -195,8 +219,10 @@ function arrive() {
195
219
  ;
196
220
  globalThis.__clUpdate = (el, next) => {
197
221
  const update = updates.get(el);
198
- // The same component: the same name and the same source (two panel.tscl files share a name).
199
- if (!update || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
222
+ // The same component: the same name and the same source (two panel.tscl files share a name). An attached island
223
+ // without inputs has nothing to update (#465: re-rendered because the content it holds changed, which its parent
224
+ // wires in place).
225
+ if (!attached.has(el) || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
200
226
  return false;
201
227
  const p = next.getAttribute('p') ?? '{}';
202
228
  el.setAttribute('p', p);
@@ -207,7 +233,7 @@ globalThis.__clUpdate = (el, next) => {
207
233
  for (const { name, value } of [...next.attributes])
208
234
  if (name.startsWith('data-cl-path-'))
209
235
  el.setAttribute(name, value);
210
- update(parse(p));
236
+ update?.(parse(p));
211
237
  return true;
212
238
  };
213
239
  globalThis.__clAttach = (root, navigated) => {
@@ -3,7 +3,12 @@ type Entry = {
3
3
  r: string;
4
4
  };
5
5
  type Page = {
6
- render(props: object): string;
6
+ render(props: object, slots?: undefined, opts?: {
7
+ route: {
8
+ path: string;
9
+ params: Record<string, string>;
10
+ };
11
+ }): string;
7
12
  };
8
13
  /** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
9
14
  export declare function matchRoute(table: Entry[], pathname: string): {
@@ -64,7 +64,7 @@ isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(
64
64
  return false;
65
65
  // The head stays (its stylesheets are every client page's, linked by the shell); the title gets the site's
66
66
  // titleTemplate, from the shell (always set: '%s' without one).
67
- await swapIn(page.render(props), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
67
+ await swapIn(page.render(props, undefined, { route: { path: url.pathname, params: found.params } }), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
68
68
  return true;
69
69
  }
70
70
  /**
@@ -1,12 +1,13 @@
1
1
  import { attrHtml } from './html.ts';
2
- export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.ts';
3
- export { classValue, styleValue } from './attrs.ts';
2
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.ts';
3
+ export { classValue, styleValue, passed } from './attrs.ts';
4
4
  /**
5
5
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
6
6
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
7
7
  * @internal Compiled components call this; apps don't.
8
8
  */
9
9
  export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string;
10
+ export declare function island(name: string, src: string, props: Record<string, unknown>, html: string | Promise<string>, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string | Promise<string>;
10
11
  /**
11
12
  * The parts of a template level that calls components or places slots (#430): joined into a string, or into a
12
13
  * promise of one when a part is a promise (a component that awaits in its <script server>). @internal
@@ -17,6 +18,11 @@ export declare function join(parts: unknown[]): string | Promise<string>;
17
18
  * with the error; without @catch, a rejection fails the render. @internal
18
19
  */
19
20
  export declare function awaitHtml(promise: unknown, then: ((v: unknown) => string | Promise<string>) | null, caught: ((e: unknown) => string | Promise<string>) | null): Promise<string>;
21
+ /**
22
+ * A slot's HTML (#455): its fill, a function called with what the slot passes and the context at the slot (#465), or
23
+ * the fallback when nothing fills it. A string fill (hand-built slots) is used as is. @internal
24
+ */
25
+ export declare function slot(fill: unknown, data: object | undefined, fallback: () => string | Promise<string>, cx?: object): string | Promise<string>;
20
26
  /** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
21
27
  export declare function sync(html: string | Promise<string>, child: string, island: string): string;
22
28
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
@@ -1,14 +1,12 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
- export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.js';
5
- export { classValue, styleValue } from './attrs.js';
6
- /**
7
- * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
8
- * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
9
- * @internal Compiled components call this; apps don't.
10
- */
4
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.js';
5
+ export { classValue, styleValue, passed } from './attrs.js';
11
6
  export function island(name, src, props, html, state, attach, paths) {
7
+ // Slot content that awaits (#430) makes the island's HTML a promise: wrap it once it's there.
8
+ if (html instanceof Promise)
9
+ return html.then((h) => island(name, src, props, h, state, attach, paths));
12
10
  const s = state === undefined ? '' : ` s="${escape(toBrowser(state))}"`;
13
11
  const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
14
12
  // A component bound two ways carries each binding's path for the forms engine (clarusjs/forms), given by its parent.
@@ -38,6 +36,15 @@ export async function awaitHtml(promise, then, caught) {
38
36
  }
39
37
  return then ? then(value) : '';
40
38
  }
39
+ /**
40
+ * A slot's HTML (#455): its fill, a function called with what the slot passes and the context at the slot (#465), or
41
+ * the fallback when nothing fills it. A string fill (hand-built slots) is used as is. @internal
42
+ */
43
+ export function slot(fill, data, fallback, cx) {
44
+ if (fill === undefined || fill === null)
45
+ return fallback();
46
+ return typeof fill === 'function' ? fill(data ?? {}, cx) : fill;
47
+ }
41
48
  /** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
42
49
  export function sync(html, child, island) {
43
50
  if (typeof html === 'string')
@@ -1,7 +1,12 @@
1
1
  import { type ModeTable } from './modes.ts';
2
2
  import { type HeadOptions, type SiteOptions } from './head.ts';
3
3
  type PageModule = {
4
- render(props?: object): string | Promise<string>;
4
+ render(props?: object, slots?: undefined, opts?: {
5
+ route: {
6
+ path: string;
7
+ params: Record<string, string>;
8
+ };
9
+ }): string | Promise<string>;
5
10
  };
6
11
  type Params = Record<string, string>;
7
12
  /**
@@ -67,6 +72,24 @@ export type LoadContext = {
67
72
  cookies: Cookies;
68
73
  locals: Locals;
69
74
  };
75
+ /**
76
+ * What a folder's `+guard.ts` gets (#457): the page's load() context plus the URL. Return a `Response` (such as
77
+ * `redirect()`) to answer instead of the page, or nothing to go on; it may set `locals` for what runs after it.
78
+ *
79
+ * ```ts
80
+ * // src/pages/admin/+guard.ts
81
+ * export function guard({ locals, url }: GuardContext) {
82
+ * if (!locals.user) return redirect('/sign-in?next=' + encodeURIComponent(url.pathname))
83
+ * }
84
+ * ```
85
+ * @see https://clarusjs.com/guide/auth
86
+ */
87
+ export type GuardContext = LoadContext & {
88
+ url: URL;
89
+ };
90
+ type GuardModule = {
91
+ guard?(context: GuardContext): Response | void | undefined | Promise<Response | void | undefined>;
92
+ };
70
93
  /**
71
94
  * `handle()` in src/server.ts: runs once per request before any page loads, to resolve the session into `locals`.
72
95
  * Returning a Response (such as `redirect('/login')`) answers the request instead.
@@ -118,11 +141,15 @@ export type EndpointModule = Partial<Record<'GET' | 'HEAD' | 'POST' | 'PUT' | 'P
118
141
  */
119
142
  export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
120
143
  /** @internal clarusjs's own build and server code call this; apps don't. */
144
+ export declare function isPageFile(file: string): boolean;
145
+ /** @internal clarusjs's own build and server code call this; apps don't. */
121
146
  export declare function routeFromFile(file: string): string;
122
147
  /** @internal clarusjs's own build and server code call this; apps don't. */
123
148
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
124
149
  loaderUrl?: string;
125
150
  data?: Record<string, () => Promise<DataModule>>;
151
+ /** Folder guards (#457): each src/pages folder's +guard.ts → its module. */
152
+ guards?: Record<string, () => Promise<GuardModule>>;
126
153
  modes?: ModeTable;
127
154
  /** Client routes (as their files name them) → URL of the page's browser render module. */
128
155
  client?: Record<string, string>;
@@ -23,15 +23,20 @@ function compile(path) {
23
23
  export function redirect(to, status = 302) {
24
24
  return new Response(null, { status, headers: { location: to } });
25
25
  }
26
+ export function isPageFile(file) {
27
+ return !/\/\+[^/]*$/.test(file);
28
+ }
26
29
  export function routeFromFile(file) {
27
30
  const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
28
31
  return path || '/';
29
32
  }
30
33
  export function createHandler(pages, options = {}) {
31
34
  const routes = Object.entries(pages)
35
+ .filter(([file]) => isPageFile(file))
32
36
  .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
33
37
  .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
34
38
  const endpointRoutes = Object.entries(options.endpoints ?? {})
39
+ .filter(([file]) => isPageFile(file))
35
40
  .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
36
41
  .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
37
42
  const matchEndpoint = (pathname) => {
@@ -49,6 +54,26 @@ export function createHandler(pages, options = {}) {
49
54
  return undefined;
50
55
  };
51
56
  const data = options.data ?? {};
57
+ const guards = options.guards ?? {};
58
+ async function guarded(file, once, context) {
59
+ const folders = file.replace(/^\/?src\/pages\//, '').split('/').slice(0, -1);
60
+ for (let i = 0; i <= folders.length; i++) {
61
+ const key = `/src/pages/${[...folders.slice(0, i), '+guard.ts'].join('/')}`;
62
+ if (!guards[key])
63
+ continue;
64
+ try {
65
+ const mod = await guards[key]();
66
+ const route = routeFromFile(`/${file.replace(/^\//, '')}`);
67
+ const answer = await mod.guard?.({ ...context, url: new URL(context.request.url), ...(once ? builtOnce(route, context.request) : {}) });
68
+ if (answer instanceof Response)
69
+ return answer;
70
+ }
71
+ catch (err) {
72
+ throw new Error(`${key.slice(1)}: guard() failed: ${err?.message ?? err}`, { cause: err });
73
+ }
74
+ }
75
+ return undefined;
76
+ }
52
77
  const modes = options.modes ?? {};
53
78
  const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
54
79
  function match(pathname) {
@@ -166,6 +191,16 @@ export function createHandler(pages, options = {}) {
166
191
  const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path;
167
192
  const found = !match(trimmed) && matchEndpoint(trimmed);
168
193
  if (found) {
194
+ try {
195
+ const stop = await guarded(found.route.file, false, { request, params: found.params, cookies, locals });
196
+ if (stop)
197
+ return stop;
198
+ }
199
+ catch (err) {
200
+ if (options.dev)
201
+ throw err;
202
+ return failure(err.message);
203
+ }
169
204
  const response = await callEndpoint(found.route.file, await found.route.load(), { request, params: found.params, cookies, locals }, options);
170
205
  if (response)
171
206
  return response;
@@ -247,6 +282,14 @@ export function createHandler(pages, options = {}) {
247
282
  }
248
283
  return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
249
284
  }
285
+ try {
286
+ const stop = await guarded(found.route.file, modeFor(found.route.path, modes) !== 'server', { params: found.params, locals, request, cookies });
287
+ if (stop)
288
+ return stop;
289
+ }
290
+ catch (err) {
291
+ return fail(err.message, err);
292
+ }
250
293
  let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
251
294
  const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
252
295
  const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
@@ -299,7 +342,7 @@ export function createHandler(pages, options = {}) {
299
342
  let html;
300
343
  try {
301
344
  const module = await found.route.load();
302
- html = await loadedStore.run(componentData, () => module.render(props));
345
+ html = await loadedStore.run(componentData, () => module.render(props, undefined, { route: { path: pathname, params: found.params } }));
303
346
  }
304
347
  catch (err) {
305
348
  return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);