rosetack 0.1.1 → 0.1.2

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.
@@ -109,11 +109,14 @@ export function ifMark(
109
109
  scope?: unknown
110
110
  ): string {
111
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 …
112
+ // The content renders the FIRST time the block shows, never before: the eager version
113
+ // crashed `{#if user()}{user().name}{/if}` …
114
114
  let snap: { html: string; closes: Close[] } | null = null;
115
115
  closes.push(() => {
116
- if (!cond()) return null;
116
+ if (!cond()) {
117
+ snap = null;
118
+ return null;
119
+ }
117
120
  if (!snap) {
118
121
  const c: Close[] = [];
119
122
  snap = { html: String(fn(scope, c)), closes: c };
@@ -140,6 +143,28 @@ export function headMark(closes: Close[], fn: Close): string {
140
143
  return `<!--\u27e6h:${i}\u27e7-->` + fn() + `<!--\u27e6/h:${i}\u27e7-->`;
141
144
  }
142
145
 
146
+ /**
147
+ * P1-2 (bug report): TRUSTED HTML - the explicit reverse of esc(). `{@html x}`
148
+ * emits the value verbatim, so a CMS's rich text renders as markup instead of
149
+ * as escaped source.
150
+ *
151
+ * The markers are an {#if} block's on purpose: wire() already knows how to
152
+ * adopt the server's nodes in place (identity preserved - an embedded iframe
153
+ * does not reload) and to swap the range for a fresh parse when the value
154
+ * changes. Reusing that machinery costs this function and nothing else: no
155
+ * new marker kind, no new wire branch, no bytes in a document that never
156
+ * 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.
161
+ */
162
+ 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;
164
+ const r = closes[i](arg) as { html: string };
165
+ return `<!--\u27e6i:${i}\u27e7-->` + r.html + `<!--\u27e6/i:${i}\u27e7-->`;
166
+ }
167
+
143
168
  // === Reactive DOM wiring (client) ===
144
169
 
145
170
  const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
@@ -183,6 +208,9 @@ export const handlers: Record<string, (e: Event) => void> =
183
208
  */
184
209
  export function applyHead(html: string): void {
185
210
  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
+ const positional = new Map<string, number>();
186
214
  const frag = tpl(html);
187
215
  const title = frag.querySelector('title');
188
216
  if (title) {
@@ -198,12 +226,21 @@ export function applyHead(html: string): void {
198
226
  for (const el of Array.from(document.head.querySelectorAll(`[${HEAD_ATTR}]`))) el.remove();
199
227
  for (const el of Array.from(frag.children)) {
200
228
  if (el.tagName === 'TITLE') continue;
201
- const key = el.getAttribute('name')
229
+ 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
+ const identity = el.getAttribute('name')
202
233
  ?? el.getAttribute('property')
203
234
  ?? el.getAttribute('rel')
204
235
  ?? el.getAttribute('charset');
205
- if (!key) continue;
206
- const managed = `${el.tagName.toLowerCase()}:${key}`;
236
+ let managed: string;
237
+ if (identity) managed = `${tag}:${identity}`;
238
+ else if (el.id) managed = `${tag}:${el.id}`;
239
+ else {
240
+ const n = positional.get(tag) ?? 0;
241
+ positional.set(tag, n + 1);
242
+ managed = `${tag}:#${n}`;
243
+ }
207
244
  if (seen.has(managed)) continue; // first block wins: page over layout
208
245
  seen.add(managed);
209
246
  el.setAttribute(HEAD_ATTR, managed);
@@ -240,16 +277,24 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
240
277
  // Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
241
278
  // pass …
242
279
  const nested = new Set<Comment>();
280
+ const open: number[] = []; // positions of the open {#if}/{#each} starts
243
281
  for (let i = 0; i < comments.length; i++) {
244
282
  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
- }
283
+ if (m && (m[1] === 'i' || m[1] === 'l')) {
284
+ open.push(i);
285
+ continue;
286
+ }
287
+ const em = (comments[i].nodeValue ?? '').match(END_RE);
288
+ if (!em) continue;
289
+ const key = em[1] + em[2];
290
+ let at = -1;
291
+ for (let k = open.length - 1; k >= 0; k--) {
292
+ const om = (comments[open[k]].nodeValue ?? '').match(MARK_RE)!;
293
+ if (om[1] + om[2] === key) { at = k; break; }
252
294
  }
295
+ if (at < 0) continue; // an end with no open block: nothing to pair with
296
+ 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
253
298
  }
254
299
 
255
300
  const ends = new Map<number, Comment>();
@@ -319,7 +364,12 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
319
364
  st.__st = undefined;
320
365
  }
321
366
  const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
322
- if (!r) return;
367
+ 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
+ st.__ever = true;
371
+ return;
372
+ }
323
373
  // First run adopts the server-rendered content (move out, wire, move back -
324
374
  // identity preserved); later runs clone the block template.
325
375
  let frag: DocumentFragment;
@@ -439,6 +489,29 @@ export function clearRequestState(): void {
439
489
  pendingDeltas.clear();
440
490
  }
441
491
 
492
+ // === Request query (P0-1) === The parsed query string of the request being rendered
493
+ // (?page=2&q=x -> {page:'2',q:'x'}) …
494
+ let requestQuery: Record<string, string> = {};
495
+ let prefetchOverride: Record<string, string> | null = null;
496
+
497
+ export function $query(): Record<string, string> {
498
+ if (prefetchOverride) return prefetchOverride;
499
+ if (typeof location === 'undefined') return requestQuery;
500
+ const q: Record<string, string> = {};
501
+ new URLSearchParams(location.search).forEach((v, k) => { q[k] = v; });
502
+ return q;
503
+ }
504
+
505
+ /** The per-request query object - the servers call this before every render. */
506
+ export function setRequestQuery(q: Record<string, string>): void {
507
+ requestQuery = q;
508
+ }
509
+
510
+ /** The query of the route a prefetch is rendering, or null outside one. */
511
+ export function setPrefetchOverride(q: Record<string, string> | null): void {
512
+ prefetchOverride = q;
513
+ }
514
+
442
515
  // === Request context === A per-request bag: pages/_middleware.rose fills it
443
516
  // (getContext().user = ...) and $data, server actions and api handlers read it.
444
517
  let requestContext: Record<string, unknown> = {};
@@ -913,3 +986,38 @@ export function $sessionCookie(
913
986
  secure || sameSite === 'None' ? 'Secure' : '',
914
987
  ].filter(Boolean).join('; ');
915
988
  }
989
+
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
+ export function reportVitals(): void {
993
+ if (typeof window === 'undefined' || typeof performance === 'undefined') return;
994
+ const live: Record<string, number> = {};
995
+ (window as unknown as { __rosetack_vitals?: Record<string, number> }).__rosetack_vitals = live;
996
+ const send = (name: string, value: number) => {
997
+ live[name] = value;
998
+ window.dispatchEvent(new CustomEvent('rosetack:vitals', { detail: { name, value, route: location.pathname } }));
999
+ };
1000
+ const nav = performance.getEntriesByType?.('navigation')?.[0] as PerformanceNavigationTiming | undefined;
1001
+ if (nav) send('ttfb', Math.round(nav.responseStart));
1002
+ const paints = performance.getEntriesByType?.('paint') ?? [];
1003
+ const fcp = paints.find((p) => p.name === 'first-contentful-paint');
1004
+ if (fcp) send('fcp', Math.round(fcp.startTime));
1005
+ const PO = (window as unknown as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;
1006
+ if (!PO) return; // a browser without observers still gets ttfb/fcp above
1007
+ let cls = 0;
1008
+ let inp = 0;
1009
+ const flush = () => {
1010
+ if (cls) send('cls', Math.round(cls * 1000) / 1000);
1011
+ if (inp) send('inp', Math.round(inp));
1012
+ };
1013
+ document.addEventListener('visibilitychange', () => {
1014
+ if (document.visibilityState === 'hidden') flush();
1015
+ });
1016
+ new PO((list) => {
1017
+ for (const e of list.getEntries() as Array<PerformanceEntry & { value?: number; duration?: number; interactionId?: number }>) {
1018
+ if (e.entryType === 'layout-shift' && !(e as unknown as { hadRecentInput?: boolean }).hadRecentInput) cls += e.value ?? 0;
1019
+ if (e.entryType === 'event' && e.interactionId) inp = Math.max(inp, e.duration ?? 0);
1020
+ if (e.entryType === 'largest-contentful-paint') send('lcp', Math.round(e.startTime));
1021
+ }
1022
+ }).observe({ entryTypes: ['layout-shift', 'event', 'largest-contentful-paint'] });
1023
+ }
@@ -47,6 +47,15 @@ declare function $data<T>(fn: () => T | Promise<T>): Getter<T>;
47
47
  /** The per-request bag filled by `pages/_middleware.rose` (auth, db, cache). */
48
48
  declare function getContext<T = Record<string, unknown>>(): T;
49
49
 
50
+ /**
51
+ * The parsed query string of the request being rendered (`?page=2&q=x` ->
52
+ * `{ page: '2', q: 'x' }`). Read it in a `$data` body or in the render:
53
+ * routing matches the pathname, so `/search?q=cats` renders the `/search`
54
+ * route with `$query().q === 'cats'`. On a client-side navigation it is the
55
+ * URL the browser is on. A repeated key keeps its first value.
56
+ */
57
+ declare function $query(): Record<string, string>;
58
+
50
59
  /**
51
60
  * Translate a key from src/locales/<lang>.json.
52
61
  *