@analogjs/vite-plugin-nitro 3.0.0-alpha.7 → 3.0.0-alpha.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/package.json +31 -11
  2. package/src/index.d.ts +19 -9
  3. package/src/index.js +9 -2
  4. package/src/index.js.map +1 -1
  5. package/src/lib/build-server.d.ts +2 -2
  6. package/src/lib/build-server.js +45 -149
  7. package/src/lib/build-server.js.map +1 -1
  8. package/src/lib/build-sitemap.d.ts +23 -9
  9. package/src/lib/build-sitemap.js +132 -63
  10. package/src/lib/build-sitemap.js.map +1 -1
  11. package/src/lib/build-ssr.d.ts +3 -2
  12. package/src/lib/build-ssr.js +26 -18
  13. package/src/lib/build-ssr.js.map +1 -1
  14. package/src/lib/hooks/post-rendering-hook.d.ts +1 -1
  15. package/src/lib/hooks/post-rendering-hook.js +10 -6
  16. package/src/lib/hooks/post-rendering-hook.js.map +1 -1
  17. package/src/lib/options.d.ts +148 -106
  18. package/src/lib/plugins/dev-server-plugin.d.ts +3 -3
  19. package/src/lib/plugins/dev-server-plugin.js +99 -101
  20. package/src/lib/plugins/dev-server-plugin.js.map +1 -1
  21. package/src/lib/plugins/page-endpoints.d.ts +5 -5
  22. package/src/lib/plugins/page-endpoints.js +26 -46
  23. package/src/lib/plugins/page-endpoints.js.map +1 -1
  24. package/src/lib/plugins/server-fn-id-plugin.d.ts +11 -0
  25. package/src/lib/plugins/server-fn-id-plugin.js +27 -0
  26. package/src/lib/plugins/server-fn-id-plugin.js.map +1 -0
  27. package/src/lib/utils/debug.d.ts +5 -0
  28. package/src/lib/utils/debug.js +15 -0
  29. package/src/lib/utils/debug.js.map +1 -0
  30. package/src/lib/utils/derive-server-fn-id.d.ts +25 -0
  31. package/src/lib/utils/derive-server-fn-id.js +37 -0
  32. package/src/lib/utils/derive-server-fn-id.js.map +1 -0
  33. package/src/lib/utils/get-content-files.d.ts +55 -55
  34. package/src/lib/utils/get-content-files.js +95 -97
  35. package/src/lib/utils/get-content-files.js.map +1 -1
  36. package/src/lib/utils/get-page-handlers.d.ts +55 -58
  37. package/src/lib/utils/get-page-handlers.js +67 -84
  38. package/src/lib/utils/get-page-handlers.js.map +1 -1
  39. package/src/lib/utils/get-server-fn-handlers.d.ts +28 -0
  40. package/src/lib/utils/get-server-fn-handlers.js +45 -0
  41. package/src/lib/utils/get-server-fn-handlers.js.map +1 -0
  42. package/src/lib/utils/i18n-prerender.d.ts +36 -0
  43. package/src/lib/utils/i18n-prerender.js +23 -0
  44. package/src/lib/utils/i18n-prerender.js.map +1 -0
  45. package/src/lib/utils/inject-server-fn-ids.d.ts +17 -0
  46. package/src/lib/utils/inject-server-fn-ids.js +94 -0
  47. package/src/lib/utils/inject-server-fn-ids.js.map +1 -0
  48. package/src/lib/utils/load-esm.d.ts +18 -18
  49. package/src/lib/utils/node-web-bridge.d.ts +1 -1
  50. package/src/lib/utils/node-web-bridge.js +50 -45
  51. package/src/lib/utils/node-web-bridge.js.map +1 -1
  52. package/src/lib/utils/register-dev-middleware.d.ts +12 -12
  53. package/src/lib/utils/register-dev-middleware.js +41 -47
  54. package/src/lib/utils/register-dev-middleware.js.map +1 -1
  55. package/src/lib/utils/register-i18n-watcher.d.ts +15 -0
  56. package/src/lib/utils/register-i18n-watcher.js +27 -0
  57. package/src/lib/utils/register-i18n-watcher.js.map +1 -0
  58. package/src/lib/utils/renderers.d.ts +29 -49
  59. package/src/lib/utils/renderers.js +37 -80
  60. package/src/lib/utils/renderers.js.map +1 -1
  61. package/src/lib/utils/rolldown.d.ts +2 -0
  62. package/src/lib/utils/rolldown.js +12 -0
  63. package/src/lib/utils/rolldown.js.map +1 -0
  64. package/src/lib/utils/server-fn-endpoints.d.ts +41 -0
  65. package/src/lib/utils/server-fn-endpoints.js +57 -0
  66. package/src/lib/utils/server-fn-endpoints.js.map +1 -0
  67. package/src/lib/vite-plugin-nitro.d.ts +3 -3
  68. package/src/lib/vite-plugin-nitro.js +793 -678
  69. package/src/lib/vite-plugin-nitro.js.map +1 -1
  70. package/README.md +0 -125
  71. package/src/lib/options.js +0 -2
  72. package/src/lib/options.js.map +0 -1
  73. package/src/lib/utils/load-esm.js +0 -23
  74. package/src/lib/utils/load-esm.js.map +0 -1
@@ -1,705 +1,820 @@
1
- import { build, createDevServer, createNitro } from 'nitro/builder';
2
- import * as vite from 'vite';
3
- import { mergeConfig, normalizePath } from 'vite';
4
- import { relative, resolve } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
- import { existsSync, readFileSync } from 'node:fs';
7
- import { buildServer, isVercelPreset } from './build-server.js';
8
- import { buildSSRApp } from './build-ssr.js';
9
- import { pageEndpointsPlugin } from './plugins/page-endpoints.js';
10
- import { getPageHandlers } from './utils/get-page-handlers.js';
11
- import { buildSitemap } from './build-sitemap.js';
12
- import { devServerPlugin } from './plugins/dev-server-plugin.js';
13
- import { toWebRequest, writeWebResponseToNode, } from './utils/node-web-bridge.js';
14
- import { getMatchingContentFilesWithFrontMatter } from './utils/get-content-files.js';
15
- import { ssrRenderer, clientRenderer, apiMiddleware, } from './utils/renderers.js';
16
- function createNitroMiddlewareHandler(handler) {
17
- return {
18
- route: '/**',
19
- handler,
20
- middleware: true,
21
- };
1
+ import { buildServer, isVercelPreset } from "./build-server.js";
2
+ import { getBundleOptionsKey, isRolldown } from "./utils/rolldown.js";
3
+ import { buildClientApp, buildSSRApp } from "./build-ssr.js";
4
+ import { clientRenderer, ssrRenderer } from "./utils/renderers.js";
5
+ import { pageEndpointsPlugin } from "./plugins/page-endpoints.js";
6
+ import { serverFnIdPlugin } from "./plugins/server-fn-id-plugin.js";
7
+ import { getPageHandlers } from "./utils/get-page-handlers.js";
8
+ import { getServerFnHandlers } from "./utils/get-server-fn-handlers.js";
9
+ import { buildServerFnDispatchModule, getServerFnDispatchHandler } from "./utils/server-fn-endpoints.js";
10
+ import { buildSitemap } from "./build-sitemap.js";
11
+ import { toWebRequest, writeWebResponseToNode } from "./utils/node-web-bridge.js";
12
+ import { devServerPlugin } from "./plugins/dev-server-plugin.js";
13
+ import { getMatchingContentFilesWithFrontMatter } from "./utils/get-content-files.js";
14
+ import { debugNitro, debugSsr } from "./utils/debug.js";
15
+ import { build, createDevServer, createNitro } from "nitro/builder";
16
+ import { mergeConfig, normalizePath } from "vite";
17
+ import { relative, resolve } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
20
+ //#region packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
21
+ function isObjectHook(value) {
22
+ return !!value && typeof value === "object" && "handler" in value;
23
+ }
24
+ function cloneObjectHook(hook) {
25
+ if (!isObjectHook(hook)) return hook;
26
+ return {
27
+ ...hook,
28
+ handler: hook.handler
29
+ };
30
+ }
31
+ function cloneUserPlugin(plugin) {
32
+ if (!plugin || typeof plugin !== "object") return plugin;
33
+ const pluginRecord = plugin;
34
+ const clone = Object.assign(Object.create(Object.getPrototypeOf(plugin)), pluginRecord);
35
+ for (const key of Object.keys(pluginRecord)) clone[key] = cloneObjectHook(pluginRecord[key]);
36
+ return clone;
37
+ }
38
+ function cloneEnvironmentEntries(environments) {
39
+ if (!environments || typeof environments !== "object") return environments;
40
+ return Object.fromEntries(Object.entries(environments).map(([name, environment]) => {
41
+ if (!environment || typeof environment !== "object") return [name, environment];
42
+ const environmentRecord = environment;
43
+ return [name, {
44
+ ...environmentRecord,
45
+ build: environmentRecord["build"] && typeof environmentRecord["build"] === "object" ? { ...environmentRecord["build"] } : environmentRecord["build"]
46
+ }];
47
+ }));
48
+ }
49
+ function cloneUserConfig(userConfig) {
50
+ const { environments, resolve, build, server, plugins } = userConfig;
51
+ const test = userConfig.test;
52
+ return {
53
+ ...userConfig,
54
+ plugins: plugins?.map(cloneUserPlugin),
55
+ build: build && { ...build },
56
+ environments: cloneEnvironmentEntries(environments),
57
+ server: server && { ...server },
58
+ test: test && { ...test },
59
+ resolve: resolve && {
60
+ ...resolve,
61
+ alias: Array.isArray(resolve.alias) ? [...resolve.alias] : resolve.alias && typeof resolve.alias === "object" ? { ...resolve.alias } : resolve.alias
62
+ }
63
+ };
22
64
  }
23
65
  /**
24
- * Creates a `rollup:before` hook that marks specified packages as external
25
- * in Nitro's bundler config (applied to both the server build and the
26
- * prerender build).
27
- *
28
- * ## Subpath matching (Rolldown compatibility)
29
- *
30
- * When `bundlerConfig.external` is an **array**, Rollup automatically
31
- * prefix-matches entries — `'rxjs'` in the array will also externalise
32
- * `'rxjs/operators'`, `'rxjs/internal/Observable'`, etc.
33
- *
34
- * Rolldown (the default bundler in Nitro v3) does **not** do this. It
35
- * treats array entries as exact strings. To keep behaviour consistent
36
- * across both bundlers, the **function** branch already needed explicit
37
- * subpath matching. We now use the same `isExternal` helper for all
38
- * branches so that `'rxjs'` reliably matches `'rxjs/operators'`
39
- * regardless of whether the existing `external` value is a function,
40
- * array, or absent.
41
- *
42
- * Without this, the Nitro prerender build fails on Windows CI with:
43
- *
44
- * [RESOLVE_ERROR] Could not resolve 'rxjs/operators'
45
- */
66
+ * Creates a `rollup:before` hook that marks specified packages as external
67
+ * in Nitro's bundler config (applied to both the server build and the
68
+ * prerender build).
69
+ *
70
+ * ## Subpath matching (Rolldown compatibility)
71
+ *
72
+ * When `bundlerConfig.external` is an **array**, Rollup automatically
73
+ * prefix-matches entries — `'rxjs'` in the array will also externalise
74
+ * `'rxjs/operators'`, `'rxjs/internal/Observable'`, etc.
75
+ *
76
+ * Rolldown (the default bundler in Nitro v3) does **not** do this. It
77
+ * treats array entries as exact strings. To keep behaviour consistent
78
+ * across both bundlers, the **function** branch already needed explicit
79
+ * subpath matching. We now use the same `isExternal` helper for all
80
+ * branches so that `'rxjs'` reliably matches `'rxjs/operators'`
81
+ * regardless of whether the existing `external` value is a function,
82
+ * array, or absent.
83
+ *
84
+ * Without this, the Nitro prerender build fails on Windows CI with:
85
+ *
86
+ * [RESOLVE_ERROR] Could not resolve 'rxjs/operators'
87
+ */
46
88
  function createRollupBeforeHook(externalEntries) {
47
- const isExternal = (source) => externalEntries.some((entry) => source === entry || source.startsWith(entry + '/'));
48
- return (_nitro, bundlerConfig) => {
49
- sanitizeNitroBundlerConfig(_nitro, bundlerConfig);
50
- if (externalEntries.length === 0) {
51
- return;
52
- }
53
- const existing = bundlerConfig.external;
54
- if (!existing) {
55
- bundlerConfig.external = externalEntries;
56
- }
57
- else if (typeof existing === 'function') {
58
- bundlerConfig.external = (source, importer, isResolved) => existing(source, importer, isResolved) || isExternal(source);
59
- }
60
- else if (Array.isArray(existing)) {
61
- bundlerConfig.external = [...existing, ...externalEntries];
62
- }
63
- else {
64
- bundlerConfig.external = [existing, ...externalEntries];
65
- }
66
- };
89
+ const isExternal = (source) => externalEntries.some((entry) => source === entry || source.startsWith(entry + "/"));
90
+ return (_nitro, bundlerConfig) => {
91
+ sanitizeNitroBundlerConfig(_nitro, bundlerConfig);
92
+ if (externalEntries.length === 0) return;
93
+ const existing = bundlerConfig.external;
94
+ if (!existing) bundlerConfig.external = externalEntries;
95
+ else if (typeof existing === "function") bundlerConfig.external = (source, importer, isResolved) => existing(source, importer, isResolved) || isExternal(source);
96
+ else if (Array.isArray(existing)) bundlerConfig.external = [...existing, ...externalEntries];
97
+ else bundlerConfig.external = [existing, ...externalEntries];
98
+ };
67
99
  }
