@verajs/renderer 0.1.4 → 0.2.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 (42) hide show
  1. package/README.md +1000 -12
  2. package/dist/development/vera-renderer-hydrate.d.ts +32 -13
  3. package/dist/development/vera-renderer-hydrate.d.ts.map +1 -1
  4. package/dist/development/vera-renderer-hydrate.js +1812 -234
  5. package/dist/development/vera-renderer-hydrate.js.map +1 -1
  6. package/dist/development/vera-renderer-keyed.d.ts +17 -0
  7. package/dist/development/vera-renderer-keyed.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-keyed.js +322 -0
  9. package/dist/development/vera-renderer-keyed.js.map +1 -0
  10. package/dist/development/vera-renderer-profiler.d.ts +57 -17
  11. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  12. package/dist/development/vera-renderer-profiler.js +1445 -209
  13. package/dist/development/vera-renderer-profiler.js.map +1 -1
  14. package/dist/development/vera-renderer-slots.d.ts +103 -0
  15. package/dist/development/vera-renderer-slots.d.ts.map +1 -0
  16. package/dist/development/vera-renderer-slots.js +1387 -0
  17. package/dist/development/vera-renderer-slots.js.map +1 -0
  18. package/dist/development/vera-renderer-spread.d.ts +51 -0
  19. package/dist/development/vera-renderer-spread.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-spread.js +499 -0
  21. package/dist/development/vera-renderer-spread.js.map +1 -0
  22. package/dist/development/vera-renderer-tag.d.ts +61 -0
  23. package/dist/development/vera-renderer-tag.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-tag.js +727 -0
  25. package/dist/development/vera-renderer-tag.js.map +1 -0
  26. package/dist/development/vera-renderer.d.ts +41 -16
  27. package/dist/development/vera-renderer.d.ts.map +1 -1
  28. package/dist/development/vera-renderer.js +1375 -200
  29. package/dist/development/vera-renderer.js.map +1 -1
  30. package/dist/vera-renderer-hydrate.min.js +1 -1
  31. package/dist/vera-renderer-hydrate.min.js.map +1 -1
  32. package/dist/vera-renderer-keyed.min.js +2 -0
  33. package/dist/vera-renderer-keyed.min.js.map +1 -0
  34. package/dist/vera-renderer-slots.min.js +2 -0
  35. package/dist/vera-renderer-slots.min.js.map +1 -0
  36. package/dist/vera-renderer-spread.min.js +2 -0
  37. package/dist/vera-renderer-spread.min.js.map +1 -0
  38. package/dist/vera-renderer-tag.min.js +2 -0
  39. package/dist/vera-renderer-tag.min.js.map +1 -0
  40. package/dist/vera-renderer.min.js +1 -1
  41. package/dist/vera-renderer.min.js.map +1 -1
  42. package/package.json +24 -1
@@ -1,3 +1,86 @@
1
+ /**
2
+ * `true ` only: the one home for *"is this value something an attribute can carry?"*
3
+ *
4
+ * **Why it is a closed vocabulary and not a predicate.** The first design asked whether a value
5
+ * stringifies meaningfully — `String(v) === '[object Object]'` means it lost its data. Driven
6
+ * through 16 value shapes rather than reasoned about, that broke four ways, and the first is
7
+ * disqualifying: `String()` THROWS on `Object.create(null)`, on `{ toString: null }`, and on any
8
+ * object whose `toString` throws — so a diagnostic would have killed the page for an author using
9
+ * the recommended dictionary idiom. It also passed `["a","b"]` as `"a,b"` (one junk class, if that
10
+ * was a `class` binding) and `new Date()` as a timezone-bearing string, which is an SSR/CSR
11
+ * divergence manufactured out of correct-looking code. And it passed `Symbol('s')` while
12
+ * `` `${sym}` `` throws — a guard and its sink disagreeing about a single expression.
13
+ *
14
+ * "Does it stringify meaningfully" is an OPEN predicate over an unbounded, environment-dependent
15
+ * space, and open predicates cannot be audited. So the test is inverted and closed: **primitives
16
+ * pass; everything else is reported; anything else that should pass is a named row added on
17
+ * evidence.** The list has exactly one member so far.
18
+ *
19
+ * Credit where it is due: the four breaks were found by the omni engine's session, which drove the
20
+ * shapes rather than arguing about them, and the closed-vocabulary form is theirs.
21
+ */
22
+ /**
23
+ * Blessed non-primitives — types whose `toString` IS the value the author means.
24
+ *
25
+ * Tested by brand rather than `instanceof`, which is false across realms: a `URL` built in an
26
+ * iframe is not `instanceof` the parent's `URL`, and a diagnostic that fires on a correct value in
27
+ * one frame and not another is worse than none.
28
+ */
29
+ const brand = (value) => Object.prototype.toString.call(value);
30
+ /** One message per element+name+kind, so a value rebuilt every render does not flood the console. */
31
+ let reported;
32
+ /**
33
+ * Returns the complaint, or `null` when the value is fine. Never throws — the shapes that break a
34
+ * naive guard are exactly the ones worth reporting, so they reach the `object` arm and are named.
35
+ */
36
+ const attributeValueComplaint = (tag, name, value) => {
37
+ const type = typeof value;
38
+ if (type === 'string' || type === 'number' || type === 'boolean' || type === 'bigint')
39
+ return null;
40
+ if (type === 'object' && brand(value) === '[object URL]')
41
+ return null;
42
+ /**
43
+ * Keyed by BRAND, not by `typeof` — `Date`, `Array` and a plain object are all `'object'`, so a
44
+ * coarser key reported whichever arrived first and silently swallowed the rest. An author who
45
+ * fixed the Date would never have been told about the array.
46
+ */
47
+ const key = `${tag}|${name}|${type === 'object' ? brand(value) : type}`;
48
+ reported ??= new Set();
49
+ if (reported.has(key))
50
+ return null;
51
+ reported.add(key);
52
+ /**
53
+ * A function into an attribute is never what the author meant, but the REASON matters: on a
54
+ * custom element the Lit-era convention is that complex values are set as properties, so
55
+ * `<my-chart formatter={fn}>` is a coherent intention that this sink simply cannot express. The
56
+ * message names the binding that can, rather than blaming the author.
57
+ */
58
+ const said = type === 'function'
59
+ ? `a function, which becomes its own SOURCE TEXT`
60
+ : type === 'symbol'
61
+ ? `a symbol, which every DOM conversion refuses`
62
+ : Array.isArray(value)
63
+ ? `an array, which becomes its members joined by commas`
64
+ : brand(value) === '[object Date]'
65
+ ? `a Date, whose text carries the TIMEZONE of whichever side rendered it`
66
+ : `an ${type}, which cannot survive as text`;
67
+ /**
68
+ * Returned WITHOUT the `[vera]` prefix, which each call site writes as a literal.
69
+ * `tests/diagnostics-convention.test.mjs` reads the prefix off the call, so a message handed over
70
+ * as a variable is invisible to it — and its answer to that is an allowance list. Taking the
71
+ * allowance would have excused these two calls rather than checked them, which is the
72
+ * reclassification this audit keeps refusing; the literal at the call site is what every other
73
+ * diagnostic in the repo does anyway.
74
+ */
75
+ return (`renderer: the attribute \`${name}\` on <${tag}> was given ${said}. ` +
76
+ `An attribute value is a string and nothing else.\n` +
77
+ `If the element is meant to RECEIVE this value, bind a property instead — \`.${name}=\${value}\` ` +
78
+ `— which is how a custom element takes anything that is not text. If it is meant to be read as ` +
79
+ `text, convert it where you know what it means: \`date.toISOString()\`, \`list.join(' ')\`. ` +
80
+ `A Date in particular serializes with the SERVER's timezone on one side and the browser's on ` +
81
+ `the other, so it will not survive hydration.`);
82
+ };
83
+
1
84
  /**
2
85
  * @verajs/renderer — a ground-up, keyed, template-identity renderer.
3
86
  *
@@ -57,18 +140,6 @@
57
140
  * deliberately do not match the pattern: the first is an interop wire format, the second is called
58
141
  * by the DOM itself.
59
142
  */
60
- /**
61
- * Marks a template result with a stable key so list reconciliation moves it instead of rewriting
62
- * it. Key all items in a list or none — mixing is undefined behaviour, as are duplicate keys.
63
- *
64
- * ```js
65
- * rows.map((r) => keyed(r.id, html`<tr>...</tr>`))
66
- * ```
67
- */
68
- const keyed = (key, result) => {
69
- result.key = key;
70
- return result;
71
- };
72
143
  /**
73
144
  * Preserves the DOM of templates a child position toggles away from, instead of destroying it —
74
145
  * form values, scroll positions and media playback survive the round trip (lit-html calls this
@@ -77,12 +148,22 @@ const keyed = (key, result) => {
77
148
  * ```js
78
149
  * html`<div>${hold(editing ? editor() : viewer())}</div>`
79
150
  * ```
151
+ *
152
+ * **Anything that is not a template passes straight through.** There is nothing to park for a
153
+ * string, a list, `null` or `false`, and the branch that produces one is the ordinary shape of the
154
+ * expression this wraps — `hold(editing && editor())`, `hold(row ?? null)`. Wrapping those handed
155
+ * the renderer a `{ $h }` carrying a non-template, which reached the held-commit path and threw on
156
+ * `result.strings`: a whole render lost, from a value the same expression renders happily one
157
+ * character to the left. Decided here rather than in the renderer so the hot path pays nothing.
80
158
  */
81
- const hold = (result) => ({ $h: result });
159
+ const hold = (result) => result != null && typeof result === 'object' && isTemplateResult(result)
160
+ ? { $h: result }
161
+ : result;
82
162
  /**
83
163
  * Unique per module load, so user text can never collide with it. Randomness here cannot break
84
164
  * template caching — the marker only ever pairs a scan with its own Template construction.
85
165
  */
166
+
86
167
  const MARKER = '$v' + ((Math.random() * 1e9) >>> 0).toString(36) + '$';
87
168
  /** `<?xyz>` parses as a bogus comment whose data is `?xyz`. */
88
169
  const MARKER_COMMENT_DATA = '?' + MARKER;
@@ -103,7 +184,37 @@ const markerWalker = doc.createTreeWalker(doc, 129 /* ELEMENT | COMMENT */);
103
184
  * TreeWalker allocation per instance, which is 10 000 allocations in a 10 000-row create.
104
185
  */
105
186
  const instanceWalker = doc.createTreeWalker(doc, 5 /* ELEMENT | TEXT */);
