@verajs/renderer 0.1.5 → 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.
Files changed (42) hide show
  1. package/README.md +1063 -27
  2. package/dist/development/vera-renderer-hydrate.d.ts +32 -13
  3. package/dist/development/vera-renderer-hydrate.d.ts.map +1 -1
  4. package/dist/development/vera-renderer-hydrate.js +1959 -269
  5. package/dist/development/vera-renderer-hydrate.js.map +1 -1
  6. package/dist/development/vera-renderer-keyed.d.ts +17 -0
  7. package/dist/development/vera-renderer-keyed.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-keyed.js +322 -0
  9. package/dist/development/vera-renderer-keyed.js.map +1 -0
  10. package/dist/development/vera-renderer-profiler.d.ts +57 -17
  11. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  12. package/dist/development/vera-renderer-profiler.js +1592 -244
  13. package/dist/development/vera-renderer-profiler.js.map +1 -1
  14. package/dist/development/vera-renderer-slots.d.ts +103 -0
  15. package/dist/development/vera-renderer-slots.d.ts.map +1 -0
  16. package/dist/development/vera-renderer-slots.js +1387 -0
  17. package/dist/development/vera-renderer-slots.js.map +1 -0
  18. package/dist/development/vera-renderer-spread.d.ts +41 -0
  19. package/dist/development/vera-renderer-spread.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-spread.js +633 -0
  21. package/dist/development/vera-renderer-spread.js.map +1 -0
  22. package/dist/development/vera-renderer-tag.d.ts +61 -0
  23. package/dist/development/vera-renderer-tag.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-tag.js +829 -0
  25. package/dist/development/vera-renderer-tag.js.map +1 -0
  26. package/dist/development/vera-renderer.d.ts +41 -16
  27. package/dist/development/vera-renderer.d.ts.map +1 -1
  28. package/dist/development/vera-renderer.js +1522 -235
  29. package/dist/development/vera-renderer.js.map +1 -1
  30. package/dist/vera-renderer-hydrate.min.js +1 -1
  31. package/dist/vera-renderer-hydrate.min.js.map +1 -1
  32. package/dist/vera-renderer-keyed.min.js +2 -0
  33. package/dist/vera-renderer-keyed.min.js.map +1 -0
  34. package/dist/vera-renderer-slots.min.js +2 -0
  35. package/dist/vera-renderer-slots.min.js.map +1 -0
  36. package/dist/vera-renderer-spread.min.js +2 -0
  37. package/dist/vera-renderer-spread.min.js.map +1 -0
  38. package/dist/vera-renderer-tag.min.js +2 -0
  39. package/dist/vera-renderer-tag.min.js.map +1 -0
  40. package/dist/vera-renderer.min.js +1 -1
  41. package/dist/vera-renderer.min.js.map +1 -1
  42. package/package.json +24 -1
