@analogjs/vite-plugin-nitro 3.0.0-beta.8 → 3.0.0

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.
@@ -1,5 +1,5 @@
1
1
  import * as ts from "typescript";
2
- //#region packages/vite-plugin-nitro/migrations/update-nitro-options/update-nitro-options.ts
2
+ // packages/vite-plugin-nitro/migrations/update-nitro-options/update-nitro-options.ts
3
3
  var NITRO_PLUGIN_PKG = "@analogjs/vite-plugin-nitro";
4
4
  var VITE_CONFIG_EXTENSIONS = [
5
5
  ".ts",
@@ -116,7 +116,6 @@ function updateNitroOptions() {
116
116
  return tree;
117
117
  };
118
118
  }
119
- //#endregion
120
119
  export { updateNitroOptions as default };
121
120
 
122
121
  //# sourceMappingURL=update-nitro-options.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/vite-plugin-nitro",
3
- "version": "3.0.0-beta.8",
3
+ "version": "3.0.0",
4
4
  "description": "A Vite plugin for adding a nitro API server",
5
5
  "type": "module",
6
6
  "author": "Brandon Roberts <robertsbt@gmail.com>",
package/src/index.js CHANGED
@@ -1,9 +1,8 @@
1
+ import { nitro } from "./lib/vite-plugin-nitro.js";
1
2
  import { deriveServerFnId, serverFnFileId } from "./lib/utils/derive-server-fn-id.js";
2
3
  import { injectServerFnIds } from "./lib/utils/inject-server-fn-ids.js";
3
- import { nitro } from "./lib/vite-plugin-nitro.js";
4
- //#region packages/vite-plugin-nitro/src/index.ts
4
+ // packages/vite-plugin-nitro/src/index.ts
5
5
  var src_default = nitro;
6
- //#endregion
7
6
  export { src_default as default, deriveServerFnId, injectServerFnIds, nitro, serverFnFileId };
8
7
 
9
8
  //# sourceMappingURL=index.js.map
@@ -5,7 +5,7 @@ import { build, copyPublicAssets, createNitro, prepare, prerender } from "nitrop
5
5
  import { dirname, join } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
7
  import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
