@jasonshimmy/vite-plugin-cer-app 0.21.1 → 0.21.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/commits.txt +1 -2
- package/dist/cli/commands/dev.d.ts.map +1 -1
- package/dist/cli/commands/dev.js +32 -16
- package/dist/cli/commands/dev.js.map +1 -1
- package/dist/runtime/app-template.d.ts +1 -1
- package/dist/runtime/app-template.d.ts.map +1 -1
- package/dist/runtime/app-template.js +16 -0
- package/dist/runtime/app-template.js.map +1 -1
- package/dist/runtime/entry-server-template.d.ts +1 -1
- package/dist/runtime/entry-server-template.d.ts.map +1 -1
- package/dist/runtime/entry-server-template.js +16 -1
- package/dist/runtime/entry-server-template.js.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/plugin/app-template.test.ts +9 -0
- package/src/__tests__/plugin/entry-server-template.test.ts +9 -0
- package/src/cli/commands/dev.ts +27 -16
- package/src/runtime/app-template.ts +16 -0
- package/src/runtime/entry-server-template.ts +16 -1
package/CHANGELOG.md
CHANGED
package/commits.txt
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
- fix:
|
|
2
|
-
- fix: ensure catch all only throws errors if one is actually encountered, enhance content-driven routing and catch-all page handling in documentation (a1ea900)
|
|
1
|
+
- fix: enhance dev mode logging in runtime and update dependencies (57a5a7c)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;
|
|
1
|
+
{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAkFnC,wBAAgB,UAAU,IAAI,OAAO,CA0CpC"}
|
package/dist/cli/commands/dev.js
CHANGED
|
@@ -21,6 +21,8 @@ async function loadCerConfig(root) {
|
|
|
21
21
|
return {};
|
|
22
22
|
}
|
|
23
23
|
try {
|
|
24
|
+
const originalNodeEnv = process.env.NODE_ENV;
|
|
25
|
+
const originalMode = process.env.MODE;
|
|
24
26
|
// Bootstrap .cer/tsconfig.json so rolldown can resolve it during cer.config.ts transform
|
|
25
27
|
const cerDir = resolve(root, '.cer');
|
|
26
28
|
const cerTsconfig = resolve(cerDir, 'tsconfig.json');
|
|
@@ -29,23 +31,35 @@ async function loadCerConfig(root) {
|
|
|
29
31
|
writeFileSync(cerTsconfig, '{"compilerOptions":{}}\n', 'utf-8');
|
|
30
32
|
}
|
|
31
33
|
// Use Vite's build to transpile TS config at runtime
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
build
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
34
|
+
try {
|
|
35
|
+
const { build } = await import('vite');
|
|
36
|
+
await build({
|
|
37
|
+
build: {
|
|
38
|
+
lib: {
|
|
39
|
+
entry: filePath,
|
|
40
|
+
formats: ['es'],
|
|
41
|
+
fileName: 'cer.config',
|
|
42
|
+
},
|
|
43
|
+
outDir: resolve(root, 'node_modules/.cer-app-cache'),
|
|
44
|
+
write: true,
|
|
45
|
+
rollupOptions: {
|
|
46
|
+
// Externalize all bare package imports (handles file: symlinks too)
|
|
47
|
+
external: (id) => !id.startsWith('.') && !id.startsWith('/'),
|
|
48
|
+
},
|
|
39
49
|
},
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
logLevel: 'silent',
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
if (typeof originalNodeEnv === 'undefined')
|
|
55
|
+
delete process.env.NODE_ENV;
|
|
56
|
+
else
|
|
57
|
+
process.env.NODE_ENV = originalNodeEnv;
|
|
58
|
+
if (typeof originalMode === 'undefined')
|
|
59
|
+
delete process.env.MODE;
|
|
60
|
+
else
|
|
61
|
+
process.env.MODE = originalMode;
|
|
62
|
+
}
|
|
49
63
|
const outFile = resolve(root, 'node_modules/.cer-app-cache/cer.config.mjs');
|
|
50
64
|
if (existsSync(outFile)) {
|
|
51
65
|
const mod = await import(pathToFileURL(outFile).href + `?t=${Date.now()}`);
|
|
@@ -74,6 +88,8 @@ export function devCommand() {
|
|
|
74
88
|
.action(async (options) => {
|
|
75
89
|
const root = resolve(options.root);
|
|
76
90
|
const userConfig = await loadCerConfig(root);
|
|
91
|
+
process.env.NODE_ENV = 'development';
|
|
92
|
+
process.env.MODE = 'development';
|
|
77
93
|
// CLI --mode flag overrides config file (mirrors build command behaviour)
|
|
78
94
|
if (options.mode) {
|
|
79
95
|
userConfig.mode = options.mode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../src/cli/commands/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAG9C;;;GAGG;AACH,KAAK,UAAU,aAAa,CAAC,IAAY;IACvC,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;IACjD,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;IAEnD,MAAM,QAAQ,GAAG,UAAU,CAAC,UAAU,CAAC;QACrC,CAAC,CAAC,UAAU;QACZ,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC;YACxB,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,IAAI,CAAA;IAEV,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAA;QACjE,OAAO,EAAE,CAAA;IACX,CAAC;IAED,IAAI,CAAC;QACH,yFAAyF;QACzF,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QACpC,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;QACpD,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YAC7B,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;YACtC,aAAa,CAAC,WAAW,EAAE,0BAA0B,EAAE,OAAO,CAAC,CAAA;QACjE,CAAC;QAED,qDAAqD;QACrD,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAA;
|
|
1
|
+
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../src/cli/commands/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAG9C;;;GAGG;AACH,KAAK,UAAU,aAAa,CAAC,IAAY;IACvC,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;IACjD,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;IAEnD,MAAM,QAAQ,GAAG,UAAU,CAAC,UAAU,CAAC;QACrC,CAAC,CAAC,UAAU;QACZ,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC;YACxB,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,IAAI,CAAA;IAEV,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAA;QACjE,OAAO,EAAE,CAAA;IACX,CAAC;IAED,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAA;QAC5C,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAA;QACrC,yFAAyF;QACzF,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QACpC,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;QACpD,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YAC7B,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;YACtC,aAAa,CAAC,WAAW,EAAE,0BAA0B,EAAE,OAAO,CAAC,CAAA;QACjE,CAAC;QAED,qDAAqD;QACrD,IAAI,CAAC;YACH,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAA;YACtC,MAAM,KAAK,CAAC;gBACV,KAAK,EAAE;oBACL,GAAG,EAAE;wBACH,KAAK,EAAE,QAAQ;wBACf,OAAO,EAAE,CAAC,IAAI,CAAC;wBACf,QAAQ,EAAE,YAAY;qBACvB;oBACD,MAAM,EAAE,OAAO,CAAC,IAAI,EAAE,6BAA6B,CAAC;oBACpD,KAAK,EAAE,IAAI;oBACX,aAAa,EAAE;wBACb,oEAAoE;wBACpE,QAAQ,EAAE,CAAC,EAAU,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC;qBACrE;iBACF;gBACD,QAAQ,EAAE,QAAQ;aACnB,CAAC,CAAA;QACJ,CAAC;gBAAS,CAAC;YACT,IAAI,OAAO,eAAe,KAAK,WAAW;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAA;;gBAClE,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,eAAe,CAAA;YAC3C,IAAI,OAAO,YAAY,KAAK,WAAW;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAA;;gBAC3D,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,YAAY,CAAA;QACtC,CAAC;QAED,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,4CAA4C,CAAC,CAAA;QAC3E,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACxB,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;YAC1E,OAAO,GAAG,CAAC,OAAO,IAAI,EAAE,CAAA;QAC1B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,0EAA0E,EAAE,GAAG,CAAC,CAAA;IAC/F,CAAC;IAED,sDAAsD;IACtD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;QAC3E,OAAO,GAAG,CAAC,OAAO,IAAI,EAAE,CAAA;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAA;IACX,CAAC;AACH,CAAC;AAED,MAAM,UAAU,UAAU;IACxB,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC;SACtB,WAAW,CAAC,8BAA8B,CAAC;SAC3C,MAAM,CAAC,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,CAAC;SACxD,MAAM,CAAC,eAAe,EAAE,iBAAiB,EAAE,WAAW,CAAC;SACvD,MAAM,CAAC,eAAe,EAAE,wBAAwB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC;SAChE,MAAM,CAAC,eAAe,EAAE,sDAAsD,CAAC;SAC/E,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;QACxB,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;QAClC,MAAM,UAAU,GAAG,MAAM,aAAa,CAAC,IAAI,CAAC,CAAA;QAC5C,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAA;QACpC,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,aAAa,CAAA;QAChC,0EAA0E;QAC1E,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;YACjB,UAAU,CAAC,IAAI,GAAG,OAAO,CAAC,IAA6B,CAAA;QACzD,CAAC;QACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,IAAI,IAAI,CAAC,CAAA;QAElF,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAA;QAE/C,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;YAChC,IAAI;YACJ,MAAM,EAAE;gBACN,IAAI;gBACJ,IAAI,EAAE,OAAO,CAAC,IAAI;aACnB;YACD,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;SAC5B,CAAC,CAAA;QAEF,MAAM,MAAM,CAAC,MAAM,EAAE,CAAA;QACrB,MAAM,CAAC,SAAS,EAAE,CAAA;QAElB,2BAA2B;QAC3B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,IAAI,EAAE;YAC/B,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;YACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjB,CAAC,CAAC,CAAA;QACF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;YAC9B,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;YACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjB,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACN,CAAC"}
|
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
* automatically receive the latest bootstrap code on plugin update.
|
|
6
6
|
* This file is gitignored and should never be edited directly.
|
|
7
7
|
*/
|
|
8
|
-
export declare const APP_ENTRY_TEMPLATE = "// AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app \u2014 do not edit.\n// Regenerated automatically on every dev server start and build.\n\nimport '@jasonshimmy/custom-elements-runtime/css'\nimport 'virtual:cer-jit-css'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport { hasLoading, loadingTag } from 'virtual:cer-loading'\nimport { hasError, errorTag } from 'virtual:cer-error'\nimport { runtimeConfig } from 'virtual:cer-app-config'\nimport {\n component,\n ref,\n provide,\n useOnConnected,\n useOnDisconnected,\n registerBuiltinComponents,\n} from '@jasonshimmy/custom-elements-runtime'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { enableJITCSS } from '@jasonshimmy/custom-elements-runtime/jit-css'\nimport { initRuntimeConfig } from '@jasonshimmy/vite-plugin-cer-app/composables'\n\nregisterBuiltinComponents()\nenableJITCSS()\ninitRuntimeConfig(runtimeConfig)\n\nconst router = initRouter({ routes })\n\n// Expose the router globally so useRoute() and navigateTo() can access it\n// from any composable without circular imports.\n;(globalThis).__cerRouter = router\n\n// \u2500\u2500\u2500 Page loader state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Holds the pre-loaded page tag and loader-derived attrs for the current route.\n// Set by _loadPageForPath before every navigation so cer-layout-view can render\n// the page element directly with the correct attributes (enabling useProps()).\nlet _currentPageTag = null\nlet _currentPageAttrs = {}\n// The pathname this tag was loaded for \u2014 used to detect router-internal\n// redirects (e.g. middleware returning '/login') so cer-layout-view falls\n// back to <router-view> when the current route differs from what was pre-loaded.\nlet _currentPagePath = null\n\nfunction _toLoaderAttrs(data) {\n if (data === undefined || data === null || typeof data !== 'object') return {}\n return Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n}\n\n// Pre-loads the page module for `path`, calls its loader if present, and\n// stores the results so cer-layout-view can pass them as element attributes.\nasync function _loadPageForPath(path, options = {}) {\n try {\n const url = new URL(path, 'http://x')\n const query = Object.fromEntries(url.searchParams)\n const { runLoader = true, initialData } = options ?? {}\n const matched = router.matchRoute(url.pathname)\n const route = matched?.route\n if (!route?.load) {\n _currentPageTag = null\n _currentPageAttrs = {}\n _currentPagePath = url.pathname\n return\n }\n const mod = await route.load()\n _currentPageTag = mod.default ?? null\n _currentPagePath = url.pathname\n const params = matched.params ?? {}\n let loaderAttrs = { ...params }\n let loaderData = initialData\n if (typeof mod.loader === 'function' && runLoader) {\n try {\n const data = await mod.loader({ params, query })\n if (data !== undefined && data !== null) {\n loaderData = data\n // Make loader data available via usePageData() for this navigation.\n ;(globalThis).__CER_DATA__ = data\n }\n } catch (err) {\n // Loader errors are surfaced through currentError so the error boundary\n // (app/error.ts) can display a meaningful message \u2014 consistent with how\n // the server-side handler behaves when a loader throws.\n currentError.value = err instanceof Error ? err.message : String(err)\n }\n }\n // For the very first hydration pass in SSR/SSG we already have the server's\n // loader payload in globalThis.__CER_DATA__ / window.__CER_DATA__. Reuse it\n // instead of re-running the loader on the client, then derive primitive attrs\n // from that payload so useProps() stays consistent with usePageData().\n loaderAttrs = { ...loaderAttrs, ..._toLoaderAttrs(loaderData) }\n _currentPageAttrs = loaderAttrs\n } catch {\n _currentPageTag = null\n _currentPageAttrs = {}\n _currentPagePath = null\n }\n}\n\n// \u2500\u2500\u2500 Navigation state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst isNavigating = ref(false)\nconst currentError = ref(null)\n\nconst resetError = () => {\n currentError.value = null\n void router.replace(router.getCurrent().path)\n}\n;(globalThis).resetError = resetError\n\nconst _push = router.push.bind(router)\nconst _replace = router.replace.bind(router)\n\nrouter.push = async (path) => {\n isNavigating.value = true\n currentError.value = null\n try {\n // Clear stale loader data from the previous route before loading the new one.\n // If the new route has no loader, __CER_DATA__ stays undefined so usePageData()\n // correctly returns null instead of leaking the previous page's data.\n delete (globalThis).__CER_DATA__\n await _loadPageForPath(path)\n await _push(path)\n } catch (err) {\n currentError.value = err instanceof Error ? err.message : String(err)\n } finally {\n isNavigating.value = false\n }\n}\n\nrouter.replace = async (path) => {\n isNavigating.value = true\n currentError.value = null\n try {\n // Clear stale loader data from the previous route before loading the new one.\n delete (globalThis).__CER_DATA__\n await _loadPageForPath(path)\n await _replace(path)\n } catch (err) {\n currentError.value = err instanceof Error ? err.message : String(err)\n } finally {\n isNavigating.value = false\n }\n}\n\n// \u2500\u2500\u2500 Plugins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Collect plugin-provided values so cer-layout-view can forward them into\n// the component context tree via the real provide() hook (which inject() walks).\n// Declared BEFORE component('cer-layout-view') to avoid a temporal dead zone\n// ReferenceError: customElements.define() upgrades existing DOM elements\n// synchronously, calling the render function immediately.\nconst _pluginProvides = new Map()\n// Expose plugin provides globally so page components can read them synchronously\n// regardless of render order.\n;(globalThis).__cerPluginProvides = _pluginProvides\n\n// \u2500\u2500\u2500 <cer-layout-view> \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// True until the initial page module has loaded and _replace has been called.\n// While true, cer-layout-view renders a <slot> so the SSR/SSG pre-rendered\n// light-DOM content stays visible and no FOUC occurs during the hydration gap.\n// Declared here (before component()) because customElements.define() upgrades\n// existing DOM elements synchronously, so the render function reads this ref\n// on the very first call \u2014 before _doHydrate has a chance to run.\nconst _cerHydrating = ref(true)\n\ncomponent('cer-layout-view', () => {\n // Forward plugin-provided values into the component context so inject() in\n // any descendant component can resolve them by walking up the DOM tree.\n for (const [key, value] of _pluginProvides) {\n provide(key, value)\n }\n\n const current = ref(router.getCurrent())\n let unsub\n let _sawInitialRouteState = false\n\n useOnConnected(() => {\n // store.subscribe() synchronously pushes the current route once on\n // subscription. That initial callback is not a real navigation and must not\n // tear down the SSR slot before _doHydrate has pre-loaded the page.\n // Subsequent callbacks are real navigations (including the initial _replace\n // in _doHydrate), so if they arrive during the hydration gap we drop the\n // slot immediately and let the live render take over.\n unsub = router.subscribe((s) => {\n const _isInitialSubscribePush = !_sawInitialRouteState\n _sawInitialRouteState = true\n if (_isInitialSubscribePush) {\n current.value = s\n return\n }\n if (_cerHydrating.value) _cerHydrating.value = false\n current.value = s\n })\n })\n useOnDisconnected(() => { unsub?.(); unsub = undefined })\n\n // While the initial page module is being loaded, keep the SSR/SSG\n // pre-rendered light-DOM content visible by forwarding it through a <slot>.\n // This prevents the intermediate blank state that occurs when the shadow DOM\n // renders layout-default with an empty <router-view> before the page chunk\n // has arrived. In SPA mode (no pre-rendered content) the slot is empty, which\n // is no worse than the current router-view behaviour.\n if (_cerHydrating.value) {\n return { tag: 'slot', props: {}, children: [] }\n }\n\n const matched = router.matchRoute(current.value.path)\n const routeMeta = matched?.route?.meta\n\n if (currentError.value !== null) {\n const routeErrorTag = routeMeta?.errorTag ?? null\n const effectiveErrorTag = routeErrorTag ?? (hasError ? errorTag : null)\n if (effectiveErrorTag) {\n return { tag: effectiveErrorTag, props: { attrs: { error: String(currentError.value) } }, children: [] }\n }\n return { tag: 'div', props: { attrs: { style: 'padding:2rem;font-family:monospace' } }, children: String(currentError.value) }\n }\n\n if (isNavigating.value && hasLoading && loadingTag) {\n return { tag: loadingTag, props: {}, children: [] }\n }\n\n // Render the page component directly when a pre-loaded tag is available AND\n // the loaded path matches the current route. The path guard detects\n // router-internal redirects (e.g. middleware returning '/login'): when the\n // router redirects to a different path, _currentPagePath won't match\n // current.value.path and we fall back to <router-view> so the correct page\n // is rendered without stale pre-loaded state.\n const _useDirectRender = _currentPageTag && _currentPagePath === current.value.path\n const pageVnode = _useDirectRender\n ? { tag: _currentPageTag, props: { attrs: _currentPageAttrs }, children: [] }\n : { tag: 'router-view', props: {}, children: [] }\n\n // Support nested layout chains: meta.layoutChain = ['default', 'admin']\n // renders <layout-default><layout-admin><page/></layout-admin></layout-default>\n const chain = routeMeta?.layoutChain\n ? routeMeta.layoutChain\n : [routeMeta?.layout ?? 'default']\n\n // Build nested vnodes 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 return vnode\n})\n\nfor (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router,\n provide: (key, value) => { _pluginProvides.set(key, value) },\n config: {},\n })\n }\n}\n\n// \u2500\u2500\u2500 Pre-load initial route + hydration strategy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Download the current page's route chunk AFTER plugins run so that\n// cer-layout-view's first render (which calls provide()) completes before\n// page components are defined and their renders are scheduled. This ensures\n// inject() in child components can find values stored by provide().\n//\n// meta.hydrate controls WHEN the initial page activates:\n// 'load' \u2014 immediately (default)\n// 'idle' \u2014 deferred until requestIdleCallback (browser idle)\n// 'visible' \u2014 deferred until cer-layout-view enters the viewport\n// 'none' \u2014 never: SSR HTML stays as-is, no JS activation\n\nif (typeof window !== 'undefined') {\n const _initMatch = router.matchRoute(window.location.pathname)\n const _hydrateStrategy = _initMatch?.route?.meta?.hydrate ?? 'load'\n\n if (_hydrateStrategy === 'none') {\n // Static HTML only \u2014 leave SSR output untouched, clean up data immediately.\n delete (globalThis).__CER_DATA__\n } else {\n const _doHydrate = async () => {\n const _initPath = window.location.pathname + window.location.search + window.location.hash\n const _hasInitialLoaderData = Object.prototype.hasOwnProperty.call(globalThis, '__CER_DATA__')\n // Pre-load the page module and run the loader so cer-layout-view renders\n // the page tag directly with loader attrs (enables useProps() on hydration).\n await _loadPageForPath(\n _initPath,\n _hasInitialLoaderData\n ? { runLoader: false, initialData: (globalThis).__CER_DATA__ }\n : undefined,\n )\n // Only activate the initial route if the URL hasn't changed while we were\n // loading the module asynchronously (e.g. a test or plugin navigated away\n // before _doHydrate finished). Calling _replace with a stale path would\n // override any navigation that happened during the async gap.\n const _currentPath = window.location.pathname + window.location.search + window.location.hash\n // Drop the hydration slot cover unconditionally: the page module is loaded\n // and cer-layout-view must switch from the <slot> to live rendering whether\n // or not a redirect changed the path during loading.\n _cerHydrating.value = false\n if (_currentPath === _initPath) {\n // Use the original (unwrapped) replace so isNavigating stays false during\n // the initial paint \u2014 the loading component must not flash over pre-rendered content.\n await _replace(_initPath)\n }\n // The client entry marks the already-rendered entry URL so generated\n // route middleware can skip the browser router's startup replay once.\n // Clear any leftover flag after the first hydrated route commits so later\n // navigations always run middleware normally.\n queueMicrotask(() => { delete (globalThis).__CER_HYDRATION_ENTRY__ })\n // Keep the initial route's SSR data available after hydration.\n // Browser engines do not all upgrade and re-render custom elements with\n // identical timing, so deleting __CER_DATA__ here can cause a later\n // hydration render to fall back to the client-only path. The next real\n // router.push/router.replace clears __CER_DATA__ before loading the new\n // route, so stale page data still does not leak across navigations.\n }\n\n if (_hydrateStrategy === 'idle') {\n // Defer until the browser has finished higher-priority work.\n if (typeof requestIdleCallback !== 'undefined') {\n requestIdleCallback(() => { void _doHydrate() })\n } else {\n // Safari / older environments fallback.\n setTimeout(() => { void _doHydrate() }, 1)\n }\n } else if (_hydrateStrategy === 'visible') {\n // Defer until cer-layout-view (or body as fallback) enters the viewport.\n const _el = document.querySelector('cer-layout-view') ?? document.body\n const _io = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) { _io.disconnect(); void _doHydrate() }\n })\n _io.observe(_el)\n } else {\n // 'load' \u2014 hydrate immediately (default behaviour).\n await _doHydrate()\n }\n }\n}\n\nexport { router }\n";
|
|
8
|
+
export declare const APP_ENTRY_TEMPLATE = "// AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app \u2014 do not edit.\n// Regenerated automatically on every dev server start and build.\n\nimport '@jasonshimmy/custom-elements-runtime/css'\nimport 'virtual:cer-jit-css'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport { hasLoading, loadingTag } from 'virtual:cer-loading'\nimport { hasError, errorTag } from 'virtual:cer-error'\nimport { runtimeConfig } from 'virtual:cer-app-config'\nimport {\n component,\n ref,\n provide,\n setDevMode,\n useOnConnected,\n useOnDisconnected,\n registerBuiltinComponents,\n} from '@jasonshimmy/custom-elements-runtime'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { enableJITCSS } from '@jasonshimmy/custom-elements-runtime/jit-css'\nimport { initRuntimeConfig } from '@jasonshimmy/vite-plugin-cer-app/composables'\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)\nenableJITCSS()\ninitRuntimeConfig(runtimeConfig)\n\nconst router = initRouter({ routes })\n\n// Expose the router globally so useRoute() and navigateTo() can access it\n// from any composable without circular imports.\n;(globalThis).__cerRouter = router\n\n// \u2500\u2500\u2500 Page loader state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Holds the pre-loaded page tag and loader-derived attrs for the current route.\n// Set by _loadPageForPath before every navigation so cer-layout-view can render\n// the page element directly with the correct attributes (enabling useProps()).\nlet _currentPageTag = null\nlet _currentPageAttrs = {}\n// The pathname this tag was loaded for \u2014 used to detect router-internal\n// redirects (e.g. middleware returning '/login') so cer-layout-view falls\n// back to <router-view> when the current route differs from what was pre-loaded.\nlet _currentPagePath = null\n\nfunction _toLoaderAttrs(data) {\n if (data === undefined || data === null || typeof data !== 'object') return {}\n return Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n}\n\n// Pre-loads the page module for `path`, calls its loader if present, and\n// stores the results so cer-layout-view can pass them as element attributes.\nasync function _loadPageForPath(path, options = {}) {\n try {\n const url = new URL(path, 'http://x')\n const query = Object.fromEntries(url.searchParams)\n const { runLoader = true, initialData } = options ?? {}\n const matched = router.matchRoute(url.pathname)\n const route = matched?.route\n if (!route?.load) {\n _currentPageTag = null\n _currentPageAttrs = {}\n _currentPagePath = url.pathname\n return\n }\n const mod = await route.load()\n _currentPageTag = mod.default ?? null\n _currentPagePath = url.pathname\n const params = matched.params ?? {}\n let loaderAttrs = { ...params }\n let loaderData = initialData\n if (typeof mod.loader === 'function' && runLoader) {\n try {\n const data = await mod.loader({ params, query })\n if (data !== undefined && data !== null) {\n loaderData = data\n // Make loader data available via usePageData() for this navigation.\n ;(globalThis).__CER_DATA__ = data\n }\n } catch (err) {\n // Loader errors are surfaced through currentError so the error boundary\n // (app/error.ts) can display a meaningful message \u2014 consistent with how\n // the server-side handler behaves when a loader throws.\n currentError.value = err instanceof Error ? err.message : String(err)\n }\n }\n // For the very first hydration pass in SSR/SSG we already have the server's\n // loader payload in globalThis.__CER_DATA__ / window.__CER_DATA__. Reuse it\n // instead of re-running the loader on the client, then derive primitive attrs\n // from that payload so useProps() stays consistent with usePageData().\n loaderAttrs = { ...loaderAttrs, ..._toLoaderAttrs(loaderData) }\n _currentPageAttrs = loaderAttrs\n } catch {\n _currentPageTag = null\n _currentPageAttrs = {}\n _currentPagePath = null\n }\n}\n\n// \u2500\u2500\u2500 Navigation state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst isNavigating = ref(false)\nconst currentError = ref(null)\n\nconst resetError = () => {\n currentError.value = null\n void router.replace(router.getCurrent().path)\n}\n;(globalThis).resetError = resetError\n\nconst _push = router.push.bind(router)\nconst _replace = router.replace.bind(router)\n\nrouter.push = async (path) => {\n isNavigating.value = true\n currentError.value = null\n try {\n // Clear stale loader data from the previous route before loading the new one.\n // If the new route has no loader, __CER_DATA__ stays undefined so usePageData()\n // correctly returns null instead of leaking the previous page's data.\n delete (globalThis).__CER_DATA__\n await _loadPageForPath(path)\n await _push(path)\n } catch (err) {\n currentError.value = err instanceof Error ? err.message : String(err)\n } finally {\n isNavigating.value = false\n }\n}\n\nrouter.replace = async (path) => {\n isNavigating.value = true\n currentError.value = null\n try {\n // Clear stale loader data from the previous route before loading the new one.\n delete (globalThis).__CER_DATA__\n await _loadPageForPath(path)\n await _replace(path)\n } catch (err) {\n currentError.value = err instanceof Error ? err.message : String(err)\n } finally {\n isNavigating.value = false\n }\n}\n\n// \u2500\u2500\u2500 Plugins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Collect plugin-provided values so cer-layout-view can forward them into\n// the component context tree via the real provide() hook (which inject() walks).\n// Declared BEFORE component('cer-layout-view') to avoid a temporal dead zone\n// ReferenceError: customElements.define() upgrades existing DOM elements\n// synchronously, calling the render function immediately.\nconst _pluginProvides = new Map()\n// Expose plugin provides globally so page components can read them synchronously\n// regardless of render order.\n;(globalThis).__cerPluginProvides = _pluginProvides\n\n// \u2500\u2500\u2500 <cer-layout-view> \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// True until the initial page module has loaded and _replace has been called.\n// While true, cer-layout-view renders a <slot> so the SSR/SSG pre-rendered\n// light-DOM content stays visible and no FOUC occurs during the hydration gap.\n// Declared here (before component()) because customElements.define() upgrades\n// existing DOM elements synchronously, so the render function reads this ref\n// on the very first call \u2014 before _doHydrate has a chance to run.\nconst _cerHydrating = ref(true)\n\ncomponent('cer-layout-view', () => {\n // Forward plugin-provided values into the component context so inject() in\n // any descendant component can resolve them by walking up the DOM tree.\n for (const [key, value] of _pluginProvides) {\n provide(key, value)\n }\n\n const current = ref(router.getCurrent())\n let unsub\n let _sawInitialRouteState = false\n\n useOnConnected(() => {\n // store.subscribe() synchronously pushes the current route once on\n // subscription. That initial callback is not a real navigation and must not\n // tear down the SSR slot before _doHydrate has pre-loaded the page.\n // Subsequent callbacks are real navigations (including the initial _replace\n // in _doHydrate), so if they arrive during the hydration gap we drop the\n // slot immediately and let the live render take over.\n unsub = router.subscribe((s) => {\n const _isInitialSubscribePush = !_sawInitialRouteState\n _sawInitialRouteState = true\n if (_isInitialSubscribePush) {\n current.value = s\n return\n }\n if (_cerHydrating.value) _cerHydrating.value = false\n current.value = s\n })\n })\n useOnDisconnected(() => { unsub?.(); unsub = undefined })\n\n // While the initial page module is being loaded, keep the SSR/SSG\n // pre-rendered light-DOM content visible by forwarding it through a <slot>.\n // This prevents the intermediate blank state that occurs when the shadow DOM\n // renders layout-default with an empty <router-view> before the page chunk\n // has arrived. In SPA mode (no pre-rendered content) the slot is empty, which\n // is no worse than the current router-view behaviour.\n if (_cerHydrating.value) {\n return { tag: 'slot', props: {}, children: [] }\n }\n\n const matched = router.matchRoute(current.value.path)\n const routeMeta = matched?.route?.meta\n\n if (currentError.value !== null) {\n const routeErrorTag = routeMeta?.errorTag ?? null\n const effectiveErrorTag = routeErrorTag ?? (hasError ? errorTag : null)\n if (effectiveErrorTag) {\n return { tag: effectiveErrorTag, props: { attrs: { error: String(currentError.value) } }, children: [] }\n }\n return { tag: 'div', props: { attrs: { style: 'padding:2rem;font-family:monospace' } }, children: String(currentError.value) }\n }\n\n if (isNavigating.value && hasLoading && loadingTag) {\n return { tag: loadingTag, props: {}, children: [] }\n }\n\n // Render the page component directly when a pre-loaded tag is available AND\n // the loaded path matches the current route. The path guard detects\n // router-internal redirects (e.g. middleware returning '/login'): when the\n // router redirects to a different path, _currentPagePath won't match\n // current.value.path and we fall back to <router-view> so the correct page\n // is rendered without stale pre-loaded state.\n const _useDirectRender = _currentPageTag && _currentPagePath === current.value.path\n const pageVnode = _useDirectRender\n ? { tag: _currentPageTag, props: { attrs: _currentPageAttrs }, children: [] }\n : { tag: 'router-view', props: {}, children: [] }\n\n // Support nested layout chains: meta.layoutChain = ['default', 'admin']\n // renders <layout-default><layout-admin><page/></layout-admin></layout-default>\n const chain = routeMeta?.layoutChain\n ? routeMeta.layoutChain\n : [routeMeta?.layout ?? 'default']\n\n // Build nested vnodes 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 return vnode\n})\n\nfor (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router,\n provide: (key, value) => { _pluginProvides.set(key, value) },\n config: {},\n })\n }\n}\n\n// \u2500\u2500\u2500 Pre-load initial route + hydration strategy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Download the current page's route chunk AFTER plugins run so that\n// cer-layout-view's first render (which calls provide()) completes before\n// page components are defined and their renders are scheduled. This ensures\n// inject() in child components can find values stored by provide().\n//\n// meta.hydrate controls WHEN the initial page activates:\n// 'load' \u2014 immediately (default)\n// 'idle' \u2014 deferred until requestIdleCallback (browser idle)\n// 'visible' \u2014 deferred until cer-layout-view enters the viewport\n// 'none' \u2014 never: SSR HTML stays as-is, no JS activation\n\nif (typeof window !== 'undefined') {\n const _initMatch = router.matchRoute(window.location.pathname)\n const _hydrateStrategy = _initMatch?.route?.meta?.hydrate ?? 'load'\n\n if (_hydrateStrategy === 'none') {\n // Static HTML only \u2014 leave SSR output untouched, clean up data immediately.\n delete (globalThis).__CER_DATA__\n } else {\n const _doHydrate = async () => {\n const _initPath = window.location.pathname + window.location.search + window.location.hash\n const _hasInitialLoaderData = Object.prototype.hasOwnProperty.call(globalThis, '__CER_DATA__')\n // Pre-load the page module and run the loader so cer-layout-view renders\n // the page tag directly with loader attrs (enables useProps() on hydration).\n await _loadPageForPath(\n _initPath,\n _hasInitialLoaderData\n ? { runLoader: false, initialData: (globalThis).__CER_DATA__ }\n : undefined,\n )\n // Only activate the initial route if the URL hasn't changed while we were\n // loading the module asynchronously (e.g. a test or plugin navigated away\n // before _doHydrate finished). Calling _replace with a stale path would\n // override any navigation that happened during the async gap.\n const _currentPath = window.location.pathname + window.location.search + window.location.hash\n // Drop the hydration slot cover unconditionally: the page module is loaded\n // and cer-layout-view must switch from the <slot> to live rendering whether\n // or not a redirect changed the path during loading.\n _cerHydrating.value = false\n if (_currentPath === _initPath) {\n // Use the original (unwrapped) replace so isNavigating stays false during\n // the initial paint \u2014 the loading component must not flash over pre-rendered content.\n await _replace(_initPath)\n }\n // The client entry marks the already-rendered entry URL so generated\n // route middleware can skip the browser router's startup replay once.\n // Clear any leftover flag after the first hydrated route commits so later\n // navigations always run middleware normally.\n queueMicrotask(() => { delete (globalThis).__CER_HYDRATION_ENTRY__ })\n // Keep the initial route's SSR data available after hydration.\n // Browser engines do not all upgrade and re-render custom elements with\n // identical timing, so deleting __CER_DATA__ here can cause a later\n // hydration render to fall back to the client-only path. The next real\n // router.push/router.replace clears __CER_DATA__ before loading the new\n // route, so stale page data still does not leak across navigations.\n }\n\n if (_hydrateStrategy === 'idle') {\n // Defer until the browser has finished higher-priority work.\n if (typeof requestIdleCallback !== 'undefined') {\n requestIdleCallback(() => { void _doHydrate() })\n } else {\n // Safari / older environments fallback.\n setTimeout(() => { void _doHydrate() }, 1)\n }\n } else if (_hydrateStrategy === 'visible') {\n // Defer until cer-layout-view (or body as fallback) enters the viewport.\n const _el = document.querySelector('cer-layout-view') ?? document.body\n const _io = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) { _io.disconnect(); void _doHydrate() }\n })\n _io.observe(_el)\n } else {\n // 'load' \u2014 hydrate immediately (default behaviour).\n await _doHydrate()\n }\n }\n}\n\nexport { router }\n";
|
|
9
9
|
//# sourceMappingURL=app-template.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-template.d.ts","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,
|
|
1
|
+
{"version":3,"file":"app-template.d.ts","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,qrhBAuW9B,CAAA"}
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
component,
|
|
21
21
|
ref,
|
|
22
22
|
provide,
|
|
23
|
+
setDevMode,
|
|
23
24
|
useOnConnected,
|
|
24
25
|
useOnDisconnected,
|
|
25
26
|
registerBuiltinComponents,
|
|
@@ -28,7 +29,22 @@ import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
|
|
|
28
29
|
import { enableJITCSS } from '@jasonshimmy/custom-elements-runtime/jit-css'
|
|
29
30
|
import { initRuntimeConfig } from '@jasonshimmy/vite-plugin-cer-app/composables'
|
|
30
31
|
|
|
32
|
+
const _cerProcess = (globalThis).process
|
|
33
|
+
const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
|
|
34
|
+
const _cerRuntimeDev =
|
|
35
|
+
typeof _cerNodeEnv === 'string'
|
|
36
|
+
? _cerNodeEnv !== 'production'
|
|
37
|
+
: typeof import.meta.env?.DEV === 'boolean'
|
|
38
|
+
? import.meta.env.DEV
|
|
39
|
+
: typeof import.meta.env?.PROD === 'boolean'
|
|
40
|
+
? !import.meta.env.PROD
|
|
41
|
+
: typeof import.meta.env?.MODE === 'string'
|
|
42
|
+
? import.meta.env.MODE !== 'production'
|
|
43
|
+
: false
|
|
44
|
+
;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
|
|
45
|
+
|
|
31
46
|
registerBuiltinComponents()
|
|
47
|
+
setDevMode(_cerRuntimeDev)
|
|
32
48
|
enableJITCSS()
|
|
33
49
|
initRuntimeConfig(runtimeConfig)
|
|
34
50
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-template.js","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG
|
|
1
|
+
{"version":3,"file":"app-template.js","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuWjC,CAAA"}
|
|
@@ -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 } 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\nregisterBuiltinComponents()\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 — decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (<, >, & \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 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 — decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (<, >, & \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,
|
|
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"}
|
|
@@ -22,7 +22,7 @@ import plugins from 'virtual:cer-plugins'
|
|
|
22
22
|
import apiRoutes from 'virtual:cer-server-api'
|
|
23
23
|
import serverMiddleware from 'virtual:cer-server-middleware'
|
|
24
24
|
import { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'
|
|
25
|
-
import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
|
|
25
|
+
import { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'
|
|
26
26
|
import { registerEntityMap, renderToStreamWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
|
|
27
27
|
import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
|
|
28
28
|
import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
|
|
@@ -30,7 +30,22 @@ import { beginHeadCollection, endHeadCollection, serializeHeadTags, initRuntimeC
|
|
|
30
30
|
import { errorTag } from 'virtual:cer-error'
|
|
31
31
|
import { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'
|
|
32
32
|
|
|
33
|
+
const _cerProcess = (globalThis).process
|
|
34
|
+
const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
|
|
35
|
+
const _cerRuntimeDev =
|
|
36
|
+
typeof _cerNodeEnv === 'string'
|
|
37
|
+
? _cerNodeEnv !== 'production'
|
|
38
|
+
: typeof import.meta.env?.DEV === 'boolean'
|
|
39
|
+
? import.meta.env.DEV
|
|
40
|
+
: typeof import.meta.env?.PROD === 'boolean'
|
|
41
|
+
? !import.meta.env.PROD
|
|
42
|
+
: typeof import.meta.env?.MODE === 'string'
|
|
43
|
+
? import.meta.env.MODE !== 'production'
|
|
44
|
+
: false
|
|
45
|
+
;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
|
|
46
|
+
|
|
33
47
|
registerBuiltinComponents()
|
|
48
|
+
setDevMode(_cerRuntimeDev)
|
|
34
49
|
|
|
35
50
|
// Resolve private config from environment variables at server startup.
|
|
36
51
|
// Each key declared in runtimeConfig.private is looked up in process.env,
|
|
@@ -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
|
|
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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jasonshimmy/vite-plugin-cer-app",
|
|
3
|
-
"version": "0.21.
|
|
3
|
+
"version": "0.21.2",
|
|
4
4
|
"description": "Nuxt-style meta-framework for @jasonshimmy/custom-elements-runtime",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"pathe": "^2.0.3"
|
|
99
99
|
},
|
|
100
100
|
"devDependencies": {
|
|
101
|
-
"@jasonshimmy/custom-elements-runtime": "^3.7.
|
|
101
|
+
"@jasonshimmy/custom-elements-runtime": "^3.7.5",
|
|
102
102
|
"@types/node": "^25.6.0",
|
|
103
103
|
"@vitest/coverage-v8": "^4.1.2",
|
|
104
104
|
"cypress": "^15.13.1",
|
|
@@ -107,7 +107,7 @@
|
|
|
107
107
|
"jiti": "^2.6.1",
|
|
108
108
|
"start-server-and-test": "^3.0.2",
|
|
109
109
|
"typescript": "^5.9.3",
|
|
110
|
-
"typescript-eslint": "^8.58.
|
|
110
|
+
"typescript-eslint": "^8.58.2",
|
|
111
111
|
"vite": "^8.0.8",
|
|
112
112
|
"vitest": "^4.1.0"
|
|
113
113
|
},
|
|
@@ -26,9 +26,18 @@ describe('app-template (APP_ENTRY_TEMPLATE content)', () => {
|
|
|
26
26
|
|
|
27
27
|
it('imports registerBuiltinComponents from custom-elements-runtime', () => {
|
|
28
28
|
expect(src).toContain('registerBuiltinComponents')
|
|
29
|
+
expect(src).toContain('setDevMode')
|
|
29
30
|
expect(src).toContain('@jasonshimmy/custom-elements-runtime')
|
|
30
31
|
})
|
|
31
32
|
|
|
33
|
+
it('enables runtime dev logging from the downstream Vite env', () => {
|
|
34
|
+
expect(src).toContain('const _cerRuntimeDev')
|
|
35
|
+
expect(src).toContain('import.meta.env?.DEV')
|
|
36
|
+
expect(src).toContain('_cerProcess?.env')
|
|
37
|
+
expect(src).toContain('(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev')
|
|
38
|
+
expect(src).toContain('setDevMode(_cerRuntimeDev)')
|
|
39
|
+
})
|
|
40
|
+
|
|
32
41
|
it('imports initRouter from the router subpath', () => {
|
|
33
42
|
expect(src).toContain('initRouter')
|
|
34
43
|
expect(src).toContain('custom-elements-runtime/router')
|
|
@@ -30,9 +30,18 @@ describe('entry-server-template (ENTRY_SERVER_TEMPLATE content)', () => {
|
|
|
30
30
|
|
|
31
31
|
it('imports registerBuiltinComponents from custom-elements-runtime', () => {
|
|
32
32
|
expect(src).toContain('registerBuiltinComponents')
|
|
33
|
+
expect(src).toContain('setDevMode')
|
|
33
34
|
expect(src).toContain('@jasonshimmy/custom-elements-runtime')
|
|
34
35
|
})
|
|
35
36
|
|
|
37
|
+
it('enables runtime dev logging from the downstream server env', () => {
|
|
38
|
+
expect(src).toContain('const _cerRuntimeDev')
|
|
39
|
+
expect(src).toContain('import.meta.env?.DEV')
|
|
40
|
+
expect(src).toContain('_cerProcess?.env')
|
|
41
|
+
expect(src).toContain('(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev')
|
|
42
|
+
expect(src).toContain('setDevMode(_cerRuntimeDev)')
|
|
43
|
+
})
|
|
44
|
+
|
|
36
45
|
it('imports renderToStreamWithJITCSSDSD and DSD_POLYFILL_SCRIPT from ssr subpath', () => {
|
|
37
46
|
expect(src).toContain('renderToStreamWithJITCSSDSD')
|
|
38
47
|
expect(src).toContain('DSD_POLYFILL_SCRIPT')
|
package/src/cli/commands/dev.ts
CHANGED
|
@@ -26,6 +26,8 @@ async function loadCerConfig(root: string): Promise<CerAppConfig> {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
try {
|
|
29
|
+
const originalNodeEnv = process.env.NODE_ENV
|
|
30
|
+
const originalMode = process.env.MODE
|
|
29
31
|
// Bootstrap .cer/tsconfig.json so rolldown can resolve it during cer.config.ts transform
|
|
30
32
|
const cerDir = resolve(root, '.cer')
|
|
31
33
|
const cerTsconfig = resolve(cerDir, 'tsconfig.json')
|
|
@@ -35,23 +37,30 @@ async function loadCerConfig(root: string): Promise<CerAppConfig> {
|
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
// Use Vite's build to transpile TS config at runtime
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
build
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
40
|
+
try {
|
|
41
|
+
const { build } = await import('vite')
|
|
42
|
+
await build({
|
|
43
|
+
build: {
|
|
44
|
+
lib: {
|
|
45
|
+
entry: filePath,
|
|
46
|
+
formats: ['es'],
|
|
47
|
+
fileName: 'cer.config',
|
|
48
|
+
},
|
|
49
|
+
outDir: resolve(root, 'node_modules/.cer-app-cache'),
|
|
50
|
+
write: true,
|
|
51
|
+
rollupOptions: {
|
|
52
|
+
// Externalize all bare package imports (handles file: symlinks too)
|
|
53
|
+
external: (id: string) => !id.startsWith('.') && !id.startsWith('/'),
|
|
54
|
+
},
|
|
45
55
|
},
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
})
|
|
56
|
+
logLevel: 'silent',
|
|
57
|
+
})
|
|
58
|
+
} finally {
|
|
59
|
+
if (typeof originalNodeEnv === 'undefined') delete process.env.NODE_ENV
|
|
60
|
+
else process.env.NODE_ENV = originalNodeEnv
|
|
61
|
+
if (typeof originalMode === 'undefined') delete process.env.MODE
|
|
62
|
+
else process.env.MODE = originalMode
|
|
63
|
+
}
|
|
55
64
|
|
|
56
65
|
const outFile = resolve(root, 'node_modules/.cer-app-cache/cer.config.mjs')
|
|
57
66
|
if (existsSync(outFile)) {
|
|
@@ -81,6 +90,8 @@ export function devCommand(): Command {
|
|
|
81
90
|
.action(async (options) => {
|
|
82
91
|
const root = resolve(options.root)
|
|
83
92
|
const userConfig = await loadCerConfig(root)
|
|
93
|
+
process.env.NODE_ENV = 'development'
|
|
94
|
+
process.env.MODE = 'development'
|
|
84
95
|
// CLI --mode flag overrides config file (mirrors build command behaviour)
|
|
85
96
|
if (options.mode) {
|
|
86
97
|
userConfig.mode = options.mode as 'spa' | 'ssr' | 'ssg'
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
component,
|
|
21
21
|
ref,
|
|
22
22
|
provide,
|
|
23
|
+
setDevMode,
|
|
23
24
|
useOnConnected,
|
|
24
25
|
useOnDisconnected,
|
|
25
26
|
registerBuiltinComponents,
|
|
@@ -28,7 +29,22 @@ import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
|
|
|
28
29
|
import { enableJITCSS } from '@jasonshimmy/custom-elements-runtime/jit-css'
|
|
29
30
|
import { initRuntimeConfig } from '@jasonshimmy/vite-plugin-cer-app/composables'
|
|
30
31
|
|
|
32
|
+
const _cerProcess = (globalThis).process
|
|
33
|
+
const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
|
|
34
|
+
const _cerRuntimeDev =
|
|
35
|
+
typeof _cerNodeEnv === 'string'
|
|
36
|
+
? _cerNodeEnv !== 'production'
|
|
37
|
+
: typeof import.meta.env?.DEV === 'boolean'
|
|
38
|
+
? import.meta.env.DEV
|
|
39
|
+
: typeof import.meta.env?.PROD === 'boolean'
|
|
40
|
+
? !import.meta.env.PROD
|
|
41
|
+
: typeof import.meta.env?.MODE === 'string'
|
|
42
|
+
? import.meta.env.MODE !== 'production'
|
|
43
|
+
: false
|
|
44
|
+
;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
|
|
45
|
+
|
|
31
46
|
registerBuiltinComponents()
|
|
47
|
+
setDevMode(_cerRuntimeDev)
|
|
32
48
|
enableJITCSS()
|
|
33
49
|
initRuntimeConfig(runtimeConfig)
|
|
34
50
|
|
|
@@ -22,7 +22,7 @@ import plugins from 'virtual:cer-plugins'
|
|
|
22
22
|
import apiRoutes from 'virtual:cer-server-api'
|
|
23
23
|
import serverMiddleware from 'virtual:cer-server-middleware'
|
|
24
24
|
import { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'
|
|
25
|
-
import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
|
|
25
|
+
import { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'
|
|
26
26
|
import { registerEntityMap, renderToStreamWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
|
|
27
27
|
import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
|
|
28
28
|
import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
|
|
@@ -30,7 +30,22 @@ import { beginHeadCollection, endHeadCollection, serializeHeadTags, initRuntimeC
|
|
|
30
30
|
import { errorTag } from 'virtual:cer-error'
|
|
31
31
|
import { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'
|
|
32
32
|
|
|
33
|
+
const _cerProcess = (globalThis).process
|
|
34
|
+
const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
|
|
35
|
+
const _cerRuntimeDev =
|
|
36
|
+
typeof _cerNodeEnv === 'string'
|
|
37
|
+
? _cerNodeEnv !== 'production'
|
|
38
|
+
: typeof import.meta.env?.DEV === 'boolean'
|
|
39
|
+
? import.meta.env.DEV
|
|
40
|
+
: typeof import.meta.env?.PROD === 'boolean'
|
|
41
|
+
? !import.meta.env.PROD
|
|
42
|
+
: typeof import.meta.env?.MODE === 'string'
|
|
43
|
+
? import.meta.env.MODE !== 'production'
|
|
44
|
+
: false
|
|
45
|
+
;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
|
|
46
|
+
|
|
33
47
|
registerBuiltinComponents()
|
|
48
|
+
setDevMode(_cerRuntimeDev)
|
|
34
49
|
|
|
35
50
|
// Resolve private config from environment variables at server startup.
|
|
36
51
|
// Each key declared in runtimeConfig.private is looked up in process.env,
|