@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
package/src/vera/index.js
DELETED
|
@@ -1,1187 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Vera-native SSR — strategy 4. No wcc, no lit, no acorn, no parse5: Node resolves the module
|
|
3
|
-
* graph (`import()`), execution registers component classes (via `customElements.define`, which
|
|
4
|
-
* the shim owns and core's own wrapper passes through), templates flatten through the
|
|
5
|
-
* sigil-aware serializer, and nested components are discovered by scanning emitted markup for
|
|
6
|
-
* tags the registry knows — never by parsing HTML.
|
|
7
|
-
*
|
|
8
|
-
* Import THIS module first — before anything that imports `@verajs/renderer`, which is the module
|
|
9
|
-
* that actually needs the shims: it builds two shared `TreeWalker`s at import time and throws
|
|
10
|
-
* against a bare Node global object. A component reaches it through `keyed` or `hold`.
|
|
11
|
-
*
|
|
12
|
-
* Measured: core, `@verajs/styles` and `@verajs/router` are all order-independent; only the
|
|
13
|
-
* renderer is not. Core is still dynamically imported below, because `wire` has to come from the
|
|
14
|
-
* same instance the components will use.
|
|
15
|
-
*
|
|
16
|
-
* Client takeover is `@verajs/renderer/hydrate`, which adopts this markup in place — markerless,
|
|
17
|
-
* so nothing here carries framework comments. (This comment used to say the renderer had no
|
|
18
|
-
* `hydrate()` yet and point at a "strategy 2"; both stopped being true when that entry shipped.)
|
|
19
|
-
*/
|
|
20
|
-
import {
|
|
21
|
-
installShims,
|
|
22
|
-
registry,
|
|
23
|
-
hoistedStyles,
|
|
24
|
-
escapeHtml,
|
|
25
|
-
escapeStyleText,
|
|
26
|
-
setRenderingTag,
|
|
27
|
-
beginHoisting,
|
|
28
|
-
flushFrames,
|
|
29
|
-
flushFramesAsync,
|
|
30
|
-
pendingInstances,
|
|
31
|
-
INSTANCE_ATTRIBUTE,
|
|
32
|
-
/**
|
|
33
|
-
* Which elements hold text rather than markup, from the one place that knows.
|
|
34
|
-
*
|
|
35
|
-
* This file kept its own copy under a different name. They agreed, and nothing made them: adding
|
|
36
|
-
* an element to one would have left the scan rendering a component inside something the shim
|
|
37
|
-
* treats as text, or the reverse — a disagreement about the same single fact, which is what
|
|
38
|
-
* CODE-PRINCIPLES #5 is about.
|
|
39
|
-
*/
|
|
40
|
-
RAW_TEXT_ELEMENTS as RAW_TEXT,
|
|
41
|
-
/** The parts a `location` carries, from the shim that installs it. Same rule as `RAW_TEXT`. */
|
|
42
|
-
LOCATION_PARTS,
|
|
43
|
-
} from './shim.js';
|
|
44
|
-
import { serializeTemplate, serializeValue } from './serializer.js';
|
|
45
|
-
/** The attribute-name charset, from the parser that owns it — see `ATTRIBUTE` below. */
|
|
46
|
-
import { ATTRIBUTE_NAME, decode as decodeEntities } from './parse.js';
|
|
47
|
-
|
|
48
|
-
installShims();
|
|
49
|
-
const { wire, inserts, setStaticStores } = await import('@verajs/core');
|
|
50
|
-
/**
|
|
51
|
-
* `static styles` moved out of core in 0.2.0 (`@verajs/styles`). Server rendering must still
|
|
52
|
-
* serialize them — the markup a browser produces includes the component's styles — and nothing on
|
|
53
|
-
* the server cares about the bytes, so SSR wires the adopter unconditionally rather than making
|
|
54
|
-
* every caller remember to.
|
|
55
|
-
*
|
|
56
|
-
* `wire` comes from core, not from `@verajs/inserts`, so the registration lands in the map core
|
|
57
|
-
* actually reads. Exactly why the render insert above is registered through core's `wire` too.
|
|
58
|
-
*/
|
|
59
|
-
const { adoptStyles } = await import('@verajs/styles');
|
|
60
|
-
wire({ on: 'init', fn: adoptStyles, priority: 50 });
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Failures during a render are collected, not swallowed.
|
|
64
|
-
*
|
|
65
|
-
* Core deliberately does not rethrow a hook error — one bad effect must not take out the hooks
|
|
66
|
-
* beside it — and with no `'error'` insert registered it logs and carries on. In a browser that is
|
|
67
|
-
* right: the component is degraded and the next render can recover it. On a server there is no
|
|
68
|
-
* next render. A component whose `render()` threw was serialized **empty**, into a 200, with a
|
|
69
|
-
* console line on a machine nobody is watching — the same "empty component and said nothing about
|
|
70
|
-
* it" that the async-`connectedCallback` guard below refuses to allow.
|
|
71
|
-
*
|
|
72
|
-
* Registered at priority 10 rather than the default 50, so an app that installs its own error
|
|
73
|
-
* reporter keeps it: at a taken priority `wire` replaces.
|
|
74
|
-
*/
|
|
75
|
-
const renderErrors = [];
|
|
76
|
-
wire({ on: 'error', fn: (error, element) => renderErrors.push({ error, tag: element?.localName }), priority: 10 });
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* What this renderer last wrote into a container, and what sat in front of it.
|
|
80
|
-
*
|
|
81
|
-
* **`render()` owns its own range and nothing else** — that is the client's contract, and it holds
|
|
82
|
-
* over time, not just on the first pass. Measured in a browser DOM: content already in the container
|
|
83
|
-
* stays *before* the rendered range, a node appended afterwards stays *after* it, and both survive
|
|
84
|
-
* every re-render. The server assigned `innerHTML` outright, so a component that called `render()`
|
|
85
|
-
* and also appended to its own root kept the appended node in the browser and lost it here.
|
|
86
|
-
*
|
|
87
|
-
* The string equivalent of a range is the text on either side of it, which is what this holds.
|
|
88
|
-
*/
|
|
89
|
-
const written = new WeakMap();
|
|
90
|
-
|
|
91
|
-
/** The server renderer: template object in, markup into the (shadow) container shim. */
|
|
92
|
-
const serverRenderer = (template, container) => {
|
|
93
|
-
/**
|
|
94
|
-
* Anything that is not a template flattens exactly as a slot's value does, which is what the
|
|
95
|
-
* client does with the same return.
|
|
96
|
-
*
|
|
97
|
-
* A string used to be written straight into `innerHTML` — so a component returning
|
|
98
|
-
* `'<b>raw</b>'` produced real elements on the server and the **escaped text** `<b>raw…` in
|
|
99
|
-
* the browser. Different content on the two paths, and an injection the client does not have the
|
|
100
|
-
* moment any of that string comes from data. A number returned nothing at all here and `42`
|
|
101
|
-
* there.
|
|
102
|
-
*/
|
|
103
|
-
const ours = template?.strings ? serializeTemplate(template) : serializeValue(template);
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Where our range sits. On a re-render the container should still open with the text we saw in
|
|
107
|
-
* front of us and continue with what we wrote, and whatever follows is somebody else's — a node a
|
|
108
|
-
* component appended to its own root, or the `children` a light-DOM component was handed.
|
|
109
|
-
*
|
|
110
|
-
* If the container no longer matches that shape someone replaced its contents wholesale, and the
|
|
111
|
-
* honest reading is that our old range is gone: start again at the end, which is where a first
|
|
112
|
-
* `render()` puts it in a browser.
|
|
113
|
-
*/
|
|
114
|
-
const current = container.innerHTML;
|
|
115
|
-
const last = written.get(container);
|
|
116
|
-
const resumable = last !== undefined && current.startsWith(last.before + last.ours);
|
|
117
|
-
const before = resumable ? last.before : current;
|
|
118
|
-
const after = resumable ? current.slice(before.length + last.ours.length) : '';
|
|
119
|
-
|
|
120
|
-
container.innerHTML = before + ours + after;
|
|
121
|
-
written.set(container, { before, ours });
|
|
122
|
-
};
|
|
123
|
-
wire({ on: 'render', fn: serverRenderer, priority: 50 });
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Registering at a taken priority **replaces**. So an app entry doing the ordinary thing —
|
|
127
|
-
* `wire({ on: 'render', fn: renderInto, priority: 50 })` — displaces this renderer the moment that
|
|
128
|
-
* module is imported server-side, and every component then renders through a renderer that writes
|
|
129
|
-
* to a real DOM which is not there. The result was
|
|
130
|
-
* `<my-el><template shadowrootmode="open"></template></my-el>`: empty, for every component, with no
|
|
131
|
-
* error and nothing in the output to suggest why.
|
|
132
|
-
*
|
|
133
|
-
* Checked per render rather than once, because the displacement happens whenever the app's module
|
|
134
|
-
* graph is evaluated, which is after this file has run. The chain is asked for `serverRenderer`
|
|
135
|
-
* itself — `wire` registers the function it is handed, so identity is the whole check. (A Set-diff
|
|
136
|
-
* around the `wire` call used to recover "the entry that was added", a leftover from `setRenderer`,
|
|
137
|
-
* which registered a wrapper; nothing wraps any more.)
|
|
138
|
-
*/
|
|
139
|
-
const assertRendererIntact = () => {
|
|
140
|
-
if (inserts.get('render')?.includes(serverRenderer)) return;
|
|
141
|
-
throw new Error(
|
|
142
|
-
'ssr: the server renderer has been replaced — something wired a renderer after ' +
|
|
143
|
-
'@verajs/ssr was imported, and every component would render empty. Guard the client wiring ' +
|
|
144
|
-
'(`if (!globalThis.__veraSsrShimmed)`) or keep it out of the module the server imports.'
|
|
145
|
-
);
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* The index just past the `>` that closes the tag starting at `start`, respecting quoted attribute
|
|
150
|
-
* values.
|
|
151
|
-
*
|
|
152
|
-
* `>` is legal unescaped inside an attribute value, and a regex that stops at the first one cuts
|
|
153
|
-
* the tag in half: `<mark-comp title="x > y">` was read as a tag ending after `x `, giving the
|
|
154
|
-
* component an attribute value of `"x` and leaving ` y">` behind as text next to it.
|
|
155
|
-
*/
|
|
156
|
-
const tagEnd = (markup, start) => {
|
|
157
|
-
let quote = '';
|
|
158
|
-
for (let i = start + 1; i < markup.length; i++) {
|
|
159
|
-
const char = markup[i];
|
|
160
|
-
if (quote) {
|
|
161
|
-
if (char === quote) quote = '';
|
|
162
|
-
} else if (char === '"' || char === "'") quote = char;
|
|
163
|
-
else if (char === '>') return i + 1;
|
|
164
|
-
}
|
|
165
|
-
return markup.length;
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* `name`, `name="v"`, `name='v'` and `name=v` — every form an author may have written.
|
|
170
|
-
*
|
|
171
|
-
* Only the double-quoted form used to be recognised. `<x-y a='one' b=two>` gave the child three
|
|
172
|
-
* empty attributes *and invented two more*, because the value text fell through to the next
|
|
173
|
-
* iteration and matched as a name.
|
|
174
|
-
*
|
|
175
|
-
* **The NAME charset comes from `parse.js`, which owns it.** This file kept its own `[\w:-]+`,
|
|
176
|
-
* which is narrower than what a start tag may carry: `data-a.b="v"` split at the dot into
|
|
177
|
-
* `data-a=""` and `b="v"`, so a nested component was rebuilt with attributes its author never
|
|
178
|
-
* wrote and read `null` for the one they did — server-side only, silently (arc-2 run 2). The same
|
|
179
|
-
* single-fact-two-copies shape as `RAW_TEXT_ELEMENTS` above, and the same fix.
|
|
180
|
-
*/
|
|
181
|
-
const ATTRIBUTE = new RegExp(`(${ATTRIBUTE_NAME})(?:=(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, 'g');
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Attribute values arrive **escaped**, because they were read back out of markup this module just
|
|
185
|
-
* wrote. Handing that to `setAttribute` gave a nested component `Tom & Jerry` where the parent
|
|
186
|
-
* had passed `Tom & Jerry`, and re-escaping on the way out produced `Tom &#38; Jerry` — entity
|
|
187
|
-
* codes visible on the page, and a mismatch against whatever the client computes on hydration.
|
|
188
|
-
*
|
|
189
|
-
* The decoder is `parse.js`'s, which owns it. This file kept a lesser copy — decimal only, and
|
|
190
|
-
* `String.fromCharCode`, which truncates above U+FFFF — correct only while `escapeHtml`'s table
|
|
191
|
-
* stayed decimal and BMP, an invariant nothing enforced. Same fact, one place (arc-2 run 3).
|
|
192
|
-
*/
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* **How deep a component tree may nest before the server calls it a cycle.**
|
|
196
|
-
*
|
|
197
|
-
* A component that renders itself recurses without bound, and on a server that is a hung request
|
|
198
|
-
* rather than a hung tab, so a limit has to exist. It is a **divergence from the client**, which has
|
|
199
|
-
* no such limit — measured on both sides.
|
|
200
|
-
*
|
|
201
|
-
* **256, raised from 32.** A cycle recurses without bound, so 256 refuses it as surely as 32 did, a
|
|
202
|
-
* few microseconds later; 32 was low enough for a real tree to reach — router children inside
|
|
203
|
-
* design-system wrappers inside a card grid — and reaching it meant a 500 for a page that renders
|
|
204
|
-
* fine in a browser. The ceiling is set *below where the client breaks*: the client managed ~340
|
|
205
|
-
* levels before `RangeError`, so the server still fails first, and fails with a sentence rather than
|
|
206
|
-
* a stack overflow. That ~340 is engine- and frame-dependent and not a constant to design against,
|
|
207
|
-
* which is the argument for an explicit limit rather than waiting for our own stack to go.
|
|
208
|
-
*
|
|
209
|
-
* The client's own floor for a genuine cycle is the JavaScript stack — it built ~340 levels before
|
|
210
|
-
* `RangeError: Maximum call stack size exceeded`, reported through the `'error'` insert. That number
|
|
211
|
-
* is engine- and frame-dependent and cannot be relied on, which is the argument for the server
|
|
212
|
-
* having an explicit limit rather than waiting for its own stack to go.
|
|
213
|
-
*
|
|
214
|
-
* Documented in the README, because a hard limit nobody can find is a 500 nobody can explain.
|
|
215
|
-
*/
|
|
216
|
-
const MAX_DEPTH = 256;
|
|
217
|
-
|
|
218
|
-
/** Tags rendered during the current `renderToString`, so only their styles reach the page shell. */
|
|
219
|
-
const renderedTags = new Set();
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* `href -> tag`, so a component rendered twice is looked up once.
|
|
223
|
-
*
|
|
224
|
-
* `import()` is cached by Node, but awaiting a cached module still builds a promise and yields:
|
|
225
|
-
* 2.36 µs of a 9.5 µs render, measured, which a server pays on every request for a page it has
|
|
226
|
-
* already served. ESM modules are immutable once evaluated, so remembering the answer changes
|
|
227
|
-
* nothing except how long it takes to get it.
|
|
228
|
-
*/
|
|
229
|
-
const entryTags = new Map();
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Renders every registered component tag found in `markup` to declarative shadow DOM, spliced in
|
|
233
|
-
* as strings right after each opening tag. Recursion covers components rendered by components.
|
|
234
|
-
*/
|
|
235
|
-
/**
|
|
236
|
-
* **One scanner, two chains.** The synchronous render calls it with nothing and it behaves exactly
|
|
237
|
-
* as it always has; the asynchronous one hands it an `emit` that records a promise and returns a
|
|
238
|
-
* placeholder, substituting the real markup once everything has settled.
|
|
239
|
-
*
|
|
240
|
-
* This is what lets the two chains share the intricate half — comments, raw-text elements, nesting,
|
|
241
|
-
* attribute spans — rather than keeping two copies of a parser that must agree forever. Two paths
|
|
242
|
-
* drifting is the failure this package has spent a week deleting; a shared parser makes it
|
|
243
|
-
* impossible for the parsing half rather than merely tested-against.
|
|
244
|
-
*
|
|
245
|
-
* **It costs the synchronous path nothing measurable**: a call through a parameter instead of a
|
|
246
|
-
* direct one is ~6% of the scanning step, and the scanning step is a fraction of a percent of a
|
|
247
|
-
* render. The alternative considered — collecting segments into an array for a caller to assemble —
|
|
248
|
-
* was 1.85x on the same step and was rejected for it.
|
|
249
|
-
*
|
|
250
|
-
* @param {string} markup @param {number} depth
|
|
251
|
-
* @param {(name: string, attrs: string, depth: number) => string} [emit] renders one component tag
|
|
252
|
-
*/
|
|
253
|
-
/**
|
|
254
|
-
* Where the element opened at `after` ends, counting nested opens of the same name — `[contentEnd,
|
|
255
|
-
* elementEnd]`, or `null` when nothing closes it.
|
|
256
|
-
*
|
|
257
|
-
* Two callers, and they were one hand-rolled loop and one absence. `<template>` skips its content
|
|
258
|
-
* whole; a COMPONENT tag needs the same span for the opposite reason — that span is its children,
|
|
259
|
-
* and it has to be handed them rather than letting them trail it in the stream.
|
|
260
|
-
*
|
|
261
|
-
* The name boundary is checked, which the `<template>` loop did not do: `<templates>` counted as a
|
|
262
|
-
* nested `<template>` and threw the depth off for the rest of the document.
|
|
263
|
-
*
|
|
264
|
-
* @param {string} markup @param {string} name @param {number} after
|
|
265
|
-
* @returns {[number, number] | null}
|
|
266
|
-
*/
|
|
267
|
-
const matchingEnd = (markup, name, after) => {
|
|
268
|
-
const lower = markup.toLowerCase();
|
|
269
|
-
const openTag = `<${name}`;
|
|
270
|
-
const closeTag = `</${name}`;
|
|
271
|
-
/** A tag name ends where a name character stops — anything else continues the name. */
|
|
272
|
-
const boundary = (at) => !/[\w-]/.test(lower[at] ?? '');
|
|
273
|
-
let depth = 1;
|
|
274
|
-
let at = after;
|
|
275
|
-
while (depth > 0) {
|
|
276
|
-
let nextOpen = lower.indexOf(openTag, at);
|
|
277
|
-
while (nextOpen !== -1 && !boundary(nextOpen + openTag.length))
|
|
278
|
-
nextOpen = lower.indexOf(openTag, nextOpen + openTag.length);
|
|
279
|
-
let nextClose = lower.indexOf(closeTag, at);
|
|
280
|
-
while (nextClose !== -1 && !boundary(nextClose + closeTag.length))
|
|
281
|
-
nextClose = lower.indexOf(closeTag, nextClose + closeTag.length);
|
|
282
|
-
if (nextClose === -1) return null;
|
|
283
|
-
if (nextOpen !== -1 && nextOpen < nextClose) {
|
|
284
|
-
at = nextOpen + openTag.length;
|
|
285
|
-
depth++;
|
|
286
|
-
} else {
|
|
287
|
-
at = markup.indexOf('>', nextClose) + 1 || markup.length;
|
|
288
|
-
depth--;
|
|
289
|
-
if (depth === 0) return [nextClose, at];
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
return null;
|
|
293
|
-
};
|
|
294
|
-
|
|
295
|
-
const renderComponentTags = (markup, depth, emit) => {
|
|
296
|
-
if (depth > MAX_DEPTH)
|
|
297
|
-
throw new Error(
|
|
298
|
-
`ssr: component nesting exceeded ${MAX_DEPTH} levels. A component that renders itself ` +
|
|
299
|
-
`recurses without bound, and on a server that is a hung request — so this refuses rather ` +
|
|
300
|
-
`than waiting for the stack to go.\nIf the tree is genuinely this deep it renders fine in a ` +
|
|
301
|
-
`browser, which has no such limit; that difference is in the @verajs/ssr README.`
|
|
302
|
-
);
|
|
303
|
-
/** No dash, no custom element — cheaper to ask than to walk the string and find nothing. */
|
|
304
|
-
if (!markup.includes('-')) return markup;
|
|
305
|
-
|
|
306
|
-
let out = '';
|
|
307
|
-
let at = 0;
|
|
308
|
-
while (at < markup.length) {
|
|
309
|
-
const open = markup.indexOf('<', at);
|
|
310
|
-
if (open === -1) {
|
|
311
|
-
out += markup.slice(at);
|
|
312
|
-
break;
|
|
313
|
-
}
|
|
314
|
-
out += markup.slice(at, open);
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* A comment is text. Markup inside one used to be rendered — a `<!-- <some-comp> -->` produced
|
|
318
|
-
* a whole shadow template inside the comment, which is wasted work at best and breaks the
|
|
319
|
-
* comment at worst.
|
|
320
|
-
*/
|
|
321
|
-
if (markup.startsWith('<!--', open)) {
|
|
322
|
-
const close = markup.indexOf('-->', open + 4);
|
|
323
|
-
const stop = close === -1 ? markup.length : close + 3;
|
|
324
|
-
out += markup.slice(open, stop);
|
|
325
|
-
at = stop;
|
|
326
|
-
continue;
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
const end = tagEnd(markup, open);
|
|
330
|
-
const tagText = markup.slice(open, end);
|
|
331
|
-
/**
|
|
332
|
-
* **Folded, because a tag name in markup is case-insensitive and every decision below is not.**
|
|
333
|
-
* This required a lower-case first letter, so `<PROBE-KID>` matched nothing at all and the tag
|
|
334
|
-
* fell through as inert text — and with it every guard keyed on the name. A component inside an
|
|
335
|
-
* upper-case `<SCRIPT>` or `<TEXTAREA>` was rendered into its source rather than left as text,
|
|
336
|
-
* and `<TEMPLATE>` lost its skip, so components inside a template were rendered on the server
|
|
337
|
-
* that the client's parser would never upgrade.
|
|
338
|
-
*/
|
|
339
|
-
const name = /^<([a-zA-Z][\w]*(?:-[\w-]*)?)/.exec(tagText)?.[1]?.toLowerCase();
|
|
340
|
-
|
|
341
|
-
/**
|
|
342
|
-
* A `<template>` is a blueprint, not live DOM: the parser builds its content into a fragment
|
|
343
|
-
* and never upgrades custom elements inside it. Rendering one there produced markup the client
|
|
344
|
-
* would never produce, inside content whose whole purpose is to be stamped out later.
|
|
345
|
-
*
|
|
346
|
-
* Skipped depth-aware, because templates nest — the raw-text elements below cannot, so a
|
|
347
|
-
* search for their closing tag is enough for them and would mis-nest here.
|
|
348
|
-
*/
|
|
349
|
-
if (name === 'template') {
|
|
350
|
-
const at2 = matchingEnd(markup, 'template', end)?.[1] ?? markup.length;
|
|
351
|
-
out += markup.slice(open, at2);
|
|
352
|
-
at = at2;
|
|
353
|
-
continue;
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/**
|
|
357
|
-
* `<textarea>`, `<script>`, `<style>`, `<title>`: their content is text. A component named
|
|
358
|
-
* inside one was rendered into it, so the markup showed up as the textarea's value or the
|
|
359
|
-
* script's source.
|
|
360
|
-
*/
|
|
361
|
-
if (name && RAW_TEXT.has(name)) {
|
|
362
|
-
const closeTag = markup.toLowerCase().indexOf(`</${name}`, end);
|
|
363
|
-
const stop = closeTag === -1 ? markup.length : closeTag;
|
|
364
|
-
out += tagText + markup.slice(end, stop);
|
|
365
|
-
at = stop;
|
|
366
|
-
continue;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
if (name && registry.has(name)) {
|
|
370
|
-
/** Rewritten, not kept — the component may have changed its own attributes. */
|
|
371
|
-
const attrs = tagText.slice(1 + name.length, -1);
|
|
372
|
-
/**
|
|
373
|
-
* **A nested component is handed its children**, exactly as `renderToString` hands them to
|
|
374
|
-
* the top-level one. They used to trail it in the stream instead: the scanner emitted the
|
|
375
|
-
* component's rendered markup and then walked its children as ordinary markup after it.
|
|
376
|
-
*
|
|
377
|
-
* For a shadow component that happens to serialise the same way, which is why it went
|
|
378
|
-
* unnoticed. For a LIGHT component with slots it is wrong — the component never sees the
|
|
379
|
-
* content it is supposed to distribute, so every slot renders its fallback and the user's
|
|
380
|
-
* markup sits after the template. The CLIENT distributes it correctly, which made this a
|
|
381
|
-
* server/client divergence: a visibly wrong first paint, and a hydration mismatch after it.
|
|
382
|
-
* It also means a nested component can now read its own children in `connectedCallback`,
|
|
383
|
-
* which on the client it always could.
|
|
384
|
-
*
|
|
385
|
-
* Malformed markup keeps the old path exactly — an unclosed or self-closing tag hands over
|
|
386
|
-
* nothing and lets the stream carry on, so nothing the fuzz suites feed it changes shape.
|
|
387
|
-
*/
|
|
388
|
-
const span = tagText.endsWith('/>') ? null : matchingEnd(markup, name, end);
|
|
389
|
-
const children = span === null ? undefined : markup.slice(end, span[0]);
|
|
390
|
-
if (emit) out += emit(name, attrs, depth + 1, children);
|
|
391
|
-
else {
|
|
392
|
-
const rendered = renderComponent(name, attrs, depth + 1, undefined, children);
|
|
393
|
-
out += rendered.open + rendered.inner;
|
|
394
|
-
}
|
|
395
|
-
if (span !== null) {
|
|
396
|
-
/** The close tag is consumed with the children, so it is written back here — normalised,
|
|
397
|
-
* like the open tag the component just rewrote. */
|
|
398
|
-
out += `</${name}>`;
|
|
399
|
-
at = span[1];
|
|
400
|
-
continue;
|
|
401
|
-
}
|
|
402
|
-
} else {
|
|
403
|
-
out += tagText;
|
|
404
|
-
}
|
|
405
|
-
at = end;
|
|
406
|
-
}
|
|
407
|
-
return out;
|
|
408
|
-
};
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* **The asynchronous chain.**
|
|
412
|
-
*
|
|
413
|
-
* Everything that decides *what* to emit is shared with the synchronous render — the scanner above,
|
|
414
|
-
* the serializer, the entry resolution. What differs is only *when* it may wait: this one awaits a
|
|
415
|
-
* component's `connectedCallback`, and lets promises settle between frame rounds, which is what a
|
|
416
|
-
* routed component's first navigation needs and what the synchronous render refuses.
|
|
417
|
-
*
|
|
418
|
-
* **The scan itself stays synchronous.** A component tag becomes a placeholder and its render a
|
|
419
|
-
* promise; once everything has settled the placeholders are substituted. Awaiting inside the scan
|
|
420
|
-
* would have meant a second copy of the parser — and measured, an async recursion costs 2.45x even
|
|
421
|
-
* when nothing suspends, which the synchronous path is not going to pay for a feature it never uses.
|
|
422
|
-
*
|
|
423
|
-
* The placeholder carries a per-process random name for the same reason `INSTANCE_ATTRIBUTE` does:
|
|
424
|
-
* it must be impossible for a component's own markup to contain one.
|
|
425
|
-
*/
|
|
426
|
-
const PLACEHOLDER = `vera-async-${crypto.randomUUID()}`;
|
|
427
|
-
const PLACEHOLDER_PATTERN = new RegExp(`${PLACEHOLDER}(\\d+)_`, 'gu');
|
|
428
|
-
|
|
429
|
-
/** @param {string} markup @param {number} depth @param {Array<Promise<string>>} pending */
|
|
430
|
-
const scanAsync = (markup, depth, pending) =>
|
|
431
|
-
renderComponentTags(markup, depth, (name, attrs, at, children) => {
|
|
432
|
-
pending.push(renderComponentAsync(name, attrs, at, undefined, children));
|
|
433
|
-
return `${PLACEHOLDER}${pending.length - 1}_`;
|
|
434
|
-
});
|
|
435
|
-
|
|
436
|
-
/** Substitutes what the scan deferred, once every component beneath it has settled. */
|
|
437
|
-
const settle = async (scanned, pending) => {
|
|
438
|
-
if (!pending.length) return scanned;
|
|
439
|
-
const parts = await Promise.all(pending);
|
|
440
|
-
return scanned.replace(PLACEHOLDER_PATTERN, (_, index) => parts[Number(index)]);
|
|
441
|
-
};
|
|
442
|
-
|
|
443
|
-
/** @param {string} markup @param {number} depth */
|
|
444
|
-
const renderComponentTagsAsync = async (markup, depth) => {
|
|
445
|
-
const pending = /** @type {Array<Promise<string>>} */ ([]);
|
|
446
|
-
return settle(scanAsync(markup, depth, pending), pending);
|
|
447
|
-
};
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
* Points `globalThis.location` at one request's URL and hands back what it held.
|
|
451
|
-
*
|
|
452
|
-
* A path is resolved against whatever `location` already describes, so `'/users/2?page=3#top'`
|
|
453
|
-
* works without a caller having to invent an origin.
|
|
454
|
-
*/
|
|
455
|
-
const applyLocation = (location) => {
|
|
456
|
-
const current = globalThis.location;
|
|
457
|
-
const previous = Object.fromEntries(LOCATION_PARTS.map((part) => [part, current?.[part]]));
|
|
458
|
-
const next = new URL(String(location), current?.href ?? 'http://localhost/');
|
|
459
|
-
for (const part of LOCATION_PARTS) current[part] = next[part];
|
|
460
|
-
return previous;
|
|
461
|
-
};
|
|
462
|
-
|
|
463
|
-
const restoreLocation = (previous) => {
|
|
464
|
-
const current = globalThis.location;
|
|
465
|
-
for (const part of LOCATION_PARTS) current[part] = previous[part];
|
|
466
|
-
};
|
|
467
|
-
|
|
468
|
-
/** Instantiates a registered component and returns its declarative-shadow (or light) markup. */
|
|
469
|
-
/**
|
|
470
|
-
* Which element a tag should be rendered as — shared by both chains, because deciding it has nothing
|
|
471
|
-
* to do with whether the render may wait.
|
|
472
|
-
*
|
|
473
|
-
* A component the *parent* built and appended is rendered as itself, carrying whatever the parent
|
|
474
|
-
* assigned to it. The fresh instance built here is discarded in that case; only its attributes were
|
|
475
|
-
* ever needed, and they came from the markup that instance wrote in the first place.
|
|
476
|
-
*
|
|
477
|
-
* **The tag has to match.** The marker's name is already unguessable, so this is the second lock on
|
|
478
|
-
* the same door: a marker can only ever produce the component it was written for.
|
|
479
|
-
*/
|
|
480
|
-
const buildInstance = (tag, attrString) => {
|
|
481
|
-
const element = new (registry.get(tag))();
|
|
482
|
-
element.localName = tag;
|
|
483
|
-
if (attrString) {
|
|
484
|
-
for (const [, name, quoted, single, bare] of attrString.matchAll(ATTRIBUTE)) {
|
|
485
|
-
element.setAttribute(name, decodeEntities(quoted ?? single ?? bare ?? ''));
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
const pending = pendingInstances.get(element.getAttribute(INSTANCE_ATTRIBUTE));
|
|
489
|
-
if (pending && pending.localName === tag) {
|
|
490
|
-
/**
|
|
491
|
-
* The markup's attributes land on the prepared instance too. A serializer-born instance — a
|
|
492
|
-
* component tag whose property bindings were delivered — has never seen them (it was built
|
|
493
|
-
* from the registry, not the markup), so without this a component reading its own
|
|
494
|
-
* `getAttribute` answered `null` against markup that plainly carries the attribute. For a
|
|
495
|
-
* node-born instance the attributes were serialized FROM the node, so re-applying them is
|
|
496
|
-
* idempotent. The marker itself comes along and `prepareInstance` removes it immediately.
|
|
497
|
-
*/
|
|
498
|
-
if (attrString) {
|
|
499
|
-
for (const [, name, quoted, single, bare] of attrString.matchAll(ATTRIBUTE)) {
|
|
500
|
-
pending.setAttribute(name, decodeEntities(quoted ?? single ?? bare ?? ''));
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
return pending;
|
|
504
|
-
}
|
|
505
|
-
return element;
|
|
506
|
-
};
|
|
507
|
-
|
|
508
|
-
const renderComponent = (tag, attrString, depth, props, children) =>
|
|
509
|
-
renderInstance(buildInstance(tag, attrString), tag, depth, props, children);
|
|
510
|
-
|
|
511
|
-
/**
|
|
512
|
-
* The asynchronous mirror of `renderComponent`. Identical in what it decides; different only in that
|
|
513
|
-
* it hands off to a lifecycle it is allowed to wait for.
|
|
514
|
-
*/
|
|
515
|
-
const renderComponentAsync = async (tag, attrString, depth, props, children) => {
|
|
516
|
-
const { open, inner } = await renderInstanceAsync(buildInstance(tag, attrString), tag, depth, props, children);
|
|
517
|
-
/**
|
|
518
|
-
* **Open tag and contents only** — the scanner emits the closing tag from the markup it is walking,
|
|
519
|
-
* exactly as it does for the synchronous chain. Returning a complete element here produced
|
|
520
|
-
* `</child-badge></child-badge>` on every nested component.
|
|
521
|
-
*/
|
|
522
|
-
return `${open}${inner}`;
|
|
523
|
-
};
|
|
524
|
-
|
|
525
|
-
/**
|
|
526
|
-
* Everything an instance needs before its lifecycle runs — the marker bookkeeping, `props`, and the
|
|
527
|
-
* children. Shared by both chains: none of it depends on whether the render may wait.
|
|
528
|
-
*
|
|
529
|
-
* @param {any} element @param {string} tag @param {Record<string, unknown>} [props] @param {string} [children]
|
|
530
|
-
*/
|
|
531
|
-
const prepareInstance = (element, tag, props, children) => {
|
|
532
|
-
element._rendered = true;
|
|
533
|
-
/** Read before it is removed, or the map keeps the instance for the rest of the process. */
|
|
534
|
-
pendingInstances.delete(element.getAttribute(INSTANCE_ATTRIBUTE));
|
|
535
|
-
element.removeAttribute(INSTANCE_ATTRIBUTE);
|
|
536
|
-
|
|
537
|
-
/**
|
|
538
|
-
* Properties are assigned before `connectedCallback`, which is where a client parent would have
|
|
539
|
-
* put them too. Attributes can only carry strings, so a component that takes rows, a config
|
|
540
|
-
* object or anything else structured could not be server-rendered with real data at all — it had
|
|
541
|
-
* to be handed a JSON string and parse it back.
|
|
542
|
-
*/
|
|
543
|
-
if (props) {
|
|
544
|
-
try {
|
|
545
|
-
/**
|
|
546
|
-
* **`__proto__` is skipped**, because `Object.assign` copies it with `[[Set]]` and that
|
|
547
|
-
* *replaces the element's prototype*. `props` exists to be handed structured data, and
|
|
548
|
-
* `props: await request.json()` is the obvious way to use it — `JSON.parse` makes `__proto__`
|
|
549
|
-
* an ordinary own key, so one request body ended the render with
|
|
550
|
-
* `element.upgrade is not a function` and, on the way there, gave the caller control of what
|
|
551
|
-
* the component inherited from. Nothing legitimate assigns a prototype through this option.
|
|
552
|
-
*/
|
|
553
|
-
for (const [name, value] of Object.entries(props)) if (name !== '__proto__') element[name] = value;
|
|
554
|
-
} catch (error) {
|
|
555
|
-
/**
|
|
556
|
-
* `Object.assign` onto a getter-only property throws `Cannot set property x of #<Class>` —
|
|
557
|
-
* true, and no help at all: it names neither the component, nor the option the value came
|
|
558
|
-
* from, nor that a server render was in progress. Every other bad input to `renderToString`
|
|
559
|
-
* says what to do about it.
|
|
560
|
-
*/
|
|
561
|
-
throw new TypeError(
|
|
562
|
-
`ssr: <${tag}> refused a value from \`props\` — ${String(/** @type {Error} */ (error).message)}. ` +
|
|
563
|
-
`A read-only property cannot be set; pass it as an attribute, or give the class a setter.`
|
|
564
|
-
);
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
/**
|
|
568
|
-
* Children go in **before** `connectedCallback`, because that is where a client finds them: the
|
|
569
|
-
* parser has already built them when the element upgrades. A component that reads or slots them
|
|
570
|
-
* therefore sees them, and one that overwrites its own light DOM wins — same order, same result.
|
|
571
|
-
*/
|
|
572
|
-
if (children) element.innerHTML = children;
|
|
573
|
-
/**
|
|
574
|
-
* Light-DOM slots: if an app wired `@verajs/renderer/slots`, snapshot the user's children NOW —
|
|
575
|
-
* before `connectedCallback` renders the template after them — so the server can distribute
|
|
576
|
-
* them into the template's `<slot>` positions once it has run (see `distributeLightSlots`).
|
|
577
|
-
* Opt-in and decoupled: `inserts` is consulted, this module imports nothing of slots.
|
|
578
|
-
*/
|
|
579
|
-
const slotInsert = /** @type {any} */ (inserts).get('slot')?.[0];
|
|
580
|
-
if (slotInsert?._$server$ !== undefined) {
|
|
581
|
-
/**
|
|
582
|
-
* Take the user's children OUT now — held by reference — so the template renders into an empty
|
|
583
|
-
* host and `serverDistribute` places them at the `<slot>` positions afterward. Removing them
|
|
584
|
-
* here (while their parent is live) rather than snapshotting-in-place avoids the shim's
|
|
585
|
-
* re-parse orphaning the references (a stale ref serialises a duplicate at the top level).
|
|
586
|
-
*
|
|
587
|
-
* **The ELEMENT's children, never the `children` string.** A NESTED component does not arrive
|
|
588
|
-
* as markup: it was already built when its parent's children were parsed, and it is carried
|
|
589
|
-
* across the string boundary through `pendingInstances`, so it reaches here with real child
|
|
590
|
-
* nodes and no `children` argument at all. Gated on the string, a nested component snapshotted
|
|
591
|
-
* nothing, rendered every slot to its fallback, and left the user's content sitting after the
|
|
592
|
-
* template — the inner half of a nested pair simply did not slot. This is also what the client
|
|
593
|
-
* does: `capture()` takes the host's direct children, whatever put them there.
|
|
594
|
-
*/
|
|
595
|
-
const source = [...element.childNodes];
|
|
596
|
-
for (const node of source) element.removeChild(node);
|
|
597
|
-
element._veraSlotSource = source;
|
|
598
|
-
}
|
|
599
|
-
};
|
|
600
|
-
|
|
601
|
-
/**
|
|
602
|
-
* After a LIGHT component's template has rendered (its `<slot>`s now sit after the snapshotted
|
|
603
|
-
* source children), hand both to the slots module's server distributor: it unwraps each `<slot>`
|
|
604
|
-
* to its assigned nodes or fallback and stamps `data-vm-slotted` on the host for the default
|
|
605
|
-
* slot. No-op unless the app wired slots and this element had children.
|
|
606
|
-
*/
|
|
607
|
-
const distributeLightSlots = (element) => {
|
|
608
|
-
const source = element._veraSlotSource;
|
|
609
|
-
if (source === undefined) return; // slots not wired for this render
|
|
610
|
-
element._veraSlotSource = undefined;
|
|
611
|
-
/**
|
|
612
|
-
* **A SHADOW component's children are its LIGHT DOM**, which the platform itself projects
|
|
613
|
-
* through the native `<slot>` in the shadow root — nothing here may touch them. They were
|
|
614
|
-
* lifted out before the lifecycle (the light path needs them out of the way), so put them back
|
|
615
|
-
* exactly as they were. Without this, wiring slots for the light components in an app silently
|
|
616
|
-
* broke every SHADOW component that had slotted content: the sync chain dropped it from the
|
|
617
|
-
* page entirely and the async chain buried it in the unassigned carrier, which is the very bug
|
|
618
|
-
* the light-DOM serialization below was added to fix.
|
|
619
|
-
*/
|
|
620
|
-
if (element._shadowRoot) {
|
|
621
|
-
for (const node of source) element.appendChild(node);
|
|
622
|
-
return;
|
|
623
|
-
}
|
|
624
|
-
/** @type {any} */ (inserts).get('slot')?.[0]?._$server$?.(element, source);
|
|
625
|
-
};
|
|
626
|
-
|
|
627
|
-
/**
|
|
628
|
-
* The `'settle'` insert: this element's tree is final — lifecycle run, frames drained — and is
|
|
629
|
-
* about to be serialized. The only moment a server can offer for reading RENDERED content, since
|
|
630
|
-
* `'init'` fires before the first render and there is no observer here to catch what follows.
|
|
631
|
-
*
|
|
632
|
-
* `@verajs/directives` uses it to evaluate declarative directives into the markup, which is what
|
|
633
|
-
* makes a server-rendered page correct before any JavaScript arrives. A throwing handler is a
|
|
634
|
-
* render failure like any other — collected and reported against the tag rather than swallowed,
|
|
635
|
-
* because there is no next render to recover in.
|
|
636
|
-
*
|
|
637
|
-
* @param {any} element
|
|
638
|
-
*/
|
|
639
|
-
const settleInstance = (element) => {
|
|
640
|
-
const chain = /** @type {any} */ (inserts).get('settle');
|
|
641
|
-
if (!chain) return;
|
|
642
|
-
for (const fn of chain) fn(element);
|
|
643
|
-
};
|
|
644
|
-
|
|
645
|
-
/** Runs the lifecycle on an element that is already built, and serializes it. */
|
|
646
|
-
const renderInstance = (element, tag, depth, props, children) => {
|
|
647
|
-
prepareInstance(element, tag, props, children);
|
|
648
|
-
|
|
649
|
-
renderedTags.add(tag);
|
|
650
|
-
const previousTag = setRenderingTag(tag) ?? tag;
|
|
651
|
-
element.upgrade();
|
|
652
|
-
const pending = element.connectedCallback?.();
|
|
653
|
-
/** Inside the rendering tag, so a re-render's styles are still hoisted against this component. */
|
|
654
|
-
flushFrames((error) => renderErrors.push({ error, tag }));
|
|
655
|
-
settleInstance(element);
|
|
656
|
-
setRenderingTag(previousTag);
|
|
657
|
-
|
|
658
|
-
/**
|
|
659
|
-
* Rendering is synchronous end to end, so an `async connectedCallback` returns a promise nobody
|
|
660
|
-
* can wait for, and everything after its first `await` happens long after the markup was
|
|
661
|
-
* serialized. That produced an empty component and said nothing about it, which is the worst of
|
|
662
|
-
* the available outcomes.
|
|
663
|
-
*
|
|
664
|
-
* **The reason it is synchronous is not what this used to say.** It claimed the recursion runs
|
|
665
|
-
* inside `String.replace` and therefore cannot await; `renderComponentTags` is a plain `while`
|
|
666
|
-
* loop and there is no such callback anywhere in the chain. The real constraint is the one stated
|
|
667
|
-
* at `renderPage`: the per-render bookkeeping — `renderedTags`, `renderErrors`,
|
|
668
|
-
* `pendingInstances`, `instanceCount`, the hoisting state — is **module-level**, so two renders
|
|
669
|
-
* that interleaved would read each other's. Being synchronous end to end is what makes concurrent
|
|
670
|
-
* `renderToString` calls safe, which `tests/ssr-request-isolation.test.mjs` relies on.
|
|
671
|
-
*
|
|
672
|
-
* Making this async is therefore a matter of threading that state through rather than of the shape
|
|
673
|
-
* of the recursion — a real change with a real payoff (async lifecycles, and a routed component
|
|
674
|
-
* rendering its route), and one nobody should start from this comment alone.
|
|
675
|
-
*
|
|
676
|
-
* Load data before `renderToString` and pass it in through attributes.
|
|
677
|
-
*/
|
|
678
|
-
if (pending && typeof pending.then === 'function') {
|
|
679
|
-
throw new Error(
|
|
680
|
-
`ssr: <${tag}> has an async connectedCallback, which cannot be awaited during a synchronous ` +
|
|
681
|
-
`render — its markup would be empty. Load data before renderToString and pass it as attributes.`
|
|
682
|
-
);
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
/** Light slots: distribute for a light host, or restore a shadow host's light children — must
|
|
686
|
-
* happen before either branch reads `openTag()`/`innerHTML`. */
|
|
687
|
-
distributeLightSlots(element);
|
|
688
|
-
const open = element.openTag();
|
|
689
|
-
/**
|
|
690
|
-
* `_shadowRoot`, not `shadowRoot` — **a closed root is hidden from the page and still serialized.**
|
|
691
|
-
* `element.shadowRoot` is `null` for `mode: 'closed'`, exactly as it is in a browser, so reading it
|
|
692
|
-
* here dropped the whole template and the component rendered empty. Declarative shadow DOM
|
|
693
|
-
* expresses `closed` (`<template shadowrootmode="closed">`) and the client re-creates it just as
|
|
694
|
-
* hidden, so there is nothing to withhold — the mode governs who can reach in, not what is written.
|
|
695
|
-
*/
|
|
696
|
-
const shadowRoot = element._shadowRoot;
|
|
697
|
-
if (shadowRoot) {
|
|
698
|
-
/** Styles are prepended after the scan, never passed through it — see `styleTags`. */
|
|
699
|
-
const inner = renderComponentTags(shadowRoot.innerHTML, depth);
|
|
700
|
-
/**
|
|
701
|
-
* The element's own light DOM follows the template. It used to be discarded for any shadow
|
|
702
|
-
* component, so content a component put in its own light DOM — the thing its `<slot>` projects
|
|
703
|
-
* — was on the page client-side and missing server-side.
|
|
704
|
-
*/
|
|
705
|
-
const light = element.innerHTML ? renderComponentTags(element.innerHTML, depth) : '';
|
|
706
|
-
return {
|
|
707
|
-
open,
|
|
708
|
-
inner: `<template${shadowRoot.templateAttributes()}>${shadowRoot.styleTags()}${inner}</template>${light}`,
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
/** Light DOM: rendered content becomes the element's children (client re-render replaces). */
|
|
712
|
-
return { open, inner: renderComponentTags(element.innerHTML, depth) };
|
|
713
|
-
};
|
|
714
|
-
|
|
715
|
-
/**
|
|
716
|
-
* What an element serializes to, before anything inside it has been scanned — shared by both chains,
|
|
717
|
-
* because none of it depends on whether the render may wait. Each chain scans the two markup
|
|
718
|
-
* fragments with its own scanner and assembles the same way.
|
|
719
|
-
*
|
|
720
|
-
* @param {any} element
|
|
721
|
-
*/
|
|
722
|
-
const instancePieces = (element) => {
|
|
723
|
-
const shadowRoot = element._shadowRoot;
|
|
724
|
-
return {
|
|
725
|
-
open: element.openTag(),
|
|
726
|
-
shadowRoot,
|
|
727
|
-
/** The template's own markup, and the element's light DOM, each still to be scanned. */
|
|
728
|
-
shadowMarkup: shadowRoot ? shadowRoot.innerHTML : '',
|
|
729
|
-
lightMarkup: element.innerHTML,
|
|
730
|
-
};
|
|
731
|
-
};
|
|
732
|
-
|
|
733
|
-
/** Puts the scanned halves back together — the one shape both chains produce. */
|
|
734
|
-
const assembleInstance = ({ open, shadowRoot }, scannedShadow, scannedLight) =>
|
|
735
|
-
shadowRoot
|
|
736
|
-
? {
|
|
737
|
-
open,
|
|
738
|
-
inner: `<template${shadowRoot.templateAttributes()}>${shadowRoot.styleTags()}${scannedShadow}</template>${scannedLight}`,
|
|
739
|
-
}
|
|
740
|
-
: { open, inner: scannedLight };
|
|
741
|
-
|
|
742
|
-
/**
|
|
743
|
-
* The asynchronous mirror of `renderInstance`. The lifecycle is awaited and the frame drain lets
|
|
744
|
-
* promises settle between rounds; everything else is the shared helpers the synchronous one uses.
|
|
745
|
-
*/
|
|
746
|
-
const renderInstanceAsync = async (element, tag, depth, props, children) => {
|
|
747
|
-
prepareInstance(element, tag, props, children);
|
|
748
|
-
|
|
749
|
-
renderedTags.add(tag);
|
|
750
|
-
const previousTag = setRenderingTag(tag) ?? tag;
|
|
751
|
-
element.upgrade();
|
|
752
|
-
/**
|
|
753
|
-
* **Awaited, which is the whole point of this chain.** The synchronous render refuses an
|
|
754
|
-
* `async connectedCallback` because its markup would be empty; here it is simply waited for.
|
|
755
|
-
*/
|
|
756
|
-
await element.connectedCallback?.();
|
|
757
|
-
await flushFramesAsync((error) => renderErrors.push({ error, tag }));
|
|
758
|
-
settleInstance(element);
|
|
759
|
-
setRenderingTag(previousTag);
|
|
760
|
-
|
|
761
|
-
distributeLightSlots(element);
|
|
762
|
-
const pieces = instancePieces(element);
|
|
763
|
-
const scannedShadow = pieces.shadowRoot ? await renderComponentTagsAsync(pieces.shadowMarkup, depth) : '';
|
|
764
|
-
const scannedLight = pieces.lightMarkup ? await renderComponentTagsAsync(pieces.lightMarkup, depth) : '';
|
|
765
|
-
return assembleInstance(pieces, scannedShadow, scannedLight);
|
|
766
|
-
};
|
|
767
|
-
|
|
768
|
-
/**
|
|
769
|
-
* Renders a component module to markup.
|
|
770
|
-
*
|
|
771
|
-
* @param url Module URL (the component's file; Node resolves its imports natively — the
|
|
772
|
-
* `.ts`-via-`.js` convention included)
|
|
773
|
-
* @param {object} [options]
|
|
774
|
-
* @param {string} [options.tag] Picks the element when the module defines several
|
|
775
|
-
* @param {string | Record<string, unknown>} [options.attributes] The entry tag's attributes — an
|
|
776
|
-
* object, whose values are escaped; a string is written through untouched
|
|
777
|
-
* @param {Record<string, unknown>} [options.props] Properties assigned before `connectedCallback`,
|
|
778
|
-
* which is how structured data reaches a component
|
|
779
|
-
* @param {string} [options.children] Markup placed inside the entry tag — what a `<slot>` renders
|
|
780
|
-
* @param {Set<string>} [options.seen] Carried across renders so a component's styles reach the
|
|
781
|
-
* page once, for a shell assembled from several islands
|
|
782
|
-
* @param {string | URL} [options.base] A directory the module must resolve inside. Pass it whenever
|
|
783
|
-
* any part of `url` came from a request
|
|
784
|
-
* @param {boolean} [options.static] Declare that this page will not be interactive, so its stores
|
|
785
|
-
* need not be reactive. Worth roughly 3x — the proxy behind `createStore` is the whole reactivity
|
|
786
|
-
* cost of a server render — and the markup is identical. A component that writes to a store during
|
|
787
|
-
* the render throws in development rather than silently rendering something that never updated.
|
|
788
|
-
* @param {string | URL} [options.location] This request's URL, for any component that reads one.
|
|
789
|
-
* Applied after every await and restored afterwards, so concurrent renders cannot see each other's
|
|
790
|
-
* — assigning to `globalThis.location` yourself is not safe once two requests overlap
|
|
791
|
-
* @return `{ html, styles, title }` — `styles` collects light-DOM `@scope` sheets for the page
|
|
792
|
-
* shell, and `title` is `document.title` as this render left it, which the shell puts in `<title>`.
|
|
793
|
-
* Both are returned rather than left on a global so concurrent renders cannot see each other's.
|
|
794
|
-
*/
|
|
795
|
-
const renderModule = async (
|
|
796
|
-
url,
|
|
797
|
-
{ tag, attributes = '', children = '', props, seen, base, location, static: isStatic = false } = {},
|
|
798
|
-
isAsync = false
|
|
799
|
-
) => {
|
|
800
|
-
/**
|
|
801
|
-
* The options are checked because getting one wrong otherwise surfaced an internal: `children: 5`
|
|
802
|
-
* threw `markup.includes is not a function`, `seen: []` threw `seen?.has is not a function`, and
|
|
803
|
-
* omitting the URL entirely produced `Cannot find package 'undefined'`. None of those name the
|
|
804
|
-
* thing the caller got wrong. Server-side, so it costs a browser nothing.
|
|
805
|
-
*/
|
|
806
|
-
if (typeof url !== 'string' && !(url instanceof URL)) {
|
|
807
|
-
throw new TypeError('ssr: renderToString needs a module URL — a URL or a string');
|
|
808
|
-
}
|
|
809
|
-
if (typeof attributes !== 'string' && (typeof attributes !== 'object' || Array.isArray(attributes))) {
|
|
810
|
-
throw new TypeError('ssr: `attributes` must be an object of names to values, or a string');
|
|
811
|
-
}
|
|
812
|
-
if (typeof children !== 'string') throw new TypeError('ssr: `children` must be a markup string');
|
|
813
|
-
/**
|
|
814
|
-
* An **array** is refused along with the other wrong types. `Object.assign(element, ['a'])` sets a
|
|
815
|
-
* property named `0`, so passing rows straight through instead of `{ rows }` — the obvious slip —
|
|
816
|
-
* assigned nothing anyone meant and said nothing about it. `attributes` already refuses one.
|
|
817
|
-
*/
|
|
818
|
-
if (props !== undefined && (typeof props !== 'object' || props === null || Array.isArray(props))) {
|
|
819
|
-
throw new TypeError('ssr: `props` must be an object of properties to assign');
|
|
820
|
-
}
|
|
821
|
-
if (seen !== undefined && !(seen instanceof Set)) throw new TypeError('ssr: `seen` must be a Set');
|
|
822
|
-
if (location !== undefined && typeof location !== 'string' && !(location instanceof URL)) {
|
|
823
|
-
throw new TypeError('ssr: `location` must be a URL or a path string');
|
|
824
|
-
}
|
|
825
|
-
if (typeof isStatic !== 'boolean') throw new TypeError('ssr: `static` must be true or false');
|
|
826
|
-
/** A `tag` that is not a string cannot name a custom element, and saying so here names the option. */
|
|
827
|
-
if (tag !== undefined && typeof tag !== 'string') {
|
|
828
|
-
throw new TypeError(`ssr: \`tag\` must be a custom element name, and ${typeof tag} is not one`);
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
const href = url instanceof URL ? url.href : url;
|
|
832
|
-
|
|
833
|
-
/**
|
|
834
|
-
* `import()` executes whatever it is given, so a URL with any request data in it needs bounding —
|
|
835
|
-
* and `new URL` resolves `../` *before* this function sees anything, so the traversal has already
|
|
836
|
-
* happened by the time the string arrives. Mapping a route to a component file is the obvious way
|
|
837
|
-
* to use a server renderer, which is exactly where that goes wrong.
|
|
838
|
-
*
|
|
839
|
-
* Opt-in rather than required: most calls name a constant, and ceremony that is always trivially
|
|
840
|
-
* satisfied stops being read. Deliberately the same shape and the same wording as
|
|
841
|
-
* `@verajs/autoloader`'s containment check, so "module URLs are bounded to a base" is one idea in
|
|
842
|
-
* this framework rather than two.
|
|
843
|
-
*/
|
|
844
|
-
if (base) {
|
|
845
|
-
/**
|
|
846
|
-
* Read as a directory whether or not it was written as one.
|
|
847
|
-
*
|
|
848
|
-
* `new URL('.', 'file:///app/components')` is `file:///app/` — the **parent**. A caller who
|
|
849
|
-
* wrote the directory without a trailing slash therefore got a bound one level wider than the
|
|
850
|
-
* one they asked for, silently, and the module was imported before anything noticed. Appending
|
|
851
|
-
* the slash can only ever tighten the bound, and a caller who meant a file gets a loud refusal
|
|
852
|
-
* on the next render rather than a quiet widening on this one.
|
|
853
|
-
*/
|
|
854
|
-
const given = base instanceof URL ? base.href : String(base);
|
|
855
|
-
const root = new URL('.', given.endsWith('/') ? given : `${given}/`).href;
|
|
856
|
-
if (!href.startsWith(root)) {
|
|
857
|
-
throw new Error(`ssr: refused ${href} — resolves outside ${root}`);
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
/**
|
|
862
|
-
* The import is what registers the component, so it cannot be skipped merely because the caller
|
|
863
|
-
* named a `tag` — a first render with `{ tag }` would then look for a definition nothing had
|
|
864
|
-
* created. `entryTags` having the href is proof the module has already been imported, and that
|
|
865
|
-
* is the only condition under which the import is skipped.
|
|
866
|
-
*/
|
|
867
|
-
if (!entryTags.has(href)) {
|
|
868
|
-
const module = await import(href);
|
|
869
|
-
let derived;
|
|
870
|
-
|
|
871
|
-
/**
|
|
872
|
-
* The entry tag is found by matching this module's **exports** against the registry, never by
|
|
873
|
-
* diffing the registry around the import.
|
|
874
|
-
*
|
|
875
|
-
* The diff was unsound the moment two renders overlapped, which for a server is the normal
|
|
876
|
-
* condition: both snapshot the registry, both await their import, and both then see both
|
|
877
|
-
* modules' registrations as "new" — so a request for one component was answered with another's
|
|
878
|
-
* markup. Verified before the change: concurrent renders of `race-a` and `race-b` both returned
|
|
879
|
-
* `race-b`. Identity matching depends on nothing outside the module being asked about.
|
|
880
|
-
*/
|
|
881
|
-
for (const exported of [module.default, ...Object.values(module)]) {
|
|
882
|
-
if (typeof exported !== 'function') continue;
|
|
883
|
-
for (const [name, Class] of registry) if (Class === exported) derived = name;
|
|
884
|
-
if (derived) break;
|
|
885
|
-
}
|
|
886
|
-
/** Recorded either way — the entry doubles as "this href has been imported". */
|
|
887
|
-
entryTags.set(href, derived ?? '');
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
tag = tag || entryTags.get(href);
|
|
891
|
-
if (!tag || !registry.has(tag)) {
|
|
892
|
-
throw new Error(
|
|
893
|
-
`ssr: no custom element definition found for ${url} — export the component's class, or pass { tag }`
|
|
894
|
-
);
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
/**
|
|
898
|
-
* An object is escaped; a string is written through untouched.
|
|
899
|
-
*
|
|
900
|
-
* The string form was the only one, and it is a hole: `attributes` reaches the markup verbatim, so
|
|
901
|
-
* a value taken from a request could close the tag and open a `<script>`. It stays, because a
|
|
902
|
-
* caller may genuinely need to write markup only they can produce, but it is no longer the
|
|
903
|
-
* ordinary way to do the ordinary thing — an object cannot escape the tag it describes.
|
|
904
|
-
*/
|
|
905
|
-
const attrString =
|
|
906
|
-
typeof attributes === 'string'
|
|
907
|
-
? attributes
|
|
908
|
-
: Object.entries(attributes)
|
|
909
|
-
.filter(([, value]) => value != null && value !== false)
|
|
910
|
-
.map(([name, value]) => {
|
|
911
|
-
/**
|
|
912
|
-
* **The name is checked, because escaping the value is only half of it.**
|
|
913
|
-
*
|
|
914
|
-
* The claim this form makes is that it cannot escape the tag it describes, and it could
|
|
915
|
-
* not — but it could add *more attributes inside* that tag, which is just as bad and
|
|
916
|
-
* less obvious: `{ 'a=1 onload': v }` wrote `a="1" onload="v"`, an event handler with a
|
|
917
|
-
* caller-controlled body, and `{ 'a x': v }` wrote two attributes from one entry. A
|
|
918
|
-
* server mapping request data onto attribute names is the case this option exists for.
|
|
919
|
-
*
|
|
920
|
-
* The rule is the HTML attribute-name production, and it is the same set the browser
|
|
921
|
-
* engines reject in `setAttribute` — space, quote, apostrophe, `>`, `/`, `=` and
|
|
922
|
-
* controls (see `tests/browser/spread-names.test.js`, which records that engines accept
|
|
923
|
-
* everything else). So this refuses exactly what the client would refuse, rather than
|
|
924
|
-
* inventing a stricter rule the two halves would then disagree about.
|
|
925
|
-
*/
|
|
926
|
-
if (/[\0-\x20"'>/=\x7f]/.test(name) || name === '')
|
|
927
|
-
throw new TypeError(
|
|
928
|
-
`ssr: \`attributes\` cannot use ${JSON.stringify(name)} as a name — an attribute name may not ` +
|
|
929
|
-
`contain whitespace, a quote, "/", "=" or ">". Written into a tag it would produce more ` +
|
|
930
|
-
`attributes than the one entry describes, and setAttribute refuses it in the browser too.`
|
|
931
|
-
);
|
|
932
|
-
return ` ${name}="${escapeHtml(value === true ? '' : value)}"`;
|
|
933
|
-
})
|
|
934
|
-
.join('');
|
|
935
|
-
|
|
936
|
-
assertRendererIntact();
|
|
937
|
-
|
|
938
|
-
/**
|
|
939
|
-
* The request's URL, applied **here** — after every `await` and immediately before the render.
|
|
940
|
-
*
|
|
941
|
-
* `globalThis.location` is process-global and a request is not. The documented way to render a
|
|
942
|
-
* route used to be to assign to it and then call this, which is safe only until two requests
|
|
943
|
-
* overlap: `renderToString` awaits `import(href)`, and on a module's first import that await
|
|
944
|
-
* yields, so whichever request assigned last won for every render after it. Measured with three
|
|
945
|
-
* concurrent first-time imports, **two of three rendered another request's path** — a page
|
|
946
|
-
* answered with someone else's data, which is the worst thing a server renderer can do.
|
|
947
|
-
*
|
|
948
|
-
* Everything from this line to the end of the render is synchronous, so setting it now and
|
|
949
|
-
* restoring it after cannot interleave with anything.
|
|
950
|
-
*/
|
|
951
|
-
const previousLocation = location === undefined ? undefined : applyLocation(location);
|
|
952
|
-
/**
|
|
953
|
-
* A component setting `document.title` is ordinary — it is how a shell names the page, and what a
|
|
954
|
-
* router's `title` option does. It is also a **process global**, so the value one render produced
|
|
955
|
-
* was left sitting there for the next one to read, and a caller doing the obvious thing
|
|
956
|
-
* (`await renderToString(...)` then `document.title`) got whichever request finished last.
|
|
957
|
-
*
|
|
958
|
-
* Returned on the result instead, exactly as `styles` is — something the render produced belongs
|
|
959
|
-
* to the render — and the global is put back, so a concurrent render cannot see it at all.
|
|
960
|
-
*/
|
|
961
|
-
const previousTitle = globalThis.document.title;
|
|
962
|
-
|
|
963
|
-
/**
|
|
964
|
-
* From here to the end in a `try`, so a render that **throws** still puts the globals back.
|
|
965
|
-
*
|
|
966
|
-
* The first version of this restored them just before returning, which is every path except the
|
|
967
|
-
* one that matters most: a failed render left its URL and its title on the process for every
|
|
968
|
-
* request after it, and a request that fails is followed by others exactly as one that succeeds
|
|
969
|
-
* is. The leak this whole area exists to close, surviving on the error path.
|
|
970
|
-
*/
|
|
971
|
-
const restore = () => {
|
|
972
|
-
globalThis.document.title = previousTitle;
|
|
973
|
-
if (previousLocation !== undefined) restoreLocation(previousLocation);
|
|
974
|
-
/** Always, so a throw cannot leave the next render's stores inert. */
|
|
975
|
-
if (isStatic) setStaticStores(false);
|
|
976
|
-
};
|
|
977
|
-
|
|
978
|
-
/**
|
|
979
|
-
* **Awaited inside the `try`, not returned from it.** `try { return promise } finally` runs the
|
|
980
|
-
* restore when the promise is *created*, not when it settles — so the title and location would go
|
|
981
|
-
* back before the render that reads them had finished. The synchronous branch stays a plain
|
|
982
|
-
* return, so it pays nothing for a hazard it does not have.
|
|
983
|
-
*/
|
|
984
|
-
if (isAsync) {
|
|
985
|
-
try {
|
|
986
|
-
return await renderPageAsync();
|
|
987
|
-
} finally {
|
|
988
|
-
restore();
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
try {
|
|
992
|
-
return renderPage();
|
|
993
|
-
} finally {
|
|
994
|
-
restore();
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
/**
|
|
998
|
-
* The bookkeeping every render starts from, shared so the two page renderers cannot drift on it.
|
|
999
|
-
* It is module-level state, which is why the synchronous render must stay synchronous end to end
|
|
1000
|
-
* and why the asynchronous one takes a turn at a time — see `renderToStringAsync`.
|
|
1001
|
-
*/
|
|
1002
|
-
function beginRender() {
|
|
1003
|
-
renderedTags.clear();
|
|
1004
|
-
renderErrors.length = 0;
|
|
1005
|
-
/** Re-arms the once-per-class hoist rule, which keeps one request's CSS out of another's. */
|
|
1006
|
-
beginHoisting();
|
|
1007
|
-
/** Anything a previous render marked and never emitted must not be adopted by this one. */
|
|
1008
|
-
pendingInstances.clear();
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
function renderPage() {
|
|
1012
|
-
/** Synchronous from here, so the per-render bookkeeping below cannot interleave with another. */
|
|
1013
|
-
beginRender();
|
|
1014
|
-
/**
|
|
1015
|
-
* `children` is what a `<slot>` in the component renders. Without it a component built around a
|
|
1016
|
-
* slot could be server-rendered only empty — the entry tag's contents were the shadow template
|
|
1017
|
-
* and nothing else.
|
|
1018
|
-
*/
|
|
1019
|
-
/**
|
|
1020
|
-
* **`static: true` says this page will not be interactive**, so its stores need not be reactive.
|
|
1021
|
-
* A server render is one shot — subscriptions built during it are never fired afterwards — and on
|
|
1022
|
-
* a component rendering twenty rows the proxy behind `createStore` is the *entire* reactivity
|
|
1023
|
-
* overhead: about 40 µs against a 15 µs baseline, where effects and the scheduler cost nothing
|
|
1024
|
-
* measurable. Turning it off is worth roughly 3x.
|
|
1025
|
-
*
|
|
1026
|
-
* Set here rather than around the whole call so it covers exactly the component tree and not the
|
|
1027
|
-
* module import, and restored in the `finally` below so a throw cannot leave a server rendering
|
|
1028
|
-
* inert pages afterwards. A write to a store while it is on throws in development, naming the
|
|
1029
|
-
* option, rather than silently changing nothing.
|
|
1030
|
-
*/
|
|
1031
|
-
if (isStatic) setStaticStores(true);
|
|
1032
|
-
const entry = renderComponent(tag, attrString, 0, props, children);
|
|
1033
|
-
return finishPage(`${entry.open}${entry.inner}</${tag}>`, /** @type {string} */ (tag), seen);
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
/** The asynchronous page render — the same bookkeeping, an entry component that may wait. */
|
|
1037
|
-
async function renderPageAsync() {
|
|
1038
|
-
beginRender();
|
|
1039
|
-
if (isStatic) setStaticStores(true);
|
|
1040
|
-
/** The entry's closing tag is added here; nested ones get theirs from the scanner. */
|
|
1041
|
-
const entry = await renderComponentAsync(/** @type {string} */ (tag), attrString, 0, props, children);
|
|
1042
|
-
return finishPage(`${entry}</${tag}>`, /** @type {string} */ (tag), seen);
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
/**
|
|
1046
|
-
* Everything after the entry component has rendered: marker cleanup, the collected failures, and
|
|
1047
|
-
* the styles this request is responsible for. Shared, because none of it depends on whether the
|
|
1048
|
-
* render was allowed to wait.
|
|
1049
|
-
*
|
|
1050
|
-
* @param {string} rendered @param {string} tag @param {Set<string>} [seen]
|
|
1051
|
-
*/
|
|
1052
|
-
function finishPage(rendered, tag, seen) {
|
|
1053
|
-
let html = rendered;
|
|
1054
|
-
/**
|
|
1055
|
-
* A marker that was never consumed must not reach the page.
|
|
1056
|
-
*
|
|
1057
|
-
* Everything the scan renders has its marker removed as it renders. Markup the scan does not
|
|
1058
|
-
* read — inside a `<template>` a component wrote itself, or a raw-text element — is never
|
|
1059
|
-
* rendered and so keeps its marker, which would ship an internal attribute to the browser.
|
|
1060
|
-
*/
|
|
1061
|
-
if (pendingInstances.size) html = html.replaceAll(new RegExp(` ${INSTANCE_ATTRIBUTE}="\\d+"`, 'g'), '');
|
|
1062
|
-
|
|
1063
|
-
/**
|
|
1064
|
-
* Thrown once the walk is over rather than at the point of failure, so the message can name
|
|
1065
|
-
* every component that failed instead of only the first — and so core's own isolation still
|
|
1066
|
-
* holds while the render runs.
|
|
1067
|
-
*
|
|
1068
|
-
* Catch it to fall back to a client-rendered shell, which is what `renderToString` throwing
|
|
1069
|
-
* means in React and Vue too. It is never right to ship the empty markup this replaces.
|
|
1070
|
-
*/
|
|
1071
|
-
if (renderErrors.length) {
|
|
1072
|
-
const [first] = renderErrors;
|
|
1073
|
-
const others = renderErrors.length > 1 ? ` (and ${renderErrors.length - 1} more)` : '';
|
|
1074
|
-
throw new Error(
|
|
1075
|
-
`ssr: <${first.tag ?? tag}> threw while rendering${others} — its markup would be empty. ` +
|
|
1076
|
-
`${String(first.error?.message ?? first.error)}`,
|
|
1077
|
-
{ cause: first.error }
|
|
1078
|
-
);
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Escaped on the way out. The caller places this string themselves — typically into a `<style>`
|
|
1082
|
-
* in their page shell — which makes that their render boundary, and handing them CSS that can
|
|
1083
|
-
* close the element is handing them an XSS. The escape is transparent to the CSS parser, so
|
|
1084
|
-
* there is no reason to make it their problem.
|
|
1085
|
-
*/
|
|
1086
|
-
/**
|
|
1087
|
-
* `seen` makes a page of several islands work.
|
|
1088
|
-
*
|
|
1089
|
-
* Each render correctly returns the styles of what *it* rendered, so two islands sharing a
|
|
1090
|
-
* component each carry that component's CSS and the assembled page ships it twice. Carrying one
|
|
1091
|
-
* `Set` across the calls emits each component's styles into the page once, and leaves a single
|
|
1092
|
-
* render — the common case — behaving exactly as before.
|
|
1093
|
-
*/
|
|
1094
|
-
const title = globalThis.document.title;
|
|
1095
|
-
|
|
1096
|
-
const styles = [];
|
|
1097
|
-
for (const rendered of renderedTags) {
|
|
1098
|
-
if (seen?.has(rendered)) continue;
|
|
1099
|
-
seen?.add(rendered);
|
|
1100
|
-
for (const css of hoistedStyles.get(rendered) ?? []) styles.push(css);
|
|
1101
|
-
}
|
|
1102
|
-
return { html, styles: styles.map(escapeStyleText).join('\n'), title };
|
|
1103
|
-
}
|
|
1104
|
-
};
|
|
1105
|
-
|
|
1106
|
-
/**
|
|
1107
|
-
* `hoistedStyles` is **not** re-exported. It is the internal `Map` of light-DOM `@scope` blocks,
|
|
1108
|
-
* keyed by the tag that hoisted them, and `renderToString` already returns the ones belonging to the
|
|
1109
|
-
* page it built as `styles` — which is the whole reason it is keyed rather than flat. Exporting the
|
|
1110
|
-
* raw map put a piece of this package's bookkeeping into its public surface, where nothing used it
|
|
1111
|
-
* and nothing documented it.
|
|
1112
|
-
*/
|
|
1113
|
-
/**
|
|
1114
|
-
* Render a component module to markup.
|
|
1115
|
-
*
|
|
1116
|
-
* @param url Module URL @param {object} [options] The same options `renderToStringAsync` takes
|
|
1117
|
-
* @return `{ html, styles, title }`
|
|
1118
|
-
*/
|
|
1119
|
-
export const renderToString = (url, options) => takeTurn(() => renderModule(url, options, false));
|
|
1120
|
-
|
|
1121
|
-
/**
|
|
1122
|
-
* **One render at a time**, so no render can see another's bookkeeping.
|
|
1123
|
-
*
|
|
1124
|
-
* The per-render state this package keeps — `renderedTags`, `renderErrors`, `pendingInstances`,
|
|
1125
|
-
* `instanceCount`, the hoisting state — is module-level, and being synchronous end to end is what
|
|
1126
|
-
* makes two `renderToString` calls safe against *each other*. An asynchronous render pauses, so
|
|
1127
|
-
* that protection does not hold for it.
|
|
1128
|
-
*
|
|
1129
|
-
* **The turn covers both entry points, and it did not always.** This queue once held only the
|
|
1130
|
-
* asynchronous renders, on the reasoning that `renderToString` "is unaffected and still runs
|
|
1131
|
-
* whenever it likes". It is not: a synchronous render fired *inside* an asynchronous one's
|
|
1132
|
-
* suspension window runs to completion on the shared state, and the async render resumes into the
|
|
1133
|
-
* wreckage. Measured, the async component came back as `<slow-a><template shadowrootmode="open">
|
|
1134
|
-
* </template></slow-a>` — empty — while core reported `render() did nothing, no component is being
|
|
1135
|
-
* set up`, because the setup it was closing had been replaced.
|
|
1136
|
-
*
|
|
1137
|
-
* A server that renders some routes synchronously and others asynchronously is the ordinary case,
|
|
1138
|
-
* so "do not mix them" was never a restriction anyone could keep. `renderModule` is `async` and
|
|
1139
|
-
* every caller already awaits, so taking a turn is invisible to them; when nothing is in flight it
|
|
1140
|
-
* costs one microtask.
|
|
1141
|
-
*
|
|
1142
|
-
* Holding the state per render instead (Node's `AsyncLocalStorage` is the mechanism, measured at
|
|
1143
|
-
* ~220 ns a render) would remove the queue altogether, and is a separate change with its own gate.
|
|
1144
|
-
*/
|
|
1145
|
-
let asyncTurn = Promise.resolve();
|
|
1146
|
-
|
|
1147
|
-
/**
|
|
1148
|
-
* Runs `work` once every render queued before it has settled, failed or not.
|
|
1149
|
-
*
|
|
1150
|
-
* Typed generically rather than left to inference: without the annotation the emitted `.d.ts` said
|
|
1151
|
-
* `Promise<void>` for both entry points, because the wrapper hid `renderModule`'s return. Nothing
|
|
1152
|
-
* about the runtime changed and the consumer typecheck (`tests/consumer/ssrcheck.ts`) is what said
|
|
1153
|
-
* so — a published type is not exercised by any test that only imports.
|
|
1154
|
-
*
|
|
1155
|
-
* @template T
|
|
1156
|
-
* @param {() => Promise<T>} work
|
|
1157
|
-
* @returns {Promise<T>}
|
|
1158
|
-
*/
|
|
1159
|
-
const takeTurn = (work) => {
|
|
1160
|
-
const mine = asyncTurn.then(work);
|
|
1161
|
-
/** The queue must survive a failed render, or one throw stops every later one. */
|
|
1162
|
-
asyncTurn = mine.then(
|
|
1163
|
-
() => undefined,
|
|
1164
|
-
() => undefined
|
|
1165
|
-
);
|
|
1166
|
-
return mine;
|
|
1167
|
-
};
|
|
1168
|
-
|
|
1169
|
-
/**
|
|
1170
|
-
* Render a component module to markup, **awaiting its lifecycle**.
|
|
1171
|
-
*
|
|
1172
|
-
* The difference from `renderToString` is only *when* a render may wait: this one awaits a
|
|
1173
|
-
* component's `connectedCallback` and lets promises settle between frame rounds. That is what an
|
|
1174
|
-
* `async connectedCallback` needs — the synchronous render refuses one, because its markup would be
|
|
1175
|
-
* empty — and what a routed component's first navigation needs to reach the page.
|
|
1176
|
-
*
|
|
1177
|
-
* Everything that decides *what* to emit is shared with `renderToString`, and
|
|
1178
|
-
* `tests/ssr-async-parity.test.mjs` renders every fixture through both and compares.
|
|
1179
|
-
*
|
|
1180
|
-
* Asynchronous renders take a turn each; see above.
|
|
1181
|
-
*
|
|
1182
|
-
* @param url Module URL @param {object} [options] The same options `renderToString` takes
|
|
1183
|
-
* @return `{ html, styles, title }`
|
|
1184
|
-
*/
|
|
1185
|
-
export const renderToStringAsync = (url, options) => takeTurn(() => renderModule(url, options, true));
|
|
1186
|
-
|
|
1187
|
-
export { registry, serializeTemplate };
|