@shadow-js/web 1.0.0 → 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 +29 -0
- package/dist/dev/attributes.d.ts +10 -5
- package/dist/dev/attributes.js +28 -51
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/autofocus.d.ts +0 -2
- package/dist/dev/autofocus.js +1 -2
- package/dist/dev/class-style.d.ts +6 -4
- package/dist/dev/class-style.js +25 -9
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/component.d.ts +0 -2
- package/dist/dev/component.js +1 -2
- package/dist/dev/control-flow/activity.d.ts +0 -2
- package/dist/dev/control-flow/activity.js +1 -2
- package/dist/dev/control-flow/branch.js +0 -1
- package/dist/dev/control-flow/client-only.d.ts +0 -2
- package/dist/dev/control-flow/client-only.js +1 -2
- package/dist/dev/control-flow/dynamic.d.ts +11 -4
- package/dist/dev/control-flow/dynamic.js +57 -41
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.d.ts +0 -2
- package/dist/dev/control-flow/error-boundary.js +1 -2
- package/dist/dev/control-flow/for.d.ts +0 -2
- package/dist/dev/control-flow/for.js +1 -2
- package/dist/dev/control-flow/fragment.d.ts +0 -2
- package/dist/dev/control-flow/fragment.js +1 -2
- package/dist/dev/control-flow/hot-link.js +1 -2
- package/dist/dev/control-flow/index-list.d.ts +0 -2
- package/dist/dev/control-flow/index-list.js +1 -2
- package/dist/dev/control-flow/lazy.d.ts +0 -2
- package/dist/dev/control-flow/lazy.js +1 -2
- package/dist/dev/control-flow/no-hydration.d.ts +0 -2
- package/dist/dev/control-flow/no-hydration.js +1 -2
- package/dist/dev/control-flow/portal.d.ts +0 -2
- package/dist/dev/control-flow/portal.js +3 -2
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/root-errors.d.ts +0 -2
- package/dist/dev/control-flow/root-errors.js +1 -2
- package/dist/dev/control-flow/show.d.ts +0 -2
- package/dist/dev/control-flow/show.js +1 -2
- package/dist/dev/control-flow/suspense-list.d.ts +0 -2
- package/dist/dev/control-flow/suspense-list.js +1 -2
- package/dist/dev/control-flow/suspense.d.ts +0 -2
- package/dist/dev/control-flow/suspense.js +1 -2
- package/dist/dev/control-flow/switch.d.ts +0 -2
- package/dist/dev/control-flow/switch.js +1 -2
- package/dist/dev/derived.d.ts +0 -2
- package/dist/dev/derived.js +1 -2
- package/dist/dev/element.d.ts +0 -2
- package/dist/dev/element.js +2 -3
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +16 -46
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/head/components.d.ts +0 -2
- package/dist/dev/head/components.js +1 -2
- package/dist/dev/head/registry.js +1 -2
- package/dist/dev/head/server-head.d.ts +0 -2
- package/dist/dev/head/server-head.js +1 -2
- package/dist/dev/head/sink.js +1 -2
- package/dist/dev/head/use-head.d.ts +0 -2
- package/dist/dev/head/use-head.js +1 -2
- package/dist/dev/head/validate.d.ts +0 -2
- package/dist/dev/head/validate.js +1 -2
- package/dist/dev/hmr.d.ts +0 -2
- package/dist/dev/hmr.js +1 -2
- package/dist/dev/hydration.d.ts +0 -2
- package/dist/dev/hydration.js +1 -2
- package/dist/dev/insert.d.ts +15 -7
- package/dist/dev/insert.js +36 -15
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -3
- package/dist/dev/internal/claim.js +19 -4
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +7 -5
- package/dist/dev/internal/diagnostics.js +15 -6
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +21 -4
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/hydration-hooks.d.ts +0 -2
- package/dist/dev/internal/hydration-hooks.js +0 -1
- package/dist/dev/internal/hydration-scope.d.ts +0 -2
- package/dist/dev/internal/hydration-scope.js +1 -2
- package/dist/dev/internal/names.d.ts +0 -2
- package/dist/dev/internal/names.js +1 -2
- package/dist/dev/internal/portal-context.d.ts +0 -2
- package/dist/dev/internal/portal-context.js +1 -2
- package/dist/dev/internal/react-names.js +26 -63
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +0 -2
- package/dist/dev/internal/reconcile.js +4 -8
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/internal/stream-context.d.ts +0 -2
- package/dist/dev/internal/stream-context.js +1 -2
- package/dist/dev/jsx/aria.d.ts +0 -2
- package/dist/dev/jsx/component.d.ts +0 -2
- package/dist/dev/jsx/events.d.ts +0 -2
- package/dist/dev/jsx/global.d.ts +5 -4
- package/dist/dev/jsx/html.d.ts +1 -2
- package/dist/dev/jsx/intrinsic.d.ts +0 -2
- package/dist/dev/jsx/mathml.d.ts +0 -2
- package/dist/dev/jsx/svg.d.ts +0 -2
- package/dist/dev/jsx/types.d.ts +0 -2
- package/dist/dev/jsx-runtime.d.ts +0 -2
- package/dist/dev/reactive.d.ts +0 -2
- package/dist/dev/reactive.js +1 -2
- package/dist/dev/render.d.ts +0 -2
- package/dist/dev/render.js +1 -2
- package/dist/dev/resource-hints.d.ts +0 -2
- package/dist/dev/resource-hints.js +5 -4
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.d.ts +0 -2
- package/dist/dev/select-value.js +6 -17
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -2
- package/dist/dev/server/attributes.js +6 -3
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/class-style.d.ts +0 -2
- package/dist/dev/server/class-style.js +1 -2
- package/dist/dev/server/component.d.ts +0 -2
- package/dist/dev/server/component.js +1 -2
- package/dist/dev/server/derived.d.ts +0 -2
- package/dist/dev/server/derived.js +1 -2
- package/dist/dev/server/element.d.ts +0 -2
- package/dist/dev/server/element.js +9 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +8 -3
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.d.ts +0 -2
- package/dist/dev/server/escape.js +15 -8
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.d.ts +0 -2
- package/dist/dev/server/form-controls.js +6 -4
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/hydration-script.d.ts +0 -2
- package/dist/dev/server/hydration-script.js +1 -2
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/node.d.ts +0 -2
- package/dist/dev/server/node.js +1 -2
- package/dist/dev/server/portals.d.ts +0 -2
- package/dist/dev/server/portals.js +0 -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 -3
- package/dist/dev/server/render.js +3 -4
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/serialize.d.ts +0 -2
- package/dist/dev/server/serialize.js +1 -2
- package/dist/dev/server/stream.d.ts +1 -3
- package/dist/dev/server/stream.js +3 -4
- 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.d.ts +0 -2
- package/dist/dev/spread.js +8 -56
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.d.ts +0 -2
- package/dist/dev/template.js +1 -2
- package/dist/dev/view-transition.d.ts +0 -2
- package/dist/dev/view-transition.js +1 -2
- 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 +28 -51
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/autofocus.js +1 -2
- package/dist/server-dev/class-style.js +25 -9
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/component.js +1 -2
- package/dist/server-dev/control-flow/activity.js +1 -2
- package/dist/server-dev/control-flow/branch.js +0 -1
- package/dist/server-dev/control-flow/client-only.js +1 -2
- package/dist/server-dev/control-flow/dynamic.js +23 -12
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +1 -2
- package/dist/server-dev/control-flow/for.js +1 -2
- package/dist/server-dev/control-flow/fragment.js +1 -2
- package/dist/server-dev/control-flow/hot-link.js +1 -2
- package/dist/server-dev/control-flow/index-list.js +1 -2
- package/dist/server-dev/control-flow/lazy.js +1 -2
- package/dist/server-dev/control-flow/no-hydration.js +1 -2
- package/dist/server-dev/control-flow/portal.js +3 -2
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/root-errors.js +1 -2
- package/dist/server-dev/control-flow/show.js +1 -2
- package/dist/server-dev/control-flow/suspense-list.js +1 -2
- package/dist/server-dev/control-flow/suspense.js +1 -2
- package/dist/server-dev/control-flow/switch.js +1 -2
- package/dist/server-dev/derived.js +1 -2
- package/dist/server-dev/element.js +4 -3
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +16 -46
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/head/components.js +1 -2
- package/dist/server-dev/head/registry.js +1 -2
- package/dist/server-dev/head/server-head.js +1 -2
- package/dist/server-dev/head/sink.js +1 -2
- package/dist/server-dev/head/use-head.js +1 -2
- package/dist/server-dev/head/validate.js +1 -2
- package/dist/server-dev/hydration.js +1 -2
- package/dist/server-dev/insert.js +36 -15
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +19 -4
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +15 -6
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +21 -4
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/hydration-hooks.js +0 -1
- package/dist/server-dev/internal/hydration-scope.js +1 -2
- package/dist/server-dev/internal/names.js +1 -2
- package/dist/server-dev/internal/portal-context.js +1 -2
- package/dist/server-dev/internal/react-names.js +26 -63
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -8
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/internal/stream-context.js +1 -2
- package/dist/server-dev/reactive.js +1 -2
- package/dist/server-dev/render.js +1 -2
- package/dist/server-dev/resource-hints.js +5 -4
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +6 -17
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +6 -3
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -2
- package/dist/server-dev/server/component.js +1 -2
- package/dist/server-dev/server/derived.js +1 -2
- package/dist/server-dev/server/element.js +9 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +8 -3
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +15 -8
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +6 -4
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -2
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/node.js +1 -2
- package/dist/server-dev/server/portals.js +0 -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 +3 -4
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/serialize.js +1 -2
- package/dist/server-dev/server/stream.js +3 -4
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +8 -56
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -2
- package/dist/server-dev/view-transition.js +1 -2
- package/package.json +3 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { invalid } from "./errors.js";
|
|
2
2
|
import { isSsrNode } from "./node.js";
|
|
3
3
|
import { untrack } from "@shadow-js/core";
|
|
4
|
-
|
|
4
|
+
// src/server/escape.ts
|
|
5
5
|
const HTML_ESCAPES = {
|
|
6
6
|
"&": "&",
|
|
7
7
|
"<": "<",
|
|
@@ -33,11 +33,11 @@ function resolveValue(value) {
|
|
|
33
33
|
}
|
|
34
34
|
return current;
|
|
35
35
|
}
|
|
36
|
-
/** Writes the markup for one resolved value that is not an array. */
|
|
37
|
-
function appendLeaf(value, out) {
|
|
36
|
+
/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */
|
|
37
|
+
function appendLeaf(value, out, text) {
|
|
38
38
|
if (value === null || value === void 0 || typeof value === "boolean") return;
|
|
39
39
|
if (typeof value === "string") {
|
|
40
|
-
out.push(
|
|
40
|
+
out.push(text(value));
|
|
41
41
|
return;
|
|
42
42
|
}
|
|
43
43
|
if (typeof value === "number" || typeof value === "bigint") {
|
|
@@ -50,7 +50,7 @@ function appendLeaf(value, out) {
|
|
|
50
50
|
return;
|
|
51
51
|
}
|
|
52
52
|
if (typeof value === "object") throw invalid("UNRECOGNIZED_INSERT_VALUE", "A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.");
|
|
53
|
-
out.push(
|
|
53
|
+
out.push(text(String(value)));
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
56
|
* Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls
|
|
@@ -79,6 +79,14 @@ function appendLeaf(value, out) {
|
|
|
79
79
|
* @since 1.0.0
|
|
80
80
|
*/
|
|
81
81
|
function escape(value) {
|
|
82
|
+
return render(value, escapeHtml);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and
|
|
86
|
+
* trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).
|
|
87
|
+
* @internal
|
|
88
|
+
*/
|
|
89
|
+
function render(value, text) {
|
|
82
90
|
const out = [];
|
|
83
91
|
const frames = [];
|
|
84
92
|
const cursors = [];
|
|
@@ -91,7 +99,7 @@ function escape(value) {
|
|
|
91
99
|
open.add(resolved);
|
|
92
100
|
frames.push(resolved);
|
|
93
101
|
cursors.push(0);
|
|
94
|
-
} else appendLeaf(resolved, out);
|
|
102
|
+
} else appendLeaf(resolved, out, text);
|
|
95
103
|
let next;
|
|
96
104
|
let found = false;
|
|
97
105
|
while (!found && frames.length > 0) {
|
|
@@ -113,7 +121,6 @@ function escape(value) {
|
|
|
113
121
|
item = next;
|
|
114
122
|
}
|
|
115
123
|
}
|
|
116
|
-
|
|
117
|
-
export { escape, escapeHtml, resolveValue };
|
|
124
|
+
export { escape, escapeHtml, render, resolveValue };
|
|
118
125
|
|
|
119
126
|
//# sourceMappingURL=escape.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"escape.js","names":["accessor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array. */\nfunction appendLeaf(value: unknown, out: string[]): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(
|
|
1
|
+
{"version":3,"file":"escape.js","names":["accessor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */\nfunction appendLeaf(value: unknown, out: string[], text: (value: string) => string): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(text(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(text(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, <Ada>3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n return render(value, escapeHtml);\n}\n\n/**\n * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and\n * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).\n * @internal\n */\nexport function render(value: unknown, text: (value: string) => string): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out, text);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":";;;;AAIA,MAAM,eAAiD;CACrD,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;AACP;AAEA,MAAM,eAAe;;AAGrB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,WAAW,MAAsB;CAC/C,OAAO,KAAK,QAAQ,eAAe,SAAS,aAAa,SAAS,IAAI;AACxE;;;;;;AAOA,SAAgB,aAAa,OAAyB;CACpD,IAAI,UAAU;CACd,KAAK,IAAI,QAAQ,GAAG,OAAO,YAAY,YAAY,SAAS,GAAG;EAC7D,IAAI,SAAS,qBACX,MAAM,IAAI,UAAU,2DAA2D;EAGjF,UAAU,QAAQA,OAAQ;CAC5B;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,OAAgB,KAAe,MAAuC;CACxF,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,OAAO,UAAU,WAAW;CACzE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,KAAK,KAAK,KAAK,CAAC;EACpB;CACF;CAEA,IAAI,OAAO,UAAU,YAAY,OAAO,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;EAC9B,OAAO;CACT;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { SsrNode } from "./node.js";
|
|
2
|
-
//#region src/server/form-controls.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Renders the content of a `<textarea>` from its value: the helper compiled server output calls for
|
|
5
4
|
* `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a
|
|
@@ -46,5 +45,4 @@ export declare function ssrTextArea(value: unknown): SsrNode;
|
|
|
46
45
|
* @since 1.0.0
|
|
47
46
|
*/
|
|
48
47
|
export declare function ssrSelectValue(value: unknown, children: unknown): SsrNode;
|
|
49
|
-
//#endregion
|
|
50
48
|
//# sourceMappingURL=form-controls.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { invalid } from "./errors.js";
|
|
2
2
|
import { SsrNode } from "./node.js";
|
|
3
3
|
import { escape, escapeHtml, resolveValue } from "./escape.js";
|
|
4
|
-
|
|
4
|
+
// src/server/form-controls.ts
|
|
5
5
|
/**
|
|
6
6
|
* Server markup for the controls whose state is not an attribute. A browser ignores `value` on a
|
|
7
7
|
* `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is
|
|
@@ -19,7 +19,10 @@ function valueText(value) {
|
|
|
19
19
|
* @internal
|
|
20
20
|
*/
|
|
21
21
|
function textareaContent(value) {
|
|
22
|
-
|
|
22
|
+
return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));
|
|
23
|
+
}
|
|
24
|
+
/** Content markup of a textarea with the line break its parser would drop kept. @internal */
|
|
25
|
+
function keepLeadingNewline(html) {
|
|
23
26
|
const first = html.charAt(0);
|
|
24
27
|
return first === "\n" || first === "\r" ? `\n${html}` : html;
|
|
25
28
|
}
|
|
@@ -187,7 +190,6 @@ function ssrSelectValue(value, children) {
|
|
|
187
190
|
function markSelectedOptions(value, html) {
|
|
188
191
|
return markOptions(html, wantedValues(value));
|
|
189
192
|
}
|
|
190
|
-
|
|
191
|
-
export { markSelectedOptions, ssrSelectValue, ssrTextArea, textareaContent };
|
|
193
|
+
export { keepLeadingNewline, markSelectedOptions, ssrSelectValue, ssrTextArea, textareaContent };
|
|
192
194
|
|
|
193
195
|
//# sourceMappingURL=form-controls.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-controls.js","names":[],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { 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 { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n const html = escapeHtml(valueText(resolveValue(value)));\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves <b>tags</b></textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and ` ` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,0CAA0C;CAEvF,OAAO,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;AAClE;;;;;;AAOA,SAAgB,gBAAgB,OAAwB;CACtD,MAAM,OAAO,WAAW,UAAU,aAAa,KAAK,CAAC,CAAC;CACtD,MAAM,QAAQ,KAAK,OAAO,CAAC;CAC3B,OAAO,UAAU,QAAQ,UAAU,OAAO,KAAK,SAAS;AAC1D;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,OAAyB;CACnD,OAAO,IAAI,QAAQ,gBAAgB,KAAK,CAAC;AAC3C;;AAGA,SAAS,aAAa,OAAwD;CAC5E,MAAM,WAAW,aAAa,KAAK;CACnC,IAAI,CAAC,MAAM,QAAQ,QAAQ,GAAG,OAAO;EAAE,wBAAQ,IAAI,IAAI,CAAC,UAAU,QAAQ,CAAC,CAAC;EAAG,MAAM;CAAM;CAC3F,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,QAAQ,UAAU;EAC3B,MAAM,MAAM,aAAa,IAAI;EAC7B,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAAW,OAAO,IAAI,UAAU,GAAG,CAAC;CAClE;CACA,OAAO;EAAE;EAAQ,MAAM;CAAK;AAC9B;;AAGA,MAAM,aAAa;;AAEnB,MAAM,SAAS;AACf,MAAM,iBAAmD;CACvD,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;AACR;;AAEA,MAAM,OAAO;;;;;AAKb,MAAM,kB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jE;;AAGA,SAAgB,oBAAoB,OAAgB,MAAsB;CACxE,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC;AAC9C"}
|
|
1
|
+
{"version":3,"file":"form-controls.js","names":[],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { 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 { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));\n}\n\n/** Content markup of a textarea with the line break its parser would drop kept. @internal */\nexport function keepLeadingNewline(html: string): string {\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves <b>tags</b></textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and ` ` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,0CAA0C;CAEvF,OAAO,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;AAClE;;;;;;AAOA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,mBAAmB,WAAW,UAAU,aAAa,KAAK,CAAC,CAAC,CAAC;AACtE;;AAGA,SAAgB,mBAAmB,MAAsB;CACvD,MAAM,QAAQ,KAAK,OAAO,CAAC;CAC3B,OAAO,UAAU,QAAQ,UAAU,OAAO,KAAK,SAAS;AAC1D;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,OAAyB;CACnD,OAAO,IAAI,QAAQ,gBAAgB,KAAK,CAAC;AAC3C;;AAGA,SAAS,aAAa,OAAwD;CAC5E,MAAM,WAAW,aAAa,KAAK;CACnC,IAAI,CAAC,MAAM,QAAQ,QAAQ,GAAG,OAAO;EAAE,wBAAQ,IAAI,IAAI,CAAC,UAAU,QAAQ,CAAC,CAAC;EAAG,MAAM;CAAM;CAC3F,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,QAAQ,UAAU;EAC3B,MAAM,MAAM,aAAa,IAAI;EAC7B,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAAW,OAAO,IAAI,UAAU,GAAG,CAAC;CAClE;CACA,OAAO;EAAE;EAAQ,MAAM;CAAK;AAC9B;;AAGA,MAAM,aAAa;;AAEnB,MAAM,SAAS;AACf,MAAM,iBAAmD;CACvD,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,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QAAQ,oBAAoB,OAAO,OAAO,QAAQ,CAAC,CAAC;AACjE;;AAGA,SAAgB,oBAAoB,OAAgB,MAAsB;CACxE,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC;AAC9C"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/server/hydration-script.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Options of {@link generateHydrationScript} and {@link HydrationScript}.
|
|
4
3
|
* @since 1.0.0
|
|
@@ -61,5 +60,4 @@ export declare function generateHydrationScript(options?: HydrationScriptOptions
|
|
|
61
60
|
* @since 1.0.0
|
|
62
61
|
*/
|
|
63
62
|
export declare function HydrationScript(props?: HydrationScriptOptions): unknown;
|
|
64
|
-
//#endregion
|
|
65
63
|
//# sourceMappingURL=hydration-script.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ssrRaw } from "./element.js";
|
|
2
2
|
import { DEFAULT_EARLY_EVENTS, captureScriptBody } from "../internal/early-events.js";
|
|
3
|
-
|
|
3
|
+
// src/server/hydration-script.ts
|
|
4
4
|
const NONCE = /^[A-Za-z0-9+/=_-]+$/;
|
|
5
5
|
/**
|
|
6
6
|
* Returns the inline `<script>` that records the events a user makes before the app has hydrated, so
|
|
@@ -53,7 +53,6 @@ function generateHydrationScript(options = {}) {
|
|
|
53
53
|
function HydrationScript(props = {}) {
|
|
54
54
|
return ssrRaw(generateHydrationScript(props));
|
|
55
55
|
}
|
|
56
|
-
//#endregion
|
|
57
56
|
export { HydrationScript, generateHydrationScript };
|
|
58
57
|
|
|
59
58
|
//# sourceMappingURL=hydration-script.js.map
|
|
@@ -9,8 +9,9 @@ import { escape } from "./escape.js";
|
|
|
9
9
|
import { ssrSelectValue, ssrTextArea } from "./form-controls.js";
|
|
10
10
|
import { HydrationScript, HydrationScriptOptions, generateHydrationScript } from "./hydration-script.js";
|
|
11
11
|
import { ServerPortals, createServerPortals } from "./portals.js";
|
|
12
|
+
import { ssrRawText } from "./raw-text.js";
|
|
12
13
|
import { AsyncRenderOptions, AsyncRenderResult, RenderOptions, renderToString, renderToStringAsync } from "./render.js";
|
|
13
14
|
import { deserialize, serialize } from "./serialize.js";
|
|
14
15
|
import { StreamOptions, renderToStream } from "./stream.js";
|
|
15
16
|
import { mergeProps as mergeProps$1 } from "@shadow-js/core";
|
|
16
|
-
export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
|
|
17
|
+
export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
|
package/dist/dev/server/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { escape } from "./escape.js";
|
|
|
2
2
|
import { ssrAttribute } from "./attributes.js";
|
|
3
3
|
import { ssrClass, ssrStyle } from "./class-style.js";
|
|
4
4
|
import { ssrSelectValue, ssrTextArea } from "./form-controls.js";
|
|
5
|
+
import { ssrRawText } from "./raw-text.js";
|
|
5
6
|
import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./element.js";
|
|
6
7
|
import { createServerPortals } from "./portals.js";
|
|
7
8
|
import { normalizeTags } from "../head/validate.js";
|
|
@@ -13,4 +14,4 @@ import { renderToString, renderToStringAsync } from "./render.js";
|
|
|
13
14
|
import { deserialize, serialize } from "./serialize.js";
|
|
14
15
|
import { renderToStream } from "./stream.js";
|
|
15
16
|
import { mergeProps as mergeProps$1 } from "@shadow-js/core";
|
|
16
|
-
export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
|
|
17
|
+
export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/server/node.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Markup that is already safe to insert: the only value `escape` writes without encoding.
|
|
4
3
|
* A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be
|
|
@@ -9,5 +8,4 @@ export declare class SsrNode {
|
|
|
9
8
|
readonly t: string;
|
|
10
9
|
constructor(t: string);
|
|
11
10
|
}
|
|
12
|
-
//#endregion
|
|
13
11
|
//# sourceMappingURL=node.d.ts.map
|
package/dist/dev/server/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/server/node.ts
|
|
2
2
|
/**
|
|
3
3
|
* Markup that is already safe to insert: the only value `escape` writes without encoding.
|
|
4
4
|
* A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be
|
|
@@ -15,7 +15,6 @@ var SsrNode = class {
|
|
|
15
15
|
function isSsrNode(value) {
|
|
16
16
|
return value instanceof SsrNode;
|
|
17
17
|
}
|
|
18
|
-
//#endregion
|
|
19
18
|
export { SsrNode, isSsrNode };
|
|
20
19
|
|
|
21
20
|
//# sourceMappingURL=node.js.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import "../internal/portal-context.js";
|
|
2
|
-
//#region src/server/portals.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to
|
|
5
4
|
* the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.
|
|
@@ -42,5 +41,4 @@ export interface ServerPortals {
|
|
|
42
41
|
* @since 1.0.0
|
|
43
42
|
*/
|
|
44
43
|
export declare function createServerPortals(): ServerPortals;
|
|
45
|
-
//#endregion
|
|
46
44
|
//# sourceMappingURL=portals.d.ts.map
|
|
@@ -93,7 +93,6 @@ function portalCollectorFor(portals) {
|
|
|
93
93
|
collector.clear();
|
|
94
94
|
return collector;
|
|
95
95
|
}
|
|
96
|
-
//#endregion
|
|
97
96
|
export { PortalCollector, collectorOf, createServerPortals, portalCollectorFor, renderServerPortal, withPortalSink };
|
|
98
97
|
|
|
99
98
|
//# sourceMappingURL=portals.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { SsrNode } from "./node.js";
|
|
2
|
+
/**
|
|
3
|
+
* Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a
|
|
4
|
+
* dynamic child of one. The browser reads these elements' content as raw text, so the value is written
|
|
5
|
+
* as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region
|
|
6
|
+
* markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of
|
|
7
|
+
* the element, in any letter case (`</style`, `<\/SCRIPT`), and `<!--` in a script, would end the element
|
|
8
|
+
* early or hide its end, so each is rewritten (`<\/style`, `<\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.
|
|
9
|
+
*
|
|
10
|
+
* Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and
|
|
11
|
+
* a symbol throws, as in {@link escape}.
|
|
12
|
+
*
|
|
13
|
+
* @param tag The element, `"script"` or `"style"` (any letter case).
|
|
14
|
+
* @param value The child value: a string, a number, an array, an accessor or `null`.
|
|
15
|
+
* @returns The text as a trusted `SsrNode`.
|
|
16
|
+
* @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of
|
|
17
|
+
* {@link escape} for the value.
|
|
18
|
+
* @example
|
|
19
|
+
* import { renderToString, ssr, ssrRawText } from "@shadow-js/web/server";
|
|
20
|
+
*
|
|
21
|
+
* const css = "a > b { color: red } </style><script>alert(1)<\/script>";
|
|
22
|
+
* const html = renderToString(() => ssr(["<style>", "</style>"], ssrRawText("style", css)));
|
|
23
|
+
* // "<style>a > b { color: red } <\/style><script>alert(1)<\/script></style>"
|
|
24
|
+
* @see escape
|
|
25
|
+
* @since 1.0.2
|
|
26
|
+
*/
|
|
27
|
+
export declare function ssrRawText(tag: "script" | "style", value: unknown): SsrNode;
|
|
28
|
+
//# sourceMappingURL=raw-text.d.ts.map
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { invalid } from "./errors.js";
|
|
2
|
+
import { SsrNode, isSsrNode } from "./node.js";
|
|
3
|
+
import { render, resolveValue } from "./escape.js";
|
|
4
|
+
// src/server/raw-text.ts
|
|
5
|
+
/** The elements whose text the parser reads raw. */
|
|
6
|
+
const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
|
|
7
|
+
/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */
|
|
8
|
+
const CLOSING_TAG = {
|
|
9
|
+
script: /<\/(script)|<!--/gi,
|
|
10
|
+
style: /<\/(style)/gi
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Keeps raw text from ending its element or the script data state. `<\/script` and `</style` get a backslash that
|
|
14
|
+
* CSS, JavaScript and JSON all read as the character itself (`<\/style` is `</style` in a string, a comment or a
|
|
15
|
+
* selector escape), and `<!--` in a script becomes `<\u0021--`: `\!` is no JSON escape, and a script that holds
|
|
16
|
+
* JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does
|
|
17
|
+
* not see a tag. Entities would instead change the text: raw text has none.
|
|
18
|
+
*/
|
|
19
|
+
function neutralize(tag, text) {
|
|
20
|
+
return text.replace(CLOSING_TAG[tag], (match) => match === "<!--" ? "<\\u0021--" : `<\\/${match.slice(2)}`);
|
|
21
|
+
}
|
|
22
|
+
/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */
|
|
23
|
+
function rawTextContent(tag, value) {
|
|
24
|
+
return neutralize(tag.toLowerCase() === "script" ? "script" : "style", render(value, (text) => text));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)
|
|
28
|
+
* is the application's own markup and is left as it is; any other value is raw text and is checked.
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
function rawElementContent(tag, value) {
|
|
32
|
+
const resolved = resolveValue(value);
|
|
33
|
+
return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a
|
|
37
|
+
* dynamic child of one. The browser reads these elements' content as raw text, so the value is written
|
|
38
|
+
* as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region
|
|
39
|
+
* markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of
|
|
40
|
+
* the element, in any letter case (`</style`, `<\/SCRIPT`), and `<!--` in a script, would end the element
|
|
41
|
+
* early or hide its end, so each is rewritten (`<\/style`, `<\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.
|
|
42
|
+
*
|
|
43
|
+
* Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and
|
|
44
|
+
* a symbol throws, as in {@link escape}.
|
|
45
|
+
*
|
|
46
|
+
* @param tag The element, `"script"` or `"style"` (any letter case).
|
|
47
|
+
* @param value The child value: a string, a number, an array, an accessor or `null`.
|
|
48
|
+
* @returns The text as a trusted `SsrNode`.
|
|
49
|
+
* @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of
|
|
50
|
+
* {@link escape} for the value.
|
|
51
|
+
* @example
|
|
52
|
+
* import { renderToString, ssr, ssrRawText } from "@shadow-js/web/server";
|
|
53
|
+
*
|
|
54
|
+
* const css = "a > b { color: red } </style><script>alert(1)<\/script>";
|
|
55
|
+
* const html = renderToString(() => ssr(["<style>", "</style>"], ssrRawText("style", css)));
|
|
56
|
+
* // "<style>a > b { color: red } <\/style><script>alert(1)<\/script></style>"
|
|
57
|
+
* @see escape
|
|
58
|
+
* @since 1.0.2
|
|
59
|
+
*/
|
|
60
|
+
function ssrRawText(tag, value) {
|
|
61
|
+
if (typeof tag !== "string" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) throw invalid("INVALID_RAW_TEXT_TAG", "ssrRawText(): the tag must be script or style.");
|
|
62
|
+
return new SsrNode(rawTextContent(tag, value));
|
|
63
|
+
}
|
|
64
|
+
export { rawElementContent, rawTextContent, ssrRawText };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=raw-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"raw-text.js","names":[],"sources":["../../../src/server/raw-text.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { render, resolveValue } from \"./escape\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/**\n * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no\n * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers\n * that delimit a dynamic child elsewhere would show up as literal text inside them.\n */\nconst TEXT_ONLY_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for an HTML element whose content is text only, so its children are written without region markers\n * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names\n * are ordinary elements and are not text only.\n * @internal\n */\nexport function isTextOnlyElement(tag: string): boolean {\n return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());\n}\n\n/** The elements whose text the parser reads raw. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\"]);\n\n/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */\nconst CLOSING_TAG = {\n script: /<\\/(script)|<!--/gi,\n style: /<\\/(style)/gi,\n} as const;\n\n/**\n * Keeps raw text from ending its element or the script data state. `</script` and `</style` get a backslash that\n * CSS, JavaScript and JSON all read as the character itself (`<\\/style` is `</style` in a string, a comment or a\n * selector escape), and `<!--` in a script becomes `<\\u0021--`: `\\!` is no JSON escape, and a script that holds\n * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does\n * not see a tag. Entities would instead change the text: raw text has none.\n */\nfunction neutralize(tag: \"script\" | \"style\", text: string): string {\n return text.replace(CLOSING_TAG[tag], (match: string) =>\n match === \"<!--\" ? \"<\\\\u0021--\" : `<\\\\/${match.slice(2)}`,\n );\n}\n\n/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */\nexport function rawTextContent(tag: string, value: unknown): string {\n return neutralize(\n tag.toLowerCase() === \"script\" ? \"script\" : \"style\",\n render(value, (text) => text),\n );\n}\n\n/**\n * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)\n * is the application's own markup and is left as it is; any other value is raw text and is checked.\n * @internal\n */\nexport function rawElementContent(tag: string, value: unknown): string {\n const resolved = resolveValue(value);\n return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);\n}\n\n/**\n * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a\n * dynamic child of one. The browser reads these elements' content as raw text, so the value is written\n * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region\n * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of\n * the element, in any letter case (`</style`, `</SCRIPT`), and `<!--` in a script, would end the element\n * early or hide its end, so each is rewritten (`<\\/style`, `<\\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.\n *\n * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and\n * a symbol throws, as in {@link escape}.\n *\n * @param tag The element, `\"script\"` or `\"style\"` (any letter case).\n * @param value The child value: a string, a number, an array, an accessor or `null`.\n * @returns The text as a trusted `SsrNode`.\n * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of\n * {@link escape} for the value.\n * @example\n * import { renderToString, ssr, ssrRawText } from \"@shadow-js/web/server\";\n *\n * const css = \"a > b { color: red } </style><script>alert(1)</script>\";\n * const html = renderToString(() => ssr([\"<style>\", \"</style>\"], ssrRawText(\"style\", css)));\n * // \"<style>a > b { color: red } <\\/style><script>alert(1)</script></style>\"\n * @see escape\n * @since 1.0.2\n */\nexport function ssrRawText(tag: \"script\" | \"style\", value: unknown): SsrNode {\n if (typeof tag !== \"string\" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) {\n throw invalid(\"INVALID_RAW_TEXT_TAG\", \"ssrRawText(): the tag must be script or style.\");\n }\n return new SsrNode(rawTextContent(tag, value));\n}\n"],"mappings":";;;;;AAsBA,MAAM,oCAAyC,IAAI,IAAI,CAAC,UAAU,OAAO,CAAC;;AAG1E,MAAM,cAAc;CAClB,QAAQ;CACR,OAAO;AACT;;;;;;;;AASA,SAAS,WAAW,KAAyB,MAAsB;CACjE,OAAO,KAAK,QAAQ,YAAY,OAAO,UACrC,UAAU,SAAS,eAAe,OAAO,MAAM,MAAM,CAAC,GACxD;AACF;;AAGA,SAAgB,eAAe,KAAa,OAAwB;CAClE,OAAO,WACL,IAAI,YAAY,MAAM,WAAW,WAAW,SAC5C,OAAO,QAAQ,SAAS,IAAI,CAC9B;AACF;;;;;;AAOA,SAAgB,kBAAkB,KAAa,OAAwB;CACrE,MAAM,WAAW,aAAa,KAAK;CACnC,OAAO,UAAU,QAAQ,IAAI,SAAS,IAAI,eAAe,KAAK,QAAQ;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,WAAW,KAAyB,OAAyB;CAC3E,IAAI,OAAO,QAAQ,YAAY,CAAC,kBAAkB,IAAI,IAAI,YAAY,CAAC,GACrE,MAAM,QAAQ,wBAAwB,gDAAgD;CAExF,OAAO,IAAI,QAAQ,eAAe,KAAK,KAAK,CAAC;AAC/C"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ServerHead } from "../head/server-head.js";
|
|
2
2
|
import { ServerPortals } from "./portals.js";
|
|
3
|
-
//#region src/server/render.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.
|
|
6
5
|
* @since 1.0.0
|
|
@@ -45,7 +44,8 @@ export interface RenderOptions {
|
|
|
45
44
|
*/
|
|
46
45
|
export interface AsyncRenderOptions extends RenderOptions {
|
|
47
46
|
/**
|
|
48
|
-
* Upper bound for the whole render, in milliseconds: a positive finite number.
|
|
47
|
+
* Upper bound for the whole render, in milliseconds: a positive finite number. Values above the
|
|
48
|
+
* timer range (2147483647, about 24.8 days) count as 2147483647.
|
|
49
49
|
* @default 10000
|
|
50
50
|
*/
|
|
51
51
|
readonly timeoutMs?: number;
|
|
@@ -125,5 +125,4 @@ export declare function renderToString(code: () => unknown, options?: RenderOpti
|
|
|
125
125
|
* @since 1.0.0
|
|
126
126
|
*/
|
|
127
127
|
export declare function renderToStringAsync(code: () => unknown, options?: AsyncRenderOptions): Promise<AsyncRenderResult>;
|
|
128
|
-
//#endregion
|
|
129
128
|
//# sourceMappingURL=render.d.ts.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
|
|
2
|
-
import { SsrError } from "./errors.js";
|
|
2
|
+
import { MAX_TIMER_MS, SsrError } from "./errors.js";
|
|
3
3
|
import { escape } from "./escape.js";
|
|
4
4
|
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
5
5
|
import { portalCollectorFor, withPortalSink } from "./portals.js";
|
|
6
6
|
import { runWithServerHead } from "../head/server-head.js";
|
|
7
7
|
import { ResourceCacheContext, createRoot } from "@shadow-js/core";
|
|
8
|
-
|
|
8
|
+
// src/server/render.ts
|
|
9
9
|
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
10
10
|
const DEFAULT_MAX_PASSES = 10;
|
|
11
11
|
const RENDER_ID = /^[A-Za-z0-9_-]+$/;
|
|
@@ -239,7 +239,7 @@ async function renderToStringAsync(code, options) {
|
|
|
239
239
|
timer = setTimeout(() => {
|
|
240
240
|
job.canceled = true;
|
|
241
241
|
reject(new SsrError("SSR_TIMEOUT", `The render did not finish within ${timeoutMs} ms.`));
|
|
242
|
-
}, timeoutMs);
|
|
242
|
+
}, Math.min(timeoutMs, MAX_TIMER_MS));
|
|
243
243
|
});
|
|
244
244
|
try {
|
|
245
245
|
const portals = portalCollectorFor(options?.portals);
|
|
@@ -250,7 +250,6 @@ async function renderToStringAsync(code, options) {
|
|
|
250
250
|
for (const dispose of job.roots.splice(0)) dispose();
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
-
//#endregion
|
|
254
253
|
export { renderToString, renderToStringAsync };
|
|
255
254
|
|
|
256
255
|
//# sourceMappingURL=render.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":[],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n }, timeoutMs);\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":";;;;;;;;AAuFA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,YAAY;;AAGlB,SAAS,cAAc,UAA0B;CAC/C,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,OAAO;AACT;;;;;AAMA,SAAS,YAAY,SAAsD;CACzE,OAAO;EACL,GAAI,SAAS,kBAAkB,KAAA,IAAY,CAAC,IA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,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,UAAU,WAAW;EACvD,QAAQ,iBAAiB;GACvB,IAAI,WAAW;GACf,OAAO,IAAI,SAAS,eAAe,oCAAoC,UAAU,KAAK,CAAC;EACzF,GAAG,SAAS;CACd,CAAC;CACD,IAAI;EACF,MAAM,UAAU,mBAAmB,SAAS,OAAO;EACnD,OAAO,MAAM,QAAQ,KAAK,CACxB,UAAU,MAAM,UAAU,WAAW,KAAK,SAAS,MAAM,SAAS,YAAY,OAAO,CAAC,GACtF,OACF,CAAC;CACH,UAAU;EACR,aAAa,KAAK;EAClB,IAAI,WAAW;EACf,KAAK,MAAM,WAAW,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ;CACrD;AACF"}
|
|
1
|
+
{"version":3,"file":"render.js","names":[],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the\n * timer range (2147483647, about 24.8 days) count as 2147483647.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n },\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":";;;;;;;;AAwFA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,YAAY;;AAGlB,SAAS,cAAc,UAA0B;CAC/C,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,OAAO;AACT;;;;;AAMA,SAAS,YAAY,SAAsD;CACzE,OAAO;EACL,GAAI,SAAS,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;EACvF,GAAI,SAAS,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;CAC/F;AACF;;;;;;AAOA,SAAS,aACP,MACA,UACA,OACA,MACA,SACA,WACQ;CACR,iBAAiB,SAAS;CAE1B,OACE,eAAe,eACb,qBAAqB;EACnB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,kBAAkB,YACvB,UAAU,gBAAgB,QAAQ,SA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,KAAK,SAAS,MAAM,SAAS,YAAY,OAAO,CAAC,GACtF,OACF,CAAC;CACH,UAAU;EACR,aAAa,KAAK;EAClB,IAAI,WAAW;EACf,KAAK,MAAM,WAAW,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ;CACrD;AACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/server/serialize.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Serializes data for embedding in a page, as JSON that is safe inside a
|
|
4
3
|
* `<script type="application/json">` element. It carries what JSON cannot: undefined, NaN,
|
|
@@ -41,5 +40,4 @@ export declare function serialize(data: unknown): string;
|
|
|
41
40
|
* @since 1.0.0
|
|
42
41
|
*/
|
|
43
42
|
export declare function deserialize(text: string): unknown;
|
|
44
|
-
//#endregion
|
|
45
43
|
//# sourceMappingURL=serialize.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { invalid } from "./errors.js";
|
|
2
|
-
|
|
2
|
+
// src/server/serialize.ts
|
|
3
3
|
/** Characters that may not appear raw in the output: they would end a script element or a line. */
|
|
4
4
|
const UNSAFE_TEXT = /[<>&\u2028\u2029]/g;
|
|
5
5
|
/** Escapes text for `<script type="application/json">`: the JSON stays valid, the markup cannot close. */
|
|
@@ -309,7 +309,6 @@ function deserialize(text) {
|
|
|
309
309
|
}
|
|
310
310
|
return decodeValue(own(payload, "r"), made);
|
|
311
311
|
}
|
|
312
|
-
//#endregion
|
|
313
312
|
export { deserialize, serialize };
|
|
314
313
|
|
|
315
314
|
//# sourceMappingURL=serialize.js.map
|