@verajs/ssr 0.1.4 → 0.2.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
@@ -3,25 +3,406 @@
3
3
  Vera-native server-side rendering. Node-only, plain ESM, **zero dependencies** — no wcc, no lit,
4
4
  no acorn, no parse5.
5
5
 
6
- import { renderToString } from '@verajs/ssr'; // ('/vera' also works)
7
- const { html, styles } = await renderToString(new URL('./components/app.js', import.meta.url));
6
+ Nested components are found by walking the emitted markup for tags the registry knows. The walk is
7
+ state-aware, not a regex: it respects quoted attribute values (a `>` is legal inside one), and it
8
+ leaves the contents of comments, `<script>`, `<style>`, `<textarea>` and `<title>` alone, because
9
+ those are text and a scan for elements has no business reading them.
10
+
11
+ import { renderToString } from '@verajs/ssr';
12
+ const { html, styles, title } = await renderToString(new URL('./components/app.js', import.meta.url), {
13
+ attributes: { 'user-id': id }, // an object — values are escaped
14
+ props: { rows }, // structured data; an attribute can only carry a string
15
+ children: '<p>slotted</p>', // what a <slot> in the component renders
16
+ location: request.url, // this request's URL — see below
17
+ seen, // a Set carried across renders — see below
18
+ });
19
+
20
+ `title` is `document.title` as that render left it — a component setting it is how a shell names its
21
+ page — and it is **returned rather than left on the global**, for the same reason `location` is
22
+ passed rather than assigned: a process global cannot belong to one request. The document's own title
23
+ is restored afterwards, so a concurrent render never sees it.
24
+
25
+ For a shell assembled from several islands, carry one `Set` through every call. Each render returns
26
+ the styles of what *it* rendered, so two islands sharing a component would otherwise each carry that
27
+ component's CSS and the page would ship it twice.
28
+
29
+ **Pass `location` rather than assigning to `globalThis.location`.** A component that reads the URL —
30
+ any routed shell does — needs the request's, and `globalThis.location` is process-global while a
31
+ request is not. Assigning to it and then calling `renderToString` is safe only until two requests
32
+ overlap: the call awaits `import()`, and on a module's first import that await yields, so whichever
33
+ request assigned last wins for every render after it. Measured with three concurrent first-time
34
+ imports, **two of three rendered another request's path**. The option applies the URL after every
35
+ await and restores it afterwards, in a stretch that is synchronous end to end and therefore cannot
36
+ interleave. A path or a full URL both work.
37
+
38
+ **`children`, and the string form of `attributes`, are raw markup.** Both are written through
39
+ untouched — that is what they are for — so neither may carry anything from a request without being
40
+ sanitized first. Everything else is checked at the render boundary: the object form of
41
+ `attributes` cannot escape the tag it describes **and cannot add a second attribute inside it** — a
42
+ name carrying a space, a quote, `/`, `=` or `>` is refused, which is the same set `setAttribute`
43
+ refuses in the browser — and every interpolated value in a template is escaped as it is written. A
44
+ `__proto__` key in `props` is skipped rather than assigned, so handing the option a parsed request
45
+ body cannot replace the component's prototype. Reach for the string form of `attributes` only when you must produce markup an object cannot
46
+ describe.
8
47
 
9
48
  - Node resolves the component's module graph natively (the `.ts`-via-`.js` convention included);
10
49
  execution registers classes through `customElements.define` — no AST walking.
