@analogjs/vite-plugin-nitro 3.0.0-alpha.99 → 3.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/migrations/update-nitro-options/update-nitro-options.js +1 -1
  2. package/migrations/update-nitro-options/update-nitro-options.js.map +1 -1
  3. package/package.json +1 -1
  4. package/src/lib/build-server.js +2 -1
  5. package/src/lib/build-server.js.map +1 -1
  6. package/src/lib/build-sitemap.js +1 -1
  7. package/src/lib/build-sitemap.js.map +1 -1
  8. package/src/lib/build-ssr.js +3 -2
  9. package/src/lib/build-ssr.js.map +1 -1
  10. package/src/lib/hooks/post-rendering-hook.js.map +1 -1
  11. package/src/lib/plugins/dev-server-plugin.js.map +1 -1
  12. package/src/lib/plugins/page-endpoints.js.map +1 -1
  13. package/src/lib/plugins/server-fn-id-plugin.js.map +1 -1
  14. package/src/lib/utils/derive-server-fn-id.js.map +1 -1
  15. package/src/lib/utils/get-content-files.js +2 -1
  16. package/src/lib/utils/get-content-files.js.map +1 -1
  17. package/src/lib/utils/get-page-handlers.js +2 -1
  18. package/src/lib/utils/get-page-handlers.js.map +1 -1
  19. package/src/lib/utils/get-server-fn-handlers.js.map +1 -1
  20. package/src/lib/utils/i18n-prerender.js.map +1 -1
  21. package/src/lib/utils/i18n-workers.js.map +1 -1
  22. package/src/lib/utils/inject-server-fn-ids.js.map +1 -1
  23. package/src/lib/utils/register-dev-middleware.js.map +1 -1
  24. package/src/lib/utils/register-i18n-watcher.js +1 -1
  25. package/src/lib/utils/register-i18n-watcher.js.map +1 -1
  26. package/src/lib/utils/renderers.js.map +1 -1
  27. package/src/lib/utils/server-fn-endpoints.js +1 -1
  28. package/src/lib/utils/server-fn-endpoints.js.map +1 -1
  29. package/src/lib/vite-plugin-nitro.js +2 -1
  30. package/src/lib/vite-plugin-nitro.js.map +1 -1
