@analogjs/vite-plugin-nitro 3.0.0-alpha.90 → 3.0.0-alpha.92

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 (61) hide show
  1. package/migrations/migration.json +7 -1
  2. package/migrations/update-nitro-options/update-nitro-options.d.ts +2 -0
  3. package/migrations/update-nitro-options/update-nitro-options.js +122 -0
  4. package/migrations/update-nitro-options/update-nitro-options.js.map +1 -0
  5. package/package.json +5 -10
  6. package/src/index.d.ts +5 -5
  7. package/src/index.js +1 -2
  8. package/src/index.js.map +1 -1
  9. package/src/lib/build-server.d.ts +2 -3
  10. package/src/lib/build-server.js +88 -35
  11. package/src/lib/build-server.js.map +1 -1
  12. package/src/lib/build-sitemap.d.ts +8 -8
  13. package/src/lib/build-sitemap.js +77 -116
  14. package/src/lib/build-sitemap.js.map +1 -1
  15. package/src/lib/build-ssr.d.ts +1 -2
  16. package/src/lib/build-ssr.js +6 -15
  17. package/src/lib/build-ssr.js.map +1 -1
  18. package/src/lib/hooks/post-rendering-hook.d.ts +1 -1
  19. package/src/lib/hooks/post-rendering-hook.js +1 -3
  20. package/src/lib/hooks/post-rendering-hook.js.map +1 -1
  21. package/src/lib/options.d.ts +30 -25
  22. package/src/lib/plugins/dev-server-plugin.d.ts +1 -1
  23. package/src/lib/plugins/dev-server-plugin.js +13 -11
  24. package/src/lib/plugins/dev-server-plugin.js.map +1 -1
  25. package/src/lib/plugins/page-endpoints.js +10 -14
  26. package/src/lib/plugins/page-endpoints.js.map +1 -1
  27. package/src/lib/plugins/server-fn-id-plugin.d.ts +4 -1
  28. package/src/lib/plugins/server-fn-id-plugin.js.map +1 -1
  29. package/src/lib/runtime/locale-worker-entry.mjs +71 -0
  30. package/src/lib/runtime/locale-workers.mjs +193 -0
  31. package/src/lib/utils/get-content-files.js +1 -1
  32. package/src/lib/utils/get-content-files.js.map +1 -1
  33. package/src/lib/utils/get-page-handlers.d.ts +10 -7
  34. package/src/lib/utils/get-page-handlers.js +10 -7
  35. package/src/lib/utils/get-page-handlers.js.map +1 -1
  36. package/src/lib/utils/i18n-prerender.d.ts +1 -0
  37. package/src/lib/utils/i18n-prerender.js +48 -1
  38. package/src/lib/utils/i18n-prerender.js.map +1 -1
  39. package/src/lib/utils/i18n-workers.d.ts +6 -0
  40. package/src/lib/utils/i18n-workers.js +55 -0
  41. package/src/lib/utils/i18n-workers.js.map +1 -0
  42. package/src/lib/utils/register-dev-middleware.d.ts +32 -4
  43. package/src/lib/utils/register-dev-middleware.js +34 -21
  44. package/src/lib/utils/register-dev-middleware.js.map +1 -1
  45. package/src/lib/utils/renderers.d.ts +5 -33
  46. package/src/lib/utils/renderers.js +121 -75
  47. package/src/lib/utils/renderers.js.map +1 -1
  48. package/src/lib/utils/server-fn-endpoints.js +3 -1
  49. package/src/lib/utils/server-fn-endpoints.js.map +1 -1
  50. package/src/lib/vite-plugin-nitro.d.ts +9 -2
  51. package/src/lib/vite-plugin-nitro.js +187 -562
  52. package/src/lib/vite-plugin-nitro.js.map +1 -1
  53. package/src/lib/utils/debug.d.ts +0 -5
  54. package/src/lib/utils/debug.js +0 -15
  55. package/src/lib/utils/debug.js.map +0 -1
  56. package/src/lib/utils/node-web-bridge.d.ts +0 -3
  57. package/src/lib/utils/node-web-bridge.js +0 -55
  58. package/src/lib/utils/node-web-bridge.js.map +0 -1
  59. package/src/lib/utils/rolldown.d.ts +0 -2
  60. package/src/lib/utils/rolldown.js +0 -12
  61. package/src/lib/utils/rolldown.js.map +0 -1
@@ -1,379 +1,81 @@
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";
1
+ import { I18N_WORKER_SSR_ENTRY, i18nWorkerSsrEntry, resolveI18nWorkers } from "./utils/i18n-workers.js";
2
+ import { apiMiddleware, clientRenderer, ssrRenderer, ssrStreamRenderer } from "./utils/renderers.js";
3
+ import { buildServer } from "./build-server.js";
4
+ import { buildSSRApp } from "./build-ssr.js";
5
5
  import { pageEndpointsPlugin } from "./plugins/page-endpoints.js";