50
+ - **The lifecycle runs the way it does in a browser.** `attributeChangedCallback` fires on upgrade
51
+ for every present observed attribute and again on every later change; there is no animation frame
52
+ to wait for — frames are queued and drained once `connectedCallback` returns, and again for
53
+ whatever those schedule, so a re-render and every `useEffect` land before the markup is
54
+ serialized, coalesced exactly as a browser coalesces them. An endless animation loop is bounded
55
+ rather than run forever. `tests/lifecycle-parity.test.mjs` renders each case on both sides and
56
+ compares the DOM.
57
+ - **A failure during a render rejects — it is never markup.** Core isolates a hook error so one bad
58
+ effect cannot take out the hooks beside it, which is right in a browser because the next render
59
+ can recover. There is no next render here, so `renderToString` collects those failures and throws,
60
+ naming the component. Catch it to fall back to a client-rendered shell, as you would with React or
61
+ Vue.
62
+ - **`renderToStringAsync` awaits the component's lifecycle.** `renderToString` is synchronous end to
63
+ end, so an `async connectedCallback` is refused — its markup would be empty, and saying so beats
64
+ shipping it. `renderToStringAsync` waits: for the callback, and for promises to settle between
65
+ frame rounds. That is what a component loading data needs, and what puts **a routed component's
66
+ first view in the first response** rather than only after hydration.
67
+
68
+ Everything that decides *what* to emit is shared with `renderToString` — the scanner, the
69
+ serializer, the instance preparation, the page assembly — and
70
+ `tests/ssr-async-parity.test.mjs` renders every fixture through both and compares. The scan itself
71
+ stays synchronous in both: a component tag becomes a placeholder and its render a promise, and the
72
+ placeholders are substituted once everything settles. Awaiting inside the scan would have meant a
73
+ second copy of the parser, and an async recursion measures 2.45x even when nothing suspends —
74
+ which the synchronous path is not going to pay for a feature it never uses.
75
+
76
+ **Asynchronous renders take a turn each.** The per-render bookkeeping is module-level, and being
77
+ synchronous end to end is what makes concurrent `renderToString` calls safe; a render that pauses
78
+ does not have that protection, so two overlapping ones would read each other's. One at a time is
79
+ the version that cannot be wrong — and the turn covers **both** entry points, because a
80
+ synchronous render fired inside an asynchronous one's suspension window would run to completion
81
+ on the shared state and the async render would resume into the wreckage. Every caller already
82
+ awaits, so the turn is invisible; when nothing is in flight it costs one microtask.
83
+
84
+ - **`static: true` renders a page that will not be interactive, about 3x faster.** A server render is
85
+ one shot — the subscriptions built while it runs are never fired afterwards — so tracking every
86
+ property read to create them is pure cost. Measured on a component rendering twenty rows, the proxy
87
+ behind `createStore` is the *entire* reactivity overhead: about 40 µs against a 15 µs baseline,
88
+ where effects and the scheduler cost nothing detectable. With `static` on, `createStore` hands back
89
+ a plain object and reads are ordinary property access.
90
+
91
+ **The markup is identical** — that is the whole safety of it, and it is not asserted on an example:
92
+ `tests/ssr-static-mode.test.mjs` renders *every* fixture in the suite both ways and compares markup,
93
+ styles and title. A mode that cannot drift is why this is a flag rather than a second renderer.
94
+
95
+ **A store written to during a static render throws**, naming the option, rather than rendering
96
+ markup that reflects none of the writes. That guard is *not* development-only, unlike most of this
97
+ framework's diagnostics: a server runs the production build, so folding it away would remove it
98
+ from the only place it matters.
99
+
100
+ - **Events are real, and they propagate** — `EventTarget` semantics on elements, shadow roots,
101
+ `document` and `window`, including `once`, `handleEvent` objects, `event.target` and a
102
+ `dispatchEvent` return value that reflects `preventDefault` — plus the capture, target and bubble
103
+ phases, `stopPropagation`, `stopImmediatePropagation`, `composedPath()`, and a shadow boundary
104
+ crossed only by a `composed` event. Bubbling used to be absent because this DOM held children as a
105
+ string and there was no ancestor chain to walk; children are nodes now, so there is. The walk is
106
+ over the node tree — an event does not continue into `document` or `window`, which are not part of
107
+ it here.
108
+ - **The properties only *some* elements have are there too, and reach the markup.** `input.disabled`,
109
+ `a.href`, `td.colSpan`, `option.selected` — 273 of them across 44 tags, measured from Chromium,
110
+ Firefox and WebKit rather than written from memory (`scripts/measure-element-reflections.mjs`).
111
+ Each tag gets a prototype carrying exactly its own interface, so `'disabled' in paragraph` stays
112
+ `false`: an element answering for members it does not have is the same lie as one missing the
113
+ members it does. Without this layer `button.disabled = true` stored a plain JavaScript property —
114
+ it read back `true`, wrote no attribute, and **served a button that was not disabled** until the
115
+ bundle landed. A property is only in the table when all three engines agree on every measured cell
116
+ *and* reading the attribute back gives what was written, which excludes the ones resolved against a
117
+ document URL (`form.action`), read out of layout (`input.width`) or clamped (`meter.value`); those
118
+ are listed with the measurement that produced each. `value`, `checked` and `selected` are the
119
+ deliberate exception — a browser keeps them off the markup, and on a server the markup is the whole
120
+ output, so they are mirrored exactly as `serializer.js` already mirrors the same three for template
121
+ bindings.
122
+ - **A parsed `<template>`'s content is opaque, and `template.content` is `undefined` here.** The
123
+ element itself is modelled — found by `querySelector`, styled, serialised back byte for byte — and
124
+ a query on the host correctly does not descend into it, which is what a real DOM does too. What is
125
+ missing is reaching INTO one: `template.content.querySelector(…)` answers nothing on the server
126
+ and a fragment in the browser.
127
+ It used to be far worse. Markup containing a `<template>` was refused outright, so the host had no
128
+ nodes at all and EVERY query on it answered emptily — one empty `<template>` turned
129
+ `querySelectorAll('*')` from three elements into none, silently, and cost light-DOM slots their
130
+ whole server render. Keeping the interior opaque, exactly as `<svg>` already was, fixed that.
131
+ Implementing `content` is a contained follow-up if anything needs it: the interior is already
132
+ retained verbatim, so the getter is a lazy `parseFragment` of the string it already holds.
133
+
134
+ - **The server DOM is complete, and checked twice.** Every member a real element, shadow root,
135
+ document, `CSSStyleSheet`, `DOMTokenList` **or window** exposes in Chromium, Firefox and WebKit is
136
+ either implemented or listed as out of scope with a reason — and every member that *is* implemented
137
+ is then compared against a real DOM, member by member, so one that exists and answers differently
138
+ fails too. That second check is the one that earns its keep: enumerating presence found a single
139
+ gap, while comparing behaviour found `tabIndex` defaulting to 0, `draggable` defaulting to true,
140
+ `role` answering `''` where the platform answers `null`, `textContent = null` writing the word
141
+ "null", and a closed shadow root handed straight back. **That comparison checks a member's *shape*
142
+ — the type it answers with — not its answer to every input**, so it is a net rather than a proof:
143
+ an empty array and a full one look the same to it. Three separate classes of defect were found by
144
+ going around it deliberately — passing values nobody would pass (a symbol, where the platform
145
+ throws), checking the members jsdom does not implement at all (which it must skip), and asking
146
+ whether a member that answers *emptily* should have answered at all. The window's ~700 interface constructors are
147
+ covered by a rule rather than a list: every interface this DOM implements is exposed, so
148
+ `instanceof` answers for anything it hands you — the list is checked in (`tests/dom-surface.mjs`, no dependency involved) and
149
+ both halves are enforced, so a gap fails a test instead of a render. That includes the sixty reflected
150
+ properties (`id`, `className`, `hidden`, `tabIndex`, `role`, the whole `aria*` family), which are
151
+ views of an attribute and therefore reach the markup, and `attachInternals()`, so a
152
+ form-associated custom element runs, and the objects those members hand back — `classList`,
153
+ `style`, `dataset` — are held to the same list rather than assumed complete once the property
154
+ exists. `attachShadow({ mode: 'closed' })` behaves as it does in a browser: `element.shadowRoot`
155
+ is `null`, and the root is serialized anyway, because declarative shadow DOM expresses `closed`
156
+ and the client re-creates it just as hidden. **Where the platform throws, this throws** — an
157
+ attribute or tag name that cannot be written, a second `attachShadow` or `attachInternals`, an
158
+ invalid custom-element name, `appendChild` of a non-node. A server that is lenient about an error
159
+ does not make anything work; it moves the failure to the client and strips the context. The
160
+ exceptions are deliberate: **a selector this DOM cannot answer honestly throws** rather than
161
+ answering `null`. It matches type, class, id, every attribute operator, `:not()` and all four
162
+ combinators — descendant, `>`, `+` and `~`. Everything else raises instead of quietly reporting no
163
+ match, for **two different reasons**: `:hover`, `:checked`, `:visible` and `:root` need user state,
164
+ layout or a document a server does not have, while `:first-child`, `:nth-child()`, `:empty`,
165
+ `:first-of-type`, `:is()` and `:has()` are answerable here and simply are not implemented. That
166
+ second group used to be covered by the first reason, which made a limit of this matcher read as a
167
+ property of servers — and predicted, wrongly, that `:first-child` would work;
168
+ **A collection is a plain array**, not a live `NodeList` or `HTMLCollection` — `childNodes`,
169
+ `children`, `querySelectorAll` and the `getElementsBy*` family all answer with one. There is nothing
170
+ to be live *over* while a render is a single pass, and an array is more useful to a caller than a
171
+ collection they have to spread. `item()` and `namedItem()` are provided anyway, because losing them
172
+ was a side effect of that choice rather than part of it: `list.item(0)` is ordinary code, and threw.
173
+ **`checkVisibility()` is always `false`**, since nothing here is laid out and a
174
+ server cannot know what CSS will do, a constructed sheet holds its CSS as **text** rather
175
+ than a parsed rule list — so `cssRules` is empty whatever the sheet contains, which is all the
176
+ markup needs and is why `deleteRule` says so rather than pretending, and `insertAdjacentHTML` with `beforebegin` or
177
+ `afterend` raises a message explaining that a server-rendered component has no parent, which is
178
+ more use than the platform's bare `SyntaxError`. A `style` value is stored as it was
179
+ written rather than re-serialized, so `url("data:…")` keeps its quotes where a browser's CSS
180
+ serializer drops them — equivalent CSS, and a semicolon inside a value does not split the
181
+ declaration, which is what matters for an inline `data:` URI. Layout reads as zero because that is what a
182
+ detached element answers in a browser too. **Names fold the way the platform folds
183
+ them**: an HTML element lower-cases its tag and its attribute names, so `setAttribute('Data-Flag', …)`
184
+ and `getAttribute('data-flag')` are one attribute and an `attributes` entry spelled `User-ID`
185
+ still matches an `observedAttributes` entry spelled `user-id`; an element created through
186
+ `createElementNS` outside the HTML namespace keeps its case, so an SVG `viewBox` survives.
187
+ - **A component can build another component.** `document.createElement('my-comp')` constructs the
188
+ registered class, so its field initialisers have run and `instanceof` answers, and appending it
189
+ renders **that instance** — everything the parent assigned to it, `kid.rows = data` included,
190
+ survives. The nested-component scan used to re-create the child from its markup, where an
191
+ attribute is the only thing that can carry a value.
192
+ - **`render()` owns its own range and nothing else**, exactly as it does in a browser. Content
193
+ already in the container stays before the rendered range, a node the component appends to its own
194
+ root stays after it, and both survive every re-render — so a component that mixes `render()` with
195
+ its own `appendChild` produces the same DOM on both sides. It also means `children` reach a
196
+ light-DOM component and are still there after it renders.
197
+ - **A `<select>`'s value is served as `<option selected>`.** And a value matching no option cannot be served —
198
+ see the exception below, which has no fix. A `<select>` has no `value` content attribute — assigning the property *selects an
199
+ option* — so the only thing markup can say is which option is chosen, and that is what the
200
+ serializer writes (React's server renderer does the same; `@lit-labs/ssr` drops the binding and
201
+ serves a control showing its first option). Matching follows the platform: the `value` attribute
202
+ verbatim if an option has one, otherwise the option's text **stripped and collapsed**, first match
203
+ wins, and a `selected` the author wrote is cleared because a property assignment overrides markup.
204
+ All of it is asserted against Chromium, Firefox and WebKit in
205
+ `tests/browser/select-value.test.js`.
206
+
207
+ The exception is real and has no fix. When the value matches **no** option the client leaves
208
+ `selectedIndex` at `-1` with nothing showing, and a parsed `<select>` whose options carry no
209
+ `selected` takes its **first** — there is no markup for "none of them", and inserting a hidden
210
+ placeholder would change the control the author wrote.
211
+
212
+ - **Component nesting is capped at 256 levels, and the client has no such cap.** A component that
213
+ renders itself recurses without bound, which on a server is a hung request rather than a hung tab,
214
+ so `renderToString` refuses past 256 and says so. This is a real divergence, and 256 is chosen to
215
+ sit *below where the client breaks*: the client managed about 340 levels before `RangeError`
216
+ (reported through the `'error'` insert), so the server still fails first and fails with a sentence.
217
+ That ~340 is engine-dependent, which is why the server does not wait for it.
218
+ - **A carriage return survives, as `&#13;` — everywhere except `<style>` and `<script>`.** The HTML
219
+ input-stream preprocessor collapses CR and CRLF to a single LF *before* tokenization, so a raw
220
+ `\r` written into markup does not come back — the server would render `a\r\nb` and the client read
221
+ `a\nb`, which is a silent hydration mismatch on every render of a `<textarea>` value, a CSV cell, or
222
+ any string from a Windows-authored source. Character references are resolved *after* preprocessing,
223
+ so the escaped form does survive; verified identical in Chromium, Firefox and WebKit.
224
+
225
+ **RAWTEXT is the exception, and it is not fixable.** A browser does not decode a character
226
+ reference inside `<style>` or `<script>` — that is what makes them RAWTEXT — so `&#13;` there is
227
+ the literal six characters, while the preprocessor still collapses the raw CR. There is no spelling
228
+ of a carriage return that survives in those two elements. `<title>` and `<textarea>` are RCDATA,
229
+ which *does* decode references, which is why they round-trip correctly. All three behaviours are
230
+ asserted against Chromium, Firefox and WebKit in `tests/browser/rawtext-carriage-return.test.js`.
231
+
232
+ In practice this reaches an interpolated stylesheet or inline script whose source has Windows line
233
+ endings — a repository checked out with `core.autocrlf=true` puts CRLF inside every template
234
+ literal, `css` blocks included. CR and LF are interchangeable whitespace to both CSS and
235
+ JavaScript, so nothing renders wrongly; the two sides simply hold different strings.
236
+ - **Three things cannot survive a server round trip, and are the only three.** Two are characters and
237
+ one is a character in a position — see the carriage return above, which round-trips everywhere
238
+ except inside `<style>` and `<script>`.
239
+ - **NUL** (`\u0000`) is dropped in text, rewritten to U+FFFD in an attribute **and inside
240
+ RAWTEXT**, and `&#0;` is a parse error that also yields U+FFFD. No spelling round-trips, so it is left alone rather than
241
+ silently turned into U+FFFD — that would make the markup lie about what the component rendered
242
+ without making the two sides agree.
243
+ - **A lone surrogate** (`\uD800` with no pair) is not encodable in UTF-8, so the *transport*
244
+ replaces it with U+FFFD — a real HTTP response does exactly what `Buffer.toString('utf8')` does.
245
+ Nothing server-side can prevent that.
246
+
247
+ Both are covered by `tests/ssr-text-boundary.test.mjs`, alongside astral pairs, combining marks,
248
+ bidi controls, noncharacters and 20 other cases that *do* round-trip exactly.
249
+ - **What a component does to itself in `connectedCallback` reaches the markup** — a `setAttribute`,
250
+ an `aria-*`, a class, a reflected property.
251
+ - **`<style>` and `<script>` content is written raw**, and their own end tags are neutralised
252
+ (`<\/style`, `<\/script` — valid CSS and JavaScript, invisible to the tokenizer). A browser does
253
+ not decode a character reference inside either, so escaping there protects nothing and corrupts
254
+ the content: an interpolated `.a > .b` used to serve `.a &#62; .b`, a selector matching nothing,
255
+ while the client rendered it correctly. `<title>` and `<textarea>` are RCDATA rather than RAWTEXT
256
+ — references *are* decoded there — so those keep ordinary escaping, which is also what the client
257
+ produces for them.
11
258
  - Templates flatten through a sigil-aware serializer with per-template-identity plan caching:
