@opentf/afw 0.0.0-stage → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +123 -2
- package/components/Link.d.ts +12 -0
- package/components/Link.jsx +54 -0
- package/core/context.d.ts +7 -0
- package/core/context.js +60 -0
- package/core/dev.js +27 -0
- package/core/errors.d.ts +14 -0
- package/core/errors.js +48 -0
- package/core/html.js +10 -0
- package/core/metadata.js +186 -0
- package/core/reactive.d.ts +5 -0
- package/core/reactive.js +190 -0
- package/core/render-context.js +11 -0
- package/core/signals.d.ts +8 -0
- package/core/signals.js +264 -0
- package/index.d.ts +5 -0
- package/index.js +13 -0
- package/jsx-runtime.d.ts +37 -0
- package/package.json +66 -4
- package/runtime/clipboard.d.ts +7 -0
- package/runtime/clipboard.js +47 -0
- package/runtime/code-block.d.ts +14 -0
- package/runtime/code-block.js +76 -0
- package/runtime/context.browser.js +163 -0
- package/runtime/context.d.ts +13 -0
- package/runtime/context.js +44 -0
- package/runtime/dom.browser.js +423 -0
- package/runtime/dom.d.ts +142 -0
- package/runtime/dom.js +670 -0
- package/runtime/error-boundary.browser.js +140 -0
- package/runtime/error-boundary.d.ts +19 -0
- package/runtime/error-boundary.js +123 -0
- package/runtime/events.browser.js +29 -0
- package/runtime/events.d.ts +1 -0
- package/runtime/events.js +17 -0
- package/runtime/head.js +29 -0
- package/runtime/hmr.js +199 -0
- package/runtime/hydrate.browser.js +144 -0
- package/runtime/hydrate.d.ts +179 -0
- package/runtime/hydrate.js +584 -0
- package/runtime/index.d.ts +14 -0
- package/runtime/index.js +24 -0
- package/runtime/lifecycle.d.ts +6 -0
- package/runtime/lifecycle.js +14 -0
- package/runtime/mount.d.ts +20 -0
- package/runtime/mount.js +88 -0
- package/runtime/portal.browser.js +85 -0
- package/runtime/portal.d.ts +12 -0
- package/runtime/portal.js +74 -0
- package/runtime/raw-html.d.ts +11 -0
- package/runtime/raw-html.js +55 -0
- package/runtime/resource.d.ts +9 -0
- package/runtime/resource.js +139 -0
- package/runtime/route-data.d.ts +15 -0
- package/runtime/route-data.js +64 -0
- package/runtime/router.d.ts +149 -0
- package/runtime/router.js +807 -0
- package/server/adapters/node.d.ts +28 -0
- package/server/adapters/node.js +74 -0
- package/server/api.d.ts +175 -0
- package/server/api.js +233 -0
- package/server/builtins.js +42 -0
- package/server/cookies.d.ts +44 -0
- package/server/cookies.js +122 -0
- package/server/head.js +9 -0
- package/server/index.d.ts +155 -0
- package/server/index.js +31 -0
- package/server/loader.js +201 -0
- package/server/middleware.js +119 -0
- package/server/render-context.js +30 -0
- package/server/render.js +175 -0
- package/server/ssg-runtime.js +297 -0
package/server/render.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
//! Server render for SSG (ARCHITECTURE.md §6) — composes a route's HTML by
|
|
2
|
+
//! calling the SSG render functions the compiler emits (page/layout factories
|
|
3
|
+
//! that return strings, components registered in the SSG registry). No DOM: this
|
|
4
|
+
//! runs in plain Bun/Node at build time.
|
|
5
|
+
//
|
|
6
|
+
// The route table (registerRoutes/matchRoute/layoutChain) is shared with the
|
|
7
|
+
// client router; here we resolve a route's page + layout chain to string
|
|
8
|
+
// renderers and concatenate them, passing `children` as an HTML string.
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
layoutChain,
|
|
12
|
+
matchRoute,
|
|
13
|
+
resolveModule,
|
|
14
|
+
routes,
|
|
15
|
+
setRouteState,
|
|
16
|
+
setRouteToc,
|
|
17
|
+
} from "../runtime/router.js";
|
|
18
|
+
import { resolveMetadata } from "./head.js";
|
|
19
|
+
import { beginHydrationCollect, endHydrationCollect } from "./ssg-runtime.js";
|
|
20
|
+
import { withRenderContext } from "./render-context.js";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Render `pathname` to `{ html, metadata, status, hydration }`: the markup for inside
|
|
24
|
+
* `#app`, the resolved SEO metadata (for the `<head>`), an HTTP `status` (200 when the
|
|
25
|
+
* path matched a real route, 404 when it fell back to the registered 404 page — the SSR
|
|
26
|
+
* server uses it; SSG ignores it), and `hydration` — the JSON island-props payload the
|
|
27
|
+
* toolchain embeds so the client resumes from rich data (`""` when nothing needs it).
|
|
28
|
+
* `params` (from `getStaticPaths`) override the matched route's params for dynamic
|
|
29
|
+
* routes. `options.data` is the route's loader result (run by the caller — serve /
|
|
30
|
+
* prerender own the loader bundle) and is exposed to the page as `router.data`.
|
|
31
|
+
* Returns `null` if there's no match and no 404 page.
|
|
32
|
+
*/
|
|
33
|
+
export async function renderRoute(pathname, params = null, search = "", { data } = {}) {
|
|
34
|
+
return withRenderContext({ route: {}, hydration: null }, () =>
|
|
35
|
+
renderInContext(pathname, params, search, data));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function renderInContext(pathname, params, search, data) {
|
|
39
|
+
const real = matchRoute(pathname);
|
|
40
|
+
const match =
|
|
41
|
+
real || (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
|
|
42
|
+
if (!match) return null;
|
|
43
|
+
if (params) match.params = params;
|
|
44
|
+
|
|
45
|
+
// Let a page reading `router.params`/`pathname`/`query`/`data` resolve to this route.
|
|
46
|
+
setRouteState({ pathname, search, params: match.params, data });
|
|
47
|
+
|
|
48
|
+
const query = Object.fromEntries(new URLSearchParams(search));
|
|
49
|
+
const props = { params: match.params, query };
|
|
50
|
+
|
|
51
|
+
// Import modules before collecting: module-level JSX must keep its inline
|
|
52
|
+
// props rather than capture hydration ids belonging to just the first request.
|
|
53
|
+
const chain = layoutChain(match.route);
|
|
54
|
+
const [pageModule, ...layoutModules] = await Promise.all(
|
|
55
|
+
[match.entry, ...chain].map(async entry => {
|
|
56
|
+
const module = await resolveModule(entry);
|
|
57
|
+
// A loader can return a bare factory. Keep it distinguishable from a
|
|
58
|
+
// loader when these resolved entries are passed to metadata resolution.
|
|
59
|
+
return typeof module === "function" ? { default: module } : module;
|
|
60
|
+
}),
|
|
61
|
+
);
|
|
62
|
+
const page = pageModule?.default ?? pageModule;
|
|
63
|
+
const layouts = layoutModules.map(module => module?.default ?? module);
|
|
64
|
+
// Before any factory runs, so a layout's `<Toc>` serves the page's outline.
|
|
65
|
+
setRouteToc(pageModule);
|
|
66
|
+
|
|
67
|
+
// Each context owns its hydration ids, including when another render is nested.
|
|
68
|
+
let html, hydration;
|
|
69
|
+
beginHydrationCollect();
|
|
70
|
+
try {
|
|
71
|
+
html = page(props);
|
|
72
|
+
// Wrap with layouts, most-specific inward to root outermost.
|
|
73
|
+
for (let i = layouts.length - 1; i >= 0; i--) {
|
|
74
|
+
html = layouts[i]({ ...props, children: html });
|
|
75
|
+
}
|
|
76
|
+
} finally {
|
|
77
|
+
hydration = endHydrationCollect();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const metadata = await resolveMetadata({
|
|
81
|
+
route: match.route,
|
|
82
|
+
entry: pageModule,
|
|
83
|
+
layouts: layoutModules,
|
|
84
|
+
params: match.params,
|
|
85
|
+
query,
|
|
86
|
+
});
|
|
87
|
+
// `route` is the matched *pattern* ("/docs/[slug]", null for the 404 fallback) — the
|
|
88
|
+
// toolchain keys its per-route chunk manifest by it to emit `<link rel="modulepreload">`.
|
|
89
|
+
return { html, metadata, status: real ? 200 : 404, hydration, route: match.route };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Back-compat / convenience: render just the `#app` markup for `pathname`. */
|
|
93
|
+
export async function renderToString(pathname, search = "") {
|
|
94
|
+
const result = await renderRoute(pathname, null, search);
|
|
95
|
+
return result ? result.html : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Validate a generated URL segment before encoding it for the route. */
|
|
99
|
+
function encodedSegment(value, route, key) {
|
|
100
|
+
if ((typeof value !== "string" && typeof value !== "number") ||
|
|
101
|
+
(typeof value === "number" && !Number.isFinite(value))) {
|
|
102
|
+
throw new Error(`getStaticPaths for ${route}: parameter "${key}" must be a string or finite number.`);
|
|
103
|
+
}
|
|
104
|
+
const text = String(value);
|
|
105
|
+
if (!text || text === "." || text === ".." || /[\\/\x00-\x1f\x7f]/.test(text)) {
|
|
106
|
+
throw new Error(`getStaticPaths for ${route}: invalid segment for "${key}". Use an array for catch-all segments.`);
|
|
107
|
+
}
|
|
108
|
+
try { return encodeURIComponent(text); }
|
|
109
|
+
catch { throw new Error(`getStaticPaths for ${route}: invalid Unicode in "${key}".`); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function fillRoute(route, params) {
|
|
113
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) {
|
|
114
|
+
throw new Error(`getStaticPaths for ${route}: params must be an object.`);
|
|
115
|
+
}
|
|
116
|
+
return route.replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, rest, key) => {
|
|
117
|
+
if (!Object.prototype.hasOwnProperty.call(params, key)) {
|
|
118
|
+
throw new Error(`getStaticPaths for ${route}: missing parameter "${key}".`);
|
|
119
|
+
}
|
|
120
|
+
const value = params[key];
|
|
121
|
+
if (rest) {
|
|
122
|
+
const segments = Array.isArray(value) ? value : [value];
|
|
123
|
+
if (!segments.length) throw new Error(`getStaticPaths for ${route}: catch-all "${key}" must not be empty.`);
|
|
124
|
+
return segments.map(segment => encodedSegment(segment, route, key)).join("/");
|
|
125
|
+
}
|
|
126
|
+
return encodedSegment(value, route, key);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Enumerate the concrete paths to pre-render as `{ path, params, route }`. Static routes
|
|
132
|
+
* are taken as-is (`params: {}`); dynamic routes (`[param]`) are expanded via the
|
|
133
|
+
* page module's optional `getStaticPaths()` (returning `[{ params }]`), carrying the
|
|
134
|
+
* params forward so the renderer/`generateMetadata` see them. `route` is the pattern the
|
|
135
|
+
* concrete path came from, so the caller can look the path up in pattern-keyed build data
|
|
136
|
+
* (the chunk manifest behind `<link rel="modulepreload">`). Dynamic routes without
|
|
137
|
+
* `getStaticPaths` are collected as `skipped`.
|
|
138
|
+
*/
|
|
139
|
+
export async function collectRoutePaths() {
|
|
140
|
+
const paths = [];
|
|
141
|
+
const skipped = [];
|
|
142
|
+
const seen = new Map();
|
|
143
|
+
function add(path, params, route) {
|
|
144
|
+
const key = new URL(path, "https://afw.invalid").pathname.replace(/\/+$/, "") || "/";
|
|
145
|
+
if (seen.has(key)) throw new Error(`Duplicate static path "${path}" from ${route}; already generated by ${seen.get(key)}.`);
|
|
146
|
+
seen.set(key, route);
|
|
147
|
+
paths.push({ path, params, route });
|
|
148
|
+
}
|
|
149
|
+
for (const route in routes.pages) {
|
|
150
|
+
if (!route.includes("[")) {
|
|
151
|
+
add(route, {}, route);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const ns = await resolveModule(routes.pages[route]);
|
|
155
|
+
const getStaticPaths =
|
|
156
|
+
ns && (ns.getStaticPaths || (ns.default && ns.default.getStaticPaths));
|
|
157
|
+
if (typeof getStaticPaths === "function") {
|
|
158
|
+
const entries = await getStaticPaths();
|
|
159
|
+
if (!Array.isArray(entries)) throw new Error(`getStaticPaths for ${route} must return an array.`);
|
|
160
|
+
for (const entry of entries) {
|
|
161
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
162
|
+
throw new Error(`getStaticPaths for ${route}: each entry must be a params object or { params }.`);
|
|
163
|
+
}
|
|
164
|
+
if (Object.prototype.hasOwnProperty.call(entry, "props")) {
|
|
165
|
+
throw new Error(`getStaticPaths for ${route}: props are unsupported. Use a route loader and router.data for page data.`);
|
|
166
|
+
}
|
|
167
|
+
const params = Object.prototype.hasOwnProperty.call(entry, "params") ? entry.params : entry;
|
|
168
|
+
add(fillRoute(route, params), params, route);
|
|
169
|
+
}
|
|
170
|
+
} else {
|
|
171
|
+
skipped.push(route);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { paths, skipped };
|
|
175
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
//! SSG runtime helpers — the string-building primitives the SSG codegen emits
|
|
2
|
+
//! (ARCHITECTURE.md §6). No DOM: these run in plain Bun/Node at build time and
|
|
3
|
+
//! return HTML strings. Component output is composed via a tag→renderer registry,
|
|
4
|
+
//! mirroring how CSR composes by Custom Element tag.
|
|
5
|
+
|
|
6
|
+
import { escapeAttr, escapeHtml } from "../core/html.js";
|
|
7
|
+
export { escapeAttr, escapeHtml } from "../core/html.js";
|
|
8
|
+
|
|
9
|
+
import { getRenderContext } from "../core/render-context.js";
|
|
10
|
+
|
|
11
|
+
const VOID = new Set([
|
|
12
|
+
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
|
|
13
|
+
"param", "source", "track", "wbr",
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const UNITLESS = new Set([
|
|
17
|
+
"opacity", "zIndex", "fontWeight", "lineHeight", "flex", "flexGrow", "flexShrink",
|
|
18
|
+
"order", "zoom", "tabSize", "columnCount", "fillOpacity", "strokeOpacity",
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
const registry = {};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Register a component's SSG renderer under its Custom Element tag. Returns the
|
|
25
|
+
* renderer so a caller can attach the optional `hostClass` / `hostAttrs` hooks.
|
|
26
|
+
*/
|
|
27
|
+
export function defineSSG(tag, render) {
|
|
28
|
+
registry[tag] = render;
|
|
29
|
+
return render;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ── hydration props collector (compiler-driven data hydration) ────────────────
|
|
33
|
+
// The lossy path is passing rich props through string attributes. Instead, each
|
|
34
|
+
// server-rendered island gets a `data-h` id and its JSON-safe props are recorded into a
|
|
35
|
+
// single payload the shell embeds as `<script type="application/json">`. At upgrade the
|
|
36
|
+
// client component initializes its prop *signals* from those real JS values (objects,
|
|
37
|
+
// arrays, numbers) — not from `getAttribute` — so islands resume with correct data, with
|
|
38
|
+
// no flash and no dependence on a parent walk re-applying props. `renderRoute` brackets a
|
|
39
|
+
// render with `beginHydrationCollect()` / `endHydrationCollect()`.
|
|
40
|
+
let _collect = null;
|
|
41
|
+
|
|
42
|
+
function hydrationCollector() {
|
|
43
|
+
const context = getRenderContext();
|
|
44
|
+
return context ? context.hydration : _collect;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function setHydrationCollector(value) {
|
|
48
|
+
const context = getRenderContext();
|
|
49
|
+
if (context) context.hydration = value;
|
|
50
|
+
else _collect = value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Start collecting per-island hydration props for one render. */
|
|
54
|
+
export function beginHydrationCollect() {
|
|
55
|
+
setHydrationCollector([]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Finish collecting and return the payload as a JSON string ("" when nothing needs
|
|
60
|
+
* hydration). `<` is escaped so a prop value can never break out of the surrounding
|
|
61
|
+
* `<script>` (a `</script>` / `<!--` injection).
|
|
62
|
+
*/
|
|
63
|
+
export function endHydrationCollect() {
|
|
64
|
+
const data = hydrationCollector();
|
|
65
|
+
setHydrationCollector(null);
|
|
66
|
+
if (!data || data.length === 0) return "";
|
|
67
|
+
return JSON.stringify(data).replace(/</g, "\\u003c");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Record an island's JSON-safe props, returning its hydration id — or `null` when not
|
|
72
|
+
* collecting, or when nothing serializes. A JSON round-trip drops functions (event
|
|
73
|
+
* callbacks are client-only — applied by the parent walk, invisible so no flash),
|
|
74
|
+
* `undefined`, and anything cyclic/DOM/signal-shaped, so only plain data crosses.
|
|
75
|
+
*/
|
|
76
|
+
function collectHydrationProps(props) {
|
|
77
|
+
const collector = hydrationCollector();
|
|
78
|
+
if (!collector) return null;
|
|
79
|
+
const safe = jsonSafeProps(props);
|
|
80
|
+
if (!safe) return null;
|
|
81
|
+
const id = collector.length;
|
|
82
|
+
collector.push(safe);
|
|
83
|
+
return id;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A component's props with everything the payload can't carry dropped, or `null` when
|
|
87
|
+
* nothing is left to send. A JSON round-trip drops functions, `undefined`, and anything
|
|
88
|
+
* cyclic/DOM/signal-shaped. */
|
|
89
|
+
function jsonSafeProps(props) {
|
|
90
|
+
if (props == null || typeof props !== "object") return null;
|
|
91
|
+
let safe;
|
|
92
|
+
try {
|
|
93
|
+
safe = JSON.parse(JSON.stringify(props));
|
|
94
|
+
} catch {
|
|
95
|
+
return null; // cyclic / non-serializable → client falls back to attributes/defaults
|
|
96
|
+
}
|
|
97
|
+
if (!safe || typeof safe !== "object" || Object.keys(safe).length === 0) return null;
|
|
98
|
+
return safe;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* An island's props as an inline `data-hp` attribute — the fallback for one rendered
|
|
103
|
+
* *outside* a route render.
|
|
104
|
+
*
|
|
105
|
+
* A JSX value held in module-level data (`export const tabs = [{ content: <CodeBlock/> }]`,
|
|
106
|
+
* the MDX idiom) is rendered when the module is imported, before any `beginHydrationCollect`
|
|
107
|
+
* bracket, so there is no payload to record its props in and no `data-h` id to key them by.
|
|
108
|
+
* The markup is then spliced into whatever page reads it (see `ssgText`) and re-parsed on
|
|
109
|
+
* the client, where the island would upgrade with no props at all and blank its own
|
|
110
|
+
* content. Carrying the props on the host keeps that markup self-contained: it hydrates
|
|
111
|
+
* correctly wherever it ends up, at the cost of a few bytes on those hosts only.
|
|
112
|
+
*/
|
|
113
|
+
function inlineHydrationProps(props) {
|
|
114
|
+
const safe = jsonSafeProps(props);
|
|
115
|
+
if (!safe) return "";
|
|
116
|
+
return JSON.stringify(safe).replace(/[&"<]/g, (c) => (c === "&" ? "&" : c === '"' ? """ : "<"));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** clsx-style class normalization (mirrors runtime/dom.js). */
|
|
120
|
+
export function clsx(value) {
|
|
121
|
+
if (!value) return "";
|
|
122
|
+
if (typeof value === "string") return value;
|
|
123
|
+
if (typeof value === "number") return String(value);
|
|
124
|
+
if (Array.isArray(value)) {
|
|
125
|
+
const parts = [];
|
|
126
|
+
for (const v of value) {
|
|
127
|
+
const s = clsx(v);
|
|
128
|
+
if (s) parts.push(s);
|
|
129
|
+
}
|
|
130
|
+
return parts.join(" ");
|
|
131
|
+
}
|
|
132
|
+
if (typeof value === "object") {
|
|
133
|
+
const parts = [];
|
|
134
|
+
for (const k in value) if (value[k]) parts.push(k);
|
|
135
|
+
return parts.join(" ");
|
|
136
|
+
}
|
|
137
|
+
return "";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Serialize a style value (string passthrough, or object → `prop:val;`). */
|
|
141
|
+
export function styleString(value) {
|
|
142
|
+
if (!value) return "";
|
|
143
|
+
if (typeof value === "string") return value;
|
|
144
|
+
let s = "";
|
|
145
|
+
for (const k in value) {
|
|
146
|
+
const v = value[k];
|
|
147
|
+
if (v == null) continue;
|
|
148
|
+
const prop = k.startsWith("--") ? k : k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
|
|
149
|
+
const val = typeof v === "number" && !UNITLESS.has(k) ? `${v}px` : v;
|
|
150
|
+
s += `${prop}:${val};`;
|
|
151
|
+
}
|
|
152
|
+
return s;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Render one attribute: ` name="value"`, ` name` (true), or "" (null/false). */
|
|
156
|
+
export function attr(name, value) {
|
|
157
|
+
if (name === "class") value = clsx(value);
|
|
158
|
+
else if (name === "style") value = styleString(value);
|
|
159
|
+
if (value == null || value === false) return "";
|
|
160
|
+
if (value === true) return ` ${name}`;
|
|
161
|
+
return ` ${name}="${escapeAttr(String(value))}"`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The dynamic attributes of an element that carries a spread (`<div {...rest} class="x">`).
|
|
166
|
+
* `entries` lists, in source order, `[name, value]` pairs for named attributes and plain
|
|
167
|
+
* objects for spreads. A later entry overrides an earlier one with the same name, which is
|
|
168
|
+
* the order the client's `spread`/`setAttribute` calls apply them in. A served tag can't
|
|
169
|
+
* repeat an attribute (the parser keeps the first one), so the merge has to happen here.
|
|
170
|
+
* Event handlers and functions have no HTML form and are left to the client.
|
|
171
|
+
*/
|
|
172
|
+
export function ssgAttrs(entries) {
|
|
173
|
+
const merged = new Map();
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
if (Array.isArray(entry)) merged.set(entry[0], entry[1]);
|
|
176
|
+
else if (entry && typeof entry === "object") {
|
|
177
|
+
for (const k in entry) merged.set(k, entry[k]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
let s = "";
|
|
181
|
+
for (const [name, value] of merged) {
|
|
182
|
+
if (name === "ref" || name === "children" || typeof value === "function") continue;
|
|
183
|
+
s += attr(name, value);
|
|
184
|
+
}
|
|
185
|
+
return s;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Tags that close an open `<p>` (the HTML parser's "close a p element" list). Mirrors
|
|
189
|
+
// `CLOSES_P` in the compiler's static_tree.rs.
|
|
190
|
+
const CLOSES_P = /<(address|article|aside|blockquote|center|details|dialog|dir|div|dl|dd|dt|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|li|listing|main|menu|nav|ol|p|plaintext|pre|search|section|summary|table|ul|xmp)[\s/>]/i;
|
|
191
|
+
const warnedParagraphs = new Set();
|
|
192
|
+
|
|
193
|
+
/** The first tag in a paragraph's inner HTML that would close the `<p>`, or null. */
|
|
194
|
+
export function paragraphBlockTag(html) {
|
|
195
|
+
const m = CLOSES_P.exec(html);
|
|
196
|
+
return m ? m[1].toLowerCase() : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The inner HTML of a `<p>` holding components (`names`, e.g. "<Badge>"), returned
|
|
201
|
+
* unchanged. If a component's markup put a block element in it, the browser will close
|
|
202
|
+
* the paragraph early and hydration rebuilds it (`hydrateParagraph`), so say so once per
|
|
203
|
+
* page and paragraph, with the fix.
|
|
204
|
+
*/
|
|
205
|
+
export function ssgParagraph(html, names) {
|
|
206
|
+
const tag = paragraphBlockTag(html);
|
|
207
|
+
if (tag) {
|
|
208
|
+
const page = getRenderContext()?.route?.pathname ?? "";
|
|
209
|
+
const key = `${page}\0${names}\0${tag}`;
|
|
210
|
+
if (!warnedParagraphs.has(key)) {
|
|
211
|
+
warnedParagraphs.add(key);
|
|
212
|
+
console.warn(
|
|
213
|
+
`⚠ ${names} renders a <${tag}> inside a paragraph${page ? ` on ${page}` : ""}. ` +
|
|
214
|
+
"The browser moves it out of the <p>, so that paragraph is rebuilt on load. " +
|
|
215
|
+
"Put the component on its own line, or render inline markup (<span>) from it.",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return html;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A dynamic hole's value → HTML: trusted `{__html}` raw, else escaped text. An
|
|
224
|
+
* array (`{[<a/>, <b/>]}` or `{[1, 2, 3]}`) renders each item concatenated with no
|
|
225
|
+
* separator — mirroring CSR's `toNodes`/`bindText`, where an array value inserts one
|
|
226
|
+
* node per item. Without this an array would stringify to `[object Object]` (JSX) or
|
|
227
|
+
* a comma-joined string, diverging from the hydrated client render.
|
|
228
|
+
*/
|
|
229
|
+
export function ssgText(v) {
|
|
230
|
+
if (v == null || v === false || v === true) return "";
|
|
231
|
+
if (Array.isArray(v)) return v.map(ssgText).join("");
|
|
232
|
+
if (typeof v === "object" && v.__html != null) return v.__html;
|
|
233
|
+
return escapeHtml(String(v));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A dynamic hole inside a **raw text** element (`<script>`, `<style>`): written verbatim.
|
|
238
|
+
*
|
|
239
|
+
* The tokenizer does not parse markup — or character references — in there, so escaping
|
|
240
|
+
* would be served literally (`a > b` in a stylesheet is the entity, not `>`), and the
|
|
241
|
+
* CSR path, which puts the value in the element's text node, doesn't escape either. The
|
|
242
|
+
* one sequence that must not survive is the element's own closing tag: `</script` inside
|
|
243
|
+
* the value would end the element early and spill the rest into the document. It is
|
|
244
|
+
* written as `<\/script`, which the tokenizer no longer recognizes as an end tag and
|
|
245
|
+
* which JavaScript reads back identically inside the string literal such a sequence
|
|
246
|
+
* almost always sits in. `<textarea>`/`<title>` are *escapable* raw text — they resolve
|
|
247
|
+
* character references — so their holes go through `ssgText` instead.
|
|
248
|
+
*/
|
|
249
|
+
export function ssgRawText(v) {
|
|
250
|
+
if (v == null || v === false || v === true) return "";
|
|
251
|
+
if (Array.isArray(v)) return v.map(ssgRawText).join("");
|
|
252
|
+
return String(v).replace(/<\/(script|style|textarea|title|xmp|iframe|noembed|noframes)/gi, "<\\/$1");
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Render an array.map list to concatenated HTML. */
|
|
256
|
+
export function ssgList(arr, fn) {
|
|
257
|
+
return (Array.isArray(arr) ? arr : []).map(fn).join("");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Render a child component `<tag>inner</tag>` via the registry. Props are passed to
|
|
262
|
+
* the renderer (which decides where they land — declared props become properties /
|
|
263
|
+
* forward into the view), so the host tag carries no reflected attributes — exactly
|
|
264
|
+
* as CSR composes a component (props go through `setProp`, declared ones as
|
|
265
|
+
* properties, not host attributes). Avoids duplicating e.g. `class` on both the
|
|
266
|
+
* host and the element the component renders.
|
|
267
|
+
*/
|
|
268
|
+
export function ssgComponent(tag, props, children) {
|
|
269
|
+
const render = registry[tag];
|
|
270
|
+
let inner;
|
|
271
|
+
try {
|
|
272
|
+
inner = render ? render(props || {}, children ?? "") : (children ?? "");
|
|
273
|
+
} catch {
|
|
274
|
+
inner = ""; // fail soft (client renders/handles it)
|
|
275
|
+
}
|
|
276
|
+
// Stamp the stable styling hook on the host (mirrors CSR's `classList.add`) so
|
|
277
|
+
// tag-hashed components are still styleable by a readable class name, plus the
|
|
278
|
+
// hydration id (`data-h`) keying this island's rich props in the payload (if any).
|
|
279
|
+
const cls = render && render.hostClass;
|
|
280
|
+
const id = collectHydrationProps(props);
|
|
281
|
+
let attrs = cls ? ` class="${cls}"` : "";
|
|
282
|
+
// A renderer may need an attribute on the *host* to be present in the served HTML,
|
|
283
|
+
// before any script runs — see `afw-internal-context-provider`, whose subtree is
|
|
284
|
+
// resolved by `closest()` at custom-element upgrade time.
|
|
285
|
+
if (render && render.hostAttrs) attrs += render.hostAttrs(props || {}) || "";
|
|
286
|
+
if (id != null) {
|
|
287
|
+
attrs += ` data-h="${id}"`;
|
|
288
|
+
} else {
|
|
289
|
+
// Rendered outside a route render (module-level JSX-as-value): carry the props on
|
|
290
|
+
// the host itself so the markup hydrates wherever it is spliced in.
|
|
291
|
+
const inline = inlineHydrationProps(props);
|
|
292
|
+
if (inline) attrs += ` data-hp="${inline}"`;
|
|
293
|
+
}
|
|
294
|
+
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export { VOID };
|