@shadow-js/web 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/dev/attributes.d.ts +10 -3
- package/dist/dev/attributes.js +27 -49
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +6 -2
- package/dist/dev/class-style.js +24 -7
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.d.ts +11 -2
- package/dist/dev/control-flow/dynamic.js +56 -39
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/portal.js +2 -0
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/element.js +1 -1
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +15 -44
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/insert.d.ts +15 -5
- package/dist/dev/insert.js +35 -13
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -1
- package/dist/dev/internal/claim.js +18 -2
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/diagnostics.d.ts +7 -3
- package/dist/dev/internal/diagnostics.js +14 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +20 -2
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/react-names.js +25 -61
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +3 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +5 -2
- package/dist/dev/jsx/html.d.ts +1 -0
- package/dist/dev/resource-hints.js +4 -2
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.js +5 -15
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -0
- package/dist/dev/server/attributes.js +5 -1
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +8 -4
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +7 -1
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.js +14 -6
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.js +5 -2
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/raw-text.d.ts +28 -0
- package/dist/dev/server/raw-text.js +66 -0
- package/dist/dev/server/raw-text.js.map +1 -0
- package/dist/dev/server/render.d.ts +2 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/stream.d.ts +1 -1
- package/dist/dev/server/stream.js +2 -2
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +2 -1
- package/dist/dev/server.js +2 -1
- package/dist/dev/spread.js +7 -54
- package/dist/dev/spread.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/resource-hints.js +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/raw-text.js +2 -0
- package/dist/prod/server/raw-text.js.map +1 -0
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/resource-hints.js +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/raw-text.js +2 -0
- package/dist/server/server/raw-text.js.map +1 -0
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server-dev/attributes.js +27 -49
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +24 -7
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +22 -10
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +2 -0
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/element.js +3 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +15 -44
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/insert.js +35 -13
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +18 -2
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +14 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +20 -2
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +25 -61
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +3 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/resource-hints.js +4 -2
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +5 -15
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +5 -1
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +8 -4
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +7 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +14 -6
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +5 -2
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/raw-text.js +86 -0
- package/dist/server-dev/server/raw-text.js.map +1 -0
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/stream.js +2 -2
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +7 -54
- package/dist/server-dev/spread.js.map +1 -1
- package/package.json +3 -2
|
@@ -11,22 +11,16 @@
|
|
|
11
11
|
* `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The
|
|
12
12
|
* families are the first words of the CSS properties SVG takes as attributes, so one rule covers the
|
|
13
13
|
* presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the
|
|
14
|
-
* same names, and a test checks each one.
|
|
14
|
+
* same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are
|
|
15
|
+
* not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.
|
|
15
16
|
*/
|
|
16
|
-
const SVG_PROPERTY_FAMILY = /^(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
"glyphRef",
|
|
24
|
-
"markerHeight",
|
|
25
|
-
"markerUnits",
|
|
26
|
-
"markerWidth",
|
|
27
|
-
"maskContentUnits",
|
|
28
|
-
"maskUnits",
|
|
29
|
-
"textLength"
|
|
17
|
+
const SVG_PROPERTY_FAMILY = /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;
|
|
18
|
+
/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */
|
|
19
|
+
const RENAMED = /* @__PURE__ */ new Map([
|
|
20
|
+
["className", "class"],
|
|
21
|
+
["htmlFor", "for"],
|
|
22
|
+
["httpEquiv", "http-equiv"],
|
|
23
|
+
["acceptCharset", "accept-charset"]
|
|
30
24
|
]);
|
|
31
25
|
/**
|
|
32
26
|
* The attribute name for a props key on an element: HTML names are lower case (what the parser and
|
|
@@ -35,28 +29,27 @@ const SVG_CAMEL_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
|
35
29
|
* @internal
|
|
36
30
|
*/
|
|
37
31
|
function attributeName(name, svg) {
|
|
38
|
-
|
|
39
|
-
if (
|
|
40
|
-
if (name === "httpEquiv") return "http-equiv";
|
|
41
|
-
if (name === "acceptCharset") return "accept-charset";
|
|
32
|
+
const renamed = RENAMED.get(name);
|
|
33
|
+
if (renamed !== void 0) return renamed;
|
|
42
34
|
if (!svg) return name.toLowerCase();
|
|
43
35
|
if (name.includes(":")) return name;
|
|
44
|
-
const
|
|
45
|
-
if (
|
|
46
|
-
|
|
47
|
-
if (xml !== null) return `xml:${lowerFirst(xml[1] ?? "")}`;
|
|
48
|
-
if (SVG_CAMEL_ATTRIBUTES.has(name) || !SVG_PROPERTY_FAMILY.test(name)) return name;
|
|
36
|
+
const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);
|
|
37
|
+
if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;
|
|
38
|
+
if (!SVG_PROPERTY_FAMILY.test(name)) return name;
|
|
49
39
|
return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
50
40
|
}
|
|
51
|
-
function lowerFirst(text) {
|
|
52
|
-
return text.replace(/^[A-Z]/, (letter) => letter.toLowerCase());
|
|
53
|
-
}
|
|
54
41
|
/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */
|
|
55
42
|
const IGNORED_KEYS = /* @__PURE__ */ new Set([
|
|
56
43
|
"key",
|
|
57
44
|
"suppressHydrationWarning",
|
|
58
45
|
"suppressContentEditableWarning"
|
|
59
46
|
]);
|
|
47
|
+
/** React events that bubble under another name. */
|
|
48
|
+
const REACT_EVENTS = /* @__PURE__ */ new Map([
|
|
49
|
+
["focus", "focusin"],
|
|
50
|
+
["blur", "focusout"],
|
|
51
|
+
["doubleclick", "dblclick"]
|
|
52
|
+
]);
|
|
60
53
|
const CHANGE_ON_TYPES = /* @__PURE__ */ new Set([
|
|
61
54
|
"checkbox",
|
|
62
55
|
"radio",
|
|
@@ -72,42 +65,13 @@ const CHANGE_ON_TYPES = /* @__PURE__ */ new Set([
|
|
|
72
65
|
function eventPlan(attribute, tag, type) {
|
|
73
66
|
const reactSpelling = /^on[A-Z]/.test(attribute);
|
|
74
67
|
const capture = reactSpelling && attribute.endsWith("Capture");
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
capture: false,
|
|
79
|
-
passive: false
|
|
80
|
-
};
|
|
81
|
-
const lower = base.toLowerCase();
|
|
82
|
-
if (lower === "change") return {
|
|
83
|
-
type: tag === "textarea" || tag === "input" && (type === null || !CHANGE_ON_TYPES.has(type)) ? "input" : "change",
|
|
84
|
-
capture,
|
|
85
|
-
passive: false
|
|
86
|
-
};
|
|
87
|
-
if (lower === "focus") return {
|
|
88
|
-
type: "focusin",
|
|
89
|
-
capture,
|
|
90
|
-
passive: false
|
|
91
|
-
};
|
|
92
|
-
if (lower === "blur") return {
|
|
93
|
-
type: "focusout",
|
|
94
|
-
capture,
|
|
95
|
-
passive: false
|
|
96
|
-
};
|
|
97
|
-
if (lower === "doubleclick") return {
|
|
98
|
-
type: "dblclick",
|
|
99
|
-
capture,
|
|
100
|
-
passive: false
|
|
101
|
-
};
|
|
102
|
-
if (lower === "wheel") return {
|
|
103
|
-
type: "wheel",
|
|
104
|
-
capture,
|
|
105
|
-
passive: !capture
|
|
106
|
-
};
|
|
68
|
+
const lower = attribute.slice(2, capture ? -7 : void 0).toLowerCase();
|
|
69
|
+
let planned = lower;
|
|
70
|
+
if (reactSpelling) planned = lower === "change" ? tag === "textarea" || tag === "input" && (type === null || !CHANGE_ON_TYPES.has(type)) ? "input" : "change" : REACT_EVENTS.get(lower) ?? lower;
|
|
107
71
|
return {
|
|
108
|
-
type:
|
|
72
|
+
type: planned,
|
|
109
73
|
capture,
|
|
110
|
-
passive:
|
|
74
|
+
passive: reactSpelling && lower === "wheel" && !capture
|
|
111
75
|
};
|
|
112
76
|
}
|
|
113
77
|
export { IGNORED_KEYS, attributeName, eventPlan };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-names.js","names":[],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n
|
|
1
|
+
{"version":3,"file":"react-names.js","names":[],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: ReadonlySet<string> = new Set([\n \"key\",\n \"suppressHydrationWarning\",\n \"suppressContentEditableWarning\",\n]);\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES: ReadonlySet<string> = new Set([\"checkbox\", \"radio\", \"file\"]);\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.has(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAM,sBACJ;;AAGF,MAAM,0BAAuC,IAAI,IAAI;CACnD,CAAC,aAAa,OAAO;CACrB,CAAC,WAAW,KAAK;CACjB,CAAC,aAAa,YAAY;CAC1B,CAAC,iBAAiB,gBAAgB;AACpC,CAAC;;;;;;;AAQD,SAAgB,cAAc,MAAc,KAAsB;CAChE,MAAM,UAAU,QAAQ,IAAI,IAAI;CAChC,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,IAAI,CAAC,KAAK,OAAO,KAAK,YAAY;CAClC,IAAI,KAAK,SAAS,GAAG,GAAG,OAAO;CAC/B,MAAM,WAAW,2BAA2B,KAAK,IAAI;CACrD,IAAI,aAAa,MAAM,OAAO,GAAG,SAAS,GAAG,GAAG,SAAS,EAAE,EAAE,YAAY,IAAI,SAAS;CACtF,IAAI,CAAC,oBAAoB,KAAK,IAAI,GAAG,OAAO;CAC5C,OAAO,KAAK,QAAQ,WAAW,WAAW,IAAI,OAAO,YAAY,GAAG;AACtE;;AAGA,MAAa,+BAAoC,IAAI,IAAI;CACvD;CACA;CACA;AACF,CAAC;;AAUD,MAAM,+BAA4C,IAAI,IAAI;CACxD,CAAC,SAAS,SAAS;CACnB,CAAC,QAAQ,UAAU;CACnB,CAAC,eAAe,UAAU;AAC5B,CAAC;AAED,MAAM,kCAAuC,IAAI,IAAI;CAAC;CAAY;CAAS;AAAM,CAAC;;;;;;;;AASlF,SAAgB,UAAU,WAAmB,KAAa,MAAgC;CACxF,MAAM,gBAAgB,WAAW,KAAK,SAAS;CAC/C,MAAM,UAAU,iBAAiB,UAAU,SAAS,SAAS;CAC7D,MAAM,QAAQ,UAAU,MAAM,GAAG,UAAU,KAAoB,KAAA,CAAS,CAAC,CAAC,YAAY;CACtF,IAAI,UAAU;CACd,IAAI,eACF,UACE,UAAU,WACN,QAAQ,cAAe,QAAQ,YAAY,SAAS,QAAQ,CAAC,gBAAgB,IAAI,IAAI,KACnF,UACA,WACD,aAAa,IAAI,KAAK,KAAK;CAEpC,OAAO;EAAE,MAAM;EAAS;EAAS,SAAS,iBAAiB,UAAU,WAAW,CAAC;CAAQ;AAC3F"}
|
|
@@ -20,10 +20,10 @@ function markLongestIncreasing(values, offset, marks) {
|
|
|
20
20
|
if ((values[tails[middle] ?? 0] ?? 0) < value) low = middle + 1;
|
|
21
21
|
else high = middle;
|
|
22
22
|
}
|
|
23
|
-
previous[index] =
|
|
23
|
+
previous[index] = tails[low - 1] ?? -1;
|
|
24
24
|
tails[low] = index;
|
|
25
25
|
}
|
|
26
|
-
let cursor = tails.
|
|
26
|
+
let cursor = tails.at(-1) ?? -1;
|
|
27
27
|
while (cursor !== -1) {
|
|
28
28
|
marks[(values[cursor] ?? 0) - offset] = 1;
|
|
29
29
|
cursor = previous[cursor] ?? -1;
|
|
@@ -96,10 +96,7 @@ function reconcileNodes(parent, prev, next, end) {
|
|
|
96
96
|
else survivors.push(position);
|
|
97
97
|
}
|
|
98
98
|
if (survivors.length === 0) {
|
|
99
|
-
for (
|
|
100
|
-
const node = next[index];
|
|
101
|
-
if (node !== void 0) parent.insertBefore(node, before);
|
|
102
|
-
}
|
|
99
|
+
for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);
|
|
103
100
|
return;
|
|
104
101
|
}
|
|
105
102
|
const stable = new Uint8Array(nextTail - head);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] ?? 0;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] ?? 0] ?? 0;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] ?? 0;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] ?? 0] ?? 0;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] ?? 0) - offset] = 1;\n cursor = previous[cursor] ?? -1;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index];\n if (node === undefined) continue;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index];\n if (node === undefined) continue;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n}\n"],"mappings":";;AAMA,SAAS,WAAW,QAAc,MAA8B;CAC9D,IAAI,SAAS,KAAA,KAAa,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI;AAC/E;;;;;;AAOA,SAAS,sBAAsB,QAA2B,QAAgB,OAAyB;CAEjG,MAAM,QAAkB,CAAC;CACzB,MAAM,WAAqB,OAAO,UAAU,EAAE;CAC9C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,QAAQ,OAAO,UAAU;EAC/B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xB,MAAM,WAAW,OAAO,IAAI,IAAI;EAChC,IAAI,aAAa,KAAA,GAAW,WAAW,QAAQ,IAAI;OAC9C,UAAU,KAAK,QAAQ;CAC9B;CAKA,IAAI,UAAU,WAAW,GAAG;EAC1B,KAAK,MAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,GAAG,OAAO,aAAa,MAAM,MAAM;EAC/E;CACF;CAEA,MAAM,SAAS,IAAI,WAAW,WAAW,IAAI;CAC7C,sBAAsB,WAAW,MAAM,MAAM;CAC7C,MAAM,UAAU,OAAQ,OAAkC,eAAe;CAEzE,IAAI,aAAa;CACjB,KAAK,IAAI,QAAQ,WAAW,GAAG,SAAS,MAAM,SAAS,GAAG;EACxD,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,QAAQ,UAAU,GAAG;GAC9B,IAAI,WAAW,KAAK,eAAe,QACjC,OAA0B,WAAW,MAAM,UAAU;QAClD,OAAO,aAAa,MAAM,UAAU;EAC3C;EACA,aAAa;CACf;AACF"}
|
|
@@ -13,7 +13,8 @@ function carries(element, attributes) {
|
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* Inserts a hint element once: an identical element already in the head (server-rendered or added
|
|
16
|
-
* earlier) is kept
|
|
16
|
+
* earlier) is kept, and a script already anywhere in the document with the same `src` and `type` is
|
|
17
|
+
* not loaded again. On the server the hint joins the render's head collector, when there is one.
|
|
17
18
|
*/
|
|
18
19
|
function hint(tag, attributes, serverTag = () => void 0) {
|
|
19
20
|
if (isServer) {
|
|
@@ -21,7 +22,8 @@ function hint(tag, attributes, serverTag = () => void 0) {
|
|
|
21
22
|
return;
|
|
22
23
|
}
|
|
23
24
|
if (typeof document === "undefined") return;
|
|
24
|
-
|
|
25
|
+
const same = tag === "script" ? (existing) => existing.getAttribute("src") === attributes["src"] && (existing.getAttribute("type") ?? "") === (attributes["type"] ?? "") : (existing) => carries(existing, attributes);
|
|
26
|
+
for (const existing of (tag === "script" ? document : document.head).querySelectorAll(tag)) if (same(existing)) return;
|
|
25
27
|
const element = document.createElement(tag);
|
|
26
28
|
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
|
|
27
29
|
document.head.append(element);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-hints.js","names":[],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n for (const existing of document.head.querySelectorAll(tag)) {\n if (carries(existing, attributes)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":";;;;AAoEA,SAAS,SAAS,MAAoB;CACpC,MAAM,MAAM,IAAI,IAAI,MAAM,sBAAsB;CAChD,IAAI,IAAI,aAAa,YAAY,IAAI,aAAa,SAChD,MAAM,IAAI,UAEJ,mBAAmB,KAAK,qCAE9B;AAEJ;;AAGA,SAAS,QAAQ,SAAkB,YAAiC;CAClE,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,GACnD,IAAI,QAAQ,aAAa,IAAI,MAAM,OAAO,OAAO;CAEnD,OAAO;AACT;;;;;AAMA,SAAS,KACP,KACA,YACA,kBAA8B,KAAA,GACxB;CACN,IAAI,UAAU;EACZ,UAAU;EACV;CACF;CACA,IAAI,OAAO,aAAa,aAAa;CACrC,KAAK,MAAM,YAAY,SAAS,KAAK,iBAAiB,GAAG,GACvD,IAAI,QAAQ,UAAU,UAAU,GAAG;CAErC,MAAM,UAAU,SAAS,cAAc,GAAG;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,GAAG,QAAQ,aAAa,MAAM,KAAK;CACxF,SAAS,KAAK,OAAO,OAAO;AAC9B;;AAGA,SAAS,WAAW,YAAsE;CACxF,aAAa,QAAQ;EAAE,KAAK;EAAQ,OAAO;CAAW,CAAC;AACzD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,WAAW,MAAc,SAAoC;CAC3E,SAAS,IAAI;CACb,MAAM,aAAyB;EAC7B,KAAK;EACL;EACA,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AAO;EACP,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAE1D,GAAG,WAAW;EAAE,KAAK;EAAW;EAAM,IAAI;CAAS,CAAC,CAAC;AAC/E;;;;;;;;;;;;;;;;;AAkBA,SAAgB,cAAc,MAAc,SAAoC;CAC9E,SAAS,IAAI;CAMb,KACE,UACA;EANA,KAAK;EACL,MAAM;EACN,GAAI,SAAS,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAIxE,GACT,WAAW;EACT,KAAK;EACL;EACA,GAAI,SAAS,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CACnF,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"resource-hints.js","names":[],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept, and a script already anywhere in the document with the same `src` and `type` is\n * not loaded again. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n // A script is the same load when its URL and kind match: the page's own bundle usually sits at the end\n // of the body, and carries `defer` or `async` or neither, so the attributes of the hint are no test.\n const same =\n tag === \"script\"\n ? (existing: Element): boolean =>\n existing.getAttribute(\"src\") === attributes[\"src\"] &&\n (existing.getAttribute(\"type\") ?? \"\") === (attributes[\"type\"] ?? \"\")\n : (existing: Element): boolean => carries(existing, attributes);\n for (const existing of (tag === \"script\" ? document : document.head).querySelectorAll(tag)) {\n if (same(existing)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":";;;;AAoEA,SAAS,SAAS,MAAoB;CACpC,MAAM,MAAM,IAAI,IAAI,MAAM,sBAAsB;CAChD,IAAI,IAAI,aAAa,YAAY,IAAI,aAAa,SAChD,MAAM,IAAI,UAEJ,mBAAmB,KAAK,qCAE9B;AAEJ;;AAGA,SAAS,QAAQ,SAAkB,YAAiC;CAClE,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,GACnD,IAAI,QAAQ,aAAa,IAAI,MAAM,OAAO,OAAO;C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
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
// src/select-value.ts
|
|
2
2
|
/** The values an array stands for, as strings; null and undefined entries are skipped. */
|
|
3
3
|
function listed(value) {
|
|
4
|
-
|
|
5
|
-
for (const item of value) if (item !== null && item !== void 0) values.add(String(item));
|
|
6
|
-
return values;
|
|
4
|
+
return new Set(value.filter((item) => item !== null && item !== void 0).map(String));
|
|
7
5
|
}
|
|
8
|
-
/** The string a
|
|
9
|
-
function
|
|
6
|
+
/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */
|
|
7
|
+
function plainText(value) {
|
|
10
8
|
return value === null || value === void 0 ? "" : String(value);
|
|
11
9
|
}
|
|
12
10
|
/**
|
|
@@ -35,16 +33,8 @@ function setSelectValue(select, value) {
|
|
|
35
33
|
for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);
|
|
36
34
|
return;
|
|
37
35
|
}
|
|
38
|
-
select.value =
|
|
36
|
+
select.value = plainText(value);
|
|
39
37
|
}
|
|
40
|
-
|
|
41
|
-
function selectShows(select, value) {
|
|
42
|
-
if (select.multiple && Array.isArray(value)) {
|
|
43
|
-
const wanted = listed(value);
|
|
44
|
-
return Array.from(select.options).every((option) => option.selected === wanted.has(option.value));
|
|
45
|
-
}
|
|
46
|
-
return select.value === single(value);
|
|
47
|
-
}
|
|
48
|
-
export { selectShows, setSelectValue };
|
|
38
|
+
export { plainText, setSelectValue };
|
|
49
39
|
|
|
50
40
|
//# sourceMappingURL=select-value.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-value.js","names":[],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n
|
|
1
|
+
{"version":3,"file":"select-value.js","names":[],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`).\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":";;AACA,SAAS,OAAO,OAAwC;CACtD,OAAO,IAAI,IAAI,MAAM,QAAQ,SAAS,SAAS,QAAQ,SAAS,KAAA,CAAS,CAAC,CAAC,IAAI,MAAM,CAAC;AACxF;;AAGA,SAAgB,UAAU,OAAwB;CAChD,OAAO,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;AAClE;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,eAAe,QAA2B,OAAsB;CAC9E,IAAI,OAAO,YAAY,MAAM,QAAQ,KAAK,GAAG;EAC3C,MAAM,SAAS,OAAO,KAAK;EAC3B,KAAK,MAAM,UAAU,MAAM,KAAK,OAAO,OAAO,GAAG,OAAO,WAAW,OAAO,IAAI,OAAO,KAAK;EAC1F;CACF;CACA,OAAO,QAAQ,UAAU,KAAK;AAChC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from "../internal/diagnostics.js";
|
|
1
2
|
import { invalid } from "./errors.js";
|
|
2
3
|
import { escapeHtml, resolveValue } from "./escape.js";
|
|
3
4
|
// src/server/attributes.ts
|
|
@@ -10,7 +11,6 @@ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
|
10
11
|
"action",
|
|
11
12
|
"formaction",
|
|
12
13
|
"xlink:href",
|
|
13
|
-
"srcdoc",
|
|
14
14
|
"poster",
|
|
15
15
|
"data"
|
|
16
16
|
]);
|
|
@@ -118,6 +118,9 @@ function assertNotSymbol(value) {
|
|
|
118
118
|
* `"true"` for those same names). Other values are written as `String(value)`, HTML-escaped.
|
|
119
119
|
* - URL attributes whose value would run script are dropped, with the check of
|
|
120
120
|
* `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).
|
|
121
|
+
* - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute
|
|
122
|
+
* and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`
|
|
123
|
+
* attribute. Development builds warn once with `SRCDOC_DYNAMIC`.
|
|
121
124
|
* - `on*` names are dropped: event handlers never reach markup.
|
|
122
125
|
* - Accessors are called (untracked) until a plain value remains.
|
|
123
126
|
*
|
|
@@ -146,6 +149,7 @@ function ssrAttribute(name, value, isBoolean = false) {
|
|
|
146
149
|
if (isBoolean) return resolved ? ` ${name}` : "";
|
|
147
150
|
const text = attributeText(lowerName, resolved);
|
|
148
151
|
if (text === null) return "";
|
|
152
|
+
if (lowerName === "srcdoc") warnOnce("SRCDOC_DYNAMIC", SRCDOC_DYNAMIC_DETAIL);
|
|
149
153
|
if (isUnsafeAttributeValue(lowerName, text)) return "";
|
|
150
154
|
return ` ${name}="${escapeHtml(text)}"`;
|
|
151
155
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":[],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"
|
|
1
|
+
{"version":3,"file":"attributes.js","names":[],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"../internal/diagnostics\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only.\n * @internal\n */\nexport const BOOLEAN_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"async\",\n \"autofocus\",\n \"autoplay\",\n \"checked\",\n \"controls\",\n \"default\",\n \"defer\",\n \"disabled\",\n \"formnovalidate\",\n \"hidden\",\n \"inert\",\n \"ismap\",\n \"loop\",\n \"multiple\",\n \"muted\",\n \"nomodule\",\n \"novalidate\",\n \"open\",\n \"playsinline\",\n \"readonly\",\n \"required\",\n \"reversed\",\n \"selected\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters, which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute\n * and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`\n * attribute. Development builds warn once with `SRCDOC_DYNAMIC`.\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom & Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":";;;;;AAKA,MAAM,iBAAiB;;AAGvB,MAAM,iCAAsC,IAAI,IAAI;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,MAAM,6CAAkD,IAAI,IAAI;CAAC;CAAU;CAAQ;CAAM;AAAI,CAAC;;AAG9F,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,sBAAyC;CAAC;CAAe;CAAkB;AAAW;;AAG5F,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAC3B,MAAM,QAAQ,0BAA0B,IAAI,KAAK,iC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;CACnC,MAAM,WAAW,aAAa,KAAK;CACnC,gBAAgB,QAAQ;CACxB,IAAI,WAAW,OAAO,WAAW,IAAI,SAAS;CAC9C,MAAM,OAAO,cAAc,WAAW,QAAQ;CAC9C,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAe,cAAc,UAAU,SAAS,kBAAkB,qBAAqB;CACvF,IAAI,uBAAuB,WAAW,IAAI,GAAG,OAAO;CACpD,OAAO,IAAI,KAAK,IAAI,WAAW,IAAI,EAAE;AACvC"}
|
|
@@ -5,7 +5,8 @@ import { SsrNode, isSsrNode } from "./node.js";
|
|
|
5
5
|
import { escape, escapeHtml, resolveValue } from "./escape.js";
|
|
6
6
|
import { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from "./attributes.js";
|
|
7
7
|
import { classText, ssrStyle, styleText } from "./class-style.js";
|
|
8
|
-
import { markSelectedOptions, textareaContent } from "./form-controls.js";
|
|
8
|
+
import { keepLeadingNewline, markSelectedOptions, textareaContent } from "./form-controls.js";
|
|
9
|
+
import { rawElementContent } from "./raw-text.js";
|
|
9
10
|
// src/server/element.ts
|
|
10
11
|
/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */
|
|
11
12
|
const TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
|
|
@@ -180,17 +181,20 @@ function ssrElement(tag, props, children = void 0, needsKey = false, svg = false
|
|
|
180
181
|
if (!Object.hasOwn(props, name)) attributes += ssrAttribute(name, value, name === "checked");
|
|
181
182
|
} else {
|
|
182
183
|
const name = attributeName(key, svg);
|
|
183
|
-
|
|
184
|
+
const flag = BOOLEAN_ATTRIBUTES.has(name) && !(name === "hidden" && value === "until-found");
|
|
185
|
+
attributes += ssrAttribute(name, value, flag);
|
|
184
186
|
}
|
|
185
187
|
}
|
|
186
188
|
if (classes.length > 0) attributes += ` class="${escapeHtml(classes.join(" "))}"`;
|
|
187
189
|
if (style !== "") attributes += ssrStyle(style);
|
|
188
190
|
if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);
|
|
189
|
-
|
|
191
|
+
const raw = !svg && (lowerTag === "script" || lowerTag === "style");
|
|
192
|
+
const given = children === void 0 ? propsChildren(props) : children;
|
|
193
|
+
let content = innerHtml !== void 0 ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);
|
|
190
194
|
if (innerHtml === void 0 && (hasValue || hasFallback)) {
|
|
191
195
|
const value = hasValue ? control.value : control.fallback;
|
|
192
196
|
content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);
|
|
193
|
-
}
|
|
197
|
+
} else if (isTextarea && innerHtml === void 0) content = keepLeadingNewline(content);
|
|
194
198
|
return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);
|
|
195
199
|
}
|
|
196
200
|
/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":[],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, <Ada></p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"<b>escaped</b><!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n attributes += ssrAttribute(name, value, BOOLEAN_ATTRIBUTES.has(name));\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n let content =\n innerHtml !== undefined\n ? innerHtml\n : escape(children === undefined ? propsChildren(props) : children);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,MAAM,gCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,+BAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAS,iBAAiB,OAAyB;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,OAAO,QAAQ,IAAI,OAAO,QAAQ;AACpC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,IAAI,OAA0B,GAAG,OAA2B;CAC1E,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,MAAM,SAAS,GAC3D,MAAM,IAAI,UAAU,6DAA6D;CAEnF,IAAI,OAAO,MAAM,MAAM;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,OAAO,MAAM;EACnB,IAAI,OAAO,SAAS,UAAU,QAAQ;OACjC,IAAI,UAAU,IAAI,GAAG,QAAQ,KAAK;OAClC,MAAM,IAAI,UAAU,wDAAwD;EACjF,QAAQ,MAAM,QAAQ,MAAM;CAC9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Aa,gBAAgB,KAAK,IAAI,oBAAoB,OAAO,OAAO;CACpF;CACA,OAAO,IAAI,QAAQ,IAAI,MAAM,WAAW,GAAG,QAAQ,IAAI,IAAI,EAAE;AAC/D;;AAGA,SAAS,cAAc,OAAyB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,OAAO,QAAQ,IAAI,OAAO,UAAU;AACtC;;AAGA,SAAS,kBAAkB,OAAgB,KAAqB;CAC9D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;CACzE,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,QAAQ,MAAM,aAAa,QAAQ,IAAI,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,GAAG;AAEzE;;AAGA,SAAS,UAAU,OAAwB;CACzC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM;CACnC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,+BAA+B;CAC5E,OAAO,OAAO,KAAK;AACrB"}
|
|
1
|
+
{"version":3,"file":"element.js","names":[],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, <Ada></p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"<b>escaped</b><!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n // `hidden=\"until-found\"` is a keyword, not a flag: a bare `hidden` would hide what it should only collapse.\n const flag =\n BOOLEAN_ATTRIBUTES.has(name) && !(name === \"hidden\" && value === \"until-found\");\n attributes += ssrAttribute(name, value, flag);\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (isTextarea && innerHtml === undefined) {\n // The children of a textarea are its value (as on the client): keep a first line break the parser drops.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,WAAW;;AAGjB,MAAM,gCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,+BAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAS,iBAAiB,OAAyB;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,U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OAAwB;CACzC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM;CACnC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,+BAA+B;CAC5E,OAAO,OAAO,KAAK;AACrB"}
|
|
@@ -20,6 +20,12 @@ var SsrError = class extends Error {
|
|
|
20
20
|
function invalid(code, detail) {
|
|
21
21
|
return /* @__PURE__ */ new TypeError(`[shadow ${code}] ${detail}`);
|
|
22
22
|
}
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it
|
|
25
|
+
* (`Number.MAX_SAFE_INTEGER` for "no limit") is clamped here instead of ending every render at once.
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
const MAX_TIMER_MS = 2147483647;
|
|
29
|
+
export { MAX_TIMER_MS, SsrError, invalid };
|
|
24
30
|
|
|
25
31
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n"],"mappings":";;;;;;AAQA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA,YAAY,MAAoB,QAAgB;EAC9C,MAAgB,WAAW,KAAK,IAAI,QAA2B;EAC/D,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,QAAQ,MAAc,QAA2B;CAC/D,uBAAO,IAAI,UAAoB,WAAW,KAAK,IAAI,QAA2B;AAChF"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":";;;;;;AAQA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA,YAAY,MAAoB,QAAgB;EAC9C,MAAgB,WAAW,KAAK,IAAI,QAA2B;EAC/D,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,QAAQ,MAAc,QAA2B;CAC/D,uBAAO,IAAI,UAAoB,WAAW,KAAK,IAAI,QAA2B;AAChF;;;;;;AAOA,MAAa,eAAe"}
|