68
100
  function appendNoExternals(noExternals, ...entries) {
69
- if (!noExternals) {
70
- return entries;
71
- }
72
- return Array.isArray(noExternals)
73
- ? [...noExternals, ...entries]
74
- : noExternals;
101
+ if (!noExternals) return entries;
102
+ return Array.isArray(noExternals) ? [...noExternals, ...entries] : noExternals;
75
103
  }
76
104
  /**
77
- * Patches Nitro's internal Rollup/Rolldown bundler config to work around
78
- * incompatibilities in the Nitro v3 alpha series.
79
- *
80
- * Called from the `rollup:before` hook, this function runs against the *final*
81
- * bundler config that Nitro assembles for its server/prerender builds — it
82
- * does NOT touch the normal Vite client or SSR environment configs.
83
- *
84
- * Each workaround is narrowly scoped and safe to remove once the corresponding
85
- * upstream Nitro issue is resolved.
86
- */
105
+ * Patches Nitro's internal Rollup/Rolldown bundler config to work around
106
+ * incompatibilities in the Nitro v3 alpha series.
107
+ *
108
+ * Called from the `rollup:before` hook, this function runs against the *final*
109
+ * bundler config that Nitro assembles for its server/prerender builds — it
110
+ * does NOT touch the normal Vite client or SSR environment configs.
111
+ *
112
+ * Each workaround is narrowly scoped and safe to remove once the corresponding
113
+ * upstream Nitro issue is resolved.
114
+ */
87
115
  function sanitizeNitroBundlerConfig(_nitro, bundlerConfig) {
88
- const output = bundlerConfig['output'];
89
- if (!output || Array.isArray(output) || typeof output !== 'object') {
90
- return;
91
- }
92
- // ── 1. Remove invalid `output.codeSplitting` ────────────────────────
93
- //
94
- // Nitro 3.0.1-alpha.2 adds `output.codeSplitting` to its internal bundler
95
- // config, but Rolldown rejects it as an unknown key:
96
- //
97
- // Warning: Invalid output options (1 issue found)
98
- // - For the "codeSplitting". Invalid key: Expected never but received "codeSplitting".
99
- //
100
- // Analog never sets this option. Removing it restores default bundler
101
- // behavior without changing any Analog semantics.
102
- if ('codeSplitting' in output) {
103
- delete output['codeSplitting'];
104
- }
105
- // ── 2. Remove invalid `output.manualChunks` ─────────────────────────
106
- //
107
- // Nitro's default config enables manual chunking for node_modules. Under
108
- // Nitro v3 alpha + Rollup 4.59 this crashes during the prerender rebundle:
109
- //
110
- // Cannot read properties of undefined (reading 'included')
111
- //
112
- // A single server bundle is acceptable for Analog's use case, so we strip
113
- // `manualChunks` until the upstream bug is fixed.
114
- if ('manualChunks' in output) {
115
- delete output['manualChunks'];
116
- }
117
- // ── 3. Escape route params in `output.chunkFileNames` ───────────────
118
- //
119
- // Nitro's `getChunkName()` derives chunk filenames from route patterns,
120
- // using its internal `routeToFsPath()` helper to convert route params
121
- // (`:productId` → `[productId]`) and catch-alls (`**` → `[...]`).
122
- //
123
- // Rollup/Rolldown interprets *any* `[token]` in the string returned by a
124
- // `chunkFileNames` function as a placeholder. Only a handful are valid —
125
- // `[name]`, `[hash]`, `[format]`, `[ext]` — so route-derived tokens like
126
- // `[productId]` or `[...]` trigger a build error:
127
- //
128
- // "[productId]" is not a valid placeholder in the "output.chunkFileNames" pattern.
129
- //
130
- // We wrap the original function to replace non-standard `[token]` patterns
131
- // with `_token_`, preserving the intended filename while avoiding the
132
- // placeholder validation error.
133
- //
134
- // Example: `_routes/products/[productId].mjs` → `_routes/products/_productId_.mjs`
135
- const VALID_ROLLUP_PLACEHOLDER = /^\[(?:name|hash|format|ext)\]$/;
136
- const chunkFileNames = output['chunkFileNames'];
137
- if (typeof chunkFileNames === 'function') {
138
- const originalFn = chunkFileNames;
139
- output['chunkFileNames'] = (...args) => {
140
- const result = originalFn(...args);
141
- if (typeof result !== 'string')
142
- return result;
143
- return result.replace(/\[[^\]]+\]/g, (match) => VALID_ROLLUP_PLACEHOLDER.test(match)
144
- ? match
145
- : `_${match.slice(1, -1)}_`);
146
- };
147
- }
116
+ const output = bundlerConfig["output"];
117
+ if (!output || Array.isArray(output) || typeof output !== "object") return;
118
+ if ("codeSplitting" in output) delete output["codeSplitting"];
119
+ if ("manualChunks" in output) delete output["manualChunks"];
120
+ const VALID_ROLLUP_PLACEHOLDER = /^\[(?:name|hash|format|ext)\]$/;
121
+ const chunkFileNames = output["chunkFileNames"];
122
+ if (typeof chunkFileNames === "function") {
123
+ const originalFn = chunkFileNames;
124
+ output["chunkFileNames"] = (...args) => {
125
+ const result = originalFn(...args);
126
+ if (typeof result !== "string") return result;
127
+ return result.replace(/\[[^\]]+\]/g, (match) => VALID_ROLLUP_PLACEHOLDER.test(match) ? match : `_${match.slice(1, -1)}_`);
128
+ };
129
+ }
130
+ }
131
+ function resolveClientOutputPath(cachedPath, workspaceRoot, rootDir, configuredOutDir) {
132
+ if (cachedPath) {
133
+ debugNitro("resolveClientOutputPath using cached path", {
134
+ cachedPath,
135
+ workspaceRoot,
136
+ rootDir,
137
+ configuredOutDir
138
+ });
139
+ return cachedPath;
140
+ }
141
+ if (configuredOutDir) {
142
+ const resolvedPath = normalizePath(resolve(workspaceRoot, rootDir, configuredOutDir));
143
+ debugNitro("resolveClientOutputPath using configured build.outDir", {
144
+ workspaceRoot,
145
+ rootDir,
146
+ configuredOutDir,
147
+ resolvedPath
148
+ });
149
+ return resolvedPath;
150
+ }
151
+ const resolvedPath = normalizePath(resolve(workspaceRoot, "dist", rootDir, "client"));
152
+ debugNitro("resolveClientOutputPath using default dist client path", {
153
+ workspaceRoot,
154
+ rootDir,
155
+ configuredOutDir,
156
+ resolvedPath
157
+ });
158
+ return resolvedPath;
159
+ }
160
+ function getEnvironmentBuildOutDir(environment) {
161
+ if (!environment || typeof environment !== "object") return;
162
+ const environmentConfig = environment;
163
+ return environmentConfig.config?.build?.outDir ?? environmentConfig.build?.outDir;
164
+ }
165
+ function resolveBuiltClientOutputPath(cachedPath, workspaceRoot, rootDir, configuredOutDir, environment) {
166
+ const environmentOutDir = getEnvironmentBuildOutDir(environment);
167
+ if (environmentOutDir) {
168
+ const resolvedPath = normalizePath(resolve(workspaceRoot, rootDir, environmentOutDir));
169
+ debugNitro("resolveBuiltClientOutputPath using environment outDir", {
170
+ cachedPath,
171
+ workspaceRoot,
172
+ rootDir,
173
+ configuredOutDir,
174
+ environmentOutDir,
175
+ resolvedPath
176
+ });
177
+ return resolvedPath;
178
+ }
179
+ debugNitro("resolveBuiltClientOutputPath falling back to shared resolver", {
180
+ cachedPath,
181
+ workspaceRoot,
182
+ rootDir,
183
+ configuredOutDir,
184
+ environmentOutDir
185
+ });
186
+ return resolveClientOutputPath(cachedPath, workspaceRoot, rootDir, configuredOutDir);
148
187
  }
