@verajs/ssr 0.3.0 → 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 CHANGED
@@ -479,6 +479,21 @@ markup itself is served byte for byte as it was written.
479
479
  repair it. `mode`, `delegatesFocus`, `clonable` and `serializable` are all serialized.
480
480
  - A function interpolated at a text position renders as nothing here and as its source on the
481
481
  client — put functions in `@event` bindings, where both sides drop them.
482
+ - **A hole right after a raw-text element's whole end-tag name (`<style>a</style${x}`) is refused here** as a
483
+ tag-name hole (as core's renderer refuses it in development), while `@verajs/lite`, `@verajs/static` and core in
484
+ production render it (the closer the value completes cannot end the element). Every shorter split (`</sty${x}`)
485
+ renders everywhere. Safe both ways; such CSS is rare.
486
+ - **A `@verajs/lite` component whose raw text holds something that only LOOKS like an end tag** (`<style>p{}</stylex>`,
487
+ `</style\v`) is refused on the server (`tier-hole-position`): lite parses its template with this DOM, which declines
488
+ markup it cannot reproduce exactly. Core's components serve it, written as every side writes a style's text
489
+ (`<\/stylex`). Safe; such text is rare.
490
+ - **A template in an HTML `<title>` or `<textarea>` is refused here** (`ssr-template-in-text`), while core's renderer
491
+ places it and warns in development that it is never shown there. Such a template is a mistake either way, and this
492
+ server cannot write elements a browser would keep there: it reads that content back as text. Render a string.
493
+ - **A value inside `<iframe>`, `<noscript>` or an obsolete raw-text element is served escaped as text**, while core's
494
+ renderer writes it fully encoded (every ASCII non-word character as a character reference), so the bytes differ and
495
+ hydration rewrites that text. Both are inert after a save and reload; a template inside a `<noscript>` is refused
496
+ here as one inside a text-only element is.
482
497
  - **What a render creates leaves every store when its render ends.** Its components are reactive DURING the render
483
498
  (a write in a setup or a router's first navigation re-renders before the markup is written), and nothing they read
484
499
  keeps them alive afterwards. Module-scope state — a store, a `computed` — belongs to the process and stays live; a
@@ -15,13 +15,17 @@ export const PROSE = {
15
15
  `<${tag}> refused the bound property \`.${name}\` — its setter threw ${thrown}.`,
16
16
  "The binding's value is the argument it was given; the setter's own error is this one's cause.",
17
17
  ],
18
+ 'ssr-script-hole': () => [
19
+ 'a value in a <script> is code — on a served page it runs — so a script hole is refused, except in a JSON data block (its type ends in `json`, with no character reference).',
20
+ 'Give the script a JSON type (`type="application/json"` or `application/ld+json`) for state or JSON-LD, or pass the value another way.',
21
+ ],
18
22
  'ssr-unfinished-tag': () => [
19
23
  'a template cannot end inside a tag — the client drops an unfinished tag.',
20
24
  'Close the tag inside the template.',
21
25
  ],
22
26
  'ssr-template-in-text': () => [
23
- 'a template cannot render inside a text-only element (`<textarea>`, `<title>`…) — its content is text.',
24
- 'Render a string there.',
27
+ 'a template cannot render inside a text-only element (`<style>`, a JSON `<script>`, `<title>`, `<textarea>`, or never-shown content: `<noscript>`, `<iframe>`) — its content is text.',
28
+ 'Render a string there; a list of strings is joined.',
25
29
  ],
26
30
  'ssr-nesting-depth': (max) => [
27
31
  `component nesting exceeded ${max} levels. A component that renders itself recurses without bound, and on a server that is a hung request — so this refuses rather than waiting for the stack to go.`,
@@ -95,8 +95,21 @@ export declare const SCRIPT_URL: RegExp;
95
95
  export declare const URL_SINK: RegExp;
96
96
  /** `SCRIPT_URL` at the start of any `;`-separated item — an animation's `values` list — the twin of `SCRIPT_URL_ITEM` there. */
97
97
  export declare const SCRIPT_URL_ITEM: RegExp;
98
+ /**
99
+ * A raw-text element's composed text, unable to end its element: the twin of shared-utils' `closedRawText`, held
100
+ * equal by a test (the renderer writes a style's or JSON block's text with it; the compiled statics here, below).
101
+ */
102
+ export declare const closedRawText: (text: string, json: boolean) => string;
98
103
  /** A bound inline event-handler attribute runs its value as code — the twin of `INLINE_HANDLER` there. */
99
104
  export declare const INLINE_HANDLER: RegExp;
105
+ /** A script `type` that names a JSON data block — the twin of `JSON_BLOCK` in `@verajs/shared-utils`. */
106
+ export declare const JSON_BLOCK: RegExp;
107
+ /**
108
+ * Whether a script START TAG, as written, opens a JSON data block — the twin of `dataBlock` in `@verajs/shared-utils`
109
+ * (held equal by `tests/script-data-blocks.test.mjs`): the first `type`, read in attribute order, holding no `&` and
110
+ * ending in `json`. The only script a bound value may enter on the server (`ssr-script-hole`).
111
+ */
112
+ export declare const dataBlock: (openTag: string) => boolean;
100
113
  /**
101
114
  * **A numeric reference's character, exactly as a parser decodes it** — the one decoder every reader here uses: NUL, a
102
115
  * surrogate or an out-of-range value is U+FFFD, and 0x80–0x9F map through `C1`. `String.fromCodePoint` THROWS past
@@ -95,6 +95,12 @@ export const escapeStyleText = (value) => `${value}`.replace(/<\/(style)/gi, '<\
95
95
  */
96
96
  const RAW_TEXT_CLOSERS = { style: /<\/(style)/gi, script: /<\/(script)/gi };
97
97
  export const escapeRawText = (value, tag) => {
98
+ /**
99
+ * A JSON data block's value (`dataBlock`, `serializer.ts`): `<` as `\u003c`, lossless in JSON — it ends no element
100
+ * and opens no escaped-script state (`<!--<script>` in a script's text swallows the rest of the page: BROWSER-LEDGER).
101
+ */
102
+ if (tag === 'json')
103
+ return `${value}`.replace(/</g, '\\u003c');
98
104
  const closer = RAW_TEXT_CLOSERS[tag];
99
105
  return closer ? `${value}`.replace(closer, '<\\/$1') : escapeHtml(value);
100
106
  };
@@ -177,8 +183,28 @@ export const URL_SINK = /^(?:(href|src|action|formaction|xlink:href|data)|to|fro
177
183
  /** `SCRIPT_URL` at the start of any `;`-separated item — an animation's `values` list — the twin of `SCRIPT_URL_ITEM` there. */
178
184
  // eslint-disable-next-line no-control-regex
179
185
  export const SCRIPT_URL_ITEM = /(?:^|;)[\u0000- ]*j[\t\n\r]*a[\t\n\r]*v[\t\n\r]*a[\t\n\r]*s[\t\n\r]*c[\t\n\r]*r[\t\n\r]*i[\t\n\r]*p[\t\n\r]*t[\t\n\r]*:/i;
186
+ /**
187
+ * A raw-text element's composed text, unable to end its element: the twin of shared-utils' `closedRawText`, held
188
+ * equal by a test (the renderer writes a style's or JSON block's text with it; the compiled statics here, below).
189
+ */
190
+ export const closedRawText = (text, json) => json ? text.replace(/</g, '\\u003c') : text.replace(/<\/(style)/gi, '<\\/$1');
180
191
  /** A bound inline event-handler attribute runs its value as code — the twin of `INLINE_HANDLER` there. */
181
192
  export const INLINE_HANDLER = /^on./i;
193
+ /** A script `type` that names a JSON data block — the twin of `JSON_BLOCK` in `@verajs/shared-utils`. */
194
+ export const JSON_BLOCK = /json\s*$/i;
195
+ /**
196
+ * Whether a script START TAG, as written, opens a JSON data block — the twin of `dataBlock` in `@verajs/shared-utils`
197
+ * (held equal by `tests/script-data-blocks.test.mjs`): the first `type`, read in attribute order, holding no `&` and
198
+ * ending in `json`. The only script a bound value may enter on the server (`ssr-script-hole`).
199
+ */
200
+ export const dataBlock = (openTag) => {
201
+ for (const [, name, double, single, bare] of openTag.slice(7).matchAll(/[\s/]*([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g))
202
+ if (name.toLowerCase() === 'type') {
203
+ const type = double ?? single ?? bare ?? '';
204
+ return !type.includes('&') && JSON_BLOCK.test(type);
205
+ }
206
+ return false;
207
+ };
182
208
  /**
183
209
  * The character references that can spell part of a scheme, decoded — enough to give the verdict a
184
210
  * browser gives on an attribute's static text, without a full entity table. Numeric references (with
@@ -9,8 +9,8 @@
9
9
  * tripping over it.
10
10
  */
11
11
  import { interfaceFor } from './reflections.js';
12
- import { escapeHtml, escapeRawText, escapeStyleText, leadingNewline, normalizeNewlines, RAW_TEXT_ELEMENTS, RCDATA_ELEMENTS, VOID_ELEMENTS } from './escaping.js';
13
- import { decode, parseFragment } from './parse.js';
12
+ import { JSON_BLOCK, escapeHtml, escapeRawText, escapeStyleText, leadingNewline, normalizeNewlines, RAW_TEXT_ELEMENTS, RCDATA_ELEMENTS, VOID_ELEMENTS } from './escaping.js';
13
+ import { contentSpace, decode, parseFragment } from './parse.js';
14
14
  import { addListener, removeListener, dispatch } from './events.js';
15
15
  import * as select from './select.js';
16
16
  import { datasetView, styleView, tokenListView } from './views.js';
@@ -87,7 +87,11 @@ const SHADOW_ATTRIBUTES = [
87
87
  */
88
88
  export const serializeElement = (element) => {
89
89
  const open = element.openTag();
90
- if (VOID_ELEMENTS.has(element.localName))
90
+ /**
91
+ * HTML's name-keyed rules are HTML's (2026-11-18): an SVG or MathML element named `link`, `img` or `pre` is an
92
+ * ordinary element, which keeps its children and its end tag. The namespace is read only for a name that matches.
93
+ */
94
+ if (VOID_ELEMENTS.has(element.localName) && element._ns === HTML_NS)
91
95
  return open;
92
96
  const inner = element.innerHTML;
93
97
  /**
@@ -97,7 +101,7 @@ export const serializeElement = (element) => {
97
101
  */
98
102
  const name = element.localName;
99
103
  /** Named, not hashed: this runs for every element written. */
100
- const guard = (name === 'pre' || name === 'textarea' || name === 'listing') && open.charCodeAt(open.length - 1) === 62 && leadingNewline(inner, 0) !== 0;
104
+ const guard = (name === 'pre' || name === 'textarea' || name === 'listing') && element._ns === HTML_NS && open.charCodeAt(open.length - 1) === 62 && leadingNewline(inner, 0) !== 0;
101
105
  const close = element._sourceCloseTag ?? `</${name}>`;
102
106
  /** Two plain joins: an empty string joined into every element cost a server DOM's serialization ~2% (measured). */
103
107
  return guard ? open + '\n' + inner + close : open + inner + close;
@@ -277,11 +281,12 @@ const parseChunks = (container) => {
277
281
  entries.push(entry);
278
282
  continue;
279
283
  }
284
+ /** Parsed in the space the container's content is in (an `<svg>`'s interior as SVG, 2026-11-18). */
280
285
  const parsed = parseFragment(entry, {
281
- element: (name) => build(name),
286
+ element: (name, namespaceURI) => build(name, namespaceURI),
282
287
  text: (data) => new TextShim(data),
283
288
  comment: (data) => new CommentShim(data),
284
- });
289
+ }, contentSpace(container));
285
290
  let round = '';
286
291
  if (parsed)
287
292
  for (const node of parsed)
@@ -555,9 +560,17 @@ export class TextShim extends CharacterDataShim {
555
560
  markup() {
556
561
  if (this._source !== null)
557
562
  return this._source;
558
- const parent = this._parent?.localName;
559
- /** Named, not looked up: a lookup keyed by every parent's name is a megamorphic load on every text node written. */
560
- return parent === 'style' || parent === 'script' ? escapeRawText(this._data, parent) : escapeHtml(this._data);
563
+ const parent = this._parent;
564
+ const name = parent?.localName;
565
+ /**
566
+ * Named, not looked up: a lookup keyed by every parent's name is a megamorphic load on every text node written. Raw
567
+ * text is HTML's alone (2026-11-18): an SVG or MathML `<style>`'s content is markup to a browser, so its text is
568
+ * escaped as text — raw-text escaping there let a value end the element and break out of it. A JSON data block's
569
+ * text keeps `<` out as `\u003c` (`escapeRawText`'s `json`): the static tier writes one here.
570
+ */
571
+ return (name === 'style' || name === 'script') && parent._ns === HTML_NS
572
+ ? escapeRawText(this._data, name === 'script' && JSON_BLOCK.test(parent.getAttribute('type') ?? '') ? 'json' : name)
573
+ : escapeHtml(this._data);
561
574
  }
562
575
  cloneNode() {
563
576
  const copy = new TextShim(this._data);
@@ -623,7 +636,7 @@ export class ContainerShim extends NodeBaseShim {
623
636
  * reading its own `innerHTML` got a different answer server-side. `localName` is undefined on
624
637
  * a fragment or shadow root, so the guard cannot fire off an element.
625
638
  */
626
- if (VOID_ELEMENTS.has(this.localName ?? ''))
639
+ if (VOID_ELEMENTS.has(this.localName ?? '') && this._ns === HTML_NS)
627
640
  return '';
628
641
  let out = '';
629
642
  for (const entry of this._entries)
@@ -647,7 +660,8 @@ export class ContainerShim extends NodeBaseShim {
647
660
  * is stored as one — and written by the text node's rule (`TextShim.markup`), never as given.
648
661
  */
649
662
  const name = this.localName ?? '';
650
- if (RAW_TEXT_ELEMENTS.has(name)) {
663
+ /** HTML's alone (2026-11-18): an SVG or MathML element of a raw-text name parses its markup. */
664
+ if (RAW_TEXT_ELEMENTS.has(name) && this._ns === HTML_NS) {
651
665
  const data = normalizeNewlines(text);
652
666
  this._replaceWithText(RCDATA_ELEMENTS.has(name) ? decode(data) : data);
653
667
  return;
@@ -2210,7 +2224,10 @@ export class ElementShim extends ContainerShim {
2210
2224
  */
2211
2225
  set textContent(value) {
2212
2226
  const text = value == null ? '' : value;
2213
- if (RAW_TEXT_ELEMENTS.has(this.localName))
2227
+ // HTML's alone, as the class's other rules (2026-11-18). Not independently observable: an SVG <style>'s text written
2228
+ // either way serializes the same once TextShim.markup escapes it as text, so this keeps one consistent rule and is
2229
+ // not a tested barrier of its own (tests/ssr-foreign-names.test.mjs).
2230
+ if (RAW_TEXT_ELEMENTS.has(this.localName) && this._ns === HTML_NS)
2214
2231
  this._replaceWithText(`${text}`);
2215
2232
  else
2216
2233
  this.innerHTML = escapeHtml(text);
@@ -7,6 +7,22 @@ import type { CommentShim, ElementShim, TextShim } from './nodes.js';
7
7
  * silently outrun what it can decode (arc-2 run 3).
8
8
  */
9
9
  export declare const decode: (text: string) => string;
10
+ export declare const SVG_NS = "http://www.w3.org/2000/svg";
11
+ export declare const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
12
+ /**
13
+ * **Which rules a chunk of markup is parsed under** (2026-11-18): HTML's; SVG's or MathML's (foreign content); or HTML's
14
+ * inside a MathML TEXT integration point (`<mi>`, `<mo>`, `<mn>`, `<ms>`, `<mtext>`), where `<mglyph>` and
15
+ * `<malignmark>` would be MathML and are declined. ONE namespace per parse: `<svg>` and `<math>` in HTML, and every
16
+ * integration point in foreign content, stay opaque boundaries, and their interior is parsed in its own namespace when
17
+ * a node view of it is asked for (`nodes.ts`'s `parseChunks`, with `contentSpace`).
18
+ */
19
+ export type Space = 'html' | 'svg' | 'math' | 'math-text';
20
+ /** The space an element's CONTENT is parsed in — what an interior kept opaque under it is read as. */
21
+ export declare const contentSpace: (element: {
22
+ readonly localName: string;
23
+ readonly namespaceURI: string | null;
24
+ getAttribute(name: string): string | null;
25
+ }) => Space;
10
26
  /**
11
27
  * **The attribute-name charset, owned here and shared.** Everything a start tag can carry as a
12
28
  * name: anything that is not whitespace, `/`, `>`, `=`, a quote, or `<`. Deliberately WIDE — every
@@ -22,7 +38,7 @@ export declare const decode: (text: string) => string;
22
38
  export declare const ATTRIBUTE_NAME = "[^\\s/>=\"'<]+";
23
39
  /** The node factories `parseFragment` builds with; the caller owns node identity, so this file never imports the DOM it builds. */
24
40
  type NodeFactories = {
25
- readonly element: (name: string) => ElementShim;
41
+ readonly element: (name: string, namespaceURI?: string) => ElementShim;
26
42
  readonly text: (data: string) => TextShim;
27
43
  readonly comment: (data: string) => CommentShim;
28
44
  };
@@ -33,5 +49,5 @@ type NodeFactories = {
33
49
  * @param create node factories; the caller owns node identity, so this file never imports the DOM it builds
34
50
  * @returns entries, or `null` when the markup needs more than this will guess at
35
51
  */
36
- export declare const parseFragment: (markup: string, create: NodeFactories) => Array<ElementShim | TextShim | CommentShim | string> | null;
52
+ export declare const parseFragment: (markup: string, create: NodeFactories, space?: Space) => Array<ElementShim | TextShim | CommentShim | string> | null;
37
53
  export {};
@@ -109,6 +109,58 @@ const FOREIGN = new Set(['svg', 'math']);
109
109
  * .querySelector`), which is a far smaller loss than the whole tree.
110
110
  */
111
111
  const OPAQUE = new Set([...FOREIGN, 'template']);
112
+ export const SVG_NS = 'http://www.w3.org/2000/svg';
113
+ export const MATHML_NS = 'http://www.w3.org/1998/Math/MathML';
114
+ /** MathML's text integration points: their content is HTML. */
115
+ const MATH_TEXT = new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
116
+ /** The space an element's CONTENT is parsed in — what an interior kept opaque under it is read as. */
117
+ export const contentSpace = (element) => {
118
+ const name = element.localName;
119
+ if (element.namespaceURI === SVG_NS)
120
+ return name === 'foreignObject' || name === 'desc' || name === 'title' ? 'html' : 'svg';
121
+ if (element.namespaceURI !== MATHML_NS)
122
+ return 'html';
123
+ if (MATH_TEXT.has(name))
124
+ return 'math-text';
125
+ return name === 'annotation-xml' && htmlEncoded(element.getAttribute('encoding')) ? 'html' : 'math';
126
+ };
127
+ /** An `<annotation-xml>` whose `encoding` makes its content HTML (an HTML integration point). */
128
+ const htmlEncoded = (encoding) => {
129
+ const value = encoding?.toLowerCase();
130
+ return value === 'text/html' || value === 'application/xhtml+xml';
131
+ };
132
+ /**
133
+ * **Start tags that BREAK OUT of foreign content** (the spec's list, "in foreign content"; `<font>` with `color`, `face`
134
+ * or `size` too, and the end tags `</br>` and `</p>`): a real parser pops out of the `<svg>` or `<math>` and continues in
135
+ * HTML, which this parser does not reproduce — so it declines them, and the markup stays a string.
136
+ */
137
+ const BREAKOUT = new Set([
138
+ 'b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4',
139
+ 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small',
140
+ 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var',
141
+ ]);
142
+ /** SVG's mixed-case element names, as the parser adjusts them (the spec's table, keyed lower case). */
143
+ const SVG_TAGS = new Map(['altGlyph', 'altGlyphDef', 'altGlyphItem', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'feBlend',
144
+ 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
145
+ 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage',
146
+ 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
147
+ 'feTurbulence', 'foreignObject', 'glyphRef', 'linearGradient', 'radialGradient', 'textPath'].map((name) => [name.toLowerCase(), name]));
148
+ /** SVG's mixed-case attribute names, as the parser adjusts them (the spec's table, keyed lower case). */
149
+ const SVG_ATTRIBUTES = new Map(['attributeName', 'attributeType', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'diffuseConstant',
150
+ 'edgeMode', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength',
151
+ 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits',
152
+ 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform',
153
+ 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits',
154
+ 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant',
155
+ 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'surfaceScale', 'systemLanguage',
156
+ 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector',
157
+ 'zoomAndPan'].map((name) => [name.toLowerCase(), name]));
158
+ /**
159
+ * An attribute name as the parser stores it on an element in `namespace`: SVG's and MathML's adjusted case. A prefixed
160
+ * name (`xlink:href`, `xmlns:xlink`) keeps its qualified name; its NAMESPACE is not modeled (`getAttributeNS` and an
161
+ * attribute's `namespaceURI` differ from a browser's) — what a selector, `getAttribute` and serialization see agree.
162
+ */
163
+ const adjustAttribute = (name, namespace) => namespace === SVG_NS ? (SVG_ATTRIBUTES.get(name) ?? name) : namespace === MATHML_NS && name === 'definitionurl' ? 'definitionURL' : name;
112
164
  const TAG_NAME = /^[a-zA-Z][^\s/>]*/;
113
165
  /**
114
166
  * **The attribute-name charset, owned here and shared.** Everything a start tag can carry as a
@@ -131,9 +183,12 @@ const ATTRIBUTE = new RegExp(`^(${ATTRIBUTE_NAME})(?:\\s*=\\s*(?:"([^"]*)"|'([^'
131
183
  * @param create node factories; the caller owns node identity, so this file never imports the DOM it builds
132
184
  * @returns entries, or `null` when the markup needs more than this will guess at
133
185
  */
134
- export const parseFragment = (markup, create) => {
186
+ export const parseFragment = (markup, create, space = 'html') => {
135
187
  if (typeof markup !== 'string' || markup === '')
136
188
  return null;
189
+ /** Foreign content: `/>` closes, names are case-adjusted, nothing is raw text, nothing closes implicitly. */
190
+ const foreign = space === 'svg' || space === 'math';
191
+ const namespace = space === 'svg' ? SVG_NS : space === 'math' ? MATHML_NS : undefined;
137
192
  const root = { children: [], localName: '#root' };
138
193
  const stack = [root];
139
194
  const open = () => stack[stack.length - 1];
@@ -173,6 +228,9 @@ export const parseFragment = (markup, create) => {
173
228
  continue;
174
229
  }
175
230
  if (markup.startsWith('<!', next)) {
231
+ /** In foreign content `<![CDATA[` is a text section, and the rest is error recovery: declined. */
232
+ if (foreign)
233
+ return null;
176
234
  const end = markup.indexOf('>', next);
177
235
  if (end === -1)
178
236
  return null;
@@ -189,6 +247,18 @@ export const parseFragment = (markup, create) => {
189
247
  if (!name)
190
248
  return null;
191
249
  flushText();
250
+ /**
251
+ * Foreign content closes only the open element, by name (any case), and `</br>` and `</p>` break out of it: anything
252
+ * else is error recovery, declined.
253
+ */
254
+ if (foreign) {
255
+ if (name === 'br' || name === 'p' || stack.length === 1 || open().localName.toLowerCase() !== name)
256
+ return null;
257
+ open().closeTag = markup.slice(next, end + 1);
258
+ stack.pop();
259
+ index = end + 1;
260
+ continue;
261
+ }
192
262
  /** Close through anything the spec would have closed implicitly; anything else is recovery. */
193
263
  let depth = stack.length - 1;
194
264
  while (depth > 0 && stack[depth].localName !== name) {
@@ -215,6 +285,17 @@ export const parseFragment = (markup, create) => {
215
285
  const name = nameMatch[0].toLowerCase();
216
286
  if (REFUSED.has(name))
217
287
  return null;
288
+ /** A start tag that leaves foreign content, or a MathML element inside a MathML text integration point: declined. */
289
+ if (foreign ? BREAKOUT.has(name) || name === 'font' : space === 'math-text' && (name === 'mglyph' || name === 'malignmark'))
290
+ return null;
291
+ /**
292
+ * The element's namespace: the foreign content's; `<svg>` and `<math>` open theirs in HTML; and an `<svg>` directly
293
+ * inside MathML's `<annotation-xml>` is SVG (the spec's one exception).
294
+ */
295
+ const elementNamespace = foreign && !(space === 'math' && name === 'svg' && open().localName === 'annotation-xml') ? namespace
296
+ : name === 'svg' ? SVG_NS
297
+ : name === 'math' ? MATHML_NS
298
+ : undefined;
218
299
  let cursor = next + 1 + nameMatch[0].length;
219
300
  const attributes = [];
220
301
  for (;;) {
@@ -230,7 +311,8 @@ export const parseFragment = (markup, create) => {
230
311
  if (!attribute || cursor >= markup.length)
231
312
  return null;
232
313
  const value = attribute[2] ?? attribute[3] ?? attribute[4] ?? '';
233
- attributes.push([attribute[1].toLowerCase(), decode(normalized(value))]);
314
+ const lower = attribute[1].toLowerCase();
315
+ attributes.push([elementNamespace === undefined ? lower : adjustAttribute(lower, elementNamespace), decode(normalized(value))]);
234
316
  cursor += attribute[0].length;
235
317
  }
236
318
  const selfClosing = markup.startsWith('/>', cursor);
@@ -239,8 +321,8 @@ export const parseFragment = (markup, create) => {
239
321
  return null;
240
322
  const openTag = markup.slice(next, end + 1);
241
323
  flushText();
242
- /** The implied end tags, before this element joins the stack. */
243
- for (;;) {
324
+ /** The implied end tags, before this element joins the stack (HTML's rule: foreign content has none). */
325
+ for (; !foreign;) {
244
326
  const current = open().localName;
245
327
  const closes = CLOSED_BY[name]?.has(current) || (current === 'p' && CLOSES_P.has(name));
246
328
  if (!closes || stack.length === 1)
@@ -253,7 +335,7 @@ export const parseFragment = (markup, create) => {
253
335
  * tag) and agree with a real parser about the tree (which requires it). Markup that writes the
254
336
  * section itself parses normally, so the common explicit form is unaffected.
255
337
  */
256
- if ((name === 'tr' || name === 'td' || name === 'th') && open().localName === 'table')
338
+ if (!foreign && (name === 'tr' || name === 'td' || name === 'th') && open().localName === 'table')
257
339
  return null;
258
340
  /**
259
341
  * **A name the DOM rejects is a DECLINE, never a throw.** `TAG_NAME` is deliberately loose
@@ -266,7 +348,7 @@ export const parseFragment = (markup, create) => {
266
348
  */
267
349
  let element;
268
350
  try {
269
- element = create.element(name);
351
+ element = elementNamespace === undefined ? create.element(name) : create.element(elementNamespace === SVG_NS ? (SVG_TAGS.get(name) ?? name) : name, elementNamespace);
270
352
  }
271
353
  catch {
272
354
  return null;
@@ -289,7 +371,7 @@ export const parseFragment = (markup, create) => {
289
371
  * text node's. It stays in the bytes as part of the source tag — which is how `serializeElement` knows the markup
290
372
  * already carries one and adds none.
291
373
  */
292
- if (NEWLINE_TAKERS.has(name)) {
374
+ if (!foreign && NEWLINE_TAKERS.has(name)) {
293
375
  const taken = leadingNewline(markup, index);
294
376
  if (taken !== 0) {
295
377
  element._sourceOpenTag += markup.slice(index, index + taken);
@@ -297,19 +379,32 @@ export const parseFragment = (markup, create) => {
297
379
  }
298
380
  }
299
381
  /** A void element never has children and never has an end tag. */
300
- if (VOID_ELEMENTS.has(name))
382
+ if (!foreign && VOID_ELEMENTS.has(name))
301
383
  continue;
302
384
  /**
303
385
  * `<div/>` is **not** self-closing in HTML — the slash is ignored and the element stays open.
304
- * Treating it as closed is a common and quiet way to build the wrong tree, so it declines.
386
+ * Treating it as closed is a common and quiet way to build the wrong tree, so it declines. In foreign content it IS
387
+ * self-closing (2026-11-18): the element is closed, with no end tag to write back.
305
388
  */
306
- if (selfClosing)
389
+ if (selfClosing) {
390
+ if (foreign)
391
+ continue;
307
392
  return null;
393
+ }
394
+ /**
395
+ * An opaque boundary: in HTML, `<svg>`, `<math>` and `<template>`; in foreign content, an integration point (its
396
+ * content is HTML: `contentSpace`) and the SVG an `<annotation-xml>` opens.
397
+ */
398
+ const opaque = foreign
399
+ ? elementNamespace !== namespace ||
400
+ (space === 'svg' ? name === 'foreignobject' || name === 'desc' || name === 'title'
401
+ : MATH_TEXT.has(name) || (name === 'annotation-xml' && htmlEncoded(attributes.find(([n]) => n === 'encoding')?.[1])))
402
+ : OPAQUE.has(name);
308
403
  /**
309
- * Foreign content runs to its matching end tag and is kept verbatim, nesting counted so an
404
+ * An opaque interior runs to its matching end tag and is kept verbatim, nesting counted so an
310
405
  * `<svg>` inside an `<svg>` closes the right one.
311
406
  */
312
- if (OPAQUE.has(name)) {
407
+ if (opaque) {
313
408
  let depth = 1;
314
409
  let closeAt = -1;
315
410
  const opener = new RegExp(`<(/?)${name}\\b`, 'giu');
@@ -333,8 +428,8 @@ export const parseFragment = (markup, create) => {
333
428
  index = closeEnd + 1;
334
429
  continue;
335
430
  }
336
- /** Raw text runs to its own end tag and is never parsed as markup. */
337
- if (RAW_TEXT_ELEMENTS.has(name)) {
431
+ /** Raw text runs to its own end tag and is never parsed as markup (HTML's rule: foreign content has none). */
432
+ if (!foreign && RAW_TEXT_ELEMENTS.has(name)) {
338
433
  const close = markup.toLowerCase().indexOf(`</${name}`, index);
339
434
  if (close === -1)
340
435
  return null;
@@ -359,7 +454,7 @@ export const parseFragment = (markup, create) => {
359
454
  * What is still open at the end is fine if the spec would have closed it implicitly, and is error
360
455
  * recovery otherwise — an unclosed `<div>` is a mistake this parser will not guess about.
361
456
  */
362
- while (stack.length > 1 && OPTIONAL_END_TAG.has(open().localName))
457
+ while (!foreign && stack.length > 1 && OPTIONAL_END_TAG.has(open().localName))
363
458
  stack.pop();
364
459
  if (stack.length !== 1)
365
460
  return null;
@@ -1,5 +1,5 @@
1
1
  import { escapeHtml, escapeRawText } from './shim.js';
2
- import { INLINE_HANDLER, NEWLINE_TAKERS, SCRIPT_URL, SCRIPT_URL_ITEM, URL_SINK, decodeCodePoint, decodeSchemeReferences, thrownMessage } from './escaping.js';
2
+ import { INLINE_HANDLER, NEWLINE_TAKERS, SCRIPT_URL, SCRIPT_URL_ITEM, URL_SINK, closedRawText, dataBlock, decodeCodePoint, decodeSchemeReferences, thrownMessage } from './escaping.js';
3
3
  import { registry } from './registry.js';
4
4
  import { PROSE, TWINS } from './diagnostics.js';
5
5
  import { once, own, quoted, ssrMisuse, ssrWarning } from './report.js';
@@ -197,6 +197,35 @@ const takesNewline = (text, before) => {
197
197
  const at = scanTag(text.slice(0, -1), { ...before, opens: before.opens.slice() });
198
198
  return (at.inTag && !at.closing && !(at.inValue && at.quote !== '') && at.comment === '' && NEWLINE_TAKERS.has(at.tagName));
199
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
+ };
200
229
  const compile = (strings, depth) => {
201
230
  /**
202
231
  * **A template is a tagged template literal's, never data shaped like one.** Template detection is by shape (`strings`),
@@ -231,6 +260,11 @@ const compile = (strings, depth) => {
231
260
  const owners = [];
232
261
  /** Which RAWTEXT element each binding sits inside, `''` when none. See `RAWTEXT`. */
233
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 = [];
234
268
  /** Per child binding (sparse): the foreign-content depth it sits at, which a template rendered there starts from. */
235
269
  const depths = [];
236
270
  /** Per child binding (sparse): whether it sits in a text-only element, where a template is refused (see `serializeValue`). */
@@ -306,8 +340,15 @@ const compile = (strings, depth) => {
306
340
  taker = takesNewline(text, tagState);
307
341
  }
308
342
  tagState = scanTag(strings[i], tagState);
343
+ rawBounds[i] = [tagState.rawFrom, tagState.rawUntil];
309
344
  if (taker && (tagState.foreign !== 0 || tagState.inert !== 0))
310
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']())));
311
352
  /**
312
353
  * **Every question about where this hole sits is answered by that scan** — whether it is inside a tag, which tag,
313
354
  * whether a new one opened, and whether the hole is a sigil binding. They used to be answered beside it, by tests
@@ -515,7 +556,13 @@ const compile = (strings, depth) => {
515
556
  parts.push(tagState.comment !== '' && !inert ? part + ' ' : taker ? part + '\n' : part);
516
557
  if (tagState.foreign)
517
558
  depths[kinds.length] = tagState.foreign;
518
- if (tagState.textTag)
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'))
519
566
  texts[kinds.length] = true;
520
567
  /** A binding inside a comment is dropped, as the client drops it — never written into the comment. */
521
568
  kinds.push(inert || tagState.comment ? DROPPED : TEXT);
@@ -579,11 +626,51 @@ const compile = (strings, depth) => {
579
626
  * that never started a tag name, as in `a < b`, is text. The client refuses the same templates in development.
580
627
  */
581
628
  const end = scanTag(strings[strings.length - 1], tagState);
629
+ rawBounds[strings.length - 1] = [end.rawFrom, end.rawUntil];
582
630
  if (end.inValue || (end.inTag && end.tagName))
583
631
  throw own(new Error(ssrMisuse('ssr-unfinished-tag', PROSE['ssr-unfinished-tag']())));
584
632
  const closers = closersOf(end);
585
633
  if (closers)
586
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
+ }
587
674
  /**
588
675
  * Dense, so the render loop reads a value at every binding: both are filled sparsely above, and a hole read falls
589
676
  * through to the prototype chain on every child binding of every render — measured at about 3% of a server render.
@@ -737,8 +824,10 @@ export const serializeTemplate = (template, depth = 0) => {
737
824
  * `<title>` and `<textarea>` are RCDATA, not RAWTEXT — references *are* decoded there — so
738
825
  * they keep ordinary escaping, which is what the client produces for them too.
739
826
  */
827
+ else if (raws[i] === 'style')
828
+ out = styleHole(out, escapeRawText(rawTextOf(value), 'style'), part, parts[i + 1]);
740
829
  else if (raws[i])
741
- out += escapeRawText(serializeValue(value, true), raws[i]);
830
+ out += escapeRawText(rawTextOf(value), raws[i]);
742
831
  else
743
832
  out += serializeValue(value, false, depths[i], texts[i]);
744
833
  break;
@@ -1027,6 +1116,47 @@ const fortify = (markup, depth) => {
1027
1116
  }
1028
1117
  return out + markup.slice(from, stop) + tail + closersOf(end);
1029
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
+ };
1030
1160
  /**
1031
1161
  * The content a `.innerHTML`/`.textContent` binding writes after the host's open tag. `innerHTML` is
1032
1162
  * `[LegacyNullToEmptyString]` (so `null` is `''` but `undefined` is `"undefined"`); `textContent` is nullable (both
@@ -1250,6 +1380,25 @@ owner, entries, deliverProp) => {
1250
1380
  const refuseTemplateInText = () => {
1251
1381
  throw own(new Error(ssrMisuse('ssr-template-in-text', PROSE['ssr-template-in-text']())));
1252
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
+ };
1253
1402
  /**
1254
1403
  * **A child value that applies itself (`_$child$`) renders on a server what it would show FIRST on a client** (2026-10-26,
1255
1404
  * found by `@verajs/renderer/until`'s server row: every such value served `[object Object]`). The applier runs against a
@@ -28,8 +28,8 @@ const RAWTEXT = new Set(['style', 'script']);
28
28
  * saw open at foreign depth 0, and every other doubt resolves to escaping. Reading raw text as markup over-escapes —
29
29
  * a visible difference, never an injection; reading markup as raw text writes a value's `<img onerror>` into the
30
30
  * page. So the set has to hold everything the parser treats as raw: the first three are the client's `RAW_TEXT_TAGS`;
31
- * `xmp`, `noembed`, `noframes` and `plaintext` are obsolete and the client does not list them, but the browser
32
- * still parses them as raw text — without them, `<xmp><style>${x}</style></xmp>` wrote `x` raw inside what the
31
+ * `xmp`, `noembed`, `noframes` and `plaintext` are obsolete (the client's scanner lists them too since 2026-11-19, as
32
+ * never-shown content), and the browser still parses them as raw text — without them, `<xmp><style>${x}</style></xmp>` wrote `x` raw inside what the
33
33
  * browser reads as one run of text, and `</xmp>` in the value closed it. `plaintext` never closes at all; ending it
34
34
  * at `</plaintext` here only ever resumes escaping too early, which writes `<style>` content raw into text the
35
35
  * browser shows verbatim — still text.
@@ -139,6 +139,12 @@ export const scanTag = (text, state, edits, tags) => {
139
139
  /** Where the attribute name being read began in THIS text — `-1` when it began in an earlier one. */
140
140
  let nameFrom = -1;
141
141
  let tagAt = -1;
142
+ /**
143
+ * Where, in THIS text, raw content last BEGAN (after its element's start tag) and first ENDED (its end tag's `<`) —
144
+ * `-1` for none: the bounds of a raw element's content inside the static around a hole (`compile`, a JSON block).
145
+ */
146
+ let rawFrom = -1;
147
+ let rawUntil = -1;
142
148
  let selfClosing = false;
143
149
  /** Where the value that opened in THIS text starts — `-1` when none did — so an `encoding` can be read whole. */
144
150
  let valueFrom = -1;
@@ -161,6 +167,8 @@ export const scanTag = (text, state, edits, tags) => {
161
167
  i = at + 1;
162
168
  continue;
163
169
  }
170
+ if (rawTag !== '' && rawUntil === -1)
171
+ rawUntil = at;
164
172
  rawTag = '';
165
173
  textTag = '';
166
174
  phase = TAG_NAME;
@@ -472,7 +480,13 @@ export const scanTag = (text, state, edits, tags) => {
472
480
  opens.push({ name: tagName, foreign, inert, space: own ? tagName : space });
473
481
  foreign++;
474
482
  }
475
- else if (tagName === 'noscript') {
483
+ else if (tagName === 'noscript' && space !== 'svg' && space !== 'math') {
484
+ /**
485
+ * Only where HTML rules read the tag (2026-11-19, a rotated-seed find): inside `<svg>`/`<math>` proper a
486
+ * `<noscript>` is a foreign element like any (raw text exists only for HTML elements), so it is not tracked and a
487
+ * breakout after it (`<svg><noscript><p>`) pops it with the foreign content, as the parser does. At an
488
+ * integration point `space` is HTML, so it is tracked there — an HTML `<noscript>`, as `<template>` below.
489
+ */
476
490
  opens.push({ name: tagName, foreign, inert, space: '' });
477
491
  foreign++;
478
492
  }
@@ -494,8 +508,19 @@ export const scanTag = (text, state, edits, tags) => {
494
508
  opens.push({ name: tagName, foreign, inert, space: 'math' });
495
509
  foreign = 1;
496
510
  }
497
- else if (foreign === 0 && RAWTEXT.has(tagName))
511
+ else if ((space === 'svg' || space === 'math') && tagName === 'script') {
512
+ /**
513
+ * A `<script>` in SVG (or a MathML element of that name) is tracked so a hole inside it is refused (see
514
+ * `compile`): its content is markup to the parser, so it is no raw text here, and an SVG script runs on a served
515
+ * page — and from a template, in Chromium and WebKit (BROWSER-LEDGER, 2026-11-18). An HTML `<script>` is raw text
516
+ * (`rawTag`, below) and never reaches `opens`, so every `script` there is a foreign one.
517
+ */
518
+ opens.push({ name: tagName, foreign, inert, space });
519
+ }
520
+ else if (foreign === 0 && RAWTEXT.has(tagName)) {
498
521
  rawTag = tagName;
522
+ rawFrom = i + 1;
523
+ }
499
524
  else if (foreign === 0 && TEXT_ONLY.has(tagName))
500
525
  textTag = tagName;
501
526
  }
@@ -507,7 +532,7 @@ export const scanTag = (text, state, edits, tags) => {
507
532
  /** A name still being read at the end carries on into the next text (a hole there is refused — see `nameHole`). */
508
533
  if (phase === ATTRIBUTE_NAME)
509
534
  attrRaw = nameFrom === -1 ? attrRaw + text : text.slice(nameFrom);
510
- return { inTag: phase !== OUTSIDE, phase, inValue, quote, rawTag, tagName, attrName, serial, closing, inert, comment, textTag, foreign, opens, attrRaw, encoding, opened, attrStart, valueStart, nameAt, tagAt };
535
+ return { inTag: phase !== OUTSIDE, phase, inValue, quote, rawTag, tagName, attrName, serial, closing, inert, comment, textTag, foreign, opens, attrRaw, encoding, opened, attrStart, valueStart, nameAt, tagAt, rawFrom, rawUntil };
511
536
  };
512
537
  /** The end-of-input closers a scan state owes: its open comment or raw-text or text-only element, then every element it opened that changes parsing (svg, math, noscript, template, an integration point), innermost first. Shared by `compile` and `fortify`. */
513
538
  export const closersOf = (end) => (end.comment || (end.rawTag ? `</${end.rawTag}>` : end.textTag ? `</${end.textTag}>` : '')) +
@@ -101,6 +101,10 @@ export interface ScanResult extends ScanState {
101
101
  readonly nameAt: number;
102
102
  /** Where, in THIS text, the tag still open at its end began — `-1` when it began in an earlier one, or none is. */
103
103
  readonly tagAt: number;
104
+ /** Where, in THIS text, raw content last began (after its element's start tag) — `-1` for none. */
105
+ readonly rawFrom: number;
106
+ /** Where, in THIS text, raw content first ended (its end tag's `<`) — `-1` for none. */
107
+ readonly rawUntil: number;
104
108
  }
105
109
  /**
106
110
  * A tag the component scan collects (`scanTag`'s `tags`): its span in the markup, its name as the tokenizer reads it,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verajs/ssr",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Vera-native server-side rendering. Node-only, plain ESM, zero dependencies.",
5
5
  "license": "MIT",
6
6
  "engines": {