@jasonshimmy/vite-plugin-cer-app 0.21.2 → 0.21.4

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 (44) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/commits.txt +1 -1
  3. package/dist/cli/create/templates/spa/package.json.tpl +4 -4
  4. package/dist/cli/create/templates/ssg/package.json.tpl +4 -4
  5. package/dist/cli/create/templates/ssr/package.json.tpl +4 -4
  6. package/dist/plugin/dev-server.d.ts +1 -0
  7. package/dist/plugin/dev-server.d.ts.map +1 -1
  8. package/dist/plugin/dev-server.js.map +1 -1
  9. package/dist/plugin/dts-generator.js +7 -7
  10. package/dist/plugin/dts-generator.js.map +1 -1
  11. package/dist/plugin/index.d.ts.map +1 -1
  12. package/dist/plugin/index.js +12 -0
  13. package/dist/plugin/index.js.map +1 -1
  14. package/dist/plugin/virtual/content-components.d.ts +6 -0
  15. package/dist/plugin/virtual/content-components.d.ts.map +1 -0
  16. package/dist/plugin/virtual/content-components.js +70 -0
  17. package/dist/plugin/virtual/content-components.js.map +1 -0
  18. package/dist/runtime/app-template.d.ts +1 -1
  19. package/dist/runtime/app-template.d.ts.map +1 -1
  20. package/dist/runtime/app-template.js +1 -0
  21. package/dist/runtime/app-template.js.map +1 -1
  22. package/dist/runtime/entry-server-template.d.ts +1 -1
  23. package/dist/runtime/entry-server-template.d.ts.map +1 -1
  24. package/dist/runtime/entry-server-template.js +1 -0
  25. package/dist/runtime/entry-server-template.js.map +1 -1
  26. package/docs/configuration.md +1 -1
  27. package/docs/content.md +39 -1
  28. package/e2e/cypress/e2e/content.cy.ts +21 -1
  29. package/e2e/kitchen-sink/content/docs/getting-started.md +2 -0
  30. package/package.json +1 -1
  31. package/src/__tests__/plugin/app-template.test.ts +4 -0
  32. package/src/__tests__/plugin/cer-app-plugin.test.ts +1 -0
  33. package/src/__tests__/plugin/dts-generator.test.ts +2 -2
  34. package/src/__tests__/plugin/entry-server-template.test.ts +4 -0
  35. package/src/__tests__/plugin/virtual/content-components.test.ts +66 -0
  36. package/src/cli/create/templates/spa/package.json.tpl +4 -4
  37. package/src/cli/create/templates/ssg/package.json.tpl +4 -4
  38. package/src/cli/create/templates/ssr/package.json.tpl +4 -4
  39. package/src/plugin/dev-server.ts +1 -0
  40. package/src/plugin/dts-generator.ts +7 -7
  41. package/src/plugin/index.ts +12 -0
  42. package/src/plugin/virtual/content-components.ts +83 -0
  43. package/src/runtime/app-template.ts +1 -0
  44. package/src/runtime/entry-server-template.ts +1 -0
@@ -11,5 +11,5 @@
11
11
  * - useHead() support via beginHeadCollection / endHeadCollection
12
12
  * - DSD polyfill injected at end of <body> after client-template merge
