@verajs/ssr 0.2.0 → 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 (63) hide show
  1. package/README.md +510 -373
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +98 -0
  4. package/dist/vera/escaping.d.ts +142 -0
  5. package/dist/vera/escaping.js +267 -0
  6. package/dist/vera/events.d.ts +41 -0
  7. package/dist/vera/events.js +162 -0
  8. package/dist/vera/frames.d.ts +38 -0
  9. package/dist/vera/frames.js +195 -0
  10. package/dist/vera/index.d.ts +48 -0
  11. package/dist/vera/index.js +480 -0
  12. package/{types → dist/vera}/nodes.d.ts +397 -300
  13. package/dist/vera/nodes.js +2322 -0
  14. package/dist/vera/parse.d.ts +37 -0
  15. package/dist/vera/parse.js +390 -0
  16. package/dist/vera/reflections.d.ts +566 -0
  17. package/dist/vera/reflections.js +820 -0
  18. package/dist/vera/registry.d.ts +14 -0
  19. package/{src → dist}/vera/registry.js +5 -1
  20. package/dist/vera/report.d.ts +27 -0
  21. package/dist/vera/report.js +56 -0
  22. package/dist/vera/scan.d.ts +37 -0
  23. package/dist/vera/scan.js +143 -0
  24. package/dist/vera/select.d.ts +40 -0
  25. package/dist/vera/select.js +261 -0
  26. package/dist/vera/serializer.d.ts +39 -0
  27. package/dist/vera/serializer.js +1372 -0
  28. package/dist/vera/shim.d.ts +42 -0
  29. package/dist/vera/shim.js +853 -0
  30. package/dist/vera/slots.d.ts +5 -0
  31. package/dist/vera/slots.js +104 -0
  32. package/dist/vera/stylesheets.d.ts +62 -0
  33. package/dist/vera/stylesheets.js +180 -0
  34. package/dist/vera/tokenizer.d.ts +32 -0
  35. package/dist/vera/tokenizer.js +528 -0
  36. package/dist/vera/types.d.ts +117 -0
  37. package/dist/vera/views.d.ts +63 -0
  38. package/dist/vera/views.js +245 -0
  39. package/package.json +12 -13
  40. package/src/vera/escaping.js +0 -135
  41. package/src/vera/events.js +0 -164
  42. package/src/vera/frames.js +0 -102
  43. package/src/vera/index.js +0 -1171
  44. package/src/vera/nodes.js +0 -2270
  45. package/src/vera/parse.js +0 -381
  46. package/src/vera/reflections.js +0 -811
  47. package/src/vera/select.js +0 -234
  48. package/src/vera/serializer.js +0 -928
  49. package/src/vera/shim.js +0 -761
  50. package/src/vera/stylesheets.js +0 -155
  51. package/src/vera/views.js +0 -240
  52. package/types/escaping.d.ts +0 -27
  53. package/types/events.d.ts +0 -4
  54. package/types/frames.d.ts +0 -12
  55. package/types/index.d.ts +0 -13
  56. package/types/parse.d.ts +0 -19
  57. package/types/reflections.d.ts +0 -657
  58. package/types/registry.d.ts +0 -8
  59. package/types/select.d.ts +0 -5
  60. package/types/serializer.d.ts +0 -26
  61. package/types/shim.d.ts +0 -23
  62. package/types/stylesheets.d.ts +0 -53
  63. package/types/views.d.ts +0 -26
