@jasonshimmy/vite-plugin-cer-app 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.github/copilot-instructions.md +2 -0
  2. package/CHANGELOG.md +8 -0
  3. package/commits.txt +1 -1
  4. package/dist/cli/create/index.js +22 -7
  5. package/dist/cli/create/index.js.map +1 -1
  6. package/dist/cli/create/templates/{ssr → shared}/app/pages/index.ts.tpl +1 -1
  7. package/dist/cli/create/templates/ssg/cer.config.ts.tpl +0 -3
  8. package/dist/cli/create/templates/ssr/cer.config.ts.tpl +0 -3
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/plugin/build-ssr.d.ts.map +1 -1
  12. package/dist/plugin/build-ssr.js +4 -211
  13. package/dist/plugin/build-ssr.js.map +1 -1
  14. package/dist/plugin/dev-server.d.ts +0 -3
  15. package/dist/plugin/dev-server.d.ts.map +1 -1
  16. package/dist/plugin/dev-server.js.map +1 -1
  17. package/dist/plugin/index.d.ts.map +1 -1
  18. package/dist/plugin/index.js +1 -6
  19. package/dist/plugin/index.js.map +1 -1
  20. package/dist/runtime/entry-server-template.d.ts +10 -4
  21. package/dist/runtime/entry-server-template.d.ts.map +1 -1
  22. package/dist/runtime/entry-server-template.js +54 -64
  23. package/dist/runtime/entry-server-template.js.map +1 -1
  24. package/dist/types/config.d.ts +0 -4
  25. package/dist/types/config.d.ts.map +1 -1
  26. package/dist/types/config.js.map +1 -1
  27. package/dist/types/index.d.ts +1 -1
  28. package/dist/types/index.d.ts.map +1 -1
  29. package/docs/cli.md +1 -1
  30. package/docs/configuration.md +0 -25
  31. package/docs/rendering-modes.md +0 -6
  32. package/e2e/kitchen-sink/cer.config.ts +0 -1
  33. package/package.json +1 -1
  34. package/src/__tests__/plugin/build-ssg-render.test.ts +0 -1
  35. package/src/__tests__/plugin/build-ssg.test.ts +0 -1
  36. package/src/__tests__/plugin/build-ssr.test.ts +3 -121
  37. package/src/__tests__/plugin/dev-server.test.ts +0 -1
  38. package/src/__tests__/plugin/entry-server-template.test.ts +106 -3
  39. package/src/__tests__/plugin/resolve-config.test.ts +0 -10
  40. package/src/__tests__/types/config.test.ts +0 -5
  41. package/src/cli/create/index.ts +21 -7
  42. package/src/cli/create/templates/{spa → shared}/app/pages/index.ts.tpl +1 -1
  43. package/src/cli/create/templates/ssg/cer.config.ts.tpl +0 -3
  44. package/src/cli/create/templates/ssr/cer.config.ts.tpl +0 -3
  45. package/src/index.ts +1 -1
  46. package/src/plugin/build-ssr.ts +4 -211
  47. package/src/plugin/dev-server.ts +0 -1
  48. package/src/plugin/index.ts +1 -6
  49. package/src/runtime/entry-server-template.ts +54 -64
  50. package/src/types/config.ts +0 -5
  51. package/src/types/index.ts +1 -1
  52. package/dist/cli/create/templates/spa/app/pages/index.ts.tpl +0 -8
  53. package/dist/cli/create/templates/ssg/app/pages/index.ts.tpl +0 -8
  54. package/dist/cli/create/templates/ssr/.gitignore.tpl +0 -25
  55. package/dist/cli/create/templates/ssr/app/layouts/default.ts.tpl +0 -15
  56. package/dist/cli/create/templates/ssr/index.html.tpl +0 -12
  57. package/dist/cli/create/templates/ssr/tsconfig.json.tpl +0 -3
  58. package/src/cli/create/templates/spa/.gitignore.tpl +0 -25
  59. package/src/cli/create/templates/spa/app/layouts/default.ts.tpl +0 -15
  60. package/src/cli/create/templates/spa/index.html.tpl +0 -12
  61. package/src/cli/create/templates/spa/tsconfig.json.tpl +0 -3
  62. package/src/cli/create/templates/ssg/.gitignore.tpl +0 -25
  63. package/src/cli/create/templates/ssg/app/layouts/default.ts.tpl +0 -15
  64. package/src/cli/create/templates/ssg/app/pages/index.ts.tpl +0 -8
  65. package/src/cli/create/templates/ssg/index.html.tpl +0 -12
  66. package/src/cli/create/templates/ssg/tsconfig.json.tpl +0 -3
  67. package/src/cli/create/templates/ssr/.gitignore.tpl +0 -25
  68. package/src/cli/create/templates/ssr/app/layouts/default.ts.tpl +0 -15
  69. package/src/cli/create/templates/ssr/app/pages/index.ts.tpl +0 -8
  70. package/src/cli/create/templates/ssr/index.html.tpl +0 -12
  71. package/src/cli/create/templates/ssr/tsconfig.json.tpl +0 -3
  72. /package/dist/cli/create/templates/{spa → shared}/.gitignore.tpl +0 -0
  73. /package/dist/cli/create/templates/{spa → shared}/app/layouts/default.ts.tpl +0 -0
  74. /package/dist/cli/create/templates/{spa → shared}/index.html.tpl +0 -0
  75. /package/dist/cli/create/templates/{spa → shared}/tsconfig.json.tpl +0 -0
  76. /package/{dist/cli/create/templates/ssg → src/cli/create/templates/shared}/.gitignore.tpl +0 -0
  77. /package/{dist/cli/create/templates/ssg → src/cli/create/templates/shared}/app/layouts/default.ts.tpl +0 -0
  78. /package/{dist/cli/create/templates/ssg → src/cli/create/templates/shared}/index.html.tpl +0 -0
  79. /package/{dist/cli/create/templates/ssg → src/cli/create/templates/shared}/tsconfig.json.tpl +0 -0