12
- `?bool` resolved by truthiness, `.value`/`.checked`/`.selected` mirrored to attributes,
13
- `@event`/`&ref` stripped without residue, every interpolated value escaped at the boundary.
259
+ `?bool` resolved by truthiness, `.value`/`.checked`/`.selected` mirrored to attributes on form
260
+ controls, `@event`/`&ref` stripped without residue, every interpolated value escaped at the
261
+ boundary.
262
+ - **A property bound on a rendered component tag is DELIVERED, not dropped**: written
263
+ (`<props-row .item=${row}>`) or spread (`props({ item })`), the value reaches the instance the
264
+ nested-component scan renders — by identity, before its lifecycle, exactly where
265
+ `renderToString`'s own `props` option puts the entry component's. The markup never changes (a
266
+ property is not an attribute), so the child's server output comes from the same data its client
267
+ render will get, which is the hydration contract. An **unregistered** dashed tag passes through
268
+ untouched — its properties stay the client's to apply. Values that cannot exist server-side
269
+ (a DOM node, a callback into browser state) are the component's to guard, as in every SSR
270
+ framework.
14
271
  - Output is declarative shadow DOM with **zero framework comments**; light-DOM `@scope` styles are
15
272
  returned separately for the page shell.
16
273
  - Client-side, `@verajs/renderer/hydrate` adopts the server DOM markerlessly (swap one import).