106
- const RAW_TEXT_TAGS = /^(?:script|style|textarea|title)$/i;
187
+ /**
188
+ * Elements whose children a parser reads as **text**, so a marker written inside one arrives as
189
+ * characters rather than a comment and the binding never becomes a part.
190
+ *
191
+ * `iframe` and `noscript` were missing, and both were measured broken in a browser rather than
192
+ * reasoned about: `html\`<iframe>${v}</iframe>\`` painted the literal marker — `<?$v8hpsho$>` — onto
193
+ * the page in **all three engines** and never updated.
194
+ *
195
+ * **`noscript` is the one worth the comment, because the engines disagree.** A template's contents
196
+ * are parsed with the scripting flag *disabled*, which is what decides whether `noscript` is raw
197
+ * text — and Chromium and WebKit parse it as markup there while Firefox parses it as text. So
198
+ * `html\`<noscript>${v}</noscript>\`` worked in two engines and painted the marker in the third: an
199
+ * app developed in Chrome shipping the framework's internals onto the page for Firefox users.
200
+ *
201
+ * Listing it here is safe in both parses. Where the marker became a comment the raw-text branch does
202
+ * not trigger, because it looks for the marker in `textContent` and finds none.
203
+ */
204
+ const RAW_TEXT_TAGS = /^(?:script|style|textarea|title|iframe|noscript)$/i;
205
+ /**
206
+ * The void elements, as a regex rather than the `Set` in `@verajs/shared-utils`, and NOT imported
207
+ * from it — measured: an imported `new Set([...])` survives production because neither rollup nor
208
+ * terser can prove the constructor call is side-effect-free, so it sat at module scope costing
209
+ * **62 B gzipped on the base bundle** for a diagnostic production does not even run. A regex
210
+ * literal read only by `warnTagShape` goes when that dead function goes.
211
+ *
212
+ * So this is a second home for a fact `@verajs/shared-utils` owns, kept deliberately and in a
213
+ * different SHAPE because a hot file's byte budget forbids the shared one. That is only acceptable
214
+ * with an enforcer: `tests/markup-grammar-homes.test.mjs` drives this regex and the canonical set
215
+ * against each other, member by member, in both directions.
216
+ */
217
+ const VOID_TAGS = /^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/i;
107
218
  const ATTR_NAME_DELIMITER = /[\s"'>=/]/;
108
219
  /** What an expression position turned out to be. */
109
220
  const CHILD = 0;
@@ -123,7 +234,31 @@ const IN_BOUND_VALUE = 5; // collecting a bound attribute's statics
123
234
  * A small state machine rather than tail regexes, because `>` inside quoted attribute values and
124
235
  * inside comments must not terminate a tag, and raw-text elements swallow markup.
125
236
  */
126
- const scan = (strings) => {
237
+ /**
238
+ * `true ` only: the two ways a hand-written template describes a tree the parser will not build.
239
+ *
240
+ * `@verajs/jsx` normalises both at compile time, so this is the channel for the BUILDLESS path —
241
+ * which is this framework's baseline, not its fallback, and was the surface left broken when the
242
+ * compiler fix landed. It reaches the browser console on the client and during hydration; a
243
+ * server-only render never runs this scanner, so an SSR page that is never hydrated is not covered.
244
+ *
245
+ * The self-close test is `markup` ending in `/`, which is the same approximation the raw-text
246
+ * branch below already makes: an unquoted attribute value ending in a slash (`<div data-x=a/>`)
247
+ * reads the same way. That is not a false positive in any way that matters — measured, such a tag
248
+ * is an OPEN tag too and swallows what follows it exactly as `<div/>` does, so both the warning and
249
+ * the fix it names are correct for it.
250
+ */
251
+ const warnTagShape = (tag, closing, selfClosed) => {
252
+ if (!closing && selfClosed && !VOID_TAGS.test(tag))
253
+ console.warn(`[vera] renderer: <${tag}> is left OPEN by this template, so everything after it becomes its ` +
254
+ `child rather than its sibling. HTML has no self-closing syntax outside <svg> and <math> — ` +
255
+ `\`<${tag} />\` is an open tag, not an empty element. Write \`<${tag}></${tag}>\`. ` +
256
+ `(@verajs/jsx rewrites this for you; a hand-written template has to say it.)`);
257
+ else if (closing && VOID_TAGS.test(tag))
258
+ console.warn(`[vera] renderer: \`</${tag}>\` is read by the parser as ANOTHER <${tag}>, so this template ` +
259
+ `renders two where it describes one. A void element has no end tag — write \`<${tag}>\` alone.`);
260
+ };
261
+ const scan = (strings, type = 1) => {
127
262
  const specs = [];
128
263
  let markup = '';
129
264
  let state = IN_TEXT;
@@ -132,6 +267,16 @@ const scan = (strings) => {
132
267
  let rawTag = ''; // which raw-text element we are inside
133
268
  let tagNameStart = 0; // markup index where the current tag's name begins
134
269
  let isClosing = false;
270
+ /**
271
+ * `true ` only. Depth of `<svg>`/`<math>` nesting, because foreign content is the one place the
272
+ * parser DOES honour XML self-closing, so neither warning applies inside it. An `svg`/`mathml`
273
+ * template is already inside one, hence the seed from `type`.
274
+ *
275
+ * `<foreignObject>` re-enters HTML content and is deliberately not tracked: suppressing a warning
276
+ * there is a missed warning, while tracking it wrongly would be a wrong one, and a diagnostic
277
+ * that cries wolf is worse than one that stays quiet.
278
+ */
279
+ let foreign = type === 1 ? 0 : 1;
135
280
  let attrName = '';
136
281
  let statics = [];
137
282
  let pending = ''; // the static chunk currently being collected IN_BOUND_VALUE
@@ -158,7 +303,9 @@ const scan = (strings) => {
158
303
  statics.push(pending);
159
304
  const quoteChar = quote || '"';
160
305
  markup += ` ${specs.length}${MARKER}=${quoteChar}${statics.join(MARKER)}${quoteChar}`;
161
- specs.push({ _type: ATTRIBUTE, _name: attrName });
306
+ specs.push(true
307
+ ? { _type: ATTRIBUTE, _name: attrName, _tag: markup.slice(tagNameStart).match(/^[a-zA-Z][^\s/>]*/)?.[0] }
308
+ : { _type: ATTRIBUTE, _name: attrName });
162
309
  state = IN_TAG;
163
310
  if (quote !== '')
164
311
  pos++; // consume the closing quote; unquoted terminators reprocess IN_TAG
@@ -190,6 +337,14 @@ const scan = (strings) => {
190
337
  }
191
338
  else if (ch === '>') {
192
339
  const tagName = markup.slice(tagNameStart).match(/^[a-zA-Z][^\s/>]*/)?.[0] ?? '';
340
+ if (true ) {
341
+ const lower = tagName.toLowerCase();
342
+ const selfClosed = markup.endsWith('/');
343
+ if (lower === 'svg' || lower === 'math')
344
+ foreign += isClosing ? -1 : selfClosed ? 0 : 1;
345
+ else if (foreign < 1)
346
+ warnTagShape(tagName, isClosing, selfClosed);
347
+ }
193
348
  if (!isClosing && RAW_TEXT_TAGS.test(tagName) && !markup.endsWith('/')) {
194
349
  rawTag = tagName.toLowerCase();
195
350
  state = IN_RAW_TEXT;
@@ -278,6 +433,44 @@ const scan = (strings) => {
278
433
  * Element-position expression — an element REF, not a no-op. Marked exactly like a bound
279
434
  * attribute ('&' cannot begin a real attribute binding), so no new machinery exists for it.
280
435
  */
436
+ if (true && (markup.endsWith('<') || markup.endsWith('</'))) {
437
+ /**
438
+ * Except in **tag position**, where it is a mistake with no useful reading. `<${name}>`
439
+ * lands here because the tag has no name yet, and what the parser then makes of a ref on
440
+ * a nameless element is escaped punctuation. Naming the entry that does support it is
441
+ * more use than an element ref nobody asked for.
442
+ */
443
+ console.error(`[vera] an expression in tag position (\`<\${…}>\`) is not a dynamic tag name — the ` +
444
+ `template has no element there and the markup around it is rendered as text.\n` +
445
+ `Runtime tag names live in @verajs/renderer/tag:\n\n` +
446
+ ` import { html, tag } from '@verajs/renderer/tag';\n` +
447
+ ` const heading = tag\`h1\`;\n` +
448
+ ` html\`<\${heading}>…</\${heading}>\`\n`);
449
+ }
450
+ /**
451
+ * **And in attribute-*name* position, which is the same mistake one step along.**
452
+ *
453
+ * `<b ${name}="x">`, `<b data-${name}="1">` and `<b a${name}b="1">` all land here: the
454
+ * marker is not preceded by `=`, so it reads as an element ref, and the `="x"` after it
455
+ * stays literal markup. The browser's parser then makes `<b ="x"="">` of it — attributes
456
+ * nobody wrote, silently.
457
+ *
458
+ * **The server already refuses this**, and said so in its README while the client shipped
459
+ * the garbage. A developer rendering only in a browser saw malformed output with no clue,
460
+ * and adding SSR later turned it into a throw with no obvious connection.
461
+ *
462
+ * Told apart from a real element ref by what follows it: a ref is always followed by
463
+ * whitespace, `>` or `/`. Anything else means the marker landed inside a name.
464
+ */
465
+ const after = strings[i + 1] ?? '';
466
+ if (true && after !== '' && !/^[\s>/]/.test(after)) {
467
+ console.error(`[vera] an expression in attribute-name position (\`<b \${…}="x">\`) is not a dynamic ` +
468
+ `attribute name — a marker is not a name, and the parser makes attributes nobody ` +
469
+ `wrote out of what follows it.\n` +
470
+ `Runtime-named bindings live in @verajs/renderer/spread:\n\n` +
471
+ ` import { spread } from '@verajs/renderer/spread';\n` +
472
+ ` html\`<b \${spread({ [name]: 'x' })}>…</b>\`\n`);
473
+ }
281
474
  markup += ` ${specs.length}${MARKER}="${MARKER}"`;
282
475
  specs.push({ _type: ATTRIBUTE, _name: '&' });
283
476
  }
@@ -285,13 +478,92 @@ const scan = (strings) => {
285
478
  }
286
479
  return { markup, specs };
287
480
  };
481
+ /**
482
+ * The container of the renderInto call currently committing — how a slot part learns its root
483
+ * (light element vs shadow root) at Instance construction. Commits are synchronous per flush, so
484
+ * one module slot suffices (the `currentInstance` pattern); null outside renderInto (hydration's
485
+ * adoption path constructs elsewhere and the seam stays inert there until it learns adoption).
486
+ */
487
+ let _slotRoot = null;
488
+ /** See the slotless branch in `Instance`. Once per host tag, so a list cannot flood a console. */
489
+ const warnedSlotless = new Set();
490
+ const warnSlotless = (root) => {
491
+ const tag = root.localName;
492
+ if (warnedSlotless.has(tag))
493
+ return;
494
+ warnedSlotless.add(tag);
495
+ console.warn(`[vera] renderer: <${tag}> renders a \`<slot>\` into LIGHT DOM, but no 'slot' insert is wired — ` +
496
+ `nothing can fill it, so it always shows its fallback, and any content the host is given for ` +
497
+ `it sits beside the component as stray markup instead. Wire it at the app entry, BEFORE anything renders: ` +
498
+ `\`import { slots } from '@verajs/renderer/slots'; wire([renderer, slots])\`. Wiring it later ` +
499
+ `does not help a template that has already rendered — a template resolves this once, at ` +
500
+ `construction, and is interned per call site for the life of the page.`);
501
+ };
502
+ /**
503
+ * `true ` only: the HTML parser dropped an element a binding was written on.
504
+ *
505
+ * Named where it is discovered rather than after the walk, because the SKIP knows exactly which
506
+ * spec went missing — `specs[from]` is the casualty by construction. A post-hoc count can only
507
+ * report the LAST unclaimed spec, which positional pairing makes the wrong element every time, and
508
+ * pointing an author at a tag that rendered correctly is the precise failure this message exists
509
+ * to cure.
510
+ */
511
+ /**
512
+ * **A child binding directly inside `<table>` renders one shape and PARSES as another.**
513
+ *
514
+ * `<table>${rows}</table>` is conforming HTML — `<tbody>` is omissible — and it is the one place a
515
+ * legal template does not survive a round trip through the platform:
516
+ *
517
+ * - CLIENT RENDER inserts the rows with DOM calls, which apply no parser rules: `table > tr`.
518
+ * - The SAME markup PARSED — a server render the browser re-parses, `innerHTML`, a static file —
519
+ * gets the implied section: `table > tbody > tr`.
520
+ *
521
+ * Measured, both shapes, same template. So a stylesheet written `table > tr` matches on one path
522
+ * and not the other, and hydration discards the server's markup for that container and rebuilds it
523
+ * (*"expected `<tr>` and found `<tbody>`"*) — silently in production, where this call is folded away.
524
+ *
525
+ * **Why this is a warning and not a repair.** Whatever is emitted, the browser re-parses it, and the
526
+ * parser ALWAYS inserts the section — so the only shape all three paths agree on is one where the
527
+ * section is already in the template. The framework could insert it, but that changes the DOM shape
528
+ * of every existing client-rendered table, across the renderer AND `@verajs/ssr`'s serializer, and
529
+ * rests on the SSR shim agreeing with browsers about implied tags. One word from the author reaches
530
+ * the same fixed point with none of that. Owner's call, recorded rather than assumed.
531
+ *
532
+ * Scoped to `<table>` deliberately: `<tbody>` (from rows) and `<colgroup>` (from `<col>`) are the
533
+ * only implied START tags reachable inside a template fragment, and both are children of `<table>`.
534
+ * The omissible END tags — `</li>`, `</p>`, `</td>`, `</option>` and the rest — insert nothing, so
535
+ * they round-trip correctly and are pinned doing so in `tests/dropped-element-bindings.test.mjs`.
536
+ */
537
+ const warnImplicitSection = (parent) => {
538
+ if (parent?.localName !== 'table')
539
+ return;
540
+ console.warn('[vera] renderer: a binding sits directly inside <table>, where the HTML parser inserts a ' +
541
+ '<tbody> that a client render does not. The same template then renders as `table > tr` and ' +
542
+ 'parses as `table > tbody > tr`, so `table > tr` selectors match on only one path and ' +
543
+ 'hydration rebuilds this container instead of adopting it. Write the section explicitly — ' +
544
+ '`<table><tbody>${rows}</tbody></table>` — and every path agrees.');
545
+ };
546
+ const warnDroppedBinding = (specs, from, count) => {
547
+ const lost = specs[from];
548
+ const where = lost?._tag
549
+ ? `\`${lost._type === ATTRIBUTE ? `${lost._name}=` : ''}\` on <${lost._tag}>`
550
+ : 'a binding';
551
+ console.warn(`[vera] renderer: ${where} never reached the parsed tree — the HTML parser DROPPED the element ` +
552
+ `it was written on, because its parent's content model forbids it (\`<select>\` takes only ` +
553
+ `options, \`<form>\` cannot nest, and so on).\n` +
554
+ `${count} binding(s) lost. The element is gone from the DOM and its binding does nothing; ` +
555
+ `the bindings AFTER it are unaffected, because each marker carries its own index. ` +
556
+ `(Before that they all shifted onto the wrong elements, which is why this kind of mistake ` +
557
+ `used to surface somewhere you had not edited.)\n` +
558
+ `Move the element out of its parent, or use one the parent can hold.`);
559
+ };
288
560
  const templateCache = new WeakMap();
289
561
  class Template {
290
562
  _element;
291
563
  _parts = [];
292
564
  constructor(result) {
293
565
  const type = result._$litType$ ?? 1;
294
- const { markup, specs } = scan(result.strings);
566
+ const { markup, specs } = scan(result.strings, type);
295
567
  this._element = doc.createElement('template');
296
568
  /** svg/mathml fragments only parse inside their root; wrap, then unwrap below. */
297
569
  this._element.innerHTML = type === 2 ? `<svg>${markup}</svg>` : type === 3 ? `<math>${markup}</math>` : markup;
@@ -325,6 +597,27 @@ class Template {
325
597
  if (element.hasAttributes()) {
326
598
  for (const attributeName of element.getAttributeNames()) {
327
599
  if (attributeName.endsWith(MARKER)) {
600
+ /**
601
+ * **Each marker carries its own spec index in its NAME**, so pairing is addressed
602
+ * rather than positional — and a marker that never arrived is visible the moment the
603
+ * next one does. Both halves matter and neither works alone:
604
+ *
605
+ * - REPAIR: an element the parser drops takes its marker with it. Paired by walk
606
+ * order, that shifted every later binding onto the wrong element, silently —
607
+ * `html\`<select><div title=${'${a}'}>x</div></select><b title=${'${b}'}>\`` rendered
608
+ * `<b title="a">`. Consuming the gap keeps every surviving binding on its own
609
+ * element; only the dropped one is lost.
610
+ * - REPORT: the repair would otherwise SILENCE the problem, which is a correct
611
+ * refusal with nothing to tell the author — so the skip is where the warning lives.
612
+ */
613
+ const declared = parseInt(attributeName, 10);
614
+ if (declared > specIndex) {
615
+ if (true )
616
+ warnDroppedBinding(specs, specIndex, declared - specIndex);
617
+ do
618
+ parts.push({ _type: IGNORED, _index: -1 });
619
+ while (++specIndex < declared);
620
+ }
328
621
  /**
329
622
  * The marker attribute's value carries the statics; the REAL (case-preserved) name
330
623
  * comes from the spec — the HTML parser lowercases attribute names, which would
@@ -336,6 +629,15 @@ class Template {
336
629
  _index: -1,
337
630
  _name: spec._name,
338
631
  _statics: element.getAttribute(attributeName).split(MARKER),
632
+ /**
633
+ * Computed here — once per template, ever — so the first commit of a nullish
634
+ * binding knows whether a fresh clone even carries the attribute. It usually does
635
+ * not, and the unconditional removal this feeds cost a real DOM call per element
636
+ * per create: 1,000 no-op `removeAttribute`s on the 1,000-row benchmark. The one
637
+ * case that must still remove — `<b title="a" title=${null}>`, where the parser
638
+ * keeps the first duplicate — is exactly what this reads.
639
+ */
640
+ _present: element.hasAttribute(spec._name),
339
641
  _node: element,
340
642
  });
341
643
  element.removeAttribute(attributeName);
@@ -367,10 +669,41 @@ class Template {
367
669
  /** Re-aim the walker before removing the node it stands on. */
368
670
  markerWalker.currentNode = primedText;
369
671
  node.remove();
672
+ if (true )
673
+ warnImplicitSection(primedText.parentNode);
370
674
  parts.push({ _type: CHILD, _index: -1, _node: primedText });
371
675
  consumeIgnored();
372
676
  }
373
677
  }
678
+ /**
679
+ * **CONSERVATION OF MARKERS — the walk must claim every spec the scan emitted.**
680
+ *
681
+ * The loop above pairs specs with markers in document order. If the HTML parser DROPPED the
682
+ * element a binding was written on, that marker never exists, the loop runs out of nodes early,
683
+ * and `specIndex` stops short — and because pairing is POSITIONAL, every binding after the
684
+ * missing one has already been handed the value of its predecessor. Measured:
685
+ *
686
+ * html`<select><div title=${a}>x</div></select><b title=${b}>after</b>`
687
+ *
688
+ * renders `<b title="a">` — the value written for the `<div>`, on an unrelated element, with
689
+ * no error anywhere. `<form>` inside `<form>` does the same. HTML's parser drops elements its
690
+ * content model forbids, which is correct of it and invisible to everything else here.
691
+ *
692
+ * **This is deliberately not a content-model check.** A table of what may contain what is a
693
+ * closed vocabulary over an open space: it catches what somebody enumerated, needs maintenance
694
+ * as HTML evolves, and would cover the compiler only — while this counts what actually
695
+ * happened, in JSX and hand-written templates alike, for every dropping context including the
696
+ * ones nobody listed. The cost of knowing is one integer comparison the construction already
697
+ * had lying around.
698
+ *
699
+ * The gap it cannot close, named rather than implied: a dropped element carrying NO bindings
700
+ * loses nothing to count. That is harmless to the renderer — nothing shifts — and it is the
701
+ * restructuring class, which `tests/jsx-tree-parity.test.mjs` records instead.
702
+ */
703
+ if (true && specIndex < specs.length) {
704
+ /** A casualty at the very END has no later marker to reveal it, so the tail is checked too. */
705
+ warnDroppedBinding(specs, specIndex, specs.length - specIndex);
706
+ }
374
707
  /** Pass 2 — INDEX over ELEMENT | TEXT, the mask instances walk with. */
375
708
  instanceWalker.currentNode = content;
376
709
  let nodeIndex = -1;
@@ -388,6 +721,40 @@ class Template {
388
721
  }
389
722
  for (const part of parts)
390
723
  part._node = undefined;
724
+ /**
725
+ * THE SLOT WALK — the whole template-side seam, and it runs only when a 'slot' insert is
726
+ * wired at construction. One dedicated pass discovers `<slot>` elements AND indexes them in
727
+ * the same ELEMENT|TEXT numbering the instance walk uses (Text has no localName, so no
728
+ * nodeType check is needed). Passes 1 and 2 above are byte-identical to their pre-seam
729
+ * selves: an unwired app's construction path is untouched, and its only cost is this one
730
+ * registry lookup per template construction.
731
+ *
732
+ * **Resolved per TEMPLATE, and templates are cached per call site for the life of the page** —
733
+ * so a shape first constructed before `wire([slots])` ran never gains slot support, silently.
734
+ * That is the ordinary insert contract (wire at the app entry, beside the renderer, before
735
+ * anything renders) and it is stated in the slots module's own docs; resolving per INSTANCE
736
+ * instead would move a registry lookup onto the hot path for every app, which is the trade
737
+ * this design refuses.
738
+ */
739
+ const seam = slotSeam();
740
+ /**
741
+ * **Dev-only: remember that this markup HAS slots even when nothing can distribute them.**
742
+ * Without it the two ways of getting the wiring wrong are indistinguishable from a component
743
+ * that simply has no slots — see the warning at the instance's slot mount.
744
+ */
745
+ if (true && seam === undefined && markup.includes('<slot'))
746
+ this._slotless = true;
747
+ if (seam !== undefined) {
748
+ instanceWalker.currentNode = content;
749
+ let index = -1;
750
+ while ((node = instanceWalker.nextNode()) !== null) {
751
+ index++;
752
+ if (node.localName === 'slot') {
753
+ this._seam = seam;
754
+ (this._slots ??= []).push(index);
755
+ }
756
+ }
757
+ }
391
758
  }
392
759
  }
393
760
  const getTemplate = (result) => {
@@ -399,8 +766,6 @@ const getTemplate = (result) => {
399
766
  const IGNORED_PART = { _commit: (_values, index) => index + 1 };
400
767
  /** Never equal to any user value, so the first commit always runs. */
401
768
  const UNSET = {};
402
- /** Removal target: nodes moved here are dropped when it is emptied. */
403
- const SCRATCH = doc.createDocumentFragment();
404
769
  /** A fresh markered part: two comments inserted before `ref` in `parent`. */
405
770
  const createMarkeredPart = (parent, ref) => {
406
771
  const start = comment();
@@ -409,13 +774,58 @@ const createMarkeredPart = (parent, ref) => {
409
774
  parent.insertBefore(end, ref);
410
775
  return new ChildPart(start, end);
411
776
  };
412
- const toText = (value) => (value == null ? '' : String(value));
777
+ /**
778
+ * Text for an attribute built from several expressions.
779
+ *
780
+ * `` `${value}` `` rather than `String(value)`, and the difference is exactly one case. Both are
781
+ * ToString with hint `'string'` for everything else; `String` alone special-cases a **symbol** and
782
+ * returns its description instead of throwing. Every single-expression binding assigns straight to
783
+ * the DOM and gets WebIDL's `DOMString` conversion, which throws on one — so `title=${symbol}` threw
784
+ * and `title="a ${symbol} b"` quietly rendered `a Symbol(s) b`. The same sigil on the same attribute,
785
+ * disagreeing with itself depending on whether static text sat beside it.
786
+ */
787
+ const toText = (value) => (value == null ? '' : `${value}`);
413
788
  /** Binding kinds, resolved once from the attribute name's first character. */
414
789
  const ATTR = 0; // plain attribute
415
790
  const PROPERTY = 1; // .name
416
791
  const BOOLEAN = 2; // ?name
417
- const EVENT = 3; // @name
418
- const REF = 4; // element-position expression
792
+ /**
793
+ * `!name` — a property written from the *live* DOM rather than from what this binding last wrote.
794
+ *
795
+ * Numbered below `EVENT` deliberately: `kind >= EVENT` is what decides a value is passed raw rather
796
+ * than joined from the statics, and a live binding is a property, so `!title="a${x}b"` has to join
797
+ * like every other one.
798
+ */
799
+ const LIVE = 3;
800
+ const EVENT = 4; // @name
801
+ /** A binding that must never write — see the `__proto__` refusal in the constructor. */
802
+ const REFUSED = -1;
803
+ /**
804
+ * Calls an element ref, and survives one that throws.
805
+ *
806
+ * A ref runs in the middle of committing a template's parts, so an unguarded throw left the commit
807
+ * half applied and unwound the render that triggered it — the component's shadow root ended up
808
+ * **empty and stayed that way**, and every later update threw at the same line. The error was
809
+ * reported, so the only symptom was a component that had silently stopped existing.
810
+ *
811
+ * The same judgement `handleEvent` makes a few lines up: a mistake in code the template was handed
812
+ * is named, not raised from inside the framework at a point where the value's origin is long gone.
813
+ * The prefix goes on our own sentence and the error is passed alongside, so it stays filterable
814
+ * without misattributing someone else's `Error`.
815
+ */
816
+ const applyRef = (callback, element) => {
817
+ try {
818
+ callback(element);
819
+ }
820
+ catch (error) {
821
+ /** The sentence is development's; production keeps the prefix and the error carries the rest. */
822
+ if (true )
823
+ console.error('[vera] an element ref threw; the render continued without it.', error);
824
+ else
825
+ console.error('[vera] ref threw', error);
826
+ }
827
+ };
828
+ const REF = 5; // element-position expression
419
829
  class AttrPart {
420
830
  _element;
421
831
  _name;
@@ -425,12 +835,57 @@ class AttrPart {
425
835
  _isFullValue; // exactly one expression with no static text around it
426
836
  _committed = UNSET;
427
837
  _handler = null;
428
- constructor(element, name, statics) {
838
+ /** `<select>.value`, which cannot be applied where it is written — see `pendingSelects`. */
839
+ _select = false;
840
+ /** The template statically wrote this attribute, so a first nullish commit must still remove. */
841
+ _present;
842
+ constructor(element, name, statics, present = false) {
429
843
  const first = name[0];
430
- let kind = first === '.' ? PROPERTY : first === '?' ? BOOLEAN : first === '@' ? EVENT : first === '&' ? REF : ATTR;
844
+ let kind = first === '.'
845
+ ? PROPERTY
846
+ : first === '?'
847
+ ? BOOLEAN
848
+ : first === '@'
849
+ ? EVENT
850
+ : first === '&'
851
+ ? REF
852
+ : first === '!'
853
+ ? LIVE
854
+ : ATTR;
431
855
  let realName = kind ? name.slice(1) : name;
432
- /** React muscle-memory, buildless: `onClick=${fn}` ≡ `@click=${fn}`. Strictly `on` + a
433
- * capital — all-lowercase `onclick` stays a plain attribute (legal inline-handler HTML). */
856
+ /**
857
+ * **`__proto__` is not a property write, so no property binding may make one.**
858
+ *
859
+ * `element.__proto__ = value` hits `Object.prototype`'s `__proto__` ACCESSOR and replaces the
860
+ * element's prototype, stripping every DOM method it has. `.__proto__=${x}` crashed out of the
861
+ * commit with an unreadable internal error; `!__proto__=${x}` bricked the element silently and
862
+ * the wreckage surfaced in a LATER render, naming the renderer rather than the binding. There
863
+ * is no legitimate use, so unlike `.innerHTML` there is no spelling to point at — the binding
864
+ * is refused and never writes.
865
+ *
866
+ * **The deliberate twin of `refusedSink` in `./spread.ts`**, which refuses the same name for
867
+ * the same reason. The two entries are independent bundles and neither imports the other, so
868
+ * the rule is copied on purpose (the repo's standing note: sigil rules live in both AttrPart
869
+ * and spread, and a fix has to visit every copy). `tests/dangerous-binding-matrix.test.mjs`
870
+ * fails if one of them starts refusing something the other allows.
871
+ */
872
+ if ((kind === PROPERTY || kind === LIVE) && realName === '__proto__') {
873
+ kind = REFUSED;
874
+ if (true )
875
+ console.warn(`[vera] <${element.localName}> binds \`${name}\`, which would replace the element's own ` +
876
+ `prototype and destroy it — no property write does this, and no use of it is legitimate. ` +
877
+ `The binding is ignored.`);
878
+ }
879
+ /**
880
+ * React muscle-memory, buildless: `onClick=${fn}` ≡ `@click=${fn}`. Strictly `on` + a capital —
881
+ * all-lowercase `onclick` stays a plain attribute (legal inline-handler HTML).
882
+ *
883
+ * `@verajs/renderer/spread` repeats these rules rather than importing them. Sharing them through
884
+ * `@verajs/shared-utils` was tried and reverted: the shared form has to return both the kind and
885
+ * the name, and the tuple it allocates cost this bundle 10 B. Principle #5 allows deliberate
886
+ * duplication where two things can legitimately diverge; here #7 decides it — weight is the
887
+ * product, and core and the renderer are the two packages where that is absolute.
888
+ */
434
889
  if (kind === ATTR && first === 'o' && name.charCodeAt(1) === 110 && name.charCodeAt(2) > 64 && name.charCodeAt(2) < 91) {
435
890
  kind = EVENT;
436
891
  realName = name.slice(2).toLowerCase();
@@ -441,14 +896,84 @@ class AttrPart {
441
896
  this._statics = statics;
442
897
  this._slots = statics.length - 1;
443
898
  this._isFullValue = this._slots === 1 && statics[0] === '' && statics[1] === '';
899
+ /** Resolved once, here, so the commit path costs one boolean rather than two comparisons. */
900
+ this._select = kind === PROPERTY && realName === 'value' && element.localName === 'select';
901
+ this._present = present;
444
902
  }
445
- /** Stable listener registered once; swapping the handler never touches the DOM. */
903
+ /**
904
+ * Releases an element ref, because the element it named is going away.
905
+ *
906
+ * A ref was told about attachment and never about detachment, so it kept a detached node alive and
907
+ * a component reading `myRef.value` after a subtree was replaced got the old element back. Lit
908
+ * passes `undefined` for the same reason.
909
+ *
910
+ * `null` rather than `undefined`, because `.value` is a store property and `null` reads as
911
+ * "deliberately nothing" where `undefined` reads as "never set".
912
+ *
913
+ * **Reached when a subtree is rendered away, and deliberately not when a component is removed
914
+ * from the document.** The two are the same event to a reader and not to this renderer: a
915
+ * disconnect here is not a destruction, since moving a node between parents fires one and the
916
+ * component renders again on reconnect. Releasing there would blank every ref for the frame a
917
+ * move takes, and `_committed = UNSET` below means the re-apply could only happen on the next
918
+ * pass. Measured in `tests/renderer-ref-lifetime.test.mjs`, which asserts both halves so the
919
+ * asymmetry is a decision rather than something nobody looked at.
920
+ *
921
+ * A **self-applying** value is
922
+ * skipped: `_$apply$` receives the part and owns its own lifecycle, so telling it about detachment
923
+ * here would be a second protocol contradicting the first.
924
+ */
925
+ _release() {
926
+ const value = this._committed;
927
+ if (typeof value === 'function')
928
+ applyRef(value, null);
929
+ else if (value !== null && typeof value === 'object' && value._$apply$ === undefined)
930
+ value.value = null;
931
+ this._committed = UNSET;
932
+ }
933
+ /**
934
+ * Stable listener; swapping one function for another never touches the DOM.
935
+ *
936
+ * **It is not registered exactly once, and the difference is load-bearing.** A handler set back to
937
+ * `undefined` or `false` nulls `_handler` *without removing the listener* — inert, because
938
+ * `handleEvent` finds nothing callable — so the next non-null value sees `_handler === null` and
939
+ * calls `addEventListener` again. Measured: `function -> undefined -> function` registers twice.
940
+ *
941
+ * That is harmless only because the listener passed is **`this`, the part object itself**. The
942
+ * platform ignores a repeated `(type, listener, capture)` triple, verified with no framework
943
+ * involved — the same listener object added three times fires once. Pass a fresh closure here
944
+ * instead and dedup stops applying: every toggle through null adds another live listener, silently,
945
+ * and only in components that turn a handler off and on again.
946
+ *
947
+ * `tests/event-binding-fuzz.test.mjs` holds that as an invariant — it counts *fires*, not
948
+ * `addEventListener` calls, and making this listener a closure fails it.
949
+ *
950
+ * **Two shapes, because `addEventListener` takes two.** A function is called with the element as
951
+ * `this`; an object with a `handleEvent` method is invoked through it — the platform's own
952
+ * `EventListenerObject` protocol, which every engine accepts and lit supports. This used to call
953
+ * `.call()` unconditionally, so passing the platform's own listener shape bound successfully and
954
+ * then threw `this._handler.call is not a function` on **every** dispatch.
955
+ *
956
+ * Anything else is inert rather than throwing. A truthy non-function is a mistake, and
957
+ * development names it at the binding (see the `EVENT` branch in `_commit`) — where the mistake
958
+ * still is. Throwing here instead would raise from inside the framework on every user click, at a
959
+ * point where the value's origin is long gone.
960
+ */
446
961
  handleEvent(event) {
447
- if (this._handler)
448
- this._handler.call(this._element, event);
962
+ const handler = this._handler;
963
+ if (typeof handler === 'function')
964
+ handler.call(this._element, event);
965
+ else if (typeof handler?.handleEvent === 'function')
966
+ handler.handleEvent(event);
449
967
  }
450
- _commit(values, index) {
968
+ /**
969
+ * `adopting` is set only by `@verajs/renderer/hydrate`, and only changes what happens to the
970
+ * three form-value properties the server can express in markup — see the branch below.
971
+ */
972
+ _commit(values, index, adopting) {
451
973
  const kind = this._kind;
974
+ /** Refused in the constructor and never writes — it still has to consume its slots. */
975
+ if (kind === REFUSED)
976
+ return index + this._slots;
452
977
  let value;
453
978
  if (this._isFullValue || kind >= EVENT) {
454
979
  value = values[index]; // raw and uncoerced — events and refs receive the actual value
@@ -460,21 +985,109 @@ class AttrPart {
460
985
  joined += toText(values[index + i]) + statics[i + 1];
461
986
  value = joined;
462
987
  }
463
- if (value !== this._committed) {
464
- /** On the very first commit the attribute does not exist, so a null needs no DOM call. */
465
- const isFirst = this._committed === UNSET;
988
+ /**
989
+ * **A live property asks the element, not its own memory.**
990
+ *
991
+ * Every other kind skips a write when the value matches what it last wrote. That is what keeps
992
+ * a field someone has typed into — and it is wrong for a control whose DOM state changes as a
993
+ * *side effect of interacting with a sibling*. Clicking one radio unchecks the others with no
994
+ * event on them, so their bindings still say `true`, still match `_committed`, and never write
995
+ * again: the model and the page diverge and no amount of re-rendering reconciles them. A
996
+ * `<select>`'s options are the same shape.
997
+ *
998
+ * Deliberately narrow. This is not for text inputs — bind those with `.value` and let a
999
+ * person's typing stand. `?hidden` and plain attributes are not offered either: nothing changes
1000
+ * them behind the renderer's back, so there is nothing to re-read.
1001
+ */
1002
+ if (kind === LIVE) {
466
1003
  this._committed = value;
1004
+ /**
1005
+ * **Except while adopting.** Hydration reaches a DOM a person may already have used, and the
1006
+ * click that checked a radio happened before any handler existed to tell the store about it —
1007
+ * so re-asserting the server's choice here would throw the interaction away and nothing would
1008
+ * ever put it back. Recorded, not written, exactly as the other form properties are; the
1009
+ * first state-driven render after that applies live semantics normally.
1010
+ */
1011
+ if (!(true && adopting)) {
1012
+ const liveTarget = this._element;
1013
+ if (liveTarget[this._name] !== value)
1014
+ liveTarget[this._name] = value;
1015
+ }
1016
+ return index + this._slots;
1017
+ }
1018
+ /**
1019
+ * **A `<select>`'s value cannot be applied where it is written.**
1020
+ *
1021
+ * Assigning it selects an option, and at the moment this part commits the options may not exist:
1022
+ * parts commit in document order, so a nested `${items.map(…)}` has not run, and an `<option
1023
+ * value=${id}>` has not been given its value either. The assignment then matches nothing, and the
1024
+ * select falls back to its first option — silently showing the wrong one. Measured: a nested list
1025
+ * selected index 0 instead of 1, and dynamic option values selected nothing at all.
1026
+ * **lit-html has the same defect, byte for byte** — it was measured there too. React solves it by
1027
+ * special-casing `<select value>` and applying it after children mount, which is what this is.
1028
+ *
1029
+ * Queued rather than dirty-checked, and that is deliberate: the value can be unchanged while the
1030
+ * *options* are replaced, which drops the selection just as thoroughly. Re-asserting once per
1031
+ * render pass is what keeps it right, and a select carries one binding, so it is one push.
1032
+ */
1033
+ if (this._select) {
1034
+ this._committed = value;
1035
+ /** Adoption never re-asserts a form value — the person may have changed it. See below. */
1036
+ if (!(true && adopting))
1037
+ (pendingSelects ??= []).push(this._element, value);
1038
+ return index + this._slots;
1039
+ }
1040
+ if (value !== this._committed) {
467
1041
  if (kind === ATTR) {
1042
+ /**
1043
+ * A nullish value removes the attribute — except on the first commit of a template that
1044
+ * never statically wrote it, where a fresh clone has nothing to remove. That skip used to
1045
+ * be unconditional-removal instead, for the one case that genuinely needs it:
1046
+ * `<b title="a" title=${null}>` parses keeping the first duplicate, so the binding —
1047
+ * written last, and authoritative on the server too — must clear it. `_present` is that
1048
+ * case, read off the parsed template once ever; without it the removal was a real DOM call
1049
+ * per nullish binding per element on create — 1,000 no-ops in the 1,000-row benchmark.
1050
+ */
468
1051
  if (value == null) {
469
- if (!isFirst)
1052
+ if (this._present || this._committed !== UNSET)
470
1053
  this._element.removeAttribute(this._name);
471
1054
  }
472
- else
1055
+ else {
1056
+ /**
1057
+ * The same question `@verajs/renderer/spread` asks at its own sink, from the same home —
1058
+ * the two are deliberately separate implementations (see spread's header on why), and a
1059
+ * diagnostic that lived in only one of them would be the very defect this audit found.
1060
+ * `setAttribute` performs the DOMString conversion itself; nothing is stringified here.
1061
+ */
1062
+ if (true ) {
1063
+ const complaint = attributeValueComplaint(this._element.localName, this._name, value);
1064
+ if (complaint !== null)
1065
+ console.warn(`[vera] ${complaint}`);
1066
+ }
473
1067
  this._element.setAttribute(this._name, value);
1068
+ }
474
1069
  }
475
1070
  else if (kind === PROPERTY) {
476
1071
  const target = this._element;
477
1072
  const name = this._name;
1073
+ /**
1074
+ * **Adopting a form value: record it, do not write it.**
1075
+ *
1076
+ * `value`, `checked` and `selected` are exactly the properties `@verajs/ssr` mirrors into
1077
+ * markup, so the element already holds what this binding says — *unless a person changed
1078
+ * it*, which is the entire reason to server-render: the page is usable before the bundle
1079
+ * lands, and the window between the two is where someone types their name, ticks a box or
1080
+ * picks an option. Writing the binding then threw that away, silently, on every hydrating
1081
+ * page. The part is told it already committed this value, so it stays live and the next
1082
+ * genuine state change still applies.
1083
+ *
1084
+ * Only these three, and only while adopting. A property the server cannot express — any
1085
+ * other `.prop` — is not in the DOM yet and must be written.
1086
+ */
1087
+ if (true && adopting && (name === 'value' || name === 'checked' || name === 'selected')) {
1088
+ this._committed = value;
1089
+ return index + this._slots;
1090
+ }
478
1091
  target[name] = value;
479
1092
  /**
480
1093
  * Detection only, and deliberately not repair.
@@ -493,13 +1106,13 @@ class AttrPart {
493
1106
  * `declare` mandatory anyway, because a property assigned imperatively is unrecoverable:
494
1107
  * the renderer never saw it, and by the time `init()` runs the value is already gone.
495
1108
  *
496
- * So this is `true`-only and production pays nothing — no check, no message, no
1109
+ * So this is `true `-only and production pays nothing — no check, no message, no
497
1110
  * `whenDefined` subscription. Lit reached the same place from the other direction and
498
1111
  * throws (`lit.dev/msg/class-field-shadowing`); a warning suffices here because Vera has no
499
1112
  * prototype accessors to shadow permanently — the damage is one lost value, not a property
500
1113
  * that never updates again.
501
1114
  */
502
- if (true) {
1115
+ if (true ) {
503
1116
  const tag = this._element.localName;
504
1117
  if (tag.indexOf('-') > 0 && !customElements.get(tag)) {
505
1118
  customElements.whenDefined(tag).then(() => {
@@ -511,7 +1124,7 @@ class AttrPart {
511
1124
  * the next render either.
512
1125
  */
513
1126
  if (target[name] !== value)
514
- console.warn(`@verajs/renderer: the value bound by \`.${name}=\${…}\` on <${tag}> was replaced ` +
1127
+ console.warn(`[vera] renderer: the value bound by \`.${name}=\${…}\` on <${tag}> was replaced ` +
515
1128
  `while the element upgraded. A class field is the usual cause: at ES2022 ` +
516
1129
  `\`${name}?: …\` emits \`${name};\`, which runs during upgrade and overwrites ` +
517
1130
  `whatever was set beforehand — write it \`declare ${name}?: …\` instead, which ` +
@@ -523,10 +1136,26 @@ class AttrPart {
523
1136
  }
524
1137
  }
525
1138
  else if (kind === BOOLEAN) {
526
- if (!isFirst || value)
527
- this._element.toggleAttribute(this._name, !!value);
1139
+ /** Unconditional for the same reason: `<b hidden ?hidden=${false}>` must end up not hidden. */
1140
+ this._element.toggleAttribute(this._name, !!value);
528
1141
  }
529
1142
  else if (kind === EVENT) {
1143
+ /**
1144
+ * A listener is the most deferred call a template makes — it is validated when a *user*
1145
+ * clicks, which in development may be never. So it is checked where it is written, the same
1146
+ * rule the setters took on: the stack at dispatch no longer contains the binding.
1147
+ *
1148
+ * `false` is deliberately allowed and silent. `@click=${enabled && onClick}` is the ordinary
1149
+ * way to bind conditionally and produces exactly that, and it already behaves correctly —
1150
+ * `handleEvent` finds nothing callable and does nothing. `true` is not produced by any
1151
+ * idiom, so it is named along with strings, numbers and objects that cannot listen.
1152
+ */
1153
+ if (true && value != null && value !== false && typeof value !== 'function' &&
1154
+ typeof value?.handleEvent !== 'function')
1155
+ console.warn(`[vera] @${this._name} on <${this._element.localName}> was given ${typeof value === 'object' ? 'an object with no handleEvent method' : `a ${typeof value}`}, ` +
1156
+ `which cannot listen — the event will do nothing.\n` +
1157
+ `Pass a function, or an object with a handleEvent method. A missing handler is ` +
1158
+ `\`undefined\` or \`false\`, both of which are fine; this is neither.`);
530
1159
  if (this._handler === null && value != null)
531
1160
  this._element.addEventListener(this._name, this);
532
1161
  this._handler = value ?? null;
@@ -537,22 +1166,112 @@ class AttrPart {
537
1166
  * the element assigned to `.value` — which makes core's own `ref()` double as an element
538
1167
  * ref, reactively. Runs once per distinct value, not once per render.
539
1168
  */
1169
+ notifyOnRemoval = true;
540
1170
  if (typeof value === 'function')
541
- value(this._element);
542
- else if (typeof value === 'object')
543
- value.value = this._element;
1171
+ applyRef(value, this._element);
1172
+ else if (typeof value === 'object') {
1173
+ /**
1174
+ * A self-applying value: anything that knows what to do with an element applies itself.
1175
+ * `@verajs/renderer/spread` is the first, and the whole protocol is this one property
1176
+ * read — the implementation lives in that entry, so an app that never spreads pays for
1177
+ * the check and nothing else. `_$…$` is exempt from property mangling, like `_$litType$`.
1178
+ *
1179
+ * Deliberately confined to the element position, which is rare. A protocol in the text,
1180
+ * attribute or property commits would sit in the hot path every benchmark measures.
1181
+ */
1182
+ const self = value;
1183
+ /** The part is passed as the ownership key: one element can carry several spreads. */
1184
+ if (self._$apply$)
1185
+ self._$apply$(this._element, this);
1186
+ else
1187
+ self.value = this._element;
1188
+ }
544
1189
  // any other value type at element position is consumed and ignored
545
1190
  }
1191
+ this._committed = value;
546
1192
  }
547
1193
  return index + this._slots;
548
1194
  }
549
1195
  }
1196
+ /**
1197
+ * `<select>.value` assignments held until the whole pass has committed — see the note in `_commit`.
1198
+ * Flat pairs rather than tuples: one array, no per-entry allocation.
1199
+ */
1200
+ let pendingSelects = null;
1201
+ const flushSelects = () => {
1202
+ const queued = pendingSelects;
1203
+ if (queued === null)
1204
+ return;
1205
+ /** Cleared first: an assignment can run a `change` handler that renders again. */
1206
+ pendingSelects = null;
1207
+ for (let i = 0; i < queued.length; i += 2)
1208
+ queued[i].value = queued[i + 1];
1209
+ };
1210
+ const SCRATCH = doc.createDocumentFragment();
1211
+ /**
1212
+ * Marks a node as the render root's OWN output — see `ChildPart._insert`. Sigil-named so property
1213
+ * mangling cannot rename it: this is read by `@verajs/renderer/slots`, across a bundle boundary,
1214
+ * and a module-scoped Symbol would be minted twice on a CDN page (the `@verajs/styles` lesson).
1215
+ *
1216
+ * A fragment is stamped through to its children, because inserting one moves the children and the
1217
+ * fragment itself never enters the document — the observer reports the children.
1218
+ *
1219
+ * **Defined rather than assigned, so it is NON-ENUMERABLE.** A plain `node._$own$ = true` is an own
1220
+ * enumerable property: measured, it then shows up in `Object.keys(element)` — which is `[]` for
1221
+ * every other DOM element — and in `for…in`. Invisibility to everything outside the framework is
1222
+ * the whole reason this is a property and not a marker or an attribute, and an enumerable one is
1223
+ * not invisible. The descriptor is shared, so this allocates nothing per node, and the path is
1224
+ * gated on slots being wired, so no app that does not use them ever reaches it.
1225
+ */
1226
+ const OWN_DESCRIPTOR = { value: true, enumerable: false, configurable: true, writable: true };
1227
+ /**
1228
+ * The stamp is VALUED, and the value is the discriminator (`docs` in the slots module read it):
1229
+ *
1230
+ * `true` — the render root's own output: never slot content.
1231
+ * a ChildPart — light content PLACED by that part from an outer template. The part identity
1232
+ * is the ordering group: a grown row belongs after ITS part's other rows, and
1233
+ * `<host>${a}${b}</host>` must not interleave a's refill into b's content —
1234
+ * which is exactly what happens if the group is the render root, shared by both.
1235
+ * absent — an imperative user mutation; the light region orders it by document position.
1236
+ *
1237
+ * One shared, mutated descriptor: `defineProperty` reads it synchronously, so this allocates
1238
+ * nothing per node while keeping the property non-enumerable (see the invisibility note above).
1239
+ */
1240
+ const stampOwn = (node, value = true) => {
1241
+ OWN_DESCRIPTOR.value = value;
1242
+ if (node.nodeType === 11) {
1243
+ for (let child = node.firstChild; child !== null; child = child.nextSibling)
1244
+ Object.defineProperty(child, '_$own$', OWN_DESCRIPTOR);
1245
+ return;
1246
+ }
1247
+ Object.defineProperty(node, '_$own$', OWN_DESCRIPTOR);
1248
+ };
1249
+ /** A row is either an element-mode instance or a markered part; both can hold appliers. */
1250
+ const detachItem = (item) => {
1251
+ item._instance?._teardown();
1252
+ item._part?._detach();
1253
+ };
550
1254
  class Instance {
551
1255
  _parts = [];
552
1256
  _fragment;
553
1257
  constructor(template) {
554
- /** cloneNode over importNode: same document, and it measures slightly cheaper. */
555
- this._fragment = template._element.content.cloneNode(true);
1258
+ /**
1259
+ * `importNode`, not `cloneNode` — the difference is custom-element upgrade, not the document.
1260
+ * Template content lives in the inert template document, so `cloneNode` copies stay
1261
+ * un-upgraded until insertion; a `.prop` committed in that window lands as an OWN property
1262
+ * that permanently shadows a defined class's setter (the setter never fires — every
1263
+ * accessor-based element, Lit's included, receives a dead value) and a bound value on a
1264
+ * class-field element is clobbered by the field initializer at insert, silently, because the
1265
+ * `whenDefined` detector below only watches definitions that arrive LATE. Hydration commits
1266
+ * onto server-parsed, already-upgraded elements, so the two render paths disagreed about the
1267
+ * same template. `importNode`'s cloning steps upgrade defined elements at clone time — in
1268
+ * every engine and in jsdom — which makes the commit order match hydration and the platform.
1269
+ * Undefined elements are untouched: nothing can upgrade them, and the pre-upgrade posture
1270
+ * (own property, clobber on define, development warning) stands as pinned in
1271
+ * `tests/pre-upgrade-property.test.mjs`. Measured cost of losing `cloneNode`: ~2–7% of the
1272
+ * raw clone operation across the three engines — nanoseconds per instance.
1273
+ */
1274
+ this._fragment = doc.importNode(template._element.content, true);
556
1275
  const templateParts = template._parts;
557
1276
  /** Shared walker, ELEMENT | TEXT — child anchors are the primed text nodes themselves. */
558
1277
  instanceWalker.currentNode = this._fragment;
@@ -570,14 +1289,130 @@ class Instance {
570
1289
  }
571
1290
  this._parts.push(templatePart._type === CHILD
572
1291
  ? new TextPart(node)
573
- : new AttrPart(node, templatePart._name, templatePart._statics));
1292
+ : new AttrPart(node, templatePart._name, templatePart._statics, templatePart._present));
1293
+ }
1294
+ /**
1295
+ * Slot records mount OUTSIDE the parts array — one extra walk from the top, paid only by
1296
+ * templates that HAVE slots, only inside a renderInto commit (null root — hydration's
1297
+ * adoption path — stays inert), and only when the 'slot' insert answers. Taking over sets
1298
+ * `notifyOnRemoval`: `_$park$` must rescue the USER'S nodes before a bulk `_clear` discards
1299
+ * the DOM holding them on a branch-away. `_update` never sees any of this.
1300
+ */
1301
+ if (template._seam !== undefined && _slotRoot !== null) {
1302
+ const slotRecords = template._slots;
1303
+ /**
1304
+ * RESOLVE every slot element to its clone in ONE walk, and mount them AFTER the first
1305
+ * `_update` — see `_mountSlots`. Collect-then-act, because the seam MUTATES the fragment
1306
+ * (it lifts each `<slot>` out and drops in anchors) and a walk that interleaved resolution
1307
+ * with those mutations would read shifted indices and miss later slots.
1308
+ */
1309
+ instanceWalker.currentNode = this._fragment;
1310
+ nodeIndex = -1;
1311
+ const slotNodes = [];
1312
+ for (let i = 0; i < slotRecords.length; i++) {
1313
+ while (nodeIndex < slotRecords[i]) {
1314
+ node = instanceWalker.nextNode();
1315
+ nodeIndex++;
1316
+ }
1317
+ slotNodes.push(node);
1318
+ }
1319
+ this._pendingSlots = slotNodes;
1320
+ }
1321
+ /** Standalone rather than an `else` branch: `_slotless` is only ever set when there was no
1322
+ * seam, so the condition stands alone — and a lone `if (true …)` folds away cleanly. */
1323
+ if (true && template._slotless === true && _slotRoot !== null && _slotRoot.nodeType === 1) {
1324
+ /**
1325
+ * **A `<slot>` in a LIGHT render that nothing will distribute.** Both ways of arriving here
1326
+ * are silent otherwise, and both leave the same confusing picture. Measured, for a host given
1327
+ * `<b slot="a">MINE</b>`:
1328
+ *
1329
+ * <b slot="a">MINE</b><!----><div class="box"><slot name="a">FB</slot></div>
1330
+ *
1331
+ * — the content is not destroyed, it is stranded ahead of the render while the slot shows its
1332
+ * fallback. The message says "any content the host is given" rather than asserting the host
1333
+ * HAS some: a component that consumes its own children before rendering and also declares
1334
+ * slots — `@verajs/ui`'s select is one — warns with nothing stray on the page, and a reader
1335
+ * sent looking for markup that is not there concludes the diagnostic is confused.
1336
+ *
1337
+ * 1. `@verajs/renderer/slots` was never wired at all.
1338
+ * 2. It was wired AFTER this template first rendered. Templates are interned per call site
1339
+ * for the life of the page and resolve the seam once, at construction — so a component
1340
+ * that rendered before the wiring keeps a slotless template forever, and every later use
1341
+ * of it fails the same way. Measured: the same `draw()` distributes at a fresh call site
1342
+ * and not at this one.
1343
+ *
1344
+ * A shadow root never reaches here: the platform slots there, which is why this is gated on
1345
+ * an element root.
1346
+ */
1347
+ warnSlotless(_slotRoot);
574
1348
  }
575
1349
  }
1350
+ /**
1351
+ * One walk, both jobs: release the element refs in this instance and tell any child applier
1352
+ * under it that it is going away.
1353
+ *
1354
+ * They were two walks over the same array — `_release` for refs, `_detach` for appliers — which
1355
+ * is the same tree traversed twice for two answers that arrive at the same moment. Merged, the
1356
+ * per-part cost is one `_kind` compare and one `_upgraded` read.
1357
+ *
1358
+ * Reached only when this instance's template holds a ref, or some applier somewhere declared
1359
+ * teardown. An app with neither never runs it: this is the per-node work the bulk removal exists
1360
+ * to skip, and the gate is what keeps it out of the path.
1361
+ *
1362
+ * Through `_upgraded`, not just `_parts`. A child position is instantiated as a `TextPart` and
1363
+ * **upgrades** to a `ChildPart` the first time it takes an object — so the part holding a
1364
+ * applier is almost never the one in this array, it is the one that array's entry points at.
1365
+ * Walking `_parts` alone found nothing at all.
1366
+ */
1367
+ _teardown() {
1368
+ const parts = this._parts;
1369
+ for (let i = 0; i < parts.length; i++) {
1370
+ const part = parts[i];
1371
+ if (part._kind === REF)
1372
+ part._release();
1373
+ part._upgraded?._detach();
1374
+ }
1375
+ /** Taken-over slots park the USER'S nodes before this instance's DOM is discarded. */
1376
+ this._slotStates?.forEach((state) => state._$park$?.());
1377
+ }
576
1378
  _update(values) {
577
1379
  let valueIndex = 0;
578
1380
  const parts = this._parts;
579
1381
  for (let i = 0; i < parts.length; i++)
580
1382
  valueIndex = parts[i]._commit(values, valueIndex);
1383
+ if (this._pendingSlots !== undefined)
1384
+ this._mountSlots();
1385
+ }
1386
+ /**
1387
+ * **Slots mount after the first `_update`, not during construction, because a `<slot>`'s own
1388
+ * bindings are part of its meaning.** `<slot name=${section}>` has no name at all until its
1389
+ * `AttrPart` has committed, and mounting first read the static markup and got `''` — the slot
1390
+ * registered as a second DEFAULT slot, took the default content, and left the real default slot
1391
+ * showing fallback. Committing first also means `@slotchange` and `&ref` are already attached to
1392
+ * the element by the time anything is dispatched on it.
1393
+ *
1394
+ * Once per instance: the fields are cleared here and every later `_update` costs one compare.
1395
+ */
1396
+ _mountSlots() {
1397
+ const slotNodes = this._pendingSlots;
1398
+ this._pendingSlots = undefined;
1399
+ /**
1400
+ * `_slotRoot` still holds the container: it is set for the whole of one `renderInto` and every
1401
+ * instance under it — nested templates included — is constructed and first-updated inside that
1402
+ * same synchronous span, so this is the root the constructor saw.
1403
+ */
1404
+ const root = _slotRoot;
1405
+ const seam = slotSeam();
1406
+ if (seam === undefined || root === null)
1407
+ return;
1408
+ for (let i = 0; i < slotNodes.length; i++) {
1409
+ const slot = slotNodes[i];
1410
+ const state = seam(slot, root, slot.getAttribute('name') ?? '');
1411
+ if (state != null) {
1412
+ (this._slotStates ??= []).push(state);
1413
+ notifyOnRemoval = true;
1414
+ }
1415
+ }
581
1416
  }
582
1417
  }
583
1418
  /** A single property read — this runs once per list item per render, so it must be minimal. */
@@ -613,9 +1448,26 @@ class TextPart {
613
1448
  */
614
1449
  const start = comment();
615
1450
  const end = comment();
616
- const parent = this._text.parentNode;
617
- parent.insertBefore(start, this._text);
618
- parent.insertBefore(end, this._text.nextSibling);
1451
+ /**
1452
+ * **Markers go where the part LIVES, which is not always where its text node is.** In a
1453
+ * light host wired for slots, this text node was captured and distributed into the
1454
+ * component's tree — planting markers beside it there put them inside the slot's range,
1455
+ * the slot's next fill swept them into the holding fragment, and the part spent the rest
1456
+ * of the page rendering into detached space (measured: `<host>${text}</host>` toggling
1457
+ * through null showed FALLBACK forever). `_$home$` answers with the host's light-region
1458
+ * sentinel for a captured node and null for everything else, so every app without light
1459
+ * slots takes the second branch untouched.
1460
+ */
1461
+ const home = slotSeam()?._$home$?.(this._text) ?? null;
1462
+ const parent = home !== null ? home.parentNode : this._text.parentNode;
1463
+ if (home !== null) {
1464
+ parent.insertBefore(start, home);
1465
+ parent.insertBefore(end, home);
1466
+ }
1467
+ else {
1468
+ parent.insertBefore(start, this._text);
1469
+ parent.insertBefore(end, this._text.nextSibling);
1470
+ }
619
1471
  const part = new ChildPart(start, end);
620
1472
  part._mode = TEXT;
621
1473
  part._text = this._text;
@@ -631,11 +1483,82 @@ class TextPart {
631
1483
  return index + 1;
632
1484
  }
633
1485
  }
1486
+ /**
1487
+ * The registry this renderer reads `'value'` handlers from, handed over by {@link renderer}.
1488
+ *
1489
+ * Not imported. The renderer carries no registry of its own for the same reason the router does
1490
+ * not: a production bundle inlines `@verajs/inserts`, so importing it would give this package one
1491
+ * registry and core another, and an app would register into whichever it happened to import — the
1492
+ * failure `connectInserts` used to repair.
1493
+ */
1494
+ let registry = null;
1495
+ /**
1496
+ * The ONE lookup for the `'slot'` insert. Three callers want the same thing in the same shape —
1497
+ * template construction (are there slots to record?), the first render into a container (capture
1498
+ * the host's children), and hydration's rescue (un-distribute before a mismatch discards) — and
1499
+ * the seam carries its cross-bundle members as sigil-named keys, which every caller had to spell
1500
+ * out again. One accessor, spelled once.
1501
+ */
1502
+ /**
1503
+ * **Whether ANY app on this page wired light slots**, latched the first time the seam answers.
1504
+ *
1505
+ * The ownership stamp in `_insert`/`$c` exists only for `@verajs/renderer/slots` to read, and its
1506
+ * guard has to be free for everyone else — `_slotRoot` is set for every `renderInto`, so without
1507
+ * this an app with no slots at all would stamp every top-level node it renders, which for a list
1508
+ * at the root is a property write per ROW. One boolean instead, false for the life of a page that
1509
+ * never wires them.
1510
+ */
1511
+ let slotsWired = false;
1512
+ const slotSeam = () => {
1513
+ const seam = registry?.get('slot')?.[0];
1514
+ if (seam !== undefined)
1515
+ slotsWired = true;
1516
+ return seam;
1517
+ };
1518
+ const noHandlers = [];
1519
+ const valueHandlers = () => (registry ? (registry.get('value') ?? noHandlers) : noHandlers);
1520
+ /**
1521
+ * Kinds this package still ships. They read from a local list rather than the registry because the
1522
+ * renderer cannot register into one it was merely handed — that needs `wire`, which it does not
1523
+ * import. The list empties when they move to packages; until then a wired handler is checked first,
1524
+ * so a module can pre-empt a built-in exactly as the priority order promises.
1525
+ */
1526
+ const builtIns = [];
1527
+ /**
1528
+ * Whether anything in this process has asked to be told when a subtree is removed — an element ref
1529
+ * to release, or a child applier that declared `_$detach$`.
1530
+ *
1531
+ * **One flag for both, and it is process-wide.** Teardown cannot be discovered from the template the
1532
+ * way a ref can — a ref is a `&` part the scan sees, while an applier arrives as a *value* and no
1533
+ * template shape predicts it — so the coarser gate is the only one that serves both.
1534
+ *
1535
+ * The finer, per-template gate for refs was measured and dropped: it saved 34 B less than nothing,
1536
+ * because the walk it avoided is not the expensive part. With one unrelated ref on the page, a
1537
+ * 1 000-row clear walks 1 000 instances and measures 3.98 ms against 4.03 ms with no ref at all —
1538
+ * the DOM removal dominates completely. What matters is that an app asking for neither walks
1539
+ * **zero**, and that still holds.
1540
+ */
1541
+ let notifyOnRemoval = false;
1542
+ /**
1543
+ * The hydrate entry's way to raise the flag. Every CLIENT path that creates removal work sets
1544
+ * `notifyOnRemoval` where the work is created (a ref committing, a slot mounting, an applier
1545
+ * declaring `_$detach$`) — but hydration ADOPTS its seams through its own walk in `hydrate.ts`,
1546
+ * a different module compiled into the same bundle, and a page whose only seams were adopted
1547
+ * left the flag down. `_clear` then skipped `_detach` entirely: no `_teardown`, no `_$park$`,
1548
+ * and the user's server-adopted slotted content was destroyed on the first branch-away — the
1549
+ * exact content-loss class the seam's park exists to prevent, reintroduced one entry over.
1550
+ */
1551
+ const declareRemovalWork = () => {
1552
+ notifyOnRemoval = true;
1553
+ };
1554
+
1555
+ const _applierSwaps = /* @__PURE__ */ new WeakMap();
634
1556
  /** What a ChildPart currently contains. */
635
1557
  const EMPTY = 0;
636
1558
  const TEXT = 1;
637
1559
  const TEMPLATE = 2;
638
1560
  const LIST = 3;
1561
+ const NODE = 4;
639
1562
  let _profileHook = null;
640
1563
  class ChildPart {
641
1564
  _start;
@@ -651,6 +1574,10 @@ class ChildPart {
651
1574
  _keyedList = false;
652
1575
  /** Held instances by template identity; survives clears so state outlives interim content. */
653
1576
  _held = null;
1577
+ /** Whatever the last `_$child$` at this part returned — its continuity across renders. */
1578
+ _applierState = undefined;
1579
+ /** Which applier that state belongs to, so two of them at one part cannot read each other's. */
1580
+ _applier = undefined;
654
1581
  constructor(start, end) {
655
1582
  this._start = start;
656
1583
  this._end = end;
@@ -659,13 +1586,117 @@ class ChildPart {
659
1586
  this._set(values[index]);
660
1587
  return index + 1;
661
1588
  }
1589
+ /**
1590
+ * **A component's own output is STAMPED, so the slot system cannot mistake it for content.**
1591
+ *
1592
+ * `@verajs/renderer/slots` captures a top-level element carrying a `slot` attribute as the
1593
+ * host's content — which a component's own rendered root may legitimately be, when it renders
1594
+ * something destined for ITS parent's slot. Measured: with slots wired,
1595
+ * `renderInto(html\`<div slot="x">…</div>\`, element)` distributed the component's output into
1596
+ * its own holding fragment and the component rendered NOTHING, on the first render, with no
1597
+ * children involved and nothing thrown.
1598
+ *
1599
+ * The renderer is the one party that knows: it is inserting at the top level of the container
1600
+ * it was asked to render into. `_slotRoot` is that container for the whole of one `renderInto`,
1601
+ * so `parent === _slotRoot` is exactly "this is the component's own output" and distinguishes it
1602
+ * from `<x-card>${value}</x-card>`, where the part's parent is the host but the render root is
1603
+ * an ancestor — the user's light content, which must still be captured.
1604
+ *
1605
+ * Two comparisons on a path that is already touching the DOM, and the stamp is a PROPERTY:
1606
+ * invisible to CSS, to serialization and to `children`, unlike any marker or attribute, and it
1607
+ * rides on text nodes, which no attribute can. An app without slots wired writes it and nothing
1608
+ * ever reads it.
1609
+ */
1610
+ /**
1611
+ * **One property read decides all stamping, and root-part-ness decides the value.**
1612
+ *
1613
+ * `_$hosted$` is set on the host element itself by `@verajs/renderer/slots` at capture, so
1614
+ * "does anything care about ownership here" is a single own-property read — no seam call, no
1615
+ * registry lookup, and pages that are not captured hosts (every container in most apps) cost
1616
+ * exactly that read and write nothing. The mark cannot go stale in the direction that matters:
1617
+ * a part's first commit runs in a detached fragment before its host is captured, reads
1618
+ * `undefined`, and stamps nothing — and that content is exactly what the initial capture walk
1619
+ * lifts anyway. Every later commit sees the mark.
1620
+ *
1621
+ * The VALUE is structural, not temporal. `_end === null` is true of root parts alone (see
1622
+ * `_clear`), and a root part's inserts are by definition the render's own output — a fact that
1623
+ * stays true for an applier committing from a microtask hours after `renderInto` returned,
1624
+ * where the earlier `parent === _slotRoot` test read null and left ASYNC output unstamped for
1625
+ * the flipped capture rule to eat. Everything else inserting into a host is placing content
1626
+ * INTO it from outside, stamped with the part — the ordering group.
1627
+ */
662
1628
  _insert(node) {
663
- this._start.parentNode.insertBefore(node, this._end);
1629
+ const parent = this._start.parentNode;
1630
+ if (slotsWired && parent._$hosted$ === true)
1631
+ stampOwn(node, this._end === null ? true : this);
1632
+ parent.insertBefore(node, this._end);
1633
+ }
1634
+ /**
1635
+ * Tells every child applier under this part that it is going away.
1636
+ *
1637
+ * Reached only when some applier somewhere declared teardown — see `notifyOnRemoval` — because
1638
+ * this is the per-node walk the bulk removal exists to skip. **Every** removal path calls it, not
1639
+ * just `_clear`: a keyed row is dropped by moving its nodes to a scratch fragment and an index-mode
1640
+ * list shrinks by removing nodes directly, so a version that only hooked `_clear` notified a
1641
+ * applier when its container was replaced and stayed silent when its row was deleted — told
1642
+ * sometimes, which is a worse contract than never.
1643
+ */
1644
+ _detach() {
1645
+ if (this._applier !== undefined)
1646
+ this._applier._$detach$?.(this._applierState);
1647
+ this._instance?._teardown();
1648
+ const items = this._items;
1649
+ if (items != null)
1650
+ for (let i = 0; i < items.length; i++)
1651
+ detachItem(items[i]);
664
1652
  }
665
1653
  _clear() {
1654
+ /**
1655
+ * One gate, two jobs. A template that holds an element ref must release it; a subtree holding a
1656
+ * applier that declared teardown must be told. Both are found by the same walk, and an app
1657
+ * with neither reads two booleans and walks nothing.
1658
+ */
1659
+ if (notifyOnRemoval)
1660
+ this._detach();
666
1661
  const parent = this._start.parentNode;
667
1662
  const end = this._end;
1663
+ const items = this._items;
668
1664
  /**
1665
+ * **Content that is no longer between the markers.** `@verajs/renderer/slots` distributes a
1666
+ * light host's children by MOVING them into the component's tree, so a part rendering those
1667
+ * children keeps its markers in the host while its content lives inside the component.
1668
+ *
1669
+ * Both branches below are wrong for that, and wrong in opposite directions. The walk finds
1670
+ * the markers adjacent and removes nothing — the content stays on screen after being cleared
1671
+ * (a template swap in a light host showed the OLD template forever). The whole-parent fast
1672
+ * path is the dangerous one: it would `textContent = ''` the HOST, component render and all.
1673
+ *
1674
+ * Every mode knows its content by IDENTITY, which is parent-agnostic and split-proof: items
1675
+ * through `$m`, TEXT through `_text`, NODE through `_value`, TEMPLATE through the top-level
1676
+ * node array recorded at commit. The one shape that cannot be found this way is a
1677
+ * DocumentFragment committed at NODE position (its children scatter and it keeps no record);
1678
+ * that falls through to the walk, as before.
1679
+ */
1680
+ if (this._start.nextSibling === end && this._mode !== EMPTY) {
1681
+ if (items !== null) {
1682
+ for (const item of items)
1683
+ if (item !== null)
1684
+ this.$m(item, null, SCRATCH);
1685
+ SCRATCH.textContent = '';
1686
+ }
1687
+ else if (this._mode === TEXT) {
1688
+ this._text?.remove();
1689
+ }
1690
+ else if (this._mode === TEMPLATE) {
1691
+ if (Array.isArray(this._value))
1692
+ for (const node of this._value)
1693
+ node.remove();
1694
+ }
1695
+ else if (this._mode === NODE && typeof this._value.remove === 'function') {
1696
+ this._value.remove();
1697
+ }
1698
+ }
1699
+ else /**
669
1700
  * When this part owns its parent's entire contents, one `textContent = ''` replaces removing
670
1701
  * every node individually. For a 1 000-row table body that is the difference between ~22 ms
671
1702
  * (lit-html's per-node teardown) and ~5 ms.
@@ -677,8 +1708,7 @@ class ChildPart {
677
1708
  * always owns an end marker, so `_end === null` alone never held for it.
678
1709
  *
679
1710
  * Re-appending both anchors in order restores the part's boundary exactly as it was.
680
- */
681
- if (this._start.previousSibling === null && (end === null || end.nextSibling === null)) {
1711
+ */ if (this._start.previousSibling === null && (end === null || end.nextSibling === null)) {
682
1712
  parent.textContent = '';
683
1713
  parent.appendChild(this._start);
684
1714
  if (end !== null)
@@ -702,6 +1732,27 @@ class ChildPart {
702
1732
  this._instance = null;
703
1733
  this._items = null;
704
1734
  this._shape = null;
1735
+ this._applierState = undefined;
1736
+ this._applier = undefined;
1737
+ }
1738
+ /**
1739
+ * How a child-position applier renders. Named to survive property mangling — `/^_[a-z]/` is the
1740
+ * pattern, and `_$…$` does not match it — because this is the half of the protocol that third
1741
+ * parties call.
1742
+ */
1743
+ _$commit$(value) {
1744
+ /**
1745
+ * The applier's own state survives its own rendering. Committing different content usually
1746
+ * runs `_clear`, which drops the state so a part that was emptied by *anything else* cannot
1747
+ * hand an applier continuity it no longer has — but an applier rendering its own next value
1748
+ * has not gone away, and losing continuity there made `until()` fall back to its placeholder on
1749
+ * the render after it resolved.
1750
+ */
1751
+ const applierState = this._applierState;
1752
+ const applier = this._applier;
1753
+ this._set(value);
1754
+ this._applierState = applierState;
1755
+ this._applier = applier;
705
1756
  }
706
1757
  _set(value) {
707
1758
  if (value == null) {
@@ -738,7 +1789,7 @@ class ChildPart {
738
1789
  * them, in practice), commit costs one identity compare before touching the values.
739
1790
  */
740
1791
  if (this._shape === value.strings) {
741
- if (true && _profileHook)
1792
+ if (true && _profileHook)
742
1793
  ;
743
1794
  this._instance._update(value.values);
744
1795
  return;
@@ -748,24 +1799,92 @@ class ChildPart {
748
1799
  * subtree below is about to be destroyed and rebuilt rather than updated. That is what
749
1800
  * `?hidden=${…}` over a swapped subtree exists to avoid, and it is otherwise invisible.
750
1801
  */
751
- if (true && _profileHook) ;
1802
+ if (true && _profileHook) ;
752
1803
  const template = getTemplate(value);
753
1804
  if (this._mode !== EMPTY)
754
1805
  this._clear();
755
1806
  const instance = new Instance(template);
756
1807
  instance._update(value.values);
1808
+ /**
1809
+ * The instance's top-level nodes, recorded while they are still in the fragment. `_value`
1810
+ * is unused in TEMPLATE mode, and this is what lets `_clear` and `hold`'s parking find the
1811
+ * content after `@verajs/renderer/slots` has moved it out of the marker range — per node,
1812
+ * parent-agnostic, so even content split across two slots comes back. Costs one small array
1813
+ * on a path that just built an Instance and cloned a template; same-shape updates never
1814
+ * reach here.
1815
+ */
1816
+ this._value = [...instance._fragment.childNodes];
757
1817
  this._insert(instance._fragment);
758
1818
  this._instance = instance;
759
1819
  this._shape = value.strings;
760
1820
  this._mode = TEMPLATE;
761
1821
  return;
762
1822
  }
763
- if (Array.isArray(value)) {
764
- this._commitList(value);
1823
+ const handlers = valueHandlers();
1824
+ for (let i = 0; i < handlers.length; i++)
1825
+ if (handlers[i](this, value))
1826
+ return;
1827
+ for (let i = 0; i < builtIns.length; i++)
1828
+ if (builtIns[i](this, value))
1829
+ return;
1830
+ /**
1831
+ * **A child-position value that applies itself.** The same idea as `_$apply$` at element
1832
+ * position — which is how `@verajs/renderer/spread` ships as a separate package the renderer
1833
+ * knows nothing about — at the one other position worth extending.
1834
+ *
1835
+ * `_$child$(part, previous)` is handed the part and whatever it returned last time at this
1836
+ * part, and calls `part._$commit$(value)` to render content. Keeping continuity in the return
1837
+ * value rather than in an applier *instance* is what keeps this a protocol rather than a
1838
+ * framework: there is no base class, no factory and no lifecycle to learn, and an applier is
1839
+ * an object literal.
1840
+ *
1841
+ * Placed **after** the template check on purpose. A template is overwhelmingly the common
1842
+ * object at a child position, and it returns above without ever reading this property — so the
1843
+ * check costs the hot path nothing and only arrays, nodes and appliers pay for it. Measured:
1844
+ * +22 B gzipped, and no runtime difference distinguishable from noise.
1845
+ *
1846
+ * There is deliberately no teardown hook. `_clear` bulk-removes DOM and, when the part owns its
1847
+ * parent, does `parent.textContent = ''` — the thing that makes clearing a 1 000-row table ~5 ms
1848
+ * against lit-html's ~22 ms. Calling teardown on a nested applier would mean walking the part
1849
+ * tree on every removal, which is precisely the per-node work that fast path exists to skip. So
1850
+ * an applier here can render, and cannot yet be told it has gone away.
1851
+ */
1852
+ const applyChild = value._$child$;
1853
+ if (applyChild !== undefined) {
1854
+ /** `previous` belongs to *this* applier; a different one at the same part starts fresh. */
1855
+ const previous = this._applier === applyChild ? this._applierState : undefined;
1856
+
1857
+ if (true && this._applier !== undefined && this._applier !== applyChild) {
1858
+ const swaps = (_applierSwaps.get(this) ?? 0) + 1;
1859
+ _applierSwaps.set(this, swaps);
1860
+ if (swaps === 3) {
1861
+ console.warn(`[vera] a child applier changed identity ${swaps} times at one part, so \`previous\` ` +
1862
+ `is always undefined and it restarts every render.\n` +
1863
+ `Hoist the applier — written as an object-literal method it is a new function per ` +
1864
+ `call:\n\n` +
1865
+ ` function applyThing(part, previous) { … } // once, at module scope\n` +
1866
+ ` const thing = (x) => ({ _$child$: applyThing, x }); // state on the object\n`);
1867
+ }
1868
+ }
1869
+ this._applier = applyChild;
1870
+ if (applyChild._$detach$ !== undefined)
1871
+ notifyOnRemoval = true;
1872
+ this._applierState = applyChild.call(value, this, previous);
765
1873
  return;
766
1874
  }
767
- if (typeof value[Symbol.iterator] === 'function') {
768
- this._commitList([...value]);
1875
+ if (value.nodeType !== undefined) {
1876
+ /**
1877
+ * A DOM node renders as itself — a canvas a charting library owns, a `<template>`'s content,
1878
+ * an element built by hand. Placed after the template check and before the list check
1879
+ * because `nodeType` is one property read and nothing else that reaches here has one.
1880
+ */
1881
+ if (this._mode !== NODE || this._value !== value) {
1882
+ if (this._mode !== EMPTY)
1883
+ this._clear();
1884
+ this._insert(value);
1885
+ this._value = value;
1886
+ this._mode = NODE;
1887
+ }
769
1888
  return;
770
1889
  }
771
1890
  // any other object: render as text
@@ -779,13 +1898,21 @@ class ChildPart {
779
1898
  }
780
1899
  const held = (this._held ??= new Map());
781
1900
  if (this._mode === TEMPLATE) {
782
- /** Park the live nodes back in their instance's own (empty) fragment. */
1901
+ /** Park the live nodes back in their instance's own (empty) fragment. When the range is
1902
+ * empty but content existed, slots relocated it — the recorded top-level nodes park it
1903
+ * from wherever it lives, split slots and holding included. */
783
1904
  const fragment = this._instance._fragment;
784
- let node = this._start.nextSibling;
785
- while (node !== this._end) {
786
- const next = node.nextSibling;
787
- fragment.appendChild(node);
788
- node = next;
1905
+ if (this._start.nextSibling === this._end && Array.isArray(this._value)) {
1906
+ for (const node of this._value)
1907
+ fragment.appendChild(node);
1908
+ }
1909
+ else {
1910
+ let node = this._start.nextSibling;
1911
+ while (node !== this._end) {
1912
+ const next = node.nextSibling;
1913
+ fragment.appendChild(node);
1914
+ node = next;
1915
+ }
789
1916
  }
790
1917
  held.set(this._shape, this._instance);
791
1918
  }
@@ -794,6 +1921,7 @@ class ChildPart {
794
1921
  }
795
1922
  const instance = held.get(result.strings) ?? new Instance(getTemplate(result));
796
1923
  instance._update(result.values);
1924
+ this._value = [...instance._fragment.childNodes];
797
1925
  this._insert(instance._fragment);
798
1926
  this._instance = instance;
799
1927
  this._shape = result.strings;
@@ -803,7 +1931,15 @@ class ChildPart {
803
1931
  * Creates one list item. A single-root template instance becomes an element-mode item with no
804
1932
  * markers at all; anything else gets its own start/end marker pair so moves can never dangle.
805
1933
  */
806
- _createItem(value, parent, ref) {
1934
+ $c(value, parent, ref) {
1935
+ /** Rows reach the DOM here rather than through `_insert`; same one-read gate, same
1936
+ * structural value — a root list's rows are the render's own output, any other part's rows
1937
+ * are content it places into the host, stamped with the part as the ordering group. */
1938
+ const stamp = slotsWired && parent._$hosted$ === true
1939
+ ? this._end === null
1940
+ ? true
1941
+ : this
1942
+ : null;
807
1943
  if (value !== null && typeof value === 'object' && value.strings !== undefined) {
808
1944
  const result = value;
809
1945
  const template = getTemplate(result);
@@ -811,9 +1947,11 @@ class ChildPart {
811
1947
  instance._update(result.values);
812
1948
  const rootNode = instance._fragment.firstChild;
813
1949
  if (rootNode !== null && rootNode.nodeType === 1 && rootNode.nextSibling === null) {
1950
+ if (stamp !== null)
1951
+ stampOwn(rootNode, stamp);
814
1952
  parent.insertBefore(rootNode, ref);
815
1953
  return {
816
- _key: result.key,
1954
+ $k: result.key,
817
1955
  _element: rootNode,
818
1956
  _instance: instance,
819
1957
  _shape: result.strings,
@@ -825,15 +1963,18 @@ class ChildPart {
825
1963
  part._instance = instance;
826
1964
  part._shape = result.strings;
827
1965
  part._mode = TEMPLATE;
1966
+ part._value = [...instance._fragment.childNodes];
1967
+ if (stamp !== null)
1968
+ stampOwn(instance._fragment, stamp);
828
1969
  part._start.parentNode.insertBefore(instance._fragment, part._end);
829
- return { _key: result.key, _element: null, _instance: null, _shape: null, _part: part };
1970
+ return { $k: result.key, _element: null, _instance: null, _shape: null, _part: part };
830
1971
  }
831
1972
  const part = createMarkeredPart(parent, ref);
832
1973
  part._set(value);
833
- return { _key: value?.key, _element: null, _instance: null, _shape: null, _part: part };
1974
+ return { $k: value?.key, _element: null, _instance: null, _shape: null, _part: part };
834
1975
  }
835
1976
  /** Commits a new value into an existing item, demoting element mode if the shape changed. */
836
- _updateItem(item, value) {
1977
+ $u(item, value) {
837
1978
  if (item._element !== null) {
838
1979
  if (value !== null && typeof value === 'object' && value.strings === item._shape) {
839
1980
  item._instance._update(value.values);
@@ -851,10 +1992,28 @@ class ChildPart {
851
1992
  item._part._set(value);
852
1993
  }
853
1994
  /** The item's first node — its move/removal handle and the insertion reference before it. */
854
- _firstNode(item) {
1995
+ $f(item) {
855
1996
  return item._element ?? item._part._start;
856
1997
  }
857
- _moveItem(item, ref, parent = this._start.parentNode) {
1998
+ /**
1999
+ * Moving and removing an item read `_element` and `_part`, which are mangled — so they stay here
2000
+ * rather than travelling with the algorithm that calls them. `$m` and `$d` are the price: two
2001
+ * cold methods, exempt from mangling, two characters each.
2002
+ */
2003
+ $m(item, ref, parent = this._start.parentNode) {
2004
+ /**
2005
+ * **Already where it is going.** A reorder asks for many positions that are already correct,
2006
+ * and re-inserting a node that is in place is not free: it detaches and re-attaches, which
2007
+ * blurs focus, restarts a CSS transition and wakes every MutationObserver watching. The
2008
+ * relocated path below leans on this — it re-places every item rather than computing which
2009
+ * ones moved — but the ordinary two-ended diff gets the same saving.
2010
+ *
2011
+ * The item's LAST node is the one whose `nextSibling` decides this, and reading `_element` /
2012
+ * `_part._end` is why the check lives here rather than travelling with the algorithm.
2013
+ */
2014
+ const last = item._element ?? item._part._end;
2015
+ if (last.nextSibling === ref && last.parentNode === parent)
2016
+ return;
858
2017
  if (item._element !== null) {
859
2018
  parent.insertBefore(item._element, ref);
860
2019
  return;
@@ -868,8 +2027,10 @@ class ChildPart {
868
2027
  }
869
2028
  }
870
2029
  /** Removal is a move into a scratch fragment that is immediately emptied. */
871
- _dropItem(item) {
872
- this._moveItem(item, null, SCRATCH);
2030
+ $d(item) {
2031
+ if (notifyOnRemoval)
2032
+ detachItem(item);
2033
+ this.$m(item, null, SCRATCH);
873
2034
  SCRATCH.textContent = '';
874
2035
  }
875
2036
  _commitList(newValues) {
@@ -889,7 +2050,7 @@ class ChildPart {
889
2050
  }
890
2051
  return;
891
2052
  }
892
- const isKeyed = newValues[0] != null && newValues[0].key !== undefined;
2053
+ const isKeyed = newValues[0] != null && newValues[0].$r !== undefined;
893
2054
  if (isKeyed !== this._keyedList && this._items.length) {
894
2055
  this._clear();
895
2056
  this._items = [];
@@ -902,7 +2063,7 @@ class ChildPart {
902
2063
  /** Initial fill builds off-document and lands in one insert. */
903
2064
  const fragment = doc.createDocumentFragment();
904
2065
  for (let i = 0; i < count; i++)
905
- items.push(this._createItem(newValues[i], fragment, null));
2066
+ items.push(this.$c(newValues[i], fragment, null));
906
2067
  this._insert(fragment);
907
2068
  return;
908
2069
  }
@@ -910,159 +2071,185 @@ class ChildPart {
910
2071
  // index mode: update in place, grow at the end, shrink from the end
911
2072
  const shared = items.length < count ? items.length : count;
912
2073
  for (let i = 0; i < shared; i++)
913
- this._updateItem(items[i], newValues[i]);
2074
+ this.$u(items[i], newValues[i]);
914
2075
  if (count > items.length) {
915
2076
  const fragment = doc.createDocumentFragment();
916
2077
  for (let i = items.length; i < count; i++)
917
- items.push(this._createItem(newValues[i], fragment, null));
2078
+ items.push(this.$c(newValues[i], fragment, null));
918
2079
  this._insert(fragment);
919
2080
  }
920
2081
  else if (count < items.length) {
921
- const last = items[items.length - 1];
922
- let node = this._firstNode(items[count]);
923
- const stop = last._element !== null ? last._element.nextSibling : last._part._end.nextSibling;
924
- while (node !== stop) {
925
- const next = node.nextSibling;
926
- parent.removeChild(node);
927
- node = next;
928
- }
2082
+ if (notifyOnRemoval)
2083
+ for (let i = count; i < items.length; i++)
2084
+ detachItem(items[i]);
2085
+ /**
2086
+ * **Removed through the items, not by walking the range.** The walk this replaced ran from
2087
+ * the first doomed item to the last one's end and called `parent.removeChild` on each node,
2088
+ * which assumes every one of them is still a child of `parent`. `@verajs/renderer/slots`
2089
+ * moves a light host's children into the component's tree, and the walk then threw
2090
+ * `NotFoundError` out of the middle of a render — a plain `<x-card>${rows}</x-card>` losing
2091
+ * one row was enough, with no keyed list anywhere in it.
2092
+ *
2093
+ * `$m` into the scratch fragment is indifferent to where a node currently lives, and the
2094
+ * batch is dropped by one clear at the end, so the contiguous-run saving the walk was for
2095
+ * is kept.
2096
+ */
2097
+ for (let i = count; i < items.length; i++)
2098
+ this.$m(items[i], null, SCRATCH);
2099
+ SCRATCH.textContent = '';
929
2100
  items.length = count;
930
2101
  }
931
2102
  return;
932
2103
  }
933
2104
  /**
934
- * Zero-allocation fast path for the dominant case: same length, same key order — a pure
935
- * in-place update (a selection change, a field edit). No key array, no output array, no null
936
- * checks. Falls through to the full algorithm on the first mismatch; the items already updated
937
- * re-verify there as cheap no-op compares.
938
- */
939
- if (items.length === count) {
940
- let i = 0;
941
- while (i < count && items[i]._key === newValues[i].key) {
942
- this._updateItem(items[i], newValues[i]);
943
- i++;
944
- }
945
- if (i === count)
946
- return;
947
- }
948
- /**
949
- * Keyed reconciliation — the standard head/tail algorithm (as in lit's `repeat` and Vue):
950
- * skip matching prefixes and suffixes, detect the two swap shapes directly, and fall back to
951
- * key maps for arbitrary moves, removals and insertions.
2105
+ * Keyed reconciliation is not here. It lives in `@verajs/renderer/keyed`, and it arrives on
2106
+ * the values themselves — `keyed()` stamps each result with the strategy that understands it,
2107
+ * so importing the marker is what loads the algorithm. Nothing registers, nothing is wired, and
2108
+ * two strategies cannot disagree about a list because the list names its own.
2109
+ *
2110
+ * The protocol is three cold members (`$c`, `$u`, `$f`) plus a returned array. Everything a
2111
+ * strategy would otherwise have to reach for — the mode switch, the empty case, the initial
2112
+ * fill — is already done above and passed in.
952
2113
  */
953
- const oldItems = items;
954
- const newKeys = new Array(count);
955
- for (let i = 0; i < count; i++)
956
- newKeys[i] = newValues[i].key;
957
- const newItems = new Array(count);
958
- let oldHead = 0;
959
- let oldTail = oldItems.length - 1;
960
- let newHead = 0;
961
- let newTail = count - 1;
962
- let newKeyToIndex;
963
- let oldKeyToIndex;
964
- const refAt = (i) => i < count && newItems[i] !== undefined ? this._firstNode(newItems[i]) : this._end;
965
- while (oldHead <= oldTail && newHead <= newTail) {
966
- if (oldItems[oldHead] === null)
967
- oldHead++;
968
- else if (oldItems[oldTail] === null)
969
- oldTail--;
970
- else if (oldItems[oldHead]._key === newKeys[newHead]) {
971
- this._updateItem((newItems[newHead] = oldItems[oldHead]), newValues[newHead]);
972
- oldHead++;
973
- newHead++;
974
- }
975
- else if (oldItems[oldTail]._key === newKeys[newTail]) {
976
- this._updateItem((newItems[newTail] = oldItems[oldTail]), newValues[newTail]);
977
- oldTail--;
978
- newTail--;
979
- }
980
- else if (oldItems[oldHead]._key === newKeys[newTail]) {
981
- const item = oldItems[oldHead];
982
- this._moveItem(item, refAt(newTail + 1));
983
- this._updateItem(item, newValues[newTail]);
984
- newItems[newTail] = item;
985
- oldHead++;
986
- newTail--;
987
- }
988
- else if (oldItems[oldTail]._key === newKeys[newHead]) {
989
- const item = oldItems[oldTail];
990
- this._moveItem(item, this._firstNode(oldItems[oldHead]));
991
- this._updateItem(item, newValues[newHead]);
992
- newItems[newHead] = item;
993
- oldTail--;
994
- newHead++;
995
- }
996
- else {
997
- if (newKeyToIndex === undefined) {
998
- newKeyToIndex = new Map();
999
- for (let i = newHead; i <= newTail; i++)
1000
- newKeyToIndex.set(newKeys[i], i);
1001
- oldKeyToIndex = new Map();
1002
- for (let i = oldHead; i <= oldTail; i++) {
1003
- if (oldItems[i] !== null)
1004
- oldKeyToIndex.set(oldItems[i]._key, i);
1005
- }
1006
- }
1007
- if (!newKeyToIndex.has(oldItems[oldHead]._key)) {
1008
- this._dropItem(oldItems[oldHead]);
1009
- oldHead++;
1010
- }
1011
- else if (!newKeyToIndex.has(oldItems[oldTail]._key)) {
1012
- this._dropItem(oldItems[oldTail]);
1013
- oldTail--;
1014
- }
1015
- else {
1016
- const oldIndex = oldKeyToIndex.get(newKeys[newHead]);
1017
- if (oldIndex === undefined) {
1018
- newItems[newHead] = this._createItem(newValues[newHead], parent, this._firstNode(oldItems[oldHead]));
1019
- }
1020
- else {
1021
- const item = oldItems[oldIndex];
1022
- this._moveItem(item, this._firstNode(oldItems[oldHead]));
1023
- this._updateItem(item, newValues[newHead]);
1024
- newItems[newHead] = item;
1025
- oldItems[oldIndex] = null;
1026
- }
1027
- newHead++;
1028
- }
1029
- }
1030
- }
1031
- while (newHead <= newTail) {
1032
- newItems[newHead] = this._createItem(newValues[newHead], parent, refAt(newTail + 1));
1033
- newHead++;
1034
- }
1035
- while (oldHead <= oldTail) {
1036
- const item = oldItems[oldHead++];
1037
- if (item !== null)
1038
- this._dropItem(item);
1039
- }
1040
- this._items = newItems;
2114
+ this._items = newValues[0].$r(this, newValues, items, parent, this._end);
1041
2115
  }
1042
2116
  }
1043
2117
  const rootParts = new WeakMap();
1044
2118
  /**
1045
- * Renders a template result into a container. Slots into Vera via `setRenderer(render)`; core's
1046
- * built-in `html` tag already produces the accepted shape, so no `setHtml` call is required —
1047
- * though lit-html's `html` also works, its results being structurally identical.
2119
+ * Writes a template result into a container. The renderer's imperative draw: no reactivity, no
2120
+ * lifecycle, no knowledge of components. Slots into Vera via `wire([renderer])`; core's built-in
2121
+ * `html` tag already produces the accepted shape, so no `setHtml` call is required — though
2122
+ * lit-html's `html` also works, its results being structurally identical.
2123
+ *
2124
+ * **It owns its own range and nothing else.** The first call appends a marker and anchors a root
2125
+ * part there; later calls with the same container reuse that part and walk only the value slots, so
2126
+ * nodes are updated in place rather than rebuilt. Content that was already in the container stays.
2127
+ *
2128
+ * **Named for the relationship, not the act.** It was `render` until 0.2.0, which collided with
2129
+ * core's `render` — a different function, with a different arity, that declares a *reactive*
2130
+ * template and commits a component's setup. Both were public and both were documented, so a reader
2131
+ * who knew one misread the other. `renderElement` and `renderDom` were considered and rejected: this
2132
+ * renders *into* a container, and the container is a `Node` — a shadow root and a fragment are both
2133
+ * valid, so "element" would be a lie in the type. Argument order is lit-html's on purpose.
1048
2134
  *
1049
- * HYDRATION lives in `@verajs/renderer/hydrate` — a drop-in superset entry whose `render` adopts
2135
+ * HYDRATION lives in `@verajs/renderer/hydrate` — a drop-in superset entry whose `renderInto` adopts
1050
2136
  * existing server-rendered children on first render. SSR apps import from there instead of here;
1051
2137
  * this entry carries zero hydration code.
1052
2138
  */
1053
- const render$1 = (result, container) => {
1054
- if (true && _profileHook)
2139
+ const renderInto$1 = (result, container) => {
2140
+ /**
2141
+ * The container is the argument people forget, and forgetting it failed with
2142
+ * `Cannot read properties of undefined (reading 'appendChild')` — a message about the internals of
2143
+ * a function the caller never named. Everything after this line assumes a node.
2144
+ */
2145
+ if (true && (!container || typeof container.appendChild !== 'function'))
2146
+ throw new TypeError(`renderInto: expected a container node as the second argument and received ${String(container)}. ` +
2147
+ `It renders *into* something — \`renderInto(html\`…\`, document.body)\`.`);
2148
+ if (true && _profileHook)
1055
2149
  ;
1056
2150
  let part = rootParts.get(container);
1057
2151
  if (part === undefined) {
2152
+ /**
2153
+ * FIRST render into this container. If it is a light element host and a 'slot' insert is
2154
+ * wired, capture its children NOW — so slot content provided before its (possibly
2155
+ * conditional) `<slot>` mounts is held rather than left visible in the host, matching native
2156
+ * "unassigned light children do not render". Once per container lifetime; shadow roots
2157
+ * (nodeType 11) and fragments are excluded.
2158
+ */
2159
+ /**
2160
+ * **The marker goes in FIRST, and capture is handed it as the light region's boundary.**
2161
+ *
2162
+ * This part's start marker already delimits where the render's output begins, so the boundary
2163
+ * slots needs is a node the renderer was creating anyway — the sentinel it used to append for
2164
+ * itself landed immediately before this one, two adjacent comments doing the same job. Passing
2165
+ * it removes one comment from every light host and keeps the two in step by construction: they
2166
+ * cannot drift apart if they are the same node.
2167
+ *
2168
+ * Appending before capture is safe and necessary. Safe because a comment is never a slottable,
2169
+ * so the children walk steps over it; necessary because capture LIFTS the host's children, and
2170
+ * a marker appended afterwards would land in the same place either way — this way slots has it.
2171
+ */
1058
2172
  const marker = comment();
1059
2173
  container.appendChild(marker);
2174
+ if (container.nodeType === 1)
2175
+ slotSeam()?._$capture$?.(container, marker);
1060
2176
  rootParts.set(container, (part = new ChildPart(marker, null)));
1061
2177
  }
1062
- part._set(result);
1063
- if (true && _profileHook)
2178
+ /**
2179
+ * **The flush is in a `finally`, and that is not tidiness.** A render that throws after a
2180
+ * `<select>.value` has been queued but before the flush left the queue holding the element — which
2181
+ * retains it in module state, and, worse, hands the stranded value to the *next* `renderInto` call.
2182
+ * An unrelated component's render then silently changed a select it has nothing to do with.
2183
+ * Measured: a failed update left the value to be applied by the following render.
2184
+ *
2185
+ * Flushing on the way out applies it with its own pass, where it belongs, and leaves nothing
2186
+ * behind either way. The error still propagates.
2187
+ */
2188
+ _slotRoot = container;
2189
+ try {
2190
+ part._set(result);
2191
+ }
2192
+ finally {
2193
+ _slotRoot = null;
2194
+ flushSelects();
2195
+ }
2196
+ if (true && _profileHook)
1064
2197
  ;
1065
2198
  };
2199
+ /**
2200
+ * Lists, as a registered kind rather than a branch — the built-in going through the same door a
2201
+ * package will. Moving it to `@verajs/renderer/lists` is step 5; nothing else has to change when
2202
+ * it does, which is what this shape is for.
2203
+ */
2204
+ builtIns.push((part, value) => {
2205
+ if (Array.isArray(value)) {
2206
+ part._commitList(value);
2207
+ return true;
2208
+ }
2209
+ if (value !== null && typeof value[Symbol.iterator] === 'function') {
2210
+ part._commitList([...value]);
2211
+ return true;
2212
+ }
2213
+ return false;
2214
+ });
2215
+ /**
2216
+ * Everything this renderer needs, in one entry: `wire([renderer])`.
2217
+ *
2218
+ * It registers on the `'render'` chain *and* takes the registry, because a package that both
2219
+ * provides a capability and reads one should not cost an app two lines. This replaced
2220
+ * `setRenderer`, which existed only because there was no general way to say "this app has a
2221
+ * renderer" — and which resolved the shadow root at registration, so a renderer wired any other
2222
+ * way silently rendered into the light DOM. That resolution lives in core's dispatch now.
2223
+ */
2224
+ /**
2225
+ * A `true `-only hint for `wire`, so the module and the raw function beside it can share a package
2226
+ * without wiring the wrong one being silent.
2227
+ *
2228
+ * A bare function has no `on`, so `wire` reads it as a connector and hands it the registry. Nothing
2229
+ * registers, nothing throws, and the page renders nothing. The marker lets `wire` name the export
2230
+ * that was meant. This mattered most when the function was called `render` and the mistake was two
2231
+ * characters wide; `renderInto` is harder to confuse, and the guard costs nothing in production.
2232
+ *
2233
+ * `$module` is deliberately generic — any package exporting a raw function next to a module of a
2234
+ * similar name can set it. Production carries neither the property nor the check that reads it.
2235
+ */
2236
+ if (true )
2237
+ renderInto$1.$module = 'renderer';
2238
+ const renderer$1 = {
2239
+ name: '@verajs/renderer',
2240
+ on: 'render',
2241
+ fn: renderInto$1,
2242
+ priority: 50,
2243
+ /**
2244
+ * Typed against the registry `wire` actually hands over, not a narrower shape that happens to
2245
+ * describe the one lookup this makes. A structural `{ get(name: 'value'): … }` is **not**
2246
+ * assignable from `Inserts`, so `wire([renderer])` failed to compile in a consumer's project while
2247
+ * this repo's own typecheck — which reads sources, not the shipped `.d.ts` — saw nothing.
2248
+ */
2249
+ connect: (given) => {
2250
+ registry = given;
2251
+ },
2252
+ };
1066
2253
 
1067
2254
  /**
1068
2255
  * @verajs/renderer/hydrate — markerless adoption of server-rendered DOM.
@@ -1071,27 +2258,36 @@ const render$1 = (result, container) => {
1071
2258
  * container that already has children adopts them as server output of the same template. Without
1072
2259
  * this import the renderer never carries adoption code — non-SSR apps pay nothing.
1073
2260
  *
1074
- * The server serializer (@verajs/ssr/vera) emits the SAME static strings the renderer parses into
2261
+ * The server serializer (@verajs/ssr) emits the SAME static strings the renderer parses into
1075
2262
  * its canonical template, so server DOM and canonical fragment diverge only at value slots — and
1076
2263
  * at adoption time the values are known. Adoption walks both trees in lockstep: statics must
1077
2264
  * match byte-for-byte (else bail), and at each slot the live text is split so the renderer's own
1078
2265
  * anchors (primed texts, marker comments) are installed into the adopted DOM. Server HTML stays
1079
2266
  * free of framework comments; the client repairs its anchors in. Any mismatch clears the
1080
- * container (preserving `<style vera-styles>` tags) and the caller renders fresh — correctness
2267
+ * container (preserving `<style data-vm-sheet="styles">` tags) and the caller renders fresh — correctness
1081
2268
  * never depends on the server markup.
1082
2269
  *
1083
2270
  * This entry re-exports the public API, so a CDN importmap can point `@verajs/renderer` at the
1084
2271
  * hydrate bundle and nothing else changes.
1085
2272
  */
1086
- // The server serializer (@verajs/ssr/vera) emits the SAME static strings this module parses into
1087
- // its canonical template, so server DOM and canonical fragment diverge only at value slots — and
1088
- // at adoption time the values are known. Adoption walks both trees in lockstep: statics must
1089
- // match byte-for-byte (else bail), and at each slot the live text is split so the renderer's own
1090
- // anchors (primed texts, marker comments) are installed into the adopted DOM. Server HTML stays
1091
- // free of framework comments; the client repairs its anchors in. Any mismatch abandons adoption
1092
- // and falls back to a clean first render — correctness never depends on the server markup.
1093
2273
  /** Internal bail signal — never escapes `tryAdopt`. */
1094
2274
  const MISMATCH = {};
2275
+ /**
2276
+ * Why the last adoption gave up, for the development warning below. Written at every `throw
2277
+ * MISMATCH` inside an `if (true )`, so a production bundle carries neither the strings nor the
2278
+ * assignments — the branches fold away with `true ` and the helper goes with them.
2279
+ */
2280
+ let why = '';
2281
+ /** A live node as a person would name it, for that message. */
2282
+ const describe = (node) => node === null
2283
+ ? 'nothing'
2284
+ : node.nodeType === 1
2285
+ ? `<${node.localName}>`
2286
+ : node.nodeType === 3
2287
+ ? `the text ${JSON.stringify(node.data.slice(0, 30))}`
2288
+ : node.nodeType === 8
2289
+ ? 'a comment'
2290
+ : `a ${node.nodeName} node`;
1095
2291
  /** Splits mid-text cursors onto a node boundary and returns the node now at the cursor. */
1096
2292
  const cursorSplit = (cursor) => {
1097
2293
  if (cursor.offset > 0) {
@@ -1100,13 +2296,43 @@ const cursorSplit = (cursor) => {
1100
2296
  }
1101
2297
  return cursor.node;
1102
2298
  };
2299
+ /**
2300
+ * **A comment carries no rendered content, so hydration neither matches nor requires one.**
2301
+ *
2302
+ * `instanceWalker` is `ELEMENT | TEXT`, and the part indices in `_parts` are numbered by that same
2303
+ * walker — so a comment in a template's statics is structurally invisible to this walk, and cannot
2304
+ * be made visible without renumbering every part the client renderer relies on. The live DOM,
2305
+ * however, still has it: `html`<p>a<!-- note -->b</p>`` adopts as text/comment/text where the walk
2306
+ * wanted one run of text, and `<p>lead<!-- tail --></p>` leaves a child the walk never asked for.
2307
+ * Both read as a disagreement, so **every template containing an HTML comment lost hydration** —
2308
+ * the server's markup discarded and re-rendered, for markup the client had itself produced. Nothing
2309
+ * failed, because the page is correct either way; that is what the fallback is for, and why this
2310
+ * went unnoticed. What it cost was the first paint the server render was paid for.
2311
+ *
2312
+ * Stepping over them is sound rather than merely convenient: the invisibility is symmetric, so a
2313
+ * comment can differ in either direction and neither direction can change what a reader sees. This
2314
+ * is only safe because hydration is markerless — the adopted markup carries no framework comments,
2315
+ * so there is nothing here whose position is load-bearing.
2316
+ *
2317
+ * Not folded into `cursorSplit`, which also answers "where do I insert?" — moving an insertion point
2318
+ * past a comment would put a slot's content on the wrong side of it.
2319
+ */
2320
+ const passComments = (cursor) => {
2321
+ while (cursor.offset === 0 && cursor.node !== null && cursor.node.nodeType === 8) {
2322
+ cursor.node = cursor.node.nextSibling;
2323
+ }
2324
+ };
1103
2325
  /** Consumes exactly `text` from the live cursor; anything else is a mismatch. */
1104
2326
  const expectText = (cursor, text) => {
1105
2327
  let need = text;
1106
2328
  while (need.length > 0) {
2329
+ passComments(cursor);
1107
2330
  const node = cursor.node;
1108
- if (node === null || node.nodeType !== 3)
2331
+ if (node === null || node.nodeType !== 3) {
2332
+ if (true )
2333
+ why = `expected the text ${JSON.stringify(text)} and found ${describe(node)}`;
1109
2334
  throw MISMATCH;
2335
+ }
1110
2336
  const data = node.data;
1111
2337
  const available = data.length - cursor.offset;
1112
2338
  if (available === 0) {
@@ -1115,8 +2341,11 @@ const expectText = (cursor, text) => {
1115
2341
  continue;
1116
2342
  }
1117
2343
  const take = available < need.length ? available : need.length;
1118
- if (data.slice(cursor.offset, cursor.offset + take) !== need.slice(0, take))
2344
+ if (data.slice(cursor.offset, cursor.offset + take) !== need.slice(0, take)) {
2345
+ if (true )
2346
+ why = `expected the text ${JSON.stringify(need.slice(0, take))} and found ${JSON.stringify(data.slice(cursor.offset, cursor.offset + take))}`;
1119
2347
  throw MISMATCH;
2348
+ }
1120
2349
  need = need.slice(take);
1121
2350
  cursor.offset += take;
1122
2351
  if (cursor.offset === data.length) {
@@ -1134,13 +2363,19 @@ const claimValueText = (cursor, text) => {
1134
2363
  cursor.parent.insertBefore(primed, at);
1135
2364
  return primed;
1136
2365
  }
1137
- if (at === null || at.nodeType !== 3)
2366
+ if (at === null || at.nodeType !== 3) {
2367
+ if (true )
2368
+ why = `expected a text node holding an interpolated value and found ${describe(at)}`;
1138
2369
  throw MISMATCH;
2370
+ }
1139
2371
  const node = at;
1140
2372
  if (node.data.length > text.length)
1141
2373
  node.splitText(text.length);
1142
- if (node.data !== text)
2374
+ if (node.data !== text) {
2375
+ if (true )
2376
+ why = `an interpolated value reads ${JSON.stringify(text)} here and the markup says ${JSON.stringify(node.data)}`;
1143
2377
  throw MISMATCH;
2378
+ }
1144
2379
  cursor.node = node.nextSibling;
1145
2380
  cursor.offset = 0;
1146
2381
  return node;
@@ -1160,6 +2395,153 @@ const canonicalNodes = (template) => {
1160
2395
  }
1161
2396
  return nodes;
1162
2397
  };
2398
+ /** The light host being hydrated — every `<slot>` in the render projects it, set once in
2399
+ * `tryAdopt` (the render container), null when no slot handler is wired. */
2400
+ let _adoptHost = null;
2401
+ /** Whether the default slot's assignment has been claimed (the host count is for the first one). */
2402
+ let _defaultTaken = false;
2403
+ /**
2404
+ * Every slot binding this adoption attempt created. If the attempt BAILS, each is parked — which
2405
+ * returns the user's nodes to holding and unregisters the binding. Without it the abandoned
2406
+ * bindings stayed registered, so the clean render's own bindings ranked as later duplicates and
2407
+ * showed fallback while the user's content sat in the discarded tree: a hydration mismatch
2408
+ * silently DESTROYED slotted content, breaking this entry's promise that correctness never
2409
+ * depends on the server markup (measured).
2410
+ */
2411
+ let _adoptedSlots = [];
2412
+ /** How many values a template part consumes — for skipping the unrendered parts inside an
2413
+ * assigned slot's fallback subtree. */
2414
+ const partValueCount = (part) => part._type === 1 ? (part._statics.length - 1) : 1;
2415
+ /**
2416
+ * Account for (skip) the parts inside a canonical subtree whose DOM the server did NOT render —
2417
+ * an assigned slot's fallback. Advances the walk indices and value cursor without touching DOM,
2418
+ * so the parts AFTER the slot still line up. Walks the node's CHILDREN (the fallback), in the
2419
+ * same ELEMENT|TEXT order the walker numbers by.
2420
+ */
2421
+ const accountSubtree = (node, state) => {
2422
+ const parts = state._template._parts;
2423
+ for (let child = node.firstChild; child !== null; child = child.nextSibling) {
2424
+ if (child.nodeType !== 1 && child.nodeType !== 3)
2425
+ continue;
2426
+ state._nodeIndex++;
2427
+ while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2428
+ state._valueIndex += partValueCount(parts[state._partIndex]);
2429
+ state._partIndex++;
2430
+ }
2431
+ if (child.nodeType === 1)
2432
+ accountSubtree(child, state);
2433
+ }
2434
+ };
2435
+ /**
2436
+ * Reconcile a canonical `<slot>` against server-distributed DOM. Named slots take the consecutive
2437
+ * cursor nodes carrying `slot="name"`; the default slot takes the host-count nodes
2438
+ * (`data-vm-slotted="N"`). Found nodes are wrapped in place as a live binding (identity/state preserved);
2439
+ * an unassigned slot adopts its server-rendered fallback children normally. The slots module's
2440
+ * `_$adopt$` (off the template's own seam fn) does the registration.
2441
+ */
2442
+ const adoptSlotElement = (canonicalSlot, cursor, state) => {
2443
+ const seamAdopt = state._template._seam._$adopt$;
2444
+ /**
2445
+ * **The slot's OWN bindings, committed onto a per-instance element.** The server unwrapped the
2446
+ * `<slot>`, so there is no live element to adopt against — but the template's parts for it are
2447
+ * still in the parts array, and skipping them left every value after the slot reading the wrong
2448
+ * one. In practice that meant adoption failed and the whole container fell back to a client
2449
+ * render: any component whose slot carried `@slotchange`, `&ref` or `name=${…}` could not be
2450
+ * server-rendered at all.
2451
+ *
2452
+ * A shallow clone is the target rather than the canonical node, which is shared by every
2453
+ * instance of the template — committing onto that would attach one instance's listeners to all
2454
+ * of them. The clone then IS this instance's slot element, exactly as the clone in a client
2455
+ * render is, so `@slotchange` and `&ref` mean the same thing in both.
2456
+ */
2457
+ const ghost = canonicalSlot.cloneNode(false);
2458
+ const parts = state._template._parts;
2459
+ while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2460
+ const templatePart = parts[state._partIndex++];
2461
+ const attrPart = new AttrPart(ghost, templatePart._name, templatePart._statics, templatePart._present);
2462
+ state._out.push(attrPart);
2463
+ state._valueIndex = attrPart._commit(state._values, state._valueIndex, true);
2464
+ drainIgnored(state);
2465
+ }
2466
+ /** After the commit, so `<slot name=${…}>` is read as the name it actually has. */
2467
+ const name = ghost.getAttribute('name') ?? '';
2468
+ passComments(cursor);
2469
+ const parent = cursor.parent;
2470
+ /** Collect the server nodes assigned to this slot. */
2471
+ const assigned = [];
2472
+ if (name !== '') {
2473
+ let node = cursorSplit(cursor);
2474
+ while (node !== null && node.nodeType === 1 && node.getAttribute('slot') === name) {
2475
+ assigned.push(node);
2476
+ cursor.node = node.nextSibling;
2477
+ node = cursorSplit(cursor);
2478
+ }
2479
+ }
2480
+ else if (!_defaultTaken) {
2481
+ /**
2482
+ * `"offset,count"` on the slot's own parent — see `SLOTTED_ATTR`. Only the count is needed
2483
+ * here (the walk is already standing in the right place); the offset is what lets a FAILED
2484
+ * adoption find these same nodes again instead of destroying them.
2485
+ *
2486
+ * `_defaultTaken` still guards: two default slots sharing a parent would otherwise both read
2487
+ * the one mark, and by native semantics only the first receives anything.
2488
+ */
2489
+ const mark = parent.getAttribute?.('data-vm-slotted');
2490
+ const count = mark === undefined || mark === null ? 0 : Number(mark.slice(mark.indexOf(',') + 1));
2491
+ if (count > 0) {
2492
+ _defaultTaken = true;
2493
+ /**
2494
+ * **The mark does not survive the page it delivered.** It describes what the SERVER emitted
2495
+ * and is meaningless the moment those nodes are adopted, so leaving it behind would put a
2496
+ * framework marker in the user's live DOM permanently — queryable, stylable, and stale.
2497
+ * `data-vm-select` sets the precedent: it is stripped before the markup even ships, with
2498
+ * a test asserting the mark must not survive.
2499
+ */
2500
+ parent.removeAttribute('data-vm-slotted');
2501
+ for (let i = 0; i < count; i++) {
2502
+ const node = cursorSplit(cursor);
2503
+ if (node === null)
2504
+ break;
2505
+ assigned.push(node);
2506
+ cursor.node = node.nextSibling;
2507
+ }
2508
+ }
2509
+ }
2510
+ if (assigned.length > 0) {
2511
+ /** Assigned: the fallback was NOT rendered, so its parts are accounted (skipped) and its
2512
+ * nodes cloned from the canonical template for live re-fallback later. */
2513
+ const before = cursor.node;
2514
+ const fallback = [];
2515
+ for (let c = canonicalSlot.firstChild; c !== null; c = c.nextSibling)
2516
+ if (c.nodeType === 1 || c.nodeType === 3)
2517
+ fallback.push(c.cloneNode(true));
2518
+ accountSubtree(canonicalSlot, state);
2519
+ const seam = seamAdopt(_adoptHost, name, assigned, fallback, parent, before, ghost);
2520
+ _adoptedSlots.push(seam);
2521
+ (state._slotStates ??= []).push(seam);
2522
+ /** An adopted seam is removal work exactly as a mounted one is — without this, a page whose
2523
+ * only seams were adopted never ran `_teardown`, and branch-away destroyed the user's
2524
+ * server-adopted content instead of parking it. See `declareRemovalWork`. */
2525
+ declareRemovalWork();
2526
+ }
2527
+ else {
2528
+ /** Unassigned: the server rendered this slot's fallback children — adopt them in lockstep
2529
+ * (they ARE the canonical children), then bind them as the shown fallback. */
2530
+ const fallbackStart = cursor.node;
2531
+ for (let c = canonicalSlot.firstChild; c !== null; c = c.nextSibling)
2532
+ if (c.nodeType === 1 || c.nodeType === 3)
2533
+ adoptNode(c, cursor, state);
2534
+ /** The fallback nodes now sit between fallbackStart and cursor.node. */
2535
+ const fallback = [];
2536
+ for (let n = fallbackStart; n !== null && n !== cursor.node; n = n.nextSibling)
2537
+ fallback.push(n);
2538
+ const seam = seamAdopt(_adoptHost, name, null, fallback, parent, cursor.node, ghost);
2539
+ _adoptedSlots.push(seam);
2540
+ (state._slotStates ??= []).push(seam);
2541
+ /** Same as the assigned branch: an unassigned seam still unregisters and re-routes at park. */
2542
+ declareRemovalWork();
2543
+ }
2544
+ };
1163
2545
  /** Adopts one canonical node (and, for elements, its subtree) against the live cursor. */
1164
2546
  const adoptNode = (canonical, cursor, state) => {
1165
2547
  state._nodeIndex++;
@@ -1177,19 +2559,33 @@ const adoptNode = (canonical, cursor, state) => {
1177
2559
  expectText(cursor, canonical.data);
1178
2560
  return;
1179
2561
  }
2562
+ /** A `<slot>` in the canonical template maps to distributed content (or fallback) in the server
2563
+ * DOM — reconciled specially — but only when a slot handler was wired at construction. */
2564
+ if (state._template._seam !== undefined && canonical.localName === 'slot') {
2565
+ adoptSlotElement(canonical, cursor, state);
2566
+ return;
2567
+ }
1180
2568
  /** Element: same tag, commit its attribute parts live, then descend children in lockstep. */
2569
+ passComments(cursor);
1181
2570
  const live = cursorSplit(cursor);
1182
- if (live === null || live.nodeType !== 1)
2571
+ if (live === null || live.nodeType !== 1) {
2572
+ if (true )
2573
+ why = `expected <${canonical.localName}> and found ${describe(live)}`;
1183
2574
  throw MISMATCH;
1184
- if (live.localName !== canonical.localName)
2575
+ }
2576
+ if (live.localName !== canonical.localName) {
2577
+ if (true )
2578
+ why = `expected <${canonical.localName}> and found <${live.localName}>`;
1185
2579
  throw MISMATCH;
2580
+ }
1186
2581
  while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
1187
2582
  const templatePart = parts[state._partIndex++];
1188
- const attrPart = new AttrPart(live, templatePart._name, templatePart._statics);
2583
+ const attrPart = new AttrPart(live, templatePart._name, templatePart._statics, templatePart._present);
1189
2584
  state._out.push(attrPart);
1190
- /** A normal commit: attributes re-set (idempotent), properties applied, listeners attached,
1191
- * refs fired — the server could only mirror form state; the client wires behavior. */
1192
- state._valueIndex = attrPart._commit(state._values, state._valueIndex);
2585
+ /** Attributes re-set (idempotent), listeners attached, refs fired — the server could only
2586
+ * mirror form state; the client wires behavior. The `true` marks this as adoption, which is
2587
+ * what keeps a form value the reader may already have changed (see `AttrPart._commit`). */
2588
+ state._valueIndex = attrPart._commit(state._values, state._valueIndex, true);
1193
2589
  drainIgnored(state);
1194
2590
  }
1195
2591
  const inner = { parent: live, node: live.firstChild, offset: 0 };
@@ -1199,9 +2595,52 @@ const adoptNode = (canonical, cursor, state) => {
1199
2595
  adoptNode(child, inner, state);
1200
2596
  child = child.nextSibling;
1201
2597
  }
2598
+ /**
2599
+ * The one place the server writes content the template does not describe: a `<textarea>`'s value
2600
+ * **is** its content, so `.value=${…}` has nowhere else to go and `@verajs/ssr` puts it there —
2601
+ * which is what shows the value to a reader with no JavaScript. The template's own statics say
2602
+ * the element is empty, so this read as foreign markup and abandoned adoption for the whole page,
2603
+ * silently: the container was cleared and re-rendered, the markup looked right, and everything
2604
+ * server rendering is for was gone.
2605
+ *
2606
+ * **Kept, not cleared.** It is the element's `defaultValue`, and it is also the only thing
2607
+ * holding the value: adoption deliberately does not write `.value` (see `AttrPart._commit`), so
2608
+ * clearing the content would empty the field it just adopted. A person who typed here before the
2609
+ * bundle landed has made the field dirty, and a dirty textarea ignores its content anyway — so
2610
+ * their text survives either way, and the server's stays as what `form.reset()` restores.
2611
+ *
2612
+ * **One of four respects in which a hydrated DOM is not byte-identical to a client-rendered one**,
2613
+ * and all four have the same cause: `@verajs/ssr` mirrors `.value`, `.checked` and `.selected` on
2614
+ * form elements into markup, because markup is the only way form state reaches the client at all.
2615
+ * The client sets those as properties and writes nothing, exactly as a browser does — so the
2616
+ * server's copy stays behind after adoption:
2617
+ *
2618
+ * | binding | hydrated | client-rendered |
2619
+ * | --- | --- | --- |
2620
+ * | `<input .value=${x}>` | `<input value="x">` | `<input>` |
2621
+ * | `<input .checked=${true}>` | `<input checked="">` | `<input>` |
2622
+ * | `<option .selected=${true}>` | `<option selected="">` | `<option>` |
2623
+ * | `<textarea .value=${x}>` | `<textarea>x</textarea>` | `<textarea></textarea>` |
2624
+ *
2625
+ * They are defaults rather than state — what `form.reset()` restores — so the *rendered* result is
2626
+ * the same and only a reset tells them apart. `tests/hydrate-parity.test.mjs` records the list,
2627
+ * because "the one respect" was written here when there was one, and a reader comparing a hydrated
2628
+ * DOM against a client-rendered one needs to know which differences are meant.
2629
+ */
2630
+ if (inner.node !== null &&
2631
+ inner.node.nodeType === 3 &&
2632
+ inner.node.nextSibling === null &&
2633
+ canonical.firstChild === null &&
2634
+ live.localName === 'textarea') {
2635
+ inner.node = null;
2636
+ }
1202
2637
  /** Leftover live children the template does not account for = not our markup. */
1203
- if (inner.node !== null && !(inner.node.nodeType === 3 && inner.node.data === '' && inner.node.nextSibling === null))
2638
+ passComments(inner);
2639
+ if (inner.node !== null && !(inner.node.nodeType === 3 && inner.node.data === '' && inner.node.nextSibling === null)) {
2640
+ if (true )
2641
+ why = `<${live.localName}> contains ${describe(inner.node)}, which the template does not describe`;
1204
2642
  throw MISMATCH;
2643
+ }
1205
2644
  cursor.node = live.nextSibling;
1206
2645
  cursor.offset = 0;
1207
2646
  };
@@ -1217,8 +2656,23 @@ const drainIgnored = (state) => {
1217
2656
  const adoptSlot = (cursor, rawValue, out) => {
1218
2657
  const heldResult = rawValue?.$h;
1219
2658
  const value = heldResult !== undefined ? heldResult : rawValue;
1220
- if (value != null && typeof value !== 'object') {
1221
- /** Primitive: claim its text and bind the fast TextPart, committed state included. */
2659
+ /**
2660
+ * Anything the client commits as text claims text here — which is every value that is not a
2661
+ * template, a node, or an iterable. `String(value)` is what `_set` falls through to, so a `Date`,
2662
+ * an object with a `toString`, a `Promise` or a plain object all produce text on the client, and
2663
+ * `@verajs/ssr` produces the same text on the server.
2664
+ *
2665
+ * The object cases used to be a deliberate mismatch, because the server emitted nothing for them
2666
+ * and the two could not be reconciled. Once the server started matching the client, the mismatch
2667
+ * was the only thing left disagreeing.
2668
+ */
2669
+ const isText = value != null &&
2670
+ (typeof value !== 'object' ||
2671
+ (!isTemplateResult(value) &&
2672
+ value.nodeType === undefined &&
2673
+ typeof value[Symbol.iterator] !== 'function'));
2674
+ if (isText) {
2675
+ /** Claim its text and bind the fast TextPart, committed state included. */
1222
2676
  const textPart = new TextPart(claimValueText(cursor, toText(value)));
1223
2677
  textPart._value = value;
1224
2678
  out.push(textPart);
@@ -1234,13 +2688,30 @@ const adoptSlot = (cursor, rawValue, out) => {
1234
2688
  part._shape = value.strings;
1235
2689
  part._mode = TEMPLATE;
1236
2690
  }
2691
+ else if (value.nodeType !== undefined) {
2692
+ /**
2693
+ * A DOM node is client-only by construction — the server has no document to have built one, so
2694
+ * it rendered nothing here and there is nothing to adopt. Inserting it at the cursor (which has
2695
+ * not moved, because no server node was claimed) puts it exactly where the end marker is about
2696
+ * to go, and leaves the part in the same state a client-side commit would.
2697
+ */
2698
+ cursor.parent.insertBefore(value, cursorSplit(cursor));
2699
+ part._value = value;
2700
+ part._mode = NODE;
2701
+ }
1237
2702
  else {
2703
+ /** Everything left is an array or another iterable — text and nodes were handled above. */
1238
2704
  const list = Array.isArray(value) ? value : [...value];
1239
2705
  const items = [];
1240
2706
  for (const entry of list)
1241
2707
  items.push(adoptItem(cursor, entry));
1242
2708
  part._items = items;
1243
- part._keyedList = list.length > 0 && list[0]?.key !== undefined;
2709
+ /**
2710
+ * The same predicate `_commitList` uses — the presence of a strategy, not of a `key`. Two
2711
+ * spellings of "is this list keyed" would drift, and disagreeing about one list destroys it:
2712
+ * a mode change is what tells the renderer to throw the adopted DOM away and start over.
2713
+ */
2714
+ part._keyedList = list.length > 0 && list[0]?.$r !== undefined;
1244
2715
  part._mode = LIST;
1245
2716
  }
1246
2717
  const end = comment();
@@ -1259,7 +2730,7 @@ const adoptItem = (cursor, value) => {
1259
2730
  const liveRoot = cursorSplit(cursor);
1260
2731
  const instance = adoptInstance(template, result.values, cursor);
1261
2732
  return {
1262
- _key: result.key,
2733
+ $k: result.key,
1263
2734
  _element: liveRoot,
1264
2735
  _instance: instance,
1265
2736
  _shape: result.strings,
@@ -1275,12 +2746,12 @@ const adoptItem = (cursor, value) => {
1275
2746
  part._instance = instance;
1276
2747
  part._shape = result.strings;
1277
2748
  part._mode = TEMPLATE;
1278
- return { _key: result.key, _element: null, _instance: null, _shape: null, _part: part };
2749
+ return { $k: result.key, _element: null, _instance: null, _shape: null, _part: part };
1279
2750
  }
1280
2751
  /** Non-template item: markered part adopting its content like a nested slot. */
1281
2752
  const out = [];
1282
2753
  adoptSlot(cursor, value, out);
1283
- return { _key: value?.key, _element: null, _instance: null, _shape: null, _part: out[0] };
2754
+ return { $k: value?.key, _element: null, _instance: null, _shape: null, _part: out[0] };
1284
2755
  };
1285
2756
  /** Builds an Instance whose parts are bound to LIVE nodes, consuming them from the cursor. */
1286
2757
  const adoptInstance = (template, values, cursor) => {
@@ -1306,29 +2777,45 @@ const adoptInstance = (template, values, cursor) => {
1306
2777
  child = child.nextSibling;
1307
2778
  }
1308
2779
  drainIgnored(state);
1309
- if (state._partIndex !== template._parts.length)
2780
+ if (state._partIndex !== template._parts.length) {
2781
+ if (true )
2782
+ why = 'the markup ran out before the template did';
1310
2783
  throw MISMATCH;
2784
+ }
2785
+ if (state._slotStates !== undefined)
2786
+ instance._slotStates = state._slotStates;
1311
2787
  return instance;
1312
2788
  };
1313
2789
  /**
1314
2790
  * Attempts to adopt a container's existing (server-rendered) children for `result`. Returns the
1315
2791
  * root part on success; null on any mismatch, leaving the caller to clean-render. Leading
1316
- * `<style vera-styles>` tags (the SSR style serialization) are skipped and preserved.
2792
+ * `<style data-vm-sheet="styles">` tags (the SSR style serialization) are skipped and preserved.
1317
2793
  */
1318
2794
  const tryAdopt = (result, container) => {
1319
2795
  /** Only the SSR-serialized style tags are skipped — templates may legitimately start with
1320
2796
  * whitespace or even their own static `<style>`, which must align against the canonical walk. */
1321
2797
  let first = container.firstChild;
1322
- while (first !== null && first.nodeType === 1 && first.hasAttribute('vera-styles')) {
2798
+ while (first !== null && first.nodeType === 1 && first.hasAttribute('data-vm-sheet')) {
1323
2799
  first = first.nextSibling;
1324
2800
  }
2801
+ if (true )
2802
+ why = '';
1325
2803
  const start = comment();
1326
2804
  container.insertBefore(start, first);
2805
+ /** The container is the light host every slot in this render projects; `_defaultTaken` resets
2806
+ * per adoption (the host count is for the first default slot). */
2807
+ _adoptHost = container.nodeType === 1 ? container : null;
2808
+ _defaultTaken = false;
2809
+ _adoptedSlots = [];
1327
2810
  try {
1328
2811
  const cursor = { parent: container, node: start.nextSibling, offset: 0 };
1329
2812
  const instance = adoptInstance(getTemplate(result), result.values, cursor);
1330
- if (cursor.node !== null)
2813
+ passComments(cursor);
2814
+ if (cursor.node !== null) {
2815
+ if (true )
2816
+ why = `${describe(cursor.node)} follows everything the template describes`;
1331
2817
  throw MISMATCH;
2818
+ }
1332
2819
  const part = new ChildPart(start, null);
1333
2820
  part._instance = instance;
1334
2821
  part._shape = result.strings;
@@ -1338,6 +2825,14 @@ const tryAdopt = (result, container) => {
1338
2825
  catch (error) {
1339
2826
  if (error !== MISMATCH)
1340
2827
  throw error;
2828
+ /**
2829
+ * Undo every slot this attempt adopted BEFORE the container is cleared: parking returns the
2830
+ * user's nodes to holding and unregisters the binding, so the clean render that follows
2831
+ * redistributes them instead of ranking behind an abandoned binding and showing fallback.
2832
+ */
2833
+ for (const seam of _adoptedSlots)
2834
+ seam._$park$();
2835
+ _adoptedSlots = [];
1341
2836
  start.remove();
1342
2837
  return null;
1343
2838
  }
@@ -1349,17 +2844,17 @@ const clearPreservingStyles = (container) => {
1349
2844
  /** `nextSibling` already yields `ChildNode | null`; annotating it `Node` widened it and broke
1350
2845
  * the assignment back into `node`, which `firstChild` typed as `ChildNode | null`. */
1351
2846
  const next = node.nextSibling;
1352
- if (!(node.nodeType === 1 && node.hasAttribute('vera-styles')))
2847
+ if (!(node.nodeType === 1 && node.hasAttribute('data-vm-sheet')))
1353
2848
  container.removeChild(node);
1354
2849
  node = next;
1355
2850
  }
1356
2851
  };
1357
2852
  /**
1358
2853
  * The hydrating `render`: a drop-in for the base entry's. The first render into a container that
1359
- * already has children adopts them; any mismatch clears (keeping `<style vera-styles>`) and falls
2854
+ * already has children adopts them; any mismatch clears (keeping `<style data-vm-sheet="styles">`) and falls
1360
2855
  * through to a clean base render. After the first render, this IS the base render.
1361
2856
  */
1362
- const render = (result, container) => {
2857
+ const renderInto = (result, container) => {
1363
2858
  if (!rootParts.has(container) &&
1364
2859
  container.firstChild !== null &&
1365
2860
  result !== null &&
@@ -1370,10 +2865,93 @@ const render = (result, container) => {
1370
2865
  rootParts.set(container, part);
1371
2866
  return;
1372
2867
  }
2868
+ /**
2869
+ * **Falling back has to say so.** The page is correct either way — that is what the fallback is
2870
+ * for — but the server's markup has just been thrown away, which means every byte the server
2871
+ * spent rendering it was wasted and the one thing server rendering exists to deliver did not
2872
+ * happen. Nothing observable changes, so without this the only symptom is a slower first paint
2873
+ * that nobody attributes to anything.
2874
+ *
2875
+ * The `<textarea>` case a few screens up is the proof: adoption was abandoned *for the whole
2876
+ * page* by one element whose content the template did not describe, and the markup still looked
2877
+ * right afterwards. It was found by reading the code. React and lit both report a mismatch;
2878
+ * this said nothing at all.
2879
+ *
2880
+ * `true `-only, and the reason comes from the check that failed, so it names the first place
2881
+ * the two renders disagreed rather than announcing that they did.
2882
+ *
2883
+ * **Scoped to this container, because that is what happened.** This function runs once per
2884
+ * container, and a mismatch clears exactly one — measured: three containers, one carrying markup
2885
+ * the template does not describe, and the other two adopt their server nodes unchanged while one
2886
+ * warning prints. The message used to say "nothing the server rendered was used", which reads as
2887
+ * a page-wide failure and sends the reader looking for a page-wide cause: a bad doctype, a broken
2888
+ * handoff, state that differs everywhere. The truth is narrower and the message already names the
2889
+ * element, so the advice can be local.
2890
+ *
2891
+ * It also said the markup was discarded, full stop; `clearPreservingStyles` keeps
2892
+ * `<style data-vm-sheet="styles">`, which is the whole reason that function exists.
2893
+ */
2894
+ if (true ) {
2895
+ /**
2896
+ * **"The page is correct" is a promise this message must not make blindly.** The bail rescue
2897
+ * preserves everything it can PROVE is the user's: content inside `data-vm-slotted` marks,
2898
+ * the `data-vm-unassigned` carrier, and elements carrying a `slot` attribute. Real server
2899
+ * output always marks its distributed default-slot content, so on genuine deploy skew the
2900
+ * rescue is complete and the promise holds — measured, named and unnamed and bare text alike.
2901
+ * But a container holding CLIENT-side markup that was never server output has no marks, and
2902
+ * its unnamed slottables are structurally indistinguishable from the stale template output
2903
+ * being discarded — so they go with it, under a message that said everything was fine. The
2904
+ * marks are the discriminator: their total absence is exactly the shape where the promise
2905
+ * can fail, so that is when the message changes.
2906
+ */
2907
+ const unmarked = container.nodeType === 1 &&
2908
+ container.querySelector('[data-vm-slotted],[data-vm-unassigned]') === null;
2909
+ console.warn(`[vera] hydration fell back to a client render: ${why}. This container's server markup was ` +
2910
+ `discarded and rebuilt (its SSR <style> is kept), ` +
2911
+ (unmarked
2912
+ ? `and it carried none of the marks server output carries. If its children were ` +
2913
+ `CLIENT-side markup rather than this template's server output, unnamed light-slot ` +
2914
+ `content (bare text, elements without a \`slot\` attribute) cannot be told apart ` +
2915
+ `from the stale markup and was discarded with it — hydrate adopts existing children ` +
2916
+ `AS server output; render client-only containers with @verajs/renderer's renderInto ` +
2917
+ `instead. `
2918
+ : `so the page is correct but the server's work on this part of it was wasted. `) +
2919
+ `Other containers on the page hydrate independently and are unaffected. The two renders ` +
2920
+ `have to agree exactly — check for markup the template does not describe, or state ` +
2921
+ `settled after the server render.`);
2922
+ }
2923
+ /**
2924
+ * **Un-distribute before discarding.** A light host's slotted content lives INSIDE the markup
2925
+ * about to be thrown away, so clearing destroyed it: the slots fell back and the user's nodes
2926
+ * were gone from the page permanently, under a warning that said the page was still correct.
2927
+ * The slots module lifts them back out (`_$rescue$`), and re-attaching them as the host's
2928
+ * children puts it in exactly the state a first client render starts from — the clean render
2929
+ * below captures and redistributes them with no special case anywhere.
2930
+ */
2931
+ const rescued = container.nodeType === 1 ? slotSeam()?._$rescue$?.(container) : null;
1373
2932
  clearPreservingStyles(container);
2933
+ if (rescued !== null && rescued !== undefined)
2934
+ for (const node of rescued)
2935
+ container.appendChild(node);
1374
2936
  }
1375
- render$1(result, container);
2937
+ renderInto$1(result, container);
1376
2938
  };
2939
+ /** Same wire-misuse guard the base entry puts on its raw function — see renderer.ts. */
2940
+ if (true )
2941
+ renderInto.$module = 'renderer';
2942
+ /**
2943
+ * This entry's `renderer` module, bound to the **hydrating** `renderInto`.
2944
+ *
2945
+ * It used to be a bare re-export of the base entry's descriptor, whose `fn` is the base,
2946
+ * non-adopting render — so the natural `import { renderer } from '@verajs/renderer/hydrate';
2947
+ * wire([renderer])` wired a renderer that never hydrated. The page still looked right (a first
2948
+ * render into a full container clears it and renders fresh), which made the failure silent: every
2949
+ * byte of server work discarded, nothing on screen to say so. The header's promise — point the
2950
+ * importmap at this bundle "and nothing else changes" — is only true now that the descriptor
2951
+ * carries this entry's own function. `connect` and the rest are shared deliberately: they operate
2952
+ * on this bundle's copy of the renderer's module state, which both functions read.
2953
+ */
2954
+ const renderer = { ...renderer$1, fn: renderInto };
1377
2955
 
1378
- export { hold, keyed, render };
2956
+ export { hold, renderInto, renderer };
1379
2957
  //# sourceMappingURL=vera-renderer-hydrate.js.map