rosetack 0.1.0 → 0.1.1

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 (49) hide show
  1. package/dist-cli/compiler.mjs +2302 -0
  2. package/dist-cli/edge.mjs +297 -0
  3. package/dist-cli/rosetack.mjs +3411 -0
  4. package/dist-cli/runtime.mjs +619 -0
  5. package/dist-cli/test.mjs +2696 -0
  6. package/pack.mjs +49 -0
  7. package/package.json +25 -7
  8. package/src/FRAMEWORK_VERSION +1 -1
  9. package/src/cli/edge.ts +58 -23
  10. package/src/cli/index.ts +521 -65
  11. package/src/cli/shell.ts +75 -22
  12. package/src/cli/test.ts +400 -0
  13. package/src/compiler/index.ts +1277 -191
  14. package/src/runtime/index.ts +356 -65
  15. package/src/types/rosetack.d.ts +142 -0
  16. package/.github/workflows/ci.yml +0 -72
  17. package/.github/workflows/release.yml +0 -122
  18. package/benchmark.ts +0 -227
  19. package/example/public/favicon.ico +0 -0
  20. package/example/public/logo.svg +0 -148
  21. package/example/public/rose-mark-black.png +0 -0
  22. package/example/public/rose-mark.png +0 -0
  23. package/example/public/rose-mono.png +0 -0
  24. package/example/rosetack.config.js +0 -10
  25. package/example/src/locales/en.json +0 -8
  26. package/example/src/locales/zh.json +0 -8
  27. package/example/src/pages/404.rose +0 -15
  28. package/example/src/pages/500.rose +0 -10
  29. package/example/src/pages/[lang]/about.rose +0 -40
  30. package/example/src/pages/_layout.rose +0 -33
  31. package/example/src/pages/_middleware.rose +0 -37
  32. package/example/src/pages/about.rose +0 -67
  33. package/example/src/pages/admin.rose +0 -27
  34. package/example/src/pages/api/hello.rose +0 -19
  35. package/example/src/pages/api/login.rose +0 -55
  36. package/example/src/pages/api/posts.rose +0 -80
  37. package/example/src/pages/api/secret.rose +0 -14
  38. package/example/src/pages/blog/[id].rose +0 -25
  39. package/example/src/pages/broken.rose +0 -16
  40. package/example/src/pages/fresh.rose +0 -22
  41. package/example/src/pages/garden.rose +0 -27
  42. package/example/src/pages/index.rose +0 -84
  43. package/example/src/pages/sign.rose +0 -45
  44. package/example/src/pages/thorn.rose +0 -23
  45. package/example/src/pages/vault.rose +0 -14
  46. package/go.mod +0 -3
  47. package/main.go +0 -470
  48. package/tools/release-notes.mjs +0 -113
  49. package/tsconfig.json +0 -17
@@ -11,7 +11,7 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
11
11
 
12
12
  let currentEffect: (() => void) | null = null;
13
13
 
14
- // ponytail: global signal map, shared across all inlined modules
14
+ // Trade-off: global signal map, shared across all inlined modules
15
15
  let signalMap: Map<string, SignalEntry> =
16
16
  (globalThis as any).__rosetack_signalMap ?? new Map();
17
17
  (globalThis as any).__rosetack_signalMap = signalMap;
@@ -87,10 +87,65 @@ export function esc(v: unknown): string {
87
87
  return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
88
88
  }
89
89
 