17
- - Measured (bench/ssr.mjs, fastest-of-7 rotated): serializer 73 µs / full component pipeline
18
- 107 µs on a 100-row table — ahead of or within 9% of Vue's compiled SSR, 5x lit, 8x React.
274
+ - Measured (`node bench/ssr.mjs`, fastest of 7 rounds), against lit on both comparisons it
275
+ supports — µs per render, small component / 100-row table:
276
+
277
+ | | small | table |
278
+ | --- | --- | --- |
279
+ | **template serialization** — `serializeTemplate` vs `@lit-labs/ssr` on a template | **0.3** | **35** |
280
+ | | lit 2.4 | lit 312 |
281
+ | **whole component** — `renderToString` vs a real `LitElement` | **4.3** | **49** |
282
+ | | lit 5.7 | lit 414 |
283
+
284
+ Vue's compiled SSR is 7.9 / 61 µs and React 6.2 / 453 µs, neither of which renders a
285
+ component. The `lit element` row runs in a separate process because `@lit-labs/ssr` and this
286
+ package both install DOM globals and cannot share one.
287
+ - **Most of a component render is core's lifecycle, not this package.** Rendering the same component
288
+ with its `connectedCallback` emptied — which removes core's `init`, store, hooks and re-render and
289
+ leaves the shim, the serializer and the nested scan — costs **1.0 µs of a 6.4 µs render**, so
290
+ everything this package does is about a sixth of it and the component's own lifecycle is the rest.
291
+ (Those two figures come from a plain `await` loop rather than `bench/ssr.mjs`'s batched rounds, so
292
+ they are higher than the table above and only their *ratio* is comparable.)
19
293
 
