@verajs/ssr 0.2.1 → 0.3.1

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 +522 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +102 -0
  4. package/dist/vera/escaping.d.ts +155 -0
  5. package/dist/vera/escaping.js +293 -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 +2339 -0
  14. package/dist/vera/parse.d.ts +53 -0
  15. package/dist/vera/parse.js +485 -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 +1521 -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 +553 -0
  36. package/dist/vera/types.d.ts +121 -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,14 @@
1
+ import type { SsrRegistry } from './types.js';
2
+ /**
3
+ * The custom-element registry: the definitions this process has seen.
4
+ *
5
+ * Filled as component modules execute, since `customElements.define` is how a component announces
6
+ * itself, and read by the nested-component scan to decide whether a tag in emitted markup is
7
+ * something to render or something to leave alone.
8
+ */
9
+ export declare const registry: SsrRegistry;
10
+ /**
11
+ * The element classes code may construct directly, as in a browser (`new.target` exactly): every class `define`
12
+ * accepted, and the two legacy factories `Image` and `Audio`. Anything else is an `Illegal constructor`.
13
+ */
14
+ export declare const constructible: WeakSet<object>;
@@ -5,5 +5,9 @@
5
5
  * itself, and read by the nested-component scan to decide whether a tag in emitted markup is
6
6
  * something to render or something to leave alone.
7
7
  */
8
-
9
8
  export const registry = new Map();