6
6
  import { serverFnIdPlugin } from "./plugins/server-fn-id-plugin.js";
7
7
  import { getPageHandlers } from "./utils/get-page-handlers.js";
8
8
  import { getServerFnHandlers } from "./utils/get-server-fn-handlers.js";
9
9
  import { SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler } from "./utils/server-fn-endpoints.js";
10
10
  import { buildSitemap } from "./build-sitemap.js";
11
- import { toWebRequest, writeWebResponseToNode } from "./utils/node-web-bridge.js";
11
+ import { createI18nPostRenderingHook, expandRoutesWithLocales } from "./utils/i18n-prerender.js";
12
12
  import { devServerPlugin } from "./plugins/dev-server-plugin.js";
13
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";
14
+ import { build, createDevServer, createNitro, loadOptions } from "nitropack";
15
+ import { toNodeListener } from "h3";
16
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";
17
+ import { dirname, relative, resolve } from "node:path";
18
+ import { platform } from "node:os";
19
+ import { fileURLToPath, pathToFileURL } from "node:url";
20
+ import { existsSync, readFileSync } from "node:fs";
20
21
  //#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
- };
64
- }
65
- /**
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
- */
88
- function createRollupBeforeHook(externalEntries) {
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
- };
99
- }
100
- function appendNoExternals(noExternals, ...entries) {
101
- if (!noExternals) return entries;
102
- return Array.isArray(noExternals) ? [...noExternals, ...entries] : noExternals;
103
- }
104
- /**
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
- */
115
- function sanitizeNitroBundlerConfig(_nitro, bundlerConfig) {
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);
187
- }
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
- };
262
- }
263
- /**
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
- */
288
- function toNitroSsrEntrypointSpecifier(ssrEntryPath) {
289
- return normalizePath(ssrEntryPath);
290
- }
291
- function applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir) {
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
- }
300
- }
301
- function resolveBuiltSsrEntryPath(ssrOutDir) {
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;
310
- }
311
- function nitro(options, nitroOptions) {
312
- const workspaceRoot = options?.workspaceRoot ?? process.cwd();
313
- const sourceRoot = options?.sourceRoot ?? "src";
22
+ var isWindows = platform() === "win32";
23
+ var filePrefix = isWindows ? "file:///" : "";
24
+ var clientOutputPath = "";
25
+ dirname(fileURLToPath(import.meta.url));
26
+ function nitro(pluginOptions = {}) {
27
+ const { analog, static: isStatic, ...pluginNitroOptions } = pluginOptions;
28
+ const nitroOptions = withAnalogRouteRuleHeaders(pluginNitroOptions);
29
+ let options;
30
+ let workspaceRoot = process.cwd();
31
+ let sourceRoot = "src";
314
32
  let isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
315
33
  const baseURL = process.env["NITRO_APP_BASE_URL"] || "";
316
34
  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;
35
+ let apiPrefix = "/api";
36
+ let useAPIMiddleware = true;
37
+ let i18nWorkers = false;
321
38
  let isBuild = false;
322
39
  let isServe = false;
323
40
  let ssrBuild = false;
324
41
  let config;
325
42
  let nitroConfig;
326
43
  let environmentBuild = false;
44
+ let hasAPIDir = false;
327
45
  let hasServerFns = false;
328
- let clientOutputPath = "";
329
- let clientIndexHtml;
330
- let legacyClientSubBuild = false;
331
- const rollupExternalEntries = [];
332
- const sitemapRoutes = [];
333
46
  const routeSitemaps = {};
334
47
  const routeSourceFiles = {};
335
48
  let rootDir = workspaceRoot;
49
+ function resolveOptions(userConfig) {
50
+ options = {
51
+ ...getAnalogOptions(userConfig),
52
+ ...isStatic === void 0 ? {} : { static: isStatic },
53
+ ...analog
54
+ };
55
+ workspaceRoot = options.workspaceRoot ?? process.cwd();
56
+ sourceRoot = options.sourceRoot ?? "src";
57
+ apiPrefix = `/${options.apiPrefix || "api"}`;
58
+ useAPIMiddleware = options.useAPIMiddleware ?? true;
59
+ }
336
60
  return [
337
- options?.ssr ? devServerPlugin({
338
- entryServer: options?.entryServer,
339
- index: options?.index,
340
- routeRules: nitroOptions?.routeRules,
341
- i18n: options?.i18n
342
- }) : false,
343
61
  {
344
62
  name: "@analogjs/vite-plugin-nitro",
345
63
  async config(userConfig, { mode, command }) {
64
+ resolveOptions(userConfig);
346
65
  isServe = command === "serve";
347
66
  isBuild = command === "build";
348
67
  ssrBuild = userConfig.build?.ssr === true;
349
- config = cloneUserConfig(userConfig);
68
+ config = userConfig;
350
69
  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);
70
+ rootDir = relative(workspaceRoot, config.root || ".") || ".";
71
+ hasAPIDir = existsSync(resolve(workspaceRoot, rootDir, `${sourceRoot}/server/routes/${options?.apiPrefix || "api"}`));
72
+ const buildPreset = process.env["BUILD_PRESET"] ?? nitroOptions?.preset;
359
73
  const pageHandlers = getPageHandlers({
360
74
  workspaceRoot,
361
75
  sourceRoot,
362
76
  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
77
+ additionalPagesDirs: options?.additionalPagesDirs,
78
+ hasAPIDir
377
79
  });
378
80
  const serverFnModules = getServerFnHandlers({
379
81
  workspaceRoot,
@@ -389,35 +91,43 @@ function nitro(options, nitroOptions) {
389
91
  appConfigModule: serverFnAppConfigModule
390
92
  }) } : {};
391
93
  nitroConfig = {
392
- rootDir: normalizePath(rootDir),
94
+ rootDir,
393
95
  preset: buildPreset,
394
- compatibilityDate: "2025-11-19",
96
+ compatibilityDate: "2024-11-19",
395
97
  logLevel: nitroOptions?.logLevel || 0,
396
- serverDir: normalizePath(`${sourceRoot}/server`),
98
+ srcDir: normalizePath(`${sourceRoot}/server`),
397
99
  scanDirs: [normalizePath(`${rootDir}/${sourceRoot}/server`), ...(options?.additionalAPIDirs || []).map((dir) => normalizePath(`${workspaceRoot}${dir}`))],
398
100
  output: {
399
101
  dir: normalizePath(resolve(workspaceRoot, "dist", rootDir, "analog")),
400
102
  publicDir: normalizePath(resolve(workspaceRoot, "dist", rootDir, "analog/public"))
401
103
  },
402
104
  buildDir: normalizePath(resolve(workspaceRoot, "dist", rootDir, ".nitro")),
105
+ typescript: { generateTsConfig: false },
403
106
  runtimeConfig: {
404
107
  apiPrefix: apiPrefix.substring(1),
405
108
  prefix
406
109
  },
407
- renderer: false,
408
- hooks: { "rollup:before": createRollupBeforeHook(rollupExternalEntries) },
110
+ imports: { autoImport: false },
111
+ ...hasServerFns ? { moduleSideEffects: ["@angular/compiler", ...serverFnModules.map((m) => normalizePath(m.file))] } : {},
409
112
  rollupConfig: {
410
113
  onwarn(warning) {
411
114
  if (warning.message.includes("empty chunk") && warning.message.endsWith(".server")) return;
412
115
  },
413
116
  plugins: [pageEndpointsPlugin(), serverFnIdPlugin(normalizePath(resolve(workspaceRoot, rootDir)))]
414
117
  },
415
- ...hasServerFns ? { moduleSideEffects: ["@angular/compiler", ...serverFnModules.map((m) => normalizePath(m.file))] } : {},
416
- handlers: [...pageHandlers, ...serverFnHandlers],
417
- routeRules: void 0,
118
+ handlers: [
119
+ ...hasAPIDir ? [] : useAPIMiddleware ? [{
120
+ handler: "#ANALOG_API_MIDDLEWARE",
121
+ middleware: true
122
+ }] : [],
123
+ ...pageHandlers,
124
+ ...serverFnHandlers
125
+ ],
126
+ routeRules: hasAPIDir ? void 0 : useAPIMiddleware ? void 0 : { [`${prefix}${apiPrefix}/**`]: { proxy: { to: "/**" } } },
418
127
  virtual: {
419
- "#ANALOG_SSR_RENDERER": ssrRenderer(),
420
- "#ANALOG_CLIENT_RENDERER": clientRenderer(),
128
+ "#ANALOG_SSR_RENDERER": options?.experimental?.streaming ? ssrStreamRenderer : ssrRenderer,
129
+ "#ANALOG_CLIENT_RENDERER": clientRenderer,
130
+ ...hasAPIDir ? {} : { "#ANALOG_API_MIDDLEWARE": apiMiddleware },
421
131
  ...serverFnVirtual
422
132
  }
423
133
  };
@@ -425,26 +135,12 @@ function nitro(options, nitroOptions) {
425
135
  if (isCloudflarePreset(buildPreset)) nitroConfig = withCloudflareOutput(nitroConfig);
426
136
  if (isNetlifyPreset(buildPreset) && rootDir === "." && !existsSync(resolve(workspaceRoot, "netlify.toml"))) nitroConfig = withNetlifyOutputAPI(nitroConfig, workspaceRoot);
427
137
  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 = {};
138
+ if (!ssrBuild && !isTest) clientOutputPath = resolve(workspaceRoot, rootDir, config.build?.outDir || "dist/client");
139
+ const indexEntry = normalizePath(resolve(clientOutputPath, "index.html"));
140
+ nitroConfig.alias = { "#analog/index": indexEntry };
437
141
  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
- }];
142
+ nitroConfig.publicAssets = [{ dir: clientOutputPath }];
143
+ nitroConfig.renderer = options?.ssr ? "#ANALOG_SSR_RENDERER" : "#ANALOG_CLIENT_RENDERER";
448
144
  if (isEmptyPrerenderRoutes(options)) {
449
145
  nitroConfig.prerender = {};
450
146
  nitroConfig.prerender.routes = ["/"];
@@ -454,14 +150,12 @@ function nitro(options, nitroOptions) {
454
150
  nitroConfig.prerender.crawlLinks = options?.prerender?.discover;
455
151
  let routes = [];
456
152
  const prerenderRoutes = options?.prerender?.routes;
457
- const hasExplicitPrerenderRoutes = typeof prerenderRoutes === "function" || Array.isArray(prerenderRoutes);
458
153
  if (isArrayWithElements(prerenderRoutes)) routes = prerenderRoutes;
459
154
  else if (typeof prerenderRoutes === "function") routes = await prerenderRoutes();
460
- const resolvedPrerenderRoutes = routes.reduce((prev, current) => {
155
+ nitroConfig.prerender.routes = routes.reduce((prev, current) => {
461
156
  if (!current) return prev;
462
157
  if (typeof current === "string") {
463
158
  prev.push(current);
464
- sitemapRoutes.push(current);
465
159
  return prev;
466
160
  }
467
161
  if ("route" in current) {
@@ -471,7 +165,6 @@ function nitro(options, nitroOptions) {
471
165
  routeSourceFiles[current.route] = readFileSync(sourcePath, "utf8");
472
166
  }
473
167
  prev.push(current.route);
474
- sitemapRoutes.push(current.route);
475
168
  if ("staticData" in current) prev.push(`${apiPrefix}/_analog/pages/${current.route}`);
476
169
  return prev;
477
170
  }
@@ -484,249 +177,163 @@ function nitro(options, nitroOptions) {
484
177
  if (sourceContent) routeSourceFiles[result] = sourceContent;
485
178
  }
486
179
  prev.push(result);
487
- sitemapRoutes.push(result);
488
180
  if ("staticData" in current) prev.push(`${apiPrefix}/_analog/pages/${result}`);
489
181
  }
490
182
  });
491
183
  return prev;
492
184
  }, []);
493
- nitroConfig.prerender.routes = hasExplicitPrerenderRoutes || resolvedPrerenderRoutes.length ? resolvedPrerenderRoutes : nitroConfig.prerender.routes ?? [];
185
+ if (options?.i18n && nitroConfig.prerender?.routes) nitroConfig.prerender.routes = expandRoutesWithLocales(nitroConfig.prerender.routes.filter(Boolean), options.i18n);
186
+ }
187
+ if (options?.i18n) {
188
+ options.prerender = options.prerender ?? {};
189
+ options.prerender.postRenderingHooks = options.prerender.postRenderingHooks ?? [];
190
+ options.prerender.postRenderingHooks.push(createI18nPostRenderingHook(options.i18n));
494
191
  }
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");
192
+ if (ssrBuild) {
193
+ if (isWindows) nitroConfig.externals = { inline: ["std-env"] };
499
194
  nitroConfig = {
500
195
  ...nitroConfig,
196
+ externals: {
197
+ ...nitroConfig.externals,
198
+ external: ["rxjs", "node-fetch-native/dist/polyfill"]
199
+ },
200
+ moduleSideEffects: [
201
+ "zone.js/node",
202
+ "zone.js/fesm2015/zone-node",
203
+ ...nitroConfig.moduleSideEffects ?? []
204
+ ],
501
205
  handlers: [
206
+ ...hasAPIDir ? [] : useAPIMiddleware ? [{
207
+ handler: "#ANALOG_API_MIDDLEWARE",
208
+ middleware: true
209
+ }] : [],
502
210
  ...pageHandlers,
503
- ...serverFnHandlers,
504
- {
505
- handler: rendererHandler,
506
- route: "/**",
507
- lazy: true
508
- }
211
+ ...serverFnHandlers
509
212
  ]
510
213
  };
511
214
  }
512
215
  }
513
216
  nitroConfig = mergeConfig(nitroConfig, nitroOptions);
514
- if (environmentBuild || ssrBuild || isServe) return {};
217
+ i18nWorkers = false;
218
+ if (isBuild && options?.i18n && options.i18n.workers !== false && (options.i18n.loader || options.i18n.workers === true)) {
219
+ const resolvedNitro = await loadOptions({
220
+ dev: false,
221
+ preset: process.env["BUILD_PRESET"],
222
+ ...nitroConfig
223
+ });
224
+ i18nWorkers = resolveI18nWorkers(options, resolvedNitro);
225
+ nitroConfig.preset = resolvedNitro.preset;
226
+ }
515
227
  return {
228
+ define: { ANALOG_I18N_FIXED_LOCALE: i18nWorkers ? "globalThis.process.env.ANALOG_I18N_LOCALE" : "undefined" },
516
229
  environments: {
517
- client: { build: {
518
- outDir: config?.build?.outDir || resolve(workspaceRoot, "dist", rootDir, "client"),
519
- emptyOutDir: true,
520
- ...isRolldown() && codeSplitting !== void 0 ? { rolldownOptions: { output: {
521
- ...viteRolldownOutputConfig,
522
- codeSplitting
523
- } } } : {}
524
- } },
525
- ssr: { build: {
526
- ssr: true,
527
- [getBundleOptionsKey()]: { input: options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
528
- outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
529
- emptyOutDir: false
530
- } }
230
+ client: { build: { outDir: config?.build?.outDir || resolve(workspaceRoot, "dist", rootDir, "client") } },
231
+ ssr: {
232
+ consumer: "server",
233
+ build: {
234
+ ssr: true,
235
+ rollupOptions: { input: i18nWorkers ? { "main.server": I18N_WORKER_SSR_ENTRY } : options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
236
+ outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr")
237
+ }
238
+ }
531
239
  },
532
240
  builder: {
533
241
  sharedPlugins: true,
534
242
  buildApp: async (builder) => {
535
243
  environmentBuild = true;
536
- debugNitro("builder.buildApp starting", {
537
- platform: process.platform,
538
- workspaceRoot,
539
- rootDir,
540
- cachedClientOutputPath: clientOutputPath,
541
- configuredBuildOutDir: config.build?.outDir,
542
- clientEnvironmentOutDir: getEnvironmentBuildOutDir(builder.environments["client"]),
543
- ssrEnvironmentOutDir: getEnvironmentBuildOutDir(builder.environments["ssr"])
544
- });
545
- await builder.build(builder.environments["client"]);
546
- const postClientBuildOutputPath = resolveBuiltClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir, builder.environments["client"]);
547
- registerIndexHtmlVirtual(nitroConfig, postClientBuildOutputPath, clientIndexHtml);
548
- debugNitro("builder.buildApp completed client build", {
549
- postClientBuildOutputPath,
550
- postClientBuildOutputInfo: getPathDebugInfo(postClientBuildOutputPath),
551
- postClientBuildIndexHtmlPath: resolve(postClientBuildOutputPath, "index.html"),
552
- postClientBuildIndexHtmlExists: existsSync(resolve(postClientBuildOutputPath, "index.html"))
553
- });
554
- if (options?.ssr || nitroConfig.prerender?.routes?.length) {
555
- debugSsr("builder.buildApp starting SSR build", {
556
- ssrEnabled: options?.ssr,
557
- prerenderRoutes: nitroConfig.prerender?.routes
558
- });
559
- /**
560
- * This launches the SSR environment as a second build from the
561
- * shared plugin graph above. When debugging an apparent
562
- * duplicate `@analogjs/vite-plugin-angular` registration, this
563
- * is the handoff to inspect: the SSR builder replays the shared
564
- * plugins for the server pass and may therefore expose multiple
565
- * Angular-plugin entries in the SSR resolved config.
566
- *
567
- * That is expected for this orchestration path and should not
568
- * be treated the same as a duplicated client build, where two
569
- * Angular plugin instances would maintain separate style maps.
570
- */
571
- await builder.build(builder.environments["ssr"]);
572
- debugSsr("builder.buildApp completed SSR build", { ssrOutputPath: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr") });
573
- }
574
- applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
575
- const resolvedClientOutputPath = resolveBuiltClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir, builder.environments["client"]);
576
- nitroConfig.publicAssets = [{
577
- dir: normalizePath(resolvedClientOutputPath),
578
- maxAge: 0
579
- }];
580
- debugNitro("builder.buildApp resolved final client output path before Nitro build", {
581
- resolvedClientOutputPath,
582
- resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath),
583
- nitroPublicAssets: nitroConfig.publicAssets
584
- });
585
- await buildServer(options, nitroConfig, routeSourceFiles);
244
+ const builds = [builder.build(builder.environments["client"])];
245
+ if (options?.ssr || nitroConfig.prerender?.routes?.length) builds.push(builder.build(builder.environments["ssr"]));
246
+ await Promise.all(builds);
247
+ let ssrEntryPath = resolve(options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, `ssr`), `main.server${filePrefix ? ".js" : ""}`);
248
+ if (isWindows && !existsSync(ssrEntryPath)) ssrEntryPath = ssrEntryPath.replace(".js", ".mjs");
249
+ const ssrEntry = normalizePath(filePrefix + ssrEntryPath);
250
+ nitroConfig.alias = {
251
+ ...nitroConfig.alias,
252
+ "#analog/ssr": ssrEntry
253
+ };
254
+ await buildServer(options, nitroConfig, routeSourceFiles, i18nWorkers);
586
255
  if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
256
+ const publicDir = nitroConfig.output?.publicDir;
257
+ if (!publicDir) throw new Error("Nitro public output directory is required to build the sitemap.");
587
258
  console.log("Building Sitemap...");
588
- await buildSitemap(config, options.prerender.sitemap, sitemapRoutes.length ? sitemapRoutes : nitroConfig.prerender.routes, getNitroPublicOutputDir(nitroConfig), routeSitemaps, { apiPrefix: options?.apiPrefix || "api" });
259
+ await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, publicDir, routeSitemaps, options.i18n);
589
260
  }
590
261
  console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
591
262
  }
592
263
  }
593
264
  };