149
- function resolveClientOutputPath(cachedPath, workspaceRoot, rootDir, configuredOutDir, ssrBuild) {
150
- if (cachedPath) {
151
- return cachedPath;
152
- }
153
- if (!ssrBuild) {
154
- return resolve(workspaceRoot, rootDir, configuredOutDir || 'dist/client');
155
- }
156
- // SSR builds write server assets to dist/<app>/ssr, but the renderer template
157
- // still needs the client index.html emitted to dist/<app>/client.
158
- return resolve(workspaceRoot, 'dist', rootDir, 'client');
188
+ function getNitroPublicOutputDir(nitroConfig) {
189
+ const publicDir = nitroConfig.output?.publicDir;
190
+ if (!publicDir) throw new Error("Nitro public output directory is required to build the sitemap.");
191
+ return publicDir;
192
+ }
193
+ function readDirectoryEntries(path) {
194
+ try {
195
+ return readdirSync(path).sort();
196
+ } catch (error) {
197
+ return [`<<unable to read directory: ${error instanceof Error ? error.message : String(error)}>>`];
198
+ }
199
+ }
200
+ function getPathDebugInfo(path) {
201
+ return {
202
+ rawPath: path,
203
+ normalizedPath: normalizePath(path),
204
+ exists: existsSync(path),
205
+ entries: existsSync(path) ? readDirectoryEntries(path) : []
206
+ };
207
+ }
208
+ function assetSourceToString(source) {
209
+ return typeof source === "string" ? source : Buffer.from(source).toString("utf8");
210
+ }
211
+ function captureClientIndexHtmlFromBundle(bundle, hook) {
212
+ const indexHtmlAsset = Object.values(bundle).find((chunk) => chunk.type === "asset" && chunk.fileName === "index.html" && typeof chunk.source !== "undefined");
213
+ if (!indexHtmlAsset?.source) {
214
+ debugNitro(`client bundle did not expose index.html during ${hook}`, {
215
+ hook,
216
+ bundleKeys: Object.keys(bundle).sort(),
217
+ assetFileNames: Object.values(bundle).filter((chunk) => chunk.type === "asset").map((chunk) => chunk.fileName).filter(Boolean)
218
+ });
219
+ return;
220
+ }
221
+ const indexHtml = assetSourceToString(indexHtmlAsset.source);
222
+ debugNitro(`captured client bundle index.html asset during ${hook}`, {
223
+ hook,
224
+ fileName: indexHtmlAsset.fileName,
225
+ htmlLength: indexHtml.length
226
+ });
227
+ return indexHtml;
228
+ }
229
+ function registerIndexHtmlVirtual(nitroConfig, clientOutputPath, inlineIndexHtml) {
230
+ const indexHtmlPath = resolve(clientOutputPath, "index.html");
231
+ debugNitro("registerIndexHtmlVirtual inspecting client output", {
232
+ platform: process.platform,
233
+ cwd: process.cwd(),
234
+ clientOutputPath,
235
+ clientOutputPathInfo: getPathDebugInfo(clientOutputPath),
236
+ indexHtmlPath,
237
+ indexHtmlExists: existsSync(indexHtmlPath),
238
+ hasInlineIndexHtml: typeof inlineIndexHtml === "string"
239
+ });
240
+ if (!existsSync(indexHtmlPath) && typeof inlineIndexHtml !== "string") {
241
+ debugNitro("registerIndexHtmlVirtual missing index.html", {
242
+ platform: process.platform,
243
+ cwd: process.cwd(),
244
+ clientOutputPath,
245
+ clientOutputPathInfo: getPathDebugInfo(clientOutputPath),
246
+ indexHtmlPath,
247
+ hasInlineIndexHtml: typeof inlineIndexHtml === "string",
248
+ nitroOutput: nitroConfig.output,
249
+ nitroPublicAssets: nitroConfig.publicAssets
250
+ });
251
+ throw new Error(`[analog] Client build output not found at ${indexHtmlPath}.\nEnsure the client environment build completed successfully before the server build.`);
252
+ }
253
+ const indexHtml = typeof inlineIndexHtml === "string" ? inlineIndexHtml : readFileSync(indexHtmlPath, "utf8");
254
+ debugNitro("registerIndexHtmlVirtual using HTML template source", {
255
+ source: typeof inlineIndexHtml === "string" ? "captured client bundle asset" : "client output index.html file",
256
+ indexHtmlPath
257
+ });
258
+ nitroConfig.virtual = {
259
+ ...nitroConfig.virtual,
260
+ "#analog/index": `export default ${JSON.stringify(indexHtml)};`
261
+ };
159
262
  }
160
263
  /**
161
- * Converts the built SSR entry path into a specifier that Nitro's bundler
162
- * can resolve, including all relative `./assets/*` chunk imports inside
163
- * the entry.
164
- *
165
- * The returned path **must** be an absolute filesystem path with forward
166
- * slashes (e.g. `D:/a/analog/dist/apps/blog-app/ssr/main.server.js`).
167
- * This lets Rollup/Rolldown determine the entry's directory and resolve
168
- * sibling chunk imports like `./assets/core-DTazUigR.js` correctly.
169
- *
170
- * ## Why not pathToFileURL() on Windows?
171
- *
172
- * Earlier versions converted the path to a `file:///D:/a/...` URL on
173
- * Windows, which worked with Nitro v2 + Rollup. Nitro v3 switched its
174
- * default bundler to Rolldown, and Rolldown does **not** extract the
175
- * importer directory from `file://` URLs. This caused every relative
176
- * import inside the SSR entry to fail during the prerender build:
177
- *
178
- * [RESOLVE_ERROR] Could not resolve './assets/core-DTazUigR.js'
179
- * in ../../dist/apps/blog-app/ssr/main.server.js
180
- *
181
- * `normalizePath()` (from Vite) simply converts backslashes to forward
182
- * slashes, which both Rollup and Rolldown handle correctly on all
183
- * platforms.
184
- */
264
+ * Converts the built SSR entry path into a specifier that Nitro's bundler
265
+ * can resolve, including all relative `./assets/*` chunk imports inside
266
+ * the entry.
267
+ *
268
+ * The returned path **must** be an absolute filesystem path with forward
269
+ * slashes (e.g. `D:/a/analog/dist/apps/blog-app/ssr/main.server.js`).
270
+ * This lets Rollup/Rolldown determine the entry's directory and resolve
271
+ * sibling chunk imports like `./assets/core-DTazUigR.js` correctly.
272
+ *
273
+ * ## Why not pathToFileURL() on Windows?
274
+ *
275
+ * Earlier versions converted the path to a `file:///D:/a/...` URL on
276
+ * Windows, which worked with Nitro v2 + Rollup. Nitro v3 switched its
277
+ * default bundler to Rolldown, and Rolldown does **not** extract the
278
+ * importer directory from `file://` URLs. This caused every relative
279
+ * import inside the SSR entry to fail during the prerender build:
280
+ *
281
+ * [RESOLVE_ERROR] Could not resolve './assets/core-DTazUigR.js'
282
+ * in ../../dist/apps/blog-app/ssr/main.server.js
283
+ *
284
+ * `normalizePath()` (from Vite) simply converts backslashes to forward
285
+ * slashes, which both Rollup and Rolldown handle correctly on all
286
+ * platforms.
287
+ */
185
288
  function toNitroSsrEntrypointSpecifier(ssrEntryPath) {
186
- return normalizePath(ssrEntryPath);
289
+ return normalizePath(ssrEntryPath);
187
290
  }
188
291
  function applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir) {
189
- const ssrOutDir = options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr');
190
- if (options?.ssr || nitroConfig.prerender?.routes?.length) {
191
- const ssrEntryPath = resolveBuiltSsrEntryPath(ssrOutDir);
192
- const ssrEntry = toNitroSsrEntrypointSpecifier(ssrEntryPath);
193
- nitroConfig.alias = {
194
- ...nitroConfig.alias,
195
- '#analog/ssr': ssrEntry,
196
- };
197
- }
292
+ const ssrOutDir = options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr");
293
+ if (options?.ssr || nitroConfig.prerender?.routes?.length) {
294
+ const ssrEntry = toNitroSsrEntrypointSpecifier(resolveBuiltSsrEntryPath(ssrOutDir));
295
+ nitroConfig.alias = {
296
+ ...nitroConfig.alias,
297
+ "#analog/ssr": ssrEntry
298
+ };
299
+ }
198
300
  }
