@jasonshimmy/custom-elements-runtime 3.1.2 → 3.2.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/dist/custom-elements-runtime.cjs.js +1 -1
- package/dist/custom-elements-runtime.es.js +3 -3
- package/dist/custom-elements-runtime.jit-css.cjs.js +1 -1
- package/dist/custom-elements-runtime.jit-css.es.js +2 -2
- package/dist/custom-elements-runtime.router.cjs.js +14 -14
- package/dist/custom-elements-runtime.router.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.router.es.js +469 -468
- package/dist/custom-elements-runtime.router.es.js.map +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js +3 -1
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.es.js +44 -42
- package/dist/custom-elements-runtime.ssr-middleware.es.js.map +1 -1
- package/dist/custom-elements-runtime.ssr.cjs.js +2 -2
- package/dist/custom-elements-runtime.ssr.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.ssr.es.js +5 -4
- package/dist/custom-elements-runtime.ssr.es.js.map +1 -1
- package/dist/{hooks-xWZhQHco.js → hooks-BH-CpUun.js} +223 -214
- package/dist/hooks-BH-CpUun.js.map +1 -0
- package/dist/hooks-NOFG9QRQ.cjs +6 -0
- package/dist/hooks-NOFG9QRQ.cjs.map +1 -0
- package/dist/runtime/ssr-context.d.ts +1 -13
- package/dist/runtime/vdom-ssr-dsd.d.ts +14 -0
- package/dist/ssr-middleware.d.ts +18 -2
- package/dist/ssr.d.ts +3 -4
- package/dist/template-compiler-CDvhsHia.cjs +22 -0
- package/dist/template-compiler-CDvhsHia.cjs.map +1 -0
- package/dist/{template-compiler-ZhSg1yPh.js → template-compiler-DiE69FLO.js} +4 -4
- package/dist/template-compiler-DiE69FLO.js.map +1 -0
- package/package.json +1 -1
- package/dist/hooks-x8M4knLc.cjs +0 -6
- package/dist/hooks-x8M4knLc.cjs.map +0 -1
- package/dist/hooks-xWZhQHco.js.map +0 -1
- package/dist/template-compiler-CTUhEHr8.cjs +0 -22
- package/dist/template-compiler-CTUhEHr8.cjs.map +0 -1
- package/dist/template-compiler-ZhSg1yPh.js.map +0 -1
|
@@ -1,69 +1,71 @@
|
|
|
1
|
-
import { renderToStringWithJITCSS as
|
|
2
|
-
function
|
|
3
|
-
if (!
|
|
4
|
-
if (
|
|
5
|
-
const r =
|
|
6
|
-
return r &&
|
|
1
|
+
import { renderToStringWithJITCSS as H, renderToStream as b } from "./custom-elements-runtime.ssr.es.js";
|
|
2
|
+
function D(t, o, c) {
|
|
3
|
+
if (!c) return t;
|
|
4
|
+
if (t.trimStart().toLowerCase().startsWith("<html") || t.includes("</html>")) {
|
|
5
|
+
const r = o ?? "", d = t.startsWith("<!DOCTYPE") ? t : `<!DOCTYPE html>${t}`;
|
|
6
|
+
return r && d.includes("</head>") ? d.replace("</head>", `${r}</head>`) : d;
|
|
7
7
|
}
|
|
8
|
-
return `<!DOCTYPE html><html><head>${
|
|
8
|
+
return `<!DOCTYPE html><html><head>${o ?? ""}</head><body>${t}</body></html>`;
|
|
9
9
|
}
|
|
10
|
-
function
|
|
11
|
-
const
|
|
10
|
+
function R(t, o) {
|
|
11
|
+
const c = {
|
|
12
12
|
dsd: !0,
|
|
13
|
-
...
|
|
14
|
-
}, { head:
|
|
15
|
-
return async (
|
|
13
|
+
...o?.render
|
|
14
|
+
}, { head: u, document: r = !0 } = o ?? {};
|
|
15
|
+
return async (d, n) => {
|
|
16
16
|
try {
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
const e = typeof t == "function" ? await t(d) : t, a = e !== null && typeof e == "object" && "vnode" in e, m = a ? e.vnode : e, p = a ? e.router : void 0, w = a ? e.head : void 0, { htmlWithStyles: h } = H(m, { ...c, router: p }), y = [u, w].filter(Boolean).join(`
|
|
18
|
+
`) || void 0, l = D(h, y, r);
|
|
19
|
+
n.setHeader("Content-Type", "text/html; charset=utf-8"), n.end(l);
|
|
20
|
+
} catch (e) {
|
|
20
21
|
try {
|
|
21
|
-
|
|
22
|
+
n.setHeader("Content-Type", "text/plain; charset=utf-8"), n.end("Internal Server Error");
|
|
22
23
|
} catch {
|
|
23
24
|
}
|
|
24
|
-
throw
|
|
25
|
+
throw e;
|
|
25
26
|
}
|
|
26
27
|
};
|
|
27
28
|
}
|
|
28
|
-
function
|
|
29
|
-
const
|
|
29
|
+
function S(t, o) {
|
|
30
|
+
const c = {
|
|
30
31
|
dsd: !0,
|
|
31
|
-
...
|
|
32
|
-
}, { head:
|
|
33
|
-
return async (
|
|
32
|
+
...o?.render
|
|
33
|
+
}, { head: u, document: r = !0 } = o ?? {};
|
|
34
|
+
return async (d, n) => {
|
|
34
35
|
try {
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
const e = typeof t == "function" ? await t(d) : t, a = e !== null && typeof e == "object" && "vnode" in e, m = a ? e.vnode : e, p = a ? e.router : void 0, w = a ? e.head : void 0, h = [u, w].filter(Boolean).join(`
|
|
37
|
+
`) || void 0;
|
|
38
|
+
n.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
39
|
+
const l = b(m, { ...c, router: p }).getReader();
|
|
40
|
+
if (n.write) {
|
|
41
|
+
n.setHeader("Transfer-Encoding", "chunked"), r && n.write(`<!DOCTYPE html><html><head>${h ?? ""}</head><body>`);
|
|
42
|
+
let s = !1;
|
|
43
|
+
for (; !s; ) {
|
|
44
|
+
const { value: i, done: f } = await l.read();
|
|
45
|
+
i && n.write(i), s = f;
|
|
44
46
|
}
|
|
45
|
-
r ?
|
|
47
|
+
r ? n.end("</body></html>") : n.end();
|
|
46
48
|
} else {
|
|
47
|
-
const
|
|
49
|
+
const s = [];
|
|
48
50
|
let i = !1;
|
|
49
51
|
for (; !i; ) {
|
|
50
|
-
const { value:
|
|
51
|
-
|
|
52
|
+
const { value: C, done: v } = await l.read();
|
|
53
|
+
C && s.push(C), i = v;
|
|
52
54
|
}
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
+
const f = s.join(""), T = r ? `<!DOCTYPE html><html><head>${h ?? ""}</head><body>${f}</body></html>` : f;
|
|
56
|
+
n.end(T);
|
|
55
57
|
}
|
|
56
|
-
} catch (
|
|
58
|
+
} catch (e) {
|
|
57
59
|
try {
|
|
58
|
-
|
|
60
|
+
n.setHeader("Content-Type", "text/plain; charset=utf-8"), n.end("Internal Server Error");
|
|
59
61
|
} catch {
|
|
60
62
|
}
|
|
61
|
-
throw
|
|
63
|
+
throw e;
|
|
62
64
|
}
|
|
63
65
|
};
|
|
64
66
|
}
|
|
65
67
|
export {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
+
R as createSSRHandler,
|
|
69
|
+
S as createStreamingSSRHandler
|
|
68
70
|
};
|
|
69
71
|
//# sourceMappingURL=custom-elements-runtime.ssr-middleware.es.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.ssr-middleware.es.js","sources":["../src/lib/ssr-middleware.ts"],"sourcesContent":["/**\n * SSR middleware helpers for Express, Fastify, Hono, and other Node.js HTTP frameworks.\n *\n * Provides two handler factories that wrap the SSR rendering pipeline and\n * emit a complete HTML document response. Both accept a static VNode **or**\n * a per-request factory function so route-specific data can be threaded into\n * the render tree.\n *\n * @example Express — static VNode\n * ```ts\n * import express from 'express';\n * import { createSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware';\n * import { html } from '@jasonshimmy/custom-elements-runtime';\n *\n * const app = express();\n * app.get('/', createSSRHandler(html`<my-app />`, {\n * render: { dsd: true, jit: { extendedColors: true } },\n * }));\n * ```\n *\n * @example Express — per-request factory\n * ```ts\n * app.get('*', createSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true }, head: '<link rel=\"stylesheet\" href=\"/app.css\">' },\n * ));\n * ```\n *\n * @example Streaming variant\n * ```ts\n * app.get('*', createStreamingSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * ));\n * ```\n */\n\nimport { renderToStringWithJITCSS, renderToStream } from './ssr';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport type { JITCSSOptions } from './runtime/style';\n\n// ---------------------------------------------------------------------------\n// Minimal framework-agnostic HTTP types\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal request interface compatible with Express, Fastify, Hono, and the\n * raw Node.js `IncomingMessage`. Extend or replace with your framework's\n * request type via the generic parameter on `createSSRHandler`.\n */\nexport interface MinimalRequest {\n url?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\n/**\n * Minimal response interface compatible with Express, Fastify, Hono, and the\n * raw Node.js `ServerResponse`. `write` is optional — handlers fall back to\n * buffering when it is absent.\n */\nexport interface MinimalResponse {\n setHeader(name: string, value: string): void;\n write?(chunk: string): boolean | void;\n end(data?: string): void;\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link createSSRHandler} and {@link createStreamingSSRHandler}.\n */\nexport interface SSRMiddlewareOptions {\n /**\n * Render options forwarded to `renderToStringWithJITCSS`.\n * Defaults to `{ dsd: true }` so DSD output is on by default.\n */\n render?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions };\n /**\n * Additional HTML inserted at the end of the `<head>` tag.\n * Use this to inject `<link>`, `<script>`, `<meta>`, or `<title>` tags.\n */\n head?: string;\n /**\n * When `true` (default), the response is wrapped in a complete\n * `<!DOCTYPE html>` document shell. Set to `false` if you want to\n * assemble the document yourself and only need the rendered fragment.\n */\n document?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction wrapInDocument(\n htmlWithStyles: string,\n head: string | undefined,\n wrapDocument: boolean,\n): string {\n if (!wrapDocument) return htmlWithStyles;\n\n // If the rendered HTML already contains a root <html> tag, inject extra\n // head tags and prepend the DOCTYPE — do not double-wrap.\n if (\n htmlWithStyles.trimStart().toLowerCase().startsWith('<html') ||\n htmlWithStyles.includes('</html>')\n ) {\n const extra = head ?? '';\n const withDoctype = htmlWithStyles.startsWith('<!DOCTYPE')\n ? htmlWithStyles\n : `<!DOCTYPE html>${htmlWithStyles}`;\n if (extra) {\n return withDoctype.includes('</head>')\n ? withDoctype.replace('</head>', `${extra}</head>`)\n : withDoctype;\n }\n return withDoctype;\n }\n\n // Minimal shell\n const headContent = head ?? '';\n return `<!DOCTYPE html><html><head>${headContent}</head><body>${htmlWithStyles}</body></html>`;\n}\n\n// ---------------------------------------------------------------------------\n// Handler factories\n// ---------------------------------------------------------------------------\n\n/**\n * Create a request handler that SSR-renders a VNode tree and sends the full\n * HTML document as the response.\n *\n * Compatible with Express, Fastify, Hono, and any framework that uses an\n * `(req, res)` handler signature. The generic `Req` parameter lets you use\n * your framework's typed request object.\n *\n * @param vnodeOrFactory - A static {@link VNode} **or** a (possibly async)\n * factory function that receives the request and returns the VNode to render.\n * @param options - Render and document-shell options.\n *\n * @example\n * ```ts\n * app.get('*', createSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true, jit: { extendedColors: true } } },\n * ));\n * ```\n */\nexport function createSSRHandler<Req extends MinimalRequest = MinimalRequest>(\n vnodeOrFactory: VNode | ((req: Req) => VNode | Promise<VNode>),\n options?: SSRMiddlewareOptions,\n): (req: Req, res: MinimalResponse) => Promise<void> {\n const renderOptions: RenderOptions &\n DSDRenderOptions & { jit?: JITCSSOptions } = {\n dsd: true,\n ...options?.render,\n };\n const { head, document: wrapDocument = true } = options ?? {};\n\n return async (req, res) => {\n try {\n const vnode =\n typeof vnodeOrFactory === 'function'\n ? await vnodeOrFactory(req)\n : vnodeOrFactory;\n\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, renderOptions);\n\n const body = wrapInDocument(htmlWithStyles, head, wrapDocument);\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.end(body);\n } catch (err) {\n // Ensure the response is always closed to prevent the request hanging.\n // Re-throw so the framework's error handler can set the proper status code.\n try {\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\n res.end('Internal Server Error');\n } catch {\n // ignore secondary errors during error response\n }\n throw err;\n }\n };\n}\n\n/**\n * Create a request handler that SSR-renders a VNode tree and streams the HTML\n * response using chunked transfer encoding.\n *\n * Each chunk produced by the underlying {@link renderToStream} call is written\n * to the response as it becomes available, minimising Time-to-First-Byte.\n * The document shell preamble (`<!DOCTYPE html>…<body>`) is sent in the first\n * write so the browser can begin parsing immediately.\n *\n * @param vnodeOrFactory - A static {@link VNode} **or** a (possibly async)\n * factory function that receives the request and returns the VNode to render.\n * @param options - Render and document-shell options.\n *\n * @example\n * ```ts\n * app.get('*', createStreamingSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true } },\n * ));\n * ```\n */\nexport function createStreamingSSRHandler<\n Req extends MinimalRequest = MinimalRequest,\n>(\n vnodeOrFactory: VNode | ((req: Req) => VNode | Promise<VNode>),\n options?: SSRMiddlewareOptions,\n): (req: Req, res: MinimalResponse) => Promise<void> {\n const renderOptions: RenderOptions &\n DSDRenderOptions & { jit?: JITCSSOptions } = {\n dsd: true,\n ...options?.render,\n };\n const { head, document: wrapDocument = true } = options ?? {};\n\n return async (req, res) => {\n try {\n const vnode =\n typeof vnodeOrFactory === 'function'\n ? await vnodeOrFactory(req)\n : vnodeOrFactory;\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n\n const stream = renderToStream(vnode, renderOptions);\n const reader = stream.getReader();\n\n if (res.write) {\n // Streaming path: pipe chunks directly to the response as they arrive.\n res.setHeader('Transfer-Encoding', 'chunked');\n if (wrapDocument) {\n res.write(`<!DOCTYPE html><html><head>${head ?? ''}</head><body>`);\n }\n let done = false;\n while (!done) {\n const { value, done: d } = await reader.read();\n if (value) res.write(value);\n done = d;\n }\n if (wrapDocument) {\n res.end('</body></html>');\n } else {\n res.end();\n }\n } else {\n // Buffered fallback: framework does not expose write(); collect and send as one response.\n const chunks: string[] = [];\n let done = false;\n while (!done) {\n const { value, done: d } = await reader.read();\n if (value) chunks.push(value);\n done = d;\n }\n const content = chunks.join('');\n const body = wrapDocument\n ? `<!DOCTYPE html><html><head>${head ?? ''}</head><body>${content}</body></html>`\n : content;\n res.end(body);\n }\n } catch (err) {\n // Ensure the response is always closed to prevent the request hanging.\n // Re-throw so the framework's error handler can set the proper status code.\n try {\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\n res.end('Internal Server Error');\n } catch {\n // ignore secondary errors during error response\n }\n throw err;\n }\n };\n}\n"],"names":["wrapInDocument","htmlWithStyles","head","wrapDocument","extra","withDoctype","createSSRHandler","vnodeOrFactory","options","renderOptions","req","res","vnode","renderToStringWithJITCSS","body","err","createStreamingSSRHandler","reader","renderToStream","done","value","d","chunks","content"],"mappings":";AAkGA,SAASA,EACPC,GACAC,GACAC,GACQ;AACR,MAAI,CAACA,EAAc,QAAOF;AAI1B,MACEA,EAAe,YAAY,cAAc,WAAW,OAAO,KAC3DA,EAAe,SAAS,SAAS,GACjC;AACA,UAAMG,IAAQF,KAAQ,IAChBG,IAAcJ,EAAe,WAAW,WAAW,IACrDA,IACA,kBAAkBA,CAAc;AACpC,WAAIG,KACKC,EAAY,SAAS,SAAS,IACjCA,EAAY,QAAQ,WAAW,GAAGD,CAAK,SAAS,IAG/CC;AAAA,EACT;AAIA,SAAO,8BADaH,KAAQ,EACoB,gBAAgBD,CAAc;AAChF;AA0BO,SAASK,EACdC,GACAC,GACmD;AACnD,QAAMC,IACyC;AAAA,IAC7C,KAAK;AAAA,IACL,GAAGD,GAAS;AAAA,EAAA,GAER,EAAE,MAAAN,GAAM,UAAUC,IAAe,GAAA,IAASK,KAAW,CAAA;AAE3D,SAAO,OAAOE,GAAKC,MAAQ;AACzB,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,KAAM;AACZ,gBAAM,EAAE,OAAAC,GAAO,MAAMC,MAAM,MAAMJ,EAAO,KAAA;AACxC,UAAIG,KAAOE,EAAO,KAAKF,CAAK,GAC5BD,IAAOE;AAAA,QACT;AACA,cAAME,IAAUD,EAAO,KAAK,EAAE,GACxBR,IAAOX,IACT,8BAA8BD,KAAQ,EAAE,gBAAgBqB,CAAO,mBAC/DA;AACJ,QAAAZ,EAAI,IAAIG,CAAI;AAAA,MACd;AAAA,IACF,SAASC,GAAK;AAGZ,UAAI;AACF,QAAAJ,EAAI,UAAU,gBAAgB,2BAA2B,GACzDA,EAAI,IAAI,uBAAuB;AAAA,MACjC,QAAQ;AAAA,MAER;AACA,YAAMI;AAAA,IACR;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.ssr-middleware.es.js","sources":["../src/lib/ssr-middleware.ts"],"sourcesContent":["/**\n * SSR middleware helpers for Express, Fastify, Hono, and other Node.js HTTP frameworks.\n *\n * Provides two handler factories that wrap the SSR rendering pipeline and\n * emit a complete HTML document response. Both accept a static VNode **or**\n * a per-request factory function so route-specific data can be threaded into\n * the render tree.\n *\n * @example Express — static VNode\n * ```ts\n * import express from 'express';\n * import { createSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware';\n * import { html } from '@jasonshimmy/custom-elements-runtime';\n *\n * const app = express();\n * app.get('/', createSSRHandler(html`<my-app />`, {\n * render: { dsd: true, jit: { extendedColors: true } },\n * }));\n * ```\n *\n * @example Express — per-request factory\n * ```ts\n * app.get('*', createSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true }, head: '<link rel=\"stylesheet\" href=\"/app.css\">' },\n * ));\n * ```\n *\n * @example Streaming variant\n * ```ts\n * app.get('*', createStreamingSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * ));\n * ```\n */\n\nimport { renderToStringWithJITCSS, renderToStream } from './ssr';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport type { JITCSSOptions } from './runtime/style';\n\n/**\n * What a per-request factory may return.\n *\n * - Plain `VNode` — backward-compatible; no per-request router threading.\n * - `{ vnode, router? }` — the router instance is threaded through the render\n * context, making concurrent SSR requests safe (each render reads from its\n * own router, not the module-level `activeRouterProxy` singleton).\n * - `{ vnode, router?, head? }` — `head` is an HTML string injected into the\n * document `<head>` for this specific request (e.g. serialized loader data).\n * It is merged with the static `head` option passed to the handler factory.\n */\nexport type VnodeFactoryResult = VNode | { vnode: VNode; router?: unknown; head?: string };\n\n// ---------------------------------------------------------------------------\n// Minimal framework-agnostic HTTP types\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal request interface compatible with Express, Fastify, Hono, and the\n * raw Node.js `IncomingMessage`. Extend or replace with your framework's\n * request type via the generic parameter on `createSSRHandler`.\n */\nexport interface MinimalRequest {\n url?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\n/**\n * Minimal response interface compatible with Express, Fastify, Hono, and the\n * raw Node.js `ServerResponse`. `write` is optional — handlers fall back to\n * buffering when it is absent.\n */\nexport interface MinimalResponse {\n setHeader(name: string, value: string): void;\n write?(chunk: string): boolean | void;\n end(data?: string): void;\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link createSSRHandler} and {@link createStreamingSSRHandler}.\n */\nexport interface SSRMiddlewareOptions {\n /**\n * Render options forwarded to `renderToStringWithJITCSS`.\n * Defaults to `{ dsd: true }` so DSD output is on by default.\n */\n render?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions };\n /**\n * Additional HTML inserted at the end of the `<head>` tag.\n * Use this to inject `<link>`, `<script>`, `<meta>`, or `<title>` tags.\n */\n head?: string;\n /**\n * When `true` (default), the response is wrapped in a complete\n * `<!DOCTYPE html>` document shell. Set to `false` if you want to\n * assemble the document yourself and only need the rendered fragment.\n */\n document?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction wrapInDocument(\n htmlWithStyles: string,\n head: string | undefined,\n wrapDocument: boolean,\n): string {\n if (!wrapDocument) return htmlWithStyles;\n\n // If the rendered HTML already contains a root <html> tag, inject extra\n // head tags and prepend the DOCTYPE — do not double-wrap.\n if (\n htmlWithStyles.trimStart().toLowerCase().startsWith('<html') ||\n htmlWithStyles.includes('</html>')\n ) {\n const extra = head ?? '';\n const withDoctype = htmlWithStyles.startsWith('<!DOCTYPE')\n ? htmlWithStyles\n : `<!DOCTYPE html>${htmlWithStyles}`;\n if (extra) {\n return withDoctype.includes('</head>')\n ? withDoctype.replace('</head>', `${extra}</head>`)\n : withDoctype;\n }\n return withDoctype;\n }\n\n // Minimal shell\n const headContent = head ?? '';\n return `<!DOCTYPE html><html><head>${headContent}</head><body>${htmlWithStyles}</body></html>`;\n}\n\n// ---------------------------------------------------------------------------\n// Handler factories\n// ---------------------------------------------------------------------------\n\n/**\n * Create a request handler that SSR-renders a VNode tree and sends the full\n * HTML document as the response.\n *\n * Compatible with Express, Fastify, Hono, and any framework that uses an\n * `(req, res)` handler signature. The generic `Req` parameter lets you use\n * your framework's typed request object.\n *\n * @param vnodeOrFactory - A static {@link VNode} **or** a (possibly async)\n * factory function that receives the request and returns the VNode to render.\n * @param options - Render and document-shell options.\n *\n * @example\n * ```ts\n * app.get('*', createSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true, jit: { extendedColors: true } } },\n * ));\n * ```\n */\nexport function createSSRHandler<Req extends MinimalRequest = MinimalRequest>(\n vnodeOrFactory:\n | VnodeFactoryResult\n | ((req: Req) => VnodeFactoryResult | Promise<VnodeFactoryResult>),\n options?: SSRMiddlewareOptions,\n): (req: Req, res: MinimalResponse) => Promise<void> {\n const renderOptions: RenderOptions &\n DSDRenderOptions & { jit?: JITCSSOptions } = {\n dsd: true,\n ...options?.render,\n };\n const { head, document: wrapDocument = true } = options ?? {};\n\n return async (req, res) => {\n try {\n const rawResult =\n typeof vnodeOrFactory === 'function'\n ? await vnodeOrFactory(req)\n : vnodeOrFactory;\n\n const isBundle =\n rawResult !== null &&\n typeof rawResult === 'object' &&\n 'vnode' in (rawResult as object);\n const vnode = isBundle\n ? (rawResult as { vnode: VNode }).vnode\n : (rawResult as VNode);\n const router = isBundle\n ? (rawResult as { vnode: VNode; router?: unknown }).router\n : undefined;\n const perRequestHead = isBundle\n ? (rawResult as { head?: string }).head\n : undefined;\n\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, { ...renderOptions, router });\n\n const mergedHead = [head, perRequestHead].filter(Boolean).join('\\n') || undefined;\n const body = wrapInDocument(htmlWithStyles, mergedHead, wrapDocument);\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.end(body);\n } catch (err) {\n // Ensure the response is always closed to prevent the request hanging.\n // Re-throw so the framework's error handler can set the proper status code.\n try {\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\n res.end('Internal Server Error');\n } catch {\n // ignore secondary errors during error response\n }\n throw err;\n }\n };\n}\n\n/**\n * Create a request handler that SSR-renders a VNode tree and streams the HTML\n * response using chunked transfer encoding.\n *\n * Each chunk produced by the underlying {@link renderToStream} call is written\n * to the response as it becomes available, minimising Time-to-First-Byte.\n * The document shell preamble (`<!DOCTYPE html>…<body>`) is sent in the first\n * write so the browser can begin parsing immediately.\n *\n * @param vnodeOrFactory - A static {@link VNode} **or** a (possibly async)\n * factory function that receives the request and returns the VNode to render.\n * @param options - Render and document-shell options.\n *\n * @example\n * ```ts\n * app.get('*', createStreamingSSRHandler(\n * (req) => html`<my-app url=\"${req.url}\" />`,\n * { render: { dsd: true } },\n * ));\n * ```\n */\nexport function createStreamingSSRHandler<\n Req extends MinimalRequest = MinimalRequest,\n>(\n vnodeOrFactory:\n | VnodeFactoryResult\n | ((req: Req) => VnodeFactoryResult | Promise<VnodeFactoryResult>),\n options?: SSRMiddlewareOptions,\n): (req: Req, res: MinimalResponse) => Promise<void> {\n const renderOptions: RenderOptions &\n DSDRenderOptions & { jit?: JITCSSOptions } = {\n dsd: true,\n ...options?.render,\n };\n const { head, document: wrapDocument = true } = options ?? {};\n\n return async (req, res) => {\n try {\n const rawResult =\n typeof vnodeOrFactory === 'function'\n ? await vnodeOrFactory(req)\n : vnodeOrFactory;\n\n const isBundle =\n rawResult !== null &&\n typeof rawResult === 'object' &&\n 'vnode' in (rawResult as object);\n const vnode = isBundle\n ? (rawResult as { vnode: VNode }).vnode\n : (rawResult as VNode);\n const router = isBundle\n ? (rawResult as { vnode: VNode; router?: unknown }).router\n : undefined;\n const perRequestHead = isBundle\n ? (rawResult as { head?: string }).head\n : undefined;\n\n const mergedHead = [head, perRequestHead].filter(Boolean).join('\\n') || undefined;\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n\n const stream = renderToStream(vnode, { ...renderOptions, router });\n const reader = stream.getReader();\n\n if (res.write) {\n // Streaming path: pipe chunks directly to the response as they arrive.\n res.setHeader('Transfer-Encoding', 'chunked');\n if (wrapDocument) {\n res.write(`<!DOCTYPE html><html><head>${mergedHead ?? ''}</head><body>`);\n }\n let done = false;\n while (!done) {\n const { value, done: d } = await reader.read();\n if (value) res.write(value);\n done = d;\n }\n if (wrapDocument) {\n res.end('</body></html>');\n } else {\n res.end();\n }\n } else {\n // Buffered fallback: framework does not expose write(); collect and send as one response.\n const chunks: string[] = [];\n let done = false;\n while (!done) {\n const { value, done: d } = await reader.read();\n if (value) chunks.push(value);\n done = d;\n }\n const content = chunks.join('');\n const body = wrapDocument\n ? `<!DOCTYPE html><html><head>${mergedHead ?? ''}</head><body>${content}</body></html>`\n : content;\n res.end(body);\n }\n } catch (err) {\n // Ensure the response is always closed to prevent the request hanging.\n // Re-throw so the framework's error handler can set the proper status code.\n try {\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\n res.end('Internal Server Error');\n } catch {\n // ignore secondary errors during error response\n }\n throw err;\n }\n };\n}\n"],"names":["wrapInDocument","htmlWithStyles","head","wrapDocument","extra","withDoctype","createSSRHandler","vnodeOrFactory","options","renderOptions","req","res","rawResult","isBundle","vnode","router","perRequestHead","renderToStringWithJITCSS","mergedHead","body","err","createStreamingSSRHandler","reader","renderToStream","done","value","d","chunks","content"],"mappings":";AA+GA,SAASA,EACPC,GACAC,GACAC,GACQ;AACR,MAAI,CAACA,EAAc,QAAOF;AAI1B,MACEA,EAAe,YAAY,cAAc,WAAW,OAAO,KAC3DA,EAAe,SAAS,SAAS,GACjC;AACA,UAAMG,IAAQF,KAAQ,IAChBG,IAAcJ,EAAe,WAAW,WAAW,IACrDA,IACA,kBAAkBA,CAAc;AACpC,WAAIG,KACKC,EAAY,SAAS,SAAS,IACjCA,EAAY,QAAQ,WAAW,GAAGD,CAAK,SAAS,IAG/CC;AAAA,EACT;AAIA,SAAO,8BADaH,KAAQ,EACoB,gBAAgBD,CAAc;AAChF;AA0BO,SAASK,EACdC,GAGAC,GACmD;AACnD,QAAMC,IACyC;AAAA,IAC7C,KAAK;AAAA,IACL,GAAGD,GAAS;AAAA,EAAA,GAER,EAAE,MAAAN,GAAM,UAAUC,IAAe,GAAA,IAASK,KAAW,CAAA;AAE3D,SAAO,OAAOE,GAAKC,MAAQ;AACzB,QAAI;AACF,YAAMC,IACJ,OAAOL,KAAmB,aACtB,MAAMA,EAAeG,CAAG,IACxBH,GAEAM,IACJD,MAAc,QACd,OAAOA,KAAc,YACrB,WAAYA,GACRE,IAAQD,IACTD,EAA+B,QAC/BA,GACCG,IAASF,IACVD,EAAiD,SAClD,QACEI,IAAiBH,IAClBD,EAAgC,OACjC,QAEE,EAAE,gBAAAX,MAAmBgB,EAAyBH,GAAO,EAAE,GAAGL,GAAe,QAAAM,GAAQ,GAEjFG,IAAa,CAAChB,GAAMc,CAAc,EAAE,OAAO,OAAO,EAAE,KAAK;AAAA,CAAI,KAAK,QAClEG,IAAOnB,EAAeC,GAAgBiB,GAAYf,CAAY;AAEpE,MAA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AAA,MAER,OAAO;AAEL,cAAMgB,IAAmB,CAAA;AACzB,YAAIH,IAAO;AACX,eAAO,CAACA,KAAM;AACZ,gBAAM,EAAE,OAAAC,GAAO,MAAMC,MAAM,MAAMJ,EAAO,KAAA;AACxC,UAAIG,KAAOE,EAAO,KAAKF,CAAK,GAC5BD,IAAOE;AAAA,QACT;AACA,cAAME,IAAUD,EAAO,KAAK,EAAE,GACxBR,IAAOhB,IACT,8BAA8Be,KAAc,EAAE,gBAAgBU,CAAO,mBACrEA;AACJ,QAAAjB,EAAI,IAAIQ,CAAI;AAAA,MACd;AAAA,IACF,SAASC,GAAK;AAGZ,UAAI;AACF,QAAAT,EAAI,UAAU,gBAAgB,2BAA2B,GACzDA,EAAI,IAAI,uBAAuB;AAAA,MACjC,QAAQ;AAAA,MAER;AACA,YAAMS;AAAA,IACR;AAAA,EACF;AACF;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./hooks-
|
|
2
|
-
`));return s?`<style>${s}</style>`:""}let p=null,E=0;function H(t){p=t,E=0}function I(){p=null}function y(t,r){if(!r.dsd)return f(t,r);if(typeof t=="string")return o.escapeHTML(t);const e=t.tag;if(e==="#text"||e==="#anchor"||e==="#raw")return f(t,r);if(_(e))return N(t,r);const n=t.props?.attrs?{...t.props.attrs}:{},s=A(n,e,r);if(j.has(e))return`<${e}${s}>`;const i=T(t.children,r);return`<${e}${s}>${i}</${e}>`}function N(t,r){const e=t.tag,n=m.registry.get(e),s=t.props?.attrs??{},i=P(s);if(!n){const h=T(t.children,r);return`<${e}${i}><template shadowrootmode="open"></template>${h}</${e}>`}const a=n.hydrate,u=a&&a!=="load"?` data-cer-hydrate="${a}"`:"",{shadowVNode:l,useStyleCSS:d,asyncPromise:S}=o.runComponentSSRRender(n,s,e);if(S&&p===null&&R.devWarn(`[SSR] Component "${e}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`),S&&p!==null){const h=`cer-stream-${E++}`,w=T(t.children,r);return p.push({id:h,tag:e,attrsString:i,hydrateAttr:u,useStyleCSS:d,lightDOM:w,opts:r,promise:S}),`<${e} id="${h}"${i}${u}><template shadowrootmode="open"></template>${w}</${e}>`}let c="";l!=null&&(Array.isArray(l)?c=l.map(h=>y(h,r)).join(""):c=y(l,r));const $=D(d,c),O=T(t.children,r);return`<${e}${i}${u}><template shadowrootmode="open">${$}${c}</template>${O}</${e}>`}function T(t,r){return t?typeof t=="string"?o.escapeHTML(t):Array.isArray(t)?t.filter(e=>e!=null).map(e=>y(e,r)).join(""):y(t,r):""}function L(t,r){const e={dsd:!0,...r},n=y(t,e);return e.dsdPolyfill!==!1?n.includes("</body>")?n.replace("</body>",`${g}</body>`):n+g:n}function M(t,r){const{jit:e,dsd:n,dsdPolyfill:s,...i}=r??{};e&&b.enableJITCSS(e),o.beginSSRGlobalStyleCollection();let a,u;try{n?a=L(t,{...i,dsd:!0,dsdPolyfill:!1}):a=f(t,i)}finally{u=o.endSSRGlobalStyleCollection()}const l=b.jitCSS(a),d=u.join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./hooks-NOFG9QRQ.cjs"),m=require("./namespace-helpers-ckeEOxpR.cjs"),b=require("./style-D40DsIqJ.cjs"),C=require("./css-utils-RqkyBWft.cjs"),R=require("./logger-CSALKaYm.cjs"),j=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function A(t,r,e){const n=e.injectSvgNamespace??!0,s=e.injectKnownNamespaces??n,i={...t};return n&&r==="svg"&&!("xmlns"in i)?i.xmlns=m.SVG_NS:s&&r in m.TAG_NAMESPACE_MAP&&!("xmlns"in i)&&(i.xmlns=m.TAG_NAMESPACE_MAP[r]),Object.entries(i).map(([a,u])=>` ${a}="${o.escapeHTML(String(u))}"`).join("")}function P(t){return Object.entries(t).map(([r,e])=>` ${r}="${o.escapeHTML(String(e))}"`).join("")}function f(t,r){if(typeof t=="string")return o.escapeHTML(t);if(t.tag==="#text")return typeof t.children=="string"?o.escapeHTML(t.children):"";if(t.tag==="#anchor")return(Array.isArray(t.children)?t.children.filter(a=>a!=null):[]).map(a=>f(a,r)).join("");if(t.tag==="#raw")return typeof t.children=="string"?t.children:"";const e=t.props?.attrs?{...t.props.attrs}:{},n=A(e,t.tag,r??{});if(j.has(t.tag))return`<${t.tag}${n}>`;const s=Array.isArray(t.children)?t.children.filter(i=>i!=null).map(i=>f(i,r)).join(""):typeof t.children=="string"?o.escapeHTML(t.children):t.children?f(t.children,r):"";return`<${t.tag}${n}>${s}</${t.tag}>`}const g="<script>(function(){if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;document.querySelectorAll('template[shadowrootmode]').forEach(function(t){var m=t.getAttribute('shadowrootmode');var s=t.parentElement.attachShadow({mode:m});s.appendChild(t.content);t.remove();});})()<\/script>";function _(t){return t.includes("-")&&m.registry.has(t)}function D(t,r){const e=[C.baseReset];t.trim()&&e.push(t);const n=b.jitCSS(r);n.trim()&&e.push(n);const s=C.minifyCSS(e.join(`
|
|
2
|
+
`));return s?`<style>${s}</style>`:""}let p=null,E=0;function H(t){p=t,E=0}function I(){p=null}function y(t,r){if(!r.dsd)return f(t,r);if(typeof t=="string")return o.escapeHTML(t);const e=t.tag;if(e==="#text"||e==="#anchor"||e==="#raw")return f(t,r);if(_(e))return N(t,r);const n=t.props?.attrs?{...t.props.attrs}:{},s=A(n,e,r);if(j.has(e))return`<${e}${s}>`;const i=T(t.children,r);return`<${e}${s}>${i}</${e}>`}function N(t,r){const e=t.tag,n=m.registry.get(e),s=t.props?.attrs??{},i=P(s);if(!n){const h=T(t.children,r);return`<${e}${i}><template shadowrootmode="open"></template>${h}</${e}>`}const a=n.hydrate,u=a&&a!=="load"?` data-cer-hydrate="${a}"`:"",{shadowVNode:l,useStyleCSS:d,asyncPromise:S}=o.runComponentSSRRender(n,s,e,r.router);if(S&&p===null&&R.devWarn(`[SSR] Component "${e}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`),S&&p!==null){const h=`cer-stream-${E++}`,w=T(t.children,r);return p.push({id:h,tag:e,attrsString:i,hydrateAttr:u,useStyleCSS:d,lightDOM:w,opts:r,promise:S,router:r.router}),`<${e} id="${h}"${i}${u}><template shadowrootmode="open"></template>${w}</${e}>`}let c="";l!=null&&(Array.isArray(l)?c=l.map(h=>y(h,r)).join(""):c=y(l,r));const $=D(d,c),O=T(t.children,r);return`<${e}${i}${u}><template shadowrootmode="open">${$}${c}</template>${O}</${e}>`}function T(t,r){return t?typeof t=="string"?o.escapeHTML(t):Array.isArray(t)?t.filter(e=>e!=null).map(e=>y(e,r)).join(""):y(t,r):""}function L(t,r){const e={dsd:!0,...r},n=y(t,e);return e.dsdPolyfill!==!1?n.includes("</body>")?n.replace("</body>",`${g}</body>`):n+g:n}function M(t,r){const{jit:e,dsd:n,dsdPolyfill:s,...i}=r??{};e&&b.enableJITCSS(e),o.beginSSRGlobalStyleCollection();let a,u;try{n?a=L(t,{...i,dsd:!0,dsdPolyfill:!1}):a=f(t,i)}finally{u=o.endSSRGlobalStyleCollection()}const l=b.jitCSS(a),d=u.join(`
|
|
3
3
|
`),S=[];l&&S.push(`<style id="cer-ssr-jit">${l}</style>`),d.trim()&&S.push(`<style id="cer-ssr-global">${d}</style>`);let c=a;if(S.length){const $=S.join("");c=a.includes("</head>")?a.replace("</head>",`${$}</head>`):`${$}${a}`}return n&&s!==!1&&(c=c.includes("</body>")?c.replace("</body>",`${g}</body>`):c+g),{html:a,css:l,globalStyles:d,htmlWithStyles:c}}function q(t,r){return M(t,{...r,dsd:!0})}function k(t,r){return new ReadableStream({async start(e){const n=[];H(n);try{const{htmlWithStyles:s}=M(t,r);e.enqueue(s)}catch(s){e.error(s);return}finally{I()}for(const s of n)try{const i=await s.promise,a=Array.isArray(i)?i.map(d=>y(d,s.opts)).join(""):y(i,s.opts),l=`${D(s.useStyleCSS,a)}${a}`;e.enqueue(`<script>(function(){var e=document.getElementById(${JSON.stringify(s.id)});if(!e)return;var s=e.shadowRoot;if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};if(s)s.innerHTML=${JSON.stringify(l)};e.removeAttribute('id');})();<\/script>`)}catch{}e.close()}})}exports.clearRegisteredEntityMap=o.clearRegisteredEntityMap;exports.loadEntityMap=o.loadEntityMap;exports.registerEntityMap=o.registerEntityMap;exports.DSD_POLYFILL_SCRIPT=g;exports.renderToStream=k;exports.renderToString=f;exports.renderToStringDSD=L;exports.renderToStringWithJITCSS=M;exports.renderToStringWithJITCSSDSD=q;
|
|
4
4
|
//# sourceMappingURL=custom-elements-runtime.ssr.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.ssr.cjs.js","sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * The current implementation flushes the complete rendered output as a single\n * chunk, providing the streaming API surface for framework adapters. True\n * incremental streaming (flush shell immediately, resolve async components\n * progressively) is planned for a future release.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"names":["VOID_ELEMENTS","buildAttrs","attrs","tag","opts","inject","injectKnown","merged","SVG_NS","TAG_NAMESPACE_MAP","k","v","escapeHTML","buildRawAttrs","renderToString","vnode","c","attrsObj","attrsString","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","registry","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","_streamingCollector","_streamingCounter","beginStreamingCollection","collector","endStreamingCollection","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","lightDOM","hydrateStrategy","hydrateAttr","shadowVNode","asyncPromise","runComponentSSRRender","devWarn","id","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","asyncEntries","err","entry","resolvedVNodes","shadowContent"],"mappings":"iRAcaA,MAAoB,IAAI,CACnC,OACA,OACA,KACA,MACA,QACA,KACA,MACA,QACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAEM,SAASC,EACdC,EACAC,EACAC,EACQ,CACR,MAAMC,EAASD,EAAK,oBAAsB,GACpCE,EAAcF,EAAK,uBAAyBC,EAC5CE,EAAS,CAAE,GAAGL,CAAA,EAEpB,OAAIG,GAAUF,IAAQ,OAAS,EAAE,UAAWI,GAC1CA,EAAO,MAAWC,EAAAA,OACTF,GAAeH,KAAOM,EAAAA,mBAAqB,EAAE,UAAWF,KACjEA,EAAO,MAAWE,EAAAA,kBAAkBN,CAAG,GAGlC,OAAO,QAAQI,CAAM,EACzB,IAAI,CAAC,CAACG,EAAGC,CAAC,IAAM,IAAID,CAAC,KAAKE,aAAW,OAAOD,CAAC,CAAC,CAAC,GAAG,EAClD,KAAK,EAAE,CACZ,CAEO,SAASE,EAAcX,EAAwC,CACpE,OAAO,OAAO,QAAQA,CAAK,EACxB,IAAI,CAAC,CAACQ,EAAGC,CAAC,IAAM,IAAID,CAAC,KAAKE,aAAW,OAAOD,CAAC,CAAC,CAAC,GAAG,EAClD,KAAK,EAAE,CACZ,CC1CO,SAASG,EAAeC,EAAcX,EAA8B,CACzE,GAAI,OAAOW,GAAU,SAAU,OAAOH,EAAAA,WAAWG,CAAK,EAEtD,GAAIA,EAAM,MAAQ,QAChB,OAAO,OAAOA,EAAM,UAAa,SAC5BH,EAAAA,WAAWG,EAAM,QAAQ,EAC1B,GAGN,GAAI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O,SAASE,EACdvD,EACAyC,EAIc,CACd,OAAOD,EAAyBxC,EAAO,CAAE,GAAGyC,EAAS,IAAK,GAAM,CAClE,CA+BO,SAASe,EACdxD,EACAyC,EACwB,CACxB,OAAO,IAAI,eAAuB,CAChC,MAAM,MAAMgB,EAAY,CACtB,MAAMC,EAAmC,CAAA,EACzCvC,EAAyBuC,CAAY,EAErC,GAAI,CACF,KAAM,CAAE,eAAAL,CAAA,EAAmBb,EAAyBxC,EAAOyC,CAAO,EAClEgB,EAAW,QAAQJ,CAAc,CACnC,OAASM,EAAK,CACZF,EAAW,MAAME,CAAG,EACpB,MACF,QAAA,CACEtC,EAAA,CACF,CAIA,UAAWuC,KAASF,EAClB,GAAI,CACF,MAAMG,EAAiB,MAAMD,EAAM,QAC7BlD,EAAa,MAAM,QAAQmD,CAAc,EAC1CA,EAA2B,IAAK1B,GAAMb,EAAYa,EAAGyB,EAAM,IAAI,CAAC,EAAE,KAAK,EAAE,EAC1EtC,EAAYuC,EAAyBD,EAAM,IAAI,EAE7CE,EAAgB,GADHtD,EAAsBoD,EAAM,YAAalD,CAAU,CACnC,GAAGA,CAAU,GAChD+C,EAAW,QACT,qDACmC,KAAK,UAAUG,EAAM,EAAE,CAAC,4HAMrC,KAAK,UAAUE,CAAa,CAAC,0CAAA,CAIvD,MAAQ,CAER,CAGFL,EAAW,MAAA,CACb,CAAA,CACD,CACH"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.ssr.cjs.js","sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"names":["VOID_ELEMENTS","buildAttrs","attrs","tag","opts","inject","injectKnown","merged","SVG_NS","TAG_NAMESPACE_MAP","k","v","escapeHTML","buildRawAttrs","renderToString","vnode","c","attrsObj","attrsString","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","registry","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","_streamingCollector","_streamingCounter","beginStreamingCollection","collector","endStreamingCollection","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","lightDOM","hydrateStrategy","hydrateAttr","shadowVNode","asyncPromise","runComponentSSRRender","devWarn","id","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","asyncEntries","err","entry","resolvedVNodes","shadowContent"],"mappings":"iRAcaA,MAAoB,IAAI,CACnC,OACA,OACA,KACA,MACA,QACA,KACA,MACA,QACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAEM,SAASC,EACdC,EACAC,EACAC,EACQ,CACR,MAAMC,EAASD,EAAK,oBAAsB,GACpCE,EAAcF,EAAK,uBAAyBC,EAC5CE,EAAS,CAAE,GAAGL,CAAA,EAEpB,OAAIG,GAAUF,IAAQ,OAAS,EAAE,UAAWI,GAC1CA,EAAO,MAAWC,EAAAA,OACTF,G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E,KAAK,EAAE,EAC1EtC,EAAYuC,EAAyBD,EAAM,IAAI,EAE7CE,EAAgB,GADHtD,EAAsBoD,EAAM,YAAalD,CAAU,CACnC,GAAGA,CAAU,GAChD+C,EAAW,QACT,qDACmC,KAAK,UAAUG,EAAM,EAAE,CAAC,4HAMrC,KAAK,UAAUE,CAAa,CAAC,0CAAA,CAIvD,MAAQ,CAER,CAGFL,EAAW,MAAA,CACb,CAAA,CACD,CACH"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as f, T as R, U as L, V as N } from "./hooks-
|
|
2
|
-
import { W as v, X as tt, Y as rt } from "./hooks-
|
|
1
|
+
import { S as f, T as R, U as L, V as N } from "./hooks-BH-CpUun.js";
|
|
2
|
+
import { W as v, X as tt, Y as rt } from "./hooks-BH-CpUun.js";
|
|
3
3
|
import { S as P, T as w, a as j } from "./namespace-helpers-D4wC2-qA.js";
|
|
4
4
|
import { j as C, e as _ } from "./style-BmyOIMcU.js";
|
|
5
5
|
import { m as x, b as I } from "./css-utils-Cg4o1MqY.js";
|
|
@@ -83,7 +83,7 @@ function V(t, e) {
|
|
|
83
83
|
const h = g(t.children, e);
|
|
84
84
|
return `<${r}${i}><template shadowrootmode="open"></template>${h}</${r}>`;
|
|
85
85
|
}
|
|
86
|
-
const a = n.hydrate, c = a && a !== "load" ? ` data-cer-hydrate="${a}"` : "", { shadowVNode: o, useStyleCSS: u, asyncPromise: d } = R(n, s, r);
|
|
86
|
+
const a = n.hydrate, c = a && a !== "load" ? ` data-cer-hydrate="${a}"` : "", { shadowVNode: o, useStyleCSS: u, asyncPromise: d } = R(n, s, r, e.router);
|
|
87
87
|
if (d && S === null && k(
|
|
88
88
|
`[SSR] Component "${r}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`
|
|
89
89
|
), d && S !== null) {
|
|
@@ -96,7 +96,8 @@ function V(t, e) {
|
|
|
96
96
|
useStyleCSS: u,
|
|
97
97
|
lightDOM: b,
|
|
98
98
|
opts: e,
|
|
99
|
-
promise: d
|
|
99
|
+
promise: d,
|
|
100
|
+
router: e.router
|
|
100
101
|
}), `<${r} id="${h}"${i}${c}><template shadowrootmode="open"></template>${b}</${r}>`;
|
|
101
102
|
}
|
|
102
103
|
let l = "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.ssr.es.js","sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * The current implementation flushes the complete rendered output as a single\n * chunk, providing the streaming API surface for framework adapters. True\n * incremental streaming (flush shell immediately, resolve async components\n * progressively) is planned for a future release.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"names":["VOID_ELEMENTS","buildAttrs","attrs","tag","opts","inject","injectKnown","merged","SVG_NS","TAG_NAMESPACE_MAP","k","v","escapeHTML","buildRawAttrs","renderToString","vnode","c","attrsObj","attrsString","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","registry","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","_streamingCollector","_streamingCounter","beginStreamingCollection","collector","endStreamingCollection","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","lightDOM","hydrateStrategy","hydrateAttr","shadowVNode","asyncPromise","runComponentSSRRender","devWarn","id","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","asyncEntries","err","entry","resolvedVNodes","shadowContent"],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AAClE;AA+BO,SAASe,EACdxD,GACAyC,GACwB;AACxB,SAAO,IAAI,eAAuB;AAAA,IAChC,MAAM,MAAMgB,GAAY;AACtB,YAAMC,IAAmC,CAAA;AACzC,MAAAvC,EAAyBuC,CAAY;AAErC,UAAI;AACF,cAAM,EAAE,gBAAAL,EAAA,IAAmBb,EAAyBxC,GAAOyC,CAAO;AAClE,QAAAgB,EAAW,QAAQJ,CAAc;AAAA,MACnC,SAASM,GAAK;AACZ,QAAAF,EAAW,MAAME,CAAG;AACpB;AAAA,MACF,UAAA;AACE,QAAAtC,EAAA;AAAA,MACF;AAIA,iBAAWuC,KAASF;AAClB,YAAI;AACF,gBAAMG,IAAiB,MAAMD,EAAM,SAC7BlD,IAAa,MAAM,QAAQmD,CAAc,IAC1CA,EAA2B,IAAI,CAAC1B,MAAMb,EAAYa,GAAGyB,EAAM,IAAI,CAAC,EAAE,KAAK,EAAE,IAC1EtC,EAAYuC,GAAyBD,EAAM,IAAI,GAE7CE,IAAgB,GADHtD,EAAsBoD,EAAM,aAAalD,CAAU,CACnC,GAAGA,CAAU;AAChD,UAAA+C,EAAW;AAAA,YACT,qDACmC,KAAK,UAAUG,EAAM,EAAE,CAAC,4HAMrC,KAAK,UAAUE,CAAa,CAAC;AAAA,UAAA;AAAA,QAIvD,QAAQ;AAAA,QAER;AAGF,MAAAL,EAAW,MAAA;AAAA,IACb;AAAA,EAAA,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.ssr.es.js","sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"names":["VOID_ELEMENTS","buildAttrs","attrs","tag","opts","inject","injectKnown","merged","SVG_NS","TAG_NAMESPACE_MAP","k","v","escapeHTML","buildRawAttrs","renderToString","vnode","c","attrsObj","attrsString","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","registry","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","_streamingCollector","_streamingCounter","beginStreamingCollection","collector","endStreamingCollection","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","lightDOM","hydrateStrategy","hydrateAttr","shadowVNode","asyncPromise","runComponentSSRRender","devWarn","id","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","asyncEntries","err","entry","resolvedVNodes","shadowContent"],"mappings":";;;;;;AAcO,MAAMA,wBAAoB,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAASC,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,IAASD,EAAK,sBAAsB,IACpCE,IAAcF,EAAK,yBAAyBC,GAC5C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