90
+ // === Generated-code marker helpers === Every reactive marker in every generated module is
91
+ // emitted through these five functions …
92
+
93
+ type Close = (s?: unknown) => unknown;
94
+
95
+ export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unknown): string {
96
+ const i = closes.push(fn) - 1;
97
+ return `<!--\u27e6m:${i}\u27e7-->` + esc(closes[i](arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
98
+ }
99
+
100
+ export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
101
+ const i = closes.push(fn) - 1;
102
+ return `${name}="${esc(closes[i](arg))}" data-b="${i}:${name}"`;
103
+ }
104
+
105
+ export function ifMark(
106
+ closes: Close[],
107
+ cond: Close,
108
+ fn: (s: unknown, c: Close[]) => unknown,
109
+ scope?: unknown
110
+ ): string {
111
+ const i = closes.length;
112
+ // The content renders the FIRST time the block shows, never before, and is then memoized
113
+ // for this render: a block that never shows costs nothing and a block that shows renders …
114
+ let snap: { html: string; closes: Close[] } | null = null;
115
+ closes.push(() => {
116
+ if (!cond()) return null;
117
+ if (!snap) {
118
+ const c: Close[] = [];
119
+ snap = { html: String(fn(scope, c)), closes: c };
120
+ }
121
+ return snap;
122
+ });
123
+ const r = closes[i]() as { html: string } | null;
124
+ return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
125
+ }
126
+
127
+ export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
128
+ const i = closes.length;
129
+ closes.push(() => (items() as unknown[]).map((v) => {
130
+ const c: Close[] = [];
131
+ return { html: String(fn(v, c)), closes: c, scope: v };
132
+ }));
133
+ let h = `<!--\u27e6l:${i}\u27e7-->`;
134
+ for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
135
+ return h + `<!--\u27e6/l:${i}\u27e7-->`;
136
+ }
137
+
138
+ export function headMark(closes: Close[], fn: Close): string {
139
+ const i = closes.push(fn) - 1;
140
+ return `<!--\u27e6h:${i}\u27e7-->` + fn() + `<!--\u27e6/h:${i}\u27e7-->`;
141
+ }
142
+
90
143
  // === Reactive DOM wiring (client) ===
91
144
 
92
145
  const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
93
- const END_RE = /^\u27e6\/([ilh]):(\d+)\u27e7$/;
146
+ // `m` ends a text marker whose value is followed by literal text:
147
+ // the pair bounds exactly the value, so patching it cannot eat the prose.
148
+ const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
94
149
 
95
150
  // Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
96
151
  // must not be re-processed by the outer pass with the wrong closes array.