199
301
  function resolveBuiltSsrEntryPath(ssrOutDir) {
200
- const candidatePaths = [
201
- resolve(ssrOutDir, 'main.server.mjs'),
202
- resolve(ssrOutDir, 'main.server.js'),
203
- resolve(ssrOutDir, 'main.server'),
204
- ];
205
- const ssrEntryPath = candidatePaths.find((candidatePath) => existsSync(candidatePath));
206
- if (!ssrEntryPath) {
207
- throw new Error(`Unable to locate the built SSR entry in "${ssrOutDir}". Expected one of: ${candidatePaths.join(', ')}`);
208
- }
209
- return ssrEntryPath;
302
+ const candidatePaths = [
303
+ resolve(ssrOutDir, "main.server.mjs"),
304
+ resolve(ssrOutDir, "main.server.js"),
305
+ resolve(ssrOutDir, "main.server")
306
+ ];
307
+ const ssrEntryPath = candidatePaths.find((candidatePath) => existsSync(candidatePath));
308
+ if (!ssrEntryPath) throw new Error(`Unable to locate the built SSR entry in "${ssrOutDir}". Expected one of: ${candidatePaths.join(", ")}`);
309
+ return ssrEntryPath;
210
310
  }
211
- export function nitro(options, nitroOptions) {
212
- const workspaceRoot = options?.workspaceRoot ?? process.cwd();
213
- const sourceRoot = options?.sourceRoot ?? 'src';
214
- let isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
215
- const baseURL = process.env['NITRO_APP_BASE_URL'] || '';
216
- const prefix = baseURL ? baseURL.substring(0, baseURL.length - 1) : '';
217
- const apiPrefix = `/${options?.apiPrefix || 'api'}`;
218
- const useAPIMiddleware = typeof options?.useAPIMiddleware !== 'undefined'
219
- ? options?.useAPIMiddleware
220
- : true;
221
- let isBuild = false;
222
- let isServe = false;
223
- let ssrBuild = false;
224
- let config;
225
- let nitroConfig;
226
- let environmentBuild = false;
227
- let hasAPIDir = false;
228
- let clientOutputPath = '';
229
- let rendererIndexEntry = '';
230
- const rollupExternalEntries = [];
231
- const routeSitemaps = {};
232
- const routeSourceFiles = {};
233
- let rootDir = workspaceRoot;
234
- return [
235
- (options?.ssr
236
- ? devServerPlugin({
237
- entryServer: options?.entryServer,
238
- index: options?.index,
239
- routeRules: nitroOptions?.routeRules,
240
- })
241
- : false),
242
- {
243
- name: '@analogjs/vite-plugin-nitro',
244
- async config(userConfig, { mode, command }) {
245
- isServe = command === 'serve';
246
- isBuild = command === 'build';
247
- ssrBuild = userConfig.build?.ssr === true;
248
- config = userConfig;
249
- isTest = isTest ? isTest : mode === 'test';
250
- rootDir = relative(workspaceRoot, config.root || '.') || '.';
251
- hasAPIDir = existsSync(resolve(workspaceRoot, rootDir, `${sourceRoot}/server/routes/${options?.apiPrefix || 'api'}`));
252
- const buildPreset = process.env['BUILD_PRESET'] ??
253
- nitroOptions?.preset ??
254
- (process.env['VERCEL'] ? 'vercel' : undefined);
255
- const pageHandlers = getPageHandlers({
256
- workspaceRoot,
257
- sourceRoot,
258
- rootDir,
259
- additionalPagesDirs: options?.additionalPagesDirs,
260
- hasAPIDir,
261
- });
262
- const resolvedClientOutputPath = resolveClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir, ssrBuild);
263
- rendererIndexEntry = normalizePath(resolve(resolvedClientOutputPath, 'index.html'));
264
- nitroConfig = {
265
- rootDir: normalizePath(rootDir),
266
- preset: buildPreset,
267
- compatibilityDate: '2025-11-19',
268
- logLevel: nitroOptions?.logLevel || 0,
269
- serverDir: normalizePath(`${sourceRoot}/server`),
270
- scanDirs: [
271
- normalizePath(`${rootDir}/${sourceRoot}/server`),
272
- ...(options?.additionalAPIDirs || []).map((dir) => normalizePath(`${workspaceRoot}${dir}`)),
273
- ],
274
- output: {
275
- dir: normalizePath(resolve(workspaceRoot, 'dist', rootDir, 'analog')),
276
- publicDir: normalizePath(resolve(workspaceRoot, 'dist', rootDir, 'analog/public')),
277
- },
278
- buildDir: normalizePath(resolve(workspaceRoot, 'dist', rootDir, '.nitro')),
279
- typescript: {
280
- generateTsConfig: false,
281
- },
282
- runtimeConfig: {
283
- apiPrefix: apiPrefix.substring(1),
284
- prefix,
285
- },
286
- // Analog provides its own renderer handler; prevent Nitro v3 from
287
- // auto-detecting index.html in rootDir and adding a conflicting one.
288
- renderer: false,
289
- imports: {
290
- autoImport: false,
291
- },
292
- hooks: {
293
- 'rollup:before': createRollupBeforeHook(rollupExternalEntries),
294
- },
295
- rollupConfig: {
296
- onwarn(warning) {
297
- if (warning.message.includes('empty chunk') &&
298
- warning.message.endsWith('.server')) {
299
- return;
300
- }
301
- },
302
- plugins: [pageEndpointsPlugin()],
303
- },
304
- handlers: [
305
- ...(hasAPIDir
306
- ? []
307
- : useAPIMiddleware
308
- ? [createNitroMiddlewareHandler('#ANALOG_API_MIDDLEWARE')]
309
- : []),
310
- ...pageHandlers,
311
- ],
312
- routeRules: hasAPIDir
313
- ? undefined
314
- : useAPIMiddleware
315
- ? undefined
316
- : {
317
- [`${prefix}${apiPrefix}/**`]: {
318
- proxy: { to: '/**' },
319
- },
320
- },
321
- virtual: {
322
- '#ANALOG_SSR_RENDERER': ssrRenderer(rendererIndexEntry),
323
- '#ANALOG_CLIENT_RENDERER': clientRenderer(rendererIndexEntry),
324
- ...(hasAPIDir ? {} : { '#ANALOG_API_MIDDLEWARE': apiMiddleware }),
325
- },
326
- };
327
- if (isVercelPreset(buildPreset)) {
328
- nitroConfig = withVercelOutputAPI(nitroConfig, workspaceRoot);
329
- }
330
- if (isCloudflarePreset(buildPreset)) {
331
- nitroConfig = withCloudflareOutput(nitroConfig);
332
- }
333
- if (isNetlifyPreset(buildPreset) &&
334
- rootDir === '.' &&
335
- !existsSync(resolve(workspaceRoot, 'netlify.toml'))) {
336
- nitroConfig = withNetlifyOutputAPI(nitroConfig, workspaceRoot);
337
- }
338
- if (isFirebaseAppHosting()) {
339
- nitroConfig = withAppHostingOutput(nitroConfig);
340
- }
341
- if (!ssrBuild && !isTest) {
342
- // store the client output path for the SSR build config
343
- clientOutputPath = resolvedClientOutputPath;
344
- }
345
- if (isBuild) {
346
- nitroConfig.publicAssets = [
347
- { dir: normalizePath(clientOutputPath), maxAge: 0 },
348
- ];
349
- // In Nitro v3, renderer.entry is resolved via resolveModulePath()
350
- // during options normalization, which requires a real filesystem path.
351
- // Virtual modules (prefixed with #) can't survive this resolution.
352
- // Instead, we add the renderer as a catch-all handler directly —
353
- // this is functionally equivalent to what Nitro does internally
354
- // (it converts renderer.entry into a { route: '/**', lazy: true }
355
- // handler), but avoids the filesystem resolution step.
356
- const rendererHandler = options?.ssr
357
- ? '#ANALOG_SSR_RENDERER'
358
- : '#ANALOG_CLIENT_RENDERER';
359
- nitroConfig.handlers = [
360
- ...(nitroConfig.handlers || []),
361
- {
362
- handler: rendererHandler,
363
- route: '/**',
364
- lazy: true,
365
- },
366
- ];
367
- if (isEmptyPrerenderRoutes(options)) {
368
- nitroConfig.prerender = {};
369
- nitroConfig.prerender.routes = ['/'];
370
- }
371
- if (options?.prerender) {
372
- nitroConfig.prerender = nitroConfig.prerender ?? {};
373
- nitroConfig.prerender.crawlLinks = options?.prerender?.discover;
374
- let routes = [];
375
- const prerenderRoutes = options?.prerender?.routes;
376
- if (isArrayWithElements(prerenderRoutes)) {
377
- routes = prerenderRoutes;
378
- }
379
- else if (typeof prerenderRoutes === 'function') {
380
- routes = await prerenderRoutes();
381
- }
382
- nitroConfig.prerender.routes = routes.reduce((prev, current) => {
383
- if (!current) {
384
- return prev;
385
- }
386
- if (typeof current === 'string') {
387
- prev.push(current);
388
- return prev;
389
- }
390
- if ('route' in current) {
391
- if (current.sitemap) {
392
- routeSitemaps[current.route] = current.sitemap;
393
- }
394
- if (current.outputSourceFile) {
395
- const sourcePath = resolve(workspaceRoot, rootDir, current.outputSourceFile);
396
- routeSourceFiles[current.route] = readFileSync(sourcePath, 'utf8');
397
- }
398
- prev.push(current.route);
399
- // Add the server-side data fetching endpoint URL
400
- if ('staticData' in current) {
401
- prev.push(`${apiPrefix}/_analog/pages/${current.route}`);
402
- }
403
- return prev;
404
- }
405
- const affectedFiles = getMatchingContentFilesWithFrontMatter(workspaceRoot, rootDir, current.contentDir);
406
- affectedFiles.forEach((f) => {
407
- const result = current.transform(f);
408
- if (result) {
409
- if (current.sitemap) {
410
- routeSitemaps[result] =
411
- current.sitemap && typeof current.sitemap === 'function'
412
- ? current.sitemap?.(f)
413
- : current.sitemap;
414
- }
415
- if (current.outputSourceFile) {
416
- const sourceContent = current.outputSourceFile(f);
417
- if (sourceContent) {
418
- routeSourceFiles[result] = sourceContent;
419
- }
420
- }
421
- prev.push(result);
422
- // Add the server-side data fetching endpoint URL
423
- if ('staticData' in current) {
424
- prev.push(`${apiPrefix}/_analog/pages/${result}`);
425
- }
426
- }
427
- });
428
- return prev;
429
- }, []);
430
- }
431
- // ── SSR / prerender Nitro config ─────────────────────────────
432
- //
433
- // This block configures Nitro for builds that rebundle the SSR
434
- // entry (main.server.{js,mjs}). That happens in two cases:
435
- //
436
- // 1. Full SSR apps — `options.ssr === true`
437
- // 2. Prerender-only — no runtime SSR, but the prerender build
438
- // still imports the SSR entry to render static pages.
439
- //
440
- // The original gate was `if (ssrBuild)`, which checks the Vite
441
- // top-level `build.ssr` flag. That worked with the legacy
442
- // single-pass build but breaks with two newer code paths:
443
- //
444
- // a. **Vite Environment API (Vite 6+)** — SSR config lives in
445
- // `environments.ssr.build.ssr`, not `build.ssr`, so
446
- // `ssrBuild` is always `false`.
447
- // b. **Prerender-only apps** (e.g. blog-app) — `options.ssr`
448
- // is `false`, but prerender routes exist and the prerender
449
- // build still processes the SSR entry.
450
- //
451
- // Without this block:
452
- // - `rxjs` is never externalised → RESOLVE_ERROR in the
453
- // Nitro prerender build (especially on Windows CI).
454
- // - `moduleSideEffects` for zone.js is never set → zone.js
455
- // side-effects may be tree-shaken.
456
- // - The handlers list is not reassembled with page endpoints
457
- // + the renderer catch-all.
458
- //
459
- // The widened condition covers all three code paths:
460
- // - `ssrBuild` → legacy closeBundle
461
- // - `options?.ssr` → Environment API SSR
462
- // - `nitroConfig.prerender?.routes?.length` → prerender-only
463
- if (ssrBuild ||
464
- options?.ssr ||
465
- nitroConfig.prerender?.routes?.length) {
466
- if (process.platform === 'win32') {
467
- nitroConfig.noExternals = appendNoExternals(nitroConfig.noExternals, 'std-env');
468
- }
469
- rollupExternalEntries.push('rxjs', 'node-fetch-native/dist/polyfill');
470
- nitroConfig = {
471
- ...nitroConfig,
472
- moduleSideEffects: ['zone.js/node', 'zone.js/fesm2015/zone-node'],
473
- handlers: [
474
- ...(hasAPIDir
475
- ? []
476
- : useAPIMiddleware
477
- ? [createNitroMiddlewareHandler('#ANALOG_API_MIDDLEWARE')]
478
- : []),
479
- ...pageHandlers,
480
- // Preserve the renderer catch-all handler added above
481
- {
482
- handler: rendererHandler,
483
- route: '/**',
484
- lazy: true,
485
- },
486
- ],
487
- };
488
- }
489
- }
490
- nitroConfig = mergeConfig(nitroConfig, nitroOptions);
491
- return {
492
- environments: {
493
- client: {
494
- build: {
495
- outDir: config?.build?.outDir ||
496
- resolve(workspaceRoot, 'dist', rootDir, 'client'),
497
- },
498
- },
499
- ssr: {
500
- build: {
501
- ssr: true,
502
- [vite.rolldownVersion ? 'rolldownOptions' : 'rollupOptions']: {
503
- input: options?.entryServer ||
504
- resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),
505
- },
506
- outDir: options?.ssrBuildDir ||
507
- resolve(workspaceRoot, 'dist', rootDir, 'ssr'),
508
- },
509
- },
510
- },
511
- builder: {
512
- sharedPlugins: true,
513
- buildApp: async (builder) => {
514
- environmentBuild = true;
515
- const builds = [builder.build(builder.environments['client'])];
516
- if (options?.ssr || nitroConfig.prerender?.routes?.length) {
517
- builds.push(builder.build(builder.environments['ssr']));
518
- }
519
- await Promise.all(builds);
520
- applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
521
- await buildServer(options, nitroConfig, routeSourceFiles);
522
- if (nitroConfig.prerender?.routes?.length &&
523
- options?.prerender?.sitemap) {
524
- const publicDir = nitroConfig.output?.publicDir;
525
- if (!publicDir) {
526
- throw new Error('Nitro public output directory is required to build the sitemap.');
527
- }
528
- console.log('Building Sitemap...');
529
- // sitemap needs to be built after all directories are built
530
- await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, publicDir, routeSitemaps);
531
- }
532
- console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
533
- },
534
- },
535
- };
536
- },
537
- async configureServer(viteServer) {
538
- if (isServe && !isTest) {
539
- const nitro = await createNitro({
540
- dev: true,
541
- // Nitro's Vite builder now rejects `build()` in dev mode, but Analog's
542
- // dev integration still relies on the builder-driven reload hooks.
543
- // Force the server worker onto Rollup for this dev-only path.
544
- builder: 'rollup',
545
- ...nitroConfig,
546
- });
547
- const server = createDevServer(nitro);
548
- await build(nitro);
549
- const apiHandler = async (req, res) => {
550
- // Nitro v3's dev server is fetch-first, so adapt Vite's Node
551
- // request once and let Nitro respond with a standard Web Response.
552
- const response = await server.fetch(toWebRequest(req));
553
- await writeWebResponseToNode(res, response);
554
- };
555
- if (hasAPIDir) {
556
- viteServer.middlewares.use((req, res, next) => {
557
- if (req.url?.startsWith(`${prefix}${apiPrefix}`)) {
558
- void apiHandler(req, res).catch((error) => next(error));
559
- return;
560
- }
561
- next();
562
- });
563
- }
564
- else {
565
- viteServer.middlewares.use(apiPrefix, (req, res, next) => {
566
- void apiHandler(req, res).catch((error) => next(error));
567
- });
568
- }
569
- viteServer.httpServer?.once('listening', () => {
570
- process.env['ANALOG_HOST'] = !viteServer.config.server.host
571
- ? 'localhost'
572
- : viteServer.config.server.host;
573
- process.env['ANALOG_PORT'] = `${viteServer.config.server.port}`;
574
- });
575
- // handle upgrades if websockets are enabled
576
- if (nitroOptions?.experimental?.websocket) {
577
- viteServer.httpServer?.on('upgrade', server.upgrade);
578
- }
579
- console.log(`\n\nThe server endpoints are accessible under the "${prefix}${apiPrefix}" path.`);
580
- }
581
- },
582
- async closeBundle() {
583
- // Skip when build is triggered by the Environment API
584
- if (environmentBuild) {
585
- return;
586
- }
587
- if (ssrBuild) {
588
- return;
589
- }
590
- if (isBuild) {
591
- if (options?.ssr) {
592
- console.log('Building SSR application...');
593
- await buildSSRApp(config, options);
594
- }
595
- if (nitroConfig.prerender?.routes?.length &&
596
- options?.prerender?.sitemap) {
597
- console.log('Building Sitemap...');
598
- // sitemap needs to be built after all directories are built
599
- await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, clientOutputPath, routeSitemaps);
600
- }
601
- applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
602
- await buildServer(options, nitroConfig, routeSourceFiles);
603
- console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
604
- }
605
- },
606
- },
607
- {
608
- name: '@analogjs/vite-plugin-nitro-api-prefix',
609
- config() {
610
- return {
611
- define: {
612
- ANALOG_API_PREFIX: `"${baseURL.substring(1)}${apiPrefix.substring(1)}"`,
613
- },
614
- };
615
- },
616
- },
617
- ];
311
+ function nitro(options, nitroOptions) {
312
+ const workspaceRoot = options?.workspaceRoot ?? process.cwd();
313
+ const sourceRoot = options?.sourceRoot ?? "src";
314
+ let isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
315
+ const baseURL = process.env["NITRO_APP_BASE_URL"] || "";
316
+ const prefix = baseURL ? baseURL.substring(0, baseURL.length - 1) : "";
317
+ const apiPrefix = `/${options?.apiPrefix || "api"}`;
318
+ const viteRolldownOutput = options?.vite?.build?.rolldownOptions?.output;
319
+ const viteRolldownOutputConfig = viteRolldownOutput && !Array.isArray(viteRolldownOutput) ? viteRolldownOutput : void 0;
320
+ const codeSplitting = viteRolldownOutputConfig?.codeSplitting;
321
+ let isBuild = false;
322
+ let isServe = false;
323
+ let ssrBuild = false;
324
+ let config;
325
+ let nitroConfig;
326
+ let environmentBuild = false;
327
+ let hasServerFns = false;
328
+ let clientOutputPath = "";
329
+ let clientIndexHtml;
330
+ let legacyClientSubBuild = false;
331
+ const rollupExternalEntries = [];
332
+ const sitemapRoutes = [];
333
+ const routeSitemaps = {};
334
+ const routeSourceFiles = {};
335
+ let rootDir = workspaceRoot;
336
+ return [
337
+ options?.ssr ? devServerPlugin({
338
+ entryServer: options?.entryServer,
339
+ index: options?.index,
340
+ routeRules: nitroOptions?.routeRules,
341
+ i18n: options?.i18n
342
+ }) : false,
343
+ {
344
+ name: "@analogjs/vite-plugin-nitro",
345
+ async config(userConfig, { mode, command }) {
346
+ isServe = command === "serve";
347
+ isBuild = command === "build";
348
+ ssrBuild = userConfig.build?.ssr === true;
349
+ config = cloneUserConfig(userConfig);
350
+ isTest = isTest ? isTest : mode === "test";
351
+ rollupExternalEntries.length = 0;
352
+ clientIndexHtml = void 0;
353
+ sitemapRoutes.length = 0;
354
+ for (const key of Object.keys(routeSitemaps)) delete routeSitemaps[key];
355
+ for (const key of Object.keys(routeSourceFiles)) delete routeSourceFiles[key];
356
+ const resolvedConfigRoot = config.root ? resolve(workspaceRoot, config.root) : workspaceRoot;
357
+ rootDir = relative(workspaceRoot, resolvedConfigRoot) || ".";
358
+ const buildPreset = process.env["BUILD_PRESET"] ?? nitroOptions?.preset ?? (process.env["VERCEL"] ? "vercel" : void 0);
359
+ const pageHandlers = getPageHandlers({
360
+ workspaceRoot,
361
+ sourceRoot,
362
+ rootDir,
363
+ additionalPagesDirs: options?.additionalPagesDirs
364
+ });
365
+ const resolvedClientOutputPath = resolveClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir);
366
+ debugNitro("nitro config resolved client output path", {
367
+ platform: process.platform,
368
+ workspaceRoot,
369
+ configRoot: config.root,
370
+ resolvedConfigRoot,
371
+ rootDir,
372
+ buildOutDir: config.build?.outDir,
373
+ clientOutputPath,
374
+ resolvedClientOutputPath,
375
+ hasEnvironmentConfig: !!config.environments,
376
+ clientEnvironmentOutDir: config.environments?.["client"] && typeof config.environments["client"] === "object" && "build" in config.environments["client"] ? config.environments["client"].build?.outDir : void 0
377
+ });
378
+ const serverFnModules = getServerFnHandlers({
379
+ workspaceRoot,
380
+ sourceRoot,
381
+ rootDir,
382
+ additionalServerFnDirs: options?.additionalServerFnDirs
383
+ });
384
+ const serverFnAppConfigModule = resolveServerFnAppConfigModule(workspaceRoot, rootDir, sourceRoot);
385
+ hasServerFns = serverFnModules.length > 0;
386
+ hasServerFns && getServerFnDispatchHandler();
387
+ serverFnModules.length > 0 && buildServerFnDispatchModule({
388
+ modules: serverFnModules,
389
+ appConfigModule: serverFnAppConfigModule
390
+ });
391
+ nitroConfig = {
392
+ rootDir: normalizePath(rootDir),
393
+ preset: buildPreset,
394
+ compatibilityDate: "2025-11-19",
395
+ logLevel: nitroOptions?.logLevel || 0,
396
+ serverDir: normalizePath(`${sourceRoot}/server`),
397
+ scanDirs: [normalizePath(`${rootDir}/${sourceRoot}/server`), ...(options?.additionalAPIDirs || []).map((dir) => normalizePath(`${workspaceRoot}${dir}`))],
398
+ output: {
399
+ dir: normalizePath(resolve(workspaceRoot, "dist", rootDir, "analog")),
400
+ publicDir: normalizePath(resolve(workspaceRoot, "dist", rootDir, "analog/public"))
401
+ },
402
+ buildDir: normalizePath(resolve(workspaceRoot, "dist", rootDir, ".nitro")),
403
+ typescript: { generateTsConfig: false },
404
+ runtimeConfig: {
405
+ apiPrefix: apiPrefix.substring(1),
406
+ prefix
407
+ },
408
+ renderer: false,
409
+ imports: { autoImport: false },
410
+ hooks: { "rollup:before": createRollupBeforeHook(rollupExternalEntries) },
411
+ rollupConfig: {
412
+ onwarn(warning) {
413
+ if (warning.message.includes("empty chunk") && warning.message.endsWith(".server")) return;
414
+ },
415
+ plugins: [pageEndpointsPlugin(), serverFnIdPlugin(normalizePath(resolve(workspaceRoot, rootDir)))]
416
+ },
417
+ handlers: [...pageHandlers],
418
+ routeRules: void 0,
419
+ virtual: {
420
+ "#ANALOG_SSR_RENDERER": ssrRenderer(),
421
+ "#ANALOG_CLIENT_RENDERER": clientRenderer()
422
+ }
423
+ };
424
+ if (isVercelPreset(buildPreset)) nitroConfig = withVercelOutputAPI(nitroConfig, workspaceRoot);
425
+ if (isCloudflarePreset(buildPreset)) nitroConfig = withCloudflareOutput(nitroConfig);
426
+ if (isNetlifyPreset(buildPreset) && rootDir === "." && !existsSync(resolve(workspaceRoot, "netlify.toml"))) nitroConfig = withNetlifyOutputAPI(nitroConfig, workspaceRoot);
427
+ if (isFirebaseAppHosting()) nitroConfig = withAppHostingOutput(nitroConfig);
428
+ if (!ssrBuild && !isTest) {
429
+ clientOutputPath = resolvedClientOutputPath;
430
+ debugNitro("nitro config cached client output path for later SSR/Nitro build", {
431
+ ssrBuild,
432
+ isTest,
433
+ clientOutputPath
434
+ });
435
+ }
436
+ nitroConfig.alias = {};
437
+ if (isBuild) {
438
+ nitroConfig.publicAssets = [{
439
+ dir: normalizePath(resolvedClientOutputPath),
440
+ maxAge: 0
441
+ }];
442
+ const rendererHandler = options?.ssr ? "#ANALOG_SSR_RENDERER" : "#ANALOG_CLIENT_RENDERER";
443
+ nitroConfig.handlers = [...nitroConfig.handlers || [], {
444
+ handler: rendererHandler,
445
+ route: "/**",
446
+ lazy: true
447
+ }];
448
+ if (isEmptyPrerenderRoutes(options)) {
449
+ nitroConfig.prerender = {};
450
+ nitroConfig.prerender.routes = ["/"];
451
+ }
452
+ if (options?.prerender) {
453
+ nitroConfig.prerender = nitroConfig.prerender ?? {};
454
+ nitroConfig.prerender.crawlLinks = options?.prerender?.discover;
455
+ let routes = [];
456
+ const prerenderRoutes = options?.prerender?.routes;
457
+ const hasExplicitPrerenderRoutes = typeof prerenderRoutes === "function" || Array.isArray(prerenderRoutes);
458
+ if (isArrayWithElements(prerenderRoutes)) routes = prerenderRoutes;
459
+ else if (typeof prerenderRoutes === "function") routes = await prerenderRoutes();
460
+ const resolvedPrerenderRoutes = routes.reduce((prev, current) => {
461
+ if (!current) return prev;
462
+ if (typeof current === "string") {
463
+ prev.push(current);
464
+ sitemapRoutes.push(current);
465
+ return prev;
466
+ }
467
+ if ("route" in current) {
468
+ if (current.sitemap) routeSitemaps[current.route] = current.sitemap;
469
+ if (current.outputSourceFile) {
470
+ const sourcePath = resolve(workspaceRoot, rootDir, current.outputSourceFile);
471
+ routeSourceFiles[current.route] = readFileSync(sourcePath, "utf8");
472
+ }
473
+ prev.push(current.route);
474
+ sitemapRoutes.push(current.route);
475
+ if ("staticData" in current) prev.push(`${apiPrefix}/_analog/pages/${current.route}`);
476
+ return prev;
477
+ }
478
+ getMatchingContentFilesWithFrontMatter(workspaceRoot, rootDir, current.contentDir, current.recursive).forEach((f) => {
479
+ const result = current.transform(f);
480
+ if (result) {
481
+ if (current.sitemap) routeSitemaps[result] = current.sitemap && typeof current.sitemap === "function" ? current.sitemap?.(f) : current.sitemap;
482
+ if (current.outputSourceFile) {
483
+ const sourceContent = current.outputSourceFile(f);
484
+ if (sourceContent) routeSourceFiles[result] = sourceContent;
485
+ }
486
+ prev.push(result);
487
+ sitemapRoutes.push(result);
488
+ if ("staticData" in current) prev.push(`${apiPrefix}/_analog/pages/${result}`);
489
+ }
490
+ });
491
+ return prev;
492
+ }, []);
493
+ nitroConfig.prerender.routes = hasExplicitPrerenderRoutes || resolvedPrerenderRoutes.length ? resolvedPrerenderRoutes : nitroConfig.prerender.routes ?? [];
494
+ }
495
+ if (ssrBuild || options?.ssr || nitroConfig.prerender?.routes?.length) {
496
+ nitroConfig.noExternals = appendNoExternals(nitroConfig.noExternals, "es-toolkit");
497
+ if (process.platform === "win32") nitroConfig.noExternals = appendNoExternals(nitroConfig.noExternals, "std-env");
498
+ rollupExternalEntries.push("rxjs", "node-fetch-native/dist/polyfill", "sharp");
499
+ nitroConfig = {
500
+ ...nitroConfig,
501
+ handlers: [...pageHandlers, {
502
+ handler: rendererHandler,
503
+ route: "/**",
504
+ lazy: true
505
+ }]
506
+ };
507
+ }
508
+ }
509
+ nitroConfig = mergeConfig(nitroConfig, nitroOptions);
510
+ if (environmentBuild || ssrBuild || isServe) return {};
511
+ return {
512
+ environments: {
513
+ client: { build: {
514
+ outDir: config?.build?.outDir || resolve(workspaceRoot, "dist", rootDir, "client"),
515
+ emptyOutDir: true,
516
+ ...isRolldown() && codeSplitting !== void 0 ? { rolldownOptions: { output: {
517
+ ...viteRolldownOutputConfig,
518
+ codeSplitting
519
+ } } } : {}
520
+ } },
521
+ ssr: { build: {
522
+ ssr: true,
523
+ [getBundleOptionsKey()]: { input: options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
524
+ outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
525
+ emptyOutDir: false
526
+ } }
527
+ },
528
+ builder: {
529
+ sharedPlugins: true,
530
+ buildApp: async (builder) => {
531
+ environmentBuild = true;
532
+ debugNitro("builder.buildApp starting", {
533
+ platform: process.platform,
534
+ workspaceRoot,
535
+ rootDir,
536
+ cachedClientOutputPath: clientOutputPath,
537
+ configuredBuildOutDir: config.build?.outDir,
538
+ clientEnvironmentOutDir: getEnvironmentBuildOutDir(builder.environments["client"]),
539
+ ssrEnvironmentOutDir: getEnvironmentBuildOutDir(builder.environments["ssr"])
540
+ });
541
+ await builder.build(builder.environments["client"]);
542
+ const postClientBuildOutputPath = resolveBuiltClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir, builder.environments["client"]);
543
+ registerIndexHtmlVirtual(nitroConfig, postClientBuildOutputPath, clientIndexHtml);
544
+ debugNitro("builder.buildApp completed client build", {
545
+ postClientBuildOutputPath,
546
+ postClientBuildOutputInfo: getPathDebugInfo(postClientBuildOutputPath),
547
+ postClientBuildIndexHtmlPath: resolve(postClientBuildOutputPath, "index.html"),
548
+ postClientBuildIndexHtmlExists: existsSync(resolve(postClientBuildOutputPath, "index.html"))
549
+ });
550
+ if (options?.ssr || nitroConfig.prerender?.routes?.length) {
551
+ debugSsr("builder.buildApp starting SSR build", {
552
+ ssrEnabled: options?.ssr,
553
+ prerenderRoutes: nitroConfig.prerender?.routes
554
+ });
555
+ /**
556
+ * This launches the SSR environment as a second build from the
557
+ * shared plugin graph above. When debugging an apparent
558
+ * duplicate `@analogjs/vite-plugin-angular` registration, this
559
+ * is the handoff to inspect: the SSR builder replays the shared
560
+ * plugins for the server pass and may therefore expose multiple
561
+ * Angular-plugin entries in the SSR resolved config.
562
+ *
563
+ * That is expected for this orchestration path and should not
564
+ * be treated the same as a duplicated client build, where two
565
+ * Angular plugin instances would maintain separate style maps.
566
+ */
567
+ await builder.build(builder.environments["ssr"]);
568
+ debugSsr("builder.buildApp completed SSR build", { ssrOutputPath: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr") });
569
+ }
570
+ applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
571
+ const resolvedClientOutputPath = resolveBuiltClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir, builder.environments["client"]);
572
+ nitroConfig.publicAssets = [{
573
+ dir: normalizePath(resolvedClientOutputPath),
574
+ maxAge: 0
575
+ }];
576
+ debugNitro("builder.buildApp resolved final client output path before Nitro build", {
577
+ resolvedClientOutputPath,
578
+ resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath),
579
+ nitroPublicAssets: nitroConfig.publicAssets
580
+ });
581
+ await buildServer(options, nitroConfig, routeSourceFiles);
582
+ if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
583
+ console.log("Building Sitemap...");
584
+ await buildSitemap(config, options.prerender.sitemap, sitemapRoutes.length ? sitemapRoutes : nitroConfig.prerender.routes, getNitroPublicOutputDir(nitroConfig), routeSitemaps, { apiPrefix: options?.apiPrefix || "api" });
585
+ }
586
+ console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
587
+ }
588
+ }
589
+ };
590
+ },
591
+ generateBundle(_options, bundle) {
592
+ if (!isBuild || ssrBuild) return;
593
+ clientIndexHtml = captureClientIndexHtmlFromBundle(bundle, "generateBundle") ?? clientIndexHtml;
594
+ },
595
+ writeBundle(_options, bundle) {
596
+ if (!isBuild || ssrBuild) return;
597
+ clientIndexHtml = captureClientIndexHtmlFromBundle(bundle, "writeBundle") ?? clientIndexHtml;
598
+ },
599
+ async configureServer(viteServer) {
600
+ if (isServe && !isTest) {
601
+ const nitro = await createNitro({
602
+ dev: true,
603
+ builder: "rollup",
604
+ ...nitroConfig
605
+ });
606
+ const server = createDevServer(nitro);
607
+ await build(nitro);
608
+ const nitroSourceRoots = [normalizePath(resolve(workspaceRoot, rootDir, `${sourceRoot}/server`)), ...(options?.additionalAPIDirs || []).map((dir) => normalizePath(`${workspaceRoot}${dir}`))];
609
+ const isNitroSourceFile = (path) => {
610
+ const normalizedPath = normalizePath(path);
611
+ return nitroSourceRoots.some((root) => normalizedPath === root || normalizedPath.startsWith(`${root}/`));
612
+ };
613
+ let nitroRebuildPromise;
614
+ let nitroRebuildPending = false;
615
+ const rebuildNitroServer = () => {
616
+ if (nitroRebuildPromise) {
617
+ nitroRebuildPending = true;
618
+ return nitroRebuildPromise;
619
+ }
620
+ nitroRebuildPromise = (async () => {
621
+ do {
622
+ nitroRebuildPending = false;
623
+ await build(nitro);
624
+ } while (nitroRebuildPending);
625
+ viteServer.ws.send("analog:debug-full-reload", {
626
+ plugin: "vite-plugin-nitro",
627
+ reason: "nitro-server-rebuilt"
628
+ });
629
+ viteServer.ws.send({ type: "full-reload" });
630
+ })().catch((error) => {
631
+ viteServer.config.logger.error(`[analog] Failed to rebuild Nitro dev server.\n${error instanceof Error ? error.stack || error.message : String(error)}`);
632
+ }).finally(() => {
633
+ nitroRebuildPromise = void 0;
634
+ });
635
+ return nitroRebuildPromise;
636
+ };
637
+ const onNitroSourceChange = (path) => {
638
+ if (!isNitroSourceFile(path)) return;
639
+ rebuildNitroServer();
640
+ };
641
+ viteServer.watcher.on("add", onNitroSourceChange);
642
+ viteServer.watcher.on("change", onNitroSourceChange);
643
+ viteServer.watcher.on("unlink", onNitroSourceChange);
644
+ const apiHandler = async (req, res) => {
645
+ await writeWebResponseToNode(res, await server.fetch(toWebRequest(req)));
646
+ };
647
+ viteServer.middlewares.use((req, res, next) => {
648
+ if (req.url?.startsWith(`${prefix}${apiPrefix}`)) {
649
+ apiHandler(req, res).catch((error) => next(error));
650
+ return;
651
+ }
652
+ next();
653
+ });
654
+ viteServer.httpServer?.once("listening", () => {
655
+ process.env["ANALOG_HOST"] = !viteServer.config.server.host ? "localhost" : viteServer.config.server.host;
656
+ process.env["ANALOG_PORT"] = `${viteServer.config.server.port}`;
657
+ });
658
+ if (nitroOptions?.experimental?.websocket) {
659
+ debugNitro("experimental websocket upgrade handler enabled");
660
+ viteServer.httpServer?.on("upgrade", server.upgrade);
661
+ }
662
+ console.log(`\n\nThe server endpoints are accessible under the "${prefix}${apiPrefix}" path.`);
663
+ }
664
+ },
665
+ async closeBundle() {
666
+ if (legacyClientSubBuild) return;
667
+ if (environmentBuild) return;
668
+ if (ssrBuild) return;
669
+ if (isBuild) {
670
+ const resolvedClientOutputPath = resolveClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir);
671
+ debugNitro("closeBundle resolved client output path before legacy SSR build", {
672
+ platform: process.platform,
673
+ workspaceRoot,
674
+ rootDir,
675
+ cachedClientOutputPath: clientOutputPath,
676
+ configuredBuildOutDir: config.build?.outDir,
677
+ resolvedClientOutputPath,
678
+ resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath)
679
+ });
680
+ const indexHtmlPath = resolve(resolvedClientOutputPath, "index.html");
681
+ if (!existsSync(indexHtmlPath) && typeof clientIndexHtml !== "string") {
682
+ debugNitro("closeBundle rebuilding missing client output before SSR/Nitro", {
683
+ platform: process.platform,
684
+ workspaceRoot,
685
+ rootDir,
686
+ configuredBuildOutDir: config.build?.outDir,
687
+ resolvedClientOutputPath,
688
+ indexHtmlPath
689
+ });
690
+ legacyClientSubBuild = true;
691
+ try {
692
+ await buildClientApp(config, options);
693
+ } finally {
694
+ legacyClientSubBuild = false;
695
+ }
696
+ }
697
+ registerIndexHtmlVirtual(nitroConfig, resolvedClientOutputPath, clientIndexHtml);
698
+ if (options?.ssr) {
699
+ console.log("Building SSR application...");
700
+ await buildSSRApp(config, options);
701
+ debugSsr("closeBundle completed standalone SSR build", {
702
+ ssrBuildDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
703
+ clientOutputPathInfo: clientOutputPath ? getPathDebugInfo(clientOutputPath) : null
704
+ });
705
+ }
706
+ applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
707
+ debugNitro("closeBundle resolved client output path before Nitro build", {
708
+ platform: process.platform,
709
+ workspaceRoot,
710
+ rootDir,
711
+ cachedClientOutputPath: clientOutputPath,
712
+ configuredBuildOutDir: config.build?.outDir,
713
+ resolvedClientOutputPath,
714
+ resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath)
715
+ });
716
+ registerIndexHtmlVirtual(nitroConfig, resolvedClientOutputPath, clientIndexHtml);
717
+ await buildServer(options, nitroConfig, routeSourceFiles);
718
+ if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
719
+ console.log("Building Sitemap...");
720
+ await buildSitemap(config, options.prerender.sitemap, sitemapRoutes.length ? sitemapRoutes : nitroConfig.prerender.routes, getNitroPublicOutputDir(nitroConfig), routeSitemaps, { apiPrefix: options?.apiPrefix || "api" });
721
+ }
722
+ console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
723
+ }
724
+ }
725
+ },
726
+ {
727
+ name: "@analogjs/vite-plugin-nitro-api-prefix",
728
+ config() {
729
+ return { define: {
730
+ ANALOG_API_PREFIX: `"${baseURL.substring(1)}${apiPrefix.substring(1)}"`,
731
+ ...options?.i18n ? {
732
+ ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(options.i18n.defaultLocale),
733
+ ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales)
734
+ } : {}
735
+ } };
736
+ }
737
+ }
738
+ ];
618
739
  }
