@verajs/ssr 0.2.1 → 0.3.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 (63) hide show
  1. package/README.md +507 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +98 -0
  4. package/dist/vera/escaping.d.ts +142 -0
  5. package/dist/vera/escaping.js +267 -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 +2322 -0
  14. package/dist/vera/parse.d.ts +37 -0
  15. package/dist/vera/parse.js +390 -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 +1372 -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 +528 -0
  36. package/dist/vera/types.d.ts +117 -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,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.0",
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
- ]);
@@ -1,164 +0,0 @@
1
- /**
2
- * Event dispatch with a propagation path.
3
- *
4
- * **Bubbling was absent, and the README said why**: this DOM held children as a string, so there was
5
- * no ancestor chain to walk and an event reached its own target's listeners and stopped. Child nodes
6
- * are retained now, so the chain exists and the reason has expired — a component dispatching a
7
- * `CustomEvent` that a parent listens for worked in the browser and did nothing on the server.
8
- *
9
- * The listeners live here rather than in the `EventTarget` these classes extend, because that one
10
- * cannot be asked to run *only* its capturing listeners: a direct dispatch runs them all, so the
11
- * three phases could not be told apart. What it did give — `once`, `handleEvent` objects, and a
12
- * return value reflecting `preventDefault` — is reproduced here and covered by the same tests.
13
- */
14
-
15
- /** @param {any} options */
16
- const capturing = (options) => (typeof options === 'boolean' ? options : Boolean(options?.capture));
17
-
18
- /**
19
- * The path from a node out to its furthest ancestor, crossing a shadow boundary only for an event
20
- * declared `composed` — which is the rule that keeps a component's internals private.
21
- *
22
- * @param {any} node @param {boolean} composed
23
- */
24
- export const pathFrom = (node, composed) => {
25
- const path = [];
26
- for (let current = node; current; ) {
27
- path.push(current);
28
- if (current._parent) {
29
- current = current._parent;
30
- continue;
31
- }
32
- current = composed && current._host ? current._host : null;
33
- }
34
- return path;
35
- };
36
-
37
- /** @param {any} node */
38
- export const addListener = (node, type, callback, options) => {
39
- if (!callback) return;
40
- const listeners = (node._listeners ??= new Map());
41
- const key = `${type}`;
42
- const entries = listeners.get(key) ?? [];
43
- const capture = capturing(options);
44
- /** The platform ignores a duplicate registration of the same callback in the same phase. */
45
- if (entries.some((entry) => entry.callback === callback && entry.capture === capture)) return;
46
- entries.push({ callback, capture, once: Boolean(options?.once) });
47
- listeners.set(key, entries);
48
- options?.signal?.addEventListener?.('abort', () => removeListener(node, type, callback, options));
49
- };
50
-
51
- /** @param {any} node */
52
- export const removeListener = (node, type, callback, options) => {
53
- const entries = node._listeners?.get(`${type}`);
54
- if (!entries) return;
55
- const capture = capturing(options);
56
- const index = entries.findIndex((entry) => entry.callback === callback && entry.capture === capture);
57
- if (index !== -1) entries.splice(index, 1);
58
- };
59
-
60
- /**
61
- * `Event.CAPTURING_PHASE`, `AT_TARGET`, `BUBBLING_PHASE` — the numbers every engine reports, and
62
- * which `installShims` also puts on `Event.prototype` where a browser has them and Node does not.
63
- */
64
- const PHASES = { capture: 1, target: 2, bubble: 3 };
65
-
66
- /**
67
- * Run the listeners registered on one node for one phase.
68
- *
69
- * @param {any} node @param {any} event @param {'capture' | 'target' | 'bubble'} phase
70
- * @param {() => boolean} immediatelyStopped
71
- */
72
- const runListeners = (node, event, phase, immediatelyStopped) => {
73
- const entries = node._listeners?.get(event.type);
74
- if (!entries?.length) return;
75
- Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
76
- /**
77
- * **`eventPhase` said `NONE` for the whole dispatch**, where every engine reports 1, 2 and 3.
78
- * `event.eventPhase === event.AT_TARGET` is the ordinary way a component asks "was this mine, or
79
- * a descendant's?", so the server took the other branch from the client for an event both of them
80
- * dispatched — with nothing to show for it until the two renders disagreed somewhere else.
81
- */
82
- Object.defineProperty(event, 'eventPhase', { value: PHASES[phase], configurable: true });
83
- /** A copy, because a listener may add or remove listeners while this runs. */
84
- for (const entry of [...entries]) {
85
- if (phase === 'capture' && !entry.capture) continue;
86
- if (phase === 'bubble' && entry.capture) continue;
87
- if (entry.once) removeListener(node, event.type, entry.callback, entry.capture);
88
- try {
89
- if (typeof entry.callback === 'function') entry.callback.call(node, event);
90
- else entry.callback?.handleEvent?.(event);
91
- } catch (error) {
92
- /** A listener that throws must not take the dispatch down, exactly as in a browser. */
93
- console.error('[vera] ssr: a listener threw', error);
94
- }
95
- if (immediatelyStopped()) return;
96
- }
97
- };
98
-
99
- /**
100
- * @param {any} node @param {any} event
101
- * @returns {boolean} false when a cancelable event was prevented, as the platform reports
102
- */
103
- export const dispatch = (node, event) => {
104
- /**
105
- * **An `Event`, not something shaped like one.** This checked `typeof event.type === 'string'`,
106
- * which `{ type: 'click' }` satisfies — so the server accepted a dispatch every engine refuses
107
- * with a `TypeError`, and the code that made it got as far as the client before failing. Being
108
- * lenient here does not make anything work; it moves the failure and strips the context.
109
- */
110
- if (!(event instanceof Event))
111
- throw new TypeError(`Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.`);
112
-
113
- const path = pathFrom(node, Boolean(event.composed));
114
- let stopped = false;
115
- let immediate = false;
116
-
117
- /**
118
- * Wrapped rather than read back: `cancelBubble` reflects `stopPropagation` on this platform's
119
- * `Event`, but nothing exposes `stopImmediatePropagation`, and the two have to be told apart —
120
- * one ends the walk, the other ends only the current node's listeners.
121
- */
122
- const original = {
123
- stop: event.stopPropagation?.bind(event),
124
- immediate: event.stopImmediatePropagation?.bind(event),
125
- };
126
- Object.defineProperty(event, 'stopPropagation', {
127
- value: () => {
128
- stopped = true;
129
- original.stop?.();
130
- },
131
- configurable: true,
132
- });
133
- Object.defineProperty(event, 'stopImmediatePropagation', {
134
- value: () => {
135
- stopped = true;
136
- immediate = true;
137
- original.immediate?.();
138
- },
139
- configurable: true,
140
- });
141
- Object.defineProperty(event, 'target', { value: node, configurable: true });
142
- Object.defineProperty(event, 'composedPath', { value: () => [...path], configurable: true });
143
-
144
- const immediatelyStopped = () => {
145
- if (!immediate) return false;
146
- immediate = false;
147
- return true;
148
- };
149
-
150
- /** Capturing runs outermost first, and never on the target itself. */
151
- for (let index = path.length - 1; index >= 1 && !stopped; index--)
152
- runListeners(path[index], event, 'capture', immediatelyStopped);
153
-
154
- if (!stopped) runListeners(path[0], event, 'target', immediatelyStopped);
155
-
156
- if (event.bubbles)
157
- for (let index = 1; index < path.length && !stopped; index++)
158
- runListeners(path[index], event, 'bubble', immediatelyStopped);
159
-
160
- Object.defineProperty(event, 'currentTarget', { value: null, configurable: true });
161
- /** Back to `NONE` once the dispatch is over, as the platform reports for a finished event. */
162
- Object.defineProperty(event, 'eventPhase', { value: 0, configurable: true });
163
- return !event.defaultPrevented;
164
- };