@@ -1,9 +1,15 @@
1
1
  /**
2
2
  * Template string for `entry-server.ts`.
3
3
  *
4
- * This is the Node.js SSR entry point. It imports all virtual modules,
5
- * wires up the routing, and exports a handler compatible with
6
- * Express/Fastify/Node http.
4
+ * This is the Node.js SSR entry point used for both development and production
5
+ * builds. It imports all virtual modules, wires up the routing, and exports a
6
+ * request handler compatible with Express/Fastify/Node http.
7
+ *
8
+ * Key features:
9
+ * - AsyncLocalStorage for race-condition-free concurrent renders (SSG concurrency > 1)
10
+ * - Declarative Shadow DOM via renderToStringWithJITCSSDSD (always on)
11
+ * - useHead() support via beginHeadCollection / endHeadCollection
12
+ * - DSD polyfill injected at end of <body> after client-template merge
7
13
  */
8
- export declare const ENTRY_SERVER_TEMPLATE = "// Server-side entry \u2014 AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport 'virtual:cer-components'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport apiRoutes from 'virtual:cer-server-api'\nimport { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'\nimport entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { createSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware'\n\nregisterBuiltinComponents()\n\n// Pre-load the full HTML entity map so named entities like &mdash; decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (&lt;, &gt;, &amp; \u2026) and re-escapes everything else.\nregisterEntityMap(entitiesJson)\n\n// Run plugins once at server startup so their provide() values are available\n// to useInject() during every SSR render pass. Stored on globalThis so all\n// dynamically-imported page chunks share the same reference (same pattern as\n// __CER_HEAD_COLLECTOR__ and __CER_DATA_STORE__).\nconst _pluginProvides = new Map()\n;(globalThis).__cerPluginProvides = _pluginProvides\nconst _pluginsReady = (async () => {\n const _bootstrapRouter = initRouter({ routes })\n for (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router: _bootstrapRouter,\n provide: (key, value) => _pluginProvides.set(key, value),\n config: {},\n })\n }\n }\n})()\n\n// Async-local storage for request-scoped SSR loader data.\n// Using AsyncLocalStorage ensures concurrent SSR renders (e.g. SSG with\n// concurrency > 1) never see each other's data \u2014 each request's async chain\n// carries its own store value, so usePageData() is always race-condition-free.\nconst _cerDataStore = new AsyncLocalStorage()\n// Expose the store so the usePageData() composable can read it server-side.\n;(globalThis).__CER_DATA_STORE__ = _cerDataStore\n\n// Load the Vite-built client index.html (dist/client/index.html) so every SSR\n// response includes the client-side scripts needed for hydration and routing.\n// The server bundle lives at dist/server/server.js, so ../client resolves correctly.\nconst _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\nconst _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n\n// Merge the SSR handler's full HTML document with the Vite client shell so the\n// final page contains both pre-rendered DSD content and the client bundle scripts.\nfunction _mergeWithClientTemplate(ssrHtml, clientTemplate) {\n const headTag = '<head>', headCloseTag = '</head>'\n const bodyTag = '<body>', bodyCloseTag = '</body>'\n const headStart = ssrHtml.indexOf(headTag)\n const headEnd = ssrHtml.indexOf(headCloseTag)\n const bodyStart = ssrHtml.indexOf(bodyTag)\n const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)\n const ssrHead = headStart >= 0 && headEnd > headStart\n ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''\n const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart\n ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml\n // Hoist only top-level <style id=...> elements (cer-ssr-jit, cer-ssr-global)\n // from the SSR body into the document <head>. Plain <style> blocks without\n // an id attribute belong to shadow DOM templates and must stay in place \u2014\n // hoisting them to <head> breaks shadow DOM style encapsulation (document\n // styles do not pierce shadow roots), which is the root cause of FOUC.\n const headParts = ssrHead ? [ssrHead] : []\n let ssrBodyContent = ssrBody\n let pos = 0\n while (pos < ssrBodyContent.length) {\n const styleOpen = ssrBodyContent.indexOf('<style id=', pos)\n if (styleOpen < 0) break\n const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)\n if (styleClose < 0) break\n headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))\n ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)\n pos = styleOpen\n }\n ssrBodyContent = ssrBodyContent.trim()\n // Inject the pre-rendered layout+page as light DOM of the app mount element\n // so it is visible before JS boots, then the client router takes over.\n let merged = clientTemplate\n if (merged.includes('<cer-layout-view></cer-layout-view>')) {\n merged = merged.replace('<cer-layout-view></cer-layout-view>',\n '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')\n } else if (merged.includes('<div id=\"app\"></div>')) {\n merged = merged.replace('<div id=\"app\"></div>',\n '<div id=\"app\">' + ssrBodyContent + '</div>')\n }\n const headAdditions = headParts.filter(Boolean).join('\\n')\n if (headAdditions) {\n // If SSR provides a <title>, replace the client template's <title> so the\n // SSR title wins (client template title is the fallback default).\n if (headAdditions.includes('<title>')) {\n merged = merged.replace(/<title>[^<]*<\\/title>/, '')\n }\n merged = merged.replace('</head>', headAdditions + '\\n</head>')\n }\n return merged\n}\n\n/**\n * Per-request VNode factory \u2014 initializes a fresh router at the request URL,\n * resolves the active layout from the matched route's meta, pre-loads the\n * matched page component (bypassing the async router-view so DSD renders\n * synchronously), calls the route's data loader (if any), and injects the\n * serialized result into the document head as window.__CER_DATA__ for\n * client-side hydration.\n *\n * createStreamingSSRHandler threads the router through each component's SSR\n * context so concurrent renders never share state.\n */\nconst vnodeFactory = async (req) => {\n await _pluginsReady\n const router = initRouter({ routes, initialUrl: req.url ?? '/' })\n const current = router.getCurrent()\n const { route, params } = router.matchRoute(current.path)\n const layoutName = route?.meta?.layout ?? 'default'\n const layoutTag = layouts[layoutName]\n\n // Pre-load the page module so we can embed the component tag directly.\n // This avoids the async router-view (which injects content via script tags\n // and breaks Declarative Shadow DOM on initial parse).\n let pageVnode = { tag: 'div', props: {}, children: [] }\n let head\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n if (pageTag) {\n pageVnode = { tag: pageTag, props: { attrs: { ...params } }, children: [] }\n }\n if (typeof mod.loader === 'function') {\n const query = current.query ?? {}\n const data = await mod.loader({ params, query, req })\n if (data !== undefined && data !== null) {\n // Make data available to usePageData() during the SSR render pass.\n // enterWith() scopes the value to the current async context so\n // concurrent renders (SSG concurrency > 1) never share data.\n _cerDataStore.enterWith(data)\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n }\n }\n } catch {\n // Non-fatal: loader errors fall back to an empty page; client will refetch.\n }\n }\n\n const vnode = layoutTag\n ? { tag: layoutTag, props: {}, children: [pageVnode] }\n : pageVnode\n\n return { vnode, router, head }\n}\n\n// Capture the raw SSR handler and wrap it to merge the response with the\n// Vite client template before sending \u2014 this injects the JS/CSS asset bundles\n// so the browser can hydrate and enable client-side routing.\nconst _rawHandler = createSSRHandler(vnodeFactory, {\n render: { dsd: true, dsdPolyfill: false },\n})\n\n/**\n * The main request handler.\n * Compatible with Express, Fastify, and Node's raw http.createServer.\n *\n * Each request is run inside a fresh _cerDataStore.run() context so that\n * concurrent renders (e.g. SSG with concurrency > 1) get isolated stores.\n * vnodeFactory calls _cerDataStore.enterWith(loaderData) from within this\n * context, making the data visible to usePageData() during SSR rendering\n * without any global-state races.\n */\nexport const handler = async (req, res) => {\n if (!_clientTemplate) {\n // No client template \u2014 run handler normally, then inject DSD polyfill.\n let _html = ''\n await _cerDataStore.run(null, async () => {\n await _rawHandler(req, { setHeader: () => {}, end: (body) => { _html = body } })\n })\n // Inject DSD polyfill at end of <body>, outside any custom element light DOM.\n const _final = _html.includes('</body>')\n ? _html.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')\n : _html + DSD_POLYFILL_SCRIPT\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n return res.end(_final)\n }\n let _capturedHtml = ''\n // Wrap _rawHandler in an isolated async-local-storage context so that\n // vnodeFactory's enterWith() call is scoped to this request only.\n await _cerDataStore.run(null, async () => {\n // Omit write() to force the non-streaming collect-then-end code path.\n await _rawHandler(req, { setHeader: () => {}, end: (body) => { _capturedHtml = body } })\n })\n let _merged = _mergeWithClientTemplate(_capturedHtml, _clientTemplate)\n // Inject DSD polyfill at end of <body>, outside <cer-layout-view> light DOM.\n _merged = _merged.includes('</body>')\n ? _merged.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')\n : _merged + DSD_POLYFILL_SCRIPT\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end(_merged)\n}\n\nexport { apiRoutes, plugins, layouts, routes }\nexport default handler\n";
14
+ export declare const ENTRY_SERVER_TEMPLATE = "// Server-side entry \u2014 AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport 'virtual:cer-components'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport apiRoutes from 'virtual:cer-server-api'\nimport { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, renderToStringWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'\nimport entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { beginHeadCollection, endHeadCollection, serializeHeadTags } from '@jasonshimmy/vite-plugin-cer-app/composables'\n\nregisterBuiltinComponents()\n\n// Pre-load the full HTML entity map so named entities like &mdash; decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (&lt;, &gt;, &amp; \u2026) and re-escapes everything else.\nregisterEntityMap(entitiesJson)\n\n// Run plugins once at server startup so their provide() values are available\n// to useInject() during every SSR/SSG render pass. Stored on globalThis so all\n// dynamically-imported page chunks share the same reference.\nconst _pluginProvides = new Map()\n;(globalThis).__cerPluginProvides = _pluginProvides\nconst _pluginsReady = (async () => {\n const _bootstrapRouter = initRouter({ routes })\n for (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router: _bootstrapRouter,\n provide: (key, value) => _pluginProvides.set(key, value),\n config: {},\n })\n }\n }\n})()\n\n// Async-local storage for request-scoped SSR loader data.\n// Using AsyncLocalStorage ensures concurrent SSR renders (e.g. SSG with\n// concurrency > 1) never see each other's data \u2014 each request's async chain\n// carries its own store value, so usePageData() is always race-condition-free.\nconst _cerDataStore = new AsyncLocalStorage()\n// Expose the store so the usePageData() composable can read it server-side.\n;(globalThis).__CER_DATA_STORE__ = _cerDataStore\n\n// Load the Vite-built client index.html (dist/client/index.html) so every SSR\n// response includes the client-side scripts needed for hydration and routing.\n// The server bundle lives at dist/server/server.js, so ../client resolves correctly.\nconst _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\nconst _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n\n// Merge the SSR rendered body with the Vite client shell so the final page\n// contains both pre-rendered DSD content and the client bundle scripts.\nfunction _mergeWithClientTemplate(ssrHtml, clientTemplate) {\n const headTag = '<head>', headCloseTag = '</head>'\n const bodyTag = '<body>', bodyCloseTag = '</body>'\n const headStart = ssrHtml.indexOf(headTag)\n const headEnd = ssrHtml.indexOf(headCloseTag)\n const bodyStart = ssrHtml.indexOf(bodyTag)\n const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)\n const ssrHead = headStart >= 0 && headEnd > headStart\n ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''\n const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart\n ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml\n // Hoist only top-level <style id=...> elements (cer-ssr-jit, cer-ssr-global)\n // from the SSR body into the document <head>. Plain <style> blocks without\n // an id attribute belong to shadow DOM templates and must stay in place \u2014\n // hoisting them to <head> breaks shadow DOM style encapsulation (document\n // styles do not pierce shadow roots), which is the root cause of FOUC.\n const headParts = ssrHead ? [ssrHead] : []\n let ssrBodyContent = ssrBody\n let pos = 0\n while (pos < ssrBodyContent.length) {\n const styleOpen = ssrBodyContent.indexOf('<style id=', pos)\n if (styleOpen < 0) break\n const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)\n if (styleClose < 0) break\n headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))\n ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)\n pos = styleOpen\n }\n ssrBodyContent = ssrBodyContent.trim()\n // Inject the pre-rendered layout+page as light DOM of the app mount element\n // so it is visible before JS boots, then the client router takes over.\n let merged = clientTemplate\n if (merged.includes('<cer-layout-view></cer-layout-view>')) {\n merged = merged.replace('<cer-layout-view></cer-layout-view>',\n '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')\n } else if (merged.includes('<div id=\"app\"></div>')) {\n merged = merged.replace('<div id=\"app\"></div>',\n '<div id=\"app\">' + ssrBodyContent + '</div>')\n }\n const headAdditions = headParts.filter(Boolean).join('\\n')\n if (headAdditions) {\n // If SSR provides a <title>, replace the client template's <title> so the\n // SSR title wins (client template title is the fallback default).\n if (headAdditions.includes('<title>')) {\n merged = merged.replace(/<title>[^<]*<\\/title>/, '')\n }\n merged = merged.replace('</head>', headAdditions + '\\n</head>')\n }\n return merged\n}\n\n// Per-request async setup: initialize a fresh router, resolve the matched\n// route and layout, pre-load the page module, and call the data loader.\n// Loader data is scoped to the current AsyncLocalStorage context via enterWith()\n// so concurrent renders never share state.\nconst _prepareRequest = async (req) => {\n await _pluginsReady\n const router = initRouter({ routes, initialUrl: req.url ?? '/' })\n const current = router.getCurrent()\n const { route, params } = router.matchRoute(current.path)\n const layoutName = route?.meta?.layout ?? 'default'\n const layoutTag = layouts[layoutName]\n\n // Pre-load the page module so we can embed the component tag directly.\n // This avoids the async router-view (which injects content via script tags\n // and breaks Declarative Shadow DOM on initial parse).\n let pageVnode = { tag: 'div', props: {}, children: [] }\n let head\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n if (pageTag) {\n pageVnode = { tag: pageTag, props: { attrs: { ...params } }, children: [] }\n }\n if (typeof mod.loader === 'function') {\n const query = current.query ?? {}\n const data = await mod.loader({ params, query, req })\n if (data !== undefined && data !== null) {\n // enterWith() scopes the value to the current async context so\n // concurrent renders (SSG concurrency > 1) never share data.\n _cerDataStore.enterWith(data)\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n }\n }\n } catch {\n // Non-fatal: loader errors fall back to an empty page; client will refetch.\n }\n }\n\n const vnode = layoutTag\n ? { tag: layoutTag, props: {}, children: [pageVnode] }\n : pageVnode\n\n return { vnode, router, head }\n}\n\nexport const handler = async (req, res) => {\n await _cerDataStore.run(null, async () => {\n const { vnode, router, head } = await _prepareRequest(req)\n\n // Begin collecting useHead() calls made during the synchronous render pass.\n beginHeadCollection()\n\n // dsdPolyfill: false \u2014 we inject the polyfill manually after merging so it\n // lands at the end of <body>, not inside <cer-layout-view> light DOM where\n // scripts may not execute.\n const { htmlWithStyles } = renderToStringWithJITCSSDSD(vnode, {\n dsdPolyfill: false,\n router,\n })\n\n // Collect and serialize any useHead() calls from the rendered components.\n const headTags = serializeHeadTags(endHeadCollection())\n\n // Merge loader data script + useHead() tags into the document head.\n const headContent = [head, headTags].filter(Boolean).join('\\n')\n\n // Wrap the rendered body in a full HTML document and inject the head additions\n // (loader data script, useHead() tags, JIT styles). No polyfill in body yet.\n const ssrHtml = `<!DOCTYPE html><html><head>${headContent}</head><body>${htmlWithStyles}</body></html>`\n\n let finalHtml = _clientTemplate\n ? _mergeWithClientTemplate(ssrHtml, _clientTemplate)\n : ssrHtml\n\n // Inject DSD polyfill at end of <body>, outside <cer-layout-view>, so the\n // browser runs it after parsing the declarative shadow roots.\n finalHtml = finalHtml.includes('</body>')\n ? finalHtml.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')\n : finalHtml + DSD_POLYFILL_SCRIPT\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end(finalHtml)\n })\n}\n\nexport { apiRoutes, plugins, layouts, routes }\nexport default handler\n";
9
15
  //# sourceMappingURL=entry-server-template.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry-server-template.d.ts","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,m6TAsNjC,CAAA"}
