@verajs/renderer 0.2.2 → 0.3.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 (90) hide show
  1. package/README.md +711 -225
  2. package/dist/development/vera-renderer-elements.d.ts +39 -0
  3. package/dist/development/vera-renderer-elements.d.ts.map +1 -0
  4. package/dist/development/vera-renderer-elements.js +193 -0
  5. package/dist/development/vera-renderer-elements.js.map +1 -0
  6. package/dist/development/vera-renderer-hydrate-slots.d.ts +94 -0
  7. package/dist/development/vera-renderer-hydrate-slots.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-hydrate-slots.js +325 -0
  9. package/dist/development/vera-renderer-hydrate-slots.js.map +1 -0
  10. package/dist/development/vera-renderer-hydration.d.ts +332 -0
  11. package/dist/development/vera-renderer-hydration.d.ts.map +1 -0
  12. package/dist/development/vera-renderer-hydration.js +864 -0
  13. package/dist/development/vera-renderer-hydration.js.map +1 -0
  14. package/dist/development/vera-renderer-keyed.d.ts +25 -8
  15. package/dist/development/vera-renderer-keyed.d.ts.map +1 -1
  16. package/dist/development/vera-renderer-keyed.js +843 -268
  17. package/dist/development/vera-renderer-keyed.js.map +1 -1
  18. package/dist/development/vera-renderer-multi-window.d.ts +5 -0
  19. package/dist/development/vera-renderer-multi-window.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-multi-window.js +40 -0
  21. package/dist/development/vera-renderer-multi-window.js.map +1 -0
  22. package/dist/development/vera-renderer-namespaces.d.ts +64 -0
  23. package/dist/development/vera-renderer-namespaces.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-namespaces.js +94 -0
  25. package/dist/development/vera-renderer-namespaces.js.map +1 -0
  26. package/dist/development/vera-renderer-native-elements.d.ts +13 -0
  27. package/dist/development/vera-renderer-native-elements.d.ts.map +1 -0
  28. package/dist/development/vera-renderer-native-elements.js +231 -0
  29. package/dist/development/vera-renderer-native-elements.js.map +1 -0
  30. package/dist/development/vera-renderer-portal.d.ts +29 -0
  31. package/dist/development/vera-renderer-portal.d.ts.map +1 -0
  32. package/dist/development/vera-renderer-portal.js +167 -0
  33. package/dist/development/vera-renderer-portal.js.map +1 -0
  34. package/dist/development/vera-renderer-profiler.d.ts +48 -96
  35. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  36. package/dist/development/vera-renderer-profiler.js +2423 -2140
  37. package/dist/development/vera-renderer-profiler.js.map +1 -1
  38. package/dist/development/vera-renderer-slots.d.ts +88 -92
  39. package/dist/development/vera-renderer-slots.d.ts.map +1 -1
  40. package/dist/development/vera-renderer-slots.js +1834 -1237
  41. package/dist/development/vera-renderer-slots.js.map +1 -1
  42. package/dist/development/vera-renderer-spread.d.ts +7 -41
  43. package/dist/development/vera-renderer-spread.d.ts.map +1 -1
  44. package/dist/development/vera-renderer-spread.js +539 -477
  45. package/dist/development/vera-renderer-spread.js.map +1 -1
  46. package/dist/development/vera-renderer-tag.d.ts +12 -3
  47. package/dist/development/vera-renderer-tag.d.ts.map +1 -1
  48. package/dist/development/vera-renderer-tag.js +671 -513
  49. package/dist/development/vera-renderer-tag.js.map +1 -1
  50. package/dist/development/vera-renderer-until.d.ts +24 -0
  51. package/dist/development/vera-renderer-until.d.ts.map +1 -0
  52. package/dist/development/vera-renderer-until.js +83 -0
  53. package/dist/development/vera-renderer-until.js.map +1 -0
  54. package/dist/development/vera-renderer.d.ts +48 -96
  55. package/dist/development/vera-renderer.d.ts.map +1 -1
  56. package/dist/development/vera-renderer.js +2400 -2104
  57. package/dist/development/vera-renderer.js.map +1 -1
  58. package/dist/vera-renderer-elements.min.js +2 -0
  59. package/dist/vera-renderer-elements.min.js.map +1 -0
  60. package/dist/vera-renderer-hydrate-slots.min.js +2 -0
  61. package/dist/vera-renderer-hydrate-slots.min.js.map +1 -0
  62. package/dist/vera-renderer-hydration.min.js +3 -0
  63. package/dist/vera-renderer-hydration.min.js.map +1 -0
  64. package/dist/vera-renderer-keyed.min.js +1 -1
  65. package/dist/vera-renderer-keyed.min.js.map +1 -1
  66. package/dist/vera-renderer-multi-window.min.js +2 -0
  67. package/dist/vera-renderer-multi-window.min.js.map +1 -0
  68. package/dist/vera-renderer-namespaces.min.js +2 -0
  69. package/dist/vera-renderer-namespaces.min.js.map +1 -0
  70. package/dist/vera-renderer-native-elements.min.js +2 -0
  71. package/dist/vera-renderer-native-elements.min.js.map +1 -0
  72. package/dist/vera-renderer-portal.min.js +2 -0
  73. package/dist/vera-renderer-portal.min.js.map +1 -0
  74. package/dist/vera-renderer-slots.min.js +1 -1
  75. package/dist/vera-renderer-slots.min.js.map +1 -1
  76. package/dist/vera-renderer-spread.min.js +1 -1
  77. package/dist/vera-renderer-spread.min.js.map +1 -1
  78. package/dist/vera-renderer-tag.min.js +1 -1
  79. package/dist/vera-renderer-tag.min.js.map +1 -1
  80. package/dist/vera-renderer-until.min.js +2 -0
  81. package/dist/vera-renderer-until.min.js.map +1 -0
  82. package/dist/vera-renderer.min.js +1 -1
  83. package/dist/vera-renderer.min.js.map +1 -1
  84. package/package.json +52 -9
  85. package/dist/development/vera-renderer-hydrate.d.ts +0 -147
  86. package/dist/development/vera-renderer-hydrate.d.ts.map +0 -1
  87. package/dist/development/vera-renderer-hydrate.js +0 -3136
  88. package/dist/development/vera-renderer-hydrate.js.map +0 -1
  89. package/dist/vera-renderer-hydrate.min.js +0 -2
  90. package/dist/vera-renderer-hydrate.min.js.map +0 -1