@@ -0,0 +1,829 @@
1
+ /**
2
+ * `true ` only: the one home for *"is this value something an attribute can carry?"*
3
+ *
4
+ * **Why it is a closed vocabulary and not a predicate.** The first design asked whether a value
5
+ * stringifies meaningfully — `String(v) === '[object Object]'` means it lost its data. Driven
6
+ * through 16 value shapes rather than reasoned about, that broke four ways, and the first is
7
+ * disqualifying: `String()` THROWS on `Object.create(null)`, on `{ toString: null }`, and on any
8
+ * object whose `toString` throws — so a diagnostic would have killed the page for an author using
9
+ * the recommended dictionary idiom. It also passed `["a","b"]` as `"a,b"` (one junk class, if that
10
+ * was a `class` binding) and `new Date()` as a timezone-bearing string, which is an SSR/CSR
11
+ * divergence manufactured out of correct-looking code. And it passed `Symbol('s')` while
12
+ * `` `${sym}` `` throws — a guard and its sink disagreeing about a single expression.
13
+ *
14
+ * "Does it stringify meaningfully" is an OPEN predicate over an unbounded, environment-dependent
15
+ * space, and open predicates cannot be audited. So the test is inverted and closed: **primitives
16
+ * pass; everything else is reported; anything else that should pass is a named row added on
17
+ * evidence.** The list has exactly one member so far.
18
+ *
19
+ * Credit where it is due: the four breaks were found by the omni engine's session, which drove the
20
+ * shapes rather than arguing about them, and the closed-vocabulary form is theirs.
21
+ */
22
+ /**
23
+ * Blessed non-primitives — types whose `toString` IS the value the author means.
24
+ *
25
+ * Tested by brand rather than `instanceof`, which is false across realms: a `URL` built in an
26
+ * iframe is not `instanceof` the parent's `URL`, and a diagnostic that fires on a correct value in
27
+ * one frame and not another is worse than none.
28
+ */
29
+ const brand = (value) => Object.prototype.toString.call(value);
30
+ /** One message per element+name+kind, so a value rebuilt every render does not flood the console. */
31
+ let reported;
32
+ /**
33
+ * Returns the complaint, or `null` when the value is fine. Never throws — the shapes that break a
34
+ * naive guard are exactly the ones worth reporting, so they reach the `object` arm and are named.
35
+ */
36
+ const attributeValueComplaint = (tag, name, value) => {
37
+ const type = typeof value;
38
+ if (type === 'string' || type === 'number' || type === 'boolean' || type === 'bigint')
39
+ return null;
40
+ if (type === 'object' && brand(value) === '[object URL]')
41
+ return null;
42
+ /**
43
+ * Keyed by BRAND, not by `typeof` — `Date`, `Array` and a plain object are all `'object'`, so a
44
+ * coarser key reported whichever arrived first and silently swallowed the rest. An author who
45
+ * fixed the Date would never have been told about the array.
46
+ */
47
+ const key = `${tag}|${name}|${type === 'object' ? brand(value) : type}`;
48
+ reported ??= new Set();
49
+ if (reported.has(key))
50
+ return null;
51
+ reported.add(key);
52
+ /**
53
+ * A function into an attribute is never what the author meant, but the REASON matters: on a
54
+ * custom element the Lit-era convention is that complex values are set as properties, so
55
+ * `<my-chart formatter={fn}>` is a coherent intention that this sink simply cannot express. The
56
+ * message names the binding that can, rather than blaming the author.
57
+ */
58
+ const said = type === 'function'
59
+ ? `a function, which becomes its own SOURCE TEXT`
60
+ : type === 'symbol'
61
+ ? `a symbol, which every DOM conversion refuses`
62
+ : Array.isArray(value)
63
+ ? `an array, which becomes its members joined by commas`
64
+ : brand(value) === '[object Date]'
65
+ ? `a Date, whose text carries the TIMEZONE of whichever side rendered it`
66
+ : `an ${type}, which cannot survive as text`;
67
+ /**
68
+ * Returned WITHOUT the `[vera]` prefix, which each call site writes as a literal.
69
+ * `tests/diagnostics-convention.test.mjs` reads the prefix off the call, so a message handed over
70
+ * as a variable is invisible to it — and its answer to that is an allowance list. Taking the
71
+ * allowance would have excused these two calls rather than checked them, which is the
72
+ * reclassification this audit keeps refusing; the literal at the call site is what every other
73
+ * diagnostic in the repo does anyway.
74
+ */
75
+ return (`renderer: the attribute \`${name}\` on <${tag}> was given ${said}. ` +
76
+ `An attribute value is a string and nothing else.\n` +
77
+ `If the element is meant to RECEIVE this value, bind a property instead — \`.${name}=\${value}\` ` +
78
+ `— which is how a custom element takes anything that is not text. If it is meant to be read as ` +
79
+ `text, convert it where you know what it means: \`date.toISOString()\`, \`list.join(' ')\`. ` +
80
+ `A Date in particular serializes with the SERVER's timezone on one side and the browser's on ` +
81
+ `the other, so it will not survive hydration.`);
82
+ };
83
+
84
+ /**
85
+ * `<div ${spread(props)}>` — bindings whose names are not known when the template is parsed.
86
+ *
87
+ * Template renderers bake attribute names in at parse time; that is what makes them small and fast,
88
+ * and it is why neither this renderer nor lit-html has had spread. Lit's spread PR has sat open as a
89
+ * draft since 2021, blocked on the questions answered below.
90
+ *
91
+ * **Why this ships separately.** The renderer holds one property read — a value at element position
92
+ * carrying `_$apply$` applies itself — and nothing else, so a base bundle grows 16 B rather than
93
+ * 176 B and an app that never spreads pays only that. Core and the renderer are the two packages
94
+ * where weight is absolute; this is not one of them, but it is still measured.
95
+ *
96
+ * The sigil rules are repeated here rather than shared through `@verajs/shared-utils`. That was
97
+ * tried: a shared resolver has to hand back both a kind and a name, and the tuple it allocates cost
98
+ * the renderer 10 B. Principle #5 permits deliberate duplication where two callers can legitimately
99
+ * diverge; #7 decides it, because the renderer is where bytes are not negotiable.
100
+ */
101
+ const ATTR = 0;
102
+ const PROPERTY = 1;
103
+ const BOOLEAN = 2;
104
+ /** `!name` — a property compared against the live DOM rather than against what this last wrote. */
105
+ const LIVE = 3;
106
+ const EVENT = 4;
107
+ const REF = 5;
108
+ /** A binding gone inert — a get-only property refusal; `write` matches it against nothing. */
109
+ const REFUSED = -1;
110
+ /**
111
+ * A key that cannot be written into a tag, and therefore cannot be used at all.
112
+ *
113
+ * Measured in Chromium, `setAttribute` accepts `"`, `'` and `<` and rejects whitespace, `>`, `=`,
114
+ * `/` and NUL — but a name carrying a quote or a `<` cannot survive **markup**, so `@verajs/ssr`
115
+ * has to refuse it, and a key that works here and vanishes server-side is worse than one that works
116
+ * nowhere. The rule is therefore the HTML attribute-name restriction (control characters,
117
+ * whitespace, `"`, `'`, `>`, `/`, `=`) plus `<` and a backtick, applied identically on both sides.
118
+ *
119
+ * Skipped rather than thrown. `setAttribute` throws `InvalidCharacterError` on some of these, which
120
+ * took down the whole render — for one bad key in a props bag, on a binding whose entire purpose is
121
+ * names that are not known until runtime.
122
+ *
123
+ * The control-character range is the point of the rule, not a mistake in it: a name carrying one
124
+ * is exactly what must never reach markup.
125
+ */
126
+
127
+ const UNSAFE_NAME = /^$|[\s"'>/=<`]|[\u0000-\u001f\u007f]/;
128
+ /**
129
+ * **Sinks spread refuses, because spread is the one place the template security model breaks.**
130
+ *
131
+ * The renderer's posture on `.innerHTML` (README, "security") rests on three properties of the
132
+ * template spelling: greppable, obviously yours, reviewable as the decision it is. A spread key
133
+ * arrives at RUNTIME inside a props object — often built from data — and has none of the three:
134
+ * `spread(fromJson)` carrying `.innerHTML` or an inline `onclick` attribute is markup or code
135
+ * injection through a door no grep can see. So spread refuses the sinks and points at the template
136
+ * spelling, which remains fully available to an author who means it.
137
+ *
138
+ * The list, deliberately minimal and named: `innerHTML`/`outerHTML` as property or live-property
139
+ * keys; `srcdoc` as an attribute (an iframe's inline document); and any attribute whose name the
140
+ * browser would treat as an inline handler (`on…` in any casing) — EXCEPT the documented event
141
+ * spelling `on` + Capital, which the constructor converts to a real listener and which therefore
142
+ * never becomes an attribute. The exemption mirrors the constructor's test byte for byte, because
143
+ * `ONCLICK` must not slip through as "looks like the event spelling": the constructor only
144
+ * converts a lowercase `on`, so only that exact shape is exempt.
145
+ *
146
+ * Returns the hint for the diagnostic, or null for a permitted key.
147
+ */
148
+ const refusedSink = (key) => {
149
+ const first = key[0];
150
+ if (first === '.' || first === '!') {
151
+ const name = key.slice(1);
152
+ if (name === 'innerHTML' || name === 'outerHTML')
153
+ return 'write it in the template — html`<div .innerHTML=${trusted}>` — sanitized first (renderer README, security note)';
154
+ /**
155
+ * `element.__proto__ = value` is not a property write — it hits Object.prototype's
156
+ * `__proto__` ACCESSOR and replaces the element's prototype, stripping every DOM method it
157
+ * has. The element is bricked, and the crash lands LATER, in whatever binding next calls
158
+ * `removeAttribute` on it — a data-driven render-kill with a stack that names the renderer
159
+ * and not the data. Found by the run-14 payload probe; there is no legitimate use, so unlike
160
+ * `.innerHTML` there is no template spelling to point at.
161
+ */
162
+ /** The deliberate twin of the same refusal in `AttrPart`'s constructor (`./renderer.ts`), for
163
+ * the template spellings `.name` / `!name`. Independent bundles, neither imports the other, so
164
+ * the rule is copied — and a fix visits both. `tests/dangerous-binding-matrix.test.mjs` holds
165
+ * the two spellings to the same answer. */
166
+ if (name === '__proto__')
167
+ return "assigning __proto__ replaces the element's own prototype and destroys it — no property write does this, and no use of it is legitimate";
168
+ return null;
169
+ }
170
+ if (first === '?' || first === '@' || first === '&')
171
+ return null;
172
+ /** The event spelling the constructor converts: `on` + Capital, lowercase `on` only. */
173
+ if (first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91)
174
+ return null;
175
+ const lower = key.toLowerCase();
176
+ if (lower === 'srcdoc')
177
+ return 'an inline iframe document is markup injection by definition — bind it in the template if you truly mean it';
178
+ if (lower.length > 2 && lower.startsWith('on'))
179
+ return 'an inline handler attribute is code from data — pass a function as `on` + Capital (onClick) or `@click` instead';
180
+ return null;
181
+ };
182
+ /** Module-local: one identity comparison, not a global symbol-registry lookup per binding. */
183
+ const UNSET = Symbol();
184
+ /**
185
+ * The deliberate twin of `commitAdopt` in `./renderer.ts` — independent bundles, neither imports
186
+ * the other, so the rule is copied IN FULL and a fix visits both. Full reasoning there; the short
187
+ * form: after the write, an accessor anywhere on the chain means something receives this property
188
+ * and the binding can latch onto the plain write for good. Unreceived, the value is recorded under
189
+ * the element-carried `_$props$` — the cross-bundle channel core's `init()` drains — and the latch
190
+ * closes once the element is upgraded (its record is final) or has no realm. The development
191
+ * clobber detector rides along, because a bag key and a written binding are the same mistake with
192
+ * the same author watching.
193
+ *
194
+ * Returns the binding's NEXT kind, exactly as the twin does: `PROPERTY` to latch onto the plain
195
+ * write, `REFUSED` to go inert (a get-only surface), `0` to keep adopting.
196
+ */
197
+ const adopt = (element, name, value) => {
198
+ const el = element;
199
+ /** The walk comes BEFORE the write — see the twin: a setter receives (its throw is the
200
+ * component's own error), a getter with no setter refuses instead of throwing a raw TypeError
201
+ * out of the render, and the dev warning defers to `_$adopt$`'s own refusal where it exists. */
202
+ let carrier = el;
203
+ while (carrier !== null) {
204
+ const desc = Object.getOwnPropertyDescriptor(carrier, name);
205
+ if (desc !== undefined) {
206
+ if (desc.set !== undefined) {
207
+ el[name] = value;
208
+ return PROPERTY;
209
+ }
210
+ if (desc.get !== undefined) {
211
+ if (el._$adopt$ !== undefined)
212
+ el._$adopt$(name, value);
213
+ else if (true )
214
+ console.warn(`[vera] renderer: <${element.localName}> declares \`${name}\` as a getter with no ` +
215
+ `setter — the value bound by \`.${name}\` cannot be delivered and the binding is ` +
216
+ `ignored. Add a setter, or stop binding it.`);
217
+ return REFUSED;
218
+ }
219
+ break; // a data property — an own field, or an inherited default: nothing receives it
220
+ }
221
+ carrier = Object.getPrototypeOf(carrier);
222
+ }
223
+ el[name] = value;
224
+ /** An initialized component receives live through `_$adopt$` — a record after the drain would
225
+ * never be read again. The door a spread bag's conditional key arrives through, reactive. */
226
+ if (el._$adopt$ !== undefined) {
227
+ el._$adopt$(name, value);
228
+ return PROPERTY;
229
+ }
230
+ const record = (el._$props$ ??= {});
231
+ const firstRecording = !Object.hasOwn(record, name);
232
+ record[name] = value;
233
+ /** Prototype, never `el.constructor` — a bag key named `constructor` shadows the real one with
234
+ * an own property, and no property write can move a prototype (`__proto__` is refused above). */
235
+ const win = element.ownerDocument.defaultView;
236
+ const upgraded = win === null || Object.getPrototypeOf(el) !== win.HTMLElement.prototype;
237
+ if (true && win !== null && !upgraded && firstRecording) {
238
+ const tag = element.localName;
239
+ win.customElements.whenDefined(tag).then(() => {
240
+ /** Ownership is asked of the whole CHAIN — see the twin: a drain accessor, a handed-to
241
+ * prototype pair, or a refused get-only surface all mean nothing is left to report. */
242
+ let owner = el;
243
+ let owned = false;
244
+ while (owner !== null) {
245
+ const desc = Object.getOwnPropertyDescriptor(owner, name);
246
+ if (desc !== undefined) {
247
+ owned = desc.get !== undefined || desc.set !== undefined;
248
+ break;
249
+ }
250
+ owner = Object.getPrototypeOf(owner);
251
+ }
252
+ if (!owned && el[name] !== record[name])
253
+ console.warn(`[vera] renderer: the value bound by \`.${name}\` on <${tag}> was replaced while the ` +
254
+ `element upgraded. A class field is the usual cause: at ES2022 \`${name}?: …\` emits ` +
255
+ `\`${name};\`, which runs during upgrade and overwrites whatever was set beforehand — ` +
256
+ `write it \`declare ${name}?: …\` instead, which emits nothing. A component that ` +
257
+ `calls init() adopts bound properties automatically and never sees this; this ` +
258
+ `element did not. Ignore this if the component replaced the value on purpose.`);
259
+ });
260
+ }
261
+ return upgraded ? PROPERTY : 0;
262
+ };
263
+ /**
264
+ * A class, not an object literal, so `handleEvent` exists once on the prototype. As a literal it was
265
+ * a fresh closure per bound key — allocation proportional to the size of every props bag.
266
+ */
267
+ class Binding {
268
+ _kind;
269
+ _name;
270
+ _element;
271
+ /** What the element held before this binding took over. Releasing puts it back. */
272
+ _initial;
273
+ _committed = UNSET;
274
+ _handler = null;
275
+ /** Twin of AttrPart's `PROP_ADOPT`: a property binding on a dashed tag goes through `adopt`
276
+ * until something receives the property, then latches onto the plain write. Bindings persist
277
+ * per element in `owned`, so the latch is safe here too. */
278
+ _recording = false;
279
+ constructor(element, key) {
280
+ const first = key[0];
281
+ let kind = first === '.'
282
+ ? PROPERTY
283
+ : first === '?'
284
+ ? BOOLEAN
285
+ : first === '@'
286
+ ? EVENT
287
+ : first === '&'
288
+ ? REF
289
+ : first === '!'
290
+ ? LIVE
291
+ : ATTR;
292
+ let name = kind ? key.slice(1) : key;
293
+ /** `on` + a capital: `onClick` ≡ `@click`. All-lowercase `onclick` never reaches here — it is
294
+ * an inline-handler attribute, which `refusedSink` rejects before a binding exists. */
295
+ if (kind === ATTR && first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91) {
296
+ kind = EVENT;
297
+ name = key.slice(2).toLowerCase();
298
+ }
299
+ this._kind = kind;
300
+ this._name = name;
301
+ this._element = element;
302
+ this._recording = kind === PROPERTY && element.localName.includes('-');
303
+ this._initial =
304
+ kind === ATTR
305
+ ? element.getAttribute(name)
306
+ : kind === BOOLEAN
307
+ ? element.hasAttribute(name)
308
+ : kind === PROPERTY || kind === LIVE
309
+ ? element[name]
310
+ : null;
311
+ }
312
+ /**
313
+ * **Two shapes, because `addEventListener` takes two** — the same rule `AttrPart.handleEvent`
314
+ * applies, and it did not travel here when that one was fixed. A function is called with the
315
+ * element as `this`; an object with a `handleEvent` method is invoked through it — the platform's
316
+ * own `EventListenerObject` protocol, which every engine accepts. This called `.call()`
317
+ * unconditionally, so `spread({ onClick: { handleEvent } })` bound without complaint, never
318
+ * fired, and raised `this._handler.call is not a function` on **every** dispatch — while the
319
+ * identical value through a written `@click` worked.
320
+ *
321
+ * Anything else is inert rather than throwing, exactly as there: development names it at the
322
+ * binding (see the event branch in `write`), where the mistake still is.
323
+ */
324
+ handleEvent(event) {
325
+ const handler = this._handler;
326
+ if (typeof handler === 'function')
327
+ handler.call(this._element, event);
328
+ else if (typeof handler?.handleEvent === 'function')
329
+ handler.handleEvent(event);
330
+ }
331
+ }
332
+ /**
333
+ * Keyed by the **part**, not the element.
334
+ *
335
+ * Keyed by element, `<div ${spread(a)} ${spread(b)}>` shares one map: whichever applies second sees
336
+ * the other's keys as absent from its own props and releases them. Measured — the first spread's
337
+ * attributes silently vanished. The part is one per element-position slot, which is exactly the
338
+ * ownership boundary, and the renderer reuses it across renders.
339
+ */
340
+ const owned = new WeakMap();
341
+ const write = (binding, value) => {
342
+ /** One comparison per key per render — the same dirty check a written binding gets. */
343
+ /**
344
+ * A live property asks the element rather than its own memory — see `AttrPart` in the renderer.
345
+ * The dirty check is what keeps a field someone typed into, and it is exactly wrong for a control
346
+ * whose DOM state changes when a *sibling* is interacted with, a radio group being the case.
347
+ */
348
+ if (binding._kind === LIVE) {
349
+ binding._committed = value;
350
+ const live = binding._element;
351
+ if (live[binding._name] !== value)
352
+ live[binding._name] = value;
353
+ return;
354
+ }
355
+ if (value === binding._committed)
356
+ return;
357
+ binding._committed = value;
358
+ const element = binding._element;
359
+ const name = binding._name;
360
+ const kind = binding._kind;
361
+ if (kind === ATTR) {
362
+ if (value == null)
363
+ element.removeAttribute(name);
364
+ else {
365
+ if (true ) {
366
+ const complaint = attributeValueComplaint(element.localName, name, value);
367
+ if (complaint !== null)
368
+ console.warn(`[vera] ${complaint}`);
369
+ }
370
+ /**
371
+ * `` `${value}` ``, never `String(value)` — the two differ on exactly one thing and it is the
372
+ * one that matters here. `String(sym)` returns `"Symbol(s)"` while every DOM conversion and
373
+ * `@verajs/ssr`'s own escaper throw, so this sink was the ONLY one of three that accepted a
374
+ * symbol, writing to the client an attribute the server refuses to produce. The rule was
375
+ * already recorded in `@verajs/ssr`'s `escapeHtml` — "serving Symbol(s) into markup the client
376
+ * cannot reproduce does not make anything work, it moves the failure across the boundary and
377
+ * strips the context" — and this file used the other form anyway. A house rule written down
378
+ * in one of three homes is a house rule in none of them.
379
+ */
380
+ element.setAttribute(name, `${value}`);
381
+ }
382
+ }
383
+ else if (kind === PROPERTY) {
384
+ if (binding._recording) {
385
+ const next = adopt(element, name, value);
386
+ if (next !== 0) {
387
+ binding._recording = false;
388
+ if (next === REFUSED)
389
+ binding._kind = REFUSED; // inert: `write` matches it against nothing
390
+ }
391
+ }
392
+ else
393
+ element[name] = value;
394
+ }
395
+ else if (kind === BOOLEAN) {
396
+ element.toggleAttribute(name, !!value);
397
+ }
398
+ else if (kind === REF) {
399
+ /**
400
+ * `&name` is the written form's ref sigil (`<input &field=${myRef} />`), and it was the one
401
+ * binding kind a spread could not express: the key fell through to `ATTR` and
402
+ * `setAttribute('&field', …)` threw on the client while the server wrote `&field="[object
403
+ * Object]"` into the markup. A function is called with the element, an object gets it assigned
404
+ * to `.value` — the same two shapes `AttrPart` handles.
405
+ */
406
+ if (typeof value === 'function')
407
+ value(element);
408
+ else if (value !== null && typeof value === 'object')
409
+ value.value = element;
410
+ }
411
+ else {
412
+ /**
413
+ * A listener is validated when a *user* clicks, which in development may be never — so it is
414
+ * checked where it is written, the same rule `AttrPart` applies to `@event`. `false` stays
415
+ * silent: `{ onClick: enabled && onClick }` is the ordinary conditional form and already
416
+ * behaves correctly, since `handleEvent` finds nothing callable and does nothing.
417
+ */
418
+ if (true && value != null && value !== false && typeof value !== 'function' &&
419
+ typeof value?.handleEvent !== 'function')
420
+ console.warn(`[vera] spread: @${name} on <${element.localName}> was given ` +
421
+ `${typeof value === 'object' ? 'an object with no handleEvent method' : `a ${typeof value}`}, ` +
422
+ `which cannot listen — the event will do nothing.\n` +
423
+ `Pass a function, or an object with a handleEvent method. A missing handler is ` +
424
+ `\`undefined\` or \`false\`, both of which are fine; this is neither.`);
425
+ if (binding._handler === null && value != null)
426
+ element.addEventListener(name, binding);
427
+ binding._handler = value ?? null;
428
+ }
429
+ };
430
+ /**
431
+ * A key that disappeared between renders restores what the element held before the binding existed.
432
+ *
433
+ * This is the question Lit's PR is stuck on, and the trap is asking it as "what value means absent".
434
+ * For a property there is no answer: assigning `undefined` runs through coercing setters, so
435
+ * dropping `.value` yields `""` rather than reverting, and `delete` cannot remove a prototype
436
+ * accessor. Asked instead as *"undo what this binding did"* it is well defined for every kind and
437
+ * never invents a value the author did not write — the initial state was, by definition, acceptable
438
+ * before the binding arrived.
439
+ *
440
+ * And asked that way it needs no code of its own: releasing is writing the initial value back.
441
+ * `null` removes an attribute, `false` untoggles a boolean, `undefined` restores a property to
442
+ * pristine, and an event handler falls to `null` — every case the existing commit already handles.
443
+ * The separate per-kind teardown this replaced was fourteen lines saying the same thing twice.
444
+ *
445
+ * Deliberately unguarded by an ownership check (`is the value still the one we wrote?`). That only
446
+ * matters when a component reassigns a property its parent is binding, which is already confused;
447
+ * per principle #3 the machinery waits for evidence rather than being pre-built.
448
+ */
449
+ function apply(element, part) {
450
+ const props = this._props;
451
+ let bindings = owned.get(part);
452
+ if (bindings === undefined)
453
+ owned.set(part, (bindings = new Map()));
454
+ /**
455
+ * Counted here rather than with `Object.keys(props).length`, which allocates an array on every
456
+ * render of every spread — garbage in the render path, for a number already being walked.
457
+ */
458
+ let count = 0;
459
+ for (const key in props) {
460
+ count++;
461
+ /**
462
+ * Counted before it is skipped, so the size comparison below still describes the key set — a
463
+ * refused key that changed the count would make every render look like a removal.
464
+ */
465
+ if (UNSAFE_NAME.test(key[0] === '.' || key[0] === '?' || key[0] === '@' || key[0] === '&' ? key.slice(1) : key)) {
466
+ if (true )
467
+ console.warn(`[vera] spread: ignoring the key ${JSON.stringify(key)} — an attribute name ` +
468
+ `cannot contain whitespace, a quote, \`<\`, \`>\`, \`/\`, \`=\` or a control character, ` +
469
+ `and one that cannot be written into markup would not survive server rendering.`);
470
+ continue;
471
+ }
472
+ /** Counted above for the same reason the unsafe skip is. */
473
+ const refused = refusedSink(key);
474
+ if (refused !== null) {
475
+ if (true )
476
+ console.warn(`[vera] spread: refusing ${JSON.stringify(key)} — spread names arrive at runtime, which is ` +
477
+ `exactly the property that makes this sink unreviewable; ${refused}.`);
478
+ continue;
479
+ }
480
+ let binding = bindings.get(key);
481
+ if (binding === undefined)
482
+ bindings.set(key, (binding = new Binding(element, key)));
483
+ write(binding, props[key]);
484
+ }
485
+ /**
486
+ * A size mismatch is the only way a key can have gone: every key in `props` was just visited, so
487
+ * equal sizes means equal sets. The steady-state render of an unchanged shape — overwhelmingly the
488
+ * common case — costs one integer comparison, not a scan.
489
+ */
490
+ if (bindings.size !== count) {
491
+ for (const [key, binding] of bindings) {
492
+ if (key in props)
493
+ continue;
494
+ bindings.delete(key);
495
+ write(binding, binding._initial);
496
+ }
497
+ }
498
+ }
499
+ /**
500
+ * The server half of the protocol: hand back every binding, resolved, and let the renderer that
501
+ * asked decide what belongs in markup.
502
+ *
503
+ * Deliberately *not* a serializer. This package knows what a key means — `.value` is a property,
504
+ * `?disabled` a boolean, `onClick` an event — and nothing else. Whether a property belongs in
505
+ * server markup (`value`, `checked`, `selected` do; the rest are client state) and how a value is
506
+ * escaped are `@verajs/ssr`'s decisions, and principle #8 wants escaping in exactly one place. So
507
+ * this returns data, never a string.
508
+ *
509
+ * Kinds are single characters rather than the module's numeric constants, because this crosses a
510
+ * package boundary: `a`ttribute, `b`oolean, `p`roperty, `e`vent, `r`ef. A ref is client state with
511
+ * no markup, exactly like an event, and the serializer drops both.
512
+ */
513
+ function attributes() {
514
+ const out = [];
515
+ for (const key in this._props) {
516
+ /** The client refusal, applied at the serializer boundary too — one predicate, both renders.
517
+ * Without this, a refused key was merely inert in the browser and LIVE in server markup. */
518
+ if (refusedSink(key) !== null)
519
+ continue;
520
+ const first = key[0];
521
+ /** `!` reports as a property: the server has nothing to re-read, so it serializes as `.` does. */
522
+ const kind = first === '.' || first === '!'
523
+ ? 'p'
524
+ : first === '?'
525
+ ? 'b'
526
+ : first === '@'
527
+ ? 'e'
528
+ : first === '&'
529
+ ? 'r'
530
+ : 'a';
531
+ if (kind !== 'a') {
532
+ out.push([kind, key.slice(1), this._props[key]]);
533
+ }
534
+ else if (first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91) {
535
+ out.push(['e', key.slice(2).toLowerCase(), this._props[key]]);
536
+ }
537
+ else {
538
+ out.push(['a', key, this._props[key]]);
539
+ }
540
+ }
541
+ return out;
542
+ }
543
+ const spread = (props) => {
544
+ /**
545
+ * **Already branded → returned as-is.** `spread(spread(x))` arises legitimately: JSX compiles
546
+ * `{...props({ date })}` to `spread(props({ date }))`, and `props()` below already returns the
547
+ * branded result. Without this line the brand itself would be iterated as a bag and bind
548
+ * attributes named `_props`, `_$apply$` and `_$attrs$`. Detected by the brand's PRESENCE, never
549
+ * by identity with this bundle's `apply` — on a CDN page the renderer and a second copy of this
550
+ * module are separate bundles with separate `apply` functions, and a result from either must
551
+ * pass through both (the two-registry failure shape `tests/cdn-cross-bundle.test.mjs` guards).
552
+ */
553
+ if (props !== null && typeof props === 'object' && props._$apply$ !== undefined)
554
+ return props;
555
+ /**
556
+ * **A props bag that is not an object is iterated anyway, and a browser accepts the result.**
557
+ *
558
+ * Everything below reads `props` with `Object.keys`/`Object.entries`, which answer for any value:
559
+ * a **string** yields its character indices, so `spread('text')` sets four attributes named `0`,
560
+ * `1`, `2`, `3` — measured in Chromium, with no error and no warning. A number, a boolean and
561
+ * `null` yield nothing at all, so `spread(someUndefinedVariable)` applies no props and says
562
+ * nothing, which reads as a renderer that ignored the spread.
563
+ *
564
+ * **jsdom hides this rather than catching it.** It implements the XML Name production and throws
565
+ * `InvalidCharacterError` on `setAttribute('0', …)`, so a probe under jsdom sees a loud failure
566
+ * for the case a real engine performs silently — the inverse of the usual trap, and the reason
567
+ * this was verified in a browser before being called a defect (`tests/browser/spread-names.test.js`
568
+ * records the engines' actual rule).
569
+ *
570
+ * Warned and ignored rather than thrown, which is exactly what an unusable *key* already does a
571
+ * few lines above: one bad props bag should not cost the render.
572
+ *
573
+ * **The message is `true `-only; the refusal is not.** They were both inside the guard, which
574
+ * made the two builds behave differently for the same code — and differently in the direction that
575
+ * hides the bug. Measured: `spread('text')` applies nothing in development, so the app under test
576
+ * looks fine; in production the string is iterated by character index and the element ends up with
577
+ * attributes named `0`, `1`, `2` and `3` (under jsdom, an `InvalidCharacterError` instead — the
578
+ * usual inversion, and why this was measured against both builds rather than reasoned about).
579
+ *
580
+ * A diagnostic belongs in `true `. A guard that changes what the program does cannot, or the
581
+ * development build stops being a faithful model of the production one, which is the property that
582
+ * makes testing in it worth anything. Costs 27 B gzipped (842 → 869, A-B-A) and buys the two builds agreeing.
583
+ */
584
+ if (props === null || typeof props !== 'object' || Array.isArray(props)) {
585
+ if (true )
586
+ console.warn(`[vera] spread: ignoring a props bag that is not a plain object — received ` +
587
+ `${Array.isArray(props) ? 'an array' : typeof props === 'object' ? 'null' : `a ${typeof props}`}. ` +
588
+ `A string is iterated by character index, so \`spread('text')\` would set attributes named ` +
589
+ `0, 1, 2 and 3; anything else applies nothing at all. This is usually an import or a ` +
590
+ `property that resolved to something unexpected.`);
591
+ props = {};
592
+ }
593
+ return {
594
+ _props: props,
595
+ _$apply$: apply,
596
+ _$attrs$: attributes,
597
+ };
598
+ };
599
+
600
+ /**
601
+ * `@verajs/renderer/tag` — an element whose **tag name** is decided at runtime.
602
+ *
603
+ * A template renderer bakes tag names into its statics; that is what makes template identity work
604
+ * and what every fast path in this renderer depends on. So a runtime tag cannot be a binding — it
605
+ * has to become part of the statics *before* the renderer sees the template, which is what this
606
+ * entry does. Downstream nothing changes: the renderer, `@verajs/ssr` and hydration all receive an
607
+ * ordinary template and are unaware this exists.
608
+ *
609
+ * ```js
610
+ * import { html, tag } from '@verajs/renderer/tag';
611
+ *
612
+ * const HEADING = { 1: tag`h1`, 2: tag`h2`, 3: tag`h3` };
613
+ * const H = HEADING[state.level];
614
+ * html`<${H} class="title">${state.text}</${H}>`;
615
+ * ```
616
+ *
617
+ * **A tag is also a JSX component**, so the same value works in both notations with no compiler
618
+ * change — `<H className="title">{state.text}</H>` compiles to `H({…})`, which is exactly what a
619
+ * capitalized JSX tag already compiles to.
620
+ *
621
+ * Additive, like `@verajs/renderer/spread` and unlike the other entries: it inlines no renderer
622
+ * internals, so it is safe alongside any of them.
623
+ */
624
+ /** The brand a tag carries. `_$…$` is exempt from this package's `/^_[a-z]/` property mangling. */
625
+ const STATIC = '_$static$';
626
+ /**
627
+ * Spliced statics, keyed by the call site's own `strings` array and then by the tags in it.
628
+ *
629
+ * The cache is the whole reason this works. `_shape === value.strings` is the renderer's identity
630
+ * check, so a fresh array per render would never match and every render would rebuild the subtree.
631
+ * A `WeakMap` on the call site's array means the entries die with the module that holds them, and
632
+ * the inner keys are bounded by the tags in the source — which is exactly what `tag` refusing a
633
+ * string guarantees.
634
+ */
635
+ const caches = new WeakMap();
636
+ /**
637
+ * The `html` to use in a template containing a runtime tag. With no tags in it, this is the
638
+ * ordinary template shape and costs one loop.
639
+ *
640
+ * It builds `{ _$litType$: 1, strings, values }` directly rather than calling core's `html`, so this
641
+ * entry keeps the renderer's independence from core. The consequence is that a `setHtml` swap does
642
+ * not reach here — which is right, since a swapped `html` belongs to a different renderer and this
643
+ * is a renderer feature.
644
+ */
645
+ const html = (strings, ...values) => {
646
+ let key = '';
647
+ for (let i = 0; i < values.length; i++) {
648
+ const value = values[i];
649
+ if (value && value[STATIC] !== undefined)
650
+ key += `${i}:${value[STATIC]};`;
651
+ /**
652
+ * A non-tag in **tag position** — `<${name}>` with a string. The refusal is the whole security
653
+ * property of this entry, and it lived only in `tag` itself, which guards interpolation into a
654
+ * tag literal. Reaching the position through `html` instead produced no error and no element:
655
+ * the base scanner reads the expression as an element ref on a tag with no name, and the page
656
+ * gets escaped punctuation where the markup should be.
657
+ *
658
+ * The static before a value is what identifies the position, so this is the one place that can
659
+ * see it. `true `-only; production carries neither the check nor the text.
660
+ */
661
+ else if (true && (strings[i].endsWith('<') || strings[i].endsWith('</'))) {
662
+ throw new Error(`tag: a ${value === null ? 'null' : typeof value} cannot become markup. ` +
663
+ `Only a tag may be interpolated into tag position:\n\n` +
664
+ ` const heading = tag\`h\${level}\`; // built from other tags\n` +
665
+ ` html\`<\${heading}>…</\${heading}>\`\n\n` +
666
+ `That is what keeps the set of tags an app can produce fixed by its source.`);
667
+ }
668
+ }
669
+ if (key === '')
670
+ return { ['_$litType$']: 1, strings, values };
671
+ let byTags = caches.get(strings);
672
+ if (byTags === undefined)
673
+ caches.set(strings, (byTags = new Map()));
674
+ let spliced = byTags.get(key);
675
+ if (spliced === undefined) {
676
+ spliced = [];
677
+ let run = strings[0];
678
+ for (let i = 0; i < values.length; i++) {
679
+ const value = values[i];
680
+ if (value && value[STATIC] !== undefined)
681
+ run += value[STATIC] + strings[i + 1];
682
+ else {
683
+ spliced.push(run);
684
+ run = strings[i + 1];
685
+ }
686
+ }
687
+ spliced.push(run);
688
+ byTags.set(key, spliced);
689
+ }
690
+ const bindings = [];
691
+ for (let i = 0; i < values.length; i++) {
692
+ const value = values[i];
693
+ if (!(value && value[STATIC] !== undefined))
694
+ bindings.push(value);
695
+ }
696
+ return { ['_$litType$']: 1, strings: spliced, values: bindings };
697
+ };
698
+ /**
699
+ * React's names, mapped the way `@verajs/jsx` maps them on a written element — so `<H1
700
+ * className="t" disabled={d}>` and `<h1 className="t" disabled={d}>` mean the same thing.
701
+ *
702
+ * Not cosmetic. Passed through raw, `disabled={false}` becomes the attribute `disabled="false"`,
703
+ * and any value at all disables the control; `className` lands as `classname` and never applies.
704
+ *
705
+ * Deliberately duplicated from the transform rather than shared through a package: the two are
706
+ * build-time and runtime, and `tests/jsx-name-mapping.test.mjs` asserts they agree on every key —
707
+ * which is the drift protection a shared module would have bought, without the dependency.
708
+ */
709
+ const NAME_MAP = { className: 'class', htmlFor: 'for' };
710
+ const PROPERTIES = { value: '.value', checked: '.checked' };
711
+ const DEFAULTS = { defaultValue: 'value', defaultChecked: '?checked' };
712
+ /**
713
+ * The props that name a BINDING rather than an attribute — and the reason this table is here and
714
+ * not in the transform's twin.
715
+ *
716
+ * The compiler must NOT rewrite these on a component: `<Card ref={r}>` hands `ref` to `Card`, which
717
+ * decides what it means, exactly as React does. But a tag's component forwards to a real element,
718
+ * so at THIS boundary — and only here — `ref` has a binding to become. Before 2026-09-12 it had
719
+ * none: it fell through to the attribute sink and `<H ref={r}>` wrote the FUNCTION'S SOURCE TEXT
720
+ * into the DOM as `ref="el => (got = el)"`, which under SSR shipped the closure body to the client,
721
+ * while the identical `<h1 ref={r}>` bound correctly.
722
+ */
723
+ const BINDINGS = { ref: '&ref' };
724
+ const BOOLEAN_ATTRIBUTES = new Set([
725
+ 'disabled', 'hidden', 'readonly', 'required', 'open', 'selected', 'multiple',
726
+ 'autofocus', 'autoplay', 'controls', 'loop', 'muted', 'playsinline', 'inert', 'reversed',
727
+ ]);
728
+ const jsxName = (key) => NAME_MAP[key] ?? PROPERTIES[key] ?? DEFAULTS[key] ?? BINDINGS[key] ?? (BOOLEAN_ATTRIBUTES.has(key) ? `?${key}` : key);
729
+ /**
730
+ * Declares a tag name.
731
+ *
732
+ * **A string can never become one.** Only another tag may be interpolated, so the set of tags an
733
+ * app can produce is fixed by its source — which is what keeps a tag out of reach of a request, and
734
+ * incidentally what bounds the template cache. There is no `unsafeStatic` here for the same reason
735
+ * there is no `unsafeHTML`: a sanctioned opt-out reads as blessed in tutorials and in review.
736
+ */
737
+ const tag = (strings, ...values) => {
738
+ /**
739
+ * A *template tag*, so it is written `` tag`h1` `` and not `tag('h1')`. The call form is the
740
+ * likelier mistake of the two and failed with `Cannot read properties of undefined (reading '0')`,
741
+ * which says nothing about either.
742
+ */
743
+ if (true && (!strings || !Array.isArray(strings.raw)))
744
+ throw new TypeError(`tag: expected a template literal and received ${String(strings)}. ` +
745
+ "It is a tagged template — write tag`h1`, not tag('h1').");
746
+ let text = strings[0];
747
+ for (let i = 0; i < values.length; i++) {
748
+ const value = values[i];
749
+ if (!value || value[STATIC] === undefined)
750
+ throw new Error('tag: only another tag may be interpolated — a string cannot become markup');
751
+ text += value[STATIC] + strings[i + 1];
752
+ }
753
+ /**
754
+ * **A tag's text must be an element NAME.** Until this, it was an unconstrained string spliced
755
+ * straight into the statics — so `` tag`div onclick=x` `` produced markup rather than a tag, and
756
+ * the name of this export was a description of intent rather than of behaviour.
757
+ *
758
+ * The concrete failure it closes is a cache collision. Spliced statics key on
759
+ * `` `${i}:${text};` `` per tag, joined with separators the text was free to contain, so two
760
+ * DIFFERENT tag assignments at one call site could derive the same key and reuse each other's
761
+ * markup. Measured: at a two-tag call site, `(a, "b;1:c")` and `("a;1:b", c)` both derive
762
+ * `"0:a;1:b;1:c;"`, and the second render came back as the FIRST one's markup.
763
+ *
764
+ * Escaping the separators would have fixed that one collision. Constraining the name fixes the
765
+ * class — no name can contain a separator, so no key can be ambiguous, and the export delivers
766
+ * what it is called. A closed grammar beats a wider escape, which is the same ruling this audit
767
+ * reached for the attribute-value sink.
768
+ *
769
+ * Unconditional, like the interpolation refusal above and unlike the shape check: both are about
770
+ * what may become markup, and a production build is where that matters most.
771
+ */
772
+ if (!/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(text))
773
+ throw new Error(
774
+ /**
775
+ * The THROW is unconditional; its EXPLANATION is not. Carrying the full sentence cost 178 B
776
+ * gzipped here — most of a 1.9 KB entry — for text an author reads once and a production
777
+ * page never reaches. Core's static-render refusal is shaped the same way for the same
778
+ * measurement.
779
+ */
780
+ true
781
+ ? `tag: ${JSON.stringify(text)} is not an element name. A tag names ONE element — letters, ` +
782
+ `then letters, digits, '.', '_' or '-' — and nothing else becomes markup here.\n` +
783
+ `Attributes and content belong in the template: html\`<\${heading} class="title">…</\${heading}>\`.`
784
+ : 'tag: not an element name');
785
+ /**
786
+ * The tag is a function, which is what makes it a JSX component: the compiler emits `H({…})` for
787
+ * a capitalized tag, and this is what receives that call. `children` is JSX's own key; everything
788
+ * else goes through `spread`, since the names are not known when this template is written.
789
+ */
790
+ const self = (({ children, key, dangerouslySetInnerHTML: rawHtml, ...props } = {}) => {
791
+ /**
792
+ * **`key` and `dangerouslySetInnerHTML` come out of the bag by name**, because neither is an
793
+ * attribute and the sink they fell into accepts anything. `key` became the literal attribute
794
+ * `key="7"` on the element AND cost the list its identity — rows then reconciled positionally,
795
+ * so focus, scroll and input state followed the index rather than the item.
796
+ *
797
+ * `@verajs/jsx` consumes `key` into `keyed(…)` before this is ever called, so the compiled path
798
+ * never reaches here. This is the HAND-CALL backstop — `H({ key: id })` — where no compiler is
799
+ * looking, and dropping it silently would be a refusal with no channel, hence the warning.
800
+ */
801
+ if (true && key !== undefined)
802
+ console.warn(`[vera] tag: \`key\` does nothing on a tag component and has been dropped — a key marks a ` +
803
+ `template for list reconciliation, and this call returns one rather than being one.\n` +
804
+ `In JSX, write it and the compiler handles it: \`<Row key=\${id}>\` becomes ` +
805
+ `\`keyed(id, Row({…}))\`. Calling by hand, wrap it yourself: \`keyed(id, Row({…}))\`.`);
806
+ /**
807
+ * **`dangerouslySetInnerHTML` cannot work here, and that is a security property rather than a
808
+ * gap.** A tag reaches its element through `spread`, and `spread` REFUSES `.innerHTML` on
809
+ * purpose: its names arrive at runtime, which is what makes that sink unreviewable. Mapping the
810
+ * prop was tried and measured — 37 B for a value `spread` then declined, so the bytes bought a
811
+ * console message. Refused here instead, where the reason can be said.
812
+ */
813
+ if (true && rawHtml !== undefined)
814
+ console.warn(`[vera] tag: \`dangerouslySetInnerHTML\` is not available on a tag component and has been ` +
815
+ `dropped. A tag binds through \`spread\`, whose names are only known at runtime — so it ` +
816
+ `refuses \`.innerHTML\` outright rather than open an unreviewable HTML sink.\n` +
817
+ `Write the element directly, with the value sanitized first: ` +
818
+ `html\`<\${Tag} .innerHTML=\${trusted}>\` (see the renderer README's security note).`);
819
+ const mapped = {};
820
+ for (const name in props)
821
+ mapped[jsxName(name)] = props[name];
822
+ return html `<${self} ${spread(mapped)}>${children}</${self}>`;
823
+ });
824
+ self[STATIC] = text;
825
+ return self;
826
+ };
827
+
828
+ export { BOOLEAN_ATTRIBUTES, html, jsxName, tag };
829
+ //# sourceMappingURL=vera-renderer-tag.js.map