594
265
  },
595
- generateBundle(_options, bundle) {
596
- if (!isBuild || ssrBuild) return;
597
- clientIndexHtml = captureClientIndexHtmlFromBundle(bundle, "generateBundle") ?? clientIndexHtml;
598
- },
599
- writeBundle(_options, bundle) {
600
- if (!isBuild || ssrBuild) return;
601
- clientIndexHtml = captureClientIndexHtmlFromBundle(bundle, "writeBundle") ?? clientIndexHtml;
602
- },
603
266
  async configureServer(viteServer) {
604
267
  if (isServe && !isTest) {
605
268
  const nitro = await createNitro({
606
269
  dev: true,
607
- builder: "rollup",
608
270
  ...nitroConfig
609
271
  });
610
272
  const server = createDevServer(nitro);
611
273
  await build(nitro);
612
- const nitroSourceRoots = [normalizePath(resolve(workspaceRoot, rootDir, `${sourceRoot}/server`)), ...(options?.additionalAPIDirs || []).map((dir) => normalizePath(`${workspaceRoot}${dir}`))];
613
- const isNitroSourceFile = (path) => {
614
- const normalizedPath = normalizePath(path);
615
- return nitroSourceRoots.some((root) => normalizedPath === root || normalizedPath.startsWith(`${root}/`));
616
- };
617
- let nitroRebuildPromise;
618
- let nitroRebuildPending = false;
619
- const rebuildNitroServer = () => {
620
- if (nitroRebuildPromise) {
621
- nitroRebuildPending = true;
622
- return nitroRebuildPromise;
274
+ const apiHandler = toNodeListener(server.app);
275
+ if (hasServerFns) viteServer.middlewares.use((req, res, next) => {
276
+ if (req.url?.startsWith("/_analog/fn/")) {
277
+ apiHandler(req, res);
278
+ return;
623
279
  }
624
- nitroRebuildPromise = (async () => {
625
- do {
626
- nitroRebuildPending = false;
627
- await build(nitro);
628
- } while (nitroRebuildPending);
629
- viteServer.ws.send("analog:debug-full-reload", {
630
- plugin: "vite-plugin-nitro",
631
- reason: "nitro-server-rebuilt"
632
- });
633
- viteServer.ws.send({ type: "full-reload" });
634
- })().catch((error) => {
635
- viteServer.config.logger.error(`[analog] Failed to rebuild Nitro dev server.\n${error instanceof Error ? error.stack || error.message : String(error)}`);
636
- }).finally(() => {
637
- nitroRebuildPromise = void 0;
638
- });
639
- return nitroRebuildPromise;
640
- };
641
- const onNitroSourceChange = (path) => {
642
- if (!isNitroSourceFile(path)) return;
643
- rebuildNitroServer();
644
- };
645
- viteServer.watcher.on("add", onNitroSourceChange);
646
- viteServer.watcher.on("change", onNitroSourceChange);
647
- viteServer.watcher.on("unlink", onNitroSourceChange);
648
- const apiHandler = async (req, res) => {
649
- await writeWebResponseToNode(res, await server.fetch(toWebRequest(req)));
650
- };
651
- viteServer.middlewares.use((req, res, next) => {
280
+ next();
281
+ });
282
+ if (hasAPIDir) viteServer.middlewares.use((req, res, next) => {
652
283
  if (req.url?.startsWith(`${prefix}${apiPrefix}`)) {
653
- apiHandler(req, res).catch((error) => next(error));
284
+ apiHandler(req, res);
654
285
  return;
655
286
  }
656
287
  next();
657
288
  });
289
+ else viteServer.middlewares.use(apiPrefix, apiHandler);
658
290
  viteServer.httpServer?.once("listening", () => {
659
291
  process.env["ANALOG_HOST"] = !viteServer.config.server.host ? "localhost" : viteServer.config.server.host;
660
292
  process.env["ANALOG_PORT"] = `${viteServer.config.server.port}`;
661
293
  });
662
- if (nitroOptions?.experimental?.websocket) {
663
- debugNitro("experimental websocket upgrade handler enabled");
664
- viteServer.httpServer?.on("upgrade", server.upgrade);
665
- }
294
+ if (nitroOptions?.experimental?.websocket) viteServer.httpServer?.on("upgrade", server.upgrade);
666
295
  console.log(`\n\nThe server endpoints are accessible under the "${prefix}${apiPrefix}" path.`);
667
296
  }
668
297
  },
669
298
  async closeBundle() {
670
- if (legacyClientSubBuild) return;
671
299
  if (environmentBuild) return;
672
300
  if (ssrBuild) return;
673
301
  if (isBuild) {
674
- const resolvedClientOutputPath = resolveClientOutputPath(clientOutputPath, workspaceRoot, rootDir, config.build?.outDir);
675
- debugNitro("closeBundle resolved client output path before legacy SSR build", {
676
- platform: process.platform,
677
- workspaceRoot,
678
- rootDir,
679
- cachedClientOutputPath: clientOutputPath,
680
- configuredBuildOutDir: config.build?.outDir,
681
- resolvedClientOutputPath,
682
- resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath)
683
- });
684
- const indexHtmlPath = resolve(resolvedClientOutputPath, "index.html");
685
- if (!existsSync(indexHtmlPath) && typeof clientIndexHtml !== "string") {
686
- debugNitro("closeBundle rebuilding missing client output before SSR/Nitro", {
687
- platform: process.platform,
688
- workspaceRoot,
689
- rootDir,
690
- configuredBuildOutDir: config.build?.outDir,
691
- resolvedClientOutputPath,
692
- indexHtmlPath
693
- });
694
- legacyClientSubBuild = true;
695
- try {
696
- await buildClientApp(config, options);
697
- } finally {
698
- legacyClientSubBuild = false;
699
- }
700
- }
701
- registerIndexHtmlVirtual(nitroConfig, resolvedClientOutputPath, clientIndexHtml);
702
302
  if (options?.ssr) {
703
303
  console.log("Building SSR application...");
704
- await buildSSRApp(config, options);
705
- debugSsr("closeBundle completed standalone SSR build", {
706
- ssrBuildDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
707
- clientOutputPathInfo: clientOutputPath ? getPathDebugInfo(clientOutputPath) : null
708
- });
304
+ await buildSSRApp(config, options, i18nWorkers);
709
305
  }
710
- applySsrEntryAlias(nitroConfig, options, workspaceRoot, rootDir);
711
- debugNitro("closeBundle resolved client output path before Nitro build", {
712
- platform: process.platform,
713
- workspaceRoot,
714
- rootDir,
715
- cachedClientOutputPath: clientOutputPath,
716
- configuredBuildOutDir: config.build?.outDir,
717
- resolvedClientOutputPath,
718
- resolvedClientOutputInfo: getPathDebugInfo(resolvedClientOutputPath)
719
- });
720
- registerIndexHtmlVirtual(nitroConfig, resolvedClientOutputPath, clientIndexHtml);
721
- await buildServer(options, nitroConfig, routeSourceFiles);
722
306
  if (nitroConfig.prerender?.routes?.length && options?.prerender?.sitemap) {
723
307
  console.log("Building Sitemap...");
724
- await buildSitemap(config, options.prerender.sitemap, sitemapRoutes.length ? sitemapRoutes : nitroConfig.prerender.routes, getNitroPublicOutputDir(nitroConfig), routeSitemaps, { apiPrefix: options?.apiPrefix || "api" });
308
+ await buildSitemap(config, options.prerender.sitemap, nitroConfig.prerender.routes, clientOutputPath, routeSitemaps, options.i18n);
725
309
  }
310
+ let ssrEntryPath = resolve(options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, `ssr`), `main.server${filePrefix ? ".js" : ""}`);
311
+ if (isWindows && !existsSync(ssrEntryPath)) ssrEntryPath = ssrEntryPath.replace(".js", ".mjs");
312
+ const ssrEntry = normalizePath(filePrefix + ssrEntryPath);
313
+ nitroConfig.alias = {
314
+ ...nitroConfig.alias,
315
+ "#analog/ssr": ssrEntry
316
+ };
317
+ await buildServer(options, nitroConfig, routeSourceFiles, i18nWorkers);
726
318
  console.log(`\n\nThe '@analogjs/platform' server has been successfully built.`);
727
319
  }
728
320
  }
729
321
  },