20
- `examples/ssr-node/server-native.mjs` is a complete server on bare `node:http`.
294
+ `examples/ssr-node/server-native.mjs` is a complete server on bare `node:http`, serving the whole
295
+ round trip — the page it returns ships a client module that imports `@verajs/renderer/hydrate` and
296
+ adopts the markup in place.
21
297
 
22
- Import `@verajs/ssr` before anything that imports `@verajs/core` — it installs the server
23
- environment first. Known limits: effects run server-side (guard browser-only work);
24
- `keyed`/`hold` are client constructs (use plain `.map` in SSR templates).
298
+ **No streaming.** `renderToString` returns a string, where `@lit-labs/ssr` yields a stream. That
299
+ buys time-to-first-byte in proportion to how long a render takes, and a 100-row table here is 47 µs
300
+ — the response is built before a streaming implementation would have flushed its first chunk. It is
301
+ a real difference in shape, and worth revisiting for a page big enough that it stops being one.
302
+
303
+ **Importing `@verajs/ssr` installs a DOM on `globalThis`.** That is what it is for, and it means the
304
+ import is not passive: `document`, `customElements`, `HTMLElement` and the rest are *replaced*, so a
305
+ process that already has a DOM — jsdom in a test, say — loses it the moment this module is loaded,
306
+ however late. A component defined afterwards is never upgraded and nothing says why. **Exercise both
307
+ sides in separate processes**, which is what this repo's own tests do; `tests/lifecycle-parity.test.mjs`
308
+ renders the server half in a subprocess for exactly this reason.
309
+
310
+ **And import it first**, before anything that imports `@verajs/renderer`.
311
+
312
+ The module that actually needs the shims is the renderer, not core: it builds two shared
313
+ `TreeWalker`s at import time, so importing it against a bare Node global object throws before your
314
+ component ever runs. A component reaches it through `keyed` or `hold`, which is why the rule reads
315
+ as "import this first" — measured, core, `@verajs/styles` and `@verajs/router` are all order-
316
+ independent, and only `@verajs/renderer` is not.
317
+
318
+ **The entry component is found by matching the module's exports against the registry**, so export
319
+ the class (`export default class …`) or pass `{ tag }`. It used to guess by diffing the registry
320
+ around the import, which two concurrent renders could not share: both saw both modules' new
321
+ registrations, and a request could be answered with another component's markup.
322
+
323
+ `renderToString` executes the module you name, so **pass `base` whenever any part of the URL came
324
+ from a request**:
325
+
326
+ renderToString(new URL(`${page}.js`, components), { base: components });
327
+
328
+ Anything resolving outside it is refused. `new URL` applies `../` before `renderToString` sees the
329
+ string, so without this the traversal has already happened by the time the call is made — and
330
+ mapping a route to a component file is the obvious way to use a server renderer. Same containment,
331
+ and the same wording, as `@verajs/autoloader` uses for the URLs it derives.
332
+
333
+ It is opt-in because most calls name a constant, and a check that is always trivially satisfied
334
+ stops being read.
335
+
336
+ The globals a component reaches for are here too — `matchMedia` (matching nothing, as every server
337
+ renderer answers), `getComputedStyle` (empty, as a detached element gives in a browser),
338
+ `IntersectionObserver`/`ResizeObserver`/`MutationObserver`/`PerformanceObserver` (inert, because
339
+ they observe things a server does not have, but constructing one must not throw), `requestIdleCallback`
340
+ (which joins the frame queue), and the DOM interfaces themselves so `instanceof Node` answers rather
341
+ than throwing.
342
+
343
+ **`localStorage`, `sessionStorage`, `indexedDB` and `caches` are deliberately absent.** They are one
344
+ browser's state, and a server that invented an empty one would render a logged-out shell that the
345
+ client immediately replaces, with nothing failing anywhere. `typeof localStorage === 'undefined'` is
346
+ the guard the ecosystem already writes, and it only works if this does not lie. The same list is
347
+ enforced in `tests/ssr-dom-surface.test.mjs`, in both directions.
348
+
349
+ Known limits:
350
+
351
+ - **`connectedCallback` must be synchronous.** Rendering recurses inside `String.replace`, which
352
+ cannot await, so an `async connectedCallback` is refused with an error rather than rendered empty.
353
+ Load data before `renderToString` and pass it in as attributes.
354
+ - **`useLayoutEffect` runs, but too late to reach the template it sits beside.** It is coalesced on
355
+ a microtask, and `renderToString` is asynchronous, so it *does* execute — a `setAttribute` or an
356
+ API call inside one happens on the server, which is worth knowing before you put one there. What
357
+ it cannot do is change what the template already rendered: state settled in a layout effect is not
358
+ in the markup. Settle it before `render()`, or use `useEffect`, whose frame is drained repeatedly
359
+ and does reach the markup. `tests/lifecycle-parity.test.mjs` pins both halves of that.
360
+ - `keyed`/`hold` are client constructs; use plain `.map` in SSR templates.
361
+ - **A routed component renders its shell, not its route.** `initRouter` works server-side — the
362
+ shim provides enough `window` for it — so the nav and the `[view]` outlet reach the markup and the
363
+ client fills the outlet on hydration. The route's own content does not, **for the same reason an
364
+ `async connectedCallback` is refused**: rendering is synchronous end to end and `navigate` is
365
+ `async`. The initial navigation is scheduled on a frame, the frame runs, `navigate` is called and
366
+ returns a promise — and the markup is serialized before that promise settles, so the component
367
+ behind the route is never called. The outlet itself *is* found, and awaiting `navigate` outside a
368
+ render works. Render the route yourself and pass it as `children` if it has to be in the first
369
+ response.
370
+ - **A dynamic attribute *name* is refused.** `<b ${name}="x">` is malformed on both sides: the
371
+ client hands the template to the platform's parser and a marker is not a name, and this serializer
372
+ used to emit `<b="x">`, which is not an attribute either. Rather than write markup no browser would
373
+ produce, it throws and names the alternative — `@verajs/renderer/spread`, which exists for names
374
+ that are not known until runtime and which this serializer understands.
375
+ - **`slotAssignment` cannot be server-rendered.** Declarative shadow DOM can express `mode`,
376
+ `delegatesFocus`, `clonable` and `serializable` — all of which are serialized — but has no form
377
+ for manual slot assignment, and `attachShadow` **ignores the options it is handed** when it reuses
378
+ a declarative root, so the client cannot repair what the markup left out.
379
+ - A function interpolated at a text position renders as nothing here and as its source on the
380
+ client — put functions in `@event` bindings, where both sides drop them.
25
381
 
