@verajs/ssr 0.2.0 → 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
@@ -256,8 +256,18 @@ describe.
256
256
  — references *are* decoded there — so those keep ordinary escaping, which is also what the client
257
257
  produces for them.
258
258
  - Templates flatten through a sigil-aware serializer with per-template-identity plan caching:
259
- `?bool` resolved by truthiness, `.value`/`.checked`/`.selected` mirrored to attributes,
260
- `@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.
261
271
  - Output is declarative shadow DOM with **zero framework comments**; light-DOM `@scope` styles are
262
272
  returned separately for the page shell.
263
273
  - Client-side, `@verajs/renderer/hydrate` adopts the server DOM markerlessly (swap one import).
@@ -380,6 +390,16 @@ are retired; strategy 4 is the only one shipped.
380
390
  `renderToString` / `renderToStringAsync`; these are listed so their presence is a decision rather
381
391
  than an accident.
382
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
+
383
403
  ## For AI assistants — and anyone who wants the whole API on one page
384
404
 
385
405
  The repository root's [`llms.txt`](../../llms.txt) is the complete, hand-maintained API
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verajs/ssr",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Vera-native server-side rendering. Node-only, plain ESM, zero dependencies.",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -22,8 +22,8 @@
22
22
  }
23
23
  },
24
24
  "peerDependencies": {
25
- "@verajs/core": "^0.3.0",
26
- "@verajs/styles": "^0.1.1"
25
+ "@verajs/core": "^0.3.1",
26
+ "@verajs/styles": "^0.1.2"
27
27
  },
28
28
  "files": [
29
29
  "src",
package/src/vera/index.js CHANGED
@@ -486,7 +486,23 @@ const buildInstance = (tag, attrString) => {
486
486
  }
487
487
  }
488
488
  const pending = pendingInstances.get(element.getAttribute(INSTANCE_ATTRIBUTE));
489
- return pending && pending.localName === tag ? pending : element;
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;
490
506
  };
491
507
 
492
508
  const renderComponent = (tag, attrString, depth, props, children) =>
package/src/vera/nodes.js CHANGED
@@ -635,10 +635,7 @@ export class ContainerShim extends EventTarget {
635
635
  * A registered component that has not rendered is marked, so the scan over this markup renders
636
636
  * this instance instead of a new one built from the tag it wrote. See `pendingInstances`.
637
637
  */
638
- if (node?.openTag && registry.has(node.localName) && !node._rendered) {
639
- node.setAttribute(INSTANCE_ATTRIBUTE, String(++instanceCount));
640
- pendingInstances.set(String(instanceCount), node);
641
- }
638
+ if (node?.openTag && registry.has(node.localName) && !node._rendered) markPending(node);
642
639
  /**
643
640
  * **A node cannot contain itself.** Retaining nodes makes this reachable where inlining markup
644
641
  * never could: appending an ancestor into its own descendant would recurse forever the next
@@ -1769,6 +1766,17 @@ export class ElementShim extends ContainerShim {
1769
1766
  get style() {
1770
1767
  return styleView(this);
1771
1768
  }
1769
+ /**
1770
+ * The platform's `style` is `[SameObject, PutForwards=cssText]` — `el.style = 'color: red'`
1771
+ * assigns THROUGH to `cssText` in every engine (and in jsdom, the regression net). The shim
1772
+ * declared only the getter, so the ordinary spelling threw `Cannot set property` server-side:
1773
+ * a component-prop delivery of `.style` was refused as read-only while the client accepted and
1774
+ * reflected it — the exact server/client divergence the differential rule exists to catch.
1775
+ * `[LegacyNullToEmptyString]` rides the same IDL attribute, so `null` means `''`.
1776
+ */
1777
+ set style(value) {
1778
+ /** @type {{ cssText: string }} */ (styleView(this)).cssText = value === null ? '' : `${value}`;
1779
+ }
1772
1780
  removeAttribute(name) {
1773
1781
  name = this._name(name);
1774
1782
  if (!this._attributes.has(name)) return;
@@ -2251,6 +2259,22 @@ export const INSTANCE_ATTRIBUTE = `vera-ssr-${crypto.randomUUID()}`;
2251
2259
 
2252
2260
  let instanceCount = 0;
2253
2261
 
2262
+ /**
2263
+ * Marks `node` as a prepared instance and returns its id, so the nested-component scan renders THIS
2264
+ * instance rather than a fresh copy built from its markup. Two callers, one discipline:
2265
+ * `appendChild` below, for an element a component built itself, and the template serializer, for a
2266
+ * component tag whose property bindings it is delivering — both stamp the node (so `prepareInstance`
2267
+ * can unregister it by the attribute) and both rely on the unguessable name above.
2268
+ *
2269
+ * @param {any} node @returns {string} the instance id, for the caller that writes markup itself
2270
+ */
2271
+ export const markPending = (node) => {
2272
+ const id = String(++instanceCount);
2273
+ node.setAttribute(INSTANCE_ATTRIBUTE, id);
2274
+ pendingInstances.set(id, node);
2275
+ return id;
2276
+ };
2277
+
2254
2278
  /** One `ElementInternals` per element, as `attachInternals` guarantees. */
2255
2279
  const internals = new WeakMap();
2256
2280
 
@@ -1,11 +1,15 @@
1
1
  import { escapeHtml, escapeRawText } from './shim.js';
2
+ import { registry } from './registry.js';
3
+ import { INSTANCE_ATTRIBUTE, markPending } from './nodes.js';
2
4
 
3
5
  /**
4
6
  * The vera-native template serializer: flattens core's `html` template objects to markup with
5
7
  * the renderer's sigil semantics applied server-side.
6
8
  *
7
9
  * `?bool=${x}` -> `bool=""` when truthy, nothing when falsy
8
- * `.prop=${x}` -> mirrored to an attribute for form state (value/checked/selected), else dropped
10
+ * `.prop=${x}` -> on a rendered COMPONENT tag, delivered to the instance the nested scan
11
+ * renders (by identity, never markup); on a form control, mirrored to an
12
+ * attribute (value/checked/selected); else dropped
9
13
  * `@event=${fn}` -> dropped (behavior is the client's job)
10
14
  * `&ref=${r}` -> dropped
11
15
  * `attr=${x}` -> quoted, escaped
@@ -98,10 +102,75 @@ const BOOLEAN = 1;
98
102
  const FORM_PROP = 2;
99
103
  const DROPPED = 3;
100
104
  const ATTRIBUTE = 4;
105
+ /** `.prop` on a component tag: delivered to the instance the scan will render, never markup. */
106
+ const COMPONENT_PROP = 5;
101
107
 
102
108
  /** strings identity -> { parts, kinds, names } — computed once per call site, ever. */
103
109
  const plans = new WeakMap();
104
110
 
111
+ /**
112
+ * Gets-or-creates the instance a component-prop slot delivers to, per application state (see
113
+ * `adoption` in `serializeTemplate`). A new instance is registered exactly as `appendChild`
114
+ * registers a component-built child, and its marker text is queued on `state.mark` for the caller
115
+ * to write into the open tag being emitted — the string boundary is crossed by the marker while
116
+ * the values stay on the node, by identity. `prepareInstance` unregisters and unstamps it as it
117
+ * renders, and the end-of-render sweep removes any marker whose tag never rendered.
118
+ */
119
+ const claimInstance = (state, ordinal, tag) => {
120
+ let node = state.instances.get(ordinal);
121
+ if (node === undefined) {
122
+ node = new (registry.get(tag))();
123
+ node.localName = tag;
124
+ state.mark += ` ${INSTANCE_ATTRIBUTE}="${markPending(node)}"`;
125
+ state.instances.set(ordinal, node);
126
+ }
127
+ return node;
128
+ };
129
+
130
+ /**
131
+ * One delivery, shared by the written form and the spread form. `__proto__` is skipped for the
132
+ * same reason `renderToString`'s own `props` option skips it — `[[Set]]` replaces the element's
133
+ * prototype. What a failed assignment means is decided in the catch below, by the client's rule;
134
+ * `prepareInstance`'s `props` OPTION keeps its stricter throw-on-readonly contract deliberately —
135
+ * an API argument is the caller's explicit data, a template binding is a component boundary.
136
+ */
137
+ const deliverProperty = (node, tag, name, value) => {
138
+ if (name === '__proto__') return;
139
+ try {
140
+ node[name] = value;
141
+ } catch (error) {
142
+ /**
143
+ * The CLIENT's rule, applied here so the two halves resolve the same contested state the same
144
+ * way: a getter with NO setter is a refusal — warned by name, the binding ignored, the render
145
+ * carried on, exactly what `init()`'s adoption does — while a setter that THREW is the
146
+ * component's own error and stays one, named against the tag and property rather than as
147
+ * `Cannot set property x of #<Class>`. Diverging here meant one binding produced a page on
148
+ * the client and an empty render server-side.
149
+ */
150
+ let carrier = node;
151
+ let refusable = false;
152
+ while (carrier !== null) {
153
+ const desc = Object.getOwnPropertyDescriptor(carrier, name);
154
+ if (desc !== undefined) {
155
+ refusable = desc.get !== undefined && desc.set === undefined;
156
+ break;
157
+ }
158
+ carrier = Object.getPrototypeOf(carrier);
159
+ }
160
+ if (refusable) {
161
+ console.warn(
162
+ `[vera] ssr: <${tag}> declares \`${name}\` as a getter with no setter — the bound value ` +
163
+ `cannot be delivered and the binding is ignored. Add a setter, or stop binding it.`
164
+ );
165
+ return;
166
+ }
167
+ throw new TypeError(
168
+ `ssr: <${tag}> refused the bound property \`.${name}\` — ${String(/** @type {Error} */ (error).message)}. ` +
169
+ `Its setter threw; the binding's value is the argument it was given.`
170
+ );
171
+ }
172
+ };
173
+
105
174
  /**
106
175
  * Whether the text so far leaves us inside an open tag — the question every sigil test below
107
176
  * silently assumed the answer to.
@@ -250,6 +319,13 @@ const compile = (strings) => {
250
319
  * difference is what the static ends with, so it is settled here rather than guessed at render.
251
320
  */
