@analogjs/platform 3.0.0-beta.4 → 3.0.0-beta.41
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/package.json +12 -9
- package/src/lib/content-plugin.js +12 -3
- package/src/lib/content-plugin.js.map +1 -1
- package/src/lib/deps-plugin.d.ts +1 -1
- package/src/lib/deps-plugin.js +11 -7
- package/src/lib/deps-plugin.js.map +1 -1
- package/src/lib/get-page-endpoints.d.ts +25 -0
- package/src/lib/get-page-endpoints.js +29 -0
- package/src/lib/get-page-endpoints.js.map +1 -0
- package/src/lib/nitro/analog-nitro-plugin.d.ts +6 -6
- package/src/lib/nitro/analog-nitro-plugin.js +115 -46
- package/src/lib/nitro/analog-nitro-plugin.js.map +1 -1
- package/src/lib/nitro/angular-linker-plugin.d.ts +4 -2
- package/src/lib/nitro/angular-linker-plugin.js +24 -38
- package/src/lib/nitro/angular-linker-plugin.js.map +1 -1
- package/src/lib/nitro/build-sitemap.js +2 -2
- package/src/lib/nitro/build-sitemap.js.map +1 -1
- package/src/lib/nitro/get-page-handlers.d.ts +4 -19
- package/src/lib/nitro/get-page-handlers.js +9 -26
- package/src/lib/nitro/get-page-handlers.js.map +1 -1
- package/src/lib/nitro/server-fn-endpoints.d.ts +3 -1
- package/src/lib/nitro/server-fn-endpoints.js +14 -5
- package/src/lib/nitro/server-fn-endpoints.js.map +1 -1
- package/src/lib/nx-plugin/executors.json +0 -7
- package/src/lib/nx-plugin/src/generators/app/compat.d.ts +2 -1
- package/src/lib/nx-plugin/src/generators/app/compat.js +4 -1
- package/src/lib/nx-plugin/src/generators/app/compat.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/app/generator.js +7 -2
- package/src/lib/nx-plugin/src/generators/app/generator.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js +2 -2
- package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.d.ts +3 -1
- package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js +5 -1
- package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/init/compat.d.ts +2 -1
- package/src/lib/nx-plugin/src/generators/init/compat.js +4 -1
- package/src/lib/nx-plugin/src/generators/init/compat.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js +2 -2
- package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/page/compat.d.ts +2 -1
- package/src/lib/nx-plugin/src/generators/page/compat.js +4 -1
- package/src/lib/nx-plugin/src/generators/page/compat.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/preset/__snapshots__/generator.spec.ts.snap +4 -0
- package/src/lib/nx-plugin/src/generators/preset/generator.js +5 -2
- package/src/lib/nx-plugin/src/generators/preset/generator.js.map +1 -1
- package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.d.ts +2 -2
- package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js +7 -3
- package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js.map +1 -1
- package/src/lib/nx-plugin/src/utils/versions/versions.d.ts +9 -6
- package/src/lib/nx-plugin/src/utils/versions/versions.js +13 -7
- package/src/lib/nx-plugin/src/utils/versions/versions.js.map +1 -1
- package/src/lib/options.d.ts +16 -0
- package/src/lib/platform-plugin.js +2 -0
- package/src/lib/platform-plugin.js.map +1 -1
- package/src/lib/route-idiom-diagnostics.js +23 -8
- package/src/lib/route-idiom-diagnostics.js.map +1 -1
- package/src/lib/router-plugin.js +1 -1
- package/src/lib/router-plugin.js.map +1 -1
- package/src/lib/server-plugin.d.ts +9 -0
- package/src/lib/server-plugin.js +170 -0
- package/src/lib/server-plugin.js.map +1 -0
- package/src/lib/typed-routes-plugin.js +5 -4
- package/src/lib/typed-routes-plugin.js.map +1 -1
- package/src/server-mode-plugin.js +1 -0
- package/src/server-mode-plugin.js.map +1 -1
- package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.d.ts +0 -3
- package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js +0 -7
- package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js.map +0 -1
- package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.d.ts +0 -1
- package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.json +0 -101
- package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.d.ts +0 -2
- package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js +0 -6
- package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@analogjs/platform",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.41",
|
|
4
4
|
"description": "The fullstack meta-framework for Angular",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"author": "Brandon Roberts <robertsbt@gmail.com>",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"url": "https://github.com/sponsors/brandonroberts"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@analogjs/vite-plugin-angular": "3.0.0-beta.
|
|
34
|
+
"@analogjs/vite-plugin-angular": "3.0.0-beta.41",
|
|
35
35
|
"es-toolkit": "^1.45.1",
|
|
36
36
|
"front-matter": "^4.0.2",
|
|
37
37
|
"magic-string": "^0.30.21",
|
|
@@ -39,25 +39,28 @@
|
|
|
39
39
|
"ofetch": "2.0.0-alpha.3",
|
|
40
40
|
"oxc-parser": "^0.124.0",
|
|
41
41
|
"rolldown": "^1.0.0-rc.13",
|
|
42
|
+
"srvx": "^1.0.8",
|
|
42
43
|
"tinyglobby": "^0.2.15",
|
|
43
44
|
"vitefu": "^1.1.2",
|
|
44
45
|
"xmlbuilder2": "^4.0.3"
|
|
45
46
|
},
|
|
46
47
|
"devDependencies": {
|
|
47
|
-
"@
|
|
48
|
-
"
|
|
49
|
-
"
|
|
48
|
+
"@nx/angular": "24.0.0",
|
|
49
|
+
"@nx/devkit": "24.0.0",
|
|
50
|
+
"@nx/vite": "24.0.0",
|
|
51
|
+
"h3": "^2.0.8",
|
|
52
|
+
"nitro": "3.0.261103-rc"
|
|
50
53
|
},
|
|
51
54
|
"peerDependencies": {
|
|
52
|
-
"@nx/angular": "^
|
|
53
|
-
"@nx/devkit": "^
|
|
54
|
-
"@nx/vite": "^
|
|
55
|
+
"@nx/angular": "^21.2.0 || ^22.0.0 || ^23.0.0 || ^24.0.0",
|
|
56
|
+
"@nx/devkit": "^21.2.0 || ^22.0.0 || ^23.0.0 || ^24.0.0",
|
|
57
|
+
"@nx/vite": "^21.2.0 || ^22.0.0 || ^23.0.0 || ^24.0.0",
|
|
55
58
|
"marked": "^18.0.0",
|
|
56
59
|
"marked-gfm-heading-id": "^4.1.3",
|
|
57
60
|
"marked-highlight": "^2.2.3",
|
|
58
61
|
"marked-mangle": "^1.1.12",
|
|
59
62
|
"marked-shiki": "^1.2.1",
|
|
60
|
-
"nitro": "3.0.
|
|
63
|
+
"nitro": "3.0.261103-rc",
|
|
61
64
|
"shiki": "^1.29.2 || ^4.0.2",
|
|
62
65
|
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
|
63
66
|
},
|
|
@@ -4,6 +4,12 @@ import { readFileSync } from "node:fs";
|
|
|
4
4
|
import * as vite from "vite";
|
|
5
5
|
import { globSync } from "tinyglobby";
|
|
6
6
|
//#region packages/platform/src/lib/content-plugin.ts
|
|
7
|
+
function toModuleValue(value) {
|
|
8
|
+
if (value instanceof Date) return `new Date(${JSON.stringify(value.toISOString())})`;
|
|
9
|
+
if (Array.isArray(value)) return `[${value.map(toModuleValue).join(",")}]`;
|
|
10
|
+
if (value && typeof value === "object") return `{${Object.entries(value).map(([key, entry]) => `${JSON.stringify(key)}:${toModuleValue(entry)}`).join(",")}}`;
|
|
11
|
+
return JSON.stringify(value) ?? "undefined";
|
|
12
|
+
}
|
|
7
13
|
/**
|
|
8
14
|
* Content plugin that provides markdown and content file processing for Analog.
|
|
9
15
|
*
|
|
@@ -30,7 +36,10 @@ function contentPlugin({ highlighter, markedOptions, shikiOptions, prismOptions
|
|
|
30
36
|
contentRootDirs = [vite.normalizePath(`${root}/src/content`), ...(options?.additionalContentDirs || []).map(normalizeContentDir)];
|
|
31
37
|
};
|
|
32
38
|
const discoverContentFilesList = () => {
|
|
33
|
-
contentFilesListCache ??= globSync(contentRootDirs.map((dir) => `${dir}/**/*.md`), {
|
|
39
|
+
contentFilesListCache ??= globSync(contentRootDirs.map((dir) => `${dir}/**/*.md`), {
|
|
40
|
+
dot: true,
|
|
41
|
+
cwd: workspaceRoot
|
|
42
|
+
});
|
|
34
43
|
return contentFilesListCache;
|
|
35
44
|
};
|
|
36
45
|
const resolveContentModulePath = (module) => vite.normalizePath(module.startsWith("/") ? module : `${workspaceRoot}/${module}`);
|
|
@@ -167,13 +176,13 @@ function contentPlugin({ highlighter, markedOptions, shikiOptions, prismOptions
|
|
|
167
176
|
}
|
|
168
177
|
}
|
|
169
178
|
const fm = await import("front-matter");
|
|
170
|
-
const { body,
|
|
179
|
+
const { body, attributes } = (fm.default || fm)(readFileSync(id.split("?")[0], "utf8"));
|
|
171
180
|
const { getMarkedSetup } = await import("./content/marked/index.js");
|
|
172
181
|
const mdContent = await getMarkedSetup({
|
|
173
182
|
mangle: true,
|
|
174
183
|
...markedOptions || {}
|
|
175
184
|
}, markedHighlighter).getMarkedInstance().parse(body);
|
|
176
|
-
return `export default ${JSON.stringify(
|
|
185
|
+
return `export default ${JSON.stringify(mdContent)};\nexport const metadata = ${toModuleValue(attributes)};`;
|
|
177
186
|
}
|
|
178
187
|
},
|
|
179
188
|
...contentDiscoveryPlugins
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content-plugin.js","names":[],"sources":["../../../src/lib/content-plugin.ts"],"sourcesContent":["import * as vite from 'vite';\nimport { readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport type { WithShikiHighlighterOptions } from './content/shiki/options.js';\nimport type { MarkedContentHighlighter } from './content/marked/marked-content-highlighter.js';\nimport type { WithPrismHighlighterOptions } from './content/prism/options.js';\nimport type { WithMarkedOptions } from './content/marked/index.js';\nimport type { Options } from './options.js';\nimport { getBundleOptionsKey } from './utils/rolldown.js';\n\ninterface Content {\n code: string;\n attributes: string;\n}\n\nexport type ContentPluginOptions = {\n highlighter?: 'shiki' | 'prism';\n markedOptions?: WithMarkedOptions;\n shikiOptions?: WithShikiHighlighterOptions;\n prismOptions?: WithPrismHighlighterOptions;\n};\n\n/**\n * Content plugin that provides markdown and content file processing for Analog.\n *\n * IMPORTANT: This plugin uses tinyglobby for file discovery.\n * Key pitfall with { dot: true }:\n * - Returns relative paths from cwd (e.g., \"apps/blog-app/src/content/...\")\n * - These paths CANNOT be used directly in ES module imports\n * - Relative paths without ./ or ../ are treated as package names\n * - Must convert to absolute paths for imports to work correctly\n */\nexport function contentPlugin(\n {\n highlighter,\n markedOptions,\n shikiOptions,\n prismOptions,\n }: ContentPluginOptions = {},\n options?: Options,\n): vite.Plugin[] {\n const cache = new Map<string, Content>();\n // The content list placeholder can be transformed several times during serve.\n // Caching the discovered markdown paths keeps those repeat passes cheap.\n let contentFilesListCache: string[] | undefined;\n\n let markedHighlighter: MarkedContentHighlighter;\n const workspaceRoot = vite.normalizePath(\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd(),\n );\n let config: vite.UserConfig;\n let root: string;\n // Keep discovery and invalidation aligned by deriving both from the same\n // normalized content roots. That way external content dirs participate in\n // cache busting exactly the same way they participate in glob discovery.\n // Initialized once in the `config` hook after `root` is resolved — all\n // inputs (`root`, `workspaceRoot`, `options`) are stable after that point.\n let contentRootDirs: string[];\n const normalizeContentDir = (dir: string) => {\n const normalized = vite.normalizePath(\n dir.startsWith('/')\n ? `${workspaceRoot}${dir}`\n : resolve(workspaceRoot, dir),\n );\n return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n };\n const initContentRootDirs = () => {\n contentRootDirs = [\n vite.normalizePath(`${root}/src/content`),\n ...(options?.additionalContentDirs || []).map(normalizeContentDir),\n ];\n };\n const discoverContentFilesList = () => {\n contentFilesListCache ??= globSync(\n contentRootDirs.map((dir) => `${dir}/**/*.md`),\n { dot: true },\n );\n\n return contentFilesListCache;\n };\n const resolveContentModulePath = (module: string) =>\n vite.normalizePath(\n module.startsWith('/') ? module : `${workspaceRoot}/${module}`,\n );\n const getContentModuleKey = (module: string) => {\n const absolutePath = resolveContentModulePath(module);\n const relativeToRoot = vite.normalizePath(relative(root, absolutePath));\n // `startsWith(root)` is not safe here because sibling directories such as\n // `/apps/my-app-tools` also start with `/apps/my-app`. A relative path only\n // represents in-app content when it stays within `root`.\n const isInApp =\n !relativeToRoot.startsWith('..') && !relativeToRoot.startsWith('/');\n\n // Both branches prepend `/` so generated keys are always absolute-\n // looking (`/src/content/...` for in-app, `/libs/shared/...` for\n // workspace-external). Downstream consumers like content-files-token\n // rely on the leading `/` for slug extraction regexes.\n return isInApp\n ? `/${relativeToRoot}`\n : `/${vite.normalizePath(relative(workspaceRoot, absolutePath))}`;\n };\n\n const contentDiscoveryPlugins: vite.Plugin[] = [\n {\n name: 'analog-content-glob-routes',\n config(_config) {\n config = _config;\n root = vite.normalizePath(\n resolve(workspaceRoot, config.root || '.') || '.',\n );\n initContentRootDirs();\n },\n // Vite 8 / Rolldown \"filtered transform\" — the `filter.code` string\n // tells the bundler to skip this handler entirely for modules whose\n // source does not contain the substring, avoiding unnecessary JS→Rust\n // round-trips. The inner `code.includes()` guard is kept for Vite 7\n // compat where filters are not evaluated by the bundler.\n transform: {\n filter: {\n code: 'ANALOG_CONTENT_FILE_LIST',\n },\n handler(code) {\n if (code.includes('ANALOG_CONTENT_FILE_LIST')) {\n const contentFilesList = discoverContentFilesList();\n\n const eagerImports: string[] = [];\n\n contentFilesList.forEach((module, index) => {\n // CRITICAL: tinyglobby returns relative paths like \"apps/blog-app/src/content/file.md\"\n // These MUST be converted to absolute paths for ES module imports\n // Otherwise Node.js treats \"apps\" as a package name and throws \"Cannot find package 'apps'\"\n const absolutePath = resolveContentModulePath(module);\n eagerImports.push(\n `import { default as analog_module_${index} } from \"${absolutePath}?analog-content-list=true\";`,\n );\n });\n\n // Match just the assignment (not the declaration) so the rewrite\n // works whether the source uses `const`, `let`, `var`, or\n // `export const` — including the post-Rolldown `var X = {};`\n // form — without destroying the declaration that keeps the\n // module binding exported.\n let result = code.replace(\n /ANALOG_CONTENT_FILE_LIST\\s*=\\s*\\{\\s*\\}/,\n `ANALOG_CONTENT_FILE_LIST = {${contentFilesList.map(\n (module, index) =>\n `\"${getContentModuleKey(module)}\": analog_module_${index}`,\n )}}`,\n );\n\n if (!code.includes('analog_module_')) {\n result = `${eagerImports.join('\\n')}\\n${result}`;\n }\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n {\n name: 'analogjs-invalidate-content-dirs',\n configureServer(server) {\n function invalidateContent(path: string) {\n const normalizedPath = vite.normalizePath(path);\n const isContentPath = contentRootDirs.some(\n (dir) =>\n normalizedPath === dir || normalizedPath.startsWith(`${dir}/`),\n );\n\n if (isContentPath) {\n // The file set only changes on add/remove because this watcher is\n // intentionally scoped to those events. Clear the list cache so the\n // next transform sees the updated directory contents.\n contentFilesListCache = undefined;\n server.moduleGraph.fileToModulesMap.forEach((mods) => {\n mods.forEach((mod) => {\n if (\n mod.id?.includes('analogjs') &&\n mod.id?.includes('content')\n ) {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n }\n });\n });\n\n server.ws.send('analog:debug-full-reload', {\n plugin: 'platform:content-plugin',\n reason: 'content-file-set-changed',\n path: normalizedPath,\n });\n server.ws.send({\n type: 'full-reload',\n });\n }\n }\n\n server.watcher.on('add', invalidateContent);\n server.watcher.on('unlink', invalidateContent);\n },\n },\n ];\n\n if (!highlighter) {\n return [\n {\n name: 'analogjs-external-content',\n config() {\n const bundleOptionsKey = getBundleOptionsKey();\n return {\n build: {\n [bundleOptionsKey]: {\n external: ['@analogjs/content'],\n },\n },\n };\n },\n },\n {\n name: 'analogjs-exclude-content-import',\n transform: {\n filter: {\n code: '@analogjs/content',\n },\n handler(code) {\n /**\n * Remove the package so it doesn't get\n * referenced when building for serverless\n * functions.\n */\n if (code.includes(`import('@analogjs/content')`)) {\n return {\n code: code.replace(\n `import('@analogjs/content')`,\n 'Promise.resolve({})',\n ),\n };\n }\n\n return;\n },\n },\n },\n ...contentDiscoveryPlugins,\n ];\n }\n\n return [\n {\n name: 'analogjs-content-frontmatter',\n // Filter by module ID so only `?analog-content-list=true` virtual\n // imports enter the handler. Returns `moduleSideEffects: false` so\n // Rolldown can tree-shake unused content list entries.\n transform: {\n filter: {\n id: /analog-content-list=true/,\n },\n async handler(code, id) {\n const cachedContent = cache.get(id);\n // There's no reason to run `readFileSync` and frontmatter parsing if the\n // `transform` hook is called with the same code. In such cases, we can simply\n // return the cached attributes, which is faster than repeatedly reading files\n // synchronously during the build process.\n if (cachedContent?.code === code) {\n return {\n code: `export default ${cachedContent.attributes}`,\n moduleSideEffects: false,\n };\n }\n\n const fm: any = await import('front-matter');\n // The `default` property will be available in CommonJS environment, for instance,\n // when running unit tests. It's safe to retrieve `default` first, since we still\n // fallback to the original implementation.\n const frontmatter = fm.default || fm;\n const fileContents = readFileSync(id.split('?')[0], 'utf8');\n const { attributes } = frontmatter(fileContents);\n const content = {\n code,\n attributes: JSON.stringify(attributes),\n };\n cache.set(id, content);\n\n return {\n code: `export default ${content.attributes}`,\n moduleSideEffects: false,\n };\n },\n },\n },\n {\n name: 'analogjs-content-file',\n enforce: 'post',\n async load(id) {\n if (!id.includes('analog-content-file=true')) {\n return;\n }\n\n if (!markedHighlighter) {\n if (highlighter === 'shiki') {\n const { getShikiHighlighter } =\n await import('./content/shiki/index.js');\n markedHighlighter = getShikiHighlighter(shikiOptions);\n } else {\n const { getPrismHighlighter } =\n await import('./content/prism/index.js');\n markedHighlighter = getPrismHighlighter();\n\n const langs = [\n 'bash',\n 'css',\n 'javascript',\n 'json',\n 'markup',\n 'typescript',\n ];\n\n if (\n Array.isArray(prismOptions?.additionalLangs) &&\n prismOptions?.additionalLangs?.length > 0\n ) {\n langs.push(...prismOptions.additionalLangs);\n }\n\n const loadLanguages = await import('prismjs/components/index.js');\n\n (\n loadLanguages as unknown as { default: (...args: any[]) => any }\n ).default(langs);\n }\n }\n\n const fm: any = await import('front-matter');\n // The `default` property will be available in CommonJS environment, for instance,\n // when running unit tests. It's safe to retrieve `default` first, since we still\n // fallback to the original implementation.\n const frontmatterFn = fm.default || fm;\n const fileContents = readFileSync(id.split('?')[0], 'utf8');\n const { body, frontmatter } = frontmatterFn(fileContents);\n\n // parse markdown and highlight\n const { getMarkedSetup } = await import('./content/marked/index.js');\n const markedSetupService = getMarkedSetup(\n { mangle: true, ...(markedOptions || {}) },\n markedHighlighter,\n );\n const mdContent = (await markedSetupService\n .getMarkedInstance()\n .parse(body)) as unknown as string;\n\n return `export default ${JSON.stringify(\n `---\\n${frontmatter}\\n---\\n\\n${mdContent}`,\n )}`;\n },\n },\n ...contentDiscoveryPlugins,\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,SAAgB,cACd,EACE,aACA,eACA,cACA,iBACwB,CAAC,GAC3B,SACe;CACf,MAAM,wBAAQ,IAAI,IAAqB;CAGvC,IAAI;CAEJ,IAAI;CACJ,MAAM,gBAAgB,KAAK,cACzB,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI,CAC5E;CACA,IAAI;CACJ,IAAI;CAMJ,IAAI;CACJ,MAAM,uBAAuB,QAAgB;EAC3C,MAAM,aAAa,KAAK,cACtB,IA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D,MAAM,EAAE,mBAAmB,MAAM,OAAO;IAKxC,MAAM,YAAa,MAJQ,eACzB;KAAE,QAAQ;KAAM,GAAI,iBAAiB,CAAC;IAAG,GACzC,iBAEuB,CAAA,CACtB,kBAAkB,CAAC,CACnB,MAAM,IAAI;IAEb,OAAO,kBAAkB,KAAK,UAC5B,QAAQ,YAAY,WAAW,WACjC;GACF;EACF;EACA,GAAG;CACL;AACF"}
|
|
1
|
+
{"version":3,"file":"content-plugin.js","names":[],"sources":["../../../src/lib/content-plugin.ts"],"sourcesContent":["import * as vite from 'vite';\nimport { readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport type { WithShikiHighlighterOptions } from './content/shiki/options.js';\nimport type { MarkedContentHighlighter } from './content/marked/marked-content-highlighter.js';\nimport type { WithPrismHighlighterOptions } from './content/prism/options.js';\nimport type { WithMarkedOptions } from './content/marked/index.js';\nimport type { Options } from './options.js';\nimport { getBundleOptionsKey } from './utils/rolldown.js';\n\ninterface Content {\n code: string;\n attributes: string;\n}\n\n// Serializes parsed frontmatter as a JS expression, keeping YAML timestamps as Dates.\nfunction toModuleValue(value: unknown): string {\n if (value instanceof Date) {\n return `new Date(${JSON.stringify(value.toISOString())})`;\n }\n if (Array.isArray(value)) {\n return `[${value.map(toModuleValue).join(',')}]`;\n }\n if (value && typeof value === 'object') {\n return `{${Object.entries(value)\n .map(([key, entry]) => `${JSON.stringify(key)}:${toModuleValue(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'undefined';\n}\n\nexport type ContentPluginOptions = {\n highlighter?: 'shiki' | 'prism';\n markedOptions?: WithMarkedOptions;\n shikiOptions?: WithShikiHighlighterOptions;\n prismOptions?: WithPrismHighlighterOptions;\n};\n\n/**\n * Content plugin that provides markdown and content file processing for Analog.\n *\n * IMPORTANT: This plugin uses tinyglobby for file discovery.\n * Key pitfall with { dot: true }:\n * - Returns relative paths from cwd (e.g., \"apps/blog-app/src/content/...\")\n * - These paths CANNOT be used directly in ES module imports\n * - Relative paths without ./ or ../ are treated as package names\n * - Must convert to absolute paths for imports to work correctly\n */\nexport function contentPlugin(\n {\n highlighter,\n markedOptions,\n shikiOptions,\n prismOptions,\n }: ContentPluginOptions = {},\n options?: Options,\n): vite.Plugin[] {\n const cache = new Map<string, Content>();\n // The content list placeholder can be transformed several times during serve.\n // Caching the discovered markdown paths keeps those repeat passes cheap.\n let contentFilesListCache: string[] | undefined;\n\n let markedHighlighter: MarkedContentHighlighter;\n const workspaceRoot = vite.normalizePath(\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd(),\n );\n let config: vite.UserConfig;\n let root: string;\n // Keep discovery and invalidation aligned by deriving both from the same\n // normalized content roots. That way external content dirs participate in\n // cache busting exactly the same way they participate in glob discovery.\n // Initialized once in the `config` hook after `root` is resolved — all\n // inputs (`root`, `workspaceRoot`, `options`) are stable after that point.\n let contentRootDirs: string[];\n const normalizeContentDir = (dir: string) => {\n const normalized = vite.normalizePath(\n dir.startsWith('/')\n ? `${workspaceRoot}${dir}`\n : resolve(workspaceRoot, dir),\n );\n return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n };\n const initContentRootDirs = () => {\n contentRootDirs = [\n vite.normalizePath(`${root}/src/content`),\n ...(options?.additionalContentDirs || []).map(normalizeContentDir),\n ];\n };\n const discoverContentFilesList = () => {\n contentFilesListCache ??= globSync(\n contentRootDirs.map((dir) => `${dir}/**/*.md`),\n { dot: true, cwd: workspaceRoot },\n );\n\n return contentFilesListCache;\n };\n const resolveContentModulePath = (module: string) =>\n vite.normalizePath(\n module.startsWith('/') ? module : `${workspaceRoot}/${module}`,\n );\n const getContentModuleKey = (module: string) => {\n const absolutePath = resolveContentModulePath(module);\n const relativeToRoot = vite.normalizePath(relative(root, absolutePath));\n // `startsWith(root)` is not safe here because sibling directories such as\n // `/apps/my-app-tools` also start with `/apps/my-app`. A relative path only\n // represents in-app content when it stays within `root`.\n const isInApp =\n !relativeToRoot.startsWith('..') && !relativeToRoot.startsWith('/');\n\n // Both branches prepend `/` so generated keys are always absolute-\n // looking (`/src/content/...` for in-app, `/libs/shared/...` for\n // workspace-external). Downstream consumers like content-files-token\n // rely on the leading `/` for slug extraction regexes.\n return isInApp\n ? `/${relativeToRoot}`\n : `/${vite.normalizePath(relative(workspaceRoot, absolutePath))}`;\n };\n\n const contentDiscoveryPlugins: vite.Plugin[] = [\n {\n name: 'analog-content-glob-routes',\n config(_config) {\n config = _config;\n root = vite.normalizePath(\n resolve(workspaceRoot, config.root || '.') || '.',\n );\n initContentRootDirs();\n },\n // Vite 8 / Rolldown \"filtered transform\" — the `filter.code` string\n // tells the bundler to skip this handler entirely for modules whose\n // source does not contain the substring, avoiding unnecessary JS→Rust\n // round-trips. The inner `code.includes()` guard is kept for Vite 7\n // compat where filters are not evaluated by the bundler.\n transform: {\n filter: {\n code: 'ANALOG_CONTENT_FILE_LIST',\n },\n handler(code) {\n if (code.includes('ANALOG_CONTENT_FILE_LIST')) {\n const contentFilesList = discoverContentFilesList();\n\n const eagerImports: string[] = [];\n\n contentFilesList.forEach((module, index) => {\n // CRITICAL: tinyglobby returns relative paths like \"apps/blog-app/src/content/file.md\"\n // These MUST be converted to absolute paths for ES module imports\n // Otherwise Node.js treats \"apps\" as a package name and throws \"Cannot find package 'apps'\"\n const absolutePath = resolveContentModulePath(module);\n eagerImports.push(\n `import { default as analog_module_${index} } from \"${absolutePath}?analog-content-list=true\";`,\n );\n });\n\n // Match just the assignment (not the declaration) so the rewrite\n // works whether the source uses `const`, `let`, `var`, or\n // `export const` — including the post-Rolldown `var X = {};`\n // form — without destroying the declaration that keeps the\n // module binding exported.\n let result = code.replace(\n /ANALOG_CONTENT_FILE_LIST\\s*=\\s*\\{\\s*\\}/,\n `ANALOG_CONTENT_FILE_LIST = {${contentFilesList.map(\n (module, index) =>\n `\"${getContentModuleKey(module)}\": analog_module_${index}`,\n )}}`,\n );\n\n if (!code.includes('analog_module_')) {\n result = `${eagerImports.join('\\n')}\\n${result}`;\n }\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n {\n name: 'analogjs-invalidate-content-dirs',\n configureServer(server) {\n function invalidateContent(path: string) {\n const normalizedPath = vite.normalizePath(path);\n const isContentPath = contentRootDirs.some(\n (dir) =>\n normalizedPath === dir || normalizedPath.startsWith(`${dir}/`),\n );\n\n if (isContentPath) {\n // The file set only changes on add/remove because this watcher is\n // intentionally scoped to those events. Clear the list cache so the\n // next transform sees the updated directory contents.\n contentFilesListCache = undefined;\n server.moduleGraph.fileToModulesMap.forEach((mods) => {\n mods.forEach((mod) => {\n if (\n mod.id?.includes('analogjs') &&\n mod.id?.includes('content')\n ) {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n }\n });\n });\n\n server.ws.send('analog:debug-full-reload', {\n plugin: 'platform:content-plugin',\n reason: 'content-file-set-changed',\n path: normalizedPath,\n });\n server.ws.send({\n type: 'full-reload',\n });\n }\n }\n\n server.watcher.on('add', invalidateContent);\n server.watcher.on('unlink', invalidateContent);\n },\n },\n ];\n\n if (!highlighter) {\n return [\n {\n name: 'analogjs-external-content',\n config() {\n const bundleOptionsKey = getBundleOptionsKey();\n return {\n build: {\n [bundleOptionsKey]: {\n external: ['@analogjs/content'],\n },\n },\n };\n },\n },\n {\n name: 'analogjs-exclude-content-import',\n transform: {\n filter: {\n code: '@analogjs/content',\n },\n handler(code) {\n /**\n * Remove the package so it doesn't get\n * referenced when building for serverless\n * functions.\n */\n if (code.includes(`import('@analogjs/content')`)) {\n return {\n code: code.replace(\n `import('@analogjs/content')`,\n 'Promise.resolve({})',\n ),\n };\n }\n\n return;\n },\n },\n },\n ...contentDiscoveryPlugins,\n ];\n }\n\n return [\n {\n name: 'analogjs-content-frontmatter',\n // Filter by module ID so only `?analog-content-list=true` virtual\n // imports enter the handler. Returns `moduleSideEffects: false` so\n // Rolldown can tree-shake unused content list entries.\n transform: {\n filter: {\n id: /analog-content-list=true/,\n },\n async handler(code, id) {\n const cachedContent = cache.get(id);\n // There's no reason to run `readFileSync` and frontmatter parsing if the\n // `transform` hook is called with the same code. In such cases, we can simply\n // return the cached attributes, which is faster than repeatedly reading files\n // synchronously during the build process.\n if (cachedContent?.code === code) {\n return {\n code: `export default ${cachedContent.attributes}`,\n moduleSideEffects: false,\n };\n }\n\n const fm: any = await import('front-matter');\n // The `default` property will be available in CommonJS environment, for instance,\n // when running unit tests. It's safe to retrieve `default` first, since we still\n // fallback to the original implementation.\n const frontmatter = fm.default || fm;\n const fileContents = readFileSync(id.split('?')[0], 'utf8');\n const { attributes } = frontmatter(fileContents);\n const content = {\n code,\n attributes: JSON.stringify(attributes),\n };\n cache.set(id, content);\n\n return {\n code: `export default ${content.attributes}`,\n moduleSideEffects: false,\n };\n },\n },\n },\n {\n name: 'analogjs-content-file',\n enforce: 'post',\n async load(id) {\n if (!id.includes('analog-content-file=true')) {\n return;\n }\n\n if (!markedHighlighter) {\n if (highlighter === 'shiki') {\n const { getShikiHighlighter } =\n await import('./content/shiki/index.js');\n markedHighlighter = getShikiHighlighter(shikiOptions);\n } else {\n const { getPrismHighlighter } =\n await import('./content/prism/index.js');\n markedHighlighter = getPrismHighlighter();\n\n const langs = [\n 'bash',\n 'css',\n 'javascript',\n 'json',\n 'markup',\n 'typescript',\n ];\n\n if (\n Array.isArray(prismOptions?.additionalLangs) &&\n prismOptions?.additionalLangs?.length > 0\n ) {\n langs.push(...prismOptions.additionalLangs);\n }\n\n const loadLanguages = await import('prismjs/components/index.js');\n\n (\n loadLanguages as unknown as { default: (...args: any[]) => any }\n ).default(langs);\n }\n }\n\n const fm: any = await import('front-matter');\n // The `default` property will be available in CommonJS environment, for instance,\n // when running unit tests. It's safe to retrieve `default` first, since we still\n // fallback to the original implementation.\n const frontmatterFn = fm.default || fm;\n const fileContents = readFileSync(id.split('?')[0], 'utf8');\n const { body, attributes } = frontmatterFn(fileContents);\n\n // parse markdown and highlight\n const { getMarkedSetup } = await import('./content/marked/index.js');\n const markedSetupService = getMarkedSetup(\n { mangle: true, ...(markedOptions || {}) },\n markedHighlighter,\n );\n const mdContent = (await markedSetupService\n .getMarkedInstance()\n .parse(body)) as unknown as string;\n\n return `export default ${JSON.stringify(mdContent)};\\nexport const metadata = ${toModuleValue(attributes)};`;\n },\n },\n ...contentDiscoveryPlugins,\n ];\n}\n"],"mappings":";;;;;;AAkBA,SAAS,cAAc,OAAwB;CAC7C,IAAI,iBAAiB,MACnB,OAAO,YAAY,KAAK,UAAU,MAAM,YAAY,CAAC,EAAE;CAEzD,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAEhD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,cAAc,KAAK,GAAG,CAAC,CACvE,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;;;;;;;;;;;AAmBA,SAAgB,cACd,EACE,aACA,eACA,cACA,iBACwB,CAAC,GAC3B,SACe;CACf,MAAM,wBAAQ,IAAI,IAAqB;CAGvC,IAAI;CAEJ,IAAI;CACJ,MAAM,gBAAgB,KAAK,cACzB,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI,CAC5E;CACA,IAAI;CACJ,IAAI;CAMJ,IAAI;CACJ,MAAM,uBAAuB,QAAgB;EAC3C,MAAM,aAAa,KAAK,cACtB,IAAI,WAAW,GAAG,IACd,GAAG,gBAAgB,QACnB,QAAQ,eAAe,GAAG,CAChC;EACA,OAAO,WAAW,SAAS,GAAG,IAAI,WAAW,MAAM,GAAG,EAAE,IAAI;CAC9D;CACA,MAAM,4BAA4B;EAChC,kBAAkB,CAChB,KAAK,cAAc,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,OAAO,kBAAkB,KAAK,UAAU,SAAS,EAAE,6BAA6B,cAAc,UAAU,EAAE;GAC5G;EACF;EACA,GAAG;CACL;AACF"}
|
package/src/lib/deps-plugin.d.ts
CHANGED
package/src/lib/deps-plugin.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { debugPlatform } from "./utils/debug.js";
|
|
2
2
|
import { getJsTransformConfigKey, isRolldown } from "./utils/rolldown.js";
|
|
3
3
|
import { angularLinkerPlugin } from "./nitro/angular-linker-plugin.js";
|
|
4
|
+
import { dirname, resolve } from "node:path";
|
|
5
|
+
import { normalizePath } from "vite";
|
|
4
6
|
import { crawlFrameworkPkgs } from "vitefu";
|
|
5
7
|
//#region packages/platform/src/lib/deps-plugin.ts
|
|
6
8
|
var ANGULAR_LINKED_SSR_DEPS = [
|
|
@@ -13,14 +15,16 @@ function depsPlugin(options) {
|
|
|
13
15
|
const workspaceRoot = options?.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd();
|
|
14
16
|
return [{
|
|
15
17
|
name: "analogjs-deps-plugin",
|
|
16
|
-
config() {
|
|
17
|
-
const
|
|
18
|
+
config(userConfig) {
|
|
19
|
+
const jsTransformKey = getJsTransformConfigKey();
|
|
20
|
+
const userTransform = userConfig?.[jsTransformKey] !== void 0 || jsTransformKey === "oxc" && !!userConfig?.esbuild;
|
|
21
|
+
const transform = options?.server ? { include: [`${normalizePath(resolve(userConfig?.root ?? process.cwd(), dirname(options.server.entry)))}/**/*.ts`] } : { exclude: ["**/*.ts", "**/*.js"] };
|
|
18
22
|
debugPlatform("deps transform config", {
|
|
19
|
-
jsTransformKey
|
|
20
|
-
|
|
23
|
+
jsTransformKey,
|
|
24
|
+
transform: userTransform ? "user" : transform
|
|
21
25
|
});
|
|
22
26
|
return {
|
|
23
|
-
[
|
|
27
|
+
...userTransform ? {} : { [jsTransformKey]: transform },
|
|
24
28
|
ssr: {
|
|
25
29
|
noExternal: [
|
|
26
30
|
"@analogjs/**",
|
|
@@ -30,7 +34,7 @@ function depsPlugin(options) {
|
|
|
30
34
|
"rxfire",
|
|
31
35
|
"@ng-web-apis/**",
|
|
32
36
|
"@taiga-ui/**",
|
|
33
|
-
|
|
37
|
+
/^@tanstack\/angular-/
|
|
34
38
|
],
|
|
35
39
|
optimizeDeps: {
|
|
36
40
|
include: [
|
|
@@ -83,7 +87,7 @@ function depsPlugin(options) {
|
|
|
83
87
|
isBuild: command === "build",
|
|
84
88
|
viteUserConfig: config,
|
|
85
89
|
isSemiFrameworkPkgByJson(pkgJson) {
|
|
86
|
-
return
|
|
90
|
+
return pkgJson["module"] && pkgJson["module"].includes("fesm");
|
|
87
91
|
}
|
|
88
92
|
});
|
|
89
93
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deps-plugin.js","names":[],"sources":["../../../src/lib/deps-plugin.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"deps-plugin.js","names":[],"sources":["../../../src/lib/deps-plugin.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path';\nimport { normalizePath, type Plugin } from 'vite';\nimport { crawlFrameworkPkgs } from 'vitefu';\n\nimport { angularLinkerPlugin } from './nitro/angular-linker-plugin.js';\nimport { Options } from './options.js';\nimport { debugPlatform } from './utils/debug.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\n\nconst ANGULAR_LINKED_SSR_DEPS = [\n '@angular/compiler',\n '@angular/core',\n '@angular/platform-browser',\n '@angular/platform-server',\n];\n\nexport function depsPlugin(options?: Options): Plugin[] {\n const workspaceRoot =\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n\n return [\n {\n name: 'analogjs-deps-plugin',\n config(userConfig) {\n // Skip Vite's built-in ts/js transform so `@analogjs/vite-plugin-angular`\n // (when the user includes it) owns Angular file compilation. Users who\n // run an alternative compiler, or compile non-Angular server code with\n // Vite, set the transform in their own Vite config. Theirs is kept\n // as-is: merging would concatenate these excludes into it, and an\n // exclude wins over any include they set.\n const jsTransformKey = getJsTransformConfigKey();\n // Vite 8 still converts a user's `esbuild` object to `oxc` (unless\n // `oxc` is set), but `esbuild: false` no longer has any effect there.\n const userTransform =\n userConfig?.[jsTransformKey] !== undefined ||\n (jsTransformKey === 'oxc' && !!userConfig?.esbuild);\n // With `server`, Vite compiles the server entry's directory instead,\n // which the Angular compiler leaves alone.\n const transform = options?.server\n ? {\n include: [\n `${normalizePath(\n resolve(\n userConfig?.root ?? process.cwd(),\n dirname(options.server.entry),\n ),\n )}/**/*.ts`,\n ],\n }\n : { exclude: ['**/*.ts', '**/*.js'] };\n debugPlatform('deps transform config', {\n jsTransformKey,\n transform: userTransform ? 'user' : transform,\n });\n\n return {\n ...(userTransform ? {} : { [jsTransformKey]: transform }),\n ssr: {\n noExternal: [\n '@analogjs/**',\n 'es-toolkit',\n 'firebase/**',\n 'firebase-admin/**',\n 'rxfire',\n '@ng-web-apis/**',\n '@taiga-ui/**',\n /^@tanstack\\/angular-/,\n ],\n // The server pre-bundle is resolved separately from the client\n // one, so a secondary entry point left out of it loads its own\n // copy of `@angular/core`. `inject()` then runs against a runtime\n // with no active injection context and SSR fails with NG0203.\n // With Rolldown, the rest of Angular is pre-bundled too and the\n // partial-compilation packages are linked, so the server needs no JIT.\n optimizeDeps: {\n include: [\n ...(isRolldown() ? ANGULAR_LINKED_SSR_DEPS : []),\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n ],\n ...(isRolldown()\n ? { rolldownOptions: { plugins: [angularLinkerPlugin()] } }\n : {}),\n },\n },\n optimizeDeps: {\n include: [\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n 'front-matter',\n ],\n exclude: [\n '@angular/platform-server',\n '@analogjs/content',\n '@analogjs/router',\n '@nx/angular',\n '@nx/vite',\n '@nx/devkit',\n '@nx/js',\n '@nx/devkit',\n '@nx/cypress',\n '@nx/jest',\n '@nx/js',\n '@nx/eslint',\n '@nx/webpack',\n '@nx/web',\n '@nx/workspace',\n '@nx/eslint',\n '@nx/module-federation',\n '@nx/rspack',\n 'webpack',\n 'fsevents',\n 'nx',\n ],\n },\n };\n },\n },\n {\n name: 'analogjs-auto-discover-deps',\n async config(config, { command }) {\n const pkgConfig = await crawlFrameworkPkgs({\n root: workspaceRoot,\n isBuild: command === 'build',\n viteUserConfig: config,\n isSemiFrameworkPkgByJson(pkgJson) {\n return pkgJson['module'] && pkgJson['module'].includes('fesm');\n },\n });\n return pkgConfig;\n },\n },\n ];\n}\n"],"mappings":";;;;;;;AASA,IAAM,0BAA0B;CAC9B;CACA;CACA;CACA;AACF;AAEA,SAAgB,WAAW,SAA6B;CACtD,MAAM,gBACJ,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAE5E,OAAO,CACL;EACE,MAAM;EACN,OAAO,YAAY;GAOjB,MAAM,iBAAiB,wBAAwB;GAG/C,MAAM,gBACJ,aAAa,oBAAoB,KAAA,KAChC,mBAAmB,SAAS,CAAC,CAAC,YAAY;GAG7C,MAAM,YAAY,SAAS,SACvB,EACE,SAAS,CACP,GAAG,cACD,QACE,YAAY,QAAQ,QAAQ,IAAI,GAChC,QAAQ,QAAQ,OAAO,KAAK,CAC9B,CACF,EAAE,SACJ,EACF,IACA,EAAE,SAAS,CAAC,WAAW,SAAS,EAAE;GACtC,cAAc,yBAAyB;IACrC;IACA,WAAW,gBAAgB,SAAS;GACtC,CAAC;GAED,OAAO;IACL,GAAI,gBAAgB,CAAC,IAAI,GAAG,iBAAiB,UAAU;IACvD,KAAK;KACH,YAAY;MACV;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;KAOA,cAAc;MACZ,SAAS;OACP,GAAI,WAAW,IAAI,0BAA0B,CAAC;OAC9C;OACA;OACA;MACF;MACA,GAAI,WAAW,IACX,EAAE,iBAAiB,EAAE,SAAS,CAAC,oBAAoB,CAAC,EAAE,EAAE,IACxD,CAAC;KACP;IACF;IACA,cAAc;KACZ,SAAS;MACP;MACA;MACA;MACA;KACF;KACA,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;IACF;GACF;EACF;CACF,GACA;EACE,MAAM;EACN,MAAM,OAAO,QAAQ,EAAE,WAAW;GAShC,OAAO,MARiB,mBAAmB;IACzC,MAAM;IACN,SAAS,YAAY;IACrB,gBAAgB;IAChB,yBAAyB,SAAS;KAChC,OAAO,QAAQ,aAAa,QAAQ,SAAS,CAAC,SAAS,MAAM;IAC/D;GACF,CAAC;EAEH;CACF,CACF;AACF"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
type GetPageEndpointsArgs = {
|
|
2
|
+
workspaceRoot: string;
|
|
3
|
+
sourceRoot: string;
|
|
4
|
+
rootDir: string;
|
|
5
|
+
additionalPagesDirs?: string[];
|
|
6
|
+
};
|
|
7
|
+
export type PageEndpoint = {
|
|
8
|
+
/** Absolute path to the page's `.server.ts` file. */
|
|
9
|
+
file: string;
|
|
10
|
+
/** Route relative to the endpoint root, e.g. `/pages/users/:id`. */
|
|
11
|
+
route: string;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Discovers server-side page endpoints: every `.server.ts` file under
|
|
15
|
+
* `app/pages/**` and any additional pages directories, mapped to a route
|
|
16
|
+
* pattern. Servers mount them under their own prefix.
|
|
17
|
+
*
|
|
18
|
+
* Route transformation examples:
|
|
19
|
+
* - index.server.ts → /pages/index
|
|
20
|
+
* - users/[id].server.ts → /pages/users/:id
|
|
21
|
+
* - products/[...slug].server.ts → /pages/products/**:slug
|
|
22
|
+
* - (auth)/login.server.ts → /pages/-auth-/login
|
|
23
|
+
*/
|
|
24
|
+
export declare function getPageEndpoints({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs }: GetPageEndpointsArgs): PageEndpoint[];
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { normalizePath } from "vite";
|
|
3
|
+
import { globSync } from "tinyglobby";
|
|
4
|
+
//#region packages/platform/src/lib/get-page-endpoints.ts
|
|
5
|
+
/**
|
|
6
|
+
* Discovers server-side page endpoints: every `.server.ts` file under
|
|
7
|
+
* `app/pages/**` and any additional pages directories, mapped to a route
|
|
8
|
+
* pattern. Servers mount them under their own prefix.
|
|
9
|
+
*
|
|
10
|
+
* Route transformation examples:
|
|
11
|
+
* - index.server.ts → /pages/index
|
|
12
|
+
* - users/[id].server.ts → /pages/users/:id
|
|
13
|
+
* - products/[...slug].server.ts → /pages/products/**:slug
|
|
14
|
+
* - (auth)/login.server.ts → /pages/-auth-/login
|
|
15
|
+
*/
|
|
16
|
+
function getPageEndpoints({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs }) {
|
|
17
|
+
const root = normalizePath(resolve(workspaceRoot, rootDir));
|
|
18
|
+
return globSync([`${root}/${sourceRoot}/app/pages/**/*.server.ts`, ...(additionalPagesDirs || []).map((dir) => `${workspaceRoot}${dir}/**/*.server.ts`)], {
|
|
19
|
+
dot: true,
|
|
20
|
+
absolute: true
|
|
21
|
+
}).map((file) => ({
|
|
22
|
+
file,
|
|
23
|
+
route: normalizePath(file).replace(/^(.*?)\/pages/, "/pages").replace(/\.server\.ts$/, "").replace(/\[\.{3}(.+)\]/g, "**:$1").replace(/\[\.{3}(\w+)\]/g, "**:$1").replace(/\/\(([^/]+)\)/g, "/-$1-").replace(/\[(\w+)\]/g, ":$1").replace(/\./g, "/")
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { getPageEndpoints };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=get-page-endpoints.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-page-endpoints.js","names":[],"sources":["../../../src/lib/get-page-endpoints.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport { normalizePath } from 'vite';\n\ntype GetPageEndpointsArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalPagesDirs?: string[];\n};\n\nexport type PageEndpoint = {\n /** Absolute path to the page's `.server.ts` file. */\n file: string;\n /** Route relative to the endpoint root, e.g. `/pages/users/:id`. */\n route: string;\n};\n\n/**\n * Discovers server-side page endpoints: every `.server.ts` file under\n * `app/pages/**` and any additional pages directories, mapped to a route\n * pattern. Servers mount them under their own prefix.\n *\n * Route transformation examples:\n * - index.server.ts → /pages/index\n * - users/[id].server.ts → /pages/users/:id\n * - products/[...slug].server.ts → /pages/products/**:slug\n * - (auth)/login.server.ts → /pages/-auth-/login\n */\nexport function getPageEndpoints({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs,\n}: GetPageEndpointsArgs): PageEndpoint[] {\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n const endpointFiles: string[] = globSync(\n [\n `${root}/${sourceRoot}/app/pages/**/*.server.ts`,\n ...(additionalPagesDirs || []).map(\n (dir) => `${workspaceRoot}${dir}/**/*.server.ts`,\n ),\n ],\n { dot: true, absolute: true },\n );\n\n return endpointFiles.map((file) => ({\n file,\n route: normalizePath(file)\n .replace(/^(.*?)\\/pages/, '/pages')\n .replace(/\\.server\\.ts$/, '')\n .replace(/\\[\\.{3}(.+)\\]/g, '**:$1')\n .replace(/\\[\\.{3}(\\w+)\\]/g, '**:$1')\n // Strip Angular Router group syntax `(group)` from any segment, not\n // just trailing ones. Routes like `(auth)/login.server.ts` need to\n // become `/-auth-/login`, otherwise the literal parens leak through\n // and the endpoint is mounted under an invalid path.\n .replace(/\\/\\(([^/]+)\\)/g, '/-$1-')\n .replace(/\\[(\\w+)\\]/g, ':$1')\n .replace(/\\./g, '/'),\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,SAAgB,iBAAiB,EAC/B,eACA,YACA,SACA,uBACuC;CACvC,MAAM,OAAO,cAAc,QAAQ,eAAe,OAAO,CAAC;CAY1D,OAVgC,SAC9B,CACE,GAAG,KAAK,GAAG,WAAW,4BACtB,IAAI,uBAAuB,CAAC,EAAA,CAAG,KAC5B,QAAQ,GAAG,gBAAgB,IAAI,gBAClC,CACF,GACA;EAAE,KAAK;EAAM,UAAU;CAAK,CAGvB,CAAA,CAAc,KAAK,UAAU;EAClC;EACA,OAAO,cAAc,IAAI,CAAC,CACvB,QAAQ,iBAAiB,QAAQ,CAAC,CAClC,QAAQ,iBAAiB,EAAE,CAAC,CAC5B,QAAQ,kBAAkB,OAAO,CAAC,CAClC,QAAQ,mBAAmB,OAAO,CAAC,CAKnC,QAAQ,kBAAkB,OAAO,CAAC,CAClC,QAAQ,cAAc,KAAK,CAAC,CAC5B,QAAQ,OAAO,GAAG;CACvB,EAAE;AACJ"}
|
|
@@ -8,11 +8,11 @@ import type { Options } from "../options.js";
|
|
|
8
8
|
*/
|
|
9
9
|
export declare function analogNitroPlugin(options?: Options): Plugin;
|
|
10
10
|
/**
|
|
11
|
-
* Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
11
|
+
* Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr` onto any rule
|
|
12
|
+
* setting `ssr`, and `x-analog-no-streaming` onto any rule setting
|
|
13
|
+
* `streaming`. Nitro drops `false` values when it merges rules, so the headers
|
|
14
|
+
* carry them, and a narrower `true` rule overrides with `'false'`. The SSR
|
|
15
|
+
* renderer virtual above reads them from the matched rules, and they reach
|
|
16
|
+
* the response as hints for downstream consumers (CDN, edge logic).
|
|
17
17
|
*/
|
|
18
18
|
export declare function injectAnalogRouteRuleHeaders(nitro: Nitro): void;
|
|
@@ -88,13 +88,10 @@ function analogNitroPlugin(options = {}) {
|
|
|
88
88
|
server: { fs: { allow: [context.workspaceRoot] } },
|
|
89
89
|
environments: { client: { build: { rollupOptions: { input: indexHtmlPath() } } } }
|
|
90
90
|
};
|
|
91
|
-
if (ssr) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
rollupOptions: { input: { index: ssrEntryMarkerPath } }
|
|
96
|
-
} };
|
|
97
|
-
}
|
|
91
|
+
if (ssr) overrides.environments["ssr"] = { build: {
|
|
92
|
+
outDir: resolve(context.workspaceRoot, "dist", context.rootDir, "ssr"),
|
|
93
|
+
rollupOptions: { input: { index: ssrEntryMarkerPath } }
|
|
94
|
+
} };
|
|
98
95
|
return overrides;
|
|
99
96
|
},
|
|
100
97
|
configureServer(server) {
|
|
@@ -212,9 +209,10 @@ function analogNitroPlugin(options = {}) {
|
|
|
212
209
|
const serverDir = resolve(context.workspaceRoot, context.rootDir, `${context.sourceRoot}/server`);
|
|
213
210
|
const apiDirs = (options.additionalAPIDirs ?? []).map((dir) => resolve(context.workspaceRoot, `.${dir}`));
|
|
214
211
|
for (const dir of [serverDir, ...apiDirs]) if (existsSync(dir) && !nitro.options.scanDirs.includes(dir)) nitro.options.scanDirs.push(dir);
|
|
215
|
-
nitro.hooks.hook("
|
|
212
|
+
nitro.hooks.hook("build:config", (_n, buildConfig) => {
|
|
213
|
+
const rollupConfig = buildConfig.rollup ?? buildConfig.rolldown;
|
|
216
214
|
if (Array.isArray(rollupConfig.plugins)) rollupConfig.plugins.push(nitroH3Resolver, pageEndpointsPlugin(), serverFnIdPlugin(resolve(context.workspaceRoot, context.rootDir)));
|
|
217
|
-
applyAnalogNitroExternals(rollupConfig);
|
|
215
|
+
if (nitro.options.node && nitro.options.noExternals !== true) applyAnalogNitroExternals(rollupConfig);
|
|
218
216
|
sanitizeNitroBundlerConfig(rollupConfig);
|
|
219
217
|
});
|
|
220
218
|
if (ssr) {
|
|
@@ -284,7 +282,8 @@ function registerServerFns(nitro, context) {
|
|
|
284
282
|
nitro.options.handlers.push(getServerFnDispatchHandler());
|
|
285
283
|
nitro.options.virtual[SERVER_FN_DISPATCH_VIRTUAL] = buildServerFnDispatchModule({
|
|
286
284
|
modules,
|
|
287
|
-
appConfigModule
|
|
285
|
+
appConfigModule,
|
|
286
|
+
root
|
|
288
287
|
});
|
|
289
288
|
}
|
|
290
289
|
/**
|
|
@@ -307,7 +306,7 @@ function serverFnIdPlugin(projectRoot) {
|
|
|
307
306
|
/**
|
|
308
307
|
* Builds the h3 handler installed as Nitro's `renderer.handler`. Short-circuits
|
|
309
308
|
* `ssr: false` routes to the raw client template; otherwise dispatches the
|
|
310
|
-
* request to the SSR service env (`
|
|
309
|
+
* request to the SSR service env (`fetchService("ssr", req)` works in dev via
|
|
311
310
|
* the env-runner and in prod via the `__nitro_vite_envs__` global set up by
|
|
312
311
|
* nitro/vite's `prodSetup`).
|
|
313
312
|
*/
|
|
@@ -322,23 +321,29 @@ const TEMPLATE = ${JSON.stringify(template)};
|
|
|
322
321
|
export default defineHandler(async (event) => {
|
|
323
322
|
event.res.headers.set('content-type', 'text/html; charset=utf-8');
|
|
324
323
|
// 'x-analog-no-ssr' is stamped on the route rule headers by
|
|
325
|
-
// injectAnalogRouteRuleHeaders
|
|
326
|
-
//
|
|
324
|
+
// injectAnalogRouteRuleHeaders. Nitro writes those headers after the
|
|
325
|
+
// handler runs, so read the matched rules.
|
|
327
326
|
const { routeRules } = getRouteRules(event.req.method, event.url.pathname);
|
|
328
327
|
if (routeRules?.headers?.['x-analog-no-ssr'] === 'true') {
|
|
329
328
|
return TEMPLATE;
|
|
330
329
|
}
|
|
331
330
|
const service = ssr.default ?? ssr;
|
|
332
331
|
// The SSR service renders without a Node response, so forward the
|
|
333
|
-
// \`streaming: false\` rule on the request for the renderer to read.
|
|
332
|
+
// \`streaming: false\` rule on the request for the renderer to read. Only
|
|
333
|
+
// the route rule decides it, never the client.
|
|
334
|
+
const headers = new Headers(event.req.headers);
|
|
335
|
+
headers.delete('x-analog-no-ssr');
|
|
336
|
+
headers.delete('x-analog-no-streaming');
|
|
334
337
|
if (routeRules?.headers?.['x-analog-no-streaming'] === 'true') {
|
|
335
|
-
const headers = new Headers(event.req.headers);
|
|
336
338
|
headers.set('x-analog-no-streaming', 'true');
|
|
337
|
-
return service.fetch(
|
|
338
|
-
new Request(event.req.url, { method: event.req.method, headers }),
|
|
339
|
-
);
|
|
340
339
|
}
|
|
341
|
-
|
|
340
|
+
const request = new Request(event.req.url, {
|
|
341
|
+
method: event.req.method,
|
|
342
|
+
headers,
|
|
343
|
+
signal: event.req.signal,
|
|
344
|
+
});
|
|
345
|
+
request.waitUntil = (task) => event.waitUntil(task);
|
|
346
|
+
return service.fetch(request);
|
|
342
347
|
});
|
|
343
348
|
`;
|
|
344
349
|
}
|
|
@@ -347,7 +352,7 @@ export default defineHandler(async (event) => {
|
|
|
347
352
|
* this function is bundler-agnostic: works in Vite-built main bundles and
|
|
348
353
|
* Rolldown-built prerender bundles alike.
|
|
349
354
|
*
|
|
350
|
-
* - Dev: dispatch through nitro/vite's env runner (\`
|
|
355
|
+
* - Dev: dispatch through nitro/vite's env runner (\`fetchService\`); the SSR
|
|
351
356
|
* service module isn't on disk yet, so we delegate to the runner.
|
|
352
357
|
* - Build / prerender: re-export the built SSR entry directly from the
|
|
353
358
|
* filesystem. By the time Nitro's bundlers ask for \`#analog/ssr\`, Vite has
|
|
@@ -356,14 +361,14 @@ export default defineHandler(async (event) => {
|
|
|
356
361
|
*/
|
|
357
362
|
function generateSsrServiceVirtual(nitro) {
|
|
358
363
|
if (nitro.options.dev) return `
|
|
359
|
-
import {
|
|
364
|
+
import { fetchService } from 'nitro/services';
|
|
360
365
|
export default {
|
|
361
366
|
// The dev runner answers from a worker, and a rejection there comes back as
|
|
362
367
|
// something Nitro cannot turn into a response, so the request hangs with no
|
|
363
368
|
// status and no message. Answer with the failure instead.
|
|
364
369
|
async fetch(req) {
|
|
365
370
|
try {
|
|
366
|
-
return await
|
|
371
|
+
return await fetchService('ssr', req);
|
|
367
372
|
} catch (err) {
|
|
368
373
|
console.error('[analog ssr]', err);
|
|
369
374
|
const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
|
|
@@ -432,24 +437,24 @@ function sanitizeNitroBundlerConfig(rollupConfig) {
|
|
|
432
437
|
}
|
|
433
438
|
}
|
|
434
439
|
/**
|
|
435
|
-
* Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
439
|
-
*
|
|
440
|
-
*
|
|
440
|
+
* Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr` onto any rule
|
|
441
|
+
* setting `ssr`, and `x-analog-no-streaming` onto any rule setting
|
|
442
|
+
* `streaming`. Nitro drops `false` values when it merges rules, so the headers
|
|
443
|
+
* carry them, and a narrower `true` rule overrides with `'false'`. The SSR
|
|
444
|
+
* renderer virtual above reads them from the matched rules, and they reach
|
|
445
|
+
* the response as hints for downstream consumers (CDN, edge logic).
|
|
441
446
|
*/
|
|
442
447
|
function injectAnalogRouteRuleHeaders(nitro) {
|
|
443
448
|
const routeRules = nitro.options.routeRules;
|
|
444
449
|
if (!routeRules) return;
|
|
445
450
|
for (const rule of Object.values(routeRules)) {
|
|
446
|
-
if (rule?.ssr ===
|
|
451
|
+
if (typeof rule?.ssr === "boolean") rule.headers = {
|
|
447
452
|
...rule.headers,
|
|
448
|
-
"x-analog-no-ssr":
|
|
453
|
+
"x-analog-no-ssr": String(!rule.ssr)
|
|
449
454
|
};
|
|
450
|
-
if (rule?.streaming ===
|
|
455
|
+
if (typeof rule?.streaming === "boolean") rule.headers = {
|
|
451
456
|
...rule.headers,
|
|
452
|
-
"x-analog-no-streaming":
|
|
457
|
+
"x-analog-no-streaming": String(!rule.streaming)
|
|
453
458
|
};
|
|
454
459
|
}
|
|
455
460
|
}
|
|
@@ -472,6 +477,7 @@ function generateSsrEntryWrapper(entryServer, template) {
|
|
|
472
477
|
// as event replay on the server.
|
|
473
478
|
import ${JSON.stringify(SERVER_MODE_ID)};
|
|
474
479
|
import { serverFetch as nitroServerFetch } from 'nitro';
|
|
480
|
+
import { getProxyRequestHeaders } from 'nitro/h3';
|
|
475
481
|
import { createFetch } from 'ofetch';
|
|
476
482
|
import renderer from ${JSON.stringify(entryServer)};
|
|
477
483
|
|
|
@@ -510,6 +516,34 @@ if (typeof globalThis.$fetch === 'undefined') {
|
|
|
510
516
|
globalThis.$fetch = ssrOFetch;
|
|
511
517
|
}
|
|
512
518
|
|
|
519
|
+
// Like h3's fetchWithEvent: in-process requests carry the incoming request's
|
|
520
|
+
// headers (minus hop-by-hop) and are cancelled with it. Conditional and range
|
|
521
|
+
// headers describe the document, not the data it loads.
|
|
522
|
+
const DOCUMENT_ONLY_HEADERS = [
|
|
523
|
+
'if-match',
|
|
524
|
+
'if-none-match',
|
|
525
|
+
'if-modified-since',
|
|
526
|
+
'if-unmodified-since',
|
|
527
|
+
'if-range',
|
|
528
|
+
'range',
|
|
529
|
+
];
|
|
530
|
+
const requestOFetch = (req) =>
|
|
531
|
+
createFetch({
|
|
532
|
+
fetch: (resource, init) => {
|
|
533
|
+
const headers = new Headers(
|
|
534
|
+
getProxyRequestHeaders(
|
|
535
|
+
{ req },
|
|
536
|
+
{ host: true, filterHeaders: DOCUMENT_ONLY_HEADERS },
|
|
537
|
+
),
|
|
538
|
+
);
|
|
539
|
+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
540
|
+
const signal = init?.signal
|
|
541
|
+
? AbortSignal.any([req.signal, init.signal])
|
|
542
|
+
: req.signal;
|
|
543
|
+
return ssrFetch(resource, { ...init, headers, signal });
|
|
544
|
+
},
|
|
545
|
+
});
|
|
546
|
+
|
|
513
547
|
export default {
|
|
514
548
|
async fetch(req) {
|
|
515
549
|
const url = new URL(req.url);
|
|
@@ -518,38 +552,73 @@ export default {
|
|
|
518
552
|
// server data loaders that read from req.url see the full path+query.
|
|
519
553
|
const requestUrl = requestPath + url.search;
|
|
520
554
|
|
|
521
|
-
if (req.headers.get('x-analog-no-ssr') === 'true') {
|
|
522
|
-
return new Response(TEMPLATE, {
|
|
523
|
-
status: 200,
|
|
524
|
-
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
525
|
-
});
|
|
526
|
-
}
|
|
527
|
-
|
|
528
555
|
const reqShim = {
|
|
529
556
|
headers: Object.fromEntries(req.headers.entries()),
|
|
530
557
|
url: requestUrl,
|
|
531
558
|
originalUrl: requestUrl,
|
|
532
559
|
connection: {},
|
|
533
560
|
};
|
|
561
|
+
// Carries the status and headers the app sets through RESPONSE.
|
|
562
|
+
const resHeaders = new Headers();
|
|
563
|
+
const resShim = {
|
|
564
|
+
statusCode: 200,
|
|
565
|
+
getHeader(name) {
|
|
566
|
+
if (name.toLowerCase() !== 'set-cookie') {
|
|
567
|
+
return resHeaders.get(name) ?? undefined;
|
|
568
|
+
}
|
|
569
|
+
const cookies = resHeaders.getSetCookie();
|
|
570
|
+
return cookies.length ? cookies : undefined;
|
|
571
|
+
},
|
|
572
|
+
hasHeader: (name) => resHeaders.has(name),
|
|
573
|
+
setHeader(name, value) {
|
|
574
|
+
resHeaders.delete(name);
|
|
575
|
+
for (const item of [value].flat()) {
|
|
576
|
+
resHeaders.append(name, String(item));
|
|
577
|
+
}
|
|
578
|
+
return resShim;
|
|
579
|
+
},
|
|
580
|
+
removeHeader: (name) => resHeaders.delete(name),
|
|
581
|
+
};
|
|
534
582
|
|
|
535
583
|
try {
|
|
536
584
|
const html = await renderer(requestUrl, TEMPLATE, {
|
|
537
585
|
req: reqShim,
|
|
586
|
+
res: resShim,
|
|
538
587
|
// Pass the ofetch-wrapped fetch — INTERNAL_FETCH is consumed by the
|
|
539
588
|
// router's request-context interceptor via \`serverFetch.raw(...)\`,
|
|
540
589
|
// which is ofetch's response-shape API. Plain fetch lacks \`.raw\`
|
|
541
590
|
// and throws TypeError during prerender/SSR.
|
|
542
|
-
fetch:
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
591
|
+
fetch: requestOFetch(req),
|
|
592
|
+
signal: req.signal,
|
|
593
|
+
waitUntil: req.waitUntil?.bind(req),
|
|
594
|
+
renderErrorsAsHtml: true,
|
|
547
595
|
});
|
|
596
|
+
const headers = new Headers(resHeaders);
|
|
597
|
+
if (!headers.has('content-type')) {
|
|
598
|
+
headers.set('content-type', 'text/html; charset=utf-8');
|
|
599
|
+
}
|
|
600
|
+
const status = resShim.statusCode;
|
|
601
|
+
if ([204, 205, 304].includes(status)) {
|
|
602
|
+
if (typeof html !== 'string') {
|
|
603
|
+
await html.cancel();
|
|
604
|
+
}
|
|
605
|
+
return new Response(null, { status, headers });
|
|
606
|
+
}
|
|
607
|
+
// So intermediaries don't cache or buffer partial HTML.
|
|
608
|
+
if (typeof html !== 'string' && !html[Symbol.for('analog.bufferedStream')]) {
|
|
609
|
+
headers.set('content-encoding', 'identity');
|
|
610
|
+
headers.set('cache-control', 'no-store, no-transform');
|
|
611
|
+
}
|
|
612
|
+
return new Response(html, { status, headers });
|
|
548
613
|
} catch (err) {
|
|
549
614
|
console.error('[analog ssr]', err);
|
|
615
|
+
const status = err?.statusCode ?? err?.status;
|
|
550
616
|
return new Response(TEMPLATE, {
|
|
551
|
-
status: 500,
|
|
552
|
-
headers: {
|
|
617
|
+
status: status >= 400 && status <= 599 ? status : 500,
|
|
618
|
+
headers: {
|
|
619
|
+
'content-type': 'text/html; charset=utf-8',
|
|
620
|
+
'cache-control': 'no-store',
|
|
621
|
+
},
|
|
553
622
|
});
|
|
554
623
|
}
|
|
555
624
|
},
|