26
382
  The pre-native strategies (wcc fork, lit-labs renderer, Astro sketch, Reef-era diff renderer)
27
383
  are retired; strategy 4 is the only one shipped.
384
+
385
+ ## Also exported
386
+
387
+ `registry` is the `Map` of tag → class this process has seen through `customElements.define`, and
388
+ `serializeTemplate` is the sigil-aware template flattener — the two seams an advanced integration
389
+ (a custom scanner, a fixture builder) reaches for. Everything an ordinary server needs is
390
+ `renderToString` / `renderToStringAsync`; these are listed so their presence is a decision rather
391
+ than an accident.
392
+
393
+ ```js
394
+ import { renderToString, renderToStringAsync, registry, serializeTemplate } from '@verajs/ssr';
395
+
396
+ const { html: markup } = await renderToString(new URL('./components/app.js', import.meta.url));
397
+ const page = await renderToStringAsync(entry); // same signature, awaits async lifecycles
398
+
399
+ registry.has('app-shell'); // true once the component module has run
400
+ const fragment = serializeTemplate(html`<p>${x}</p>`); // one template to markup, no component scan
401
+ ```
402
+
403
+ ## For AI assistants — and anyone who wants the whole API on one page
404
+
405
+ The repository root's [`llms.txt`](../../llms.txt) is the complete, hand-maintained API
406
+ reference for every package, written to be pasted into a model's context window: full export
407
+ tables, the buildless CDN and JSX recipes, semantics that differ from other frameworks, and the
408
+ mistakes that come up most. Its recipes are executed by the test suite, so they stay honest.
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@verajs/ssr",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
4
4
  "description": "Vera-native server-side rendering. Node-only, plain ESM, zero dependencies.",