252
321
  const elementPositions = [];
322
+ /**
323
+ * Which ELEMENT each slot belongs to — an ordinal that advances when a tag opens. The owner tag
324
+ * NAME cannot tell two sibling `<x-row .item=${…}>`s apart, and component-prop delivery needs
325
+ * to: every slot sharing an ordinal delivers to one instance, per application.
326
+ */
327
+ const elements = [];
328
+ let elementOrdinal = 0;
253
329
  /** Names written so far in the tag being built — statics and earlier bindings alike. */
254
330
  let written = new Set();
255
331
  /** A spread's keys are runtime values, so a tag holding one can never be settled here. */
@@ -282,6 +358,7 @@ const compile = (strings) => {
282
358
  written = new Set();
283
359
  dynamicTag = false;
284
360
  owner = openTagName(part);
361
+ if (opensTag) elementOrdinal++;
285
362
  }
286
363
  /**
287
364
  * Names in the statics are recorded from the text that is actually **emitted**, which is the
@@ -305,6 +382,18 @@ const compile = (strings) => {
305
382
  const sigilName = sigil[2] ?? '';
306
383
  if (kind === '?') {
307
384
  kinds.push(BOOLEAN);
385
+ } else if ((kind === '.' || kind === '!') && sigilName && owner.includes('-')) {
386
+ /**
387
+ * A property on a COMPONENT tag is neither markup nor a client concern: it is the data the
388
+ * child renders from, so it is delivered to the instance the nested-component scan will
389
+ * render — before `FORM_ATTRIBUTES`, because `.value` on `<my-input>` is that component's
390
+ * prop, not a form control's dirty value. `!name` is here beside `.name` for the same
391
+ * reason it serializes as `.name` on form controls, and because a spread reports `!` keys
392
+ * as properties — the two spellings of one binding must get one answer. Whether the tag is
393
+ * actually registered is a render-time question (the registry fills as modules execute),
394
+ * answered in the case below.
395
+ */
396
+ kinds.push(COMPONENT_PROP);
308
397
  } else if ((kind === '.' || kind === '!') && FORM_ATTRIBUTES.includes(sigilName)) {
309
398
  kinds.push(FORM_PROP);
310
399
  } else {
@@ -316,6 +405,7 @@ const compile = (strings) => {
316
405
  raws.push(tagState.rawTag);
317
406
  attrValues.push(false);
318
407
  elementPositions.push(false);
408
+ elements.push(elementOrdinal);
319
409
  if (sigilName) written.add(sigilName.toLowerCase());
320
410
  continue;
321
411
  }
@@ -336,6 +426,7 @@ const compile = (strings) => {
336
426
  raws.push(tagState.rawTag);
337
427
  attrValues.push(false);
338
428
  elementPositions.push(false);
429
+ elements.push(elementOrdinal);
339
430
  continue;
340
431
  }
341
432
 
@@ -359,6 +450,7 @@ const compile = (strings) => {
359
450
  raws.push(tagState.rawTag);
360
451
  attrValues.push(false);
361
452
  elementPositions.push(false);
453
+ elements.push(elementOrdinal);
362
454
  written.add(name.toLowerCase());
363
455
  continue;
364
456
  }
@@ -380,6 +472,7 @@ const compile = (strings) => {
380
472
  /** Inside a tag, and not inside an attribute value: `<input ${ref} />`, `<b ${spread(…)}>`. */
381
473
  const elementPosition = tagState.inTag && !tagState.inValue;
382
474
  elementPositions.push(elementPosition);
475
+ elements.push(elementOrdinal);
383
476
  /** A spread's keys are unknown until it runs, so its tag can no longer be settled here. */
384
477
  if (elementPosition) dynamicTag = true;
385
478
  }
@@ -388,15 +481,26 @@ const compile = (strings) => {
388
481
  if (openQuote && last.startsWith(openQuote)) last = last.slice(1);
389
482
  parts.push(last);
390
483
 
391
- const plan = { parts, kinds, names, strip, owners, raws, attrValues, elementPositions };
484
+ const plan = { parts, kinds, names, strip, owners, raws, attrValues, elementPositions, elements };
392
485
  plans.set(strings, plan);
393
486
  return plan;
394
487
  };
395
488
 
396
489
  export const serializeTemplate = (template) => {
397
490
  const { strings, values } = template;
398
- const { parts, kinds, names, strip, owners, raws, attrValues, elementPositions } = plans.get(strings) ?? compile(strings);
491
+ const { parts, kinds, names, strip, owners, raws, attrValues, elementPositions, elements } =
492
+ plans.get(strings) ?? compile(strings);
399
493
  let out = '';
494
+ /**
495
+ * The instances this application is delivering properties to, allocated on the FIRST
496
+ * component-prop slot — `serializeTemplate` is the hot path the public SSR numbers rest on, and
497
+ * a template with no component props (almost all of them) must pay one `null` local and nothing
498
+ * else. `instances` is keyed by element ordinal, so `<x-row .a=${…} .b=${…}>` builds ONE
499
+ * instance for both keys while a list's N applications build N; `mark` is the marker text for a
500
+ * just-built instance, held rather than appended directly because the spread path folds `out`
501
+ * while delivering — each delivering case flushes it into the open tag it is building.
502
+ */
503
+ let adoption = null;
400
504
  /**
401
505
  * Content that belongs *after* the tag being built rather than inside it — a `<textarea>`'s
402
506
  * value, which is text and not an attribute. Written into the next static right after the `>`
@@ -421,8 +525,28 @@ export const serializeTemplate = (template) => {
421
525
  case TEXT:
422
526
  /** A spread rewrites the open tag it sits in, so it is folded rather than appended. */
423
527
  if (value !== null && typeof value === 'object' && value._$attrs$) {
424
- const folded = foldSpread(out, value._$attrs$());
528
+ /**
529
+ * A spread's property keys deliver exactly as the written form above does — `props()`
530
+ * IS a spread, so this is the surface the headline API arrives through. Lazily: the
531
+ * receiving instance is built on the spread's first property key, so a spread of plain
532
+ * attributes on a component never builds one.
533
+ */
534
+ const componentTag = owners[i].includes('-') && registry.has(owners[i]) ? owners[i] : '';
535
+ const folded = foldSpread(
536
+ out,
537
+ value._$attrs$(),
538
+ componentTag === ''
539
+ ? undefined
540
+ : (name, propValue) => {
541
+ adoption ??= { instances: new Map(), mark: '' };
542
+ deliverProperty(claimInstance(adoption, elements[i], componentTag), componentTag, name, propValue);
543
+ }
544
+ );
425
545
  out = folded.out;
546
+ if (adoption !== null && adoption.mark !== '') {
547
+ out += adoption.mark;
548
+ adoption.mark = '';
549
+ }
426
550
  if (folded.text !== null) pendingText = folded.text;
427
551
  if (folded.select !== null) out += ` ${SELECT_MARK}="${selectValues.push(folded.select) - 1}"`;
428
552
  }
@@ -556,7 +680,25 @@ export const serializeTemplate = (template) => {
556
680
  if (strip[i]) out = removeAttribute(out, names[i]);
557
681
  if (value != null) out += ` ${names[i]}="${escapeHtml(serializeValue(value, true))}"`;
558
682
  break;
559
- /** DROPPED: '@' and '&' and a non-form '.' or '!': nothing — client concerns. */
683
+ case COMPONENT_PROP:
684
+ /**
685
+ * Delivered only when the tag is REGISTERED — a component this process will render, whose
686
+ * server output should come from the same data its client render gets. An unregistered
687
+ * dashed tag (client-only, autoloaded later) is left exactly as before: the tag passes
688
+ * through as markup, the property is the client's to apply, nothing here to receive it.
689
+ * Registration is asked per render, not per plan, because the registry fills as component
690
+ * modules execute.
691
+ */
692
+ if (registry.has(owners[i])) {
693
+ adoption ??= { instances: new Map(), mark: '' };
694
+ deliverProperty(claimInstance(adoption, elements[i], owners[i]), owners[i], names[i], value);
695
+ if (adoption.mark !== '') {
696
+ out += adoption.mark;
697
+ adoption.mark = '';
698
+ }
699
+ }
700
+ break;
701
+ /** DROPPED: '@' and '&' and a non-component, non-form '.' or '!': nothing — client concerns. */
560
702
  }
561
703
  }
562
704
  const tail = parts[kinds.length];
@@ -758,7 +900,7 @@ const removeAttribute = (out, name) => {
758
900
  return out.slice(0, tagStart) + stripAttribute(out.slice(tagStart), name);
759
901
  };
760
902
 
761
- const foldSpread = (out, entries) => {
903
+ const foldSpread = (out, entries, deliverProp) => {
762
904
  const tagStart = out.lastIndexOf('<');
763
905
  let tag = out.slice(tagStart);
764
906
  let added = '';
@@ -770,6 +912,16 @@ const foldSpread = (out, entries) => {
770
912
  const owner = openTagName(out);
771
913
  const isFormElement = FORM_ELEMENTS.has(owner);
772
914
  for (const [kind, name, value] of entries) {
915
+ /**
916
+ * A property key on a rendered component tag is handed to the caller's delivery — the same
917
+ * door the written `.prop=${…}` form takes, because `props()` IS a spread and a key must mean
918
+ * the same thing in both spellings. The callback exists only when the owner is a registered
919
+ * component; everywhere else the key falls through to the rules below unchanged.
920
+ */
921
+ if (kind === 'p' && deliverProp !== undefined) {
922
+ deliverProp(name, value);
923
+ continue;
924
+ }
773
925
  const serializes =
774
926
  kind === 'a' || kind === 'b' || (kind === 'p' && isFormElement && FORM_ATTRIBUTES.includes(name));
775
927
  if (!serializes) continue;
package/types/nodes.d.ts CHANGED
@@ -364,6 +364,15 @@ export class ElementShim extends ContainerShim {
364
364
  * lose it.
365
365
  */
366
366
  get dataset(): {};
367
+ /**
368
+ * The platform's `style` is `[SameObject, PutForwards=cssText]` — `el.style = 'color: red'`
369
+ * assigns THROUGH to `cssText` in every engine (and in jsdom, the regression net). The shim
370
+ * declared only the getter, so the ordinary spelling threw `Cannot set property` server-side:
371
+ * a component-prop delivery of `.style` was refused as read-only while the client accepted and
372
+ * reflected it — the exact server/client divergence the differential rule exists to catch.
373
+ * `[LegacyNullToEmptyString]` rides the same IDL attribute, so `null` means `''`.
374
+ */
375
+ set style(value: {});
367
376
  get style(): {};
368
377
  removeAttribute(name: any): void;
369
378
  /**
@@ -679,6 +688,7 @@ export const pendingInstances: Map<any, any>;
679
688
  * the marker, so nothing observable depends on it.
680
689
  */
681
690
  export const INSTANCE_ATTRIBUTE: string;
691
+ export function markPending(node: any): string;
682
692
  /**
683
693
  * **Text and comments are nodes.**
684
694
  *