@@ -1,3136 +0,0 @@
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
-
84
- /**
85
- * @verajs/renderer — a ground-up, keyed, template-identity renderer.
86
- *
87
- * Replaces the Reef-derived renderer, which flattened every template to an HTML string and
88
- * re-parsed it on each change — O(whole template) work for a one-row edit, measured at 85 ms for a
89
- * two-row swap that lit-html does in 3.5 ms.
90
- *
91
- * The architecture here is the one that wins that benchmark:
92
- *
93
- * 1. A tagged template literal's `strings` array is frozen and IDENTICAL for every call from the
94
- * same call site, so it is a cache key for the template's static shape. The shape is parsed
95
- * ONCE into a `<template>` element with markers where the expressions go.
96
- * 2. Rendering clones that template and binds "parts" to the marker positions. Every later render
97
- * of the same shape only compares and commits the dynamic values — static content is never
98
- * touched again.
99
- * 3. Arrays reconcile KEYED (see `keyed()`), with head/tail fast paths and map-based moves, so a
100
- * reorder moves nodes instead of rebuilding them.
101
- *
102
- * Built in, where lit-html requires directive imports: keyed list reconciliation (`keyed`),
103
- * element refs (element-position expressions), toggled-DOM preservation (`hold`), and a
104
- * whole-range fast clear — one `textContent = ''` where lit removes thousands of nodes one at a
105
- * time. Like-for-like (lit-html + repeat + ref + cache: 5 021 B gzip), this file is ~28% smaller.
106
- *
107
- * What it deliberately does NOT have, which is why it is smaller than lit-html: no directive
108
- * protocol, no `noChange`/`nothing` sentinels (in a single-expression attribute, `null`/`undefined`
109
- * REMOVE the attribute; in a child, they clear it), no sanitizer indirection, no async parts, no
110
- * dev-mode branches.
111
- *
112
- * Known limits, deliberate and shared with lit-html's envelope: no bindings inside comments (the
113
- * value is consumed and ignored), no dynamic tag names, and nested `<template>` elements' contents
114
- * are not traversed.
115
- *
116
- * CONTRACTS THE SPEED PAYS FOR — these are the trade, documented rather than discovered:
117
- *
118
- * - **The renderer owns its container below the mount point.** The whole-range fast clear wipes
119
- * everything in a parent the part fully owns, including nodes user code appended there by hand
120
- * (lit-html would preserve them). Same contract as mounting Vue or React into a container.
121
- * - **Do not call `Node.normalize()` on rendered content.** Child anchors are text nodes, and
122
- * normalize merges adjacent text — lit-html's comment anchors are immune to this; ours are not.
123
- * - **A plain string renders as text, never as HTML.** The Reef renderer parsed strings as markup;
124
- * this one has no innerHTML sink at all (an XSS class removed). The deliberate escape hatch for
125
- * trusted markup is a property binding: `.innerHTML=${trusted}`.
126
- * - **Hydration is automatic and markerless.** The first render into a container that already has
127
- * children adopts them as server output of the same template (statics matched byte-for-byte,
128
- * anchors installed by splitting live text at known value positions), falling back to a clean
129
- * render on any mismatch. Requires the initial client render to match server state — same
130
- * contract as React/Vue hydration.
131
- * - **No directive protocol.** The template language itself is closed to extension — Vera extends
132
- * at the framework layer (inserts) and through element refs, not inside the renderer's value
133
- * handling.
134
- * - Event handlers are invoked with `this` bound to the ELEMENT (lit binds its host).
135
- *
136
- * NAMING NOTE: internal class fields and methods are `_`-prefixed because the production build
137
- * mangles properties matching /^_[a-z]/ (see defaultRollupConfig). That is what lets this file use
138
- * full descriptive names while still shipping one-letter properties — locals and top-level names
139
- * are mangled by default anyway, but property names are not. `_$litType$` and `handleEvent`
140
- * deliberately do not match the pattern: the first is an interop wire format, the second is called
141
- * by the DOM itself.
142
- */
143
- /**
144
- * Preserves the DOM of templates a child position toggles away from, instead of destroying it —
145
- * form values, scroll positions and media playback survive the round trip (lit-html calls this
146
- * `cache`). Stashed DOM is parked in its instance's own fragment and re-adopted on return.
147
- *
148
- * ```js
149
- * html`<div>${hold(editing ? editor() : viewer())}</div>`
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.
158
- */
159
- const hold = (result) => result != null && typeof result === 'object' && isTemplateResult(result)
160
- ? { $h: result }
161
- : result;
162
- /**
163
- * Unique per module load, so user text can never collide with it. Randomness here cannot break
164
- * template caching — the marker only ever pairs a scan with its own Template construction.
165
- */
166
-
167
- const MARKER = '$v' + ((Math.random() * 1e9) >>> 0).toString(36) + '$';
168
- /** `<?xyz>` parses as a bogus comment whose data is `?xyz`. */
169
- const MARKER_COMMENT_DATA = '?' + MARKER;
170
- const doc = document;
171
- const comment = (data = '') => doc.createComment(data);
172
- /**
173
- * One walker for every template construction, re-aimed by assigning `currentNode`. Traversal of a
174
- * detached fragment cannot escape it — ascent stops at a null parent — and no walk is ever
175
- * re-entered mid-flight: an inner instantiation only begins after the outer walk has finished
176
- * collecting its parts.
177
- */
178
- const markerWalker = doc.createTreeWalker(doc, 129 /* ELEMENT | COMMENT */);
179
- /**
180
- * Second shared walker for indexing and instantiation. Templates ship with NO marker comments —
181
- * every child slot's anchor is its primed text node — so instances index over elements and texts.
182
- * Marker comments exist only transiently during template construction, and are created lazily at
183
- * runtime only if a slot upgrades from text to template/array content. Sharing the walker saves a
184
- * TreeWalker allocation per instance, which is 10 000 allocations in a 10 000-row create.
185
- */
186
- const instanceWalker = doc.createTreeWalker(doc, 5 /* ELEMENT | TEXT */);
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;
218
- const ATTR_NAME_DELIMITER = /[\s"'>=/]/;
219
- /** What an expression position turned out to be. */
220
- const CHILD = 0;
221
- const ATTRIBUTE = 1;
222
- const IGNORED = 2; // value consumed, nothing rendered (bindings inside comments, junk positions)
223
- /** Scanner states. */
224
- const IN_TEXT = 0;
225
- const IN_TAG = 1;
226
- const IN_QUOTED_VALUE = 2; // a static quoted attribute value (no binding seen yet)
227
- const IN_COMMENT = 3;
228
- const IN_RAW_TEXT = 4; // inside <script>/<style>/<textarea>/<title>
229
- const IN_BOUND_VALUE = 5; // collecting a bound attribute's statics
230
- /**
231
- * One pass over the template strings, producing parseable HTML with markers plus an ordered spec
232
- * list. Runs once per template shape, so clarity beats micro-optimisation here.
233
- *
234
- * A small state machine rather than tail regexes, because `>` inside quoted attribute values and
235
- * inside comments must not terminate a tag, and raw-text elements swallow markup.
236
- */
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) => {
262
- const specs = [];
263
- let markup = '';
264
- let state = IN_TEXT;
265
- let quote = '';
266
- let quoteStart = 0; // markup index of the opening quote while IN_QUOTED_VALUE
267
- let rawTag = ''; // which raw-text element we are inside
268
- let tagNameStart = 0; // markup index where the current tag's name begins
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;
280
- let attrName = '';
281
- let statics = [];
282
- let pending = ''; // the static chunk currently being collected IN_BOUND_VALUE
283
- /** Backscan an attribute name that ends at `end` (exclusive); '' when malformed. */
284
- const attrNameBefore = (end) => {
285
- let at = end;
286
- while (at > 0 && !ATTR_NAME_DELIMITER.test(markup[at - 1]))
287
- at--;
288
- return markup.slice(at, end);
289
- };
290
- for (let i = 0; i < strings.length; i++) {
291
- const segment = strings[i];
292
- let pos = 0;
293
- while (pos < segment.length) {
294
- const ch = segment[pos];
295
- if (state === IN_BOUND_VALUE) {
296
- if (ch === quote ||
297
- (quote === '' && (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '>' || ch === '/'))) {
298
- /**
299
- * The bound attribute closes. Emit a marker attribute whose VALUE carries the statics
300
- * joined by the marker — reading them back from the parsed attribute means entities
301
- * arrive decoded, exactly as a static attribute would.
302
- */
303
- statics.push(pending);
304
- const quoteChar = quote || '"';
305
- markup += ` ${specs.length}${MARKER}=${quoteChar}${statics.join(MARKER)}${quoteChar}`;
306
- specs.push(true
307
- ? { _type: ATTRIBUTE, _name: attrName, _tag: markup.slice(tagNameStart).match(/^[a-zA-Z][^\s/>]*/)?.[0] }
308
- : { _type: ATTRIBUTE, _name: attrName });
309
- state = IN_TAG;
310
- if (quote !== '')
311
- pos++; // consume the closing quote; unquoted terminators reprocess IN_TAG
312
- continue;
313
- }
314
- pending += ch;
315
- pos++;
316
- }
317
- else if (state === IN_TEXT) {
318
- if (ch === '<') {
319
- if (segment.startsWith('!--', pos + 1)) {
320
- state = IN_COMMENT;
321
- markup += '<!--';
322
- pos += 4;
323
- continue;
324
- }
325
- isClosing = segment[pos + 1] === '/';
326
- tagNameStart = markup.length + (isClosing ? 2 : 1);
327
- state = IN_TAG;
328
- }
329
- markup += ch;
330
- pos++;
331
- }
332
- else if (state === IN_TAG) {
333
- if (ch === '"' || ch === "'") {
334
- quote = ch;
335
- quoteStart = markup.length;
336
- state = IN_QUOTED_VALUE;
337
- }
338
- else if (ch === '>') {
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
- }
348
- if (!isClosing && RAW_TEXT_TAGS.test(tagName) && !markup.endsWith('/')) {
349
- rawTag = tagName.toLowerCase();
350
- state = IN_RAW_TEXT;
351
- }
352
- else {
353
- state = IN_TEXT;
354
- }
355
- }
356
- markup += ch;
357
- pos++;
358
- }
359
- else if (state === IN_QUOTED_VALUE) {
360
- if (ch === quote)
361
- state = IN_TAG;
362
- markup += ch;
363
- pos++;
364
- }
365
- else if (state === IN_COMMENT) {
366
- if (ch === '-' && segment.startsWith('->', pos + 1)) {
367
- markup += '-->';
368
- pos += 3;
369
- state = IN_TEXT;
370
- continue;
371
- }
372
- markup += ch;
373
- pos++;
374
- }
375
- else {
376
- // IN_RAW_TEXT
377
- if (ch === '<' &&
378
- segment.slice(pos + 1, pos + 2 + rawTag.length).toLowerCase() === '/' + rawTag &&
379
- (pos + 2 + rawTag.length >= segment.length || /[\s/>]/.test(segment[pos + 2 + rawTag.length]))) {
380
- isClosing = true;
381
- tagNameStart = markup.length + 2;
382
- state = IN_TAG;
383
- }
384
- markup += ch;
385
- pos++;
386
- }
387
- }
388
- // ── expression boundary ──────────────────────────────────────────────────
389
- if (i === strings.length - 1)
390
- break;
391
- if (state === IN_TEXT) {
392
- markup += `<?${MARKER}>`;
393
- specs.push({ _type: CHILD });
394
- }
395
- else if (state === IN_RAW_TEXT) {
396
- markup += MARKER; // a text marker; comments cannot be parsed inside raw-text elements
397
- specs.push({ _type: CHILD });
398
- }
399
- else if (state === IN_COMMENT) {
400
- specs.push({ _type: IGNORED }); // binding inside a comment: consumed, ignored
401
- }
402
- else if (state === IN_BOUND_VALUE) {
403
- statics.push(pending); // this attribute spans another expression
404
- pending = '';
405
- }
406
- else if (state === IN_QUOTED_VALUE) {
407
- // expression inside a quoted attribute value -> becomes a bound attribute
408
- const name = markup[quoteStart - 1] === '=' ? attrNameBefore(quoteStart - 1) : '';
409
- if (name) {
410
- attrName = name;
411
- statics = [markup.slice(quoteStart + 1)]; // the static prefix already inside the quotes
412
- pending = '';
413
- markup = markup.slice(0, quoteStart - 1 - name.length); // cut `name="` back out
414
- state = IN_BOUND_VALUE;
415
- }
416
- else {
417
- specs.push({ _type: IGNORED });
418
- }
419
- }
420
- else {
421
- // IN_TAG: `name=${x}` unquoted, or an element-position expression
422
- const name = markup.endsWith('=') ? attrNameBefore(markup.length - 1) : '';
423
- if (name) {
424
- attrName = name;
425
- statics = [''];
426
- pending = '';
427
- quote = '';
428
- markup = markup.slice(0, markup.length - 1 - name.length);
429
- state = IN_BOUND_VALUE;
430
- }
431
- else {
432
- /**
433
- * Element-position expression — an element REF, not a no-op. Marked exactly like a bound
434
- * attribute ('&' cannot begin a real attribute binding), so no new machinery exists for it.
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
- }
474
- markup += ` ${specs.length}${MARKER}="${MARKER}"`;
475
- specs.push({ _type: ATTRIBUTE, _name: '&' });
476
- }
477
- }
478
- }
479
- return { markup, specs };
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
- };
560
- const templateCache = new WeakMap();
561
- class Template {
562
- _element;
563
- _parts = [];
564
- constructor(result) {
565
- const type = result._$litType$ ?? 1;
566
- const { markup, specs } = scan(result.strings, type);
567
- this._element = doc.createElement('template');
568
- /** svg/mathml fragments only parse inside their root; wrap, then unwrap below. */
569
- this._element.innerHTML = type === 2 ? `<svg>${markup}</svg>` : type === 3 ? `<math>${markup}</math>` : markup;
570
- const content = this._element.content;
571
- if (type !== 1) {
572
- const wrapper = content.firstChild;
573
- while (wrapper.firstChild)
574
- content.insertBefore(wrapper.firstChild, wrapper);
575
- content.removeChild(wrapper);
576
- }
577
- /**
578
- * Pass 1 — DISCOVER over ELEMENT | COMMENT: pair scan specs with parsed nodes in document
579
- * order (which is expression order), and swap every marker comment for a primed empty text
580
- * node. The shipped template then contains no comments at all: each clone is three nodes
581
- * lighter per typical row, and the primed text doubles as both anchor and first-commit target.
582
- */
583
- markerWalker.currentNode = content;
584
- let specIndex = 0;
585
- let node;
586
- const parts = this._parts;
587
- const consumeIgnored = () => {
588
- while (specIndex < specs.length && specs[specIndex]._type === IGNORED) {
589
- parts.push({ _type: IGNORED, _index: -1 });
590
- specIndex++;
591
- }
592
- };
593
- consumeIgnored();
594
- while (specIndex < specs.length && (node = markerWalker.nextNode()) !== null) {
595
- if (node.nodeType === 1) {
596
- const element = node;
597
- if (element.hasAttributes()) {
598
- for (const attributeName of element.getAttributeNames()) {
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
- }
621
- /**
622
- * The marker attribute's value carries the statics; the REAL (case-preserved) name
623
- * comes from the spec — the HTML parser lowercases attribute names, which would
624
- * corrupt `.someProp`.
625
- */
626
- const spec = specs[specIndex++];
627
- parts.push({
628
- _type: ATTRIBUTE,
629
- _index: -1,
630
- _name: spec._name,
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),
641
- _node: element,
642
- });
643
- element.removeAttribute(attributeName);
644
- consumeIgnored();
645
- }
646
- }
647
- }
648
- if (RAW_TEXT_TAGS.test(element.tagName) && element.textContent.includes(MARKER)) {
649
- /**
650
- * Comments cannot be PARSED inside raw-text elements, but they are legal DOM once
651
- * created — so the scan left text markers, and here they become real marker comments.
652
- * The walker visits them next and they pair as ordinary child parts.
653
- */
654
- const pieces = element.textContent.split(MARKER);
655
- element.textContent = '';
656
- for (let p = 0; p < pieces.length - 1; p++) {
657
- if (pieces[p])
658
- element.append(pieces[p]);
659
- element.append(comment(MARKER_COMMENT_DATA));
660
- }
661
- if (pieces[pieces.length - 1])
662
- element.append(pieces[pieces.length - 1]);
663
- }
664
- }
665
- else if (node.data === MARKER_COMMENT_DATA) {
666
- specIndex++;
667
- const primedText = doc.createTextNode('');
668
- node.parentNode.insertBefore(primedText, node);
669
- /** Re-aim the walker before removing the node it stands on. */
670
- markerWalker.currentNode = primedText;
671
- node.remove();
672
- if (true )
673
- warnImplicitSection(primedText.parentNode);
674
- parts.push({ _type: CHILD, _index: -1, _node: primedText });
675
- consumeIgnored();
676
- }
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
- }
707
- /** Pass 2 — INDEX over ELEMENT | TEXT, the mask instances walk with. */
708
- instanceWalker.currentNode = content;
709
- let nodeIndex = -1;
710
- let partIndex = 0;
711
- while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
712
- partIndex++;
713
- while (partIndex < parts.length && (node = instanceWalker.nextNode()) !== null) {
714
- nodeIndex++;
715
- while (partIndex < parts.length && parts[partIndex]._node === node) {
716
- parts[partIndex]._index = nodeIndex;
717
- partIndex++;
718
- while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
719
- partIndex++;
720
- }
721
- }
722
- for (const part of parts)
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
- }
758
- }
759
- }
760
- const getTemplate = (result) => {
761
- let template = templateCache.get(result.strings);
762
- if (template === undefined)
763
- templateCache.set(result.strings, (template = new Template(result)));
764
- return template;
765
- };
766
- /** Anything bound to a live position: commits values[index..], returns the next value index. */
767
- const IGNORED_PART = { _commit: (_values, index) => index + 1 };
768
- /** Never equal to any user value, so the first commit always runs. */
769
- const UNSET = {};
770
- /** A fresh markered part: two comments inserted before `ref` in `parent`. */
771
- const createMarkeredPart = (parent, ref) => {
772
- const start = comment();
773
- const end = comment();
774
- parent.insertBefore(start, ref);
775
- parent.insertBefore(end, ref);
776
- return new ChildPart(start, end);
777
- };
778
- /**
779
- * Text for an attribute built from several expressions.
780
- *
781
- * `` `${value}` `` rather than `String(value)`, and the difference is exactly one case. Both are
782
- * ToString with hint `'string'` for everything else; `String` alone special-cases a **symbol** and
783
- * returns its description instead of throwing. Every single-expression binding assigns straight to
784
- * the DOM and gets WebIDL's `DOMString` conversion, which throws on one — so `title=${symbol}` threw
785
- * and `title="a ${symbol} b"` quietly rendered `a Symbol(s) b`. The same sigil on the same attribute,
786
- * disagreeing with itself depending on whether static text sat beside it.
787
- */
788
- const toText = (value) => (value == null ? '' : `${value}`);
789
- /** Binding kinds, resolved once from the attribute name's first character. */
790
- const ATTR = 0; // plain attribute
791
- const PROPERTY = 1; // .name
792
- const BOOLEAN = 2; // ?name
793
- /**
794
- * `!name` — a property written from the *live* DOM rather than from what this binding last wrote.
795
- *
796
- * Numbered below `EVENT` deliberately: `kind >= EVENT` is what decides a value is passed raw rather
797
- * than joined from the statics, and a live binding is a property, so `!title="a${x}b"` has to join
798
- * like every other one.
799
- */
800
- const LIVE = 3;
801
- const EVENT = 4; // @name
802
- /** A binding that must never write — see the `__proto__` refusal in the constructor. */
803
- const REFUSED = -1;
804
- /** `.name` on a custom element nothing receives yet — records into `_$props$`, then becomes
805
- * `PROPERTY`. A distinct kind keeps the steady-state property path free of any adoption check. */
806
- const PROP_ADOPT = 6;
807
- /**
808
- * The `PROP_ADOPT` commit, kept OUT of `_commit` so that function's size — and the JIT layout of
809
- * its hot `PROPERTY`/`ATTR` branches — is unchanged from before this feature. `_commit` carries one
810
- * dispatch line; all of this lives here, off every part's steady state.
811
- *
812
- * One question decides everything: **after the write, does anything receive this property?** An
813
- * accessor anywhere on the chain — the platform's own (`title`, `hidden`), a component's declared
814
- * one, or the pair core's `init()` defines — means the write just landed in real hands: no record,
815
- * and the part rejoins `PROPERTY` for good. The walk is one step when the write created an own data
816
- * property (nobody consumed it) and stops at the first descriptor either way, and it is what keeps
817
- * a platform property on a lazy tag out of the record — recording `.title` would end with the drain
818
- * shadowing `HTMLElement.prototype.title` and breaking it.
819
- *
820
- * An unreceived write is recorded under the sigiled expando **`_$props$`**, because two arrival
821
- * orders both need it: on a LAZY tag the value sits as a plain own property that the class's field
822
- * initializers will overwrite at upgrade (the clobber the `PROPERTY` branch only *detects*), and on
823
- * an EAGER one the value survives but is indistinguishable from the component's own fields by the
824
- * time `init()` runs. The record answers both — core's `init()` drains it, re-applying values
825
- * unconditionally, which repairs BOTH spellings of the clobber (`item;` and `item = default`): it
826
- * never asks whether a clobber happened, it asserts a bound value outranks a class default, which
827
- * is what props mean. Element-carried because `./spread.ts` writes the same properties from a
828
- * separate bundle with no shared registry — the `_$`-sigiled member is the cross-bundle channel,
829
- * and the recorder there is this one's deliberate twin.
830
- *
831
- * Returns the part's NEXT kind: `PROPERTY` once something receives the property or the element is
832
- * upgraded (its record is final — `init()` drains it in the same tick) or has no realm; `REFUSED`
833
- * for a getter with no setter, so the binding goes inert instead of the flipped plain write
834
- * throwing on the next commit; `0` to stay adopting — a dash-named element that never upgrades and
835
- * never receives keeps recording, so its record stays current rather than staling. The one
836
- * retention this leaves: a defined non-vera element with a plain data property keeps its FIRST
837
- * committed values in `_$props$` for its lifetime — bounded, one generation, and the part itself
838
- * already retains the current generation in `_committed`.
839
- */
840
- const commitAdopt = (element, name, value) => {
841
- const el = element;
842
- /**
843
- * The walk comes BEFORE the write, because what the walk finds decides whether writing is even
844
- * legal: a SETTER receives the value (and a setter that throws is the component's own error), a
845
- * GETTER with no setter cannot — the old order assigned first, which in strict mode threw a raw
846
- * TypeError out of the render for the eager spelling of exactly the case the drain refuses by
847
- * name for the lazy one. Same contested state, one rule, both arrival orders — and the server's
848
- * `deliverProperty` applies it too. The dev warning defers to `_$adopt$` where it exists: an
849
- * initialized component's drain already speaks, and two voices for one binding is noise.
850
- */
851
- let carrier = el;
852
- while (carrier !== null) {
853
- const desc = Object.getOwnPropertyDescriptor(carrier, name);
854
- if (desc !== undefined) {
855
- if (desc.set !== undefined) {
856
- el[name] = value;
857
- return PROPERTY;
858
- }
859
- if (desc.get !== undefined) {
860
- /** An initialized component's receiver owns the refusal (and its channel); for anything
861
- * else this is the only door, so it says so itself. Either way the binding goes INERT —
862
- * flipping to `PROPERTY` would make the next commit's plain write throw. */
863
- if (el._$adopt$ !== undefined)
864
- el._$adopt$(name, value);
865
- else if (true )
866
- console.warn(`[vera] renderer: <${element.localName}> declares \`${name}\` as a getter with no ` +
867
- `setter — the value bound by \`.${name}=\${…}\` cannot be delivered and the binding ` +
868
- `is ignored. Add a setter, or stop binding it.`);
869
- return REFUSED;
870
- }
871
- break; // a data property — an own field, or an inherited default: nothing receives it
872
- }
873
- carrier = Object.getPrototypeOf(carrier);
874
- }
875
- el[name] = value;
876
- /**
877
- * An initialized component receives LIVE: `init()` left `_$adopt$` on the element, and a key it
878
- * has not adopted yet goes through that door — a record here would never be read again, because
879
- * the drain already ran. This is how a hydrated child gets the props its parent commits after
880
- * the child settled, and how a spread bag's conditional key arrives reactive on a live element.
881
- */
882
- if (el._$adopt$ !== undefined) {
883
- el._$adopt$(name, value);
884
- return PROPERTY;
885
- }
886
- const record = (el._$props$ ??= {});
887
- const firstRecording = !Object.hasOwn(record, name);
888
- record[name] = value;
889
- /**
890
- * Upgrade is read off the PROTOTYPE, never off `el.constructor`: a spread bag's keys are runtime
891
- * data, so a bag carrying a key named `constructor` writes an own property that shadows the real
892
- * one, and a check that reads it would then misjudge every later commit. No property write can
893
- * move an element's prototype — the one assignment that could, `__proto__`, both twins refuse.
894
- * The realm comes from the element, as always.
895
- */
896
- const win = element.ownerDocument.defaultView;
897
- const upgraded = win === null || Object.getPrototypeOf(el) !== win.HTMLElement.prototype;
898
- /**
899
- * **The clobber detector, for the element the drain will never reach.** A component that calls
900
- * `init()` has the record re-applied, so for it the pre-upgrade window is repaired; an element
901
- * that never drains — a plain custom element with a class field — still loses the bound value to
902
- * the field initializer at upgrade, exactly as before this feature, and still deserves the
903
- * warning. Told apart by OWNERSHIP, not by value: after the definition arrives (and, for a
904
- * connected element, `connectedCallback` and the drain have run synchronously inside `define()`),
905
- * an own accessor means the drain took the property and there is nothing to report. Identity
906
- * against the COMMITTED value would lie twice — a drained value reads back through the store's
907
- * proxy, and a value superseded by a later pre-upgrade commit differs without anything being
908
- * wrong — so the comparison is against the RECORD, which later recordings keep current, and the
909
- * subscription is installed once per (element, property), on the first recording. The registry
910
- * is the element's own realm's. Development only; production carries no check, no message, no
911
- * `whenDefined` subscription.
912
- */
913
- if (true && win !== null && !upgraded && firstRecording) {
914
- const tag = element.localName;
915
- win.customElements.whenDefined(tag).then(() => {
916
- /** Ownership is asked of the whole CHAIN: the drain's own accessor, a class's prototype
917
- * pair the value was handed to, or a get-only surface the drain refused by name — every
918
- * one means the property has an owner and this closure has nothing left to report. */
919
- let carrier = el;
920
- let owned = false;
921
- while (carrier !== null) {
922
- const desc = Object.getOwnPropertyDescriptor(carrier, name);
923
- if (desc !== undefined) {
924
- owned = desc.get !== undefined || desc.set !== undefined;
925
- break;
926
- }
927
- carrier = Object.getPrototypeOf(carrier);
928
- }
929
- if (!owned && el[name] !== record[name])
930
- console.warn(`[vera] renderer: the value bound by \`.${name}=\${…}\` on <${tag}> was replaced ` +
931
- `while the element upgraded. A class field is the usual cause: at ES2022 ` +
932
- `\`${name}?: …\` emits \`${name};\`, which runs during upgrade and overwrites ` +
933
- `whatever was set beforehand — write it \`declare ${name}?: …\` instead, which ` +
934
- `emits nothing. A component that calls init() adopts bound properties automatically ` +
935
- `and never sees this; this element did not. Ignore this if the component replaced ` +
936
- `the value on purpose.`);
937
- });
938
- }
939
- return upgraded ? PROPERTY : 0;
940
- };
941
- /**
942
- * Calls an element ref, and survives one that throws.
943
- *
944
- * A ref runs in the middle of committing a template's parts, so an unguarded throw left the commit
945
- * half applied and unwound the render that triggered it — the component's shadow root ended up
946
- * **empty and stayed that way**, and every later update threw at the same line. The error was
947
- * reported, so the only symptom was a component that had silently stopped existing.
948
- *
949
- * The same judgement `handleEvent` makes a few lines up: a mistake in code the template was handed
950
- * is named, not raised from inside the framework at a point where the value's origin is long gone.
951
- * The prefix goes on our own sentence and the error is passed alongside, so it stays filterable
952
- * without misattributing someone else's `Error`.
953
- */
954
- const applyRef = (callback, element) => {
955
- try {
956
- callback(element);
957
- }
958
- catch (error) {
959
- /** The sentence is development's; production keeps the prefix and the error carries the rest. */
960
- if (true )
961
- console.error('[vera] an element ref threw; the render continued without it.', error);
962
- else
963
- console.error('[vera] ref threw', error);
964
- }
965
- };
966
- const REF = 5; // element-position expression
967
- class AttrPart {
968
- _element;
969
- _name;
970
- _statics;
971
- _slots; // how many expression values this binding consumes
972
- _kind;
973
- _isFullValue; // exactly one expression with no static text around it
974
- _committed = UNSET;
975
- _handler = null;
976
- /** `<select>.value`, which cannot be applied where it is written — see `pendingSelects`. */
977
- _select = false;
978
- /** The template statically wrote this attribute, so a first nullish commit must still remove. */
979
- _present;
980
- constructor(element, name, statics, present = false) {
981
- const first = name[0];
982
- let kind = first === '.'
983
- ? PROPERTY
984
- : first === '?'
985
- ? BOOLEAN
986
- : first === '@'
987
- ? EVENT
988
- : first === '&'
989
- ? REF
990
- : first === '!'
991
- ? LIVE
992
- : ATTR;
993
- let realName = kind ? name.slice(1) : name;
994
- /**
995
- * **`__proto__` is not a property write, so no property binding may make one.**
996
- *
997
- * `element.__proto__ = value` hits `Object.prototype`'s `__proto__` ACCESSOR and replaces the
998
- * element's prototype, stripping every DOM method it has. `.__proto__=${x}` crashed out of the
999
- * commit with an unreadable internal error; `!__proto__=${x}` bricked the element silently and
1000
- * the wreckage surfaced in a LATER render, naming the renderer rather than the binding. There
1001
- * is no legitimate use, so unlike `.innerHTML` there is no spelling to point at — the binding
1002
- * is refused and never writes.
1003
- *
1004
- * **The deliberate twin of `refusedSink` in `./spread.ts`**, which refuses the same name for
1005
- * the same reason. The two entries are independent bundles and neither imports the other, so
1006
- * the rule is copied on purpose (the repo's standing note: sigil rules live in both AttrPart
1007
- * and spread, and a fix has to visit every copy). `tests/dangerous-binding-matrix.test.mjs`
1008
- * fails if one of them starts refusing something the other allows.
1009
- */
1010
- if ((kind === PROPERTY || kind === LIVE) && realName === '__proto__') {
1011
- kind = REFUSED;
1012
- if (true )
1013
- console.warn(`[vera] <${element.localName}> binds \`${name}\`, which would replace the element's own ` +
1014
- `prototype and destroy it — no property write does this, and no use of it is legitimate. ` +
1015
- `The binding is ignored.`);
1016
- }
1017
- /**
1018
- * React muscle-memory, buildless: `onClick=${fn}` ≡ `@click=${fn}`. Strictly `on` + a capital —
1019
- * all-lowercase `onclick` stays a plain attribute (legal inline-handler HTML).
1020
- *
1021
- * `@verajs/renderer/spread` repeats these rules rather than importing them. Sharing them through
1022
- * `@verajs/shared-utils` was tried and reverted: the shared form has to return both the kind and
1023
- * the name, and the tuple it allocates cost this bundle 10 B. Principle #5 allows deliberate
1024
- * duplication where two things can legitimately diverge; here #7 decides it — weight is the
1025
- * product, and core and the renderer are the two packages where that is absolute.
1026
- */
1027
- if (kind === ATTR && first === 'o' && name.charCodeAt(1) === 110 && name.charCodeAt(2) > 64 && name.charCodeAt(2) < 91) {
1028
- kind = EVENT;
1029
- realName = name.slice(2).toLowerCase();
1030
- }
1031
- /**
1032
- * **A property write to a custom element starts as `PROP_ADOPT`**, a distinct kind so the
1033
- * steady-state `PROPERTY` commit path stays byte-for-byte unchanged — zero added instruction
1034
- * for every `.value=` on a built-in. Every dash-named element starts here, defined or not,
1035
- * because the record has to exist for BOTH arrival orders: an eager component's first commit
1036
- * lands after upgrade but before `init()` (one commit records, then the part flips), and a
1037
- * lazy one's land before upgrade (the part records until the definition arrives). `commitAdopt`
1038
- * decides which per commit and flips the part back to `PROPERTY` the moment something real
1039
- * receives the property, so the window is one commit for a defined element and the pre-upgrade
1040
- * stretch for a lazy one.
1041
- */
1042
- if (kind === PROPERTY && element.localName.includes('-'))
1043
- kind = PROP_ADOPT;
1044
- this._kind = kind;
1045
- this._name = realName;
1046
- this._element = element;
1047
- this._statics = statics;
1048
- this._slots = statics.length - 1;
1049
- this._isFullValue = this._slots === 1 && statics[0] === '' && statics[1] === '';
1050
- /** Resolved once, here, so the commit path costs one boolean rather than two comparisons. */
1051
- this._select = kind === PROPERTY && realName === 'value' && element.localName === 'select';
1052
- this._present = present;
1053
- }
1054
- /**
1055
- * Releases an element ref, because the element it named is going away.
1056
- *
1057
- * A ref was told about attachment and never about detachment, so it kept a detached node alive and
1058
- * a component reading `myRef.value` after a subtree was replaced got the old element back. Lit
1059
- * passes `undefined` for the same reason.
1060
- *
1061
- * `null` rather than `undefined`, because `.value` is a store property and `null` reads as
1062
- * "deliberately nothing" where `undefined` reads as "never set".
1063
- *
1064
- * **Reached when a subtree is rendered away, and deliberately not when a component is removed
1065
- * from the document.** The two are the same event to a reader and not to this renderer: a
1066
- * disconnect here is not a destruction, since moving a node between parents fires one and the
1067
- * component renders again on reconnect. Releasing there would blank every ref for the frame a
1068
- * move takes, and `_committed = UNSET` below means the re-apply could only happen on the next
1069
- * pass. Measured in `tests/renderer-ref-lifetime.test.mjs`, which asserts both halves so the
1070
- * asymmetry is a decision rather than something nobody looked at.
1071
- *
1072
- * A **self-applying** value is
1073
- * skipped: `_$apply$` receives the part and owns its own lifecycle, so telling it about detachment
1074
- * here would be a second protocol contradicting the first.
1075
- */
1076
- _release() {
1077
- const value = this._committed;
1078
- if (typeof value === 'function')
1079
- applyRef(value, null);
1080
- else if (value !== null && typeof value === 'object' && value._$apply$ === undefined)
1081
- value.value = null;
1082
- this._committed = UNSET;
1083
- }
1084
- /**
1085
- * Stable listener; swapping one function for another never touches the DOM.
1086
- *
1087
- * **It is not registered exactly once, and the difference is load-bearing.** A handler set back to
1088
- * `undefined` or `false` nulls `_handler` *without removing the listener* — inert, because
1089
- * `handleEvent` finds nothing callable — so the next non-null value sees `_handler === null` and
1090
- * calls `addEventListener` again. Measured: `function -> undefined -> function` registers twice.
1091
- *
1092
- * That is harmless only because the listener passed is **`this`, the part object itself**. The
1093
- * platform ignores a repeated `(type, listener, capture)` triple, verified with no framework
1094
- * involved — the same listener object added three times fires once. Pass a fresh closure here
1095
- * instead and dedup stops applying: every toggle through null adds another live listener, silently,
1096
- * and only in components that turn a handler off and on again.
1097
- *
1098
- * `tests/event-binding-fuzz.test.mjs` holds that as an invariant — it counts *fires*, not
1099
- * `addEventListener` calls, and making this listener a closure fails it.
1100
- *
1101
- * **Two shapes, because `addEventListener` takes two.** A function is called with the element as
1102
- * `this`; an object with a `handleEvent` method is invoked through it — the platform's own
1103
- * `EventListenerObject` protocol, which every engine accepts and lit supports. This used to call
1104
- * `.call()` unconditionally, so passing the platform's own listener shape bound successfully and
1105
- * then threw `this._handler.call is not a function` on **every** dispatch.
1106
- *
1107
- * Anything else is inert rather than throwing. A truthy non-function is a mistake, and
1108
- * development names it at the binding (see the `EVENT` branch in `_commit`) — where the mistake
1109
- * still is. Throwing here instead would raise from inside the framework on every user click, at a
1110
- * point where the value's origin is long gone.
1111
- */
1112
- handleEvent(event) {
1113
- const handler = this._handler;
1114
- if (typeof handler === 'function')
1115
- handler.call(this._element, event);
1116
- else if (typeof handler?.handleEvent === 'function')
1117
- handler.handleEvent(event);
1118
- }
1119
- /**
1120
- * `adopting` is set only by `@verajs/renderer/hydrate`, and only changes what happens to the
1121
- * three form-value properties the server can express in markup — see the branch below.
1122
- */
1123
- _commit(values, index, adopting) {
1124
- const kind = this._kind;
1125
- /** Refused in the constructor and never writes — it still has to consume its slots. */
1126
- if (kind === REFUSED)
1127
- return index + this._slots;
1128
- let value;
1129
- if (this._isFullValue || kind >= EVENT) {
1130
- value = values[index]; // raw and uncoerced — events and refs receive the actual value
1131
- }
1132
- else {
1133
- const statics = this._statics;
1134
- let joined = statics[0];
1135
- for (let i = 0; i < this._slots; i++)
1136
- joined += toText(values[index + i]) + statics[i + 1];
1137
- value = joined;
1138
- }
1139
- /**
1140
- * **A live property asks the element, not its own memory.**
1141
- *
1142
- * Every other kind skips a write when the value matches what it last wrote. That is what keeps
1143
- * a field someone has typed into — and it is wrong for a control whose DOM state changes as a
1144
- * *side effect of interacting with a sibling*. Clicking one radio unchecks the others with no
1145
- * event on them, so their bindings still say `true`, still match `_committed`, and never write
1146
- * again: the model and the page diverge and no amount of re-rendering reconciles them. A
1147
- * `<select>`'s options are the same shape.
1148
- *
1149
- * Deliberately narrow. This is not for text inputs — bind those with `.value` and let a
1150
- * person's typing stand. `?hidden` and plain attributes are not offered either: nothing changes
1151
- * them behind the renderer's back, so there is nothing to re-read.
1152
- */
1153
- if (kind === LIVE) {
1154
- this._committed = value;
1155
- /**
1156
- * **Except while adopting — on a form control.** Hydration reaches a DOM a person may
1157
- * already have used, and the click that checked a radio happened before any handler existed
1158
- * to tell the store about it — so re-asserting the server's choice here would throw the
1159
- * interaction away and nothing would ever put it back. Recorded, not written, exactly as
1160
- * the other form properties are; the first state-driven render after that applies live
1161
- * semantics normally.
1162
- *
1163
- * **A COMPONENT tag is the exception to the exception**: there is no user-editable carrier
1164
- * behind `!prop` on a component — it is a property delivery spelled with `!` — and the
1165
- * server DELIVERED it to the child's render, so yielding here dropped the one copy the
1166
- * client would ever get and hydration regressed the child's content to its prop-less state.
1167
- * Found by the hydration fixture on its first run. The write is unconditional and routes
1168
- * through the element like any component prop: an accessor receives it, an initialized
1169
- * component adopts it live.
1170
- */
1171
- if (true && adopting) {
1172
- /** Routed through `commitAdopt`, not written raw: the child hydrated BEFORE this commit,
1173
- * so only the adoption door re-runs its render. The part stays `LIVE` — the return is
1174
- * deliberately dropped — so live semantics resume on the next state-driven render. */
1175
- if (this._element.localName.includes('-'))
1176
- commitAdopt(this._element, this._name, value);
1177
- }
1178
- else {
1179
- const liveTarget = this._element;
1180
- if (liveTarget[this._name] !== value)
1181
- liveTarget[this._name] = value;
1182
- }
1183
- return index + this._slots;
1184
- }
1185
- /**
1186
- * **A `<select>`'s value cannot be applied where it is written.**
1187
- *
1188
- * Assigning it selects an option, and at the moment this part commits the options may not exist:
1189
- * parts commit in document order, so a nested `${items.map(…)}` has not run, and an `<option
1190
- * value=${id}>` has not been given its value either. The assignment then matches nothing, and the
1191
- * select falls back to its first option — silently showing the wrong one. Measured: a nested list
1192
- * selected index 0 instead of 1, and dynamic option values selected nothing at all.
1193
- * **lit-html has the same defect, byte for byte** — it was measured there too. React solves it by
1194
- * special-casing `<select value>` and applying it after children mount, which is what this is.
1195
- *
1196
- * Queued rather than dirty-checked, and that is deliberate: the value can be unchanged while the
1197
- * *options* are replaced, which drops the selection just as thoroughly. Re-asserting once per
1198
- * render pass is what keeps it right, and a select carries one binding, so it is one push.
1199
- */
1200
- if (this._select) {
1201
- this._committed = value;
1202
- /** Adoption never re-asserts a form value — the person may have changed it. See below. */
1203
- if (!(true && adopting))
1204
- (pendingSelects ??= []).push(this._element, value);
1205
- return index + this._slots;
1206
- }
1207
- if (value !== this._committed) {
1208
- if (kind === ATTR) {
1209
- /**
1210
- * A nullish value removes the attribute — except on the first commit of a template that
1211
- * never statically wrote it, where a fresh clone has nothing to remove. That skip used to
1212
- * be unconditional-removal instead, for the one case that genuinely needs it:
1213
- * `<b title="a" title=${null}>` parses keeping the first duplicate, so the binding —
1214
- * written last, and authoritative on the server too — must clear it. `_present` is that
1215
- * case, read off the parsed template once ever; without it the removal was a real DOM call
1216
- * per nullish binding per element on create — 1,000 no-ops in the 1,000-row benchmark.
1217
- */
1218
- if (value == null) {
1219
- if (this._present || this._committed !== UNSET)
1220
- this._element.removeAttribute(this._name);
1221
- }
1222
- else {
1223
- /**
1224
- * The same question `@verajs/renderer/spread` asks at its own sink, from the same home —
1225
- * the two are deliberately separate implementations (see spread's header on why), and a
1226
- * diagnostic that lived in only one of them would be the very defect this audit found.
1227
- * `setAttribute` performs the DOMString conversion itself; nothing is stringified here.
1228
- */
1229
- if (true ) {
1230
- const complaint = attributeValueComplaint(this._element.localName, this._name, value);
1231
- if (complaint !== null)
1232
- console.warn(`[vera] ${complaint}`);
1233
- }
1234
- this._element.setAttribute(this._name, value);
1235
- }
1236
- }
1237
- else if (kind === PROPERTY) {
1238
- const target = this._element;
1239
- const name = this._name;
1240
- /**
1241
- * **Adopting a form value: record it, do not write it.**
1242
- *
1243
- * `value`, `checked` and `selected` are exactly the properties `@verajs/ssr` mirrors into
1244
- * markup, so the element already holds what this binding says — *unless a person changed
1245
- * it*, which is the entire reason to server-render: the page is usable before the bundle
1246
- * lands, and the window between the two is where someone types their name, ticks a box or
1247
- * picks an option. Writing the binding then threw that away, silently, on every hydrating
1248
- * page. The part is told it already committed this value, so it stays live and the next
1249
- * genuine state change still applies.
1250
- *
1251
- * Only these three, and only while adopting. A property the server cannot express — any
1252
- * other `.prop` — is not in the DOM yet and must be written.
1253
- */
1254
- if (true && adopting && (name === 'value' || name === 'checked' || name === 'selected')) {
1255
- this._committed = value;
1256
- return index + this._slots;
1257
- }
1258
- /**
1259
- * No un-upgraded custom element can be behind this write: a dash-named property part is
1260
- * born `PROP_ADOPT` and only flips here once something receives the property, so the
1261
- * pre-upgrade window — the clobber, its repair for components, and the `whenDefined`
1262
- * detector for elements that never drain — lives entirely in `commitAdopt` above. History
1263
- * worth keeping: an earlier repair was tried HERE and removed as silently partial (it
1264
- * re-applied on `undefined`, so `item = someDefault` never looked clobbered); the record
1265
- * the drain re-applies unconditionally is what answered that objection.
1266
- */
1267
- target[name] = value;
1268
- }
1269
- else if (kind === BOOLEAN) {
1270
- /** Unconditional for the same reason: `<b hidden ?hidden=${false}>` must end up not hidden. */
1271
- this._element.toggleAttribute(this._name, !!value);
1272
- }
1273
- else if (kind === EVENT) {
1274
- /**
1275
- * A listener is the most deferred call a template makes — it is validated when a *user*
1276
- * clicks, which in development may be never. So it is checked where it is written, the same
1277
- * rule the setters took on: the stack at dispatch no longer contains the binding.
1278
- *
1279
- * `false` is deliberately allowed and silent. `@click=${enabled && onClick}` is the ordinary
1280
- * way to bind conditionally and produces exactly that, and it already behaves correctly —
1281
- * `handleEvent` finds nothing callable and does nothing. `true` is not produced by any
1282
- * idiom, so it is named along with strings, numbers and objects that cannot listen.
1283
- */
1284
- if (true && value != null && value !== false && typeof value !== 'function' &&
1285
- typeof value?.handleEvent !== 'function')
1286
- console.warn(`[vera] @${this._name} on <${this._element.localName}> was given ${typeof value === 'object' ? 'an object with no handleEvent method' : `a ${typeof value}`}, ` +
1287
- `which cannot listen — the event will do nothing.\n` +
1288
- `Pass a function, or an object with a handleEvent method. A missing handler is ` +
1289
- `\`undefined\` or \`false\`, both of which are fine; this is neither.`);
1290
- if (this._handler === null && value != null)
1291
- this._element.addEventListener(this._name, this);
1292
- this._handler = value ?? null;
1293
- }
1294
- else if (kind === PROP_ADOPT) {
1295
- const next = commitAdopt(this._element, this._name, value);
1296
- if (next !== 0)
1297
- this._kind = next;
1298
- }
1299
- else if (value != null) {
1300
- /**
1301
- * Element ref: `<input ${myRef} />`. A function is called with the element; an object gets
1302
- * the element assigned to `.value` — which makes core's own `ref()` double as an element
1303
- * ref, reactively. Runs once per distinct value, not once per render.
1304
- */
1305
- notifyOnRemoval = true;
1306
- if (typeof value === 'function')
1307
- applyRef(value, this._element);
1308
- else if (typeof value === 'object') {
1309
- /**
1310
- * A self-applying value: anything that knows what to do with an element applies itself.
1311
- * `@verajs/renderer/spread` is the first, and the whole protocol is this one property
1312
- * read — the implementation lives in that entry, so an app that never spreads pays for
1313
- * the check and nothing else. `_$…$` is exempt from property mangling, like `_$litType$`.
1314
- *
1315
- * Deliberately confined to the element position, which is rare. A protocol in the text,
1316
- * attribute or property commits would sit in the hot path every benchmark measures.
1317
- */
1318
- const self = value;
1319
- /** The part is passed as the ownership key: one element can carry several spreads. */
1320
- if (self._$apply$)
1321
- self._$apply$(this._element, this);
1322
- else
1323
- self.value = this._element;
1324
- }
1325
- // any other value type at element position is consumed and ignored
1326
- }
1327
- this._committed = value;
1328
- }
1329
- return index + this._slots;
1330
- }
1331
- }
1332
- /**
1333
- * `<select>.value` assignments held until the whole pass has committed — see the note in `_commit`.
1334
- * Flat pairs rather than tuples: one array, no per-entry allocation.
1335
- */
1336
- let pendingSelects = null;
1337
- const flushSelects = () => {
1338
- const queued = pendingSelects;
1339
- if (queued === null)
1340
- return;
1341
- /** Cleared first: an assignment can run a `change` handler that renders again. */
1342
- pendingSelects = null;
1343
- for (let i = 0; i < queued.length; i += 2)
1344
- queued[i].value = queued[i + 1];
1345
- };
1346
- const SCRATCH = doc.createDocumentFragment();
1347
- /**
1348
- * Marks a node as the render root's OWN output — see `ChildPart._insert`. Sigil-named so property
1349
- * mangling cannot rename it: this is read by `@verajs/renderer/slots`, across a bundle boundary,
1350
- * and a module-scoped Symbol would be minted twice on a CDN page (the `@verajs/styles` lesson).
1351
- *
1352
- * A fragment is stamped through to its children, because inserting one moves the children and the
1353
- * fragment itself never enters the document — the observer reports the children.
1354
- *
1355
- * **Defined rather than assigned, so it is NON-ENUMERABLE.** A plain `node._$own$ = true` is an own
1356
- * enumerable property: measured, it then shows up in `Object.keys(element)` — which is `[]` for
1357
- * every other DOM element — and in `for…in`. Invisibility to everything outside the framework is
1358
- * the whole reason this is a property and not a marker or an attribute, and an enumerable one is
1359
- * not invisible. The descriptor is shared, so this allocates nothing per node, and the path is
1360
- * gated on slots being wired, so no app that does not use them ever reaches it.
1361
- */
1362
- const OWN_DESCRIPTOR = { value: true, enumerable: false, configurable: true, writable: true };
1363
- /**
1364
- * The stamp is VALUED, and the value is the discriminator (`docs` in the slots module read it):
1365
- *
1366
- * `true` — the render root's own output: never slot content.
1367
- * a ChildPart — light content PLACED by that part from an outer template. The part identity
1368
- * is the ordering group: a grown row belongs after ITS part's other rows, and
1369
- * `<host>${a}${b}</host>` must not interleave a's refill into b's content —
1370
- * which is exactly what happens if the group is the render root, shared by both.
1371
- * absent — an imperative user mutation; the light region orders it by document position.
1372
- *
1373
- * One shared, mutated descriptor: `defineProperty` reads it synchronously, so this allocates
1374
- * nothing per node while keeping the property non-enumerable (see the invisibility note above).
1375
- */
1376
- const stampOwn = (node, value = true) => {
1377
- OWN_DESCRIPTOR.value = value;
1378
- if (node.nodeType === 11) {
1379
- for (let child = node.firstChild; child !== null; child = child.nextSibling)
1380
- Object.defineProperty(child, '_$own$', OWN_DESCRIPTOR);
1381
- return;
1382
- }
1383
- Object.defineProperty(node, '_$own$', OWN_DESCRIPTOR);
1384
- };
1385
- /** A row is either an element-mode instance or a markered part; both can hold appliers. */
1386
- const detachItem = (item) => {
1387
- item._instance?._teardown();
1388
- item._part?._detach();
1389
- };
1390
- class Instance {
1391
- _parts = [];
1392
- _fragment;
1393
- constructor(template) {
1394
- /**
1395
- * `importNode`, not `cloneNode` — the difference is custom-element upgrade, not the document.
1396
- * Template content lives in the inert template document, so `cloneNode` copies stay
1397
- * un-upgraded until insertion; a `.prop` committed in that window lands as an OWN property
1398
- * that permanently shadows a defined class's setter (the setter never fires — every
1399
- * accessor-based element, Lit's included, receives a dead value) and a bound value on a
1400
- * class-field element is clobbered by the field initializer at insert, silently, because the
1401
- * `whenDefined` detector below only watches definitions that arrive LATE. Hydration commits
1402
- * onto server-parsed, already-upgraded elements, so the two render paths disagreed about the
1403
- * same template. `importNode`'s cloning steps upgrade defined elements at clone time — in
1404
- * every engine and in jsdom — which makes the commit order match hydration and the platform.
1405
- * Undefined elements are untouched: nothing can upgrade them, and the pre-upgrade posture
1406
- * (own property, clobber on define, development warning) stands as pinned in
1407
- * `tests/pre-upgrade-property.test.mjs`. Measured cost of losing `cloneNode`: ~2–7% of the
1408
- * raw clone operation across the three engines — nanoseconds per instance.
1409
- */
1410
- this._fragment = doc.importNode(template._element.content, true);
1411
- const templateParts = template._parts;
1412
- /** Shared walker, ELEMENT | TEXT — child anchors are the primed text nodes themselves. */
1413
- instanceWalker.currentNode = this._fragment;
1414
- let nodeIndex = -1;
1415
- let node = null;
1416
- for (let i = 0; i < templateParts.length; i++) {
1417
- const templatePart = templateParts[i];
1418
- if (templatePart._type === IGNORED) {
1419
- this._parts.push(IGNORED_PART);
1420
- continue;
1421
- }
1422
- while (nodeIndex < templatePart._index) {
1423
- node = instanceWalker.nextNode();
1424
- nodeIndex++;
1425
- }
1426
- this._parts.push(templatePart._type === CHILD
1427
- ? new TextPart(node)
1428
- : new AttrPart(node, templatePart._name, templatePart._statics, templatePart._present));
1429
- }
1430
- /**
1431
- * Slot records mount OUTSIDE the parts array — one extra walk from the top, paid only by
1432
- * templates that HAVE slots, only inside a renderInto commit (null root — hydration's
1433
- * adoption path — stays inert), and only when the 'slot' insert answers. Taking over sets
1434
- * `notifyOnRemoval`: `_$park$` must rescue the USER'S nodes before a bulk `_clear` discards
1435
- * the DOM holding them on a branch-away. `_update` never sees any of this.
1436
- */
1437
- if (template._seam !== undefined && _slotRoot !== null) {
1438
- const slotRecords = template._slots;
1439
- /**
1440
- * RESOLVE every slot element to its clone in ONE walk, and mount them AFTER the first
1441
- * `_update` — see `_mountSlots`. Collect-then-act, because the seam MUTATES the fragment
1442
- * (it lifts each `<slot>` out and drops in anchors) and a walk that interleaved resolution
1443
- * with those mutations would read shifted indices and miss later slots.
1444
- */
1445
- instanceWalker.currentNode = this._fragment;
1446
- nodeIndex = -1;
1447
- const slotNodes = [];
1448
- for (let i = 0; i < slotRecords.length; i++) {
1449
- while (nodeIndex < slotRecords[i]) {
1450
- node = instanceWalker.nextNode();
1451
- nodeIndex++;
1452
- }
1453
- slotNodes.push(node);
1454
- }
1455
- this._pendingSlots = slotNodes;
1456
- }
1457
- /** Standalone rather than an `else` branch: `_slotless` is only ever set when there was no
1458
- * seam, so the condition stands alone — and a lone `if (true …)` folds away cleanly. */
1459
- if (true && template._slotless === true && _slotRoot !== null && _slotRoot.nodeType === 1) {
1460
- /**
1461
- * **A `<slot>` in a LIGHT render that nothing will distribute.** Both ways of arriving here
1462
- * are silent otherwise, and both leave the same confusing picture. Measured, for a host given
1463
- * `<b slot="a">MINE</b>`:
1464
- *
1465
- * <b slot="a">MINE</b><!----><div class="box"><slot name="a">FB</slot></div>
1466
- *
1467
- * — the content is not destroyed, it is stranded ahead of the render while the slot shows its
1468
- * fallback. The message says "any content the host is given" rather than asserting the host
1469
- * HAS some: a component that consumes its own children before rendering and also declares
1470
- * slots — `@verajs/ui`'s select is one — warns with nothing stray on the page, and a reader
1471
- * sent looking for markup that is not there concludes the diagnostic is confused.
1472
- *
1473
- * 1. `@verajs/renderer/slots` was never wired at all.
1474
- * 2. It was wired AFTER this template first rendered. Templates are interned per call site
1475
- * for the life of the page and resolve the seam once, at construction — so a component
1476
- * that rendered before the wiring keeps a slotless template forever, and every later use
1477
- * of it fails the same way. Measured: the same `draw()` distributes at a fresh call site
1478
- * and not at this one.
1479
- *
1480
- * A shadow root never reaches here: the platform slots there, which is why this is gated on
1481
- * an element root.
1482
- */
1483
- warnSlotless(_slotRoot);
1484
- }
1485
- }
1486
- /**
1487
- * One walk, both jobs: release the element refs in this instance and tell any child applier
1488
- * under it that it is going away.
1489
- *
1490
- * They were two walks over the same array — `_release` for refs, `_detach` for appliers — which
1491
- * is the same tree traversed twice for two answers that arrive at the same moment. Merged, the
1492
- * per-part cost is one `_kind` compare and one `_upgraded` read.
1493
- *
1494
- * Reached only when this instance's template holds a ref, or some applier somewhere declared
1495
- * teardown. An app with neither never runs it: this is the per-node work the bulk removal exists
1496
- * to skip, and the gate is what keeps it out of the path.
1497
- *
1498
- * Through `_upgraded`, not just `_parts`. A child position is instantiated as a `TextPart` and
1499
- * **upgrades** to a `ChildPart` the first time it takes an object — so the part holding a
1500
- * applier is almost never the one in this array, it is the one that array's entry points at.
1501
- * Walking `_parts` alone found nothing at all.
1502
- */
1503
- _teardown() {
1504
- const parts = this._parts;
1505
- for (let i = 0; i < parts.length; i++) {
1506
- const part = parts[i];
1507
- if (part._kind === REF)
1508
- part._release();
1509
- part._upgraded?._detach();
1510
- }
1511
- /** Taken-over slots park the USER'S nodes before this instance's DOM is discarded. */
1512
- this._slotStates?.forEach((state) => state._$park$?.());
1513
- }
1514
- _update(values) {
1515
- let valueIndex = 0;
1516
- const parts = this._parts;
1517
- for (let i = 0; i < parts.length; i++)
1518
- valueIndex = parts[i]._commit(values, valueIndex);
1519
- if (this._pendingSlots !== undefined)
1520
- this._mountSlots();
1521
- }
1522
- /**
1523
- * **Slots mount after the first `_update`, not during construction, because a `<slot>`'s own
1524
- * bindings are part of its meaning.** `<slot name=${section}>` has no name at all until its
1525
- * `AttrPart` has committed, and mounting first read the static markup and got `''` — the slot
1526
- * registered as a second DEFAULT slot, took the default content, and left the real default slot
1527
- * showing fallback. Committing first also means `@slotchange` and `&ref` are already attached to
1528
- * the element by the time anything is dispatched on it.
1529
- *
1530
- * Once per instance: the fields are cleared here and every later `_update` costs one compare.
1531
- */
1532
- _mountSlots() {
1533
- const slotNodes = this._pendingSlots;
1534
- this._pendingSlots = undefined;
1535
- /**
1536
- * `_slotRoot` still holds the container: it is set for the whole of one `renderInto` and every
1537
- * instance under it — nested templates included — is constructed and first-updated inside that
1538
- * same synchronous span, so this is the root the constructor saw.
1539
- */
1540
- const root = _slotRoot;
1541
- const seam = slotSeam();
1542
- if (seam === undefined || root === null)
1543
- return;
1544
- for (let i = 0; i < slotNodes.length; i++) {
1545
- const slot = slotNodes[i];
1546
- const state = seam(slot, root, slot.getAttribute('name') ?? '');
1547
- if (state != null) {
1548
- (this._slotStates ??= []).push(state);
1549
- notifyOnRemoval = true;
1550
- }
1551
- }
1552
- }
1553
- }
1554
- /** A single property read — this runs once per list item per render, so it must be minimal. */
1555
- const isTemplateResult = (value) => value.strings !== undefined;
1556
- /**
1557
- * The common case of a child expression is plain text, and the template primes every child slot
1558
- * with a text node — so the steady state is compare-and-assign on `.data`. This part carries only
1559
- * that, upgrading itself to a full ChildPart the first time it sees null, a template, or an array.
1560
- */
1561
- /**
1562
- * **A boolean in a child position renders the WORD, and almost nobody means that.**
1563
- *
1564
- * `${items.length > 0 && html`…`}` is the ordinary conditional idiom, and when the test is false
1565
- * the whole expression is `false` — which becomes the text `false` on the page. Nothing throws;
1566
- * the value is legitimate; only the intent is wrong. lit-html does the same and this renderer
1567
- * matches it deliberately (anything not nullish renders), so the BEHAVIOUR stays and the mistake
1568
- * is named where it happens instead of being found by looking at the page.
1569
- *
1570
- * `@verajs/jsx` compiles this case away — in JSX a boolean child becomes nothing, React's rule,
1571
- * because that is where React expectations live. **That is the one value semantic on which JSX and
1572
- * a hand-written template differ**, which makes this the warning that meets JSX-shaped code pasted
1573
- * into a template.
1574
- *
1575
- * Called from BOTH child sinks, because a text position is a `TextPart` until something upgrades
1576
- * it and a boolean never triggers that upgrade — putting the check in `ChildPart` alone left it
1577
- * silent for exactly the common case. One function, two call sites, per the standing rule that a
1578
- * deliberate duplication is a fix's second address.
1579
- *
1580
- * Both sinks gate this on the value CHANGING — not merely on reaching a commit — so an unchanged
1581
- * `false` is reported once and not once per render. `ChildPart` needed that stated explicitly: its
1582
- * dirty check sits below, and calling this above it spammed every pass.
1583
- */
1584
- const warnBooleanChild = (value) => {
1585
- if (typeof value !== 'boolean')
1586
- return;
1587
- console.warn(`[vera] renderer: a child position was given \`${value}\`, which renders as the word ` +
1588
- `"${value}" — the usual cause is \`\${cond && …}\` with a false \`cond\`.\n` +
1589
- `Write \`\${cond ? … : null}\`, or \`\${(cond && …) || null}\`; \`null\` and \`undefined\` are ` +
1590
- `the values that render nothing. If you meant to display the boolean, say so with ` +
1591
- `\`\${String(value)}\` and this goes quiet.`);
1592
- };
1593
- class TextPart {
1594
- _text;
1595
- _value = '';
1596
- _upgraded = null;
1597
- constructor(text) {
1598
- this._text = text;
1599
- }
1600
- _commit(values, index) {
1601
- const value = values[index];
1602
- if (this._upgraded !== null) {
1603
- this._upgraded._set(value);
1604
- return index + 1;
1605
- }
1606
- if (value == null || typeof value === 'object') {
1607
- /**
1608
- * Upgrade in place: marker comments come into existence only now, anchored around the text
1609
- * node, and the full part inherits the committed text state and delegates forever.
1610
- *
1611
- * BOTH markers are ours. Borrowing `this._text.nextSibling` as the end instead would hand
1612
- * this part a boundary owned by the NEXT part — and the next part removes that very node
1613
- * when it upgrades and clears its own text. The stale reference then makes `_clear()` walk
1614
- * past the end of the child list. Owning both anchors also makes `_end === null` mean
1615
- * exactly one thing: the root part, which really does own its container.
1616
- */
1617
- const start = comment();
1618
- const end = comment();
1619
- /**
1620
- * **Markers go where the part LIVES, which is not always where its text node is.** In a
1621
- * light host wired for slots, this text node was captured and distributed into the
1622
- * component's tree — planting markers beside it there put them inside the slot's range,
1623
- * the slot's next fill swept them into the holding fragment, and the part spent the rest
1624
- * of the page rendering into detached space (measured: `<host>${text}</host>` toggling
1625
- * through null showed FALLBACK forever). `_$home$` answers with the host's light-region
1626
- * sentinel for a captured node and null for everything else, so every app without light
1627
- * slots takes the second branch untouched.
1628
- */
1629
- const home = slotSeam()?._$home$?.(this._text) ?? null;
1630
- const parent = home !== null ? home.parentNode : this._text.parentNode;
1631
- if (home !== null) {
1632
- parent.insertBefore(start, home);
1633
- parent.insertBefore(end, home);
1634
- }
1635
- else {
1636
- parent.insertBefore(start, this._text);
1637
- parent.insertBefore(end, this._text.nextSibling);
1638
- }
1639
- const part = new ChildPart(start, end);
1640
- part._mode = TEXT;
1641
- part._text = this._text;
1642
- part._value = this._value;
1643
- this._upgraded = part;
1644
- part._set(value);
1645
- return index + 1;
1646
- }
1647
- if (value !== this._value) {
1648
- if (true )
1649
- warnBooleanChild(value);
1650
- this._value = value;
1651
- this._text.data = value;
1652
- }
1653
- return index + 1;
1654
- }
1655
- }
1656
- /**
1657
- * The registry this renderer reads `'value'` handlers from, handed over by {@link renderer}.
1658
- *
1659
- * Not imported. The renderer carries no registry of its own for the same reason the router does
1660
- * not: a production bundle inlines `@verajs/inserts`, so importing it would give this package one
1661
- * registry and core another, and an app would register into whichever it happened to import — the
1662
- * failure `connectInserts` used to repair.
1663
- */
1664
- let registry = null;
1665
- /**
1666
- * The ONE lookup for the `'slot'` insert. Three callers want the same thing in the same shape —
1667
- * template construction (are there slots to record?), the first render into a container (capture
1668
- * the host's children), and hydration's rescue (un-distribute before a mismatch discards) — and
1669
- * the seam carries its cross-bundle members as sigil-named keys, which every caller had to spell
1670
- * out again. One accessor, spelled once.
1671
- */
1672
- /**
1673
- * **Whether ANY app on this page wired light slots**, latched the first time the seam answers.
1674
- *
1675
- * The ownership stamp in `_insert`/`$c` exists only for `@verajs/renderer/slots` to read, and its
1676
- * guard has to be free for everyone else — `_slotRoot` is set for every `renderInto`, so without
1677
- * this an app with no slots at all would stamp every top-level node it renders, which for a list
1678
- * at the root is a property write per ROW. One boolean instead, false for the life of a page that
1679
- * never wires them.
1680
- */
1681
- let slotsWired = false;
1682
- const slotSeam = () => {
1683
- const seam = registry?.get('slot')?.[0];
1684
- if (seam !== undefined)
1685
- slotsWired = true;
1686
- return seam;
1687
- };
1688
- const noHandlers = [];
1689
- const valueHandlers = () => (registry ? (registry.get('value') ?? noHandlers) : noHandlers);
1690
- /**
1691
- * Kinds this package still ships. They read from a local list rather than the registry because the
1692
- * renderer cannot register into one it was merely handed — that needs `wire`, which it does not
1693
- * import. The list empties when they move to packages; until then a wired handler is checked first,
1694
- * so a module can pre-empt a built-in exactly as the priority order promises.
1695
- */
1696
- const builtIns = [];
1697
- /**
1698
- * Whether anything in this process has asked to be told when a subtree is removed — an element ref
1699
- * to release, or a child applier that declared `_$detach$`.
1700
- *
1701
- * **One flag for both, and it is process-wide.** Teardown cannot be discovered from the template the
1702
- * way a ref can — a ref is a `&` part the scan sees, while an applier arrives as a *value* and no
1703
- * template shape predicts it — so the coarser gate is the only one that serves both.
1704
- *
1705
- * The finer, per-template gate for refs was measured and dropped: it saved 34 B less than nothing,
1706
- * because the walk it avoided is not the expensive part. With one unrelated ref on the page, a
1707
- * 1 000-row clear walks 1 000 instances and measures 3.98 ms against 4.03 ms with no ref at all —
1708
- * the DOM removal dominates completely. What matters is that an app asking for neither walks
1709
- * **zero**, and that still holds.
1710
- */
1711
- let notifyOnRemoval = false;
1712
- /**
1713
- * The hydrate entry's way to raise the flag. Every CLIENT path that creates removal work sets
1714
- * `notifyOnRemoval` where the work is created (a ref committing, a slot mounting, an applier
1715
- * declaring `_$detach$`) — but hydration ADOPTS its seams through its own walk in `hydrate.ts`,
1716
- * a different module compiled into the same bundle, and a page whose only seams were adopted
1717
- * left the flag down. `_clear` then skipped `_detach` entirely: no `_teardown`, no `_$park$`,
1718
- * and the user's server-adopted slotted content was destroyed on the first branch-away — the
1719
- * exact content-loss class the seam's park exists to prevent, reintroduced one entry over.
1720
- */
1721
- const declareRemovalWork = () => {
1722
- notifyOnRemoval = true;
1723
- };
1724
-
1725
- const _applierSwaps = /* @__PURE__ */ new WeakMap();
1726
- /** What a ChildPart currently contains. */
1727
- const EMPTY = 0;
1728
- const TEXT = 1;
1729
- const TEMPLATE = 2;
1730
- const LIST = 3;
1731
- const NODE = 4;
1732
- let _profileHook = null;
1733
- class ChildPart {
1734
- _start;
1735
- /** Exclusive end of this part's range; null means "to the end of the parent". */
1736
- _end;
1737
- _mode = EMPTY;
1738
- _value;
1739
- _text = null;
1740
- _instance = null;
1741
- /** The committed template's strings identity — the same-template fast path in `_set`. */
1742
- _shape = null;
1743
- _items = null;
1744
- _keyedList = false;
1745
- /** Held instances by template identity; survives clears so state outlives interim content. */
1746
- _held = null;
1747
- /** Whatever the last `_$child$` at this part returned — its continuity across renders. */
1748
- _applierState = undefined;
1749
- /** Which applier that state belongs to, so two of them at one part cannot read each other's. */
1750
- _applier = undefined;
1751
- constructor(start, end) {
1752
- this._start = start;
1753
- this._end = end;
1754
- }
1755
- _commit(values, index) {
1756
- this._set(values[index]);
1757
- return index + 1;
1758
- }
1759
- /**
1760
- * **A component's own output is STAMPED, so the slot system cannot mistake it for content.**
1761
- *
1762
- * `@verajs/renderer/slots` captures a top-level element carrying a `slot` attribute as the
1763
- * host's content — which a component's own rendered root may legitimately be, when it renders
1764
- * something destined for ITS parent's slot. Measured: with slots wired,
1765
- * `renderInto(html\`<div slot="x">…</div>\`, element)` distributed the component's output into
1766
- * its own holding fragment and the component rendered NOTHING, on the first render, with no
1767
- * children involved and nothing thrown.
1768
- *
1769
- * The renderer is the one party that knows: it is inserting at the top level of the container
1770
- * it was asked to render into. `_slotRoot` is that container for the whole of one `renderInto`,
1771
- * so `parent === _slotRoot` is exactly "this is the component's own output" and distinguishes it
1772
- * from `<x-card>${value}</x-card>`, where the part's parent is the host but the render root is
1773
- * an ancestor — the user's light content, which must still be captured.
1774
- *
1775
- * Two comparisons on a path that is already touching the DOM, and the stamp is a PROPERTY:
1776
- * invisible to CSS, to serialization and to `children`, unlike any marker or attribute, and it
1777
- * rides on text nodes, which no attribute can. An app without slots wired writes it and nothing
1778
- * ever reads it.
1779
- */
1780
- /**
1781
- * **One property read decides all stamping, and root-part-ness decides the value.**
1782
- *
1783
- * `_$hosted$` is set on the host element itself by `@verajs/renderer/slots` at capture, so
1784
- * "does anything care about ownership here" is a single own-property read — no seam call, no
1785
- * registry lookup, and pages that are not captured hosts (every container in most apps) cost
1786
- * exactly that read and write nothing. The mark cannot go stale in the direction that matters:
1787
- * a part's first commit runs in a detached fragment before its host is captured, reads
1788
- * `undefined`, and stamps nothing — and that content is exactly what the initial capture walk
1789
- * lifts anyway. Every later commit sees the mark.
1790
- *
1791
- * The VALUE is structural, not temporal. `_end === null` is true of root parts alone (see
1792
- * `_clear`), and a root part's inserts are by definition the render's own output — a fact that
1793
- * stays true for an applier committing from a microtask hours after `renderInto` returned,
1794
- * where the earlier `parent === _slotRoot` test read null and left ASYNC output unstamped for
1795
- * the flipped capture rule to eat. Everything else inserting into a host is placing content
1796
- * INTO it from outside, stamped with the part — the ordering group.
1797
- */
1798
- _insert(node) {
1799
- const parent = this._start.parentNode;
1800
- if (slotsWired && parent._$hosted$ === true)
1801
- stampOwn(node, this._end === null ? true : this);
1802
- parent.insertBefore(node, this._end);
1803
- }
1804
- /**
1805
- * Tells every child applier under this part that it is going away.
1806
- *
1807
- * Reached only when some applier somewhere declared teardown — see `notifyOnRemoval` — because
1808
- * this is the per-node walk the bulk removal exists to skip. **Every** removal path calls it, not
1809
- * just `_clear`: a keyed row is dropped by moving its nodes to a scratch fragment and an index-mode
1810
- * list shrinks by removing nodes directly, so a version that only hooked `_clear` notified a
1811
- * applier when its container was replaced and stayed silent when its row was deleted — told
1812
- * sometimes, which is a worse contract than never.
1813
- */
1814
- _detach() {
1815
- if (this._applier !== undefined)
1816
- this._applier._$detach$?.(this._applierState);
1817
- this._instance?._teardown();
1818
- const items = this._items;
1819
- if (items != null)
1820
- for (let i = 0; i < items.length; i++)
1821
- detachItem(items[i]);
1822
- }
1823
- _clear() {
1824
- /**
1825
- * One gate, two jobs. A template that holds an element ref must release it; a subtree holding a
1826
- * applier that declared teardown must be told. Both are found by the same walk, and an app
1827
- * with neither reads two booleans and walks nothing.
1828
- */
1829
- if (notifyOnRemoval)
1830
- this._detach();
1831
- const parent = this._start.parentNode;
1832
- const end = this._end;
1833
- const items = this._items;
1834
- /**
1835
- * **Content that is no longer between the markers.** `@verajs/renderer/slots` distributes a
1836
- * light host's children by MOVING them into the component's tree, so a part rendering those
1837
- * children keeps its markers in the host while its content lives inside the component.
1838
- *
1839
- * Both branches below are wrong for that, and wrong in opposite directions. The walk finds
1840
- * the markers adjacent and removes nothing — the content stays on screen after being cleared
1841
- * (a template swap in a light host showed the OLD template forever). The whole-parent fast
1842
- * path is the dangerous one: it would `textContent = ''` the HOST, component render and all.
1843
- *
1844
- * Every mode knows its content by IDENTITY, which is parent-agnostic and split-proof: items
1845
- * through `$m`, TEXT through `_text`, NODE through `_value`, TEMPLATE through the top-level
1846
- * node array recorded at commit. The one shape that cannot be found this way is a
1847
- * DocumentFragment committed at NODE position (its children scatter and it keeps no record);
1848
- * that falls through to the walk, as before.
1849
- */
1850
- if (this._start.nextSibling === end && this._mode !== EMPTY) {
1851
- if (items !== null) {
1852
- for (const item of items)
1853
- if (item !== null)
1854
- this.$m(item, null, SCRATCH);
1855
- SCRATCH.textContent = '';
1856
- }
1857
- else if (this._mode === TEXT) {
1858
- this._text?.remove();
1859
- }
1860
- else if (this._mode === TEMPLATE) {
1861
- if (Array.isArray(this._value))
1862
- for (const node of this._value)
1863
- node.remove();
1864
- }
1865
- else if (this._mode === NODE && typeof this._value.remove === 'function') {
1866
- this._value.remove();
1867
- }
1868
- }
1869
- else /**
1870
- * When this part owns its parent's entire contents, one `textContent = ''` replaces removing
1871
- * every node individually. For a 1 000-row table body that is the difference between ~22 ms
1872
- * (lit-html's per-node teardown) and ~5 ms.
1873
- *
1874
- * A part owns the whole parent when nothing precedes its start AND nothing follows its end —
1875
- * `_end === null` (a root part, which runs to the end by definition) or `_end` is the last
1876
- * child. The second case is the common one and used to miss this path entirely: every list
1877
- * written as `<tbody>${rows}</tbody>` sits inside a template, and since 0.1.2 a nested part
1878
- * always owns an end marker, so `_end === null` alone never held for it.
1879
- *
1880
- * Re-appending both anchors in order restores the part's boundary exactly as it was.
1881
- */ if (this._start.previousSibling === null && (end === null || end.nextSibling === null)) {
1882
- parent.textContent = '';
1883
- parent.appendChild(this._start);
1884
- if (end !== null)
1885
- parent.appendChild(end);
1886
- }
1887
- else {
1888
- let node = this._start.nextSibling;
1889
- /**
1890
- * `node !== null` is a backstop, not an expected exit. Reaching the end of the child list
1891
- * without meeting `_end` means something detached this part's boundary; stopping leaves
1892
- * nodes behind, which beats throwing out of the middle of a render pass.
1893
- */
1894
- while (node !== null && node !== this._end) {
1895
- const next = node.nextSibling;
1896
- parent.removeChild(node);
1897
- node = next;
1898
- }
1899
- }
1900
- this._mode = EMPTY;
1901
- this._text = null;
1902
- this._instance = null;
1903
- this._items = null;
1904
- this._shape = null;
1905
- this._applierState = undefined;
1906
- this._applier = undefined;
1907
- }
1908
- /**
1909
- * How a child-position applier renders. Named to survive property mangling — `/^_[a-z]/` is the
1910
- * pattern, and `_$…$` does not match it — because this is the half of the protocol that third
1911
- * parties call.
1912
- */
1913
- _$commit$(value) {
1914
- /**
1915
- * The applier's own state survives its own rendering. Committing different content usually
1916
- * runs `_clear`, which drops the state so a part that was emptied by *anything else* cannot
1917
- * hand an applier continuity it no longer has — but an applier rendering its own next value
1918
- * has not gone away, and losing continuity there made `until()` fall back to its placeholder on
1919
- * the render after it resolved.
1920
- */
1921
- const applierState = this._applierState;
1922
- const applier = this._applier;
1923
- this._set(value);
1924
- this._applierState = applierState;
1925
- this._applier = applier;
1926
- }
1927
- _set(value) {
1928
- if (value == null) {
1929
- if (this._mode !== EMPTY)
1930
- this._clear();
1931
- return;
1932
- }
1933
- if (typeof value !== 'object') {
1934
- /**
1935
- * Gated on the value CHANGING, which is the same condition the commit below uses. Called
1936
- * before that check it fired on every render of an unchanged `false` — a channel that
1937
- * repeats is as useless as one that stays silent, and the comment on `warnBooleanChild`
1938
- * claimed this was already true. `_value` holds whatever was last committed here, so a part
1939
- * arriving from a template state differs and reports once.
1940
- */
1941
- if (true && this._value !== value)
1942
- warnBooleanChild(value);
1943
- if (this._mode === TEXT) {
1944
- if (this._value !== value) {
1945
- this._value = value;
1946
- this._text.data = value; // the DOM coerces numbers etc.
1947
- }
1948
- }
1949
- else {
1950
- if (this._mode !== EMPTY)
1951
- this._clear();
1952
- this._text = doc.createTextNode(value);
1953
- this._insert(this._text);
1954
- this._value = value;
1955
- this._mode = TEXT;
1956
- }
1957
- return;
1958
- }
1959
- const heldResult = value.$h;
1960
- if (heldResult !== undefined) {
1961
- this._commitHeld(heldResult);
1962
- return;
1963
- }
1964
- if (isTemplateResult(value)) {
1965
- /**
1966
- * Same-shape fast path on `strings` identity alone — no template-cache lookup. This is the
1967
- * hottest line in a keyed list update: for every row whose shape did not change (all of
1968
- * them, in practice), commit costs one identity compare before touching the values.
1969
- */
1970
- if (this._shape === value.strings) {
1971
- if (true && _profileHook)
1972
- ;
1973
- this._instance._update(value.values);
1974
- return;
1975
- }
1976
- /**
1977
- * Reaching here with a template already committed means the identity changed, so the
1978
- * subtree below is about to be destroyed and rebuilt rather than updated. That is what
1979
- * `?hidden=${…}` over a swapped subtree exists to avoid, and it is otherwise invisible.
1980
- */
1981
- if (true && _profileHook) ;
1982
- const template = getTemplate(value);
1983
- if (this._mode !== EMPTY)
1984
- this._clear();
1985
- const instance = new Instance(template);
1986
- instance._update(value.values);
1987
- /**
1988
- * The instance's top-level nodes, recorded while they are still in the fragment. `_value`
1989
- * is unused in TEMPLATE mode, and this is what lets `_clear` and `hold`'s parking find the
1990
- * content after `@verajs/renderer/slots` has moved it out of the marker range — per node,
1991
- * parent-agnostic, so even content split across two slots comes back. Costs one small array
1992
- * on a path that just built an Instance and cloned a template; same-shape updates never
1993
- * reach here.
1994
- */
1995
- this._value = [...instance._fragment.childNodes];
1996
- this._insert(instance._fragment);
1997
- this._instance = instance;
1998
- this._shape = value.strings;
1999
- this._mode = TEMPLATE;
2000
- return;
2001
- }
2002
- const handlers = valueHandlers();
2003
- for (let i = 0; i < handlers.length; i++)
2004
- if (handlers[i](this, value))
2005
- return;
2006
- for (let i = 0; i < builtIns.length; i++)
2007
- if (builtIns[i](this, value))
2008
- return;
2009
- /**
2010
- * **A child-position value that applies itself.** The same idea as `_$apply$` at element
2011
- * position — which is how `@verajs/renderer/spread` ships as a separate package the renderer
2012
- * knows nothing about — at the one other position worth extending.
2013
- *
2014
- * `_$child$(part, previous)` is handed the part and whatever it returned last time at this
2015
- * part, and calls `part._$commit$(value)` to render content. Keeping continuity in the return
2016
- * value rather than in an applier *instance* is what keeps this a protocol rather than a
2017
- * framework: there is no base class, no factory and no lifecycle to learn, and an applier is
2018
- * an object literal.
2019
- *
2020
- * Placed **after** the template check on purpose. A template is overwhelmingly the common
2021
- * object at a child position, and it returns above without ever reading this property — so the
2022
- * check costs the hot path nothing and only arrays, nodes and appliers pay for it. Measured:
2023
- * +22 B gzipped, and no runtime difference distinguishable from noise.
2024
- *
2025
- * There is deliberately no teardown hook. `_clear` bulk-removes DOM and, when the part owns its
2026
- * parent, does `parent.textContent = ''` — the thing that makes clearing a 1 000-row table ~5 ms
2027
- * against lit-html's ~22 ms. Calling teardown on a nested applier would mean walking the part
2028
- * tree on every removal, which is precisely the per-node work that fast path exists to skip. So
2029
- * an applier here can render, and cannot yet be told it has gone away.
2030
- */
2031
- const applyChild = value._$child$;
2032
- if (applyChild !== undefined) {
2033
- /** `previous` belongs to *this* applier; a different one at the same part starts fresh. */
2034
- const previous = this._applier === applyChild ? this._applierState : undefined;
2035
-
2036
- if (true && this._applier !== undefined && this._applier !== applyChild) {
2037
- const swaps = (_applierSwaps.get(this) ?? 0) + 1;
2038
- _applierSwaps.set(this, swaps);
2039
- if (swaps === 3) {
2040
- console.warn(`[vera] a child applier changed identity ${swaps} times at one part, so \`previous\` ` +
2041
- `is always undefined and it restarts every render.\n` +
2042
- `Hoist the applier — written as an object-literal method it is a new function per ` +
2043
- `call:\n\n` +
2044
- ` function applyThing(part, previous) { … } // once, at module scope\n` +
2045
- ` const thing = (x) => ({ _$child$: applyThing, x }); // state on the object\n`);
2046
- }
2047
- }
2048
- this._applier = applyChild;
2049
- if (applyChild._$detach$ !== undefined)
2050
- notifyOnRemoval = true;
2051
- this._applierState = applyChild.call(value, this, previous);
2052
- return;
2053
- }
2054
- if (value.nodeType !== undefined) {
2055
- /**
2056
- * A DOM node renders as itself — a canvas a charting library owns, a `<template>`'s content,
2057
- * an element built by hand. Placed after the template check and before the list check
2058
- * because `nodeType` is one property read and nothing else that reaches here has one.
2059
- */
2060
- if (this._mode !== NODE || this._value !== value) {
2061
- if (this._mode !== EMPTY)
2062
- this._clear();
2063
- this._insert(value);
2064
- this._value = value;
2065
- this._mode = NODE;
2066
- }
2067
- return;
2068
- }
2069
- // any other object: render as text
2070
- this._set(String(value));
2071
- }
2072
- /** Commits a template while stashing whatever it replaces — see the `hold()` export. */
2073
- _commitHeld(result) {
2074
- if (this._mode === TEMPLATE && this._shape === result.strings) {
2075
- this._instance._update(result.values);
2076
- return;
2077
- }
2078
- const held = (this._held ??= new Map());
2079
- if (this._mode === TEMPLATE) {
2080
- /** Park the live nodes back in their instance's own (empty) fragment. When the range is
2081
- * empty but content existed, slots relocated it — the recorded top-level nodes park it
2082
- * from wherever it lives, split slots and holding included. */
2083
- const fragment = this._instance._fragment;
2084
- if (this._start.nextSibling === this._end && Array.isArray(this._value)) {
2085
- for (const node of this._value)
2086
- fragment.appendChild(node);
2087
- }
2088
- else {
2089
- let node = this._start.nextSibling;
2090
- while (node !== this._end) {
2091
- const next = node.nextSibling;
2092
- fragment.appendChild(node);
2093
- node = next;
2094
- }
2095
- }
2096
- held.set(this._shape, this._instance);
2097
- }
2098
- else if (this._mode !== EMPTY) {
2099
- this._clear();
2100
- }
2101
- const instance = held.get(result.strings) ?? new Instance(getTemplate(result));
2102
- instance._update(result.values);
2103
- this._value = [...instance._fragment.childNodes];
2104
- this._insert(instance._fragment);
2105
- this._instance = instance;
2106
- this._shape = result.strings;
2107
- this._mode = TEMPLATE;
2108
- }
2109
- /**
2110
- * Creates one list item. A single-root template instance becomes an element-mode item with no
2111
- * markers at all; anything else gets its own start/end marker pair so moves can never dangle.
2112
- */
2113
- $c(value, parent, ref) {
2114
- /** Rows reach the DOM here rather than through `_insert`; same one-read gate, same
2115
- * structural value — a root list's rows are the render's own output, any other part's rows
2116
- * are content it places into the host, stamped with the part as the ordering group. */
2117
- const stamp = slotsWired && parent._$hosted$ === true
2118
- ? this._end === null
2119
- ? true
2120
- : this
2121
- : null;
2122
- if (value !== null && typeof value === 'object' && value.strings !== undefined) {
2123
- const result = value;
2124
- const template = getTemplate(result);
2125
- const instance = new Instance(template);
2126
- instance._update(result.values);
2127
- const rootNode = instance._fragment.firstChild;
2128
- if (rootNode !== null && rootNode.nodeType === 1 && rootNode.nextSibling === null) {
2129
- if (stamp !== null)
2130
- stampOwn(rootNode, stamp);
2131
- parent.insertBefore(rootNode, ref);
2132
- return {
2133
- $k: result.key,
2134
- _element: rootNode,
2135
- _instance: instance,
2136
- _shape: result.strings,
2137
- _part: null,
2138
- };
2139
- }
2140
- /** Multi-root template: markered part, content already instantiated. */
2141
- const part = createMarkeredPart(parent, ref);
2142
- part._instance = instance;
2143
- part._shape = result.strings;
2144
- part._mode = TEMPLATE;
2145
- part._value = [...instance._fragment.childNodes];
2146
- if (stamp !== null)
2147
- stampOwn(instance._fragment, stamp);
2148
- part._start.parentNode.insertBefore(instance._fragment, part._end);
2149
- return { $k: result.key, _element: null, _instance: null, _shape: null, _part: part };
2150
- }
2151
- const part = createMarkeredPart(parent, ref);
2152
- part._set(value);
2153
- return { $k: value?.key, _element: null, _instance: null, _shape: null, _part: part };
2154
- }
2155
- /** Commits a new value into an existing item, demoting element mode if the shape changed. */
2156
- $u(item, value) {
2157
- if (item._element !== null) {
2158
- if (value !== null && typeof value === 'object' && value.strings === item._shape) {
2159
- item._instance._update(value.values);
2160
- return;
2161
- }
2162
- /** Shape changed: swap the bare element for a markered part in its place. */
2163
- const part = createMarkeredPart(item._element.parentNode, item._element);
2164
- item._element.remove();
2165
- item._element = null;
2166
- item._instance = null;
2167
- item._shape = null;
2168
- (item._part = part)._set(value);
2169
- return;
2170
- }
2171
- item._part._set(value);
2172
- }
2173
- /** The item's first node — its move/removal handle and the insertion reference before it. */
2174
- $f(item) {
2175
- return item._element ?? item._part._start;
2176
- }
2177
- /**
2178
- * Moving and removing an item read `_element` and `_part`, which are mangled — so they stay here
2179
- * rather than travelling with the algorithm that calls them. `$m` and `$d` are the price: two
2180
- * cold methods, exempt from mangling, two characters each.
2181
- */
2182
- $m(item, ref, parent = this._start.parentNode) {
2183
- /**
2184
- * **Already where it is going.** A reorder asks for many positions that are already correct,
2185
- * and re-inserting a node that is in place is not free: it detaches and re-attaches, which
2186
- * blurs focus, restarts a CSS transition and wakes every MutationObserver watching. The
2187
- * relocated path below leans on this — it re-places every item rather than computing which
2188
- * ones moved — but the ordinary two-ended diff gets the same saving.
2189
- *
2190
- * The item's LAST node is the one whose `nextSibling` decides this, and reading `_element` /
2191
- * `_part._end` is why the check lives here rather than travelling with the algorithm.
2192
- */
2193
- const last = item._element ?? item._part._end;
2194
- if (last.nextSibling === ref && last.parentNode === parent)
2195
- return;
2196
- if (item._element !== null) {
2197
- parent.insertBefore(item._element, ref);
2198
- return;
2199
- }
2200
- let node = item._part._start;
2201
- const stop = item._part._end.nextSibling;
2202
- while (node !== stop) {
2203
- const next = node.nextSibling;
2204
- parent.insertBefore(node, ref);
2205
- node = next;
2206
- }
2207
- }
2208
- /** Removal is a move into a scratch fragment that is immediately emptied. */
2209
- $d(item) {
2210
- if (notifyOnRemoval)
2211
- detachItem(item);
2212
- this.$m(item, null, SCRATCH);
2213
- SCRATCH.textContent = '';
2214
- }
2215
- _commitList(newValues) {
2216
- if (this._mode !== LIST) {
2217
- if (this._mode !== EMPTY)
2218
- this._clear();
2219
- this._items = [];
2220
- this._keyedList = false;
2221
- this._mode = LIST;
2222
- }
2223
- const count = newValues.length;
2224
- if (count === 0) {
2225
- if (this._items.length) {
2226
- this._clear();
2227
- this._items = [];
2228
- this._mode = LIST;
2229
- }
2230
- return;
2231
- }
2232
- const isKeyed = newValues[0] != null && newValues[0].$r !== undefined;
2233
- if (isKeyed !== this._keyedList && this._items.length) {
2234
- this._clear();
2235
- this._items = [];
2236
- this._mode = LIST;
2237
- }
2238
- this._keyedList = isKeyed;
2239
- const items = this._items;
2240
- const parent = this._start.parentNode;
2241
- if (items.length === 0) {
2242
- /** Initial fill builds off-document and lands in one insert. */
2243
- const fragment = doc.createDocumentFragment();
2244
- for (let i = 0; i < count; i++)
2245
- items.push(this.$c(newValues[i], fragment, null));
2246
- this._insert(fragment);
2247
- return;
2248
- }
2249
- if (!isKeyed) {
2250
- // index mode: update in place, grow at the end, shrink from the end
2251
- const shared = items.length < count ? items.length : count;
2252
- for (let i = 0; i < shared; i++)
2253
- this.$u(items[i], newValues[i]);
2254
- if (count > items.length) {
2255
- const fragment = doc.createDocumentFragment();
2256
- for (let i = items.length; i < count; i++)
2257
- items.push(this.$c(newValues[i], fragment, null));
2258
- this._insert(fragment);
2259
- }
2260
- else if (count < items.length) {
2261
- if (notifyOnRemoval)
2262
- for (let i = count; i < items.length; i++)
2263
- detachItem(items[i]);
2264
- /**
2265
- * **Removed through the items, not by walking the range.** The walk this replaced ran from
2266
- * the first doomed item to the last one's end and called `parent.removeChild` on each node,
2267
- * which assumes every one of them is still a child of `parent`. `@verajs/renderer/slots`
2268
- * moves a light host's children into the component's tree, and the walk then threw
2269
- * `NotFoundError` out of the middle of a render — a plain `<x-card>${rows}</x-card>` losing
2270
- * one row was enough, with no keyed list anywhere in it.
2271
- *
2272
- * `$m` into the scratch fragment is indifferent to where a node currently lives, and the
2273
- * batch is dropped by one clear at the end, so the contiguous-run saving the walk was for
2274
- * is kept.
2275
- */
2276
- for (let i = count; i < items.length; i++)
2277
- this.$m(items[i], null, SCRATCH);
2278
- SCRATCH.textContent = '';
2279
- items.length = count;
2280
- }
2281
- return;
2282
- }
2283
- /**
2284
- * Keyed reconciliation is not here. It lives in `@verajs/renderer/keyed`, and it arrives on
2285
- * the values themselves — `keyed()` stamps each result with the strategy that understands it,
2286
- * so importing the marker is what loads the algorithm. Nothing registers, nothing is wired, and
2287
- * two strategies cannot disagree about a list because the list names its own.
2288
- *
2289
- * The protocol is three cold members (`$c`, `$u`, `$f`) plus a returned array. Everything a
2290
- * strategy would otherwise have to reach for — the mode switch, the empty case, the initial
2291
- * fill — is already done above and passed in.
2292
- */
2293
- this._items = newValues[0].$r(this, newValues, items, parent, this._end);
2294
- }
2295
- }
2296
- const rootParts = new WeakMap();
2297
- /**
2298
- * Writes a template result into a container. The renderer's imperative draw: no reactivity, no
2299
- * lifecycle, no knowledge of components. Slots into Vera via `wire([renderer])`; core's built-in
2300
- * `html` tag already produces the accepted shape, so no `setHtml` call is required — though
2301
- * lit-html's `html` also works, its results being structurally identical.
2302
- *
2303
- * **It owns its own range and nothing else.** The first call appends a marker and anchors a root
2304
- * part there; later calls with the same container reuse that part and walk only the value slots, so
2305
- * nodes are updated in place rather than rebuilt. Content that was already in the container stays.
2306
- *
2307
- * **Named for the relationship, not the act.** It was `render` until 0.2.0, which collided with
2308
- * core's `render` — a different function, with a different arity, that declares a *reactive*
2309
- * template and commits a component's setup. Both were public and both were documented, so a reader
2310
- * who knew one misread the other. `renderElement` and `renderDom` were considered and rejected: this
2311
- * renders *into* a container, and the container is a `Node` — a shadow root and a fragment are both
2312
- * valid, so "element" would be a lie in the type. Argument order is lit-html's on purpose.
2313
- *
2314
- * HYDRATION lives in `@verajs/renderer/hydrate` — a drop-in superset entry whose `renderInto` adopts
2315
- * existing server-rendered children on first render. SSR apps import from there instead of here;
2316
- * this entry carries zero hydration code.
2317
- */
2318
- const renderInto$1 = (result, container) => {
2319
- /**
2320
- * The container is the argument people forget, and forgetting it failed with
2321
- * `Cannot read properties of undefined (reading 'appendChild')` — a message about the internals of
2322
- * a function the caller never named. Everything after this line assumes a node.
2323
- */
2324
- if (true && (!container || typeof container.appendChild !== 'function'))
2325
- throw new TypeError(`renderInto: expected a container node as the second argument and received ${String(container)}. ` +
2326
- `It renders *into* something — \`renderInto(html\`…\`, document.body)\`.`);
2327
- if (true && _profileHook)
2328
- ;
2329
- let part = rootParts.get(container);
2330
- if (part === undefined) {
2331
- /**
2332
- * FIRST render into this container. If it is a light element host and a 'slot' insert is
2333
- * wired, capture its children NOW — so slot content provided before its (possibly
2334
- * conditional) `<slot>` mounts is held rather than left visible in the host, matching native
2335
- * "unassigned light children do not render". Once per container lifetime; shadow roots
2336
- * (nodeType 11) and fragments are excluded.
2337
- */
2338
- /**
2339
- * **The marker goes in FIRST, and capture is handed it as the light region's boundary.**
2340
- *
2341
- * This part's start marker already delimits where the render's output begins, so the boundary
2342
- * slots needs is a node the renderer was creating anyway — the sentinel it used to append for
2343
- * itself landed immediately before this one, two adjacent comments doing the same job. Passing
2344
- * it removes one comment from every light host and keeps the two in step by construction: they
2345
- * cannot drift apart if they are the same node.
2346
- *
2347
- * Appending before capture is safe and necessary. Safe because a comment is never a slottable,
2348
- * so the children walk steps over it; necessary because capture LIFTS the host's children, and
2349
- * a marker appended afterwards would land in the same place either way — this way slots has it.
2350
- */
2351
- const marker = comment();
2352
- container.appendChild(marker);
2353
- if (container.nodeType === 1)
2354
- slotSeam()?._$capture$?.(container, marker);
2355
- rootParts.set(container, (part = new ChildPart(marker, null)));
2356
- }
2357
- /**
2358
- * **The flush is in a `finally`, and that is not tidiness.** A render that throws after a
2359
- * `<select>.value` has been queued but before the flush left the queue holding the element — which
2360
- * retains it in module state, and, worse, hands the stranded value to the *next* `renderInto` call.
2361
- * An unrelated component's render then silently changed a select it has nothing to do with.
2362
- * Measured: a failed update left the value to be applied by the following render.
2363
- *
2364
- * Flushing on the way out applies it with its own pass, where it belongs, and leaves nothing
2365
- * behind either way. The error still propagates.
2366
- */
2367
- _slotRoot = container;
2368
- try {
2369
- part._set(result);
2370
- }
2371
- finally {
2372
- _slotRoot = null;
2373
- flushSelects();
2374
- }
2375
- if (true && _profileHook)
2376
- ;
2377
- };
2378
- /**
2379
- * Lists, as a registered kind rather than a branch — the built-in going through the same door a
2380
- * package will. Moving it to `@verajs/renderer/lists` is step 5; nothing else has to change when
2381
- * it does, which is what this shape is for.
2382
- */
2383
- builtIns.push((part, value) => {
2384
- if (Array.isArray(value)) {
2385
- part._commitList(value);
2386
- return true;
2387
- }
2388
- if (value !== null && typeof value[Symbol.iterator] === 'function') {
2389
- part._commitList([...value]);
2390
- return true;
2391
- }
2392
- return false;
2393
- });
2394
- /**
2395
- * Everything this renderer needs, in one entry: `wire([renderer])`.
2396
- *
2397
- * It registers on the `'render'` chain *and* takes the registry, because a package that both
2398
- * provides a capability and reads one should not cost an app two lines. This replaced
2399
- * `setRenderer`, which existed only because there was no general way to say "this app has a
2400
- * renderer" — and which resolved the shadow root at registration, so a renderer wired any other
2401
- * way silently rendered into the light DOM. That resolution lives in core's dispatch now.
2402
- */
2403
- /**
2404
- * A `true `-only hint for `wire`, so the module and the raw function beside it can share a package
2405
- * without wiring the wrong one being silent.
2406
- *
2407
- * A bare function has no `on`, so `wire` reads it as a connector and hands it the registry. Nothing
2408
- * registers, nothing throws, and the page renders nothing. The marker lets `wire` name the export
2409
- * that was meant. This mattered most when the function was called `render` and the mistake was two
2410
- * characters wide; `renderInto` is harder to confuse, and the guard costs nothing in production.
2411
- *
2412
- * `$module` is deliberately generic — any package exporting a raw function next to a module of a
2413
- * similar name can set it. Production carries neither the property nor the check that reads it.
2414
- */
2415
- if (true )
2416
- renderInto$1.$module = 'renderer';
2417
- const renderer$1 = {
2418
- name: '@verajs/renderer',
2419
- on: 'render',
2420
- fn: renderInto$1,
2421
- priority: 50,
2422
- /**
2423
- * Typed against the registry `wire` actually hands over, not a narrower shape that happens to
2424
- * describe the one lookup this makes. A structural `{ get(name: 'value'): … }` is **not**
2425
- * assignable from `Inserts`, so `wire([renderer])` failed to compile in a consumer's project while
2426
- * this repo's own typecheck — which reads sources, not the shipped `.d.ts` — saw nothing.
2427
- */
2428
- connect: (given) => {
2429
- registry = given;
2430
- },
2431
- };
2432
-
2433
- /**
2434
- * @verajs/renderer/hydrate — markerless adoption of server-rendered DOM.
2435
- *
2436
- * Importing this module (once, anywhere) arms hydration: the renderer's first render into a
2437
- * container that already has children adopts them as server output of the same template. Without
2438
- * this import the renderer never carries adoption code — non-SSR apps pay nothing.
2439
- *
2440
- * The server serializer (@verajs/ssr) emits the SAME static strings the renderer parses into
2441
- * its canonical template, so server DOM and canonical fragment diverge only at value slots — and
2442
- * at adoption time the values are known. Adoption walks both trees in lockstep: statics must
2443
- * match byte-for-byte (else bail), and at each slot the live text is split so the renderer's own
2444
- * anchors (primed texts, marker comments) are installed into the adopted DOM. Server HTML stays
2445
- * free of framework comments; the client repairs its anchors in. Any mismatch clears the
2446
- * container (preserving `<style data-vm-sheet="styles">` tags) and the caller renders fresh — correctness
2447
- * never depends on the server markup.
2448
- *
2449
- * This entry re-exports the public API, so a CDN importmap can point `@verajs/renderer` at the
2450
- * hydrate bundle and nothing else changes.
2451
- */
2452
- /** Internal bail signal — never escapes `tryAdopt`. */
2453
- const MISMATCH = {};
2454
- /**
2455
- * Why the last adoption gave up, for the development warning below. Written at every `throw
2456
- * MISMATCH` inside an `if (true )`, so a production bundle carries neither the strings nor the
2457
- * assignments — the branches fold away with `true ` and the helper goes with them.
2458
- */
2459
- let why = '';
2460
- /** A live node as a person would name it, for that message. */
2461
- const describe = (node) => node === null
2462
- ? 'nothing'
2463
- : node.nodeType === 1
2464
- ? `<${node.localName}>`
2465
- : node.nodeType === 3
2466
- ? `the text ${JSON.stringify(node.data.slice(0, 30))}`
2467
- : node.nodeType === 8
2468
- ? 'a comment'
2469
- : `a ${node.nodeName} node`;
2470
- /** Splits mid-text cursors onto a node boundary and returns the node now at the cursor. */
2471
- const cursorSplit = (cursor) => {
2472
- if (cursor.offset > 0) {
2473
- cursor.node = cursor.node.splitText(cursor.offset);
2474
- cursor.offset = 0;
2475
- }
2476
- return cursor.node;
2477
- };
2478
- /**
2479
- * **A comment carries no rendered content, so hydration neither matches nor requires one.**
2480
- *
2481
- * `instanceWalker` is `ELEMENT | TEXT`, and the part indices in `_parts` are numbered by that same
2482
- * walker — so a comment in a template's statics is structurally invisible to this walk, and cannot
2483
- * be made visible without renumbering every part the client renderer relies on. The live DOM,
2484
- * however, still has it: `html`<p>a<!-- note -->b</p>`` adopts as text/comment/text where the walk
2485
- * wanted one run of text, and `<p>lead<!-- tail --></p>` leaves a child the walk never asked for.
2486
- * Both read as a disagreement, so **every template containing an HTML comment lost hydration** —
2487
- * the server's markup discarded and re-rendered, for markup the client had itself produced. Nothing
2488
- * failed, because the page is correct either way; that is what the fallback is for, and why this
2489
- * went unnoticed. What it cost was the first paint the server render was paid for.
2490
- *
2491
- * Stepping over them is sound rather than merely convenient: the invisibility is symmetric, so a
2492
- * comment can differ in either direction and neither direction can change what a reader sees. This
2493
- * is only safe because hydration is markerless — the adopted markup carries no framework comments,
2494
- * so there is nothing here whose position is load-bearing.
2495
- *
2496
- * Not folded into `cursorSplit`, which also answers "where do I insert?" — moving an insertion point
2497
- * past a comment would put a slot's content on the wrong side of it.
2498
- */
2499
- const passComments = (cursor) => {
2500
- while (cursor.offset === 0 && cursor.node !== null && cursor.node.nodeType === 8) {
2501
- cursor.node = cursor.node.nextSibling;
2502
- }
2503
- };
2504
- /** Consumes exactly `text` from the live cursor; anything else is a mismatch. */
2505
- const expectText = (cursor, text) => {
2506
- let need = text;
2507
- while (need.length > 0) {
2508
- passComments(cursor);
2509
- const node = cursor.node;
2510
- if (node === null || node.nodeType !== 3) {
2511
- if (true )
2512
- why = `expected the text ${JSON.stringify(text)} and found ${describe(node)}`;
2513
- throw MISMATCH;
2514
- }
2515
- const data = node.data;
2516
- const available = data.length - cursor.offset;
2517
- if (available === 0) {
2518
- cursor.node = node.nextSibling;
2519
- cursor.offset = 0;
2520
- continue;
2521
- }
2522
- const take = available < need.length ? available : need.length;
2523
- if (data.slice(cursor.offset, cursor.offset + take) !== need.slice(0, take)) {
2524
- if (true )
2525
- why = `expected the text ${JSON.stringify(need.slice(0, take))} and found ${JSON.stringify(data.slice(cursor.offset, cursor.offset + take))}`;
2526
- throw MISMATCH;
2527
- }
2528
- need = need.slice(take);
2529
- cursor.offset += take;
2530
- if (cursor.offset === data.length) {
2531
- cursor.node = node.nextSibling;
2532
- cursor.offset = 0;
2533
- }
2534
- }
2535
- };
2536
- /** Claims the value's rendered text as a standalone node (splitting as needed) and returns it. */
2537
- const claimValueText = (cursor, text) => {
2538
- const at = cursorSplit(cursor);
2539
- if (text === '') {
2540
- /** Nothing was rendered — install a fresh primed anchor at the cursor. */
2541
- const primed = doc.createTextNode('');
2542
- cursor.parent.insertBefore(primed, at);
2543
- return primed;
2544
- }
2545
- if (at === null || at.nodeType !== 3) {
2546
- if (true )
2547
- why = `expected a text node holding an interpolated value and found ${describe(at)}`;
2548
- throw MISMATCH;
2549
- }
2550
- const node = at;
2551
- if (node.data.length > text.length)
2552
- node.splitText(text.length);
2553
- if (node.data !== text) {
2554
- if (true )
2555
- why = `an interpolated value reads ${JSON.stringify(text)} here and the markup says ${JSON.stringify(node.data)}`;
2556
- throw MISMATCH;
2557
- }
2558
- cursor.node = node.nextSibling;
2559
- cursor.offset = 0;
2560
- return node;
2561
- };
2562
- /** Per-template canonical node list (ELEMENT | TEXT order), cached — adoption of a 100-row list
2563
- * hits the same template 100 times. */
2564
- const canonicalCache = new WeakMap();
2565
- const canonicalNodes = (template) => {
2566
- let nodes = canonicalCache.get(template);
2567
- if (nodes === undefined) {
2568
- nodes = [];
2569
- instanceWalker.currentNode = template._element.content;
2570
- let node;
2571
- while ((node = instanceWalker.nextNode()) !== null)
2572
- nodes.push(node);
2573
- canonicalCache.set(template, nodes);
2574
- }
2575
- return nodes;
2576
- };
2577
- /** The light host being hydrated — every `<slot>` in the render projects it, set once in
2578
- * `tryAdopt` (the render container), null when no slot handler is wired. */
2579
- let _adoptHost = null;
2580
- /** Whether the default slot's assignment has been claimed (the host count is for the first one). */
2581
- let _defaultTaken = false;
2582
- /**
2583
- * Every slot binding this adoption attempt created. If the attempt BAILS, each is parked — which
2584
- * returns the user's nodes to holding and unregisters the binding. Without it the abandoned
2585
- * bindings stayed registered, so the clean render's own bindings ranked as later duplicates and
2586
- * showed fallback while the user's content sat in the discarded tree: a hydration mismatch
2587
- * silently DESTROYED slotted content, breaking this entry's promise that correctness never
2588
- * depends on the server markup (measured).
2589
- */
2590
- let _adoptedSlots = [];
2591
- /** How many values a template part consumes — for skipping the unrendered parts inside an
2592
- * assigned slot's fallback subtree. */
2593
- const partValueCount = (part) => part._type === 1 ? (part._statics.length - 1) : 1;
2594
- /**
2595
- * Account for (skip) the parts inside a canonical subtree whose DOM the server did NOT render —
2596
- * an assigned slot's fallback. Advances the walk indices and value cursor without touching DOM,
2597
- * so the parts AFTER the slot still line up. Walks the node's CHILDREN (the fallback), in the
2598
- * same ELEMENT|TEXT order the walker numbers by.
2599
- */
2600
- const accountSubtree = (node, state) => {
2601
- const parts = state._template._parts;
2602
- for (let child = node.firstChild; child !== null; child = child.nextSibling) {
2603
- if (child.nodeType !== 1 && child.nodeType !== 3)
2604
- continue;
2605
- state._nodeIndex++;
2606
- while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2607
- state._valueIndex += partValueCount(parts[state._partIndex]);
2608
- state._partIndex++;
2609
- }
2610
- if (child.nodeType === 1)
2611
- accountSubtree(child, state);
2612
- }
2613
- };
2614
- /**
2615
- * Reconcile a canonical `<slot>` against server-distributed DOM. Named slots take the consecutive
2616
- * cursor nodes carrying `slot="name"`; the default slot takes the host-count nodes
2617
- * (`data-vm-slotted="N"`). Found nodes are wrapped in place as a live binding (identity/state preserved);
2618
- * an unassigned slot adopts its server-rendered fallback children normally. The slots module's
2619
- * `_$adopt$` (off the template's own seam fn) does the registration.
2620
- */
2621
- const adoptSlotElement = (canonicalSlot, cursor, state) => {
2622
- const seamAdopt = state._template._seam._$adopt$;
2623
- /**
2624
- * **The slot's OWN bindings, committed onto a per-instance element.** The server unwrapped the
2625
- * `<slot>`, so there is no live element to adopt against — but the template's parts for it are
2626
- * still in the parts array, and skipping them left every value after the slot reading the wrong
2627
- * one. In practice that meant adoption failed and the whole container fell back to a client
2628
- * render: any component whose slot carried `@slotchange`, `&ref` or `name=${…}` could not be
2629
- * server-rendered at all.
2630
- *
2631
- * A shallow clone is the target rather than the canonical node, which is shared by every
2632
- * instance of the template — committing onto that would attach one instance's listeners to all
2633
- * of them. The clone then IS this instance's slot element, exactly as the clone in a client
2634
- * render is, so `@slotchange` and `&ref` mean the same thing in both.
2635
- */
2636
- const ghost = canonicalSlot.cloneNode(false);
2637
- const parts = state._template._parts;
2638
- while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2639
- const templatePart = parts[state._partIndex++];
2640
- const attrPart = new AttrPart(ghost, templatePart._name, templatePart._statics, templatePart._present);
2641
- state._out.push(attrPart);
2642
- state._valueIndex = attrPart._commit(state._values, state._valueIndex, true);
2643
- drainIgnored(state);
2644
- }
2645
- /** After the commit, so `<slot name=${…}>` is read as the name it actually has. */
2646
- const name = ghost.getAttribute('name') ?? '';
2647
- passComments(cursor);
2648
- const parent = cursor.parent;
2649
- /** Collect the server nodes assigned to this slot. */
2650
- const assigned = [];
2651
- if (name !== '') {
2652
- let node = cursorSplit(cursor);
2653
- while (node !== null && node.nodeType === 1 && node.getAttribute('slot') === name) {
2654
- assigned.push(node);
2655
- cursor.node = node.nextSibling;
2656
- node = cursorSplit(cursor);
2657
- }
2658
- }
2659
- else if (!_defaultTaken) {
2660
- /**
2661
- * `"offset,count"` on the slot's own parent — see `SLOTTED_ATTR`. Only the count is needed
2662
- * here (the walk is already standing in the right place); the offset is what lets a FAILED
2663
- * adoption find these same nodes again instead of destroying them.
2664
- *
2665
- * `_defaultTaken` still guards: two default slots sharing a parent would otherwise both read
2666
- * the one mark, and by native semantics only the first receives anything.
2667
- */
2668
- const mark = parent.getAttribute?.('data-vm-slotted');
2669
- const count = mark === undefined || mark === null ? 0 : Number(mark.slice(mark.indexOf(',') + 1));
2670
- if (count > 0) {
2671
- _defaultTaken = true;
2672
- /**
2673
- * **The mark does not survive the page it delivered.** It describes what the SERVER emitted
2674
- * and is meaningless the moment those nodes are adopted, so leaving it behind would put a
2675
- * framework marker in the user's live DOM permanently — queryable, stylable, and stale.
2676
- * `data-vm-select` sets the precedent: it is stripped before the markup even ships, with
2677
- * a test asserting the mark must not survive.
2678
- */
2679
- parent.removeAttribute('data-vm-slotted');
2680
- for (let i = 0; i < count; i++) {
2681
- const node = cursorSplit(cursor);
2682
- if (node === null)
2683
- break;
2684
- assigned.push(node);
2685
- cursor.node = node.nextSibling;
2686
- }
2687
- }
2688
- }
2689
- if (assigned.length > 0) {
2690
- /** Assigned: the fallback was NOT rendered, so its parts are accounted (skipped) and its
2691
- * nodes cloned from the canonical template for live re-fallback later. */
2692
- const before = cursor.node;
2693
- const fallback = [];
2694
- for (let c = canonicalSlot.firstChild; c !== null; c = c.nextSibling)
2695
- if (c.nodeType === 1 || c.nodeType === 3)
2696
- fallback.push(c.cloneNode(true));
2697
- accountSubtree(canonicalSlot, state);
2698
- const seam = seamAdopt(_adoptHost, name, assigned, fallback, parent, before, ghost);
2699
- _adoptedSlots.push(seam);
2700
- (state._slotStates ??= []).push(seam);
2701
- /** An adopted seam is removal work exactly as a mounted one is — without this, a page whose
2702
- * only seams were adopted never ran `_teardown`, and branch-away destroyed the user's
2703
- * server-adopted content instead of parking it. See `declareRemovalWork`. */
2704
- declareRemovalWork();
2705
- }
2706
- else {
2707
- /** Unassigned: the server rendered this slot's fallback children — adopt them in lockstep
2708
- * (they ARE the canonical children), then bind them as the shown fallback. */
2709
- const fallbackStart = cursor.node;
2710
- for (let c = canonicalSlot.firstChild; c !== null; c = c.nextSibling)
2711
- if (c.nodeType === 1 || c.nodeType === 3)
2712
- adoptNode(c, cursor, state);
2713
- /** The fallback nodes now sit between fallbackStart and cursor.node. */
2714
- const fallback = [];
2715
- for (let n = fallbackStart; n !== null && n !== cursor.node; n = n.nextSibling)
2716
- fallback.push(n);
2717
- const seam = seamAdopt(_adoptHost, name, null, fallback, parent, cursor.node, ghost);
2718
- _adoptedSlots.push(seam);
2719
- (state._slotStates ??= []).push(seam);
2720
- /** Same as the assigned branch: an unassigned seam still unregisters and re-routes at park. */
2721
- declareRemovalWork();
2722
- }
2723
- };
2724
- /** Adopts one canonical node (and, for elements, its subtree) against the live cursor. */
2725
- const adoptNode = (canonical, cursor, state) => {
2726
- state._nodeIndex++;
2727
- const parts = state._template._parts;
2728
- if (canonical.nodeType === 3) {
2729
- /** A primed empty text is a child slot; any other text is a static to match. */
2730
- let isSlot = false;
2731
- while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2732
- isSlot = true;
2733
- state._partIndex++;
2734
- adoptSlot(cursor, state._values[state._valueIndex++], state._out);
2735
- drainIgnored(state);
2736
- }
2737
- if (!isSlot)
2738
- expectText(cursor, canonical.data);
2739
- return;
2740
- }
2741
- /** A `<slot>` in the canonical template maps to distributed content (or fallback) in the server
2742
- * DOM — reconciled specially — but only when a slot handler was wired at construction. */
2743
- if (state._template._seam !== undefined && canonical.localName === 'slot') {
2744
- adoptSlotElement(canonical, cursor, state);
2745
- return;
2746
- }
2747
- /** Element: same tag, commit its attribute parts live, then descend children in lockstep. */
2748
- passComments(cursor);
2749
- const live = cursorSplit(cursor);
2750
- if (live === null || live.nodeType !== 1) {
2751
- if (true )
2752
- why = `expected <${canonical.localName}> and found ${describe(live)}`;
2753
- throw MISMATCH;
2754
- }
2755
- if (live.localName !== canonical.localName) {
2756
- if (true )
2757
- why = `expected <${canonical.localName}> and found <${live.localName}>`;
2758
- throw MISMATCH;
2759
- }
2760
- while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
2761
- const templatePart = parts[state._partIndex++];
2762
- const attrPart = new AttrPart(live, templatePart._name, templatePart._statics, templatePart._present);
2763
- state._out.push(attrPart);
2764
- /** Attributes re-set (idempotent), listeners attached, refs fired — the server could only
2765
- * mirror form state; the client wires behavior. The `true` marks this as adoption, which is
2766
- * what keeps a form value the reader may already have changed (see `AttrPart._commit`). */
2767
- state._valueIndex = attrPart._commit(state._values, state._valueIndex, true);
2768
- drainIgnored(state);
2769
- }
2770
- const inner = { parent: live, node: live.firstChild, offset: 0 };
2771
- let child = canonical.firstChild;
2772
- while (child !== null) {
2773
- if (child.nodeType === 1 || child.nodeType === 3)
2774
- adoptNode(child, inner, state);
2775
- child = child.nextSibling;
2776
- }
2777
- /**
2778
- * The one place the server writes content the template does not describe: a `<textarea>`'s value
2779
- * **is** its content, so `.value=${…}` has nowhere else to go and `@verajs/ssr` puts it there —
2780
- * which is what shows the value to a reader with no JavaScript. The template's own statics say
2781
- * the element is empty, so this read as foreign markup and abandoned adoption for the whole page,
2782
- * silently: the container was cleared and re-rendered, the markup looked right, and everything
2783
- * server rendering is for was gone.
2784
- *
2785
- * **Kept, not cleared.** It is the element's `defaultValue`, and it is also the only thing
2786
- * holding the value: adoption deliberately does not write `.value` (see `AttrPart._commit`), so
2787
- * clearing the content would empty the field it just adopted. A person who typed here before the
2788
- * bundle landed has made the field dirty, and a dirty textarea ignores its content anyway — so
2789
- * their text survives either way, and the server's stays as what `form.reset()` restores.
2790
- *
2791
- * **One of four respects in which a hydrated DOM is not byte-identical to a client-rendered one**,
2792
- * and all four have the same cause: `@verajs/ssr` mirrors `.value`, `.checked` and `.selected` on
2793
- * form elements into markup, because markup is the only way form state reaches the client at all.
2794
- * The client sets those as properties and writes nothing, exactly as a browser does — so the
2795
- * server's copy stays behind after adoption:
2796
- *
2797
- * | binding | hydrated | client-rendered |
2798
- * | --- | --- | --- |
2799
- * | `<input .value=${x}>` | `<input value="x">` | `<input>` |
2800
- * | `<input .checked=${true}>` | `<input checked="">` | `<input>` |
2801
- * | `<option .selected=${true}>` | `<option selected="">` | `<option>` |
2802
- * | `<textarea .value=${x}>` | `<textarea>x</textarea>` | `<textarea></textarea>` |
2803
- *
2804
- * They are defaults rather than state — what `form.reset()` restores — so the *rendered* result is
2805
- * the same and only a reset tells them apart. `tests/hydrate-parity.test.mjs` records the list,
2806
- * because "the one respect" was written here when there was one, and a reader comparing a hydrated
2807
- * DOM against a client-rendered one needs to know which differences are meant.
2808
- */
2809
- if (inner.node !== null &&
2810
- inner.node.nodeType === 3 &&
2811
- inner.node.nextSibling === null &&
2812
- canonical.firstChild === null &&
2813
- live.localName === 'textarea') {
2814
- inner.node = null;
2815
- }
2816
- /** Leftover live children the template does not account for = not our markup. */
2817
- passComments(inner);
2818
- if (inner.node !== null && !(inner.node.nodeType === 3 && inner.node.data === '' && inner.node.nextSibling === null)) {
2819
- if (true )
2820
- why = `<${live.localName}> contains ${describe(inner.node)}, which the template does not describe`;
2821
- throw MISMATCH;
2822
- }
2823
- cursor.node = live.nextSibling;
2824
- cursor.offset = 0;
2825
- };
2826
- const drainIgnored = (state) => {
2827
- const parts = state._template._parts;
2828
- while (state._partIndex < parts.length && parts[state._partIndex]._type === IGNORED) {
2829
- state._out.push(IGNORED_PART);
2830
- state._valueIndex++;
2831
- state._partIndex++;
2832
- }
2833
- };
2834
- /** Adopts one child slot's rendered content, producing the part that will own it. */
2835
- const adoptSlot = (cursor, rawValue, out) => {
2836
- const heldResult = rawValue?.$h;
2837
- const value = heldResult !== undefined ? heldResult : rawValue;
2838
- /**
2839
- * Anything the client commits as text claims text here — which is every value that is not a
2840
- * template, a node, or an iterable. `String(value)` is what `_set` falls through to, so a `Date`,
2841
- * an object with a `toString`, a `Promise` or a plain object all produce text on the client, and
2842
- * `@verajs/ssr` produces the same text on the server.
2843
- *
2844
- * The object cases used to be a deliberate mismatch, because the server emitted nothing for them
2845
- * and the two could not be reconciled. Once the server started matching the client, the mismatch
2846
- * was the only thing left disagreeing.
2847
- */
2848
- const isText = value != null &&
2849
- (typeof value !== 'object' ||
2850
- (!isTemplateResult(value) &&
2851
- value.nodeType === undefined &&
2852
- typeof value[Symbol.iterator] !== 'function'));
2853
- if (isText) {
2854
- /** Claim its text and bind the fast TextPart, committed state included. */
2855
- const textPart = new TextPart(claimValueText(cursor, toText(value)));
2856
- textPart._value = value;
2857
- out.push(textPart);
2858
- return;
2859
- }
2860
- /** Structured content gets a markered ChildPart wrapped around whatever it rendered. */
2861
- const start = comment();
2862
- cursor.parent.insertBefore(start, cursorSplit(cursor));
2863
- const part = new ChildPart(start, null);
2864
- if (value == null) ;
2865
- else if (isTemplateResult(value)) {
2866
- part._instance = adoptInstance(getTemplate(value), value.values, cursor);
2867
- part._shape = value.strings;
2868
- part._mode = TEMPLATE;
2869
- }
2870
- else if (value.nodeType !== undefined) {
2871
- /**
2872
- * A DOM node is client-only by construction — the server has no document to have built one, so
2873
- * it rendered nothing here and there is nothing to adopt. Inserting it at the cursor (which has
2874
- * not moved, because no server node was claimed) puts it exactly where the end marker is about
2875
- * to go, and leaves the part in the same state a client-side commit would.
2876
- */
2877
- cursor.parent.insertBefore(value, cursorSplit(cursor));
2878
- part._value = value;
2879
- part._mode = NODE;
2880
- }
2881
- else {
2882
- /** Everything left is an array or another iterable — text and nodes were handled above. */
2883
- const list = Array.isArray(value) ? value : [...value];
2884
- const items = [];
2885
- for (const entry of list)
2886
- items.push(adoptItem(cursor, entry));
2887
- part._items = items;
2888
- /**
2889
- * The same predicate `_commitList` uses — the presence of a strategy, not of a `key`. Two
2890
- * spellings of "is this list keyed" would drift, and disagreeing about one list destroys it:
2891
- * a mode change is what tells the renderer to throw the adopted DOM away and start over.
2892
- */
2893
- part._keyedList = list.length > 0 && list[0]?.$r !== undefined;
2894
- part._mode = LIST;
2895
- }
2896
- const end = comment();
2897
- cursor.parent.insertBefore(end, cursorSplit(cursor));
2898
- part._end = end;
2899
- out.push(part);
2900
- };
2901
- /** Adopts one list item — element mode for single-root templates, markered otherwise. */
2902
- const adoptItem = (cursor, value) => {
2903
- if (value !== null && typeof value === 'object' && value.strings !== undefined) {
2904
- const result = value;
2905
- const template = getTemplate(result);
2906
- const content = template._element.content;
2907
- const root = content.firstChild;
2908
- if (root !== null && root.nodeType === 1 && root.nextSibling === null) {
2909
- const liveRoot = cursorSplit(cursor);
2910
- const instance = adoptInstance(template, result.values, cursor);
2911
- return {
2912
- $k: result.key,
2913
- _element: liveRoot,
2914
- _instance: instance,
2915
- _shape: result.strings,
2916
- _part: null,
2917
- };
2918
- }
2919
- const start = comment();
2920
- cursor.parent.insertBefore(start, cursorSplit(cursor));
2921
- const instance = adoptInstance(template, result.values, cursor);
2922
- const end = comment();
2923
- cursor.parent.insertBefore(end, cursorSplit(cursor));
2924
- const part = new ChildPart(start, end);
2925
- part._instance = instance;
2926
- part._shape = result.strings;
2927
- part._mode = TEMPLATE;
2928
- return { $k: result.key, _element: null, _instance: null, _shape: null, _part: part };
2929
- }
2930
- /** Non-template item: markered part adopting its content like a nested slot. */
2931
- const out = [];
2932
- adoptSlot(cursor, value, out);
2933
- return { $k: value?.key, _element: null, _instance: null, _shape: null, _part: out[0] };
2934
- };
2935
- /** Builds an Instance whose parts are bound to LIVE nodes, consuming them from the cursor. */
2936
- const adoptInstance = (template, values, cursor) => {
2937
- const instance = Object.create(Instance.prototype);
2938
- instance._parts = [];
2939
- instance._fragment = doc.createDocumentFragment();
2940
- const state = {
2941
- _template: template,
2942
- _values: values,
2943
- _valueIndex: 0,
2944
- _partIndex: 0,
2945
- _nodeIndex: -1,
2946
- _out: instance._parts,
2947
- };
2948
- drainIgnored(state);
2949
- /** Cached walk exists for repeated templates; the recursion itself visits in the same
2950
- * ELEMENT | TEXT document order the instance walker uses. */
2951
- canonicalNodes(template);
2952
- let child = template._element.content.firstChild;
2953
- while (child !== null) {
2954
- if (child.nodeType === 1 || child.nodeType === 3)
2955
- adoptNode(child, cursor, state);
2956
- child = child.nextSibling;
2957
- }
2958
- drainIgnored(state);
2959
- if (state._partIndex !== template._parts.length) {
2960
- if (true )
2961
- why = 'the markup ran out before the template did';
2962
- throw MISMATCH;
2963
- }
2964
- if (state._slotStates !== undefined)
2965
- instance._slotStates = state._slotStates;
2966
- return instance;
2967
- };
2968
- /**
2969
- * Attempts to adopt a container's existing (server-rendered) children for `result`. Returns the
2970
- * root part on success; null on any mismatch, leaving the caller to clean-render. Leading
2971
- * `<style data-vm-sheet="styles">` tags (the SSR style serialization) are skipped and preserved.
2972
- */
2973
- const tryAdopt = (result, container) => {
2974
- /** Only the SSR-serialized style tags are skipped — templates may legitimately start with
2975
- * whitespace or even their own static `<style>`, which must align against the canonical walk. */
2976
- let first = container.firstChild;
2977
- while (first !== null && first.nodeType === 1 && first.hasAttribute('data-vm-sheet')) {
2978
- first = first.nextSibling;
2979
- }
2980
- if (true )
2981
- why = '';
2982
- const start = comment();
2983
- container.insertBefore(start, first);
2984
- /** The container is the light host every slot in this render projects; `_defaultTaken` resets
2985
- * per adoption (the host count is for the first default slot). */
2986
- _adoptHost = container.nodeType === 1 ? container : null;
2987
- _defaultTaken = false;
2988
- _adoptedSlots = [];
2989
- try {
2990
- const cursor = { parent: container, node: start.nextSibling, offset: 0 };
2991
- const instance = adoptInstance(getTemplate(result), result.values, cursor);
2992
- passComments(cursor);
2993
- if (cursor.node !== null) {
2994
- if (true )
2995
- why = `${describe(cursor.node)} follows everything the template describes`;
2996
- throw MISMATCH;
2997
- }
2998
- const part = new ChildPart(start, null);
2999
- part._instance = instance;
3000
- part._shape = result.strings;
3001
- part._mode = TEMPLATE;
3002
- return part;
3003
- }
3004
- catch (error) {
3005
- if (error !== MISMATCH)
3006
- throw error;
3007
- /**
3008
- * Undo every slot this attempt adopted BEFORE the container is cleared: parking returns the
3009
- * user's nodes to holding and unregisters the binding, so the clean render that follows
3010
- * redistributes them instead of ranking behind an abandoned binding and showing fallback.
3011
- */
3012
- for (const seam of _adoptedSlots)
3013
- seam._$park$();
3014
- _adoptedSlots = [];
3015
- start.remove();
3016
- return null;
3017
- }
3018
- };
3019
- /** Mismatch cleanup lives here, not in the slim renderer: clear all but the SSR style tags. */
3020
- const clearPreservingStyles = (container) => {
3021
- let node = container.firstChild;
3022
- while (node !== null) {
3023
- /** `nextSibling` already yields `ChildNode | null`; annotating it `Node` widened it and broke
3024
- * the assignment back into `node`, which `firstChild` typed as `ChildNode | null`. */
3025
- const next = node.nextSibling;
3026
- if (!(node.nodeType === 1 && node.hasAttribute('data-vm-sheet')))
3027
- container.removeChild(node);
3028
- node = next;
3029
- }
3030
- };
3031
- /**
3032
- * The hydrating `render`: a drop-in for the base entry's. The first render into a container that
3033
- * already has children adopts them; any mismatch clears (keeping `<style data-vm-sheet="styles">`) and falls
3034
- * through to a clean base render. After the first render, this IS the base render.
3035
- */
3036
- const renderInto = (result, container) => {
3037
- if (!rootParts.has(container) &&
3038
- container.firstChild !== null &&
3039
- result !== null &&
3040
- typeof result === 'object' &&
3041
- isTemplateResult(result)) {
3042
- const part = tryAdopt(result, container);
3043
- if (part !== null) {
3044
- rootParts.set(container, part);
3045
- return;
3046
- }
3047
- /**
3048
- * **Falling back has to say so.** The page is correct either way — that is what the fallback is
3049
- * for — but the server's markup has just been thrown away, which means every byte the server
3050
- * spent rendering it was wasted and the one thing server rendering exists to deliver did not
3051
- * happen. Nothing observable changes, so without this the only symptom is a slower first paint
3052
- * that nobody attributes to anything.
3053
- *
3054
- * The `<textarea>` case a few screens up is the proof: adoption was abandoned *for the whole
3055
- * page* by one element whose content the template did not describe, and the markup still looked
3056
- * right afterwards. It was found by reading the code. React and lit both report a mismatch;
3057
- * this said nothing at all.
3058
- *
3059
- * `true `-only, and the reason comes from the check that failed, so it names the first place
3060
- * the two renders disagreed rather than announcing that they did.
3061
- *
3062
- * **Scoped to this container, because that is what happened.** This function runs once per
3063
- * container, and a mismatch clears exactly one — measured: three containers, one carrying markup
3064
- * the template does not describe, and the other two adopt their server nodes unchanged while one
3065
- * warning prints. The message used to say "nothing the server rendered was used", which reads as
3066
- * a page-wide failure and sends the reader looking for a page-wide cause: a bad doctype, a broken
3067
- * handoff, state that differs everywhere. The truth is narrower and the message already names the
3068
- * element, so the advice can be local.
3069
- *
3070
- * It also said the markup was discarded, full stop; `clearPreservingStyles` keeps
3071
- * `<style data-vm-sheet="styles">`, which is the whole reason that function exists.
3072
- */
3073
- if (true ) {
3074
- /**
3075
- * **"The page is correct" is a promise this message must not make blindly.** The bail rescue
3076
- * preserves everything it can PROVE is the user's: content inside `data-vm-slotted` marks,
3077
- * the `data-vm-unassigned` carrier, and elements carrying a `slot` attribute. Real server
3078
- * output always marks its distributed default-slot content, so on genuine deploy skew the
3079
- * rescue is complete and the promise holds — measured, named and unnamed and bare text alike.
3080
- * But a container holding CLIENT-side markup that was never server output has no marks, and
3081
- * its unnamed slottables are structurally indistinguishable from the stale template output
3082
- * being discarded — so they go with it, under a message that said everything was fine. The
3083
- * marks are the discriminator: their total absence is exactly the shape where the promise
3084
- * can fail, so that is when the message changes.
3085
- */
3086
- const unmarked = container.nodeType === 1 &&
3087
- container.querySelector('[data-vm-slotted],[data-vm-unassigned]') === null;
3088
- console.warn(`[vera] hydration fell back to a client render: ${why}. This container's server markup was ` +
3089
- `discarded and rebuilt (its SSR <style> is kept), ` +
3090
- (unmarked
3091
- ? `and it carried none of the marks server output carries. If its children were ` +
3092
- `CLIENT-side markup rather than this template's server output, unnamed light-slot ` +
3093
- `content (bare text, elements without a \`slot\` attribute) cannot be told apart ` +
3094
- `from the stale markup and was discarded with it — hydrate adopts existing children ` +
3095
- `AS server output; render client-only containers with @verajs/renderer's renderInto ` +
3096
- `instead. `
3097
- : `so the page is correct but the server's work on this part of it was wasted. `) +
3098
- `Other containers on the page hydrate independently and are unaffected. The two renders ` +
3099
- `have to agree exactly — check for markup the template does not describe, or state ` +
3100
- `settled after the server render.`);
3101
- }
3102
- /**
3103
- * **Un-distribute before discarding.** A light host's slotted content lives INSIDE the markup
3104
- * about to be thrown away, so clearing destroyed it: the slots fell back and the user's nodes
3105
- * were gone from the page permanently, under a warning that said the page was still correct.
3106
- * The slots module lifts them back out (`_$rescue$`), and re-attaching them as the host's
3107
- * children puts it in exactly the state a first client render starts from — the clean render
3108
- * below captures and redistributes them with no special case anywhere.
3109
- */
3110
- const rescued = container.nodeType === 1 ? slotSeam()?._$rescue$?.(container) : null;
3111
- clearPreservingStyles(container);
3112
- if (rescued !== null && rescued !== undefined)
3113
- for (const node of rescued)
3114
- container.appendChild(node);
3115
- }
3116
- renderInto$1(result, container);
3117
- };
3118
- /** Same wire-misuse guard the base entry puts on its raw function — see renderer.ts. */
3119
- if (true )
3120
- renderInto.$module = 'renderer';
3121
- /**
3122
- * This entry's `renderer` module, bound to the **hydrating** `renderInto`.
3123
- *
3124
- * It used to be a bare re-export of the base entry's descriptor, whose `fn` is the base,
3125
- * non-adopting render — so the natural `import { renderer } from '@verajs/renderer/hydrate';
3126
- * wire([renderer])` wired a renderer that never hydrated. The page still looked right (a first
3127
- * render into a full container clears it and renders fresh), which made the failure silent: every
3128
- * byte of server work discarded, nothing on screen to say so. The header's promise — point the
3129
- * importmap at this bundle "and nothing else changes" — is only true now that the descriptor
3130
- * carries this entry's own function. `connect` and the rest are shared deliberately: they operate
3131
- * on this bundle's copy of the renderer's module state, which both functions read.
3132
- */
3133
- const renderer = { ...renderer$1, fn: renderInto };
3134
-
3135
- export { hold, renderInto, renderer };
3136
- //# sourceMappingURL=vera-renderer-hydrate.js.map