@verajs/ssr 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +522 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +102 -0
  4. package/dist/vera/escaping.d.ts +155 -0
  5. package/dist/vera/escaping.js +293 -0
  6. package/dist/vera/events.d.ts +41 -0
  7. package/dist/vera/events.js +162 -0
  8. package/dist/vera/frames.d.ts +38 -0
  9. package/dist/vera/frames.js +195 -0
  10. package/dist/vera/index.d.ts +48 -0
  11. package/dist/vera/index.js +480 -0
  12. package/{types → dist/vera}/nodes.d.ts +389 -302
  13. package/dist/vera/nodes.js +2339 -0
  14. package/dist/vera/parse.d.ts +53 -0
  15. package/dist/vera/parse.js +485 -0
  16. package/dist/vera/reflections.d.ts +566 -0
  17. package/dist/vera/reflections.js +820 -0
  18. package/dist/vera/registry.d.ts +14 -0
  19. package/{src → dist}/vera/registry.js +5 -1
  20. package/dist/vera/report.d.ts +27 -0
  21. package/dist/vera/report.js +56 -0
  22. package/dist/vera/scan.d.ts +37 -0
  23. package/dist/vera/scan.js +143 -0
  24. package/dist/vera/select.d.ts +40 -0
  25. package/dist/vera/select.js +261 -0
  26. package/dist/vera/serializer.d.ts +39 -0
  27. package/dist/vera/serializer.js +1521 -0
  28. package/dist/vera/shim.d.ts +42 -0
  29. package/dist/vera/shim.js +853 -0
  30. package/dist/vera/slots.d.ts +5 -0
  31. package/dist/vera/slots.js +104 -0
  32. package/dist/vera/stylesheets.d.ts +62 -0
  33. package/dist/vera/stylesheets.js +180 -0
  34. package/dist/vera/tokenizer.d.ts +32 -0
  35. package/dist/vera/tokenizer.js +553 -0
  36. package/dist/vera/types.d.ts +121 -0
  37. package/dist/vera/views.d.ts +63 -0
  38. package/dist/vera/views.js +245 -0
  39. package/package.json +12 -13
  40. package/src/vera/escaping.js +0 -135
  41. package/src/vera/events.js +0 -164
  42. package/src/vera/frames.js +0 -102
  43. package/src/vera/index.js +0 -1187
  44. package/src/vera/nodes.js +0 -2294
  45. package/src/vera/parse.js +0 -381
  46. package/src/vera/reflections.js +0 -811
  47. package/src/vera/select.js +0 -234
  48. package/src/vera/serializer.js +0 -1080
  49. package/src/vera/shim.js +0 -761
  50. package/src/vera/stylesheets.js +0 -155
  51. package/src/vera/views.js +0 -240
  52. package/types/escaping.d.ts +0 -27
  53. package/types/events.d.ts +0 -4
  54. package/types/frames.d.ts +0 -12
  55. package/types/index.d.ts +0 -13
  56. package/types/parse.d.ts +0 -19
  57. package/types/reflections.d.ts +0 -657
  58. package/types/registry.d.ts +0 -8
  59. package/types/select.d.ts +0 -5
  60. package/types/serializer.d.ts +0 -26
  61. package/types/shim.d.ts +0 -23
  62. package/types/stylesheets.d.ts +0 -53
  63. package/types/views.d.ts +0 -26
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `@verajs/ssr`'s cross-file and public types (CODE-PRINCIPLES §1 Types). It imports nothing from inside this package,
3
+ * so it sits at the root of the package's import graph; a type that NAMES one of this package's runtime classes (the
4
+ * DOM shim's `ElementShim` and the rest) cannot be hoisted above that class, and stays beside it in `nodes.ts`.
5
+ * A type one file uses stays in that file, unexported.
6
+ */
7
+ /**
8
+ * A template value as the serializer receives it: a tagged template literal's result, or data shaped like one. `strings`
9
+ * is `unknown` on purpose — only a literal's strings array, which owns `raw`, makes a template (`isLiteral` in
10
+ * `serializer.ts`); anything else is rendered as the text any object renders as, never as markup.
11
+ */
12
+ export type SsrTemplate = {
13
+ readonly strings: unknown;
14
+ readonly values: readonly unknown[];
15
+ readonly _$litType$?: number;
16
+ };
17
+ /** The custom-element definitions this process has seen, by tag name — filled as component modules execute. */
18
+ export type SsrRegistry = Map<string, CustomElementConstructor>;
19
+ /**
20
+ * The options `renderToString` and `renderToStringAsync` take — each one is documented on `renderToString`. Checked at
21
+ * run time too, so a JavaScript caller passing the wrong kind of value gets a `TypeError` naming the option.
22
+ */
23
+ export type SsrRenderOptions = {
24
+ readonly tag?: string;
25
+ readonly attributes?: string | Record<string, unknown>;
26
+ readonly props?: Record<string, unknown>;
27
+ readonly children?: string;
28
+ readonly seen?: Set<string>;
29
+ readonly base?: string | URL;
30
+ readonly static?: boolean;
31
+ readonly location?: string | URL;
32
+ /**
33
+ * How long `renderToStringAsync` waits on promises a component starts before serving what it has (ms; 2000). `0`
34
+ * waits for nothing — it is not "no limit", which cannot be asked for.
35
+ */
36
+ readonly timeout?: number;
37
+ };
38
+ /**
39
+ * What a render resolves to: the entry element's markup, the hoisted styles this render is responsible for (escaped, for
40
+ * the caller to place in a `<style>`), and the document title the render left set.
41
+ */
42
+ export type SsrRenderResult = {
43
+ html: string;
44
+ styles: string;
45
+ title: string;
46
+ };
47
+ /**
48
+ * **The tag scanner's state** (`tokenizer.ts`), shared by the template compiler and the `.innerHTML` and component
49
+ * scans. Internal to this package: nothing in its public API names these.
50
+ */
51
+ /**
52
+ * An element that changes how what follows it parses, as the scan opened it: its name (what closes it, and what a
53
+ * template's end writes to close it), the foreign and `<template>` depths BEFORE it (restored when it closes), and the namespace its
54
+ * content is read in — `html`, `svg`, `math`, or `''` when unknown (a template that starts at a foreign depth its
55
+ * parent gave it cannot know which namespace that is, so it recognizes no integration point: the safe side).
56
+ */
57
+ export type Open = {
58
+ readonly name: string;
59
+ readonly foreign: number;
60
+ readonly inert: number;
61
+ readonly space: string;
62
+ };
63
+ export type Phase = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
64
+ /** Where the scan stands at the end of a static — carried into the next one, and what a template's end must close. */
65
+ export type ScanState = {
66
+ readonly inTag: boolean;
67
+ /** Which tokenizer state the tag being read is in — `OUTSIDE` when there is none (see the phases above). */
68
+ readonly phase: Phase;
69
+ readonly inValue: boolean;
70
+ readonly quote: string;
71
+ readonly rawTag: string;
72
+ readonly tagName: string;
73
+ readonly attrName: string;
74
+ readonly serial: number;
75
+ readonly closing: boolean;
76
+ readonly inert: number;
77
+ /** The open comment's closer — `-->` for a comment, `>` for a bogus one (`<!x`, `<?x`, `</ x`) — or `''`. */
78
+ readonly comment: string;
79
+ readonly textTag: string;
80
+ readonly foreign: number;
81
+ /** Mutated by `scanTag`, so every fresh state owns its own. */
82
+ readonly opens: Open[];
83
+ /** The `encoding` of the tag being read, while one is — what makes an `annotation-xml` an integration point. */
84
+ readonly encoding: string;
85
+ readonly attrRaw: string;
86
+ };
87
+ /** A state before any static has been scanned: it carries none of the offsets a scan reports about its own text. */
88
+ export interface ScanStart extends ScanState {
89
+ readonly opened?: undefined;
90
+ readonly attrStart?: undefined;
91
+ readonly valueStart?: undefined;
92
+ readonly nameAt?: undefined;
93
+ readonly tagAt?: undefined;
94
+ }
95
+ /** What `scanTag` answers: the state carried on, and where in THIS text the last attribute to open here starts. */
96
+ export interface ScanResult extends ScanState {
97
+ readonly opened: boolean;
98
+ readonly attrStart: number;
99
+ readonly valueStart: number;
100
+ /** Where, in THIS text, the name of the attribute whose value opened here starts — `0` when it began earlier. */
101
+ readonly nameAt: number;
102
+ /** Where, in THIS text, the tag still open at its end began — `-1` when it began in an earlier one, or none is. */
103
+ readonly tagAt: number;
104
+ /** Where, in THIS text, raw content last began (after its element's start tag) — `-1` for none. */
105
+ readonly rawFrom: number;
106
+ /** Where, in THIS text, raw content first ended (its end tag's `<`) — `-1` for none. */
107
+ readonly rawUntil: number;
108
+ }
109
+ /**
110
+ * A tag the component scan collects (`scanTag`'s `tags`): its span in the markup, its name as the tokenizer reads it,
111
+ * whether it is an end tag, and whether it is LIVE — a start tag in HTML, where the parser creates an element a custom
112
+ * element definition upgrades (never inside `<svg>`/`<math>` outside an integration point). Only names with a `-`
113
+ * are collected, and none inside `<template>` content.
114
+ */
115
+ export type ScannedTag = {
116
+ readonly at: number;
117
+ readonly end: number;
118
+ readonly name: string;
119
+ readonly closing: boolean;
120
+ readonly live: boolean;
121
+ };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The element properties that are a *view of an attribute* — `dataset`, `style`, `classList`, `part`.
3
+ *
4
+ * Each returns an object whose every write goes through to the attribute it reflects, because a
5
+ * plain object would accept `this.dataset.x = 'y'` and lose it. Shared from here rather than written
6
+ * per class: `classList` and `part` are one token list over two attribute names, and having them as
7
+ * two copies is how the shims drifted apart the first time.
8
+ */
9
+ import type { ElementShim } from './nodes.js';
10
+ /**
11
+ * `element.style` as this DOM answers it: `cssText`, the declaration count, the CSSOM methods, and every
12
+ * property by name — camel-cased or custom — read as its value or `''`.
13
+ */
14
+ type StyleView = {
15
+ cssText: string;
16
+ readonly length: number;
17
+ setProperty(name: unknown, value: unknown, priority?: unknown): void;
18
+ removeProperty(name: unknown): string;
19
+ getPropertyValue(name: unknown): string;
20
+ getPropertyPriority(name: unknown): string;
21
+ item(index: number): string;
22
+ [property: string]: unknown;
23
+ };
24
+ /**
25
+ * `dataset` and `style` are **views over an attribute**, not stores of their own: an assignment that
26
+ * does not reach the markup is an assignment the server loses. Written as proxies over the element
27
+ * so `this.dataset.userId = '7'` and `this.style.color = 'red'` end up in the tag, which is what
28
+ * they do in a browser.
29
+ */
30
+ export declare const datasetView: (element: ElementShim) => Record<string, string | undefined>;
31
+ /**
32
+ * A `DOMTokenList` over a space-separated attribute — `class` for `classList`, `part` for `part`.
33
+ *
34
+ * Shared because they are the same thing: `classList` was written first and `part` would have been
35
+ * a second copy of it, which is how `ElementShim` and `ShadowRootShim` came to disagree.
36
+ */
37
+ export declare const tokenListView: (element: ElementShim, attribute: string) => {
38
+ add: (...names: string[]) => void;
39
+ remove: (...names: string[]) => void;
40
+ toggle: (name: string, force?: boolean) => boolean;
41
+ /** Replaces in place, and answers `false` without writing when the old token is not there. */
42
+ replace: (oldToken: string, newToken: string) => boolean;
43
+ contains: (name: string) => boolean;
44
+ /**
45
+ * `supports` throws for these two lists in every engine — `class` and `part` define no supported
46
+ * tokens, and the spec says a `DOMTokenList` with none raises `TypeError`. Present and throwing
47
+ * is the accurate shim; absent would be a `TypeError` too, but the wrong one.
48
+ */
49
+ supports: () => never;
50
+ item: (index: number) => string | null;
51
+ forEach: (callback: (token: string, index: number, list: string[]) => void, thisArg?: unknown) => void;
52
+ keys: () => ArrayIterator<number>;
53
+ values: () => ArrayIterator<string>;
54
+ entries: () => ArrayIterator<[number, string]>;
55
+ /** `String(el.classList)` is the attribute's value, not `[object Object]`. */
56
+ toString: () => string;
57
+ get value(): string;
58
+ set value(text: unknown);
59
+ readonly length: number;
60
+ [Symbol.iterator]: () => ArrayIterator<string>;
61
+ };
62
+ export declare const styleView: (element: ElementShim) => StyleView;
63
+ export {};
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The element properties that are a *view of an attribute* — `dataset`, `style`, `classList`, `part`.
3
+ *
4
+ * Each returns an object whose every write goes through to the attribute it reflects, because a
5
+ * plain object would accept `this.dataset.x = 'y'` and lose it. Shared from here rather than written
6
+ * per class: `classList` and `part` are one token list over two attribute names, and having them as
7
+ * two copies is how the shims drifted apart the first time.
8
+ */
9
+ /** `backgroundColor` -> `background-color`, for the `style` and `dataset` views below. */
10
+ const dashed = (name) => name.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());
11
+ /**
12
+ * `dataset` and `style` are **views over an attribute**, not stores of their own: an assignment that
13
+ * does not reach the markup is an assignment the server loses. Written as proxies over the element
14
+ * so `this.dataset.userId = '7'` and `this.style.color = 'red'` end up in the tag, which is what
15
+ * they do in a browser.
16
+ */
17
+ export const datasetView = (element) => new Proxy({}, {
18
+ get: (_, key) => element.getAttribute(`data-${dashed(String(key))}`) ?? undefined,
19
+ set: (_, key, value) => (element.setAttribute(`data-${dashed(String(key))}`, value), true),
20
+ deleteProperty: (_, key) => (element.removeAttribute(`data-${dashed(String(key))}`), true),
21
+ has: (_, key) => element.hasAttribute(`data-${dashed(String(key))}`),
22
+ });
23
+ /**
24
+ * A `DOMTokenList` over a space-separated attribute — `class` for `classList`, `part` for `part`.
25
+ *
26
+ * Shared because they are the same thing: `classList` was written first and `part` would have been
27
+ * a second copy of it, which is how `ElementShim` and `ShadowRootShim` came to disagree.
28
+ */
29
+ export const tokenListView = (element, attribute) => {
30
+ const tokens = () => (element.getAttribute(attribute) ?? '').split(/\s+/).filter(Boolean);
31
+ /**
32
+ * **Emptying an attribute is not removing it.** A browser leaves `class=""` behind when the last
33
+ * token goes, and only leaves the attribute absent when it was never there to begin with. Removing
34
+ * it outright made the server's markup differ from the client's for an element that had ever
35
+ * carried a class, which is the whole class of difference this package exists not to produce.
36
+ */
37
+ const write = (list) => {
38
+ if (list.length)
39
+ element.setAttribute(attribute, list.join(' '));
40
+ else if (element.hasAttribute(attribute))
41
+ element.setAttribute(attribute, '');
42
+ };
43
+ /**
44
+ * A token has to be a token. A browser throws on an empty string and on one containing whitespace,
45
+ * with those two names, and it is worth throwing here for the same reason `connectedCallback` is
46
+ * refused when it is `async`: code that cannot work in the browser should not quietly work here.
47
+ */
48
+ const check = (...names) => {
49
+ for (const name of names) {
50
+ if (name === '')
51
+ throw new DOMException('The token provided must not be empty.', 'SyntaxError');
52
+ if (/\s/.test(String(name)))
53
+ throw new DOMException(`The token provided ('${name}') contains HTML space characters, which are not valid in tokens.`, 'InvalidCharacterError');
54
+ }
55
+ };
56
+ const list = {
57
+ add: (...names) => {
58
+ check(...names);
59
+ const current = tokens();
60
+ for (const name of names)
61
+ if (!current.includes(name))
62
+ current.push(name);
63
+ write(current);
64
+ },
65
+ remove: (...names) => {
66
+ check(...names);
67
+ write(tokens().filter((token) => !names.includes(token)));
68
+ },
69
+ toggle: (name, force) => {
70
+ check(name);
71
+ const current = tokens();
72
+ const wanted = force ?? !current.includes(name);
73
+ write(wanted ? [...current.filter((token) => token !== name), name] : current.filter((token) => token !== name));
74
+ return wanted;
75
+ },
76
+ /** Replaces in place, and answers `false` without writing when the old token is not there. */
77
+ replace: (oldToken, newToken) => {
78
+ check(oldToken, newToken);
79
+ const current = tokens();
80
+ const at = current.indexOf(oldToken);
81
+ if (at === -1)
82
+ return false;
83
+ current[at] = newToken;
84
+ write(current.filter((token, index) => current.indexOf(token) === index));
85
+ return true;
86
+ },
87
+ contains: (name) => tokens().includes(name),
88
+ /**
89
+ * `supports` throws for these two lists in every engine — `class` and `part` define no supported
90
+ * tokens, and the spec says a `DOMTokenList` with none raises `TypeError`. Present and throwing
91
+ * is the accurate shim; absent would be a `TypeError` too, but the wrong one.
92
+ */
93
+ supports: () => {
94
+ throw new TypeError('supports() is not applicable to this attribute.');
95
+ },
96
+ item: (index) => tokens()[index] ?? null,
97
+ forEach: (callback, thisArg) => tokens().forEach(callback, thisArg),
98
+ keys: () => tokens().keys(),
99
+ values: () => tokens().values(),
100
+ entries: () => tokens().entries(),
101
+ /** `String(el.classList)` is the attribute's value, not `[object Object]`. */
102
+ toString: () => element.getAttribute(attribute) ?? '',
103
+ get value() {
104
+ return element.getAttribute(attribute) ?? '';
105
+ },
106
+ set value(text) {
107
+ element.setAttribute(attribute, String(text));
108
+ },
109
+ get length() {
110
+ return tokens().length;
111
+ },
112
+ [Symbol.iterator]: () => tokens()[Symbol.iterator](),
113
+ };
114
+ /** `list[0]` is indexed access on a real `DOMTokenList`, which a plain object cannot answer. */
115
+ return new Proxy(list, {
116
+ get: (target, key, receiver) => typeof key === 'string' && /^\d+$/.test(key) ? tokens()[Number(key)] : Reflect.get(target, key, receiver),
117
+ has: (target, key) => (typeof key === 'string' && /^\d+$/.test(key) ? Number(key) < tokens().length : key in target),
118
+ });
119
+ };
120
+ /**
121
+ * The declarations in a `style` attribute, split on the semicolons that actually separate them.
122
+ *
123
+ * **A plain `split(';')` corrupts a value that contains one**, and the common case is not exotic:
124
+ * `background: url("data:image/svg+xml;base64,…")` is how an inline SVG is written, and splitting it
125
+ * produced `background: url("data:image/svg+xml` as one declaration and `base64,…")` as another —
126
+ * so the *markup* came out as `background: url("data:x; color: red;`, an unterminated `url(` with
127
+ * the rest of the declaration eaten. A quoted `;` in `content` did the same.
128
+ *
129
+ * Quotes and parentheses both nest a semicolon, and CSS allows one inside either.
130
+ */
131
+ const declarations = (text) => {
132
+ const out = [];
133
+ let start = 0;
134
+ let depth = 0;
135
+ let quote = '';
136
+ for (let at = 0; at < text.length; at++) {
137
+ const ch = text[at];
138
+ if (quote) {
139
+ if (ch === '\\')
140
+ at++;
141
+ else if (ch === quote)
142
+ quote = '';
143
+ }
144
+ else if (ch === '"' || ch === "'")
145
+ quote = ch;
146
+ else if (ch === '(')
147
+ depth++;
148
+ else if (ch === ')' && depth > 0)
149
+ depth--;
150
+ else if (ch === ';' && depth === 0) {
151
+ out.push(text.slice(start, at));
152
+ start = at + 1;
153
+ }
154
+ }
155
+ out.push(text.slice(start));
156
+ return out;
157
+ };
158
+ export const styleView = (element) => {
159
+ /** `[name, value, priority]` per declaration, in source order. */
160
+ const read = () => {
161
+ /**
162
+ * A loop rather than `map().filter(Boolean)`: the filter does not narrow, so the entries reach
163
+ * `new Map` typed as `(any[] | null)[]` and the type check rejects them. Building the map directly
164
+ * says the same thing without a cast.
165
+ */
166
+ const rules = new Map();
167
+ for (const rule of declarations(element.getAttribute('style') ?? '')) {
168
+ const at = rule.indexOf(':');
169
+ if (at === -1)
170
+ continue;
171
+ const name = rule.slice(0, at).trim();
172
+ let value = rule.slice(at + 1).trim();
173
+ let priority = '';
174
+ const important = /\s*!\s*important$/i.exec(value);
175
+ if (important) {
176
+ value = value.slice(0, important.index).trim();
177
+ priority = 'important';
178
+ }
179
+ if (name && value)
180
+ rules.set(name, { value, priority });
181
+ }
182
+ return rules;
183
+ };
184
+ /**
185
+ * Each declaration ends in a semicolon, including the last, because that is what a browser writes
186
+ * into the attribute when you set a property — `style.color = 'red'` gives `style="color: red;"`.
187
+ * Dropping the final one made every component that styles itself disagree with the client on its
188
+ * own host attribute.
189
+ *
190
+ * An emptied `style` stays as `style=""` rather than being removed, for the reason the token list
191
+ * above does the same: a browser removes the declarations, not the attribute.
192
+ */
193
+ const write = (rules) => {
194
+ const text = [...rules]
195
+ .map(([name, { value, priority }]) => `${name}: ${value}${priority ? ' !important' : ''};`)
196
+ .join(' ');
197
+ if (text)
198
+ element.setAttribute('style', text);
199
+ else if (element.hasAttribute('style'))
200
+ element.setAttribute('style', '');
201
+ };
202
+ /** A custom property keeps its name verbatim; everything else is camel-cased in JS and dashed in CSS. */
203
+ const cssName = (key) => (key.startsWith('--') ? key : dashed(key));
204
+ const methods = {
205
+ setProperty: (name, value, priority = '') => write(read().set(cssName(String(name)), { value: String(value), priority: priority ? 'important' : '' })),
206
+ removeProperty: (name) => {
207
+ const rules = read();
208
+ const key = cssName(String(name));
209
+ const previous = rules.get(key)?.value ?? '';
210
+ rules.delete(key);
211
+ write(rules);
212
+ return previous;
213
+ },
214
+ getPropertyValue: (name) => read().get(cssName(String(name)))?.value ?? '',
215
+ getPropertyPriority: (name) => read().get(cssName(String(name)))?.priority ?? '',
216
+ item: (index) => [...read().keys()][index] ?? '',
217
+ };
218
+ /** The target is never read — every trap answers from the attribute — so it is typed as the proxy's answers. */
219
+ return new Proxy({}, {
220
+ get: (_, key) => {
221
+ if (key === 'cssText')
222
+ return element.getAttribute('style') ?? '';
223
+ if (key === 'length')
224
+ return read().size;
225
+ if (key in methods)
226
+ return methods[key];
227
+ if (typeof key === 'string' && /^\d+$/.test(key))
228
+ return methods.item(Number(key));
229
+ return read().get(cssName(String(key)))?.value ?? '';
230
+ },
231
+ set: (_, key, value) => {
232
+ /** Round-tripped rather than stored verbatim, so `cssText = 'color: red'` normalizes the way a browser does. */
233
+ if (key === 'cssText') {
234
+ element.setAttribute('style', String(value));
235
+ write(read());
236
+ }
237
+ else if (value === '' || value == null)
238
+ methods.removeProperty(String(key));
239
+ else
240
+ write(read().set(cssName(String(key)), { value: String(value), priority: '' }));
241
+ return true;
242
+ },
243
+ has: (_, key) => key === 'cssText' || key === 'length' || key in methods || read().has(cssName(String(key))),
244
+ });
245
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verajs/ssr",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Vera-native server-side rendering. Node-only, plain ESM, zero dependencies.",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -14,20 +14,20 @@
14
14
  "author": "Brian Grider <hello@verajs.com>",
15
15
  "homepage": "https://verajs.dev",
16
16
  "type": "module",
17
- "main": "./src/vera/index.js",
17
+ "main": "./dist/vera/index.js",
18
18
  "exports": {
19
19
  ".": {
20
- "types": "./types/index.d.ts",
21
- "default": "./src/vera/index.js"
20
+ "types": "./dist/vera/index.d.ts",
21
+ "default": "./dist/vera/index.js"
22
22
  }
23
23
  },
24
24
  "peerDependencies": {
25
- "@verajs/core": "^0.3.1",
26
- "@verajs/styles": "^0.1.2"
25
+ "@verajs/core": "^0.4.0",
26
+ "@verajs/styles": "^0.1.3"
27
27
  },
28
28
  "files": [
29
- "src",
30
- "types"
29
+ "dist",
30
+ "!dist/vera/types.js"
31
31
  ],
32
32
  "keywords": [
33
33
  "ssr",
@@ -40,7 +40,7 @@
40
40
  "publishConfig": {
41
41
  "access": "public"
42
42
  },
43
- "types": "./types/index.d.ts",
43
+ "types": "./dist/vera/index.d.ts",
44
44
  "scripts": {
45
45
  "build": "wireit"
46
46
  },
@@ -50,16 +50,15 @@
50
50
  "../core:build",
51
51
  "../styles:build"
52
52
  ],
53
- "command": "npx tsc -p tsconfig.json --noEmit false --declaration --emitDeclarationOnly --rootDir src/vera --outDir types",
53
+ "command": "npx tsc -p tsconfig.json",
54
54
  "clean": "if-file-deleted",
55
55
  "files": [
56
- "src/**/*.js",
56
+ "src/**/*.ts",
57
57
  "tsconfig.json",
58
- "../../tsconfig.json",
59
58
  "../tsconfig/base.json"
60
59
  ],
61
60
  "output": [
62
- "types/**/*.d.ts"
61
+ "dist/**"
63
62
  ]
64
63
  }