8
- //#region packages/vite-plugin-nitro/src/lib/build-server.ts
8
+ // packages/vite-plugin-nitro/src/lib/build-server.ts
9
9
  async function buildServer(options, nitroConfig = {}, routeSourceFiles, i18nWorkers = false) {
10
10
  if (i18nWorkers && options?.i18n) {
11
11
  validateI18nWorkers(options, nitroConfig);
@@ -47,7 +47,7 @@ async function buildServer(options, nitroConfig = {}, routeSourceFiles, i18nWork
47
47
  if (options?.prerender?.postRenderingHooks) addPostRenderingHooks(nitro, options.prerender.postRenderingHooks);
48
48
  await prepare(nitro);
49
49
  await copyPublicAssets(nitro);
50
- if (options?.ssr && nitroConfig?.prerender?.routes && (nitroConfig?.prerender?.routes.find((route) => route === "/") || nitroConfig?.prerender?.routes?.length === 0)) [
50
+ if (options?.ssr && (!(options.static || nitro.options.static) || nitroConfig.prerender?.routes?.includes("/"))) [
51
51
  "",
52
52
  ".br",
53
53
  ".gz"
@@ -96,7 +96,6 @@ async function buildServer(options, nitroConfig = {}, routeSourceFiles, i18nWork
96
96
  await nitro.close();
97
97
  }
98
98
  }
99
- //#endregion
100
99
  export { buildServer };
101
100
 
102
101
  //# sourceMappingURL=build-server.js.map
@@ -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,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,Q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,OAAO,cAAc,KAAK,CAAC,CAAC,MAAA,CACvB;IAC7B,CAAC;GACH,CAAC,IACD,KAAA;GACJ,IAAI;IACF,MAAM,UAAU,KAAK;GACvB,UAAU;IACR,SAAS;IACT,IAAI;KACF,MAAM,mBAAmB;IAC3B,UAAU;KACR,MAAM,aAAa,MAAM;IAC3B;GACF;EACF;EAEA,IAAI,oBAAoB,OAAO,KAAK,gBAAgB,CAAC,CAAC,SAAS,GAAG;GAChE,MAAM,YAAY,aAAa,QAAQ;GACvC,IAAI,CAAC,WACH,MAAM,IAAI,MACR,wEACF;GAGF,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,gBAAgB,GAAG;IAC/D,MAAM,aAAa,KAAK,WAAW,GAAG,MAAM,IAAI;IAChD,MAAM,YAAY,QAAQ,UAAU;IAEpC,IAAI,CAAC,WAAW,SAAS,GACvB,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;IAG1C,cAAc,YAAY,SAAS,MAAM;GAC3C;EACF;EAEA,IAAI,CAAC,SAAS,QAAQ;GACpB,QAAQ,IAAI,oBAAoB;GAChC,MAAM,MAAM,KAAK;EACnB;CACF,UAAU;EACR,MAAM,MAAM,MAAM;CACpB;AACF"}
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 (!(options.static || nitro.options.static) ||\n nitroConfig.prerender?.routes?.includes('/'))\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;G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,CAAC;GACH,CAAC,IACD,KAAA;GACJ,IAAI;IACF,MAAM,UAAU,KAAK;GACvB,UAAU;IACR,SAAS;IACT,IAAI;KACF,MAAM,mBAAmB;IAC3B,UAAU;KACR,MAAM,aAAa,MAAM;IAC3B;GACF;EACF;EAEA,IAAI,oBAAoB,OAAO,KAAK,gBAAgB,CAAC,CAAC,SAAS,GAAG;GAChE,MAAM,YAAY,aAAa,QAAQ;GACvC,IAAI,CAAC,WACH,MAAM,IAAI,MACR,wEACF;GAGF,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,gBAAgB,GAAG;IAC/D,MAAM,aAAa,KAAK,WAAW,GAAG,MAAM,IAAI;IAChD,MAAM,YAAY,QAAQ,UAAU;IAEpC,IAAI,CAAC,WAAW,SAAS,GACvB,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;IAG1C,cAAc,YAAY,SAAS,MAAM;GAC3C;EACF;EAEA,IAAI,CAAC,SAAS,QAAQ;GACpB,QAAQ,IAAI,oBAAoB;GAChC,MAAM,MAAM,KAAK;EACnB;CACF,UAAU;EACR,MAAM,MAAM,MAAM;CACpB;AACF"}
@@ -6,7 +6,7 @@ export type PagesJson = {
6
6
  changefreq?: string;
7
7
  priority?: string;
8
8
  };
9
- export declare function buildSitemap(config: UserConfig, sitemapConfig: SitemapConfig, routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>), outputDir: string, routeSitemaps: Record<string, PrerenderSitemapConfig | (() => PrerenderSitemapConfig) | undefined>, i18nOptions?: I18nPrerenderOptions): Promise<void>;
9
+ export declare function buildSitemap(config: UserConfig, sitemapConfig: SitemapConfig, routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>), outputDir: string, routeSitemaps: Record<string, PrerenderSitemapConfig | (() => PrerenderSitemapConfig) | undefined>, i18nOptions?: I18nPrerenderOptions, apiPrefix?: string): Promise<void>;
10
10
  /**
11
11
  * Generates hreflang alternate URLs for a given page URL.
12
12
  * For a URL like `https://example.com/fr/about`, it produces alternates
@@ -1,17 +1,17 @@
1
1
  import { resolve } from "node:path";
2
2
  import { writeFileSync } from "node:fs";
3
3
  import { create } from "xmlbuilder2";
4
- //#region packages/vite-plugin-nitro/src/lib/build-sitemap.ts
5
- async function buildSitemap(config, sitemapConfig, routes, outputDir, routeSitemaps, i18nOptions) {
6
- const routeList = await optionHasRoutes(routes);
4
+ // packages/vite-plugin-nitro/src/lib/build-sitemap.ts
5
+ async function buildSitemap(config, sitemapConfig, routes, outputDir, routeSitemaps, i18nOptions, apiPrefix = "/api") {
6
+ const routeList = (await optionHasRoutes(routes)).filter((route) => !route.startsWith(`${apiPrefix}/_analog/pages/`) && !route.includes("?"));
7
7
  if (routeList.length) {
8
8
  const slash = checkSlash(sitemapConfig.host || "");
9
9
  const sitemapData = routeList.map((page) => {
10
- const url = `${slash}${page.replace(/^\/+/g, "")}`;
11
- const config = routeSitemaps[url];
10
+ const path = page.replace(/^\/+/g, "");
11
+ const config = routeSitemaps[`/${path}`] ?? (Object.prototype.hasOwnProperty.call(routeSitemaps, path) ? routeSitemaps[path] : void 0);
12
12
  const props = typeof config === "object" ? config : config?.();
13
13
  return {
14
- page: `${sitemapConfig.host}${url}`,
14
+ page: `${sitemapConfig.host}${slash}${path}`,
15
15
  lastMod: props?.lastmod ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
16
16
  changefreq: props?.changefreq,
17
17
  priority: props?.priority
@@ -92,7 +92,6 @@ async function optionHasRoutes(routes) {
92
92
  else routeList = [];
93
93
  return routeList.filter(Boolean);
94
94
  }
95
- //#endregion
96
95
  export { buildSitemap, getHreflangAlternates, stripLocalePrefix };
97
96
 
98
97
  //# 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,MAAM;CAExD,IAAI,UAAU,QAAQ;EACpB,MAAM,QAAQ,WAAW,cAAc,QAAQ,EAAE;EACjD,MAAM,cAA2B,UAAU,KAAK,SAAiB;GAC/D,MAAM,MAAM,GAAG,QAAQ,KAAK,QAAQ,SAAS,EAAE;GAC/C,MAAM,SAAS,cAAc;GAC7B,MAAM,QAAQ,OAAO,WAAW,WAAW,SAAS,SAAS;GAE7D,OAAO;IACL,MAAM,GAAG,cAAc,OAAO;IAC9B,SAAS,OAAO,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC/D,YAAY,OAAO;IACnB,UAAU,OAAO;GACnB;EACF,CAAC;EAED,MAAM,UAAU,eAAe,YAAY,QAAQ,SAAS;EAC5D,MAAM,UAAU,UAAU,UAAU,OAAO;EAE3C,KAAK,MAAM,QAAQ,aAAa;GAC9B,MAAM,OAAO,QAAQ,IAAI,KAAK;GAC9B,KAAK,IAAI,KAAK,CAAC,CAAC,IAAI,KAAK,IAAI;GAC7B,KAAK,IAAI,SAAS,CAAC,CAAC,IAAI,KAAK,OAAO;GAEpC,IAAI,KAAK,YACP,KAAK,IAAI,YAAY,CAAC,CAAC,IAAI,KAAK,UAAU;GAG5C,IAAI,KAAK,UACP,KAAK,IAAI,UAAU,CAAC,CAAC,IAAI,KAAK,QAAQ;GAIxC,IAAI,SAAS;IACX,MAAM,aAAa,sBACjB,KAAK,MACL,cAAc,MACd,WACF;IACA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AAM,QAAgC,EACpC,OAAO,8CACT;CACA,IAAI,cACF,MAAM,iBAAiB;CAGzB,OAAO,OAAO;EAAE,SAAS;EAAO,UAAU;CAAQ,CAAC,CAAC,CACjD,IAAI,aAAa,KAAK,CAAC,CACvB,IAAI,kDAAkD;AAC3D;AAEA,SAAS,WAAW,MAAsB;CAExC,OADkB,KAAK,MAAM,EACtB,MAAc,MAAM,KAAK;AAClC;AAEA,eAAe,gBACb,QACmB;CACnB,IAAI;CAEJ,IAAI,OAAO,WAAW,YAEpB,YAAY,MAAM,OAAO;MACpB,IAAI,MAAM,QAAQ,MAAM,GAE7B,YAAY;MAGZ,YAAY,CAAC;CAGf,OAAO,UAAU,OAAO,OAAO;AACjC"}
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 apiPrefix = '/api',\n): Promise<void> {\n // Internal static-data endpoints and routes with query params are not\n // canonical pages, so they are left out of the sitemap.\n const routeList: string[] = (await optionHasRoutes(routes)).filter(\n (route) =>\n !route.startsWith(`${apiPrefix}/_analog/pages/`) && !route.includes('?'),\n );\n\n if (routeList.length) {\n const slash = checkSlash(sitemapConfig.host || '');\n const sitemapData: PagesJson[] = routeList.map((page: string) => {\n const path = page.replace(/^\\/+/g, '');\n const config =\n routeSitemaps[`/${path}`] ??\n (Object.prototype.hasOwnProperty.call(routeSitemaps, path)\n ? routeSitemaps[path]\n : undefined);\n const props = typeof config === 'object' ? config : config?.();\n\n return {\n page: `${sitemapConfig.host}${slash}${path}`,\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,aACA,YAAY,QACG;CAGf,MAAM,aAAuB,MAAM,gBAAgB,MAAM,EAAA,CAAG,QACzD,UACC,CAAC,MAAM,WAAW,GAAG,UAAU,gBAAgB,KAAK,CAAC,MAAM,S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AAM,KAAK;AAClC;AAEA,eAAe,gBACb,QACmB;CACnB,IAAI;CAEJ,IAAI,OAAO,WAAW,YAEpB,YAAY,MAAM,OAAO;MACpB,IAAI,MAAM,QAAQ,MAAM,GAE7B,YAAY;MAGZ,YAAY,CAAC;CAGf,OAAO,UAAU,OAAO,OAAO;AACjC"}
@@ -2,7 +2,7 @@ import { I18N_WORKER_SSR_ENTRY } from "./utils/i18n-workers.js";
2
2
  import * as vite from "vite";
3
3
  import { build, mergeConfig } from "vite";
4
4
  import { relative, resolve } from "node:path";
5
- //#region packages/vite-plugin-nitro/src/lib/build-ssr.ts
5
+ // packages/vite-plugin-nitro/src/lib/build-ssr.ts
6
6
  async function buildSSRApp(config, options, i18nWorkers = false) {
7
7
  const workspaceRoot = options?.workspaceRoot ?? process.cwd();
8
8
  const sourceRoot = options?.sourceRoot ?? "src";
@@ -14,7 +14,6 @@ async function buildSSRApp(config, options, i18nWorkers = false) {
14
14
  } });
15
15
  await build(ssrBuildConfig);
16
16
  }
17
- //#endregion
18
17
  export { buildSSRApp };
19
18
 
20
19
  //# sourceMappingURL=build-ssr.js.map
@@ -1,10 +1,9 @@
1
- //#region packages/vite-plugin-nitro/src/lib/hooks/post-rendering-hook.ts
1
+ // packages/vite-plugin-nitro/src/lib/hooks/post-rendering-hook.ts
2
2
  function addPostRenderingHooks(nitro, hooks) {
3
3
  hooks.forEach((hook) => {
4
4
  nitro.hooks.hook("prerender:generate", hook);
5
5
  });
6
6
  }
7
- //#endregion
8
7
  export { addPostRenderingHooks };
9
8
 
10
9
  //# sourceMappingURL=post-rendering-hook.js.map
@@ -7,7 +7,7 @@ import { resolve } from "node:path";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { createRouter, toRouteMatcher } from "radix3";
9
9
  import { defu } from "defu";
10
- //#region packages/vite-plugin-nitro/src/lib/plugins/dev-server-plugin.ts
10
+ // packages/vite-plugin-nitro/src/lib/plugins/dev-server-plugin.ts
11
11
  function devServerPlugin(getOptions) {
12
12
  let options;
13
13
  let sourceRoot;
@@ -115,7 +115,6 @@ function prepareError(req, error) {
115
115
  stack: typeof e === "string" ? "" : e.stack
116
116
  };
117
117
  }
118
- //#endregion
119
118
  export { devServerPlugin };
120
119
 
121
120
  //# sourceMappingURL=dev-server-plugin.js.map
@@ -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;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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,GAAG,CAAC;CAE5B;AACF;;;;;;;AAQA,SAAS,aAAa,KAA8B,OAAgB;CAClE,MAAM,IAAI;CACV,OAAO;EACL,SAAS,2CAA2C,IAAI,IAAI,SAC1D,OAAO,MAAM,WAAW,IAAI,EAAE,QAC/B;EACD,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;CACxC;AACF"}
1
+ {"version":3,"file":"dev-server-plugin.js","names":["createRadixRouter"],"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,WA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,iBAAiB,SAAS,WAAW,GACtD,OAAO,MAAM,OAAO,GAAG,CAAC;CAE5B;AACF;;;;;;;AAQA,SAAS,aAAa,KAA8B,OAAgB;CAClE,MAAM,IAAI;CACV,OAAO;EACL,SAAS,2CAA2C,IAAI,IAAI,SAC1D,OAAO,MAAM,WAAW,IAAI,EAAE,QAC/B;EACD,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;CACxC;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { normalizePath } from "vite";
2
2
  import { parseSync } from "oxc-parser";
3
- //#region packages/vite-plugin-nitro/src/lib/plugins/page-endpoints.ts
3
+ // packages/vite-plugin-nitro/src/lib/plugins/page-endpoints.ts
4
4
  function pageEndpointsPlugin() {
5
5
  return {
6
6
  name: "analogjs-vite-plugin-nitro-rollup-page-endpoint",
@@ -62,7 +62,6 @@ function pageEndpointsPlugin() {
62
62
  }
63
63
  };
64
64
  }
65
- //#endregion
66
65
  export { pageEndpointsPlugin };
67
66
 
68
67
  //# sourceMappingURL=page-endpoints.js.map
@@ -1,6 +1,6 @@
1
1
  import { serverFnFileId } from "../utils/derive-server-fn-id.js";
2
2
  import { injectServerFnIds } from "../utils/inject-server-fn-ids.js";
3
- //#region packages/vite-plugin-nitro/src/lib/plugins/server-fn-id-plugin.ts
3
+ // packages/vite-plugin-nitro/src/lib/plugins/server-fn-id-plugin.ts
4
4
  /**
5
5
  * Nitro-build transform that stamps the derived id into each `serverFn` config
6
6
  * in a `*.server.ts`, so a function registers under the same opaque route the
@@ -21,7 +21,6 @@ function serverFnIdPlugin(projectRoot) {
21
21
  }
22
22
  };
23
23
  }
24
- //#endregion
25
24
  export { serverFnIdPlugin };
26
25
 
27
26
  //# sourceMappingURL=server-fn-id-plugin.js.map
@@ -1,6 +1,6 @@
1
1
  import { relative } from "node:path";
2
2
  import { createHash } from "node:crypto";
3
- //#region packages/vite-plugin-nitro/src/lib/utils/derive-server-fn-id.ts
3
+ // packages/vite-plugin-nitro/src/lib/utils/derive-server-fn-id.ts
4
4
  var toPosix = (p) => p.replace(/\\/g, "/");
5
5
  /**
6
6
  * Server-function ids are derived, never author-chosen, for security:
@@ -31,7 +31,6 @@ function serverFnFileId(absPath, projectRoot) {
31
31
  function deriveServerFnId(fileId, exportName) {
32
32
  return createHash("sha256").update(`${fileId}#${exportName}`).digest("hex").slice(0, 16);
33
33
  }
34
- //#endregion
35
34
  export { deriveServerFnId, serverFnFileId };
36
35
 
37
36
  //# sourceMappingURL=derive-server-fn-id.js.map
@@ -3,7 +3,7 @@ import { join, relative, resolve } from "node:path";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { globSync } from "tinyglobby";
5
5
  import { createRequire } from "node:module";
6
- //#region packages/vite-plugin-nitro/src/lib/utils/get-content-files.ts
6
+ // packages/vite-plugin-nitro/src/lib/utils/get-content-files.ts
7
7
  var require = createRequire(import.meta.url);
8
8
  /**
9
9
  * Discovers content files with front matter and extracts metadata for prerendering.
@@ -93,7 +93,6 @@ function getMatchingContentFilesWithFrontMatter(workspaceRoot, rootDir, glob, re
93
93
  };
94
94
  });
95
95
  }
96
- //#endregion
97
96
  export { getMatchingContentFilesWithFrontMatter };
98
97
 
99
98
  //# sourceMappingURL=get-content-files.js.map
@@ -1,7 +1,7 @@
1
1
  import { normalizePath } from "vite";
2
2
  import { resolve } from "node:path";
3
3
  import { globSync } from "tinyglobby";
4
- //#region packages/vite-plugin-nitro/src/lib/utils/get-page-handlers.ts
4
+ // packages/vite-plugin-nitro/src/lib/utils/get-page-handlers.ts
5
5
  /**
6
6
  * Discovers and generates Nitro event handlers for server-side page routes.
7
7
  *
@@ -66,7 +66,6 @@ function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDi
66
66
  };
67
67
  });
68
68
  }
69
- //#endregion
70
69
  export { getPageHandlers };
71
70
 
72
71
  //# sourceMappingURL=get-page-handlers.js.map
@@ -3,7 +3,7 @@ import { resolve } from "node:path";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { parseSync } from "oxc-parser";
5
5
  import { globSync } from "tinyglobby";
6
- //#region packages/vite-plugin-nitro/src/lib/utils/get-server-fn-handlers.ts
6
+ // packages/vite-plugin-nitro/src/lib/utils/get-server-fn-handlers.ts
7
7
  /**
8
8
  * `*.server.ts` files that are matched by the glob but are never server-function
9
9
  * hosts, so importing them for registration side-effects would be wrong.
@@ -60,7 +60,6 @@ function definesServerFn(file) {
60
60
  if (localNames.size === 0) localNames.add("serverFn");
61
61
  return program.body.some((node) => node.type === "ExportNamedDeclaration" && node.declaration?.type === "VariableDeclaration" && node.declaration.declarations.some((declarator) => declarator.id?.type === "Identifier" && declarator.init?.type === "CallExpression" && declarator.init.callee?.type === "Identifier" && localNames.has(declarator.init.callee.name)));
62
62
  }
63
- //#endregion
64
63
  export { getServerFnHandlers };
65
64
 
66
65
  //# sourceMappingURL=get-server-fn-handlers.js.map
@@ -12,9 +12,10 @@ import { I18nPrerenderOptions } from "../options.js";
12
12
  *
13
13
  * @param routes - The original routes to expand
14
14
  * @param i18n - The i18n prerender configuration
15
+ * @param apiPrefix - The API route prefix (default `api`); API routes are not localized
15
16
  * @returns Expanded routes with locale prefixes
16
17
  */
17
- export declare function expandRoutesWithLocales(routes: string[], i18n: I18nPrerenderOptions): string[];
18
+ export declare function expandRoutesWithLocales(routes: string[], i18n: I18nPrerenderOptions, apiPrefix?: string): string[];
18
19
  /**
19
20
  * Creates a post-rendering hook that injects the `lang` attribute
20
21
  * into the `<html>` tag of prerendered pages based on the route's
@@ -1,4 +1,4 @@
1
- //#region packages/vite-plugin-nitro/src/lib/utils/i18n-prerender.ts
1
+ // packages/vite-plugin-nitro/src/lib/utils/i18n-prerender.ts
2
2
  /**
3
3
  * Expands a list of routes to include locale-prefixed variants.
4
4
  *
@@ -11,13 +11,15 @@
11
11
  *
12
12
  * @param routes - The original routes to expand
13
13
  * @param i18n - The i18n prerender configuration
14
+ * @param apiPrefix - The API route prefix (default `api`); API routes are not localized
14
15
  * @returns Expanded routes with locale prefixes
15
16
  */
16
- function expandRoutesWithLocales(routes, i18n) {
17
+ function expandRoutesWithLocales(routes, i18n, apiPrefix = "api") {
17
18
  const expanded = /* @__PURE__ */ new Set();
19
+ const apiRoute = `/${apiPrefix.replace(/^\/+|\/+$/g, "")}`;
18
20
  for (const route of routes) {
19
21
  const firstSegment = route.split("/").filter(Boolean)[0];
20
- if (route.includes("/_analog/") || route.startsWith("/api/") || i18n.locales.includes(firstSegment)) {
22
+ if (route.includes("/_analog/") || route === apiRoute || route.startsWith(`${apiRoute}/`) || i18n.locales.includes(firstSegment)) {
21
23
  expanded.add(route);
22
24
  continue;
23
25
  }
@@ -64,7 +66,6 @@ function setHtmlLang(html, locale) {
64
66
  if (/<html[^>]*\slang\s*=\s*["'][^"']*["']/i.test(html)) return html.replace(/(<html[^>]*\s)lang\s*=\s*["'][^"']*["']/i, `$1lang="${locale}"`);
65
67
  return html.replace(/<html/i, `<html lang="${locale}"`);
66
68
  }
67
- //#endregion
68
69
  export { createI18nPostRenderingHook, detectLocaleFromRoute, expandRoutesWithLocales, setHtmlLang };
69
70
 
70
71
  //# sourceMappingURL=i18n-prerender.js.map
@@ -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,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
+ {"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 * @param apiPrefix - The API route prefix (default `api`); API routes are not localized\n * @returns Expanded routes with locale prefixes\n */\nexport function expandRoutesWithLocales(\n routes: string[],\n i18n: I18nPrerenderOptions,\n apiPrefix = 'api',\n): string[] {\n const expanded = new Set<string>();\n const apiRoute = `/${apiPrefix.replace(/^\\/+|\\/+$/g, '')}`;\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 === apiRoute ||\n route.startsWith(`${apiRoute}/`) ||\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":";;;;;;;;;;;;;;;;AAkBA,SAAgB,wBACd,QACA,MACA,YAAY,OACF;CACV,MAAM,2BAAW,IAAI,IAAY;CACjC,MAAM,WAAW,IAAI,UAAU,QAAQ,cAAc,EAAE;CAEvD,KAAK,MAAM,SAAS,QAAQ;EAE1B,MAAM,eAAe,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;EACtD,IACE,MAAM,SAAS,WAAW,KAC1B,UAAU,YACV,MAAM,WAAW,GAAG,SAAS,EAAE,KAC/B,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,6 +1,6 @@
1
1
  import { dirname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- //#region packages/vite-plugin-nitro/src/lib/utils/i18n-workers.ts
3
+ // packages/vite-plugin-nitro/src/lib/utils/i18n-workers.ts
4
4
  var I18N_WORKER_SSR_ENTRY = "virtual:analog-i18n/main.server";
5
5
  function validateI18nWorkers(options, nitro) {
6
6
  if (!options.i18n?.loader) throw new Error("i18n.workers requires an i18n.loader module.");
@@ -49,7 +49,6 @@ export default async function (...args) {
49
49
  }
50
50
  `;
51
51
  }
52
- //#endregion
53
52
  export { I18N_WORKER_SSR_ENTRY, i18nWorkerSsrEntry, resolveI18nWorkers, validateI18nWorkers };
54
53
 
55
54
  //# sourceMappingURL=i18n-workers.js.map
@@ -1,7 +1,7 @@
1
1
  import { deriveServerFnId } from "./derive-server-fn-id.js";
2
2
  import { parseSync } from "oxc-parser";
3
3
  import MagicString from "magic-string";
4
- //#region packages/vite-plugin-nitro/src/lib/utils/inject-server-fn-ids.ts
4
+ // packages/vite-plugin-nitro/src/lib/utils/inject-server-fn-ids.ts
5
5
  var SERVER_FN_SOURCE = "@analogjs/router/server";
6
6
  /**
7
7
  * Server/SSR-build transform: injects the derived `id` into each
@@ -88,7 +88,6 @@ function collectServerFnLocalNames(body) {
88
88
  if (names.size === 0) names.add("serverFn");
89
89
  return names;
90
90
  }
91
- //#endregion
92
91
  export { injectServerFnIds };
93
92
 
94
93
  //# sourceMappingURL=inject-server-fn-ids.js.map
@@ -1,6 +1,6 @@
1
1
  import { createEvent } from "h3";
2
2
  import { globSync } from "tinyglobby";
3
- //#region packages/vite-plugin-nitro/src/lib/utils/register-dev-middleware.ts
3
+ // packages/vite-plugin-nitro/src/lib/utils/register-dev-middleware.ts
4
4
  /**
5
5
  * Registers development server middleware by discovering and loading middleware files.
6
6
  *
@@ -51,7 +51,6 @@ async function registerDevServerMiddleware(root, sourceRoot, viteServer) {
51
51
  });
52
52
  });
53
53
  }
54
- //#endregion
55
54
  export { registerDevServerMiddleware };
56
55
 
57
56
  //# sourceMappingURL=register-dev-middleware.js.map
@@ -1,4 +1,4 @@
1
- //#region packages/vite-plugin-nitro/src/lib/utils/register-i18n-watcher.ts
1
+ // packages/vite-plugin-nitro/src/lib/utils/register-i18n-watcher.ts
2
2
  /**
3
3
  * Registers a file watcher that triggers a full page reload
4
4
  * when translation files are added or modified.
@@ -21,7 +21,6 @@ function registerI18nWatcher(viteServer) {
21
21
  function isTranslationFile(path) {
22
22
  return /i18n.*\.(json|xlf|xmb|arb)$/.test(path);
23
23
  }
24
- //#endregion
25
24
  export { isTranslationFile, registerI18nWatcher };
26
25
 
27
26
  //# sourceMappingURL=register-i18n-watcher.js.map
@@ -1,4 +1,4 @@
1
- //#region packages/vite-plugin-nitro/src/lib/utils/renderers.ts
1
+ // packages/vite-plugin-nitro/src/lib/utils/renderers.ts
2
2
  var ssrRenderer = `
3
3
  import { eventHandler, getResponseHeader } from 'h3';
4
4
  // @ts-ignore
@@ -97,7 +97,6 @@ export default eventHandler(async () => {
97
97
  return template;
98
98
  });
99
99
  `;
100
- //#endregion
101
100
  export { clientRenderer, createSsrStreamRenderer, ssrRenderer, ssrStreamRenderer };
102
101
 
103
102
  //# sourceMappingURL=renderers.js.map
@@ -29,6 +29,8 @@ export type BuildServerFnDispatchModuleArgs = {
29
29
  * app configured. When absent, handlers run with only `providedIn: 'root'`.
30
30
  */
31
31
  appConfigModule?: string;
32
+ /** The app's root directory, where `zone.js` is resolved from. */
33
+ root: string;
32
34
  };
33
35
  /**
34
36
  * Generates the source of the Nitro dispatch handler.
@@ -38,4 +40,4 @@ export type BuildServerFnDispatchModuleArgs = {
38
40
  * each request looks up the function by id and runs it via `dispatchServerFn` —
39
41
  * the same call path the validation harnesses exercise.
40
42
  */
41
- export declare function buildServerFnDispatchModule({ modules, appConfigModule }: BuildServerFnDispatchModuleArgs): string;
43
+ export declare function buildServerFnDispatchModule({ modules, appConfigModule, root }: BuildServerFnDispatchModuleArgs): string;
@@ -1,5 +1,7 @@
1
1
  import { normalizePath } from "vite";
2
- //#region packages/vite-plugin-nitro/src/lib/utils/server-fn-endpoints.ts
2
+ import { join } from "node:path";
3
+ import { createRequire } from "node:module";
4
+ // packages/vite-plugin-nitro/src/lib/utils/server-fn-endpoints.ts
3
5
  /**
4
6
  * Nitro virtual-module id for the generated server-function dispatch handler.
5
7
  * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.
@@ -33,16 +35,17 @@ function getServerFnDispatchHandler() {
33
35
  * each request looks up the function by id and runs it via `dispatchServerFn` —
34
36
  * the same call path the validation harnesses exercise.
35
37
  */
36
- function buildServerFnDispatchModule({ modules, appConfigModule }) {
38
+ function buildServerFnDispatchModule({ modules, appConfigModule, root }) {
39
+ const registrationImports = modules.map((m) => `import ${JSON.stringify(normalizePath(m.file))};`).join("\n");
40
+ const appConfig = appConfigModule ? `import { config as serverFnAppConfig } from ${JSON.stringify(normalizePath(appConfigModule))};` : `const serverFnAppConfig = { providers: [] };`;
37
41
  return `import '@angular/compiler';
38
- import 'zone.js/node';
39
- import '@angular/platform-server/init';
42
+ ${hasZoneJs(root) ? `import 'zone.js/node';\n` : ""}import '@angular/platform-server/init';
40
43
  import { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';
41
44
 
42
45
  // Discovered server-function modules (registration side-effects).
43
- ${modules.map((m) => `import ${JSON.stringify(normalizePath(m.file))};`).join("\n")}
46
+ ${registrationImports}
44
47
 
45
- ${appConfigModule ? `import { config as serverFnAppConfig } from ${JSON.stringify(normalizePath(appConfigModule))};` : `const serverFnAppConfig = { providers: [] };`}
48
+ ${appConfig}
46
49
 
47
50
  // Bootstrapped once from the app's own server config, so a handler resolves the
48
51
  // same DI as an SSR render (\`providedIn: 'root'\` and listed providers alike).
@@ -53,7 +56,14 @@ export default createServerFnEventHandler(
53
56
  );
54
57
  `;
55
58
  }
56
- //#endregion
59
+ function hasZoneJs(root) {
60
+ try {
61
+ createRequire(join(root, "noop.js")).resolve("zone.js/node");
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
57
67
  export { SERVER_FN_DISPATCH_PREFIX, SERVER_FN_DISPATCH_ROUTE, SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
58
68
 
59
69
  //# 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;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"}
1
+ {"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/utils/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitropack';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\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 /** The app's root directory, where `zone.js` is resolved from. */\n root: 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 root,\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` (when installed; zoneless apps may omit it) and the server\n // platform init match the SSR entry, so bootstrapping the app injector below\n // 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 const zoneImport = hasZoneJs(root) ? `import 'zone.js/node';\\n` : '';\n\n return `import '@angular/compiler';\n${zoneImport}import '@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\nfunction hasZoneJs(root: string): boolean {\n try {\n createRequire(join(root, 'noop.js')).resolve('zone.js/node');\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;AAWA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;AAGxC,IAAa,4BAA4B;;;;;;;;;;AAWzC,SAAgB,6BAAgD;CAC9D,OAAO;EACL,OAAO;EACP,SAAS;EACT,MAAM;CACR;AACF;;;;;;;;;AAwBA,SAAgB,4BAA4B,EAC1C,SACA,iBACA,QAC0C;CAC1C,MAAM,sBAAsB,QACzB,KAAK,MAAM,UAAU,KAAK,UAAU,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAC9D,KAAK,IAAI;CAKZ,MAAM,YAAY,kBACd,+CAA+C,KAAK,UAClD,cAAc,eAAe,CAC/B,EAAE,KACF;CAeJ,OAAO;EAFY,UAAU,IAAI,IAAI,6BAA6B,GAGvD;;;;EAIX,oBAAoB;;EAEpB,UAAU;;;;;;;;;;AAUZ;AAEA,SAAS,UAAU,MAAuB;CACxC,IAAI;EACF,cAAc,KAAK,MAAM,SAAS,CAAC,CAAC,CAAC,QAAQ,cAAc;EAC3D,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -1,16 +1,16 @@
1
- import { I18N_WORKER_SSR_ENTRY, i18nWorkerSsrEntry, resolveI18nWorkers } from "./utils/i18n-workers.js";
2
- import { clientRenderer, ssrRenderer, ssrStreamRenderer } from "./utils/renderers.js";
3
1
  import { buildServer } from "./build-server.js";
4
2
  import { buildSSRApp } from "./build-ssr.js";
3
+ import { I18N_WORKER_SSR_ENTRY, i18nWorkerSsrEntry, resolveI18nWorkers } from "./utils/i18n-workers.js";
5
4
  import { pageEndpointsPlugin } from "./plugins/page-endpoints.js";
6
5
  import { serverFnIdPlugin } from "./plugins/server-fn-id-plugin.js";
7
6
  import { getPageHandlers } from "./utils/get-page-handlers.js";
8
7
  import { getServerFnHandlers } from "./utils/get-server-fn-handlers.js";
9
8
  import { SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler } from "./utils/server-fn-endpoints.js";
10
9
  import { buildSitemap } from "./build-sitemap.js";
11
- import { createI18nPostRenderingHook, expandRoutesWithLocales } from "./utils/i18n-prerender.js";
12
10
  import { devServerPlugin } from "./plugins/dev-server-plugin.js";
13
11
  import { getMatchingContentFilesWithFrontMatter } from "./utils/get-content-files.js";
12
+ import { clientRenderer, ssrRenderer, ssrStreamRenderer } from "./utils/renderers.js";
13
+ import { createI18nPostRenderingHook, expandRoutesWithLocales } from "./utils/i18n-prerender.js";
14
14
  import { build, createDevServer, createNitro, loadOptions } from "nitropack";
15
15
  import { toNodeListener } from "h3";
16
16
  import { mergeConfig, normalizePath } from "vite";
@@ -18,7 +18,7 @@ import { dirname, relative, resolve } from "node:path";
18
18
  import { platform } from "node:os";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { existsSync, readFileSync } from "node:fs";
21
- //#region packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
21
+ // packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
22
22
  var isWindows = platform() === "win32";
23
23
  var filePrefix = isWindows ? "file:///" : "";
24
24
  var clientOutputPath = "";
@@ -85,7 +85,8 @@ function nitro(pluginOptions = {}) {
85
85
  const serverFnHandlers = hasServerFns ? [getServerFnDispatchHandler()] : [];
86
86
  const serverFnVirtual = serverFnModules.length > 0 ? { [SERVER_FN_DISPATCH_VIRTUAL]: buildServerFnDispatchModule({
87
87
  modules: serverFnModules,
88
- appConfigModule: serverFnAppConfigModule
88
+ appConfigModule: serverFnAppConfigModule,
89
+ root: resolve(workspaceRoot, rootDir)
89
90
  }) } : {};
90
91
  nitroConfig = {
91
92
  rootDir,
@@ -170,7 +171,7 @@ function nitro(pluginOptions = {}) {
170
171
  });
171
172
  return prev;
172
173
  }, []);
173
- if (options?.i18n && nitroConfig.prerender?.routes) nitroConfig.prerender.routes = expandRoutesWithLocales(nitroConfig.prerender.routes.filter(Boolean), options.i18n);
174
+ if (options?.i18n && nitroConfig.prerender?.routes) nitroConfig.prerender.routes = expandRoutesWithLocales(nitroConfig.prerender.routes.filter(Boolean), options.i18n, apiPrefix);
174
175
  }
175
176
  if (options?.i18n) {
176
177
  options.prerender = options.prerender ?? {};
@@ -232,13 +233,11 @@ function nitro(pluginOptions = {}) {
232
233
  ...nitroConfig.alias,
233
234
  "#analog/ssr": ssrEntry
234
235
  };
235
- await buildServer(options, nitroConfig, routeSourceFiles, i18nWorkers);
236
236
  if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
237
- const publicDir = nitroConfig.output?.publicDir;
238
- if (!publicDir) throw new Error("Nitro public output directory is required to build the sitemap.");
239
237
  console.log("Building Sitemap...");
240
- await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, publicDir, routeSitemaps, options.i18n);
238
+ await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, clientOutputPath, routeSitemaps, options.i18n, apiPrefix);
241
239
  }
240
+ await buildServer(options, nitroConfig, routeSourceFiles, i18nWorkers);
242
241
  console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
243
242
  }
244
243
  }
@@ -281,7 +280,7 @@ function nitro(pluginOptions = {}) {
281
280
  }
282
281
  if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
283
282
  console.log("Building Sitemap...");
284
- await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, clientOutputPath, routeSitemaps, options.i18n);
283
+ await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, clientOutputPath, routeSitemaps, options.i18n, apiPrefix);
285
284
  }
286
285
  let ssrEntryPath = resolve(options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, `ssr`), `main.server${filePrefix ? ".js" : ""}`);