@@ -11,7 +11,7 @@ var VITE_CONFIG_EXTENSIONS = [
11
11
  * Keys that only exist on the Analog options, so an object using any of them
12
12
  * was passed as the old first argument.
13
13
  */
14
- var ANALOG_ONLY_KEYS = new Set([
14
+ var ANALOG_ONLY_KEYS = /* @__PURE__ */ new Set([
15
15
  "ssr",
16
16
  "ssrBuildDir",
17
17
  "entryServer",
@@ -1 +1 @@
1
- {"version":3,"file":"update-nitro-options.js","names":[],"sources":["../../../migrations/update-nitro-options/update-nitro-options.ts"],"sourcesContent":["import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\n\nconst NITRO_PLUGIN_PKG = '@analogjs/vite-plugin-nitro';\nconst VITE_CONFIG_EXTENSIONS = ['.ts', '.mts', '.js', '.mjs'];\n\n/**\n * Keys that only exist on the Analog options, so an object using any of them\n * was passed as the old first argument.\n */\nconst ANALOG_ONLY_KEYS = new Set([\n 'ssr',\n 'ssrBuildDir',\n 'entryServer',\n 'index',\n 'sourceRoot',\n 'workspaceRoot',\n 'additionalPagesDirs',\n 'additionalAPIDirs',\n 'additionalServerFnDirs',\n 'apiPrefix',\n 'useAPIMiddleware',\n 'i18n',\n]);\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\nfunction isViteConfig(filePath: string): boolean {\n const file = filePath.slice(filePath.lastIndexOf('/') + 1);\n return (\n file.startsWith('vite.config.') &&\n VITE_CONFIG_EXTENSIONS.some((ext) => file.endsWith(ext))\n );\n}\n\n/** Local names `nitro()` is imported under from the plugin package. */\nfunction getNitroImportNames(sourceFile: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of sourceFile.statements) {\n if (\n !ts.isImportDeclaration(statement) ||\n !ts.isStringLiteral(statement.moduleSpecifier) ||\n statement.moduleSpecifier.text !== NITRO_PLUGIN_PKG\n ) {\n continue;\n }\n const clause = statement.importClause;\n if (clause?.name) {\n names.add(clause.name.text);\n }\n if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n if ((element.propertyName ?? element.name).text === 'nitro') {\n names.add(element.name.text);\n }\n }\n }\n }\n return names;\n}\n\nfunction usesAnalogOnlyKeys(node: ts.ObjectLiteralExpression): boolean {\n return node.properties.some(\n (prop) =>\n prop.name !== undefined &&\n (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) &&\n ANALOG_ONLY_KEYS.has(prop.name.text),\n );\n}\n\nfunction isEmptyObject(node: ts.Expression): boolean {\n return ts.isObjectLiteralExpression(node) && node.properties.length === 0;\n}\n\n/**\n * Rewrites the old `nitro(options, nitroConfig)` calls to the single\n * `nitro({ ...nitroConfig, analog: options })` argument. Returns `null` when a\n * call can't be rewritten safely.\n */\nfunction rewriteCall(\n call: ts.CallExpression,\n source: string,\n sourceFile: ts.SourceFile,\n): Edit | undefined | null {\n const text = (node: ts.Node) =>\n source.slice(node.getStart(sourceFile), node.getEnd());\n const [options, nitroConfig] = call.arguments;\n let argument: string;\n\n if (nitroConfig) {\n const analog = isEmptyObject(options) ? '' : `analog: ${text(options)}`;\n if (ts.isObjectLiteralExpression(nitroConfig)) {\n const props = nitroConfig.properties.map(text);\n argument = `{ ${[...props, analog].filter(Boolean).join(', ')} }`;\n } else {\n argument = analog\n ? `{ ...${text(nitroConfig)}, ${analog} }`\n : text(nitroConfig);\n }\n } else if (!options || isEmptyObject(options)) {\n return undefined;\n } else if (ts.isObjectLiteralExpression(options)) {\n if (!usesAnalogOnlyKeys(options)) {\n return undefined;\n }\n argument = `{ analog: ${text(options)} }`;\n } else {\n return null;\n }\n\n // Replace everything between the parentheses, including a trailing comma.\n return {\n start: call.arguments.pos,\n end: call.getEnd() - 1,\n text: argument,\n };\n}\n\nfunction transformViteConfig(\n filePath: string,\n source: string,\n): { source: string; unhandled: boolean } | null {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n );\n const names = getNitroImportNames(sourceFile);\n if (!names.size) {\n return null;\n }\n\n const edits: Edit[] = [];\n let unhandled = false;\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n names.has(node.expression.text)\n ) {\n const edit = rewriteCall(node, source, sourceFile);\n if (edit === null) {\n unhandled = true;\n } else if (edit) {\n edits.push(edit);\n }\n }\n ts.forEachChild(node, visit);\n }\n visit(sourceFile);\n\n // Apply right-to-left so earlier offsets stay valid.\n let result = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);\n }\n return { source: result, unhandled };\n}\n\nexport default function updateNitroOptions(): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const rewrittenFiles: string[] = [];\n const unhandledFiles: string[] = [];\n\n tree.visit((filePath) => {\n if (filePath.includes('/node_modules/') || !isViteConfig(filePath)) {\n return;\n }\n const content = tree.read(filePath);\n if (!content) return;\n\n const source = content.toString('utf-8');\n const transformed = transformViteConfig(filePath, source);\n if (!transformed) return;\n\n if (transformed.source !== source) {\n tree.overwrite(filePath, transformed.source);\n rewrittenFiles.push(filePath);\n }\n if (transformed.unhandled) {\n unhandledFiles.push(filePath);\n }\n });\n\n if (rewrittenFiles.length) {\n context.logger.info(\n `Moved nitro() options to its single argument in: ${rewrittenFiles.join(', ')}`,\n );\n }\n if (unhandledFiles.length) {\n context.logger.warn(\n `Could not rewrite every nitro() call in: ${unhandledFiles.join(', ')}. ` +\n 'nitro() now takes the Nitro config, with Analog options under `analog`: ' +\n '`nitro({ ...nitroConfig, analog: options })`.',\n );\n }\n\n return tree;\n };\n}\n"],"mappings":";;AAGA,IAAM,mBAAmB;AACzB,IAAM,yBAAyB;CAAC;CAAO;CAAQ;CAAO;CAAO;;;;;AAM7D,IAAM,mBAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAQF,SAAS,aAAa,UAA2B;CAC/C,MAAM,OAAO,SAAS,MAAM,SAAS,YAAY,IAAI,GAAG,EAAE;AAC1D,QACE,KAAK,WAA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,OAAI,CAAC,QAAS;GAEd,MAAM,SAAS,QAAQ,SAAS,QAAQ;GACxC,MAAM,cAAc,oBAAoB,UAAU,OAAO;AACzD,OAAI,CAAC,YAAa;AAElB,OAAI,YAAY,WAAW,QAAQ;AACjC,SAAK,UAAU,UAAU,YAAY,OAAO;AAC5C,mBAAe,KAAK,SAAS;;AAE/B,OAAI,YAAY,UACd,gBAAe,KAAK,SAAS;IAE/B;AAEF,MAAI,eAAe,OACjB,SAAQ,OAAO,KACb,oDAAoD,eAAe,KAAK,KAAK,GAC9E;AAEH,MAAI,eAAe,OACjB,SAAQ,OAAO,KACb,4CAA4C,eAAe,KAAK,KAAK,CAAC,6HAGvE;AAGH,SAAO"}
1
+ {"version":3,"file":"update-nitro-options.js","names":[],"sources":["../../../migrations/update-nitro-options/update-nitro-options.ts"],"sourcesContent":["import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\n\nconst NITRO_PLUGIN_PKG = '@analogjs/vite-plugin-nitro';\nconst VITE_CONFIG_EXTENSIONS = ['.ts', '.mts', '.js', '.mjs'];\n\n/**\n * Keys that only exist on the Analog options, so an object using any of them\n * was passed as the old first argument.\n */\nconst ANALOG_ONLY_KEYS = new Set([\n 'ssr',\n 'ssrBuildDir',\n 'entryServer',\n 'index',\n 'sourceRoot',\n 'workspaceRoot',\n 'additionalPagesDirs',\n 'additionalAPIDirs',\n 'additionalServerFnDirs',\n 'apiPrefix',\n 'useAPIMiddleware',\n 'i18n',\n]);\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\nfunction isViteConfig(filePath: string): boolean {\n const file = filePath.slice(filePath.lastIndexOf('/') + 1);\n return (\n file.startsWith('vite.config.') &&\n VITE_CONFIG_EXTENSIONS.some((ext) => file.endsWith(ext))\n );\n}\n\n/** Local names `nitro()` is imported under from the plugin package. */\nfunction getNitroImportNames(sourceFile: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of sourceFile.statements) {\n if (\n !ts.isImportDeclaration(statement) ||\n !ts.isStringLiteral(statement.moduleSpecifier) ||\n statement.moduleSpecifier.text !== NITRO_PLUGIN_PKG\n ) {\n continue;\n }\n const clause = statement.importClause;\n if (clause?.name) {\n names.add(clause.name.text);\n }\n if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n if ((element.propertyName ?? element.name).text === 'nitro') {\n names.add(element.name.text);\n }\n }\n }\n }\n return names;\n}\n\nfunction usesAnalogOnlyKeys(node: ts.ObjectLiteralExpression): boolean {\n return node.properties.some(\n (prop) =>\n prop.name !== undefined &&\n (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) &&\n ANALOG_ONLY_KEYS.has(prop.name.text),\n );\n}\n\nfunction isEmptyObject(node: ts.Expression): boolean {\n return ts.isObjectLiteralExpression(node) && node.properties.length === 0;\n}\n\n/**\n * Rewrites the old `nitro(options, nitroConfig)` calls to the single\n * `nitro({ ...nitroConfig, analog: options })` argument. Returns `null` when a\n * call can't be rewritten safely.\n */\nfunction rewriteCall(\n call: ts.CallExpression,\n source: string,\n sourceFile: ts.SourceFile,\n): Edit | undefined | null {\n const text = (node: ts.Node) =>\n source.slice(node.getStart(sourceFile), node.getEnd());\n const [options, nitroConfig] = call.arguments;\n let argument: string;\n\n if (nitroConfig) {\n const analog = isEmptyObject(options) ? '' : `analog: ${text(options)}`;\n if (ts.isObjectLiteralExpression(nitroConfig)) {\n const props = nitroConfig.properties.map(text);\n argument = `{ ${[...props, analog].filter(Boolean).join(', ')} }`;\n } else {\n argument = analog\n ? `{ ...${text(nitroConfig)}, ${analog} }`\n : text(nitroConfig);\n }\n } else if (!options || isEmptyObject(options)) {\n return undefined;\n } else if (ts.isObjectLiteralExpression(options)) {\n if (!usesAnalogOnlyKeys(options)) {\n return undefined;\n }\n argument = `{ analog: ${text(options)} }`;\n } else {\n return null;\n }\n\n // Replace everything between the parentheses, including a trailing comma.\n return {\n start: call.arguments.pos,\n end: call.getEnd() - 1,\n text: argument,\n };\n}\n\nfunction transformViteConfig(\n filePath: string,\n source: string,\n): { source: string; unhandled: boolean } | null {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n );\n const names = getNitroImportNames(sourceFile);\n if (!names.size) {\n return null;\n }\n\n const edits: Edit[] = [];\n let unhandled = false;\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n names.has(node.expression.text)\n ) {\n const edit = rewriteCall(node, source, sourceFile);\n if (edit === null) {\n unhandled = true;\n } else if (edit) {\n edits.push(edit);\n }\n }\n ts.forEachChild(node, visit);\n }\n visit(sourceFile);\n\n // Apply right-to-left so earlier offsets stay valid.\n let result = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);\n }\n return { source: result, unhandled };\n}\n\nexport default function updateNitroOptions(): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const rewrittenFiles: string[] = [];\n const unhandledFiles: string[] = [];\n\n tree.visit((filePath) => {\n if (filePath.includes('/node_modules/') || !isViteConfig(filePath)) {\n return;\n }\n const content = tree.read(filePath);\n if (!content) return;\n\n const source = content.toString('utf-8');\n const transformed = transformViteConfig(filePath, source);\n if (!transformed) return;\n\n if (transformed.source !== source) {\n tree.overwrite(filePath, transformed.source);\n rewrittenFiles.push(filePath);\n }\n if (transformed.unhandled) {\n unhandledFiles.push(filePath);\n }\n });\n\n if (rewrittenFiles.length) {\n context.logger.info(\n `Moved nitro() options to its single argument in: ${rewrittenFiles.join(', ')}`,\n );\n }\n if (unhandledFiles.length) {\n context.logger.warn(\n `Could not rewrite every nitro() call in: ${unhandledFiles.join(', ')}. ` +\n 'nitro() now takes the Nitro config, with Analog options under `analog`: ' +\n '`nitro({ ...nitroConfig, analog: options })`.',\n );\n }\n\n return tree;\n };\n}\n"],"mappings":";;AAGA,IAAM,mBAAmB;AACzB,IAAM,yBAAyB;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,KAAK,IAAI,KAAK,OAAO,OAAO,MAAM,KAAK,GAAG;CAE1E,OAAO;EAAE,QAAQ;EAAQ;CAAU;AACrC;AAEA,SAAwB,qBAA2B;CACjD,QAAQ,MAAY,YAA8B;EAChD,MAAM,iBAA2B,CAAC;EAClC,MAAM,iBAA2B,CAAC;EAElC,KAAK,OAAO,aAAa;GACvB,IAAI,SAAS,SAAS,gBAAgB,KAAK,CAAC,aAAa,QAAQ,GAC/D;GAEF,MAAM,UAAU,KAAK,KAAK,QAAQ;GAClC,IAAI,CAAC,SAAS;GAEd,MAAM,SAAS,QAAQ,SAAS,OAAO;GACvC,MAAM,cAAc,oBAAoB,UAAU,MAAM;GACxD,IAAI,CAAC,aAAa;GAElB,IAAI,YAAY,WAAW,QAAQ;IACjC,KAAK,UAAU,UAAU,YAAY,MAAM;IAC3C,eAAe,KAAK,QAAQ;GAC9B;GACA,IAAI,YAAY,WACd,eAAe,KAAK,QAAQ;EAEhC,CAAC;EAED,IAAI,eAAe,QACjB,QAAQ,OAAO,KACb,oDAAoD,eAAe,KAAK,IAAI,GAC9E;EAEF,IAAI,eAAe,QACjB,QAAQ,OAAO,KACb,4CAA4C,eAAe,KAAK,IAAI,EAAE,4HAGxE;EAGF,OAAO;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/vite-plugin-nitro",
3
- "version": "3.0.0-alpha.99",
3
+ "version": "3.0.0-beta.10",
4
4
  "description": "A Vite plugin for adding a nitro API server",
5
5
  "type": "module",
6
6
  "author": "Brandon Roberts <robertsbt@gmail.com>",
@@ -63,7 +63,8 @@ async function buildServer(options, nitroConfig = {}, routeSourceFiles, i18nWork
63
63
  prerenderer = renderer;
64
64
  renderer.hooks.hook("compiled", async () => {
65
65
  const fileName = renderer.options.rollupConfig?.output?.entryFileNames;
66
- closePrerenderer = (await import(pathToFileURL(join(renderer.options.output.serverDir, typeof fileName === "string" ? fileName : "index.mjs")).href)).closePrerenderer;
66
+ const entry = join(renderer.options.output.serverDir, typeof fileName === "string" ? fileName : "index.mjs");
67
+ closePrerenderer = (await import(pathToFileURL(entry).href)).closePrerenderer;
67
68
  });
68
69
  }) : void 0;
69
70
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"build-server.js","names":[],"sources":["../../../src/lib/build-server.ts"],"sourcesContent":["import { Nitro, NitroConfig, copyPublicAssets, prerender } from 'nitropack';\nimport { createNitro, build, prepare } from 'nitropack';\nimport { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\n\nimport { Options } from './options.js';\nimport { addPostRenderingHooks } from './hooks/post-rendering-hook.js';\nimport { validateI18nWorkers } from './utils/i18n-workers.js';\nimport { createSsrStreamRenderer } from './utils/renderers.js';\n\nexport async function buildServer(\n options?: Options,\n nitroConfig: NitroConfig = {},\n routeSourceFiles?: Record<string, string>,\n i18nWorkers = false,\n): Promise<void> {\n if (i18nWorkers && options?.i18n) {\n validateI18nWorkers(options, nitroConfig);\n nitroConfig = {\n ...nitroConfig,\n entry: join(\n dirname(fileURLToPath(import.meta.url)),\n 'runtime/locale-worker-entry.mjs',\n ),\n externals: {\n ...nitroConfig.externals,\n inline: [...(nitroConfig.externals?.inline ?? []), '@analogjs/router'],\n },\n replace: {\n ...nitroConfig.replace,\n ANALOG_I18N_FIXED_LOCALE: \"process.env['ANALOG_I18N_LOCALE']\",\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(options.i18n.defaultLocale),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n },\n virtual: {\n ...nitroConfig.virtual,\n '#analog/i18n-workers': `export default ${JSON.stringify({\n locales: options.i18n.locales,\n defaultLocale: options.i18n.defaultLocale,\n baseURL: nitroConfig.baseURL || '/',\n })}`,\n },\n };\n }\n const nitro = await createNitro({\n dev: false,\n preset: process.env['BUILD_PRESET'],\n ...nitroConfig,\n });\n\n try {\n if (options?.experimental?.streaming) {\n nitro.hooks.hook('prerender:init', (renderer) => {\n renderer.options.virtual = {\n ...renderer.options.virtual,\n '#ANALOG_SSR_RENDERER': createSsrStreamRenderer(true),\n };\n });\n }\n if (options?.prerender?.postRenderingHooks) {\n addPostRenderingHooks(nitro, options.prerender.postRenderingHooks);\n }\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n\n if (\n options?.ssr &&\n nitroConfig?.prerender?.routes &&\n (nitroConfig?.prerender?.routes.find((route) => route === '/') ||\n nitroConfig?.prerender?.routes?.length === 0)\n ) {\n const indexFileExts = ['', '.br', '.gz'];\n\n indexFileExts.forEach((fileExt) => {\n // Remove the root index.html(.br|.gz) files\n const indexFilePath = `${nitroConfig?.output?.publicDir}/index.html${fileExt ? `${fileExt}` : ''}`;\n\n if (existsSync(indexFilePath)) {\n unlinkSync(indexFilePath);\n }\n });\n }\n\n if (\n nitroConfig?.prerender?.routes &&\n nitroConfig?.prerender?.routes?.length > 0\n ) {\n console.log(`Prerendering static pages...`);\n let closePrerenderer: (() => Promise<void>) | undefined;\n let prerenderer: Nitro | undefined;\n const unhook = i18nWorkers\n ? nitro.hooks.hook('prerender:init', (renderer) => {\n prerenderer = renderer;\n renderer.hooks.hook('compiled', async () => {\n const fileName =\n renderer.options.rollupConfig?.output?.entryFileNames;\n const entry = join(\n renderer.options.output.serverDir,\n typeof fileName === 'string' ? fileName : 'index.mjs',\n );\n // Capture cleanup only after a successful build, before Nitro starts rendering.\n const runtime = await import(pathToFileURL(entry).href);\n closePrerenderer = runtime.closePrerenderer;\n });\n })\n : undefined;\n try {\n await prerender(nitro);\n } finally {\n unhook?.();\n try {\n await closePrerenderer?.();\n } finally {\n await prerenderer?.close();\n }\n }\n }\n\n if (routeSourceFiles && Object.keys(routeSourceFiles).length > 0) {\n const publicDir = nitroConfig?.output?.publicDir;\n if (!publicDir) {\n throw new Error(\n 'Nitro public output directory is required to write route source files.',\n );\n }\n\n for (const [route, content] of Object.entries(routeSourceFiles)) {\n const outputPath = join(publicDir, `${route}.md`);\n const outputDir = dirname(outputPath);\n\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n writeFileSync(outputPath, content, 'utf8');\n }\n }\n\n if (!options?.static) {\n console.log('Building Server...');\n await build(nitro);\n }\n } finally {\n await nitro.close();\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,YACpB,SACA,cAA2B,EAAE,EAC7B,kBACA,cAAc,OACC;AACf,KAAI,eAAe,SAAS,MAAM;AAChC,sBAAoB,SAAS,YAAY;AACzC,gBAAc;GACZ,GAAG;GACH,OAAO,KACL,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC,EACvC,kCACD;GACD,WAAW;IACT,GAAG,YAAY;IACf,QAAQ,CAAC,GAAI,YAAY,WAAW,UAAU,EAAE,EAAG,mBAAmB;IACvE;GACD,SAAS;IACP,GAAG,YAAY;IACf,0BAA0B;IAC1B,4BAA4B,KAAK,UAAU,QAAQ,KAAK,cAAc;IACtE,qBAAqB,KAAK,UAAU,QAAQ,KAAK,QAAQ;IAC1D;GACD,SAAS;IACP,GAAG,YAAY;IACf,wBAAwB,kBAAkB,KAAK,UAAU;KACvD,SAAS,QAAQ,KAAK;KACtB,eAAe,QAAQ,KAAK;KAC5B,SAAS,YAAY,WAAW;KACjC,CAAC;IACH;GACF;;CAEH,MAAM,QAAQ,MAAM,YAAY;EAC9B,KAAK;EACL,QAAQ,QAAQ,IAAI;EACpB,GAAG;EACJ,CAAC;AAEF,KAAI;AACF,MAAI,SAAS,cAAc,UACzB,OAAM,MAAM,KAAK,mBAAmB,aAAa;AAC/C,YAAS,QAAQ,UAAU;IACzB,GAAG,SAAS,QAAQ;IACpB,wBAAwB,wBAAwB,KAAK;IACtD;IACD;AAEJ,MAAI,SAAS,WAAW,mBACtB,uBAAsB,OAAO,QAAQ,UAAU,mBAAmB;AAGpE,QAAM,QAAQ,MAAM;AACpB,QAAM,iBAAiB,MAAM;AAE7B,MACE,SAAS,OACT,a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SAAM,MAAM,MAAM;;WAEZ;AACR,QAAM,MAAM,OAAO"}
1
+ {"version":3,"file":"build-server.js","names":[],"sources":["../../../src/lib/build-server.ts"],"sourcesContent":["import { Nitro, NitroConfig, copyPublicAssets, prerender } from 'nitropack';\nimport { createNitro, build, prepare } from 'nitropack';\nimport { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\n\nimport { Options } from './options.js';\nimport { addPostRenderingHooks } from './hooks/post-rendering-hook.js';\nimport { validateI18nWorkers } from './utils/i18n-workers.js';\nimport { createSsrStreamRenderer } from './utils/renderers.js';\n\nexport async function buildServer(\n options?: Options,\n nitroConfig: NitroConfig = {},\n routeSourceFiles?: Record<string, string>,\n i18nWorkers = false,\n): Promise<void> {\n if (i18nWorkers && options?.i18n) {\n validateI18nWorkers(options, nitroConfig);\n nitroConfig = {\n ...nitroConfig,\n entry: join(\n dirname(fileURLToPath(import.meta.url)),\n 'runtime/locale-worker-entry.mjs',\n ),\n externals: {\n ...nitroConfig.externals,\n inline: [...(nitroConfig.externals?.inline ?? []), '@analogjs/router'],\n },\n replace: {\n ...nitroConfig.replace,\n ANALOG_I18N_FIXED_LOCALE: \"process.env['ANALOG_I18N_LOCALE']\",\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(options.i18n.defaultLocale),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n },\n virtual: {\n ...nitroConfig.virtual,\n '#analog/i18n-workers': `export default ${JSON.stringify({\n locales: options.i18n.locales,\n defaultLocale: options.i18n.defaultLocale,\n baseURL: nitroConfig.baseURL || '/',\n })}`,\n },\n };\n }\n const nitro = await createNitro({\n dev: false,\n preset: process.env['BUILD_PRESET'],\n ...nitroConfig,\n });\n\n try {\n if (options?.experimental?.streaming) {\n nitro.hooks.hook('prerender:init', (renderer) => {\n renderer.options.virtual = {\n ...renderer.options.virtual,\n '#ANALOG_SSR_RENDERER': createSsrStreamRenderer(true),\n };\n });\n }\n if (options?.prerender?.postRenderingHooks) {\n addPostRenderingHooks(nitro, options.prerender.postRenderingHooks);\n }\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n\n if (\n options?.ssr &&\n nitroConfig?.prerender?.routes &&\n (nitroConfig?.prerender?.routes.find((route) => route === '/') ||\n nitroConfig?.prerender?.routes?.length === 0)\n ) {\n const indexFileExts = ['', '.br', '.gz'];\n\n indexFileExts.forEach((fileExt) => {\n // Remove the root index.html(.br|.gz) files\n const indexFilePath = `${nitroConfig?.output?.publicDir}/index.html${fileExt ? `${fileExt}` : ''}`;\n\n if (existsSync(indexFilePath)) {\n unlinkSync(indexFilePath);\n }\n });\n }\n\n if (\n nitroConfig?.prerender?.routes &&\n nitroConfig?.prerender?.routes?.length > 0\n ) {\n console.log(`Prerendering static pages...`);\n let closePrerenderer: (() => Promise<void>) | undefined;\n let prerenderer: Nitro | undefined;\n const unhook = i18nWorkers\n ? nitro.hooks.hook('prerender:init', (renderer) => {\n prerenderer = renderer;\n renderer.hooks.hook('compiled', async () => {\n const fileName =\n renderer.options.rollupConfig?.output?.entryFileNames;\n const entry = join(\n renderer.options.output.serverDir,\n typeof fileName === 'string' ? fileName : 'index.mjs',\n );\n // Capture cleanup only after a successful build, before Nitro starts rendering.\n const runtime = await import(pathToFileURL(entry).href);\n closePrerenderer = runtime.closePrerenderer;\n });\n })\n : undefined;\n try {\n await prerender(nitro);\n } finally {\n unhook?.();\n try {\n await closePrerenderer?.();\n } finally {\n await prerenderer?.close();\n }\n }\n }\n\n if (routeSourceFiles && Object.keys(routeSourceFiles).length > 0) {\n const publicDir = nitroConfig?.output?.publicDir;\n if (!publicDir) {\n throw new Error(\n 'Nitro public output directory is required to write route source files.',\n );\n }\n\n for (const [route, content] of Object.entries(routeSourceFiles)) {\n const outputPath = join(publicDir, `${route}.md`);\n const outputDir = dirname(outputPath);\n\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n writeFileSync(outputPath, content, 'utf8');\n }\n }\n\n if (!options?.static) {\n console.log('Building Server...');\n await build(nitro);\n }\n } finally {\n await nitro.close();\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,YACpB,SACA,cAA2B,CAAC,GAC5B,kBACA,cAAc,OACC;CACf,IAAI,eAAe,SAAS,MAAM;EAChC,oBAAoB,SAAS,WAAW;EACxC,cAAc;GACZ,GAAG;GACH,OAAO,KACL,QAAQ,cAAc,YAAY,GAAG,CAAC,GACtC,iCACF;GACA,WAAW;IACT,GAAG,YAAY;IACf,QAAQ,CAAC,GAAI,YAAY,WAAW,UAAU,CAAC,GAAI,kBAAkB;GACvE;GACA,SAAS;IACP,GAAG,YAAY;IACf,0BAA0B;IAC1B,4BAA4B,KAAK,UAAU,QAAQ,KAAK,aAAa;IACrE,qBAAqB,KAAK,UAAU,QAAQ,KAAK,OAAO;GAC1D;GACA,SAAS;IACP,GAAG,YAAY;IACf,wBAAwB,kBAAkB,KAAK,UAAU;KACvD,SAAS,QAAQ,KAAK;KACtB,eAAe,QAAQ,KAAK;KAC5B,SAAS,YAAY,WAAW;IAClC,CAAC;GACH;EACF;CACF;CACA,MAAM,QAAQ,MAAM,YAAY;EAC9B,KAAK;EACL,QAAQ,QAAQ,IAAI;EACpB,GAAG;CACL,CAAC;CAED,IAAI;EACF,IAAI,SAAS,cAAc,WACzB,MAAM,MAAM,KAAK,mBAAmB,aAAa;GAC/C,SAAS,QAAQ,UAAU;IACzB,GAAG,SAAS,QAAQ;IACpB,wBAAwB,wBAAwB,IAAI;GACtD;EACF,CAAC;EAEH,IAAI,SAAS,WAAW,oBACtB,sBAAsB,OAAO,QAAQ,UAAU,kBAAkB;EAGnE,MAAM,QAAQ,KAAK;EACnB,MAAM,iBAAiB,KAAK;EAE5B,IACE,SAAS,OACT,aAAa,WAAW,WACvB,aAAa,WAAW,OAAO,MAAM,UAAU,UAAU,GAAG,KAC3D,aAAa,WAAW,QAAQ,WAAW,IAI7C;GA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AM,KAAK;EACnB;CACF,UAAU;EACR,MAAM,MAAM,MAAM;CACpB;AACF"}
@@ -93,6 +93,6 @@ async function optionHasRoutes(routes) {
93
93
  return routeList.filter(Boolean);
94
94
  }
95
95
  //#endregion
96
- export { buildSitemap };
96
+ export { buildSitemap, getHreflangAlternates, stripLocalePrefix };
97
97
 
98
98
  //# sourceMappingURL=build-sitemap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"build-sitemap.js","names":[],"sources":["../../../src/lib/build-sitemap.ts"],"sourcesContent":["import { writeFileSync } from 'node:fs';\nimport { XMLBuilder } from 'xmlbuilder2/lib/interfaces';\nimport { create } from 'xmlbuilder2';\nimport { UserConfig } from 'vite';\nimport { resolve } from 'node:path';\nimport {\n I18nPrerenderOptions,\n PrerenderContentFile,\n PrerenderSitemapConfig,\n SitemapConfig,\n} from './options';\n\nexport type PagesJson = {\n page: string;\n lastMod: string;\n changefreq?: string;\n priority?: string;\n};\n\nexport async function buildSitemap(\n config: UserConfig,\n sitemapConfig: SitemapConfig,\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n outputDir: string,\n routeSitemaps: Record<\n string,\n PrerenderSitemapConfig | (() => PrerenderSitemapConfig) | undefined\n >,\n i18nOptions?: I18nPrerenderOptions,\n): Promise<void> {\n const routeList: string[] = await optionHasRoutes(routes);\n\n if (routeList.length) {\n const slash = checkSlash(sitemapConfig.host || '');\n const sitemapData: PagesJson[] = routeList.map((page: string) => {\n const url = `${slash}${page.replace(/^\\/+/g, '')}`;\n const config = routeSitemaps[url];\n const props = typeof config === 'object' ? config : config?.();\n\n return {\n page: `${sitemapConfig.host}${url}`,\n lastMod: props?.lastmod ?? new Date().toISOString().split('T')[0],\n changefreq: props?.changefreq,\n priority: props?.priority,\n };\n });\n\n const hasI18n = i18nOptions && i18nOptions.locales.length > 1;\n const sitemap = createXml('urlset', hasI18n);\n\n for (const item of sitemapData) {\n const page = sitemap.ele('url');\n page.ele('loc').txt(item.page);\n page.ele('lastmod').txt(item.lastMod);\n\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq);\n }\n\n if (item.priority) {\n page.ele('priority').txt(item.priority);\n }\n\n // Add hreflang alternate links for each locale\n if (hasI18n) {\n const alternates = getHreflangAlternates(\n item.page,\n sitemapConfig.host,\n i18nOptions,\n );\n for (const alt of alternates) {\n page\n .ele('xhtml:link')\n .att('rel', 'alternate')\n .att('hreflang', alt.locale)\n .att('href', alt.href);\n }\n }\n }\n\n const mapPath = `${resolve(outputDir)}/sitemap.xml`;\n try {\n console.log(`Writing sitemap at ${mapPath}`);\n writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));\n } catch (e) {\n console.error(`Unable to write file at ${mapPath}`, e);\n }\n }\n}\n\n/**\n * Generates hreflang alternate URLs for a given page URL.\n * For a URL like `https://example.com/fr/about`, it produces alternates\n * for all configured locales.\n */\nexport function getHreflangAlternates(\n pageUrl: string,\n host: string,\n i18n: I18nPrerenderOptions,\n): { locale: string; href: string }[] {\n const alternates: { locale: string; href: string }[] = [];\n const normalizedHost = host.replace(/\\/+$/, '');\n\n // Extract the path portion after the host\n const path = pageUrl.replace(normalizedHost, '');\n\n // Strip locale prefix to get the base path\n const basePath = stripLocalePrefix(path, i18n.locales);\n\n for (const locale of i18n.locales) {\n const localizedPath =\n basePath === '/' || basePath === ''\n ? `/${locale}`\n : `/${locale}${basePath}`;\n alternates.push({\n locale,\n href: `${normalizedHost}${localizedPath}`,\n });\n }\n\n // Add x-default pointing to the default locale variant\n const defaultPath =\n basePath === '/' || basePath === ''\n ? `/${i18n.defaultLocale}`\n : `/${i18n.defaultLocale}${basePath}`;\n alternates.push({\n locale: 'x-default',\n href: `${normalizedHost}${defaultPath}`,\n });\n\n return alternates;\n}\n\n/**\n * Strips a locale prefix from a URL path.\n * E.g., '/fr/about' -> '/about', '/en' -> '/'\n */\nexport function stripLocalePrefix(path: string, locales: string[]): string {\n const segments = path.split('/').filter(Boolean);\n if (segments.length > 0 && locales.includes(segments[0])) {\n const rest = segments.slice(1).join('/');\n return rest ? `/${rest}` : '/';\n }\n return path || '/';\n}\n\nfunction createXml(\n elementName: 'urlset' | 'sitemapindex',\n includeXhtml = false,\n): XMLBuilder {\n const attrs: Record<string, string> = {\n xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',\n };\n if (includeXhtml) {\n attrs['xmlns:xhtml'] = 'http://www.w3.org/1999/xhtml';\n }\n\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, attrs)\n .com(`This file was automatically generated by Analog.`);\n}\n\nfunction checkSlash(host: string): string {\n const finalChar = host.slice(-1);\n return finalChar === '/' ? '' : '/';\n}\n\nasync function optionHasRoutes(\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n): Promise<string[]> {\n let routeList: (string | undefined)[];\n\n if (typeof routes === 'function') {\n // returns an array or undefined\n routeList = await routes();\n } else if (Array.isArray(routes)) {\n // returns an array of strings\n routeList = routes;\n } else {\n // default it to an empty of array\n routeList = [];\n }\n\n return routeList.filter(Boolean) as string[];\n}\n"],"mappings":";;;;AAmBA,eAAsB,aACpB,QACA,eACA,QACA,WACA,eAIA,aACe;CACf,MAAM,YAAsB,MAAM,gBAAgB,OAAO;AAEzD,KAAI,UAAU,QAAQ;EACpB,MAAM,QAAQ,WAAW,cAAc,QAAQ,GAAG;EAClD,MAAM,cAA2B,UAAU,KAAK,SAAiB;GAC/D,MAAM,MAAM,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;GAChD,MAAM,SAAS,cAAc;GAC7B,MAAM,QAAQ,OAAO,WAAW,WAAW,SAAS,UAAU;AAE9D,UAAO;IACL,MAAM,GAAG,cAAc,OAAO;IAC9B,SAAS,OAAO,4BAAW,IAAI,MAAM,EAAC,aAAa,CAAC,MAAM,IAAI,CAAC;IAC/D,YAAY,OAAO;IACnB,UAAU,OAAO;IAClB;IACD;EAEF,MAAM,UAAU,eAAe,YAAY,QAAQ,SAAS;EAC5D,MAAM,UAAU,UAAU,UAAU,QAA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F,QAAO;;;;;;AAOT,SAAgB,kBAAkB,MAAc,SAA2B;CACzE,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;AAChD,KAAI,SAAS,SAAS,KAAK,QAAQ,SAAS,SAAS,GAAG,EAAE;EACxD,MAAM,OAAO,SAAS,MAAM,EAAE,CAAC,KAAK,IAAI;AACxC,SAAO,OAAO,IAAI,SAAS;;AAE7B,QAAO,QAAQ;;AAGjB,SAAS,UACP,aACA,eAAe,OACH;CACZ,MAAM,QAAgC,EACpC,OAAO,+CACR;AACD,KAAI,aACF,OAAM,iBAAiB;AAGzB,QAAO,OAAO;EAAE,SAAS;EAAO,UAAU;EAAS,CAAC,CACjD,IAAI,aAAa,MAAM,CACvB,IAAI,mDAAmD;;AAG5D,SAAS,WAAW,MAAsB;AAExC,QADkB,KAAK,MAAM,GAAG,KACX,MAAM,KAAK;;AAGlC,eAAe,gBACb,QACmB;CACnB,IAAI;AAEJ,KAAI,OAAO,WAAW,WAEpB,aAAY,MAAM,QAAQ;UACjB,MAAM,QAAQ,OAAO,CAE9B,aAAY;KAGZ,aAAY,EAAE;AAGhB,QAAO,UAAU,OAAO,QAAQ"}
1
+ {"version":3,"file":"build-sitemap.js","names":[],"sources":["../../../src/lib/build-sitemap.ts"],"sourcesContent":["import { writeFileSync } from 'node:fs';\nimport { XMLBuilder } from 'xmlbuilder2/lib/interfaces';\nimport { create } from 'xmlbuilder2';\nimport { UserConfig } from 'vite';\nimport { resolve } from 'node:path';\nimport {\n I18nPrerenderOptions,\n PrerenderContentFile,\n PrerenderSitemapConfig,\n SitemapConfig,\n} from './options';\n\nexport type PagesJson = {\n page: string;\n lastMod: string;\n changefreq?: string;\n priority?: string;\n};\n\nexport async function buildSitemap(\n config: UserConfig,\n sitemapConfig: SitemapConfig,\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n outputDir: string,\n routeSitemaps: Record<\n string,\n PrerenderSitemapConfig | (() => PrerenderSitemapConfig) | undefined\n >,\n i18nOptions?: I18nPrerenderOptions,\n): Promise<void> {\n const routeList: string[] = await optionHasRoutes(routes);\n\n if (routeList.length) {\n const slash = checkSlash(sitemapConfig.host || '');\n const sitemapData: PagesJson[] = routeList.map((page: string) => {\n const url = `${slash}${page.replace(/^\\/+/g, '')}`;\n const config = routeSitemaps[url];\n const props = typeof config === 'object' ? config : config?.();\n\n return {\n page: `${sitemapConfig.host}${url}`,\n lastMod: props?.lastmod ?? new Date().toISOString().split('T')[0],\n changefreq: props?.changefreq,\n priority: props?.priority,\n };\n });\n\n const hasI18n = i18nOptions && i18nOptions.locales.length > 1;\n const sitemap = createXml('urlset', hasI18n);\n\n for (const item of sitemapData) {\n const page = sitemap.ele('url');\n page.ele('loc').txt(item.page);\n page.ele('lastmod').txt(item.lastMod);\n\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq);\n }\n\n if (item.priority) {\n page.ele('priority').txt(item.priority);\n }\n\n // Add hreflang alternate links for each locale\n if (hasI18n) {\n const alternates = getHreflangAlternates(\n item.page,\n sitemapConfig.host,\n i18nOptions,\n );\n for (const alt of alternates) {\n page\n .ele('xhtml:link')\n .att('rel', 'alternate')\n .att('hreflang', alt.locale)\n .att('href', alt.href);\n }\n }\n }\n\n const mapPath = `${resolve(outputDir)}/sitemap.xml`;\n try {\n console.log(`Writing sitemap at ${mapPath}`);\n writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));\n } catch (e) {\n console.error(`Unable to write file at ${mapPath}`, e);\n }\n }\n}\n\n/**\n * Generates hreflang alternate URLs for a given page URL.\n * For a URL like `https://example.com/fr/about`, it produces alternates\n * for all configured locales.\n */\nexport function getHreflangAlternates(\n pageUrl: string,\n host: string,\n i18n: I18nPrerenderOptions,\n): { locale: string; href: string }[] {\n const alternates: { locale: string; href: string }[] = [];\n const normalizedHost = host.replace(/\\/+$/, '');\n\n // Extract the path portion after the host\n const path = pageUrl.replace(normalizedHost, '');\n\n // Strip locale prefix to get the base path\n const basePath = stripLocalePrefix(path, i18n.locales);\n\n for (const locale of i18n.locales) {\n const localizedPath =\n basePath === '/' || basePath === ''\n ? `/${locale}`\n : `/${locale}${basePath}`;\n alternates.push({\n locale,\n href: `${normalizedHost}${localizedPath}`,\n });\n }\n\n // Add x-default pointing to the default locale variant\n const defaultPath =\n basePath === '/' || basePath === ''\n ? `/${i18n.defaultLocale}`\n : `/${i18n.defaultLocale}${basePath}`;\n alternates.push({\n locale: 'x-default',\n href: `${normalizedHost}${defaultPath}`,\n });\n\n return alternates;\n}\n\n/**\n * Strips a locale prefix from a URL path.\n * E.g., '/fr/about' -> '/about', '/en' -> '/'\n */\nexport function stripLocalePrefix(path: string, locales: string[]): string {\n const segments = path.split('/').filter(Boolean);\n if (segments.length > 0 && locales.includes(segments[0])) {\n const rest = segments.slice(1).join('/');\n return rest ? `/${rest}` : '/';\n }\n return path || '/';\n}\n\nfunction createXml(\n elementName: 'urlset' | 'sitemapindex',\n includeXhtml = false,\n): XMLBuilder {\n const attrs: Record<string, string> = {\n xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',\n };\n if (includeXhtml) {\n attrs['xmlns:xhtml'] = 'http://www.w3.org/1999/xhtml';\n }\n\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, attrs)\n .com(`This file was automatically generated by Analog.`);\n}\n\nfunction checkSlash(host: string): string {\n const finalChar = host.slice(-1);\n return finalChar === '/' ? '' : '/';\n}\n\nasync function optionHasRoutes(\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n): Promise<string[]> {\n let routeList: (string | undefined)[];\n\n if (typeof routes === 'function') {\n // returns an array or undefined\n routeList = await routes();\n } else if (Array.isArray(routes)) {\n // returns an array of strings\n routeList = routes;\n } else {\n // default it to an empty of array\n routeList = [];\n }\n\n return routeList.filter(Boolean) as string[];\n}\n"],"mappings":";;;;AAmBA,eAAsB,aACpB,QACA,eACA,QACA,WACA,eAIA,aACe;CACf,MAAM,YAAsB,MAAM,gBAAgB,MAAM;CAExD,IA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AAY,MAAM,OAAO;MACpB,IAAI,MAAM,QAAQ,MAAM,GAE7B,YAAY;MAGZ,YAAY,CAAC;CAGf,OAAO,UAAU,OAAO,OAAO;AACjC"}
@@ -7,11 +7,12 @@ async function buildSSRApp(config, options, i18nWorkers = false) {
7
7
  const workspaceRoot = options?.workspaceRoot ?? process.cwd();
8
8
  const sourceRoot = options?.sourceRoot ?? "src";
9
9
  const rootDir = relative(workspaceRoot, config.root || ".") || ".";
10
- await build(mergeConfig(config, { build: {
10
+ const ssrBuildConfig = mergeConfig(config, { build: {
11
11
  ssr: true,
12
12
  [vite.rolldownVersion ? "rolldownOptions" : "rollupOptions"]: { input: i18nWorkers ? { "main.server": I18N_WORKER_SSR_ENTRY } : options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
13
13
  outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr")
14
- } }));
14
+ } });
15
+ await build(ssrBuildConfig);
15
16
  }
16
17
  //#endregion
17
18
  export { buildSSRApp };
@@ -1 +1 @@
1
- {"version":3,"file":"build-ssr.js","names":[],"sources":["../../../src/lib/build-ssr.ts"],"sourcesContent":["import { build, mergeConfig, UserConfig } from 'vite';\nimport * as vite from 'vite';\nimport { relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport { I18N_WORKER_SSR_ENTRY } from './utils/i18n-workers.js';\n\nexport async function buildSSRApp(\n config: UserConfig,\n options?: Options,\n i18nWorkers = false,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const ssrBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: true,\n [vite.rolldownVersion ? 'rolldownOptions' : 'rollupOptions']: {\n input: i18nWorkers\n ? { 'main.server': I18N_WORKER_SSR_ENTRY }\n : options?.entryServer ||\n resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),\n },\n outDir:\n options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n },\n });\n\n await build(ssrBuildConfig);\n}\n"],"mappings":";;;;;AAOA,eAAsB,YACpB,QACA,SACA,cAAc,OACC;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAe/D,OAAM,MAdiB,YAAY,QAAoB,EACrD,OAAO;EACL,KAAK;GACJ,KAAK,kBAAkB,oBAAoB,kBAAkB,EAC5D,OAAO,cACH,EAAE,eAAe,uBAAuB,GACxC,SAAS,eACT,QAAQ,eAAe,SAAS,GAAG,WAAW,iBAAiB,EACpE;EACD,QACE,SAAS,eAAe,QAAQ,eAAe,QAAQ,SAAS,MAAM;EACzE,EACF,CAAC,CAEyB"}
1
+ {"version":3,"file":"build-ssr.js","names":[],"sources":["../../../src/lib/build-ssr.ts"],"sourcesContent":["import { build, mergeConfig, UserConfig } from 'vite';\nimport * as vite from 'vite';\nimport { relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport { I18N_WORKER_SSR_ENTRY } from './utils/i18n-workers.js';\n\nexport async function buildSSRApp(\n config: UserConfig,\n options?: Options,\n i18nWorkers = false,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const ssrBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: true,\n [vite.rolldownVersion ? 'rolldownOptions' : 'rollupOptions']: {\n input: i18nWorkers\n ? { 'main.server': I18N_WORKER_SSR_ENTRY }\n : options?.entryServer ||\n resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),\n },\n outDir:\n options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n },\n });\n\n await build(ssrBuildConfig);\n}\n"],"mappings":";;;;;AAOA,eAAsB,YACpB,QACA,SACA,cAAc,OACC;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,IAAI;CAC5D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,GAAG,KAAK;CAC/D,MAAM,iBAAiB,YAAY,QAAoB,EACrD,OAAO;EACL,KAAK;GACJ,KAAK,kBAAkB,oBAAoB,kBAAkB,EAC5D,OAAO,cACH,EAAE,eAAe,sBAAsB,IACvC,SAAS,eACT,QAAQ,eAAe,SAAS,GAAG,WAAW,gBAAgB,EACpE;EACA,QACE,SAAS,eAAe,QAAQ,eAAe,QAAQ,SAAS,KAAK;CACzE,EACF,CAAC;CAED,MAAM,MAAM,cAAc;AAC5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"post-rendering-hook.js","names":[],"sources":["../../../../src/lib/hooks/post-rendering-hook.ts"],"sourcesContent":["import { Nitro, PrerenderRoute } from 'nitropack';\n\nexport function addPostRenderingHooks(\n nitro: Nitro,\n hooks: ((pr: PrerenderRoute) => Promise<void>)[],\n): void {\n hooks.forEach((hook) => {\n nitro.hooks.hook('prerender:generate', hook);\n });\n}\n"],"mappings":";AAEA,SAAgB,sBACd,OACA,OACM;AACN,OAAM,SAAS,SAAS;AACtB,QAAM,MAAM,KAAK,sBAAsB,KAAK;GAC5C"}
1
+ {"version":3,"file":"post-rendering-hook.js","names":[],"sources":["../../../../src/lib/hooks/post-rendering-hook.ts"],"sourcesContent":["import { Nitro, PrerenderRoute } from 'nitropack';\n\nexport function addPostRenderingHooks(\n nitro: Nitro,\n hooks: ((pr: PrerenderRoute) => Promise<void>)[],\n): void {\n hooks.forEach((hook) => {\n nitro.hooks.hook('prerender:generate', hook);\n });\n}\n"],"mappings":";AAEA,SAAgB,sBACd,OACA,OACM;CACN,MAAM,SAAS,SAAS;EACtB,MAAM,MAAM,KAAK,sBAAsB,IAAI;CAC7C,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server-plugin.js","names":[],"sources":["../../../../src/lib/plugins/dev-server-plugin.ts"],"sourcesContent":["// SSR dev server, middleware and error page source modified from\n// https://github.com/solidjs/solid-start/blob/main/packages/start/dev/server.js\n\nimport {\n Connect,\n Plugin,\n UserConfig,\n ViteDevServer,\n normalizePath,\n} from 'vite';\nimport { resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { createEvent, sendWebResponse } from 'h3';\nimport { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';\nimport { defu } from 'defu';\nimport { NitroRouteRules } from 'nitropack';\n\nimport { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';\nimport { registerI18nWatcher } from '../utils/register-i18n-watcher.js';\nimport { Options } from '../options.js';\nimport { detectLocaleFromRoute, setHtmlLang } from '../utils/i18n-prerender.js';\n\ntype ServerOptions = Options & { routeRules?: Record<string, any> | undefined };\n\nexport function devServerPlugin(getOptions: () => ServerOptions): Plugin {\n let options: ServerOptions;\n let sourceRoot: string;\n let index: string;\n let config: UserConfig;\n let root: string;\n let isTest = false;\n\n return {\n name: 'analogjs-dev-ssr-plugin',\n config(userConfig, { mode }) {\n options = getOptions();\n if (!options.ssr) {\n return;\n }\n const workspaceRoot = options.workspaceRoot || process.cwd();\n sourceRoot = options.sourceRoot ?? 'src';\n index = options.index || 'index.html';\n config = userConfig;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n isTest = isTest ? isTest : mode === 'test';\n return {\n resolve: {\n alias: {\n '~analog/entry-server':\n options.entryServer || `${root}/${sourceRoot}/main.server.ts`,\n },\n },\n };\n },\n configureServer(viteServer) {\n if (isTest || !options.ssr) {\n return;\n }\n\n return async () => {\n remove_html_middlewares(viteServer.middlewares);\n registerDevServerMiddleware(root, sourceRoot, viteServer);\n\n if (options.i18n) {\n registerI18nWatcher(viteServer);\n }\n\n viteServer.middlewares.use(async (req, res) => {\n let template = readFileSync(\n resolve(viteServer.config.root, index),\n 'utf-8',\n );\n\n template = await viteServer.transformIndexHtml(\n req.originalUrl as string,\n template,\n );\n\n const _routeRulesMatcher = toRouteMatcher(\n createRadixRouter({ routes: options.routeRules }),\n );\n const _getRouteRules = (path: string) =>\n defu(\n {},\n ..._routeRulesMatcher.matchAll(path).reverse(),\n ) as NitroRouteRules;\n\n try {\n let result: string | Response;\n // Check for route rules explicitly disabling SSR\n if (_getRouteRules(req.originalUrl as string).ssr === false) {\n result = template;\n } else {\n const entryServer = (\n await viteServer.ssrLoadModule('~analog/entry-server')\n )['default'];\n result = await entryServer(req.originalUrl, template, {\n req,\n res,\n });\n }\n\n if (result instanceof Response) {\n sendWebResponse(createEvent(req, res), result);\n return;\n }\n\n // Inject lang attribute when i18n is configured\n let html = typeof result === 'string' ? result : template;\n if (options.i18n) {\n const locale = detectLocaleFromRoute(\n req.originalUrl as string,\n options.i18n,\n );\n html = setHtmlLang(html, locale);\n }\n\n res.setHeader('Content-Type', 'text/html');\n res.end(html);\n } catch (e) {\n viteServer.ssrFixStacktrace(e as Error);\n res.statusCode = 500;\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `);\n }\n });\n };\n },\n };\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n ];\n for (let i = server.stack.length - 1; i > 0; i--) {\n const handler = server.stack[i]?.handle;\n const handlerName =\n typeof handler === 'function' ? handler.name : undefined;\n if (handlerName && html_middlewares.includes(handlerName)) {\n server.stack.splice(i, 1);\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error;\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n };\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,gBAAgB,YAAyC;CACvE,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;AAEb,QAAO;EACL,MAAM;EACN,OAAO,YAAY,EAAE,QAAQ;AAC3B,aAAU,YAAY;AACtB,OAAI,CAAC,QAAQ,IACX;GAEF,MAAM,gBAAgB,QAAQ,iBAAiB,QAAQ,KAAK;AAC5D,gBAAa,QAAQ,cAAc;AACnC,WAAQ,QAAQ,SAAS;AACzB,YAAS;AACT,UAAO,cAAc,QAAQ,eAAe,OAAO,QAAQ,IAAI,IAAI,IAAI;AACvE,YAAS,SAAS,SAAS,SAAS;AACpC,UAAO,EACL,SAAS,EACP,OAAO,EACL,wBACE,QAAQ,eAAe,GAAG,KAAK,GAAG,WAAW,kBAChD,EACF,EACF;;EAEH,gBAAgB,YAAY;AAC1B,OAAI,UAAU,CAAC,QAAQ,IACrB;AAGF,UAAO,YAAY;AACjB,4BAAwB,WAAW,YAAY;AAC/C,gCAA4B,MAAM,YAAY,WAAW;AAEzD,QAAI,QAAQ,KACV,qBAAoB,WAAW;AAGjC,eAAW,YAAY,IAAI,OAAO,KAAK,QAAQ;KAC7C,IAAI,WAAW,aACb,QAAQ,WAAW,OAAO,MAAM,MAAM,EACtC,QACD;AAED,gBAAW,MAAM,WAAW,mBAC1B,IAAI,aACJ,SACD;KAED,MAAM,qBAAqB,eACzB,aAAkB,EAAE,QAAQ,QAAQ,YAAY,CAAC,CAClD;KACD,MAAM,kBAAkB,SACtB,KACE,EAAE,EACF,GAAG,mBAAmB,SAAS,KAAK,CAAC,SA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sources":["../../../../src/lib/plugins/dev-server-plugin.ts"],"sourcesContent":["// SSR dev server, middleware and error page source modified from\n// https://github.com/solidjs/solid-start/blob/main/packages/start/dev/server.js\n\nimport {\n Connect,\n Plugin,\n UserConfig,\n ViteDevServer,\n normalizePath,\n} from 'vite';\nimport { resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { createEvent, sendWebResponse } from 'h3';\nimport { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';\nimport { defu } from 'defu';\nimport { NitroRouteRules } from 'nitropack';\n\nimport { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';\nimport { registerI18nWatcher } from '../utils/register-i18n-watcher.js';\nimport { Options } from '../options.js';\nimport { detectLocaleFromRoute, setHtmlLang } from '../utils/i18n-prerender.js';\n\ntype ServerOptions = Options & { routeRules?: Record<string, any> | undefined };\n\nexport function devServerPlugin(getOptions: () => ServerOptions): Plugin {\n let options: ServerOptions;\n let sourceRoot: string;\n let index: string;\n let config: UserConfig;\n let root: string;\n let isTest = false;\n\n return {\n name: 'analogjs-dev-ssr-plugin',\n config(userConfig, { mode }) {\n options = getOptions();\n if (!options.ssr) {\n return;\n }\n const workspaceRoot = options.workspaceRoot || process.cwd();\n sourceRoot = options.sourceRoot ?? 'src';\n index = options.index || 'index.html';\n config = userConfig;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n isTest = isTest ? isTest : mode === 'test';\n return {\n resolve: {\n alias: {\n '~analog/entry-server':\n options.entryServer || `${root}/${sourceRoot}/main.server.ts`,\n },\n },\n };\n },\n configureServer(viteServer) {\n if (isTest || !options.ssr) {\n return;\n }\n\n return async () => {\n remove_html_middlewares(viteServer.middlewares);\n registerDevServerMiddleware(root, sourceRoot, viteServer);\n\n if (options.i18n) {\n registerI18nWatcher(viteServer);\n }\n\n viteServer.middlewares.use(async (req, res) => {\n let template = readFileSync(\n resolve(viteServer.config.root, index),\n 'utf-8',\n );\n\n template = await viteServer.transformIndexHtml(\n req.originalUrl as string,\n template,\n );\n\n const _routeRulesMatcher = toRouteMatcher(\n createRadixRouter({ routes: options.routeRules }),\n );\n const _getRouteRules = (path: string) =>\n defu(\n {},\n ..._routeRulesMatcher.matchAll(path).reverse(),\n ) as NitroRouteRules;\n\n try {\n let result: string | Response;\n // Check for route rules explicitly disabling SSR\n if (_getRouteRules(req.originalUrl as string).ssr === false) {\n result = template;\n } else {\n const entryServer = (\n await viteServer.ssrLoadModule('~analog/entry-server')\n )['default'];\n result = await entryServer(req.originalUrl, template, {\n req,\n res,\n });\n }\n\n if (result instanceof Response) {\n sendWebResponse(createEvent(req, res), result);\n return;\n }\n\n // Inject lang attribute when i18n is configured\n let html = typeof result === 'string' ? result : template;\n if (options.i18n) {\n const locale = detectLocaleFromRoute(\n req.originalUrl as string,\n options.i18n,\n );\n html = setHtmlLang(html, locale);\n }\n\n res.setHeader('Content-Type', 'text/html');\n res.end(html);\n } catch (e) {\n viteServer.ssrFixStacktrace(e as Error);\n res.statusCode = 500;\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `);\n }\n });\n };\n },\n };\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n ];\n for (let i = server.stack.length - 1; i > 0; i--) {\n const handler = server.stack[i]?.handle;\n const handlerName =\n typeof handler === 'function' ? handler.name : undefined;\n if (handlerName && html_middlewares.includes(handlerName)) {\n server.stack.splice(i, 1);\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error;\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n };\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,gBAAgB,YAAyC;CACvE,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;CAEb,OAAO;EACL,MAAM;EACN,OAAO,YAAY,EAAE,QAAQ;GAC3B,UAAU,WAAW;GACrB,IAAI,CAAC,QAAQ,KACX;GAEF,MAAM,gBAAgB,QAAQ,iBAAiB,QAAQ,IAAI;GAC3D,aAAa,QAAQ,cAAc;GACnC,QAAQ,QAAQ,SAAS;GACzB,SAAS;GACT,OAAO,cAAc,QAAQ,eAAe,OAAO,QAAQ,GAAG,KAAK,GAAG;GACtE,SAAS,SAAS,SAAS,SAAS;GACpC,OAAO,EACL,SAAS,EACP,OAAO,EACL,wBACE,QAAQ,eAAe,GAAG,KAAK,GAAG,WAAW,iBACjD,EACF,EACF;EACF;EACA,gBAAgB,YAAY;GAC1B,IAAI,UAAU,CAAC,QAAQ,KACrB;GAGF,OAAO,YAAY;IACjB,wBAAwB,WAAW,WAAW;IAC9C,4BAA4B,MAAM,YAAY,UAAU;IAExD,IAAI,QAAQ,MACV,oBAAoB,UAAU;IAGhC,WAAW,YAAY,IAAI,OAAO,KAAK,QAAQ;KAC7C,IAAI,WAAW,aACb,QAAQ,WAAW,OAAO,MAAM,KAAK,GACrC,OACF;KAEA,WAAW,MAAM,WAAW,mBAC1B,IAAI,aACJ,QACF;KAEA,MAAM,qBAAqB,eACzB,aAAkB,EAAE,QAAQ,QAAQ,WAAW,CAAC,CAClD;KACA,MAAM,kBAAkB,SACtB,KACE,CAAC,GACD,GAAG,mBAAmB,SAAS,IAAI,CAAC,CAAC,QAAQ,CAC/C;KAEF,IAAI;MACF,IAAI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 -1 +1 @@
1
- {"version":3,"file":"page-endpoints.js","names":[],"sources":["../../../../src/lib/plugins/page-endpoints.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\nimport { normalizePath } from 'vite';\n\nexport function pageEndpointsPlugin() {\n return {\n name: 'analogjs-vite-plugin-nitro-rollup-page-endpoint',\n async transform(\n _code: string,\n id: string,\n ): Promise<{ code: string; map: null } | undefined> {\n if (normalizePath(id).includes('/pages/') && id.endsWith('.server.ts')) {\n const result = parseSync(id, _code, {\n sourceType: 'module',\n lang: 'ts',\n });\n\n const fileExports: string[] = result.module.staticExports.flatMap((e) =>\n e.entries\n .filter((entry) => entry.exportName.name !== null)\n .map((entry) => entry.exportName.name as string),\n );\n\n const code = `\n import { defineEventHandler } from 'h3';\n\n ${\n fileExports.includes('load')\n ? _code\n : `\n ${_code}\n export const load = () => {\n return {};\n }`\n }\n\n ${\n fileExports.includes('action')\n ? ''\n : `\n export const action = () => {\n return {};\n } \n `\n }\n\n export default defineEventHandler(async(event) => {\n if (event.method === 'GET') {\n try {\n return await load({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n }\n } else {\n try {\n return await action({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n } \n }\n });\n `;\n\n return {\n code,\n map: null,\n };\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;AAGA,SAAgB,sBAAsB;AACpC,QAAO;EACL,MAAM;EACN,MAAM,UACJ,OACA,IACkD;AAClD,OAAI,cAAc,GAAG,CAAC,SAAS,UAAU,IAAI,GAAG,SAAS,aAAa,EAAE;IAMtE,MAAM,cALS,UAAU,IAAI,OAAO;KAClC,YAAY;KACZ,MAAM;KACP,CAAC,CAEmC,OAAO,cAAc,SAAS,MACjE,EAAE,QACC,QAAQ,UAAU,MAAM,WAAW,SAAS,KAAK,CACjD,KAAK,UAAU,MAAM,WAAW,KAAe,CACnD;AAwDD,WAAO;KACL,MAvDW;;;cAIP,YAAY,SAAS,OAAO,GACxB,QACA;kBACA,MAAM;;;mBAIX;;cAGC,YAAY,SAAS,SAAS,GAC1B,KACA;;;;gBAKL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmCH,KAAK;KACN;;;EAKN"}
1
+ {"version":3,"file":"page-endpoints.js","names":[],"sources":["../../../../src/lib/plugins/page-endpoints.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\nimport { normalizePath } from 'vite';\n\nexport function pageEndpointsPlugin() {\n return {\n name: 'analogjs-vite-plugin-nitro-rollup-page-endpoint',\n async transform(\n _code: string,\n id: string,\n ): Promise<{ code: string; map: null } | undefined> {\n if (normalizePath(id).includes('/pages/') && id.endsWith('.server.ts')) {\n const result = parseSync(id, _code, {\n sourceType: 'module',\n lang: 'ts',\n });\n\n const fileExports: string[] = result.module.staticExports.flatMap((e) =>\n e.entries\n .filter((entry) => entry.exportName.name !== null)\n .map((entry) => entry.exportName.name as string),\n );\n\n const code = `\n import { defineEventHandler } from 'h3';\n\n ${\n fileExports.includes('load')\n ? _code\n : `\n ${_code}\n export const load = () => {\n return {};\n }`\n }\n\n ${\n fileExports.includes('action')\n ? ''\n : `\n export const action = () => {\n return {};\n } \n `\n }\n\n export default defineEventHandler(async(event) => {\n if (event.method === 'GET') {\n try {\n return await load({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n }\n } else {\n try {\n return await action({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n } \n }\n });\n `;\n\n return {\n code,\n map: null,\n };\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;AAGA,SAAgB,sBAAsB;CACpC,OAAO;EACL,MAAM;EACN,MAAM,UACJ,OACA,IACkD;GAClD,IAAI,cAAc,EAAE,CAAC,CAAC,SAAS,SAAS,KAAK,GAAG,SAAS,YAAY,GAAG;IAMtE,MAAM,cALS,UAAU,IAAI,OAAO;KAClC,YAAY;KACZ,MAAM;IACR,CAE8B,CAAA,CAAO,OAAO,cAAc,SAAS,MACjE,EAAE,QACC,QAAQ,UAAU,MAAM,WAAW,SAAS,IAAI,CAAC,CACjD,KAAK,UAAU,MAAM,WAAW,IAAc,CACnD;IAwDA,OAAO;KACL,MAAA;;;cAnDI,YAAY,SAAS,MAAM,IACvB,QACA;kBACA,MAAM;;;mBAIX;;cAGC,YAAY,SAAS,QAAQ,IACzB,KACA;;;;gBAKL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmCH,KAAK;IACP;GACF;EAGF;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"server-fn-id-plugin.js","names":[],"sources":["../../../../src/lib/plugins/server-fn-id-plugin.ts"],"sourcesContent":["import { serverFnFileId } from '../utils/derive-server-fn-id.js';\nimport { injectServerFnIds } from '../utils/inject-server-fn-ids.js';\n\n/**\n * Nitro-build transform that stamps the derived id into each `serverFn` config\n * in a `*.server.ts`, so a function registers under the same opaque route the\n * client proxy dispatches to. The SSR app build does the same via the platform\n * plugin; this covers the separate Nitro server graph the dispatch handler pulls\n * the modules into.\n */\nexport function serverFnIdPlugin(projectRoot: string): {\n name: string;\n transform(code: string, id: string): { code: string; map: null } | undefined;\n} {\n return {\n name: 'analogjs-server-fn-id',\n transform(\n code: string,\n id: string,\n ): { code: string; map: null } | undefined {\n if (!id.endsWith('.server.ts')) {\n return;\n }\n const injected = injectServerFnIds(code, serverFnFileId(id, projectRoot));\n return injected ? { code: injected.code, map: null } : undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,iBAAiB,aAG/B;AACA,QAAO;EACL,MAAM;EACN,UACE,MACA,IACyC;AACzC,OAAI,CAAC,GAAG,SAAS,aAAa,CAC5B;GAEF,MAAM,WAAW,kBAAkB,MAAM,eAAe,IAAI,YAAY,CAAC;AACzE,UAAO,WAAW;IAAE,MAAM,SAAS;IAAM,KAAK;IAAM,GAAG,KAAA;;EAE1D"}
1
+ {"version":3,"file":"server-fn-id-plugin.js","names":[],"sources":["../../../../src/lib/plugins/server-fn-id-plugin.ts"],"sourcesContent":["import { serverFnFileId } from '../utils/derive-server-fn-id.js';\nimport { injectServerFnIds } from '../utils/inject-server-fn-ids.js';\n\n/**\n * Nitro-build transform that stamps the derived id into each `serverFn` config\n * in a `*.server.ts`, so a function registers under the same opaque route the\n * client proxy dispatches to. The SSR app build does the same via the platform\n * plugin; this covers the separate Nitro server graph the dispatch handler pulls\n * the modules into.\n */\nexport function serverFnIdPlugin(projectRoot: string): {\n name: string;\n transform(code: string, id: string): { code: string; map: null } | undefined;\n} {\n return {\n name: 'analogjs-server-fn-id',\n transform(\n code: string,\n id: string,\n ): { code: string; map: null } | undefined {\n if (!id.endsWith('.server.ts')) {\n return;\n }\n const injected = injectServerFnIds(code, serverFnFileId(id, projectRoot));\n return injected ? { code: injected.code, map: null } : undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,iBAAiB,aAG/B;CACA,OAAO;EACL,MAAM;EACN,UACE,MACA,IACyC;GACzC,IAAI,CAAC,GAAG,SAAS,YAAY,GAC3B;GAEF,MAAM,WAAW,kBAAkB,MAAM,eAAe,IAAI,WAAW,CAAC;GACxE,OAAO,WAAW;IAAE,MAAM,SAAS;IAAM,KAAK;GAAK,IAAI,KAAA;EACzD;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"derive-server-fn-id.js","names":[],"sources":["../../../../src/lib/utils/derive-server-fn-id.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { relative } from 'node:path';\n\n// Intentionally dependency-light (node built-ins only): this module is loaded by\n// the client scrub, so it must not drag in vite/nitro. POSIX-normalize inline.\nconst toPosix = (p: string): string => p.replace(/\\\\/g, '/');\n\n/**\n * Server-function ids are derived, never author-chosen, for security:\n *\n * - **Collision-free.** `hash(fileId + exportName)` is unique per file+export, so\n * two functions can never share a route and hijack each other's dispatch — a\n * real risk with hand-picked ids where two authors independently pick `getUser`.\n * - **Non-enumerable.** The public route is an opaque digest, not a guessable\n * verb like `/_analog/fn/deleteAccount`, shrinking the discoverable surface.\n * - **Not author-controlled.** Authors cannot expose a meaningful or duplicate\n * route by accident; the id is a pure function of location.\n *\n * Both build transforms (server registration + client proxy) MUST derive the\n * same id, so this is the single source of truth for the algorithm and the\n * `fileId` must be the **project-root-relative** POSIX path — identical across\n * the client, SSR, and Nitro builds regardless of absolute checkout location.\n */\n\n/** Project-root-relative POSIX module path used as the stable hash input. */\nexport function serverFnFileId(absPath: string, projectRoot: string): string {\n return toPosix(relative(projectRoot, absPath));\n}\n\n/**\n * Derives the opaque, collision-free id for a server function from its\n * project-root-relative file id and export name. 16 hex chars (64 bits) is far\n * beyond birthday-collision range for any realistic function count while keeping\n * the route short.\n */\nexport function deriveServerFnId(fileId: string, exportName: string): string {\n return createHash('sha256')\n .update(`${fileId}#${exportName}`)\n .digest('hex')\n .slice(0, 16);\n}\n"],"mappings":";;;AAKA,IAAM,WAAW,MAAsB,EAAE,QAAQ,OAAO,IAAI;;;;;;;;;;;;;;;;;;AAoB5D,SAAgB,eAAe,SAAiB,aAA6B;AAC3E,QAAO,QAAQ,SAAS,aAAa,QAAQ,CAAC;;;;;;;;AAShD,SAAgB,iBAAiB,QAAgB,YAA4B;AAC3E,QAAO,WAAW,SAAS,CACxB,OAAO,GAAG,OAAO,GAAG,aAAa,CACjC,OAAO,MAAM,CACb,MAAM,GAAG,GAAG"}
1
+ {"version":3,"file":"derive-server-fn-id.js","names":[],"sources":["../../../../src/lib/utils/derive-server-fn-id.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { relative } from 'node:path';\n\n// Intentionally dependency-light (node built-ins only): this module is loaded by\n// the client scrub, so it must not drag in vite/nitro. POSIX-normalize inline.\nconst toPosix = (p: string): string => p.replace(/\\\\/g, '/');\n\n/**\n * Server-function ids are derived, never author-chosen, for security:\n *\n * - **Collision-free.** `hash(fileId + exportName)` is unique per file+export, so\n * two functions can never share a route and hijack each other's dispatch — a\n * real risk with hand-picked ids where two authors independently pick `getUser`.\n * - **Non-enumerable.** The public route is an opaque digest, not a guessable\n * verb like `/_analog/fn/deleteAccount`, shrinking the discoverable surface.\n * - **Not author-controlled.** Authors cannot expose a meaningful or duplicate\n * route by accident; the id is a pure function of location.\n *\n * Both build transforms (server registration + client proxy) MUST derive the\n * same id, so this is the single source of truth for the algorithm and the\n * `fileId` must be the **project-root-relative** POSIX path — identical across\n * the client, SSR, and Nitro builds regardless of absolute checkout location.\n */\n\n/** Project-root-relative POSIX module path used as the stable hash input. */\nexport function serverFnFileId(absPath: string, projectRoot: string): string {\n return toPosix(relative(projectRoot, absPath));\n}\n\n/**\n * Derives the opaque, collision-free id for a server function from its\n * project-root-relative file id and export name. 16 hex chars (64 bits) is far\n * beyond birthday-collision range for any realistic function count while keeping\n * the route short.\n */\nexport function deriveServerFnId(fileId: string, exportName: string): string {\n return createHash('sha256')\n .update(`${fileId}#${exportName}`)\n .digest('hex')\n .slice(0, 16);\n}\n"],"mappings":";;;AAKA,IAAM,WAAW,MAAsB,EAAE,QAAQ,OAAO,GAAG;;;;;;;;;;;;;;;;;;AAoB3D,SAAgB,eAAe,SAAiB,aAA6B;CAC3E,OAAO,QAAQ,SAAS,aAAa,OAAO,CAAC;AAC/C;;;;;;;AAQA,SAAgB,iBAAiB,QAAgB,YAA4B;CAC3E,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,GAAG,OAAO,GAAG,YAAY,CAAC,CACjC,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;AAChB"}
@@ -63,7 +63,8 @@ function getMatchingContentFilesWithFrontMatter(workspaceRoot, rootDir, glob, re
63
63
  const fm = require("front-matter");
64
64
  const root = normalizePath(resolve(workspaceRoot, rootDir));
65
65
  const resolvedDir = normalizePath(relative(root, join(root, glob)));
66
- const contentFiles = globSync([recursive ? `${root}/${resolvedDir}/**/*` : `${root}/${resolvedDir}/*`], {
66
+ const pattern = recursive ? `${root}/${resolvedDir}/**/*` : `${root}/${resolvedDir}/*`;
67
+ const contentFiles = globSync([pattern], {
67
68
  dot: true,
68
69
  absolute: true,
69
70
  onlyFiles: true
@@ -1 +1 @@
1
- {"version":3,"file":"get-content-files.js","names":[],"sources":["../../../../src/lib/utils/get-content-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { createRequire } from 'node:module';\nimport { globSync } from 'tinyglobby';\n\nimport { PrerenderContentFile } from '../options';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Discovers content files with front matter and extracts metadata for prerendering.\n *\n * This function:\n * 1. Discovers all content files matching the specified glob pattern\n * 2. Reads each file and parses front matter metadata\n * 3. Extracts file name, extension, and path information\n * 4. Returns structured data for prerendering content pages\n *\n * @param workspaceRoot The workspace root directory path\n * @param rootDir The project root directory relative to workspace\n * @param glob The glob pattern to match content files (e.g., 'content/blog')\n * @returns Array of PrerenderContentFile objects with metadata and front matter\n *\n * Example usage:\n * const contentFiles = getMatchingContentFilesWithFrontMatter(\n * '/workspace',\n * 'apps/my-app',\n * 'content/blog'\n * );\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/content/blog/first-post.md\n * - /workspace/apps/my-app/content/blog/2024/01/hello-world.md\n * - /workspace/apps/my-app/content/blog/tech/angular-v17.mdx\n * - /workspace/apps/my-app/content/blog/about/index.md\n *\n * Sample output structure:\n * {\n * name: 'first-post',\n * extension: 'md',\n * path: 'content/blog',\n * attributes: { title: 'My First Post', date: '2024-01-01', tags: ['intro'] }\n * }\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding content files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Front matter parsing:\n * - Uses front-matter library to parse YAML/TOML front matter\n * - Extracts metadata like title, date, tags, author, etc.\n * - Supports both YAML (---) and TOML (+++) delimiters\n * - Returns structured attributes for prerendering\n *\n * File path processing:\n * - Normalizes paths for cross-platform compatibility\n * - Extracts file name without extension\n * - Determines file extension for content type handling\n * - Maintains relative path structure for routing\n */\nexport function getMatchingContentFilesWithFrontMatter(\n workspaceRoot: string,\n rootDir: string,\n glob: string,\n recursive = false,\n): PrerenderContentFile[] {\n // Dynamically require front-matter library\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const fm = require('front-matter');\n\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Resolve the content directory path relative to the project root\n const resolvedDir = normalizePath(relative(root, join(root, glob)));\n\n // Discover all content files in the specified directory.\n // Default pattern matches only top-level files; recursive opt-in walks subdirectories.\n const pattern = recursive\n ? `${root}/${resolvedDir}/**/*`\n : `${root}/${resolvedDir}/*`;\n const contentFiles: string[] = globSync([pattern], {\n dot: true,\n absolute: true,\n onlyFiles: true,\n });\n\n const dirPrefix = `${root}/${resolvedDir}`;\n\n // Process each discovered content file to extract metadata and front matter\n const mappedFilesWithFm: PrerenderContentFile[] = contentFiles.map((f) => {\n // Read the file contents as UTF-8 text\n const fileContents = readFileSync(f, 'utf8');\n\n // Parse front matter from the file content\n const raw = fm(fileContents);\n\n // Get the relative file path by removing the root directory\n const filepath = f.replace(root, '');\n\n // Extract file name and extension using regex\n // Matches: /filename.ext or /filename (with optional extension)\n const match = filepath.match(/\\/([^/.]+)(\\.([^/.]+))?$/);\n let name = '';\n let extension = '';\n if (match) {\n name = match[1]; // File name without extension\n extension = match[3] || ''; // File extension or empty string if no extension\n }\n\n // Path of the file's directory relative to the configured contentDir.\n // For top-level files this is an empty string; for nested files it\n // gives transforms enough context to disambiguate identically-named\n // files (e.g. docs/a/post.md vs docs/b/post.md).\n const relativeDir = normalizePath(relative(dirPrefix, f));\n const lastSlash = relativeDir.lastIndexOf('/');\n const relativePath =\n lastSlash === -1 ? '' : relativeDir.slice(0, lastSlash);\n\n // Return structured content file data for prerendering\n return {\n name,\n extension,\n path: resolvedDir,\n attributes: raw.attributes as { attributes: Record<string, any> },\n content: fileContents,\n relativePath,\n };\n });\n\n return mappedFilesWithFm;\n}\n"],"mappings":";;;;;;AAQA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwD9C,SAAgB,uCACd,eACA,SACA,MACA,YAAY,OACY;CAGxB,MAAM,KAAK,QAAQ,eAAe;CAGlC,MAAM,OAAO,cAAc,QAAQ,eAAe,QAAQ,CAAC;CAG3D,MAAM,cAAc,cAAc,SAAS,MAAM,KAAK,MAAM,KAAK,CAAC,CAAC;CAOnE,MAAM,eAAyB,SAAS,CAHxB,YACZ,GAAG,KAAK,GAAG,YAAY,SACvB,GAAG,KAAK,GAAG,YAAY,IACsB,EAAE;EACjD,KAAK;EACL,UAAU;EACV,WAAW;EACZ,CAAC;CAEF,MAAM,YAAY,GAAG,KAAK,GAAG;AA2C7B,QAxCkD,aAAa,KAAK,MAAM;EAExE,MAAM,eAAe,aAAa,GAAG,OAAO;EAG5C,MAAM,MAAM,GAAG,aAAa;EAO5B,MAAM,QAJW,EAAE,QAAQ,MAAM,GAAG,CAIb,MAAM,2BAA2B;EACxD,IAAI,OAAO;EACX,IAAI,YAAY;AAChB,MAAI,OAAO;AACT,UAAO,MAAM;AACb,eAAY,MAAM,MAAM;;EAO1B,MAAM,cAAc,cAAc,SAAS,WAAW,EAAE,CAAC;EACzD,MAAM,YAAY,YAAY,YAAY,IAAI;EAC9C,MAAM,eACJ,cAAc,KAAK,KAAK,YAAY,MAAM,GAAG,UAAU;AAGzD,SAAO;GACL;GACA;GACA,MAAM;GACN,YAAY,IAAI;GAChB,SAAS;GACT;GACD;GACD"}
1
+ {"version":3,"file":"get-content-files.js","names":[],"sources":["../../../../src/lib/utils/get-content-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { createRequire } from 'node:module';\nimport { globSync } from 'tinyglobby';\n\nimport { PrerenderContentFile } from '../options';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Discovers content files with front matter and extracts metadata for prerendering.\n *\n * This function:\n * 1. Discovers all content files matching the specified glob pattern\n * 2. Reads each file and parses front matter metadata\n * 3. Extracts file name, extension, and path information\n * 4. Returns structured data for prerendering content pages\n *\n * @param workspaceRoot The workspace root directory path\n * @param rootDir The project root directory relative to workspace\n * @param glob The glob pattern to match content files (e.g., 'content/blog')\n * @returns Array of PrerenderContentFile objects with metadata and front matter\n *\n * Example usage:\n * const contentFiles = getMatchingContentFilesWithFrontMatter(\n * '/workspace',\n * 'apps/my-app',\n * 'content/blog'\n * );\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/content/blog/first-post.md\n * - /workspace/apps/my-app/content/blog/2024/01/hello-world.md\n * - /workspace/apps/my-app/content/blog/tech/angular-v17.mdx\n * - /workspace/apps/my-app/content/blog/about/index.md\n *\n * Sample output structure:\n * {\n * name: 'first-post',\n * extension: 'md',\n * path: 'content/blog',\n * attributes: { title: 'My First Post', date: '2024-01-01', tags: ['intro'] }\n * }\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding content files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Front matter parsing:\n * - Uses front-matter library to parse YAML/TOML front matter\n * - Extracts metadata like title, date, tags, author, etc.\n * - Supports both YAML (---) and TOML (+++) delimiters\n * - Returns structured attributes for prerendering\n *\n * File path processing:\n * - Normalizes paths for cross-platform compatibility\n * - Extracts file name without extension\n * - Determines file extension for content type handling\n * - Maintains relative path structure for routing\n */\nexport function getMatchingContentFilesWithFrontMatter(\n workspaceRoot: string,\n rootDir: string,\n glob: string,\n recursive = false,\n): PrerenderContentFile[] {\n // Dynamically require front-matter library\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const fm = require('front-matter');\n\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Resolve the content directory path relative to the project root\n const resolvedDir = normalizePath(relative(root, join(root, glob)));\n\n // Discover all content files in the specified directory.\n // Default pattern matches only top-level files; recursive opt-in walks subdirectories.\n const pattern = recursive\n ? `${root}/${resolvedDir}/**/*`\n : `${root}/${resolvedDir}/*`;\n const contentFiles: string[] = globSync([pattern], {\n dot: true,\n absolute: true,\n onlyFiles: true,\n });\n\n const dirPrefix = `${root}/${resolvedDir}`;\n\n // Process each discovered content file to extract metadata and front matter\n const mappedFilesWithFm: PrerenderContentFile[] = contentFiles.map((f) => {\n // Read the file contents as UTF-8 text\n const fileContents = readFileSync(f, 'utf8');\n\n // Parse front matter from the file content\n const raw = fm(fileContents);\n\n // Get the relative file path by removing the root directory\n const filepath = f.replace(root, '');\n\n // Extract file name and extension using regex\n // Matches: /filename.ext or /filename (with optional extension)\n const match = filepath.match(/\\/([^/.]+)(\\.([^/.]+))?$/);\n let name = '';\n let extension = '';\n if (match) {\n name = match[1]; // File name without extension\n extension = match[3] || ''; // File extension or empty string if no extension\n }\n\n // Path of the file's directory relative to the configured contentDir.\n // For top-level files this is an empty string; for nested files it\n // gives transforms enough context to disambiguate identically-named\n // files (e.g. docs/a/post.md vs docs/b/post.md).\n const relativeDir = normalizePath(relative(dirPrefix, f));\n const lastSlash = relativeDir.lastIndexOf('/');\n const relativePath =\n lastSlash === -1 ? '' : relativeDir.slice(0, lastSlash);\n\n // Return structured content file data for prerendering\n return {\n name,\n extension,\n path: resolvedDir,\n attributes: raw.attributes as { attributes: Record<string, any> },\n content: fileContents,\n relativePath,\n };\n });\n\n return mappedFilesWithFm;\n}\n"],"mappings":";;;;;;AAQA,IAAM,UAAU,cAAc,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwD7C,SAAgB,uCACd,eACA,SACA,MACA,YAAY,OACY;CAGxB,MAAM,KAAK,QAAQ,cAAc;CAGjC,MAAM,OAAO,cAAc,QAAQ,eAAe,OAAO,CAAC;CAG1D,MAAM,cAAc,cAAc,SAAS,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC;CAIlE,MAAM,UAAU,YACZ,GAAG,KAAK,GAAG,YAAY,SACvB,GAAG,KAAK,GAAG,YAAY;CAC3B,MAAM,eAAyB,SAAS,CAAC,OAAO,GAAG;EACjD,KAAK;EACL,UAAU;EACV,WAAW;CACb,CAAC;CAED,MAAM,YAAY,GAAG,KAAK,GAAG;CA2C7B,OAxCkD,aAAa,KAAK,MAAM;EAExE,MAAM,eAAe,aAAa,GAAG,MAAM;EAG3C,MAAM,MAAM,GAAG,YAAY;EAO3B,MAAM,QAJW,EAAE,QAAQ,MAAM,EAInB,CAAA,CAAS,MAAM,0BAA0B;EACvD,IAAI,OAAO;EACX,IAAI,YAAY;EAChB,IAAI,OAAO;GACT,OAAO,MAAM;GACb,YAAY,MAAM,MAAM;EAC1B;EAMA,MAAM,cAAc,cAAc,SAAS,WAAW,CAAC,CAAC;EACxD,MAAM,YAAY,YAAY,YAAY,GAAG;EAC7C,MAAM,eACJ,cAAc,KAAK,KAAK,YAAY,MAAM,GAAG,SAAS;EAGxD,OAAO;GACL;GACA;GACA,MAAM;GACN,YAAY,IAAI;GAChB,SAAS;GACT;EACF;CACF,CAEO;AACT"}
@@ -54,7 +54,8 @@ import { globSync } from "tinyglobby";
54
54
  * 6. Prefixes with the API prefix and /_analog/pages
55
55
  */
56
56
  function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs, apiPrefix = "/api" }) {
57
- return globSync([`${normalizePath(resolve(workspaceRoot, rootDir))}/${sourceRoot}/app/pages/**/*.server.ts`, ...(additionalPagesDirs || []).map((dir) => `${workspaceRoot}${dir}/**/*.server.ts`)], {
57
+ const root = normalizePath(resolve(workspaceRoot, rootDir));
58
+ return globSync([`${root}/${sourceRoot}/app/pages/**/*.server.ts`, ...(additionalPagesDirs || []).map((dir) => `${workspaceRoot}${dir}/**/*.server.ts`)], {
58
59
  dot: true,
59
60
  absolute: true
60
61
  }).map((endpointFile) => {
@@ -1 +1 @@
1
- {"version":3,"file":"get-page-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-page-handlers.ts"],"sourcesContent":["import { resolve, relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\ntype GetHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalPagesDirs?: string[];\n apiPrefix?: string;\n};\n\n/**\n * Discovers and generates Nitro event handlers for server-side page routes.\n *\n * This function:\n * 1. Discovers all .server.ts files in the app/pages directory and additional pages directories\n * 2. Converts file paths to route patterns using Angular-style route syntax\n * 3. Generates Nitro event handlers with proper route mapping and lazy loading\n * 4. Handles dynamic route parameters and catch-all routes\n *\n * @param workspaceRoot The workspace root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param rootDir The project root directory relative to workspace\n * @param additionalPagesDirs Optional array of additional pages directories to scan\n * @param apiPrefix The API route prefix (defaults to '/api')\n * @returns Array of NitroEventHandler objects with handler paths and route patterns\n *\n * Example usage:\n * const handlers = getPageHandlers({\n * workspaceRoot: '/workspace',\n * sourceRoot: 'src',\n * rootDir: 'apps/my-app',\n * additionalPagesDirs: ['/libs/shared/pages'],\n * });\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/src/app/pages/index.server.ts\n * - /workspace/apps/my-app/src/app/pages/users/[id].server.ts\n * - /workspace/apps/my-app/src/app/pages/products/[...slug].server.ts\n * - /workspace/apps/my-app/src/app/pages/(auth)/login.server.ts\n *\n * Route transformation examples:\n * - index.server.ts → /api/_analog/pages/index\n * - users/[id].server.ts → /api/_analog/pages/users/:id\n * - products/[...slug].server.ts → /api/_analog/pages/products/**:slug\n * - (auth)/login.server.ts → /api/_analog/pages/-auth-/login\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding server-side page files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Route transformation rules:\n * 1. Removes .server.ts extension\n * 2. Converts [param] to :param for dynamic routes\n * 3. Converts [...param] to **:param for catch-all routes\n * 4. Converts (group) to -group- for route groups\n * 5. Converts dots to forward slashes\n * 6. Prefixes with the API prefix and /_analog/pages\n */\nexport function getPageHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs,\n apiPrefix = '/api',\n}: GetHandlersArgs): NitroEventHandler[] {\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Discover all .server.ts files in the app/pages directory and additional pages directories\n // Pattern: looks for any .server.ts files in app/pages/**/*.server.ts and additional directories\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 // Transform each discovered file into a Nitro event handler\n const handlers: NitroEventHandler[] = endpointFiles.map((endpointFile) => {\n // Convert file path to route pattern using Angular-style route syntax\n const route = endpointFile\n .replace(/^(.*?)\\/pages/, '/pages') // Remove everything before /pages\n .replace(/\\.server\\.ts$/, '') // Remove .server.ts extension\n .replace(/\\[\\.{3}(.+)\\]/g, '**:$1') // Convert [...param] to **:param (catch-all routes)\n .replace(/\\[\\.{3}(\\w+)\\]/g, '**:$1') // Alternative catch-all pattern\n .replace(/\\/\\((.*?)\\)$/, '/-$1-') // Convert (group) to -group- (route groups)\n .replace(/\\[(\\w+)\\]/g, ':$1') // Convert [param] to :param (dynamic routes)\n .replace(/\\./g, '/'); // Convert dots to forward slashes\n\n // Return Nitro event handler with absolute handler path and transformed route\n return {\n handler: endpointFile,\n route: `${apiPrefix}/_analog${route}`,\n lazy: true,\n };\n });\n\n return handlers;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,gBAAgB,EAC9B,eACA,YACA,SACA,qBACA,YAAY,UAC2B;AAoCvC,QA9BgC,SAC9B,CACE,GANS,cAAc,QAAQ,eAAe,QAAQ,CAAC,CAM/C,GAAG,WAAW,4BACtB,IAAI,uBAAuB,EAAE,EAAE,KAC5B,QAAQ,GAAG,gBAAgB,IAAI,iBACjC,CACF,EACD;EAAE,KAAK;EAAM,UAAU;EAAM,CAC9B,CAGmD,KAAK,iBAAiB;AAYxE,SAAO;GACL,SAAS;GACT,OAAO,GAAG,UAAU,UAZR,aACX,QAAQ,iBAAiB,SAAS,CAClC,QAAQ,iBAAiB,GAAG,CAC5B,QAAQ,kBAAkB,QAAQ,CAClC,QAAQ,mBAAmB,QAAQ,CACnC,QAAQ,gBAAgB,QAAQ,CAChC,QAAQ,cAAc,MAAM,CAC5B,QAAQ,OAAO,IAAI;GAMpB,MAAM;GACP;GACD"}
1
+ {"version":3,"file":"get-page-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-page-handlers.ts"],"sourcesContent":["import { resolve, relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\ntype GetHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalPagesDirs?: string[];\n apiPrefix?: string;\n};\n\n/**\n * Discovers and generates Nitro event handlers for server-side page routes.\n *\n * This function:\n * 1. Discovers all .server.ts files in the app/pages directory and additional pages directories\n * 2. Converts file paths to route patterns using Angular-style route syntax\n * 3. Generates Nitro event handlers with proper route mapping and lazy loading\n * 4. Handles dynamic route parameters and catch-all routes\n *\n * @param workspaceRoot The workspace root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param rootDir The project root directory relative to workspace\n * @param additionalPagesDirs Optional array of additional pages directories to scan\n * @param apiPrefix The API route prefix (defaults to '/api')\n * @returns Array of NitroEventHandler objects with handler paths and route patterns\n *\n * Example usage:\n * const handlers = getPageHandlers({\n * workspaceRoot: '/workspace',\n * sourceRoot: 'src',\n * rootDir: 'apps/my-app',\n * additionalPagesDirs: ['/libs/shared/pages'],\n * });\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/src/app/pages/index.server.ts\n * - /workspace/apps/my-app/src/app/pages/users/[id].server.ts\n * - /workspace/apps/my-app/src/app/pages/products/[...slug].server.ts\n * - /workspace/apps/my-app/src/app/pages/(auth)/login.server.ts\n *\n * Route transformation examples:\n * - index.server.ts → /api/_analog/pages/index\n * - users/[id].server.ts → /api/_analog/pages/users/:id\n * - products/[...slug].server.ts → /api/_analog/pages/products/**:slug\n * - (auth)/login.server.ts → /api/_analog/pages/-auth-/login\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding server-side page files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Route transformation rules:\n * 1. Removes .server.ts extension\n * 2. Converts [param] to :param for dynamic routes\n * 3. Converts [...param] to **:param for catch-all routes\n * 4. Converts (group) to -group- for route groups\n * 5. Converts dots to forward slashes\n * 6. Prefixes with the API prefix and /_analog/pages\n */\nexport function getPageHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs,\n apiPrefix = '/api',\n}: GetHandlersArgs): NitroEventHandler[] {\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Discover all .server.ts files in the app/pages directory and additional pages directories\n // Pattern: looks for any .server.ts files in app/pages/**/*.server.ts and additional directories\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 // Transform each discovered file into a Nitro event handler\n const handlers: NitroEventHandler[] = endpointFiles.map((endpointFile) => {\n // Convert file path to route pattern using Angular-style route syntax\n const route = endpointFile\n .replace(/^(.*?)\\/pages/, '/pages') // Remove everything before /pages\n .replace(/\\.server\\.ts$/, '') // Remove .server.ts extension\n .replace(/\\[\\.{3}(.+)\\]/g, '**:$1') // Convert [...param] to **:param (catch-all routes)\n .replace(/\\[\\.{3}(\\w+)\\]/g, '**:$1') // Alternative catch-all pattern\n .replace(/\\/\\((.*?)\\)$/, '/-$1-') // Convert (group) to -group- (route groups)\n .replace(/\\[(\\w+)\\]/g, ':$1') // Convert [param] to :param (dynamic routes)\n .replace(/\\./g, '/'); // Convert dots to forward slashes\n\n // Return Nitro event handler with absolute handler path and transformed route\n return {\n handler: endpointFile,\n route: `${apiPrefix}/_analog${route}`,\n lazy: true,\n };\n });\n\n return handlers;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,gBAAgB,EAC9B,eACA,YACA,SACA,qBACA,YAAY,UAC2B;CAEvC,MAAM,OAAO,cAAc,QAAQ,eAAe,OAAO,CAAC;CAkC1D,OA9BgC,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,CAIQ,CAAA,CAAc,KAAK,iBAAiB;EAYxE,OAAO;GACL,SAAS;GACT,OAAO,GAAG,UAAU,UAZR,aACX,QAAQ,iBAAiB,QAAQ,CAAC,CAClC,QAAQ,iBAAiB,EAAE,CAAC,CAC5B,QAAQ,kBAAkB,OAAO,CAAC,CAClC,QAAQ,mBAAmB,OAAO,CAAC,CACnC,QAAQ,gBAAgB,OAAO,CAAC,CAChC,QAAQ,cAAc,KAAK,CAAC,CAC5B,QAAQ,OAAO,GAKc;GAC9B,MAAM;EACR;CACF,CAEO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"get-server-fn-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-server-fn-handlers.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { parseSync } from 'oxc-parser';\nimport { resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { normalizePath } from 'vite';\n\nexport type GetServerFnHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalServerFnDirs?: string[];\n};\n\nexport type ServerFnHandlerModule = {\n /** Absolute, normalized path to a discovered `*.server.ts` module. */\n file: string;\n};\n\n/**\n * `*.server.ts` files that are matched by the glob but are never server-function\n * hosts, so importing them for registration side-effects would be wrong.\n *\n * The SSR entries (`main.server.ts`, `main-cf.server.ts`, …) sit at the top of\n * the source root and bootstrap the whole Angular application; importing one\n * would pull the entire app into the dispatch bundle. They are matched by\n * directory rather than by name so a page named `main.server.ts` still counts.\n */\nconst EXCLUDED_SERVER_FILES: RegExp[] = [/\\/app\\.config\\.server\\.ts$/];\n\n/**\n * Discovers the `*.server.ts` modules that may define server functions.\n *\n * Unlike page endpoints (one Nitro handler per file), server functions all\n * share a single `/_analog/fn/:id` dispatch route. The discovered modules are\n * imported for their registration side-effects — each `serverFn(...)` call\n * registers itself into the server-side registry at import time — after which\n * dispatch looks up the requested function by id.\n *\n * Scope is `<projectRoot>/<sourceRoot>/**\\/*.server.ts` because the RFC allows a\n * server function to live in any `.server.ts` module, including existing page\n * server files. Only modules defining a server function that the client\n * transform can rewrite participate.\n * Angular SSR config (`app.config.server.ts`) is excluded — it is not a route or\n * function module and must not be pulled into the dispatch bundle.\n *\n * @returns discovered modules, de-duplicated and sorted for deterministic output\n */\nexport function getServerFnHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalServerFnDirs,\n}: GetServerFnHandlersArgs): ServerFnHandlerModule[] {\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n const files = globSync(\n [\n `${root}/${sourceRoot}/**/*.server.ts`,\n ...(additionalServerFnDirs || []).map(\n (dir) => `${workspaceRoot}${dir}/**/*.server.ts`,\n ),\n ],\n { dot: true, absolute: true },\n ).map((file) => normalizePath(file));\n\n const sourceRootDir = `${root}/${sourceRoot}/`;\n const seen = new Set<string>();\n return files\n .filter((file) => !EXCLUDED_SERVER_FILES.some((re) => re.test(file)))\n .filter(\n (file) =>\n !file.startsWith(sourceRootDir) ||\n file.slice(sourceRootDir.length).includes('/'),\n )\n .filter((file) => (seen.has(file) ? false : (seen.add(file), true)))\n .sort()\n .filter(definesServerFn)\n .map((file) => ({ file }));\n}\n\n/**\n * Match the client scrub's supported server-function declaration shape. The\n * scrub deliberately falls back to the conventional `serverFn` name when the\n * function is re-exported through a local barrel, so discovery must make the\n * same choice or the browser receives a proxy without a dispatch route.\n */\nfunction definesServerFn(file: string): boolean {\n const code = readFileSync(file, 'utf8');\n if (!code.includes('serverFn')) return false;\n\n const { program } = parseSync(file, code);\n const localNames = new Set<string>();\n for (const node of program.body) {\n if (\n node.type !== 'ImportDeclaration' ||\n node.source.value !== '@analogjs/router/server'\n ) {\n continue;\n }\n for (const specifier of node.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n (specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value) === 'serverFn'\n ) {\n localNames.add(specifier.local.name);\n }\n }\n }\n if (localNames.size === 0) localNames.add('serverFn');\n\n return program.body.some(\n (node) =>\n node.type === 'ExportNamedDeclaration' &&\n node.declaration?.type === 'VariableDeclaration' &&\n node.declaration.declarations.some(\n (declarator) =>\n declarator.id?.type === 'Identifier' &&\n declarator.init?.type === 'CallExpression' &&\n declarator.init.callee?.type === 'Identifier' &&\n localNames.has(declarator.init.callee.name),\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,IAAM,wBAAkC,CAAC,6BAA6B;;;;;;;;;;;;;;;;;;;AAoBtE,SAAgB,oBAAoB,EAClC,eACA,YACA,SACA,0BACmD;CACnD,MAAM,OAAO,cAAc,QAAQ,eAAe,QAAQ,CAAC;CAE3D,MAAM,QAAQ,SACZ,CACE,GAAG,KAAK,GAAG,WAAW,kBACtB,IAAI,0BAA0B,EAAE,EAAE,KAC/B,QAAQ,GAAG,gBAAgB,IAAI,iBACjC,CACF,EACD;EAAE,KAAK;EAAM,UAAU;EAAM,CAC9B,CAAC,KAAK,SAAS,cAAc,KAAK,CAAC;CAEpC,MAAM,gBAAgB,GAAG,KAAK,GAAG,WAAW;CAC5C,MAAM,uBAAO,IAAI,KAAa;AAC9B,QAAO,MACJ,QAAQ,SAAS,CAAC,sBAAsB,MAAM,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC,CACpE,QACE,SACC,CAAC,KAAK,WAAW,cAAc,IAC/B,KAAK,MAAM,cAAc,OAAO,CAAC,SAAS,IAAI,CACjD,CACA,QAAQ,SAAU,KAAK,IAAI,KAAK,GAAG,SAAS,KAAK,IAAI,KAAK,EAAE,MAAO,CACnE,MAAM,CACN,OAAO,gBAAgB,CACvB,KAAK,UAAU,EAAE,MAAM,EAAE;;;;;;;;AAS9B,SAAS,gBAAgB,MAAuB;CAC9C,MAAM,OAAO,aAAa,MAAM,OAAO;AACvC,KAAI,CAAC,KAAK,SAAS,WAAW,CAAE,QAAO;CAEvC,MAAM,EAAE,YAAY,UAAU,MAAM,KAAK;CACzC,MAAM,6BAAa,IAAI,KAAa;AACpC,MAAK,MAAM,QAAQ,QAAQ,MAAM;AAC/B,MACE,KAAK,SAAS,uBACd,KAAK,OAAO,UAAU,0BAEtB;AAEF,OAAK,MAAM,aAAa,KAAK,WAC3B,KACE,UAAU,SAAS,sBAClB,UAAU,SAAS,SAAS,eACzB,UAAU,SAAS,OACnB,UAAU,SAAS,WAAW,WAElC,YAAW,IAAI,UAAU,MAAM,KAAK;;AAI1C,KAAI,WAAW,SAAS,EAAG,YAAW,IAAI,WAAW;AAErD,QAAO,QAAQ,KAAK,MACjB,SACC,KAAK,SAAS,4BACd,KAAK,aAAa,SAAS,yBAC3B,KAAK,YAAY,aAAa,MAC3B,eACC,WAAW,IAAI,SAAS,gBACxB,WAAW,MAAM,SAAS,oBAC1B,WAAW,KAAK,QAAQ,SAAS,gBACjC,WAAW,IAAI,WAAW,KAAK,OAAO,KAAK,CAC9C,CACJ"}
1
+ {"version":3,"file":"get-server-fn-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-server-fn-handlers.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { parseSync } from 'oxc-parser';\nimport { resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { normalizePath } from 'vite';\n\nexport type GetServerFnHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalServerFnDirs?: string[];\n};\n\nexport type ServerFnHandlerModule = {\n /** Absolute, normalized path to a discovered `*.server.ts` module. */\n file: string;\n};\n\n/**\n * `*.server.ts` files that are matched by the glob but are never server-function\n * hosts, so importing them for registration side-effects would be wrong.\n *\n * The SSR entries (`main.server.ts`, `main-cf.server.ts`, …) sit at the top of\n * the source root and bootstrap the whole Angular application; importing one\n * would pull the entire app into the dispatch bundle. They are matched by\n * directory rather than by name so a page named `main.server.ts` still counts.\n */\nconst EXCLUDED_SERVER_FILES: RegExp[] = [/\\/app\\.config\\.server\\.ts$/];\n\n/**\n * Discovers the `*.server.ts` modules that may define server functions.\n *\n * Unlike page endpoints (one Nitro handler per file), server functions all\n * share a single `/_analog/fn/:id` dispatch route. The discovered modules are\n * imported for their registration side-effects — each `serverFn(...)` call\n * registers itself into the server-side registry at import time — after which\n * dispatch looks up the requested function by id.\n *\n * Scope is `<projectRoot>/<sourceRoot>/**\\/*.server.ts` because the RFC allows a\n * server function to live in any `.server.ts` module, including existing page\n * server files. Only modules defining a server function that the client\n * transform can rewrite participate.\n * Angular SSR config (`app.config.server.ts`) is excluded — it is not a route or\n * function module and must not be pulled into the dispatch bundle.\n *\n * @returns discovered modules, de-duplicated and sorted for deterministic output\n */\nexport function getServerFnHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalServerFnDirs,\n}: GetServerFnHandlersArgs): ServerFnHandlerModule[] {\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n const files = globSync(\n [\n `${root}/${sourceRoot}/**/*.server.ts`,\n ...(additionalServerFnDirs || []).map(\n (dir) => `${workspaceRoot}${dir}/**/*.server.ts`,\n ),\n ],\n { dot: true, absolute: true },\n ).map((file) => normalizePath(file));\n\n const sourceRootDir = `${root}/${sourceRoot}/`;\n const seen = new Set<string>();\n return files\n .filter((file) => !EXCLUDED_SERVER_FILES.some((re) => re.test(file)))\n .filter(\n (file) =>\n !file.startsWith(sourceRootDir) ||\n file.slice(sourceRootDir.length).includes('/'),\n )\n .filter((file) => (seen.has(file) ? false : (seen.add(file), true)))\n .sort()\n .filter(definesServerFn)\n .map((file) => ({ file }));\n}\n\n/**\n * Match the client scrub's supported server-function declaration shape. The\n * scrub deliberately falls back to the conventional `serverFn` name when the\n * function is re-exported through a local barrel, so discovery must make the\n * same choice or the browser receives a proxy without a dispatch route.\n */\nfunction definesServerFn(file: string): boolean {\n const code = readFileSync(file, 'utf8');\n if (!code.includes('serverFn')) return false;\n\n const { program } = parseSync(file, code);\n const localNames = new Set<string>();\n for (const node of program.body) {\n if (\n node.type !== 'ImportDeclaration' ||\n node.source.value !== '@analogjs/router/server'\n ) {\n continue;\n }\n for (const specifier of node.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n (specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value) === 'serverFn'\n ) {\n localNames.add(specifier.local.name);\n }\n }\n }\n if (localNames.size === 0) localNames.add('serverFn');\n\n return program.body.some(\n (node) =>\n node.type === 'ExportNamedDeclaration' &&\n node.declaration?.type === 'VariableDeclaration' &&\n node.declaration.declarations.some(\n (declarator) =>\n declarator.id?.type === 'Identifier' &&\n declarator.init?.type === 'CallExpression' &&\n declarator.init.callee?.type === 'Identifier' &&\n localNames.has(declarator.init.callee.name),\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,IAAM,wBAAkC,CAAC,4BAA4B;;;;;;;;;;;;;;;;;;;AAoBrE,SAAgB,oBAAoB,EAClC,eACA,YACA,SACA,0BACmD;CACnD,MAAM,OAAO,cAAc,QAAQ,eAAe,OAAO,CAAC;CAE1D,MAAM,QAAQ,SACZ,CACE,GAAG,KAAK,GAAG,WAAW,kBACtB,IAAI,0BAA0B,CAAC,EAAA,CAAG,KAC/B,QAAQ,GAAG,gBAAgB,IAAI,gBAClC,CACF,GACA;EAAE,KAAK;EAAM,UAAU;CAAK,CAC9B,CAAC,CAAC,KAAK,SAAS,cAAc,IAAI,CAAC;CAEnC,MAAM,gBAAgB,GAAG,KAAK,GAAG,WAAW;CAC5C,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,MACJ,QAAQ,SAAS,CAAC,sBAAsB,MAAM,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,CACpE,QACE,SACC,CAAC,KAAK,WAAW,aAAa,KAC9B,KAAK,MAAM,cAAc,MAAM,CAAC,CAAC,SAAS,GAAG,CACjD,CAAC,CACA,QAAQ,SAAU,KAAK,IAAI,IAAI,IAAI,SAAS,KAAK,IAAI,IAAI,GAAG,KAAM,CAAC,CACnE,KAAK,CAAC,CACN,OAAO,eAAe,CAAC,CACvB,KAAK,UAAU,EAAE,KAAK,EAAE;AAC7B;;;;;;;AAQA,SAAS,gBAAgB,MAAuB;CAC9C,MAAM,OAAO,aAAa,MAAM,MAAM;CACtC,IAAI,CAAC,KAAK,SAAS,UAAU,GAAG,OAAO;CAEvC,MAAM,EAAE,YAAY,UAAU,MAAM,IAAI;CACxC,MAAM,6BAAa,IAAI,IAAY;CACnC,KAAK,MAAM,QAAQ,QAAQ,MAAM;EAC/B,IACE,KAAK,SAAS,uBACd,KAAK,OAAO,UAAU,2BAEtB;EAEF,KAAK,MAAM,aAAa,KAAK,YAC3B,IACE,UAAU,SAAS,sBAClB,UAAU,SAAS,SAAS,eACzB,UAAU,SAAS,OACnB,UAAU,SAAS,WAAW,YAElC,WAAW,IAAI,UAAU,MAAM,IAAI;CAGzC;CACA,IAAI,WAAW,SAAS,GAAG,WAAW,IAAI,UAAU;CAEpD,OAAO,QAAQ,KAAK,MACjB,SACC,KAAK,SAAS,4BACd,KAAK,aAAa,SAAS,yBAC3B,KAAK,YAAY,aAAa,MAC3B,eACC,WAAW,IAAI,SAAS,gBACxB,WAAW,MAAM,SAAS,oBAC1B,WAAW,KAAK,QAAQ,SAAS,gBACjC,WAAW,IAAI,WAAW,KAAK,OAAO,IAAI,CAC9C,CACJ;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"i18n-prerender.js","names":[],"sources":["../../../../src/lib/utils/i18n-prerender.ts"],"sourcesContent":["import { PrerenderRoute } from 'nitropack';\nimport { I18nPrerenderOptions } from '../options.js';\n\n/**\n * Expands a list of routes to include locale-prefixed variants.\n *\n * For each route and each locale, generates a prefixed route:\n * '/' + locale + route\n *\n * The default locale's routes are included both with and without the prefix\n * so that `/about` and `/en/about` both render.\n * Routes that already have a configured locale prefix are kept as-is.\n *\n * @param routes - The original routes to expand\n * @param i18n - The i18n prerender configuration\n * @returns Expanded routes with locale prefixes\n */\nexport function expandRoutesWithLocales(\n routes: string[],\n i18n: I18nPrerenderOptions,\n): string[] {\n const expanded = new Set<string>();\n\n for (const route of routes) {\n // API routes and explicitly localized routes don't need locale prefixes.\n const firstSegment = route.split('/').filter(Boolean)[0];\n if (\n route.includes('/_analog/') ||\n route.startsWith('/api/') ||\n i18n.locales.includes(firstSegment)\n ) {\n expanded.add(route);\n continue;\n }\n\n for (const locale of i18n.locales) {\n const prefix = `/${locale}`;\n const localizedRoute = route === '/' ? prefix : `${prefix}${route}`;\n expanded.add(localizedRoute);\n }\n\n // Keep the unprefixed route for the default locale\n expanded.add(route);\n }\n\n return [...expanded];\n}\n\n/**\n * Creates a post-rendering hook that injects the `lang` attribute\n * into the `<html>` tag of prerendered pages based on the route's\n * locale prefix.\n *\n * @param i18n - The i18n prerender configuration\n * @returns A post-rendering hook function\n */\nexport function createI18nPostRenderingHook(\n i18n: I18nPrerenderOptions,\n): (route: PrerenderRoute) => Promise<void> {\n return async (route: PrerenderRoute) => {\n if (!route.contents || typeof route.contents !== 'string') {\n return;\n }\n\n const locale = detectLocaleFromRoute(route.route, i18n);\n if (!locale) {\n return;\n }\n\n // Inject or replace the lang attribute on <html>\n route.contents = setHtmlLang(route.contents, locale);\n };\n}\n\n/**\n * Detects the locale from a prerendered route path by checking\n * the first path segment against the configured locales.\n */\nexport function detectLocaleFromRoute(\n route: string,\n i18n: I18nPrerenderOptions,\n): string {\n const segments = route.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && i18n.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return i18n.defaultLocale;\n}\n\n/**\n * Sets the `lang` attribute on the `<html>` tag in an HTML string.\n * If a `lang` attribute already exists, it is replaced.\n * If no `lang` attribute exists, it is added.\n */\nexport function setHtmlLang(html: string, locale: string): string {\n // Replace existing lang attribute\n if (/<html[^>]*\\slang\\s*=\\s*[\"'][^\"']*[\"']/i.test(html)) {\n return html.replace(\n /(<html[^>]*\\s)lang\\s*=\\s*[\"'][^\"']*[\"']/i,\n `$1lang=\"${locale}\"`,\n );\n }\n\n // Add lang attribute to <html> tag\n return html.replace(/<html/i, `<html lang=\"${locale}\"`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,SAAgB,wBACd,QACA,MACU;CACV,MAAM,2BAAW,IAAI,KAAa;AAElC,MAAK,MAAM,SAAS,QAAQ;EAE1B,MAAM,eAAe,MAAM,MAAM,IAAI,CAAC,OAAO,QAAQ,CAAC;AACtD,MACE,MAAM,SAAS,YAAY,IAC3B,MAAM,WAAW,QAAQ,IACzB,KAAK,QAAQ,SAAS,aAAa,EACnC;AACA,YAAS,IAAI,MAAM;AACnB;;AAGF,OAAK,MAAM,UAAU,KAAK,SAAS;GACjC,MAAM,SAAS,IAAI;GACnB,MAAM,iBAAiB,UAAU,MAAM,SAAS,GAAG,SAAS;AAC5D,YAAS,IAAI,eAAe;;AAI9B,WAAS,IAAI,MAAM;;AAGrB,QAAO,CAAC,GAAG,SAAS;;;;;;;;;;AAWtB,SAAgB,4BACd,MAC0C;AAC1C,QAAO,OAAO,UAA0B;AACtC,MAAI,CAAC,MAAM,YAAY,OAAO,MAAM,aAAa,SAC/C;EAGF,MAAM,SAAS,sBAAsB,MAAM,OAAO,KAAK;AACvD,MAAI,CAAC,OACH;AAIF,QAAM,WAAW,YAAY,MAAM,UAAU,OAAO;;;;;;;AAQxD,SAAgB,sBACd,OACA,MACQ;CAER,MAAM,eADW,MAAM,MAAM,IAAI,CAAC,OAAO,QAAQ,CACnB;AAE9B,KAAI,gBAAgB,KAAK,QAAQ,SAAS,aAAa,CACrD,QAAO;AAGT,QAAO,KAAK;;;;;;;AAQd,SAAgB,YAAY,MAAc,QAAwB;AAEhE,KAAI,yCAAyC,KAAK,KAAK,CACrD,QAAO,KAAK,QACV,4CACA,WAAW,OAAO,GACnB;AAIH,QAAO,KAAK,QAAQ,UAAU,eAAe,OAAO,GAAG"}
1
+ {"version":3,"file":"i18n-prerender.js","names":[],"sources":["../../../../src/lib/utils/i18n-prerender.ts"],"sourcesContent":["import { PrerenderRoute } from 'nitropack';\nimport { I18nPrerenderOptions } from '../options.js';\n\n/**\n * Expands a list of routes to include locale-prefixed variants.\n *\n * For each route and each locale, generates a prefixed route:\n * '/' + locale + route\n *\n * The default locale's routes are included both with and without the prefix\n * so that `/about` and `/en/about` both render.\n * Routes that already have a configured locale prefix are kept as-is.\n *\n * @param routes - The original routes to expand\n * @param i18n - The i18n prerender configuration\n * @returns Expanded routes with locale prefixes\n */\nexport function expandRoutesWithLocales(\n routes: string[],\n i18n: I18nPrerenderOptions,\n): string[] {\n const expanded = new Set<string>();\n\n for (const route of routes) {\n // API routes and explicitly localized routes don't need locale prefixes.\n const firstSegment = route.split('/').filter(Boolean)[0];\n if (\n route.includes('/_analog/') ||\n route.startsWith('/api/') ||\n i18n.locales.includes(firstSegment)\n ) {\n expanded.add(route);\n continue;\n }\n\n for (const locale of i18n.locales) {\n const prefix = `/${locale}`;\n const localizedRoute = route === '/' ? prefix : `${prefix}${route}`;\n expanded.add(localizedRoute);\n }\n\n // Keep the unprefixed route for the default locale\n expanded.add(route);\n }\n\n return [...expanded];\n}\n\n/**\n * Creates a post-rendering hook that injects the `lang` attribute\n * into the `<html>` tag of prerendered pages based on the route's\n * locale prefix.\n *\n * @param i18n - The i18n prerender configuration\n * @returns A post-rendering hook function\n */\nexport function createI18nPostRenderingHook(\n i18n: I18nPrerenderOptions,\n): (route: PrerenderRoute) => Promise<void> {\n return async (route: PrerenderRoute) => {\n if (!route.contents || typeof route.contents !== 'string') {\n return;\n }\n\n const locale = detectLocaleFromRoute(route.route, i18n);\n if (!locale) {\n return;\n }\n\n // Inject or replace the lang attribute on <html>\n route.contents = setHtmlLang(route.contents, locale);\n };\n}\n\n/**\n * Detects the locale from a prerendered route path by checking\n * the first path segment against the configured locales.\n */\nexport function detectLocaleFromRoute(\n route: string,\n i18n: I18nPrerenderOptions,\n): string {\n const segments = route.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && i18n.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return i18n.defaultLocale;\n}\n\n/**\n * Sets the `lang` attribute on the `<html>` tag in an HTML string.\n * If a `lang` attribute already exists, it is replaced.\n * If no `lang` attribute exists, it is added.\n */\nexport function setHtmlLang(html: string, locale: string): string {\n // Replace existing lang attribute\n if (/<html[^>]*\\slang\\s*=\\s*[\"'][^\"']*[\"']/i.test(html)) {\n return html.replace(\n /(<html[^>]*\\s)lang\\s*=\\s*[\"'][^\"']*[\"']/i,\n `$1lang=\"${locale}\"`,\n );\n }\n\n // Add lang attribute to <html> tag\n return html.replace(/<html/i, `<html lang=\"${locale}\"`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,SAAgB,wBACd,QACA,MACU;CACV,MAAM,2BAAW,IAAI,IAAY;CAEjC,KAAK,MAAM,SAAS,QAAQ;EAE1B,MAAM,eAAe,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;EACtD,IACE,MAAM,SAAS,WAAW,KAC1B,MAAM,WAAW,OAAO,KACxB,KAAK,QAAQ,SAAS,YAAY,GAClC;GACA,SAAS,IAAI,KAAK;GAClB;EACF;EAEA,KAAK,MAAM,UAAU,KAAK,SAAS;GACjC,MAAM,SAAS,IAAI;GACnB,MAAM,iBAAiB,UAAU,MAAM,SAAS,GAAG,SAAS;GAC5D,SAAS,IAAI,cAAc;EAC7B;EAGA,SAAS,IAAI,KAAK;CACpB;CAEA,OAAO,CAAC,GAAG,QAAQ;AACrB;;;;;;;;;AAUA,SAAgB,4BACd,MAC0C;CAC1C,OAAO,OAAO,UAA0B;EACtC,IAAI,CAAC,MAAM,YAAY,OAAO,MAAM,aAAa,UAC/C;EAGF,MAAM,SAAS,sBAAsB,MAAM,OAAO,IAAI;EACtD,IAAI,CAAC,QACH;EAIF,MAAM,WAAW,YAAY,MAAM,UAAU,MAAM;CACrD;AACF;;;;;AAMA,SAAgB,sBACd,OACA,MACQ;CAER,MAAM,eADW,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OACpB,CAAA,CAAS;CAE9B,IAAI,gBAAgB,KAAK,QAAQ,SAAS,YAAY,GACpD,OAAO;CAGT,OAAO,KAAK;AACd;;;;;;AAOA,SAAgB,YAAY,MAAc,QAAwB;CAEhE,IAAI,yCAAyC,KAAK,IAAI,GACpD,OAAO,KAAK,QACV,4CACA,WAAW,OAAO,EACpB;CAIF,OAAO,KAAK,QAAQ,UAAU,eAAe,OAAO,EAAE;AACxD"}
@@ -1 +1 @@
1
- {"version":3,"file":"i18n-workers.js","names":[],"sources":["../../../../src/lib/utils/i18n-workers.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { NitroConfig } from 'nitropack';\nimport type { Options, I18nPrerenderOptions } from '../options.js';\n\nexport const I18N_WORKER_SSR_ENTRY = 'virtual:analog-i18n/main.server';\n\nexport function validateI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): void {\n if (!options.i18n?.loader) {\n throw new Error('i18n.workers requires an i18n.loader module.');\n }\n if (!options.ssr || nitro.preset !== 'node-server') {\n throw new Error('i18n.workers requires SSR and the node-server preset.');\n }\n if (\n options.experimental?.streaming ||\n nitro.experimental?.websocket ||\n Object.keys(nitro.scheduledTasks ?? {}).length\n ) {\n throw new Error(\n 'i18n.workers does not support experimental streaming, WebSockets, or scheduled tasks.',\n );\n }\n const { locales, defaultLocale } = options.i18n;\n if (\n !locales.length ||\n new Set(locales).size !== locales.length ||\n !locales.includes(defaultLocale)\n ) {\n throw new Error(\n 'i18n.workers requires unique locales including defaultLocale.',\n );\n }\n}\n\nexport function resolveI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): boolean {\n const i18n = options.i18n;\n if (!i18n || i18n.workers === false) return false;\n if (i18n.workers !== true && (!i18n.loader || i18n.locales.length < 2))\n return false;\n try {\n validateI18nWorkers(options, nitro);\n return true;\n } catch (error) {\n if (i18n.workers === true) throw error;\n console.warn(\n `[@analogjs/platform] Automatic i18n workers disabled: ${(error as Error).message} Concurrent cross-locale SSR remains unisolated.`,\n );\n return false;\n }\n}\n\nexport function i18nWorkerSsrEntry(\n entry: string,\n loader: string,\n config: I18nPrerenderOptions,\n) {\n return `\nimport '@angular/localize/init';\nimport { loadTranslations } from '@angular/localize';\nimport load from ${JSON.stringify(loader)};\nimport { setHtmlLang } from ${JSON.stringify(join(dirname(fileURLToPath(import.meta.url)), 'i18n-prerender.js'))};\n\nconst locale = process.env['ANALOG_I18N_LOCALE'];\nlet renderer;\nexport const i18nReady = locale ? (async () => {\n if (!${JSON.stringify(config.locales)}.includes(locale)) {\n throw new Error('Unsupported i18n worker locale: ' + locale);\n }\n if (locale !== ${JSON.stringify(config.locales[0])}) {\n loadTranslations(await load(locale));\n }\n renderer = (await import(${JSON.stringify(entry)})).default;\n})() : Promise.resolve();\n\nexport default async function (...args) {\n if (!locale) throw new Error('This SSR build must run in its locale worker.');\n await i18nReady;\n args[1] = setHtmlLang(args[1], locale);\n return renderer(...args);\n}\n`;\n}\n"],"mappings":";;;AAKA,IAAa,wBAAwB;AAErC,SAAgB,oBACd,SACA,OACM;AACN,KAAI,CAAC,QAAQ,MAAM,OACjB,OAAM,IAAI,MAAM,+CAA+C;AAEjE,KAAI,CAAC,QAAQ,OAAO,MAAM,WAAW,cACnC,OAAM,IAAI,MAAM,wDAAwD;AAE1E,KACE,QAAQ,cAAc,aACtB,MAAM,cAAc,aACpB,OAAO,KAAK,MAAM,kBAAkB,EAAE,CAAC,CAAC,OAExC,OAAM,IAAI,MACR,wFACD;CAEH,MAAM,EAAE,SAAS,kBAAkB,QAAQ;AAC3C,KACE,CAAC,QAAQ,UACT,IAAI,IAAI,QAAQ,CAAC,SAAS,QAAQ,UAClC,CAAC,QAAQ,SAAS,cAAc,CAEhC,OAAM,IAAI,MACR,gEACD;;AAIL,SAAgB,mBACd,SACA,OACS;CACT,MAAM,OAAO,QAAQ;AACrB,KAAI,CAAC,QAAQ,KAAK,YAAY,MAAO,QAAO;AAC5C,KAAI,KAAK,YAAY,SAAS,CAAC,KAAK,UAAU,KAAK,QAAQ,SAAS,GAClE,QAAO;AACT,KAAI;AACF,sBAAoB,SAAS,MAAM;AACnC,SAAO;UACA,OAAO;AACd,MAAI,KAAK,YAAY,KAAM,OAAM;AACjC,UAAQ,KACN,yDAA0D,MAAgB,QAAQ,kDACnF;AACD,SAAO;;;AAIX,SAAgB,mBACd,OACA,QACA,QACA;AACA,QAAO;;;mBAGU,KAAK,UAAU,OAAO,CAAC;8BACZ,KAAK,UAAU,KAAK,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC,EAAE,oBAAoB,CAAC,CAAC;;;;;SAKxG,KAAK,UAAU,OAAO,QAAQ,CAAC;;;mBAGrB,KAAK,UAAU,OAAO,QAAQ,GAAG,CAAC;;;6BAGxB,KAAK,UAAU,MAAM,CAAC"}
1
+ {"version":3,"file":"i18n-workers.js","names":[],"sources":["../../../../src/lib/utils/i18n-workers.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { NitroConfig } from 'nitropack';\nimport type { Options, I18nPrerenderOptions } from '../options.js';\n\nexport const I18N_WORKER_SSR_ENTRY = 'virtual:analog-i18n/main.server';\n\nexport function validateI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): void {\n if (!options.i18n?.loader) {\n throw new Error('i18n.workers requires an i18n.loader module.');\n }\n if (!options.ssr || nitro.preset !== 'node-server') {\n throw new Error('i18n.workers requires SSR and the node-server preset.');\n }\n if (\n options.experimental?.streaming ||\n nitro.experimental?.websocket ||\n Object.keys(nitro.scheduledTasks ?? {}).length\n ) {\n throw new Error(\n 'i18n.workers does not support experimental streaming, WebSockets, or scheduled tasks.',\n );\n }\n const { locales, defaultLocale } = options.i18n;\n if (\n !locales.length ||\n new Set(locales).size !== locales.length ||\n !locales.includes(defaultLocale)\n ) {\n throw new Error(\n 'i18n.workers requires unique locales including defaultLocale.',\n );\n }\n}\n\nexport function resolveI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): boolean {\n const i18n = options.i18n;\n if (!i18n || i18n.workers === false) return false;\n if (i18n.workers !== true && (!i18n.loader || i18n.locales.length < 2))\n return false;\n try {\n validateI18nWorkers(options, nitro);\n return true;\n } catch (error) {\n if (i18n.workers === true) throw error;\n console.warn(\n `[@analogjs/platform] Automatic i18n workers disabled: ${(error as Error).message} Concurrent cross-locale SSR remains unisolated.`,\n );\n return false;\n }\n}\n\nexport function i18nWorkerSsrEntry(\n entry: string,\n loader: string,\n config: I18nPrerenderOptions,\n) {\n return `\nimport '@angular/localize/init';\nimport { loadTranslations } from '@angular/localize';\nimport load from ${JSON.stringify(loader)};\nimport { setHtmlLang } from ${JSON.stringify(join(dirname(fileURLToPath(import.meta.url)), 'i18n-prerender.js'))};\n\nconst locale = process.env['ANALOG_I18N_LOCALE'];\nlet renderer;\nexport const i18nReady = locale ? (async () => {\n if (!${JSON.stringify(config.locales)}.includes(locale)) {\n throw new Error('Unsupported i18n worker locale: ' + locale);\n }\n if (locale !== ${JSON.stringify(config.locales[0])}) {\n loadTranslations(await load(locale));\n }\n renderer = (await import(${JSON.stringify(entry)})).default;\n})() : Promise.resolve();\n\nexport default async function (...args) {\n if (!locale) throw new Error('This SSR build must run in its locale worker.');\n await i18nReady;\n args[1] = setHtmlLang(args[1], locale);\n return renderer(...args);\n}\n`;\n}\n"],"mappings":";;;AAKA,IAAa,wBAAwB;AAErC,SAAgB,oBACd,SACA,OACM;CACN,IAAI,CAAC,QAAQ,MAAM,QACjB,MAAM,IAAI,MAAM,8CAA8C;CAEhE,IAAI,CAAC,QAAQ,OAAO,MAAM,WAAW,eACnC,MAAM,IAAI,MAAM,uDAAuD;CAEzE,IACE,QAAQ,cAAc,aACtB,MAAM,cAAc,aACpB,OAAO,KAAK,MAAM,kBAAkB,CAAC,CAAC,CAAC,CAAC,QAExC,MAAM,IAAI,MACR,uFACF;CAEF,MAAM,EAAE,SAAS,kBAAkB,QAAQ;CAC3C,IACE,CAAC,QAAQ,UACT,IAAI,IAAI,OAAO,CAAC,CAAC,SAAS,QAAQ,UAClC,CAAC,QAAQ,SAAS,aAAa,GAE/B,MAAM,IAAI,MACR,+DACF;AAEJ;AAEA,SAAgB,mBACd,SACA,OACS;CACT,MAAM,OAAO,QAAQ;CACrB,IAAI,CAAC,QAAQ,KAAK,YAAY,OAAO,OAAO;CAC5C,IAAI,KAAK,YAAY,SAAS,CAAC,KAAK,UAAU,KAAK,QAAQ,SAAS,IAClE,OAAO;CACT,IAAI;EACF,oBAAoB,SAAS,KAAK;EAClC,OAAO;CACT,SAAS,OAAO;EACd,IAAI,KAAK,YAAY,MAAM,MAAM;EACjC,QAAQ,KACN,yDAA0D,MAAgB,QAAQ,iDACpF;EACA,OAAO;CACT;AACF;AAEA,SAAgB,mBACd,OACA,QACA,QACA;CACA,OAAO;;;mBAGU,KAAK,UAAU,MAAM,EAAE;8BACZ,KAAK,UAAU,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,GAAG,mBAAmB,CAAC,EAAE;;;;;SAKxG,KAAK,UAAU,OAAO,OAAO,EAAE;;;mBAGrB,KAAK,UAAU,OAAO,QAAQ,EAAE,EAAE;;;6BAGxB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;AAUnD"}
@@ -1 +1 @@
1
- {"version":3,"file":"inject-server-fn-ids.js","names":[],"sources":["../../../../src/lib/utils/inject-server-fn-ids.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\nimport { deriveServerFnId } from './derive-server-fn-id.js';\n\nconst SERVER_FN_SOURCE = '@analogjs/router/server';\n\nexport interface InjectServerFnIdsResult {\n code: string;\n ids: { name: string; id: string }[];\n}\n\n/**\n * Server/SSR-build transform: injects the derived `id` into each\n * `export const NAME = serverFn(config, handler)` so the function registers\n * under the same opaque id the client proxy dispatches to. Unlike the client\n * scrub this keeps the handler and every other statement intact — it only edits\n * the config object — so the server module still runs the real implementation.\n *\n * Returns `null` when the module defines no server function.\n */\nexport function injectServerFnIds(\n code: string,\n fileId: string,\n): InjectServerFnIdsResult | null {\n if (!code.includes('serverFn')) {\n return null;\n }\n\n const { program } = parseSync(fileId, code);\n const body = (program as { body: any[] }).body;\n const serverFnLocalNames = collectServerFnLocalNames(body);\n\n const magic = new MagicString(code);\n const ids: { name: string; id: string }[] = [];\n\n for (const node of body) {\n if (\n node.type !== 'ExportNamedDeclaration' ||\n node.declaration?.type !== 'VariableDeclaration'\n ) {\n continue;\n }\n for (const declarator of node.declaration.declarations) {\n if (\n declarator.id?.type !== 'Identifier' ||\n declarator.init?.type !== 'CallExpression' ||\n declarator.init.callee?.type !== 'Identifier' ||\n !serverFnLocalNames.has(declarator.init.callee.name)\n ) {\n continue;\n }\n\n const name = declarator.id.name;\n const id = deriveServerFnId(fileId, name);\n ids.push({ name, id });\n\n const args = declarator.init.arguments ?? [];\n const arg0 = args[0];\n const idProp = `id: ${JSON.stringify(id)}`;\n\n if (arg0?.type === 'ObjectExpression') {\n // serverFn({ … }, handler) — inject the id into the config object.\n assertMethodInputCompatible(arg0, name, fileId);\n injectId(magic, arg0, id);\n } else if (isFunctionNode(arg0)) {\n // serverFn(handler) — synthesize a config: `{ id }, handler`.\n magic.appendLeft(arg0.start, `{ ${idProp} }, `);\n } else if (arg0 && args.length >= 2) {\n // serverFn(schema, handler) — wrap the schema into `{ id, input: <schema> }`.\n magic.appendLeft(arg0.start, `{ ${idProp}, input: `);\n magic.appendRight(arg0.end, ` }`);\n } else {\n throw new Error(\n `[analog] serverFn \"${name}\" in ${fileId} must be called as serverFn(handler), serverFn(schema, handler), or serverFn(config, handler).`,\n );\n }\n }\n }\n\n if (ids.length === 0) {\n return null;\n }\n\n return { code: magic.toString(), ids };\n}\n\n/**\n * Insert (or replace) `id: \"<derived>\"` in the config object. Authors do not\n * supply an id; a stray one is overwritten so the route is always the derived,\n * non-enumerable digest — never an author-controlled value.\n */\nfunction injectId(magic: MagicString, configArg: any, id: string): void {\n const existing = (configArg.properties ?? []).find(\n (prop: any) =>\n prop.type === 'Property' &&\n (prop.key?.type === 'Identifier' ? prop.key.name : prop.key?.value) ===\n 'id',\n );\n\n if (existing) {\n magic.overwrite(\n existing.value.start,\n existing.value.end,\n JSON.stringify(id),\n );\n return;\n }\n\n // Insert as the first property, right after the opening brace.\n magic.appendRight(configArg.start + 1, ` id: ${JSON.stringify(id)},`);\n}\n\n/**\n * Reject `method: 'GET'` alongside an `input` schema at build time: GET carries\n * no body, so a GET function can never receive validated input.\n */\nfunction assertMethodInputCompatible(\n configArg: any,\n name: string,\n fileId: string,\n): void {\n let method: string | undefined;\n let hasInput = false;\n for (const prop of configArg.properties ?? []) {\n if (prop.type !== 'Property') continue;\n const key =\n prop.key?.type === 'Identifier' ? prop.key.name : prop.key?.value;\n if (key === 'method' && prop.value?.type === 'Literal') {\n method = prop.value.value;\n } else if (key === 'input') {\n hasInput = true;\n }\n }\n if (method === 'GET' && hasInput) {\n throw new Error(\n `[analog] serverFn \"${name}\" in ${fileId} declares method: 'GET' with an input schema; GET carries no body. Use POST (the default when input is present) or drop the input.`,\n );\n }\n}\n\nfunction isFunctionNode(node: any): boolean {\n return (\n node?.type === 'ArrowFunctionExpression' ||\n node?.type === 'FunctionExpression'\n );\n}\n\nfunction collectServerFnLocalNames(body: any[]): Set<string> {\n const names = new Set<string>();\n for (const node of body) {\n if (\n node.type !== 'ImportDeclaration' ||\n node.source?.value !== SERVER_FN_SOURCE\n ) {\n continue;\n }\n for (const spec of node.specifiers ?? []) {\n if (\n spec.type === 'ImportSpecifier' &&\n spec.imported?.name === 'serverFn'\n ) {\n names.add(spec.local.name);\n }\n }\n }\n if (names.size === 0) {\n names.add('serverFn');\n }\n return names;\n}\n"],"mappings":";;;;AAKA,IAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAgB,kBACd,MACA,QACgC;AAChC,KAAI,CAAC,KAAK,SAAS,WAAW,CAC5B,QAAO;CAGT,MAAM,EAAE,YAAY,UAAU,QAAQ,KAAK;CAC3C,MAAM,OAAQ,QAA4B;CAC1C,MAAM,qBAAqB,0BAA0B,KAAK;CAE1D,MAAM,QAAQ,IAAI,YAAY,KAAK;CACnC,MAAM,MAAsC,EAAE;AAE9C,MAAK,MAAM,QAAQ,MAAM;AACvB,MACE,KAAK,SAAS,4BACd,KAAK,aA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S,4BACP,WACA,MACA,QACM;CACN,IAAI;CACJ,IAAI,WAAW;AACf,MAAK,MAAM,QAAQ,UAAU,cAAc,EAAE,EAAE;AAC7C,MAAI,KAAK,SAAS,WAAY;EAC9B,MAAM,MACJ,KAAK,KAAK,SAAS,eAAe,KAAK,IAAI,OAAO,KAAK,KAAK;AAC9D,MAAI,QAAQ,YAAY,KAAK,OAAO,SAAS,UAC3C,UAAS,KAAK,MAAM;WACX,QAAQ,QACjB,YAAW;;AAGf,KAAI,WAAW,SAAS,SACtB,OAAM,IAAI,MACR,sBAAsB,KAAK,OAAO,OAAO,oIAC1C;;AAIL,SAAS,eAAe,MAAoB;AAC1C,QACE,MAAM,SAAS,6BACf,MAAM,SAAS;;AAInB,SAAS,0BAA0B,MAA0B;CAC3D,MAAM,wBAAQ,IAAI,KAAa;AAC/B,MAAK,MAAM,QAAQ,MAAM;AACvB,MACE,KAAK,SAAS,uBACd,KAAK,QAAQ,UAAU,iBAEvB;AAEF,OAAK,MAAM,QAAQ,KAAK,cAAc,EAAE,CACtC,KACE,KAAK,SAAS,qBACd,KAAK,UAAU,SAAS,WAExB,OAAM,IAAI,KAAK,MAAM,KAAK;;AAIhC,KAAI,MAAM,SAAS,EACjB,OAAM,IAAI,WAAW;AAEvB,QAAO"}
1
+ {"version":3,"file":"inject-server-fn-ids.js","names":[],"sources":["../../../../src/lib/utils/inject-server-fn-ids.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\nimport { deriveServerFnId } from './derive-server-fn-id.js';\n\nconst SERVER_FN_SOURCE = '@analogjs/router/server';\n\nexport interface InjectServerFnIdsResult {\n code: string;\n ids: { name: string; id: string }[];\n}\n\n/**\n * Server/SSR-build transform: injects the derived `id` into each\n * `export const NAME = serverFn(config, handler)` so the function registers\n * under the same opaque id the client proxy dispatches to. Unlike the client\n * scrub this keeps the handler and every other statement intact — it only edits\n * the config object — so the server module still runs the real implementation.\n *\n * Returns `null` when the module defines no server function.\n */\nexport function injectServerFnIds(\n code: string,\n fileId: string,\n): InjectServerFnIdsResult | null {\n if (!code.includes('serverFn')) {\n return null;\n }\n\n const { program } = parseSync(fileId, code);\n const body = (program as { body: any[] }).body;\n const serverFnLocalNames = collectServerFnLocalNames(body);\n\n const magic = new MagicString(code);\n const ids: { name: string; id: string }[] = [];\n\n for (const node of body) {\n if (\n node.type !== 'ExportNamedDeclaration' ||\n node.declaration?.type !== 'VariableDeclaration'\n ) {\n continue;\n }\n for (const declarator of node.declaration.declarations) {\n if (\n declarator.id?.type !== 'Identifier' ||\n declarator.init?.type !== 'CallExpression' ||\n declarator.init.callee?.type !== 'Identifier' ||\n !serverFnLocalNames.has(declarator.init.callee.name)\n ) {\n continue;\n }\n\n const name = declarator.id.name;\n const id = deriveServerFnId(fileId, name);\n ids.push({ name, id });\n\n const args = declarator.init.arguments ?? [];\n const arg0 = args[0];\n const idProp = `id: ${JSON.stringify(id)}`;\n\n if (arg0?.type === 'ObjectExpression') {\n // serverFn({ … }, handler) — inject the id into the config object.\n assertMethodInputCompatible(arg0, name, fileId);\n injectId(magic, arg0, id);\n } else if (isFunctionNode(arg0)) {\n // serverFn(handler) — synthesize a config: `{ id }, handler`.\n magic.appendLeft(arg0.start, `{ ${idProp} }, `);\n } else if (arg0 && args.length >= 2) {\n // serverFn(schema, handler) — wrap the schema into `{ id, input: <schema> }`.\n magic.appendLeft(arg0.start, `{ ${idProp}, input: `);\n magic.appendRight(arg0.end, ` }`);\n } else {\n throw new Error(\n `[analog] serverFn \"${name}\" in ${fileId} must be called as serverFn(handler), serverFn(schema, handler), or serverFn(config, handler).`,\n );\n }\n }\n }\n\n if (ids.length === 0) {\n return null;\n }\n\n return { code: magic.toString(), ids };\n}\n\n/**\n * Insert (or replace) `id: \"<derived>\"` in the config object. Authors do not\n * supply an id; a stray one is overwritten so the route is always the derived,\n * non-enumerable digest — never an author-controlled value.\n */\nfunction injectId(magic: MagicString, configArg: any, id: string): void {\n const existing = (configArg.properties ?? []).find(\n (prop: any) =>\n prop.type === 'Property' &&\n (prop.key?.type === 'Identifier' ? prop.key.name : prop.key?.value) ===\n 'id',\n );\n\n if (existing) {\n magic.overwrite(\n existing.value.start,\n existing.value.end,\n JSON.stringify(id),\n );\n return;\n }\n\n // Insert as the first property, right after the opening brace.\n magic.appendRight(configArg.start + 1, ` id: ${JSON.stringify(id)},`);\n}\n\n/**\n * Reject `method: 'GET'` alongside an `input` schema at build time: GET carries\n * no body, so a GET function can never receive validated input.\n */\nfunction assertMethodInputCompatible(\n configArg: any,\n name: string,\n fileId: string,\n): void {\n let method: string | undefined;\n let hasInput = false;\n for (const prop of configArg.properties ?? []) {\n if (prop.type !== 'Property') continue;\n const key =\n prop.key?.type === 'Identifier' ? prop.key.name : prop.key?.value;\n if (key === 'method' && prop.value?.type === 'Literal') {\n method = prop.value.value;\n } else if (key === 'input') {\n hasInput = true;\n }\n }\n if (method === 'GET' && hasInput) {\n throw new Error(\n `[analog] serverFn \"${name}\" in ${fileId} declares method: 'GET' with an input schema; GET carries no body. Use POST (the default when input is present) or drop the input.`,\n );\n }\n}\n\nfunction isFunctionNode(node: any): boolean {\n return (\n node?.type === 'ArrowFunctionExpression' ||\n node?.type === 'FunctionExpression'\n );\n}\n\nfunction collectServerFnLocalNames(body: any[]): Set<string> {\n const names = new Set<string>();\n for (const node of body) {\n if (\n node.type !== 'ImportDeclaration' ||\n node.source?.value !== SERVER_FN_SOURCE\n ) {\n continue;\n }\n for (const spec of node.specifiers ?? []) {\n if (\n spec.type === 'ImportSpecifier' &&\n spec.imported?.name === 'serverFn'\n ) {\n names.add(spec.local.name);\n }\n }\n }\n if (names.size === 0) {\n names.add('serverFn');\n }\n return names;\n}\n"],"mappings":";;;;AAKA,IAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAgB,kBACd,MACA,QACgC;CAChC,IAAI,CAAC,KAAK,SAAS,UAAU,GAC3B,OAAO;CAGT,MAAM,EAAE,YAAY,UAAU,QAAQ,IAAI;CAC1C,MAAM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,IAAI,OAAO,KAAK,KAAK,WAC3D,IACN;CAEA,IAAI,UAAU;EACZ,MAAM,UACJ,SAAS,MAAM,OACf,SAAS,MAAM,KACf,KAAK,UAAU,EAAE,CACnB;EACA;CACF;CAGA,MAAM,YAAY,UAAU,QAAQ,GAAG,QAAQ,KAAK,UAAU,EAAE,EAAE,EAAE;AACtE;;;;;AAMA,SAAS,4BACP,WACA,MACA,QACM;CACN,IAAI;CACJ,IAAI,WAAW;CACf,KAAK,MAAM,QAAQ,UAAU,cAAc,CAAC,GAAG;EAC7C,IAAI,KAAK,SAAS,YAAY;EAC9B,MAAM,MACJ,KAAK,KAAK,SAAS,eAAe,KAAK,IAAI,OAAO,KAAK,KAAK;EAC9D,IAAI,QAAQ,YAAY,KAAK,OAAO,SAAS,WAC3C,SAAS,KAAK,MAAM;OACf,IAAI,QAAQ,SACjB,WAAW;CAEf;CACA,IAAI,WAAW,SAAS,UACtB,MAAM,IAAI,MACR,sBAAsB,KAAK,OAAO,OAAO,mIAC3C;AAEJ;AAEA,SAAS,eAAe,MAAoB;CAC1C,OACE,MAAM,SAAS,6BACf,MAAM,SAAS;AAEnB;AAEA,SAAS,0BAA0B,MAA0B;CAC3D,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,QAAQ,MAAM;EACvB,IACE,KAAK,SAAS,uBACd,KAAK,QAAQ,UAAU,kBAEvB;EAEF,KAAK,MAAM,QAAQ,KAAK,cAAc,CAAC,GACrC,IACE,KAAK,SAAS,qBACd,KAAK,UAAU,SAAS,YAExB,MAAM,IAAI,KAAK,MAAM,IAAI;CAG/B;CACA,IAAI,MAAM,SAAS,GACjB,MAAM,IAAI,UAAU;CAEtB,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"register-dev-middleware.js","names":[],"sources":["../../../../src/lib/utils/register-dev-middleware.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\nimport { EventHandler, createEvent } from 'h3';\nimport { globSync } from 'tinyglobby';\n\n/**\n * Registers development server middleware by discovering and loading middleware files.\n *\n * This function:\n * 1. Discovers all TypeScript middleware files in the server/middleware directory\n * 2. Dynamically loads each middleware module using Vite's SSR module loader\n * 3. Registers each middleware handler with the Vite development server\n * 4. Handles middleware execution flow and error handling\n *\n * @param root The project root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param viteServer The Vite development server instance\n *\n * Example usage:\n * await registerDevServerMiddleware('/workspace/my-app', 'src', viteServer);\n *\n * Sample middleware file paths that would be discovered:\n * - /workspace/my-app/src/server/middleware/auth.ts\n * - /workspace/my-app/src/server/middleware/cors.ts\n * - /workspace/my-app/src/server/middleware/logging.ts\n * - /workspace/my-app/src/server/middleware/validation.ts\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding middleware files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * globSync options explained:\n * - dot: true - Includes files/directories that start with a dot (e.g., .env.middleware)\n * - absolute: true - Returns absolute file paths instead of relative paths\n *\n * Middleware execution flow:\n * 1. Request comes to Vite dev server\n * 2. Each registered middleware is executed in order\n * 3. If middleware returns a result, request processing stops\n * 4. If middleware returns no result, next middleware is called\n * 5. If no middleware handles the request, it continues to normal Vite processing\n */\nexport async function registerDevServerMiddleware(\n root: string,\n sourceRoot: string,\n viteServer: ViteDevServer,\n): Promise<void> {\n // Discover all TypeScript middleware files in the server/middleware directory\n // Pattern: looks for any .ts files in server/middleware/**/*.ts\n const middlewareFiles = globSync(\n [`${root}/${sourceRoot}/server/middleware/**/*.ts`],\n {\n dot: true,\n absolute: true,\n },\n );\n\n // Register each discovered middleware file with the Vite dev server\n middlewareFiles.forEach((file) => {\n viteServer.middlewares.use(async (req, res, next) => {\n // Dynamically load the middleware module using Vite's SSR module loader\n // This allows for hot module replacement during development\n const middlewareHandler: EventHandler = await viteServer\n .ssrLoadModule(file)\n .then((m: unknown) => (m as { default: EventHandler }).default);\n\n // Execute the middleware handler with the request/response event\n const result = await middlewareHandler(createEvent(req, res));\n\n // If middleware doesn't return a result, continue to next middleware\n // If middleware returns a result, stop processing (middleware handled the request)\n if (!result) {\n next();\n }\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,eAAsB,4BACpB,MACA,YACA,YACe;AAGS,UACtB,CAAC,GAAG,KAAK,GAAG,WAAW,4BAA4B,EACnD;EACE,KAAK;EACL,UAAU;EACX,CACF,CAGe,SAAS,SAAS;AAChC,aAAW,YAAY,IAAI,OAAO,KAAK,KAAK,SAAS;AAYnD,OAAI,CAJW,OALyB,MAAM,WAC3C,cAAc,KAAK,CACnB,MAAM,MAAgB,EAAgC,QAAQ,EAG1B,YAAY,KAAK,IAAI,CAAC,CAK3D,OAAM;IAER;GACF"}
1
+ {"version":3,"file":"register-dev-middleware.js","names":[],"sources":["../../../../src/lib/utils/register-dev-middleware.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\nimport { EventHandler, createEvent } from 'h3';\nimport { globSync } from 'tinyglobby';\n\n/**\n * Registers development server middleware by discovering and loading middleware files.\n *\n * This function:\n * 1. Discovers all TypeScript middleware files in the server/middleware directory\n * 2. Dynamically loads each middleware module using Vite's SSR module loader\n * 3. Registers each middleware handler with the Vite development server\n * 4. Handles middleware execution flow and error handling\n *\n * @param root The project root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param viteServer The Vite development server instance\n *\n * Example usage:\n * await registerDevServerMiddleware('/workspace/my-app', 'src', viteServer);\n *\n * Sample middleware file paths that would be discovered:\n * - /workspace/my-app/src/server/middleware/auth.ts\n * - /workspace/my-app/src/server/middleware/cors.ts\n * - /workspace/my-app/src/server/middleware/logging.ts\n * - /workspace/my-app/src/server/middleware/validation.ts\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding middleware files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * globSync options explained:\n * - dot: true - Includes files/directories that start with a dot (e.g., .env.middleware)\n * - absolute: true - Returns absolute file paths instead of relative paths\n *\n * Middleware execution flow:\n * 1. Request comes to Vite dev server\n * 2. Each registered middleware is executed in order\n * 3. If middleware returns a result, request processing stops\n * 4. If middleware returns no result, next middleware is called\n * 5. If no middleware handles the request, it continues to normal Vite processing\n */\nexport async function registerDevServerMiddleware(\n root: string,\n sourceRoot: string,\n viteServer: ViteDevServer,\n): Promise<void> {\n // Discover all TypeScript middleware files in the server/middleware directory\n // Pattern: looks for any .ts files in server/middleware/**/*.ts\n const middlewareFiles = globSync(\n [`${root}/${sourceRoot}/server/middleware/**/*.ts`],\n {\n dot: true,\n absolute: true,\n },\n );\n\n // Register each discovered middleware file with the Vite dev server\n middlewareFiles.forEach((file) => {\n viteServer.middlewares.use(async (req, res, next) => {\n // Dynamically load the middleware module using Vite's SSR module loader\n // This allows for hot module replacement during development\n const middlewareHandler: EventHandler = await viteServer\n .ssrLoadModule(file)\n .then((m: unknown) => (m as { default: EventHandler }).default);\n\n // Execute the middleware handler with the request/response event\n const result = await middlewareHandler(createEvent(req, res));\n\n // If middleware doesn't return a result, continue to next middleware\n // If middleware returns a result, stop processing (middleware handled the request)\n if (!result) {\n next();\n }\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,eAAsB,4BACpB,MACA,YACA,YACe;CAYf,SARE,CAAC,GAAG,KAAK,GAAG,WAAW,2BAA2B,GAClD;EACE,KAAK;EACL,UAAU;CACZ,CAIF,CAAA,CAAgB,SAAS,SAAS;EAChC,WAAW,YAAY,IAAI,OAAO,KAAK,KAAK,SAAS;GAYnD,IAAI,CAAC,OAJgB,MALyB,WAC3C,cAAc,IAAI,CAAC,CACnB,MAAM,MAAgB,EAAgC,OAAO,EAAA,CAGzB,YAAY,KAAK,GAAG,CAAC,GAK1D,KAAK;EAET,CAAC;CACH,CAAC;AACH"}
@@ -22,6 +22,6 @@ function isTranslationFile(path) {
22
22
  return /i18n.*\.(json|xlf|xmb|arb)$/.test(path);
23
23
  }
24
24
  //#endregion
25
- export { registerI18nWatcher };
25
+ export { isTranslationFile, registerI18nWatcher };
26
26
 
27
27
  //# sourceMappingURL=register-i18n-watcher.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"register-i18n-watcher.js","names":[],"sources":["../../../../src/lib/utils/register-i18n-watcher.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\n\n/**\n * Registers a file watcher that triggers a full page reload\n * when translation files are added or modified.\n *\n * Matches files in i18n directories with .json, .xlf, .xmb, or .arb extensions.\n *\n * @param viteServer The Vite development server instance\n */\nexport function registerI18nWatcher(viteServer: ViteDevServer): void {\n const triggerReload = (path: string) => {\n if (isTranslationFile(path)) {\n viteServer.ws.send({ type: 'full-reload' });\n }\n };\n\n viteServer.watcher.on('change', triggerReload);\n viteServer.watcher.on('add', triggerReload);\n}\n\n/**\n * Checks whether a file path looks like a translation file\n * based on its location in an i18n directory and its extension.\n */\nexport function isTranslationFile(path: string): boolean {\n return /i18n.*\\.(json|xlf|xmb|arb)$/.test(path);\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,oBAAoB,YAAiC;CACnE,MAAM,iBAAiB,SAAiB;AACtC,MAAI,kBAAkB,KAAK,CACzB,YAAW,GAAG,KAAK,EAAE,MAAM,eAAe,CAAC;;AAI/C,YAAW,QAAQ,GAAG,UAAU,cAAc;AAC9C,YAAW,QAAQ,GAAG,OAAO,cAAc;;;;;;AAO7C,SAAgB,kBAAkB,MAAuB;AACvD,QAAO,8BAA8B,KAAK,KAAK"}
1
+ {"version":3,"file":"register-i18n-watcher.js","names":[],"sources":["../../../../src/lib/utils/register-i18n-watcher.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\n\n/**\n * Registers a file watcher that triggers a full page reload\n * when translation files are added or modified.\n *\n * Matches files in i18n directories with .json, .xlf, .xmb, or .arb extensions.\n *\n * @param viteServer The Vite development server instance\n */\nexport function registerI18nWatcher(viteServer: ViteDevServer): void {\n const triggerReload = (path: string) => {\n if (isTranslationFile(path)) {\n viteServer.ws.send({ type: 'full-reload' });\n }\n };\n\n viteServer.watcher.on('change', triggerReload);\n viteServer.watcher.on('add', triggerReload);\n}\n\n/**\n * Checks whether a file path looks like a translation file\n * based on its location in an i18n directory and its extension.\n */\nexport function isTranslationFile(path: string): boolean {\n return /i18n.*\\.(json|xlf|xmb|arb)$/.test(path);\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,oBAAoB,YAAiC;CACnE,MAAM,iBAAiB,SAAiB;EACtC,IAAI,kBAAkB,IAAI,GACxB,WAAW,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;CAE9C;CAEA,WAAW,QAAQ,GAAG,UAAU,aAAa;CAC7C,WAAW,QAAQ,GAAG,OAAO,aAAa;AAC5C;;;;;AAMA,SAAgB,kBAAkB,MAAuB;CACvD,OAAO,8BAA8B,KAAK,IAAI;AAChD"}
@@ -1 +1 @@
1
- {"version":3,"file":"renderers.js","names":[],"sources":["../../../../src/lib/utils/renderers.ts"],"sourcesContent":["export const ssrRenderer = `\nimport { eventHandler, getResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const html = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: event.node.res,\n });\n\n return html;\n});`;\n\nexport const ssrStreamRenderer: string = createSsrStreamRenderer();\n\nexport function createSsrStreamRenderer(prerender = false): string {\n return `\nimport { eventHandler, getResponseHeader, setResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const noStreaming = ${prerender} || getResponseHeader(event, 'x-analog-no-streaming') === 'true';\n const abort = new AbortController();\n const response = event.node.res;\n const cleanup = () => {\n response.removeListener('close', disconnected);\n response.removeListener('finish', cleanup);\n };\n const disconnected = () => {\n cleanup();\n if (!response.writableEnded) abort.abort();\n };\n response.once('close', disconnected);\n response.once('finish', cleanup);\n\n let stream;\n try {\n stream = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: response,\n streaming: !noStreaming,\n signal: abort.signal,\n renderErrorsAsHtml: true,\n });\n } catch (error) {\n cleanup();\n throw error;\n }\n\n setResponseHeader(event, 'content-type', 'text/html;charset=utf-8');\n\n // A \\`streaming: false\\` route rule sets this header; renderStream then emits\n // the buffered render() output as a single chunk. Collect it into a string so\n // the response is a normal buffered document (content-length), not chunked.\n if (noStreaming) {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let html = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n html += decoder.decode(value, { stream: true });\n }\n html += decoder.decode();\n return html;\n }\n\n setResponseHeader(event, 'content-encoding', 'identity');\n setResponseHeader(event, 'cache-control', 'no-store, no-transform');\n return stream;\n});`;\n}\n\nexport const clientRenderer = `\nimport { eventHandler } from 'h3';\n\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async () => {\n return template;\n});\n`;\n"],"mappings":";AAAA,IAAa,cAAc;;;;;;;;;;;;;;;;;;;;;AAsB3B,IAAa,oBAA4B,yBAAyB;AAElE,SAAgB,wBAAwB,YAAY,OAAe;AACjE,QAAO;;;;;;;;;;;;;;wBAce,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDlC,IAAa,iBAAiB"}
1
+ {"version":3,"file":"renderers.js","names":[],"sources":["../../../../src/lib/utils/renderers.ts"],"sourcesContent":["export const ssrRenderer = `\nimport { eventHandler, getResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const html = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: event.node.res,\n });\n\n return html;\n});`;\n\nexport const ssrStreamRenderer: string = createSsrStreamRenderer();\n\nexport function createSsrStreamRenderer(prerender = false): string {\n return `\nimport { eventHandler, getResponseHeader, setResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const noStreaming = ${prerender} || getResponseHeader(event, 'x-analog-no-streaming') === 'true';\n const abort = new AbortController();\n const response = event.node.res;\n const cleanup = () => {\n response.removeListener('close', disconnected);\n response.removeListener('finish', cleanup);\n };\n const disconnected = () => {\n cleanup();\n if (!response.writableEnded) abort.abort();\n };\n response.once('close', disconnected);\n response.once('finish', cleanup);\n\n let stream;\n try {\n stream = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: response,\n streaming: !noStreaming,\n signal: abort.signal,\n renderErrorsAsHtml: true,\n });\n } catch (error) {\n cleanup();\n throw error;\n }\n\n setResponseHeader(event, 'content-type', 'text/html;charset=utf-8');\n\n // A \\`streaming: false\\` route rule sets this header; renderStream then emits\n // the buffered render() output as a single chunk. Collect it into a string so\n // the response is a normal buffered document (content-length), not chunked.\n if (noStreaming) {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let html = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n html += decoder.decode(value, { stream: true });\n }\n html += decoder.decode();\n return html;\n }\n\n setResponseHeader(event, 'content-encoding', 'identity');\n setResponseHeader(event, 'cache-control', 'no-store, no-transform');\n return stream;\n});`;\n}\n\nexport const clientRenderer = `\nimport { eventHandler } from 'h3';\n\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async () => {\n return template;\n});\n`;\n"],"mappings":";AAAA,IAAa,cAAc;;;;;;;;;;;;;;;;;;;;;AAsB3B,IAAa,oBAA4B,wBAAwB;AAEjE,SAAgB,wBAAwB,YAAY,OAAe;CACjE,OAAO;;;;;;;;;;;;;;wBAce,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDlC;AAEA,IAAa,iBAAiB"}
@@ -54,6 +54,6 @@ export default createServerFnEventHandler(
54
54
  `;
55
55
  }
56
56
  //#endregion
57
- export { SERVER_FN_DISPATCH_PREFIX, SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
57
+ export { SERVER_FN_DISPATCH_PREFIX, SERVER_FN_DISPATCH_ROUTE, SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
58
58
 
59
59
  //# sourceMappingURL=server-fn-endpoints.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/utils/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\nimport type { ServerFnHandlerModule } from './get-server-fn-handlers';\n\n/**\n * Nitro virtual-module id for the generated server-function dispatch handler.\n * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.\n */\nexport const SERVER_FN_DISPATCH_VIRTUAL = '#ANALOG_SERVER_FN_DISPATCH';\n\n/** The single transport route all server functions dispatch through. */\nexport const SERVER_FN_DISPATCH_ROUTE = '/_analog/fn/:id';\n\n/** URL prefix of that route, for matching requests before the id is known. */\nexport const SERVER_FN_DISPATCH_PREFIX = '/_analog/fn/';\n\n/**\n * The Nitro handler registration for the server-function dispatch route.\n * Unlike page endpoints (one handler per file), every server function shares\n * this one `/_analog/fn/:id` route; the id selects the function at runtime.\n *\n * The route is fixed and NOT `/api`-prefixed: client proxies always call the\n * absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)\n * would leave the handler unreachable in apps that have an API directory.\n */\nexport function getServerFnDispatchHandler(): NitroEventHandler {\n return {\n route: SERVER_FN_DISPATCH_ROUTE,\n handler: SERVER_FN_DISPATCH_VIRTUAL,\n lazy: true,\n };\n}\n\nexport type BuildServerFnDispatchModuleArgs = {\n /** Discovered `*.server.ts` modules, imported for registration side-effects. */\n modules: ServerFnHandlerModule[];\n /**\n * Absolute path to the app's server config module (`app.config.server.ts`),\n * which exports the `ApplicationConfig` (as `config`) that `main.server.ts`\n * renders with. Handlers bootstrap against it, so they see the same DI the\n * app configured. When absent, handlers run with only `providedIn: 'root'`.\n */\n appConfigModule?: string;\n};\n\n/**\n * Generates the source of the Nitro dispatch handler.\n *\n * The handler imports every discovered `*.server.ts` module so each\n * `serverFn(...)` registers itself, imports the app's server config, then on\n * each request looks up the function by id and runs it via `dispatchServerFn` —\n * the same call path the validation harnesses exercise.\n */\nexport function buildServerFnDispatchModule({\n modules,\n appConfigModule,\n}: BuildServerFnDispatchModuleArgs): string {\n const registrationImports = modules\n .map((m) => `import ${JSON.stringify(normalizePath(m.file))};`)\n .join('\\n');\n\n // Bootstrap against the app's own server config so a handler resolves exactly\n // the services, tokens, and interceptors the app configured — one config, no\n // second provider list. Fall back to an empty config when the app has none.\n const appConfig = appConfigModule\n ? `import { config as serverFnAppConfig } from ${JSON.stringify(\n normalizePath(appConfigModule),\n )};`\n : `const serverFnAppConfig = { providers: [] };`;\n\n // `@analogjs/router/server` is a partially-compiled Angular library, and this\n // module is bundled by Nitro rather than by the app's Angular pipeline, so the\n // linker never runs over it. Loading the compiler gives it the JIT fallback.\n // `zone.js` and the server platform init match the SSR entry, so bootstrapping\n // the app injector below runs in the same environment a render would.\n //\n // The transport itself — id decoding, the malformed-body contract, dispatch,\n // and response writing — lives in `createServerFnEventHandler`, so this module\n // is only wiring: bootstrap the app injector from the app's server config, and\n // hand it to that handler.\n return `import '@angular/compiler';\nimport 'zone.js/node';\nimport '@angular/platform-server/init';\nimport { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';\n\n// Discovered server-function modules (registration side-effects).\n${registrationImports}\n\n${appConfig}\n\n// Bootstrapped once from the app's own server config, so a handler resolves the\n// same DI as an SSR render (\\`providedIn: 'root'\\` and listed providers alike).\n// No component is bootstrapped, so nothing renders and the router never\n// navigates. Only REQUEST/RESPONSE are rebuilt per call.\nexport default createServerFnEventHandler(\n createServerFnAppInjector(serverFnAppConfig),\n);\n`;\n}\n"],"mappings":";;;;;;AASA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;AAGxC,IAAa,4BAA4B;;;;;;;;;;AAWzC,SAAgB,6BAAgD;AAC9D,QAAO;EACL,OAAO;EACP,SAAS;EACT,MAAM;EACP;;;;;;;;;;AAuBH,SAAgB,4BAA4B,EAC1C,SACA,mBAC0C;AAwB1C,QAAO;;;;;;EAvBqB,QACzB,KAAK,MAAM,UAAU,KAAK,UAAU,cAAc,EAAE,KAAK,CAAC,CAAC,GAAG,CAC9D,KAAK,KAAK,CA2BO;;EAtBF,kBACd,+CAA+C,KAAK,UAClD,cAAc,gBAAgB,CAC/B,CAAC,KACF,+CAoBM"}
1
+ {"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/utils/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\nimport type { ServerFnHandlerModule } from './get-server-fn-handlers';\n\n/**\n * Nitro virtual-module id for the generated server-function dispatch handler.\n * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.\n */\nexport const SERVER_FN_DISPATCH_VIRTUAL = '#ANALOG_SERVER_FN_DISPATCH';\n\n/** The single transport route all server functions dispatch through. */\nexport const SERVER_FN_DISPATCH_ROUTE = '/_analog/fn/:id';\n\n/** URL prefix of that route, for matching requests before the id is known. */\nexport const SERVER_FN_DISPATCH_PREFIX = '/_analog/fn/';\n\n/**\n * The Nitro handler registration for the server-function dispatch route.\n * Unlike page endpoints (one handler per file), every server function shares\n * this one `/_analog/fn/:id` route; the id selects the function at runtime.\n *\n * The route is fixed and NOT `/api`-prefixed: client proxies always call the\n * absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)\n * would leave the handler unreachable in apps that have an API directory.\n */\nexport function getServerFnDispatchHandler(): NitroEventHandler {\n return {\n route: SERVER_FN_DISPATCH_ROUTE,\n handler: SERVER_FN_DISPATCH_VIRTUAL,\n lazy: true,\n };\n}\n\nexport type BuildServerFnDispatchModuleArgs = {\n /** Discovered `*.server.ts` modules, imported for registration side-effects. */\n modules: ServerFnHandlerModule[];\n /**\n * Absolute path to the app's server config module (`app.config.server.ts`),\n * which exports the `ApplicationConfig` (as `config`) that `main.server.ts`\n * renders with. Handlers bootstrap against it, so they see the same DI the\n * app configured. When absent, handlers run with only `providedIn: 'root'`.\n */\n appConfigModule?: string;\n};\n\n/**\n * Generates the source of the Nitro dispatch handler.\n *\n * The handler imports every discovered `*.server.ts` module so each\n * `serverFn(...)` registers itself, imports the app's server config, then on\n * each request looks up the function by id and runs it via `dispatchServerFn` —\n * the same call path the validation harnesses exercise.\n */\nexport function buildServerFnDispatchModule({\n modules,\n appConfigModule,\n}: BuildServerFnDispatchModuleArgs): string {\n const registrationImports = modules\n .map((m) => `import ${JSON.stringify(normalizePath(m.file))};`)\n .join('\\n');\n\n // Bootstrap against the app's own server config so a handler resolves exactly\n // the services, tokens, and interceptors the app configured — one config, no\n // second provider list. Fall back to an empty config when the app has none.\n const appConfig = appConfigModule\n ? `import { config as serverFnAppConfig } from ${JSON.stringify(\n normalizePath(appConfigModule),\n )};`\n : `const serverFnAppConfig = { providers: [] };`;\n\n // `@analogjs/router/server` is a partially-compiled Angular library, and this\n // module is bundled by Nitro rather than by the app's Angular pipeline, so the\n // linker never runs over it. Loading the compiler gives it the JIT fallback.\n // `zone.js` and the server platform init match the SSR entry, so bootstrapping\n // the app injector below runs in the same environment a render would.\n //\n // The transport itself — id decoding, the malformed-body contract, dispatch,\n // and response writing — lives in `createServerFnEventHandler`, so this module\n // is only wiring: bootstrap the app injector from the app's server config, and\n // hand it to that handler.\n return `import '@angular/compiler';\nimport 'zone.js/node';\nimport '@angular/platform-server/init';\nimport { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';\n\n// Discovered server-function modules (registration side-effects).\n${registrationImports}\n\n${appConfig}\n\n// Bootstrapped once from the app's own server config, so a handler resolves the\n// same DI as an SSR render (\\`providedIn: 'root'\\` and listed providers alike).\n// No component is bootstrapped, so nothing renders and the router never\n// navigates. Only REQUEST/RESPONSE are rebuilt per call.\nexport default createServerFnEventHandler(\n createServerFnAppInjector(serverFnAppConfig),\n);\n`;\n}\n"],"mappings":";;;;;;AASA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;AAGxC,IAAa,4BAA4B;;;;;;;;;;AAWzC,SAAgB,6BAAgD;CAC9D,OAAO;EACL,OAAO;EACP,SAAS;EACT,MAAM;CACR;AACF;;;;;;;;;AAsBA,SAAgB,4BAA4B,EAC1C,SACA,mBAC0C;CAwB1C,OAAO;;;;;;EAvBqB,QACzB,KAAK,MAAM,UAAU,KAAK,UAAU,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAC9D,KAAK,IA2BR,EAAoB;;EAtBF,kBACd,+CAA+C,KAAK,UAClD,cAAc,eAAe,CAC/B,EAAE,KACF,+CAoBM;;;;;;;;;;AAUZ"}
@@ -22,7 +22,8 @@ import { existsSync, readFileSync } from "node:fs";
22
22
  var isWindows = platform() === "win32";
23
23
  var filePrefix = isWindows ? "file:///" : "";
24
24
  var clientOutputPath = "";
25
- dirname(fileURLToPath(import.meta.url));
25
+ var __filename = fileURLToPath(import.meta.url);
26
+ dirname(__filename);
26
27
  function nitro(pluginOptions = {}) {
27
28
  const { analog, static: isStatic, ...pluginNitroOptions } = pluginOptions;
28
29
  const nitroOptions = withAnalogRouteRuleHeaders(pluginNitroOptions);
@@ -1 +1 @@
1
- {"version":3,"file":"vite-plugin-nitro.js","names":[],"sources":["../../../src/lib/vite-plugin-nitro.ts"],"sourcesContent":["import {\n NitroConfig,\n build,\n createDevServer,\n createNitro,\n loadOptions,\n} from 'nitropack';\nimport { App, toNodeListener } from 'h3';\nimport type { Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { mergeConfig, normalizePath } from 'vite';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { platform } from 'node:os';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { buildServer } from './build-server.js';\nimport { buildSSRApp } from './build-ssr.js';\nimport {\n I18N_WORKER_SSR_ENTRY,\n i18nWorkerSsrEntry,\n resolveI18nWorkers,\n} from './utils/i18n-workers.js';\nimport {\n Options,\n PrerenderContentDir,\n PrerenderContentFile,\n PrerenderRouteConfig,\n PrerenderSitemapConfig,\n} from './options.js';\nimport { pageEndpointsPlugin } from './plugins/page-endpoints.js';\nimport { serverFnIdPlugin } from './plugins/server-fn-id-plugin.js';\nimport { getPageHandlers } from './utils/get-page-handlers.js';\nimport { getServerFnHandlers } from './utils/get-server-fn-handlers.js';\nimport {\n buildServerFnDispatchModule,\n getServerFnDispatchHandler,\n SERVER_FN_DISPATCH_PREFIX,\n SERVER_FN_DISPATCH_VIRTUAL,\n} from './utils/server-fn-endpoints.js';\nimport { buildSitemap } from './build-sitemap.js';\nimport { devServerPlugin } from './plugins/dev-server-plugin.js';\nimport { getMatchingContentFilesWithFrontMatter } from './utils/get-content-files.js';\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n ssrRenderer,\n ssrStreamRenderer,\n clientRenderer,\n} from './utils/renderers.js';\nimport {\n expandRoutesWithLocales,\n createI18nPostRenderingHook,\n} from './utils/i18n-prerender.js';\n\nconst isWindows = platform() === 'win32';\nconst filePrefix = isWindows ? 'file:///' : '';\nlet clientOutputPath = '';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nexport interface NitroPluginOptions extends NitroConfig {\n /**\n * Analog options for apps that don't use `analog()` from\n * `@analogjs/platform`. They override the options passed to `analog()`.\n */\n analog?: Options;\n}\n\nexport function nitro(pluginOptions: NitroPluginOptions = {}): Plugin[] {\n // Nitro's `static` means the same as Analog's: prerender without a server.\n const { analog, static: isStatic, ...pluginNitroOptions } = pluginOptions;\n const nitroOptions = withAnalogRouteRuleHeaders(pluginNitroOptions);\n let options: Options | undefined;\n let workspaceRoot = process.cwd();\n let sourceRoot = 'src';\n let isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const baseURL = process.env['NITRO_APP_BASE_URL'] || '';\n const prefix = baseURL ? baseURL.substring(0, baseURL.length - 1) : '';\n let apiPrefix = '/api';\n\n let i18nWorkers = false;\n let isBuild = false;\n let isServe = false;\n let ssrBuild = false;\n let config: UserConfig;\n let nitroConfig: NitroConfig;\n let environmentBuild = false;\n let hasServerFns = false;\n const routeSitemaps: Record<\n string,\n PrerenderSitemapConfig | (() => PrerenderSitemapConfig)\n > = {};\n const routeSourceFiles: Record<string, string> = {};\n let rootDir = workspaceRoot;\n\n // Options passed to `analog()` are the defaults, so an Analog app configures\n // SSR, prerendering and API routes in one place.\n function resolveOptions(userConfig: UserConfig) {\n options = {\n ...getAnalogOptions(userConfig),\n ...(isStatic === undefined ? {} : { static: isStatic }),\n ...analog,\n };\n workspaceRoot = options.workspaceRoot ?? process.cwd();\n sourceRoot = options.sourceRoot ?? 'src';\n apiPrefix = `/${options.apiPrefix || 'api'}`;\n }\n\n return [\n {\n name: '@analogjs/vite-plugin-nitro',\n async config(userConfig, { mode, command }) {\n resolveOptions(userConfig);\n isServe = command === 'serve';\n isBuild = command === 'build';\n ssrBuild = userConfig.build?.ssr === true;\n config = userConfig;\n isTest = isTest ? isTest : mode === 'test';\n\n rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const buildPreset =\n process.env['BUILD_PRESET'] ??\n (nitroOptions?.preset as string | undefined);\n\n const pageHandlers = getPageHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs: options?.additionalPagesDirs,\n apiPrefix,\n });\n\n // Server functions: discover every `*.server.ts` module, then register a\n // single `/_analog/fn/:id` dispatch handler backed by a generated Nitro\n // virtual module that imports those modules (registration side-effects)\n // and the app provider set. Only wired when server functions exist.\n const serverFnModules = getServerFnHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalServerFnDirs: options?.additionalServerFnDirs,\n });\n const serverFnAppConfigModule = resolveServerFnAppConfigModule(\n workspaceRoot,\n rootDir,\n sourceRoot,\n );\n hasServerFns = serverFnModules.length > 0;\n const serverFnHandlers = hasServerFns\n ? [getServerFnDispatchHandler()]\n : [];\n const serverFnVirtual =\n serverFnModules.length > 0\n ? {\n [SERVER_FN_DISPATCH_VIRTUAL]: buildServerFnDispatchModule({\n modules: serverFnModules,\n appConfigModule: serverFnAppConfigModule,\n }),\n }\n : {};\n\n nitroConfig = {\n rootDir,\n preset: buildPreset,\n compatibilityDate: '2024-11-19',\n logLevel: nitroOptions?.logLevel || 0,\n srcDir: normalizePath(`${sourceRoot}/server`),\n scanDirs: [\n normalizePath(`${rootDir}/${sourceRoot}/server`),\n ...(options?.additionalAPIDirs || []).map((dir) =>\n normalizePath(`${workspaceRoot}${dir}`),\n ),\n ],\n output: {\n dir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, 'analog'),\n ),\n publicDir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, 'analog/public'),\n ),\n },\n buildDir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, '.nitro'),\n ),\n typescript: {\n generateTsConfig: false,\n },\n runtimeConfig: {\n apiPrefix: apiPrefix.substring(1),\n prefix,\n },\n // Fixes support for Rolldown\n imports: {\n autoImport: false,\n },\n // The dispatch module's imports are all bare side-effect imports —\n // the JIT compiler it needs, and each `*.server.ts` whose import is\n // what registers its functions. Nitro treeshakes those away unless\n // the modules are declared side-effectful, which would leave every\n // call 404ing against an empty registry.\n ...(hasServerFns\n ? {\n moduleSideEffects: [\n '@angular/compiler',\n ...serverFnModules.map((m) => normalizePath(m.file)),\n ],\n }\n : {}),\n rollupConfig: {\n onwarn(warning) {\n if (\n warning.message.includes('empty chunk') &&\n warning.message.endsWith('.server')\n ) {\n return;\n }\n },\n plugins: [\n pageEndpointsPlugin(),\n serverFnIdPlugin(normalizePath(resolve(workspaceRoot, rootDir))),\n ],\n },\n handlers: [...pageHandlers, ...serverFnHandlers],\n virtual: {\n '#ANALOG_SSR_RENDERER': options?.experimental?.streaming\n ? ssrStreamRenderer\n : ssrRenderer,\n '#ANALOG_CLIENT_RENDERER': clientRenderer,\n ...serverFnVirtual,\n },\n };\n\n if (isVercelPreset(buildPreset)) {\n nitroConfig = withVercelOutputAPI(nitroConfig, workspaceRoot);\n }\n\n if (isCloudflarePreset(buildPreset)) {\n nitroConfig = withCloudflareOutput(nitroConfig);\n }\n\n if (\n isNetlifyPreset(buildPreset) &&\n rootDir === '.' &&\n !existsSync(resolve(workspaceRoot, 'netlify.toml'))\n ) {\n nitroConfig = withNetlifyOutputAPI(nitroConfig, workspaceRoot);\n }\n\n if (isFirebaseAppHosting()) {\n nitroConfig = withAppHostingOutput(nitroConfig);\n }\n\n if (!ssrBuild && !isTest) {\n // store the client output path for the SSR build config\n clientOutputPath = resolve(\n workspaceRoot,\n rootDir,\n config.build?.outDir || 'dist/client',\n );\n }\n\n const indexEntry = normalizePath(\n resolve(clientOutputPath, 'index.html'),\n );\n nitroConfig.alias = {\n '#analog/index': indexEntry,\n };\n\n if (isBuild) {\n nitroConfig.publicAssets = [{ dir: clientOutputPath }];\n nitroConfig.renderer = options?.ssr\n ? '#ANALOG_SSR_RENDERER'\n : '#ANALOG_CLIENT_RENDERER';\n\n if (isEmptyPrerenderRoutes(options)) {\n nitroConfig.prerender = {};\n nitroConfig.prerender.routes = ['/'];\n }\n\n if (options?.prerender) {\n nitroConfig.prerender = nitroConfig.prerender ?? {};\n nitroConfig.prerender.crawlLinks = options?.prerender?.discover;\n\n let routes: (\n | string\n | PrerenderContentDir\n | PrerenderRouteConfig\n | undefined\n )[] = [];\n\n const prerenderRoutes = options?.prerender?.routes;\n if (\n isArrayWithElements<string | PrerenderContentDir>(prerenderRoutes)\n ) {\n routes = prerenderRoutes;\n } else if (typeof prerenderRoutes === 'function') {\n routes = await prerenderRoutes();\n }\n\n nitroConfig.prerender.routes = routes.reduce<string[]>(\n (prev, current) => {\n if (!current) {\n return prev;\n }\n if (typeof current === 'string') {\n prev.push(current);\n return prev;\n }\n\n if ('route' in current) {\n if (current.sitemap) {\n routeSitemaps[current.route] = current.sitemap;\n }\n\n if (current.outputSourceFile) {\n const sourcePath = resolve(\n workspaceRoot,\n rootDir,\n current.outputSourceFile,\n );\n routeSourceFiles[current.route] = readFileSync(\n sourcePath,\n 'utf8',\n );\n }\n\n prev.push(current.route);\n\n // Add the server-side data fetching endpoint URL\n if ('staticData' in current) {\n prev.push(`${apiPrefix}/_analog/pages/${current.route}`);\n }\n\n return prev;\n }\n\n const affectedFiles: PrerenderContentFile[] =\n getMatchingContentFilesWithFrontMatter(\n workspaceRoot,\n rootDir,\n current.contentDir,\n current.recursive,\n );\n\n affectedFiles.forEach((f) => {\n const result = current.transform(f);\n\n if (result) {\n if (current.sitemap) {\n routeSitemaps[result] =\n current.sitemap && typeof current.sitemap === 'function'\n ? current.sitemap?.(f)\n : current.sitemap;\n }\n\n if (current.outputSourceFile) {\n const sourceContent = current.outputSourceFile(f);\n if (sourceContent) {\n routeSourceFiles[result] = sourceContent;\n }\n }\n\n prev.push(result);\n\n // Add the server-side data fetching endpoint URL\n if ('staticData' in current) {\n prev.push(`${apiPrefix}/_analog/pages/${result}`);\n }\n }\n });\n\n return prev;\n },\n [],\n );\n\n // Expand routes with locale prefixes when i18n is configured\n if (options?.i18n && nitroConfig.prerender?.routes) {\n nitroConfig.prerender.routes = expandRoutesWithLocales(\n nitroConfig.prerender.routes.filter(Boolean) as string[],\n options.i18n,\n );\n }\n }\n\n // Register i18n post-rendering hook for lang attribute injection\n if (options?.i18n) {\n options.prerender = options.prerender ?? {};\n options.prerender.postRenderingHooks =\n options.prerender.postRenderingHooks ?? [];\n options.prerender.postRenderingHooks.push(\n createI18nPostRenderingHook(options.i18n),\n );\n }\n\n if (ssrBuild) {\n if (isWindows) {\n nitroConfig.externals = {\n inline: ['std-env'],\n };\n }\n\n nitroConfig = {\n ...nitroConfig,\n externals: {\n ...nitroConfig.externals,\n external: ['rxjs', 'node-fetch-native/dist/polyfill'],\n },\n moduleSideEffects: [\n 'zone.js/node',\n 'zone.js/fesm2015/zone-node',\n ...(nitroConfig.moduleSideEffects ?? []),\n ],\n handlers: [...pageHandlers, ...serverFnHandlers],\n };\n }\n }\n\n nitroConfig = mergeConfig(\n nitroConfig,\n nitroOptions as Record<string, any>,\n );\n\n i18nWorkers = false;\n if (\n isBuild &&\n options?.i18n &&\n options.i18n.workers !== false &&\n (options.i18n.loader || options.i18n.workers === true)\n ) {\n const resolvedNitro = await loadOptions({\n dev: false,\n preset: process.env['BUILD_PRESET'],\n ...nitroConfig,\n });\n i18nWorkers = resolveI18nWorkers(options, resolvedNitro);\n nitroConfig.preset = resolvedNitro.preset;\n }\n\n return {\n define: {\n ANALOG_I18N_FIXED_LOCALE: i18nWorkers\n ? 'globalThis.process.env.ANALOG_I18N_LOCALE'\n : 'undefined',\n },\n environments: {\n client: {\n build: {\n outDir:\n config?.build?.outDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'client'),\n },\n },\n ssr: {\n consumer: 'server',\n build: {\n ssr: true,\n rollupOptions: {\n input: i18nWorkers\n ? { 'main.server': I18N_WORKER_SSR_ENTRY }\n : options?.entryServer ||\n resolve(\n workspaceRoot,\n rootDir,\n `${sourceRoot}/main.server.ts`,\n ),\n },\n outDir:\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n },\n },\n },\n builder: {\n sharedPlugins: true,\n buildApp: async (builder) => {\n environmentBuild = true;\n const builds = [builder.build(builder.environments['client'])];\n\n if (options?.ssr || nitroConfig.prerender?.routes?.length) {\n builds.push(builder.build(builder.environments['ssr']));\n }\n\n await Promise.all(builds);\n\n let ssrEntryPath = resolve(\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, `ssr`),\n `main.server${filePrefix ? '.js' : ''}`,\n );\n\n // add check for main.server.mjs fallback on Windows\n if (isWindows && !existsSync(ssrEntryPath)) {\n ssrEntryPath = ssrEntryPath.replace('.js', '.mjs');\n }\n\n const ssrEntry = normalizePath(filePrefix + ssrEntryPath);\n\n nitroConfig.alias = {\n ...nitroConfig.alias,\n '#analog/ssr': ssrEntry,\n };\n\n await buildServer(\n options,\n nitroConfig,\n routeSourceFiles,\n i18nWorkers,\n );\n\n if (\n nitroConfig.prerender?.routes?.length &&\n options?.prerender?.sitemap\n ) {\n const publicDir = nitroConfig.output?.publicDir;\n if (!publicDir) {\n throw new Error(\n 'Nitro public output directory is required to build the sitemap.',\n );\n }\n\n console.log('Building Sitemap...');\n // sitemap needs to be built after all directories are built\n await buildSitemap(\n config,\n options.prerender.sitemap,\n nitroConfig.prerender.routes,\n publicDir,\n routeSitemaps,\n options.i18n,\n );\n }\n\n console.log(\n `\\n\\nThe '@analogjs/platform' server has been successfully built.`,\n );\n },\n },\n };\n },\n async configureServer(viteServer: ViteDevServer) {\n if (isServe && !isTest) {\n const nitro = await createNitro({\n dev: true,\n ...nitroConfig,\n });\n const server = createDevServer(nitro);\n await build(nitro);\n const apiHandler = toNodeListener(server.app as unknown as App);\n\n // Server functions dispatch through `/_analog/fn/:id`, outside the\n // API prefix the Nitro dev server is mounted under, so route them\n // explicitly — otherwise a call falls through to the SSR catch-all\n // and the client gets HTML back instead of its result.\n if (hasServerFns) {\n viteServer.middlewares.use(\n (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => {\n if (req.url?.startsWith(SERVER_FN_DISPATCH_PREFIX)) {\n apiHandler(req, res);\n return;\n }\n\n next();\n },\n );\n }\n\n viteServer.middlewares.use(\n (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => {\n if (req.url?.startsWith(`${prefix}${apiPrefix}`)) {\n apiHandler(req, res);\n return;\n }\n\n next();\n },\n );\n\n // handle upgrades if websockets are enabled\n if (nitroOptions?.experimental?.websocket) {\n viteServer.httpServer?.on('upgrade', server.upgrade);\n }\n\n console.log(\n `\\n\\nThe server endpoints are accessible under the \"${prefix}${apiPrefix}\" path.`,\n );\n }\n },\n\n async closeBundle() {\n // Skip when build is triggered by the Environment API\n if (environmentBuild) {\n return;\n }\n\n if (ssrBuild) {\n return;\n }\n\n if (isBuild) {\n if (options?.ssr) {\n console.log('Building SSR application...');\n await buildSSRApp(config, options, i18nWorkers);\n }\n\n if (\n nitroConfig.prerender?.routes?.length &&\n options?.prerender?.sitemap\n ) {\n console.log('Building Sitemap...');\n // sitemap needs to be built after all directories are built\n await buildSitemap(\n config,\n options.prerender.sitemap,\n nitroConfig.prerender.routes,\n clientOutputPath,\n routeSitemaps,\n options.i18n,\n );\n }\n\n let ssrEntryPath = resolve(\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, `ssr`),\n `main.server${filePrefix ? '.js' : ''}`,\n );\n\n // add check for main.server.mjs fallback on Windows\n if (isWindows && !existsSync(ssrEntryPath)) {\n ssrEntryPath = ssrEntryPath.replace('.js', '.mjs');\n }\n\n const ssrEntry = normalizePath(filePrefix + ssrEntryPath);\n\n nitroConfig.alias = {\n ...nitroConfig.alias,\n '#analog/ssr': ssrEntry,\n };\n\n await buildServer(\n options,\n nitroConfig,\n routeSourceFiles,\n i18nWorkers,\n );\n\n console.log(\n `\\n\\nThe '@analogjs/platform' server has been successfully built.`,\n );\n }\n },\n },\n {\n name: 'analog-i18n-worker-entry',\n apply: 'build' as const,\n resolveId(id: string) {\n return id === I18N_WORKER_SSR_ENTRY && options?.i18n?.loader\n ? '\\0' + id\n : undefined;\n },\n load(id: string) {\n if (id !== '\\0' + I18N_WORKER_SSR_ENTRY || !options?.i18n?.loader)\n return;\n return i18nWorkerSsrEntry(\n normalizePath(\n resolve(\n workspaceRoot,\n rootDir,\n options.entryServer || `${sourceRoot}/main.server.ts`,\n ),\n ),\n normalizePath(resolve(workspaceRoot, rootDir, options.i18n.loader)),\n options.i18n,\n );\n },\n },\n devServerPlugin(() => ({\n ...options,\n routeRules: nitroOptions?.routeRules,\n })),\n {\n name: '@analogjs/vite-plugin-nitro-api-prefix',\n config() {\n return {\n define: {\n ANALOG_API_PREFIX: `\"${baseURL.substring(1)}${apiPrefix.substring(1)}\"`,\n ...(options?.i18n\n ? {\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(\n options.i18n.defaultLocale,\n ),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n }\n : {}),\n },\n };\n },\n },\n ];\n}\n\nfunction isEmptyPrerenderRoutes(options?: Options): boolean {\n if (!options || isArrayWithElements(options?.prerender?.routes)) {\n return false;\n }\n return !options.prerender?.routes;\n}\n\nfunction isArrayWithElements<T>(arr: unknown): arr is [T, ...T[]] {\n return !!(Array.isArray(arr) && arr.length);\n}\n\nconst isVercelPreset = (buildPreset: string | undefined) =>\n process.env['VERCEL'] ||\n (buildPreset && buildPreset.toLowerCase().includes('vercel'));\n\nconst withVercelOutputAPI = (\n nitroConfig: NitroConfig | undefined,\n workspaceRoot: string,\n) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n dir: normalizePath(resolve(workspaceRoot, '.vercel', 'output')),\n publicDir: normalizePath(\n resolve(workspaceRoot, '.vercel', 'output/static'),\n ),\n },\n});\n\nconst isCloudflarePreset = (buildPreset: string | undefined) =>\n process.env['CF_PAGES'] ||\n (buildPreset && buildPreset.toLowerCase().includes('cloudflare-pages'));\n\nconst withCloudflareOutput = (nitroConfig: NitroConfig | undefined) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n serverDir: '{{ output.publicDir }}/_worker.js',\n },\n});\n\nconst isFirebaseAppHosting = () => !!process.env['NG_BUILD_LOGS_JSON'];\nconst withAppHostingOutput = (nitroConfig: NitroConfig) => {\n let hasOutput = false;\n\n return <NitroConfig>{\n ...nitroConfig,\n serveStatic: true,\n rollupConfig: {\n ...nitroConfig.rollupConfig,\n output: {\n ...nitroConfig.rollupConfig?.output,\n entryFileNames: 'server.mjs',\n },\n },\n hooks: {\n ...nitroConfig.hooks,\n compiled: () => {\n if (!hasOutput) {\n const buildOutput = {\n errors: [],\n warnings: [],\n outputPaths: {\n root: pathToFileURL(`${nitroConfig.output?.dir}`),\n browser: pathToFileURL(`${nitroConfig.output?.publicDir}`),\n server: pathToFileURL(`${nitroConfig.output?.dir}/server`),\n },\n };\n\n // Log the build output for Firebase App Hosting to pick up\n console.log(JSON.stringify(buildOutput, null, 2));\n hasOutput = true;\n }\n },\n },\n };\n};\n\nfunction resolveServerFnAppConfigModule(\n workspaceRoot: string,\n rootDir: string,\n sourceRoot: string,\n): string | undefined {\n // The app's server config (the one `main.server.ts` renders with), exporting\n // `config`. Server-function handlers bootstrap against it, so they resolve the\n // same DI as SSR with no separate provider list to maintain.\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n const candidates = [\n `${root}/${sourceRoot}/app/app.config.server.ts`,\n `${root}/${sourceRoot}/app.config.server.ts`,\n ];\n return candidates.find((candidate) => existsSync(candidate));\n}\n\nconst isNetlifyPreset = (buildPreset: string | undefined) =>\n process.env['NETLIFY'] ||\n (buildPreset && buildPreset.toLowerCase().includes('netlify'));\n\nconst withNetlifyOutputAPI = (\n nitroConfig: NitroConfig | undefined,\n workspaceRoot: string,\n) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n dir: normalizePath(resolve(workspaceRoot, 'netlify/functions')),\n },\n});\n\n/**\n * Reads the options passed to `analog()` from `@analogjs/platform`, which\n * exposes them on its plugin `api`.\n */\nfunction getAnalogOptions(userConfig: UserConfig): Options | undefined {\n const plugins = ((userConfig.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { api?: { analogOptions?: Options } }\n | null\n | undefined\n )[];\n return plugins.find((plugin) => plugin?.api?.analogOptions)?.api\n ?.analogOptions;\n}\n\n/**\n * Stamps `ssr: false` and `streaming: false` route rules as response headers,\n * which the renderers read to skip SSR or streaming for matching routes.\n */\nfunction withAnalogRouteRuleHeaders(nitroOptions: NitroConfig): NitroConfig {\n if (!nitroOptions.routeRules) {\n return nitroOptions;\n }\n\n const routeRules = Object.fromEntries(\n Object.entries(nitroOptions.routeRules).map(([route, rule]) => [\n route,\n {\n ...rule,\n headers: {\n ...rule.headers,\n ...(rule.ssr === false ? { 'x-analog-no-ssr': 'true' } : {}),\n ...(rule.streaming === false\n ? { 'x-analog-no-streaming': 'true' }\n : {}),\n },\n },\n ]),\n );\n\n return { ...nitroOptions, routeRules };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqDA,IAAM,YAAY,UAAU,KAAK;AACjC,IAAM,aAAa,YAAY,aAAa;AAC5C,IAAI,mBAAmB;AAGL,QADC,cAAc,OAAO,KAAK,IAAI,CACZ;AAUrC,SAAgB,MAAM,gBAAoC,EAAE,EAAY;CAEtE,MAAM,EAAE,QAAQ,QAAQ,UAAU,GAAG,uBAAuB;CAC5D,MAAM,eAAe,2BAA2B,mBAAmB;CACnE,IAAI;CACJ,IAAI,gBAAgB,QAAQ,KAAK;CACjC,IAAI,aAAa;CACjB,IAAI,SAAA,QAAA,IAAA,aAAqC,UAAU,CAAC,CAAC,QAAQ,IAAI;CACjE,MAAM,UAAU,QAAQ,IAAI,yBAAyB;CACrD,MAAM,SAAS,UAAU,QAAQ,UAAU,GAAG,QAAQ,SAAS,EAAE,GAAG;CACpE,IAAI,YAAY;CAEhB,IAAI,cAAc;CAClB,IAAI,UAAU;CACd,IAAI,UAAU;CACd,IAAI,WAAW;CACf,IAAI;CACJ,IA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H,SAAS;GACP,GAAG,KAAK;GACR,GAAI,KAAK,QAAQ,QAAQ,EAAE,mBAAmB,QAAQ,GAAG,EAAE;GAC3D,GAAI,KAAK,cAAc,QACnB,EAAE,yBAAyB,QAAQ,GACnC,EAAE;GACP;EACF,CACF,CAAC,CACH;AAED,QAAO;EAAE,GAAG;EAAc;EAAY"}
1
+ {"version":3,"file":"vite-plugin-nitro.js","names":[],"sources":["../../../src/lib/vite-plugin-nitro.ts"],"sourcesContent":["import {\n NitroConfig,\n build,\n createDevServer,\n createNitro,\n loadOptions,\n} from 'nitropack';\nimport { App, toNodeListener } from 'h3';\nimport type { Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { mergeConfig, normalizePath } from 'vite';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { platform } from 'node:os';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { buildServer } from './build-server.js';\nimport { buildSSRApp } from './build-ssr.js';\nimport {\n I18N_WORKER_SSR_ENTRY,\n i18nWorkerSsrEntry,\n resolveI18nWorkers,\n} from './utils/i18n-workers.js';\nimport {\n Options,\n PrerenderContentDir,\n PrerenderContentFile,\n PrerenderRouteConfig,\n PrerenderSitemapConfig,\n} from './options.js';\nimport { pageEndpointsPlugin } from './plugins/page-endpoints.js';\nimport { serverFnIdPlugin } from './plugins/server-fn-id-plugin.js';\nimport { getPageHandlers } from './utils/get-page-handlers.js';\nimport { getServerFnHandlers } from './utils/get-server-fn-handlers.js';\nimport {\n buildServerFnDispatchModule,\n getServerFnDispatchHandler,\n SERVER_FN_DISPATCH_PREFIX,\n SERVER_FN_DISPATCH_VIRTUAL,\n} from './utils/server-fn-endpoints.js';\nimport { buildSitemap } from './build-sitemap.js';\nimport { devServerPlugin } from './plugins/dev-server-plugin.js';\nimport { getMatchingContentFilesWithFrontMatter } from './utils/get-content-files.js';\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n ssrRenderer,\n ssrStreamRenderer,\n clientRenderer,\n} from './utils/renderers.js';\nimport {\n expandRoutesWithLocales,\n createI18nPostRenderingHook,\n} from './utils/i18n-prerender.js';\n\nconst isWindows = platform() === 'win32';\nconst filePrefix = isWindows ? 'file:///' : '';\nlet clientOutputPath = '';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nexport interface NitroPluginOptions extends NitroConfig {\n /**\n * Analog options for apps that don't use `analog()` from\n * `@analogjs/platform`. They override the options passed to `analog()`.\n */\n analog?: Options;\n}\n\nexport function nitro(pluginOptions: NitroPluginOptions = {}): Plugin[] {\n // Nitro's `static` means the same as Analog's: prerender without a server.\n const { analog, static: isStatic, ...pluginNitroOptions } = pluginOptions;\n const nitroOptions = withAnalogRouteRuleHeaders(pluginNitroOptions);\n let options: Options | undefined;\n let workspaceRoot = process.cwd();\n let sourceRoot = 'src';\n let isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const baseURL = process.env['NITRO_APP_BASE_URL'] || '';\n const prefix = baseURL ? baseURL.substring(0, baseURL.length - 1) : '';\n let apiPrefix = '/api';\n\n let i18nWorkers = false;\n let isBuild = false;\n let isServe = false;\n let ssrBuild = false;\n let config: UserConfig;\n let nitroConfig: NitroConfig;\n let environmentBuild = false;\n let hasServerFns = false;\n const routeSitemaps: Record<\n string,\n PrerenderSitemapConfig | (() => PrerenderSitemapConfig)\n > = {};\n const routeSourceFiles: Record<string, string> = {};\n let rootDir = workspaceRoot;\n\n // Options passed to `analog()` are the defaults, so an Analog app configures\n // SSR, prerendering and API routes in one place.\n function resolveOptions(userConfig: UserConfig) {\n options = {\n ...getAnalogOptions(userConfig),\n ...(isStatic === undefined ? {} : { static: isStatic }),\n ...analog,\n };\n workspaceRoot = options.workspaceRoot ?? process.cwd();\n sourceRoot = options.sourceRoot ?? 'src';\n apiPrefix = `/${options.apiPrefix || 'api'}`;\n }\n\n return [\n {\n name: '@analogjs/vite-plugin-nitro',\n async config(userConfig, { mode, command }) {\n resolveOptions(userConfig);\n isServe = command === 'serve';\n isBuild = command === 'build';\n ssrBuild = userConfig.build?.ssr === true;\n config = userConfig;\n isTest = isTest ? isTest : mode === 'test';\n\n rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const buildPreset =\n process.env['BUILD_PRESET'] ??\n (nitroOptions?.preset as string | undefined);\n\n const pageHandlers = getPageHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs: options?.additionalPagesDirs,\n apiPrefix,\n });\n\n // Server functions: discover every `*.server.ts` module, then register a\n // single `/_analog/fn/:id` dispatch handler backed by a generated Nitro\n // virtual module that imports those modules (registration side-effects)\n // and the app provider set. Only wired when server functions exist.\n const serverFnModules = getServerFnHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalServerFnDirs: options?.additionalServerFnDirs,\n });\n const serverFnAppConfigModule = resolveServerFnAppConfigModule(\n workspaceRoot,\n rootDir,\n sourceRoot,\n );\n hasServerFns = serverFnModules.length > 0;\n const serverFnHandlers = hasServerFns\n ? [getServerFnDispatchHandler()]\n : [];\n const serverFnVirtual =\n serverFnModules.length > 0\n ? {\n [SERVER_FN_DISPATCH_VIRTUAL]: buildServerFnDispatchModule({\n modules: serverFnModules,\n appConfigModule: serverFnAppConfigModule,\n }),\n }\n : {};\n\n nitroConfig = {\n rootDir,\n preset: buildPreset,\n compatibilityDate: '2024-11-19',\n logLevel: nitroOptions?.logLevel || 0,\n srcDir: normalizePath(`${sourceRoot}/server`),\n scanDirs: [\n normalizePath(`${rootDir}/${sourceRoot}/server`),\n ...(options?.additionalAPIDirs || []).map((dir) =>\n normalizePath(`${workspaceRoot}${dir}`),\n ),\n ],\n output: {\n dir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, 'analog'),\n ),\n publicDir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, 'analog/public'),\n ),\n },\n buildDir: normalizePath(\n resolve(workspaceRoot, 'dist', rootDir, '.nitro'),\n ),\n typescript: {\n generateTsConfig: false,\n },\n runtimeConfig: {\n apiPrefix: apiPrefix.substring(1),\n prefix,\n },\n // Fixes support for Rolldown\n imports: {\n autoImport: false,\n },\n // The dispatch module's imports are all bare side-effect imports —\n // the JIT compiler it needs, and each `*.server.ts` whose import is\n // what registers its functions. Nitro treeshakes those away unless\n // the modules are declared side-effectful, which would leave every\n // call 404ing against an empty registry.\n ...(hasServerFns\n ? {\n moduleSideEffects: [\n '@angular/compiler',\n ...serverFnModules.map((m) => normalizePath(m.file)),\n ],\n }\n : {}),\n rollupConfig: {\n onwarn(warning) {\n if (\n warning.message.includes('empty chunk') &&\n warning.message.endsWith('.server')\n ) {\n return;\n }\n },\n plugins: [\n pageEndpointsPlugin(),\n serverFnIdPlugin(normalizePath(resolve(workspaceRoot, rootDir))),\n ],\n },\n handlers: [...pageHandlers, ...serverFnHandlers],\n virtual: {\n '#ANALOG_SSR_RENDERER': options?.experimental?.streaming\n ? ssrStreamRenderer\n : ssrRenderer,\n '#ANALOG_CLIENT_RENDERER': clientRenderer,\n ...serverFnVirtual,\n },\n };\n\n if (isVercelPreset(buildPreset)) {\n nitroConfig = withVercelOutputAPI(nitroConfig, workspaceRoot);\n }\n\n if (isCloudflarePreset(buildPreset)) {\n nitroConfig = withCloudflareOutput(nitroConfig);\n }\n\n if (\n isNetlifyPreset(buildPreset) &&\n rootDir === '.' &&\n !existsSync(resolve(workspaceRoot, 'netlify.toml'))\n ) {\n nitroConfig = withNetlifyOutputAPI(nitroConfig, workspaceRoot);\n }\n\n if (isFirebaseAppHosting()) {\n nitroConfig = withAppHostingOutput(nitroConfig);\n }\n\n if (!ssrBuild && !isTest) {\n // store the client output path for the SSR build config\n clientOutputPath = resolve(\n workspaceRoot,\n rootDir,\n config.build?.outDir || 'dist/client',\n );\n }\n\n const indexEntry = normalizePath(\n resolve(clientOutputPath, 'index.html'),\n );\n nitroConfig.alias = {\n '#analog/index': indexEntry,\n };\n\n if (isBuild) {\n nitroConfig.publicAssets = [{ dir: clientOutputPath }];\n nitroConfig.renderer = options?.ssr\n ? '#ANALOG_SSR_RENDERER'\n : '#ANALOG_CLIENT_RENDERER';\n\n if (isEmptyPrerenderRoutes(options)) {\n nitroConfig.prerender = {};\n nitroConfig.prerender.routes = ['/'];\n }\n\n if (options?.prerender) {\n nitroConfig.prerender = nitroConfig.prerender ?? {};\n nitroConfig.prerender.crawlLinks = options?.prerender?.discover;\n\n let routes: (\n | string\n | PrerenderContentDir\n | PrerenderRouteConfig\n | undefined\n )[] = [];\n\n const prerenderRoutes = options?.prerender?.routes;\n if (\n isArrayWithElements<string | PrerenderContentDir>(prerenderRoutes)\n ) {\n routes = prerenderRoutes;\n } else if (typeof prerenderRoutes === 'function') {\n routes = await prerenderRoutes();\n }\n\n nitroConfig.prerender.routes = routes.reduce<string[]>(\n (prev, current) => {\n if (!current) {\n return prev;\n }\n if (typeof current === 'string') {\n prev.push(current);\n return prev;\n }\n\n if ('route' in current) {\n if (current.sitemap) {\n routeSitemaps[current.route] = current.sitemap;\n }\n\n if (current.outputSourceFile) {\n const sourcePath = resolve(\n workspaceRoot,\n rootDir,\n current.outputSourceFile,\n );\n routeSourceFiles[current.route] = readFileSync(\n sourcePath,\n 'utf8',\n );\n }\n\n prev.push(current.route);\n\n // Add the server-side data fetching endpoint URL\n if ('staticData' in current) {\n prev.push(`${apiPrefix}/_analog/pages/${current.route}`);\n }\n\n return prev;\n }\n\n const affectedFiles: PrerenderContentFile[] =\n getMatchingContentFilesWithFrontMatter(\n workspaceRoot,\n rootDir,\n current.contentDir,\n current.recursive,\n );\n\n affectedFiles.forEach((f) => {\n const result = current.transform(f);\n\n if (result) {\n if (current.sitemap) {\n routeSitemaps[result] =\n current.sitemap && typeof current.sitemap === 'function'\n ? current.sitemap?.(f)\n : current.sitemap;\n }\n\n if (current.outputSourceFile) {\n const sourceContent = current.outputSourceFile(f);\n if (sourceContent) {\n routeSourceFiles[result] = sourceContent;\n }\n }\n\n prev.push(result);\n\n // Add the server-side data fetching endpoint URL\n if ('staticData' in current) {\n prev.push(`${apiPrefix}/_analog/pages/${result}`);\n }\n }\n });\n\n return prev;\n },\n [],\n );\n\n // Expand routes with locale prefixes when i18n is configured\n if (options?.i18n && nitroConfig.prerender?.routes) {\n nitroConfig.prerender.routes = expandRoutesWithLocales(\n nitroConfig.prerender.routes.filter(Boolean) as string[],\n options.i18n,\n );\n }\n }\n\n // Register i18n post-rendering hook for lang attribute injection\n if (options?.i18n) {\n options.prerender = options.prerender ?? {};\n options.prerender.postRenderingHooks =\n options.prerender.postRenderingHooks ?? [];\n options.prerender.postRenderingHooks.push(\n createI18nPostRenderingHook(options.i18n),\n );\n }\n\n if (ssrBuild) {\n if (isWindows) {\n nitroConfig.externals = {\n inline: ['std-env'],\n };\n }\n\n nitroConfig = {\n ...nitroConfig,\n externals: {\n ...nitroConfig.externals,\n external: ['rxjs', 'node-fetch-native/dist/polyfill'],\n },\n moduleSideEffects: [\n 'zone.js/node',\n 'zone.js/fesm2015/zone-node',\n ...(nitroConfig.moduleSideEffects ?? []),\n ],\n handlers: [...pageHandlers, ...serverFnHandlers],\n };\n }\n }\n\n nitroConfig = mergeConfig(\n nitroConfig,\n nitroOptions as Record<string, any>,\n );\n\n i18nWorkers = false;\n if (\n isBuild &&\n options?.i18n &&\n options.i18n.workers !== false &&\n (options.i18n.loader || options.i18n.workers === true)\n ) {\n const resolvedNitro = await loadOptions({\n dev: false,\n preset: process.env['BUILD_PRESET'],\n ...nitroConfig,\n });\n i18nWorkers = resolveI18nWorkers(options, resolvedNitro);\n nitroConfig.preset = resolvedNitro.preset;\n }\n\n return {\n define: {\n ANALOG_I18N_FIXED_LOCALE: i18nWorkers\n ? 'globalThis.process.env.ANALOG_I18N_LOCALE'\n : 'undefined',\n },\n environments: {\n client: {\n build: {\n outDir:\n config?.build?.outDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'client'),\n },\n },\n ssr: {\n consumer: 'server',\n build: {\n ssr: true,\n rollupOptions: {\n input: i18nWorkers\n ? { 'main.server': I18N_WORKER_SSR_ENTRY }\n : options?.entryServer ||\n resolve(\n workspaceRoot,\n rootDir,\n `${sourceRoot}/main.server.ts`,\n ),\n },\n outDir:\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n },\n },\n },\n builder: {\n sharedPlugins: true,\n buildApp: async (builder) => {\n environmentBuild = true;\n const builds = [builder.build(builder.environments['client'])];\n\n if (options?.ssr || nitroConfig.prerender?.routes?.length) {\n builds.push(builder.build(builder.environments['ssr']));\n }\n\n await Promise.all(builds);\n\n let ssrEntryPath = resolve(\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, `ssr`),\n `main.server${filePrefix ? '.js' : ''}`,\n );\n\n // add check for main.server.mjs fallback on Windows\n if (isWindows && !existsSync(ssrEntryPath)) {\n ssrEntryPath = ssrEntryPath.replace('.js', '.mjs');\n }\n\n const ssrEntry = normalizePath(filePrefix + ssrEntryPath);\n\n nitroConfig.alias = {\n ...nitroConfig.alias,\n '#analog/ssr': ssrEntry,\n };\n\n await buildServer(\n options,\n nitroConfig,\n routeSourceFiles,\n i18nWorkers,\n );\n\n if (\n nitroConfig.prerender?.routes?.length &&\n options?.prerender?.sitemap\n ) {\n const publicDir = nitroConfig.output?.publicDir;\n if (!publicDir) {\n throw new Error(\n 'Nitro public output directory is required to build the sitemap.',\n );\n }\n\n console.log('Building Sitemap...');\n // sitemap needs to be built after all directories are built\n await buildSitemap(\n config,\n options.prerender.sitemap,\n nitroConfig.prerender.routes,\n publicDir,\n routeSitemaps,\n options.i18n,\n );\n }\n\n console.log(\n `\\n\\nThe '@analogjs/platform' server has been successfully built.`,\n );\n },\n },\n };\n },\n async configureServer(viteServer: ViteDevServer) {\n if (isServe && !isTest) {\n const nitro = await createNitro({\n dev: true,\n ...nitroConfig,\n });\n const server = createDevServer(nitro);\n await build(nitro);\n const apiHandler = toNodeListener(server.app as unknown as App);\n\n // Server functions dispatch through `/_analog/fn/:id`, outside the\n // API prefix the Nitro dev server is mounted under, so route them\n // explicitly — otherwise a call falls through to the SSR catch-all\n // and the client gets HTML back instead of its result.\n if (hasServerFns) {\n viteServer.middlewares.use(\n (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => {\n if (req.url?.startsWith(SERVER_FN_DISPATCH_PREFIX)) {\n apiHandler(req, res);\n return;\n }\n\n next();\n },\n );\n }\n\n viteServer.middlewares.use(\n (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => {\n if (req.url?.startsWith(`${prefix}${apiPrefix}`)) {\n apiHandler(req, res);\n return;\n }\n\n next();\n },\n );\n\n // handle upgrades if websockets are enabled\n if (nitroOptions?.experimental?.websocket) {\n viteServer.httpServer?.on('upgrade', server.upgrade);\n }\n\n console.log(\n `\\n\\nThe server endpoints are accessible under the \"${prefix}${apiPrefix}\" path.`,\n );\n }\n },\n\n async closeBundle() {\n // Skip when build is triggered by the Environment API\n if (environmentBuild) {\n return;\n }\n\n if (ssrBuild) {\n return;\n }\n\n if (isBuild) {\n if (options?.ssr) {\n console.log('Building SSR application...');\n await buildSSRApp(config, options, i18nWorkers);\n }\n\n if (\n nitroConfig.prerender?.routes?.length &&\n options?.prerender?.sitemap\n ) {\n console.log('Building Sitemap...');\n // sitemap needs to be built after all directories are built\n await buildSitemap(\n config,\n options.prerender.sitemap,\n nitroConfig.prerender.routes,\n clientOutputPath,\n routeSitemaps,\n options.i18n,\n );\n }\n\n let ssrEntryPath = resolve(\n options?.ssrBuildDir ||\n resolve(workspaceRoot, 'dist', rootDir, `ssr`),\n `main.server${filePrefix ? '.js' : ''}`,\n );\n\n // add check for main.server.mjs fallback on Windows\n if (isWindows && !existsSync(ssrEntryPath)) {\n ssrEntryPath = ssrEntryPath.replace('.js', '.mjs');\n }\n\n const ssrEntry = normalizePath(filePrefix + ssrEntryPath);\n\n nitroConfig.alias = {\n ...nitroConfig.alias,\n '#analog/ssr': ssrEntry,\n };\n\n await buildServer(\n options,\n nitroConfig,\n routeSourceFiles,\n i18nWorkers,\n );\n\n console.log(\n `\\n\\nThe '@analogjs/platform' server has been successfully built.`,\n );\n }\n },\n },\n {\n name: 'analog-i18n-worker-entry',\n apply: 'build' as const,\n resolveId(id: string) {\n return id === I18N_WORKER_SSR_ENTRY && options?.i18n?.loader\n ? '\\0' + id\n : undefined;\n },\n load(id: string) {\n if (id !== '\\0' + I18N_WORKER_SSR_ENTRY || !options?.i18n?.loader)\n return;\n return i18nWorkerSsrEntry(\n normalizePath(\n resolve(\n workspaceRoot,\n rootDir,\n options.entryServer || `${sourceRoot}/main.server.ts`,\n ),\n ),\n normalizePath(resolve(workspaceRoot, rootDir, options.i18n.loader)),\n options.i18n,\n );\n },\n },\n devServerPlugin(() => ({\n ...options,\n routeRules: nitroOptions?.routeRules,\n })),\n {\n name: '@analogjs/vite-plugin-nitro-api-prefix',\n config() {\n return {\n define: {\n ANALOG_API_PREFIX: `\"${baseURL.substring(1)}${apiPrefix.substring(1)}\"`,\n ...(options?.i18n\n ? {\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(\n options.i18n.defaultLocale,\n ),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n }\n : {}),\n },\n };\n },\n },\n ];\n}\n\nfunction isEmptyPrerenderRoutes(options?: Options): boolean {\n if (!options || isArrayWithElements(options?.prerender?.routes)) {\n return false;\n }\n return !options.prerender?.routes;\n}\n\nfunction isArrayWithElements<T>(arr: unknown): arr is [T, ...T[]] {\n return !!(Array.isArray(arr) && arr.length);\n}\n\nconst isVercelPreset = (buildPreset: string | undefined) =>\n process.env['VERCEL'] ||\n (buildPreset && buildPreset.toLowerCase().includes('vercel'));\n\nconst withVercelOutputAPI = (\n nitroConfig: NitroConfig | undefined,\n workspaceRoot: string,\n) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n dir: normalizePath(resolve(workspaceRoot, '.vercel', 'output')),\n publicDir: normalizePath(\n resolve(workspaceRoot, '.vercel', 'output/static'),\n ),\n },\n});\n\nconst isCloudflarePreset = (buildPreset: string | undefined) =>\n process.env['CF_PAGES'] ||\n (buildPreset && buildPreset.toLowerCase().includes('cloudflare-pages'));\n\nconst withCloudflareOutput = (nitroConfig: NitroConfig | undefined) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n serverDir: '{{ output.publicDir }}/_worker.js',\n },\n});\n\nconst isFirebaseAppHosting = () => !!process.env['NG_BUILD_LOGS_JSON'];\nconst withAppHostingOutput = (nitroConfig: NitroConfig) => {\n let hasOutput = false;\n\n return <NitroConfig>{\n ...nitroConfig,\n serveStatic: true,\n rollupConfig: {\n ...nitroConfig.rollupConfig,\n output: {\n ...nitroConfig.rollupConfig?.output,\n entryFileNames: 'server.mjs',\n },\n },\n hooks: {\n ...nitroConfig.hooks,\n compiled: () => {\n if (!hasOutput) {\n const buildOutput = {\n errors: [],\n warnings: [],\n outputPaths: {\n root: pathToFileURL(`${nitroConfig.output?.dir}`),\n browser: pathToFileURL(`${nitroConfig.output?.publicDir}`),\n server: pathToFileURL(`${nitroConfig.output?.dir}/server`),\n },\n };\n\n // Log the build output for Firebase App Hosting to pick up\n console.log(JSON.stringify(buildOutput, null, 2));\n hasOutput = true;\n }\n },\n },\n };\n};\n\nfunction resolveServerFnAppConfigModule(\n workspaceRoot: string,\n rootDir: string,\n sourceRoot: string,\n): string | undefined {\n // The app's server config (the one `main.server.ts` renders with), exporting\n // `config`. Server-function handlers bootstrap against it, so they resolve the\n // same DI as SSR with no separate provider list to maintain.\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n const candidates = [\n `${root}/${sourceRoot}/app/app.config.server.ts`,\n `${root}/${sourceRoot}/app.config.server.ts`,\n ];\n return candidates.find((candidate) => existsSync(candidate));\n}\n\nconst isNetlifyPreset = (buildPreset: string | undefined) =>\n process.env['NETLIFY'] ||\n (buildPreset && buildPreset.toLowerCase().includes('netlify'));\n\nconst withNetlifyOutputAPI = (\n nitroConfig: NitroConfig | undefined,\n workspaceRoot: string,\n) => ({\n ...nitroConfig,\n output: {\n ...nitroConfig?.output,\n dir: normalizePath(resolve(workspaceRoot, 'netlify/functions')),\n },\n});\n\n/**\n * Reads the options passed to `analog()` from `@analogjs/platform`, which\n * exposes them on its plugin `api`.\n */\nfunction getAnalogOptions(userConfig: UserConfig): Options | undefined {\n const plugins = ((userConfig.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { api?: { analogOptions?: Options } }\n | null\n | undefined\n )[];\n return plugins.find((plugin) => plugin?.api?.analogOptions)?.api\n ?.analogOptions;\n}\n\n/**\n * Stamps `ssr: false` and `streaming: false` route rules as response headers,\n * which the renderers read to skip SSR or streaming for matching routes.\n */\nfunction withAnalogRouteRuleHeaders(nitroOptions: NitroConfig): NitroConfig {\n if (!nitroOptions.routeRules) {\n return nitroOptions;\n }\n\n const routeRules = Object.fromEntries(\n Object.entries(nitroOptions.routeRules).map(([route, rule]) => [\n route,\n {\n ...rule,\n headers: {\n ...rule.headers,\n ...(rule.ssr === false ? { 'x-analog-no-ssr': 'true' } : {}),\n ...(rule.streaming === false\n ? { 'x-analog-no-streaming': 'true' }\n : {}),\n },\n },\n ]),\n );\n\n return { ...nitroOptions, routeRules };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqDA,IAAM,YAAY,SAAS,MAAM;AACjC,IAAM,aAAa,YAAY,aAAa;AAC5C,IAAI,mBAAmB;AAEvB,IAAM,aAAa,cAAc,YAAY,GAAG;AAC9B,QAAQ,UAAU;AAUpC,SAAgB,MAAM,gBAAoC,CAAC,GAAa;CAEtE,MAAM,EAAE,QAAQ,QAAQ,UAAU,GAAG,uBAAuB;CAC5D,MAAM,eAAe,2BAA2B,kBAAkB;CAClE,IAAI;CACJ,IAAI,gBAAgB,QAAQ,IAAI;CAChC,IAAI,aAAa;CACjB,IAAI,SAAA,QAAA,IAAA,aAAqC,UAAU,CAAC,CAAC,QAAQ,IAAI;CACjE,MAAM,UAAU,QAAQ,IAAI,yBAAyB;CACrD,MAAM,S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