13
13
  */
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 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 serverMiddleware from 'virtual:cer-server-middleware'\nimport { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'\nimport { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, renderToStreamWithJITCSSDSD, 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, initRuntimeConfig, resolvePrivateConfig, useSession } from '@jasonshimmy/vite-plugin-cer-app/composables'\nimport { errorTag } from 'virtual:cer-error'\nimport { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'\n\nconst _cerProcess = (globalThis).process\nconst _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE\nconst _cerRuntimeDev =\n typeof _cerNodeEnv === 'string'\n ? _cerNodeEnv !== 'production'\n : typeof import.meta.env?.DEV === 'boolean'\n ? import.meta.env.DEV\n : typeof import.meta.env?.PROD === 'boolean'\n ? !import.meta.env.PROD\n : typeof import.meta.env?.MODE === 'string'\n ? import.meta.env.MODE !== 'production'\n : false\n;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev\n\nregisterBuiltinComponents()\nsetDevMode(_cerRuntimeDev)\n\n// Resolve private config from environment variables at server startup.\n// Each key declared in runtimeConfig.private is looked up in process.env,\n// first as-is, then as ALL_CAPS. The declared default is used as fallback.\ninitRuntimeConfig({ ...runtimeConfig, private: resolvePrivateConfig(_runtimePrivateDefaults ?? {}) })\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// Async-local storage for request-scoped req/res access.\n// Allows isomorphic composables (e.g. useCookie) to read/write HTTP headers\n// without prop-drilling the request context through the component tree.\nconst _cerReqStore = new AsyncLocalStorage()\n;(globalThis).__CER_REQ_STORE__ = _cerReqStore\n\n// Async-local storage for the authenticated user resolved before each render.\n// useAuth() reads this store server-side to return the current user synchronously.\nconst _cerAuthStore = new AsyncLocalStorage()\n;(globalThis).__CER_AUTH_STORE__ = _cerAuthStore\n\n// Async-local storage for per-request useFetch() data.\n// useFetch() writes fetched results here; the handler serialises the map into\n// window.__CER_FETCH_DATA__ for client-side hydration.\nconst _cerFetchStore = new AsyncLocalStorage()\n;(globalThis).__CER_FETCH_STORE__ = _cerFetchStore\n\n// Async-local storage for the current route info (path, params, query, meta).\n// useRoute() reads this on the server so layouts and components can access\n// route metadata without prop-drilling.\nconst _cerRouteStore = new AsyncLocalStorage()\n;(globalThis).__CER_ROUTE_STORE__ = _cerRouteStore\n\n// Async-local storage for per-request useState() reactive state.\n// Each request gets a fresh Map so concurrent SSR/SSG renders never share\n// reactive state set by different pages or loaders.\nconst _cerStateStore = new AsyncLocalStorage()\n;(globalThis).__CER_STATE_STORE__ = _cerStateStore\n\n// Runs fn inside the per-request AsyncLocalStorage context so that isomorphic\n// composables (useCookie, useSession, etc.) can access req/res without prop-drilling.\n// Call this for every API handler invocation \u2014 not just SSR renders.\nexport function runWithRequestContext(req, res, fn) {\n return _cerReqStore.run({ req, res }, fn)\n}\n\n// Runs the server/middleware/ chain for a request.\n// Returns false if a middleware short-circuited the response; true to continue.\n// Exported so Netlify / Vercel / Cloudflare bridges can also call it for API routes.\n// P1-2: Middleware may throw { status: 401 } (or any numeric .status) to produce\n// a non-500 response \u2014 the status is extracted and forwarded to res.statusCode.\nexport async function runServerMiddleware(req, res) {\n for (const { handler: mw } of (serverMiddleware ?? [])) {\n if (typeof mw !== 'function') continue\n let calledNext = false\n try {\n await new Promise((resolve, reject) => {\n Promise.resolve(mw(req, res, (err) => {\n if (err) reject(err)\n else { calledNext = true; resolve() }\n })).catch(reject)\n })\n } catch (err) {\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'middleware', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n if (!res.writableEnded) {\n const statusCode = (typeof err === 'object' && err !== null && 'status' in err && typeof err.status === 'number')\n ? (isNaN(err.status) ? 500 : err.status)\n : 500\n res.statusCode = statusCode\n res.end('Internal Server Error')\n }\n return false\n }\n if (res.writableEnded || !calledNext) return false\n }\n return true\n}\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.\n//\n// Cloudflare Workers (and other runtimes without node:fs) can inject the\n// template before this module loads by setting globalThis.__CER_CLIENT_TEMPLATE__.\n// The Cloudflare adapter inlines dist/client/index.html as a string constant in\n// _worker.js and sets the global before dynamically importing the server bundle.\nlet _clientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? null\nif (!_clientTemplate) {\n try {\n const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\n _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n } catch {\n // node:fs not available in this runtime \u2014 Cloudflare adapter must set\n // globalThis.__CER_CLIENT_TEMPLATE__ before importing this bundle.\n }\n}\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 returned so the handler can scope it to _cerDataStore.run()\n// during rendering. (AsyncLocalStorage.enterWith() inside an awaited child\n// function does not propagate back to the parent continuation, so run() is\n// the only reliable approach.)\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\n // Store the current route info so useRoute() can read it synchronously\n // from any layout or component during this render pass.\n _cerRouteStore.enterWith({\n path: current.path,\n params,\n query: current.query ?? {},\n meta: route?.meta ?? null,\n })\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 // Loader data to pass to usePageData() during rendering. Declared here\n // (outside try/catch) so it's visible in all return paths.\n let loaderData = null\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n // P2-2: Route-level error tag (from co-located .error.ts or _error.ts).\n // Preferred over the global errorTag when rendering loader errors for this route.\n const routeErrorTag = mod.errorTag ?? null\n\n // P1-1: Synthetic 404 catch-all \u2014 no page component registered.\n if (!pageTag) {\n const notFoundErrorTag = routeErrorTag ?? errorTag\n const notFoundVnode = notFoundErrorTag\n ? { tag: notFoundErrorTag, props: { attrs: { error: 'Not Found', status: '404' } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: notFoundVnode, router, head: undefined, status: 404 }\n }\n\n // Run the loader before creating the page vnode so we can pass its\n // primitive return values as HTML attributes. useProps() in the page\n // component reads element attributes, so merging loader data here makes\n // both useProps() and usePageData() work in SSR / SSG.\n let loaderAttrs = {}\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 // Store loader data so the handler can pass it to _cerDataStore.run()\n // below. Using enterWith() here doesn't work because it only modifies\n // the async context *inside* this awaited function, not the outer\n // handler's continuation where renderToStreamWithJITCSSDSD runs.\n loaderData = data\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n // Expose primitive loader values as element attributes so useProps()\n // can read them. Complex objects are only accessible via usePageData().\n loaderAttrs = Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n }\n }\n\n pageVnode = { tag: pageTag, props: { attrs: { ...params, ...loaderAttrs } }, children: [] }\n } catch (err) {\n // Loader threw \u2014 render the error page server-side if app/error.ts exists.\n const status = (err && typeof err === 'object' && 'status' in err && typeof err.status === 'number')\n ? err.status : 500\n const message = (err instanceof Error) ? err.message : String(err)\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'loader', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n // P2-2: Prefer the route-level errorTag over the global one.\n // routeErrorTag is not in scope here; use route?.meta?.errorTag from the matched route.\n const effectiveErrorTag = route?.meta?.errorTag ?? errorTag\n if (!effectiveErrorTag) {\n console.error('[cer-app] Loader error (no app/error.ts defined):', err)\n }\n const errVnode = effectiveErrorTag\n ? { tag: effectiveErrorTag, props: { attrs: { error: message, status: String(status) } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: errVnode, router, head: undefined, status }\n }\n }\n\n // Resolve layout chain: nested layouts (meta.layoutChain) or single layout.\n const chain = route?.meta?.layoutChain\n ? route.meta.layoutChain\n : [route?.meta?.layout ?? 'default']\n\n // Wrap pageVnode in the layout chain from innermost to outermost.\n let vnode = pageVnode\n for (let i = chain.length - 1; i >= 0; i--) {\n const tag = layouts[chain[i]]\n if (tag) vnode = { tag, props: {}, children: [vnode] }\n }\n\n // Only framework-owned not-found routes should force a 404 status. A user\n // catch-all page ([...all].ts) may successfully resolve real content paths\n // and should stay 200 unless its loader explicitly throws a 404.\n const isNotFoundRoute = route?.meta?._cerNotFound === true\n return { vnode, router, head, status: isNotFoundRoute ? 404 : null, loaderData }\n}\n\nexport const handler = async (req, res) => {\n const _requestPath = new URL(req.url ?? '/', 'http://x').pathname\n const _requestStart = Date.now()\n if (_hooks?.onRequest) {\n try { await _hooks.onRequest({ path: _requestPath, method: req.method ?? 'GET', req }) } catch { /* hooks must not crash the handler */ }\n }\n await _cerStateStore.run(new Map(), async () => {\n await _cerReqStore.run({ req, res }, async () => {\n await _cerDataStore.run(null, async () => {\n // Fresh per-request fetch map \u2014 populated by useFetch() calls inside loaders.\n const _fetchMap = new Map()\n await _cerFetchStore.run(_fetchMap, async () => {\n // Pre-resolve the authenticated user so useAuth() works synchronously during rendering.\n let _authUser = null\n if (_authSessionKey) {\n try { _authUser = await useSession({ name: _authSessionKey }).get() } catch { /* no session secret */ }\n }\n await _cerAuthStore.run(_authUser, async () => {\n const { vnode, router, head, status, loaderData } = await _prepareRequest(req)\n if (status != null) res.statusCode = status\n\n let _headCollectionOpen = false\n // Wrap the entire render pass in _cerDataStore.run(loaderData) so that\n // usePageData() inside component renderFn calls sees the correct store\n // value. AsyncLocalStorage.enterWith() inside _prepareRequest does NOT\n // propagate back to this outer async continuation \u2014 it only affects the\n // async chain inside _prepareRequest itself. Using run() here is the only\n // reliable way to scope the data store to the synchronous render pass.\n await _cerDataStore.run(loaderData ?? null, async () => {\n try {\n // Begin collecting useHead() calls made during the synchronous render pass.\n // IMPORTANT: the stream's start() function runs synchronously on construction,\n // so ALL useHead() calls happen before the stream object is returned. We must\n // call endHeadCollection() immediately \u2014 before any await \u2014 to avoid a race\n // window where a concurrent request (e.g. SSG concurrency > 1) resets the\n // shared globalThis collector while this handler is suspended at an await.\n _headCollectionOpen = true\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 // The first chunk from the stream is the full synchronous render. Subsequent\n // chunks are async component swap scripts streamed as they resolve.\n const stream = renderToStreamWithJITCSSDSD(vnode, { dsdPolyfill: false, router })\n\n // Collect head tags synchronously \u2014 all useHead() calls have already fired\n // inside the stream constructor's start() before it returned.\n const headTags = serializeHeadTags(endHeadCollection())\n _headCollectionOpen = false\n\n const reader = stream.getReader()\n\n // Read the first (synchronous) chunk \u2014 rejects if the sync render failed.\n const { value: firstChunk = '' } = await reader.read()\n\n // Serialise useFetch() results collected during loader execution.\n const _fetchObj = Object.fromEntries(_fetchMap)\n const _fetchScript = Object.keys(_fetchObj).length > 0\n ? `<script>window.__CER_FETCH_DATA__ = ${JSON.stringify(_fetchObj)}</script>`\n : ''\n\n // Serialise the auth user for client-side hydration via useAuth().\n const _authScript = _authUser\n ? `<script>window.__CER_AUTH_USER__ = ${JSON.stringify(_authUser)}</script>`\n : ''\n\n // Serialise useState() values for client-side hydration.\n // The state Map is populated by loader calls (in _prepareRequest) and by component\n // render functions (during renderToStreamWithJITCSSDSD above). Both run before this\n // point. Injected as window.__CER_STATE_INIT__ so the client useState() can\n // pre-populate its singleton Map on first use \u2014 no flash to default values.\n const _stateMap = _cerStateStore.getStore()\n let _stateScript = ''\n if (_stateMap && _stateMap.size > 0) {\n const _stateObj = {}\n for (const [k, v] of _stateMap) { _stateObj[k] = v.value }\n _stateScript = `<script>window.__CER_STATE_INIT__ = ${JSON.stringify(_stateObj)}</script>`\n }\n\n // Merge loader data script + useHead() tags + fetch/auth/state hydration scripts.\n const headContent = [head, headTags, _fetchScript, _authScript, _stateScript].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>${firstChunk}</body></html>`\n\n // In dev mode the module-level _clientTemplate is null (only the\n // production dist/client/index.html path is searched at init time).\n // The dev server sets (globalThis).__CER_CLIENT_TEMPLATE__ per-request\n // after running server.transformIndexHtml so the Vite client scripts\n // (/@vite/client, HMR) are included in every SSR response.\n const _resolvedClientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? _clientTemplate\n const merged = _resolvedClientTemplate\n ? _mergeWithClientTemplate(ssrHtml, _resolvedClientTemplate)\n : ssrHtml\n\n // Split at </body> so async swap scripts and the DSD polyfill can be streamed\n // in before the document is closed.\n const bodyCloseIdx = merged.lastIndexOf('</body>')\n const beforeBodyClose = bodyCloseIdx >= 0 ? merged.slice(0, bodyCloseIdx) : merged\n const fromBodyClose = bodyCloseIdx >= 0 ? merged.slice(bodyCloseIdx) : ''\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Transfer-Encoding', 'chunked')\n res.write(beforeBodyClose)\n\n // Stream async component swap scripts through as-is.\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n res.write(value)\n }\n\n // Inject DSD polyfill immediately before </body>, then close the document.\n res.end(DSD_POLYFILL_SCRIPT + fromBodyClose)\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n } catch (_renderErr) {\n if (_hooks?.onError) {\n try { await _hooks.onError(_renderErr, { type: 'render', path: _requestPath, req }) } catch { /* hooks must not crash the handler */ }\n }\n // Ensure the head collector is never left open on error.\n if (_headCollectionOpen) { try { endHeadCollection() } catch { /* ignore */ } }\n // If headers have not been flushed yet we can still send a proper 500 page.\n // If writing has already started we can only close the connection cleanly.\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end('<!DOCTYPE html><html><head></head><body><h1>500 Internal Server Error</h1><p>An unexpected error occurred while rendering this page.</p></body></html>')\n } else {\n res.end()\n }\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n }\n }) // _cerDataStore.run(loaderData)\n }) // _cerAuthStore.run\n }) // _cerFetchStore.run\n }) // _cerDataStore.run\n }) // _cerReqStore.run\n }) // _cerStateStore.run\n}\n\n// ISR-wrapped handler for production integrations (Express, Hono, Fastify).\n// Routes with meta.ssg.revalidate are served stale-while-revalidate.\nexport const isrHandler = createIsrHandler(routes, handler)\n\nexport { apiRoutes, plugins, layouts, routes, serverMiddleware }\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-content-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 serverMiddleware from 'virtual:cer-server-middleware'\nimport { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'\nimport { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, renderToStreamWithJITCSSDSD, 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, initRuntimeConfig, resolvePrivateConfig, useSession } from '@jasonshimmy/vite-plugin-cer-app/composables'\nimport { errorTag } from 'virtual:cer-error'\nimport { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'\n\nconst _cerProcess = (globalThis).process\nconst _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE\nconst _cerRuntimeDev =\n typeof _cerNodeEnv === 'string'\n ? _cerNodeEnv !== 'production'\n : typeof import.meta.env?.DEV === 'boolean'\n ? import.meta.env.DEV\n : typeof import.meta.env?.PROD === 'boolean'\n ? !import.meta.env.PROD\n : typeof import.meta.env?.MODE === 'string'\n ? import.meta.env.MODE !== 'production'\n : false\n;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev\n\nregisterBuiltinComponents()\nsetDevMode(_cerRuntimeDev)\n\n// Resolve private config from environment variables at server startup.\n// Each key declared in runtimeConfig.private is looked up in process.env,\n// first as-is, then as ALL_CAPS. The declared default is used as fallback.\ninitRuntimeConfig({ ...runtimeConfig, private: resolvePrivateConfig(_runtimePrivateDefaults ?? {}) })\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// Async-local storage for request-scoped req/res access.\n// Allows isomorphic composables (e.g. useCookie) to read/write HTTP headers\n// without prop-drilling the request context through the component tree.\nconst _cerReqStore = new AsyncLocalStorage()\n;(globalThis).__CER_REQ_STORE__ = _cerReqStore\n\n// Async-local storage for the authenticated user resolved before each render.\n// useAuth() reads this store server-side to return the current user synchronously.\nconst _cerAuthStore = new AsyncLocalStorage()\n;(globalThis).__CER_AUTH_STORE__ = _cerAuthStore\n\n// Async-local storage for per-request useFetch() data.\n// useFetch() writes fetched results here; the handler serialises the map into\n// window.__CER_FETCH_DATA__ for client-side hydration.\nconst _cerFetchStore = new AsyncLocalStorage()\n;(globalThis).__CER_FETCH_STORE__ = _cerFetchStore\n\n// Async-local storage for the current route info (path, params, query, meta).\n// useRoute() reads this on the server so layouts and components can access\n// route metadata without prop-drilling.\nconst _cerRouteStore = new AsyncLocalStorage()\n;(globalThis).__CER_ROUTE_STORE__ = _cerRouteStore\n\n// Async-local storage for per-request useState() reactive state.\n// Each request gets a fresh Map so concurrent SSR/SSG renders never share\n// reactive state set by different pages or loaders.\nconst _cerStateStore = new AsyncLocalStorage()\n;(globalThis).__CER_STATE_STORE__ = _cerStateStore\n\n// Runs fn inside the per-request AsyncLocalStorage context so that isomorphic\n// composables (useCookie, useSession, etc.) can access req/res without prop-drilling.\n// Call this for every API handler invocation \u2014 not just SSR renders.\nexport function runWithRequestContext(req, res, fn) {\n return _cerReqStore.run({ req, res }, fn)\n}\n\n// Runs the server/middleware/ chain for a request.\n// Returns false if a middleware short-circuited the response; true to continue.\n// Exported so Netlify / Vercel / Cloudflare bridges can also call it for API routes.\n// P1-2: Middleware may throw { status: 401 } (or any numeric .status) to produce\n// a non-500 response \u2014 the status is extracted and forwarded to res.statusCode.\nexport async function runServerMiddleware(req, res) {\n for (const { handler: mw } of (serverMiddleware ?? [])) {\n if (typeof mw !== 'function') continue\n let calledNext = false\n try {\n await new Promise((resolve, reject) => {\n Promise.resolve(mw(req, res, (err) => {\n if (err) reject(err)\n else { calledNext = true; resolve() }\n })).catch(reject)\n })\n } catch (err) {\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'middleware', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n if (!res.writableEnded) {\n const statusCode = (typeof err === 'object' && err !== null && 'status' in err && typeof err.status === 'number')\n ? (isNaN(err.status) ? 500 : err.status)\n : 500\n res.statusCode = statusCode\n res.end('Internal Server Error')\n }\n return false\n }\n if (res.writableEnded || !calledNext) return false\n }\n return true\n}\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.\n//\n// Cloudflare Workers (and other runtimes without node:fs) can inject the\n// template before this module loads by setting globalThis.__CER_CLIENT_TEMPLATE__.\n// The Cloudflare adapter inlines dist/client/index.html as a string constant in\n// _worker.js and sets the global before dynamically importing the server bundle.\nlet _clientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? null\nif (!_clientTemplate) {\n try {\n const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\n _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n } catch {\n // node:fs not available in this runtime \u2014 Cloudflare adapter must set\n // globalThis.__CER_CLIENT_TEMPLATE__ before importing this bundle.\n }\n}\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 returned so the handler can scope it to _cerDataStore.run()\n// during rendering. (AsyncLocalStorage.enterWith() inside an awaited child\n// function does not propagate back to the parent continuation, so run() is\n// the only reliable approach.)\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\n // Store the current route info so useRoute() can read it synchronously\n // from any layout or component during this render pass.\n _cerRouteStore.enterWith({\n path: current.path,\n params,\n query: current.query ?? {},\n meta: route?.meta ?? null,\n })\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 // Loader data to pass to usePageData() during rendering. Declared here\n // (outside try/catch) so it's visible in all return paths.\n let loaderData = null\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n // P2-2: Route-level error tag (from co-located .error.ts or _error.ts).\n // Preferred over the global errorTag when rendering loader errors for this route.\n const routeErrorTag = mod.errorTag ?? null\n\n // P1-1: Synthetic 404 catch-all \u2014 no page component registered.\n if (!pageTag) {\n const notFoundErrorTag = routeErrorTag ?? errorTag\n const notFoundVnode = notFoundErrorTag\n ? { tag: notFoundErrorTag, props: { attrs: { error: 'Not Found', status: '404' } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: notFoundVnode, router, head: undefined, status: 404 }\n }\n\n // Run the loader before creating the page vnode so we can pass its\n // primitive return values as HTML attributes. useProps() in the page\n // component reads element attributes, so merging loader data here makes\n // both useProps() and usePageData() work in SSR / SSG.\n let loaderAttrs = {}\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 // Store loader data so the handler can pass it to _cerDataStore.run()\n // below. Using enterWith() here doesn't work because it only modifies\n // the async context *inside* this awaited function, not the outer\n // handler's continuation where renderToStreamWithJITCSSDSD runs.\n loaderData = data\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n // Expose primitive loader values as element attributes so useProps()\n // can read them. Complex objects are only accessible via usePageData().\n loaderAttrs = Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n }\n }\n\n pageVnode = { tag: pageTag, props: { attrs: { ...params, ...loaderAttrs } }, children: [] }\n } catch (err) {\n // Loader threw \u2014 render the error page server-side if app/error.ts exists.\n const status = (err && typeof err === 'object' && 'status' in err && typeof err.status === 'number')\n ? err.status : 500\n const message = (err instanceof Error) ? err.message : String(err)\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'loader', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n // P2-2: Prefer the route-level errorTag over the global one.\n // routeErrorTag is not in scope here; use route?.meta?.errorTag from the matched route.\n const effectiveErrorTag = route?.meta?.errorTag ?? errorTag\n if (!effectiveErrorTag) {\n console.error('[cer-app] Loader error (no app/error.ts defined):', err)\n }\n const errVnode = effectiveErrorTag\n ? { tag: effectiveErrorTag, props: { attrs: { error: message, status: String(status) } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: errVnode, router, head: undefined, status }\n }\n }\n\n // Resolve layout chain: nested layouts (meta.layoutChain) or single layout.\n const chain = route?.meta?.layoutChain\n ? route.meta.layoutChain\n : [route?.meta?.layout ?? 'default']\n\n // Wrap pageVnode in the layout chain from innermost to outermost.\n let vnode = pageVnode\n for (let i = chain.length - 1; i >= 0; i--) {\n const tag = layouts[chain[i]]\n if (tag) vnode = { tag, props: {}, children: [vnode] }\n }\n\n // Only framework-owned not-found routes should force a 404 status. A user\n // catch-all page ([...all].ts) may successfully resolve real content paths\n // and should stay 200 unless its loader explicitly throws a 404.\n const isNotFoundRoute = route?.meta?._cerNotFound === true\n return { vnode, router, head, status: isNotFoundRoute ? 404 : null, loaderData }\n}\n\nexport const handler = async (req, res) => {\n const _requestPath = new URL(req.url ?? '/', 'http://x').pathname\n const _requestStart = Date.now()\n if (_hooks?.onRequest) {\n try { await _hooks.onRequest({ path: _requestPath, method: req.method ?? 'GET', req }) } catch { /* hooks must not crash the handler */ }\n }\n await _cerStateStore.run(new Map(), async () => {\n await _cerReqStore.run({ req, res }, async () => {\n await _cerDataStore.run(null, async () => {\n // Fresh per-request fetch map \u2014 populated by useFetch() calls inside loaders.\n const _fetchMap = new Map()\n await _cerFetchStore.run(_fetchMap, async () => {\n // Pre-resolve the authenticated user so useAuth() works synchronously during rendering.\n let _authUser = null\n if (_authSessionKey) {\n try { _authUser = await useSession({ name: _authSessionKey }).get() } catch { /* no session secret */ }\n }\n await _cerAuthStore.run(_authUser, async () => {\n const { vnode, router, head, status, loaderData } = await _prepareRequest(req)\n if (status != null) res.statusCode = status\n\n let _headCollectionOpen = false\n // Wrap the entire render pass in _cerDataStore.run(loaderData) so that\n // usePageData() inside component renderFn calls sees the correct store\n // value. AsyncLocalStorage.enterWith() inside _prepareRequest does NOT\n // propagate back to this outer async continuation \u2014 it only affects the\n // async chain inside _prepareRequest itself. Using run() here is the only\n // reliable way to scope the data store to the synchronous render pass.\n await _cerDataStore.run(loaderData ?? null, async () => {\n try {\n // Begin collecting useHead() calls made during the synchronous render pass.\n // IMPORTANT: the stream's start() function runs synchronously on construction,\n // so ALL useHead() calls happen before the stream object is returned. We must\n // call endHeadCollection() immediately \u2014 before any await \u2014 to avoid a race\n // window where a concurrent request (e.g. SSG concurrency > 1) resets the\n // shared globalThis collector while this handler is suspended at an await.\n _headCollectionOpen = true\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 // The first chunk from the stream is the full synchronous render. Subsequent\n // chunks are async component swap scripts streamed as they resolve.\n const stream = renderToStreamWithJITCSSDSD(vnode, { dsdPolyfill: false, router })\n\n // Collect head tags synchronously \u2014 all useHead() calls have already fired\n // inside the stream constructor's start() before it returned.\n const headTags = serializeHeadTags(endHeadCollection())\n _headCollectionOpen = false\n\n const reader = stream.getReader()\n\n // Read the first (synchronous) chunk \u2014 rejects if the sync render failed.\n const { value: firstChunk = '' } = await reader.read()\n\n // Serialise useFetch() results collected during loader execution.\n const _fetchObj = Object.fromEntries(_fetchMap)\n const _fetchScript = Object.keys(_fetchObj).length > 0\n ? `<script>window.__CER_FETCH_DATA__ = ${JSON.stringify(_fetchObj)}</script>`\n : ''\n\n // Serialise the auth user for client-side hydration via useAuth().\n const _authScript = _authUser\n ? `<script>window.__CER_AUTH_USER__ = ${JSON.stringify(_authUser)}</script>`\n : ''\n\n // Serialise useState() values for client-side hydration.\n // The state Map is populated by loader calls (in _prepareRequest) and by component\n // render functions (during renderToStreamWithJITCSSDSD above). Both run before this\n // point. Injected as window.__CER_STATE_INIT__ so the client useState() can\n // pre-populate its singleton Map on first use \u2014 no flash to default values.\n const _stateMap = _cerStateStore.getStore()\n let _stateScript = ''\n if (_stateMap && _stateMap.size > 0) {\n const _stateObj = {}\n for (const [k, v] of _stateMap) { _stateObj[k] = v.value }\n _stateScript = `<script>window.__CER_STATE_INIT__ = ${JSON.stringify(_stateObj)}</script>`\n }\n\n // Merge loader data script + useHead() tags + fetch/auth/state hydration scripts.\n const headContent = [head, headTags, _fetchScript, _authScript, _stateScript].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>${firstChunk}</body></html>`\n\n // In dev mode the module-level _clientTemplate is null (only the\n // production dist/client/index.html path is searched at init time).\n // The dev server sets (globalThis).__CER_CLIENT_TEMPLATE__ per-request\n // after running server.transformIndexHtml so the Vite client scripts\n // (/@vite/client, HMR) are included in every SSR response.\n const _resolvedClientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? _clientTemplate\n const merged = _resolvedClientTemplate\n ? _mergeWithClientTemplate(ssrHtml, _resolvedClientTemplate)\n : ssrHtml\n\n // Split at </body> so async swap scripts and the DSD polyfill can be streamed\n // in before the document is closed.\n const bodyCloseIdx = merged.lastIndexOf('</body>')\n const beforeBodyClose = bodyCloseIdx >= 0 ? merged.slice(0, bodyCloseIdx) : merged\n const fromBodyClose = bodyCloseIdx >= 0 ? merged.slice(bodyCloseIdx) : ''\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Transfer-Encoding', 'chunked')\n res.write(beforeBodyClose)\n\n // Stream async component swap scripts through as-is.\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n res.write(value)\n }\n\n // Inject DSD polyfill immediately before </body>, then close the document.\n res.end(DSD_POLYFILL_SCRIPT + fromBodyClose)\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n } catch (_renderErr) {\n if (_hooks?.onError) {\n try { await _hooks.onError(_renderErr, { type: 'render', path: _requestPath, req }) } catch { /* hooks must not crash the handler */ }\n }\n // Ensure the head collector is never left open on error.\n if (_headCollectionOpen) { try { endHeadCollection() } catch { /* ignore */ } }\n // If headers have not been flushed yet we can still send a proper 500 page.\n // If writing has already started we can only close the connection cleanly.\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end('<!DOCTYPE html><html><head></head><body><h1>500 Internal Server Error</h1><p>An unexpected error occurred while rendering this page.</p></body></html>')\n } else {\n res.end()\n }\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n }\n }) // _cerDataStore.run(loaderData)\n }) // _cerAuthStore.run\n }) // _cerFetchStore.run\n }) // _cerDataStore.run\n }) // _cerReqStore.run\n }) // _cerStateStore.run\n}\n\n// ISR-wrapped handler for production integrations (Express, Hono, Fastify).\n// Routes with meta.ssg.revalidate are served stale-while-revalidate.\nexport const isrHandler = createIsrHandler(routes, handler)\n\nexport { apiRoutes, plugins, layouts, routes, serverMiddleware }\nexport default handler\n";
15
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;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,s9vBA8djC,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,+/vBA+djC,CAAA"}
@@ -16,6 +16,7 @@ import { readFileSync, existsSync } from 'node:fs'
16
16
  import { dirname, join } from 'node:path'
17
17
  import { fileURLToPath } from 'node:url'
18
18
  import { AsyncLocalStorage } from 'node:async_hooks'
19
+ import 'virtual:cer-content-components'
19
20
  import routes from 'virtual:cer-routes'
20
21
  import layouts from 'virtual:cer-layouts'
21
22
  import plugins from 'virtual:cer-plugins'
@@ -1 +1 @@
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8dpC,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+dpC,CAAA"}
@@ -288,7 +288,7 @@ See [cli.md](./cli.md#cer-app-adapt) for full details.
288
288
 
289
289
  ## `content` options
290
290
 
291
- Enables the file-based content layer. Drop Markdown or JSON files into `content/` at the project root and query them with `queryContent()` or search with `useContentSearch()`.
291
+ Enables the file-based content layer. Drop Markdown or JSON files into `content/` at the project root and query them with `queryContent()` or search with `useContentSearch()`. Custom elements referenced directly inside markdown are also auto-registered from `app/components/`.
292
292
 
293
293
  ```ts
294
294
  export default defineConfig({
package/docs/content.md CHANGED
@@ -7,7 +7,7 @@ CER Content is a file-based content layer built into `vite-plugin-cer-app`. It p
7
7
  ## Overview
8
8
 
9
9
  - **Zero config** — drop files into `content/` at the project root and they are available immediately.
10
- - **Markdown + JSON** — Markdown files are parsed with frontmatter, rendered to HTML, and have their headings extracted into a table of contents. JSON files are stored as raw string bodies.
10
+ - **Markdown + JSON** — Markdown files are parsed with frontmatter, rendered to HTML, have their headings extracted into a table of contents, and auto-register matching custom elements from `app/components/` when those tags appear in the markdown body. JSON files are stored as raw string bodies.
11
11
  - **Draft support** — items with `draft: true` in frontmatter are excluded from production builds by default.
12
12
  - **Excerpt extraction** — place `<!-- more -->` in a Markdown file to set the excerpt boundary.
13
13
  - **Full-text search** — a MiniSearch index is emitted at build time and loaded lazily on the client via `useContentSearch()`.
@@ -103,6 +103,19 @@ When `false`, any file with `draft: true` in its frontmatter is excluded from th
103
103
 
104
104
  Markdown files use [gray-matter](https://github.com/jonschlinkert/gray-matter) for YAML frontmatter. All frontmatter keys are stored in the content item. The body is rendered to HTML using [marked](https://marked.js.org). Heading elements receive an `id` attribute derived from their slug.
105
105
 
106
+ If the rendered markdown body contains custom-element tags that match components registered in `app/components/`, CER automatically imports those component modules for both client and server entry points. That means markdown like `<site-callout>Note</site-callout>` works in SPA, SSR, and SSG without adding manual imports to your page component.
107
+
108
+ Props passed from markdown follow normal HTML attribute rules:
109
+
110
+ - String props work directly: `<site-callout tone="info" heading="Heads up">…</site-callout>`
111
+ - Number and boolean props work when the component declares them via `useProps()` defaults, because the runtime coerces attribute values to the declared primitive type
112
+ - Boolean presence attributes are appropriate for flag-style props such as `<site-callout dismissible>`
113
+ - All markdown-supplied props are attribute-based, so they must be serializable as plain HTML attribute values
114
+ - Arrays, objects, and function props are not passed as rich JavaScript values from markdown
115
+ - CER template bindings and directives do not run inside markdown HTML, so syntax like `:bind`, `@click`, `:class`, or `${...}` is treated as plain text/attributes, not live bindings
116
+
117
+ In practice, components used from markdown should expose a string/number/boolean attribute API and read those values with `useProps()`.
118
+
106
119
  ```md
107
120
  ---
108
121
  title: Hello World
@@ -118,6 +131,31 @@ draft: false
118
131
  Everything below the excerpt boundary is in `body` but not in `excerpt`.
119
132
  ```
120
133
 
134
+ ```md
135
+ # Docs
136
+
137
+ <site-callout>Remember to configure your content directory.</site-callout>
138
+ ```
139
+
140
+ ```ts
141
+ component('site-callout', () => {
142
+ const props = useProps({ tone: 'info', heading: '', dismissible: false, priority: 0 })
143
+
144
+ return html`
145
+ <aside data-tone="${props.tone}">
146
+ ${props.heading ? html`<strong>${props.heading}</strong>` : ''}
147
+ <slot></slot>
148
+ </aside>
149
+ `
150
+ })
151
+ ```
152
+
153
+ ```md
154
+ <site-callout tone="warning" heading="Before You Start" dismissible priority="2">
155
+ Install dependencies first.
156
+ </site-callout>
157
+ ```
158
+
121
159
  Recognized frontmatter keys:
122
160
 
123
161
  | Key | Type | Description |
@@ -10,7 +10,7 @@
10
10
  * /content-fallback — title/description derived from body when frontmatter omits them
11
11
  */
12
12
 
13
- const mode = Cypress.env('mode') as 'spa' | 'ssr' | 'ssg'
13
+ const mode = Cypress.env('mode') as 'spa' | 'ssr' | 'ssg' | 'dev'
14
14
 
15
15
  // ─── /content-index ───────────────────────────────────────────────────────────
16
16
 
@@ -115,6 +115,18 @@ describe('Content doc — queryContent("/docs/getting-started").first()', () =>
115
115
  expect(response.body).to.include('Installation')
116
116
  })
117
117
  })
118
+
119
+ it('includes markdown component registration hints in initial HTML', () => {
120
+ cy.request('/content-doc').then((response) => {
121
+ expect(response.body).to.include('<ks-badge>Docs Badge</ks-badge>')
122
+ if (mode === 'dev') {
123
+ expect(response.body).to.include('/@cer/app.ts')
124
+ } else {
125
+ expect(response.body).to.match(/ks-badge-[^"']+\.js/)
126
+ }
127
+ expect(response.body).to.include('Docs Badge')
128
+ })
129
+ })
118
130
  }
119
131
 
120
132
  it('renders doc title after hydration', () => {
@@ -156,6 +168,14 @@ describe('Content doc — queryContent("/docs/getting-started").first()', () =>
156
168
  cy.visit('/content-doc')
157
169
  cy.get('[data-cy=content-doc-body]', { timeout: 8000 }).contains('h2', 'Installation')
158
170
  })
171
+
172
+ it('renders app components referenced inside markdown after hydration', () => {
173
+ cy.visit('/content-doc')
174
+ cy.get('[data-cy=content-doc-body]', { timeout: 8000 }).within(() => {
175
+ cy.get('ks-badge').should('contain', 'Docs Badge')
176
+ cy.get('[data-cy=ks-badge]').should('exist')
177
+ })
178
+ })
159
179
  })
160
180
 
161
181
  // ─── /content-guides ─────────────────────────────────────────────────────────
@@ -7,6 +7,8 @@ description: How to install and configure the content layer — tests TOC depth
7
7
 
8
8
  This guide walks you through installation and basic usage.
9
9
 
10
+ <ks-badge>Docs Badge</ks-badge>
11
+
10
12
  ## Installation
11
13
 
12
14
  Run the following command:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jasonshimmy/vite-plugin-cer-app",
3
- "version": "0.21.2",
3
+ "version": "0.21.4",
4
4
  "description": "Nuxt-style meta-framework for @jasonshimmy/custom-elements-runtime",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -52,6 +52,10 @@ describe('app-template (APP_ENTRY_TEMPLATE content)', () => {
52
52
  expect(src).toContain('virtual:cer-jit-css')
53
53
  })
54
54
 
55
+ it('imports virtual:cer-content-components for markdown-backed custom elements', () => {
56
+ expect(src).toContain('virtual:cer-content-components')
57
+ })
58
+
55
59
  it('exports router', () => {
56
60
  expect(src).toContain('export { router }')
57
61
  })
@@ -34,6 +34,7 @@ vi.mock('../../plugin/virtual/server-api.js', () => ({ generateServerApiCode: vi
34
34
  vi.mock('../../plugin/virtual/server-middleware.js', () => ({ generateServerMiddlewareCode: vi.fn().mockResolvedValue('// server-middleware') }))
35
35
  vi.mock('../../plugin/virtual/loading.js', () => ({ generateLoadingCode: vi.fn().mockResolvedValue('// loading') }))
36
36
  vi.mock('../../plugin/virtual/error.js', () => ({ generateErrorCode: vi.fn().mockResolvedValue('// error') }))
37
+ vi.mock('../../plugin/virtual/content-components.js', () => ({ generateContentComponentsCode: vi.fn().mockResolvedValue('// content-components') }))
37
38
  vi.mock('../../plugin/transforms/auto-import.js', () => ({ autoImportTransform: vi.fn().mockReturnValue(null) }))
38
39
 
39
40
  import { cerApp } from '../../plugin/index.js'
@@ -258,8 +258,8 @@ describe('generateAutoImportDts', () => {
258
258
  it('uses relative path for user composables', async () => {
259
259
  const exports = new Map([['useFoo', `${ROOT}/app/composables/foo.ts`]])
260
260
  const dts = await generateAutoImportDts(ROOT, COMPOSABLES_DIR, exports)
261
- // Path should be relative from root
262
- expect(dts).toContain('./app/composables/foo')
261
+ // Path must be relative from .cer/ (one level up from root) so TypeScript can resolve it
262
+ expect(dts).toContain('../app/composables/foo')
263
263
  })
264
264
  })
265
265
 
@@ -28,6 +28,10 @@ describe('entry-server-template (ENTRY_SERVER_TEMPLATE content)', () => {
28
28
  expect(src).toContain('virtual:cer-server-api')
29
29
  })
30
30
 
31
+ it('imports virtual:cer-content-components for markdown-backed custom elements', () => {
32
+ expect(src).toContain('virtual:cer-content-components')
33
+ })
34
+
31
35
  it('imports registerBuiltinComponents from custom-elements-runtime', () => {
32
36
  expect(src).toContain('registerBuiltinComponents')
33
37
  expect(src).toContain('setDevMode')
@@ -0,0 +1,66 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'pathe'
5
+ import { generateContentComponentsCode } from '../../../plugin/virtual/content-components.js'
6
+
7
+ let tmpRoot: string
8
+ let componentsDir: string
9
+ let contentDir: string
10
+
11
+ beforeAll(() => {
12
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cer-content-components-'))
13
+ componentsDir = join(tmpRoot, 'app', 'components')
14
+ contentDir = join(tmpRoot, 'content')
15
+
16
+ mkdirSync(componentsDir, { recursive: true })
17
+ mkdirSync(contentDir, { recursive: true })
18
+
19
+ writeFileSync(
20
+ join(componentsDir, 'site-callout.ts'),
21
+ "component('site-callout', () => html`<div>Callout</div>`)",
22
+ )
23
+ writeFileSync(
24
+ join(componentsDir, 'site-alert.ts'),
25
+ "component('site-alert', () => html`<div>Alert</div>`)",
26
+ )
27
+
28
+ writeFileSync(
29
+ join(contentDir, 'guide.md'),
30
+ [
31
+ '# Guide',
32
+ '',
33
+ '<site-callout>Docs</site-callout>',
34
+ '',
35
+ '```html',
36
+ '<site-alert>Example only</site-alert>',
37
+ '```',
38
+ '',
39
+ '<unknown-widget>Ignored</unknown-widget>',
40
+ ].join('\n'),
41
+ )
42
+ })
43
+
44
+ afterAll(() => {
45
+ rmSync(tmpRoot, { recursive: true, force: true })
46
+ })
47
+
48
+ describe('generateContentComponentsCode', () => {
49
+ it('imports only registered components referenced by rendered markdown', async () => {
50
+ const code = await generateContentComponentsCode(componentsDir, contentDir)
51
+
52
+ expect(code).toContain(JSON.stringify(join(componentsDir, 'site-callout.ts')))
53
+ expect(code).not.toContain(JSON.stringify(join(componentsDir, 'site-alert.ts')))
54
+ expect(code).not.toContain('unknown-widget')
55
+ expect(code).toContain('export {}')
56
+ })
57
+
58
+ it('returns an empty module when no markdown-backed components are found', async () => {
59
+ const emptyContentDir = join(tmpRoot, 'empty-content')
60
+ mkdirSync(emptyContentDir, { recursive: true })
61
+ writeFileSync(join(emptyContentDir, 'plain.md'), '# Plain\n\nNo custom elements here.')
62
+
63
+ const code = await generateContentComponentsCode(componentsDir, emptyContentDir)
64
+ expect(code).toBe('// AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nexport {}\n')
65
+ })
66
+ })
@@ -8,11 +8,11 @@
8
8
  "preview": "cer-app preview"