@@ -0,0 +1,2322 @@
1
+ /**
2
+ * The server's DOM nodes: an element, a shadow root, a fragment, and the container they share.
3
+ *
4
+ * These hold their children as a **string**. Nothing in this package parses HTML, so queries answer
5
+ * emptily and `insertBefore`/`cloneNode` are deliberately absent — they need a tree, and faking them
6
+ * would misplace content silently. Everything else a real node exposes is either here or listed in
7
+ * `tests/dom-surface.mjs` as out of scope with a reason, and both directions are enforced: the code
8
+ * that runs on this DOM is *user* code, and for years every missing member was found by someone
9
+ * tripping over it.
10
+ */
11
+ import { interfaceFor } from './reflections.js';
12
+ import { escapeHtml, escapeRawText, escapeStyleText, leadingNewline, normalizeNewlines, RAW_TEXT_ELEMENTS, RCDATA_ELEMENTS, VOID_ELEMENTS } from './escaping.js';
13
+ import { decode, parseFragment } from './parse.js';
14
+ import { addListener, removeListener, dispatch } from './events.js';
15
+ import * as select from './select.js';
16
+ import { datasetView, styleView, tokenListView } from './views.js';
17
+ import { currentRenderingTag, StyleSheetShim, toSheetSequence } from './stylesheets.js';
18
+ import { constructible, registry } from './registry.js';
19
+ import { PROSE } from './diagnostics.js';
20
+ import { once, ssrWarning } from './report.js';
21
+ /**
22
+ * The HTML namespace, which is what `createElement` produces and what almost everything here is.
23
+ *
24
+ * It is load-bearing rather than decorative: **an HTML element folds tag and attribute names to
25
+ * lower case, and an element in any other namespace does not.** `svg.setAttribute('viewBox', …)`
26
+ * has to keep its capital B or the viewport is ignored, while `div.setAttribute('Data-Flag', …)`
27
+ * has to lose its capitals or the `getAttribute('data-flag')` beside it reads `null`.
28
+ */
29
+ const HTML_NS = 'http://www.w3.org/1999/xhtml';
30
+ /**
31
+ * The characters that make a name unusable, checked so the shim refuses what the platform refuses.
32
+ *
33
+ * **Deliberately the engines' rule and not jsdom's.** jsdom implements the XML `Name` production and
34
+ * rejects `a(b)`, `a|b`, `a?b` and about fifty other shapes that every real engine accepts —
35
+ * `tests/browser/spread-names.test.js` records that the engines refuse exactly `a b`, `a>b`, `a=b`
36
+ * and `a/b`, and `CLAUDE.md` records the false finding that came of trusting jsdom here. So this is
37
+ * whitespace, `>`, `=`, `/` and controls, plus the empty string: strictly the set that cannot survive
38
+ * being written into a tag, and nothing invented on top.
39
+ */
40
+ const UNUSABLE_IN_A_NAME = /[\0-\x20/>=\x7f]/;
41
+ /**
42
+ * A tag name is checked slightly harder, because a quote or a `<` inside one **does** break the
43
+ * markup where the same character inside an attribute name does not.
44
+ */
45
+ const UNUSABLE_IN_A_TAG = /[\0-\x20"'<>/=\x7f]/;
46
+ /**
47
+ * Declarative shadow DOM can carry more than the mode, and the extras are **not recoverable on the
48
+ * client**: `attachShadow` reuses a declarative root and ignores the options it is handed, so a
49
+ * component asking for `delegatesFocus: true` over server-rendered markup that omitted it keeps
50
+ * `delegatesFocus === false` for the life of the page. Measured in Chromium. Focus delegation is an
51
+ * accessibility behavior, so losing it silently under SSR is the kind of difference that never gets
52
+ * reported — it just works worse.
53
+ *
54
+ * `slotAssignment` has no declarative form at all; a component that needs it cannot be faithfully
55
+ * server-rendered, and the README says so rather than pretending.
56
+ */
57
+ const SHADOW_ATTRIBUTES = [
58
+ ['delegatesFocus', 'shadowrootdelegatesfocus'],
59
+ ['clonable', 'shadowrootclonable'],
60
+ ['serializable', 'shadowrootserializable'],
61
+ ];
62
+ /**
63
+ * What an element and a shadow root both are: something that holds children as markup and can be
64
+ * appended to, queried and listened to.
65
+ *
66
+ * Shared because they kept drifting. `ShadowRootShim` was built for the renderer and `ElementShim`
67
+ * for core, so each was short of a different set of members — the router threw on
68
+ * `shadowRoot.addEventListener`, component code threw on `element.dataset`, and every gap was found
69
+ * by probing rather than by the two being one thing. Anything a container does belongs here.
70
+ *
71
+ * Queries answer emptily because this holds a **string**, not a tree; nothing in this package parses
72
+ * HTML. `insertBefore` and `cloneNode` are deliberately absent for the same reason — they need a
73
+ * tree, and faking them would misplace content silently.
74
+ *
75
+ * Events come from Node's own `EventTarget`, so `once`, `handleEvent`, `event.target`,
76
+ * `stopImmediatePropagation` and the return value of `dispatchEvent` are all correct without this
77
+ * package implementing any of them. They used to be no-ops that reported every event delivered, so
78
+ * anything a component decided from its own event — a control reading back its change, a callback
79
+ * dispatched at mount, a `preventDefault` deciding whether to proceed — took one branch here and
80
+ * the other in a browser. **Bubbling is still absent**: with children held as a string there is no
81
+ * ancestor chain to walk, so an event reaches its own element's listeners and stops.
82
+ */
83
+ /**
84
+ * One entry's markup. A retained node serializes itself **at output time**, which is the entire
85
+ * point of keeping it: a mutation made after `appendChild` is still on the node when this runs.
86
+ * The expression is the one `appendChild` used to inline, unchanged, so the bytes are identical.
87
+ */
88
+ export const serializeElement = (element) => {
89
+ const open = element.openTag();
90
+ if (VOID_ELEMENTS.has(element.localName))
91
+ return open;
92
+ const inner = element.innerHTML;
93
+ /**
94
+ * Content that starts with a line feed gets one more for the parser to take (`NEWLINE_TAKERS`) — unless the open
95
+ * tag is parsed source still carrying the one the parser took from it, which is the only way it ends in anything
96
+ * but `>` (see `parseFragment`). So the markup round-trips: what parses back is this element's content.
97
+ */
98
+ const name = element.localName;
99
+ /** Named, not hashed: this runs for every element written. */
100
+ const guard = (name === 'pre' || name === 'textarea' || name === 'listing') && open.charCodeAt(open.length - 1) === 62 && leadingNewline(inner, 0) !== 0;
101
+ const close = element._sourceCloseTag ?? `</${name}>`;
102
+ /** Two plain joins: an empty string joined into every element cost a server DOM's serialization ~2% (measured). */
103
+ return guard ? open + '\n' + inner + close : open + inner + close;
104
+ };
105
+ const serializeEntry = (entry) => typeof entry === 'string'
106
+ ? entry
107
+ : typeof entry?.markup === 'function'
108
+ ? entry.markup()
109
+ : (entry?.innerHTML ?? '');
110
+ /**
111
+ * The attribute list, with the `NamedNodeMap` methods on it. A free function taking the element so
112
+ * nothing has to alias `this`, and one cast because the methods are added to an array.
113
+ */
114
+ const namedNodeMap = (element) => {
115
+ const list = ([...element._attributes].map(([name, value]) => ({
116
+ name,
117
+ value,
118
+ localName: name,
119
+ namespaceURI: null,
120
+ ownerElement: element,
121
+ })));
122
+ list.getNamedItem = (name) => list.find((entry) => entry.name === `${name}`.toLowerCase()) ?? null;
123
+ list.getNamedItemNS = (_namespace, name) => list.getNamedItem(name);
124
+ list.item = (index) => list[index] ?? null;
125
+ list.setNamedItem = (attribute) => {
126
+ const previous = list.getNamedItem(attribute?.name);
127
+ element.setAttribute(attribute.name, attribute.value);
128
+ return previous;
129
+ };
130
+ list.removeNamedItem = (name) => {
131
+ const previous = list.getNamedItem(name);
132
+ if (!previous)
133
+ throw new DOMException(`Failed to execute 'removeNamedItem' on 'NamedNodeMap': No item with name '${name}' was found.`, 'NotFoundError');
134
+ element.removeAttribute(name);
135
+ return previous;
136
+ };
137
+ return list;
138
+ };
139
+ /** A node this DOM keeps by reference, rather than inlining its markup — see `appendChild`. */
140
+ const isNode = (value) => typeof value?.markup === 'function';
141
+ /**
142
+ * The slot a node asks for. Text has no attributes, so it can only take the default slot.
143
+ * A free function so neither caller has to alias `this` — see `equalNodes` for the same reason.
144
+ *
145
+ * **`null` means NOT SLOTTABLE, and that is the platform's own line.** Only elements and text are
146
+ * slottables; a comment is never assigned to a slot (native `assignedNodes()` omits it, measured).
147
+ * This answered `''` for everything that was not an element, which put COMMENTS in the default
148
+ * slot's assignment — a server answering a question the client and the platform answer differently.
149
+ *
150
+ * **A deliberate twin of `slotNameOf` in `@verajs/renderer/slots`, byte-for-byte the same rule.**
151
+ * Independent packages (CODE-PRINCIPLES #6) and ssr must not import the renderer at runtime, so
152
+ * the rule is copied rather than shared — recorded here, as `@verajs/cms`'s `escapeHtml` records
153
+ * the same choice, so nobody "fixes" it into a dependency and so a change to one is known to need
154
+ * the other. `tests/ssr-slot-assignment-parity.test.mjs` fails if they ever disagree.
155
+ */
156
+ const slotNameOf = (node) => node.nodeType === 3 ? '' : node.nodeType === 1 ? (node.getAttribute('slot') ?? '') : null;
157
+ /** For the server's distributor (`slots.ts`) — an alias, so this module's own reads stay module-local. */
158
+ export const slotName = slotNameOf;
159
+ /**
160
+ * **What a `<slot>` projects.** A slot shows the host's light-DOM children whose `slot` attribute
161
+ * names it — the default slot taking everything unnamed. That is answerable on a server: the host,
162
+ * its children and their names are all here. It answered nothing, so a component inspecting what it
163
+ * had been given found an empty list and rendered its fallback content, on the server only.
164
+ *
165
+ * `flatten` falls back to the slot's own children when nothing is assigned, which is what makes it
166
+ * the useful form: it answers "what will actually be shown here".
167
+ */
168
+ const assignedTo = (slot, options) => {
169
+ const root = slot.getRootNode();
170
+ const host = root?._host;
171
+ if (!host)
172
+ return options?.flatten ? nodesOf(slot) : [];
173
+ const name = slot.getAttribute('name') ?? '';
174
+ /** `slotNameOf` answers `null` for a non-slottable, which matches no name — comments out. */
175
+ const assigned = nodesOf(host).filter((node) => slotNameOf(node) === name);
176
+ return assigned.length || !options?.flatten ? assigned : nodesOf(slot);
177
+ };
178
+ /**
179
+ * **`before`, `after` and `replaceWith`** — the `ChildNode` trio, which every one of these classes
180
+ * needs and none can inherit from the other: text and comments extend `EventTarget` directly rather
181
+ * than the container. Written once here and delegated to, rather than three times over.
182
+ *
183
+ * A plain string becomes a text node, which is what the spec says and what makes
184
+ * `node.after('some text')` do the obvious thing instead of nothing.
185
+ */
186
+ const insertAround = (node, inserted, where) => {
187
+ const parent = node._parent;
188
+ if (!parent)
189
+ return;
190
+ /** A node with a parent is always one of the child kinds — shadow roots and fragments never get one. */
191
+ const reference = where === 'after' ? node.nextSibling : node;
192
+ for (const one of inserted)
193
+ parent.insertBefore(one instanceof NodeBaseShim ? one : new TextShim(one), reference);
194
+ /**
195
+ * **Unless the node replaced itself.** `x.replaceWith(x)` inserted `x` back where it was and then
196
+ * removed it, so a node replaced by itself **disappeared** — measured against jsdom, which leaves
197
+ * it in place.
198
+ *
199
+ * Same root cause as the `after` case above: this helper treated `node` and `inserted` as disjoint,
200
+ * and every operation here allows them to overlap.
201
+ */
202
+ if (where === 'replace' && !inserted.includes(node))
203
+ parent.removeChild(node);
204
+ };
205
+ /**
206
+ * **Structural equality, as the spec defines it** — type, name, attributes as a set, and children
207
+ * pairwise. `isEqualNode` used to compare identity, which is what `isSameNode` is for, so two
208
+ * elements built identically reported themselves different.
209
+ *
210
+ * A free function rather than a method so neither node has to be `this`: a shadow root and a
211
+ * fragment are containers with no attributes and no `nodeName` of their own, and reaching for those
212
+ * through `this` needs a cast that the lint rules and the type-checker disagree about.
213
+ */
214
+ const equalNodes = (a, b) => {
215
+ if (a === b)
216
+ return true;
217
+ if (!b || b.nodeType !== a.nodeType || b.nodeName !== a.nodeName)
218
+ return false;
219
+ const mine = a._attributes ?? new Map();
220
+ const theirs = b._attributes ?? new Map();
221
+ if (mine.size !== theirs.size)
222
+ return false;
223
+ for (const [name, value] of mine)
224
+ if (theirs.get(name) !== value)
225
+ return false;
226
+ const ours = nodesOf(a);
227
+ const others = nodesOf(b);
228
+ if (ours.length !== others.length)
229
+ return false;
230
+ return ours.every((child, index) => child.isEqualNode(others[index]));
231
+ };
232
+ /**
233
+ * **Walks the tree**, as `textContent` is defined to. It used to strip tags out of the serialized
234
+ * markup with a regular expression and undo the numeric escapes, which answered `a &amp; b` for an
235
+ * element holding the text `a & b` — the entity spellings this package does not itself emit came
236
+ * back raw. A comment contributes nothing, which is what the platform says.
237
+ *
238
+ * A chunk of markup this DOM could not parse has no nodes to walk, so it keeps the old treatment.
239
+ */
240
+ const textOf = (container) => {
241
+ parseChunks(container);
242
+ let out = '';
243
+ for (const entry of container._entries) {
244
+ if (typeof entry === 'string')
245
+ out += entry.replace(/<[^>]*>/gu, '').replace(/&#(\d+);/gu, (_, code) => String.fromCharCode(Number(code)));
246
+ else if (entry.nodeType === 8)
247
+ continue;
248
+ else
249
+ out += entry.textContent;
250
+ }
251
+ return out;
252
+ };
253
+ /**
254
+ * The retained nodes among the entries.
255
+ *
256
+ * **Markup supplied as a string is not nodes**, and this is where that shows. Until a parser
257
+ * arrives — a later, deliberately separate step — a container filled by `innerHTML`
258
+ * or by the `children:` option has markup and no node view, so asking for one answers emptily —
259
+ * which is a wrong answer, and says so rather than being discovered later as a defect.
260
+ */
261
+ /**
262
+ * **Parse the markup chunks, but only keep the result if it reproduces them exactly.**
263
+ *
264
+ * The parse is discarded unless re-serializing it is byte-identical to the string it came from, so
265
+ * reading `children` can never change what the page renders — the worst case is the behavior that
266
+ * was there before, plus a warning. That check is also what makes a parser defect cheap: a wrong
267
+ * tree that does not round-trip is thrown away rather than served.
268
+ */
269
+ const parseChunks = (container) => {
270
+ if (container._parsed)
271
+ return;
272
+ container._parsed = true;
273
+ const entries = [];
274
+ let gained = false;
275
+ for (const entry of container._entries) {
276
+ if (typeof entry !== 'string') {
277
+ entries.push(entry);
278
+ continue;
279
+ }
280
+ const parsed = parseFragment(entry, {
281
+ element: (name) => build(name),
282
+ text: (data) => new TextShim(data),
283
+ comment: (data) => new CommentShim(data),
284
+ });
285
+ let round = '';
286
+ if (parsed)
287
+ for (const node of parsed)
288
+ round += serializeEntry(node);
289
+ if (!parsed || round !== entry) {
290
+ entries.push(entry);
291
+ continue;
292
+ }
293
+ for (const node of parsed)
294
+ if (typeof node !== 'string')
295
+ node._parent = container;
296
+ entries.push(...parsed);
297
+ gained = true;
298
+ }
299
+ if (gained)
300
+ container._entries = entries;
301
+ };
302
+ /**
303
+ * **A collection is a plain array here, and that costs `item()` unless it is given one.**
304
+ *
305
+ * `childNodes`, `children` and the query methods answer with arrays rather than live `NodeList`s and
306
+ * `HTMLCollection`s. That is deliberate and the reason is good — there is nothing to be live *over*
307
+ * while a render is a single pass, and an array is more useful to the caller.
308
+ *
309
+ * But liveness is not the only difference, and the rest was a side effect rather than a decision:
310
+ * `list.item(0)` is a plain method on both interfaces, `namedItem` on `HTMLCollection`, and an array
311
+ * has neither. `list.item(0)` threw `TypeError` — from ordinary code, and from any library written
312
+ * against the DOM rather than against arrays.
313
+ *
314
+ * The prototype is built once and shared. `item` answers `null` out of range, as the platform does,
315
+ * rather than `undefined`.
316
+ */
317
+ const COLLECTION_PROTOTYPE = Object.assign(Object.create(Array.prototype), {
318
+ item(index) {
319
+ return this[index] ?? null;
320
+ },
321
+ /**
322
+ * `HTMLCollection` only. **Document order, not `id` before `name`** — the spec says "the first
323
+ * element in the collection" for which *either* holds, so a `name="x"` earlier in the tree wins
324
+ * over an `id="x"` later.
325
+ *
326
+ * Written the other way round first, from memory, and caught by comparing against a real DOM
327
+ * instead of against the expectation. The two orders are indistinguishable unless one element
328
+ * carries the `name` and a *later* one carries the `id`, which is why the fixture has exactly that.
329
+ */
330
+ namedItem(name) {
331
+ const wanted = `${name}`;
332
+ return (this.find((element) => element.getAttribute?.('id') === wanted || element.getAttribute?.('name') === wanted) ?? null);
333
+ },
334
+ });
335
+ const asCollection = (list) => {
336
+ Object.setPrototypeOf(list, COLLECTION_PROTOTYPE);
337
+ return list;
338
+ };
339
+ /** **Elements only** — what `children` and every element-wise accessor mean. */
340
+ const elementsOf = (container) => asCollection(nodesOf(container).filter((node) => node.openTag));
341
+ const nodesOf = (container) => {
342
+ parseChunks(container);
343
+ const nodes = container._entries.filter((entry) => typeof entry !== 'string');
344
+ /**
345
+ * **Not `!nodes.length`.** That guard silenced this in the case that needs it most: a container
346
+ * holding *both* parsed nodes and a declined chunk answered `children` with only the nodes, said
347
+ * nothing, and still emitted the declined markup into the output. Some content visible and some
348
+ * invisible is harder to diagnose than none visible, and it was the half with no warning.
349
+ *
350
+ * Dropping the guard is safe because a surviving string means exactly one thing. Measured: markup
351
+ * that parses becomes nodes, `append('text')` becomes a **text node**, and even
352
+ * `append('<p>x</b>')` becomes a text node — a string argument is text, not markup. The only entry
353
+ * still a string after `parseChunks` is a chunk the parser declined, so there is no legitimate
354
+ * content this can fire on. Checked once per container (the fast path, an object key); said once per process per
355
+ * component (the tag key).
356
+ */
357
+ if (container._entries.some((entry) => typeof entry === 'string' && entry.trim()) && once('ssr-markup-declined', container)) {
358
+ /**
359
+ * **The message has to describe the parser that exists.** It used to say "markup assigned as a
360
+ * string is not parsed on the server", which was true before `parse.js` and is now false for
361
+ * almost everything: nested elements, attributes, void elements, comments, an unclosed tag, a
362
+ * table fragment and raw text all parse. What reaches this line is the narrow case the parser
363
+ * *declined* — markup it cannot re-serialize byte-identically, so it keeps the string rather than
364
+ * hand back a tree the client would not build.
365
+ *
366
+ * The distinction changes the advice. "Not parsed" tells the author to rewrite working code with
367
+ * `createElement`; the truth is that this particular markup was refused, and making it
368
+ * well-formed is usually the fix.
369
+ */
370
+ const tag = currentRenderingTag();
371
+ if (once('ssr-markup-declined', tag))
372
+ console.warn(ssrWarning((tag ? `<${tag}>` : 'the page'), 'ssr-markup-declined', PROSE['ssr-markup-declined']()));
373
+ }
374
+ return nodes;
375
+ };
376
+ /**
377
+ * **Text and comments are nodes.**
378
+ *
379
+ * They were not: `createTextNode` returned an object literal with an `innerHTML` string, so it had
380
+ * no identity, no parent and no `nodeType`, and appending one inlined its markup and lost the node.
381
+ * `childNodes` therefore reported `1` for `text <b>bold</b> tail`, where every browser says `3`.
382
+ *
383
+ * Like an element, a parsed one keeps **the exact bytes it came from** so re-serializing reproduces
384
+ * the input — `&amp;` stays `&amp;` rather than becoming this package's `&#38;` — and falls back to
385
+ * escaping its data the moment somebody writes to it.
386
+ */
387
+ /**
388
+ * **`Node` itself — the one base every node of this DOM shares** (2026-10-09). Text and comments were a separate
389
+ * line from containers, and `Node` was the container class, so `text instanceof Node` answered `false` where every
390
+ * engine answers `true`, and a Node-typed parameter could not tell a node from any object: `appendChild({})` and
391
+ * `replaceChild({}, child)` were accepted, `contains({})` answered `false`, `removeChild(null)` threw the wrong class.
392
+ * Measured by differential against jsdom (tests/ssr-imitations-differential).
393
+ */
394
+ export class NodeBaseShim extends EventTarget {
395
+ constructor() {
396
+ super();
397
+ /** `new Node()` is an `Illegal constructor` in every engine — the interface is abstract. */
398
+ if (new.target === NodeBaseShim)
399
+ throw new TypeError('Illegal constructor');
400
+ }
401
+ }
402
+ /** The token this DOM's own creation paths hand `ElementShim` — see its constructor. Module-local, so it cannot be forged. */
403
+ const MADE = Symbol('made');
404
+ /**
405
+ * **A Node-typed WebIDL parameter refuses what is not a node**, with the platform's `TypeError`. Being lenient here only
406
+ * moves the failure to the client, where the same call throws with the server's context gone.
407
+ */
408
+ const mustBeNode = (value, method, position) => {
409
+ if (!(value instanceof NodeBaseShim))
410
+ throw new TypeError(`Failed to execute '${method}' on 'Node': parameter ${position} is not of type 'Node'.`);
411
+ };
412
+ /** A required argument that is absent: WebIDL counts arguments before it converts them. */
413
+ const required = (method, needed, present) => {
414
+ if (present < needed)
415
+ throw new TypeError(`Failed to execute '${method}' on 'Node': ${needed} argument${needed === 1 ? '' : 's'} required, but only ${present} present.`);
416
+ };
417
+ export class CharacterDataShim extends NodeBaseShim {
418
+ constructor(data) {
419
+ super();
420
+ /** Abstract too: `new CharacterData()` is refused, where `new Text()` and `new Comment()` are not. */
421
+ if (new.target === CharacterDataShim)
422
+ throw new TypeError('Illegal constructor');
423
+ this._data = `${data}`;
424
+ this._source = null;
425
+ this._parent = null;
426
+ this.isConnected = true;
427
+ }
428
+ /** Registered here rather than on the platform's `EventTarget`; see `events.js`. */
429
+ addEventListener(type, callback, options) {
430
+ addListener(this, type, callback, options);
431
+ }
432
+ removeEventListener(type, callback, options) {
433
+ removeListener(this, type, callback, options);
434
+ }
435
+ dispatchEvent(event) {
436
+ return dispatch(this, event);
437
+ }
438
+ get data() {
439
+ return this._data;
440
+ }
441
+ set data(value) {
442
+ this._data = `${value}`;
443
+ this._source = null;
444
+ }
445
+ get nodeValue() {
446
+ return this._data;
447
+ }
448
+ set nodeValue(value) {
449
+ this.data = value;
450
+ }
451
+ get textContent() {
452
+ return this._data;
453
+ }
454
+ set textContent(value) {
455
+ this.data = value;
456
+ }
457
+ get length() {
458
+ return this._data.length;
459
+ }
460
+ get parentNode() {
461
+ return this._parent;
462
+ }
463
+ get parentElement() {
464
+ return this._parent?.openTag ? this._parent : null;
465
+ }
466
+ get childNodes() {
467
+ return [];
468
+ }
469
+ get firstChild() {
470
+ return null;
471
+ }
472
+ get lastChild() {
473
+ return null;
474
+ }
475
+ hasChildNodes() {
476
+ return false;
477
+ }
478
+ get ownerDocument() {
479
+ return globalThis.document ?? null;
480
+ }
481
+ get nextSibling() {
482
+ return this._siblingAt(1);
483
+ }
484
+ get previousSibling() {
485
+ return this._siblingAt(-1);
486
+ }
487
+ _siblingAt(step, view = nodesOf) {
488
+ if (!this._parent)
489
+ return null;
490
+ const siblings = view(this._parent);
491
+ const index = siblings.indexOf(this);
492
+ return index === -1 ? null : (siblings[index + step] ?? null);
493
+ }
494
+ remove() {
495
+ this._parent?.removeChild(this);
496
+ }
497
+ before(...nodes) {
498
+ insertAround(this, nodes, 'before');
499
+ }
500
+ after(...nodes) {
501
+ insertAround(this, nodes, 'after');
502
+ }
503
+ replaceWith(...nodes) {
504
+ insertAround(this, nodes, 'replace');
505
+ }
506
+ isSameNode(node) {
507
+ if (node != null)
508
+ mustBeNode(node, 'isSameNode', 1);
509
+ return node === this;
510
+ }
511
+ isEqualNode(node) {
512
+ if (node != null)
513
+ mustBeNode(node, 'isEqualNode', 1);
514
+ /** `nodeType` is the subclass's — this base is never instantiated on its own. */
515
+ return node?.nodeType === this.nodeType && node?.data === this._data;
516
+ }
517
+ contains(node) {
518
+ required('contains', 1, arguments.length);
519
+ if (node != null)
520
+ mustBeNode(node, 'contains', 1);
521
+ return node === this;
522
+ }
523
+ getRootNode() {
524
+ if (!this._parent)
525
+ return this;
526
+ let root = this._parent;
527
+ while (root._parent)
528
+ root = root._parent;
529
+ return root;
530
+ }
531
+ appendData(value) {
532
+ this.data = this._data + `${value}`;
533
+ }
534
+ substringData(offset, count) {
535
+ return this._data.substr(offset, count);
536
+ }
537
+ }
538
+ export class TextShim extends CharacterDataShim {
539
+ get nodeType() {
540
+ return 3;
541
+ }
542
+ get nodeName() {
543
+ return '#text';
544
+ }
545
+ get wholeText() {
546
+ return this._data;
547
+ }
548
+ /**
549
+ * **A text node is written by its PARENT's rule — the platform's serialization rule, and the one place this DOM
550
+ * decides it.** Inside `<style>`/`<script>` it is raw, with only the element's own end tag neutralized
551
+ * (`escapeRawText`); everywhere else, `<textarea>` and `<title>` included, it is escaped. Untouched parsed text keeps
552
+ * the bytes it came from. Raw-text content used to be stored as MARKUP by `textContent`/`value`, which nothing then
553
+ * escaped: `textarea.value = '</textarea><img onerror=…>'` closed the element and served the `<img>`.
554
+ */
555
+ markup() {
556
+ if (this._source !== null)
557
+ return this._source;
558
+ const parent = this._parent?.localName;
559
+ /** Named, not looked up: a lookup keyed by every parent's name is a megamorphic load on every text node written. */
560
+ return parent === 'style' || parent === 'script' ? escapeRawText(this._data, parent) : escapeHtml(this._data);
561
+ }
562
+ cloneNode() {
563
+ const copy = new TextShim(this._data);
564
+ copy._source = this._source;
565
+ return copy;
566
+ }
567
+ /** Splits at `offset`, leaving this node with the first half and inserting the second after it. */
568
+ splitText(offset) {
569
+ const tail = new TextShim(this._data.slice(offset));
570
+ this.data = this._data.slice(0, offset);
571
+ if (this._parent)
572
+ this._parent.insertBefore(tail, this.nextSibling);
573
+ return tail;
574
+ }
575
+ }
576
+ export class CommentShim extends CharacterDataShim {
577
+ get nodeType() {
578
+ return 8;
579
+ }
580
+ get nodeName() {
581
+ return '#comment';
582
+ }
583
+ markup() {
584
+ return this._source ?? `<!--${this._data}-->`;
585
+ }
586
+ cloneNode() {
587
+ const copy = new CommentShim(this._data);
588
+ copy._source = this._source;
589
+ return copy;
590
+ }
591
+ }
592
+ export class ContainerShim extends NodeBaseShim {
593
+ constructor() {
594
+ super();
595
+ /**
596
+ * **Children are entries, not one string.** Each entry is either a retained node or a chunk of
597
+ * raw markup. Serialization happens when `innerHTML` is *read*, not when a child is appended —
598
+ * appending used to serialize immediately and drop the node, so `appendChild(kid)` followed by
599
+ * `kid.textContent = 'x'` rendered `<b></b>` and lost the text with no diagnostic.
600
+ */
601
+ this._entries = [];
602
+ this._parent = null;
603
+ /** A server-rendered node is in the document being built, so it is connected. */
604
+ this.isConnected = true;
605
+ }
606
+ /** Registered here rather than on the platform's `EventTarget`; see `events.js`. */
607
+ addEventListener(type, callback, options) {
608
+ addListener(this, type, callback, options);
609
+ }
610
+ removeEventListener(type, callback, options) {
611
+ removeListener(this, type, callback, options);
612
+ }
613
+ dispatchEvent(event) {
614
+ return dispatch(this, event);
615
+ }
616
+ get innerHTML() {
617
+ /**
618
+ * A void element's children exist in the DOM but never in its serialization — the HTML
619
+ * serialization algorithm skips them, so engines answer `""` here even with children attached
620
+ * (measured, Chromium and jsdom agreeing; `childNodes` still reports them, and `textContent`
621
+ * still reads their text, because those are DOM questions, not serialization ones).
622
+ * `serializeElement` already knew this for `outerHTML`; the getter did not, so a component
623
+ * reading its own `innerHTML` got a different answer server-side. `localName` is undefined on
624
+ * a fragment or shadow root, so the guard cannot fire off an element.
625
+ */
626
+ if (VOID_ELEMENTS.has(this.localName ?? ''))
627
+ return '';
628
+ let out = '';
629
+ for (const entry of this._entries)
630
+ out += serializeEntry(entry);
631
+ return out;
632
+ }
633
+ set innerHTML(markup) {
634
+ for (const entry of this._entries)
635
+ if (typeof entry !== 'string')
636
+ entry._parent = null;
637
+ /**
638
+ * **`[LegacyNullToEmptyString]`** — `innerHTML` stores `''` for `null`, not the word `"null"`.
639
+ * Same rule as `input.value` and `textarea.value` in `reflections.js`, and the same rule the
640
+ * README already records as fixed for `textContent`; it was fixed there for the member rather
641
+ * than for the class, so the rest of the class stayed wrong. `undefined` is not special-cased —
642
+ * the platform stringifies it.
643
+ */
644
+ const text = markup === null ? '' : `${markup}`;
645
+ /**
646
+ * A raw-text element's markup is never markup: the platform parses it as ONE text node (decoded in RCDATA), so it
647
+ * is stored as one — and written by the text node's rule (`TextShim.markup`), never as given.
648
+ */
649
+ const name = this.localName ?? '';
650
+ if (RAW_TEXT_ELEMENTS.has(name)) {
651
+ const data = normalizeNewlines(text);
652
+ this._replaceWithText(RCDATA_ELEMENTS.has(name) ? decode(data) : data);
653
+ return;
654
+ }
655
+ this._entries = text === '' ? [] : [text];
656
+ /** New markup has not been looked at yet, whatever was true of the markup it replaced. */
657
+ this._parsed = false;
658
+ }
659
+ /** Children replaced by one text node holding `data` — none for `''`, as `textContent` does. */
660
+ _replaceWithText(data) {
661
+ for (const entry of this._entries)
662
+ if (typeof entry !== 'string')
663
+ entry._parent = null;
664
+ this._entries = [];
665
+ this._parsed = true;
666
+ if (data === '')
667
+ return;
668
+ const node = new TextShim(data);
669
+ node._parent = this;
670
+ this._entries.push(node);
671
+ }
672
+ /**
673
+ * **Every insertion path places its nodes here, at `at`, replacing `replace` entries** — `appendChild`,
674
+ * `insertBefore` and `replaceChild` (and everything that routes through them: `before`, `after`, `replaceWith`,
675
+ * `prepend`, `append`). They each kept their own copy, and only `appendChild`'s knew that a FRAGMENT hands over its
676
+ * children and is left empty: `insertBefore` and `replaceChild` inserted a fragment as its markup, so the children
677
+ * never arrived where a browser puts them and the fragment still reported having them. And none of them noticed
678
+ * markup TEXT arriving after this container had been parsed, so a query never saw it: inserting text resets `_parsed`.
679
+ * The caller has already detached `node` from any parent.
680
+ */
681
+ _place(node, at, replace) {
682
+ let incoming;
683
+ if (node.nodeType === 11) {
684
+ incoming = node._entries;
685
+ node._entries = [];
686
+ }
687
+ else
688
+ incoming = isNode(node) ? [node] : [node?.innerHTML ?? ''];
689
+ for (const entry of incoming)
690
+ if (isNode(entry))
691
+ entry._parent = this;
692
+ else
693
+ this._parsed = false;
694
+ this._entries.splice(at, replace, ...incoming);
695
+ }
696
+ appendChild(node) {
697
+ /**
698
+ * **Not a node is a `TypeError`, as it is in a browser.** `appendChild(null)` was a silent no-op
699
+ * here and throws in every engine, so `this.appendChild(maybeMissing)` — ordinary code —
700
+ * rendered a server page with the child quietly absent and then crashed the client.
701
+ */
702
+ mustBeNode(node, 'appendChild', 1);
703
+ /**
704
+ * A registered component that has not rendered is marked, so the scan over this markup renders
705
+ * this instance instead of a new one built from the tag it wrote. See `pendingInstances`.
706
+ */
707
+ if (node?.openTag &&
708
+ registry.has(node.localName) &&
709
+ !node._rendered)
710
+ markPending(node);
711
+ /**
712
+ * **A node cannot contain itself.** Retaining nodes makes this reachable where inlining markup
713
+ * never could: appending an ancestor into its own descendant would recurse forever the next
714
+ * time anything read `innerHTML`. Every engine throws `HierarchyRequestError`.
715
+ */
716
+ let contains = node === this;
717
+ for (let above = this._parent; above && !contains; above = above._parent)
718
+ if (above === node)
719
+ contains = true;
720
+ if (contains)
721
+ throw new DOMException(`Failed to execute 'appendChild' on 'Node': The new child element contains the parent.`, 'HierarchyRequestError');
722
+ /** A fragment hands over its children and is left empty — see `_place`, which every insertion path shares. */
723
+ if (node.nodeType !== 11 && isNode(node))
724
+ node._parent?._detach(node);
725
+ this._place(node, this._entries.length, 0);
726
+ return node;
727
+ }
728
+ /**
729
+ * **Position a node among the children**, which needed a tree and now has one. `reference` of
730
+ * `null` appends, as the platform says, and a reference that is not a child is a `NotFoundError`
731
+ * rather than a silent append — the difference between "put it at the end" and "you asked about
732
+ * a node I do not have" is exactly the kind of thing a server should not paper over.
733
+ */
734
+ insertBefore(node, reference) {
735
+ required('insertBefore', 2, arguments.length);
736
+ mustBeNode(node, 'insertBefore', 1);
737
+ if (reference === null || reference === undefined)
738
+ return this.appendChild(node);
739
+ mustBeNode(reference, 'insertBefore', 2);
740
+ if (this._entries.indexOf(reference) === -1)
741
+ throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be ` +
742
+ `inserted is not a child of this node.`, 'NotFoundError');
743
+ let contains = node === this;
744
+ for (let above = this._parent; above && !contains; above = above._parent)
745
+ if (above === node)
746
+ contains = true;
747
+ if (contains)
748
+ throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.`, 'HierarchyRequestError');
749
+ /**
750
+ * **Inserting a node before itself is a no-op, and it was not.** The spec's pre-insert step 3 is
751
+ * "if referenceChild is node, then set referenceChild to node's next sibling", and without it the
752
+ * detach below removes `node` and the `indexOf(reference)` that follows returns `-1` — so
753
+ * `splice(-1, 0, node)` puts it back **before the last child** instead of where it was.
754
+ *
755
+ * Reached in practice through `after()`: `insertAround` computes its reference once, up front, so
756
+ * `a.after(b)` where `b` is already `a`'s next sibling becomes exactly `insertBefore(b, b)`.
757
+ * Measured against jsdom, with `n` children the node landed at index `n - 2` every time — two
758
+ * children put it *first*, five put it second-to-last, and **three put it back where it belonged**,
759
+ * which is the size a hand-written test uses.
760
+ *
761
+ * Found by fuzzing sequences of tree mutations rather than operations one at a time; every
762
+ * individual member here already agreed with jsdom.
763
+ */
764
+ if (reference === node) {
765
+ reference = node.nextSibling;
766
+ if (reference === null)
767
+ return this.appendChild(node);
768
+ }
769
+ if (node.nodeType !== 11 && isNode(node))
770
+ node._parent?._detach(node);
771
+ /** Re-found after the detach: moving a node forwards within one parent shifts the index. */
772
+ this._place(node, this._entries.indexOf(reference), 0);
773
+ return node;
774
+ }
775
+ /**
776
+ * **`moveBefore` is `insertBefore` with a precondition**: the node must already have a parent.
777
+ * Measured on Chromium and Firefox, which agree on all of it (WebKit does not implement it yet):
778
+ * an unparented node is a `HierarchyRequestError`, and a *parented* node with a reference that is
779
+ * not a child here is a `NotFoundError` — a different error from the same call depending on which
780
+ * argument is wrong, and checked in that order.
781
+ *
782
+ * The point of the API in a browser is moving a node without tearing down its state. There is no
783
+ * state to preserve on a server, so this is a move; having it means code written for the browser
784
+ * runs here rather than hitting a missing method.
785
+ */
786
+ moveBefore(node, reference) {
787
+ required('moveBefore', 2, arguments.length);
788
+ mustBeNode(node, 'moveBefore', 1);
789
+ if (reference !== null && reference !== undefined)
790
+ mustBeNode(reference, 'moveBefore', 2);
791
+ if (!node._parent)
792
+ throw new DOMException(`Failed to execute 'moveBefore' on 'Node': The node to be moved has no parent.`, 'HierarchyRequestError');
793
+ if (reference !== null && reference !== undefined && this._entries.indexOf(reference) === -1)
794
+ throw new DOMException(`Failed to execute 'moveBefore' on 'Node': The node before which the new node is to be ` +
795
+ `inserted is not a child of this node.`, 'NotFoundError');
796
+ return this.insertBefore(node, reference ?? null);
797
+ }
798
+ replaceChild(node, old) {
799
+ mustBeNode(node, 'replaceChild', 1);
800
+ mustBeNode(old, 'replaceChild', 2);
801
+ if (this._entries.indexOf(old) === -1)
802
+ throw new DOMException(`Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.`, 'NotFoundError');
803
+ /**
804
+ * **The one insertion path that had no ancestor check.** `prepend`, `append`, `appendChild`,
805
+ * `before` and `replaceWith` all route through `insertBefore` and inherit its guard; this does
806
+ * not, so `root.replaceChild(root, child)` was accepted and built a tree containing itself.
807
+ *
808
+ * A cycle in the tree is worse than a misordered one: it is not a wrong answer, it is a structure
809
+ * nothing downstream can walk. The nesting cap in `index.js` would eventually refuse the render,
810
+ * naming recursion rather than the call that caused it.
811
+ *
812
+ * Found by fuzzing mutation *sequences* against jsdom — `ssr-tree-operations` covers this method
813
+ * and could not see it, because the case needs a node and its own ancestor in one call.
814
+ */
815
+ let contains = node === this;
816
+ for (let above = this._parent; above && !contains; above = above._parent)
817
+ if (above === node)
818
+ contains = true;
819
+ if (contains)
820
+ throw new DOMException(`Failed to execute 'replaceChild' on 'Node': The new child element contains the parent.`, 'HierarchyRequestError');
821
+ /**
822
+ * **Where `old` sits, captured before anything moves.** Detaching `node` can remove `old` from
823
+ * this list — they are allowed to be the same node — and the `indexOf(old)` that followed then
824
+ * returned `-1`, so `splice(-1, 1, …)` **replaced the last child instead**: `x.replaceChild(x, x)`
825
+ * moved `x` to the end and destroyed whatever had been there.
826
+ *
827
+ * The spec makes replacing a node with itself a no-op, by the same step `insertBefore` needed —
828
+ * "if referenceChild is node, then set referenceChild to node's next sibling". Third instance of
829
+ * one root cause: this file treated a node and its own argument as necessarily different, and
830
+ * every one of these operations allows them to be the same.
831
+ */
832
+ const at = this._entries.indexOf(old);
833
+ /** Only a child kind has a parent to be detached from; a fragment's is always `null`. */
834
+ if (node.nodeType !== 11 && isNode(node))
835
+ node._parent?._detach(node);
836
+ /** Re-found after the detach: moving a node forwards within one parent shifts the index. */
837
+ const index = this._entries.indexOf(old);
838
+ if (old !== node)
839
+ old._parent = null;
840
+ if (index === -1)
841
+ this._place(node, at, 0);
842
+ else
843
+ this._place(node, index, 1);
844
+ return old;
845
+ }
846
+ /**
847
+ * **Where each node sits relative to another**, as the spec's bit field. Two nodes with no common
848
+ * root are `DISCONNECTED | IMPLEMENTATION_SPECIFIC` plus a direction the spec leaves to the
849
+ * implementation, so only the disconnected bit is worth comparing across implementations.
850
+ */
851
+ compareDocumentPosition(other) {
852
+ mustBeNode(other, 'compareDocumentPosition', 1);
853
+ if (other === this)
854
+ return 0;
855
+ if (this.contains(other))
856
+ return 16 + 4;
857
+ if (other.contains?.(this))
858
+ return 8 + 2;
859
+ const chain = (node) => {
860
+ const out = [];
861
+ for (let current = node; current; current = current._parent)
862
+ out.unshift(current);
863
+ return out;
864
+ };
865
+ const mine = chain(this);
866
+ const theirs = chain(other);
867
+ if (mine[0] !== theirs[0])
868
+ return 1 + 32 + 2;
869
+ let depth = 0;
870
+ while (mine[depth] === theirs[depth])
871
+ depth++;
872
+ /** The deepest common ancestor holds children, and the two nodes below it are among them. */
873
+ const siblings = nodesOf(mine[depth - 1]);
874
+ return siblings.indexOf(mine[depth]) < siblings.indexOf(theirs[depth]) ? 4 : 2;
875
+ }
876
+ /** Remove a node from this container's entries without touching its own parent pointer. */
877
+ _detach(node) {
878
+ const index = this._entries.indexOf(node);
879
+ if (index !== -1)
880
+ this._entries.splice(index, 1);
881
+ }
882
+ /**
883
+ * **Absent until nodes were retained**, so `host.removeChild(kid)` was a `TypeError` — there was
884
+ * nothing to remove, the child having been flattened into a string at append time.
885
+ */
886
+ removeChild(node) {
887
+ mustBeNode(node, 'removeChild', 1);
888
+ const index = this._entries.indexOf(node);
889
+ if (index === -1)
890
+ throw new DOMException(`Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`, 'NotFoundError');
891
+ this._entries.splice(index, 1);
892
+ node._parent = null;
893
+ return node;
894
+ }
895
+ /**
896
+ * What a node with no tree above or below it answers — shared, because an element and a shadow
897
+ * root answer these identically and two copies is how they came to disagree in the first place.
898
+ *
899
+ * Every one is the truthful answer rather than a placeholder: a detached node has no parent, no
900
+ * siblings and no box, and a browser returns exactly these. They are here because their
901
+ * *absence* was a `TypeError` that took the whole render down — `this.parentElement && …` is
902
+ * ordinary defensive code and it crashed.
903
+ */
904
+ get parentNode() {
905
+ return this._parent;
906
+ }
907
+ /** `null` when the parent is not an element — a shadow root is a parent and not an element. */
908
+ get parentElement() {
909
+ return this._parent?.openTag ? this._parent : null;
910
+ }
911
+ get firstChild() {
912
+ return nodesOf(this)[0] ?? null;
913
+ }
914
+ get lastChild() {
915
+ return nodesOf(this).at(-1) ?? null;
916
+ }
917
+ get lastElementChild() {
918
+ return elementsOf(this).at(-1) ?? null;
919
+ }
920
+ /**
921
+ * **The siblings are real now.** These answered `null` unconditionally, which was truthful while a
922
+ * child was flattened into its parent's markup and became a lie the moment nodes were retained —
923
+ * `element.nextSibling` on the middle of three children reported nothing at all. There are no text
924
+ * nodes in this DOM, so the element-wise and node-wise spellings answer the same list.
925
+ */
926
+ get nextSibling() {
927
+ return this._siblingAt(1);
928
+ }
929
+ get previousSibling() {
930
+ return this._siblingAt(-1);
931
+ }
932
+ get nextElementSibling() {
933
+ return this._siblingAt(1, elementsOf);
934
+ }
935
+ get previousElementSibling() {
936
+ return this._siblingAt(-1, elementsOf);
937
+ }
938
+ _siblingAt(step, view = nodesOf) {
939
+ if (!this._parent)
940
+ return null;
941
+ const siblings = view(this._parent);
942
+ const index = siblings.indexOf(this);
943
+ return index === -1 ? null : (siblings[index + step] ?? null);
944
+ }
945
+ /**
946
+ * **The slot this node is projected into**, which needs the host's shadow root and the node's own
947
+ * `slot` name — both of which are here. It answered `null` for every node, so a component asking
948
+ * where its light DOM had landed was told "nowhere".
949
+ */
950
+ get assignedSlot() {
951
+ /** Only an element has a `_shadowRoot`, and only an element child is read for its slot. */
952
+ const root = this._parent?._shadowRoot;
953
+ if (!root)
954
+ return null;
955
+ const name = slotNameOf(this);
956
+ return (root
957
+ .querySelectorAll('slot')
958
+ .find((slot) => (slot.getAttribute('name') ?? '') === name) ?? null);
959
+ }
960
+ get offsetParent() {
961
+ return null;
962
+ }
963
+ get childElementCount() {
964
+ return elementsOf(this).length;
965
+ }
966
+ hasChildNodes() {
967
+ return nodesOf(this).length > 0;
968
+ }
969
+ get nodeValue() {
970
+ return null;
971
+ }
972
+ get baseURI() {
973
+ return globalThis.location?.href ?? '';
974
+ }
975
+ get namespaceURI() {
976
+ return HTML_NS;
977
+ }
978
+ get prefix() {
979
+ return null;
980
+ }
981
+ /** `null` before the environment exists, as its twin on the other node classes already answers. */
982
+ get ownerDocument() {
983
+ return globalThis.document ?? null;
984
+ }
985
+ /**
986
+ * **Walks the parent chain**, as the platform does. It compared identity only, so
987
+ * `host.contains(child)` was `false` for a child the host plainly held — ordinary defensive code
988
+ * reading as "this is not mine".
989
+ */
990
+ contains(node) {
991
+ required('contains', 1, arguments.length);
992
+ if (node != null)
993
+ mustBeNode(node, 'contains', 1);
994
+ for (let current = node; current; current = current._parent)
995
+ if (current === this)
996
+ return true;
997
+ return false;
998
+ }
999
+ /** The `ChildNode` trio, shared with text and comments through `insertAround`. */
1000
+ before(...nodes) {
1001
+ insertAround(this, nodes, 'before');
1002
+ }
1003
+ after(...nodes) {
1004
+ insertAround(this, nodes, 'after');
1005
+ }
1006
+ replaceWith(...nodes) {
1007
+ insertAround(this, nodes, 'replace');
1008
+ }
1009
+ isSameNode(node) {
1010
+ if (node != null)
1011
+ mustBeNode(node, 'isSameNode', 1);
1012
+ return node === this;
1013
+ }
1014
+ /**
1015
+ * **Structural equality, not identity** — that is what `isSameNode` is for, and this answered the
1016
+ * same thing, so two elements built identically reported themselves different. The spec compares
1017
+ * type, name, attributes as a set, and children pairwise.
1018
+ */
1019
+ isEqualNode(node) {
1020
+ if (node != null)
1021
+ mustBeNode(node, 'isEqualNode', 1);
1022
+ return equalNodes(this, node);
1023
+ }
1024
+ /**
1025
+ * **Merges adjacent text and drops the empty**, which is what it is for. It was a no-op because
1026
+ * there were no text nodes to merge — appending two of them left two entries a browser would have
1027
+ * joined into one, so `childNodes.length` disagreed after the most ordinary DOM building there is.
1028
+ */
1029
+ normalize() {
1030
+ parseChunks(this);
1031
+ /** A markup chunk is read for a `nodeType` it does not have, so it is typed as having none. */
1032
+ const merged = [];
1033
+ for (const entry of this._entries) {
1034
+ const previous = merged[merged.length - 1];
1035
+ if (entry?.nodeType === 3 && entry.data === '')
1036
+ continue;
1037
+ if (entry?.nodeType === 3 && previous?.nodeType === 3) {
1038
+ previous.data += entry.data;
1039
+ entry._parent = null;
1040
+ continue;
1041
+ }
1042
+ merged.push(entry);
1043
+ }
1044
+ this._entries = merged;
1045
+ for (const entry of merged)
1046
+ if (isNode(entry) && entry.nodeType === 1)
1047
+ entry.normalize();
1048
+ }
1049
+ /**
1050
+ * The furthest ancestor, which is the shadow root for anything a component rendered into one —
1051
+ * unless `composed` is asked for, which keeps going out through the root's host as a browser does.
1052
+ */
1053
+ getRootNode(options) {
1054
+ if (!this._parent)
1055
+ return this;
1056
+ let root = this._parent;
1057
+ for (;;) {
1058
+ while (root._parent)
1059
+ root = root._parent;
1060
+ if (!options?.composed || !root._host)
1061
+ return root;
1062
+ root = root._host;
1063
+ }
1064
+ }
1065
+ /** Needs layout, which a string does not have; a browser with no box returns nothing either. */
1066
+ elementFromPoint() {
1067
+ return null;
1068
+ }
1069
+ elementsFromPoint() {
1070
+ return [];
1071
+ }
1072
+ getSelection() {
1073
+ return null;
1074
+ }
1075
+ /** `append` takes several nodes, and strings as text — the modern spelling of `appendChild`. */
1076
+ /**
1077
+ * A string is markup to escape and keep as a chunk. It used to go through `innerHTML +=`, which
1078
+ * now reads every retained node back into text and writes it as one chunk — flattening the tree
1079
+ * this class exists to keep. Pushing the chunk is the same bytes and keeps the nodes.
1080
+ */
1081
+ append(...nodes) {
1082
+ for (const node of nodes) {
1083
+ /** `(Node or DOMString)`: anything that is not a node is converted to a string — `append({})` is the text `[object Object]`. */
1084
+ if (!(node instanceof NodeBaseShim)) {
1085
+ this._entries.push(escapeHtml(`${node}`));
1086
+ this._parsed = false;
1087
+ }
1088
+ else
1089
+ this.appendChild(node);
1090
+ }
1091
+ }
1092
+ replaceChildren(...nodes) {
1093
+ this.innerHTML = '';
1094
+ this.append(...nodes);
1095
+ }
1096
+ /** Splices the entries rather than concatenating markup, for the reason `append` gives. */
1097
+ /**
1098
+ * **The restore has to survive a throw.** `append` can reject a node — an ancestor of `this` is a
1099
+ * `HierarchyRequestError` — and the children were already moved aside by then, so the final
1100
+ * `push` never ran and **every existing child was destroyed by a call that failed**.
1101
+ *
1102
+ * Measured against jsdom: `child.prepend(root)` throws on both, and afterwards jsdom still holds
1103
+ * the child's text while this held nothing. A failed operation that mutates is worse than one that
1104
+ * does the wrong thing, because the caller has already handled the error and moved on.
1105
+ *
1106
+ * `finally`, not a validity pre-pass: matching the spec exactly would mean checking every argument
1107
+ * before inserting any, so that a second bad node undoes a first good one. That difference is
1108
+ * narrower than this one and is left alone deliberately — what is fixed here is the destruction of
1109
+ * children that were never arguments.
1110
+ *
1111
+ * Found by fuzzing sequences of tree mutations against jsdom; the failing sequence ended
1112
+ * `prepend(n1, root)` and the loss showed up as a missing text node four operations later.
1113
+ */
1114
+ prepend(...nodes) {
1115
+ const existing = this._entries;
1116
+ this._entries = [];
1117
+ try {
1118
+ this.append(...nodes);
1119
+ }
1120
+ finally {
1121
+ /**
1122
+ * **Minus the arguments themselves.** Prepending a node that is ALREADY a child of this
1123
+ * element is a move-to-front, and `append`'s detach cannot see it: the child's entry sits
1124
+ * in this local array while `_entries` is swapped empty, so nothing was removed and pushing
1125
+ * `existing` back restored a second copy — `prepend(b)` on `[a,b,c]` answered `[b,a,b,c]`
1126
+ * where every engine answers `[b,a,c]`. Found by the virgin-seed tree fuzz (three sequences,
1127
+ * one signature, all ending in a same-parent prepend); every other move op detaches through
1128
+ * the live `_entries` and was already right. Strings are always kept — they are text
1129
+ * entries, never arguments' identities.
1130
+ */
1131
+ for (const entry of existing)
1132
+ if (typeof entry === 'string' || !nodes.includes(entry))
1133
+ this._entries.push(entry);
1134
+ }
1135
+ }
1136
+ /**
1137
+ * **Answers from the node view**, which markup assigned as a string now has. Every query used to
1138
+ * return nothing whatever was asked, so a component branched the wrong way with nothing said.
1139
+ * A selector this DOM cannot answer honestly throws rather than answering `null` — see
1140
+ * `select.js`.
1141
+ */
1142
+ querySelector(selector) {
1143
+ parseChunks(this);
1144
+ return select.querySelector(this, selector);
1145
+ }
1146
+ querySelectorAll(selector) {
1147
+ parseChunks(this);
1148
+ return asCollection(select.querySelectorAll(this, selector));
1149
+ }
1150
+ getElementById(id) {
1151
+ parseChunks(this);
1152
+ return select.querySelector(this, `[id="${`${id}`.replace(/"/gu, '\\"')}"]`);
1153
+ }
1154
+ /**
1155
+ * **Only retained nodes.** Every entry this DOM holds as an element *is* an element, so `children`
1156
+ * and `childNodes` answer the same list — there are no text nodes to separate them, and markup
1157
+ * kept as a string is not nodes at all (`nodesOf` says so).
1158
+ */
1159
+ get children() {
1160
+ return elementsOf(this);
1161
+ }
1162
+ get childNodes() {
1163
+ return asCollection(nodesOf(this));
1164
+ }
1165
+ get firstElementChild() {
1166
+ return elementsOf(this)[0] ?? null;
1167
+ }
1168
+ }
1169
+ /**
1170
+ * A fragment is a container and nothing more.
1171
+ *
1172
+ * Its own class rather than a reused `ElementShim`, so `instanceof DocumentFragment` answers `false`
1173
+ * for an element — a check the renderer makes, and one that a shared class would have made true for
1174
+ * everything.
1175
+ */
1176
+ export class FragmentShim extends ContainerShim {
1177
+ get nodeType() {
1178
+ return 11;
1179
+ }
1180
+ get nodeName() {
1181
+ return '#document-fragment';
1182
+ }
1183
+ }
1184
+ export class ShadowRootShim extends ContainerShim {
1185
+ constructor(init) {
1186
+ super();
1187
+ this.mode = init.mode ?? 'open';
1188
+ this._init = init;
1189
+ /** Set by `attachShadow`; a shadow root's `host` is part of the contract the router reads. */
1190
+ this._host = null;
1191
+ this.innerHTML = '';
1192
+ this._styles = [];
1193
+ }
1194
+ /** `shadowrootmode` plus whatever else the root was opened with, as the parser expects them. */
1195
+ templateAttributes() {
1196
+ let out = ` shadowrootmode="${this.mode}"`;
1197
+ for (const [option, attribute] of SHADOW_ATTRIBUTES)
1198
+ if (this._init[option])
1199
+ out += ` ${attribute}=""`;
1200
+ return out;
1201
+ }
1202
+ /**
1203
+ * A `<style>` joins the stylesheet collection; anything else is content.
1204
+ *
1205
+ * Every append used to be treated as a stylesheet, on the assumption that only `adoptStyles`
1206
+ * would ever reach here. A component appending an element to its own shadow root — ordinary DOM
1207
+ * code — therefore had that element silently turned into CSS and its markup lost.
1208
+ */
1209
+ appendChild(node) {
1210
+ if (node?.localName === 'style') {
1211
+ this._styles.push(node.innerHTML);
1212
+ return node;
1213
+ }
1214
+ return super.appendChild(node);
1215
+ }
1216
+ /** A shadow root's `host` is part of the contract `@verajs/router` reads. */
1217
+ get host() {
1218
+ return this._host;
1219
+ }
1220
+ /**
1221
+ * The options it was opened with, readable the way a browser exposes them.
1222
+ *
1223
+ * These are already serialized into the declarative template — they have to be, because
1224
+ * `attachShadow` reuses a declarative root and ignores the options it is handed. A component
1225
+ * that *reads* them back, to decide whether to manage focus itself, saw `undefined`.
1226
+ */
1227
+ get delegatesFocus() {
1228
+ return !!this._init.delegatesFocus;
1229
+ }
1230
+ get clonable() {
1231
+ return !!this._init.clonable;
1232
+ }
1233
+ get serializable() {
1234
+ return !!this._init.serializable;
1235
+ }
1236
+ get slotAssignment() {
1237
+ return this._init.slotAssignment ?? 'named';
1238
+ }
1239
+ get nodeType() {
1240
+ return 11;
1241
+ }
1242
+ get nodeName() {
1243
+ return '#document-fragment';
1244
+ }
1245
+ /** Nothing is focused on a server, and nothing is in a top layer. */
1246
+ get activeElement() {
1247
+ return null;
1248
+ }
1249
+ get fullscreenElement() {
1250
+ return null;
1251
+ }
1252
+ get pointerLockElement() {
1253
+ return null;
1254
+ }
1255
+ get pictureInPictureElement() {
1256
+ return null;
1257
+ }
1258
+ /** `<style>` elements appended here; the constructed ones are `adoptedStyleSheets`. */
1259
+ get styleSheets() {
1260
+ return this._styles.map((cssText) => Object.assign(new StyleSheetShim(), { cssText }));
1261
+ }
1262
+ /** A shadow root's text is its content's text, and setting it replaces the content. */
1263
+ get textContent() {
1264
+ return textOf(this);
1265
+ }
1266
+ set textContent(value) {
1267
+ this.innerHTML = escapeHtml(value);
1268
+ }
1269
+ /**
1270
+ * Constructed sheets land here; serialized alongside string styles.
1271
+ *
1272
+ * **Checked, because the platform checks.** A browser raises `TypeError` for a value that is not
1273
+ * a sequence and for an entry that is not a `CSSStyleSheet`, and taking anything meant that
1274
+ * `root.adoptedStyleSheets = sheet` — the single missing `[…]`, and the most likely way to get
1275
+ * this wrong — was accepted here and threw in the browser, after the server had already rendered.
1276
+ */
1277
+ set adoptedStyleSheets(sheets) {
1278
+ /** Any iterable of sheets, as the platform takes — see `toSheetSequence`; kept as an array of its own. */
1279
+ this._adopted = toSheetSequence(sheets);
1280
+ }
1281
+ get adoptedStyleSheets() {
1282
+ return this._adopted ?? [];
1283
+ }
1284
+ /**
1285
+ * The `<style>` tags, kept separate from the content.
1286
+ *
1287
+ * They used to be concatenated here and the whole string handed to the nested-component scan,
1288
+ * which then read the stylesheet as markup: CSS containing a registered tag name — a
1289
+ * `content: "<some-comp>"` is enough — had that component **rendered inside the stylesheet**.
1290
+ * A scan for elements has no business reading a raw-text element.
1291
+ */
1292
+ styleTags() {
1293
+ const sheets = (this._adopted ?? []).map((sheet) => sheet.cssText ?? '');
1294
+ /**
1295
+ * **Text first, adopted sheets last — because that is the order the browser cascades them in.**
1296
+ *
1297
+ * A shadow root's own `<style>` elements are its tree-order sheets, and `adoptedStyleSheets`
1298
+ * apply *after* them: measured in Chromium, a constructed rule beats an identical-specificity
1299
+ * rule from a `<style>` in the same root no matter which appears first in the markup. Here both
1300
+ * are `<style>` elements, so the cascade is document order and whichever is written last wins.
1301
+ *
1302
+ * Emitting sheets first therefore inverted it. `static styles = [sheet, '.plain { … }']` — a
1303
+ * legal shape this package serializes on purpose — had the string win on the server and lose in
1304
+ * the browser, so the page changed appearance as it hydrated, in the one direction nothing
1305
+ * compares: markup, node identity and property values all matched.
1306
+ */
1307
+ return [...this._styles, ...sheets]
1308
+ .filter(Boolean)
1309
+ .map((css) => `<style data-vm-sheet="styles">${escapeStyleText(css)}</style>`)
1310
+ .join('');
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Properties that are a **view of an attribute**, and the attribute each one reflects.
1315
+ *
1316
+ * `this.id = 'x'`, `this.className = 'a b'`, `this.ariaLabel = 'Close'`, `this.hidden = true` are
1317
+ * all ordinary component code, and every one of them was a plain property here: the assignment
1318
+ * stuck to the object and never reached the markup, so the server and the client disagreed about
1319
+ * the element's own attributes. Generated from a table rather than written out, because there are
1320
+ * sixty of them and the ARIA half is pure repetition — the list is the specification, and adding
1321
+ * one is adding a name.
1322
+ *
1323
+ * `booleans` are present/absent (`hidden`), the rest carry their value. `role` and the `aria-*`
1324
+ * family are ordinary string reflections; `tabIndex` is a number that still round-trips as text.
1325
+ */
1326
+ const dashedAria = (name) => `aria-${name.slice(4).toLowerCase()}`;
1327
+ /** Plain strings: the attribute's value, or `''` when it is absent. */
1328
+ const REFLECTED = {
1329
+ id: 'id',
1330
+ className: 'class',
1331
+ title: 'title',
1332
+ lang: 'lang',
1333
+ dir: 'dir',
1334
+ slot: 'slot',
1335
+ nonce: 'nonce',
1336
+ accessKey: 'accesskey',
1337
+ role: 'role',
1338
+ autocorrect: 'autocorrect',
1339
+ };
1340
+ /** The reflected strings declared `DOMString?`, which answer `null` rather than `''`. */
1341
+ const NULLABLE_REFLECTED = new Set(['role']);
1342
+ /**
1343
+ * **Enumerated reflections answer a *state*, not the attribute's text.** `inputmode="bogus"` reads
1344
+ * back as `''` in every engine, not `'bogus'`, and an absent attribute has its own answer that is
1345
+ * often different again — `autocapitalize` is `''` when missing and `'sentences'` when invalid. The
1346
+ * markup is unaffected either way (the attribute is stored verbatim, which is also what the engines
1347
+ * do), so this is only visible to a component that *reads* the property server-side — and that is
1348
+ * exactly the divergence that surfaces later as a hydration mismatch with nothing left to explain it.
1349
+ *
1350
+ * Every value here was measured on Chromium, Firefox and WebKit rather than read off a spec; all
1351
+ * three agree on all of it. `tests/browser/reflected-enumerations.test.js` records the measurement.
1352
+ * Two deliberate omissions:
1353
+ *
1354
+ * - **`spellcheck` is not here** — the engines genuinely disagree (an invalid value reads `true` in
1355
+ * Chromium and WebKit, `false` in Firefox), so there is no single answer to match.
1356
+ * - **`autocorrect` is not here** for the same reason: Chromium does not implement it at all, and
1357
+ * Firefox and WebKit answer a boolean rather than a string.
1358
+ *
1359
+ * `popover: 'hint'` is treated as known because the spec and two engines say so; WebKit does not
1360
+ * implement that state yet and clamps it to `'manual'`. Following the majority is the lesser wrong,
1361
+ * and it cannot affect markup.
1362
+ */
1363
+ const ENUMERATED = {
1364
+ popover: [['auto', 'manual', 'hint'], null, 'manual'],
1365
+ autocapitalize: [['none', 'off', 'on', 'sentences', 'words', 'characters'], '', 'sentences'],
1366
+ enterKeyHint: [['enter', 'done', 'go', 'next', 'previous', 'search', 'send'], '', ''],
1367
+ inputMode: [['none', 'text', 'tel', 'url', 'email', 'numeric', 'decimal', 'search'], '', ''],
1368
+ writingSuggestions: [['true', 'false'], 'true', 'true'],
1369
+ virtualKeyboardPolicy: [['auto', 'manual'], '', ''],
1370
+ };
1371
+ /** The attribute each of them reflects. */
1372
+ const ENUMERATED_ATTRIBUTES = {
1373
+ popover: 'popover',
1374
+ autocapitalize: 'autocapitalize',
1375
+ enterKeyHint: 'enterkeyhint',
1376
+ inputMode: 'inputmode',
1377
+ writingSuggestions: 'writingsuggestions',
1378
+ virtualKeyboardPolicy: 'virtualkeyboardpolicy',
1379
+ };
1380
+ /** `contentEditable` is enumerated too, and is the only one whose setter validates. */
1381
+ const CONTENT_EDITABLE_STATES = ['true', 'false', 'plaintext-only'];
1382
+ /** Present or absent. */
1383
+ const REFLECTED_PRESENCE = { hidden: 'hidden', autofocus: 'autofocus', inert: 'inert' };
1384
+ /**
1385
+ * A boolean in JavaScript, the words `true`/`false` in the markup — **each with its own default**,
1386
+ * because they do not share one. With the attribute absent a browser reports `draggable` as `false`
1387
+ * and `spellcheck` as `true`. One shared rule gave both `true`, so `draggable` was wrong on every
1388
+ * element that had not set it, and `spellcheck` was right by accident.
1389
+ */
1390
+ const REFLECTED_TRUE_FALSE = { draggable: ['draggable', false], spellcheck: ['spellcheck', true] };
1391
+ /** The one that spells its booleans differently. */
1392
+ const REFLECTED_YES_NO = { translate: 'translate' };
1393
+ /** A number in JavaScript, its digits in the markup. */
1394
+ const REFLECTED_NUMBERS = { tabIndex: 'tabindex' };
1395
+ /**
1396
+ * The tags that are focusable without a `tabindex`, and so report `tabIndex === 0` rather than `-1`.
1397
+ *
1398
+ * `tabIndex` had no default at all — every element answered `0`, which says "in the tab order" about
1399
+ * a `<div>` that is not in it. `element.tabIndex < 0` is the ordinary way to ask whether something
1400
+ * can be focused, so the server answered the opposite of the browser for the common case.
1401
+ *
1402
+ * `a` and `area` need an `href` to be focusable, and `audio`/`video` need `controls`. jsdom reports
1403
+ * `0` for a bare `<a>`, so a differential run against it will flag that one cell — the browsers are
1404
+ * right and jsdom is loose, which is the usual direction.
1405
+ */
1406
+ const FOCUSABLE = new Set(['button', 'input', 'select', 'textarea', 'details', 'iframe', 'summary']);
1407
+ const CONDITIONALLY_FOCUSABLE = {
1408
+ a: 'href',
1409
+ area: 'href',
1410
+ audio: 'controls',
1411
+ video: 'controls',
1412
+ };
1413
+ /**
1414
+ * `Node`'s numeric constants, and the measurements a box that was never laid out reports.
1415
+ *
1416
+ * Zero is what a browser returns for a detached element, so these are accurate rather than
1417
+ * convenient. `currentCSSZoom` is 1 for the same reason.
1418
+ */
1419
+ export const NODE_CONSTANTS = {
1420
+ ELEMENT_NODE: 1,
1421
+ ATTRIBUTE_NODE: 2,
1422
+ TEXT_NODE: 3,
1423
+ CDATA_SECTION_NODE: 4,
1424
+ ENTITY_REFERENCE_NODE: 5,
1425
+ ENTITY_NODE: 6,
1426
+ PROCESSING_INSTRUCTION_NODE: 7,
1427
+ COMMENT_NODE: 8,
1428
+ DOCUMENT_NODE: 9,
1429
+ DOCUMENT_TYPE_NODE: 10,
1430
+ DOCUMENT_FRAGMENT_NODE: 11,
1431
+ NOTATION_NODE: 12,
1432
+ DOCUMENT_POSITION_DISCONNECTED: 1,
1433
+ DOCUMENT_POSITION_PRECEDING: 2,
1434
+ DOCUMENT_POSITION_FOLLOWING: 4,
1435
+ DOCUMENT_POSITION_CONTAINS: 8,
1436
+ DOCUMENT_POSITION_CONTAINED_BY: 16,
1437
+ DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32,
1438
+ };
1439
+ const LAYOUT_ZEROS = [
1440
+ 'clientWidth', 'clientHeight', 'clientLeft', 'clientTop',
1441
+ 'offsetWidth', 'offsetHeight', 'offsetLeft', 'offsetTop',
1442
+ 'scrollWidth', 'scrollHeight', 'scrollLeftMax', 'scrollTopMax',
1443
+ ];
1444
+ /** Installs the generated accessors onto the shim's prototype. */
1445
+ const defineReflections = (Shim) => {
1446
+ for (const name of LAYOUT_ZEROS)
1447
+ Object.defineProperty(Shim.prototype, name, { value: 0, writable: true, configurable: true });
1448
+ /** Scroll offsets are writable and read back, which is what a scroll-restoring component does. */
1449
+ for (const name of ['scrollLeft', 'scrollTop'])
1450
+ Object.defineProperty(Shim.prototype, name, { value: 0, writable: true, configurable: true });
1451
+ Object.defineProperty(Shim.prototype, 'currentCSSZoom', { value: 1, configurable: true });
1452
+ /**
1453
+ * **It follows the `contentEditable` *state*, not the attribute's text.** Comparing the raw
1454
+ * attribute to `'true'` answered `false` for `plaintext-only`, for an empty attribute and for
1455
+ * `TRUE` — all three of which are editable in Chromium and Firefox whether the element is in the
1456
+ * document or not, and in WebKit once it is.
1457
+ *
1458
+ * WebKit's answer for a *detached* element is unstable — it flips depending on whether an
1459
+ * attached editable element happens to exist elsewhere in the document — so it is not evidence
1460
+ * about the mapping. The mapping itself is unanimous.
1461
+ */
1462
+ Object.defineProperty(Shim.prototype, 'isContentEditable', {
1463
+ get() {
1464
+ const state = this.contentEditable;
1465
+ return state === 'true' || state === 'plaintext-only';
1466
+ },
1467
+ configurable: true,
1468
+ });
1469
+ for (const [property, attribute] of Object.entries(REFLECTED)) {
1470
+ Object.defineProperty(Shim.prototype, property, {
1471
+ get() {
1472
+ /**
1473
+ * **`role` and `popover` are nullable and the rest are not.** Both are declared `DOMString?`,
1474
+ * so a browser answers `null` when the attribute is absent where `id` and `title` answer
1475
+ * `''`. Returning `''` for `role` made `element.role === null` false on every element that
1476
+ * had never been given one — a test a component writes to mean "this has no explicit role".
1477
+ */
1478
+ return this.getAttribute(attribute) ?? (NULLABLE_REFLECTED.has(property) ? null : '');
1479
+ },
1480
+ set(value) {
1481
+ this.setAttribute(attribute, value);
1482
+ },
1483
+ configurable: true,
1484
+ });
1485
+ }
1486
+ for (const [property, attribute] of Object.entries(ENUMERATED_ATTRIBUTES)) {
1487
+ const [known, missing, invalid] = ENUMERATED[property];
1488
+ Object.defineProperty(Shim.prototype, property, {
1489
+ get() {
1490
+ const raw = this.getAttribute(attribute);
1491
+ if (raw === null)
1492
+ return missing;
1493
+ /** Enumerated attributes are ASCII case-insensitive and the getter answers canonically. */
1494
+ const state = raw.toLowerCase();
1495
+ return known.includes(state) ? state : invalid;
1496
+ },
1497
+ /** The setter writes what it is given; only the getter maps to a state. */
1498
+ set(value) {
1499
+ this.setAttribute(attribute, value);
1500
+ },
1501
+ configurable: true,
1502
+ });
1503
+ }
1504
+ /**
1505
+ * **`contentEditable` is the one whose setter validates.** Every engine throws a `SyntaxError`
1506
+ * for a value outside the three states, lowercases what it accepts, and treats `'inherit'` as
1507
+ * "remove the attribute" rather than a value to write. An empty string throws — it is not the
1508
+ * same as `'inherit'`, though the attribute *being* empty reads back as `'true'`.
1509
+ */
1510
+ Object.defineProperty(Shim.prototype, 'contentEditable', {
1511
+ get() {
1512
+ const raw = this.getAttribute('contenteditable');
1513
+ if (raw === null)
1514
+ return 'inherit';
1515
+ const state = raw.toLowerCase();
1516
+ if (state === '')
1517
+ return 'true';
1518
+ return CONTENT_EDITABLE_STATES.includes(state) ? state : 'inherit';
1519
+ },
1520
+ set(value) {
1521
+ const state = `${value}`.toLowerCase();
1522
+ if (state === 'inherit') {
1523
+ this.removeAttribute('contenteditable');
1524
+ return;
1525
+ }
1526
+ if (!CONTENT_EDITABLE_STATES.includes(state))
1527
+ throw new DOMException(`Failed to set the 'contentEditable' property on 'HTMLElement': The value provided ` +
1528
+ `('${value}') is not one of 'true', 'false', 'plaintext-only' or 'inherit'.`, 'SyntaxError');
1529
+ this.setAttribute('contenteditable', state);
1530
+ },
1531
+ configurable: true,
1532
+ });
1533
+ for (const [property, attribute] of Object.entries(REFLECTED_PRESENCE)) {
1534
+ Object.defineProperty(Shim.prototype, property, {
1535
+ get() {
1536
+ return this.hasAttribute(attribute);
1537
+ },
1538
+ set(value) {
1539
+ if (value)
1540
+ this.setAttribute(attribute, '');
1541
+ else
1542
+ this.removeAttribute(attribute);
1543
+ },
1544
+ configurable: true,
1545
+ });
1546
+ }
1547
+ for (const [words, table] of [
1548
+ [['true', 'false'], REFLECTED_TRUE_FALSE],
1549
+ [['yes', 'no'], REFLECTED_YES_NO],
1550
+ ]) {
1551
+ for (const [property, entry] of Object.entries(table)) {
1552
+ /** `['attribute', default]` where the default differs per property; a bare string means `true`. */
1553
+ const [attribute, fallback] = Array.isArray(entry) ? entry : [entry, true];
1554
+ Object.defineProperty(Shim.prototype, property, {
1555
+ get() {
1556
+ const written = this.getAttribute(attribute);
1557
+ return written === null ? fallback : written !== words[1];
1558
+ },
1559
+ set(value) {
1560
+ this.setAttribute(attribute, value ? words[0] : words[1]);
1561
+ },
1562
+ configurable: true,
1563
+ });
1564
+ }
1565
+ }
1566
+ for (const [property, attribute] of Object.entries(REFLECTED_NUMBERS)) {
1567
+ Object.defineProperty(Shim.prototype, property, {
1568
+ get() {
1569
+ const written = this.getAttribute(attribute);
1570
+ if (written !== null)
1571
+ return Number(written);
1572
+ const conditional = CONDITIONALLY_FOCUSABLE[this.localName];
1573
+ return FOCUSABLE.has(this.localName) || (conditional && this.hasAttribute(conditional)) ? 0 : -1;
1574
+ },
1575
+ set(value) {
1576
+ this.setAttribute(attribute, Number(value));
1577
+ },
1578
+ configurable: true,
1579
+ });
1580
+ }
1581
+ for (const property of ARIA_PROPERTIES) {
1582
+ const attribute = dashedAria(property);
1583
+ Object.defineProperty(Shim.prototype, property, {
1584
+ get() {
1585
+ return this.getAttribute(attribute);
1586
+ },
1587
+ set(value) {
1588
+ if (value == null)
1589
+ this.removeAttribute(attribute);
1590
+ else
1591
+ this.setAttribute(attribute, value);
1592
+ },
1593
+ configurable: true,
1594
+ });
1595
+ }
1596
+ };
1597
+ /**
1598
+ * The ARIA reflection family, named once. Each is `aria-` plus the rest, lowercased —
1599
+ * `ariaValueMax` is `aria-valuemax` — with no exceptions in the set a component uses.
1600
+ */
1601
+ const ARIA_PROPERTIES = [
1602
+ 'ariaAtomic', 'ariaAutoComplete', 'ariaBrailleLabel', 'ariaBrailleRoleDescription', 'ariaBusy',
1603
+ 'ariaChecked', 'ariaColCount', 'ariaColIndex',
1604
+ 'ariaColIndexText', 'ariaColSpan', 'ariaCurrent', 'ariaDescription', 'ariaDisabled',
1605
+ 'ariaExpanded', 'ariaHasPopup', 'ariaHidden', 'ariaInvalid', 'ariaKeyShortcuts', 'ariaLabel',
1606
+ 'ariaLevel', 'ariaLive', 'ariaModal', 'ariaMultiLine', 'ariaMultiSelectable', 'ariaOrientation',
1607
+ 'ariaPlaceholder', 'ariaPosInSet', 'ariaPressed', 'ariaReadOnly', 'ariaRelevant', 'ariaRequired',
1608
+ 'ariaRoleDescription', 'ariaRowCount', 'ariaRowIndex', 'ariaRowIndexText', 'ariaRowSpan',
1609
+ 'ariaSelected', 'ariaSetSize', 'ariaSort', 'ariaValueMax', 'ariaValueMin', 'ariaValueNow',
1610
+ 'ariaValueText',
1611
+ ];
1612
+ /**
1613
+ * A component's own `attributeChangedCallback`, when it declared one.
1614
+ *
1615
+ * Read through a cast rather than declared as a field: a field in this base class would be an own
1616
+ * property set to `undefined`, which shadows the subclass's method and silently switches observed
1617
+ * attributes back off — the very thing this exists to deliver.
1618
+ */
1619
+ const observerOf = (element) => element.attributeChangedCallback;
1620
+ export class ElementShim extends ContainerShim {
1621
+ constructor(localName = '', namespaceURI = HTML_NS, made) {
1622
+ super();
1623
+ /**
1624
+ * **`Illegal constructor`, as in every engine, unless this DOM is the one creating it** (2026-10-09): `new
1625
+ * HTMLElement()`, `new HTMLElement('div')` and `new X()` for a class never defined all constructed here. Only a
1626
+ * DEFINED class may be constructed directly — `new.target` exactly, so a subclass of a defined class is refused too.
1627
+ */
1628
+ if (made !== MADE && !constructible.has(new.target))
1629
+ throw new TypeError('Illegal constructor');
1630
+ this._ns = namespaceURI;
1631
+ this.localName = localName;
1632
+ this.isConnected = true;
1633
+ this._attributes = new Map();
1634
+ this.innerHTML = '';
1635
+ this._shadowRoot = null;
1636
+ /**
1637
+ * The bytes this element's own tags were parsed from, when it came from markup rather than
1638
+ * `createElement`. Declared here so every element has the same shape — and so a type-checker
1639
+ * knows about a field the parser is what assigns.
1640
+ */
1641
+ this._sourceOpenTag = null;
1642
+ this._sourceCloseTag = null;
1643
+ }
1644
+ get namespaceURI() {
1645
+ return this._ns;
1646
+ }
1647
+ /**
1648
+ * An attribute name as this element stores it.
1649
+ *
1650
+ * A browser lower-cases the name inside `setAttribute` on an HTML element, so `setAttribute('Data-Flag', '1')`
1651
+ * and `getAttribute('data-flag')` are the *same* attribute. Storing the name as written made them two,
1652
+ * and a component that set one spelling and read another got `null` on the server and `'1'` in the
1653
+ * browser — a lifecycle divergence with no symptom until the two renders disagreed. Worse, an
1654
+ * attribute handed in as `{ 'User-ID': … }` never matched an `observedAttributes` entry, so
1655
+ * `attributeChangedCallback` simply did not fire.
1656
+ */
1657
+ _name(name) {
1658
+ /**
1659
+ * **Template coercion, not `String()`** — the difference is a symbol, which `String()` answers
1660
+ * `'Symbol(s)'` for and which every engine refuses with a `TypeError` (recorded across all
1661
+ * three in `tests/browser/dom-string-coercion.test.js`). Being the lenient one server-side
1662
+ * only moves the failure to the client with the context stripped off.
1663
+ */
1664
+ return this._ns === HTML_NS ? `${name}`.toLowerCase() : `${name}`;
1665
+ }
1666
+ /**
1667
+ * **`mode: 'closed'` means `element.shadowRoot` is `null`** — that is the entire difference between
1668
+ * the two modes, and it was not honored: a closed root was handed straight back, so a component
1669
+ * guarding on `this.shadowRoot` took the branch the browser will not, and anything holding the
1670
+ * element could reach inside a root the platform hides. The root is kept on `_shadowRoot`, because
1671
+ * it still has to be serialized — declarative shadow DOM expresses `closed` perfectly well
1672
+ * (`<template shadowrootmode="closed">`) and the client's parser re-creates it just as hidden.
1673
+ */
1674
+ get shadowRoot() {
1675
+ return this._shadowRoot?.mode === 'closed' ? null : this._shadowRoot;
1676
+ }
1677
+ /**
1678
+ * Both refusals are the platform's. `mode` is a required member, and an element that already has
1679
+ * a root raises `NotSupportedError` rather than getting a second one — which matters here because
1680
+ * silently replacing the first root discards everything rendered into it, on the server only.
1681
+ * `@verajs/core` already guards against calling this twice *because* the browser throws; the shim
1682
+ * accepting it meant the server was the one place that guard was not being checked.
1683
+ */
1684
+ attachShadow(init = {}) {
1685
+ if (init.mode !== 'open' && init.mode !== 'closed')
1686
+ throw new TypeError("Failed to execute 'attachShadow' on 'Element': Failed to read the 'mode' property from 'ShadowRootInit': Required member is undefined.");
1687
+ if (this._shadowRoot)
1688
+ throw new DOMException("Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree.", 'NotSupportedError');
1689
+ this._shadowRoot = new ShadowRootShim(init);
1690
+ this._shadowRoot._host = this;
1691
+ return this._shadowRoot;
1692
+ }
1693
+ getAttribute(name) {
1694
+ name = this._name(name);
1695
+ return this._attributes.has(name) ? this._attributes.get(name) : null;
1696
+ }
1697
+ setAttribute(name, value) {
1698
+ name = this._name(name);
1699
+ /**
1700
+ * **A name the platform refuses is refused here**, because the alternative is worse than a
1701
+ * throw: `setAttribute('a b', v)` wrote `a b="v"` into the tag, which a parser reads back as
1702
+ * *two* attributes, so the server and the client disagreed about the element's own attributes
1703
+ * and the browser threw `InvalidCharacterError` on the same call anyway.
1704
+ */
1705
+ if (name === '' || UNUSABLE_IN_A_NAME.test(name))
1706
+ throw new DOMException(`Failed to execute 'setAttribute' on 'Element': '${name}' is not a valid attribute name.`, 'InvalidCharacterError');
1707
+ const previous = this.getAttribute(name);
1708
+ this._attributes.set(name, `${value}`);
1709
+ this._attributeChanged(name, previous);
1710
+ }
1711
+ hasAttribute(name) {
1712
+ return this._attributes.has(this._name(name));
1713
+ }
1714
+ /**
1715
+ * `force` decides, and when the attribute is already in the wanted state **nothing happens** —
1716
+ * no write, no callback. This used to reset the value to `''` on `toggleAttribute(name, true)`
1717
+ * for an attribute that was already there, which silently erased it.
1718
+ */
1719
+ toggleAttribute(name, force) {
1720
+ name = this._name(name);
1721
+ if (name === '' || UNUSABLE_IN_A_NAME.test(name))
1722
+ throw new DOMException(`Failed to execute 'toggleAttribute' on 'Element': '${name}' is not a valid attribute name.`, 'InvalidCharacterError');
1723
+ const present = this._attributes.has(name);
1724
+ const wanted = force ?? !present;
1725
+ if (wanted === present)
1726
+ return wanted;
1727
+ /** The OLD value, read before the change: it was read after the delete, so a removal reported `null` -> `null`. */
1728
+ const old = this.getAttribute(name);
1729
+ if (wanted)
1730
+ this._attributes.set(name, '');
1731
+ else
1732
+ this._attributes.delete(name);
1733
+ this._attributeChanged(name, old);
1734
+ return wanted;
1735
+ }
1736
+ /**
1737
+ * Upgrade, the way the parser does it: `attributeChangedCallback` fires once per **present**
1738
+ * observed attribute, before `connectedCallback`, with a `null` old value.
1739
+ *
1740
+ * It never fired at all on the server. `attributeChangedCallback` is the only reactive-attribute
1741
+ * mechanism a plain custom element has, so a component that derives its state there rendered
1742
+ * its *initial* state into the page and then corrected itself on the client — a hydration
1743
+ * mismatch on every such component, and a flash of the wrong content for anyone without JS.
1744
+ */
1745
+ upgrade() {
1746
+ this._observed = this.constructor.observedAttributes;
1747
+ this._upgraded = true;
1748
+ const changed = observerOf(this);
1749
+ if (!this._observed || !changed)
1750
+ return;
1751
+ for (const name of this._observed) {
1752
+ const value = this.getAttribute(name);
1753
+ if (value !== null)
1754
+ changed.call(this, name, null, value);
1755
+ }
1756
+ }
1757
+ /**
1758
+ * And it keeps firing afterwards, because a browser does: a component that changes its own
1759
+ * attribute during a render sees the callback on the client and must see it here.
1760
+ *
1761
+ * Guarded on `_upgraded` first, which is the common case for the renderer's attribute writes —
1762
+ * an element mid-upgrade has no observers yet, and one that observes nothing never reaches the
1763
+ * `includes`.
1764
+ */
1765
+ _attributeChanged(name, previous) {
1766
+ /**
1767
+ * **A written element stops being its source text.** A parsed element serves the bytes it came
1768
+ * from so a parse can reproduce the page exactly; the moment an attribute changes, those bytes
1769
+ * are stale and canonical output takes over. Every write — `setAttribute`, `removeAttribute`,
1770
+ * `toggleAttribute` — arrives here, which is why this is the only place it has to be said.
1771
+ */
1772
+ this._sourceOpenTag = null;
1773
+ if (!this._upgraded || !this._observed?.includes(name))
1774
+ return;
1775
+ /**
1776
+ * Fired even when the value did not change, because a browser does: `setAttribute` runs the
1777
+ * attribute-change steps unconditionally. Only a *no-op* — removing what was not there,
1778
+ * toggling to the state it is already in — is silent, and those never reach here.
1779
+ */
1780
+ observerOf(this)?.call(this, name, previous, this.getAttribute(name));
1781
+ }
1782
+ /** Enough of a `NamedNodeMap` to iterate, which is what component code does with it. */
1783
+ /**
1784
+ * An array rather than a live `NamedNodeMap` — already a recorded difference, since there is
1785
+ * nothing to be live over in a single render pass. **The map's own methods are on it**, though:
1786
+ * `attributes.getNamedItem('x')` is how a good deal of existing code reads an attribute, and it
1787
+ * was simply missing, so that code got a `TypeError` on the server and worked in a browser.
1788
+ */
1789
+ get attributes() {
1790
+ return namedNodeMap(this);
1791
+ }
1792
+ getAttributeNames() {
1793
+ return [...this._attributes.keys()];
1794
+ }
1795
+ /**
1796
+ * `this.dataset.x = 'y'` and `this.style.color = 'red'` both change the markup, so both write
1797
+ * through to the attribute they are a view of. A plain object would accept the assignment and
1798
+ * lose it.
1799
+ */
1800
+ get dataset() {
1801
+ return datasetView(this);
1802
+ }
1803
+ get style() {
1804
+ return styleView(this);
1805
+ }
1806
+ /**
1807
+ * The platform's `style` is `[SameObject, PutForwards=cssText]` — `el.style = 'color: red'`
1808
+ * assigns THROUGH to `cssText` in every engine (and in jsdom, the regression net). The shim
1809
+ * declared only the getter, so the ordinary spelling threw `Cannot set property` server-side:
1810
+ * a component-prop delivery of `.style` was refused as read-only while the client accepted and
1811
+ * reflected it — the exact server/client divergence the differential rule exists to catch.
1812
+ * `[LegacyNullToEmptyString]` rides the same IDL attribute, so `null` means `''`.
1813
+ */
1814
+ set style(value) {
1815
+ styleView(this).cssText = value === null ? '' : `${value}`;
1816
+ }
1817
+ removeAttribute(name) {
1818
+ name = this._name(name);
1819
+ if (!this._attributes.has(name))
1820
+ return;
1821
+ const previous = this.getAttribute(name);
1822
+ this._attributes.delete(name);
1823
+ this._attributeChanged(name, previous);
1824
+ }
1825
+ /**
1826
+ * The rest of the surface an ordinary custom element reaches for.
1827
+ *
1828
+ * The shim was built as "the smallest DOM core's server path touches", which is the wrong bar:
1829
+ * the code that runs here is *user* code, and a component that emits an event, reads its
1830
+ * `tagName`, or adds a class in `connectedCallback` is doing nothing unusual. Each of these threw
1831
+ * a `TypeError` that took the whole render down — measured: `dispatchEvent`, `ownerDocument`,
1832
+ * `tagName`, `children`, `classList`, `closest` and `getRootNode`, all of them.
1833
+ *
1834
+ * They answer the way a detached, childless element would, because that is what this is.
1835
+ */
1836
+ get tagName() {
1837
+ return this.localName.toUpperCase();
1838
+ }
1839
+ get nodeType() {
1840
+ return 1;
1841
+ }
1842
+ get nodeName() {
1843
+ return this.tagName;
1844
+ }
1845
+ /** Walks the real parent chain, which exists now that children are nodes. */
1846
+ closest(selector) {
1847
+ return select.closest(this, selector);
1848
+ }
1849
+ matches(selector) {
1850
+ return select.matches(this, selector);
1851
+ }
1852
+ /**
1853
+ * **A no-op until nodes were retained** — an appended child had been flattened into its parent's
1854
+ * markup, so there was no parent to ask and nothing to take out. It silently left the element on
1855
+ * the page.
1856
+ */
1857
+ remove() {
1858
+ this._parent?.removeChild(this);
1859
+ }
1860
+ /**
1861
+ * Backed by the `class` attribute, so a class added during `connectedCallback` reaches the
1862
+ * markup — which it now can, because the opening tag is written from these attributes rather
1863
+ * than copied from the source text.
1864
+ */
1865
+ get classList() {
1866
+ return tokenListView(this, 'class');
1867
+ }
1868
+ /** `[PutForwards=value]`, for the same reason as `part`. */
1869
+ set classList(value) {
1870
+ this.setAttribute('class', value);
1871
+ }
1872
+ /**
1873
+ * What a **detached, childless** element answers.
1874
+ *
1875
+ * Every one of these is the truthful answer for this element, not a placeholder: an element with
1876
+ * no parent has no siblings and no parent, an element outside a document has no box, and a
1877
+ * childless one contains nothing. A browser returns exactly these values for a detached element.
1878
+ * They are here because their *absence* was a `TypeError` that took the whole render down —
1879
+ * `this.parentElement && …` is ordinary defensive code and it crashed.
1880
+ */
1881
+ /** No layout on a server, and none for a detached element in a browser either. */
1882
+ getBoundingClientRect() {
1883
+ return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0, toJSON: () => ({}) };
1884
+ }
1885
+ getClientRects() {
1886
+ return [];
1887
+ }
1888
+ checkVisibility() {
1889
+ return false;
1890
+ }
1891
+ /**
1892
+ * **The collection queries answer from the tree.** Each returned an empty array whatever the tree
1893
+ * held — the same placeholder shape `querySelector` had, and just as silent. They are live
1894
+ * `HTMLCollection`s in a browser and plain arrays here, a deliberate difference recorded in the
1895
+ * README: there is nothing to be live *over* while a render is a single pass. (That comment said
1896
+ * "already recorded" while the README said nothing about it — the difference is written down now,
1897
+ * along with the `item()`/`namedItem()` half of it that was a side effect rather than a decision.)
1898
+ */
1899
+ getElementsByTagName(name) {
1900
+ parseChunks(this);
1901
+ const wanted = `${name}`.toLowerCase();
1902
+ return select.descendantsOf(this).filter((element) => wanted === '*' || element.localName === wanted);
1903
+ }
1904
+ getElementsByTagNameNS(namespace, name) {
1905
+ parseChunks(this);
1906
+ const wanted = `${name}`.toLowerCase();
1907
+ const ns = `${namespace}`;
1908
+ return select
1909
+ .descendantsOf(this)
1910
+ .filter((element) => (wanted === '*' || element.localName === wanted) && (ns === '*' || element.namespaceURI === ns));
1911
+ }
1912
+ getElementsByClassName(names) {
1913
+ parseChunks(this);
1914
+ const wanted = `${names}`.split(/\s+/u).filter(Boolean);
1915
+ if (!wanted.length)
1916
+ return [];
1917
+ return select.descendantsOf(this).filter((element) => {
1918
+ const has = (element.getAttribute('class') ?? '').split(/\s+/u);
1919
+ return wanted.every((one) => has.includes(one));
1920
+ });
1921
+ }
1922
+ /**
1923
+ * Namespaces collapse to the plain attribute methods. This DOM serializes HTML, where an
1924
+ * `xml:lang` or `xlink:href` is one attribute with a colon in its name — which is how the
1925
+ * serializer already treats it, and how the markup reads it back.
1926
+ */
1927
+ getAttributeNS(_namespace, name) {
1928
+ return this.getAttribute(name);
1929
+ }
1930
+ setAttributeNS(_namespace, name, value) {
1931
+ this.setAttribute(name, value);
1932
+ }
1933
+ hasAttributeNS(_namespace, name) {
1934
+ return this.hasAttribute(name);
1935
+ }
1936
+ removeAttributeNS(_namespace, name) {
1937
+ this.removeAttribute(name);
1938
+ }
1939
+ hasAttributes() {
1940
+ return this._attributes.size > 0;
1941
+ }
1942
+ getAttributeNode(name) {
1943
+ return this.hasAttribute(name) ? { name, value: this.getAttribute(name) } : null;
1944
+ }
1945
+ getAttributeNodeNS(_namespace, name) {
1946
+ return this.getAttributeNode(name);
1947
+ }
1948
+ setAttributeNode(node) {
1949
+ this.setAttribute(node.name, node.value);
1950
+ return null;
1951
+ }
1952
+ setAttributeNodeNS(node) {
1953
+ return this.setAttributeNode(node);
1954
+ }
1955
+ removeAttributeNode(node) {
1956
+ this.removeAttribute(node.name);
1957
+ return node;
1958
+ }
1959
+ /** Aliases the engines still carry. */
1960
+ webkitMatchesSelector() {
1961
+ return false;
1962
+ }
1963
+ mozMatchesSelector() {
1964
+ return false;
1965
+ }
1966
+ /**
1967
+ * Interaction, which a server has none of — but the calls are ordinary and must not throw.
1968
+ *
1969
+ * `click()` is the exception: it *dispatches an event*, and now that listeners are real, a
1970
+ * component that clicks itself to seed its own state gets the same result on both sides.
1971
+ */
1972
+ focus() { }
1973
+ blur() { }
1974
+ click() {
1975
+ this.dispatchEvent(new globalThis.Event('click', { bubbles: true, cancelable: true, composed: true }));
1976
+ }
1977
+ scrollIntoView() { }
1978
+ scroll() { }
1979
+ scrollTo() { }
1980
+ scrollBy() { }
1981
+ /**
1982
+ * All four positions. `beforebegin`/`afterend` used to be refused outright on the claim that
1983
+ * this element has no parent — true for a component root, and FALSE for everything inside one:
1984
+ * `_parent` is live for any nested element (the `outerHTML` setter below runs on it), so a
1985
+ * component doing `this.querySelector(…).insertAdjacentHTML('afterend', …)` worked in the
1986
+ * browser and took the whole server render down. The two positions now splice into the parent's
1987
+ * entries exactly as `outerHTML=` does, and only a genuine orphan refuses — with the platform's
1988
+ * own answer, `NoModificationAllowedError`, measured on jsdom and Chromium (the spec raises it
1989
+ * for a null or Document parent; a bare `Error` here was a second divergence inside the first).
1990
+ *
1991
+ * **A markup sink, deliberately** (CODE-PRINCIPLES #8). It writes what it is given, exactly as
1992
+ * the DOM's own `insertAdjacentHTML` does, because a component calling it has already decided
1993
+ * that: the same call on the client is the same sink, and a server that escaped where the browser
1994
+ * does not would render one page and hydrate into another. `insertAdjacentText` escapes, which is
1995
+ * the difference between the two methods and the one to reach for with anything from a request.
1996
+ */
1997
+ insertAdjacentHTML(position, markup) {
1998
+ const where = `${position}`.toLowerCase();
1999
+ if (where === 'afterbegin' || where === 'beforeend') {
2000
+ if (where === 'afterbegin')
2001
+ this._entries.unshift(`${markup}`);
2002
+ else
2003
+ this._entries.push(`${markup}`);
2004
+ /** New markup has not been looked at yet. */
2005
+ this._parsed = false;
2006
+ }
2007
+ else if (where !== 'beforebegin' && where !== 'afterend')
2008
+ throw new DOMException(`Failed to execute 'insertAdjacentHTML' on 'Element': The value provided ` +
2009
+ `('${position}') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.`, 'SyntaxError');
2010
+ else {
2011
+ const parent = this._parent;
2012
+ if (!parent)
2013
+ throw new DOMException(`Failed to execute 'insertAdjacentHTML' on 'Element': The element has no parent.`, 'NoModificationAllowedError');
2014
+ const index = parent._entries.indexOf(this);
2015
+ parent._entries.splice(where === 'beforebegin' ? index : index + 1, 0, `${markup}`);
2016
+ parent._parsed = false;
2017
+ }
2018
+ }
2019
+ insertAdjacentText(position, text) {
2020
+ this.insertAdjacentHTML(position, escapeHtml(text));
2021
+ }
2022
+ insertAdjacentElement(position, element) {
2023
+ this.insertAdjacentHTML(position, serializeElement(element));
2024
+ return element;
2025
+ }
2026
+ /** The element's own markup, which the serializer builds anyway. */
2027
+ get outerHTML() {
2028
+ return serializeElement(this);
2029
+ }
2030
+ /**
2031
+ * **Replaces this element in its parent with the given markup.** Assigning it used to be a
2032
+ * `TypeError` — there was no setter — so `element.outerHTML = '<p>x</p>'`, an ordinary way to swap
2033
+ * a node out, did nothing on the server and worked in the browser.
2034
+ *
2035
+ * **With no parent it returns silently**, which is what the spec says and what all three engines
2036
+ * do — measured, because the obvious guess was a `NoModificationAllowedError` and that is wrong:
2037
+ * the spec raises it only when the parent is a *Document*, not when there is no parent at all.
2038
+ */
2039
+ set outerHTML(markup) {
2040
+ const parent = this._parent;
2041
+ if (!parent)
2042
+ return;
2043
+ parent._entries.splice(parent._entries.indexOf(this), 1, `${markup}`);
2044
+ parent._parsed = false;
2045
+ this._parent = null;
2046
+ }
2047
+ get innerText() {
2048
+ return this.textContent;
2049
+ }
2050
+ /**
2051
+ * **A line break becomes a `<br>`, which is the whole difference from `textContent`.** Every
2052
+ * engine splits the assigned string on `\r\n`, `\r` and `\n` and joins the escaped pieces with
2053
+ * `<br>`; assigning through `textContent` instead left a literal newline, which collapses to a
2054
+ * single space when the page is laid out. So a component that set `innerText` rendered its lines
2055
+ * run together on the server and correctly broken on the client — a visible difference in the
2056
+ * markup itself, not merely in what a property reads back.
2057
+ *
2058
+ * Measured on Chromium, Firefox and WebKit, attached and detached, in
2059
+ * `tests/browser/inner-text.test.js`.
2060
+ */
2061
+ set innerText(value) {
2062
+ this.innerHTML = `${value}`.split(/\r\n|[\r\n]/u).map(escapeHtml).join('<br>');
2063
+ }
2064
+ /** `part` is a token list over the `part` attribute, exactly as `classList` is over `class`. */
2065
+ get part() {
2066
+ return tokenListView(this, 'part');
2067
+ }
2068
+ /**
2069
+ * **Assignable, because the IDL says `[PutForwards=value]`.** Both `part` and `classList` are
2070
+ * declared that way, so `element.part = 'a b'` is a legal operation in every engine and writes
2071
+ * the attribute. A getter with no setter made it a `TypeError` here instead — a server that
2072
+ * refuses what the browser performs, which is the same failure as being too permissive with the
2073
+ * direction reversed.
2074
+ */
2075
+ set part(value) {
2076
+ this.setAttribute('part', value);
2077
+ }
2078
+ /**
2079
+ * Form-associated custom elements.
2080
+ *
2081
+ * `attachInternals()` not existing meant `static formAssociated = true` — the standard way to
2082
+ * write a custom form control — threw during `connectedCallback` and took the page with it. None
2083
+ * of what internals carry reaches markup (form value, validity and implicit ARIA are all
2084
+ * internal state), so this is inert by design rather than by omission: the component runs, and
2085
+ * the client's real internals take over on hydration.
2086
+ */
2087
+ attachInternals() {
2088
+ /**
2089
+ * **Only a custom element has internals.** Every engine raises `NotSupportedError` for a plain
2090
+ * element, because `ElementInternals` is the mechanism by which a *defined* element joins a form
2091
+ * — there is nothing for a `<div>` to attach. Allowing it here meant a call that cannot work in
2092
+ * a browser worked on the server, which is the leniency this DOM exists not to have.
2093
+ */
2094
+ if (!registry.has(this.localName))
2095
+ throw new DOMException(`Failed to execute 'attachInternals' on 'HTMLElement': Unable to attach ElementInternals to non-custom elements.`, 'NotSupportedError');
2096
+ /** A second call raises `NotSupportedError` in every engine; returning the first set hid that. */
2097
+ if (internals.has(this))
2098
+ throw new DOMException(`Failed to execute 'attachInternals' on 'HTMLElement': ElementInternals for the specified element was already attached.`, 'NotSupportedError');
2099
+ internals.set(this, {
2100
+ shadowRoot: this._shadowRoot,
2101
+ form: null,
2102
+ labels: [],
2103
+ willValidate: true,
2104
+ validity: { valid: true },
2105
+ validationMessage: '',
2106
+ states: new Set(),
2107
+ setFormValue: () => { },
2108
+ setValidity: () => { },
2109
+ checkValidity: () => true,
2110
+ reportValidity: () => true,
2111
+ });
2112
+ return internals.get(this);
2113
+ }
2114
+ /**
2115
+ * The element's own opening tag, written from the attributes it holds **now**.
2116
+ *
2117
+ * Copying the source text instead meant everything a component did to itself during
2118
+ * `connectedCallback` was thrown away: `setAttribute('role', 'button')`, a class, an `aria-*` —
2119
+ * present on the client after hydration, absent in the server markup, so the two disagreed on
2120
+ * every one.
2121
+ */
2122
+ /**
2123
+ * **A copy that shares nothing.** The reason this was out of scope was that a copy sharing the
2124
+ * markup string would alias it; entries are an array now, so a deep clone copies them. The source
2125
+ * text rides along, so a cloned subtree still reproduces the markup it was parsed from.
2126
+ */
2127
+ cloneNode(deep = false) {
2128
+ const copy = createElement(this.localName, this._ns);
2129
+ for (const [name, value] of this._attributes)
2130
+ copy.setAttribute(name, value);
2131
+ copy._sourceOpenTag = this._sourceOpenTag;
2132
+ copy._sourceCloseTag = this._sourceCloseTag;
2133
+ if (!deep)
2134
+ return copy;
2135
+ for (const entry of this._entries) {
2136
+ if (typeof entry === 'string')
2137
+ copy._entries.push(entry);
2138
+ else {
2139
+ const child = entry.cloneNode(true);
2140
+ child._parent = copy;
2141
+ copy._entries.push(child);
2142
+ }
2143
+ }
2144
+ copy._parsed = this._parsed;
2145
+ return copy;
2146
+ }
2147
+ /** This element's own markup, end tag included — the call every node kind answers. */
2148
+ /**
2149
+ * A `<slot>` shows the host's children that name it; see `assignedTo`.
2150
+ *
2151
+ * **Getters returning `undefined` off a slot**, because these live on `HTMLSlotElement` and this
2152
+ * DOM has one element class. Defining them as plain methods put them on every element, where
2153
+ * `typeof element.assignedNodes === 'function'` — the ordinary way to ask "is this a slot" —
2154
+ * answered yes for a `<div>`. Being present where the platform has nothing is the same kind of
2155
+ * divergence as answering wrongly, and it is the one a feature check walks straight into.
2156
+ */
2157
+ get assignedNodes() {
2158
+ if (this.localName !== 'slot')
2159
+ return undefined;
2160
+ return (options) => assignedTo(this, options);
2161
+ }
2162
+ get assignedElements() {
2163
+ if (this.localName !== 'slot')
2164
+ return undefined;
2165
+ return (options) => assignedTo(this, options).filter((node) => node.nodeType === 1);
2166
+ }
2167
+ markup() {
2168
+ return serializeElement(this);
2169
+ }
2170
+ openTag() {
2171
+ /**
2172
+ * **The bytes it was parsed from**, until something writes to it. That is what lets a parsed
2173
+ * tree reproduce its own markup exactly — quoting style, entity spelling, attribute order and
2174
+ * interior whitespace included — instead of normalizing the page as a side effect of somebody
2175
+ * reading `children`.
2176
+ */
2177
+ if (this._sourceOpenTag)
2178
+ return this._sourceOpenTag;
2179
+ let out = `<${this.localName}`;
2180
+ for (const [name, value] of this._attributes)
2181
+ out += ` ${name}="${escapeHtml(value)}"`;
2182
+ return out + '>';
2183
+ }
2184
+ /**
2185
+ * Tags stripped and the escaping undone, so what goes in comes back out.
2186
+ *
2187
+ * Reading back what `textContent` had just written returned `&#60;b&#62;` for `<b>` — the setter
2188
+ * escapes and the getter did not decode, so the round trip a component may reasonably rely on was
2189
+ * broken. Only the numeric references the setter emits need undoing; anything else in there came
2190
+ * from author markup and is text as written.
2191
+ */
2192
+ get textContent() {
2193
+ return textOf(this);
2194
+ }
2195
+ /**
2196
+ * Escaped for an ordinary element, stored as-is for a raw-text one.
2197
+ *
2198
+ * `@verajs/styles` sets a `<style>` element's `textContent` to the stylesheet, and escaping it
2199
+ * turned every `>` into `&#62;` and every `"` into `&#34;`. A browser does not decode those inside
2200
+ * `<style>`, so a component with `static styles = '.a > .b { … }'` shipped a broken stylesheet —
2201
+ * every child selector, every attribute selector, every `content: "…"`. The client never had it:
2202
+ * there, `textContent` sets real text and the serializer of a raw-text element emits it verbatim.
2203
+ */
2204
+ /**
2205
+ * **`null` and `undefined` are the empty string, not their own names.** `textContent` is a
2206
+ * nullable `DOMString` with `[LegacyNullToEmptyString]`, and WebIDL converts `undefined` to `null`
2207
+ * for a nullable type — so both erase the content in every engine. This wrote the text `null`,
2208
+ * which meant `this.textContent = maybeMissing` put the word on the page server-side and nothing
2209
+ * client-side: a hydration mismatch produced by ordinary defensive code.
2210
+ */
2211
+ set textContent(value) {
2212
+ const text = value == null ? '' : value;
2213
+ if (RAW_TEXT_ELEMENTS.has(this.localName))
2214
+ this._replaceWithText(`${text}`);
2215
+ else
2216
+ this.innerHTML = escapeHtml(text);
2217
+ }
2218
+ }
2219
+ /**
2220
+ * `document.createElement('my-comp')` builds **the component**, not a blank element.
2221
+ *
2222
+ * A browser upgrades a known tag as it creates it, so the class's constructor runs and its field
2223
+ * initializers are in place before anyone touches the element. This returned a bare `ElementShim`,
2224
+ * so a component created imperatively had none of its own state, and `instanceof` said no.
2225
+ */
2226
+ /**
2227
+ * A fresh element carrying the properties its tag actually has — `input.disabled`, `a.href` — as
2228
+ * well as the ones every element shares. See `reflections.js`; without this an assignment to an
2229
+ * element-specific property became a plain JavaScript property that reached no markup at all.
2230
+ *
2231
+ * Only HTML elements get one. An SVG element's properties are a different interface again, and
2232
+ * guessing at them is what this whole file exists not to do.
2233
+ */
2234
+ const build = (name, namespaceURI = HTML_NS) => {
2235
+ const Element = namespaceURI === HTML_NS ? interfaceFor(name, ElementShim) : ElementShim;
2236
+ return new Element(name, namespaceURI, MADE);
2237
+ };
2238
+ export const createElement = (localName, namespaceURI = HTML_NS) => {
2239
+ const name = namespaceURI === HTML_NS ? `${localName}`.toLowerCase() : `${localName}`;
2240
+ /**
2241
+ * **A tag name that cannot be written is refused**, as it is in every engine. Accepting one meant
2242
+ * `createElement('a b')` serialized `<a b>` — an element `a` with an empty attribute `b` once a
2243
+ * parser sees it — and `createElement('')` produced `<>`. Both render markup no browser would
2244
+ * have produced from the same call, which is the one thing this DOM exists not to do.
2245
+ */
2246
+ if (name === '' || UNUSABLE_IN_A_TAG.test(name))
2247
+ throw new DOMException(`Failed to execute 'createElement' on 'Document': The tag name provided ('${name}') is not a valid name.`, 'InvalidCharacterError');
2248
+ const Component = registry.get(name);
2249
+ if (!Component)
2250
+ return build(name, namespaceURI);
2251
+ /** Constructed against the installed globals, so a component's `HTMLElement` base is `ElementShim`. */
2252
+ const element = new Component();
2253
+ element.localName = name;
2254
+ element._ns = namespaceURI;
2255
+ return element;
2256
+ };
2257
+ /**
2258
+ * Instances handed to `appendChild` before they have rendered, so the scan renders **them** rather
2259
+ * than a fresh copy built from their markup.
2260
+ *
2261
+ * The nested-component scan reads emitted markup and instantiates what it finds, which is right for
2262
+ * a tag written in a template and wrong for an element the component built itself: everything
2263
+ * assigned to it — `kid.rows = data`, the ordinary way to hand structured data to a child — was
2264
+ * lost, because an attribute cannot carry it and a fresh instance never saw it. The marker attribute
2265
+ * is the handle, and `renderComponent` removes it as it renders.
2266
+ */
2267
+ export const pendingInstances = new Map();
2268
+ /**
2269
+ * The marker's **name** carries a per-process random token, because the markup it is written into is
2270
+ * not all ours.
2271
+ *
2272
+ * `children` and the string form of `attributes` are raw markup by design, so a caller passing
2273
+ * request data through either hands an attacker a way to write attributes into this document. With a
2274
+ * fixed name, injected markup could claim a component's prepared instance — and win, because it is
2275
+ * already in the markup when the real one is appended, and the scan reads in order. Demonstrated: an
2276
+ * injected `<x-y vera-ssr-instance="1">` rendered with the parent's data while the parent's own
2277
+ * child fell back to defaults. A name nothing outside this module can guess closes it, and
2278
+ * `renderComponent` also refuses a marker whose instance is not the tag being rendered.
2279
+ *
2280
+ * Import-time rather than per-render: an attacker cannot read either, and the output never contains
2281
+ * the marker, so nothing observable depends on it.
2282
+ */
2283
+ export const INSTANCE_ATTRIBUTE = `vera-ssr-${crypto.randomUUID()}`;
2284
+ let instanceCount = 0;
2285
+ /**
2286
+ * Marks `node` as a prepared instance and returns its id, so the nested-component scan renders THIS
2287
+ * instance rather than a fresh copy built from its markup. Two callers, one discipline:
2288
+ * `appendChild` below, for an element a component built itself, and the template serializer, for a
2289
+ * component tag whose property bindings it is delivering — both stamp the node (so `prepareInstance`
2290
+ * can unregister it by the attribute) and both rely on the unguessable name above.
2291
+ *
2292
+ * @returns the instance id, for the caller that writes markup itself
2293
+ */
2294
+ export const markPending = (node) => {
2295
+ const id = String(++instanceCount);
2296
+ node.setAttribute(INSTANCE_ATTRIBUTE, id);
2297
+ pendingInstances.set(id, node);
2298
+ return id;
2299
+ };
2300
+ /** One `ElementInternals` per element, as `attachInternals` guarantees. */
2301
+ const internals = new WeakMap();
2302
+ /**
2303
+ * Installed once, here, because both are properties of *every* node of their kind rather than of any
2304
+ * one of them — and generating them beats sixty hand-written accessors that go stale.
2305
+ */
2306
+ defineReflections(ElementShim);
2307
+ /** `Node`'s constants are on every node, so they go on the shared base — text and comments included. */
2308
+ Object.assign(NodeBaseShim.prototype, NODE_CONSTANTS);
2309
+ /**
2310
+ * **And on the interface object itself.** WebIDL puts a constant on both the prototype and the
2311
+ * constructor, so `node.nodeType === Node.TEXT_NODE` is the ordinary spelling — and `Node` is this
2312
+ * class (`shim.js` assigns it). The constants reached instances and not the constructor, so that
2313
+ * comparison was against `undefined` and quietly false for every node.
2314
+ */
2315
+ Object.assign(NodeBaseShim, NODE_CONSTANTS);
2316
+ /**
2317
+ * **What `String(node)` says** — the interface's name, as every engine answers (`[object Text]`), where it said
2318
+ * `[object EventTarget]` for every node. The kinds with one interface each; an element's depends on its tag (a measured
2319
+ * table, not a guess — still open), so elements keep the base answer for now.
2320
+ */
2321
+ for (const [Kind, tag] of [[NodeBaseShim, 'Node'], [CharacterDataShim, 'CharacterData'], [TextShim, 'Text'], [CommentShim, 'Comment'], [FragmentShim, 'DocumentFragment'], [ShadowRootShim, 'ShadowRoot']])
2322
+ Object.defineProperty(Kind.prototype, Symbol.toStringTag, { value: tag, configurable: true });