@verajs/renderer 0.1.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.
@@ -0,0 +1,1292 @@
1
+ /**
2
+ * @verajs/renderer — a ground-up, keyed, template-identity renderer.
3
+ *
4
+ * Replaces the Reef-derived renderer, which flattened every template to an HTML string and
5
+ * re-parsed it on each change — O(whole template) work for a one-row edit, measured at 85 ms for a
6
+ * two-row swap that lit-html does in 3.5 ms.
7
+ *
8
+ * The architecture here is the one that wins that benchmark:
9
+ *
10
+ * 1. A tagged template literal's `strings` array is frozen and IDENTICAL for every call from the
11
+ * same call site, so it is a cache key for the template's static shape. The shape is parsed
12
+ * ONCE into a `<template>` element with markers where the expressions go.
13
+ * 2. Rendering clones that template and binds "parts" to the marker positions. Every later render
14
+ * of the same shape only compares and commits the dynamic values — static content is never
15
+ * touched again.
16
+ * 3. Arrays reconcile KEYED (see `keyed()`), with head/tail fast paths and map-based moves, so a
17
+ * reorder moves nodes instead of rebuilding them.
18
+ *
19
+ * Built in, where lit-html requires directive imports: keyed list reconciliation (`keyed`),
20
+ * element refs (element-position expressions), toggled-DOM preservation (`hold`), and a
21
+ * whole-range fast clear — one `textContent = ''` where lit removes thousands of nodes one at a
22
+ * time. Like-for-like (lit-html + repeat + ref + cache: 5 021 B gzip), this file is ~28% smaller.
23
+ *
24
+ * What it deliberately does NOT have, which is why it is smaller than lit-html: no directive
25
+ * protocol, no `noChange`/`nothing` sentinels (in a single-expression attribute, `null`/`undefined`
26
+ * REMOVE the attribute; in a child, they clear it), no sanitizer indirection, no async parts, no
27
+ * dev-mode branches.
28
+ *
29
+ * Known limits, deliberate and shared with lit-html's envelope: no bindings inside comments (the
30
+ * value is consumed and ignored), no dynamic tag names, and nested `<template>` elements' contents
31
+ * are not traversed.
32
+ *
33
+ * CONTRACTS THE SPEED PAYS FOR — these are the trade, documented rather than discovered:
34
+ *
35
+ * - **The renderer owns its container below the mount point.** The whole-range fast clear wipes
36
+ * everything in a parent the part fully owns, including nodes user code appended there by hand
37
+ * (lit-html would preserve them). Same contract as mounting Vue or React into a container.
38
+ * - **Do not call `Node.normalize()` on rendered content.** Child anchors are text nodes, and
39
+ * normalize merges adjacent text — lit-html's comment anchors are immune to this; ours are not.
40
+ * - **A plain string renders as text, never as HTML.** The Reef renderer parsed strings as markup;
41
+ * this one has no innerHTML sink at all (an XSS class removed). The deliberate escape hatch for
42
+ * trusted markup is a property binding: `.innerHTML=${trusted}`.
43
+ * - **Hydration is automatic and markerless.** The first render into a container that already has
44
+ * children adopts them as server output of the same template (statics matched byte-for-byte,
45
+ * anchors installed by splitting live text at known value positions), falling back to a clean
46
+ * render on any mismatch. Requires the initial client render to match server state — same
47
+ * contract as React/Vue hydration.
48
+ * - **No directive protocol.** The template language itself is closed to extension — Vera extends
49
+ * at the framework layer (inserts) and through element refs, not inside the renderer's value
50
+ * handling.
51
+ * - Event handlers are invoked with `this` bound to the ELEMENT (lit binds its host).
52
+ *
53
+ * NAMING NOTE: internal class fields and methods are `_`-prefixed because the production build
54
+ * mangles properties matching /^_[a-z]/ (see defaultRollupConfig). That is what lets this file use
55
+ * full descriptive names while still shipping one-letter properties — locals and top-level names
56
+ * are mangled by default anyway, but property names are not. `_$litType$` and `handleEvent`
57
+ * deliberately do not match the pattern: the first is an interop wire format, the second is called
58
+ * by the DOM itself.
59
+ */
60
+ /**
61
+ * Marks a template result with a stable key so list reconciliation moves it instead of rewriting
62
+ * it. Key all items in a list or none — mixing is undefined behaviour, as are duplicate keys.
63
+ *
64
+ * ```js
65
+ * rows.map((r) => keyed(r.id, html`<tr>...</tr>`))
66
+ * ```
67
+ */
68
+ const keyed = (key, result) => {
69
+ result.key = key;
70
+ return result;
71
+ };
72
+ /**
73
+ * Preserves the DOM of templates a child position toggles away from, instead of destroying it —
74
+ * form values, scroll positions and media playback survive the round trip (lit-html calls this
75
+ * `cache`). Stashed DOM is parked in its instance's own fragment and re-adopted on return.
76
+ *
77
+ * ```js
78
+ * html`<div>${hold(editing ? editor() : viewer())}</div>`
79
+ * ```
80
+ */
81
+ const hold = (result) => ({ $h: result });
82
+ /**
83
+ * Unique per module load, so user text can never collide with it. Randomness here cannot break
84
+ * template caching — the marker only ever pairs a scan with its own Template construction.
85
+ */
86
+ const MARKER = '$v' + ((Math.random() * 1e9) >>> 0).toString(36) + '$';
87
+ /** `<?xyz>` parses as a bogus comment whose data is `?xyz`. */
88
+ const MARKER_COMMENT_DATA = '?' + MARKER;
89
+ const doc = document;
90
+ const comment = (data = '') => doc.createComment(data);
91
+ /**
92
+ * One walker for every template construction, re-aimed by assigning `currentNode`. Traversal of a
93
+ * detached fragment cannot escape it — ascent stops at a null parent — and no walk is ever
94
+ * re-entered mid-flight: an inner instantiation only begins after the outer walk has finished
95
+ * collecting its parts.
96
+ */
97
+ const markerWalker = doc.createTreeWalker(doc, 129 /* ELEMENT | COMMENT */);
98
+ /**
99
+ * Second shared walker for indexing and instantiation. Templates ship with NO marker comments —
100
+ * every child slot's anchor is its primed text node — so instances index over elements and texts.
101
+ * Marker comments exist only transiently during template construction, and are created lazily at
102
+ * runtime only if a slot upgrades from text to template/array content. Sharing the walker saves a
103
+ * TreeWalker allocation per instance, which is 10 000 allocations in a 10 000-row create.
104
+ */
105
+ const instanceWalker = doc.createTreeWalker(doc, 5 /* ELEMENT | TEXT */);
106
+ const RAW_TEXT_TAGS = /^(?:script|style|textarea|title)$/i;
107
+ const ATTR_NAME_DELIMITER = /[\s"'>=/]/;
108
+ /** What an expression position turned out to be. */
109
+ const CHILD = 0;
110
+ const ATTRIBUTE = 1;
111
+ const IGNORED = 2; // value consumed, nothing rendered (bindings inside comments, junk positions)
112
+ /** Scanner states. */
113
+ const IN_TEXT = 0;
114
+ const IN_TAG = 1;
115
+ const IN_QUOTED_VALUE = 2; // a static quoted attribute value (no binding seen yet)
116
+ const IN_COMMENT = 3;
117
+ const IN_RAW_TEXT = 4; // inside <script>/<style>/<textarea>/<title>
118
+ const IN_BOUND_VALUE = 5; // collecting a bound attribute's statics
119
+ /**
120
+ * One pass over the template strings, producing parseable HTML with markers plus an ordered spec
121
+ * list. Runs once per template shape, so clarity beats micro-optimisation here.
122
+ *
123
+ * A small state machine rather than tail regexes, because `>` inside quoted attribute values and
124
+ * inside comments must not terminate a tag, and raw-text elements swallow markup.
125
+ */
126
+ const scan = (strings) => {
127
+ const specs = [];
128
+ let markup = '';
129
+ let state = IN_TEXT;
130
+ let quote = '';
131
+ let quoteStart = 0; // markup index of the opening quote while IN_QUOTED_VALUE
132
+ let rawTag = ''; // which raw-text element we are inside
133
+ let tagNameStart = 0; // markup index where the current tag's name begins
134
+ let isClosing = false;
135
+ let attrName = '';
136
+ let statics = [];
137
+ let pending = ''; // the static chunk currently being collected IN_BOUND_VALUE
138
+ /** Backscan an attribute name that ends at `end` (exclusive); '' when malformed. */
139
+ const attrNameBefore = (end) => {
140
+ let at = end;
141
+ while (at > 0 && !ATTR_NAME_DELIMITER.test(markup[at - 1]))
142
+ at--;
143
+ return markup.slice(at, end);
144
+ };
145
+ for (let i = 0; i < strings.length; i++) {
146
+ const segment = strings[i];
147
+ let pos = 0;
148
+ while (pos < segment.length) {
149
+ const ch = segment[pos];
150
+ if (state === IN_BOUND_VALUE) {
151
+ if (ch === quote ||
152
+ (quote === '' && (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '>' || ch === '/'))) {
153
+ /**
154
+ * The bound attribute closes. Emit a marker attribute whose VALUE carries the statics
155
+ * joined by the marker — reading them back from the parsed attribute means entities
156
+ * arrive decoded, exactly as a static attribute would.
157
+ */
158
+ statics.push(pending);
159
+ const quoteChar = quote || '"';
160
+ markup += ` ${specs.length}${MARKER}=${quoteChar}${statics.join(MARKER)}${quoteChar}`;
161
+ specs.push({ _type: ATTRIBUTE, _name: attrName });
162
+ state = IN_TAG;
163
+ if (quote !== '')
164
+ pos++; // consume the closing quote; unquoted terminators reprocess IN_TAG
165
+ continue;
166
+ }
167
+ pending += ch;
168
+ pos++;
169
+ }
170
+ else if (state === IN_TEXT) {
171
+ if (ch === '<') {
172
+ if (segment.startsWith('!--', pos + 1)) {
173
+ state = IN_COMMENT;
174
+ markup += '<!--';
175
+ pos += 4;
176
+ continue;
177
+ }
178
+ isClosing = segment[pos + 1] === '/';
179
+ tagNameStart = markup.length + (isClosing ? 2 : 1);
180
+ state = IN_TAG;
181
+ }
182
+ markup += ch;
183
+ pos++;
184
+ }
185
+ else if (state === IN_TAG) {
186
+ if (ch === '"' || ch === "'") {
187
+ quote = ch;
188
+ quoteStart = markup.length;
189
+ state = IN_QUOTED_VALUE;
190
+ }
191
+ else if (ch === '>') {
192
+ const tagName = markup.slice(tagNameStart).match(/^[a-zA-Z][^\s/>]*/)?.[0] ?? '';
193
+ if (!isClosing && RAW_TEXT_TAGS.test(tagName) && !markup.endsWith('/')) {
194
+ rawTag = tagName.toLowerCase();
195
+ state = IN_RAW_TEXT;
196
+ }
197
+ else {
198
+ state = IN_TEXT;
199
+ }
200
+ }
201
+ markup += ch;
202
+ pos++;
203
+ }
204
+ else if (state === IN_QUOTED_VALUE) {
205
+ if (ch === quote)
206
+ state = IN_TAG;
207
+ markup += ch;
208
+ pos++;
209
+ }
210
+ else if (state === IN_COMMENT) {
211
+ if (ch === '-' && segment.startsWith('->', pos + 1)) {
212
+ markup += '-->';
213
+ pos += 3;
214
+ state = IN_TEXT;
215
+ continue;
216
+ }
217
+ markup += ch;
218
+ pos++;
219
+ }
220
+ else {
221
+ // IN_RAW_TEXT
222
+ if (ch === '<' &&
223
+ segment.slice(pos + 1, pos + 2 + rawTag.length).toLowerCase() === '/' + rawTag &&
224
+ (pos + 2 + rawTag.length >= segment.length || /[\s/>]/.test(segment[pos + 2 + rawTag.length]))) {
225
+ isClosing = true;
226
+ tagNameStart = markup.length + 2;
227
+ state = IN_TAG;
228
+ }
229
+ markup += ch;
230
+ pos++;
231
+ }
232
+ }
233
+ // ── expression boundary ──────────────────────────────────────────────────
234
+ if (i === strings.length - 1)
235
+ break;
236
+ if (state === IN_TEXT) {
237
+ markup += `<?${MARKER}>`;
238
+ specs.push({ _type: CHILD });
239
+ }
240
+ else if (state === IN_RAW_TEXT) {
241
+ markup += MARKER; // a text marker; comments cannot be parsed inside raw-text elements
242
+ specs.push({ _type: CHILD });
243
+ }
244
+ else if (state === IN_COMMENT) {
245
+ specs.push({ _type: IGNORED }); // binding inside a comment: consumed, ignored
246
+ }
247
+ else if (state === IN_BOUND_VALUE) {
248
+ statics.push(pending); // this attribute spans another expression
249
+ pending = '';
250
+ }
251
+ else if (state === IN_QUOTED_VALUE) {
252
+ // expression inside a quoted attribute value -> becomes a bound attribute
253
+ const name = markup[quoteStart - 1] === '=' ? attrNameBefore(quoteStart - 1) : '';
254
+ if (name) {
255
+ attrName = name;
256
+ statics = [markup.slice(quoteStart + 1)]; // the static prefix already inside the quotes
257
+ pending = '';
258
+ markup = markup.slice(0, quoteStart - 1 - name.length); // cut `name="` back out
259
+ state = IN_BOUND_VALUE;
260
+ }
261
+ else {
262
+ specs.push({ _type: IGNORED });
263
+ }
264
+ }
265
+ else {
266
+ // IN_TAG: `name=${x}` unquoted, or an element-position expression
267
+ const name = markup.endsWith('=') ? attrNameBefore(markup.length - 1) : '';
268
+ if (name) {
269
+ attrName = name;
270
+ statics = [''];
271
+ pending = '';
272
+ quote = '';
273
+ markup = markup.slice(0, markup.length - 1 - name.length);
274
+ state = IN_BOUND_VALUE;
275
+ }
276
+ else {
277
+ /**
278
+ * Element-position expression — an element REF, not a no-op. Marked exactly like a bound
279
+ * attribute ('&' cannot begin a real attribute binding), so no new machinery exists for it.
280
+ */
281
+ markup += ` ${specs.length}${MARKER}="${MARKER}"`;
282
+ specs.push({ _type: ATTRIBUTE, _name: '&' });
283
+ }
284
+ }
285
+ }
286
+ return { markup, specs };
287
+ };
288
+ const templateCache = new WeakMap();
289
+ class Template {
290
+ _element;
291
+ _parts = [];
292
+ constructor(result) {
293
+ const type = result._$litType$ ?? 1;
294
+ const { markup, specs } = scan(result.strings);
295
+ this._element = doc.createElement('template');
296
+ /** svg/mathml fragments only parse inside their root; wrap, then unwrap below. */
297
+ this._element.innerHTML = type === 2 ? `<svg>${markup}</svg>` : type === 3 ? `<math>${markup}</math>` : markup;
298
+ const content = this._element.content;
299
+ if (type !== 1) {
300
+ const wrapper = content.firstChild;
301
+ while (wrapper.firstChild)
302
+ content.insertBefore(wrapper.firstChild, wrapper);
303
+ content.removeChild(wrapper);
304
+ }
305
+ /**
306
+ * Pass 1 — DISCOVER over ELEMENT | COMMENT: pair scan specs with parsed nodes in document
307
+ * order (which is expression order), and swap every marker comment for a primed empty text
308
+ * node. The shipped template then contains no comments at all: each clone is three nodes
309
+ * lighter per typical row, and the primed text doubles as both anchor and first-commit target.
310
+ */
311
+ markerWalker.currentNode = content;
312
+ let specIndex = 0;
313
+ let node;
314
+ const parts = this._parts;
315
+ const consumeIgnored = () => {
316
+ while (specIndex < specs.length && specs[specIndex]._type === IGNORED) {
317
+ parts.push({ _type: IGNORED, _index: -1 });
318
+ specIndex++;
319
+ }
320
+ };
321
+ consumeIgnored();
322
+ while (specIndex < specs.length && (node = markerWalker.nextNode()) !== null) {
323
+ if (node.nodeType === 1) {
324
+ const element = node;
325
+ if (element.hasAttributes()) {
326
+ for (const attributeName of element.getAttributeNames()) {
327
+ if (attributeName.endsWith(MARKER)) {
328
+ /**
329
+ * The marker attribute's value carries the statics; the REAL (case-preserved) name
330
+ * comes from the spec — the HTML parser lowercases attribute names, which would
331
+ * corrupt `.someProp`.
332
+ */
333
+ const spec = specs[specIndex++];
334
+ parts.push({
335
+ _type: ATTRIBUTE,
336
+ _index: -1,
337
+ _name: spec._name,
338
+ _statics: element.getAttribute(attributeName).split(MARKER),
339
+ _node: element,
340
+ });
341
+ element.removeAttribute(attributeName);
342
+ consumeIgnored();
343
+ }
344
+ }
345
+ }
346
+ if (RAW_TEXT_TAGS.test(element.tagName) && element.textContent.includes(MARKER)) {
347
+ /**
348
+ * Comments cannot be PARSED inside raw-text elements, but they are legal DOM once
349
+ * created — so the scan left text markers, and here they become real marker comments.
350
+ * The walker visits them next and they pair as ordinary child parts.
351
+ */
352
+ const pieces = element.textContent.split(MARKER);
353
+ element.textContent = '';
354
+ for (let p = 0; p < pieces.length - 1; p++) {
355
+ if (pieces[p])
356
+ element.append(pieces[p]);
357
+ element.append(comment(MARKER_COMMENT_DATA));
358
+ }
359
+ if (pieces[pieces.length - 1])
360
+ element.append(pieces[pieces.length - 1]);
361
+ }
362
+ }
363
+ else if (node.data === MARKER_COMMENT_DATA) {
364
+ specIndex++;
365
+ const primedText = doc.createTextNode('');
366
+ node.parentNode.insertBefore(primedText, node);
367
+ /** Re-aim the walker before removing the node it stands on. */
368
+ markerWalker.currentNode = primedText;
369
+ node.remove();
370
+ parts.push({ _type: CHILD, _index: -1, _node: primedText });
371
+ consumeIgnored();
372
+ }
373
+ }
374
+ /** Pass 2 — INDEX over ELEMENT | TEXT, the mask instances walk with. */
375
+ instanceWalker.currentNode = content;
376
+ let nodeIndex = -1;
377
+ let partIndex = 0;
378
+ while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
379
+ partIndex++;
380
+ while (partIndex < parts.length && (node = instanceWalker.nextNode()) !== null) {
381
+ nodeIndex++;
382
+ while (partIndex < parts.length && parts[partIndex]._node === node) {
383
+ parts[partIndex]._index = nodeIndex;
384
+ partIndex++;
385
+ while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
386
+ partIndex++;
387
+ }
388
+ }
389
+ for (const part of parts)
390
+ part._node = undefined;
391
+ }
392
+ }
393
+ const getTemplate = (result) => {
394
+ let template = templateCache.get(result.strings);
395
+ if (template === undefined)
396
+ templateCache.set(result.strings, (template = new Template(result)));
397
+ return template;
398
+ };
399
+ const IGNORED_PART = { _commit: (_values, index) => index + 1 };
400
+ /** Never equal to any user value, so the first commit always runs. */
401
+ const UNSET = {};
402
+ /** Removal target: nodes moved here are dropped when it is emptied. */
403
+ const SCRATCH = doc.createDocumentFragment();
404
+ /** A fresh markered part: two comments inserted before `ref` in `parent`. */
405
+ const createMarkeredPart = (parent, ref) => {
406
+ const start = comment();
407
+ const end = comment();
408
+ parent.insertBefore(start, ref);
409
+ parent.insertBefore(end, ref);
410
+ return new ChildPart(start, end);
411
+ };
412
+ const toText = (value) => (value == null ? '' : String(value));
413
+ /** Binding kinds, resolved once from the attribute name's first character. */
414
+ const ATTR = 0; // plain attribute
415
+ const PROPERTY = 1; // .name
416
+ const BOOLEAN = 2; // ?name
417
+ const EVENT = 3; // @name
418
+ const REF = 4; // element-position expression
419
+ class AttrPart {
420
+ _element;
421
+ _name;
422
+ _statics;
423
+ _slots; // how many expression values this binding consumes
424
+ _kind;
425
+ _isFullValue; // exactly one expression with no static text around it
426
+ _committed = UNSET;
427
+ _handler = null;
428
+ constructor(element, name, statics) {
429
+ const first = name[0];
430
+ let kind = first === '.' ? PROPERTY : first === '?' ? BOOLEAN : first === '@' ? EVENT : first === '&' ? REF : ATTR;
431
+ let realName = kind ? name.slice(1) : name;
432
+ /** React muscle-memory, buildless: `onClick=${fn}` ≡ `@click=${fn}`. Strictly `on` + a
433
+ * capital — all-lowercase `onclick` stays a plain attribute (legal inline-handler HTML). */
434
+ if (kind === ATTR && first === 'o' && name.charCodeAt(1) === 110 && name.charCodeAt(2) > 64 && name.charCodeAt(2) < 91) {
435
+ kind = EVENT;
436
+ realName = name.slice(2).toLowerCase();
437
+ }
438
+ this._kind = kind;
439
+ this._name = realName;
440
+ this._element = element;
441
+ this._statics = statics;
442
+ this._slots = statics.length - 1;
443
+ this._isFullValue = this._slots === 1 && statics[0] === '' && statics[1] === '';
444
+ }
445
+ /** Stable listener registered once; swapping the handler never touches the DOM. */
446
+ handleEvent(event) {
447
+ if (this._handler)
448
+ this._handler.call(this._element, event);
449
+ }
450
+ _commit(values, index) {
451
+ const kind = this._kind;
452
+ let value;
453
+ if (this._isFullValue || kind >= EVENT) {
454
+ value = values[index]; // raw and uncoerced — events and refs receive the actual value
455
+ }
456
+ else {
457
+ const statics = this._statics;
458
+ let joined = statics[0];
459
+ for (let i = 0; i < this._slots; i++)
460
+ joined += toText(values[index + i]) + statics[i + 1];
461
+ value = joined;
462
+ }
463
+ if (value !== this._committed) {
464
+ /** On the very first commit the attribute does not exist, so a null needs no DOM call. */
465
+ const isFirst = this._committed === UNSET;
466
+ this._committed = value;
467
+ if (kind === ATTR) {
468
+ if (value == null) {
469
+ if (!isFirst)
470
+ this._element.removeAttribute(this._name);
471
+ }
472
+ else
473
+ this._element.setAttribute(this._name, value);
474
+ }
475
+ else if (kind === PROPERTY) {
476
+ this._element[this._name] = value;
477
+ }
478
+ else if (kind === BOOLEAN) {
479
+ if (!isFirst || value)
480
+ this._element.toggleAttribute(this._name, !!value);
481
+ }
482
+ else if (kind === EVENT) {
483
+ if (this._handler === null && value != null)
484
+ this._element.addEventListener(this._name, this);
485
+ this._handler = value ?? null;
486
+ }
487
+ else if (value != null) {
488
+ /**
489
+ * Element ref: `<input ${myRef} />`. A function is called with the element; an object gets
490
+ * the element assigned to `.value` — which makes core's own `ref()` double as an element
491
+ * ref, reactively. Runs once per distinct value, not once per render.
492
+ */
493
+ if (typeof value === 'function')
494
+ value(this._element);
495
+ else if (typeof value === 'object')
496
+ value.value = this._element;
497
+ // any other value type at element position is consumed and ignored
498
+ }
499
+ }
500
+ return index + this._slots;
501
+ }
502
+ }
503
+ class Instance {
504
+ _parts = [];
505
+ _fragment;
506
+ constructor(template) {
507
+ /** cloneNode over importNode: same document, and it measures slightly cheaper. */
508
+ this._fragment = template._element.content.cloneNode(true);
509
+ const templateParts = template._parts;
510
+ /** Shared walker, ELEMENT | TEXT — child anchors are the primed text nodes themselves. */
511
+ instanceWalker.currentNode = this._fragment;
512
+ let nodeIndex = -1;
513
+ let node = null;
514
+ for (let i = 0; i < templateParts.length; i++) {
515
+ const templatePart = templateParts[i];
516
+ if (templatePart._type === IGNORED) {
517
+ this._parts.push(IGNORED_PART);
518
+ continue;
519
+ }
520
+ while (nodeIndex < templatePart._index) {
521
+ node = instanceWalker.nextNode();
522
+ nodeIndex++;
523
+ }
524
+ this._parts.push(templatePart._type === CHILD
525
+ ? new TextPart(node)
526
+ : new AttrPart(node, templatePart._name, templatePart._statics));
527
+ }
528
+ }
529
+ _update(values) {
530
+ let valueIndex = 0;
531
+ const parts = this._parts;
532
+ for (let i = 0; i < parts.length; i++)
533
+ valueIndex = parts[i]._commit(values, valueIndex);
534
+ }
535
+ }
536
+ /** A single property read — this runs once per list item per render, so it must be minimal. */
537
+ const isTemplateResult = (value) => value.strings !== undefined;
538
+ /**
539
+ * The common case of a child expression is plain text, and the template primes every child slot
540
+ * with a text node — so the steady state is compare-and-assign on `.data`. This part carries only
541
+ * that, upgrading itself to a full ChildPart the first time it sees null, a template, or an array.
542
+ */
543
+ class TextPart {
544
+ _text;
545
+ _value = '';
546
+ _upgraded = null;
547
+ constructor(text) {
548
+ this._text = text;
549
+ }
550
+ _commit(values, index) {
551
+ const value = values[index];
552
+ if (this._upgraded !== null) {
553
+ this._upgraded._set(value);
554
+ return index + 1;
555
+ }
556
+ if (value == null || typeof value === 'object') {
557
+ /**
558
+ * Upgrade in place: only now does a marker comment come into existence, anchored where the
559
+ * text sits, and the full part inherits the committed text state and delegates forever.
560
+ */
561
+ const start = comment();
562
+ this._text.parentNode.insertBefore(start, this._text);
563
+ const part = new ChildPart(start, this._text.nextSibling);
564
+ part._mode = TEXT;
565
+ part._text = this._text;
566
+ part._value = this._value;
567
+ this._upgraded = part;
568
+ part._set(value);
569
+ return index + 1;
570
+ }
571
+ if (value !== this._value) {
572
+ this._value = value;
573
+ this._text.data = value;
574
+ }
575
+ return index + 1;
576
+ }
577
+ }
578
+ /** What a ChildPart currently contains. */
579
+ const EMPTY = 0;
580
+ const TEXT = 1;
581
+ const TEMPLATE = 2;
582
+ const LIST = 3;
583
+ class ChildPart {
584
+ _start;
585
+ /** Exclusive end of this part's range; null means "to the end of the parent". */
586
+ _end;
587
+ _mode = EMPTY;
588
+ _value;
589
+ _text = null;
590
+ _instance = null;
591
+ /** The committed template's strings identity — the same-template fast path in `_set`. */
592
+ _shape = null;
593
+ _items = null;
594
+ _keyedList = false;
595
+ /** Held instances by template identity; survives clears so state outlives interim content. */
596
+ _held = null;
597
+ constructor(start, end) {
598
+ this._start = start;
599
+ this._end = end;
600
+ }
601
+ _commit(values, index) {
602
+ this._set(values[index]);
603
+ return index + 1;
604
+ }
605
+ _insert(node) {
606
+ this._start.parentNode.insertBefore(node, this._end);
607
+ }
608
+ _clear() {
609
+ const parent = this._start.parentNode;
610
+ /**
611
+ * When this part owns its parent's entire contents, one `textContent = ''` replaces removing
612
+ * every node individually. For a 1 000-row table body that is the difference between ~22 ms
613
+ * (lit-html's per-node teardown) and ~5 ms.
614
+ */
615
+ if (this._start.previousSibling === null && this._end === null) {
616
+ parent.textContent = '';
617
+ parent.appendChild(this._start);
618
+ }
619
+ else {
620
+ let node = this._start.nextSibling;
621
+ while (node !== this._end) {
622
+ const next = node.nextSibling;
623
+ parent.removeChild(node);
624
+ node = next;
625
+ }
626
+ }
627
+ this._mode = EMPTY;
628
+ this._text = null;
629
+ this._instance = null;
630
+ this._items = null;
631
+ this._shape = null;
632
+ }
633
+ _set(value) {
634
+ if (value == null) {
635
+ if (this._mode !== EMPTY)
636
+ this._clear();
637
+ return;
638
+ }
639
+ if (typeof value !== 'object') {
640
+ if (this._mode === TEXT) {
641
+ if (this._value !== value) {
642
+ this._value = value;
643
+ this._text.data = value; // the DOM coerces numbers etc.
644
+ }
645
+ }
646
+ else {
647
+ if (this._mode !== EMPTY)
648
+ this._clear();
649
+ this._text = doc.createTextNode(value);
650
+ this._insert(this._text);
651
+ this._value = value;
652
+ this._mode = TEXT;
653
+ }
654
+ return;
655
+ }
656
+ const heldResult = value.$h;
657
+ if (heldResult !== undefined) {
658
+ this._commitHeld(heldResult);
659
+ return;
660
+ }
661
+ if (isTemplateResult(value)) {
662
+ /**
663
+ * Same-shape fast path on `strings` identity alone — no template-cache lookup. This is the
664
+ * hottest line in a keyed list update: for every row whose shape did not change (all of
665
+ * them, in practice), commit costs one identity compare before touching the values.
666
+ */
667
+ if (this._shape === value.strings) {
668
+ this._instance._update(value.values);
669
+ return;
670
+ }
671
+ const template = getTemplate(value);
672
+ if (this._mode !== EMPTY)
673
+ this._clear();
674
+ const instance = new Instance(template);
675
+ instance._update(value.values);
676
+ this._insert(instance._fragment);
677
+ this._instance = instance;
678
+ this._shape = value.strings;
679
+ this._mode = TEMPLATE;
680
+ return;
681
+ }
682
+ if (Array.isArray(value)) {
683
+ this._commitList(value);
684
+ return;
685
+ }
686
+ if (typeof value[Symbol.iterator] === 'function') {
687
+ this._commitList([...value]);
688
+ return;
689
+ }
690
+ // any other object: render as text
691
+ this._set(String(value));
692
+ }
693
+ /** Commits a template while stashing whatever it replaces — see the `hold()` export. */
694
+ _commitHeld(result) {
695
+ if (this._mode === TEMPLATE && this._shape === result.strings) {
696
+ this._instance._update(result.values);
697
+ return;
698
+ }
699
+ const held = (this._held ??= new Map());
700
+ if (this._mode === TEMPLATE) {
701
+ /** Park the live nodes back in their instance's own (empty) fragment. */
702
+ const fragment = this._instance._fragment;
703
+ let node = this._start.nextSibling;
704
+ while (node !== this._end) {
705
+ const next = node.nextSibling;
706
+ fragment.appendChild(node);
707
+ node = next;
708
+ }
709
+ held.set(this._shape, this._instance);
710
+ }
711
+ else if (this._mode !== EMPTY) {
712
+ this._clear();
713
+ }
714
+ const instance = held.get(result.strings) ?? new Instance(getTemplate(result));
715
+ instance._update(result.values);
716
+ this._insert(instance._fragment);
717
+ this._instance = instance;
718
+ this._shape = result.strings;
719
+ this._mode = TEMPLATE;
720
+ }
721
+ /**
722
+ * Creates one list item. A single-root template instance becomes an element-mode item with no
723
+ * markers at all; anything else gets its own start/end marker pair so moves can never dangle.
724
+ */
725
+ _createItem(value, parent, ref) {
726
+ if (value !== null && typeof value === 'object' && value.strings !== undefined) {
727
+ const result = value;
728
+ const template = getTemplate(result);
729
+ const instance = new Instance(template);
730
+ instance._update(result.values);
731
+ const rootNode = instance._fragment.firstChild;
732
+ if (rootNode !== null && rootNode.nodeType === 1 && rootNode.nextSibling === null) {
733
+ parent.insertBefore(rootNode, ref);
734
+ return {
735
+ _key: result.key,
736
+ _element: rootNode,
737
+ _instance: instance,
738
+ _shape: result.strings,
739
+ _part: null,
740
+ };
741
+ }
742
+ /** Multi-root template: markered part, content already instantiated. */
743
+ const part = createMarkeredPart(parent, ref);
744
+ part._instance = instance;
745
+ part._shape = result.strings;
746
+ part._mode = TEMPLATE;
747
+ part._start.parentNode.insertBefore(instance._fragment, part._end);
748
+ return { _key: result.key, _element: null, _instance: null, _shape: null, _part: part };
749
+ }
750
+ const part = createMarkeredPart(parent, ref);
751
+ part._set(value);
752
+ return { _key: value?.key, _element: null, _instance: null, _shape: null, _part: part };
753
+ }
754
+ /** Commits a new value into an existing item, demoting element mode if the shape changed. */
755
+ _updateItem(item, value) {
756
+ if (item._element !== null) {
757
+ if (value !== null && typeof value === 'object' && value.strings === item._shape) {
758
+ item._instance._update(value.values);
759
+ return;
760
+ }
761
+ /** Shape changed: swap the bare element for a markered part in its place. */
762
+ const part = createMarkeredPart(item._element.parentNode, item._element);
763
+ item._element.remove();
764
+ item._element = null;
765
+ item._instance = null;
766
+ item._shape = null;
767
+ (item._part = part)._set(value);
768
+ return;
769
+ }
770
+ item._part._set(value);
771
+ }
772
+ /** The item's first node — its move/removal handle and the insertion reference before it. */
773
+ _firstNode(item) {
774
+ return item._element ?? item._part._start;
775
+ }
776
+ _moveItem(item, ref, parent = this._start.parentNode) {
777
+ if (item._element !== null) {
778
+ parent.insertBefore(item._element, ref);
779
+ return;
780
+ }
781
+ let node = item._part._start;
782
+ const stop = item._part._end.nextSibling;
783
+ while (node !== stop) {
784
+ const next = node.nextSibling;
785
+ parent.insertBefore(node, ref);
786
+ node = next;
787
+ }
788
+ }
789
+ /** Removal is a move into a scratch fragment that is immediately emptied. */
790
+ _dropItem(item) {
791
+ this._moveItem(item, null, SCRATCH);
792
+ SCRATCH.textContent = '';
793
+ }
794
+ _commitList(newValues) {
795
+ if (this._mode !== LIST) {
796
+ if (this._mode !== EMPTY)
797
+ this._clear();
798
+ this._items = [];
799
+ this._keyedList = false;
800
+ this._mode = LIST;
801
+ }
802
+ const count = newValues.length;
803
+ if (count === 0) {
804
+ if (this._items.length) {
805
+ this._clear();
806
+ this._items = [];
807
+ this._mode = LIST;
808
+ }
809
+ return;
810
+ }
811
+ const isKeyed = newValues[0] != null && newValues[0].key !== undefined;
812
+ if (isKeyed !== this._keyedList && this._items.length) {
813
+ this._clear();
814
+ this._items = [];
815
+ this._mode = LIST;
816
+ }
817
+ this._keyedList = isKeyed;
818
+ const items = this._items;
819
+ const parent = this._start.parentNode;
820
+ if (items.length === 0) {
821
+ /** Initial fill builds off-document and lands in one insert. */
822
+ const fragment = doc.createDocumentFragment();
823
+ for (let i = 0; i < count; i++)
824
+ items.push(this._createItem(newValues[i], fragment, null));
825
+ this._insert(fragment);
826
+ return;
827
+ }
828
+ if (!isKeyed) {
829
+ // index mode: update in place, grow at the end, shrink from the end
830
+ const shared = items.length < count ? items.length : count;
831
+ for (let i = 0; i < shared; i++)
832
+ this._updateItem(items[i], newValues[i]);
833
+ if (count > items.length) {
834
+ const fragment = doc.createDocumentFragment();
835
+ for (let i = items.length; i < count; i++)
836
+ items.push(this._createItem(newValues[i], fragment, null));
837
+ this._insert(fragment);
838
+ }
839
+ else if (count < items.length) {
840
+ const last = items[items.length - 1];
841
+ let node = this._firstNode(items[count]);
842
+ const stop = last._element !== null ? last._element.nextSibling : last._part._end.nextSibling;
843
+ while (node !== stop) {
844
+ const next = node.nextSibling;
845
+ parent.removeChild(node);
846
+ node = next;
847
+ }
848
+ items.length = count;
849
+ }
850
+ return;
851
+ }
852
+ /**
853
+ * Zero-allocation fast path for the dominant case: same length, same key order — a pure
854
+ * in-place update (a selection change, a field edit). No key array, no output array, no null
855
+ * checks. Falls through to the full algorithm on the first mismatch; the items already updated
856
+ * re-verify there as cheap no-op compares.
857
+ */
858
+ if (items.length === count) {
859
+ let i = 0;
860
+ while (i < count && items[i]._key === newValues[i].key) {
861
+ this._updateItem(items[i], newValues[i]);
862
+ i++;
863
+ }
864
+ if (i === count)
865
+ return;
866
+ }
867
+ /**
868
+ * Keyed reconciliation — the standard head/tail algorithm (as in lit's `repeat` and Vue):
869
+ * skip matching prefixes and suffixes, detect the two swap shapes directly, and fall back to
870
+ * key maps for arbitrary moves, removals and insertions.
871
+ */
872
+ const oldItems = items;
873
+ const newKeys = new Array(count);
874
+ for (let i = 0; i < count; i++)
875
+ newKeys[i] = newValues[i].key;
876
+ const newItems = new Array(count);
877
+ let oldHead = 0;
878
+ let oldTail = oldItems.length - 1;
879
+ let newHead = 0;
880
+ let newTail = count - 1;
881
+ let newKeyToIndex;
882
+ let oldKeyToIndex;
883
+ const refAt = (i) => i < count && newItems[i] !== undefined ? this._firstNode(newItems[i]) : this._end;
884
+ while (oldHead <= oldTail && newHead <= newTail) {
885
+ if (oldItems[oldHead] === null)
886
+ oldHead++;
887
+ else if (oldItems[oldTail] === null)
888
+ oldTail--;
889
+ else if (oldItems[oldHead]._key === newKeys[newHead]) {
890
+ this._updateItem((newItems[newHead] = oldItems[oldHead]), newValues[newHead]);
891
+ oldHead++;
892
+ newHead++;
893
+ }
894
+ else if (oldItems[oldTail]._key === newKeys[newTail]) {
895
+ this._updateItem((newItems[newTail] = oldItems[oldTail]), newValues[newTail]);
896
+ oldTail--;
897
+ newTail--;
898
+ }
899
+ else if (oldItems[oldHead]._key === newKeys[newTail]) {
900
+ const item = oldItems[oldHead];
901
+ this._moveItem(item, refAt(newTail + 1));
902
+ this._updateItem(item, newValues[newTail]);
903
+ newItems[newTail] = item;
904
+ oldHead++;
905
+ newTail--;
906
+ }
907
+ else if (oldItems[oldTail]._key === newKeys[newHead]) {
908
+ const item = oldItems[oldTail];
909
+ this._moveItem(item, this._firstNode(oldItems[oldHead]));
910
+ this._updateItem(item, newValues[newHead]);
911
+ newItems[newHead] = item;
912
+ oldTail--;
913
+ newHead++;
914
+ }
915
+ else {
916
+ if (newKeyToIndex === undefined) {
917
+ newKeyToIndex = new Map();
918
+ for (let i = newHead; i <= newTail; i++)
919
+ newKeyToIndex.set(newKeys[i], i);
920
+ oldKeyToIndex = new Map();
921
+ for (let i = oldHead; i <= oldTail; i++) {
922
+ if (oldItems[i] !== null)
923
+ oldKeyToIndex.set(oldItems[i]._key, i);
924
+ }
925
+ }
926
+ if (!newKeyToIndex.has(oldItems[oldHead]._key)) {
927
+ this._dropItem(oldItems[oldHead]);
928
+ oldHead++;
929
+ }
930
+ else if (!newKeyToIndex.has(oldItems[oldTail]._key)) {
931
+ this._dropItem(oldItems[oldTail]);
932
+ oldTail--;
933
+ }
934
+ else {
935
+ const oldIndex = oldKeyToIndex.get(newKeys[newHead]);
936
+ if (oldIndex === undefined) {
937
+ newItems[newHead] = this._createItem(newValues[newHead], parent, this._firstNode(oldItems[oldHead]));
938
+ }
939
+ else {
940
+ const item = oldItems[oldIndex];
941
+ this._moveItem(item, this._firstNode(oldItems[oldHead]));
942
+ this._updateItem(item, newValues[newHead]);
943
+ newItems[newHead] = item;
944
+ oldItems[oldIndex] = null;
945
+ }
946
+ newHead++;
947
+ }
948
+ }
949
+ }
950
+ while (newHead <= newTail) {
951
+ newItems[newHead] = this._createItem(newValues[newHead], parent, refAt(newTail + 1));
952
+ newHead++;
953
+ }
954
+ while (oldHead <= oldTail) {
955
+ const item = oldItems[oldHead++];
956
+ if (item !== null)
957
+ this._dropItem(item);
958
+ }
959
+ this._items = newItems;
960
+ }
961
+ }
962
+ const rootParts = new WeakMap();
963
+ /**
964
+ * Renders a template result into a container. Slots into Vera via `setRenderer(render)`; core's
965
+ * built-in `html` tag already produces the accepted shape, so no `setHtml` call is required —
966
+ * though lit-html's `html` also works, its results being structurally identical.
967
+ *
968
+ * HYDRATION lives in `@verajs/renderer/hydrate` — a drop-in superset entry whose `render` adopts
969
+ * existing server-rendered children on first render. SSR apps import from there instead of here;
970
+ * this entry carries zero hydration code.
971
+ */
972
+ const render$1 = (result, container) => {
973
+ let part = rootParts.get(container);
974
+ if (part === undefined) {
975
+ const marker = comment();
976
+ container.appendChild(marker);
977
+ rootParts.set(container, (part = new ChildPart(marker, null)));
978
+ }
979
+ part._set(result);
980
+ };
981
+
982
+ /**
983
+ * @verajs/renderer/hydrate — markerless adoption of server-rendered DOM.
984
+ *
985
+ * Importing this module (once, anywhere) arms hydration: the renderer's first render into a
986
+ * container that already has children adopts them as server output of the same template. Without
987
+ * this import the renderer never carries adoption code — non-SSR apps pay nothing.
988
+ *
989
+ * The server serializer (@verajs/ssr/vera) emits the SAME static strings the renderer parses into
990
+ * its canonical template, so server DOM and canonical fragment diverge only at value slots — and
991
+ * at adoption time the values are known. Adoption walks both trees in lockstep: statics must
992
+ * match byte-for-byte (else bail), and at each slot the live text is split so the renderer's own
993
+ * anchors (primed texts, marker comments) are installed into the adopted DOM. Server HTML stays
994
+ * free of framework comments; the client repairs its anchors in. Any mismatch clears the
995
+ * container (preserving `<style vera-styles>` tags) and the caller renders fresh — correctness
996
+ * never depends on the server markup.
997
+ *
998
+ * This entry re-exports the public API, so a CDN importmap can point `@verajs/renderer` at the
999
+ * hydrate bundle and nothing else changes.
1000
+ */
1001
+ // The server serializer (@verajs/ssr/vera) emits the SAME static strings this module parses into
1002
+ // its canonical template, so server DOM and canonical fragment diverge only at value slots — and
1003
+ // at adoption time the values are known. Adoption walks both trees in lockstep: statics must
1004
+ // match byte-for-byte (else bail), and at each slot the live text is split so the renderer's own
1005
+ // anchors (primed texts, marker comments) are installed into the adopted DOM. Server HTML stays
1006
+ // free of framework comments; the client repairs its anchors in. Any mismatch abandons adoption
1007
+ // and falls back to a clean first render — correctness never depends on the server markup.
1008
+ /** Internal bail signal — never escapes `tryAdopt`. */
1009
+ const MISMATCH = {};
1010
+ /** Splits mid-text cursors onto a node boundary and returns the node now at the cursor. */
1011
+ const cursorSplit = (cursor) => {
1012
+ if (cursor.offset > 0) {
1013
+ cursor.node = cursor.node.splitText(cursor.offset);
1014
+ cursor.offset = 0;
1015
+ }
1016
+ return cursor.node;
1017
+ };
1018
+ /** Consumes exactly `text` from the live cursor; anything else is a mismatch. */
1019
+ const expectText = (cursor, text) => {
1020
+ let need = text;
1021
+ while (need.length > 0) {
1022
+ const node = cursor.node;
1023
+ if (node === null || node.nodeType !== 3)
1024
+ throw MISMATCH;
1025
+ const data = node.data;
1026
+ const available = data.length - cursor.offset;
1027
+ if (available === 0) {
1028
+ cursor.node = node.nextSibling;
1029
+ cursor.offset = 0;
1030
+ continue;
1031
+ }
1032
+ const take = available < need.length ? available : need.length;
1033
+ if (data.slice(cursor.offset, cursor.offset + take) !== need.slice(0, take))
1034
+ throw MISMATCH;
1035
+ need = need.slice(take);
1036
+ cursor.offset += take;
1037
+ if (cursor.offset === data.length) {
1038
+ cursor.node = node.nextSibling;
1039
+ cursor.offset = 0;
1040
+ }
1041
+ }
1042
+ };
1043
+ /** Claims the value's rendered text as a standalone node (splitting as needed) and returns it. */
1044
+ const claimValueText = (cursor, text) => {
1045
+ const at = cursorSplit(cursor);
1046
+ if (text === '') {
1047
+ /** Nothing was rendered — install a fresh primed anchor at the cursor. */
1048
+ const primed = doc.createTextNode('');
1049
+ cursor.parent.insertBefore(primed, at);
1050
+ return primed;
1051
+ }
1052
+ if (at === null || at.nodeType !== 3)
1053
+ throw MISMATCH;
1054
+ let node = at;
1055
+ if (node.data.length > text.length)
1056
+ node.splitText(text.length);
1057
+ if (node.data !== text)
1058
+ throw MISMATCH;
1059
+ cursor.node = node.nextSibling;
1060
+ cursor.offset = 0;
1061
+ return node;
1062
+ };
1063
+ /** Per-template canonical node list (ELEMENT | TEXT order), cached — adoption of a 100-row list
1064
+ * hits the same template 100 times. */
1065
+ const canonicalCache = new WeakMap();
1066
+ const canonicalNodes = (template) => {
1067
+ let nodes = canonicalCache.get(template);
1068
+ if (nodes === undefined) {
1069
+ nodes = [];
1070
+ instanceWalker.currentNode = template._element.content;
1071
+ let node;
1072
+ while ((node = instanceWalker.nextNode()) !== null)
1073
+ nodes.push(node);
1074
+ canonicalCache.set(template, nodes);
1075
+ }
1076
+ return nodes;
1077
+ };
1078
+ /** Adopts one canonical node (and, for elements, its subtree) against the live cursor. */
1079
+ const adoptNode = (canonical, cursor, state) => {
1080
+ state._nodeIndex++;
1081
+ const parts = state._template._parts;
1082
+ if (canonical.nodeType === 3) {
1083
+ /** A primed empty text is a child slot; any other text is a static to match. */
1084
+ let isSlot = false;
1085
+ while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
1086
+ isSlot = true;
1087
+ state._partIndex++;
1088
+ adoptSlot(cursor, state._values[state._valueIndex++], state._out);
1089
+ drainIgnored(state);
1090
+ }
1091
+ if (!isSlot)
1092
+ expectText(cursor, canonical.data);
1093
+ return;
1094
+ }
1095
+ /** Element: same tag, commit its attribute parts live, then descend children in lockstep. */
1096
+ const live = cursorSplit(cursor);
1097
+ if (live === null || live.nodeType !== 1)
1098
+ throw MISMATCH;
1099
+ if (live.localName !== canonical.localName)
1100
+ throw MISMATCH;
1101
+ while (state._partIndex < parts.length && parts[state._partIndex]._index === state._nodeIndex) {
1102
+ const templatePart = parts[state._partIndex++];
1103
+ const attrPart = new AttrPart(live, templatePart._name, templatePart._statics);
1104
+ state._out.push(attrPart);
1105
+ /** A normal commit: attributes re-set (idempotent), properties applied, listeners attached,
1106
+ * refs fired — the server could only mirror form state; the client wires behavior. */
1107
+ state._valueIndex = attrPart._commit(state._values, state._valueIndex);
1108
+ drainIgnored(state);
1109
+ }
1110
+ const inner = { parent: live, node: live.firstChild, offset: 0 };
1111
+ let child = canonical.firstChild;
1112
+ while (child !== null) {
1113
+ if (child.nodeType === 1 || child.nodeType === 3)
1114
+ adoptNode(child, inner, state);
1115
+ child = child.nextSibling;
1116
+ }
1117
+ /** Leftover live children the template does not account for = not our markup. */
1118
+ if (inner.node !== null && !(inner.node.nodeType === 3 && inner.node.data === '' && inner.node.nextSibling === null))
1119
+ throw MISMATCH;
1120
+ cursor.node = live.nextSibling;
1121
+ cursor.offset = 0;
1122
+ };
1123
+ const drainIgnored = (state) => {
1124
+ const parts = state._template._parts;
1125
+ while (state._partIndex < parts.length && parts[state._partIndex]._type === IGNORED) {
1126
+ state._out.push(IGNORED_PART);
1127
+ state._valueIndex++;
1128
+ state._partIndex++;
1129
+ }
1130
+ };
1131
+ /** Adopts one child slot's rendered content, producing the part that will own it. */
1132
+ const adoptSlot = (cursor, rawValue, out) => {
1133
+ const heldResult = rawValue?.$h;
1134
+ const value = heldResult !== undefined ? heldResult : rawValue;
1135
+ if (value != null && typeof value !== 'object') {
1136
+ /** Primitive: claim its text and bind the fast TextPart, committed state included. */
1137
+ const textPart = new TextPart(claimValueText(cursor, toText(value)));
1138
+ textPart._value = value;
1139
+ out.push(textPart);
1140
+ return;
1141
+ }
1142
+ /** Structured content gets a markered ChildPart wrapped around whatever it rendered. */
1143
+ const start = comment();
1144
+ cursor.parent.insertBefore(start, cursorSplit(cursor));
1145
+ const part = new ChildPart(start, null);
1146
+ if (value == null) ;
1147
+ else if (isTemplateResult(value)) {
1148
+ part._instance = adoptInstance(getTemplate(value), value.values, cursor);
1149
+ part._shape = value.strings;
1150
+ part._mode = TEMPLATE;
1151
+ }
1152
+ else {
1153
+ const list = Array.isArray(value) ? value : [...value];
1154
+ const items = [];
1155
+ for (const entry of list)
1156
+ items.push(adoptItem(cursor, entry));
1157
+ part._items = items;
1158
+ part._keyedList = list.length > 0 && list[0]?.key !== undefined;
1159
+ part._mode = LIST;
1160
+ }
1161
+ const end = comment();
1162
+ cursor.parent.insertBefore(end, cursorSplit(cursor));
1163
+ part._end = end;
1164
+ out.push(part);
1165
+ };
1166
+ /** Adopts one list item — element mode for single-root templates, markered otherwise. */
1167
+ const adoptItem = (cursor, value) => {
1168
+ if (value !== null && typeof value === 'object' && value.strings !== undefined) {
1169
+ const result = value;
1170
+ const template = getTemplate(result);
1171
+ const content = template._element.content;
1172
+ const root = content.firstChild;
1173
+ if (root !== null && root.nodeType === 1 && root.nextSibling === null) {
1174
+ const liveRoot = cursorSplit(cursor);
1175
+ const instance = adoptInstance(template, result.values, cursor);
1176
+ return {
1177
+ _key: result.key,
1178
+ _element: liveRoot,
1179
+ _instance: instance,
1180
+ _shape: result.strings,
1181
+ _part: null,
1182
+ };
1183
+ }
1184
+ const start = comment();
1185
+ cursor.parent.insertBefore(start, cursorSplit(cursor));
1186
+ const instance = adoptInstance(template, result.values, cursor);
1187
+ const end = comment();
1188
+ cursor.parent.insertBefore(end, cursorSplit(cursor));
1189
+ const part = new ChildPart(start, end);
1190
+ part._instance = instance;
1191
+ part._shape = result.strings;
1192
+ part._mode = TEMPLATE;
1193
+ return { _key: result.key, _element: null, _instance: null, _shape: null, _part: part };
1194
+ }
1195
+ /** Non-template item: markered part adopting its content like a nested slot. */
1196
+ const out = [];
1197
+ adoptSlot(cursor, value, out);
1198
+ return { _key: value?.key, _element: null, _instance: null, _shape: null, _part: out[0] };
1199
+ };
1200
+ /** Builds an Instance whose parts are bound to LIVE nodes, consuming them from the cursor. */
1201
+ const adoptInstance = (template, values, cursor) => {
1202
+ const instance = Object.create(Instance.prototype);
1203
+ instance._parts = [];
1204
+ instance._fragment = doc.createDocumentFragment();
1205
+ const state = {
1206
+ _template: template,
1207
+ _values: values,
1208
+ _valueIndex: 0,
1209
+ _partIndex: 0,
1210
+ _nodeIndex: -1,
1211
+ _out: instance._parts,
1212
+ };
1213
+ drainIgnored(state);
1214
+ /** Cached walk exists for repeated templates; the recursion itself visits in the same
1215
+ * ELEMENT | TEXT document order the instance walker uses. */
1216
+ canonicalNodes(template);
1217
+ let child = template._element.content.firstChild;
1218
+ while (child !== null) {
1219
+ if (child.nodeType === 1 || child.nodeType === 3)
1220
+ adoptNode(child, cursor, state);
1221
+ child = child.nextSibling;
1222
+ }
1223
+ drainIgnored(state);
1224
+ if (state._partIndex !== template._parts.length)
1225
+ throw MISMATCH;
1226
+ return instance;
1227
+ };
1228
+ /**
1229
+ * Attempts to adopt a container's existing (server-rendered) children for `result`. Returns the
1230
+ * root part on success; null on any mismatch, leaving the caller to clean-render. Leading
1231
+ * `<style vera-styles>` tags (the SSR style serialization) are skipped and preserved.
1232
+ */
1233
+ const tryAdopt = (result, container) => {
1234
+ /** Only the SSR-serialized style tags are skipped — templates may legitimately start with
1235
+ * whitespace or even their own static `<style>`, which must align against the canonical walk. */
1236
+ let first = container.firstChild;
1237
+ while (first !== null && first.nodeType === 1 && first.hasAttribute('vera-styles')) {
1238
+ first = first.nextSibling;
1239
+ }
1240
+ const start = comment();
1241
+ container.insertBefore(start, first);
1242
+ try {
1243
+ const cursor = { parent: container, node: start.nextSibling, offset: 0 };
1244
+ const instance = adoptInstance(getTemplate(result), result.values, cursor);
1245
+ if (cursor.node !== null)
1246
+ throw MISMATCH;
1247
+ const part = new ChildPart(start, null);
1248
+ part._instance = instance;
1249
+ part._shape = result.strings;
1250
+ part._mode = TEMPLATE;
1251
+ return part;
1252
+ }
1253
+ catch (error) {
1254
+ if (error !== MISMATCH)
1255
+ throw error;
1256
+ start.remove();
1257
+ return null;
1258
+ }
1259
+ };
1260
+ /** Mismatch cleanup lives here, not in the slim renderer: clear all but the SSR style tags. */
1261
+ const clearPreservingStyles = (container) => {
1262
+ let node = container.firstChild;
1263
+ while (node !== null) {
1264
+ const next = node.nextSibling;
1265
+ if (!(node.nodeType === 1 && node.hasAttribute('vera-styles')))
1266
+ container.removeChild(node);
1267
+ node = next;
1268
+ }
1269
+ };
1270
+ /**
1271
+ * The hydrating `render`: a drop-in for the base entry's. The first render into a container that
1272
+ * already has children adopts them; any mismatch clears (keeping `<style vera-styles>`) and falls
1273
+ * through to a clean base render. After the first render, this IS the base render.
1274
+ */
1275
+ const render = (result, container) => {
1276
+ if (!rootParts.has(container) &&
1277
+ container.firstChild !== null &&
1278
+ result !== null &&
1279
+ typeof result === 'object' &&
1280
+ isTemplateResult(result)) {
1281
+ const part = tryAdopt(result, container);
1282
+ if (part !== null) {
1283
+ rootParts.set(container, part);
1284
+ return;
1285
+ }
1286
+ clearPreservingStyles(container);
1287
+ }
1288
+ render$1(result, container);
1289
+ };
1290
+
1291
+ export { hold, keyed, render };
1292
+ //# sourceMappingURL=vera-renderer-hydrate.js.map