9
9
  },
10
10
  "dependencies": {
11
- "@jasonshimmy/custom-elements-runtime": "^3.7.2"
11
+ "@jasonshimmy/custom-elements-runtime": "^3.7.5"
12
12
  },
13
13
  "devDependencies": {
14
- "@jasonshimmy/vite-plugin-cer-app": "^0.19.3",
15
- "typescript": "^5.9.3",
16
- "vite": "^8.0.3"
14
+ "@jasonshimmy/vite-plugin-cer-app": "^0.21.3",
15
+ "typescript": "^6.0.2",
16
+ "vite": "^8.0.8"
17
17
  }
18
18
  }
@@ -9,11 +9,11 @@
9
9
  "preview": "cer-app preview"
10
10
  },
11
11
  "dependencies": {
12
- "@jasonshimmy/custom-elements-runtime": "^3.7.2"
12
+ "@jasonshimmy/custom-elements-runtime": "^3.7.5"
13
13
  },
14
14
  "devDependencies": {
15
- "@jasonshimmy/vite-plugin-cer-app": "^0.19.3",
16
- "typescript": "^5.9.3",
17
- "vite": "^8.0.3"
15
+ "@jasonshimmy/vite-plugin-cer-app": "^0.21.3",
16
+ "typescript": "^6.0.2",
17
+ "vite": "^8.0.8"
18
18
  }