5
5
  "license": "MIT",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
6
9
  "repository": {
7
10
  "type": "git",
8
11
  "url": "git+https://github.com/vera-js/vera.git",
@@ -13,11 +16,18 @@
13
16
  "type": "module",
14
17
  "main": "./src/vera/index.js",
15
18
  "exports": {
16
- ".": "./src/vera/index.js",
17
- "./vera": "./src/vera/index.js"
19
+ ".": {
20
+ "types": "./types/index.d.ts",
21
+ "default": "./src/vera/index.js"
22
+ }
23
+ },
24
+ "peerDependencies": {
25
+ "@verajs/core": "^0.3.1",
26
+ "@verajs/styles": "^0.1.2"
18
27
  },
19
28
  "files": [
20
- "src"
29
+ "src",
30
+ "types"
21
31
  ],
22
32
  "keywords": [
23
33
  "ssr",
@@ -29,5 +39,28 @@
29
39
  ],
30
40
  "publishConfig": {
31
41
  "access": "public"
42
+ },
43
+ "types": "./types/index.d.ts",
44
+ "scripts": {
45
+ "build": "wireit"
46
+ },
47
+ "wireit": {
48
+ "build": {
49
+ "dependencies": [
50
+ "../core:build",
51
+ "../styles:build"
52
+ ],
53
+ "command": "npx tsc -p tsconfig.json --noEmit false --declaration --emitDeclarationOnly --rootDir src/vera --outDir types",
54
+ "clean": "if-file-deleted",
55
+ "files": [
56
+ "src/**/*.js",
57
+ "tsconfig.json",
58
+ "../../tsconfig.json",
59
+ "../tsconfig/base.json"
60
+ ],
61
+ "output": [
62
+ "types/**/*.d.ts"
63
+ ]
64
+ }
32
65
  }
33
66
  }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Escaping at the render boundary, and the elements that must not be escaped at all.