9
+ /**
10
+ * The element classes code may construct directly, as in a browser (`new.target` exactly): every class `define`
11
+ * accepted, and the two legacy factories `Image` and `Audio`. Anything else is an `Illegal constructor`.
12
+ */
13
+ export const constructible = new WeakSet();
@@ -0,0 +1,27 @@
1
+ /**
2
+ * **How @verajs/ssr says what it says** (2026-10-09). Twins of @verajs/shared-utils' `misuse()`
3
+ * and `diagnostic()` DEVELOPMENT output — ssr cannot import the private package, so the shapes are restated here and
4
+ * `tests/ssr-shared-twins.test.mjs` holds the generated strings equal — plus the two server rules:
5
+ * text that came from outside is quoted, and a warning is said once per process per key, never at request rate.
6
+ */
7
+ type Said = readonly [string, string?];
8
+ /** A thrown message: `ssr: <sentence> <fix> (<code>)` — what `misuse('ssr', code, prose)` says in development. */
9
+ export declare const ssrMisuse: (code: string, prose: Said) => string;
10
+ /** A warning line: `[vera] ssr: <subject> — <sentence> <fix> (<code>)` — `diagnostic('ssr', subject, code, prose)`. */
11
+ export declare const ssrWarning: (subject: string, code: string, prose: Said) => string;
12
+ /**
13
+ * **Text from outside — an error's message, a URL, a selector, a name — quoted before it reaches a line.** A server's
14
+ * console is a log pipeline, and that text can be shaped by a request: a newline in it forges a log line, an ESC
15
+ * sequence hides one (log injection — the server's form of the '%s' class). `JSON.stringify` escapes both; cut to 80
16
+ * characters so one value cannot fill the log either.
17
+ */
18
+ /**
19
+ * `max` caps the length (80 by default); `Infinity` keeps the whole text for a value worth reading in full — a site
20
+ * owner's own path — which is still ESCAPED: truncation and escaping are separate jobs, and a path is not free of control
21
+ * characters just because its owner wrote it (2026-10-09).
22
+ */
23
+ export declare const quoted: (text: string, max?: number) => string;
24
+ export declare const once: (code: string, key?: string | object) => boolean;
25
+ export declare const own: <E extends Error>(error: E) => E;
26
+ export declare const isOwn: (error: unknown) => boolean;
27
+ export {};
@@ -0,0 +1,56 @@
1
+ const sentence = ([what, fix]) => `${what}${fix ? ` ${fix}` : ''}`;
2
+ /** A thrown message: `ssr: <sentence> <fix> (<code>)` — what `misuse('ssr', code, prose)` says in development. */
3
+ export const ssrMisuse = (code, prose) => `ssr: ${sentence(prose)} (${code})`;
4
+ /** A warning line: `[vera] ssr: <subject> — <sentence> <fix> (<code>)` — `diagnostic('ssr', subject, code, prose)`. */
5
+ export const ssrWarning = (subject, code, prose) => `[vera] ssr: ${subject} — ${sentence(prose)} (${code})`;
6
+ /**
7
+ * **Text from outside — an error's message, a URL, a selector, a name — quoted before it reaches a line.** A server's
8
+ * console is a log pipeline, and that text can be shaped by a request: a newline in it forges a log line, an ESC
9
+ * sequence hides one (log injection — the server's form of the '%s' class). `JSON.stringify` escapes both; cut to 80
10
+ * characters so one value cannot fill the log either.
11
+ */
12
+ /**
13
+ * `max` caps the length (80 by default); `Infinity` keeps the whole text for a value worth reading in full — a site
14
+ * owner's own path — which is still ESCAPED: truncation and escaping are separate jobs, and a path is not free of control
15
+ * characters just because its owner wrote it (2026-10-09).
16
+ */
17
+ export const quoted = (text, max = 80) => JSON.stringify(text.length > max ? `${text.slice(0, max)}…` : text);
18
+ /**
19
+ * **Once per process per (code, key).** A server renders per request, so a warning that fires per render floods the log
20
+ * at request rate; every ssr warning names its key (a component tag, with an attribute or an event type where that
21
+ * distinguishes two facts), or an object (a container). Bounded by the number of component classes and their names:
22
+ * the code, not the traffic. The TWIN of @verajs/shared-utils' once-memory (`hasWarned`, then `warnOnce`; ssr cannot import the private package),
23
+ * the same memory shape: `code` or `code key` in a Set, an object key in a WeakMap; tests/ssr-coded-diagnostics holds
24
+ * the two answering alike.
25
+ */
26
+ const printed = new Set();
27
+ const printedOn = new WeakMap();
28
+ export const once = (code, key) => {
29
+ if (key === undefined || typeof key === 'string') {
30
+ const entry = key === undefined ? code : `${code} ${key}`;
31
+ if (printed.has(entry))
32
+ return false;
33
+ printed.add(entry);
34
+ return true;
35
+ }
36
+ const codes = printedOn.get(key);
37
+ if (codes?.has(code))
38
+ return false;
39
+ if (codes)
40
+ codes.add(code);
41
+ else
42
+ printedOn.set(key, new Set([code]));
43
+ return true;
44
+ };
45
+ /**
46
+ * **The errors ssr constructs, marked as its own.** A refusal raised inside a render is reported by the render's
47
+ * `ssr-render-threw` beside the component's tag, and quoting it as foreign text would cut its code off: one of ours
48
+ * is already formatted, its outside text already quoted, so it is carried as it is. Anything else is the app's —
49
+ * quoted. A set of instances, never a shape test: a message can imitate ours, an identity cannot.
50
+ */
51
+ const ours = new WeakSet();
52
+ export const own = (error) => {
53
+ ours.add(error);
54
+ return error;
55
+ };
56
+ export const isOwn = (error) => typeof error === 'object' && error !== null && ours.has(error);
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `name`, `name="v"`, `name='v'` and `name=v` — every form an author may have written.
3
+ *
4
+ * Only the double-quoted form used to be recognized. `<x-y a='one' b=two>` gave the child three
5
+ * empty attributes *and invented two more*, because the value text fell through to the next
6
+ * iteration and matched as a name.
7
+ *
8
+ * **The NAME charset comes from `parse.js`, which owns it.** This file kept its own `[\w:-]+`,
9
+ * which is narrower than what a start tag may carry: `data-a.b="v"` split at the dot into
10
+ * `data-a=""` and `b="v"`, so a nested component was rebuilt with attributes its author never
11
+ * wrote and read `null` for the one they did — server-side only, silently (arc-2 run 2). The same
12
+ * single-fact-two-copies shape this file's own tag walk had with the tokenizer, and the same fix.
13
+ */
14
+ export declare const ATTRIBUTE: RegExp;
15
+ /**
16
+ * Renders every registered component tag found in `markup` to declarative shadow DOM, spliced in
17
+ * as strings right after each opening tag. Recursion covers components rendered by components.
18
+ */
19
+ /**
20
+ * **One scanner, two chains.** The synchronous render calls it with nothing and it behaves exactly
21
+ * as it always has; the asynchronous one hands it an `emit` that records a promise and returns a
22
+ * placeholder, substituting the real markup once everything has settled.
23
+ *
24
+ * This is what lets the two chains share the intricate half — comments, raw-text elements, nesting,
25
+ * attribute spans — rather than keeping two copies of a parser that must agree forever. Two paths
26
+ * drifting is the failure this package has spent a week deleting; a shared parser makes it
27
+ * impossible for the parsing half rather than merely tested-against.
28
+ *
29
+ * **It costs the synchronous path nothing measurable**: a call through a parameter instead of a
30
+ * direct one is ~6% of the scanning step, and the scanning step is a fraction of a percent of a
31
+ * render. The alternative considered — collecting segments into an array for a caller to assemble —
32
+ * was 1.85x on the same step and was rejected for it.
33
+ *
34
+ * @param markup @param depth
35
+ * @param emit renders one component tag — its open tag and contents; the scanner writes the close tag
36
+ */
37
+ export declare const renderComponentTags: (markup: string, depth: number, emit: (name: string, attrs: string, depth: number, children?: string) => string) => string;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * **The markup scanner** — finds the registered component tags in markup the server has just written,
3
+ * and hands each one to the renderer that called it. Never an HTML parse: a walk that knows exactly
4
+ * what a component render needs to know — quoted attribute values, comments, raw-text elements,
5
+ * `<template>` contents, and where a component's children end.
6
+ *
7
+ * Moved out of the render pipeline unchanged (2026-09-28): it is finely tuned
8
+ * parsing work, audited in place rather than rewritten, and the pipeline around it is what was rebuilt.
9
+ * The per-component renderer is a parameter — both chains pass their own — so this file imports
10
+ * nothing of the pipeline.
11
+ */
12
+ import { registry } from './shim.js';
13
+ import { PROSE } from './diagnostics.js';
14
+ import { own, ssrMisuse } from './report.js';
15
+ /** The attribute-name charset, from the parser that owns it — see `ATTRIBUTE` below. */
16
+ import { ATTRIBUTE_NAME } from './parse.js';
17
+ import { freshScan, scanTag } from './tokenizer.js';
18
+ /**
19
+ * `name`, `name="v"`, `name='v'` and `name=v` — every form an author may have written.
20
+ *
21
+ * Only the double-quoted form used to be recognized. `<x-y a='one' b=two>` gave the child three
22
+ * empty attributes *and invented two more*, because the value text fell through to the next
23
+ * iteration and matched as a name.
24
+ *
25
+ * **The NAME charset comes from `parse.js`, which owns it.** This file kept its own `[\w:-]+`,
26
+ * which is narrower than what a start tag may carry: `data-a.b="v"` split at the dot into
27
+ * `data-a=""` and `b="v"`, so a nested component was rebuilt with attributes its author never
28
+ * wrote and read `null` for the one they did — server-side only, silently (arc-2 run 2). The same
29
+ * single-fact-two-copies shape this file's own tag walk had with the tokenizer, and the same fix.
30
+ */
31
+ export const ATTRIBUTE = new RegExp(`(${ATTRIBUTE_NAME})(?:=(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, 'g');
32
+ /**
33
+ * **How deep a component tree may nest before the server calls it a cycle.**
34
+ *
35
+ * A component that renders itself recurses without bound, and on a server that is a hung request
36
+ * rather than a hung tab, so a limit has to exist. It is a **divergence from the client**, which has
37
+ * no such limit — measured on both sides.
38
+ *
39
+ * **256, raised from 32.** A cycle recurses without bound, so 256 refuses it as surely as 32 did, a
40
+ * few microseconds later; 32 was low enough for a real tree to reach — router children inside
41
+ * design-system wrappers inside a card grid — and reaching it meant a 500 for a page that renders
42
+ * fine in a browser. The ceiling is set *below where the client breaks*: the client managed ~340
43
+ * levels before `RangeError`, so the server still fails first, and fails with a sentence rather than
44
+ * a stack overflow. That ~340 is engine- and frame-dependent and not a constant to design against,
45
+ * which is the argument for an explicit limit rather than waiting for our own stack to go.
46
+ *
47
+ * The client's own floor for a genuine cycle is the JavaScript stack — it built ~340 levels before
48
+ * `RangeError: Maximum call stack size exceeded`, reported through the `'error'` insert. That number
49
+ * is engine- and frame-dependent and cannot be relied on, which is the argument for the server
50
+ * having an explicit limit rather than waiting for its own stack to go.
51
+ *
52
+ * Documented in the README, because a hard limit nobody can find is a 500 nobody can explain.
53
+ */
54
+ const MAX_DEPTH = 256;
55
+ /**
56
+ * Renders every registered component tag found in `markup` to declarative shadow DOM, spliced in
57
+ * as strings right after each opening tag. Recursion covers components rendered by components.
58
+ */
59
+ /**
60
+ * **One scanner, two chains.** The synchronous render calls it with nothing and it behaves exactly
61
+ * as it always has; the asynchronous one hands it an `emit` that records a promise and returns a
62
+ * placeholder, substituting the real markup once everything has settled.
63
+ *
64
+ * This is what lets the two chains share the intricate half — comments, raw-text elements, nesting,
65
+ * attribute spans — rather than keeping two copies of a parser that must agree forever. Two paths
66
+ * drifting is the failure this package has spent a week deleting; a shared parser makes it
67
+ * impossible for the parsing half rather than merely tested-against.
68
+ *
69
+ * **It costs the synchronous path nothing measurable**: a call through a parameter instead of a
70
+ * direct one is ~6% of the scanning step, and the scanning step is a fraction of a percent of a
71
+ * render. The alternative considered — collecting segments into an array for a caller to assemble —
72
+ * was 1.85x on the same step and was rejected for it.
73
+ *
74
+ * @param markup @param depth
75
+ * @param emit renders one component tag — its open tag and contents; the scanner writes the close tag
76
+ */
77
+ export const renderComponentTags = (markup, depth, emit) => {
78
+ if (depth > MAX_DEPTH)
79
+ throw own(new Error(ssrMisuse('ssr-nesting-depth', PROSE['ssr-nesting-depth'](String(MAX_DEPTH)))));
80
+ /** No dash, no custom element — cheaper to ask than to walk the string and find nothing. */
81
+ if (!markup.includes('-'))
82
+ return markup;
83
+ /**
84
+ * **The tags come from the server's one tag scanner** (`tokenizer.ts`), so this reads markup where the browser
85
+ * does. It used to walk the markup with its own copy — a quote-aware tag end, a name pattern, a comment skip, a
86
+ * `<template>` skip and a raw-text skip — and each part drifted: `<b x"><x-kid>` read the quote as opening a value
87
+ * and missed the live component; `<x-kid.y>` stopped the name at the dot, rendered `x-kid` and rewrote the tag as
88
+ * `<x-kid .y="">`; `</textareax>` and `</scripts>` ended raw text, so a component was rendered into a textarea's
89
+ * value and a script's source; and `<svg><x-kid>` was rendered, where the browser never upgrades a foreign element.
90
+ * Comments, raw text, `<template>` content, quoted values, foreign content and its integration points
91
+ * (`<svg><foreignObject><x-kid>` IS live) are now the scanner's answers, the same ones every template gets.
92
+ */
93
+ const tags = [];
94
+ scanTag(markup, freshScan(0), undefined, tags);
95
+ let out = '';
96
+ let at = 0;
97
+ for (let k = 0; k < tags.length; k++) {
98
+ const tag = tags[k];
99
+ if (!tag.live || !registry.has(tag.name))
100
+ continue;
101
+ const { name } = tag;
102
+ const tagText = markup.slice(tag.at, tag.end);
103
+ /** Rewritten, not kept — the component may have changed its own attributes. */
104
+ const attrs = tagText.slice(1 + name.length, -1);
105
+ out += markup.slice(at, tag.at);
106
+ /**
107
+ * **A nested component is handed its children**, exactly as `renderToString` hands them to
108
+ * the top-level one. They used to trail it in the stream instead: the scanner emitted the
109
+ * component's rendered markup and then walked its children as ordinary markup after it.
110
+ *
111
+ * For a shadow component that happens to serialize the same way, which is why it went
112
+ * unnoticed. For a LIGHT component with slots it is wrong — the component never sees the
113
+ * content it is supposed to distribute, so every slot renders its fallback and the user's
114
+ * markup sits after the template. The CLIENT distributes it correctly, which made this a
115
+ * server/client divergence: a visibly wrong first paint, and a hydration mismatch after it.
116
+ * It also means a nested component can now read its own children in `connectedCallback`,
117
+ * which on the client it always could.
118
+ *
119
+ * Its children end at the matching end tag of its name, counting nested elements of the same name — read from
120
+ * the same scan, so a `</x-kid>` inside a comment, a `<template>` or an attribute value is not one. Malformed
121
+ * markup keeps the old path exactly — an unclosed or self-closing tag hands over nothing and lets the stream carry
122
+ * on, so nothing the fuzz suites feed it changes shape.
123
+ */
124
+ let close = -1;
125
+ if (!tagText.endsWith('/>'))
126
+ for (let open = 1, j = k + 1; j < tags.length; j++)
127
+ if (tags[j].name === name && (tags[j].closing ? --open : ++open) === 0) {
128
+ close = j;
129
+ break;
130
+ }
131
+ out += emit(name, attrs, depth + 1, close === -1 ? undefined : markup.slice(tag.end, tags[close].at));
132
+ if (close === -1)
133
+ at = tag.end;
134
+ else {
135
+ /** The close tag is consumed with the children, so it is written back here — normalized, like the open tag the component just rewrote. */
136
+ out += `</${name}>`;
137
+ at = tags[close].end;
138
+ k = close;
139
+ }
140
+ }
141
+ out += markup.slice(at);
142
+ return out;
143
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A selector matcher for the node view.
3
+ *
4
+ * **It answers, or it refuses — it never guesses.** Every query used to return `null` or an empty
5
+ * list whatever was asked, so `this.matches('[data-open]')` was `false` on an element that plainly
6
+ * had the attribute and a component branched the wrong way with nothing said. Replacing that with a
7
+ * matcher that silently mishandles `:hover` would be the same defect in a new place, so anything
8
+ * outside the grammar below throws and names itself.
9
+ *
10
+ * ## What it accepts
11
+ *
12
+ * Type, universal, class, id, every attribute operator with the `i`/`s` flag, `:not()` over one
13
+ * compound, and all four combinators — descendant, `>`, `+`, `~`.
14
+ *
15
+ * ## What it refuses, and why that is two different reasons
16
+ *
17
+ * Most refusals need something a server does not have: user state (`:hover`, `:focus`, `:checked`),
18
+ * layout (`:visible`), or a document (`:root`, `:target`).
19
+ *
20
+ * **But not all of them, and the difference used to be papered over.** `:first-child`,
21
+ * `:last-child`, `:nth-child()`, `:only-child`, `:empty`, `:first-of-type` and `:nth-of-type()` are
22
+ * pure structure — this DOM has everything needed to answer them — and they are refused too, because
23
+ * this matcher does not implement them. So are `:is()`, `:where()` and `:has()`.
24
+ *
25
+ * Saying only "a pseudo-class needs user state, layout or a document" made that sound like a
26
+ * property of servers rather than a limit of this file, and a reader following the rule would predict
27
+ * `:first-child` works. Refusing is still the right behavior — it is loud, and a wrong answer would
28
+ * not be — but the reason has to be the true one. Implementing the structural set is a **feature**,
29
+ * not a fix, and is not being done here on the way past.
30
+ *
31
+ * `tests/ssr-selector-grammar.test.mjs` holds the boundary as a list, so a selector moving from one side
32
+ * to the other is a decision rather than a surprise.
33
+ */
34
+ import type { ContainerShim, ElementShim } from './nodes.js';
35
+ export declare const matches: (element: ElementShim, selector: string, scope?: ContainerShim) => boolean;
36
+ /** Every descendant element, in document order — shared with the collection queries. */
37
+ export declare const descendantsOf: (node: ContainerShim) => ElementShim[];
38
+ export declare const querySelectorAll: (node: ContainerShim, selector: string) => ElementShim[];
39
+ export declare const querySelector: (node: ContainerShim, selector: string) => ElementShim | null;
40
+ export declare const closest: (element: ElementShim, selector: string) => ElementShim | null;
@@ -0,0 +1,261 @@
1
+ /**
2
+ * A selector matcher for the node view.
3
+ *
4
+ * **It answers, or it refuses — it never guesses.** Every query used to return `null` or an empty
5
+ * list whatever was asked, so `this.matches('[data-open]')` was `false` on an element that plainly
6
+ * had the attribute and a component branched the wrong way with nothing said. Replacing that with a
7
+ * matcher that silently mishandles `:hover` would be the same defect in a new place, so anything
8
+ * outside the grammar below throws and names itself.
9
+ *
10
+ * ## What it accepts
11
+ *
12
+ * Type, universal, class, id, every attribute operator with the `i`/`s` flag, `:not()` over one
13
+ * compound, and all four combinators — descendant, `>`, `+`, `~`.
14
+ *
15
+ * ## What it refuses, and why that is two different reasons
16
+ *
17
+ * Most refusals need something a server does not have: user state (`:hover`, `:focus`, `:checked`),
18
+ * layout (`:visible`), or a document (`:root`, `:target`).
19
+ *
20
+ * **But not all of them, and the difference used to be papered over.** `:first-child`,
21
+ * `:last-child`, `:nth-child()`, `:only-child`, `:empty`, `:first-of-type` and `:nth-of-type()` are
22
+ * pure structure — this DOM has everything needed to answer them — and they are refused too, because
23
+ * this matcher does not implement them. So are `:is()`, `:where()` and `:has()`.
24
+ *
25
+ * Saying only "a pseudo-class needs user state, layout or a document" made that sound like a
26
+ * property of servers rather than a limit of this file, and a reader following the rule would predict
27
+ * `:first-child` works. Refusing is still the right behavior — it is loud, and a wrong answer would
28
+ * not be — but the reason has to be the true one. Implementing the structural set is a **feature**,
29
+ * not a fix, and is not being done here on the way past.
30
+ *
31
+ * `tests/ssr-selector-grammar.test.mjs` holds the boundary as a list, so a selector moving from one side
32
+ * to the other is a decision rather than a surprise.
33
+ */
34
+ import { PROSE } from './diagnostics.js';
35
+ import { own, quoted, ssrMisuse } from './report.js';
36
+ /** `[name op "value" i]` — every attribute operator the platform defines. */
37
+ const ATTRIBUTE = /^\[\s*([^\s\]~^$*|=]+)\s*(?:([~^$*|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]*))\s*)?(?:([iIsS])\s*)?\]/;
38
+ const NAME = /^[*]|^[a-zA-Z][\w-]*/;
39
+ const CLASS = /^\.([\w-]+)/;
40
+ const ID = /^#([\w-]+)/;
41
+ const NOT = /^:not\(/i;
42
+ const refuse = (selector, why) => {
43
+ throw own(new Error(ssrMisuse('ssr-selector-unsupported', PROSE['ssr-selector-unsupported'](quoted(selector), why))));
44
+ };
45
+ /**
46
+ * One compound selector — `div.a#b[c=d]:not(.e)` — as a list of tests.
47
+ * Returns the parsed compound and how much of the string it consumed.
48
+ */
49
+ const parseCompound = (source, selector) => {
50
+ const tests = [];
51
+ let rest = source;
52
+ let consumed = 0;
53
+ /**
54
+ * Every branch below assigns this before it is read; `refuse` throws rather than falling through. A branch
55
+ * that measures its own length assigns `{ 0: text }`, which never carries a regex match's `index` — that is
56
+ * what lets a regex branch's assignment narrow back to the match.
57
+ */
58
+ let match;
59
+ for (;;) {
60
+ if (rest === '' || /^[\s,>+~)]/.test(rest))
61
+ break;
62
+ if ((match = NAME.exec(rest))) {
63
+ const name = match[0].toLowerCase();
64
+ if (name !== '*')
65
+ tests.push((element) => element.localName === name);
66
+ }
67
+ else if ((match = CLASS.exec(rest))) {
68
+ const wanted = match[1];
69
+ tests.push((element) => (element.getAttribute('class') ?? '').split(/\s+/u).includes(wanted));
70
+ }
71
+ else if ((match = ID.exec(rest))) {
72
+ const wanted = match[1];
73
+ tests.push((element) => element.getAttribute('id') === wanted);
74
+ }
75
+ else if ((match = NOT.exec(rest))) {
76
+ const inner = parseCompound(rest.slice(match[0].length), selector);
77
+ const after = rest.slice(match[0].length + inner.consumed);
78
+ if (!after.startsWith(')'))
79
+ refuse(selector, ':not() takes a single compound selector here');
80
+ tests.push((element, scope) => !inner.tests.every((test) => test(element, scope)));
81
+ match = { 0: rest.slice(0, match[0].length + inner.consumed + 1) };
82
+ }
83
+ else if ((match = ATTRIBUTE.exec(rest))) {
84
+ const [, name, operator, quoted, single, bare, flag] = match;
85
+ const wanted = quoted ?? single ?? bare ?? '';
86
+ const fold = flag && flag.toLowerCase() === 'i';
87
+ tests.push((element) => {
88
+ let actual = element.getAttribute(name);
89
+ if (actual === null)
90
+ return false;
91
+ if (!operator)
92
+ return true;
93
+ let target = wanted;
94
+ if (fold) {
95
+ actual = actual.toLowerCase();
96
+ target = target.toLowerCase();
97
+ }
98
+ switch (operator) {
99
+ case '=':
100
+ return actual === target;
101
+ case '~=':
102
+ return target !== '' && actual.split(/\s+/u).includes(target);
103
+ case '|=':
104
+ return actual === target || actual.startsWith(`${target}-`);
105
+ case '^=':
106
+ return target !== '' && actual.startsWith(target);
107
+ case '$=':
108
+ return target !== '' && actual.endsWith(target);
109
+ case '*=':
110
+ return target !== '' && actual.includes(target);
111
+ default:
112
+ return false;
113
+ }
114
+ });
115
+ }
116
+ else if (/^:scope\b/iu.test(rest)) {
117
+ /**
118
+ * **`:scope` is the element the query started from**, which is knowable here — unlike the
119
+ * pseudo-classes below it, which need user state, layout or a document. It is what makes
120
+ * `element.querySelector(':scope > b')` mean "a direct child", the usual reason to reach for
121
+ * a pseudo-class in a server render at all.
122
+ */
123
+ tests.push((element, scope) => element === scope);
124
+ match = { 0: rest.slice(0, ':scope'.length) };
125
+ }
126
+ else if (rest.startsWith(':')) {
127
+ refuse(selector, 'a pseudo-class needs user state, layout or a document, and a server has none');
128
+ }
129
+ else {
130
+ refuse(selector, 'it is not a selector this parser understands');
131
+ }
132
+ rest = rest.slice(match[0].length);
133
+ consumed += match[0].length;
134
+ }
135
+ if (tests.length === 0 && consumed === 0)
136
+ refuse(selector, 'it is empty');
137
+ return { tests, consumed };
138
+ };
139
+ /** A full complex selector — compounds joined by combinators — parsed right to left for matching. */
140
+ const parseComplex = (selector) => {
141
+ const steps = [];
142
+ let rest = selector.trim();
143
+ let combinator = null;
144
+ for (;;) {
145
+ rest = rest.replace(/^\s+/u, '');
146
+ if (rest === '')
147
+ break;
148
+ const compound = parseCompound(rest, selector);
149
+ steps.push({ tests: compound.tests, combinator });
150
+ rest = rest.slice(compound.consumed).replace(/^\s*/u, '');
151
+ if (rest === '')
152
+ break;
153
+ const symbol = /^[>+~]/.exec(rest);
154
+ if (symbol) {
155
+ combinator = symbol[0];
156
+ rest = rest.slice(1);
157
+ }
158
+ else {
159
+ combinator = ' ';
160
+ }
161
+ if (rest.replace(/^\s+/u, '') === '')
162
+ refuse(selector, 'it ends with a combinator');
163
+ }
164
+ if (steps.length === 0)
165
+ refuse(selector, 'it is empty');
166
+ return steps;
167
+ };
168
+ const cache = new Map();
169
+ const compile = (selector) => {
170
+ if (typeof selector !== 'string')
171
+ selector = `${selector}`;
172
+ let compiled = cache.get(selector);
173
+ if (compiled)
174
+ return compiled;
175
+ compiled = selector.split(',').map((one) => {
176
+ if (one.trim() === '')
177
+ refuse(selector, 'it has an empty item in its list');
178
+ return parseComplex(one);
179
+ });
180
+ cache.set(selector, compiled);
181
+ return compiled;
182
+ };
183
+ /** **Elements only.** A selector matches elements; text and comment nodes are not candidates. */
184
+ const childrenOf = (node) => (node?._entries ?? []).filter((entry) => typeof entry !== 'string' && entry.openTag);
185
+ const siblingsOf = (element) => childrenOf(element._parent);
186
+ /**
187
+ * **The parent a combinator walks to, only when it is an ELEMENT** — `parentElement`, never `parentNode`. A shadow root,
188
+ * fragment or document above an element is not a candidate for `>` or a descendant combinator: walked onto, it was
189
+ * tested as one, so `* > i` matched a shadow root's top-level child (the root passed `*`) and `.a b` THREW reading an
190
+ * element property off the root. The browser's answer, measured against jsdom, is no match.
191
+ */
192
+ const elementParent = (element) => {
193
+ const parent = element._parent;
194
+ return parent?.openTag ? parent : null;
195
+ };
196
+ /** Match one complex selector against one element, walking its steps from right to left. */
197
+ const matchesComplex = (element, steps, scope) => {
198
+ const last = steps[steps.length - 1];
199
+ if (!last.tests.every((test) => test(element, scope)))
200
+ return false;
201
+ let current = element;
202
+ for (let i = steps.length - 2; i >= 0; i--) {
203
+ const step = steps[i];
204
+ const combinator = steps[i + 1].combinator;
205
+ const passes = (candidate) => candidate && step.tests.every((test) => test(candidate, scope));
206
+ if (combinator === '>') {
207
+ const parent = elementParent(current);
208
+ if (parent === null || !passes(parent))
209
+ return false;
210
+ current = parent;
211
+ }
212
+ else if (combinator === '+') {
213
+ const siblings = siblingsOf(current);
214
+ current = siblings[siblings.indexOf(current) - 1];
215
+ if (!passes(current))
216
+ return false;
217
+ }
218
+ else if (combinator === '~') {
219
+ const siblings = siblingsOf(current);
220
+ const before = siblings.slice(0, siblings.indexOf(current)).reverse().find(passes);
221
+ if (!before)
222
+ return false;
223
+ current = before;
224
+ }
225
+ else {
226
+ let above = elementParent(current);
227
+ while (above && !passes(above))
228
+ above = elementParent(above);
229
+ if (!above)
230
+ return false;
231
+ current = above;
232
+ }
233
+ }
234
+ return true;
235
+ };
236
+ export const matches = (element, selector, scope = element) => compile(selector).some((steps) => matchesComplex(element, steps, scope));
237
+ /** Every descendant, in document order. */
238
+ const descendants = (node, out = []) => {
239
+ for (const child of childrenOf(node)) {
240
+ out.push(child);
241
+ descendants(child, out);
242
+ }
243
+ return out;
244
+ };
245
+ /** Every descendant element, in document order — shared with the collection queries. */
246
+ export const descendantsOf = (node) => descendants(node);
247
+ export const querySelectorAll = (node, selector) => {
248
+ const compiled = compile(selector);
249
+ return descendants(node).filter((element) => compiled.some((steps) => matchesComplex(element, steps, node)));
250
+ };
251
+ export const querySelector = (node, selector) => {
252
+ const compiled = compile(selector);
253
+ return descendants(node).find((element) => compiled.some((steps) => matchesComplex(element, steps, node))) ?? null;
254
+ };
255
+ export const closest = (element, selector) => {
256
+ const compiled = compile(selector);
257
+ for (let current = element; current; current = current._parent)
258
+ if (current.localName && compiled.some((steps) => matchesComplex(current, steps, element)))
259
+ return current;
260
+ return null;
261
+ };
@@ -0,0 +1,39 @@
1
+ import type { SsrTemplate } from './types.js';
2
+ /**
3
+ * `depth` is the foreign-content depth of the position the template renders into — 0 at the top and in HTML.
4
+ *
5
+ * **Where a template renders decides how its raw text parses, and the template cannot see it.** The browser parses
6
+ * the ONE string this produces, so `html`<svg>${child}</svg>`` puts `child`'s `<style>` inside SVG, where its
7
+ * content is markup, however `child` was written; and an `svg`/`mathml` template is foreign content wherever it
8
+ * goes, because the client parses it inside an `<svg>`/`<math>` wrapper. Scanning each template as though it began
9
+ * in HTML wrote both as raw text — unescaped — and the browser then parsed a value's `<img onerror>` as an element.
10
+ * So a template starts at its position's depth, and at least 1 if it is foreign itself. Erring deep is the safe
11
+ * direction: an `svg` template rendered outside any `<svg>` is HTML to the browser, and its `<style>` then shows
12
+ * the escapes as text — a visible mismatch, never an injection.
13
+ */
14
+ export declare const serializeTemplate: (template: SsrTemplate, depth?: number) => string;
15
+ /**
16
+ * A name that cannot be written into a tag safely.
17
+ *
18
+ * A spread's keys are the one part of a template that is runtime data — that is what the module is
19
+ * for — and they were interpolated into the open tag with no check at all, while every *value*
20
+ * around them was escaped. A key carrying a quote or a `>` therefore closed the attribute, or the
21
+ * element:
22
+ *
23
+ * spread({ 'x><script>alert(1)</script': '1' })
24
+ * -> <b x><script>alert(1)</script="1">x</b>
25
+ *
26
+ * The set is the HTML attribute-name restriction — control characters, whitespace, `"`, `'`, `>`,
27
+ * `/`, `=` — plus `<` and a backtick, which the specification permits and no real name uses.
28
+ *
29
+ * It is deliberately **stricter than `setAttribute`**, which was measured in Chromium and accepts
30
+ * `"`, `'` and `<` while rejecting whitespace, `>`, `=`, `/` and NUL. A name the platform accepts
31
+ * but markup cannot carry is unusable in a framework that server-renders, so `@verajs/renderer/spread`
32
+ * applies this same rule client-side and the two sides agree on every key rather than one of them
33
+ * quietly serving different markup.
34
+ *
35
+ * The control-character range is the point of the rule, not a mistake in it: a name carrying one
36
+ * is exactly what must never reach markup.
37
+ */
38
+ export declare const UNSAFE_ATTRIBUTE_NAME: RegExp;
39
+ export declare const serializeValue: (value: unknown, raw?: boolean, depth?: number, text?: boolean) => string;