@@ -109,50 +164,51 @@ export function tpl(html: string): DocumentFragment {
109
164
  // head changes and user-authored <head> content is never touched.
110
165
  const HEAD_ATTR = 'data-rosetack-head';
111
166
 
167
+ // The delegated-event handler registry: every compiled module registers its handlers here
168
+ // (Object.assign(handlers, { ...
169
+ export const handlers: Record<string, (e: Event) => void> =
170
+ (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
171
+
112
172
  /**
113
- * Apply one rendered <head> block to the document: <title> replaces the title,
114
- * <meta>/<link>/<base> are matched by name/property/rel/charset and updated
115
- * in place (or created). `provided` accumulates the keys of every block in the
116
- * route's head (a page renders inside its layouts, so several blocks apply per
117
- * navigation); keys it stops providing are dropped from the document.
173
+ * Apply one route's whole <head> (every block of its chain, page first) to the
174
+ * document: <title> replaces the title, <meta>/<link>/<base> are matched by
175
+ * name/property/rel/charset. First occurrence of a key wins, so a page
176
+ * overrides its layouts - the same rule the server's mergeHeadBlocks applies,
177
+ * which is why the two halves agree without talking to each other.
178
+ *
179
+ * The managed set is REBUILT from the block rather than patched element by
180
+ * element: a route's head is the whole truth, so anything the previous route
181
+ * provided and this one does not is dropped, and a key that moved tags is
182
+ * replaced instead of duplicated. It is also a third of the code.
118
183
  */
119
- export function applyHead(html: string, provided: Set<string>): void {
184
+ export function applyHead(html: string): void {
185
+ const seen = new Set<string>();
120
186
  const frag = tpl(html);
121
- for (const el of Array.from(frag.children)) {
122
- const tag = el.tagName.toLowerCase();
123
- if (tag === 'title') {
124
- // Manage the title element directly: the document.title setter would update the FIRST
125
- // title element in tree order …
126
- let titleEl = document.head.querySelector('title');
127
- if (!titleEl) {
128
- titleEl = document.createElement('title');
129
- document.head.appendChild(titleEl);
130
- }
131
- titleEl.textContent = el.textContent ?? '';
132
- continue;
187
+ const title = frag.querySelector('title');
188
+ if (title) {
189
+ // Manage the title element directly: the document.title setter would update the FIRST
190
+ // title element in tree order …
191
+ let cur = document.head.querySelector('title');
192
+ if (!cur) {
193
+ cur = document.createElement('title');
194
+ document.head.appendChild(cur);
133
195
  }
134
- if (tag !== 'meta' && tag !== 'link' && tag !== 'base') continue;
196
+ cur.textContent = title.textContent ?? '';
197
+ }
198
+ for (const el of Array.from(document.head.querySelectorAll(`[${HEAD_ATTR}]`))) el.remove();
199
+ for (const el of Array.from(frag.children)) {
200
+ if (el.tagName === 'TITLE') continue;
135
201
  const key = el.getAttribute('name')
136
202
  ?? el.getAttribute('property')
137
203
  ?? el.getAttribute('rel')
138
204
  ?? el.getAttribute('charset');
139
205
  if (!key) continue;
140
- const managed = `${tag}:${key}`;
141
- provided.add(managed);
142
- let target = document.head.querySelector(`[${HEAD_ATTR}="${managed}"]`);
143
- if (!target) {
144
- target = document.createElement(tag);
145
- target.setAttribute(HEAD_ATTR, managed);
146
- document.head.appendChild(target);
147
- }
148
- for (const a of Array.from(el.attributes)) target.setAttribute(a.name, a.value);
149
- target.textContent = el.textContent;
206
+ const managed = `${el.tagName.toLowerCase()}:${key}`;
207
+ if (seen.has(managed)) continue; // first block wins: page over layout
208
+ seen.add(managed);
209
+ el.setAttribute(HEAD_ATTR, managed);
210
+ document.head.appendChild(el);
150
211
  }
151
- // Drop managed meta/link/base the new head no longer provides. The title
152
- // persists across routes that don't declare one (standard SPA behavior).
153
- document.head.querySelectorAll(`[${HEAD_ATTR}]`).forEach((el) => {
154
- if (!provided.has(el.getAttribute(HEAD_ATTR)!)) el.remove();
155
- });
156
212
  }
157
213
 
158
214
  /** Drop every rosetack-managed head element (routes without <head> blocks). */
@@ -181,19 +237,34 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
181
237
  const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
182
238
  while (walker.nextNode()) comments.push(walker.currentNode as Comment);
183
239
 
240
+ // Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
241
+ // pass …
242
+ const nested = new Set<Comment>();
243
+ for (let i = 0; i < comments.length; i++) {
244
+ const m = (comments[i].nodeValue ?? '').match(MARK_RE);
245
+ if (!m || (m[1] !== 'i' && m[1] !== 'l')) continue;
246
+ for (let j = i + 1; j < comments.length; j++) {
247
+ const em = (comments[j].nodeValue ?? '').match(END_RE);
248
+ if (em && em[1] === m[1] && +em[2] === +m[2]) {
249
+ for (let k = i + 1; k < j; k++) nested.add(comments[k]);
250
+ break;
251
+ }
252
+ }
253
+ }
254
+
184
255
  const ends = new Map<number, Comment>();
185
256
  for (const c of comments) {
257
+ if (nested.has(c)) continue;
186
258
  const m = (c.nodeValue ?? '').match(END_RE);
187
259
  if (m) ends.set(+m[2], c);
188
260
  }
189
261
 
190
- // Head blocks are collected during the walk and applied afterwards in REVERSE document
191
- // order: a page renders inside its layout's <slot/> …
262
+ // Head blocks are collected during the walk and applied afterwards as ONE effect over the
263
+ // whole route's head: the blocks render in document order …
192
264
  const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
193
- const headProvided = new Set<string>();
194
265
 
195
266
  for (const c of comments) {
196
- if (wired.has(c) || !c.parentNode) continue;
267
+ if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
197
268
  wired.add(c);
198
269
  const m = (c.nodeValue ?? '').match(MARK_RE);
199
270
  if (!m) continue;
@@ -214,13 +285,23 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
214
285
  }
215
286
  headBlocks.push({ idx, start: c, end, nodes });
216
287
  } else if (kind === 'm') {
217
- // Text: update the text node that follows the marker comment
288
+ // Text: update the text node that follows the marker comment. When the marker is a
289
+ // PAIR (value followed by literal text) …
218
290
  let target = c.nextSibling;
219
291
  if (!target || target.nodeType !== 3) {
220
292
  target = document.createTextNode('');
221
293
  c.parentNode!.insertBefore(target, c.nextSibling);
222
294
  }
223
295
  const tn = target as Text;
296
+ const end = ends.get(idx);
297
+ if (end) {
298
+ let n: ChildNode | null = tn.nextSibling;
299
+ while (n && n !== end) {
300
+ const nx = n.nextSibling;
301
+ n.remove();
302
+ n = nx;
303
+ }
304
+ }
224
305
  weff(() => {
225
306
  tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
226
307
  });
@@ -254,7 +335,9 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
254
335
  n = nx;
255
336
  }
256
337
  }
257
- const disp = wire(frag, r.closes, scope);
338
+ // r.scope is set by a named slot's block: its content is scoped to the object the child
339
+ // passed in, exactly like a list item.
340
+ const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
258
341
  const nodes = Array.from(frag.childNodes);
259
342
  const parent = anchor.parentNode!;
260
343
  for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
@@ -290,16 +373,22 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
290
373
  }
291
374
  }
292
375
 
293
- // Apply head blocks in reverse document order (page over layout), then drop the inert
294
- // placeholder nodes from the page body.
295
- for (let i = headBlocks.length - 1; i >= 0; i--) {
296
- const { idx, start, end, nodes } = headBlocks[i];
297
- weff(() => applyHead(String((closes[idx] as (s?: unknown) => unknown)(scope)), headProvided));
298
- nodes.forEach((nd) => nd.remove());
299
- start.remove();
300
- end.remove();
301
- }
302
- if (headBlocks.length === 0 && root.nodeType !== 11) clearHead();
376
+ // Apply head blocks, then drop the inert placeholder nodes from the page body. A
377
+ // top-level wire with no head blocks (route without <head>) clears the previous route's
378
+ // managed …
379
+ if (headBlocks.length > 0) {
380
+ const blocks = headBlocks;
381
+ weff(() => {
382
+ let html = '';
383
+ for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
384
+ applyHead(html);
385
+ });
386
+ for (const b of blocks) {
387
+ b.nodes.forEach((nd) => nd.remove());
388
+ b.start.remove();
389
+ b.end.remove();
390
+ }
391
+ } else if (root.nodeType !== 11) clearHead();
303
392
 
304
393
  // Attributes: data-b="K:attrName"
305
394
  const els = (holder as Element).querySelectorAll('[data-b]');
@@ -328,7 +417,7 @@ export function resetEffects(): void {
328
417
 
329
418
  // === Server Data Fetching ($data) ===
330
419
 
331
- // ponytail: cache keyed by function source, cleared per request/navigation.
420
+ // Trade-off: cache keyed by function source, cleared per request/navigation.
332
421
  // Upgrade path: explicit keys if two $data calls share identical source.
333
422
  let dataCache = new Map<string, Promise<unknown>>();
334
423
 
@@ -347,6 +436,7 @@ export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
347
436
  export function clearRequestState(): void {
348
437
  signalMap.clear();
349
438
  dataCache.clear();
439
+ pendingDeltas.clear();
350
440
  }
351
441
 
352
442
  // === Request context === A per-request bag: pages/_middleware.rose fills it
@@ -376,7 +466,7 @@ export function resetRequestContext(): void {
376
466
  * the captured disposers so the NEXT resetEffects() disposes them (a prefetch
377
467
  * render's cleanups firing early would dispose a route that was never
378
468
  * painted, and dropping them would leak the painted route's timers).
379
- * Concurrent prefetches are queued by the caller (ponytail: hover prefetches
469
+ * Concurrent prefetches are queued by the caller (trade-off: hover prefetches
380
470
  * are rare and cheap).
381
471
  */
382
472
  export async function isolateStateAsync<T>(
@@ -384,6 +474,8 @@ export async function isolateStateAsync<T>(
384
474
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
385
475
  const savedSignals = signalMap;
386
476
  const savedData = dataCache;
477
+ const savedDeltas = new Map(pendingDeltas); // a prefetch render must not consume a delta
478
+ pendingDeltas.clear();
387
479
  const savedMounts = mountQueue.splice(0, mountQueue.length);
388
480
  const savedCleanups = new Set(cleanups);
389
481
  cleanups.clear();
@@ -400,6 +492,8 @@ export async function isolateStateAsync<T>(
400
492
  } finally {
401
493
  signalMap = savedSignals;
402
494
  dataCache = savedData;
495
+ pendingDeltas.clear();
496
+ savedDeltas.forEach((d, k) => pendingDeltas.set(k, d)); // restore what was pending
403
497
  mountQueue.splice(0, 0, ...savedMounts); // prepend what was queued before
404
498
  cleanups.clear();
405
499
  savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
@@ -478,22 +572,55 @@ export function adoptCleanups(fns: Iterable<Cleanup>): void {
478
572
  for (const fn of fns) cleanups.add(fn);
479
573
  }
480
574
 
481
- // === i18n: localized routes (innovation #27) === Every JSON file in src/locales/ is a
482
- // language: { "key": "string" }.
575
+ // === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
576
+ // "string" }.
483
577
  let LOCALES: Record<string, Record<string, string>> = {};
484
578
  let DEFAULT_LOCALE = 'en';
579
+ // The locales this build did NOT bake in: they live at /locales/<lang>.json and
580
+ // ensureLocale() fetches one on first use.
581
+ let LOCALE_PACKS: string[] = [];
485
582
 
486
583
  export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
487
584
  LOCALES = dicts;
488
585
  DEFAULT_LOCALE = def;
489
586
  }
490
587
 
588
+ /** The locales the build left out of this bundle (generated code calls this). */
589
+ export function setLocalePacks(langs: string[]): void {
590
+ LOCALE_PACKS = langs;
591
+ }
592
+
593
+ /** Merge a dictionary that arrived at runtime - a fetched pack, or an app's own import(). */
594
+ export function loadLocale(lang: string, dict: Record<string, string>): void {
595
+ LOCALES[lang] = { ...LOCALES[lang], ...dict };
596
+ }
597
+
598
+ /**
599
+ * Resolve once `lang`'s dictionary is present: immediately for an inline
600
+ * locale, after one fetch for a runtime pack, never for an unknown one (the
601
+ * URL is the contract - the server 404s it). A failed fetch leaves the locale
602
+ * unresolved and $t falls back to the default language; the next navigation
603
+ * retries. This is the seam a bundled-per-locale app can bypass entirely by
604
+ * calling loadLocale() itself.
605
+ */
606
+ export async function ensureLocale(lang: string): Promise<void> {
607
+ if (LOCALES[lang] || !LOCALE_PACKS.includes(lang)) return;
608
+ try {
609
+ const res = await fetch(`/locales/${encodeURIComponent(lang)}.json`);
610
+ if (res.ok) loadLocale(lang, await res.json());
611
+ } catch {
612
+ // offline, or the pack is missing: the inline dictionaries still render
613
+ }
614
+ }
615
+
491
616
  export function localeList(): string[] {
492
617
  return Object.keys(LOCALES);
493
618
  }
494
619
 
495
620
  export function isLocale(lang: string): boolean {
496
- return Object.prototype.hasOwnProperty.call(LOCALES, lang);
621
+ // A pack counts as a known locale BEFORE it loads: the client router must
622
+ // not 404 /ar/about while /locales/ar.json is still in flight.
623
+ return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
497
624
  }
498
625
 
499
626
  /**
@@ -513,22 +640,70 @@ export function bestLocale(header: string | null | undefined): string | null {
513
640
  return null;
514
641
  }
515
642
 
643
+ /**
644
+ * Reading direction of a locale. The set of right-to-left scripts is closed
645
+ * (Arabic, Hebrew and their relatives), so a base-tag test covers every
646
+ * language that uses them - no per-app config, and the document's <html dir>
647
+ * is server-rendered correct for no-JS visitors. A regex LITERAL, not a
648
+ * string .split(): esbuild drops side-effect-free initializers, so an app
649
+ * whose scripts never call localeDir ships neither it nor the table.
650
+ */
651
+ const RTL_RE = /^(ar|fa|he|ur|ps|sd|ug|yi|ckb|dv|ks|prs|haz|mzn|nqo)/;
652
+ /** 'rtl' for a right-to-left locale, '' otherwise - '' is the html default. */
653
+ export function localeDir(lang: string): string {
654
+ return RTL_RE.test(lang) ? 'rtl' : '';
655
+ }
656
+
657
+ // --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
658
+ // {No signatures yet} one {# item} other {# items}} {n, selectordinal …
659
+ const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
660
+ const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
661
+
662
+ /** The CLDR category of `n` in `locale`, or null where Intl has no answer. */
663
+ function pluralCategory(locale: string, ordinal: boolean, n: number): string | null {
664
+ try {
665
+ return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
666
+ } catch {
667
+ return null; // no Intl.PluralRules, or an invalid tag: the English-ish fallback
668
+ }
669
+ }
670
+
671
+ /** Expand every ICU block of a message; leave the rest (and {name} holes) alone. */
672
+ function expandIcu(msg: string, vars: Record<string, string | number> | undefined, locale: string): string {
673
+ return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
674
+ const branches: Record<string, string> = {};
675
+ for (const m of branchText.matchAll(BRANCH_RE)) branches[m[1]] = m[2];
676
+ if (!branches.other) return whole; // no fallback arm: not valid ICU, render it verbatim
677
+ const v = vars?.[arg];
678
+ if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
679
+ const num = typeof v === 'number' ? v : Number(v);
680
+ // An =N arm wins over the category; a value with no number in it has no category at
681
+ // all, so it takes the other arm - and # prints the value as given …
682
+ const cat = isFinite(num)
683
+ ? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
684
+ : 'other';
685
+ return (branches[cat] ?? branches.other).replace(/#/g, String(v));
686
+ });
687
+ }
688
+
516
689
  /**
517
690
  * Translate a key for the current language. The [lang] route param arrives
518
691
  * as state before the render (the same seeding as any dynamic param), and
519
692
  * reading it through the signal getter makes $t reactive: switching locale
520
693
  * re-runs the marker, so only the translated nodes repaint.
521
694
  */
522
- export function $t(key: string, vars?: Record<string, string>): string {
695
+ export function $t(key: string, vars?: Record<string, string | number>): string {
523
696
  const [lang] = state('lang', DEFAULT_LOCALE);
524
697
  const dict = LOCALES[lang()] ?? LOCALES[DEFAULT_LOCALE] ?? {};
525
- let s = Object.prototype.hasOwnProperty.call(dict, key) ? dict[key] : key;
526
- if (vars) for (const k in vars) s = s.split(`{${k}}`).join(vars[k]);
527
- return s;
698
+ const msg = dict[key];
699
+ let out = expandIcu(typeof msg === 'string' ? msg : key, vars, lang());
700
+ if (vars) for (const k in vars) out = out.split(`{${k}}`).join(String(vars[k]));
701
+ return out;
528
702
  }
529
703
 
530
- // --- Phase 2: the shared server store ---------------------------------------- Module
531
- // scope (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds …
704
+ // --- the shared server store ---------------------------------------- Module scope
705
+ // (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds its
706
+ // own …
532
707
 
533
708
  const STORES = new Map<string, { value: unknown }>();
534
709
  let storeTransport: ((name: string, value: unknown) => void) | null = null;
@@ -579,8 +754,124 @@ export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void
579
754
  };
580
755
  }
581
756
 
582
- // --- Phase 1: cookie helpers ------------------------------------------------- Sessions
583
- // are the first thing every real app needs and the easiest thing to get subtly wrong …
757
+ // --- server action errors, guards and incremental patches -----------
758
+ //
759
+ // The action model's three gaps, closed with one request-scoped mechanism.
760
+ //
761
+ // 1. A standardized failure object. An action that cannot do its job (bad
762
+ // input, not signed in, a duplicate) throws ActionError; the dispatch
763
+ // catches it, seeds the page's state with it and re-renders, so the page
764
+ // answers with the failure VISIBLE (status = the error's code) instead of
765
+ // a 500 or a silent no-op. A bug still propagates to the 500 page.
766
+ // 2. A guard. `export async function beforeAction(name, form)` runs before
767
+ // every action of its page and vetoes with an ActionError - the
768
+ // action-level permission check (a redirect stays the middleware's job).
769
+ // 3. Incremental patches. A patch value may be an OPERATION ($append and
770
+ // friends) instead of a whole replacement, so growing a large list costs
771
+ // one row instead of a second copy of the list.
772
+
773
+ export class ActionError extends Error {
774
+ /** the HTTP status the response carries (400/401/403/409/422/...) */
775
+ code: number;
776
+ /** the form field the failure belongs to, when it belongs to one */
777
+ field?: string;
778
+ constructor(message: string, code = 400, field?: string) {
779
+ super(message);
780
+ this.name = 'ActionError';
781
+ this.code = code;
782
+ this.field = field;
783
+ }
784
+ }
785
+
786
+ /** The JSON-safe shape the dispatch seeds into state (what `$actionError()` returns). */
787
+ export type ActionErrorInfo = { action: string; message: string; code: number; field?: string };
788
+
789
+ /**
790
+ * The failure of the action that produced the response being rendered, or
791
+ * null. It is ordinary state under the key `actionError`, so the client's
792
+ * resumeState() restores it and the post-adopt re-render sees exactly what
793
+ * the server saw - one read, both sides, no hydration payload.
794
+ *
795
+ * Read it as data (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
796
+ * or let a {#boundary} contain it ($actionErrorOrThrow below).
797
+ */
798
+ export function $actionError(): ActionErrorInfo | null {
799
+ const e = signalMap.get('actionError');
800
+ if (!e) return null;
801
+ if (currentEffect) e.subs.add(currentEffect); // subscribe like a state read
802
+ return (e.value as ActionErrorInfo | null) ?? null;
803
+ }
804
+
805
+ /**
806
+ * What a {#boundary} whose content depends on an action calls first: when the
807
+ * action that produced this response failed, throw - the boundary's own catch
808
+ * turns it into the fallback, so the section degrades to the error message
809
+ * instead of rendering a widget built on work that never happened.
810
+ */
811
+ export function $actionErrorOrThrow(): void {
812
+ const info = $actionError();
813
+ if (info) throw new ActionError(info.message, info.code, info.field);
814
+ }
815
+
816
+ /** The {#boundary} fallback: the action's own message when the failure is a business one. */
817
+ export function $boundaryFallback(err: unknown): string {
818
+ if (err instanceof ActionError) return `<p class="rosetack-action-error">${esc(err.message)}</p>`;
819
+ return '<p>This section failed to render.</p>';
820
+ }
821
+
822
+ // An incremental patch: an action's return value may map a key to an OPERATION instead of a
823
+ // whole replacement value …
824
+ export type StateDeltaOp = 'append' | 'prepend' | 'merge';
825
+
826
+ export class StateDelta {
827
+ constructor(public op: StateDeltaOp, public value: unknown) {}
828
+ }
829
+
830
+ /** Append (or prepend) items to a list-valued state key. */
831
+ export const $append = (value: unknown): StateDelta => new StateDelta('append', value);
832
+ export const $prepend = (value: unknown): StateDelta => new StateDelta('prepend', value);
833
+ /** Shallow-merge an object into an object-valued state key. */
834
+ export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('merge', value);
835
+
836
+ const pendingDeltas = new Map<string, StateDelta>();
837
+
838
+ /** Record the deltas of the action that just ran (the dispatch calls this). */
839
+ export function setStateDelta(key: string, delta: StateDelta): void {
840
+ pendingDeltas.set(key, delta);
841
+ }
842
+
843
+ /**
844
+ * Apply every pending delta to the live state and clear them. The generated
845
+ * render calls this once, right after its state declarations - and only the
846
+ * SSR side ever emits the call: a delta is recorded by a server dispatch, so
847
+ * on the client (post-adopt re-render, client-side navigation, refresh) the
848
+ * map is empty and this is a no-op. That is also why a delta can never apply
849
+ * twice: the value it produced is what the state script carried, and the
850
+ * client resumes THAT instead of recomputing it.
851
+ */
852
+ export function applyStateDeltas(): void {
853
+ if (pendingDeltas.size === 0) return;
854
+ for (const [key, delta] of [...pendingDeltas]) {
855
+ pendingDeltas.delete(key);
856
+ applyStateDelta(key, delta);
857
+ }
858
+ }
859
+
860
+ /** Apply one delta to the live state. */
861
+ export function applyStateDelta(key: string, delta: StateDelta): void {
862
+ const cur = signalMap.get(key)?.value;
863
+ if (delta.op === 'merge') {
864
+ setState(key, { ...(cur as Record<string, unknown> | undefined), ...(delta.value as Record<string, unknown>) });
865
+ return;
866
+ }
867
+ const list = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
868
+ const merged =
869
+ delta.op === 'append' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
870
+ setState(key, merged);
871
+ }
872
+
873
+ // --- cookie helpers ------------------------------------------------- Sessions are the
874
+ // first thing every real app needs and the easiest thing to get subtly wrong …
584
875
 
585
876
  /**
586
877
  * Parse the cookies of a request (server) or of this document (client, where