@verajs/ssr 0.2.1 → 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 +507 -390
  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 +389 -302
  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 -1187
  44. package/src/vera/nodes.js +0 -2294
  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 -1080
  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,853 @@
1
+ /**
2
+ * Installs the server environment: the globals a component finds when it runs outside a browser.
3
+ *
4
+ * Import this **before anything that imports `@verajs/core`** — core evaluates against these, and
5
+ * `@verajs/ssr` does it for you. What each global is, and why it answers the way it does, lives
6
+ * with the thing it is made of: the nodes in `./nodes.js`, escaping in `./escaping.js`, the frame
7
+ * queue in `./frames.js`, stylesheets in `./stylesheets.js`, the registry in `./registry.js`.
8
+ *
9
+ * The rule every one of them follows: **answer honestly or do not exist** — and its corollary,
10
+ * **where the platform throws, this throws.** A server that is lenient about an error does not make
11
+ * anything work: it moves the failure to the client, strips the context that would have explained
12
+ * it, and in the meantime writes markup no browser would have produced from the same call. That
13
+ * corollary has found more defects here than asking whether a member is present, because a member
14
+ * that is present and too permissive looks exactly like one that is correct. A detached element has no
15
+ * parent, no siblings and no box, and a browser returns exactly what these do. Where a server cannot
16
+ * answer at all — `localStorage` is one browser's state — the global stays undefined, because
17
+ * `typeof localStorage === 'undefined'` is the guard the ecosystem already writes and it only works
18
+ * if this does not lie. `tests/ssr-dom-surface.test.mjs` enforces both halves.
19
+ */
20
+ import { escapeHtml, escapeStyleText, escapeRawText, RAW_TEXT_ELEMENTS } from './escaping.js';
21
+ import { hoistedStyles, setRenderingTag, StyleSheetShim, hoist, beginHoisting, documentAdoptedSheets, setDocumentAdoptedSheets } from './stylesheets.js';
22
+ import { beginBudget, bounded, cancelFrame, endBudget, flushFrames, flushFramesAsync, requestFrame, setCoreFlush } from './frames.js';
23
+ import { constructible, registry } from './registry.js';
24
+ import { NodeBaseShim, CharacterDataShim, TextShim, CommentShim, FragmentShim, ShadowRootShim, ElementShim, createElement, pendingInstances, INSTANCE_ATTRIBUTE, NODE_CONSTANTS, } from './nodes.js';
25
+ /** The eight hyphenated names SVG and MathML already define, which a custom element may not take. */
26
+ const RESERVED_NAMES = new Set([
27
+ 'annotation-xml',
28
+ 'color-profile',
29
+ 'font-face',
30
+ 'font-face-src',
31
+ 'font-face-uri',
32
+ 'font-face-format',
33
+ 'font-face-name',
34
+ 'missing-glyph',
35
+ ]);
36
+ /** A name `define` accepts — the spec's rule, shared with `whenDefined` so the two refuse exactly the same names. */
37
+ const validName = (name) => typeof name === 'string' && /^[a-z][^A-Z]*-[^A-Z]*$/.test(name) && !RESERVED_NAMES.has(name);
38
+ /**
39
+ * The promises `whenDefined` handed out for names not yet defined, settled by their `define`. Cleared at each render's
40
+ * start: a wait from a finished render has nothing left to resume, and names that come from DATA (tags found in user
41
+ * content) would otherwise grow it for the life of the process.
42
+ */
43
+ const pendingDefinitions = new Map();
44
+ /** What `index.ts` needs of it: the names still awaited — named when a render runs out of time — and the per-render reset. */
45
+ export const pendingDefinitionNames = () => [...pendingDefinitions.keys()];
46
+ export const resetPendingDefinitions = () => pendingDefinitions.clear();
47
+ /**
48
+ * Re-exported so a consumer of the server environment has one import, not seven. The homes above are
49
+ * where the code lives; this is the door.
50
+ */
51
+ export { escapeHtml, escapeStyleText, escapeRawText, RAW_TEXT_ELEMENTS, hoistedStyles, beginHoisting, setRenderingTag, flushFrames, flushFramesAsync, setCoreFlush, beginBudget, bounded, endBudget, registry, pendingInstances, INSTANCE_ATTRIBUTE, };
52
+ /**
53
+ * The three event methods, bound to a real `EventTarget`, ready to spread onto a plain-object shim.
54
+ *
55
+ * `document` and `window` are object literals rather than classes, so they cannot simply extend
56
+ * `EventTarget` the way the containers do. They still have to *work*: both were no-ops that
57
+ * reported every event delivered.
58
+ *
59
+ * The dispatched event's `target` is corrected to the shim, because the listener reads it and
60
+ * `document` is the answer it expects — not the private object the listeners happen to live on.
61
+ * An own property shadows `Event`'s prototype getter, which is read-only.
62
+ *
63
+ * @param self What the event should report as its target, resolved at dispatch
64
+ * because `document` does not exist yet when this is called.
65
+ */
66
+ const delegateEvents = (target, self) => ({
67
+ addEventListener: target.addEventListener.bind(target),
68
+ removeEventListener: target.removeEventListener.bind(target),
69
+ dispatchEvent: (event) => {
70
+ for (const name of ['target', 'currentTarget'])
71
+ Object.defineProperty(event, name, { value: self(), configurable: true });
72
+ return target.dispatchEvent(event);
73
+ },
74
+ });
75
+ /** `window` and the global scope are the same object here, so they share one target. */
76
+ const windowEvents = new EventTarget();
77
+ /** Idempotent. Installs the server environment; the registry is filled as modules execute. */
78
+ /**
79
+ * The roots a document-level query has to cover. `documentElement` and `body` are separate elements
80
+ * here rather than one nested pair, so every query walks both — `documentElement` first, which is
81
+ * where a real document would find anything under `<html>` before reaching `<body>`.
82
+ */
83
+ /** A filter's verdict as the platform reads it: `whatToShow` first (a node it excludes is SKIPPED), then the filter. */
84
+ const ACCEPT = 1;
85
+ const REJECT = 2;
86
+ const SKIP = 3;
87
+ const verdictOf = (node, whatToShow, filter) => {
88
+ const bit = node.nodeType === 1 ? 1 : node.nodeType === 3 ? 4 : node.nodeType === 8 ? 128 : 0;
89
+ // eslint-disable-next-line no-bitwise -- whatToShow is the platform's own NodeFilter bitmask
90
+ if (!(whatToShow & bit))
91
+ return SKIP;
92
+ const verdict = typeof filter === 'function' ? filter(node) : filter?.acceptNode?.(node);
93
+ return verdict === REJECT || verdict === SKIP ? verdict : ACCEPT;
94
+ };
95
+ const linked = (node) => (node ?? null);
96
+ /**
97
+ * `createNodeIterator`: document order, the root included, forwards and backwards. An iterator reads `FILTER_REJECT`
98
+ * as `FILTER_SKIP` — only a walker prunes — so a flat filtered list is exactly its answer.
99
+ */
100
+ const makeIterator = (root, whatToShow = 0xffffffff, filter) => {
101
+ /** Document order, depth first. `childNodes` rather than `_entries`: it is what makes markup held as a string get parsed. */
102
+ const flatten = (node, out = []) => {
103
+ for (const child of node.childNodes ?? []) {
104
+ out.push(child);
105
+ flatten(child, out);
106
+ }
107
+ return out;
108
+ };
109
+ let current = null;
110
+ const step = (direction) => {
111
+ const nodes = [root, ...flatten(root)].filter((node) => verdictOf(node, whatToShow, filter) === ACCEPT);
112
+ const index = current === null ? -1 : nodes.indexOf(current);
113
+ const next = direction > 0 ? nodes[index + 1] : nodes[index - 1];
114
+ if (!next)
115
+ return null;
116
+ current = next;
117
+ return next;
118
+ };
119
+ return { root, whatToShow, filter: filter ?? null, nextNode: () => step(1), previousNode: () => step(-1) };
120
+ };
121
+ /**
122
+ * **`createTreeWalker`, by the DOM standard's own algorithms** — "traverse children", "traverse siblings" and the
123
+ * rest, transcribed rather than approximated. The approximation climbed above `root` in `parentNode`, gave up in
124
+ * `nextSibling` at the first filtered sibling instead of searching on (into a SKIPPED sibling's children, past a
125
+ * REJECTED one's), and never pruned a REJECTED subtree in `nextNode`. jsdom implements the same algorithms, and
126
+ * `tests/ssr-tree-walker.test.mjs` compares the two over generated trees and filters.
127
+ */
128
+ const makeTreeWalker = (root, whatToShow = 0xffffffff, filter) => {
129
+ let current = root;
130
+ const judge = (node) => verdictOf(node, whatToShow, filter);
131
+ const children = (first) => {
132
+ let node = linked(first ? linked(current).firstChild : linked(current).lastChild);
133
+ while (node !== null) {
134
+ const result = judge(node);
135
+ if (result === ACCEPT)
136
+ return (current = node);
137
+ if (result === SKIP) {
138
+ const child = linked(first ? node.firstChild : node.lastChild);
139
+ if (child !== null) {
140
+ node = child;
141
+ continue;
142
+ }
143
+ }
144
+ while (node !== null) {
145
+ const sibling = linked(first ? node.nextSibling : node.previousSibling);
146
+ if (sibling !== null) {
147
+ node = sibling;
148
+ break;
149
+ }
150
+ const parent = linked(node.parentNode);
151
+ if (parent === null || parent === root || parent === current)
152
+ return null;
153
+ node = parent;
154
+ }
155
+ }
156
+ return null;
157
+ };
158
+ const siblings = (next) => {
159
+ let node = linked(current);
160
+ if (node === root)
161
+ return null;
162
+ for (;;) {
163
+ let sibling = linked(next ? node.nextSibling : node.previousSibling);
164
+ while (sibling !== null) {
165
+ node = sibling;
166
+ const result = judge(node);
167
+ if (result === ACCEPT)
168
+ return (current = node);
169
+ sibling = linked(next ? node.firstChild : node.lastChild);
170
+ if (result === REJECT || sibling === null)
171
+ sibling = linked(next ? node.nextSibling : node.previousSibling);
172
+ }
173
+ const parent = linked(node.parentNode);
174
+ if (parent === null || parent === root)
175
+ return null;
176
+ node = parent;
177
+ if (judge(node) === ACCEPT)
178
+ return null;
179
+ }
180
+ };
181
+ return {
182
+ root,
183
+ whatToShow,
184
+ filter: filter ?? null,
185
+ get currentNode() {
186
+ return current;
187
+ },
188
+ set currentNode(node) {
189
+ current = node;
190
+ },
191
+ parentNode: () => {
192
+ let node = linked(current);
193
+ while (node !== null && node !== root) {
194
+ node = linked(node.parentNode);
195
+ if (node !== null && judge(node) === ACCEPT)
196
+ return (current = node);
197
+ }
198
+ return null;
199
+ },
200
+ firstChild: () => children(true),
201
+ lastChild: () => children(false),
202
+ nextSibling: () => siblings(true),
203
+ previousSibling: () => siblings(false),
204
+ previousNode: () => {
205
+ let node = linked(current);
206
+ while (node !== root) {
207
+ let sibling = linked(node.previousSibling);
208
+ while (sibling !== null) {
209
+ node = sibling;
210
+ let result = judge(node);
211
+ while (result !== REJECT && linked(node.lastChild) !== null) {
212
+ node = linked(node.lastChild);
213
+ result = judge(node);
214
+ }
215
+ if (result === ACCEPT)
216
+ return (current = node);
217
+ sibling = linked(node.previousSibling);
218
+ }
219
+ const parent = linked(node.parentNode);
220
+ if (node === root || parent === null)
221
+ return null;
222
+ node = parent;
223
+ if (judge(node) === ACCEPT)
224
+ return (current = node);
225
+ }
226
+ return null;
227
+ },
228
+ nextNode: () => {
229
+ let node = linked(current);
230
+ let result = ACCEPT;
231
+ for (;;) {
232
+ while (result !== REJECT && linked(node.firstChild) !== null) {
233
+ node = linked(node.firstChild);
234
+ result = judge(node);
235
+ if (result === ACCEPT)
236
+ return (current = node);
237
+ }
238
+ let sibling = null;
239
+ let temporary = node;
240
+ while (temporary !== null) {
241
+ if (temporary === root)
242
+ return null;
243
+ sibling = linked(temporary.nextSibling);
244
+ if (sibling !== null) {
245
+ node = sibling;
246
+ break;
247
+ }
248
+ temporary = linked(temporary.parentNode);
249
+ }
250
+ if (sibling === null)
251
+ return null;
252
+ result = judge(node);
253
+ if (result === ACCEPT)
254
+ return (current = node);
255
+ }
256
+ },
257
+ };
258
+ };
259
+ const documentRoots = () => [globalThis.document.documentElement, globalThis.document.body];
260
+ /**
261
+ * Which parts of a URL `location` carries — the one place that knows.
262
+ *
263
+ * `index.js` kept its own copy for `applyLocation`/`restoreLocation` to walk. They agreed, and
264
+ * nothing made them: a part added to one list would be installed and never restored, or restored
265
+ * from a property the install never wrote. Same single fact, same reasoning as `RAW_TEXT_ELEMENTS`
266
+ * below it — CODE-PRINCIPLES #5.
267
+ */
268
+ export const LOCATION_PARTS = [
269
+ 'href', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash', 'origin',
270
+ ];
271
+ export const installShims = () => {
272
+ if (globalThis.__veraSsrShimmed)
273
+ return registry;
274
+ globalThis.__veraSsrShimmed = true;
275
+ /**
276
+ * Every assignment here is a deliberate lie: a shim is not an `HTMLElement`, and saying so is the
277
+ * point — elements hold strings, not trees. The casts mark each one as intended rather than
278
+ * missed, which is what type-checking this package is for. Anything a component genuinely reaches
279
+ * for is on `ElementShim`; anything else was never going to work server-side anyway.
280
+ */
281
+ globalThis.HTMLElement = ElementShim;
282
+ globalThis.CSSStyleSheet = StyleSheetShim;
283
+ /**
284
+ * The DOM interfaces, so `instanceof` answers correctly.
285
+ *
286
+ * `value instanceof Node` is how ordinary code tells a node from a string, and `Node` being undefined made it a
287
+ * `ReferenceError` rather than `false`. These are the real shim classes, so an element made here *is* a `Node`, an
288
+ * `Element` and an `HTMLElement`, exactly as it would be in a browser — and since 2026-10-09 a text node is a `Node`,
289
+ * a `CharacterData` and a `Text` too: `Node` was the container class, so text and comments answered `false`, and
290
+ * `Text`, `Comment` and `CharacterData` were not exposed at all.
291
+ */
292
+ globalThis.Node = NodeBaseShim;
293
+ globalThis.CharacterData = CharacterDataShim;
294
+ globalThis.Text = TextShim;
295
+ globalThis.Comment = CommentShim;
296
+ globalThis.Element = ElementShim;
297
+ globalThis.ShadowRoot = ShadowRootShim;
298
+ /**
299
+ * `Document` exists so that **feature detection** can read it.
300
+ *
301
+ * The standard constructed-stylesheet probe is
302
+ * `ShadowRoot && 'adoptedStyleSheets' in Document.prototype && 'replace' in CSSStyleSheet.prototype`
303
+ * — lit's, and everyone else's. Defining `ShadowRoot` without `Document` moved that probe from
304
+ * "no shadow DOM at all" to "shadow DOM, now read `Document.prototype`", which threw. Every
305
+ * clause is true of this environment, so all three are answerable and the probe takes the branch
306
+ * this shim actually supports.
307
+ *
308
+ * The document is a literal rather than a class — it has one instance and no subclasses — so it
309
+ * is given this prototype rather than built from it.
310
+ */
311
+ globalThis.Document = (class Document {
312
+ });
313
+ Object.defineProperty(globalThis.Document.prototype, 'adoptedStyleSheets', { value: [], writable: true });
314
+ globalThis.DocumentFragment = FragmentShim;
315
+ /** `new Image()` is a spelling of `createElement('img')`, and `Audio` of `createElement('audio')`. */
316
+ globalThis.Image = (class Image extends ElementShim {
317
+ constructor() {
318
+ super('img');
319
+ }
320
+ });
321
+ globalThis.Audio = (class Audio extends ElementShim {
322
+ constructor() {
323
+ super('audio');
324
+ }
325
+ });
326
+ constructible.add(globalThis.Image);
327
+ constructible.add(globalThis.Audio);
328
+ /**
329
+ * The observers, inert.
330
+ *
331
+ * Every one of them observes something a server does not have — a viewport, a box, a live tree —
332
+ * so none can ever fire here. What matters is that constructing one does not throw: a component
333
+ * that lazy-loads on intersection, or watches its own size, is written for a browser and must
334
+ * still *render* on a server. `@verajs/autoloader` builds a `MutationObserver`, which made an app
335
+ * entry that wires it unrenderable.
336
+ */
337
+ for (const name of ['IntersectionObserver', 'ResizeObserver', 'MutationObserver', 'PerformanceObserver'])
338
+ globalThis[name] = class Observer {
339
+ observe() { }
340
+ unobserve() { }
341
+ disconnect() { }
342
+ takeRecords() {
343
+ return [];
344
+ }
345
+ };
346
+ /**
347
+ * A media query with no viewport to match matches nothing, which is what every server renderer
348
+ * answers and what hydration then corrects. Absent, it was a `TypeError` in `connectedCallback`.
349
+ */
350
+ globalThis.matchMedia = ((media) => ({
351
+ media,
352
+ matches: false,
353
+ addEventListener: () => { },
354
+ removeEventListener: () => { },
355
+ addListener: () => { },
356
+ removeListener: () => { },
357
+ dispatchEvent: () => true,
358
+ onchange: null,
359
+ }));
360
+ /** No layout means no computed value; a browser gives a detached element nothing useful either. */
361
+ globalThis.getComputedStyle = (() => ({
362
+ getPropertyValue: () => '',
363
+ getPropertyPriority: () => '',
364
+ length: 0,
365
+ item: () => '',
366
+ }));
367
+ globalThis.getSelection = () => null;
368
+ /**
369
+ * Idle time joins the frame queue rather than inventing a second one — the render is over when
370
+ * `flushFrames` runs out, and work deferred to "when the browser is free" has to land before
371
+ * then or it lands nowhere.
372
+ */
373
+ globalThis.requestIdleCallback = ((fn) => requestFrame(() => fn({ didTimeout: false, timeRemaining: () => 0 }), true));
374
+ globalThis.cancelIdleCallback = ((id) => cancelFrame(id, true));
375
+ /** Defined so core's `@scope` support check passes — SSR output gets scoped light-DOM CSS. */
376
+ globalThis.CSSScopeRule = (function CSSScopeRule() { });
377
+ globalThis.customElements = ({
378
+ /**
379
+ * Refused on a second definition, exactly as the platform does. The registry used to overwrite
380
+ * silently, so a module defining a tag twice rendered fine on the server and threw
381
+ * `NotSupportedError` in the browser — the server being lenient about an error is the server
382
+ * hiding it.
383
+ */
384
+ define: (name, Class) => {
385
+ /**
386
+ * **A name the browser will refuse is refused here too**, or the server renders markup the
387
+ * client can never upgrade: `customElements.define('nodash', …)` throws `SyntaxError` in every
388
+ * engine, and this accepted it — so the component rendered server-side, shipped, and the
389
+ * client threw on the very line that was supposed to bring it to life.
390
+ *
391
+ * The rule is the spec's: starts with a lowercase ASCII letter, contains a hyphen, contains no
392
+ * uppercase, and is not one of the eight names SVG and MathML already use.
393
+ */
394
+ if (!validName(name))
395
+ throw new DOMException(`Failed to execute 'define' on 'CustomElementRegistry': "${String(name)}" is not a valid custom element name`, 'SyntaxError');
396
+ /**
397
+ * Refused as the platform refuses: a value that is not a constructor (`TypeError`), and a class already defined
398
+ * under another name (`NotSupportedError` — one class, one definition). Both were accepted here.
399
+ */
400
+ if (typeof Class !== 'function' || !Class.prototype)
401
+ throw new TypeError(`Failed to execute 'define' on 'CustomElementRegistry': parameter 2 is not a constructor.`);
402
+ for (const defined of registry.values())
403
+ if (defined === Class)
404
+ throw new DOMException(`Failed to execute 'define' on 'CustomElementRegistry': this constructor has already been used with this registry`, 'NotSupportedError');
405
+ if (registry.has(name)) {
406
+ throw new DOMException(`Failed to execute 'define' on 'CustomElementRegistry': the name "${name}" has already been used with this registry`, 'NotSupportedError');
407
+ }
408
+ registry.set(name, Class);
409
+ constructible.add(Class);
410
+ const waiting = pendingDefinitions.get(name);
411
+ if (waiting !== undefined) {
412
+ pendingDefinitions.delete(name);
413
+ waiting.resolve(Class);
414
+ }
415
+ },
416
+ get: (name) => registry.get(name),
417
+ /**
418
+ * **The platform's promise**: resolved WITH the constructor, at once for a defined name, at its `define` for a
419
+ * later one — one promise per name until then — and rejected with `SyntaxError` for a name `define` would refuse.
420
+ * It resolved immediately with `undefined` for any name, so code awaiting a definition ran before it existed and
421
+ * got no class, and a client-only component's wait, which never settles in a browser, settled on the server.
422
+ */
423
+ whenDefined: (name) => {
424
+ if (!validName(name))
425
+ return Promise.reject(new DOMException(`Failed to execute 'whenDefined' on 'CustomElementRegistry': "${String(name)}" is not a valid custom element name`, 'SyntaxError'));
426
+ const defined = registry.get(name);
427
+ if (defined !== undefined)
428
+ return Promise.resolve(defined);
429
+ let waiting = pendingDefinitions.get(name);
430
+ if (waiting === undefined) {
431
+ let resolve;
432
+ const promise = new Promise((done) => (resolve = done));
433
+ pendingDefinitions.set(name, (waiting = { promise, resolve }));
434
+ }
435
+ return waiting.promise;
436
+ },
437
+ });
438
+ /**
439
+ * The document, with the surface a component reaches for.
440
+ *
441
+ * `body`, `documentElement` and `title` are real enough to be written to — a component setting
442
+ * `document.title` or appending to `document.body` is ordinary code, and losing the assignment
443
+ * silently is the failure mode this package keeps producing. Queries answer emptily for the same
444
+ * reason the containers do: this holds strings, not a tree.
445
+ */
446
+ globalThis.document = ({
447
+ title: '',
448
+ body: createElement('body'),
449
+ documentElement: createElement('html'),
450
+ /**
451
+ * **`body` is what a browser reports when nothing has focus**, and it never answers `null` for a
452
+ * document that exists. `null` here meant `document.activeElement.tagName` — ordinary code —
453
+ * threw on the server and worked in the browser.
454
+ */
455
+ get activeElement() {
456
+ return globalThis.document.body;
457
+ },
458
+ /**
459
+ * This document *has* a `documentElement`, so saying it has no children contradicted itself —
460
+ * the same shape as `document.contains` answering `false` while every element reported
461
+ * `isConnected`. One element, first and last, exactly as a real document reports.
462
+ */
463
+ get firstElementChild() {
464
+ return globalThis.document.documentElement;
465
+ },
466
+ get lastElementChild() {
467
+ return globalThis.document.documentElement;
468
+ },
469
+ get childElementCount() {
470
+ return 1;
471
+ },
472
+ createElement: (localName) => createElement(localName),
473
+ createElementNS: (namespace, localName) => createElement(localName, namespace),
474
+ createTextNode: (text) => new TextShim(text),
475
+ createDocumentFragment: () => new FragmentShim(),
476
+ /**
477
+ * **The document's queries search the document.** Each answered nothing whatever it was asked,
478
+ * because there was no tree to search; `document.getElementById('x')` was `null` for an element
479
+ * that had been appended to `body` moments earlier.
480
+ *
481
+ * `documentElement` and `body` are separate roots here rather than one nested pair, so each
482
+ * query covers both — the order is `documentElement` first, which is where a real document would
483
+ * have found anything under `<html>` before reaching `<body>`.
484
+ */
485
+ querySelector: (selector) => {
486
+ for (const root of documentRoots()) {
487
+ const found = root.querySelector(selector);
488
+ if (found)
489
+ return found;
490
+ }
491
+ return null;
492
+ },
493
+ querySelectorAll: (selector) => documentRoots().flatMap((root) => root.querySelectorAll(selector)),
494
+ getElementById: (id) => {
495
+ for (const root of documentRoots()) {
496
+ const found = root.getElementById(id);
497
+ if (found)
498
+ return found;
499
+ }
500
+ return null;
501
+ },
502
+ ...NODE_CONSTANTS,
503
+ getElementsByTagName: (name) => documentRoots().flatMap((root) => root.getElementsByTagName(name)),
504
+ getElementsByTagNameNS: (namespace, name) => documentRoots().flatMap((root) => root.getElementsByTagNameNS(namespace, name)),
505
+ getElementsByClassName: (names) => documentRoots().flatMap((root) => root.getElementsByClassName(names)),
506
+ /**
507
+ * The elements whose `name` attribute IS `name`, compared directly. It was a selector built from the name with only
508
+ * `"` escaped, so a `\\` was read as a CSS escape (`a\\b` matched nothing, or the wrong elements).
509
+ */
510
+ getElementsByName: (name) => {
511
+ const wanted = `${name}`;
512
+ return documentRoots()
513
+ .flatMap((root) => [root, ...root.querySelectorAll('[name]')])
514
+ .filter((element) => element.getAttribute('name') === wanted);
515
+ },
516
+ /**
517
+ * **`complete`, because nothing more is coming.** `loading` is the truthful description of a
518
+ * document still being assembled, and it is the wrong answer to give a component: the guard
519
+ * everyone writes is `if (readyState === 'loading') addEventListener('DOMContentLoaded', boot)`,
520
+ * and this DOM never fires that event — so `loading` meant the callback was registered and never
521
+ * ran, and the component silently rendered nothing. `@verajs/jsx/standalone` is written exactly
522
+ * that way. `complete` sends the same code down the branch that runs `boot()` now, which is what
523
+ * the browser ends up doing too.
524
+ */
525
+ readyState: 'complete',
526
+ visibilityState: 'visible',
527
+ hidden: false,
528
+ characterSet: 'UTF-8',
529
+ inputEncoding: 'UTF-8',
530
+ charset: 'UTF-8',
531
+ contentType: 'text/html',
532
+ compatMode: 'CSS1Compat',
533
+ dir: '',
534
+ designMode: 'off',
535
+ nodeType: 9,
536
+ nodeName: '#document',
537
+ currentScript: null,
538
+ /**
539
+ * **`documentElement`, because this document declares standards mode.** `null` is the answer a
540
+ * *quirks-mode* document gives, so returning it beside `compatMode: 'CSS1Compat'` two lines up
541
+ * was a document contradicting itself — and a component reading
542
+ * `document.scrollingElement.scrollTop`, which every engine allows, crashed on the server with
543
+ * a `TypeError` and worked in the browser. Measured on Chromium, Firefox and WebKit: all three
544
+ * answer `documentElement`.
545
+ */
546
+ get scrollingElement() {
547
+ return globalThis.document.documentElement;
548
+ },
549
+ fullscreenElement: null,
550
+ pointerLockElement: null,
551
+ pictureInPictureElement: null,
552
+ /**
553
+ * The output is an HTML document, so it has a doctype. A browser reports these three fields and
554
+ * an empty public and system id, which is exactly what `<!doctype html>` means.
555
+ */
556
+ doctype: { name: 'html', publicId: '', systemId: '' },
557
+ children: [],
558
+ childNodes: [],
559
+ styleSheets: [],
560
+ forms: [],
561
+ images: [],
562
+ links: [],
563
+ scripts: [],
564
+ embeds: [],
565
+ plugins: [],
566
+ anchors: [],
567
+ hasFocus: () => false,
568
+ createComment: (text) => new CommentShim(text),
569
+ getSelection: () => null,
570
+ /**
571
+ * An empty walk over an empty tree, which is the truthful answer for a DOM that holds strings.
572
+ *
573
+ * `@verajs/renderer` builds two shared `TreeWalker`s **at import time**, so importing it threw
574
+ * here — and a component doing nothing unusual imports it: `keyed` and `hold` are exported from
575
+ * that entry, and a keyed list is the renderer's headline feature. Any component using either
576
+ * could not be server-rendered at all. Nothing walks this DOM (`@verajs/ssr` has its own
577
+ * renderer and never uses these), so an inert walker is the whole requirement.
578
+ */
579
+ /**
580
+ * **The walkers walk.** Both existed and answered `null` to everything, whatever the tree held —
581
+ * a stub that reported "no more nodes" from the first call, so a component walking its own
582
+ * subtree found it empty and did nothing, on the server only. There is a tree to walk now.
583
+ */
584
+ createTreeWalker: (root, whatToShow, filter) => makeTreeWalker(root, whatToShow, filter),
585
+ createNodeIterator: (root, whatToShow, filter) => makeIterator(root, whatToShow, filter),
586
+ elementFromPoint: () => null,
587
+ elementsFromPoint: () => [],
588
+ /**
589
+ * Everything this DOM builds is in the document — the shim sets `isConnected` on every element
590
+ * for the same reason, since a server render is exactly the case where the tree *is* live. A
591
+ * flat `false` contradicted that, and `if (!document.contains(el)) return;` is ordinary
592
+ * defensive code that bailed out of a render that was in fact perfectly connected.
593
+ */
594
+ contains: (node) => node?.isConnected === true,
595
+ /**
596
+ * `importNode` CLONES — the spec's "import" is a copy into this document, never the node
597
+ * itself. The identity it used to return was a lie with teeth: a caller mutates the "copy"
598
+ * and corrupts the original (for the renderer's Instance, the template's canonical content —
599
+ * every later render of that template starts from the corrupted tree). Element, text and
600
+ * comment shims clone for real; a kind without `cloneNode` (a fragment) refuses loudly, which
601
+ * is this DOM's posture — decline what cannot be reproduced, never hand back an alias.
602
+ * `adoptNode` stays the identity: adopting MOVES a node and nothing here owns another
603
+ * document, so the node itself is the correct answer there.
604
+ */
605
+ importNode: (node, deep) => node.cloneNode(deep === true),
606
+ adoptNode: (node) => node,
607
+ get defaultView() {
608
+ return globalThis.window;
609
+ },
610
+ get URL() {
611
+ return globalThis.location?.href ?? '';
612
+ },
613
+ get documentURI() {
614
+ return globalThis.location?.href ?? '';
615
+ },
616
+ get baseURI() {
617
+ return globalThis.location?.href ?? '';
618
+ },
619
+ get referrer() {
620
+ return '';
621
+ },
622
+ /**
623
+ * Real listeners here too, delegated to an `EventTarget` of the document's own. A component
624
+ * that listens on `document` and dispatches there — a store broadcasting, a dialog closing on
625
+ * `keydown` it fires itself — behaved one way in a browser and not at all here.
626
+ */
627
+ ...delegateEvents(new EventTarget(), () => globalThis.document),
628
+ /** Light-DOM styles hoist here — `adoptStyles`' constructed-sheet path. See `documentAdoptedSheets`. */
629
+ get adoptedStyleSheets() {
630
+ return documentAdoptedSheets;
631
+ },
632
+ set adoptedStyleSheets(sheets) {
633
+ setDocumentAdoptedSheets(sheets);
634
+ },
635
+ head: {
636
+ /**
637
+ * A `<style>` appended to the head is the page's CSS, hoisted into the render's styles. Nothing else is: this
638
+ * hoisted ANY node's `innerHTML`, so an appended `<script>` shipped its source inside the stylesheet.
639
+ */
640
+ appendChild: (node) => {
641
+ if (node?.localName === 'style' && node.innerHTML)
642
+ hoist(node.innerHTML);
643
+ return node;
644
+ },
645
+ },
646
+ });
647
+ /** Given `Document.prototype` here, where the document it describes finally exists. */
648
+ Object.setPrototypeOf(globalThis.document, globalThis.Document.prototype);
649
+ /**
650
+ * Enough `window` for `@verajs/router` to initialize.
651
+ *
652
+ * Without it, a component calling `initRouter` threw `window is not defined` and could not be
653
+ * server-rendered at all — which rules out the app shell of every routed app, the exact thing
654
+ * server rendering is for. The router is careful to be *importable* in Node and says so; nothing
655
+ * made it *runnable*.
656
+ *
657
+ * Listeners are real — a component that dispatches a window event and listens for it, which is
658
+ * how loosely coupled components talk to each other, used to be talking into a no-op. Nothing on
659
+ * a server *navigates*, so `popstate` and friends still never arrive on their own. `location`
660
+ * describes the page being rendered, so a route resolves against a real path; set
661
+ * `globalThis.location.pathname` before `renderToString` to render a route other than `/`.
662
+ * `history` is inert: a server has no session history to push onto. A **per-request** URL belongs
663
+ * in `renderToString`'s `location` option, which applies it after every await and restores it
664
+ * afterwards; assigning to this global directly is safe only until two requests overlap.
665
+ */
666
+ globalThis.window = globalThis;
667
+ /**
668
+ * `self` is the other name for the global, and UMD bundles feature-detect on it. `window` is
669
+ * already defined here, so those bundles have taken the browser branch regardless — leaving `self`
670
+ * undefined only made the two disagree.
671
+ *
672
+ * **`??=`, because a Web Worker already has one and it is read-only.** Assigning threw
673
+ * `Cannot set property self of #<WorkerGlobalScope> which has only a getter`, which is where this
674
+ * shim stopped when it was first run off the main thread. Nothing is lost by skipping it there:
675
+ * in a worker `self` already *is* the global, which is exactly what this line wanted. Node
676
+ * defines no `self` on the main thread or inside `worker_threads`, so the server still assigns.
677
+ */
678
+ globalThis.self ??= globalThis;
679
+ /**
680
+ * Every part, built from a real `URL`, so the default is as complete as the one `renderToString`'s
681
+ * `location` option installs. It used to carry four properties — `pathname`, `search`, `hash`,
682
+ * `href` — so `location.origin`, `.protocol`, `.host` and `.hostname` read `undefined` until a
683
+ * render supplied a URL, and then started working. Two different shapes for the same object
684
+ * depending on when you looked at it.
685
+ */
686
+ /**
687
+ * **Installed as an own, writable property rather than assigned, because `applyLocation` mutates
688
+ * it and not every environment's `location` can be mutated.** `renderToString`'s `location` option
689
+ * writes each part in place, which a plain object takes and a Web Worker's real `WorkerLocation`
690
+ * refuses — every property is a getter, so a per-request URL threw
691
+ * `Cannot set property href of [object WorkerLocation]`. `??=` could not see that: a worker *has*
692
+ * a location, so it short-circuited and left the read-only one in place. Rendering one route per
693
+ * URL is the whole point of the option, so this is the difference between the option working and
694
+ * not.
695
+ *
696
+ * Seeded from whatever the environment describes, so a worker keeps its real URL as the default
697
+ * instead of being told it is localhost. Node has no `location` at all, on the main thread or in
698
+ * `worker_threads`, so the server gets the identical localhost object it got before — a writable,
699
+ * configurable own property is what a plain assignment already produced.
700
+ */
701
+ Object.defineProperty(globalThis, 'location', {
702
+ value: ((() => {
703
+ const url = new URL(globalThis.location?.href ?? 'http://localhost/');
704
+ return Object.fromEntries(LOCATION_PARTS.map((part) => [part, url[part]]));
705
+ })()),
706
+ writable: true,
707
+ configurable: true,
708
+ });
709
+ globalThis.history = ({
710
+ scrollRestoration: 'auto',
711
+ pushState: () => { },
712
+ replaceState: () => { },
713
+ go: () => { },
714
+ back: () => { },
715
+ forward: () => { },
716
+ });
717
+ Object.assign(globalThis, delegateEvents(windowEvents, () => globalThis.window));
718
+ /**
719
+ * **A server render is a top-level, unframed, open window — and saying nothing says otherwise.**
720
+ *
721
+ * This is the one place where *absence* gives the wrong answer rather than no answer.
722
+ * `window.top === window` is how a page asks "am I in an iframe"; with `top` undefined that
723
+ * comparison is **false**, so a component concludes it *is* framed and takes the branch meant for
724
+ * a page it does not control. Every value here is what a browser reports for a page that is not
725
+ * framed, which is exactly the situation a server render is in.
726
+ */
727
+ globalThis.top = globalThis;
728
+ globalThis.parent = globalThis;
729
+ globalThis.frames = globalThis;
730
+ globalThis.frameElement = null;
731
+ globalThis.opener = null;
732
+ globalThis.length = 0;
733
+ globalThis.closed = false;
734
+ /** `name` is `Window`'s, not `globalThis`'s, so TypeScript needs telling which one this is. */
735
+ globalThis.name ??= '';
736
+ /**
737
+ * Derived from `location` rather than stored, so the two cannot disagree — `renderToString`'s
738
+ * `location` option rewrites the URL per request, and a copied-at-install `origin` would answer
739
+ * for whichever request installed the shim.
740
+ */
741
+ Object.defineProperty(globalThis, 'origin', {
742
+ get: () => globalThis.location?.origin ?? '',
743
+ configurable: true,
744
+ });
745
+ /**
746
+ * **Inert, because a server has no user and no window to move** — the same reason the observers
747
+ * are inert and `scrollTo` already was. A browser does not throw for any of these, so neither can
748
+ * this: a component that calls one during setup would work in the browser and crash here, which
749
+ * is the divergence this package exists to remove.
750
+ *
751
+ * The ones with a return value get the answer a browser gives when the thing did not happen —
752
+ * `confirm` when the user declines, `prompt` when they cancel, `open` when the browser refuses,
753
+ * `find` when there is no match. None of those is invented; each is a real outcome of the call.
754
+ */
755
+ for (const name of [
756
+ 'alert', 'print', 'blur', 'focus', 'close', 'stop', 'scroll', 'scrollBy', 'scrollTo',
757
+ 'moveBy', 'moveTo', 'resizeBy', 'resizeTo', 'captureEvents', 'releaseEvents',
758
+ ])
759
+ globalThis[name] = () => { };
760
+ /**
761
+ * **`postMessage` is `??=` and the rest are not, because in a Web Worker it is the only channel
762
+ * back to the page.** Replacing it with a no-op does not throw and does not stop the render — it
763
+ * silently severs the host's reporting, so a worker that rendered perfectly looks exactly like one
764
+ * that crashed. That cost two debugging rounds the first time this shim ran off the main thread.
765
+ *
766
+ * **`close` deliberately stays unconditional**, which is the same reasoning arriving at the
767
+ * opposite answer: in a worker `close()` *terminates* it, so a component calling `window.close()`
768
+ * during setup would kill the render. A no-op is both what a browser does for a page it did not
769
+ * open and what protects the render; a host still terminates its worker from the outside.
770
+ *
771
+ * Node defines neither name — on the main thread or inside `worker_threads` — so the server
772
+ * assigns both exactly as before.
773
+ */
774
+ globalThis.postMessage ??= (() => { });
775
+ globalThis.confirm = () => false;
776
+ globalThis.prompt = () => null;
777
+ globalThis.find = () => false;
778
+ globalThis.open = () => null;
779
+ /**
780
+ * `reportError` hands an error to the page's error handling. A no-op would **swallow** it, which
781
+ * is the one outcome worse than not having the function — so it goes where every other unhandled
782
+ * failure in this package goes.
783
+ */
784
+ globalThis.reportError ??= (error) => console.error(error);
785
+ /**
786
+ * The `NodeFilter` constants, because `createTreeWalker` is provided and these are what it takes.
787
+ * `@verajs/renderer` passes the numbers directly, so nothing here needs them — but a component
788
+ * writing `NodeFilter.SHOW_ELEMENT` is writing ordinary DOM code, and these are facts rather than
789
+ * answers this DOM has to invent.
790
+ */
791
+ globalThis.NodeFilter = (Object.assign(function NodeFilter() {
792
+ throw new TypeError('Illegal constructor');
793
+ }, {
794
+ FILTER_ACCEPT: 1,
795
+ FILTER_REJECT: 2,
796
+ FILTER_SKIP: 3,
797
+ SHOW_ALL: 0xffffffff,
798
+ SHOW_ELEMENT: 1,
799
+ SHOW_ATTRIBUTE: 2,
800
+ SHOW_TEXT: 4,
801
+ SHOW_CDATA_SECTION: 8,
802
+ SHOW_ENTITY_REFERENCE: 16,
803
+ SHOW_ENTITY: 32,
804
+ SHOW_PROCESSING_INSTRUCTION: 64,
805
+ SHOW_COMMENT: 128,
806
+ SHOW_DOCUMENT: 256,
807
+ SHOW_DOCUMENT_TYPE: 512,
808
+ SHOW_DOCUMENT_FRAGMENT: 1024,
809
+ SHOW_NOTATION: 2048,
810
+ }));
811
+ Object.freeze(globalThis.NodeFilter);
812
+ /**
813
+ * Node supplies `Event` and `CustomEvent`; this fills in only where it does not, and matches the
814
+ * shape `EventTarget` dispatches.
815
+ */
816
+ globalThis.CustomEvent ??= (class CustomEvent extends Event {
817
+ constructor(type, init = {}) {
818
+ super(type, init);
819
+ this.detail = init.detail ?? null;
820
+ }
821
+ });
822
+ /**
823
+ * **The phase constants belong on the prototype, not only on the interface.** Node puts
824
+ * `CAPTURING_PHASE` and friends on `Event` alone; all three engines put them on `Event.prototype`
825
+ * too, so `event.AT_TARGET` reads `2` in a browser and `undefined` here. That matters because
826
+ * `event.eventPhase === event.AT_TARGET` is how the comparison is normally written, and against
827
+ * `undefined` it is `false` for every phase — the test silently never matches instead of failing.
828
+ */
829
+ for (const [name, value] of [['NONE', 0], ['CAPTURING_PHASE', 1], ['AT_TARGET', 2], ['BUBBLING_PHASE', 3]])
830
+ if (!(name in Event.prototype))
831
+ Object.defineProperty(Event.prototype, name, { value, enumerable: false, configurable: true });
832
+ /**
833
+ * Frames are queued and drained once the component's `connectedCallback` has returned — see
834
+ * `flushFrames`.
835
+ *
836
+ * This deferred to `setTimeout`, which ran every scheduled callback long after the response was
837
+ * built. Core's render scheduler is `requestAnimationFrame`, so any state a component settled
838
+ * after its first `render()` — the ordinary `render(); this.state.x = fromAttribute` shape —
839
+ * was dropped, and every effect was too. Both landed on the client instead, so the server
840
+ * shipped one page and the browser immediately replaced it with a different one.
841
+ *
842
+ * Shimmed rather than left undefined so that unguarded callers — `@verajs/router`'s initial
843
+ * navigation, any third-party component measuring itself — run instead of throwing.
844
+ */
845
+ /** A browser raises `TypeError` for a non-callable, and a silent no-op here is a frame that never runs. */
846
+ globalThis.requestAnimationFrame = (fn) => {
847
+ if (typeof fn !== 'function')
848
+ throw new TypeError(`Failed to execute 'requestAnimationFrame' on 'Window': parameter 1 is not of type 'Function'.`);
849
+ return requestFrame(fn, false);
850
+ };
851
+ globalThis.cancelAnimationFrame = (id) => cancelFrame(id, false);
852
+ return registry;
853
+ };