1
+ {"version":3,"file":"entry-server-template.d.ts","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,giSAsMjC,CAAA"}
@@ -1,9 +1,15 @@
1
1
  /**
2
2
  * Template string for `entry-server.ts`.
3
3
  *
4
- * This is the Node.js SSR entry point. It imports all virtual modules,
5
- * wires up the routing, and exports a handler compatible with
6
- * Express/Fastify/Node http.
4
+ * This is the Node.js SSR entry point used for both development and production
5
+ * builds. It imports all virtual modules, wires up the routing, and exports a
6
+ * request handler compatible with Express/Fastify/Node http.
7
+ *
8
+ * Key features:
9
+ * - AsyncLocalStorage for race-condition-free concurrent renders (SSG concurrency > 1)
10
+ * - Declarative Shadow DOM via renderToStringWithJITCSSDSD (always on)
11
+ * - useHead() support via beginHeadCollection / endHeadCollection
12
+ * - DSD polyfill injected at end of <body> after client-template merge
7
13
  */
8
14
  export const ENTRY_SERVER_TEMPLATE = `// Server-side entry — AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app
9
15
  import { readFileSync, existsSync } from 'node:fs'
@@ -16,10 +22,10 @@ import layouts from 'virtual:cer-layouts'
16
22
  import plugins from 'virtual:cer-plugins'
17
23
  import apiRoutes from 'virtual:cer-server-api'
18
24
  import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
19
- import { registerEntityMap, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
25
+ import { registerEntityMap, renderToStringWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
20
26
  import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
21
27
  import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
22
- import { createSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware'
28
+ import { beginHeadCollection, endHeadCollection, serializeHeadTags } from '@jasonshimmy/vite-plugin-cer-app/composables'
23
29
 
24
30
  registerBuiltinComponents()
25
31
 
@@ -29,9 +35,8 @@ registerBuiltinComponents()
29
35
  registerEntityMap(entitiesJson)
30
36
 
31
37
  // Run plugins once at server startup so their provide() values are available
32
- // to useInject() during every SSR render pass. Stored on globalThis so all
33
- // dynamically-imported page chunks share the same reference (same pattern as
34
- // __CER_HEAD_COLLECTOR__ and __CER_DATA_STORE__).
38
+ // to useInject() during every SSR/SSG render pass. Stored on globalThis so all
39
+ // dynamically-imported page chunks share the same reference.
35
40
  const _pluginProvides = new Map()
36
41
  ;(globalThis).__cerPluginProvides = _pluginProvides
37
42
  const _pluginsReady = (async () => {
@@ -63,8 +68,8 @@ const _clientTemplate = existsSync(_clientTemplatePath)
63
68
  ? readFileSync(_clientTemplatePath, 'utf-8')
64
69
  : null
65
70
 
66
- // Merge the SSR handler's full HTML document with the Vite client shell so the
67
- // final page contains both pre-rendered DSD content and the client bundle scripts.
71
+ // Merge the SSR rendered body with the Vite client shell so the final page
72
+ // contains both pre-rendered DSD content and the client bundle scripts.
68
73
  function _mergeWithClientTemplate(ssrHtml, clientTemplate) {
69
74
  const headTag = '<head>', headCloseTag = '</head>'
70
75
  const bodyTag = '<body>', bodyCloseTag = '</body>'
@@ -116,18 +121,11 @@ function _mergeWithClientTemplate(ssrHtml, clientTemplate) {
116
121
  return merged
117
122
  }
118
123
 
119
- /**
120
- * Per-request VNode factory initializes a fresh router at the request URL,
121
- * resolves the active layout from the matched route's meta, pre-loads the
122
- * matched page component (bypassing the async router-view so DSD renders
123
- * synchronously), calls the route's data loader (if any), and injects the
124
- * serialized result into the document head as window.__CER_DATA__ for
125
- * client-side hydration.
126
- *
127
- * createStreamingSSRHandler threads the router through each component's SSR
128
- * context so concurrent renders never share state.
129
- */
130
- const vnodeFactory = async (req) => {
124
+ // Per-request async setup: initialize a fresh router, resolve the matched
125
+ // route and layout, pre-load the page module, and call the data loader.
126
+ // Loader data is scoped to the current AsyncLocalStorage context via enterWith()
127
+ // so concurrent renders never share state.
128
+ const _prepareRequest = async (req) => {
131
129
  await _pluginsReady
132
130
  const router = initRouter({ routes, initialUrl: req.url ?? '/' })
133
131
  const current = router.getCurrent()
@@ -151,7 +149,6 @@ const vnodeFactory = async (req) => {
151
149
  const query = current.query ?? {}
152
150
  const data = await mod.loader({ params, query, req })
153
151
  if (data !== undefined && data !== null) {
154
- // Make data available to usePageData() during the SSR render pass.
155
152
  // enterWith() scopes the value to the current async context so
156
153
  // concurrent renders (SSG concurrency > 1) never share data.
157
154
  _cerDataStore.enterWith(data)
@@ -170,51 +167,44 @@ const vnodeFactory = async (req) => {
170
167
  return { vnode, router, head }
171
168
  }
172
169
 
173
- // Capture the raw SSR handler and wrap it to merge the response with the
174
- // Vite client template before sending — this injects the JS/CSS asset bundles
175
- // so the browser can hydrate and enable client-side routing.
176
- const _rawHandler = createSSRHandler(vnodeFactory, {
177
- render: { dsd: true, dsdPolyfill: false },
178
- })
179
-
180
- /**
181
- * The main request handler.
182
- * Compatible with Express, Fastify, and Node's raw http.createServer.
183
- *
184
- * Each request is run inside a fresh _cerDataStore.run() context so that
185
- * concurrent renders (e.g. SSG with concurrency > 1) get isolated stores.
186
- * vnodeFactory calls _cerDataStore.enterWith(loaderData) from within this
187
- * context, making the data visible to usePageData() during SSR rendering
188
- * without any global-state races.
189
- */
190
170
  export const handler = async (req, res) => {
191
- if (!_clientTemplate) {
192
- // No client template run handler normally, then inject DSD polyfill.
193
- let _html = ''
194
- await _cerDataStore.run(null, async () => {
195
- await _rawHandler(req, { setHeader: () => {}, end: (body) => { _html = body } })
171
+ await _cerDataStore.run(null, async () => {
172
+ const { vnode, router, head } = await _prepareRequest(req)
173
+
174
+ // Begin collecting useHead() calls made during the synchronous render pass.
175
+ beginHeadCollection()
176
+
177
+ // dsdPolyfill: false — we inject the polyfill manually after merging so it
178
+ // lands at the end of <body>, not inside <cer-layout-view> light DOM where
179
+ // scripts may not execute.
180
+ const { htmlWithStyles } = renderToStringWithJITCSSDSD(vnode, {
181
+ dsdPolyfill: false,
182
+ router,
196
183
  })
197
- // Inject DSD polyfill at end of <body>, outside any custom element light DOM.
198
- const _final = _html.includes('</body>')
199
- ? _html.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
200
- : _html + DSD_POLYFILL_SCRIPT
184
+
185
+ // Collect and serialize any useHead() calls from the rendered components.
186
+ const headTags = serializeHeadTags(endHeadCollection())
187
+
188
+ // Merge loader data script + useHead() tags into the document head.
189
+ const headContent = [head, headTags].filter(Boolean).join('\\n')
190
+
191
+ // Wrap the rendered body in a full HTML document and inject the head additions
192
+ // (loader data script, useHead() tags, JIT styles). No polyfill in body yet.
193
+ const ssrHtml = \`<!DOCTYPE html><html><head>\${headContent}</head><body>\${htmlWithStyles}</body></html>\`
194
+
195
+ let finalHtml = _clientTemplate
196
+ ? _mergeWithClientTemplate(ssrHtml, _clientTemplate)
197
+ : ssrHtml
198
+
199
+ // Inject DSD polyfill at end of <body>, outside <cer-layout-view>, so the
200
+ // browser runs it after parsing the declarative shadow roots.
201
+ finalHtml = finalHtml.includes('</body>')
202
+ ? finalHtml.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
203
+ : finalHtml + DSD_POLYFILL_SCRIPT
204
+
201
205
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
202
- return res.end(_final)
203
- }
204
- let _capturedHtml = ''
205
- // Wrap _rawHandler in an isolated async-local-storage context so that
206
- // vnodeFactory's enterWith() call is scoped to this request only.
207
- await _cerDataStore.run(null, async () => {
208
- // Omit write() to force the non-streaming collect-then-end code path.
209
- await _rawHandler(req, { setHeader: () => {}, end: (body) => { _capturedHtml = body } })
206
+ res.end(finalHtml)
210
207
  })
211
- let _merged = _mergeWithClientTemplate(_capturedHtml, _clientTemplate)
212
- // Inject DSD polyfill at end of <body>, outside <cer-layout-view> light DOM.
213
- _merged = _merged.includes('</body>')
214
- ? _merged.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
215
- : _merged + DSD_POLYFILL_SCRIPT
216
- res.setHeader('Content-Type', 'text/html; charset=utf-8')
217
- res.end(_merged)
218
208
  }
219
209
 
220
210
  export { apiRoutes, plugins, layouts, routes }
@@ -1 +1 @@
1
- {"version":3,"file":"entry-server-template.js","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsNpC,CAAA"}
1
+ {"version":3,"file":"entry-server-template.js","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsMpC,CAAA"}
@@ -8,9 +8,6 @@ export interface JitCssConfig {
8
8
  content?: string[];
9
9
  extendedColors?: boolean;
10
10
  }
11
- export interface SsrConfig {
12
- dsd?: boolean;
13
- }
14
11
  export interface AutoImportsConfig {
15
12
  components?: boolean;
16
13
  composables?: boolean;
@@ -23,7 +20,6 @@ export interface CerAppConfig {
23
20
  ssg?: SsgConfig;
24
21
  router?: Pick<RouterConfig, 'base' | 'scrollToFragment'>;
25
22
  jitCss?: JitCssConfig;
26
- ssr?: SsrConfig;
27
23
  autoImports?: AutoImportsConfig;
28
24
  port?: number;
29
25
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6CAA6C,CAAA;AAE/E,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC1B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB;AAED,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,EAAE,OAAO,CAAA;CACd;AAED,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAA;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,CAAC,EAAE,SAAS,CAAA;IACf,MAAM,CAAC,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,kBAAkB,CAAC,CAAA;IACxD,MAAM,CAAC,EAAE,YAAY,CAAA;IACrB,GAAG,CAAC,EAAE,SAAS,CAAA;IACf,WAAW,CAAC,EAAE,iBAAiB,CAAA;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,YAAY,CAE/D"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6CAA6C,CAAA;AAE/E,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC1B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB;AAED,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAA;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,CAAC,EAAE,SAAS,CAAA;IACf,MAAM,CAAC,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,kBAAkB,CAAC,CAAA;IACxD,MAAM,CAAC,EAAE,YAAY,CAAA;IACrB,WAAW,CAAC,EAAE,iBAAiB,CAAA;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,YAAY,CAE/D"}
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAmCA,MAAM,UAAU,YAAY,CAAC,MAAoB;IAC/C,OAAO,MAAM,CAAA;AACf,CAAC"}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AA8BA,MAAM,UAAU,YAAY,CAAC,MAAoB;IAC/C,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -1,4 +1,4 @@
1
- export type { CerAppConfig, SsgConfig, JitCssConfig, SsrConfig, AutoImportsConfig } from './config.js';
1
+ export type { CerAppConfig, SsgConfig, JitCssConfig, AutoImportsConfig } from './config.js';
2
2
  export { defineConfig } from './config.js';
3
3
  export type { HydrateStrategy, SsgPathsContext, PageSsgConfig, PageMeta, PageLoaderContext, PageLoader } from './page.js';
4
4
  export type { ApiRequest, ApiResponse, ApiHandler, ApiContext } from './api.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AACtG,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,QAAQ,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AACzH,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAC/E,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACxD,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC3F,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,QAAQ,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AACzH,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAC/E,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACxD,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA"}
package/docs/cli.md CHANGED
@@ -187,7 +187,7 @@ my-app/
187
187
  | Mode | `cer.config.ts` | `package.json` scripts |
188
188
  |---|---|---|
189
189
  | SPA | `mode: 'spa'` | `dev`, `build`, `preview` |
190
- | SSR | `mode: 'ssr'`, `ssr.dsd: true` | `dev`, `build`, `preview --ssr` |
190
+ | SSR | `mode: 'ssr'` | `dev`, `build`, `preview --ssr` |
191
191
  | SSG | `mode: 'ssg'`, `ssg.routes: 'auto'` | `dev`, `build`, `preview`, `generate` |
192
192
 
193
193
  ---
@@ -11,10 +11,6 @@ export default defineConfig({
11
11
  srcDir: 'app',
12
12
  port: 3000,
13
13
 
14
- ssr: {
15
- dsd: true,
16
- },
17
-
18
14
  ssg: {
19
15
  routes: 'auto',
20
16
  concurrency: 4,
@@ -80,25 +76,6 @@ Dev server port. Overridden by the `--port` CLI flag.
80
76
 
81
77
  ---
82
78
 
83
- ## `ssr` options
84
-
85
- Controls SSR rendering behavior.
86
-
87
- ```ts
88
- ssr: {
89
- dsd: true, // Emit Declarative Shadow DOM
90
- }
91
- ```
92
-
93
- ### `ssr.dsd`
94
-
95
- **Type:** `boolean`
96
- **Default:** `true`
97
-
98
- When `true`, renders components with [Declarative Shadow DOM](https://developer.chrome.com/docs/css-ui/declarative-shadow-dom) markup. This eliminates Flash of Unstyled Content (FOUC) because styles are embedded directly in the HTML.
99
-
100
- ---
101
-
102
79
  ## `ssg` options
103
80
 
104
81
  Controls static site generation.
@@ -238,7 +215,6 @@ export default defineConfig({
238
215
  plugins: [
239
216
  cerApp({
240
217
  mode: 'ssr',
241
- ssr: { dsd: true },
242
218
  }),
243
219
  ],
244
220
  })
@@ -257,7 +233,6 @@ import type {
257
233
  CerAppConfig,
258
234
  SsgConfig,
259
235
  JitCssConfig,
260
- SsrConfig,
261
236
  AutoImportsConfig,
262
237
  } from '@jasonshimmy/vite-plugin-cer-app/types'
263
238
  ```
