rosetack 0.1.2 → 0.1.3

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/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +818 -445
  11. package/dist-cli/edge.mjs +115 -39
  12. package/dist-cli/rosetack.mjs +1078 -529
  13. package/dist-cli/runtime.mjs +115 -34
  14. package/dist-cli/test.mjs +875 -464
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/edge.ts +69 -61
  18. package/src/cli/index.ts +243 -328
  19. package/src/cli/prompt.ts +4 -1
  20. package/src/cli/shell.ts +67 -69
  21. package/src/cli/test.ts +9 -70
  22. package/src/compiler/index.ts +921 -851
  23. package/src/runtime/index.ts +155 -158
  24. package/src/types/rosetack.d.ts +16 -66
  25. package/templates/admin/package.json +14 -0
  26. package/templates/admin/rosetack.config.js +1 -0
  27. package/templates/admin/src/pages/_middleware.rose +33 -0
  28. package/templates/admin/src/pages/api/items.rose +37 -0
  29. package/templates/admin/src/pages/api/login.rose +25 -0
  30. package/templates/admin/src/pages/index.rose +79 -0
  31. package/templates/api/package.json +14 -0
  32. package/templates/api/rosetack.config.js +1 -0
  33. package/templates/api/src/pages/api/health.rose +7 -0
  34. package/templates/api/src/pages/api/items.rose +46 -0
  35. package/templates/api/src/pages/api/login.rose +24 -0
  36. package/templates/api/src/pages/index.rose +25 -0
  37. package/templates/blog/package.json +14 -0
  38. package/templates/blog/rosetack.config.js +1 -0
  39. package/templates/blog/src/pages/404.rose +2 -0
  40. package/templates/blog/src/pages/_layout.rose +42 -0
  41. package/templates/blog/src/pages/_middleware.rose +74 -0
  42. package/templates/blog/src/pages/admin.rose +85 -0
  43. package/templates/blog/src/pages/api/login.rose +46 -0
  44. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  45. package/templates/blog/src/pages/api/posts.rose +72 -0
  46. package/templates/blog/src/pages/index.rose +31 -0
  47. package/templates/blog/src/pages/post/[id].rose +36 -0
  48. package/templates/site/package.json +14 -0
  49. package/templates/site/rosetack.config.js +1 -0
  50. package/templates/site/src/pages/404.rose +2 -0
  51. package/templates/site/src/pages/_layout.rose +40 -0
  52. package/templates/site/src/pages/about.rose +6 -0
  53. package/templates/site/src/pages/index.rose +13 -0
  54. package/templates/site/src/pages/pricing.rose +8 -0
@@ -1,9 +1,4 @@
1
- /**
2
- * rosetack Runtime - Zero-hydration, compile-time reactivity
3
- * Target: < 2KB gzipped
4
- */
5
-
6
- // === Reactive Primitives ===
1
+ // rosetack Runtime - Zero-hydration, compile-time reactivity Target: < 2KB gzipped
7
2
 
8
3
  type Subscriber = () => void;
9
4
  type Cleanup = () => void;
@@ -11,12 +6,10 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
11
6
 
12
7
  let currentEffect: (() => void) | null = null;
13
8
 
14
- // Trade-off: global signal map, shared across all inlined modules
15
9
  let signalMap: Map<string, SignalEntry> =
16
10
  (globalThis as any).__rosetack_signalMap ?? new Map();
17
11
  (globalThis as any).__rosetack_signalMap = signalMap;
18
12
 
19
- // One get-or-create helper shared by state / setState / resumeState.
20
13
  function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subscriber> } {
21
14
  const e = signalMap.get(key) ?? { value: initial, subs: new Set<Subscriber>() };
22
15
  signalMap.set(key, e);
@@ -24,6 +17,7 @@ function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subsc
24
17
  }
25
18
 
26
19
  export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
20
+ ownerKeys()?.add(key);
27
21
  const e = entry(key, initial);
28
22
 
