@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.
- package/README.md +522 -390
- package/dist/vera/diagnostics.d.ts +20 -0
- package/dist/vera/diagnostics.js +102 -0
- package/dist/vera/escaping.d.ts +155 -0
- package/dist/vera/escaping.js +293 -0
- package/dist/vera/events.d.ts +41 -0
- package/dist/vera/events.js +162 -0
- package/dist/vera/frames.d.ts +38 -0
- package/dist/vera/frames.js +195 -0
- package/dist/vera/index.d.ts +48 -0
- package/dist/vera/index.js +480 -0
- package/{types → dist/vera}/nodes.d.ts +389 -302
- package/dist/vera/nodes.js +2339 -0
- package/dist/vera/parse.d.ts +53 -0
- package/dist/vera/parse.js +485 -0
- package/dist/vera/reflections.d.ts +566 -0
- package/dist/vera/reflections.js +820 -0
- package/dist/vera/registry.d.ts +14 -0
- package/{src → dist}/vera/registry.js +5 -1
- package/dist/vera/report.d.ts +27 -0
- package/dist/vera/report.js +56 -0
- package/dist/vera/scan.d.ts +37 -0
- package/dist/vera/scan.js +143 -0
- package/dist/vera/select.d.ts +40 -0
- package/dist/vera/select.js +261 -0
- package/dist/vera/serializer.d.ts +39 -0
- package/dist/vera/serializer.js +1521 -0
- package/dist/vera/shim.d.ts +42 -0
- package/dist/vera/shim.js +853 -0
- package/dist/vera/slots.d.ts +5 -0
- package/dist/vera/slots.js +104 -0
- package/dist/vera/stylesheets.d.ts +62 -0
- package/dist/vera/stylesheets.js +180 -0
- package/dist/vera/tokenizer.d.ts +32 -0
- package/dist/vera/tokenizer.js +553 -0
- package/dist/vera/types.d.ts +121 -0
- package/dist/vera/views.d.ts +63 -0
- package/dist/vera/views.js +245 -0
- package/package.json +12 -13
- package/src/vera/escaping.js +0 -135
- package/src/vera/events.js +0 -164
- package/src/vera/frames.js +0 -102
- package/src/vera/index.js +0 -1187
- package/src/vera/nodes.js +0 -2294
- package/src/vera/parse.js +0 -381
- package/src/vera/reflections.js +0 -811
- package/src/vera/select.js +0 -234
- package/src/vera/serializer.js +0 -1080
- package/src/vera/shim.js +0 -761
- package/src/vera/stylesheets.js +0 -155
- package/src/vera/views.js +0 -240
- package/types/escaping.d.ts +0 -27
- package/types/events.d.ts +0 -4
- package/types/frames.d.ts +0 -12
- package/types/index.d.ts +0 -13
- package/types/parse.d.ts +0 -19
- package/types/reflections.d.ts +0 -657
- package/types/registry.d.ts +0 -8
- package/types/select.d.ts +0 -5
- package/types/serializer.d.ts +0 -26
- package/types/shim.d.ts +0 -23
- package/types/stylesheets.d.ts +0 -53
- package/types/views.d.ts +0 -26
|
@@ -0,0 +1,1521 @@
|
|
|
1
|
+
import { escapeHtml, escapeRawText } from './shim.js';
|
|
2
|
+
import { INLINE_HANDLER, NEWLINE_TAKERS, SCRIPT_URL, SCRIPT_URL_ITEM, URL_SINK, closedRawText, dataBlock, decodeCodePoint, decodeSchemeReferences, thrownMessage } from './escaping.js';
|
|
3
|
+
import { registry } from './registry.js';
|
|
4
|
+
import { PROSE, TWINS } from './diagnostics.js';
|
|
5
|
+
import { once, own, quoted, ssrMisuse, ssrWarning } from './report.js';
|
|
6
|
+
import { currentRenderingTag } from './stylesheets.js';
|
|
7
|
+
import { INSTANCE_ATTRIBUTE, NodeBaseShim, markPending } from './nodes.js';
|
|
8
|
+
import { PHASE_END_TAG_OPEN as END_TAG_OPEN, INERT_EDIT as EDIT_INERT, RAW_TEXT_TAGS as RAWTEXT, PHASE_TAG_NAME as TAG_NAME, PHASE_TAG_OPEN as TAG_OPEN, TEXT_ONLY_TAGS as TEXT_ONLY, closersOf, freshScan, isTokenizerSpace as isSpace, scanTag } from './tokenizer.js';
|
|
9
|
+
/** Module-local, because serializeValue (the hottest function here) reads it: an imported binding is a live one, which
|
|
10
|
+
* V8 reaches less directly (CLAUDE.md, measured on the tokenizer's constants). */
|
|
11
|
+
const NodeBase = NodeBaseShim;
|
|
12
|
+
/**
|
|
13
|
+
* The vera-native template serializer: flattens core's `html` template objects to markup with
|
|
14
|
+
* the renderer's sigil semantics applied server-side.
|
|
15
|
+
*
|
|
16
|
+
* `?bool=${x}` -> `bool=""` when truthy, nothing when falsy
|
|
17
|
+
* `.prop=${x}` -> on a rendered COMPONENT tag, delivered to the instance the nested scan
|
|
18
|
+
* renders (by identity, never markup); on a form control, mirrored to an
|
|
19
|
+
* attribute (value/checked/selected); else dropped
|
|
20
|
+
* `@event=${fn}` -> dropped (behavior is the client's job)
|
|
21
|
+
* `&ref=${r}` -> dropped
|
|
22
|
+
* `attr=${x}` -> quoted, escaped
|
|
23
|
+
* text `${x}` -> escaped; nested templates and arrays flatten; only null/undefined vanish
|
|
24
|
+
* (`false` renders the word, as the client and as a JS template literal do —
|
|
25
|
+
* measured on both sides; saying otherwise here described a divergence that
|
|
26
|
+
* does not exist and would have sent someone hunting a hydration bug)
|
|
27
|
+
*
|
|
28
|
+
* Like the client renderer, analysis is **per template identity**: each call site's frozen
|
|
29
|
+
* `strings` array is classified once into a plan (slot kinds + pre-trimmed static parts), cached
|
|
30
|
+
* in a WeakMap. Rendering a 100-row list re-uses one plan 100 times instead of re-running the
|
|
31
|
+
* sigil regexes per row — the same template-identity architecture, server-side.
|
|
32
|
+
*
|
|
33
|
+
* `keyed()`/`hold()` wrappers are client-renderer constructs — SSR templates use plain `.map`.
|
|
34
|
+
*/
|
|
35
|
+
/** `.prop` bindings whose server-side truth belongs in an attribute. */
|
|
36
|
+
const FORM_ATTRIBUTES = ['value', 'checked', 'selected'];
|
|
37
|
+
/**
|
|
38
|
+
* Whether a property binding on `owner` is one this serializer writes. `selectedIndex` is a form property on a
|
|
39
|
+
* `<select>` only — it chooses an option, exactly as `value` does (see `SELECT_MARK`) — and on anything else it is
|
|
40
|
+
* the client's concern, with no markup. The written form and a spread key ask the same question, here.
|
|
41
|
+
*/
|
|
42
|
+
const isFormProperty = (owner, name) => FORM_ATTRIBUTES.includes(name) || (owner === 'select' && name === 'selectedIndex');
|
|
43
|
+
/**
|
|
44
|
+
* `checked` and `selected` are **boolean** properties; `value` is a string one.
|
|
45
|
+
*
|
|
46
|
+
* The element coerces on assignment, so `.checked=${0}` leaves a browser with `checked === false`
|
|
47
|
+
* while `.value=${0}` leaves it with `"0"`. All three were treated as string-ish here — present
|
|
48
|
+
* unless nullish or exactly `false` — so every falsy-but-not-false value (`0`, `''`, `NaN`) served
|
|
49
|
+
* a **ticked** checkbox against a browser's unticked one, and hydration then had to throw the
|
|
50
|
+
* server's markup away to correct it.
|
|
51
|
+
*/
|
|
52
|
+
const BOOLEAN_FORM_PROPERTIES = new Set(['checked', 'selected']);
|
|
53
|
+
/**
|
|
54
|
+
* …and the elements where that is true.
|
|
55
|
+
*
|
|
56
|
+
* Mirroring `.value` to an attribute exists so hydration can read form state back out of the
|
|
57
|
+
* markup, which only means anything on a form control. Applied to every element, `.value` on a
|
|
58
|
+
* `<b>` wrote `value="…"` server-side where the client sets a plain JS property and no attribute at
|
|
59
|
+
* all — a difference in the rendered DOM for no benefit. Anywhere else a `.prop` is client state,
|
|
60
|
+
* which is what it already was.
|
|
61
|
+
*/
|
|
62
|
+
const FORM_ELEMENTS = new Set(['input', 'textarea', 'select', 'option']);
|
|
63
|
+
/** The first character of a sigil binding's name — see `compile`. */
|
|
64
|
+
const SIGILS = new Set(['.', '?', '@', '&', '!']);
|
|
65
|
+
/**
|
|
66
|
+
* Where a sigil or event binding's name is cut from the static before it: at the one whitespace character before the
|
|
67
|
+
* name, which the binding takes with it so a dropped binding leaves no residue (`compile` then trims one more space).
|
|
68
|
+
*/
|
|
69
|
+
const nameCut = (text, nameAt) => (nameAt > 0 && isSpace(text[nameAt - 1]) ? nameAt - 1 : nameAt);
|
|
70
|
+
/**
|
|
71
|
+
* **An expression inside an attribute NAME is refused** — the twin of the client's rule (`nameHole` in the renderer),
|
|
72
|
+
* so the two halves refuse the same templates: inside a tag and outside a value, a hole a name character touches on
|
|
73
|
+
* either side (`<p data-${k}="1">`, `<b ${name}="x">`, `<p ${k}-x>`, `<p a${k}b>`) — never a ref, never the TAG name.
|
|
74
|
+
* Refused at plan time, from statics only: no value ever reaches the message.
|
|
75
|
+
*/
|
|
76
|
+
const NAME_CHAR_BEFORE = /[^\s"'>=/]$/;
|
|
77
|
+
const NAME_CHAR_AFTER = /^(?:[^\s"'>=/]|[ \t\n\f\r]*=)/;
|
|
78
|
+
/**
|
|
79
|
+
* A bound `javascript:` URL, refused — said once per process per component and attribute. The VALUE is never printed:
|
|
80
|
+
* it is attacker-shaped by definition, and a server's console is a log pipeline (2026-10-09).
|
|
81
|
+
*/
|
|
82
|
+
const refusedScriptUrl = (name) => {
|
|
83
|
+
const tag = currentRenderingTag();
|
|
84
|
+
if (once('script-url', `${tag} ${name}`))
|
|
85
|
+
console.warn(ssrWarning((tag ? `<${tag}>` : 'the page'), 'script-url', TWINS.scriptUrl(name)));
|
|
86
|
+
};
|
|
87
|
+
const nameHole = (before, after) => {
|
|
88
|
+
const prefix = (/[^\s"'>=/]*$/.exec(before) ?? [''])[0];
|
|
89
|
+
const suffix = (/^[^\s"'>=/]*/.exec(after) ?? [''])[0];
|
|
90
|
+
const value = /^[ \t\n\f\r]*=[ \t\n\f\r]*(?:"([^"]*)("?)|'([^']*)('?)|([^\s>]*))/.exec(after.slice(suffix.length));
|
|
91
|
+
const given = value === null ? "''" : value[2] === '"' ? JSON.stringify(value[1]) : value[4] === "'" ? JSON.stringify(value[3]) : value[5] ? JSON.stringify(value[5]) : '…';
|
|
92
|
+
throw own(new Error(ssrMisuse('name-expression', TWINS.nameExpression(`${prefix}${'${…}'}${suffix}`, given))));
|
|
93
|
+
};
|
|
94
|
+
/** Slot kinds: text, boolean, form-prop, dropped binding, plain attribute. */
|
|
95
|
+
const TEXT = 0;
|
|
96
|
+
const BOOLEAN = 1;
|
|
97
|
+
const FORM_PROP = 2;
|
|
98
|
+
const DROPPED = 3;
|
|
99
|
+
const ATTRIBUTE = 4;
|
|
100
|
+
/** `.prop` on a component tag: delivered to the instance the scan will render, never markup. */
|
|
101
|
+
const COMPONENT_PROP = 5;
|
|
102
|
+
/** `.innerHTML`/`.textContent` on a plain element: content written after the open tag, the one sanctioned trusted-markup door. */
|
|
103
|
+
const CONTENT = 6;
|
|
104
|
+
/** The two content properties the server renders; `innerText`/`outerHTML`/`outerText` stay client-only (README). */
|
|
105
|
+
const CONTENT_PROPS = new Set(['innerHTML', 'textContent']);
|
|
106
|
+
/** What `compile` answers for data shaped like a template: no plan, so `serializeTemplate` renders it as text. */
|
|
107
|
+
const FORGED = {};
|
|
108
|
+
const FORGED_TEXT = `${{}}`;
|
|
109
|
+
/** A tagged template literal's strings: an array owning `raw`, which nothing from `JSON.parse` can be (see `compile`). */
|
|
110
|
+
const isLiteral = (strings) => Array.isArray(strings) && Object.hasOwn(strings, 'raw');
|
|
111
|
+
/** strings identity -> { parts, kinds, names } — computed once per call site, ever. */
|
|
112
|
+
const plans = new WeakMap();
|
|
113
|
+
/**
|
|
114
|
+
* strings identity -> foreign depth -> plan, for a template that STARTS inside `<svg>`/`<math>` — an `svg`/`mathml`
|
|
115
|
+
* template, or any template rendered into a foreign-content position. The plan differs because raw text does (see
|
|
116
|
+
* `foreign` in `scanTag`), and the common case — depth 0 — keeps its one lookup.
|
|
117
|
+
*/
|
|
118
|
+
const foreignPlans = new WeakMap();
|
|
119
|
+
const claimInstance = (state, ordinal, tag) => {
|
|
120
|
+
let node = state.instances.get(ordinal);
|
|
121
|
+
if (node === undefined) {
|
|
122
|
+
node = new (registry.get(tag))();
|
|
123
|
+
node.localName = tag;
|
|
124
|
+
state.mark += ` ${INSTANCE_ATTRIBUTE}="${markPending(node)}"`;
|
|
125
|
+
state.instances.set(ordinal, node);
|
|
126
|
+
}
|
|
127
|
+
return node;
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* One delivery, shared by the written form and the spread form. `__proto__` is skipped for the
|
|
131
|
+
* same reason `renderToString`'s own `props` option skips it — `[[Set]]` replaces the element's
|
|
132
|
+
* prototype. What a failed assignment means is decided in the catch below, by the client's rule;
|
|
133
|
+
* `prepareInstance`'s `props` OPTION keeps its stricter throw-on-readonly contract deliberately —
|
|
134
|
+
* an API argument is the caller's explicit data, a template binding is a component boundary.
|
|
135
|
+
*/
|
|
136
|
+
const deliverProperty = (node, tag, name, value) => {
|
|
137
|
+
if (name === '__proto__')
|
|
138
|
+
return;
|
|
139
|
+
try {
|
|
140
|
+
/** Any property the component declares, by name: the element is written as the open bag it is to a binding. */
|
|
141
|
+
node[name] = value;
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
/**
|
|
145
|
+
* The CLIENT's rule, applied here so the two halves resolve the same contested state the same
|
|
146
|
+
* way: a getter with NO setter is a refusal — warned by name, the binding ignored, the render
|
|
147
|
+
* carried on, exactly what `init()`'s adoption does — while a setter that THREW is the
|
|
148
|
+
* component's own error and stays one, named against the tag and property rather than as
|
|
149
|
+
* `Cannot set property x of #<Class>`. Diverging here meant one binding produced a page on
|
|
150
|
+
* the client and an empty render server-side.
|
|
151
|
+
*/
|
|
152
|
+
let carrier = node;
|
|
153
|
+
let refusable = false;
|
|
154
|
+
while (carrier !== null) {
|
|
155
|
+
const desc = Object.getOwnPropertyDescriptor(carrier, name);
|
|
156
|
+
if (desc !== undefined) {
|
|
157
|
+
refusable = desc.get !== undefined && desc.set === undefined;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
carrier = Object.getPrototypeOf(carrier);
|
|
161
|
+
}
|
|
162
|
+
if (refusable) {
|
|
163
|
+
if (once('getter-only-prop', `${tag} ${name}`))
|
|
164
|
+
console.warn(ssrWarning(`<${tag}>`, 'getter-only-prop', TWINS.getterOnlyProp(name)));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
throw own(new TypeError(ssrMisuse('ssr-setter-threw', PROSE['ssr-setter-threw'](tag, name, quoted(thrownMessage(error)))), { cause: error }));
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
/** Attribute names written into the statics, so a duplicate can be spotted before a render. */
|
|
171
|
+
/**
|
|
172
|
+
* Preceded by whitespace, so a **tag name** is not counted as an attribute of itself, and allowed to
|
|
173
|
+
* end the string, because the emitted static of an unfinished tag has no `>` yet — `<b hidden` is
|
|
174
|
+
* how `<b hidden ?hidden=${x}>` arrives here, and its bare `hidden` is exactly the duplicate that
|
|
175
|
+
* has to be seen.
|
|
176
|
+
*/
|
|
177
|
+
const STATIC_ATTRIBUTE = /\s([a-zA-Z][\w:-]*)(?==|[\s>]|$)/g;
|
|
178
|
+
/**
|
|
179
|
+
* An author's static, ready to sit inside the DOUBLE quotes the server writes around every bound value.
|
|
180
|
+
* Only a `"` can end them; an entity stays an entity, because the browser decodes one identically in any
|
|
181
|
+
* quoting.
|
|
182
|
+
*/
|
|
183
|
+
const forDoubleQuotes = (text, quote) => (quote === '"' || !text.includes('"') ? text : text.replaceAll('"', '"'));
|
|
184
|
+
/**
|
|
185
|
+
* Whether this static's LAST character — a `>`, which the caller has checked — ends a start tag that takes a leading
|
|
186
|
+
* line feed (`NEWLINE_TAKERS`). Only that position matters: content written as static text after the tag is parsed
|
|
187
|
+
* alike on both sides, while what the next binding writes there arrives on the client through the DOM, which takes
|
|
188
|
+
* nothing. Such a static gets one `\n` of its own, ALWAYS: the parser takes exactly one, so whatever comes first —
|
|
189
|
+
* a value, an empty one, a list, a nested template's static, the next static — arrives as the client has it, and the
|
|
190
|
+
* render does nothing at all (measured: 28 tag × content shapes, 2026-10-07). One byte per such element.
|
|
191
|
+
*
|
|
192
|
+
* Asked of the scan itself — the static minus its `>`, from a copy of the state before it — so a `<pre>` inside an
|
|
193
|
+
* attribute value, a comment or raw text is never mistaken for one. Whether it is HTML is the full scan's answer,
|
|
194
|
+
* after the `>`: a `<pre>` breaks out of `<svg>`. Plan time only.
|
|
195
|
+
*/
|
|
196
|
+
const takesNewline = (text, before) => {
|
|
197
|
+
const at = scanTag(text.slice(0, -1), { ...before, opens: before.opens.slice() });
|
|
198
|
+
return (at.inTag && !at.closing && !(at.inValue && at.quote !== '') && at.comment === '' && NEWLINE_TAKERS.has(at.tagName));
|
|
199
|
+
};
|
|
200
|
+
/** A scan state to run `scanTag` from without touching the original (`scanTag` mutates `opens`). */
|
|
201
|
+
const copyScan = (state) => ({ ...state, opens: [...state.opens] });
|
|
202
|
+
/**
|
|
203
|
+
* **The start tag that OPENED the script hole `hole` sits in, as written** (a hole inside the tag as `\uFFFF`), read by
|
|
204
|
+
* THIS tokenizer, never searched for: the static in which `rawTag` turns `script`, the `>` that turns it (the shortest
|
|
205
|
+
* prefix of that static whose scan does), and where that tag began — in that static (`tagAt`) or in the earlier one it
|
|
206
|
+
* was left open in. Cold: once per script hole, once per template (`compile`).
|
|
207
|
+
*/
|
|
208
|
+
const openingTag = (strings, hole, depth) => {
|
|
209
|
+
let state = freshScan(depth);
|
|
210
|
+
let open = [0, 0];
|
|
211
|
+
let found = '';
|
|
212
|
+
for (let j = 0; j <= hole; j++) {
|
|
213
|
+
const text = strings[j];
|
|
214
|
+
const after = scanTag(text, copyScan(state));
|
|
215
|
+
if (state.rawTag !== 'script' && after.rawTag === 'script') {
|
|
216
|
+
let end = 1;
|
|
217
|
+
while (scanTag(text.slice(0, end), copyScan(state)).rawTag !== 'script')
|
|
218
|
+
end++;
|
|
219
|
+
const before = scanTag(text.slice(0, end - 1), copyScan(state));
|
|
220
|
+
const [from, at] = before.tagAt >= 0 ? [j, before.tagAt] : open;
|
|
221
|
+
found = from === j ? text.slice(at, end) : strings[from].slice(at) + '\uFFFF' + strings.slice(from + 1, j).map((t) => `${t}\uFFFF`).join('') + text.slice(0, end);
|
|
222
|
+
}
|
|
223
|
+
if (after.inTag && after.tagAt >= 0)
|
|
224
|
+
open = [j, after.tagAt];
|
|
225
|
+
state = after;
|
|
226
|
+
}
|
|
227
|
+
return found;
|
|
228
|
+
};
|
|
229
|
+
const compile = (strings, depth) => {
|
|
230
|
+
/**
|
|
231
|
+
* **A template is a tagged template literal's, never data shaped like one.** Template detection is by shape (`strings`),
|
|
232
|
+
* so `JSON.parse('{"strings":["<img src=x onerror=…>"]}')` — a request body, an API field an attacker can make an
|
|
233
|
+
* object — was rendered as MARKUP wherever it was interpolated. A literal's strings array owns a `raw` property, which
|
|
234
|
+
* JSON cannot give an array (and an object that owns one is not an array): the check Lit makes, here on the plan
|
|
235
|
+
* cache's miss, which a forged array always is — so it costs a cached template nothing. A forgery is answered with
|
|
236
|
+
* `null` — the caller renders it as the ordinary object it is — and never a throw: the value is attacker-controlled
|
|
237
|
+
* by definition, and a throw would trade the injection for the whole response.
|
|
238
|
+
*/
|
|
239
|
+
if (!isLiteral(strings)) {
|
|
240
|
+
/** Once per process per component (Brian, 2026-10-09); the forgery itself still renders as the object it is. */
|
|
241
|
+
const tag = currentRenderingTag();
|
|
242
|
+
if (once('forged-template', tag))
|
|
243
|
+
console.warn(ssrWarning((tag ? `<${tag}>` : 'the page'), 'forged-template', TWINS.forgedTemplate()));
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
const parts = [];
|
|
247
|
+
const kinds = [];
|
|
248
|
+
const names = [];
|
|
249
|
+
/**
|
|
250
|
+
* Whether a slot has to scan the open tag for an earlier write of its own name, and the tag it
|
|
251
|
+
* sits in.
|
|
252
|
+
*
|
|
253
|
+
* Both are properties of the *template*, not of a render: an attribute can only be duplicated by
|
|
254
|
+
* the statics around it, by an earlier binding in the same tag, or by a spread — and every one of
|
|
255
|
+
* those is visible here. Computing them per render cost 0.03–0.06 µs on every attribute, boolean
|
|
256
|
+
* and form-property binding, which is 18–68% of what those bindings cost in total. Almost no tag
|
|
257
|
+
* writes a name twice, so almost every one of those scans found nothing.
|
|
258
|
+
*/
|
|
259
|
+
const strip = [];
|
|
260
|
+
const owners = [];
|
|
261
|
+
/** Which RAWTEXT element each binding sits inside, `''` when none. See `RAWTEXT`. */
|
|
262
|
+
const raws = [];
|
|
263
|
+
/**
|
|
264
|
+
* Per static, the raw-content bounds its scan reported (`rawFrom`, `rawUntil`) — read only for a JSON block or an
|
|
265
|
+
* HTML style, below.
|
|
266
|
+
*/
|
|
267
|
+
const rawBounds = [];
|
|
268
|
+
/** Per child binding (sparse): the foreign-content depth it sits at, which a template rendered there starts from. */
|
|
269
|
+
const depths = [];
|
|
270
|
+
/** Per child binding (sparse): whether it sits in a text-only element, where a template is refused (see `serializeValue`). */
|
|
271
|
+
const texts = [];
|
|
272
|
+
/**
|
|
273
|
+
* Whether each slot is an **element position** — inside a tag but not inside an attribute value.
|
|
274
|
+
*
|
|
275
|
+
* `<b title="${x}">` is also a value inside a tag, and it is *not* an element position: the
|
|
276
|
+
* statics carry `title="` and `">` around it and the value is simply written between them. The
|
|
277
|
+
* difference is what the static ends with, so it is settled here rather than guessed at render.
|
|
278
|
+
*/
|
|
279
|
+
const elementPositions = [];
|
|
280
|
+
/**
|
|
281
|
+
* Which ELEMENT each slot belongs to — an ordinal that advances when a tag opens. The owner tag
|
|
282
|
+
* NAME cannot tell two sibling `<x-row .item=${…}>`s apart, and component-prop delivery needs
|
|
283
|
+
* to: every slot sharing an ordinal delivers to one instance, per application.
|
|
284
|
+
*/
|
|
285
|
+
const elements = [];
|
|
286
|
+
let elementOrdinal = 0;
|
|
287
|
+
/** Names written so far in the tag being built — statics and earlier bindings alike. */
|
|
288
|
+
let written = new Set();
|
|
289
|
+
/** A spread's keys are runtime values, so a tag holding one can never be settled here. */
|
|
290
|
+
let dynamicTag = false;
|
|
291
|
+
let owner = '';
|
|
292
|
+
/** The quote character a binding opened with, to be stripped off the front of the next static. */
|
|
293
|
+
let openQuote = '';
|
|
294
|
+
let wasInTag = false;
|
|
295
|
+
/** Carried across statics — see `scanTag`. */
|
|
296
|
+
let tagState = freshScan(depth);
|
|
297
|
+
/** Per binding: whether a component property's name is a URL sink. */
|
|
298
|
+
const urls = [];
|
|
299
|
+
/**
|
|
300
|
+
* Per attribute-value binding, by binding index (sparse): its attribute's group (shared by every hole in one value), the static
|
|
301
|
+
* written before the value — ready for double quotes — and that static decoded, for the URL check.
|
|
302
|
+
*/
|
|
303
|
+
const groups = [];
|
|
304
|
+
const leads = [];
|
|
305
|
+
const decodedLeads = [];
|
|
306
|
+
for (let i = 0; i < strings.length - 1; i++) {
|
|
307
|
+
let part = strings[i];
|
|
308
|
+
if (openQuote && part.startsWith(openQuote))
|
|
309
|
+
part = part.slice(1);
|
|
310
|
+
/**
|
|
311
|
+
* Scanned from the **author's** static, not the trimmed one.
|
|
312
|
+
*
|
|
313
|
+
* `part` has already had a binding's opening quote removed by the `openQuote` handling above, so
|
|
314
|
+
* `?hidden='${x}'` reaches the scanner as `?hidden=` followed by `>bs</b>` — the closing quote
|
|
315
|
+
* gone. The scanner then waits for a `'` that never comes and reads the whole rest of the
|
|
316
|
+
* template as one attribute value, which made every element position after it invisible.
|
|
317
|
+
*/
|
|
318
|
+
/**
|
|
319
|
+
* Whether this static ends with such a start tag. The cheap part is written out here, no call: on a cold server a
|
|
320
|
+
* newly compiled function costs its first render more than the check does (measured 2026-10-07). Only a static
|
|
321
|
+
* ending in `>` that continues such a tag, or holds `<pre`, `<lis` or `<tex` in any case, is asked properly —
|
|
322
|
+
* three letters, because one let `<p>`, `<li>`, `<td>` and `<title>` through and every template paid the scan.
|
|
323
|
+
*/
|
|
324
|
+
let taker = false;
|
|
325
|
+
const text = strings[i];
|
|
326
|
+
if (text.charCodeAt(text.length - 1) === 62) {
|
|
327
|
+
const open = tagState.inTag ? tagState.tagName : '';
|
|
328
|
+
let maybe = open === 'pre' || open === 'listing' || open === 'textarea';
|
|
329
|
+
for (let at = text.indexOf('<'); !maybe && at !== -1; at = text.indexOf('<', at + 1)) {
|
|
330
|
+
const a = text.charCodeAt(at + 1);
|
|
331
|
+
const b = text.charCodeAt(at + 2);
|
|
332
|
+
const c = text.charCodeAt(at + 3);
|
|
333
|
+
/** `pre`, `lis` or `tex`, each letter in either case. */
|
|
334
|
+
maybe =
|
|
335
|
+
((a === 112 || a === 80) && (b === 114 || b === 82) && (c === 101 || c === 69)) ||
|
|
336
|
+
((a === 108 || a === 76) && (b === 105 || b === 73) && (c === 115 || c === 83)) ||
|
|
337
|
+
((a === 116 || a === 84) && (b === 101 || b === 69) && (c === 120 || c === 88));
|
|
338
|
+
}
|
|
339
|
+
if (maybe)
|
|
340
|
+
taker = takesNewline(text, tagState);
|
|
341
|
+
}
|
|
342
|
+
tagState = scanTag(strings[i], tagState);
|
|
343
|
+
rawBounds[i] = [tagState.rawFrom, tagState.rawUntil];
|
|
344
|
+
if (taker && (tagState.foreign !== 0 || tagState.inert !== 0))
|
|
345
|
+
taker = false;
|
|
346
|
+
/**
|
|
347
|
+
* A hole in the content of an SVG `<script>` (or a MathML element of that name) is code too: refused as an HTML
|
|
348
|
+
* script's is (`ssr-script-hole`, every build), JSON or not — a foreign script is no data block (2026-11-18).
|
|
349
|
+
*/
|
|
350
|
+
if (!tagState.inTag && tagState.opens.some((open) => open.name === 'script'))
|
|
351
|
+
throw own(new Error(ssrMisuse('ssr-script-hole', PROSE['ssr-script-hole']())));
|
|
352
|
+
/**
|
|
353
|
+
* **Every question about where this hole sits is answered by that scan** — whether it is inside a tag, which tag,
|
|
354
|
+
* whether a new one opened, and whether the hole is a sigil binding. They used to be answered beside it, by tests
|
|
355
|
+
* on the static's tail (its last `<` against its last `>`, a sigil pattern, a tag-name pattern), which knew nothing
|
|
356
|
+
* of comments, raw text or the tokenizer's names: `<!-- <div .innerHTML=${v}> -->` honored the binding INSIDE the
|
|
357
|
+
* comment, so a `-->` in `v` ended it, and `<textarea><b .innerHTML=${v}>` broke out of the textarea the same way.
|
|
358
|
+
*/
|
|
359
|
+
const inTag = tagState.inTag;
|
|
360
|
+
/** `<template>`'s content: inert markup the client never walks, so it never reaches this
|
|
361
|
+
* binding — it neither renders the value nor keeps the attribute holding it. Nor does this.
|
|
362
|
+
*/
|
|
363
|
+
const inert = tagState.inert > 0;
|
|
364
|
+
/** A new tag starts wherever this text opens one that is still open at its end; what the previous tag held is irrelevant. */
|
|
365
|
+
const opensTag = inTag && tagState.tagAt !== -1;
|
|
366
|
+
if (opensTag || (!inTag && wasInTag)) {
|
|
367
|
+
written = new Set();
|
|
368
|
+
dynamicTag = false;
|
|
369
|
+
if (opensTag)
|
|
370
|
+
elementOrdinal++;
|
|
371
|
+
}
|
|
372
|
+
wasInTag = inTag;
|
|
373
|
+
/** The tag a binding belongs to, by the name the tokenizer reads — the element's `localName` on the client. */
|
|
374
|
+
owner = inTag && !tagState.closing ? tagState.tagName : '';
|
|
375
|
+
/**
|
|
376
|
+
* Whether this hole is an attribute's WHOLE value as it opens — `name=${…}`, quoted or not, with space around `=`
|
|
377
|
+
* as the tokenizer allows. Only then can it be a sigil or event binding: a hole later in a value (`title="a
|
|
378
|
+
* .x=${…}"`) is part of that value.
|
|
379
|
+
*/
|
|
380
|
+
const whole = inTag && tagState.inValue && tagState.opened && tagState.valueStart === strings[i].length;
|
|
381
|
+
/** Offsets are in the author's static; `part` may have lost a leading quote to the binding before it. */
|
|
382
|
+
const shift = strings[i].length - part.length;
|
|
383
|
+
/**
|
|
384
|
+
* Names in the statics are recorded from the text that is actually **emitted**, which is the
|
|
385
|
+
* part with this binding's own name already trimmed off. Scanning the raw part instead counts
|
|
386
|
+
* `title=` — the binding's own name — as a prior write, and in `<b title="a" title=${x}>` the
|
|
387
|
+
* two collapse into one entry, so the real duplicate goes unnoticed.
|
|
388
|
+
*/
|
|
389
|
+
const record = (staticText) => {
|
|
390
|
+
if (inTag)
|
|
391
|
+
for (const [, found] of staticText.matchAll(STATIC_ATTRIBUTE))
|
|
392
|
+
written.add(found.toLowerCase());
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* **A sigil binding** — `.prop`, `?bool`, `@event`, `&ref`, `!live` — is an attribute whose name starts with the
|
|
396
|
+
* sigil and whose whole value is this hole, however it is quoted. The name after the sigil is any name character,
|
|
397
|
+
* as the client's scanner reads it: `._private` and `@_tap` are sigil bindings, and a sigil INSIDE a name is part
|
|
398
|
+
* of it (`data-x.y` is an attribute). A sigil the server does not know is not inert — it would fall through to the
|
|
399
|
+
* attribute path and emit an attribute named `!` — so every sigil is added here in the same pass it is added to
|
|
400
|
+
* the renderer.
|
|
401
|
+
*/
|
|
402
|
+
if (whole && SIGILS.has(tagState.attrRaw[0])) {
|
|
403
|
+
/** The space that preceded the binding goes with it, so dropped bindings leave no residue. */
|
|
404
|
+
const before = part.slice(0, nameCut(strings[i], tagState.nameAt) - shift).replace(/ $/, '');
|
|
405
|
+
record(before);
|
|
406
|
+
parts.push(before);
|
|
407
|
+
openQuote = tagState.quote;
|
|
408
|
+
const kind = tagState.attrRaw[0];
|
|
409
|
+
/**
|
|
410
|
+
* Absent after a bare `&=`, which is an element ref with no name — legal: the renderer back-reads the name `&`
|
|
411
|
+
* and maps it to a ref, so the client renders nothing, and so does this. A nameless `.=`, `?=`, `@=` or `!=` has
|
|
412
|
+
* no meaning either, and is dropped the same way.
|
|
413
|
+
*/
|
|
414
|
+
const sigilName = tagState.attrRaw.slice(1);
|
|
415
|
+
if (inert) {
|
|
416
|
+
kinds.push(DROPPED);
|
|
417
|
+
}
|
|
418
|
+
else if (kind === '?') {
|
|
419
|
+
kinds.push(BOOLEAN);
|
|
420
|
+
}
|
|
421
|
+
else if ((kind === '.' || kind === '!') && sigilName && owner.includes('-')) {
|
|
422
|
+
/**
|
|
423
|
+
* A property on a COMPONENT tag is neither markup nor a client concern: it is the data the
|
|
424
|
+
* child renders from, so it is delivered to the instance the nested-component scan will
|
|
425
|
+
* render — before `FORM_ATTRIBUTES`, because `.value` on `<my-input>` is that component's
|
|
426
|
+
* prop, not a form control's dirty value. `!name` is here beside `.name` for the same
|
|
427
|
+
* reason it serializes as `.name` on form controls, and because a spread reports `!` keys
|
|
428
|
+
* as properties — the two spellings of one binding must get one answer. Whether the tag is
|
|
429
|
+
* actually registered is a render-time question (the registry fills as modules execute),
|
|
430
|
+
* answered in the case below.
|
|
431
|
+
*/
|
|
432
|
+
kinds.push(COMPONENT_PROP);
|
|
433
|
+
urls[kinds.length - 1] = URL_SINK.test(sigilName);
|
|
434
|
+
}
|
|
435
|
+
else if (kind === '.' && CONTENT_PROPS.has(sigilName)) {
|
|
436
|
+
/**
|
|
437
|
+
* `.innerHTML`/`.textContent` on a plain element is the trusted-markup door (`@verajs/renderer`'s property
|
|
438
|
+
* binding): the value is the element's content, written after the open tag. Its foreign depth is the host's
|
|
439
|
+
* INSIDE — the tag's depth, plus one when the host is itself `<svg>`/`<math>` — so a `<style>` in it is read
|
|
440
|
+
* the way the browser will read it. A custom-element host took the `COMPONENT_PROP` branch above.
|
|
441
|
+
*/
|
|
442
|
+
kinds.push(CONTENT);
|
|
443
|
+
depths[kinds.length - 1] = tagState.foreign + (owner === 'svg' || owner === 'math' ? 1 : 0);
|
|
444
|
+
}
|
|
445
|
+
else if ((kind === '.' || kind === '!') && isFormProperty(owner, sigilName)) {
|
|
446
|
+
/**
|
|
447
|
+
* `!name` is a **live** property, and still a property: the sigil only changes when the client re-writes it,
|
|
448
|
+
* and a server has nothing to re-write against — so it serializes exactly as `.name` does, and the first
|
|
449
|
+
* paint is right before the client takes over.
|
|
450
|
+
*/
|
|
451
|
+
kinds.push(FORM_PROP);
|
|
452
|
+
}
|
|
453
|
+
else {
|
|
454
|
+
kinds.push(DROPPED);
|
|
455
|
+
}
|
|
456
|
+
names.push(sigilName);
|
|
457
|
+
strip.push(dynamicTag || written.has(sigilName.toLowerCase()));
|
|
458
|
+
owners.push(owner);
|
|
459
|
+
raws.push(tagState.rawTag);
|
|
460
|
+
elementPositions.push(false);
|
|
461
|
+
elements.push(elementOrdinal);
|
|
462
|
+
if (sigilName)
|
|
463
|
+
written.add(sigilName.toLowerCase());
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
openQuote = '';
|
|
467
|
+
/** `onClick=${fn}` — the React-shaped event binding, named as the client names it: a client concern, dropped like `@`. */
|
|
468
|
+
if (whole && /^on[A-Z]/.test(tagState.attrRaw)) {
|
|
469
|
+
const before = part.slice(0, tagState.nameAt - shift).replace(/ $/, '');
|
|
470
|
+
record(before);
|
|
471
|
+
parts.push(before);
|
|
472
|
+
openQuote = tagState.quote;
|
|
473
|
+
kinds.push(DROPPED);
|
|
474
|
+
names.push('');
|
|
475
|
+
strip.push(false);
|
|
476
|
+
owners.push(owner);
|
|
477
|
+
raws.push(tagState.rawTag);
|
|
478
|
+
elementPositions.push(false);
|
|
479
|
+
elements.push(elementOrdinal);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* **A bound attribute value, in any position** — double-quoted, single-quoted or unquoted, with space
|
|
484
|
+
* around `=`, with statics beside it, or several holes in one value.
|
|
485
|
+
*
|
|
486
|
+
* The client never lets the tokenizer see a value: it joins the attribute's statics and values and calls
|
|
487
|
+
* `setAttribute`. This streamed each position differently instead — a lone unquoted `title=${x}` was
|
|
488
|
+
* quoted, a quoted value was escaped between the author's quotes, and every other shape went out raw
|
|
489
|
+
* and UNQUOTED: `title=pre${x}`, `title=${a}${b}` and `title = ${x}` let a value carrying
|
|
490
|
+
* ` onmouseover=…` end the attribute and start a live handler, while the client rendered one harmless
|
|
491
|
+
* `title`. So every hole in one value shares ONE group, compiled here from `scanTag`'s state: the
|
|
492
|
+
* attribute's head (name, `=`, opening quote, static prefix) and tail (static suffix, closing quote)
|
|
493
|
+
* come off the statics, and the render writes the whole attribute once, always double-quoted — or not
|
|
494
|
+
* at all. Position stops mattering because nothing a value holds can reach the tokenizer.
|
|
495
|
+
*/
|
|
496
|
+
if (tagState.inTag && tagState.inValue && (tagState.opened || groups[kinds.length - 1]?.serial === tagState.serial)) {
|
|
497
|
+
const previous = groups[kinds.length - 1];
|
|
498
|
+
let group;
|
|
499
|
+
if (previous !== undefined && previous.serial === tagState.serial) {
|
|
500
|
+
group = previous;
|
|
501
|
+
group.sole = false;
|
|
502
|
+
parts.push('');
|
|
503
|
+
leads[kinds.length] = forDoubleQuotes(part, group.quote);
|
|
504
|
+
decodedLeads[kinds.length] = decodeSchemeReferences(part);
|
|
505
|
+
}
|
|
506
|
+
else {
|
|
507
|
+
const before = part.slice(0, tagState.attrStart - shift);
|
|
508
|
+
const prefix = part.slice(tagState.valueStart - shift);
|
|
509
|
+
const lower = tagState.attrName;
|
|
510
|
+
/** Whether the name is a URL sink, and which kind (captured: from the start; not: item by item). */
|
|
511
|
+
const sink = URL_SINK.exec(lower);
|
|
512
|
+
record(before);
|
|
513
|
+
parts.push(before);
|
|
514
|
+
group = {
|
|
515
|
+
name: tagState.attrRaw,
|
|
516
|
+
/** Everything the render writes before the value: the separating space, the name, `=` and the quote. */
|
|
517
|
+
open: ` ${tagState.attrRaw}="`,
|
|
518
|
+
serial: tagState.serial,
|
|
519
|
+
quote: tagState.quote,
|
|
520
|
+
first: kinds.length,
|
|
521
|
+
last: kinds.length,
|
|
522
|
+
/**
|
|
523
|
+
* Never served (1): inert content, a bound `srcdoc` (it renders its value as a document) and a bound inline
|
|
524
|
+
* handler (`onclick=${…}` runs its value as code). A URL sink refuses `javascript:` (2), and an animation's
|
|
525
|
+
* value refuses it in any `;`-separated item (3) — as the client does. Above 1: the joined value is checked.
|
|
526
|
+
*/
|
|
527
|
+
refuse: inert || lower === 'srcdoc' || INLINE_HANDLER.test(lower) ? 1 : sink === null ? 0 : sink[1] ? 2 : 3,
|
|
528
|
+
/** An earlier write of this name in the tag: the client's `setAttribute` replaces it, so it is removed. */
|
|
529
|
+
strip: dynamicTag || written.has(lower),
|
|
530
|
+
/** The WHOLE value is this one binding — the only shape where a nullish value removes the attribute. */
|
|
531
|
+
sole: prefix === '',
|
|
532
|
+
suffix: '',
|
|
533
|
+
decodedSuffix: '',
|
|
534
|
+
};
|
|
535
|
+
written.add(lower);
|
|
536
|
+
leads[kinds.length] = forDoubleQuotes(prefix, group.quote);
|
|
537
|
+
decodedLeads[kinds.length] = decodeSchemeReferences(prefix);
|
|
538
|
+
}
|
|
539
|
+
group.last = kinds.length;
|
|
540
|
+
groups[kinds.length] = group;
|
|
541
|
+
kinds.push(ATTRIBUTE);
|
|
542
|
+
names.push(group.name);
|
|
543
|
+
strip.push(false);
|
|
544
|
+
owners.push(owner);
|
|
545
|
+
raws.push(tagState.rawTag);
|
|
546
|
+
elementPositions.push(false);
|
|
547
|
+
elements.push(elementOrdinal);
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
record(part);
|
|
551
|
+
/**
|
|
552
|
+
* A binding dropped inside a comment leaves ONE space where it was, so the statics on either side cannot meet as
|
|
553
|
+
* a different token: `<!${…}--!>` read as a bogus comment, ended by its `>`, while the bare join `<!--!>` OPENS a
|
|
554
|
+
* comment that swallowed the page after it; `-${…}->` joined to `-->` and ended a comment early.
|
|
555
|
+
*/
|
|
556
|
+
parts.push(tagState.comment !== '' && !inert ? part + ' ' : taker ? part + '\n' : part);
|
|
557
|
+
if (tagState.foreign)
|
|
558
|
+
depths[kinds.length] = tagState.foreign;
|
|
559
|
+
/**
|
|
560
|
+
* Inside `<noscript>` too, at any depth (2026-11-18): the client reads a noscript's content as raw text (Firefox, and
|
|
561
|
+
* the renderer's scanner everywhere) and writes its values as encoded text, so a template there cannot be placed —
|
|
562
|
+
* refused here as in a text-only element (`ssr-template-in-text`), one rule on both sides. Values stay escaped, and
|
|
563
|
+
* an attribute value stays quoted.
|
|
564
|
+
*/
|
|
565
|
+
if (tagState.textTag || tagState.opens.some((open) => open.name === 'noscript'))
|
|
566
|
+
texts[kinds.length] = true;
|
|
567
|
+
/** A binding inside a comment is dropped, as the client drops it — never written into the comment. */
|
|
568
|
+
kinds.push(inert || tagState.comment ? DROPPED : TEXT);
|
|
569
|
+
names.push('');
|
|
570
|
+
strip.push(false);
|
|
571
|
+
owners.push(owner);
|
|
572
|
+
raws.push(tagState.rawTag);
|
|
573
|
+
/** Inside a tag, and not inside an attribute value: `<input ${ref} />`, `<b ${spread(…)}>`. */
|
|
574
|
+
const elementPosition = tagState.inTag && !tagState.inValue;
|
|
575
|
+
/**
|
|
576
|
+
* A TAG-name hole — right after `<` or `</`, or inside a tag name: refused in every build, the twin of the client's
|
|
577
|
+
* development refusal, one message.
|
|
578
|
+
*/
|
|
579
|
+
const tagNameHole = tagState.phase === TAG_OPEN || tagState.phase === END_TAG_OPEN || tagState.phase === TAG_NAME;
|
|
580
|
+
if (tagNameHole)
|
|
581
|
+
throw own(new Error(ssrMisuse('tag-hole', TWINS.tagHole())));
|
|
582
|
+
if (elementPosition && !tagNameHole && (NAME_CHAR_BEFORE.test(part) || NAME_CHAR_AFTER.test(strings[i + 1])))
|
|
583
|
+
nameHole(part, strings[i + 1]);
|
|
584
|
+
elementPositions.push(elementPosition);
|
|
585
|
+
elements.push(elementOrdinal);
|
|
586
|
+
/** A spread's keys are unknown until it runs, so its tag can no longer be settled here. */
|
|
587
|
+
if (elementPosition)
|
|
588
|
+
dynamicTag = true;
|
|
589
|
+
}
|
|
590
|
+
let last = strings[strings.length - 1];
|
|
591
|
+
if (openQuote && last.startsWith(openQuote))
|
|
592
|
+
last = last.slice(1);
|
|
593
|
+
parts.push(last);
|
|
594
|
+
/** Each attribute's tail — its static suffix and closing quote — comes off the static after its last hole. */
|
|
595
|
+
for (let i = 0; i < groups.length; i++) {
|
|
596
|
+
const group = groups[i];
|
|
597
|
+
if (group === undefined || group.last !== i)
|
|
598
|
+
continue;
|
|
599
|
+
const next = parts[i + 1];
|
|
600
|
+
/**
|
|
601
|
+
* An unquoted value ends at the tokenizer's whitespace (never `\s`: a `\v` is value text, and cutting there left
|
|
602
|
+
* the rest to open a quote that never closed, losing the element) or `>` — and at a `/>` RIGHT after its last hole, which is the tag's
|
|
603
|
+
* self-close, not value text: the client's scanner keeps the slash out of the value the same way (`<circle
|
|
604
|
+
* r=${r}/>`). Taken as text, it served `r="5/"` and left the element open, nesting the next one inside it.
|
|
605
|
+
*/
|
|
606
|
+
let end = group.quote ? next.indexOf(group.quote) : next.startsWith('/>') ? 0 : next.search(/[\t\n\f\r >]/);
|
|
607
|
+
/** A template that ends inside the value: the rest is the suffix, as the client's parser reads it. */
|
|
608
|
+
const closed = end !== -1;
|
|
609
|
+
if (!closed)
|
|
610
|
+
end = next.length;
|
|
611
|
+
const suffix = next.slice(0, end);
|
|
612
|
+
if (suffix !== '')
|
|
613
|
+
group.sole = false;
|
|
614
|
+
group.suffix = forDoubleQuotes(suffix, group.quote);
|
|
615
|
+
group.decodedSuffix = decodeSchemeReferences(suffix);
|
|
616
|
+
parts[i + 1] = next.slice(closed && group.quote ? end + 1 : end);
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* **A template ends where it began.** The client parses every template on its own, so whatever one leaves open — a
|
|
620
|
+
* comment, a `<style>`, a `<textarea>`, an `<svg>` — the parser closes at its end. The server concatenates, and
|
|
621
|
+
* left open, that state swallowed the PARENT's markup: `${html`<svg>`}<style>${x}</style>` wrote `x` raw inside what
|
|
622
|
+
* the browser parses as SVG, and `${html`<!--`}` let a `-->` in a later raw value end the comment. So the end closes
|
|
623
|
+
* what this template opened, innermost first — the client's own end-of-input rule, read off the statics once. A
|
|
624
|
+
* template that ends INSIDE a tag is refused, in every build: the client's parser drops an unfinished tag whole,
|
|
625
|
+
* which no closer can reproduce, and left open it swallowed the parent's next markup into its attributes. A bare `<`
|
|
626
|
+
* that never started a tag name, as in `a < b`, is text. The client refuses the same templates in development.
|
|
627
|
+
*/
|
|
628
|
+
const end = scanTag(strings[strings.length - 1], tagState);
|
|
629
|
+
rawBounds[strings.length - 1] = [end.rawFrom, end.rawUntil];
|
|
630
|
+
if (end.inValue || (end.inTag && end.tagName))
|
|
631
|
+
throw own(new Error(ssrMisuse('ssr-unfinished-tag', PROSE['ssr-unfinished-tag']())));
|
|
632
|
+
const closers = closersOf(end);
|
|
633
|
+
if (closers)
|
|
634
|
+
parts[parts.length - 1] += closers;
|
|
635
|
+
/**
|
|
636
|
+
* A value in a `<script>` is code — on a served page it runs — so a script hole is refused (`ssr-script-hole`, every
|
|
637
|
+
* build) unless the script is a JSON data block, judged on the start tag that OPENED it (`openingTag`: this tokenizer's
|
|
638
|
+
* own reading, never a search back, so a `<script…>` inside a script's text or a quoted value is never taken for it).
|
|
639
|
+
* A data block's values are written with `<` as `\u003c` (`escapeRawText`'s `json`). Once per template, here.
|
|
640
|
+
*/
|
|
641
|
+
for (let i = 0; i < raws.length; i++) {
|
|
642
|
+
if (raws[i] === 'script') {
|
|
643
|
+
/**
|
|
644
|
+
* A start tag holding a hole is no data block either (2026-11-18): a binding there — `?type=${false}`, a spread,
|
|
645
|
+
* `.type` — changes the type after it was judged, and the script is then served (or saved) as code.
|
|
646
|
+
*/
|
|
647
|
+
const tag = openingTag(strings, i, depth);
|
|
648
|
+
if (!dataBlock(tag) || tag.includes('\uFFFF'))
|
|
649
|
+
throw own(new Error(ssrMisuse('ssr-script-hole', PROSE['ssr-script-hole']())));
|
|
650
|
+
raws[i] = 'json';
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* **The author's static text of a JSON block or an HTML `<style>` is written closed too** (2026-11-18), so the
|
|
654
|
+
* served text is the COMPOSED text closed (`closedRawText`), byte for byte what a client writes: in a block every
|
|
655
|
+
* `<` as `\u003c` (a static `<` before a value, `"<${'/script>…'}"`, otherwise closed it early; in valid JSON a `<` is
|
|
656
|
+
* only ever inside a string, so it is lossless), in a style each `</style` as `<\/style` (a static `</stylex` ends
|
|
657
|
+
* nothing, and is written so all the same). A closer formed ACROSS a style hole is `styleHole`'s, per render. The
|
|
658
|
+
* content in the static before this hole (from where its raw text began, or all of it inside the element) and in the
|
|
659
|
+
* static after (up to its end tag). Raw text follows the tag edits, so it is the same text in the part. Idempotent,
|
|
660
|
+
* so a static between two holes of one element may be visited twice.
|
|
661
|
+
*/
|
|
662
|
+
if (raws[i] === 'json' || raws[i] === 'style') {
|
|
663
|
+
const json = raws[i] === 'json';
|
|
664
|
+
const [from] = rawBounds[i];
|
|
665
|
+
const [, until] = rawBounds[i + 1];
|
|
666
|
+
const before = parts[i];
|
|
667
|
+
const cut = from === -1 ? 0 : before.length - (strings[i].length - from);
|
|
668
|
+
parts[i] = before.slice(0, cut) + closedRawText(before.slice(cut), json);
|
|
669
|
+
const after = parts[i + 1];
|
|
670
|
+
const stop = until === -1 ? after.length : until;
|
|
671
|
+
parts[i + 1] = closedRawText(after.slice(0, stop), json) + after.slice(stop);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Dense, so the render loop reads a value at every binding: both are filled sparsely above, and a hole read falls
|
|
676
|
+
* through to the prototype chain on every child binding of every render — measured at about 3% of a server render.
|
|
677
|
+
*/
|
|
678
|
+
const plan = {
|
|
679
|
+
parts, kinds, names, strip, owners, raws,
|
|
680
|
+
depths: Array.from(kinds, (_, i) => depths[i] ?? 0),
|
|
681
|
+
texts: Array.from(kinds, (_, i) => texts[i] === true),
|
|
682
|
+
elementPositions, elements, groups, leads, decodedLeads, urls,
|
|
683
|
+
};
|
|
684
|
+
if (depth === 0)
|
|
685
|
+
plans.set(strings, plan);
|
|
686
|
+
else {
|
|
687
|
+
let byDepth = foreignPlans.get(strings);
|
|
688
|
+
if (byDepth === undefined)
|
|
689
|
+
foreignPlans.set(strings, (byDepth = new Map()));
|
|
690
|
+
byDepth.set(depth, plan);
|
|
691
|
+
}
|
|
692
|
+
return plan;
|
|
693
|
+
};
|
|
694
|
+
/**
|
|
695
|
+
* `depth` is the foreign-content depth of the position the template renders into — 0 at the top and in HTML.
|
|
696
|
+
*
|
|
697
|
+
* **Where a template renders decides how its raw text parses, and the template cannot see it.** The browser parses
|
|
698
|
+
* the ONE string this produces, so `html`<svg>${child}</svg>`` puts `child`'s `<style>` inside SVG, where its
|
|
699
|
+
* content is markup, however `child` was written; and an `svg`/`mathml` template is foreign content wherever it
|
|
700
|
+
* goes, because the client parses it inside an `<svg>`/`<math>` wrapper. Scanning each template as though it began
|
|
701
|
+
* in HTML wrote both as raw text — unescaped — and the browser then parsed a value's `<img onerror>` as an element.
|
|
702
|
+
* So a template starts at its position's depth, and at least 1 if it is foreign itself. Erring deep is the safe
|
|
703
|
+
* direction: an `svg` template rendered outside any `<svg>` is HTML to the browser, and its `<style>` then shows
|
|
704
|
+
* the escapes as text — a visible mismatch, never an injection.
|
|
705
|
+
*/
|
|
706
|
+
export const serializeTemplate = (template, depth = 0) => {
|
|
707
|
+
const { strings, values } = template;
|
|
708
|
+
/** Absent on core's `html`, and `undefined > 1` is false — the answer wanted; the `!` only lets the comparison be written. */
|
|
709
|
+
if (template['_$litType$'] > 1 && depth === 0)
|
|
710
|
+
depth = 1;
|
|
711
|
+
/**
|
|
712
|
+
* `strings` is any value here, a forgery's included: the cast only names the key the maps hold, and `WeakMap#get`
|
|
713
|
+
* answers `undefined` for a key it could never hold, which sends a forgery on to `compile`'s refusal.
|
|
714
|
+
*/
|
|
715
|
+
const { parts, kinds, names, strip, owners, raws, depths, texts, elementPositions, elements, groups, leads, decodedLeads, urls } = (depth === 0 ? plans.get(strings) : foreignPlans.get(strings)?.get(depth)) ??
|
|
716
|
+
compile(strings, depth) ??
|
|
717
|
+
FORGED;
|
|
718
|
+
/**
|
|
719
|
+
* Not a template — data shaped like one (see `compile`): the text a plain object renders as, the client's very
|
|
720
|
+
* constant. Never the forgery's own conversion: JSON can supply a `"toString"` key, and converting through it throws.
|
|
721
|
+
*/
|
|
722
|
+
if (parts === undefined)
|
|
723
|
+
return FORGED_TEXT;
|
|
724
|
+
/** The attribute being built: its escaped value so far, and the value the client would join (for the URL check). */
|
|
725
|
+
let attribute = '';
|
|
726
|
+
let joined = '';
|
|
727
|
+
let out = '';
|
|
728
|
+
/**
|
|
729
|
+
* The instances this application is delivering properties to, allocated on the FIRST
|
|
730
|
+
* component-prop slot — `serializeTemplate` is the hot path the public SSR numbers rest on, and
|
|
731
|
+
* a template with no component props (almost all of them) must pay one `null` local and nothing
|
|
732
|
+
* else. `instances` is keyed by element ordinal, so `<x-row .a=${…} .b=${…}>` builds ONE
|
|
733
|
+
* instance for both keys while a list's N applications build N; `mark` is the marker text for a
|
|
734
|
+
* just-built instance, held rather than appended directly because the spread path folds `out`
|
|
735
|
+
* while delivering — each delivering case flushes it into the open tag it is building.
|
|
736
|
+
*/
|
|
737
|
+
let adoption = null;
|
|
738
|
+
/**
|
|
739
|
+
* Content that belongs *after* the tag being built rather than inside it — a `<textarea>`'s
|
|
740
|
+
* value, which is text and not an attribute. Written into the next static right after the `>`
|
|
741
|
+
* that closes the tag, replacing whatever the author wrote there, exactly as assigning `.value`
|
|
742
|
+
* does on the client.
|
|
743
|
+
*/
|
|
744
|
+
let pendingText = null;
|
|
745
|
+
/** The close tag `insertContent` strips to when flushing `pendingText` — the host whose content it is (`textarea` for a form value). */
|
|
746
|
+
let pendingStrip = 'textarea';
|
|
747
|
+
/**
|
|
748
|
+
* What each `<select>`'s `.value` or `.selectedIndex` asks for, resolved into `<option selected>` after the loop —
|
|
749
|
+
* the options are usually a nested template, so nothing can be decided until the string is whole.
|
|
750
|
+
*/
|
|
751
|
+
const selectValues = [];
|
|
752
|
+
for (let i = 0; i < kinds.length; i++) {
|
|
753
|
+
const part = parts[i];
|
|
754
|
+
if (pendingText === null)
|
|
755
|
+
out += part;
|
|
756
|
+
else {
|
|
757
|
+
out += insertContent(part, pendingText, pendingStrip);
|
|
758
|
+
pendingText = null;
|
|
759
|
+
}
|
|
760
|
+
const value = values[i];
|
|
761
|
+
switch (kinds[i]) {
|
|
762
|
+
case TEXT:
|
|
763
|
+
/** A spread rewrites the open tag it sits in, so it is folded rather than appended. */
|
|
764
|
+
if (value !== null && typeof value === 'object' && typeof value._$attrs$ === 'function') {
|
|
765
|
+
/**
|
|
766
|
+
* A spread's property keys deliver exactly as the written form above does — `props()`
|
|
767
|
+
* IS a spread, so this is the surface the headline API arrives through. Lazily: the
|
|
768
|
+
* receiving instance is built on the spread's first property key, so a spread of plain
|
|
769
|
+
* attributes on a component never builds one.
|
|
770
|
+
*/
|
|
771
|
+
const componentTag = owners[i].includes('-') && registry.has(owners[i]) ? owners[i] : '';
|
|
772
|
+
const folded = foldSpread(out, owners[i], value._$attrs$(), componentTag === ''
|
|
773
|
+
? undefined
|
|
774
|
+
: (name, propValue) => {
|
|
775
|
+
adoption ??= { instances: new Map(), mark: '' };
|
|
776
|
+
deliverProperty(claimInstance(adoption, elements[i], componentTag), componentTag, name, propValue);
|
|
777
|
+
});
|
|
778
|
+
out = folded.out;
|
|
779
|
+
if (adoption !== null && adoption.mark !== '') {
|
|
780
|
+
out += adoption.mark;
|
|
781
|
+
adoption.mark = '';
|
|
782
|
+
}
|
|
783
|
+
/** With its own host: a stale `pendingStrip` from an earlier `.textContent` kept the author's content. */
|
|
784
|
+
if (folded.text !== null) {
|
|
785
|
+
pendingText = folded.text;
|
|
786
|
+
pendingStrip = owners[i];
|
|
787
|
+
}
|
|
788
|
+
if (folded.select !== null)
|
|
789
|
+
out += ` ${SELECT_MARK}="${selectValues.push(folded.select) - 1}"`;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* An **element-position** expression that is not a spread is a ref — `<input ${myRef} />`,
|
|
793
|
+
* where the renderer hands the element to a function or assigns it to `.value`. It is
|
|
794
|
+
* client state, like `@event`, and has no markup.
|
|
795
|
+
*
|
|
796
|
+
* It used to be stringified into the open tag, so `<input ${ref(null)} />` served
|
|
797
|
+
* `<input [object Object]>` — which the parser then read as two attributes named
|
|
798
|
+
* `[object` and `object]`. A value in this position never has markup; only a spread does.
|
|
799
|
+
*/
|
|
800
|
+
else if (elementPositions[i]) {
|
|
801
|
+
/**
|
|
802
|
+
* The space that introduced the binding goes with it, exactly as a dropped sigil binding's
|
|
803
|
+
* does. Leaving it served `<p >r</p>` where the client renders `<p>r</p>` — harmless to a
|
|
804
|
+
* parser, and still a difference between the two halves for something neither of them
|
|
805
|
+
* renders at all.
|
|
806
|
+
*/
|
|
807
|
+
out = out.replace(/ $/, '');
|
|
808
|
+
break;
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* **Raw text is written raw, and its own end tag is neutralized.**
|
|
812
|
+
*
|
|
813
|
+
* A browser does not decode a character reference inside `<style>` or `<script>`, so
|
|
814
|
+
* escaping there protects nothing and corrupts the content: `<style>${'.a > .b'}</style>`
|
|
815
|
+
* served `.a > .b`, a selector that matches nothing, while the client — which sets text
|
|
816
|
+
* through the DOM and never re-parses — rendered `.a > .b`. Every interpolated stylesheet
|
|
817
|
+
* was broken server-side and correct client-side, which is also a hydration divergence.
|
|
818
|
+
*
|
|
819
|
+
* Not escaping means the element's end tag has to be taken out of the value instead, or it
|
|
820
|
+
* closes the element and everything after it parses as markup. `<\/style` is valid CSS and
|
|
821
|
+
* `<\/script` is the canonical form in JavaScript; both render identically and neither is
|
|
822
|
+
* seen by the tokenizer.
|
|
823
|
+
*
|
|
824
|
+
* `<title>` and `<textarea>` are RCDATA, not RAWTEXT — references *are* decoded there — so
|
|
825
|
+
* they keep ordinary escaping, which is what the client produces for them too.
|
|
826
|
+
*/
|
|
827
|
+
else if (raws[i] === 'style')
|
|
828
|
+
out = styleHole(out, escapeRawText(rawTextOf(value), 'style'), part, parts[i + 1]);
|
|
829
|
+
else if (raws[i])
|
|
830
|
+
out += escapeRawText(rawTextOf(value), raws[i]);
|
|
831
|
+
else
|
|
832
|
+
out += serializeValue(value, false, depths[i], texts[i]);
|
|
833
|
+
break;
|
|
834
|
+
case ATTRIBUTE: {
|
|
835
|
+
/** Every ATTRIBUTE slot has its group — `compile` sets the two together. */
|
|
836
|
+
const group = groups[i];
|
|
837
|
+
/**
|
|
838
|
+
* ONE conversion, the platform's own (`String`, as `setAttribute` does): the URL check reads the very
|
|
839
|
+
* string that is written, so a value whose `toString` answers differently each time cannot pass the
|
|
840
|
+
* check with one answer and be written with another.
|
|
841
|
+
*/
|
|
842
|
+
const text = serializeValue(value, true);
|
|
843
|
+
/** Assembled two ways — one hole that is the whole value, or holes joined with statics — and escaped by one function. */
|
|
844
|
+
if (group.sole) {
|
|
845
|
+
attribute = group.open + escapeHtml(text);
|
|
846
|
+
joined = text;
|
|
847
|
+
}
|
|
848
|
+
else {
|
|
849
|
+
if (group.first === i) {
|
|
850
|
+
attribute = group.open;
|
|
851
|
+
joined = '';
|
|
852
|
+
}
|
|
853
|
+
attribute += leads[i] + escapeHtml(text);
|
|
854
|
+
/** Only a URL sink needs the value the client would join. */
|
|
855
|
+
if (group.refuse > 1)
|
|
856
|
+
joined += decodedLeads[i] + text;
|
|
857
|
+
if (group.last !== i)
|
|
858
|
+
break;
|
|
859
|
+
attribute += group.suffix;
|
|
860
|
+
if (group.refuse > 1)
|
|
861
|
+
joined += group.decodedSuffix;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* ONE decision for every shape, written whole or not at all: a sole nullish value removes the attribute,
|
|
865
|
+
* and a bound srcdoc or a `javascript:` URL is refused — as the client decides each of them.
|
|
866
|
+
*/
|
|
867
|
+
if ((group.sole && value == null) || group.refuse === 1)
|
|
868
|
+
break;
|
|
869
|
+
if (group.refuse > 1 && (group.refuse === 3 ? SCRIPT_URL_ITEM : SCRIPT_URL).test(joined)) {
|
|
870
|
+
refusedScriptUrl(group.name);
|
|
871
|
+
break;
|
|
872
|
+
}
|
|
873
|
+
if (group.strip)
|
|
874
|
+
out = removeAttribute(out, group.name);
|
|
875
|
+
out += attribute + '"';
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
case BOOLEAN:
|
|
879
|
+
if (strip[i])
|
|
880
|
+
out = removeAttribute(out, names[i]);
|
|
881
|
+
if (value)
|
|
882
|
+
out += ` ${names[i]}=""`;
|
|
883
|
+
break;
|
|
884
|
+
case CONTENT:
|
|
885
|
+
pendingText = serverContent(value, owners[i], names[i], depths[i]);
|
|
886
|
+
pendingStrip = owners[i];
|
|
887
|
+
break;
|
|
888
|
+
case FORM_PROP:
|
|
889
|
+
if (!FORM_ELEMENTS.has(owners[i]))
|
|
890
|
+
break;
|
|
891
|
+
/**
|
|
892
|
+
* A `<textarea>`'s value is its **text content**. `<textarea value="x">` is ignored by
|
|
893
|
+
* every parser, so writing the attribute served an empty control while the client — which
|
|
894
|
+
* sets the property — showed the text. Held until the tag closes, because that is where the
|
|
895
|
+
* content goes; see `pendingText` below.
|
|
896
|
+
*/
|
|
897
|
+
/**
|
|
898
|
+
* A `<select>`'s `value` is not an attribute — see `SELECT_MARK`. Marked here and resolved
|
|
899
|
+
* once the options exist; writing ` value="b"` on the tag, which is what this used to do,
|
|
900
|
+
* means nothing to a parser and left the control showing its first option.
|
|
901
|
+
*/
|
|
902
|
+
if (owners[i] === 'select' && (names[i] === 'value' || names[i] === 'selectedIndex')) {
|
|
903
|
+
if (strip[i])
|
|
904
|
+
out = removeAttribute(out, names[i]);
|
|
905
|
+
out += ` ${SELECT_MARK}="${selectValues.push(selection(names[i], value)) - 1}"`;
|
|
906
|
+
break;
|
|
907
|
+
}
|
|
908
|
+
if (owners[i] === 'textarea' && names[i] === 'value') {
|
|
909
|
+
/**
|
|
910
|
+
* `null` and `undefined` are **not** the same value here, and treating them as one is what
|
|
911
|
+
* this used to do. `value` carries `[LegacyNullToEmptyString]` in its IDL, so assigning
|
|
912
|
+
* `null` gives `''` while `undefined` goes through the ordinary ToString and gives the text
|
|
913
|
+
* `"undefined"` — measured in Chromium, Firefox and WebKit, since that is the platform's
|
|
914
|
+
* rule and not this package's to guess. A `== null` test collapses them.
|
|
915
|
+
*
|
|
916
|
+
* The booleans used to be emptied too, which disagreed with `<input>` **one branch below**
|
|
917
|
+
* — the same property, on the same rule, serialized by a different branch: `true` served an
|
|
918
|
+
* empty `<textarea>` against the browser's `true`.
|
|
919
|
+
*/
|
|
920
|
+
pendingText = value === null ? '' : escapeHtml(value);
|
|
921
|
+
break;
|
|
922
|
+
}
|
|
923
|
+
if (strip[i])
|
|
924
|
+
out = removeAttribute(out, names[i]);
|
|
925
|
+
if (BOOLEAN_FORM_PROPERTIES.has(names[i])) {
|
|
926
|
+
if (value)
|
|
927
|
+
out += ` ${names[i]}=""`;
|
|
928
|
+
}
|
|
929
|
+
else if (value !== null || owners[i] === 'option') {
|
|
930
|
+
/**
|
|
931
|
+
* A string property: `true` is `"true"`, exactly as assigning it to the element gives.
|
|
932
|
+
*
|
|
933
|
+
* Three rules, not one, and they were measured rather than assumed:
|
|
934
|
+
*
|
|
935
|
+
* - `<input>` and `<textarea>` carry `[LegacyNullToEmptyString]`, so `null` means the empty
|
|
936
|
+
* string. Omitting the attribute is how markup says that — a parsed `<input>` with no
|
|
937
|
+
* `value` answers `''`.
|
|
938
|
+
* - `<option>` does **not**. `option.value = null` is the text `"null"` in every engine, and
|
|
939
|
+
* omitting the attribute is worse than wrong there: `option.value` then falls back to the
|
|
940
|
+
* element's own text.
|
|
941
|
+
* - `undefined` is never the empty string on any of them. It is `"undefined"`, which looks
|
|
942
|
+
* like a bug because it *is* one — but it is the client's bug too, and the two sides
|
|
943
|
+
* disagreeing about it is a hydration mismatch on top of it.
|
|
944
|
+
*/
|
|
945
|
+
out += ` ${names[i]}="${escapeHtml(value)}"`;
|
|
946
|
+
}
|
|
947
|
+
break;
|
|
948
|
+
case COMPONENT_PROP:
|
|
949
|
+
/**
|
|
950
|
+
* Delivered only when the tag is REGISTERED — a component this process will render, whose
|
|
951
|
+
* server output should come from the same data its client render gets. An unregistered
|
|
952
|
+
* dashed tag (client-only, autoloaded later) is left exactly as before: the tag passes
|
|
953
|
+
* through as markup, the property is the client's to apply, nothing here to receive it.
|
|
954
|
+
* Registration is asked per render, not per plan, because the registry fills as component
|
|
955
|
+
* modules execute.
|
|
956
|
+
*/
|
|
957
|
+
if (registry.has(owners[i]) && !(urls[i] && value != null && SCRIPT_URL.test(`${value}`))) {
|
|
958
|
+
adoption ??= { instances: new Map(), mark: '' };
|
|
959
|
+
deliverProperty(claimInstance(adoption, elements[i], owners[i]), owners[i], names[i], value);
|
|
960
|
+
if (adoption.mark !== '') {
|
|
961
|
+
out += adoption.mark;
|
|
962
|
+
adoption.mark = '';
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
break;
|
|
966
|
+
/** DROPPED: '@' and '&' and a non-component, non-form '.' or '!': nothing — client concerns. */
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
const tail = parts[kinds.length];
|
|
970
|
+
const finished = pendingText === null ? out + tail : out + insertContent(tail, pendingText, pendingStrip);
|
|
971
|
+
return selectValues.length ? resolveSelects(finished, selectValues) : finished;
|
|
972
|
+
};
|
|
973
|
+
/**
|
|
974
|
+
* Puts `text` inside the element the static closes, replacing what the author wrote there.
|
|
975
|
+
*
|
|
976
|
+
* Only `<textarea>` needs this, and only for `.value` — every other form property is an attribute.
|
|
977
|
+
* `<textarea .value=${x}>anything</textarea>` must serve `x`, because that is what the element
|
|
978
|
+
* will hold on the client the moment the property is assigned.
|
|
979
|
+
*/
|
|
980
|
+
/**
|
|
981
|
+
* A `<select>` has **no `value` content attribute**. Assigning the property *selects an option*, so
|
|
982
|
+
* the only way markup can express it is `<option selected>` on the matching one — which is what
|
|
983
|
+
* React's server renderer does, and what this does. Lit's SSR drops the binding entirely and serves
|
|
984
|
+
* a control showing the wrong option.
|
|
985
|
+
*
|
|
986
|
+
* The mark is an index into a per-render list rather than the value itself, so nothing has to be
|
|
987
|
+
* escaped on the way in and unescaped on the way out; it is removed again by `resolveSelects`, and
|
|
988
|
+
* removing it is what terminates that loop.
|
|
989
|
+
*
|
|
990
|
+
* `selectedIndex` chooses an option too, by position rather than by value, so it rides the same mark: the list holds
|
|
991
|
+
* a string for `value` and a number for `selectedIndex`. A tag carrying two marks resolves to its LAST, because on the
|
|
992
|
+
* client the later assignment is the one that stands. Two things each guarantee it, so either may change alone: the
|
|
993
|
+
* greedy `[^>]*` in `MARKED_SELECT` reads a tag's last mark, and a pass removes only one mark, so the tag is resolved
|
|
994
|
+
* again (clearing what the previous pass marked) until its last mark is gone.
|
|
995
|
+
*/
|
|
996
|
+
const SELECT_MARK = 'data-vm-select';
|
|
997
|
+
/**
|
|
998
|
+
* What a `<select>` binding asks for: the value's string, or the index as the platform converts it — `selectedIndex`
|
|
999
|
+
* is a WebIDL `long`, and `| 0` is exactly its conversion (ToInt32: `'1'` is 1, `null` and `NaN` are 0, 1.7 is 1).
|
|
1000
|
+
*/
|
|
1001
|
+
// eslint-disable-next-line no-bitwise -- ToInt32, exactly the WebIDL `long` conversion described above
|
|
1002
|
+
const selection = (name, value) => (name === 'value' ? `${value}` : value | 0);
|
|
1003
|
+
const MARKED_SELECT = new RegExp(`<select\\b[^>]*\\s${SELECT_MARK}="(\\d+)"[^>]*>`, 'i');
|
|
1004
|
+
const OPTION = /<option\b([^>]*)>([\s\S]*?)<\/option>/gi;
|
|
1005
|
+
const OPTION_VALUE = /\bvalue\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
|
|
1006
|
+
const SELECTED_ATTR = /(<option\b[^>]*?)\s+selected(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?/gi;
|
|
1007
|
+
const NAMED = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
1008
|
+
/**
|
|
1009
|
+
* Enough of a decoder to compare an option against a value.
|
|
1010
|
+
*
|
|
1011
|
+
* Everything this serializer writes is escaped as a numeric reference, and the five named ones are
|
|
1012
|
+
* what an author writes by hand. A full entity table would be several kilobytes to decide which
|
|
1013
|
+
* `<option>` is selected, and anything it missed would simply fail to match — which is the same
|
|
1014
|
+
* outcome as an option that genuinely does not match, and is already a documented divergence.
|
|
1015
|
+
*/
|
|
1016
|
+
const decodeRefs = (text) => text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(amp|lt|gt|quot|apos));/g, (whole, dec, hex, name) =>
|
|
1017
|
+
/** Neither number matched, so the name did. */
|
|
1018
|
+
dec ? decodeCodePoint(+dec) : hex ? decodeCodePoint(parseInt(hex, 16)) : NAMED[name] ?? whole);
|
|
1019
|
+
/**
|
|
1020
|
+
* What an engine reports for `option.value`: the `value` attribute verbatim if there is one, and
|
|
1021
|
+
* otherwise the option's text **stripped and collapsed**. Both halves measured in Chromium, Firefox
|
|
1022
|
+
* and WebKit — `tests/browser/select-value.test.js` — because the fallback is easy to assume is the
|
|
1023
|
+
* raw text, and it is not.
|
|
1024
|
+
*/
|
|
1025
|
+
const optionValue = (attributes, text) => {
|
|
1026
|
+
const attribute = OPTION_VALUE.exec(attributes);
|
|
1027
|
+
if (attribute)
|
|
1028
|
+
return decodeRefs(attribute[1] ?? attribute[2] ?? attribute[3]);
|
|
1029
|
+
return decodeRefs(text).replace(/[\t\n\f\r ]+/g, ' ').trim();
|
|
1030
|
+
};
|
|
1031
|
+
/**
|
|
1032
|
+
* Marks the first option matching `wanted`, and clears any `selected` the author wrote.
|
|
1033
|
+
*
|
|
1034
|
+
* Clearing is not tidiness: a property assignment overrides markup, so `<option selected>` beside a
|
|
1035
|
+
* `.value` binding loses on the client and has to lose here too. **First match wins**, which is the
|
|
1036
|
+
* engines' rule for duplicate values.
|
|
1037
|
+
*
|
|
1038
|
+
* When nothing matches, nothing is marked — and that is a divergence markup cannot close. The client
|
|
1039
|
+
* leaves `selectedIndex` at `-1` with nothing showing; a parsed `<select>` with no selected option
|
|
1040
|
+
* takes its **first**. See the SSR README. An index is the same: one out of range — `-1` included — selects nothing
|
|
1041
|
+
* on the client, and marks nothing here.
|
|
1042
|
+
*/
|
|
1043
|
+
const markSelected = (content, wanted) => {
|
|
1044
|
+
const cleared = content.replace(SELECTED_ATTR, '$1');
|
|
1045
|
+
OPTION.lastIndex = 0;
|
|
1046
|
+
let at = 0;
|
|
1047
|
+
for (let match = OPTION.exec(cleared); match; match = OPTION.exec(cleared)) {
|
|
1048
|
+
if (typeof wanted === 'number' ? at++ !== wanted : optionValue(match[1], match[2]) !== wanted)
|
|
1049
|
+
continue;
|
|
1050
|
+
const open = match[0].slice(0, match[0].indexOf('>'));
|
|
1051
|
+
return (cleared.slice(0, match.index) +
|
|
1052
|
+
open.replace(/\s*\/?$/, '') +
|
|
1053
|
+
' selected>' +
|
|
1054
|
+
match[0].slice(match[0].indexOf('>') + 1) +
|
|
1055
|
+
cleared.slice(match.index + match[0].length));
|
|
1056
|
+
}
|
|
1057
|
+
return cleared;
|
|
1058
|
+
};
|
|
1059
|
+
/** Resolves every marked `<select>` once its options are in the string — see `SELECT_MARK`. */
|
|
1060
|
+
const resolveSelects = (markup, wanted) => {
|
|
1061
|
+
for (let match = MARKED_SELECT.exec(markup); match; match = MARKED_SELECT.exec(markup)) {
|
|
1062
|
+
const openTag = match[0].replace(new RegExp(`\\s*${SELECT_MARK}="\\d+"`, 'i'), '');
|
|
1063
|
+
const contentStart = match.index + match[0].length;
|
|
1064
|
+
const closeAt = markup.toLowerCase().indexOf('</select', contentStart);
|
|
1065
|
+
const end = closeAt === -1 ? markup.length : closeAt;
|
|
1066
|
+
markup =
|
|
1067
|
+
markup.slice(0, match.index) +
|
|
1068
|
+
openTag +
|
|
1069
|
+
markSelected(markup.slice(contentStart, end), wanted[+match[1]]) +
|
|
1070
|
+
markup.slice(end);
|
|
1071
|
+
}
|
|
1072
|
+
return markup;
|
|
1073
|
+
};
|
|
1074
|
+
/** The type that makes a classic script inert; written FIRST, so the parser's first-duplicate-wins rule defeats any author `type`. */
|
|
1075
|
+
const INERT_TYPE = ' type="text/x-vera-inert"';
|
|
1076
|
+
/**
|
|
1077
|
+
* **Trusted `innerHTML` markup, made to behave as an `innerHTML` ASSIGNMENT rather than as parsed page markup** —
|
|
1078
|
+
* inert, and self-contained. The two parses differ in exactly two ways a served page would otherwise run: a
|
|
1079
|
+
* `<script>` executes when the browser parses it from the response but never when assigned through `innerHTML`, and a
|
|
1080
|
+
* `<template shadowrootmode>` attaches a shadow root when parsed but not when assigned. Both are neutralized wherever
|
|
1081
|
+
* the tokenizer reads a start tag — never inside a comment, an attribute value or raw text, which `innerHTML` does not
|
|
1082
|
+
* act on either — so the served page matches the client's assignment, and hydration (which re-assigns) agrees.
|
|
1083
|
+
*
|
|
1084
|
+
* **The tags come from `scanTag`, the scan every template gets.** This used to run its own mini-tokenizer, and the two
|
|
1085
|
+
* drifted: it read a quote inside an attribute NAME as opening a value, so `<b x"><script>` served live, and it
|
|
1086
|
+
* skipped `<style>` content inside `<svg>`, where it is markup, so `<svg><style><script>` served live. Reading a tag
|
|
1087
|
+
* where the browser does not is only ever safe in one direction — over-neutralizing a `<script` that was text makes
|
|
1088
|
+
* an inert thing inert — and `scanTag` errs that way wherever it is deliberately incomplete (see its foreign depth).
|
|
1089
|
+
*
|
|
1090
|
+
* Whatever the markup leaves open is closed, so it cannot reach the host's parent: its comment, raw-text element and
|
|
1091
|
+
* svg/math/noscript/template (`closersOf`). An UNFINISHED tag is dropped, as an assignment's parser drops it at the
|
|
1092
|
+
* end of input — served, it swallowed the page's next markup into its attributes. A `<` or `</` that never started a
|
|
1093
|
+
* tag is text, written escaped, so the host's own end tag cannot become the rest of it.
|
|
1094
|
+
*/
|
|
1095
|
+
const fortify = (markup, depth) => {
|
|
1096
|
+
const edits = [];
|
|
1097
|
+
const end = scanTag(markup, freshScan(depth), edits);
|
|
1098
|
+
let stop = markup.length;
|
|
1099
|
+
let tail = '';
|
|
1100
|
+
if (end.phase === TAG_OPEN || end.phase === END_TAG_OPEN) {
|
|
1101
|
+
stop = end.tagAt;
|
|
1102
|
+
tail = '<' + markup.slice(stop + 1);
|
|
1103
|
+
}
|
|
1104
|
+
else if (end.inTag) {
|
|
1105
|
+
stop = end.tagAt;
|
|
1106
|
+
/** An unfinished END tag of the raw-text element it was ending leaves that element open — so it is closed. */
|
|
1107
|
+
if (end.closing && end.foreign === 0 && (RAWTEXT.has(end.tagName) || TEXT_ONLY.has(end.tagName)))
|
|
1108
|
+
tail = `</${end.tagName}>`;
|
|
1109
|
+
}
|
|
1110
|
+
let out = '';
|
|
1111
|
+
let from = 0;
|
|
1112
|
+
for (let i = 0; i < edits.length && edits[i] < stop; i += 2) {
|
|
1113
|
+
const at = edits[i];
|
|
1114
|
+
out += markup.slice(from, at) + (edits[i + 1] === EDIT_INERT ? INERT_TYPE : 'data-vera-');
|
|
1115
|
+
from = at;
|
|
1116
|
+
}
|
|
1117
|
+
return out + markup.slice(from, stop) + tail + closersOf(end);
|
|
1118
|
+
};
|
|
1119
|
+
/**
|
|
1120
|
+
* **A value written into a `<style>`, with every closer it takes part in neutralized** (2026-11-18). `</style` (any
|
|
1121
|
+
* case) ends the element wherever it is formed, and it can be formed ACROSS a hole: the static before a value and the
|
|
1122
|
+
* value (`"<${'/style><img…>'}"`), the value and the static after, or several values. A closer is 7 characters, so one
|
|
1123
|
+
* that crosses this hole lies within the 6 characters already written, the value, and the next static's first 6; each
|
|
1124
|
+
* such closer gets a `\` before its `/` (`<\/style`, the same CSS), wherever the `/` falls — in what is written, the
|
|
1125
|
+
* value, or the next static (the `\` then goes after the value). A closer wholly inside the next static is the element's
|
|
1126
|
+
* own end tag, and one wholly in what was written was dealt with at its own hole. Statics alone never hold a closer, so
|
|
1127
|
+
* the output is the composed text's: byte for byte what a client writes.
|
|
1128
|
+
*/
|
|
1129
|
+
const styleHole = (out, value, before, next) => {
|
|
1130
|
+
/**
|
|
1131
|
+
* What was written last, read from the static just written when it holds 6 characters — `out` is the whole document
|
|
1132
|
+
* so far, and slicing it flattens that string on every hole (measured: most of a page's style-hole cost, 2026-11-18).
|
|
1133
|
+
* A closer crossing this hole starts with a `<` in it or in the value; with neither, nothing crosses.
|
|
1134
|
+
*/
|
|
1135
|
+
const tail = before.length >= 6 ? before.slice(-6) : out.slice(-6);
|
|
1136
|
+
if (!value.includes('<') && !tail.includes('<'))
|
|
1137
|
+
return out + value;
|
|
1138
|
+
const head = next.slice(0, 6);
|
|
1139
|
+
const window = tail + value + head;
|
|
1140
|
+
const start = tail.length;
|
|
1141
|
+
const stop = start + value.length;
|
|
1142
|
+
/** Where, in the window, a `\` goes: before each crossing closer's `/`. */
|
|
1143
|
+
const at = [];
|
|
1144
|
+
for (const match of window.matchAll(/<\/style/gi)) {
|
|
1145
|
+
const m = match.index;
|
|
1146
|
+
if (m < stop && m + 7 > start)
|
|
1147
|
+
at.push(m + 1);
|
|
1148
|
+
}
|
|
1149
|
+
if (at.length === 0)
|
|
1150
|
+
return out + value;
|
|
1151
|
+
let written = out.slice(0, out.length - tail.length);
|
|
1152
|
+
let from = 0;
|
|
1153
|
+
const marked = window.slice(0, stop);
|
|
1154
|
+
for (const p of at) {
|
|
1155
|
+
written += marked.slice(from, Math.min(p, stop)) + '\\';
|
|
1156
|
+
from = Math.min(p, stop);
|
|
1157
|
+
}
|
|
1158
|
+
return written + marked.slice(from);
|
|
1159
|
+
};
|
|
1160
|
+
/**
|
|
1161
|
+
* The content a `.innerHTML`/`.textContent` binding writes after the host's open tag. `innerHTML` is
|
|
1162
|
+
* `[LegacyNullToEmptyString]` (so `null` is `''` but `undefined` is `"undefined"`); `textContent` is nullable (both
|
|
1163
|
+
* are `''`) — measured against a browser, not guessed. The host decides escaping: a RAWTEXT host (`<style>`,
|
|
1164
|
+
* `<script>`) neutralizes its own close tag and is otherwise raw; a text-only or foreign host, and any
|
|
1165
|
+
* `textContent`, is escaped text; only `innerHTML` on an ordinary HTML host is live markup, made inert first.
|
|
1166
|
+
*/
|
|
1167
|
+
const serverContent = (value, owner, property, depth) => {
|
|
1168
|
+
const text = value === null || (value === undefined && property === 'textContent') ? '' : `${value}`;
|
|
1169
|
+
if (RAWTEXT.has(owner))
|
|
1170
|
+
return escapeRawText(text, owner);
|
|
1171
|
+
if (property === 'textContent' || TEXT_ONLY.has(owner) || owner === 'noscript' || depth > 0)
|
|
1172
|
+
return escapeHtml(text);
|
|
1173
|
+
return fortify(text, depth);
|
|
1174
|
+
};
|
|
1175
|
+
const insertContent = (staticText, text, strip) => {
|
|
1176
|
+
const close = staticText.indexOf('>');
|
|
1177
|
+
if (close === -1)
|
|
1178
|
+
return staticText;
|
|
1179
|
+
const rest = staticText.slice(close + 1);
|
|
1180
|
+
const end = rest.toLowerCase().indexOf('</' + strip);
|
|
1181
|
+
/** One line feed for the parser to take, always — the client sets this content through the DOM (see `takesNewline`). */
|
|
1182
|
+
const guard = NEWLINE_TAKERS.has(strip) ? '\n' : '';
|
|
1183
|
+
return staticText.slice(0, close + 1) + guard + text + (end === -1 ? rest : rest.slice(end));
|
|
1184
|
+
};
|
|
1185
|
+
/**
|
|
1186
|
+
* Fold resolved spread bindings into the tag being built, mirroring what the client does.
|
|
1187
|
+
*
|
|
1188
|
+
* Appending is not enough, and the difference is a correctness bug rather than a nicety.
|
|
1189
|
+
* `<input type="text" ${spread({ type: 'number' })}>` appends a second `type`, and an HTML parser
|
|
1190
|
+
* keeps the **first** duplicate — so the server would render `type="text"` while the client, where
|
|
1191
|
+
* `setAttribute` overwrites, renders `type="number"`. Same template, two answers, and a hydration
|
|
1192
|
+
* mismatch between them.
|
|
1193
|
+
*
|
|
1194
|
+
* So a spread key removes any attribute of that name already written into the open tag before
|
|
1195
|
+
* adding its own — including when it adds nothing, because `?disabled: false` and `id: null` both
|
|
1196
|
+
* *remove* on the client and must remove here too. Kinds that never touch attributes client-side
|
|
1197
|
+
* (events, non-form properties) leave the tag alone.
|
|
1198
|
+
*
|
|
1199
|
+
* Splitting on the last `<` is safe: attribute values are escaped, so no raw `<` can appear inside
|
|
1200
|
+
* one.
|
|
1201
|
+
*/
|
|
1202
|
+
/**
|
|
1203
|
+
* Removes an attribute already written into the open tag being built, so the last write wins.
|
|
1204
|
+
*
|
|
1205
|
+
* An HTML parser keeps the **first** of a duplicate pair; `setAttribute` on the client overwrites,
|
|
1206
|
+
* so the **last** wins there. `<b title="a" title=${x}>` therefore showed `a` on a server-rendered
|
|
1207
|
+
* page and `b` in the browser — the same disagreement `foldSpread` was written to fix for spreads,
|
|
1208
|
+
* which is where this logic came from. It applies to anything that writes a name into the tag.
|
|
1209
|
+
*/
|
|
1210
|
+
/**
|
|
1211
|
+
* One pattern per attribute name, built once. `new RegExp` per binding was 16% of a 100-row render.
|
|
1212
|
+
*/
|
|
1213
|
+
const removalPatterns = new Map();
|
|
1214
|
+
/**
|
|
1215
|
+
* The name is **escaped** before it becomes a pattern. A spread's keys are runtime data, and an
|
|
1216
|
+
* attribute name may legally contain regular-expression metacharacters — `a|b`, `a.b`, `a*` are all
|
|
1217
|
+
* names `setAttribute` accepts — so interpolating one raw built a pattern that matched something
|
|
1218
|
+
* else entirely. `a|b` compiled to an alternation and removed text nowhere near the attribute it
|
|
1219
|
+
* named.
|
|
1220
|
+
*/
|
|
1221
|
+
const escapeForPattern = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1222
|
+
const removalPattern = (name) => {
|
|
1223
|
+
let pattern = removalPatterns.get(name);
|
|
1224
|
+
if (!pattern)
|
|
1225
|
+
removalPatterns.set(name, (pattern = new RegExp(`\\s${escapeForPattern(name)}(=("[^"]*"|'[^']*'|[^\\s>]*))?`, 'i')));
|
|
1226
|
+
return pattern;
|
|
1227
|
+
};
|
|
1228
|
+
/**
|
|
1229
|
+
* A name that cannot be written into a tag safely.
|
|
1230
|
+
*
|
|
1231
|
+
* A spread's keys are the one part of a template that is runtime data — that is what the module is
|
|
1232
|
+
* for — and they were interpolated into the open tag with no check at all, while every *value*
|
|
1233
|
+
* around them was escaped. A key carrying a quote or a `>` therefore closed the attribute, or the
|
|
1234
|
+
* element:
|
|
1235
|
+
*
|
|
1236
|
+
* spread({ 'x><script>alert(1)</script': '1' })
|
|
1237
|
+
* -> <b x><script>alert(1)</script="1">x</b>
|
|
1238
|
+
*
|
|
1239
|
+
* The set is the HTML attribute-name restriction — control characters, whitespace, `"`, `'`, `>`,
|
|
1240
|
+
* `/`, `=` — plus `<` and a backtick, which the specification permits and no real name uses.
|
|
1241
|
+
*
|
|
1242
|
+
* It is deliberately **stricter than `setAttribute`**, which was measured in Chromium and accepts
|
|
1243
|
+
* `"`, `'` and `<` while rejecting whitespace, `>`, `=`, `/` and NUL. A name the platform accepts
|
|
1244
|
+
* but markup cannot carry is unusable in a framework that server-renders, so `@verajs/renderer/spread`
|
|
1245
|
+
* applies this same rule client-side and the two sides agree on every key rather than one of them
|
|
1246
|
+
* quietly serving different markup.
|
|
1247
|
+
*
|
|
1248
|
+
* The control-character range is the point of the rule, not a mistake in it: a name carrying one
|
|
1249
|
+
* is exactly what must never reach markup.
|
|
1250
|
+
*/
|
|
1251
|
+
// eslint-disable-next-line no-control-regex
|
|
1252
|
+
export const UNSAFE_ATTRIBUTE_NAME = /^$|[\s"'>/=<`]|[\u0000-\u001f\u007f]/;
|
|
1253
|
+
/**
|
|
1254
|
+
* Strips one attribute out of an open tag, and the one place that knows how.
|
|
1255
|
+
*
|
|
1256
|
+
* `foldSpread` had its own copy of this pattern, character for character — so a fix to one was a
|
|
1257
|
+
* fix to one. It also rebuilt the pattern on every key of every spread, which is the per-render
|
|
1258
|
+
* work `tests/ssr-serializer-work.test.mjs` exists to refuse.
|
|
1259
|
+
*/
|
|
1260
|
+
const stripAttribute = (tag, name) =>
|
|
1261
|
+
/**
|
|
1262
|
+
* Almost no tag carries the name twice, and a substring search settles that far faster than a
|
|
1263
|
+
* pattern match does. Case-insensitive to match the pattern it guards, which HTML requires.
|
|
1264
|
+
*/
|
|
1265
|
+
tag.toLowerCase().includes(name.toLowerCase()) ? tag.replace(removalPattern(name), '') : tag;
|
|
1266
|
+
const removeAttribute = (out, name) => {
|
|
1267
|
+
const tagStart = out.lastIndexOf('<');
|
|
1268
|
+
if (tagStart === -1)
|
|
1269
|
+
return out;
|
|
1270
|
+
return out.slice(0, tagStart) + stripAttribute(out.slice(tagStart), name);
|
|
1271
|
+
};
|
|
1272
|
+
const foldSpread = (out,
|
|
1273
|
+
/** The tag the spread sits in, as the template's scan named it (see `compile`). */
|
|
1274
|
+
owner, entries, deliverProp) => {
|
|
1275
|
+
const tagStart = out.lastIndexOf('<');
|
|
1276
|
+
let tag = out.slice(tagStart);
|
|
1277
|
+
let added = '';
|
|
1278
|
+
/** A `<textarea>`'s value is its text content, so a `.value` key here is not an attribute. */
|
|
1279
|
+
let text = null;
|
|
1280
|
+
/** A `<select>`'s value is not an attribute either; the caller marks the tag — see `SELECT_MARK`. */
|
|
1281
|
+
let select = null;
|
|
1282
|
+
const isFormElement = FORM_ELEMENTS.has(owner);
|
|
1283
|
+
for (const [kind, name, value] of entries) {
|
|
1284
|
+
/**
|
|
1285
|
+
* A property key on a rendered component tag is handed to the caller's delivery — the same
|
|
1286
|
+
* door the written `.prop=${…}` form takes, because `props()` IS a spread and a key must mean
|
|
1287
|
+
* the same thing in both spellings. The callback exists only when the owner is a registered
|
|
1288
|
+
* component; everywhere else the key falls through to the rules below unchanged.
|
|
1289
|
+
*/
|
|
1290
|
+
if (kind === 'p' && deliverProp !== undefined) {
|
|
1291
|
+
deliverProp(name, value);
|
|
1292
|
+
continue;
|
|
1293
|
+
}
|
|
1294
|
+
const serializes = kind === 'a' || kind === 'b' || (kind === 'p' && isFormElement && isFormProperty(owner, name));
|
|
1295
|
+
if (!serializes)
|
|
1296
|
+
continue;
|
|
1297
|
+
/**
|
|
1298
|
+
* Dropped, and dropped **before** anything is done with the name — `stripAttribute` compiles it
|
|
1299
|
+
* into a pattern, so an unchecked name is a second way in.
|
|
1300
|
+
*
|
|
1301
|
+
* Silent here on purpose. A key that reaches this is either a mistake, which the identical check
|
|
1302
|
+
* in `@verajs/renderer/spread` reports in development where the author will see it, or it is
|
|
1303
|
+
* hostile — and a server that logs a line per hostile key hands an attacker the log file.
|
|
1304
|
+
*/
|
|
1305
|
+
if (UNSAFE_ATTRIBUTE_NAME.test(name))
|
|
1306
|
+
continue;
|
|
1307
|
+
/** Quoted, single-quoted, unquoted, or valueless — whatever the template author wrote. */
|
|
1308
|
+
tag = stripAttribute(tag, name);
|
|
1309
|
+
/**
|
|
1310
|
+
* A `<textarea>`'s `.value` is its **content**, exactly as it is for a written binding — the
|
|
1311
|
+
* attribute this would otherwise write is ignored by every parser, so the control arrived empty
|
|
1312
|
+
* while the client, which sets the property, showed the text. The written form was fixed and
|
|
1313
|
+
* this one was not: a spread key means what the written binding means, always.
|
|
1314
|
+
*/
|
|
1315
|
+
if (kind === 'p' && owner === 'select' && (name === 'value' || name === 'selectedIndex')) {
|
|
1316
|
+
/** A spread key means what the written binding means, always — see `SELECT_MARK`. */
|
|
1317
|
+
select = selection(name, value);
|
|
1318
|
+
continue;
|
|
1319
|
+
}
|
|
1320
|
+
if (kind === 'p' && owner === 'textarea' && name === 'value') {
|
|
1321
|
+
text = value === null ? '' : escapeHtml(value);
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Same coercions as a written binding, kind by kind — which is the contract, and which this had
|
|
1326
|
+
* only approximately.
|
|
1327
|
+
*
|
|
1328
|
+
* A **boolean** is truthiness, and so are `checked` and `selected`. A plain **attribute** takes
|
|
1329
|
+
* anything that is not nullish, `false` included: `String(false)` is `"false"`, which is what
|
|
1330
|
+
* `setAttribute` writes and what the written form already emitted. Treating `false` as removal
|
|
1331
|
+
* for every kind meant `${spread({ title: false })}` dropped the attribute while
|
|
1332
|
+
* `title=${false}` kept it — the same value, two answers, from the two spellings of one binding.
|
|
1333
|
+
*/
|
|
1334
|
+
if (kind === 'b' || (kind === 'p' && BOOLEAN_FORM_PROPERTIES.has(name))) {
|
|
1335
|
+
if (value)
|
|
1336
|
+
added += ` ${name}=""`;
|
|
1337
|
+
}
|
|
1338
|
+
else if (kind === 'p') {
|
|
1339
|
+
/**
|
|
1340
|
+
* **A string form property and a plain attribute are no longer the same rule**, which is why
|
|
1341
|
+
* this branch split. An attribute is removed by either nullish value — the renderer's own
|
|
1342
|
+
* documented behavior, matching lit, on both sides. A `value` property is not: its IDL carries
|
|
1343
|
+
* `[LegacyNullToEmptyString]` on `<input>` and `<textarea>`, so `null` alone means the empty
|
|
1344
|
+
* string, `undefined` is the text `"undefined"`, and `<option>` has neither rule and takes
|
|
1345
|
+
* `"null"`. Written and spread must agree about all of it —
|
|
1346
|
+
* `tests/ssr-spread-equivalence.test.mjs` is what caught this one, and it caught it the same
|
|
1347
|
+
* afternoon the written form was corrected.
|
|
1348
|
+
*/
|
|
1349
|
+
if (value !== null || owner === 'option')
|
|
1350
|
+
added += ` ${name}="${escapeHtml(value)}"`;
|
|
1351
|
+
}
|
|
1352
|
+
else if (value != null) {
|
|
1353
|
+
/**
|
|
1354
|
+
* A plain attribute takes anything not nullish and is removed by either nullish value.
|
|
1355
|
+
* `false` is `"false"` and `true` is `"true"`, because that is what `setAttribute` produces.
|
|
1356
|
+
*/
|
|
1357
|
+
added += ` ${name}="${escapeHtml(serializeValue(value, true))}"`;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* The element-position slot already carries the separating space, so the first addition drops its
|
|
1362
|
+
* own. When a spread contributes nothing — every key nullish, or all of them client concerns —
|
|
1363
|
+
* that space is left dangling before the `>`, which the parser ignores and which is still a byte
|
|
1364
|
+
* in every response and untidy in a view-source.
|
|
1365
|
+
*/
|
|
1366
|
+
return {
|
|
1367
|
+
out: out.slice(0, tagStart) + (added ? tag + added.slice(1) : tag.replace(/ $/, '')),
|
|
1368
|
+
/** Written into the next static, after the `>` that closes this tag — see `insertContent`. */
|
|
1369
|
+
text,
|
|
1370
|
+
select,
|
|
1371
|
+
};
|
|
1372
|
+
};
|
|
1373
|
+
/**
|
|
1374
|
+
* **Out of line on purpose: `serializeValue` must stay under V8's inlining budget.** It is inlined into
|
|
1375
|
+
* `serializeTemplate`'s per-binding loop only while its bytecode is at most 460 bytes (`--max-inlined-bytecode-size`), and
|
|
1376
|
+
* it sat at 455: the DOM-node case (2026-10-09) took it to 467 and cost 3.6% steady on renders that never reach the
|
|
1377
|
+
* case — any statement did (a never-taken branch alone measured +4.0%). A refusal's error construction is the cheapest
|
|
1378
|
+
* thing to move out: it runs once, at the throw.
|
|
1379
|
+
*/
|
|
1380
|
+
const refuseTemplateInText = () => {
|
|
1381
|
+
throw own(new Error(ssrMisuse('ssr-template-in-text', PROSE['ssr-template-in-text']())));
|
|
1382
|
+
};
|
|
1383
|
+
/**
|
|
1384
|
+
* **A value in a `<style>` or JSON data block, as text** — the rule `<textarea>`/`<title>` already follow, and every
|
|
1385
|
+
* client writes (2026-11-18): nothing for `null`/`undefined`, a list its items' text (nested lists flattened by the same
|
|
1386
|
+
* rule), a template refused (`ssr-template-in-text`), anything else `String`. Before, `String(value)` wrote a list as
|
|
1387
|
+
* `a,b` (commas between CSS rules) and a template as `[object Object]`.
|
|
1388
|
+
*/
|
|
1389
|
+
const rawTextOf = (value) => {
|
|
1390
|
+
if (value == null)
|
|
1391
|
+
return '';
|
|
1392
|
+
if (Array.isArray(value)) {
|
|
1393
|
+
let out = '';
|
|
1394
|
+
for (let i = 0; i < value.length; i++)
|
|
1395
|
+
out += rawTextOf(value[i]);
|
|
1396
|
+
return out;
|
|
1397
|
+
}
|
|
1398
|
+
if (typeof value === 'object' && isLiteral(value.strings))
|
|
1399
|
+
refuseTemplateInText();
|
|
1400
|
+
return `${value}`;
|
|
1401
|
+
};
|
|
1402
|
+
/**
|
|
1403
|
+
* **A child value that applies itself (`_$child$`) renders on a server what it would show FIRST on a client** (2026-10-26,
|
|
1404
|
+
* found by `@verajs/renderer/until`'s server row: every such value served `[object Object]`). The applier runs against a
|
|
1405
|
+
* server part whose `_$commit$` keeps what it commits; the last SYNCHRONOUS commit is served, as the client's first
|
|
1406
|
+
* frame shows it. A commit that arrives later (a promise settling) lands on a part already served and dropped. Out of
|
|
1407
|
+
* line: `serializeValue` sits near V8's inlining budget (`tests/ssr-inlining-budget.test.mjs`).
|
|
1408
|
+
*/
|
|
1409
|
+
const serializeChild = (value, depth, text) => {
|
|
1410
|
+
let committed;
|
|
1411
|
+
value._$child$.call(value, { _$commit$: (next) => { committed = next; }, $R: null }, undefined, false);
|
|
1412
|
+
return serializeValue(committed, false, depth, text);
|
|
1413
|
+
};
|
|
1414
|
+
export const serializeValue = (value, raw = false, depth = 0, text = false) => {
|
|
1415
|
+
/**
|
|
1416
|
+
* Only `null` and `undefined` are empty, exactly as on the client — `false` and `0` render.
|
|
1417
|
+
* `false` used to serialize as empty here, which made `${cond && 'x'}` emit nothing on the server
|
|
1418
|
+
* and the text `false` in the browser: a silent content difference on a static page, and a full
|
|
1419
|
+
* re-render on a hydrated one.
|
|
1420
|
+
*/
|
|
1421
|
+
if (value == null)
|
|
1422
|
+
return '';
|
|
1423
|
+
/**
|
|
1424
|
+
* **An attribute stringifies exactly as the platform does, and nothing else.**
|
|
1425
|
+
*
|
|
1426
|
+
* A child position renders a value — a template becomes markup, an array renders every item, a
|
|
1427
|
+
* function is client state and disappears. An attribute does none of that: it goes through
|
|
1428
|
+
* `setAttribute`, which is `String(value)` and only that. The two are different rules and this
|
|
1429
|
+
* had one of them.
|
|
1430
|
+
*
|
|
1431
|
+
* Measured against a browser, every one of these disagreed: `[1, 2]` served `12` against `1,2`
|
|
1432
|
+
* (arrays have their own `toString`), a `Set` served `1,2` against `[object Set]`, a function
|
|
1433
|
+
* served nothing against its own source, and a **template served its markup into an attribute
|
|
1434
|
+
* value** against `[object Object]`. Escaped, so not an injection — and still a completely
|
|
1435
|
+
* different page before and after hydration.
|
|
1436
|
+
*/
|
|
1437
|
+
if (raw)
|
|
1438
|
+
return `${value}`;
|
|
1439
|
+
/**
|
|
1440
|
+
* Loops, never `map` with an arrow: an arrow capturing `depth`/`text` makes V8 heap-allocate a context on EVERY call of
|
|
1441
|
+
* this function, whichever branch runs — measured at about 5% of a server render.
|
|
1442
|
+
*/
|
|
1443
|
+
if (Array.isArray(value)) {
|
|
1444
|
+
let out = '';
|
|
1445
|
+
for (let i = 0; i < value.length; i++)
|
|
1446
|
+
out += serializeValue(value[i], false, depth, text);
|
|
1447
|
+
return out;
|
|
1448
|
+
}
|
|
1449
|
+
if (typeof value === 'function')
|
|
1450
|
+
return '';
|
|
1451
|
+
if (typeof value === 'object') {
|
|
1452
|
+
/** Template-shaped (core's html, by shape) recurses. `keyed()` mutates one, so it arrives here. */
|
|
1453
|
+
/**
|
|
1454
|
+
* Inside `<textarea>`, `<title>` and the other text-only elements a template is refused: their content is text to
|
|
1455
|
+
* the browser, where the client's elements are never shown, and a template's markup there is the one way a value
|
|
1456
|
+
* can CLOSE the element — `${html`</textarea>`}` — and turn the statics after it into unchecked markup.
|
|
1457
|
+
*/
|
|
1458
|
+
if (value.strings) {
|
|
1459
|
+
if (text && isLiteral(value.strings))
|
|
1460
|
+
refuseTemplateInText();
|
|
1461
|
+
return serializeTemplate(value, depth);
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* `hold(result)` is `{ $h: result }` — a client-renderer construct that keeps the DOM of a
|
|
1465
|
+
* toggled-away subtree alive so form values and scroll positions survive the round trip. There
|
|
1466
|
+
* is no previous DOM on a server, so the wrapper means nothing here and the template inside it
|
|
1467
|
+
* means everything.
|
|
1468
|
+
*
|
|
1469
|
+
* It used to fall through to `String(value)` and serve the text `[object Object]` into the
|
|
1470
|
+
* page. `keyed()` works because it mutates the template and hands the same object back; `hold`
|
|
1471
|
+
* wraps one, and nothing unwrapped it.
|
|
1472
|
+
*/
|
|
1473
|
+
if (value.$h)
|
|
1474
|
+
return serializeValue(value.$h, raw, depth, text);
|
|
1475
|
+
/**
|
|
1476
|
+
* A spread (`@verajs/renderer/spread`) at element position. It hands back resolved bindings and this
|
|
1477
|
+
* decides what reaches markup: attributes and truthy booleans do, form properties do because
|
|
1478
|
+
* hydration reads them back, and events and other properties are client state. Escaping happens
|
|
1479
|
+
* here and only here — principle #8 puts it at the render boundary, not at the source.
|
|
1480
|
+
*/
|
|
1481
|
+
if (typeof value._$attrs$ === 'function')
|
|
1482
|
+
return '';
|
|
1483
|
+
if (typeof value._$child$ === 'function')
|
|
1484
|
+
return serializeChild(value, depth, text);
|
|
1485
|
+
/**
|
|
1486
|
+
* **A DOM node writes nothing** (2026-10-09). The client inserts the node itself, and hydration's contract is that
|
|
1487
|
+
* the server rendered nothing for it — the renderer README's "the one thing the server cannot have rendered", which
|
|
1488
|
+
* adoption relies on to keep everything around it. This fell through to `String(value)` and served
|
|
1489
|
+
* `[object EventTarget]` into the page, which the client then refused as markup the template does not describe:
|
|
1490
|
+
* junk on the static page AND the whole container's adoption discarded. Before the iterable test, so a fragment
|
|
1491
|
+
* (whose children are a node list) never reads as a list.
|
|
1492
|
+
*/
|
|
1493
|
+
if (value instanceof NodeBase)
|
|
1494
|
+
return '';
|
|
1495
|
+
/**
|
|
1496
|
+
* An iterable renders its entries, exactly as the client's child position does — a `Set` or a
|
|
1497
|
+
* `Map` reaching a template is not obviously deliberate, but the two sides have to agree about
|
|
1498
|
+
* it or hydration is discarded.
|
|
1499
|
+
*/
|
|
1500
|
+
if (typeof value[Symbol.iterator] === 'function') {
|
|
1501
|
+
let out = '';
|
|
1502
|
+
for (const entry of value)
|
|
1503
|
+
out += serializeValue(entry, false, depth, text);
|
|
1504
|
+
return out;
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Everything else falls through to `String(value)`, which is what the client does.
|
|
1508
|
+
*
|
|
1509
|
+
* This used to return `''` for any object that was not template-shaped, and the client has
|
|
1510
|
+
* never agreed: a `Date` rendered its full date string there and nothing here, an object with a
|
|
1511
|
+
* `toString` rendered its text, a `Promise` rendered `[object Promise]`. Whether any of those is
|
|
1512
|
+
* a *sensible* thing to interpolate is beside the point — the two sides disagreeing is a silent
|
|
1513
|
+
* hydration mismatch, and matching junk is worth more than differing junk.
|
|
1514
|
+
*
|
|
1515
|
+
* A DOM node is the one exception, and it cannot occur: the server has no document to have
|
|
1516
|
+
* built one.
|
|
1517
|
+
*/
|
|
1518
|
+
}
|
|
1519
|
+
/** `raw` cannot be true here — it returned at the top of the function. */
|
|
1520
|
+
return escapeHtml(value);
|
|
1521
|
+
};
|