19
19
  }
@@ -8,11 +8,11 @@
8
8
  "preview": "cer-app preview --ssr"
9
9
  },
10
10
  "dependencies": {
11
- "@jasonshimmy/custom-elements-runtime": "^3.7.2"
11
+ "@jasonshimmy/custom-elements-runtime": "^3.7.5"
12
12
  },
13
13
  "devDependencies": {
14
- "@jasonshimmy/vite-plugin-cer-app": "^0.19.3",
15
- "typescript": "^5.9.3",
16
- "vite": "^8.0.3"
14
+ "@jasonshimmy/vite-plugin-cer-app": "^0.21.3",
15
+ "typescript": "^6.0.2",
16
+ "vite": "^8.0.8"
17
17
  }
18
18
  }
@@ -9,6 +9,7 @@ export interface ResolvedCerConfig {
9
9
  mode: 'spa' | 'ssr' | 'ssg'
10
10
  srcDir: string
11
11
  root: string
12
+ contentDir: string
12
13
  pagesDir: string
13
14
  layoutsDir: string
14
15
  componentsDir: string
@@ -146,18 +146,18 @@ export async function generateAutoImportDts(
146
146
  if (exports.size > 0) {
147
147
  lines.push('')
148
148
  for (const [name, filePath] of exports) {
149
- // Use a path relative to the project root so the .d.ts is portable
150
- const rel = './' + relative(root, filePath).replace(/\.ts$/, '')
149
+ // Use a path relative to .cer/ (one level up from root) so the .d.ts resolves correctly
150
+ const rel = '../' + relative(root, filePath).replace(/\.ts$/, '')
151
151
  lines.push(` const ${name}: typeof import('${rel}')['${name}']`)
152
152
  }
153
153
  }
154
154
 
155
155
  lines.push('')
156
156
  lines.push(' // Content layer types')
157
- lines.push(` type ContentMeta = import('@jasonshimmy/vite-plugin-cer-app')['ContentMeta']`)
158
- lines.push(` type ContentItem = import('@jasonshimmy/vite-plugin-cer-app')['ContentItem']`)
159
- lines.push(` type ContentHeading = import('@jasonshimmy/vite-plugin-cer-app')['ContentHeading']`)
160
- lines.push(` type ContentSearchResult = import('@jasonshimmy/vite-plugin-cer-app')['ContentSearchResult']`)
157
+ lines.push(` type ContentMeta = import('@jasonshimmy/vite-plugin-cer-app').ContentMeta`)
158
+ lines.push(` type ContentItem = import('@jasonshimmy/vite-plugin-cer-app').ContentItem`)
159
+ lines.push(` type ContentHeading = import('@jasonshimmy/vite-plugin-cer-app').ContentHeading`)
160
+ lines.push(` type ContentSearchResult = import('@jasonshimmy/vite-plugin-cer-app').ContentSearchResult`)
161
161
  lines.push('')
162
162
  lines.push(' // SSR loader data injected as window.__CER_DATA__ by the server.')
163
163
  lines.push(' // Consumed once by usePageData() during client hydration.')
@@ -210,7 +210,7 @@ export async function generateVirtualModuleDts(
210
210
  ]
211
211
 
212
212
  for (const [name, filePath] of exports) {
213
- const rel = './' + relative(root, filePath).replace(/\.ts$/, '')
213
+ const rel = '../' + relative(root, filePath).replace(/\.ts$/, '')
214
214
  lines.push(` export { ${name} } from '${rel}'`)
215
215
  }
216
216
 
@@ -18,6 +18,7 @@ import { generateServerApiCode } from './virtual/server-api.js'
18
18
  import { generateServerMiddlewareCode } from './virtual/server-middleware.js'
19
19
  import { generateLoadingCode } from './virtual/loading.js'
20
20
  import { generateErrorCode } from './virtual/error.js'
21
+ import { generateContentComponentsCode } from './virtual/content-components.js'
21
22
  import { createWatcher } from './scanner.js'
22
23
  import { cerContent } from './content/index.js'
23
24
 
@@ -33,6 +34,7 @@ const VIRTUAL_IDS = {
33
34
  appConfig: 'virtual:cer-app-config',
34
35
  loading: 'virtual:cer-loading',
35
36
  error: 'virtual:cer-error',
37
+ contentComponents: 'virtual:cer-content-components',
36
38
  i18n: 'virtual:cer-i18n',
37
39
  } as const
38
40
 
@@ -60,6 +62,7 @@ export function resolveConfig(userConfig: CerAppConfig, root: string = process.c
60
62
  mode,
61
63
  srcDir,
62
64
  root,
65
+ contentDir: resolve(root, userConfig.content?.dir ?? 'content'),
63
66
  pagesDir: join(srcDir, 'pages'),
64
67
  layoutsDir: join(srcDir, 'layouts'),
65
68
  componentsDir: join(srcDir, 'components'),
@@ -136,6 +139,8 @@ async function generateVirtualModule(
136
139
  return generateLoadingCode(config.srcDir)
137
140
  case RESOLVED_IDS.error:
138
141
  return generateErrorCode(config.srcDir)
142
+ case RESOLVED_IDS.contentComponents:
143
+ return generateContentComponentsCode(config.componentsDir, config.contentDir)
139
144
  case RESOLVED_IDS.i18n:
140
145
  return generateI18nModule(config.i18n)
141
146
  default:
@@ -223,6 +228,9 @@ function getDirtyVirtualIds(filePath: string, config: ResolvedCerConfig): string
223
228
  if (filePath.startsWith(config.layoutsDir)) {
224
229
  dirty.push(RESOLVED_IDS.layouts)
225
230
  }
231
+ if (filePath.startsWith(config.componentsDir)) {
232
+ dirty.push(RESOLVED_IDS.contentComponents)
233
+ }
226
234
  if (filePath.startsWith(config.composablesDir)) {
227
235
  dirty.push(RESOLVED_IDS.composables)
228
236
  }
@@ -238,6 +246,9 @@ function getDirtyVirtualIds(filePath: string, config: ResolvedCerConfig): string
238
246
  if (filePath.startsWith(config.serverMiddlewareDir)) {
239
247
  dirty.push(RESOLVED_IDS.serverMiddleware)
240
248
  }
249
+ if (filePath.startsWith(config.contentDir)) {
250
+ dirty.push(RESOLVED_IDS.contentComponents)
251
+ }
241
252
 
242
253
  return dirty
243
254
  }
@@ -393,6 +404,7 @@ export function cerApp(userConfig: CerAppConfig = {}): Plugin[] {
393
404
  config.pagesDir,
394
405
  config.layoutsDir,
395
406
  config.componentsDir,
407
+ config.contentDir,
396
408
  config.composablesDir,
397
409
  config.pluginsDir,
398
410
  config.middlewareDir,