322
+ {
323
+ name: "analog-i18n-worker-entry",
324
+ apply: "build",
325
+ resolveId(id) {
326
+ return id === "virtual:analog-i18n/main.server" && options?.i18n?.loader ? "\0" + id : void 0;
327
+ },
328
+ load(id) {
329
+ if (id !== "\0virtual:analog-i18n/main.server" || !options?.i18n?.loader) return;
330
+ return i18nWorkerSsrEntry(normalizePath(resolve(workspaceRoot, rootDir, options.entryServer || `${sourceRoot}/main.server.ts`)), normalizePath(resolve(workspaceRoot, rootDir, options.i18n.loader)), options.i18n);
331
+ }
332
+ },
333
+ devServerPlugin(() => ({
334
+ ...options,
335
+ routeRules: nitroOptions?.routeRules
336
+ })),
730
337
  {
731
338
  name: "@analogjs/vite-plugin-nitro-api-prefix",
732
339
  config() {
@@ -748,24 +355,16 @@ function isEmptyPrerenderRoutes(options) {
748
355
  function isArrayWithElements(arr) {
749
356
  return !!(Array.isArray(arr) && arr.length);
750
357
  }
358
+ var isVercelPreset = (buildPreset) => process.env["VERCEL"] || buildPreset && buildPreset.toLowerCase().includes("vercel");
751
359
  var withVercelOutputAPI = (nitroConfig, workspaceRoot) => ({
752
360
  ...nitroConfig,
753
- preset: nitroConfig?.preset ?? "vercel",
754
- vercel: {
755
- ...nitroConfig?.vercel,
756
- entryFormat: nitroConfig?.vercel?.entryFormat ?? "node",
757
- functions: {
758
- runtime: nitroConfig?.vercel?.functions?.runtime ?? "nodejs24.x",
759
- ...nitroConfig?.vercel?.functions
760
- }
761
- },
762
361
  output: {
763
362
  ...nitroConfig?.output,
764
363
  dir: normalizePath(resolve(workspaceRoot, ".vercel", "output")),
765
364
  publicDir: normalizePath(resolve(workspaceRoot, ".vercel", "output/static"))
766
365
  }
767
366
  });
768
- var isCloudflarePreset = (buildPreset) => process.env["CF_PAGES"] || buildPreset && (buildPreset.toLowerCase().includes("cloudflare-pages") || buildPreset.toLowerCase().includes("cloudflare_pages"));
367
+ var isCloudflarePreset = (buildPreset) => process.env["CF_PAGES"] || buildPreset && buildPreset.toLowerCase().includes("cloudflare-pages");
769
368
  var withCloudflareOutput = (nitroConfig) => ({
770
369
  ...nitroConfig,
771
370
  output: {
@@ -818,6 +417,32 @@ var withNetlifyOutputAPI = (nitroConfig, workspaceRoot) => ({
818
417
  dir: normalizePath(resolve(workspaceRoot, "netlify/functions"))
819
418
  }
820
419
  });
420
+ /**
421
+ * Reads the options passed to `analog()` from `@analogjs/platform`, which
422
+ * exposes them on its plugin `api`.
423
+ */
424
+ function getAnalogOptions(userConfig) {
425
+ return (userConfig.plugins ?? []).flat(Infinity).find((plugin) => plugin?.api?.analogOptions)?.api?.analogOptions;
426
+ }
427
+ /**
428
+ * Stamps `ssr: false` and `streaming: false` route rules as response headers,
429
+ * which the renderers read to skip SSR or streaming for matching routes.
430
+ */
431
+ function withAnalogRouteRuleHeaders(nitroOptions) {
432
+ if (!nitroOptions.routeRules) return nitroOptions;
433
+ const routeRules = Object.fromEntries(Object.entries(nitroOptions.routeRules).map(([route, rule]) => [route, {
434
+ ...rule,
435
+ headers: {
436
+ ...rule.headers,
437
+ ...rule.ssr === false ? { "x-analog-no-ssr": "true" } : {},
438
+ ...rule.streaming === false ? { "x-analog-no-streaming": "true" } : {}
439
+ }
440
+ }]));
441
+ return {
442
+ ...nitroOptions,
443
+ routeRules
444
+ };
445
+ }
821
446
  //#endregion
822
447
  export { nitro };
823
448