287
286
  if (isWindows && !existsSync(ssrEntryPath)) ssrEntryPath = ssrEntryPath.replace(".js", ".mjs");
@@ -401,8 +400,9 @@ function getAnalogOptions(userConfig) {
401
400
  return (userConfig.plugins ?? []).flat(Infinity).find((plugin) => plugin?.api?.analogOptions)?.api?.analogOptions;
402
401
  }
403
402
  /**
404
- * Stamps `ssr: false` and `streaming: false` route rules as response headers,
405
- * which the renderers read to skip SSR or streaming for matching routes.
403
+ * Stamps `ssr` and `streaming` route rules as response headers, which the
404
+ * renderers read to skip SSR or streaming for matching routes. `true` rules
405
+ * stamp `'false'` so they override a broader `false` rule.
406
406
  */
407
407
  function withAnalogRouteRuleHeaders(nitroOptions) {
408
408
  if (!nitroOptions.routeRules) return nitroOptions;
@@ -410,8 +410,8 @@ function withAnalogRouteRuleHeaders(nitroOptions) {
410
410
  ...rule,
411
411
  headers: {
412
412
  ...rule.headers,
413
- ...rule.ssr === false ? { "x-analog-no-ssr": "true" } : {},
414
- ...rule.streaming === false ? { "x-analog-no-streaming": "true" } : {}
413
+ ...typeof rule.ssr === "boolean" ? { "x-analog-no-ssr": String(!rule.ssr) } : {},
414
+ ...typeof rule.streaming === "boolean" ? { "x-analog-no-streaming": String(!rule.streaming) } : {}
415
415
  }
416
416
  }]));