29
23
  const getter = () => {
@@ -49,16 +43,51 @@ export function setState<T>(key: string, value: T): void {
49
43
  e.subs.forEach((fn: Subscriber) => fn());
50
44
  }
51
45
 
52
- // Effects are tracked so client-side navigation can dispose the old ones.
53
- // Each cleanup removes itself, so locally disposed effects do not leak.
54
46
  const cleanups = new Set<Cleanup>();
55
47
 
48
+ let fxOwner: object | null = null;
49
+ const fxByOwner = new WeakMap<object, Set<Cleanup>>();
50
+ const keysByOwner = new WeakMap<object, Set<string>>();
51
+ const fxSet = (): Set<Cleanup> => {
52
+ if (!fxOwner) return cleanups;
53
+ let s = fxByOwner.get(fxOwner);
54
+ if (!s) { s = new Set(); fxByOwner.set(fxOwner, s); }
55
+ return s;
56
+ };
57
+ const ownerKeys = (): Set<string> | null => {
58
+ if (!fxOwner) return null;
59
+ let s = keysByOwner.get(fxOwner);
60
+ if (!s) { s = new Set(); keysByOwner.set(fxOwner, s); }
61
+ return s;
62
+ };
63
+
64
+ // Attribute everything the current render creates to `container` (null = the document's global bookkeeping).
65
+ export function setFxOwner(container: object | null): void {
66
+ fxOwner = container;
67
+ }
68
+
69
+ // Dispose everything ONE container created - its effects, its onCleanups, the state keys its render seeded.
70
+ export function resetContainerFx(container: object): void {
71
+ const set = fxByOwner.get(container);
72
+ if (set) {
73
+ set.forEach((fn: Cleanup) => fn());
74
+ fxByOwner.delete(container);
75
+ }
76
+ const keys = keysByOwner.get(container);
77
+ if (keys) {
78
+ keys.forEach((k: string) => signalMap.delete(k));
79
+ keysByOwner.delete(container);
80
+ }
81
+ dataCache.clear();
82
+ pendingDeltas.clear();
83
+ }
84
+
56
85
  export function effect(fn: () => void): Cleanup {
57
86
  const wrapped: Subscriber = () => {
58
87
  try {
59
88
  fn();
60
89
  } catch {
61
- // subscriber may be stale; ignore
90
+
62
91
  }
63
92
  };
64
93
  const prev = currentEffect;
@@ -67,14 +96,12 @@ export function effect(fn: () => void): Cleanup {
67
96
  currentEffect = prev;
68
97
  const cleanup: Cleanup = () => {
69
98
  signalMap.forEach((e: { subs: Set<Subscriber> }) => e.subs.delete(wrapped));
70
- cleanups.delete(cleanup);
99
+ fxSet().delete(cleanup);
71
100
  };
72
- cleanups.add(cleanup);
101
+ fxSet().add(cleanup);
73
102
  return cleanup;
74
103
  }
75
104
 
76
- // === HTML escaping (server-side interpolation safety) ===
77
-
78
105
  const ESC_MAP: Record<string, string> = {
79
106
  '&': '&amp;',
80
107
  '<': '&lt;',
@@ -87,19 +114,16 @@ export function esc(v: unknown): string {
87
114
  return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
88
115
  }
89
116
 
90
- // === Generated-code marker helpers === Every reactive marker in every generated module is
91
- // emitted through these five functions …
92
-
93
117
  type Close = (s?: unknown) => unknown;
94
118
 
95
119
  export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unknown): string {
96
120
  const i = closes.push(fn) - 1;
97
- return `<!--\u27e6m:${i}\u27e7-->` + esc(closes[i](arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
121
+ return `<!--\u27e6m:${i}\u27e7-->` + esc(fn(arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
98
122
  }
99
123
 
100
124
  export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
101
125
  const i = closes.push(fn) - 1;
102
- return `${name}="${esc(closes[i](arg))}" data-b="${i}:${name}"`;
126
+ return `${name}="${esc(fn(arg))}" data-b="${i}:${name}"`;
103
127
  }
104
128
 
105
129
  export function ifMark(
@@ -108,31 +132,25 @@ export function ifMark(
108
132
  fn: (s: unknown, c: Close[]) => unknown,
109
133
  scope?: unknown
110
134
  ): string {
111
- const i = closes.length;
112
- // The content renders the FIRST time the block shows, never before: the eager version
113
- // crashed `{#if user()}{user().name}{/if}` …
114
135
  let snap: { html: string; closes: Close[] } | null = null;
115
- closes.push(() => {
136
+ const i = closes.push(() => {
116
137
  if (!cond()) {
117
138
  snap = null;
118
139
  return null;
119
140
  }
120
141
  if (!snap) {
121
- const c: Close[] = [];
122
- snap = { html: String(fn(scope, c)), closes: c };
142
+ snap = { html: String(fn(scope, closes)), closes };
123
143
  }
124
144
  return snap;
125
- });
145
+ }) - 1;
126
146
  const r = closes[i]() as { html: string } | null;
127
147
  return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
128
148
  }
129
149
 
130
150
  export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
131
- const i = closes.length;
132
- closes.push(() => (items() as unknown[]).map((v) => {
133
- const c: Close[] = [];
134
- return { html: String(fn(v, c)), closes: c, scope: v };
135
- }));
151
+ const i = closes.push(() => (items() as unknown[]).map((v) => {
152
+ return { html: String(fn(v, closes)), closes, scope: v };
153
+ })) - 1;
136
154
  let h = `<!--\u27e6l:${i}\u27e7-->`;
137
155
  for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
138
156
  return h + `<!--\u27e6/l:${i}\u27e7-->`;
@@ -154,26 +172,43 @@ export function headMark(closes: Close[], fn: Close): string {
154
172
  * changes. Reusing that machinery costs this function and nothing else: no
155
173
  * new marker kind, no new wire branch, no bytes in a document that never
156
174
  * uses it. The close returns the same {html, closes} shape an {#if} block
157
- * does, with an EMPTY closes array - trusted HTML is opaque markup, the
158
- * compiler never scans inside it, so there are no inner markers to wire.
159
- * `arg` is the enclosing block's scope value, exactly as textMark takes it:
160
- * a `{@html row.body}` inside an {#each} resolves against the row.
175
+ * does, with the RENDER's array - trusted html is usually opaque markup
176
+ * with no markers inside, but when a loader's value was itself rendered
177
+ * inside this same pass (a theme skin built from another composable) the
178
+ * markers it carries belong to this array, and a nested wire() pass must be
179
+ * able to resolve them. `arg` is the enclosing block's scope value, exactly
180
+ * as textMark takes it: a `{@html row.body}` inside an {#each} resolves
181
+ * against the row.
161
182
  */
162
183
  export function rawMark(closes: Close[], fn: Close, arg?: unknown): string {
163
- const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes: [] })) - 1;
184
+ const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes })) - 1;
164
185
  const r = closes[i](arg) as { html: string };
165
186
  return `<!--\u27e6i:${i}\u27e7-->` + r.html + `<!--\u27e6/i:${i}\u27e7-->`;
166
187
  }
167
188
 
168
- // === Reactive DOM wiring (client) ===
189
+ /**
190
+ * A named slot's block. The child rendered its slot content into the
191
+ * render's shared array scoped to the slot object; the block wraps it in
192
+ * markers from the SAME index space, so the ids stay unique across the whole
193
+ * composition (a plain <slot/> inlines the children html directly and needs
194
+ * none of this). Lives here rather than in the compiler's emitted helper
195
+ * string so the array is the one the rest of the render uses.
196
+ */
197
+ export function slotBlockMark(
198
+ closes: Close[],
199
+ hit: { o: Record<string, unknown>; fn: (o: unknown, c: Close[]) => unknown } | null
200
+ ): string {
201
+ if (!hit) return '';
202
+ const i = closes.push(() => {
203
+ if (!hit) return null;
204
+ return { html: String(hit.fn(hit.o, closes)), closes, scope: hit.o };
205
+ }) - 1;
206
+ return `<!--\u27e6i:${i}\u27e7-->` + String(hit.fn(hit.o, closes)) + `<!--\u27e6/i:${i}\u27e7-->`;
207
+ }
169
208
 
170
209
  const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
171
- // `m` ends a text marker whose value is followed by literal text:
172
- // the pair bounds exactly the value, so patching it cannot eat the prose.
173
210
  const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
174
211
 
175
- // Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
176
- // must not be re-processed by the outer pass with the wrong closes array.
177
212
  const wired = new WeakSet<Node>();
178
213
 
179
214
  /** Parse an html string into a DocumentFragment. */
@@ -183,14 +218,8 @@ export function tpl(html: string): DocumentFragment {
183
218
  return t.content;
184
219
  }
185
220
 
186
- // === Document head (<head> blocks) ===
187
-
188
- // Marks the head elements rosetack manages, so stale ones can be removed when a route's
189
- // head changes and user-authored <head> content is never touched.
190
221
  const HEAD_ATTR = 'data-rosetack-head';
191
222
 
192
- // The delegated-event handler registry: every compiled module registers its handlers here
193
- // (Object.assign(handlers, { ...
194
223
  export const handlers: Record<string, (e: Event) => void> =
195
224
  (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
196
225
 
@@ -208,14 +237,10 @@ export const handlers: Record<string, (e: Event) => void> =
208
237
  */
209
238
  export function applyHead(html: string): void {
210
239
  const seen = new Set<string>();
211
- // tag -> how many unkeyed elements of that tag came before (the server's
212
- // mergeHeadBlocks counts the same way over the same block order)
213
240
  const positional = new Map<string, number>();
214
241
  const frag = tpl(html);
215
242
  const title = frag.querySelector('title');
216
243
  if (title) {
217
- // Manage the title element directly: the document.title setter would update the FIRST
218
- // title element in tree order …
219
244
  let cur = document.head.querySelector('title');
220
245
  if (!cur) {
221
246
  cur = document.createElement('title');
@@ -227,8 +252,6 @@ export function applyHead(html: string): void {
227
252
  for (const el of Array.from(frag.children)) {
228
253
  if (el.tagName === 'TITLE') continue;
229
254
  const tag = el.tagName.toLowerCase();
230
- // Bug report 2026.9.22 11:46: a head element with no name/property/rel/ charset
231
- // attribute used to be dropped here in silence …
232
255
  const identity = el.getAttribute('name')
233
256
  ?? el.getAttribute('property')
234
257
  ?? el.getAttribute('rel')
@@ -241,7 +264,7 @@ export function applyHead(html: string): void {
241
264
  positional.set(tag, n + 1);
242
265
  managed = `${tag}:#${n}`;
243
266
  }
244
- if (seen.has(managed)) continue; // first block wins: page over layout
267
+ if (seen.has(managed)) continue;
245
268
  seen.add(managed);
246
269
  el.setAttribute(HEAD_ATTR, managed);
247
270
  document.head.appendChild(el);
@@ -261,7 +284,6 @@ export function clearHead(): void {
261
284
  export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
262
285
  let holder: Node = root;
263
286
  if (root.nodeType === 11) {
264
- // DocumentFragment: wrap so querySelectorAll sees the root element too
265
287
  const div = document.createElement('div');
266
288
  div.appendChild(root);
267
289
  holder = div;
@@ -274,13 +296,12 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
274
296
  const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
275
297
  while (walker.nextNode()) comments.push(walker.currentNode as Comment);
276
298
 
277
- // Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
278
- // pass …
279
299
  const nested = new Set<Comment>();
280
- const open: number[] = []; // positions of the open {#if}/{#each} starts
300
+ const headPair = new Set<Comment>();
301
+ const open: number[] = [];
281
302
  for (let i = 0; i < comments.length; i++) {
282
303
  const m = (comments[i].nodeValue ?? '').match(MARK_RE);
283
- if (m && (m[1] === 'i' || m[1] === 'l')) {
304
+ if (m && (m[1] === 'i' || m[1] === 'l' || m[1] === 'h')) {
284
305
  open.push(i);
285
306
  continue;
286
307
  }
@@ -292,10 +313,16 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
292
313
  const om = (comments[open[k]].nodeValue ?? '').match(MARK_RE)!;
293
314
  if (om[1] + om[2] === key) { at = k; break; }
294
315
  }
295
- if (at < 0) continue; // an end with no open block: nothing to pair with
316
+ if (at < 0) continue;
317
+ const om = (comments[open[at]].nodeValue ?? '').match(MARK_RE)!;
318
+ if (om[1] === 'h') {
319
+ headPair.add(comments[open[at]]);
320
+ headPair.add(comments[i]);
321
+ }
296
322
  for (let k = open[at] + 1; k < i; k++) nested.add(comments[k]);
297
- open.length = at; // pop this block and any inner block left unclosed
323
+ open.length = at;
298
324
  }
325
+ for (const c of headPair) nested.delete(c);
299
326
 
300
327
  const ends = new Map<number, Comment>();
301
328
  for (const c of comments) {
@@ -304,21 +331,21 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
304
331
  if (m) ends.set(+m[2], c);
305
332
  }
306
333
 
307
- // Head blocks are collected during the walk and applied afterwards as ONE effect over the
308
- // whole route's head: the blocks render in document order …
309
334
  const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
310
335
 
336
+ const ownsHead = root === document.getElementById('app');
337
+
311
338
  for (const c of comments) {
312
339
  if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
313
- wired.add(c);
314
340
  const m = (c.nodeValue ?? '').match(MARK_RE);
315
341
  if (!m) continue;
316
342
  const kind = m[1];
317
343
  const idx = +m[2];
318
344
 
345
+ if (kind === 'h' && !ownsHead) continue;
346
+ wired.add(c);
347
+
319
348
  if (kind === 'h') {
320
- // Document head: the closure re-renders the <head> block (no inner
321
- // markers), so one effect drives title/meta for this route.
322
349
  const end = ends.get(idx);
323
350
  if (!end) continue;
324
351
  const nodes: ChildNode[] = [];
@@ -330,8 +357,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
330
357
  }
331
358
  headBlocks.push({ idx, start: c, end, nodes });
332
359
  } else if (kind === 'm') {
333
- // Text: update the text node that follows the marker comment. When the marker is a
334
- // PAIR (value followed by literal text) …
335
360
  let target = c.nextSibling;
336
361
  if (!target || target.nodeType !== 3) {
337
362
  target = document.createTextNode('');
@@ -351,8 +376,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
351
376
  tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
352
377
  });
353
378
  } else if (kind === 'i') {
354
- // Conditional block: first run adopts the server-rendered content in
355
- // place (node identity preserved); later runs swap in a fresh clone.
356
379
  const anchor = c;
357
380
  const end = ends.get(idx);
358
381
  if (!end) continue;
@@ -365,13 +388,9 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
365
388
  }
366
389
  const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
367
390
  if (!r) {
368
- // Hidden. The client has now evaluated this block once, so from here on whatever
369
- // sits between the anchors is client-rendered: a block the server left hidden …
370
391
  st.__ever = true;
371
392
  return;
372
393
  }
373
- // First run adopts the server-rendered content (move out, wire, move back -
374
- // identity preserved); later runs clone the block template.
375
394
  let frag: DocumentFragment;
376
395
  if (st.__ever) {
377
396
  frag = tpl(r.html);
@@ -385,16 +404,13 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
385
404
  n = nx;
386
405
  }
387
406
  }
388
- // r.scope is set by a named slot's block: its content is scoped to the object the child
389
- // passed in, exactly like a list item.
390
407
  const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
391
408
  const nodes = Array.from(frag.childNodes);
392
409
  const parent = anchor.parentNode!;
393
- for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
410
+ for (const nd of nodes) parent.insertBefore(nd, end);
394
411
  st.__st = { nodes, disp };
395
412
  });
396
413
  } else {
397
- // List: rebuild items between the start and end anchors
398
414
  const start = c;
399
415
  const end = ends.get(idx);
400
416
  if (!end) continue;
@@ -423,24 +439,22 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
423
439
  }
424
440
  }
425
441
 
426
- // Apply head blocks, then drop the inert placeholder nodes from the page body. A
427
- // top-level wire with no head blocks (route without <head>) clears the previous route's
428
- // managed …
429
- if (headBlocks.length > 0) {
430
- const blocks = headBlocks;
431
- weff(() => {
432
- let html = '';
433
- for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
434
- applyHead(html);
435
- });
436
- for (const b of blocks) {
437
- b.nodes.forEach((nd) => nd.remove());
438
- b.start.remove();
439
- b.end.remove();
440
- }
441
- } else if (root.nodeType !== 11) clearHead();
442
+ if (root === document.getElementById('app')) {
443
+ if (headBlocks.length > 0) {
444
+ const blocks = headBlocks;
445
+ weff(() => {
446
+ let html = '';
447
+ for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
448
+ applyHead(html);
449
+ });
450
+ for (const b of blocks) {
451
+ b.nodes.forEach((nd) => nd.remove());
452
+ b.start.remove();
453
+ b.end.remove();
454
+ }
455
+ } else if (root.nodeType !== 11) clearHead();
456
+ }
442
457
 
443
- // Attributes: data-b="K:attrName"
444
458
  const els = (holder as Element).querySelectorAll('[data-b]');
445
459
  els.forEach((el) => {
446
460
  const spec = el.getAttribute('data-b')!;
@@ -465,10 +479,6 @@ export function resetEffects(): void {
465
479
  cleanups.clear();
466
480
  }
467
481
 
468
- // === Server Data Fetching ($data) ===
469
-
470
- // Trade-off: cache keyed by function source, cleared per request/navigation.
471
- // Upgrade path: explicit keys if two $data calls share identical source.
472
482
  let dataCache = new Map<string, Promise<unknown>>();
473
483
 
474
484
  export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
@@ -481,16 +491,12 @@ export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
481
491
  return p as Promise<T>;
482
492
  }
483
493
 
484
- // Per-request isolation: state + data cache reset before each SSR render. The request
485
- // context bag is NOT reset here: it is owned by the middleware pass (runMiddleware) …
486
494
  export function clearRequestState(): void {
487
495
  signalMap.clear();
488
496
  dataCache.clear();
489
497
  pendingDeltas.clear();
490
498
  }
491
499
 
492
- // === Request query (P0-1) === The parsed query string of the request being rendered
493
- // (?page=2&q=x -> {page:'2',q:'x'}) …
494
500
  let requestQuery: Record<string, string> = {};
495
501
  let prefetchOverride: Record<string, string> | null = null;
496
502
 
@@ -512,8 +518,6 @@ export function setPrefetchOverride(q: Record<string, string> | null): void {
512
518
  prefetchOverride = q;
513
519
  }
514
520
 
515
- // === Request context === A per-request bag: pages/_middleware.rose fills it
516
- // (getContext().user = ...) and $data, server actions and api handlers read it.
517
521
  let requestContext: Record<string, unknown> = {};
518
522
 
519
523
  export function getContext(): Record<string, unknown> {
@@ -547,7 +551,7 @@ export async function isolateStateAsync<T>(
547
551
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
548
552
  const savedSignals = signalMap;
549
553
  const savedData = dataCache;
550
- const savedDeltas = new Map(pendingDeltas); // a prefetch render must not consume a delta
554
+ const savedDeltas = new Map(pendingDeltas);
551
555
  pendingDeltas.clear();
552
556
  const savedMounts = mountQueue.splice(0, mountQueue.length);
553
557
  const savedCleanups = new Set(cleanups);
@@ -566,8 +570,8 @@ export async function isolateStateAsync<T>(
566
570
  signalMap = savedSignals;
567
571
  dataCache = savedData;
568
572
  pendingDeltas.clear();
569
- savedDeltas.forEach((d, k) => pendingDeltas.set(k, d)); // restore what was pending
570
- mountQueue.splice(0, 0, ...savedMounts); // prepend what was queued before
573
+ savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
574
+ mountQueue.splice(0, 0, ...savedMounts);
571
575
  cleanups.clear();
572
576
  savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
573
577
  }
@@ -579,8 +583,6 @@ export function restoreState(entries: Map<string, SignalEntry>): void {
579
583
  entries.forEach((e: SignalEntry, k: string) => signalMap.set(k, e));
580
584
  }
581
585
 
582
- // === Serialization (for zero-hydration resume) ===
583
-
584
586
  export function serializeState(): string {
585
587
  const obj: Record<string, unknown> = {};
586
588
  signalMap.forEach((v: { value: unknown }, k: string) => (obj[k] = v.value));
@@ -598,8 +600,6 @@ export function resumeState(json: string): void {
598
600
  }
599
601
  }
600
602
 
601
- // === Client-side route refresh === The client entry registers the re-render here at boot;
602
- // components import refresh() like state() and call it from any handler …
603
603
  let refreshHook: (() => Promise<void>) | null = null;
604
604
 
605
605
  export function setRefreshHook(fn: () => Promise<void>): void {
@@ -610,12 +610,10 @@ export function refresh(): Promise<void> {
610
610
  return refreshHook ? refreshHook() : Promise.resolve();
611
611
  }
612
612
 
613
- // === Lifecycle === Client-only. onMount queues a callback; the client entry flushes the
614
- // queue after wire() completes - initial adoption, client-side navigation, prefetch paint …
615
613
  const mountQueue: Array<() => void> = [];
616
614
 
617
615
  export function onMount(fn: () => void): void {
618
- if (typeof document === 'undefined') return; // server render: nothing mounts
616
+ if (typeof document === 'undefined') return;
619
617
  mountQueue.push(fn);
620
618
  }
621
619
 
@@ -632,7 +630,7 @@ export function flushMounts(): void {
632
630
 
633
631
  /** Register a disposer for the current render (the effects' cleanup channel). */
634
632
  export function onCleanup(fn: Cleanup): void {
635
- cleanups.add(fn);
633
+ fxSet().add(fn);
636
634
  }
637
635
 
638
636
  /**
@@ -645,12 +643,8 @@ export function adoptCleanups(fns: Iterable<Cleanup>): void {
645
643
  for (const fn of fns) cleanups.add(fn);
646
644
  }
647
645
 
648
- // === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
649
- // "string" }.
650
646
  let LOCALES: Record<string, Record<string, string>> = {};
651
647
  let DEFAULT_LOCALE = 'en';
652
- // The locales this build did NOT bake in: they live at /locales/<lang>.json and
653
- // ensureLocale() fetches one on first use.
654
648
  let LOCALE_PACKS: string[] = [];
655
649
 
656
650
  export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
@@ -691,8 +685,6 @@ export function localeList(): string[] {
691
685
  }
692
686
 
693
687
  export function isLocale(lang: string): boolean {
694
- // A pack counts as a known locale BEFORE it loads: the client router must
695
- // not 404 /ar/about while /locales/ar.json is still in flight.
696
688
  return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
697
689
  }
698
690
 
@@ -713,6 +705,42 @@ export function bestLocale(header: string | null | undefined): string | null {
713
705
  return null;
714
706
  }
715
707
 
708
+ /** The signal `redirect()` throws. */
709
+ export class RoseRedirect extends Error {
710
+ readonly __rosetack = 'redirect';
711
+ constructor(readonly path: string, readonly status = 307) {
712
+ super(`redirect to ${path}`);
713
+ }
714
+ }
715
+
716
+ /** The signal `notFound()` throws. */
717
+ export class RoseNotFound extends Error {
718
+ readonly __rosetack = 'notFound';
719
+ constructor() {
720
+ super('notFound()');
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Send the visitor somewhere else: the response becomes a 30x with this
726
+ * Location. Call it from a page's `$data` body (a wall, a renamed slug, a
727
+ * canonical URL) or from an api handler. A route that calls it is buffered by
728
+ * the compiler, so the status can still be set.
729
+ */
730
+ export function redirect(path: string, status = 307): never {
731
+ throw new RoseRedirect(path, status);
732
+ }
733
+
734
+ /**
735
+ * Answer 404 with the app's own 404 route (pages/404.rose) instead of the
736
+ * built-in page. Call it from a page's `$data` body when the slug resolves to
737
+ * nothing - the status is a real 404 and the body is the app's design, which
738
+ * is the one thing a middleware wall cannot do from outside the render.
739
+ */
740
+ export function notFound(): never {
741
+ throw new RoseNotFound();
742
+ }
743
+
716
744
  /**
717
745
  * Reading direction of a locale. The set of right-to-left scripts is closed
718
746
  * (Arabic, Hebrew and their relatives), so a base-tag test covers every
@@ -727,8 +755,6 @@ export function localeDir(lang: string): string {
727
755
  return RTL_RE.test(lang) ? 'rtl' : '';
728
756
  }
729
757
 
730
- // --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
731
- // {No signatures yet} one {# item} other {# items}} {n, selectordinal …
732
758
  const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
733
759
  const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
734
760
 
@@ -737,7 +763,7 @@ function pluralCategory(locale: string, ordinal: boolean, n: number): string | n
737
763
  try {
738
764
  return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
739
765
  } catch {
740
- return null; // no Intl.PluralRules, or an invalid tag: the English-ish fallback
766
+ return null;
741
767
  }
742
768
  }
743
769
 
@@ -746,12 +772,10 @@ function expandIcu(msg: string, vars: Record<string, string | number> | undefine
746
772
  return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
747
773
  const branches: Record<string, string> = {};
748
774
  for (const m of branchText.matchAll(BRANCH_RE)) branches[m[1]] = m[2];
749
- if (!branches.other) return whole; // no fallback arm: not valid ICU, render it verbatim
775
+ if (!branches.other) return whole;
750
776
  const v = vars?.[arg];
751
777
  if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
752
778
  const num = typeof v === 'number' ? v : Number(v);
753
- // An =N arm wins over the category; a value with no number in it has no category at
754
- // all, so it takes the other arm - and # prints the value as given …
755
779
  const cat = isFinite(num)
756
780
  ? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
757
781
  : 'other';
@@ -774,10 +798,6 @@ export function $t(key: string, vars?: Record<string, string | number>): string
774
798
  return out;
775
799
  }
776
800
 
777
- // --- the shared server store ---------------------------------------- Module scope
778
- // (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds its
779
- // own …
780
-
781
801
  const STORES = new Map<string, { value: unknown }>();
782
802
  let storeTransport: ((name: string, value: unknown) => void) | null = null;
783
803
 
@@ -827,22 +847,6 @@ export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void
827
847
  };
828
848
  }
829
849
 
830
- // --- server action errors, guards and incremental patches -----------
831
- //
832
- // The action model's three gaps, closed with one request-scoped mechanism.
833
- //
834
- // 1. A standardized failure object. An action that cannot do its job (bad
835
- // input, not signed in, a duplicate) throws ActionError; the dispatch
836
- // catches it, seeds the page's state with it and re-renders, so the page
837
- // answers with the failure VISIBLE (status = the error's code) instead of
838
- // a 500 or a silent no-op. A bug still propagates to the 500 page.
839
- // 2. A guard. `export async function beforeAction(name, form)` runs before
840
- // every action of its page and vetoes with an ActionError - the
841
- // action-level permission check (a redirect stays the middleware's job).
842
- // 3. Incremental patches. A patch value may be an OPERATION ($append and
843
- // friends) instead of a whole replacement, so growing a large list costs
844
- // one row instead of a second copy of the list.
845
-
846
850
  export class ActionError extends Error {
847
851
  /** the HTTP status the response carries (400/401/403/409/422/...) */
848
852
  code: number;
@@ -871,7 +875,7 @@ export type ActionErrorInfo = { action: string; message: string; code: number; f
871
875
  export function $actionError(): ActionErrorInfo | null {
872
876
  const e = signalMap.get('actionError');
873
877
  if (!e) return null;
874
- if (currentEffect) e.subs.add(currentEffect); // subscribe like a state read
878
+ if (currentEffect) e.subs.add(currentEffect);
875
879
  return (e.value as ActionErrorInfo | null) ?? null;
876
880
  }
877
881
 
@@ -892,8 +896,6 @@ export function $boundaryFallback(err: unknown): string {
892
896
  return '<p>This section failed to render.</p>';
893
897
  }
894
898
 
895
- // An incremental patch: an action's return value may map a key to an OPERATION instead of a
896
- // whole replacement value …
897
899
  export type StateDeltaOp = 'append' | 'prepend' | 'merge';
898
900
 
899
901
  export class StateDelta {
@@ -943,9 +945,6 @@ export function applyStateDelta(key: string, delta: StateDelta): void {
943
945
  setState(key, merged);
944
946
  }
945
947
 
946
- // --- cookie helpers ------------------------------------------------- Sessions are the
947
- // first thing every real app needs and the easiest thing to get subtly wrong …
948
-
949
948
  /**
950
949
  * Parse the cookies of a request (server) or of this document (client, where
951
950
  * HttpOnly cookies are invisible by design - that is the point of HttpOnly).
@@ -987,8 +986,6 @@ export function $sessionCookie(
987
986
  ].filter(Boolean).join('; ');
988
987
  }
989
988
 
990
- // === Client observability: the web-vitals hook === A framework that sells TTFB, one
991
- // request and zero hydration owes the app a way to prove it in production.
992
989
  export function reportVitals(): void {
993
990
  if (typeof window === 'undefined' || typeof performance === 'undefined') return;
994
991
  const live: Record<string, number> = {};
@@ -1003,7 +1000,7 @@ export function reportVitals(): void {
1003
1000
  const fcp = paints.find((p) => p.name === 'first-contentful-paint');
1004
1001
  if (fcp) send('fcp', Math.round(fcp.startTime));
1005
1002
  const PO = (window as unknown as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;
1006
- if (!PO) return; // a browser without observers still gets ttfb/fcp above
1003
+ if (!PO) return;
1007
1004
  let cls = 0;
1008
1005
  let inp = 0;
1009
1006
  const flush = () => {