@verajs/renderer 0.1.4 → 0.2.0

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 +1000 -12
  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 +1812 -234
  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 +1445 -209
  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 +51 -0
  19. package/dist/development/vera-renderer-spread.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-spread.js +499 -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 +727 -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 +1375 -200
  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,727 @@
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
+ /**
109
+ * A key that cannot be written into a tag, and therefore cannot be used at all.
110
+ *
111
+ * Measured in Chromium, `setAttribute` accepts `"`, `'` and `<` and rejects whitespace, `>`, `=`,
112
+ * `/` and NUL — but a name carrying a quote or a `<` cannot survive **markup**, so `@verajs/ssr`
113
+ * has to refuse it, and a key that works here and vanishes server-side is worse than one that works
114
+ * nowhere. The rule is therefore the HTML attribute-name restriction (control characters,
115
+ * whitespace, `"`, `'`, `>`, `/`, `=`) plus `<` and a backtick, applied identically on both sides.
116
+ *
117
+ * Skipped rather than thrown. `setAttribute` throws `InvalidCharacterError` on some of these, which
118
+ * took down the whole render — for one bad key in a props bag, on a binding whose entire purpose is
119
+ * names that are not known until runtime.
120
+ *
121
+ * The control-character range is the point of the rule, not a mistake in it: a name carrying one
122
+ * is exactly what must never reach markup.
123
+ */
124
+
125
+ const UNSAFE_NAME = /^$|[\s"'>/=<`]|[\u0000-\u001f\u007f]/;
126
+ /**
127
+ * **Sinks spread refuses, because spread is the one place the template security model breaks.**
128
+ *
129
+ * The renderer's posture on `.innerHTML` (README, "security") rests on three properties of the
130
+ * template spelling: greppable, obviously yours, reviewable as the decision it is. A spread key
131
+ * arrives at RUNTIME inside a props object — often built from data — and has none of the three:
132
+ * `spread(fromJson)` carrying `.innerHTML` or an inline `onclick` attribute is markup or code
133
+ * injection through a door no grep can see. So spread refuses the sinks and points at the template
134
+ * spelling, which remains fully available to an author who means it.
135
+ *
136
+ * The list, deliberately minimal and named: `innerHTML`/`outerHTML` as property or live-property
137
+ * keys; `srcdoc` as an attribute (an iframe's inline document); and any attribute whose name the
138
+ * browser would treat as an inline handler (`on…` in any casing) — EXCEPT the documented event
139
+ * spelling `on` + Capital, which the constructor converts to a real listener and which therefore
140
+ * never becomes an attribute. The exemption mirrors the constructor's test byte for byte, because
141
+ * `ONCLICK` must not slip through as "looks like the event spelling": the constructor only
142
+ * converts a lowercase `on`, so only that exact shape is exempt.
143
+ *
144
+ * Returns the hint for the diagnostic, or null for a permitted key.
145
+ */
146
+ const refusedSink = (key) => {
147
+ const first = key[0];
148
+ if (first === '.' || first === '!') {
149
+ const name = key.slice(1);
150
+ if (name === 'innerHTML' || name === 'outerHTML')
151
+ return 'write it in the template — html`<div .innerHTML=${trusted}>` — sanitized first (renderer README, security note)';
152
+ /**
153
+ * `element.__proto__ = value` is not a property write — it hits Object.prototype's
154
+ * `__proto__` ACCESSOR and replaces the element's prototype, stripping every DOM method it
155
+ * has. The element is bricked, and the crash lands LATER, in whatever binding next calls
156
+ * `removeAttribute` on it — a data-driven render-kill with a stack that names the renderer
157
+ * and not the data. Found by the run-14 payload probe; there is no legitimate use, so unlike
158
+ * `.innerHTML` there is no template spelling to point at.
159
+ */
160
+ /** The deliberate twin of the same refusal in `AttrPart`'s constructor (`./renderer.ts`), for
161
+ * the template spellings `.name` / `!name`. Independent bundles, neither imports the other, so
162
+ * the rule is copied — and a fix visits both. `tests/dangerous-binding-matrix.test.mjs` holds
163
+ * the two spellings to the same answer. */
164
+ if (name === '__proto__')
165
+ return "assigning __proto__ replaces the element's own prototype and destroys it — no property write does this, and no use of it is legitimate";
166
+ return null;
167
+ }
168
+ if (first === '?' || first === '@' || first === '&')
169
+ return null;
170
+ /** The event spelling the constructor converts: `on` + Capital, lowercase `on` only. */
171
+ if (first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91)
172
+ return null;
173
+ const lower = key.toLowerCase();
174
+ if (lower === 'srcdoc')
175
+ return 'an inline iframe document is markup injection by definition — bind it in the template if you truly mean it';
176
+ if (lower.length > 2 && lower.startsWith('on'))
177
+ return 'an inline handler attribute is code from data — pass a function as `on` + Capital (onClick) or `@click` instead';
178
+ return null;
179
+ };
180
+ /** Module-local: one identity comparison, not a global symbol-registry lookup per binding. */
181
+ const UNSET = Symbol();
182
+ /**
183
+ * A class, not an object literal, so `handleEvent` exists once on the prototype. As a literal it was
184
+ * a fresh closure per bound key — allocation proportional to the size of every props bag.
185
+ */
186
+ class Binding {
187
+ _kind;
188
+ _name;
189
+ _element;
190
+ /** What the element held before this binding took over. Releasing puts it back. */
191
+ _initial;
192
+ _committed = UNSET;
193
+ _handler = null;
194
+ constructor(element, key) {
195
+ const first = key[0];
196
+ let kind = first === '.'
197
+ ? PROPERTY
198
+ : first === '?'
199
+ ? BOOLEAN
200
+ : first === '@'
201
+ ? EVENT
202
+ : first === '&'
203
+ ? REF
204
+ : first === '!'
205
+ ? LIVE
206
+ : ATTR;
207
+ let name = kind ? key.slice(1) : key;
208
+ /** `on` + a capital: `onClick` ≡ `@click`. All-lowercase `onclick` never reaches here — it is
209
+ * an inline-handler attribute, which `refusedSink` rejects before a binding exists. */
210
+ if (kind === ATTR && first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91) {
211
+ kind = EVENT;
212
+ name = key.slice(2).toLowerCase();
213
+ }
214
+ this._kind = kind;
215
+ this._name = name;
216
+ this._element = element;
217
+ this._initial =
218
+ kind === ATTR
219
+ ? element.getAttribute(name)
220
+ : kind === BOOLEAN
221
+ ? element.hasAttribute(name)
222
+ : kind === PROPERTY || kind === LIVE
223
+ ? element[name]
224
+ : null;
225
+ }
226
+ /**
227
+ * **Two shapes, because `addEventListener` takes two** — the same rule `AttrPart.handleEvent`
228
+ * applies, and it did not travel here when that one was fixed. A function is called with the
229
+ * element as `this`; an object with a `handleEvent` method is invoked through it — the platform's
230
+ * own `EventListenerObject` protocol, which every engine accepts. This called `.call()`
231
+ * unconditionally, so `spread({ onClick: { handleEvent } })` bound without complaint, never
232
+ * fired, and raised `this._handler.call is not a function` on **every** dispatch — while the
233
+ * identical value through a written `@click` worked.
234
+ *
235
+ * Anything else is inert rather than throwing, exactly as there: development names it at the
236
+ * binding (see the event branch in `write`), where the mistake still is.
237
+ */
238
+ handleEvent(event) {
239
+ const handler = this._handler;
240
+ if (typeof handler === 'function')
241
+ handler.call(this._element, event);
242
+ else if (typeof handler?.handleEvent === 'function')
243
+ handler.handleEvent(event);
244
+ }
245
+ }
246
+ /**
247
+ * Keyed by the **part**, not the element.
248
+ *
249
+ * Keyed by element, `<div ${spread(a)} ${spread(b)}>` shares one map: whichever applies second sees
250
+ * the other's keys as absent from its own props and releases them. Measured — the first spread's
251
+ * attributes silently vanished. The part is one per element-position slot, which is exactly the
252
+ * ownership boundary, and the renderer reuses it across renders.
253
+ */
254
+ const owned = new WeakMap();
255
+ const write = (binding, value) => {
256
+ /** One comparison per key per render — the same dirty check a written binding gets. */
257
+ /**
258
+ * A live property asks the element rather than its own memory — see `AttrPart` in the renderer.
259
+ * The dirty check is what keeps a field someone typed into, and it is exactly wrong for a control
260
+ * whose DOM state changes when a *sibling* is interacted with, a radio group being the case.
261
+ */
262
+ if (binding._kind === LIVE) {
263
+ binding._committed = value;
264
+ const live = binding._element;
265
+ if (live[binding._name] !== value)
266
+ live[binding._name] = value;
267
+ return;
268
+ }
269
+ if (value === binding._committed)
270
+ return;
271
+ binding._committed = value;
272
+ const element = binding._element;
273
+ const name = binding._name;
274
+ const kind = binding._kind;
275
+ if (kind === ATTR) {
276
+ if (value == null)
277
+ element.removeAttribute(name);
278
+ else {
279
+ if (true ) {
280
+ const complaint = attributeValueComplaint(element.localName, name, value);
281
+ if (complaint !== null)
282
+ console.warn(`[vera] ${complaint}`);
283
+ }
284
+ /**
285
+ * `` `${value}` ``, never `String(value)` — the two differ on exactly one thing and it is the
286
+ * one that matters here. `String(sym)` returns `"Symbol(s)"` while every DOM conversion and
287
+ * `@verajs/ssr`'s own escaper throw, so this sink was the ONLY one of three that accepted a
288
+ * symbol, writing to the client an attribute the server refuses to produce. The rule was
289
+ * already recorded in `@verajs/ssr`'s `escapeHtml` — "serving Symbol(s) into markup the client
290
+ * cannot reproduce does not make anything work, it moves the failure across the boundary and
291
+ * strips the context" — and this file used the other form anyway. A house rule written down
292
+ * in one of three homes is a house rule in none of them.
293
+ */
294
+ element.setAttribute(name, `${value}`);
295
+ }
296
+ }
297
+ else if (kind === PROPERTY) {
298
+ element[name] = value;
299
+ }
300
+ else if (kind === BOOLEAN) {
301
+ element.toggleAttribute(name, !!value);
302
+ }
303
+ else if (kind === REF) {
304
+ /**
305
+ * `&name` is the written form's ref sigil (`<input &field=${myRef} />`), and it was the one
306
+ * binding kind a spread could not express: the key fell through to `ATTR` and
307
+ * `setAttribute('&field', …)` threw on the client while the server wrote `&field="[object
308
+ * Object]"` into the markup. A function is called with the element, an object gets it assigned
309
+ * to `.value` — the same two shapes `AttrPart` handles.
310
+ */
311
+ if (typeof value === 'function')
312
+ value(element);
313
+ else if (value !== null && typeof value === 'object')
314
+ value.value = element;
315
+ }
316
+ else {
317
+ /**
318
+ * A listener is validated when a *user* clicks, which in development may be never — so it is
319
+ * checked where it is written, the same rule `AttrPart` applies to `@event`. `false` stays
320
+ * silent: `{ onClick: enabled && onClick }` is the ordinary conditional form and already
321
+ * behaves correctly, since `handleEvent` finds nothing callable and does nothing.
322
+ */
323
+ if (true && value != null && value !== false && typeof value !== 'function' &&
324
+ typeof value?.handleEvent !== 'function')
325
+ console.warn(`[vera] spread: @${name} on <${element.localName}> was given ` +
326
+ `${typeof value === 'object' ? 'an object with no handleEvent method' : `a ${typeof value}`}, ` +
327
+ `which cannot listen — the event will do nothing.\n` +
328
+ `Pass a function, or an object with a handleEvent method. A missing handler is ` +
329
+ `\`undefined\` or \`false\`, both of which are fine; this is neither.`);
330
+ if (binding._handler === null && value != null)
331
+ element.addEventListener(name, binding);
332
+ binding._handler = value ?? null;
333
+ }
334
+ };
335
+ /**
336
+ * A key that disappeared between renders restores what the element held before the binding existed.
337
+ *
338
+ * This is the question Lit's PR is stuck on, and the trap is asking it as "what value means absent".
339
+ * For a property there is no answer: assigning `undefined` runs through coercing setters, so
340
+ * dropping `.value` yields `""` rather than reverting, and `delete` cannot remove a prototype
341
+ * accessor. Asked instead as *"undo what this binding did"* it is well defined for every kind and
342
+ * never invents a value the author did not write — the initial state was, by definition, acceptable
343
+ * before the binding arrived.
344
+ *
345
+ * And asked that way it needs no code of its own: releasing is writing the initial value back.
346
+ * `null` removes an attribute, `false` untoggles a boolean, `undefined` restores a property to
347
+ * pristine, and an event handler falls to `null` — every case the existing commit already handles.
348
+ * The separate per-kind teardown this replaced was fourteen lines saying the same thing twice.
349
+ *
350
+ * Deliberately unguarded by an ownership check (`is the value still the one we wrote?`). That only
351
+ * matters when a component reassigns a property its parent is binding, which is already confused;
352
+ * per principle #3 the machinery waits for evidence rather than being pre-built.
353
+ */
354
+ function apply(element, part) {
355
+ const props = this._props;
356
+ let bindings = owned.get(part);
357
+ if (bindings === undefined)
358
+ owned.set(part, (bindings = new Map()));
359
+ /**
360
+ * Counted here rather than with `Object.keys(props).length`, which allocates an array on every
361
+ * render of every spread — garbage in the render path, for a number already being walked.
362
+ */
363
+ let count = 0;
364
+ for (const key in props) {
365
+ count++;
366
+ /**
367
+ * Counted before it is skipped, so the size comparison below still describes the key set — a
368
+ * refused key that changed the count would make every render look like a removal.
369
+ */
370
+ if (UNSAFE_NAME.test(key[0] === '.' || key[0] === '?' || key[0] === '@' || key[0] === '&' ? key.slice(1) : key)) {
371
+ if (true )
372
+ console.warn(`[vera] spread: ignoring the key ${JSON.stringify(key)} — an attribute name ` +
373
+ `cannot contain whitespace, a quote, \`<\`, \`>\`, \`/\`, \`=\` or a control character, ` +
374
+ `and one that cannot be written into markup would not survive server rendering.`);
375
+ continue;
376
+ }
377
+ /** Counted above for the same reason the unsafe skip is. */
378
+ const refused = refusedSink(key);
379
+ if (refused !== null) {
380
+ if (true )
381
+ console.warn(`[vera] spread: refusing ${JSON.stringify(key)} — spread names arrive at runtime, which is ` +
382
+ `exactly the property that makes this sink unreviewable; ${refused}.`);
383
+ continue;
384
+ }
385
+ let binding = bindings.get(key);
386
+ if (binding === undefined)
387
+ bindings.set(key, (binding = new Binding(element, key)));
388
+ write(binding, props[key]);
389
+ }
390
+ /**
391
+ * A size mismatch is the only way a key can have gone: every key in `props` was just visited, so
392
+ * equal sizes means equal sets. The steady-state render of an unchanged shape — overwhelmingly the
393
+ * common case — costs one integer comparison, not a scan.
394
+ */
395
+ if (bindings.size !== count) {
396
+ for (const [key, binding] of bindings) {
397
+ if (key in props)
398
+ continue;
399
+ bindings.delete(key);
400
+ write(binding, binding._initial);
401
+ }
402
+ }
403
+ }
404
+ /**
405
+ * The server half of the protocol: hand back every binding, resolved, and let the renderer that
406
+ * asked decide what belongs in markup.
407
+ *
408
+ * Deliberately *not* a serializer. This package knows what a key means — `.value` is a property,
409
+ * `?disabled` a boolean, `onClick` an event — and nothing else. Whether a property belongs in
410
+ * server markup (`value`, `checked`, `selected` do; the rest are client state) and how a value is
411
+ * escaped are `@verajs/ssr`'s decisions, and principle #8 wants escaping in exactly one place. So
412
+ * this returns data, never a string.
413
+ *
414
+ * Kinds are single characters rather than the module's numeric constants, because this crosses a
415
+ * package boundary: `a`ttribute, `b`oolean, `p`roperty, `e`vent, `r`ef. A ref is client state with
416
+ * no markup, exactly like an event, and the serializer drops both.
417
+ */
418
+ function attributes() {
419
+ const out = [];
420
+ for (const key in this._props) {
421
+ /** The client refusal, applied at the serializer boundary too — one predicate, both renders.
422
+ * Without this, a refused key was merely inert in the browser and LIVE in server markup. */
423
+ if (refusedSink(key) !== null)
424
+ continue;
425
+ const first = key[0];
426
+ /** `!` reports as a property: the server has nothing to re-read, so it serializes as `.` does. */
427
+ const kind = first === '.' || first === '!'
428
+ ? 'p'
429
+ : first === '?'
430
+ ? 'b'
431
+ : first === '@'
432
+ ? 'e'
433
+ : first === '&'
434
+ ? 'r'
435
+ : 'a';
436
+ if (kind !== 'a') {
437
+ out.push([kind, key.slice(1), this._props[key]]);
438
+ }
439
+ else if (first === 'o' && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 64 && key.charCodeAt(2) < 91) {
440
+ out.push(['e', key.slice(2).toLowerCase(), this._props[key]]);
441
+ }
442
+ else {
443
+ out.push(['a', key, this._props[key]]);
444
+ }
445
+ }
446
+ return out;
447
+ }
448
+ /**
449
+ * Branded rather than duck-typed: the element position already means "element ref", and a props bag
450
+ * is indistinguishable from a ref object — `{ value: 5 }` is legitimately either.
451
+ */
452
+ const spread = (props) => {
453
+ /**
454
+ * **A props bag that is not an object is iterated anyway, and a browser accepts the result.**
455
+ *
456
+ * Everything below reads `props` with `Object.keys`/`Object.entries`, which answer for any value:
457
+ * a **string** yields its character indices, so `spread('text')` sets four attributes named `0`,
458
+ * `1`, `2`, `3` — measured in Chromium, with no error and no warning. A number, a boolean and
459
+ * `null` yield nothing at all, so `spread(someUndefinedVariable)` applies no props and says
460
+ * nothing, which reads as a renderer that ignored the spread.
461
+ *
462
+ * **jsdom hides this rather than catching it.** It implements the XML Name production and throws
463
+ * `InvalidCharacterError` on `setAttribute('0', …)`, so a probe under jsdom sees a loud failure
464
+ * for the case a real engine performs silently — the inverse of the usual trap, and the reason
465
+ * this was verified in a browser before being called a defect (`tests/browser/spread-names.test.js`
466
+ * records the engines' actual rule).
467
+ *
468
+ * Warned and ignored rather than thrown, which is exactly what an unusable *key* already does a
469
+ * few lines above: one bad props bag should not cost the render.
470
+ *
471
+ * **The message is `true `-only; the refusal is not.** They were both inside the guard, which
472
+ * made the two builds behave differently for the same code — and differently in the direction that
473
+ * hides the bug. Measured: `spread('text')` applies nothing in development, so the app under test
474
+ * looks fine; in production the string is iterated by character index and the element ends up with
475
+ * attributes named `0`, `1`, `2` and `3` (under jsdom, an `InvalidCharacterError` instead — the
476
+ * usual inversion, and why this was measured against both builds rather than reasoned about).
477
+ *
478
+ * A diagnostic belongs in `true `. A guard that changes what the program does cannot, or the
479
+ * development build stops being a faithful model of the production one, which is the property that
480
+ * makes testing in it worth anything. Costs 27 B gzipped (842 → 869, A-B-A) and buys the two builds agreeing.
481
+ */
482
+ if (props === null || typeof props !== 'object' || Array.isArray(props)) {
483
+ if (true )
484
+ console.warn(`[vera] spread: ignoring a props bag that is not a plain object — received ` +
485
+ `${Array.isArray(props) ? 'an array' : typeof props === 'object' ? 'null' : `a ${typeof props}`}. ` +
486
+ `A string is iterated by character index, so \`spread('text')\` would set attributes named ` +
487
+ `0, 1, 2 and 3; anything else applies nothing at all. This is usually an import or a ` +
488
+ `property that resolved to something unexpected.`);
489
+ props = {};
490
+ }
491
+ return {
492
+ _props: props,
493
+ _$apply$: apply,
494
+ _$attrs$: attributes,
495
+ };
496
+ };
497
+
498
+ /**
499
+ * `@verajs/renderer/tag` — an element whose **tag name** is decided at runtime.
500
+ *
501
+ * A template renderer bakes tag names into its statics; that is what makes template identity work
502
+ * and what every fast path in this renderer depends on. So a runtime tag cannot be a binding — it
503
+ * has to become part of the statics *before* the renderer sees the template, which is what this
504
+ * entry does. Downstream nothing changes: the renderer, `@verajs/ssr` and hydration all receive an
505
+ * ordinary template and are unaware this exists.
506
+ *
507
+ * ```js
508
+ * import { html, tag } from '@verajs/renderer/tag';
509
+ *
510
+ * const HEADING = { 1: tag`h1`, 2: tag`h2`, 3: tag`h3` };
511
+ * const H = HEADING[state.level];
512
+ * html`<${H} class="title">${state.text}</${H}>`;
513
+ * ```
514
+ *
515
+ * **A tag is also a JSX component**, so the same value works in both notations with no compiler
516
+ * change — `<H className="title">{state.text}</H>` compiles to `H({…})`, which is exactly what a
517
+ * capitalized JSX tag already compiles to.
518
+ *
519
+ * Additive, like `@verajs/renderer/spread` and unlike the other entries: it inlines no renderer
520
+ * internals, so it is safe alongside any of them.
521
+ */
522
+ /** The brand a tag carries. `_$…$` is exempt from this package's `/^_[a-z]/` property mangling. */
523
+ const STATIC = '_$static$';
524
+ /**
525
+ * Spliced statics, keyed by the call site's own `strings` array and then by the tags in it.
526
+ *
527
+ * The cache is the whole reason this works. `_shape === value.strings` is the renderer's identity
528
+ * check, so a fresh array per render would never match and every render would rebuild the subtree.
529
+ * A `WeakMap` on the call site's array means the entries die with the module that holds them, and
530
+ * the inner keys are bounded by the tags in the source — which is exactly what `tag` refusing a
531
+ * string guarantees.
532
+ */
533
+ const caches = new WeakMap();
534
+ /**
535
+ * The `html` to use in a template containing a runtime tag. With no tags in it, this is the
536
+ * ordinary template shape and costs one loop.
537
+ *
538
+ * It builds `{ _$litType$: 1, strings, values }` directly rather than calling core's `html`, so this
539
+ * entry keeps the renderer's independence from core. The consequence is that a `setHtml` swap does
540
+ * not reach here — which is right, since a swapped `html` belongs to a different renderer and this
541
+ * is a renderer feature.
542
+ */
543
+ const html = (strings, ...values) => {
544
+ let key = '';
545
+ for (let i = 0; i < values.length; i++) {
546
+ const value = values[i];
547
+ if (value && value[STATIC] !== undefined)
548
+ key += `${i}:${value[STATIC]};`;
549
+ /**
550
+ * A non-tag in **tag position** — `<${name}>` with a string. The refusal is the whole security
551
+ * property of this entry, and it lived only in `tag` itself, which guards interpolation into a
552
+ * tag literal. Reaching the position through `html` instead produced no error and no element:
553
+ * the base scanner reads the expression as an element ref on a tag with no name, and the page
554
+ * gets escaped punctuation where the markup should be.
555
+ *
556
+ * The static before a value is what identifies the position, so this is the one place that can
557
+ * see it. `true `-only; production carries neither the check nor the text.
558
+ */
559
+ else if (true && (strings[i].endsWith('<') || strings[i].endsWith('</'))) {
560
+ throw new Error(`tag: a ${value === null ? 'null' : typeof value} cannot become markup. ` +
561
+ `Only a tag may be interpolated into tag position:\n\n` +
562
+ ` const heading = tag\`h\${level}\`; // built from other tags\n` +
563
+ ` html\`<\${heading}>…</\${heading}>\`\n\n` +
564
+ `That is what keeps the set of tags an app can produce fixed by its source.`);
565
+ }
566
+ }
567
+ if (key === '')
568
+ return { ['_$litType$']: 1, strings, values };
569
+ let byTags = caches.get(strings);
570
+ if (byTags === undefined)
571
+ caches.set(strings, (byTags = new Map()));
572
+ let spliced = byTags.get(key);
573
+ if (spliced === undefined) {
574
+ spliced = [];
575
+ let run = strings[0];
576
+ for (let i = 0; i < values.length; i++) {
577
+ const value = values[i];
578
+ if (value && value[STATIC] !== undefined)
579
+ run += value[STATIC] + strings[i + 1];
580
+ else {
581
+ spliced.push(run);
582
+ run = strings[i + 1];
583
+ }
584
+ }
585
+ spliced.push(run);
586
+ byTags.set(key, spliced);
587
+ }
588
+ const bindings = [];
589
+ for (let i = 0; i < values.length; i++) {
590
+ const value = values[i];
591
+ if (!(value && value[STATIC] !== undefined))
592
+ bindings.push(value);
593
+ }
594
+ return { ['_$litType$']: 1, strings: spliced, values: bindings };
595
+ };
596
+ /**
597
+ * React's names, mapped the way `@verajs/jsx` maps them on a written element — so `<H1
598
+ * className="t" disabled={d}>` and `<h1 className="t" disabled={d}>` mean the same thing.
599
+ *
600
+ * Not cosmetic. Passed through raw, `disabled={false}` becomes the attribute `disabled="false"`,
601
+ * and any value at all disables the control; `className` lands as `classname` and never applies.
602
+ *
603
+ * Deliberately duplicated from the transform rather than shared through a package: the two are
604
+ * build-time and runtime, and `tests/jsx-name-mapping.test.mjs` asserts they agree on every key —
605
+ * which is the drift protection a shared module would have bought, without the dependency.
606
+ */
607
+ const NAME_MAP = { className: 'class', htmlFor: 'for' };
608
+ const PROPERTIES = { value: '.value', checked: '.checked' };
609
+ const DEFAULTS = { defaultValue: 'value', defaultChecked: '?checked' };
610
+ /**
611
+ * The props that name a BINDING rather than an attribute — and the reason this table is here and
612
+ * not in the transform's twin.
613
+ *
614
+ * The compiler must NOT rewrite these on a component: `<Card ref={r}>` hands `ref` to `Card`, which
615
+ * decides what it means, exactly as React does. But a tag's component forwards to a real element,
616
+ * so at THIS boundary — and only here — `ref` has a binding to become. Before 2026-09-12 it had
617
+ * none: it fell through to the attribute sink and `<H ref={r}>` wrote the FUNCTION'S SOURCE TEXT
618
+ * into the DOM as `ref="el => (got = el)"`, which under SSR shipped the closure body to the client,
619
+ * while the identical `<h1 ref={r}>` bound correctly.
620
+ */
621
+ const BINDINGS = { ref: '&ref' };
622
+ const BOOLEAN_ATTRIBUTES = new Set([
623
+ 'disabled', 'hidden', 'readonly', 'required', 'open', 'selected', 'multiple',
624
+ 'autofocus', 'autoplay', 'controls', 'loop', 'muted', 'playsinline', 'inert', 'reversed',
625
+ ]);
626
+ const jsxName = (key) => NAME_MAP[key] ?? PROPERTIES[key] ?? DEFAULTS[key] ?? BINDINGS[key] ?? (BOOLEAN_ATTRIBUTES.has(key) ? `?${key}` : key);
627
+ /**
628
+ * Declares a tag name.
629
+ *
630
+ * **A string can never become one.** Only another tag may be interpolated, so the set of tags an
631
+ * app can produce is fixed by its source — which is what keeps a tag out of reach of a request, and
632
+ * incidentally what bounds the template cache. There is no `unsafeStatic` here for the same reason
633
+ * there is no `unsafeHTML`: a sanctioned opt-out reads as blessed in tutorials and in review.
634
+ */
635
+ const tag = (strings, ...values) => {
636
+ /**
637
+ * A *template tag*, so it is written `` tag`h1` `` and not `tag('h1')`. The call form is the
638
+ * likelier mistake of the two and failed with `Cannot read properties of undefined (reading '0')`,
639
+ * which says nothing about either.
640
+ */
641
+ if (true && (!strings || !Array.isArray(strings.raw)))
642
+ throw new TypeError(`tag: expected a template literal and received ${String(strings)}. ` +
643
+ "It is a tagged template — write tag`h1`, not tag('h1').");
644
+ let text = strings[0];
645
+ for (let i = 0; i < values.length; i++) {
646
+ const value = values[i];
647
+ if (!value || value[STATIC] === undefined)
648
+ throw new Error('tag: only another tag may be interpolated — a string cannot become markup');
649
+ text += value[STATIC] + strings[i + 1];
650
+ }
651
+ /**
652
+ * **A tag's text must be an element NAME.** Until this, it was an unconstrained string spliced
653
+ * straight into the statics — so `` tag`div onclick=x` `` produced markup rather than a tag, and
654
+ * the name of this export was a description of intent rather than of behaviour.
655
+ *
656
+ * The concrete failure it closes is a cache collision. Spliced statics key on
657
+ * `` `${i}:${text};` `` per tag, joined with separators the text was free to contain, so two
658
+ * DIFFERENT tag assignments at one call site could derive the same key and reuse each other's
659
+ * markup. Measured: at a two-tag call site, `(a, "b;1:c")` and `("a;1:b", c)` both derive
660
+ * `"0:a;1:b;1:c;"`, and the second render came back as the FIRST one's markup.
661
+ *
662
+ * Escaping the separators would have fixed that one collision. Constraining the name fixes the
663
+ * class — no name can contain a separator, so no key can be ambiguous, and the export delivers
664
+ * what it is called. A closed grammar beats a wider escape, which is the same ruling this audit
665
+ * reached for the attribute-value sink.
666
+ *
667
+ * Unconditional, like the interpolation refusal above and unlike the shape check: both are about
668
+ * what may become markup, and a production build is where that matters most.
669
+ */
670
+ if (!/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(text))
671
+ throw new Error(
672
+ /**
673
+ * The THROW is unconditional; its EXPLANATION is not. Carrying the full sentence cost 178 B
674
+ * gzipped here — most of a 1.9 KB entry — for text an author reads once and a production
675
+ * page never reaches. Core's static-render refusal is shaped the same way for the same
676
+ * measurement.
677
+ */
678
+ true
679
+ ? `tag: ${JSON.stringify(text)} is not an element name. A tag names ONE element — letters, ` +
680
+ `then letters, digits, '.', '_' or '-' — and nothing else becomes markup here.\n` +
681
+ `Attributes and content belong in the template: html\`<\${heading} class="title">…</\${heading}>\`.`
682
+ : 'tag: not an element name');
683
+ /**
684
+ * The tag is a function, which is what makes it a JSX component: the compiler emits `H({…})` for
685
+ * a capitalized tag, and this is what receives that call. `children` is JSX's own key; everything
686
+ * else goes through `spread`, since the names are not known when this template is written.
687
+ */
688
+ const self = (({ children, key, dangerouslySetInnerHTML: rawHtml, ...props } = {}) => {
689
+ /**
690
+ * **`key` and `dangerouslySetInnerHTML` come out of the bag by name**, because neither is an
691
+ * attribute and the sink they fell into accepts anything. `key` became the literal attribute
692
+ * `key="7"` on the element AND cost the list its identity — rows then reconciled positionally,
693
+ * so focus, scroll and input state followed the index rather than the item.
694
+ *
695
+ * `@verajs/jsx` consumes `key` into `keyed(…)` before this is ever called, so the compiled path
696
+ * never reaches here. This is the HAND-CALL backstop — `H({ key: id })` — where no compiler is
697
+ * looking, and dropping it silently would be a refusal with no channel, hence the warning.
698
+ */
699
+ if (true && key !== undefined)
700
+ console.warn(`[vera] tag: \`key\` does nothing on a tag component and has been dropped — a key marks a ` +
701
+ `template for list reconciliation, and this call returns one rather than being one.\n` +
702
+ `In JSX, write it and the compiler handles it: \`<Row key=\${id}>\` becomes ` +
703
+ `\`keyed(id, Row({…}))\`. Calling by hand, wrap it yourself: \`keyed(id, Row({…}))\`.`);
704
+ /**
705
+ * **`dangerouslySetInnerHTML` cannot work here, and that is a security property rather than a
706
+ * gap.** A tag reaches its element through `spread`, and `spread` REFUSES `.innerHTML` on
707
+ * purpose: its names arrive at runtime, which is what makes that sink unreviewable. Mapping the
708
+ * prop was tried and measured — 37 B for a value `spread` then declined, so the bytes bought a
709
+ * console message. Refused here instead, where the reason can be said.
710
+ */
711
+ if (true && rawHtml !== undefined)
712
+ console.warn(`[vera] tag: \`dangerouslySetInnerHTML\` is not available on a tag component and has been ` +
713
+ `dropped. A tag binds through \`spread\`, whose names are only known at runtime — so it ` +
714
+ `refuses \`.innerHTML\` outright rather than open an unreviewable HTML sink.\n` +
715
+ `Write the element directly, with the value sanitized first: ` +
716
+ `html\`<\${Tag} .innerHTML=\${trusted}>\` (see the renderer README's security note).`);
717
+ const mapped = {};
718
+ for (const name in props)
719
+ mapped[jsxName(name)] = props[name];
720
+ return html `<${self} ${spread(mapped)}>${children}</${self}>`;
721
+ });
722
+ self[STATIC] = text;
723
+ return self;
724
+ };
725
+
726
+ export { BOOLEAN_ATTRIBUTES, html, jsxName, tag };
727
+ //# sourceMappingURL=vera-renderer-tag.js.map