417
417
  return {
@@ -419,7 +419,6 @@ function withAnalogRouteRuleHeaders(nitroOptions) {
419
419
  routeRules
420
420
  };
421
421
  }
422
- //#endregion
423
422
  export { nitro };
424
423
 
425
424
  //# sourceMappingURL=vite-plugin-nitro.js.map
@@ -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,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,C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ACN,GAAG,aAAa;EAChB,KAAK,cAAc,QAAQ,eAAe,mBAAmB,CAAC;CAChE;AACF;;;;;AAMA,SAAS,iBAAiB,YAA6C;CAMrE,QALkB,WAAW,WAAW,CAAC,EAAA,CAAiB,KAAK,QAKxD,CAAA,CAAQ,MAAM,WAAW,QAAQ,KAAK,aAAa,CAAC,EAAE,KACzD;AACN;;;;;AAMA,SAAS,2BAA2B,cAAwC;CAC1E,IAAI,CAAC,aAAa,YAChB,OAAO;CAGT,MAAM,aAAa,OAAO,YACxB,OAAO,QAAQ,aAAa,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAC7D,OACA;EACE,GAAG;EACH,SAAS;GACP,GAAG,KAAK;GACR,GAAI,KAAK,QAAQ,QAAQ,EAAE,mBAAmB,OAAO,IAAI,CAAC;GAC1D,GAAI,KAAK,cAAc,QACnB,EAAE,yBAAyB,OAAO,IAClC,CAAC;EACP;CACF,CACF,CAAC,CACH;CAEA,OAAO;EAAE,GAAG;EAAc;CAAW;AACvC"}
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 root: resolve(workspaceRoot, rootDir),\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 apiPrefix,\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 if (\n nitroConfig.prerender?.routes?.length &&\n options?.prerender?.sitemap\n ) {\n console.log('Building Sitemap...');\n // build before the server so Nitro includes it in its public assets\n await buildSitemap(\n config,\n options.prerender.sitemap,\n nitroConfig.prerender.routes,\n clientOutputPath,\n routeSitemaps,\n options.i18n,\n apiPrefix,\n );\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 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 apiPrefix,\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` and `streaming` route rules as response headers, which the\n * renderers read to skip SSR or streaming for matching routes. `true` rules\n * stamp `'false'` so they override a broader `false` rule.\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 ...(typeof rule.ssr === 'boolean'\n ? { 'x-analog-no-ssr': String(!rule.ssr) }\n : {}),\n ...(typeof rule.streaming === 'boolean'\n ? { 'x-analog-no-streaming': String(!rule.streaming) }\n : {}),\n },\n },\n ]),\n );\n\n return { ...nitroOptions, routeRules };\n}\n"],"mappings":";;;;;;;;;;;;;;;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