65
64
  }
@@ -1,135 +0,0 @@
1
- /**
2
- * Escaping at the render boundary, and the elements that must not be escaped at all.
3
- *
4
- * One place decides what becomes a character reference, because escaping in two places
5
- * double-escapes and escaping in none is an injection. `<style>`, `<script>`, `<textarea>` and
6
- * `<title>` hold **text**, not markup: a browser does not decode a character reference inside them,
7
- * so escaping there does not protect anything and does corrupt the content — a `static styles` with
8
- * `.a > .b` shipped a broken stylesheet until that was understood.
9
- */
10
-
11
- const NEEDS_ESCAPE = /[&<>"'\r]/;
12
-
13
- const ESCAPE = /[&<>"'\r]/g;
14
-
15
- /**
16
- * Escaping is the hottest thing in a large render, and most values have nothing to escape.
17
- *
18
- * Asking first is worth it: 200 escapes of ordinary text measured 9.60 µs going straight to
19
- * `replace` against 3.03 µs testing first — and text that *does* need escaping came out slightly
20
- * ahead too (21.73 vs 20.03), because a global `replace` sets up more than a single `test` does. On
21
- * a 100-row table of clean data that is a quarter of the whole render.
22
- */
23
-
24
- /**
25
- * **Carriage return is here for correctness, not for safety.**
26
- *
27
- * The HTML input-stream preprocessor rewrites CR and CRLF to a single LF *before* tokenization, so a
28
- * raw `\r` written into markup does not survive being parsed — the server renders `a\r\nb` and the
29
- * client reads back `a\nb`. Nothing is injected and nothing looks wrong; the two sides simply hold
30
- * different strings, which is a hydration mismatch on every render of anything carrying a Windows
31
- * newline: a `<textarea>` value, a CSV cell, a string from an HTTP payload.
32
- *
33
- * Character references are resolved *after* preprocessing, so `&#13;` does survive. **Verified in
34
- * Chromium, Firefox and WebKit**, all three identical: raw CRLF parses to `[97, 10, 98]` and
35
- * `a&#13;\nb` parses to `[97, 13, 10, 98]`, in text and in attribute values alike.
36
- *
37
- * **NUL is the other character the preprocessor rewrites, and it is not fixable here.** A raw NUL is
38
- * dropped in text and becomes U+FFFD in an attribute, and `&#0;` is a parse error that also becomes
39
- * U+FFFD — there is no spelling that round-trips, so a string containing NUL cannot be server
40
- * rendered faithfully by anyone. It is listed as a limitation in the README rather than silently
41
- * transformed here, because turning it into U+FFFD would make the markup lie about what the
42
- * component rendered without making the two sides agree.
43
- *
44
- * Precomputed, because building `'&#' + c.charCodeAt(0) + ';'` per character is the slow half.
45
- */
46
- const ESCAPED = { '&': '&#38;', '<': '&#60;', '>': '&#62;', '"': '&#34;', "'": '&#39;', '\r': '&#13;' };
47
-
48
- export const escapeHtml = (value) => {
49
- /**
50
- * `` `${value}` `` rather than `String(value)`: identical for everything except a **symbol**,
51
- * which `String` special-cases into its description while every DOM conversion on the client
52
- * throws. Serving `Symbol(s)` into markup the client cannot reproduce is the leniency this
53
- * package's README warns about — it does not make anything work, it moves the failure across the
54
- * boundary and strips the context.
55
- */
56
- const text = typeof value === 'string' ? value : `${value}`;
57
- return NEEDS_ESCAPE.test(text) ? text.replace(ESCAPE, (character) => ESCAPED[character]) : text;
58
- };
59
-
60
- /**
61
- * Neutralise a `</style>` sequence inside CSS text.
62
- *
63
- * `<style>` is a raw-text element: its content is not HTML, so `escapeHtml` cannot be used here —
64
- * it would turn every `>` in a selector into `&#62;` and break the stylesheet. The only sequence
65
- * that matters is the end tag, because it is the one thing the HTML tokenizer looks for while
66
- * inside the element. A value interpolated into `css` and carrying `</style>` therefore closes the
67
- * element and everything after it parses as markup.
68
- *
69
- * `<\/style` is valid CSS — a backslash escape is legal in identifiers and strings, and renders
70
- * identically — while the tokenizer no longer matches an end tag. Applied here, at the render
71
- * boundary, rather than in `css` itself: escaping at the source would corrupt the constructed
72
- * stylesheet path, which is the double-escaping principle #8 warns about. It also catches a
73
- * sequence assembled across several interpolations, which source-side escaping cannot see.
74
- *
75
- * **Deliberately duplicated** in `@verajs/styles` (`escapeStyleText` there is the same three
76
- * lines). It cannot be shared: the obvious home is `@verajs/shared-utils`, which is private and
77
- * inlined at build time, and `@verajs/ssr` publishes its `src` with **no dependencies at all** — an
78
- * import of a package that is never published would break the published tarball. Two copies of a
79
- * security rule is a real risk, so `tests/ssr-escaping.test.mjs` asserts the two agree on the
80
- * payloads that matter rather than trusting they will be edited together.
81
- */
82
- export const escapeStyleText = (value) => `${value}`.replace(/<\/(style)/gi, '<\\/$1');
83
-
84
- /**
85
- * The same neutralisation, for whichever RAWTEXT element the value landed in.
86
- *
87
- * `<style>` and `<script>` are the only two: a browser does not decode a character reference inside
88
- * either, so escaping their content protects nothing and corrupts it. Interpolating `.a > .b` into a
89
- * stylesheet produced `.a &#62; .b` — a selector matching nothing — while the client, which sets
90
- * text through the DOM and never re-parses, rendered it correctly. Every interpolated stylesheet was
91
- * broken on the server and right in the browser.
92
- *
93
- * Writing raw means the element's own end tag has to come out of the value instead, or it closes the
94
- * element and everything after it parses as markup. `<\/style` is valid CSS and `<\/script` is the
95
- * canonical form in JavaScript; both render identically and neither is seen by the tokenizer. Only
96
- * the end tag matters, because it is the only sequence the tokenizer looks for while inside.
97
- *
98
- * `<title>` and `<textarea>` are **RCDATA** — references *are* decoded there — so they keep ordinary
99
- * escaping, which is also what the client produces for them.
100
- */
101
- const RAW_TEXT_CLOSERS = { style: /<\/(style)/gi, script: /<\/(script)/gi };
102
-
103
- export const escapeRawText = (value, tag) => {
104
- const closer = RAW_TEXT_CLOSERS[tag];
105
- return closer ? `${value}`.replace(closer, '<\\/$1') : escapeHtml(value);
106
- };
107
-
108
- /**
109
- * Elements whose content is text rather than markup. Setting `textContent` on one of these stores
110
- * the text as written: inside `<style>` or `<script>` a character reference is **not** decoded, so
111
- * escaping there does not protect anything and does corrupt the content.
112
- */
113
- /**
114
- * Elements a parser reads the children of as text.
115
- *
116
- * `iframe` and `noscript` were absent, so this DOM built a tree no browser builds:
117
- * `<noscript><img src="x"></noscript>` parsed to an element here and `querySelectorAll('noscript img')`
118
- * answered **1** where every engine answers 0, because the content is a text node.
119
- *
120
- * Measured across Chromium, Firefox and WebKit rather than read off a spec — and jsdom is not the
121
- * oracle for this one. It parses with scripting *disabled*, so it agrees with the old list about
122
- * `noscript` and all three real engines disagree with both.
123
- */
124
- export const RAW_TEXT_ELEMENTS = new Set(['style', 'script', 'textarea', 'title', 'iframe', 'noscript']);
125
-
126
- /**
127
- * Elements that have no end tag. Writing one is not merely redundant — a parser reads `</br>` as
128
- * *another* `<br>`, so `appendChild(createElement('br'))` served `<br></br>` and rendered two line
129
- * breaks where the client has one. The same content assigned as a markup string was already correct,
130
- * so the two paths disagreed with each other as well as with the browser.
131
- */
132
- export const VOID_ELEMENTS = new Set([
133
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
134
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
135
- ]);