@@ -92,9 +92,6 @@ export default handler
92
92
  ```ts
93
93
  export default defineConfig({
94
94
  mode: 'ssr',
95
- ssr: {
96
- dsd: true, // Declarative Shadow DOM (eliminates FOUC)
97
- },
98
95
  })
99
96
  ```
100
97
 
@@ -188,9 +185,6 @@ export default defineConfig({
188
185
  concurrency: 4, // parallel renders
189
186
  fallback: false, // serve 404 for unenumerated routes
190
187
  },
191
- ssr: {
192
- dsd: true, // embed styles in static HTML
193
- },
194
188
  })
195
189
  ```
196
190
 
@@ -1,6 +1,5 @@
1
1
  // Kitchen sink configuration — mode is overridden by --mode CLI flag
2
2
  export default {
3
- ssr: { dsd: true, streaming: false },
4
3
  ssg: { routes: 'auto', concurrency: 2 },
5
4
  autoImports: { runtime: true, components: true, composables: true },
6
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jasonshimmy/vite-plugin-cer-app",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Nuxt-style meta-framework for @jasonshimmy/custom-elements-runtime",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -54,7 +54,6 @@ function makeConfig(overrides: Partial<ResolvedCerConfig> = {}): ResolvedCerConf
54
54
  srcDir: join(tmpRoot, 'app'),
55
55
  pagesDir: join(tmpRoot, 'app', 'pages'),
56
56
  mode: 'ssg',
57
- ssr: { dsd: true },
58
57
  ssg: { routes: ['/'], concurrency: 1 },
59
58
  ...overrides,
60
59
  } as unknown as ResolvedCerConfig
@@ -28,7 +28,6 @@ function makeConfig(overrides: Partial<ResolvedCerConfig> = {}): ResolvedCerConf
28
28
  srcDir: '/project/app',
29
29
  pagesDir: '/project/app/pages',
30
30
  mode: 'ssg',
31
- ssr: { dsd: true },
32
31
  ssg: { concurrency: 4 },
33
32
  ...overrides,
34
33
  } as unknown as ResolvedCerConfig
@@ -1,10 +1,7 @@
1
1
  import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'
2
- import { readFileSync } from 'node:fs'
3
- import { resolve } from 'pathe'
4
2
 
5
- // We test the server entry code generation by importing just that function.
6
- // The `buildSSR` function itself invokes Vite's `build` API which we don't
7
- // need to exercise in unit tests (it's an integration concern).
3
+ // We test the SSR build pipeline by exercising buildSSR and its helpers.
4
+ // Template content is tested in entry-server-template.test.ts.
8
5
  vi.mock('vite', () => ({ build: vi.fn().mockResolvedValue(undefined) }))
9
6
  vi.mock('../../plugin/generated-dir.js', () => ({
10
7
  writeGeneratedDir: vi.fn(),
@@ -20,131 +17,16 @@ vi.mock('node:fs', async (importOriginal) => {
20
17
 
21
18
  import type { ResolvedCerConfig } from '../../plugin/dev-server.js'
22
19
 
23
- // Build a minimal ResolvedCerConfig so we can call generateServerEntryCode
24
- // without spinning up a real Vite build.
25
20
  function makeConfig(overrides: Partial<ResolvedCerConfig> = {}): ResolvedCerConfig {
26
21
  return {
27
22
  root: '/project',
28
23
  srcDir: '/project/app',
29
24
  mode: 'ssr',
30
- ssr: { dsd: true },
31
25
  ssg: { paths: [], concurrency: 4 },
32
26
  ...overrides,
33
27
  } as unknown as ResolvedCerConfig
34
28
  }
35
29
 
36
- describe('build-ssr generateServerEntryCode (template content)', () => {
37
- // Read the source of build-ssr.ts to assert it contains the expected
38
- // generated code strings. This is intentionally coarse-grained:
39
- // we check that the template emits the right imports, exports, and
40
- // structural elements rather than testing every character.
41
- const src = readFileSync(
42
- resolve(import.meta.dirname, '../../plugin/build-ssr.ts'),
43
- 'utf-8',
44
- )
45
-
46
- it('template imports registerBuiltinComponents from custom-elements-runtime', () => {
47
- expect(src).toContain('registerBuiltinComponents')
48
- })
49
-
50
- it('template imports renderToStringWithJITCSS from ssr subpath', () => {
51
- expect(src).toContain('renderToStringWithJITCSS')
52
- expect(src).toContain('custom-elements-runtime/ssr')
53
- })
54
-
55
- it('template imports initRouter from router subpath', () => {
56
- expect(src).toContain('initRouter')
57
- expect(src).toContain('custom-elements-runtime/router')
58
- })
59
-
60
- it('template loads client index.html for merging', () => {
61
- expect(src).toContain('_clientTemplate')
62
- expect(src).toContain('../client/index.html')
63
- })
64
-
65
- it('template defines _mergeWithClientTemplate helper', () => {
66
- expect(src).toContain('_mergeWithClientTemplate')
67
- })
68
-
69
- it('template defines _prepareRequest async function', () => {
70
- expect(src).toContain('_prepareRequest')
71
- })
72
-
73
- it('template exports handler as both named and default export', () => {
74
- expect(src).toContain('export const handler')
75
- expect(src).toContain('export default handler')
76
- })
77
-
78
- it('template exports apiRoutes, plugins, and layouts', () => {
79
- expect(src).toContain('export { apiRoutes, plugins, layouts }')
80
- })
81
-
82
- it('template sets globalThis.__CER_DATA__ synchronously before render', () => {
83
- expect(src).toContain('globalThis).__CER_DATA__ = loaderData')
84
- })
85
-
86
- it('template deletes __CER_DATA__ after render', () => {
87
- expect(src).toContain('delete (globalThis).__CER_DATA__')
88
- })
89
-
90
- it('template uses renderToStringWithJITCSSDSD (dsd always on)', () => {
91
- expect(src).toContain('renderToStringWithJITCSSDSD')
92
- })
93
-
94
- it('template passes dsdPolyfill: false to suppress inline polyfill', () => {
95
- expect(src).toContain('dsdPolyfill: false')
96
- })
97
-
98
- it('template calls registerEntityMap with entities.json', () => {
99
- expect(src).toContain('registerEntityMap(entitiesJson)')
100
- expect(src).toContain('entities.json')
101
- })
102
-
103
- it('template imports DSD_POLYFILL_SCRIPT and injects before </body>', () => {
104
- expect(src).toContain('DSD_POLYFILL_SCRIPT')
105
- expect(src).toContain("finalHtml.replace('</body>'")
106
- })
107
-
108
- it('template merges SSR html with client template when available', () => {
109
- expect(src).toContain('_clientTemplate')
110
- expect(src).toContain('_mergeWithClientTemplate(ssrHtml, _clientTemplate)')
111
- })
112
-
113
- it('template reads virtual:cer-routes', () => {
114
- expect(src).toContain('virtual:cer-routes')
115
- })
116
-
117
- it('template reads virtual:cer-layouts', () => {
118
- expect(src).toContain('virtual:cer-layouts')
119
- })
120
-
121
- it('template reads virtual:cer-plugins', () => {
122
- expect(src).toContain('virtual:cer-plugins')
123
- })
124
-
125
- it('template reads virtual:cer-server-api', () => {
126
- expect(src).toContain('virtual:cer-server-api')
127
- })
128
-
129
- it('template reads virtual:cer-components', () => {
130
- expect(src).toContain('virtual:cer-components')
131
- })
132
-
133
- it('sets Content-Type header on response', () => {
134
- expect(src).toContain('text/html; charset=utf-8')
135
- })
136
-
137
- it('template initializes plugins and sets globalThis.__cerPluginProvides', () => {
138
- expect(src).toContain('__cerPluginProvides')
139
- expect(src).toContain('_pluginProvides')
140
- expect(src).toContain('_pluginsReady')
141
- })
142
-
143
- it('template awaits _pluginsReady before handling each request', () => {
144
- expect(src).toContain('await _pluginsReady')
145
- })
146
- })
147
-
148
30
  describe('buildSSR', () => {
149
31
  let buildMock: ReturnType<typeof vi.fn>
150
32
  let buildSSR: (config: ResolvedCerConfig, userConfig?: Record<string, unknown>) => Promise<void>
@@ -286,7 +168,7 @@ describe('buildSSR — virtual server-entry plugin', () => {
286
168
  const plugin = await getServerPlugin()
287
169
  const source = plugin.load('\0virtual:cer-server-entry')
288
170
  expect(typeof source).toBe('string')
289
- expect(source).toContain('AUTO-GENERATED server entry')
171
+ expect(source).toContain('AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app')
290
172
  })
291
173
 
292
174
  it('load returns undefined for other ids', async () => {
@@ -48,7 +48,6 @@ function makeConfig(overrides: Partial<ResolvedCerConfig> = {}): ResolvedCerConf
48
48
  serverApiDir: '/project/server/api',
49
49
  serverMiddlewareDir: '/project/server/middleware',
50
50
  port: 3000,
51
- ssr: { dsd: true },
52
51
  ssg: { routes: 'auto', concurrency: 2, fallback: false },
53
52
  router: {},
54
53
  jitCss: { content: [], extendedColors: false },