619
740
  function isEmptyPrerenderRoutes(options) {
620
- if (!options || isArrayWithElements(options?.prerender?.routes)) {
621
- return false;
622
- }
623
- return !options.prerender?.routes;
741
+ if (!options || isArrayWithElements(options?.prerender?.routes)) return false;
742
+ return !options.prerender?.routes;
624
743
  }
625
744
  function isArrayWithElements(arr) {
626
- return !!(Array.isArray(arr) && arr.length);
745
+ return !!(Array.isArray(arr) && arr.length);
627
746
  }
628
- const VERCEL_PRESET = 'vercel';
629
- // Nitro v3 consolidates the old `vercel-edge` preset into `vercel` with
630
- // fluid compute enabled by default, so a single preset covers both
631
- // serverless and edge deployments.
632
- const withVercelOutputAPI = (nitroConfig, workspaceRoot) => ({
633
- ...nitroConfig,
634
- preset: nitroConfig?.preset ?? 'vercel',
635
- vercel: {
636
- ...nitroConfig?.vercel,
637
- entryFormat: nitroConfig?.vercel?.entryFormat ?? 'node',
638
- functions: {
639
- runtime: nitroConfig?.vercel?.functions?.runtime ?? 'nodejs24.x',
640
- ...nitroConfig?.vercel?.functions,
641
- },
642
- },
643
- output: {
644
- ...nitroConfig?.output,
645
- dir: normalizePath(resolve(workspaceRoot, '.vercel', 'output')),
646
- publicDir: normalizePath(resolve(workspaceRoot, '.vercel', 'output/static')),
647
- },
747
+ var withVercelOutputAPI = (nitroConfig, workspaceRoot) => ({
748
+ ...nitroConfig,
749
+ preset: nitroConfig?.preset ?? "vercel",
750
+ vercel: {
751
+ ...nitroConfig?.vercel,
752
+ entryFormat: nitroConfig?.vercel?.entryFormat ?? "node",
753
+ functions: {
754
+ runtime: nitroConfig?.vercel?.functions?.runtime ?? "nodejs24.x",
755
+ ...nitroConfig?.vercel?.functions
756
+ }
757
+ },
758
+ output: {
759
+ ...nitroConfig?.output,
760
+ dir: normalizePath(resolve(workspaceRoot, ".vercel", "output")),
761
+ publicDir: normalizePath(resolve(workspaceRoot, ".vercel", "output/static"))
762
+ }
648
763
  });
649
- // Nitro v3 uses underscore-separated preset names (e.g. `cloudflare_pages`),
650
- // but we accept both hyphen and underscore forms for backwards compatibility.
651
- const isCloudflarePreset = (buildPreset) => process.env['CF_PAGES'] ||
652
- (buildPreset &&
653
- (buildPreset.toLowerCase().includes('cloudflare-pages') ||
654
- buildPreset.toLowerCase().includes('cloudflare_pages')));
655
- const withCloudflareOutput = (nitroConfig) => ({
656
- ...nitroConfig,
657
- output: {
658
- ...nitroConfig?.output,
659
- serverDir: '{{ output.publicDir }}/_worker.js',
660
- },
764
+ var isCloudflarePreset = (buildPreset) => process.env["CF_PAGES"] || buildPreset && (buildPreset.toLowerCase().includes("cloudflare-pages") || buildPreset.toLowerCase().includes("cloudflare_pages"));
765
+ var withCloudflareOutput = (nitroConfig) => ({
766
+ ...nitroConfig,
767
+ output: {
768
+ ...nitroConfig?.output,
769
+ serverDir: "{{ output.publicDir }}/_worker.js"
770
+ }
661
771
  });
662
- const isFirebaseAppHosting = () => !!process.env['NG_BUILD_LOGS_JSON'];
663
- const withAppHostingOutput = (nitroConfig) => {
664
- let hasOutput = false;
665
- return {
666
- ...nitroConfig,
667
- serveStatic: true,
668
- rollupConfig: {
669
- ...nitroConfig.rollupConfig,
670
- output: {
671
- ...nitroConfig.rollupConfig?.output,
672
- entryFileNames: 'server.mjs',
673
- },
674
- },
675
- hooks: {
676
- ...nitroConfig.hooks,
677
- compiled: () => {
678
- if (!hasOutput) {
679
- const buildOutput = {
680
- errors: [],
681
- warnings: [],
682
- outputPaths: {
683
- root: pathToFileURL(`${nitroConfig.output?.dir}`),
684
- browser: pathToFileURL(`${nitroConfig.output?.publicDir}`),
685
- server: pathToFileURL(`${nitroConfig.output?.dir}/server`),
686
- },
687
- };
688
- // Log the build output for Firebase App Hosting to pick up
689
- console.log(JSON.stringify(buildOutput, null, 2));
690
- hasOutput = true;
691
- }
692
- },
693
- },
694
- };
772
+ var isFirebaseAppHosting = () => !!process.env["NG_BUILD_LOGS_JSON"];
773
+ var withAppHostingOutput = (nitroConfig) => {
774
+ let hasOutput = false;
775
+ return {
776
+ ...nitroConfig,
777
+ serveStatic: true,
778
+ rollupConfig: {
779
+ ...nitroConfig.rollupConfig,
780
+ output: {
781
+ ...nitroConfig.rollupConfig?.output,
782
+ entryFileNames: "server.mjs"
783
+ }
784
+ },
785
+ hooks: {
786
+ ...nitroConfig.hooks,
787
+ compiled: () => {
788
+ if (!hasOutput) {
789
+ const buildOutput = {
790
+ errors: [],
791
+ warnings: [],
792
+ outputPaths: {
793
+ root: pathToFileURL(`${nitroConfig.output?.dir}`),
794
+ browser: pathToFileURL(`${nitroConfig.output?.publicDir}`),
795
+ server: pathToFileURL(`${nitroConfig.output?.dir}/server`)
796
+ }
797
+ };
798
+ console.log(JSON.stringify(buildOutput, null, 2));
799
+ hasOutput = true;
800
+ }
801
+ }
802
+ }
803
+ };
695
804
  };
696
- const isNetlifyPreset = (buildPreset) => process.env['NETLIFY'] ||
697
- (buildPreset && buildPreset.toLowerCase().includes('netlify'));
698
- const withNetlifyOutputAPI = (nitroConfig, workspaceRoot) => ({
699
- ...nitroConfig,
700
- output: {
701
- ...nitroConfig?.output,
702
- dir: normalizePath(resolve(workspaceRoot, 'netlify/functions')),
703
- },
805
+ function resolveServerFnAppConfigModule(workspaceRoot, rootDir, sourceRoot) {
806
+ const root = normalizePath(resolve(workspaceRoot, rootDir));
807
+ return [`${root}/${sourceRoot}/app/app.config.server.ts`, `${root}/${sourceRoot}/app.config.server.ts`].find((candidate) => existsSync(candidate));
808
+ }
809
+ var isNetlifyPreset = (buildPreset) => process.env["NETLIFY"] || buildPreset && buildPreset.toLowerCase().includes("netlify");
810
+ var withNetlifyOutputAPI = (nitroConfig, workspaceRoot) => ({
811
+ ...nitroConfig,
812
+ output: {
813
+ ...nitroConfig?.output,
814
+ dir: normalizePath(resolve(workspaceRoot, "netlify/functions"))
815
+ }
704
816
  });
817
+ //#endregion
818
+ export { nitro };
819
+
705
820
  //# sourceMappingURL=vite-plugin-nitro.js.map