3
+ *
4
+ * One place decides what becomes a character reference, because escaping in two places
5
+ * double-escapes and escaping in none is an injection. `<style>`, `<script>`, `<textarea>` and
6
+ * `<title>` hold **text**, not markup: a browser does not decode a character reference inside them,
7
+ * so escaping there does not protect anything and does corrupt the content — a `static styles` with
8
+ * `.a > .b` shipped a broken stylesheet until that was understood.
9
+ */
10
+
11
+ const NEEDS_ESCAPE = /[&<>"'\r]/;
12
+
13
+ const ESCAPE = /[&<>"'\r]/g;
14
+
15
+ /**
16
+ * Escaping is the hottest thing in a large render, and most values have nothing to escape.
17
+ *
18
+ * Asking first is worth it: 200 escapes of ordinary text measured 9.60 µs going straight to
19
+ * `replace` against 3.03 µs testing first — and text that *does* need escaping came out slightly
20
+ * ahead too (21.73 vs 20.03), because a global `replace` sets up more than a single `test` does. On
21
+ * a 100-row table of clean data that is a quarter of the whole render.
22
+ */
23
+
24
+ /**
25
+ * **Carriage return is here for correctness, not for safety.**
26
+ *
27
+ * The HTML input-stream preprocessor rewrites CR and CRLF to a single LF *before* tokenization, so a
28
+ * raw `\r` written into markup does not survive being parsed — the server renders `a\r\nb` and the
29
+ * client reads back `a\nb`. Nothing is injected and nothing looks wrong; the two sides simply hold
30
+ * different strings, which is a hydration mismatch on every render of anything carrying a Windows
31
+ * newline: a `<textarea>` value, a CSV cell, a string from an HTTP payload.
32
+ *
33
+ * Character references are resolved *after* preprocessing, so `&#13;` does survive. **Verified in
34
+ * Chromium, Firefox and WebKit**, all three identical: raw CRLF parses to `[97, 10, 98]` and
35
+ * `a&#13;\nb` parses to `[97, 13, 10, 98]`, in text and in attribute values alike.
36
+ *
37
+ * **NUL is the other character the preprocessor rewrites, and it is not fixable here.** A raw NUL is
38
+ * dropped in text and becomes U+FFFD in an attribute, and `&#0;` is a parse error that also becomes
39
+ * U+FFFD — there is no spelling that round-trips, so a string containing NUL cannot be server
40
+ * rendered faithfully by anyone. It is listed as a limitation in the README rather than silently
41
+ * transformed here, because turning it into U+FFFD would make the markup lie about what the
42
+ * component rendered without making the two sides agree.
43
+ *
44
+ * Precomputed, because building `'&#' + c.charCodeAt(0) + ';'` per character is the slow half.
45
+ */
46
+ const ESCAPED = { '&': '&#38;', '<': '&#60;', '>': '&#62;', '"': '&#34;', "'": '&#39;', '\r': '&#13;' };
47
+
48
+ export const escapeHtml = (value) => {
49
+ /**
50
+ * `` `${value}` `` rather than `String(value)`: identical for everything except a **symbol**,
51
+ * which `String` special-cases into its description while every DOM conversion on the client
52
+ * throws. Serving `Symbol(s)` into markup the client cannot reproduce is the leniency this
53
+ * package's README warns about — it does not make anything work, it moves the failure across the
54
+ * boundary and strips the context.
55
+ */
56
+ const text = typeof value === 'string' ? value : `${value}`;
57
+ return NEEDS_ESCAPE.test(text) ? text.replace(ESCAPE, (character) => ESCAPED[character]) : text;
58
+ };
59
+
60
+ /**
61
+ * Neutralise a `</style>` sequence inside CSS text.
62
+ *
63
+ * `<style>` is a raw-text element: its content is not HTML, so `escapeHtml` cannot be used here —
64
+ * it would turn every `>` in a selector into `&#62;` and break the stylesheet. The only sequence
65
+ * that matters is the end tag, because it is the one thing the HTML tokenizer looks for while
66
+ * inside the element. A value interpolated into `css` and carrying `</style>` therefore closes the
67
+ * element and everything after it parses as markup.
68
+ *
69
+ * `<\/style` is valid CSS — a backslash escape is legal in identifiers and strings, and renders
70
+ * identically — while the tokenizer no longer matches an end tag. Applied here, at the render
71
+ * boundary, rather than in `css` itself: escaping at the source would corrupt the constructed
72
+ * stylesheet path, which is the double-escaping principle #8 warns about. It also catches a
73
+ * sequence assembled across several interpolations, which source-side escaping cannot see.
74
+ *
75
+ * **Deliberately duplicated** in `@verajs/styles` (`escapeStyleText` there is the same three
76
+ * lines). It cannot be shared: the obvious home is `@verajs/shared-utils`, which is private and
77
+ * inlined at build time, and `@verajs/ssr` publishes its `src` with **no dependencies at all** — an
78
+ * import of a package that is never published would break the published tarball. Two copies of a
79
+ * security rule is a real risk, so `tests/ssr-escaping.test.mjs` asserts the two agree on the
80
+ * payloads that matter rather than trusting they will be edited together.
81
+ */
82
+ export const escapeStyleText = (value) => `${value}`.replace(/<\/(style)/gi, '<\\/$1');
83
+
84
+ /**
85
+ * The same neutralisation, for whichever RAWTEXT element the value landed in.
86
+ *
87
+ * `<style>` and `<script>` are the only two: a browser does not decode a character reference inside
88
+ * either, so escaping their content protects nothing and corrupts it. Interpolating `.a > .b` into a
89
+ * stylesheet produced `.a &#62; .b` — a selector matching nothing — while the client, which sets
90
+ * text through the DOM and never re-parses, rendered it correctly. Every interpolated stylesheet was
91
+ * broken on the server and right in the browser.
92
+ *
93
+ * Writing raw means the element's own end tag has to come out of the value instead, or it closes the
94
+ * element and everything after it parses as markup. `<\/style` is valid CSS and `<\/script` is the
95
+ * canonical form in JavaScript; both render identically and neither is seen by the tokenizer. Only
96
+ * the end tag matters, because it is the only sequence the tokenizer looks for while inside.
97
+ *
98
+ * `<title>` and `<textarea>` are **RCDATA** — references *are* decoded there — so they keep ordinary
99
+ * escaping, which is also what the client produces for them.
100
+ */
101
+ const RAW_TEXT_CLOSERS = { style: /<\/(style)/gi, script: /<\/(script)/gi };
102
+
103
+ export const escapeRawText = (value, tag) => {
104
+ const closer = RAW_TEXT_CLOSERS[tag];
105
+ return closer ? `${value}`.replace(closer, '<\\/$1') : escapeHtml(value);
106
+ };
107
+
108
+ /**
109
+ * Elements whose content is text rather than markup. Setting `textContent` on one of these stores
110
+ * the text as written: inside `<style>` or `<script>` a character reference is **not** decoded, so
111
+ * escaping there does not protect anything and does corrupt the content.
112
+ */
113
+ /**
114
+ * Elements a parser reads the children of as text.
115
+ *
116
+ * `iframe` and `noscript` were absent, so this DOM built a tree no browser builds:
117
+ * `<noscript><img src="x"></noscript>` parsed to an element here and `querySelectorAll('noscript img')`
118
+ * answered **1** where every engine answers 0, because the content is a text node.
119
+ *
120
+ * Measured across Chromium, Firefox and WebKit rather than read off a spec — and jsdom is not the
121
+ * oracle for this one. It parses with scripting *disabled*, so it agrees with the old list about
122
+ * `noscript` and all three real engines disagree with both.
123
+ */
124
+ export const RAW_TEXT_ELEMENTS = new Set(['style', 'script', 'textarea', 'title', 'iframe', 'noscript']);
125
+
126
+ /**
127
+ * Elements that have no end tag. Writing one is not merely redundant — a parser reads `</br>` as
128
+ * *another* `<br>`, so `appendChild(createElement('br'))` served `<br></br>` and rendered two line
129
+ * breaks where the client has one. The same content assigned as a markup string was already correct,
130
+ * so the two paths disagreed with each other as well as with the browser.
131
+ */
132
+ export const VOID_ELEMENTS = new Set([
133
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
134
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
135
+ ]);