Skip to content

Commit 56683ea

Browse files
authored
perf(compiler): write non-ASCII SSR template text as character references (#4331)
* perf(compiler): write non-ASCII SSR template text as character references One character above U+00FF in a static SSR template, such as the arrow in `<a>View →</a>`, made V8 store the whole rendered page as a two-byte string, which roughly doubled the cost of flattening it and encoding it to UTF-8. Both compilers now write those characters in static text and quoted attribute values as numeric character references, including the static attributes baked into a spread element's attribute string. Latin-1 characters stay literal, since they already fit a one-byte string and `&#128;` through `&#159;` decode to other characters. Tag internals, comments, raw-text bodies and the children of a spread `<script>` or `<style>` keep their characters, because browsers do not decode references there. Fixes #4328 * fix(compiler): keep spread raw-text element children and quotes raw Element children of a spread raw-text element such as `<xmp {...p}>` now keep their characters in the Rust compiler, matching Babel. In both compilers a quote opens an attribute value only after `=`, and `<plaintext>` is treated as raw text to the end of the template.
1 parent 17ec571 commit 56683ea

24 files changed

Lines changed: 788 additions & 39 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@solidjs/compiler": patch
3+
"@solidjs/babel-plugin": patch
4+
---
5+
6+
SSR templates write characters above U+00FF in static text and quoted attribute values as numeric character references (`→` becomes `&#8594;`), as do the static attributes baked into a spread element's attribute string. One character above U+00FF in a template made V8 store the whole rendered page as a two-byte string, which roughly doubled the cost of flattening and UTF-8 encoding the response (#4328). Latin-1 characters stay literal. Tag internals, comments, raw-text bodies such as `<script>` and `<style>`, and the children of a spread `<script>` or `<style>` keep their characters, since browsers do not decode references there. Client output is unchanged.

‎packages/babel-plugin/src/ssr/element.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,14 @@ import {
2525
} from "../shared/utils";
2626
import { transformNode, getCreateTemplate } from "../shared/transform";
2727
import { decodedAttrValue } from "../universal/element";
28-
import { createTemplate, linkAttrsKey, registerLinkAttrs, registerSkip } from "./template";
28+
import {
29+
asciiAttributeMarkup,
30+
createTemplate,
31+
rawTextElements,
32+
linkAttrsKey,
33+
registerLinkAttrs,
34+
registerSkip
35+
} from "./template";
2936
import { markPropsLiteral } from "./props";
3037
import type {
3138
BabelPath,
@@ -1084,6 +1091,7 @@ function createElement(
10841091
const allocatesIds = hydratable && canChildSlotAllocateIds(path);
10851092
const child = transformNode(path, { doNotEscape });
10861093
if (!child) return memo;
1094+
if (rawTextElements.has(tagName)) child.rawText = true;
10871095
if (markers && child.exprs.length && !child.spreadElement)
10881096
memo.push(t.stringLiteral("<!--$-->"));
10891097
if (child.exprs.length && !doNotEscape && !child.spreadElement)
@@ -1362,7 +1370,7 @@ function tailAttribute(
13621370
text = trimWhitespace(text);
13631371
if (key === "style") text = text.replace(/; /g, ";").replace(/: /g, ":");
13641372
}
1365-
return text === "" ? ` ${key}` : ` ${key}="${escapeHTML(text, true)}"`;
1373+
return text === "" ? ` ${key}` : asciiAttributeMarkup(` ${key}="${escapeHTML(text, true)}"`);
13661374
}
13671375
if (t.isJSXEmptyExpression(literal) || t.isJSXElement(literal) || t.isJSXFragment(literal))
13681376
return undefined;

‎packages/babel-plugin/src/ssr/template.ts‎

Lines changed: 131 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ export function createTemplate(
3434
}
3535

3636
let template, id;
37+
const raw = Array.isArray(result.template) ? result.template : [result.template as string];
38+
const parts = result.rawText ? raw : asciiTemplateParts(raw);
3739

38-
if (!Array.isArray(result.template)) {
39-
template = t.stringLiteral(result.template as string);
40-
} else if (result.template.length === 1) {
41-
template = t.stringLiteral(result.template[0]);
40+
if (parts.length === 1) {
41+
template = t.stringLiteral(parts[0]);
4242
} else {
43-
const strings = result.template.map((tmpl: string) => t.stringLiteral(tmpl));
43+
const strings = parts.map((tmpl: string) => t.stringLiteral(tmpl));
4444
template = t.arrayExpression(strings);
4545
}
4646

@@ -150,6 +150,132 @@ export function createTemplate(
150150
]);
151151
}
152152

153+
type AsciiState =
154+
| { kind: "text" }
155+
// Only a quote right after `=` opens a quoted value.
156+
| { kind: "tag"; raw?: string; value?: boolean }
157+
| { kind: "quoted"; quote: string; raw?: string }
158+
// Comments, CDATA and bogus comments, kept as written up to `end`.
159+
| { kind: "preserve"; end: string }
160+
// `<!--` in a script can start the double-escaped state, where `</script>` does not close it.
161+
| { kind: "raw"; close: string; escaped: boolean };
162+
163+
// Browsers do not decode references in raw-text bodies, so those keep their characters.
164+
export const rawTextElements = new Set([
165+
"script",
166+
"style",
167+
"noscript",
168+
"iframe",
169+
"noembed",
170+
"noframes",
171+
"xmp",
172+
// `<plaintext>` has no end tag.
173+
"plaintext"
174+
]);
175+
// Latin-1 already keeps a V8 string one-byte, and `&#128;`-`&#159;` decode to other characters.
176+
const nonLatin1 = /[^\x00-\xff]/;
177+
const preservedOpens: [string, string][] = [
178+
["<!--", "-->"],
179+
["<![CDATA[", "]]>"],
180+
["<!", ">"],
181+
["<?", ">"]
182+
];
183+
const tagName = /[^\t\n\f\r />]*/y;
184+
const endsTagName = (next: string | undefined) => next === undefined || /[\t\n\f\r />]/.test(next);
185+
186+
/** Characters above U+00FF outside tags, comments and raw text become `&#N;`, keeping SSR output one-byte in V8. */
187+
export function asciiTemplateParts(parts: string[]): string[] {
188+
return asciiParts(parts, { kind: "text" });
189+
}
190+
191+
/** `asciiTemplateParts` for a spread element's static attribute markup. */
192+
export function asciiAttributeMarkup(markup: string): string {
193+
return nonLatin1.test(markup) ? asciiParts([markup], { kind: "tag" })[0] : markup;
194+
}
195+
196+
// State carries across parts because holes can split a tag or a raw-text body.
197+
function asciiParts(parts: string[], state: AsciiState): string[] {
198+
if (!parts.some(part => nonLatin1.test(part))) return parts;
199+
return parts.map(part => {
200+
let out = "";
201+
let i = 0;
202+
while (i < part.length) {
203+
const ch = String.fromCodePoint(part.codePointAt(i)!);
204+
let len = ch.length;
205+
if (state.kind === "text") {
206+
const open = preservedOpens.find(([open]) => part.startsWith(open, i));
207+
if (open) {
208+
state = { kind: "preserve", end: open[1] };
209+
len = open[0].length;
210+
} else if (ch === "<") {
211+
const closing = part[i + 1] === "/";
212+
const start = i + (closing ? 2 : 1);
213+
if (/[a-z]/i.test(part[start] ?? "")) {
214+
tagName.lastIndex = start;
215+
const name = tagName.exec(part)![0].toLowerCase();
216+
state = {
217+
kind: "tag",
218+
raw:
219+
closing || !rawTextElements.has(name)
220+
? undefined
221+
: name === "plaintext"
222+
? ""
223+
: `</${name}`,
224+
value: false
225+
};
226+
} else if (closing) {
227+
state = { kind: "preserve", end: ">" };
228+
len = 2;
229+
}
230+
}
231+
out += len === ch.length ? toAscii(ch) : part.slice(i, i + len);
232+
} else if (state.kind === "tag") {
233+
if (state.value && (ch === '"' || ch === "'"))
234+
state = { kind: "quoted", quote: ch, raw: state.raw };
235+
else if (ch === ">")
236+
state =
237+
state.raw !== undefined
238+
? { kind: "raw", close: state.raw, escaped: false }
239+
: { kind: "text" };
240+
else
241+
state = {
242+
kind: "tag",
243+
raw: state.raw,
244+
value: ch === "=" || (!!state.value && /[\t\n\f\r ]/.test(ch))
245+
};
246+
out += ch;
247+
} else if (state.kind === "quoted") {
248+
if (ch === state.quote) state = { kind: "tag", raw: state.raw };
249+
out += toAscii(ch);
250+
} else if (state.kind === "preserve") {
251+
if (part.startsWith(state.end, i)) {
252+
len = state.end.length;
253+
state = { kind: "text" };
254+
}
255+
out += part.slice(i, i + len);
256+
} else {
257+
const end = i + state.close.length;
258+
if (state.close === "</script" && part.startsWith("<!--", i))
259+
state = { ...state, escaped: true };
260+
else if (
261+
!state.escaped &&
262+
state.close !== "" &&
263+
part.slice(i, end).toLowerCase() === state.close &&
264+
endsTagName(part[end])
265+
)
266+
state = { kind: "tag" };
267+
out += ch;
268+
}
269+
i += len;
270+
}
271+
return out;
272+
});
273+
}
274+
275+
function toAscii(ch: string): string {
276+
return ch.charCodeAt(0) <= 0xff ? ch : `&#${ch.codePointAt(0)};`;
277+
}
278+
153279
export function appendTemplates(path: NodePath<t.Program>, templates: TemplateRecord[]) {
154280
const declarators = templates.map(template => {
155281
return t.variableDeclarator(template.id, template.template as t.Expression);

‎packages/babel-plugin/src/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ export interface TransformResult {
102102
text?: boolean;
103103
dynamic?: boolean;
104104
wontEscape?: boolean;
105+
rawText?: boolean;
105106
tagName?: string;
106107
renderer?: RendererName;
107108
isImportNode?: boolean;

‎packages/babel-plugin/test/__ssr_fixtures__/textInterpolation/code.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,35 @@ const lastElementExpression = (
9595
);
9696

9797
const messwithTemplates = <p>{"${blah}"}</p>;
98+
99+
const nonAsciiText = (
100+
<p title="Next →">
101+
Next → <style>{'.a::after{content:"→"}'}</style>
102+
</p>
103+
);
104+
const nonAsciiSpreadTail = <a {...spread} title="Next →" data-static="é" />;
105+
const nonAsciiCustomElement = <style-guide>Next →</style-guide>;
106+
const nonAsciiSpreadStyle = <style {...spread}>{'.a::after{content:"→"}'}</style>;
107+
const nonAsciiScriptture = <script>{'x = "</scripture>→";'}</script>;
108+
const latin1AndC1 = <p title="café">{"café \u0080\u0091"}</p>;
109+
const nonAsciiSpreadXmp = <xmp {...spread}>{"→"}</xmp>;
110+
const nonAsciiEscapedScript = <script>{'h = "<!--<script></script>→";'}</script>;
111+
const nonAsciiCdata = (
112+
<svg>
113+
<text innerHTML={"<![CDATA[→]]>"} />
114+
</svg>
115+
);
116+
const nonAsciiSpreadXmpElement = (
117+
<xmp {...spread}>
118+
<span>→</span>
119+
</xmp>
120+
);
121+
const nonAsciiSpreadScriptElement = (
122+
<script {...spread}>
123+
<span>→</span>
124+
</script>
125+
);
126+
const nonAsciiUnquotedQuote = (
127+
<div innerHTML={`<style data-x=a'b>.a::after{content:"→"}</style>`} />
128+
);
129+
const nonAsciiPlaintext = <div innerHTML={"<plaintext><p>→</p>"} />;

‎packages/babel-plugin/test/__ssr_fixtures__/textInterpolation/output.js‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ssrElement as _$ssrElement } from "r-server";
12
import { escape as _$escape } from "r-server";
23
import { ssr as _$ssr } from "r-server";
34
var _tmpl$ = "<span>Hello </span>",
@@ -17,9 +18,21 @@ var _tmpl$ = "<span>Hello </span>",
1718
_tmpl$13 = ["<div>", "</div>"],
1819
_tmpl$14 = ["<span> ", "</span>"],
1920
_tmpl$15 = ["<span>", " </span>"],
20-
_tmpl$16 = '<div normal="Search\u2026" title="Search&amp;hellip;"></div>',
21+
_tmpl$16 = '<div normal="Search&#8230;" title="Search&amp;hellip;"></div>',
2122
_tmpl$17 = ["<div><div></div>", "</div>"],
22-
_tmpl$18 = "<p>${blah}</p>";
23+
_tmpl$18 = "<p>${blah}</p>",
24+
_tmpl$19 = '<p title="Next &#8594;">Next &#8594; <style>.a::after{content:"\u2192"}</style></p>',
25+
_tmpl$20 = "<style-guide>Next &#8594;</style-guide>",
26+
_tmpl$21 = '.a::after{content:"\u2192"}',
27+
_tmpl$22 = '<script>x = "</scripture>\u2192";</script>',
28+
_tmpl$23 = '<p title="caf\xE9">caf\xE9 \x80\x91</p>',
29+
_tmpl$24 = "\u2192",
30+
_tmpl$25 = '<script>h = "<!--<script></script>\u2192";</script>',
31+
_tmpl$26 = "<svg><text><![CDATA[\u2192]]></text></svg>",
32+
_tmpl$27 = "<span>\u2192</span>",
33+
_tmpl$28 = '<div><style data-x=a\'b>.a::after{content:"\u2192"}</style></div>',
34+
_tmpl$29 = "<div><plaintext><p>\u2192</p></div>";
35+
var _sk$ = k => k === "title" || k === "data-static";
2336
const trailing = _$ssr(_tmpl$);
2437
const leading = _$ssr(_tmpl$2);
2538

@@ -101,3 +114,23 @@ const escapeCompAttribute = Div({
101114
var _v$11 = () => _$escape(expr());
102115
const lastElementExpression = _$ssr(_tmpl$17, _v$11);
103116
const messwithTemplates = _$ssr(_tmpl$18);
117+
const nonAsciiText = _$ssr(_tmpl$19);
118+
const nonAsciiSpreadTail = _$ssrElement(
119+
"a",
120+
spread,
121+
undefined,
122+
false,
123+
_sk$,
124+
' title="Next &#8594;" data-static="\xE9"'
125+
);
126+
const nonAsciiCustomElement = _$ssr(_tmpl$20);
127+
const nonAsciiSpreadStyle = _$ssrElement("style", spread, _$ssr(_tmpl$21), false);
128+
const nonAsciiScriptture = _$ssr(_tmpl$22);
129+
const latin1AndC1 = _$ssr(_tmpl$23);
130+
const nonAsciiSpreadXmp = _$ssrElement("xmp", spread, _$ssr(_tmpl$24), false);
131+
const nonAsciiEscapedScript = _$ssr(_tmpl$25);
132+
const nonAsciiCdata = _$ssr(_tmpl$26);
133+
const nonAsciiSpreadXmpElement = _$ssrElement("xmp", spread, _$ssr(_tmpl$27), false);
134+
const nonAsciiSpreadScriptElement = _$ssrElement("script", spread, _$ssr(_tmpl$27), false);
135+
const nonAsciiUnquotedQuote = _$ssr(_tmpl$28);
136+
const nonAsciiPlaintext = _$ssr(_tmpl$29);

‎packages/babel-plugin/test/__ssr_hydratable_fixtures__/document/output.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ import { escape as _$escape } from "r-server";
33
import { ssrHydrationKey as _$ssrHydrationKey } from "r-server";
44
var _tmpl$ = [
55
"<html",
6-
'><head><title>\uD83D\uDD25 Blazing \uD83D\uDD25</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="/styles.css"><!--$-->',
6+
'><head><title>&#128293; Blazing &#128293;</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="/styles.css"><!--$-->',
77
"<!--/--></head><body><header><h1>Welcome to the Jungle</h1></header><!--$-->",
88
"<!--/--><footer>The Bottom</footer></body></html>"
99
],
1010
_tmpl$2 = [
1111
"<head",
12-
'><title>\uD83D\uDD25 Blazing \uD83D\uDD25</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="/styles.css"><!--$-->',
12+
'><title>&#128293; Blazing &#128293;</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="/styles.css"><!--$-->',
1313
"<!--/--></head>"
1414
],
1515
_tmpl$3 = [

‎packages/babel-plugin/test/__ssr_hydratable_fixtures__/textInterpolation/code.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,35 @@ const lastElementExpression = (
9393
{expr()}
9494
</div>
9595
);
96+
97+
const nonAsciiText = (
98+
<p title="Next →">
99+
Next → <style>{'.a::after{content:"→"}'}</style>
100+
</p>
101+
);
102+
const nonAsciiSpreadTail = <a {...spread} title="Next →" data-static="é" />;
103+
const nonAsciiCustomElement = <style-guide>Next →</style-guide>;
104+
const nonAsciiSpreadStyle = <style {...spread}>{'.a::after{content:"→"}'}</style>;
105+
const nonAsciiScriptture = <script>{'x = "</scripture>→";'}</script>;
106+
const latin1AndC1 = <p title="café">{"café \u0080\u0091"}</p>;
107+
const nonAsciiSpreadXmp = <xmp {...spread}>{"→"}</xmp>;
108+
const nonAsciiEscapedScript = <script>{'h = "<!--<script></script>→";'}</script>;
109+
const nonAsciiCdata = (
110+
<svg>
111+
<text innerHTML={"<![CDATA[→]]>"} />
112+
</svg>
113+
);
114+
const nonAsciiSpreadXmpElement = (
115+
<xmp {...spread}>
116+
<span>→</span>
117+
</xmp>
118+
);
119+
const nonAsciiSpreadScriptElement = (
120+
<script {...spread}>
121+
<span>→</span>
122+
</script>
123+
);
124+
const nonAsciiUnquotedQuote = (
125+
<div innerHTML={`<style data-x=a'b>.a::after{content:"→"}</style>`} />
126+
);
127+
const nonAsciiPlaintext = <div innerHTML={"<plaintext><p>→</p>"} />;

0 commit comments

Comments
 (0)