@nuxt/nitro-server 4.2.2 → 4.3.1

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 (68) hide show
  1. package/README.md +5 -3
  2. package/dist/THIRD-PARTY-LICENSES.md +18 -0
  3. package/dist/index.d.mts +50741 -79
  4. package/dist/index.mjs +678 -754
  5. package/dist/runtime/handlers/{error.d.ts → error.d.mts} +1 -1
  6. package/dist/runtime/handlers/error.mjs +77 -0
  7. package/dist/runtime/handlers/island.d.mts +2 -0
  8. package/dist/runtime/handlers/island.mjs +120 -0
  9. package/dist/runtime/handlers/renderer.d.mts +2 -0
  10. package/dist/runtime/handlers/renderer.mjs +305 -0
  11. package/dist/runtime/middleware/no-ssr.d.mts +2 -0
  12. package/dist/runtime/middleware/no-ssr.mjs +7 -0
  13. package/dist/runtime/plugins/dev-server-logs.d.mts +2 -0
  14. package/dist/runtime/plugins/dev-server-logs.mjs +94 -0
  15. package/dist/runtime/templates/error-500.d.mts +2 -0
  16. package/dist/runtime/templates/error-500.mjs +15 -0
  17. package/dist/runtime/utils/app-config.d.mts +3 -0
  18. package/dist/runtime/utils/app-config.mjs +31 -0
  19. package/dist/runtime/utils/cache.d.mts +5 -0
  20. package/dist/runtime/utils/cache.mjs +20 -0
  21. package/dist/runtime/utils/config.d.mts +1 -0
  22. package/dist/runtime/utils/{dev.d.ts → dev.d.mts} +1 -1
  23. package/dist/runtime/utils/dev.mjs +985 -0
  24. package/dist/runtime/utils/error.d.mts +6 -0
  25. package/dist/runtime/utils/error.mjs +15 -0
  26. package/dist/runtime/utils/paths.mjs +19 -0
  27. package/dist/runtime/utils/renderer/{app.d.ts → app.d.mts} +4 -4
  28. package/dist/runtime/utils/renderer/app.mjs +38 -0
  29. package/dist/runtime/utils/renderer/build-files.d.mts +16 -0
  30. package/dist/runtime/utils/renderer/build-files.mjs +100 -0
  31. package/dist/runtime/utils/renderer/{inline-styles.d.ts → inline-styles.d.mts} +1 -1
  32. package/dist/runtime/utils/renderer/inline-styles.mjs +13 -0
  33. package/dist/runtime/utils/renderer/{islands.d.ts → islands.d.mts} +5 -5
  34. package/dist/runtime/utils/renderer/islands.mjs +87 -0
  35. package/dist/runtime/utils/renderer/payload.d.mts +24 -0
  36. package/dist/runtime/utils/renderer/payload.mjs +64 -0
  37. package/package.json +20 -18
  38. package/dist/index.d.ts +0 -85
  39. package/dist/runtime/handlers/error.js +0 -63
  40. package/dist/runtime/handlers/island.d.ts +0 -4
  41. package/dist/runtime/handlers/island.js +0 -100
  42. package/dist/runtime/handlers/renderer.d.ts +0 -8
  43. package/dist/runtime/handlers/renderer.js +0 -238
  44. package/dist/runtime/middleware/no-ssr.d.ts +0 -2
  45. package/dist/runtime/middleware/no-ssr.js +0 -7
  46. package/dist/runtime/plugins/dev-server-logs.d.ts +0 -3
  47. package/dist/runtime/plugins/dev-server-logs.js +0 -82
  48. package/dist/runtime/templates/error-500.d.ts +0 -2
  49. package/dist/runtime/templates/error-500.js +0 -6
  50. package/dist/runtime/utils/app-config.d.ts +0 -2
  51. package/dist/runtime/utils/app-config.js +0 -25
  52. package/dist/runtime/utils/cache-driver.d.ts +0 -6
  53. package/dist/runtime/utils/cache.d.ts +0 -8
  54. package/dist/runtime/utils/cache.js +0 -19
  55. package/dist/runtime/utils/config.d.ts +0 -1
  56. package/dist/runtime/utils/dev.js +0 -334
  57. package/dist/runtime/utils/error.d.ts +0 -6
  58. package/dist/runtime/utils/error.js +0 -11
  59. package/dist/runtime/utils/paths.js +0 -16
  60. package/dist/runtime/utils/renderer/app.js +0 -33
  61. package/dist/runtime/utils/renderer/build-files.d.ts +0 -22
  62. package/dist/runtime/utils/renderer/build-files.js +0 -85
  63. package/dist/runtime/utils/renderer/inline-styles.js +0 -13
  64. package/dist/runtime/utils/renderer/islands.js +0 -82
  65. package/dist/runtime/utils/renderer/payload.d.ts +0 -37
  66. package/dist/runtime/utils/renderer/payload.js +0 -67
  67. /package/dist/runtime/utils/{config.js → config.mjs} +0 -0
  68. /package/dist/runtime/utils/{paths.d.ts → paths.d.mts} +0 -0
package/dist/index.mjs CHANGED
@@ -1,99 +1,71 @@
1
- import { fileURLToPath, pathToFileURL } from 'node:url';
2
- import { existsSync, promises, readFileSync } from 'node:fs';
3
- import { cpus } from 'node:os';
4
- import process from 'node:process';
5
- import { readFile, mkdir, writeFile } from 'node:fs/promises';
6
- import { randomUUID } from 'node:crypto';
7
- import { dirname, relative, resolve, join, isAbsolute } from 'pathe';
8
- import { readPackageJSON } from 'pkg-types';
9
- import { toRouteMatcher, createRouter, exportMatcher } from 'radix3';
10
- import { withTrailingSlash, joinURL } from 'ufo';
11
- import { createNitro, scanHandlers, writeTypes, copyPublicAssets, prepare, build, prerender, createDevServer } from 'nitropack';
12
- import { getLayerDirectories, getDirectory, resolveNuxtModule, addTemplate, resolveAlias, addPlugin, resolveIgnorePatterns, createIsIgnored, addVitePlugin, logger, findPath } from '@nuxt/kit';
13
- import escapeRE from 'escape-string-regexp';
14
- import { defu } from 'defu';
15
- import { dynamicEventHandler, defineEventHandler } from 'h3';
16
- import { isWindows } from 'std-env';
17
- import { ImpoundPlugin } from 'impound';
18
- import { resolveModulePath } from 'exsolve';
19
-
20
- const version = "4.2.2";
21
-
1
+ import { fileURLToPath, pathToFileURL } from "node:url";
2
+ import { existsSync, promises, readFileSync } from "node:fs";
3
+ import { cpus } from "node:os";
4
+ import process from "node:process";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { randomUUID } from "node:crypto";
7
+ import { addRoute, createRouter, findAllRoutes } from "rou3";
8
+ import { compileRouterToString } from "rou3/compiler";
9
+ import { dirname, isAbsolute, join, relative, resolve } from "pathe";
10
+ import { readPackageJSON } from "pkg-types";
11
+ import { joinURL, withTrailingSlash } from "ufo";
12
+ import { hash } from "ohash";
13
+ import { build, copyPublicAssets, createDevServer, createNitro, prepare, prerender, scanHandlers, writeTypes } from "nitropack";
14
+ import { addPlugin, addTemplate, addVitePlugin, createIsIgnored, findPath, getDirectory, getLayerDirectories, logger, resolveAlias, resolveIgnorePatterns, resolveNuxtModule } from "@nuxt/kit";
15
+ import escapeRE from "escape-string-regexp";
16
+ import { defu } from "defu";
17
+ import { defineEventHandler, dynamicEventHandler, handleCors, setHeader } from "h3";
18
+ import { isWindows } from "std-env";
19
+ import { ImpoundPlugin } from "impound";
20
+ import { resolveModulePath } from "exsolve";
21
+ import { runtimeDependencies } from "nitropack/runtime/meta";
22
+ var version = "4.3.1";
22
23
  function toArray(value) {
23
- return Array.isArray(value) ? value : [value];
24
+ return Array.isArray(value) ? value : [value];
24
25
  }
25
26
  let _distDir = dirname(fileURLToPath(import.meta.url));
26
- if (/(?:chunks|shared)$/.test(_distDir)) {
27
- _distDir = dirname(_distDir);
28
- }
27
+ if (/(?:chunks|shared)$/.test(_distDir)) _distDir = dirname(_distDir);
29
28
  const distDir = _distDir;
30
-
31
29
  const template = () => {
32
- return '<svg xmlns="http://www.w3.org/2000/svg" width="80" fill="none" class="nuxt-spa-loading" viewBox="0 0 37 25"><path d="M24.236 22.006h10.742L25.563 5.822l-8.979 14.31a4 4 0 0 1-3.388 1.874H2.978l11.631-20 5.897 10.567"/></svg><style>.nuxt-spa-loading{left:50%;position:fixed;top:50%;transform:translate(-50%,-50%)}.nuxt-spa-loading>path{animation:nuxt-spa-loading-move 3s linear infinite;fill:none;stroke:#00dc82;stroke-dasharray:128;stroke-dashoffset:128;stroke-linecap:round;stroke-linejoin:round;stroke-width:4px}@keyframes nuxt-spa-loading-move{to{stroke-dashoffset:-128}}</style>';
30
+ return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" fill=\"none\" class=\"nuxt-spa-loading\" viewBox=\"0 0 37 25\"><path d=\"M24.236 22.006h10.742L25.563 5.822l-8.979 14.31a4 4 0 0 1-3.388 1.874H2.978l11.631-20 5.897 10.567\"/></svg><style>.nuxt-spa-loading{left:50%;position:fixed;top:50%;transform:translate(-50%,-50%)}.nuxt-spa-loading>path{animation:nuxt-spa-loading-move 3s linear infinite;fill:none;stroke:#00dc82;stroke-dasharray:128;stroke-dashoffset:128;stroke-linecap:round;stroke-linejoin:round;stroke-width:4px}@keyframes nuxt-spa-loading-move{to{stroke-dashoffset:-128}}</style>";
33
31
  };
34
-
35
32
  function createImportProtectionPatterns(nuxt, options) {
36
- const patterns = [];
37
- const context = contextFlags[options.context];
38
- patterns.push([
39
- /^(nuxt|nuxt3|nuxt-nightly)$/,
40
- `\`nuxt\`, or \`nuxt-nightly\` cannot be imported directly in ${context}.` + (options.context === "nuxt-app" ? " Instead, import runtime Nuxt composables from `#app` or `#imports`." : "")
41
- ]);
42
- patterns.push([
43
- /^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/,
44
- "Importing directly from a `nuxt.config` file is not allowed. Instead, use runtime config or a module."
45
- ]);
46
- patterns.push([/(^|node_modules\/)@vue\/composition-api/]);
47
- for (const mod of nuxt.options._installedModules) {
48
- if (mod.entryPath) {
49
- patterns.push([
50
- new RegExp(`^${escapeRE(mod.entryPath)}$`),
51
- "Importing directly from module entry-points is not allowed."
52
- ]);
53
- }
54
- }
55
- for (const i of [/(^|node_modules\/)@nuxt\/(cli|kit|test-utils)/, /(^|node_modules\/)nuxi/, /(^|node_modules\/)nitro(?:pack)?(?:-nightly)?(?:$|\/)(?!(?:dist\/)?(?:node_modules|presets|runtime|types))/, /(^|node_modules\/)nuxt\/(config|kit|schema)/]) {
56
- patterns.push([i, `This module cannot be imported in ${context}.`]);
57
- }
58
- if (options.context === "nitro-app" || options.context === "shared") {
59
- for (const i of ["#app", /^#build(\/|$)/]) {
60
- patterns.push([i, `Vue app aliases are not allowed in ${context}.`]);
61
- }
62
- }
63
- if (options.context === "nuxt-app" || options.context === "shared") {
64
- patterns.push([
65
- new RegExp(escapeRE(relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, nuxt.options.serverDir || "server"))) + "\\/(api|routes|middleware|plugins)\\/"),
66
- `Importing from server is not allowed in ${context}.`
67
- ]);
68
- }
69
- return patterns;
33
+ const patterns = [];
34
+ const context = contextFlags[options.context];
35
+ patterns.push([/^(nuxt|nuxt3|nuxt-nightly)$/, `\`nuxt\`, or \`nuxt-nightly\` cannot be imported directly in ${context}.` + (options.context === "nuxt-app" ? " Instead, import runtime Nuxt composables from `#app` or `#imports`." : "")]);
36
+ patterns.push([/^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/, "Importing directly from a `nuxt.config` file is not allowed. Instead, use runtime config or a module."]);
37
+ patterns.push([/(^|node_modules\/)@vue\/composition-api/]);
38
+ for (const mod of nuxt.options._installedModules) if (mod.entryPath) patterns.push([new RegExp(`^${escapeRE(mod.entryPath)}$`), "Importing directly from module entry-points is not allowed."]);
39
+ for (const i of [
40
+ /(^|node_modules\/)@nuxt\/(cli|kit|test-utils)/,
41
+ /(^|node_modules\/)nuxi/,
42
+ /(^|node_modules\/)nitro(?:pack)?(?:-nightly)?(?:$|\/)(?!(?:dist\/)?(?:node_modules|presets|runtime|types))/,
43
+ /(^|node_modules\/)nuxt\/(config|kit|schema)/
44
+ ]) patterns.push([i, `This module cannot be imported in ${context}.`]);
45
+ if (options.context === "nitro-app" || options.context === "shared") for (const i of ["#app", /^#build(\/|$)/]) patterns.push([i, `Vue app aliases are not allowed in ${context}.`]);
46
+ if (options.context === "nuxt-app" || options.context === "shared") {
47
+ patterns.push([new RegExp(escapeRE(relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, nuxt.options.serverDir || "server"))) + "\\/(api|routes|middleware|plugins)\\/"), `Importing from server is not allowed in ${context}.`]);
48
+ patterns.push([/^#server(\/|$)/, `Server aliases are not allowed in ${context}.`]);
49
+ }
50
+ return patterns;
70
51
  }
71
52
  const contextFlags = {
72
- "nitro-app": "server runtime",
73
- "nuxt-app": "the Vue part of your app",
74
- "shared": "the #shared directory"
53
+ "nitro-app": "server runtime",
54
+ "nuxt-app": "the Vue part of your app",
55
+ "shared": "the #shared directory"
75
56
  };
76
-
77
57
  const nitroSchemaTemplate = {
78
- filename: "types/nitro-nuxt.d.ts",
79
- async getContents({ nuxt }) {
80
- const references = [];
81
- const declarations = [];
82
- await nuxt.callHook("nitro:prepare:types", { references, declarations });
83
- const sourceDir = join(nuxt.options.buildDir, "types");
84
- const lines = [
85
- ...references.map((ref) => {
86
- if ("path" in ref && isAbsolute(ref.path)) {
87
- ref.path = relative(sourceDir, ref.path);
88
- }
89
- return `/// <reference ${renderAttrs(ref)} />`;
90
- }),
91
- ...declarations
92
- ];
93
- return (
94
- /* typescript */
95
- `
96
- ${lines.join("\n")}
58
+ filename: "types/nitro-nuxt.d.ts",
59
+ async getContents({ nuxt }) {
60
+ const references = [];
61
+ const declarations = [];
62
+ await nuxt.callHook("nitro:prepare:types", {
63
+ references,
64
+ declarations
65
+ });
66
+ const typesDir = join(nuxt.options.buildDir, "types");
67
+ return `
68
+ ${[...references.map((ref) => renderReference(ref, typesDir)), ...declarations].join("\n")}
97
69
 
98
70
  import type { RuntimeConfig } from 'nuxt/schema'
99
71
  import type { H3Event } from 'h3'
@@ -118,6 +90,7 @@ declare module 'nitropack' {
118
90
  /** @deprecated Use \`noScripts\` instead */
119
91
  experimentalNoScripts?: boolean
120
92
  appMiddleware?: Record<string, boolean>
93
+ appLayout?: string | false
121
94
  }
122
95
  interface NitroRuntimeHooks {
123
96
  'dev:ssr-logs': (ctx: { logs: LogObject[], path: string }) => void | Promise<void>
@@ -143,6 +116,7 @@ declare module 'nitropack/types' {
143
116
  /** @deprecated Use \`noScripts\` instead */
144
117
  experimentalNoScripts?: boolean
145
118
  appMiddleware?: Record<string, boolean>
119
+ appLayout?: string | false
146
120
  }
147
121
  interface NitroRuntimeHooks {
148
122
  'dev:ssr-logs': (ctx: { logs: LogObject[], path: string }) => void | Promise<void>
@@ -150,688 +124,638 @@ declare module 'nitropack/types' {
150
124
  'render:island': (islandResponse: NuxtIslandResponse, context: { event: H3Event, islandContext: NuxtIslandContext }) => void | Promise<void>
151
125
  }
152
126
  }
153
- `
154
- );
155
- }
127
+ `;
128
+ }
156
129
  };
157
- function renderAttr(key, value) {
158
- return value ? `${key}="${value}"` : "";
159
- }
160
- function renderAttrs(obj) {
161
- const attrs = [];
162
- for (const key in obj) {
163
- attrs.push(renderAttr(key, obj[key]));
164
- }
165
- return attrs.join(" ");
130
+ function renderReference(ref, baseDir) {
131
+ return `/// <reference ${"path" in ref ? `path="${isAbsolute(ref.path) ? relative(baseDir, ref.path) : ref.path}"` : `types="${ref.types}"`} />`;
166
132
  }
167
-
168
133
  const logLevelMapReverse = {
169
- silent: 0,
170
- info: 3,
171
- verbose: 3
134
+ silent: 0,
135
+ info: 3,
136
+ verbose: 3
172
137
  };
173
138
  const NODE_MODULES_RE = /(?<=\/)node_modules\/(.+)$/;
174
139
  const PNPM_NODE_MODULES_RE = /\.pnpm\/.+\/node_modules\/(.+)$/;
175
140
  async function bundle(nuxt) {
176
- const layerDirs = getLayerDirectories(nuxt);
177
- const excludePaths = [];
178
- for (const dirs of layerDirs) {
179
- const paths = [
180
- dirs.root.match(NODE_MODULES_RE)?.[1]?.replace(/\/$/, ""),
181
- dirs.root.match(PNPM_NODE_MODULES_RE)?.[1]?.replace(/\/$/, "")
182
- ];
183
- for (const dir of paths) {
184
- if (dir) {
185
- excludePaths.push(escapeRE(dir));
186
- }
187
- }
188
- }
189
- const layerPublicAssetsDirs = [];
190
- for (const dirs of layerDirs) {
191
- if (existsSync(dirs.public)) {
192
- layerPublicAssetsDirs.push({ dir: dirs.public });
193
- }
194
- }
195
- const excludePattern = excludePaths.length ? [new RegExp(`node_modules\\/(?!${excludePaths.join("|")})`)] : [/node_modules/];
196
- const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
197
- const moduleEntryPaths = [];
198
- for (const m of nuxt.options._installedModules) {
199
- const path = m.meta?.rawPath || m.entryPath;
200
- if (path) {
201
- moduleEntryPaths.push(getDirectory(path));
202
- }
203
- }
204
- const modules = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
205
- addTemplate(nitroSchemaTemplate);
206
- const sharedDirs = /* @__PURE__ */ new Set();
207
- if (nuxt.options.nitro.imports !== false && nuxt.options.imports.scan !== false) {
208
- for (const layer of nuxt.options._layers) {
209
- if (layer.config?.imports?.scan === false) {
210
- continue;
211
- }
212
- sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "utils"));
213
- sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "types"));
214
- }
215
- }
216
- nuxt.options.nitro.plugins ||= [];
217
- nuxt.options.nitro.plugins = nuxt.options.nitro.plugins.map((plugin) => plugin ? resolveAlias(plugin, nuxt.options.alias) : plugin);
218
- if (nuxt.options.dev && nuxt.options.features.devLogs) {
219
- addPlugin(resolve(nuxt.options.appDir, "plugins/dev-server-logs"));
220
- nuxt.options.nitro.plugins.push(resolve(distDir, "runtime/plugins/dev-server-logs"));
221
- nuxt.options.nitro.externals = defu(nuxt.options.nitro.externals, {
222
- inline: [/#internal\/dev-server-logs-options/]
223
- });
224
- nuxt.options.nitro.virtual = defu(nuxt.options.nitro.virtual, {
225
- "#internal/dev-server-logs-options": () => `export const rootDir = ${JSON.stringify(nuxt.options.rootDir)};`
226
- });
227
- }
228
- if (nuxt.options.experimental.componentIslands) {
229
- nuxt.options.nitro.virtual ||= {};
230
- nuxt.options.nitro.virtual["#internal/nuxt/island-renderer.mjs"] = () => {
231
- if (nuxt.options.dev || nuxt.options.experimental.componentIslands !== "auto" || nuxt.apps.default?.pages?.some((p) => p.mode === "server") || nuxt.apps.default?.components?.some((c) => c.mode === "server" && !nuxt.apps.default?.components.some((other) => other.pascalName === c.pascalName && other.mode === "client"))) {
232
- return `export { default } from '${resolve(distDir, "runtime/handlers/island")}'`;
233
- }
234
- return `import { defineEventHandler } from 'h3'; export default defineEventHandler(() => {});`;
235
- };
236
- nuxt.options.nitro.handlers ||= [];
237
- nuxt.options.nitro.handlers.push({
238
- route: "/__nuxt_island/**",
239
- handler: "#internal/nuxt/island-renderer.mjs"
240
- });
241
- if (!nuxt.options.ssr && nuxt.options.experimental.componentIslands !== "auto") {
242
- nuxt.options.ssr = true;
243
- nuxt.options.nitro.routeRules ||= {};
244
- nuxt.options.nitro.routeRules["/**"] = defu(nuxt.options.nitro.routeRules["/**"], { ssr: false });
245
- }
246
- }
247
- const mockProxy = resolveModulePath("mocked-exports/proxy", { from: import.meta.url });
248
- const { version: nuxtVersion } = await readPackageJSON("nuxt", { from: import.meta.url });
249
- const nitroConfig = defu(nuxt.options.nitro, {
250
- debug: nuxt.options.debug ? nuxt.options.debug.nitro : false,
251
- rootDir: nuxt.options.rootDir,
252
- workspaceDir: nuxt.options.workspaceDir,
253
- srcDir: nuxt.options.serverDir,
254
- dev: nuxt.options.dev,
255
- buildDir: nuxt.options.buildDir,
256
- experimental: {
257
- asyncContext: nuxt.options.experimental.asyncContext,
258
- typescriptBundlerResolution: nuxt.options.future.typescriptBundlerResolution || nuxt.options.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler" || nuxt.options.nitro.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler"
259
- },
260
- framework: {
261
- name: "nuxt",
262
- version: nuxtVersion || version
263
- },
264
- imports: {
265
- autoImport: nuxt.options.imports.autoImport,
266
- dirs: [...sharedDirs],
267
- imports: [
268
- {
269
- as: "__buildAssetsURL",
270
- name: "buildAssetsURL",
271
- from: resolve(distDir, "runtime/utils/paths")
272
- },
273
- {
274
- as: "__publicAssetsURL",
275
- name: "publicAssetsURL",
276
- from: resolve(distDir, "runtime/utils/paths")
277
- },
278
- {
279
- // TODO: Remove after https://github.com/nitrojs/nitro/issues/1049
280
- as: "defineAppConfig",
281
- name: "defineAppConfig",
282
- from: resolve(distDir, "runtime/utils/config"),
283
- priority: -1
284
- }
285
- ],
286
- exclude: [...excludePattern, /[\\/]\.git[\\/]/]
287
- },
288
- esbuild: {
289
- options: { exclude: excludePattern }
290
- },
291
- analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) ? {
292
- template: "treemap",
293
- projectRoot: nuxt.options.rootDir,
294
- filename: join(nuxt.options.analyzeDir, "{name}.html")
295
- } : false,
296
- scanDirs: layerDirs.map((dirs) => dirs.server),
297
- renderer: resolve(distDir, "runtime/handlers/renderer"),
298
- nodeModulesDirs: nuxt.options.modulesDir,
299
- handlers: nuxt.options.serverHandlers,
300
- devHandlers: [],
301
- baseURL: nuxt.options.app.baseURL,
302
- virtual: {
303
- "#internal/nuxt.config.mjs": () => nuxt.vfs["#build/nuxt.config.mjs"] || "",
304
- "#internal/nuxt/app-config": () => nuxt.vfs["#build/app.config.mjs"]?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, "") || "",
305
- "#spa-template": async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`,
306
- // this will be overridden in vite plugin
307
- "#internal/entry-chunk.mjs": () => `export const entryFileName = undefined`,
308
- "#internal/nuxt/entry-ids.mjs": () => `export default []`
309
- },
310
- routeRules: {
311
- "/__nuxt_error": { cache: false }
312
- },
313
- appConfig: nuxt.options.appConfig,
314
- appConfigFiles: layerDirs.map((dirs) => join(dirs.app, "app.config")),
315
- typescript: {
316
- strict: true,
317
- generateTsConfig: true,
318
- tsconfigPath: "tsconfig.server.json",
319
- tsConfig: {
320
- compilerOptions: {
321
- lib: ["esnext", "webworker", "dom.iterable"],
322
- skipLibCheck: true
323
- },
324
- include: [
325
- join(nuxt.options.buildDir, "types/nitro-nuxt.d.ts"),
326
- ...modules.flatMap((m) => {
327
- const moduleDir = relativeWithDot(nuxt.options.buildDir, m);
328
- return [
329
- join(moduleDir, "runtime/server"),
330
- join(moduleDir, "dist/runtime/server")
331
- ];
332
- }),
333
- ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.server, "**/*"))),
334
- ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.shared, "**/*.d.ts")))
335
- ],
336
- exclude: [
337
- ...nuxt.options.modulesDir.map((m) => relativeWithDot(nuxt.options.buildDir, m)),
338
- relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, "dist"))
339
- ]
340
- }
341
- },
342
- publicAssets: [
343
- nuxt.options.dev ? { dir: resolve(nuxt.options.buildDir, "dist/client") } : {
344
- dir: join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir),
345
- maxAge: 31536e3,
346
- baseURL: nuxt.options.app.buildAssetsDir
347
- },
348
- ...layerPublicAssetsDirs
349
- ],
350
- prerender: {
351
- ignoreUnprefixedPublicAssets: true,
352
- failOnError: true,
353
- concurrency: cpus().length * 4 || 4,
354
- routes: [].concat(nuxt.options.generate.routes)
355
- },
356
- sourceMap: nuxt.options.sourcemap.server,
357
- externals: {
358
- inline: [
359
- ...nuxt.options.dev ? [] : [
360
- ...nuxt.options.experimental.externalVue ? [] : ["vue", "@vue/"],
361
- "@nuxt/",
362
- nuxt.options.buildDir
363
- ],
364
- ...nuxt.options.build.transpile.filter((i) => typeof i === "string"),
365
- "nuxt/dist",
366
- "nuxt3/dist",
367
- "nuxt-nightly/dist",
368
- distDir,
369
- // Ensure app config files have auto-imports injected even if they are pure .js files
370
- ...layerDirs.map((dirs) => join(dirs.app, "app.config"))
371
- ],
372
- traceInclude: [
373
- // force include files used in generated code from the runtime-compiler
374
- ...nuxt.options.vue.runtimeCompiler && !nuxt.options.experimental.externalVue ? [
375
- ...nuxt.options.modulesDir.reduce((targets, path) => {
376
- const serverRendererPath = resolve(path, "vue/server-renderer/index.js");
377
- if (existsSync(serverRendererPath)) {
378
- targets.push(serverRendererPath);
379
- }
380
- return targets;
381
- }, [])
382
- ] : []
383
- ]
384
- },
385
- alias: {
386
- // Vue 3 mocks
387
- ...nuxt.options.vue.runtimeCompiler || nuxt.options.experimental.externalVue ? {} : {
388
- "estree-walker": mockProxy,
389
- "@babel/parser": mockProxy,
390
- "@vue/compiler-core": mockProxy,
391
- "@vue/compiler-dom": mockProxy,
392
- "@vue/compiler-ssr": mockProxy
393
- },
394
- "@vue/devtools-api": "vue-devtools-stub",
395
- // Nuxt aliases
396
- ...nuxt.options.alias,
397
- // Paths
398
- "#internal/nuxt/paths": resolve(distDir, "runtime/utils/paths")
399
- },
400
- replace: {
401
- "process.env.NUXT_NO_SSR": String(nuxt.options.ssr === false),
402
- "process.env.NUXT_EARLY_HINTS": String(nuxt.options.experimental.writeEarlyHints !== false),
403
- "process.env.NUXT_NO_SCRIPTS": String(nuxt.options.features.noScripts === "all" || !!nuxt.options.features.noScripts && !nuxt.options.dev),
404
- "process.env.NUXT_INLINE_STYLES": String(!!nuxt.options.features.inlineStyles),
405
- "process.env.PARSE_ERROR_DATA": String(!!nuxt.options.experimental.parseErrorData),
406
- "process.env.NUXT_JSON_PAYLOADS": String(!!nuxt.options.experimental.renderJsonPayloads),
407
- "process.env.NUXT_ASYNC_CONTEXT": String(!!nuxt.options.experimental.asyncContext),
408
- "process.env.NUXT_SHARED_DATA": String(!!nuxt.options.experimental.sharedPrerenderData),
409
- "process.dev": String(nuxt.options.dev),
410
- "__VUE_PROD_DEVTOOLS__": String(false)
411
- },
412
- rollupConfig: {
413
- output: {
414
- generatedCode: {
415
- symbols: true
416
- // temporary fix for https://github.com/vuejs/core/issues/8351
417
- }
418
- },
419
- plugins: []
420
- },
421
- logLevel: logLevelMapReverse[nuxt.options.logLevel]
422
- });
423
- if (nuxt.options.experimental.serverAppConfig && nitroConfig.imports) {
424
- nitroConfig.imports.imports ||= [];
425
- nitroConfig.imports.imports.push({
426
- name: "useAppConfig",
427
- from: resolve(distDir, "runtime/utils/app-config"),
428
- priority: -1
429
- });
430
- }
431
- if (!nitroConfig.errorHandler && (nuxt.options.dev || !nuxt.options.experimental.noVueServer)) {
432
- nitroConfig.errorHandler = resolve(distDir, "runtime/handlers/error");
433
- }
434
- nitroConfig.srcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nitroConfig.srcDir);
435
- nitroConfig.ignore ||= [];
436
- nitroConfig.ignore.push(
437
- ...resolveIgnorePatterns(nitroConfig.srcDir),
438
- `!${join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir, "**/*")}`
439
- );
440
- if (nuxt.options.experimental.appManifest) {
441
- const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
442
- const buildTimestamp = Date.now();
443
- const manifestPrefix = joinURL(nuxt.options.app.buildAssetsDir, "builds");
444
- const tempDir = join(nuxt.options.buildDir, "manifest");
445
- nitroConfig.prerender ||= {};
446
- nitroConfig.prerender.ignore ||= [];
447
- nitroConfig.prerender.ignore.push(joinURL(nuxt.options.app.baseURL, manifestPrefix));
448
- nitroConfig.publicAssets.unshift(
449
- // build manifest
450
- {
451
- dir: join(tempDir, "meta"),
452
- maxAge: 31536e3,
453
- baseURL: joinURL(manifestPrefix, "meta")
454
- },
455
- // latest build
456
- {
457
- dir: tempDir,
458
- maxAge: 1,
459
- baseURL: manifestPrefix
460
- }
461
- );
462
- nuxt.options.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
463
- if (!nuxt.options.dev) {
464
- nuxt.hook("build:before", async () => {
465
- await promises.mkdir(join(tempDir, "meta"), { recursive: true });
466
- await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify({}));
467
- });
468
- }
469
- nuxt.hook("nitro:config", (config) => {
470
- config.alias ||= {};
471
- config.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
472
- const rules = config.routeRules;
473
- for (const rule in rules) {
474
- if (!rules[rule].appMiddleware) {
475
- continue;
476
- }
477
- const value = rules[rule].appMiddleware;
478
- if (typeof value === "string") {
479
- rules[rule].appMiddleware = { [value]: true };
480
- } else if (Array.isArray(value)) {
481
- const normalizedRules = {};
482
- for (const middleware of value) {
483
- normalizedRules[middleware] = true;
484
- }
485
- rules[rule].appMiddleware = normalizedRules;
486
- }
487
- }
488
- });
489
- nuxt.hook("nitro:init", (nitro2) => {
490
- nitro2.hooks.hook("rollup:before", async (nitro3) => {
491
- const routeRules = {};
492
- const _routeRules = nitro3.options.routeRules;
493
- const validManifestKeys = /* @__PURE__ */ new Set(["prerender", "redirect", "appMiddleware"]);
494
- for (const key in _routeRules) {
495
- if (key === "/__nuxt_error") {
496
- continue;
497
- }
498
- let hasRules = false;
499
- const filteredRules = {};
500
- for (const routeKey in _routeRules[key]) {
501
- const value = _routeRules[key][routeKey];
502
- if (value && validManifestKeys.has(routeKey)) {
503
- if (routeKey === "redirect") {
504
- filteredRules[routeKey] = typeof value === "string" ? value : value.to;
505
- } else {
506
- filteredRules[routeKey] = value;
507
- }
508
- hasRules = true;
509
- }
510
- }
511
- if (hasRules) {
512
- routeRules[key] = filteredRules;
513
- }
514
- }
515
- const prerenderedRoutes = /* @__PURE__ */ new Set();
516
- const routeRulesMatcher = toRouteMatcher(
517
- createRouter({ routes: routeRules })
518
- );
519
- if (nitro3._prerenderedRoutes?.length) {
520
- const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? "/_payload.json" : "/_payload.js";
521
- for (const route of nitro3._prerenderedRoutes) {
522
- if (!route.error && route.route.endsWith(payloadSuffix)) {
523
- const url = route.route.slice(0, -payloadSuffix.length) || "/";
524
- const rules = defu({}, ...routeRulesMatcher.matchAll(url).reverse());
525
- if (!rules.prerender) {
526
- prerenderedRoutes.add(url);
527
- }
528
- }
529
- }
530
- }
531
- const manifest = {
532
- id: buildId,
533
- timestamp: buildTimestamp,
534
- matcher: exportMatcher(routeRulesMatcher),
535
- prerendered: nuxt.options.dev ? [] : [...prerenderedRoutes]
536
- };
537
- await promises.mkdir(join(tempDir, "meta"), { recursive: true });
538
- await promises.writeFile(join(tempDir, "latest.json"), JSON.stringify({
539
- id: buildId,
540
- timestamp: buildTimestamp
541
- }));
542
- await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify(manifest));
543
- });
544
- });
545
- }
546
- if (!nuxt.options.experimental.appManifest) {
547
- nuxt.options.alias["#app-manifest"] = mockProxy;
548
- }
549
- const FORWARD_SLASH_RE = /\//g;
550
- if (!nuxt.options.ssr) {
551
- nitroConfig.virtual["#build/dist/server/server.mjs"] = "export default () => {}";
552
- if (process.platform === "win32") {
553
- nitroConfig.virtual["#build/dist/server/server.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default () => {}";
554
- }
555
- }
556
- if (nuxt.options.dev || nuxt.options.builder === "@nuxt/webpack-builder" || nuxt.options.builder === "@nuxt/rspack-builder") {
557
- nitroConfig.virtual["#build/dist/server/styles.mjs"] = "export default {}";
558
- if (process.platform === "win32") {
559
- nitroConfig.virtual["#build/dist/server/styles.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default {}";
560
- }
561
- }
562
- nitroConfig.rollupConfig.plugins = await nitroConfig.rollupConfig.plugins || [];
563
- nitroConfig.rollupConfig.plugins = toArray(nitroConfig.rollupConfig.plugins);
564
- const sharedDir = withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared));
565
- const relativeSharedDir = withTrailingSlash(relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, nuxt.options.dir.shared)));
566
- const sharedPatterns = [/^#shared\//, new RegExp("^" + escapeRE(sharedDir)), new RegExp("^" + escapeRE(relativeSharedDir))];
567
- nitroConfig.rollupConfig.plugins.push(
568
- ImpoundPlugin.rollup({
569
- cwd: nuxt.options.rootDir,
570
- include: sharedPatterns,
571
- patterns: createImportProtectionPatterns(nuxt, { context: "shared" })
572
- }),
573
- ImpoundPlugin.rollup({
574
- cwd: nuxt.options.rootDir,
575
- patterns: createImportProtectionPatterns(nuxt, { context: "nitro-app" }),
576
- exclude: [/node_modules[\\/]nitro(?:pack)?(?:-nightly)?[\\/]|(packages|@nuxt)[\\/]nitro-server(?:-nightly)?[\\/](src|dist)[\\/]runtime[\\/]/, ...sharedPatterns]
577
- })
578
- );
579
- const isIgnored = createIsIgnored(nuxt);
580
- nitroConfig.devStorage ??= {};
581
- nitroConfig.devStorage.root ??= {
582
- driver: "fs",
583
- readOnly: true,
584
- base: nitroConfig.rootDir,
585
- watchOptions: {
586
- ignored: [isIgnored]
587
- }
588
- };
589
- nitroConfig.devStorage.src ??= {
590
- driver: "fs",
591
- readOnly: true,
592
- base: nitroConfig.srcDir,
593
- watchOptions: {
594
- ignored: [isIgnored]
595
- }
596
- };
597
- await nuxt.callHook("nitro:config", nitroConfig);
598
- const excludedAlias = [/^@vue\/.*$/, "vue", /vue-router/, "vite/client", "#imports", "vue-demi", /^#app/, "~", "@", "~~", "@@"];
599
- const basePath = nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl ? resolve(nuxt.options.buildDir, nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl) : nuxt.options.buildDir;
600
- const aliases = nitroConfig.alias;
601
- const tsConfig = nitroConfig.typescript.tsConfig;
602
- tsConfig.compilerOptions ||= {};
603
- tsConfig.compilerOptions.paths ||= {};
604
- for (const _alias in aliases) {
605
- const alias = _alias;
606
- if (excludedAlias.some((pattern) => typeof pattern === "string" ? alias === pattern : pattern.test(alias))) {
607
- continue;
608
- }
609
- if (alias in tsConfig.compilerOptions.paths) {
610
- continue;
611
- }
612
- const absolutePath = resolve(basePath, aliases[alias]);
613
- const isDirectory = aliases[alias].endsWith("/") || await promises.stat(absolutePath).then((r) => r.isDirectory()).catch(
614
- () => null
615
- /* file does not exist */
616
- );
617
- tsConfig.compilerOptions.paths[alias] = [absolutePath];
618
- if (isDirectory) {
619
- tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`];
620
- }
621
- }
622
- const nitro = await createNitro(nitroConfig, {
623
- compatibilityDate: nuxt.options.compatibilityDate,
624
- dotenv: nuxt.options._loadOptions?.dotenv
625
- });
626
- const spaLoadingTemplateFilePath = await spaLoadingTemplatePath(nuxt);
627
- nuxt.hook("builder:watch", async (_event, relativePath) => {
628
- const path = resolve(nuxt.options.srcDir, relativePath);
629
- if (path === spaLoadingTemplateFilePath) {
630
- await nitro.hooks.callHook("rollup:reload");
631
- }
632
- });
633
- const cacheDir = resolve(nuxt.options.buildDir, "cache/nitro/prerender");
634
- const cacheDriverPath = join(distDir, "runtime/utils/cache-driver.js");
635
- await promises.rm(cacheDir, { recursive: true, force: true }).catch(() => {
636
- });
637
- nitro.options._config.storage = defu(nitro.options._config.storage, {
638
- "internal:nuxt:prerender": {
639
- // TODO: resolve upstream where file URLs are not being resolved/inlined correctly
640
- driver: isWindows ? pathToFileURL(cacheDriverPath).href : cacheDriverPath,
641
- base: cacheDir
642
- }
643
- });
644
- nuxt._nitro = nitro;
645
- await nuxt.callHook("nitro:init", nitro);
646
- nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
647
- nuxt.hook("close", () => nitro.hooks.callHook("close"));
648
- nitro.hooks.hook("prerender:routes", (routes) => {
649
- return nuxt.callHook("prerender:routes", { routes });
650
- });
651
- if (nuxt.options.vue.runtimeCompiler) {
652
- addVitePlugin({
653
- name: "nuxt:vue:runtime-compiler",
654
- applyToEnvironment: (environment) => environment.name === "client",
655
- enforce: "pre",
656
- resolveId(id, importer) {
657
- if (id === "vue") {
658
- return this.resolve("vue/dist/vue.esm-bundler", importer, { skipSelf: true });
659
- }
660
- }
661
- });
662
- for (const hook of ["webpack:config", "rspack:config"]) {
663
- nuxt.hook(hook, (configuration) => {
664
- const clientConfig = configuration.find((config) => config.name === "client");
665
- if (!clientConfig.resolve) {
666
- clientConfig.resolve.alias = {};
667
- }
668
- if (Array.isArray(clientConfig.resolve.alias)) {
669
- clientConfig.resolve.alias.push({
670
- name: "vue",
671
- alias: "vue/dist/vue.esm-bundler"
672
- });
673
- } else {
674
- clientConfig.resolve.alias.vue = "vue/dist/vue.esm-bundler";
675
- }
676
- });
677
- }
678
- }
679
- const devMiddlewareHandler = dynamicEventHandler();
680
- nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
681
- nitro.options.devHandlers.push(...nuxt.options.devServerHandlers);
682
- nitro.options.handlers.unshift({
683
- route: "/__nuxt_error",
684
- lazy: true,
685
- handler: resolve(distDir, "runtime/handlers/renderer")
686
- });
687
- if (nuxt.options.experimental.chromeDevtoolsProjectSettings) {
688
- const cacheDir2 = resolve(nuxt.options.rootDir, "node_modules/.cache/nuxt");
689
- let projectConfiguration = await readFile(join(cacheDir2, "chrome-workspace.json"), "utf-8").then((r) => JSON.parse(r)).catch(() => null);
690
- if (!projectConfiguration) {
691
- projectConfiguration = { uuid: randomUUID() };
692
- await mkdir(cacheDir2, { recursive: true });
693
- await writeFile(join(cacheDir2, "chrome-workspace.json"), JSON.stringify(projectConfiguration), "utf-8");
694
- }
695
- nitro.options.devHandlers.push({
696
- route: "/.well-known/appspecific/com.chrome.devtools.json",
697
- handler: defineEventHandler(() => ({
698
- workspace: {
699
- ...projectConfiguration,
700
- root: nuxt.options.rootDir
701
- }
702
- }))
703
- });
704
- }
705
- if (!nuxt.options.dev && nuxt.options.experimental.noVueServer) {
706
- nitro.hooks.hook("rollup:before", (nitro2) => {
707
- if (nitro2.options.preset === "nitro-prerender") {
708
- nitro2.options.errorHandler = resolve(distDir, "runtime/handlers/error");
709
- return;
710
- }
711
- const nuxtErrorHandler = nitro2.options.handlers.findIndex((h) => h.route === "/__nuxt_error");
712
- if (nuxtErrorHandler >= 0) {
713
- nitro2.options.handlers.splice(nuxtErrorHandler, 1);
714
- }
715
- nitro2.options.renderer = void 0;
716
- });
717
- }
718
- nitro.hooks.hook("types:extend", (types) => {
719
- types.tsConfig ||= {};
720
- const rootDirGlob = relativeWithDot(nuxt.options.buildDir, join(nuxt.options.rootDir, "**/*"));
721
- types.tsConfig.include = types.tsConfig.include?.filter((i) => i !== rootDirGlob);
722
- });
723
- nuxt.hook("prepare:types", async (opts) => {
724
- if (!nuxt.options.dev) {
725
- await scanHandlers(nitro);
726
- await writeTypes(nitro);
727
- }
728
- opts.tsConfig.exclude ||= [];
729
- opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nitro.options.output.dir)));
730
- opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nuxt.options.serverDir)));
731
- opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
732
- opts.sharedTsConfig.compilerOptions ||= {};
733
- opts.sharedTsConfig.compilerOptions.paths ||= {};
734
- for (const key in nuxt.options.alias) {
735
- if (nitro.options.alias[key] && nitro.options.alias[key] === nuxt.options.alias[key]) {
736
- const dirKey = join(key, "*");
737
- if (opts.tsConfig.compilerOptions?.paths[key]) {
738
- opts.sharedTsConfig.compilerOptions.paths[key] = opts.tsConfig.compilerOptions.paths[key];
739
- }
740
- if (opts.tsConfig.compilerOptions?.paths[dirKey]) {
741
- opts.sharedTsConfig.compilerOptions.paths[dirKey] = opts.tsConfig.compilerOptions.paths[dirKey];
742
- }
743
- }
744
- }
745
- });
746
- if (nitro.options.static) {
747
- nitro.hooks.hook("prerender:routes", (routes) => {
748
- for (const route of ["/200.html", "/404.html"]) {
749
- routes.add(route);
750
- }
751
- if (!nuxt.options.ssr) {
752
- routes.add("/index.html");
753
- }
754
- });
755
- }
756
- if (!nuxt.options.dev) {
757
- nitro.hooks.hook("rollup:before", async (nitro2) => {
758
- await copyPublicAssets(nitro2);
759
- await nuxt.callHook("nitro:build:public-assets", nitro2);
760
- });
761
- }
762
- async function symlinkDist() {
763
- if (nitro.options.static) {
764
- const distDir2 = resolve(nuxt.options.rootDir, "dist");
765
- if (!existsSync(distDir2)) {
766
- await promises.symlink(nitro.options.output.publicDir, distDir2, "junction").catch(() => {
767
- });
768
- }
769
- }
770
- }
771
- nuxt.hook("build:done", async () => {
772
- await nuxt.callHook("nitro:build:before", nitro);
773
- await prepare(nitro);
774
- if (nuxt.options.dev) {
775
- return build(nitro);
776
- }
777
- await prerender(nitro);
778
- logger.restoreAll();
779
- await build(nitro);
780
- logger.wrapAll();
781
- await symlinkDist();
782
- });
783
- if (nuxt.options.dev) {
784
- for (const builder of ["webpack", "rspack"]) {
785
- nuxt.hook(`${builder}:compile`, ({ name, compiler }) => {
786
- if (name === "server") {
787
- const memfs = compiler.outputFileSystem;
788
- nitro.options.virtual["#build/dist/server/server.mjs"] = () => memfs.readFileSync(join(nuxt.options.buildDir, "dist/server/server.mjs"), "utf-8");
789
- }
790
- });
791
- nuxt.hook(`${builder}:compiled`, () => {
792
- nuxt.server.reload();
793
- });
794
- }
795
- nuxt.hook("vite:compiled", () => {
796
- nuxt.server.reload();
797
- });
798
- nuxt.hook("server:devHandler", (h) => {
799
- devMiddlewareHandler.set(h);
800
- });
801
- nuxt.server = createDevServer(nitro);
802
- const waitUntilCompile = new Promise((resolve2) => nitro.hooks.hook("compiled", () => resolve2()));
803
- nuxt.hook("build:done", () => waitUntilCompile);
804
- }
141
+ const layerDirs = getLayerDirectories(nuxt);
142
+ const excludePaths = [];
143
+ for (const dirs of layerDirs) {
144
+ const paths = [dirs.root.match(NODE_MODULES_RE)?.[1]?.replace(/\/$/, ""), dirs.root.match(PNPM_NODE_MODULES_RE)?.[1]?.replace(/\/$/, "")];
145
+ for (const dir of paths) if (dir) excludePaths.push(escapeRE(dir));
146
+ }
147
+ const layerPublicAssetsDirs = [];
148
+ for (const dirs of layerDirs) if (existsSync(dirs.public)) layerPublicAssetsDirs.push({ dir: dirs.public });
149
+ const excludePattern = excludePaths.length ? [new RegExp(`node_modules\\/(?!${excludePaths.join("|")})`)] : [/node_modules/];
150
+ const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
151
+ const moduleEntryPaths = [];
152
+ for (const m of nuxt.options._installedModules) {
153
+ const path = m.meta?.rawPath || m.entryPath;
154
+ if (path) moduleEntryPaths.push(getDirectory(path));
155
+ }
156
+ const modules = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
157
+ addTemplate(nitroSchemaTemplate);
158
+ const sharedDirs = /* @__PURE__ */ new Set();
159
+ if (nuxt.options.nitro.imports !== false && nuxt.options.imports.scan !== false) for (const layer of nuxt.options._layers) {
160
+ if (layer.config?.imports?.scan === false) continue;
161
+ sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "utils"));
162
+ sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "types"));
163
+ }
164
+ nuxt.options.nitro.plugins ||= [];
165
+ nuxt.options.nitro.plugins = nuxt.options.nitro.plugins.map((plugin) => plugin ? resolveAlias(plugin, nuxt.options.alias) : plugin);
166
+ if (nuxt.options.dev && nuxt.options.features.devLogs) {
167
+ addPlugin(resolve(nuxt.options.appDir, "plugins/dev-server-logs"));
168
+ nuxt.options.nitro.plugins.push(resolve(distDir, "runtime/plugins/dev-server-logs"));
169
+ nuxt.options.nitro.externals = defu(nuxt.options.nitro.externals, { inline: [/#internal\/dev-server-logs-options/] });
170
+ nuxt.options.nitro.virtual = defu(nuxt.options.nitro.virtual, { "#internal/dev-server-logs-options": () => `export const rootDir = ${JSON.stringify(nuxt.options.rootDir)};` });
171
+ }
172
+ if (nuxt.options.experimental.componentIslands) {
173
+ nuxt.options.nitro.virtual ||= {};
174
+ nuxt.options.nitro.virtual["#internal/nuxt/island-renderer.mjs"] = () => {
175
+ if (nuxt.options.dev || nuxt.options.experimental.componentIslands !== "auto" || nuxt.apps.default?.pages?.some((p) => p.mode === "server") || nuxt.apps.default?.components?.some((c) => c.mode === "server" && !nuxt.apps.default?.components.some((other) => other.pascalName === c.pascalName && other.mode === "client"))) return `export { default } from '${resolve(distDir, "runtime/handlers/island")}'`;
176
+ return `import { defineEventHandler } from 'h3'; export default defineEventHandler(() => {});`;
177
+ };
178
+ nuxt.options.nitro.handlers ||= [];
179
+ nuxt.options.nitro.handlers.push({
180
+ route: "/__nuxt_island/**",
181
+ handler: "#internal/nuxt/island-renderer.mjs"
182
+ });
183
+ if (!nuxt.options.ssr && nuxt.options.experimental.componentIslands !== "auto") {
184
+ nuxt.options.ssr = true;
185
+ nuxt.options.nitro.routeRules ||= {};
186
+ nuxt.options.nitro.routeRules["/**"] = defu(nuxt.options.nitro.routeRules["/**"], { ssr: false });
187
+ }
188
+ }
189
+ const mockProxy = resolveModulePath("mocked-exports/proxy", { from: import.meta.url });
190
+ const { version: nuxtVersion } = await readPackageJSON("nuxt", { from: import.meta.url });
191
+ const nitroConfig = defu(nuxt.options.nitro, {
192
+ debug: nuxt.options.debug ? nuxt.options.debug.nitro : false,
193
+ rootDir: nuxt.options.rootDir,
194
+ workspaceDir: nuxt.options.workspaceDir,
195
+ srcDir: nuxt.options.serverDir,
196
+ dev: nuxt.options.dev,
197
+ buildDir: nuxt.options.buildDir,
198
+ experimental: {
199
+ asyncContext: nuxt.options.experimental.asyncContext,
200
+ typescriptBundlerResolution: nuxt.options.future.typescriptBundlerResolution || nuxt.options.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler" || nuxt.options.nitro.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler"
201
+ },
202
+ framework: {
203
+ name: "nuxt",
204
+ version: nuxtVersion || version
205
+ },
206
+ imports: nuxt.options.experimental.nitroAutoImports === false ? false : {
207
+ autoImport: nuxt.options.imports.autoImport,
208
+ dirs: [...sharedDirs],
209
+ imports: [
210
+ {
211
+ as: "__buildAssetsURL",
212
+ name: "buildAssetsURL",
213
+ from: resolve(distDir, "runtime/utils/paths")
214
+ },
215
+ {
216
+ as: "__publicAssetsURL",
217
+ name: "publicAssetsURL",
218
+ from: resolve(distDir, "runtime/utils/paths")
219
+ },
220
+ {
221
+ as: "defineAppConfig",
222
+ name: "defineAppConfig",
223
+ from: resolve(distDir, "runtime/utils/config"),
224
+ priority: -1
225
+ }
226
+ ],
227
+ presets: [{
228
+ from: "h3",
229
+ imports: ["H3Event", "H3Error"]
230
+ }, {
231
+ from: "h3",
232
+ type: true,
233
+ imports: [
234
+ "EventHandler",
235
+ "EventHandlerRequest",
236
+ "EventHandlerResponse",
237
+ "EventHandlerObject",
238
+ "H3EventContext"
239
+ ]
240
+ }],
241
+ exclude: [...excludePattern, /[\\/]\.git[\\/]/]
242
+ },
243
+ esbuild: { options: { exclude: excludePattern } },
244
+ analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) ? {
245
+ template: "treemap",
246
+ projectRoot: nuxt.options.rootDir,
247
+ filename: join(nuxt.options.analyzeDir, "{name}.html")
248
+ } : false,
249
+ scanDirs: layerDirs.map((dirs) => dirs.server),
250
+ renderer: resolve(distDir, "runtime/handlers/renderer"),
251
+ nodeModulesDirs: nuxt.options.modulesDir,
252
+ handlers: nuxt.options.serverHandlers,
253
+ devHandlers: [],
254
+ baseURL: nuxt.options.app.baseURL,
255
+ virtual: {
256
+ "#internal/nuxt.config.mjs": () => nuxt.vfs["#build/nuxt.config.mjs"] || "",
257
+ "#internal/nuxt/app-config": () => nuxt.vfs["#build/app.config.mjs"]?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, "") || "",
258
+ "#spa-template": async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`,
259
+ "#internal/entry-chunk.mjs": () => `export const entryFileName = undefined`,
260
+ "#internal/nuxt/entry-ids.mjs": () => `export default []`,
261
+ "#internal/nuxt/nitro-config.mjs": () => {
262
+ const hasCachedRoutes = Object.values(nitro.options.routeRules).some((r) => r.isr || r.cache);
263
+ return [
264
+ `export const NUXT_NO_SSR = ${nuxt.options.ssr === false}`,
265
+ `export const NUXT_EARLY_HINTS = ${nuxt.options.experimental.writeEarlyHints !== false}`,
266
+ `export const NUXT_NO_SCRIPTS = ${nuxt.options.features.noScripts === "all" || !!nuxt.options.features.noScripts && !nuxt.options.dev}`,
267
+ `export const NUXT_INLINE_STYLES = ${!!nuxt.options.features.inlineStyles}`,
268
+ `export const PARSE_ERROR_DATA = ${!!nuxt.options.experimental.parseErrorData}`,
269
+ `export const NUXT_JSON_PAYLOADS = ${!!nuxt.options.experimental.renderJsonPayloads}`,
270
+ `export const NUXT_ASYNC_CONTEXT = ${!!nuxt.options.experimental.asyncContext}`,
271
+ `export const NUXT_SHARED_DATA = ${!!nuxt.options.experimental.sharedPrerenderData}`,
272
+ `export const NUXT_PAYLOAD_EXTRACTION = ${!!nuxt.options.experimental.payloadExtraction}`,
273
+ `export const NUXT_RUNTIME_PAYLOAD_EXTRACTION = ${hasCachedRoutes}`
274
+ ].join("\n");
275
+ }
276
+ },
277
+ routeRules: { "/__nuxt_error": { cache: false } },
278
+ appConfig: nuxt.options.appConfig,
279
+ appConfigFiles: layerDirs.map((dirs) => join(dirs.app, "app.config")),
280
+ typescript: {
281
+ strict: true,
282
+ generateTsConfig: true,
283
+ tsconfigPath: "tsconfig.server.json",
284
+ tsConfig: {
285
+ compilerOptions: {
286
+ lib: [
287
+ "esnext",
288
+ "webworker",
289
+ "dom.iterable"
290
+ ],
291
+ skipLibCheck: true,
292
+ noUncheckedIndexedAccess: true,
293
+ allowArbitraryExtensions: true
294
+ },
295
+ include: [
296
+ join(nuxt.options.buildDir, "types/nitro-nuxt.d.ts"),
297
+ ...modules.flatMap((m) => {
298
+ const moduleDir = relativeWithDot(nuxt.options.buildDir, m);
299
+ return [join(moduleDir, "runtime/server"), join(moduleDir, "dist/runtime/server")];
300
+ }),
301
+ ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.server, "**/*"))),
302
+ ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.shared, "**/*.d.ts")))
303
+ ],
304
+ exclude: [...nuxt.options.modulesDir.map((m) => relativeWithDot(nuxt.options.buildDir, m)), relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, "dist"))]
305
+ }
306
+ },
307
+ publicAssets: [nuxt.options.dev ? { dir: resolve(nuxt.options.buildDir, "dist/client") } : {
308
+ dir: join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir),
309
+ maxAge: 31536e3,
310
+ baseURL: nuxt.options.app.buildAssetsDir
311
+ }, ...layerPublicAssetsDirs],
312
+ prerender: {
313
+ ignoreUnprefixedPublicAssets: true,
314
+ failOnError: true,
315
+ concurrency: cpus().length * 4 || 4,
316
+ routes: [].concat(nuxt.options.generate.routes)
317
+ },
318
+ sourceMap: nuxt.options.sourcemap.server,
319
+ externals: {
320
+ inline: [
321
+ ...nuxt.options.dev ? [] : [
322
+ ...nuxt.options.experimental.externalVue ? [] : ["vue", "@vue/"],
323
+ "@nuxt/",
324
+ nuxt.options.buildDir
325
+ ],
326
+ ...nuxt.options.build.transpile.filter((i) => typeof i === "string"),
327
+ "nuxt/dist",
328
+ "nuxt3/dist",
329
+ "nuxt-nightly/dist",
330
+ distDir,
331
+ ...layerDirs.map((dirs) => join(dirs.app, "app.config"))
332
+ ],
333
+ traceInclude: [...nuxt.options.vue.runtimeCompiler && !nuxt.options.experimental.externalVue ? [...nuxt.options.modulesDir.reduce((targets, path) => {
334
+ const serverRendererPath = resolve(path, "vue/server-renderer/index.js");
335
+ if (existsSync(serverRendererPath)) targets.push(serverRendererPath);
336
+ return targets;
337
+ }, [])] : []]
338
+ },
339
+ alias: {
340
+ ...nuxt.options.vue.runtimeCompiler || nuxt.options.experimental.externalVue ? {} : {
341
+ "estree-walker": mockProxy,
342
+ "@babel/parser": mockProxy,
343
+ "@vue/compiler-core": mockProxy,
344
+ "@vue/compiler-dom": mockProxy,
345
+ "@vue/compiler-ssr": mockProxy
346
+ },
347
+ "@vue/devtools-api": "vue-devtools-stub",
348
+ ...nuxt.options.alias,
349
+ "#internal/nuxt/paths": resolve(distDir, "runtime/utils/paths")
350
+ },
351
+ replace: { "__VUE_PROD_DEVTOOLS__": String(false) },
352
+ rollupConfig: {
353
+ output: { generatedCode: { symbols: true } },
354
+ plugins: []
355
+ },
356
+ logLevel: logLevelMapReverse[nuxt.options.logLevel]
357
+ });
358
+ if (nuxt.options.experimental.serverAppConfig === true && nitroConfig.imports) {
359
+ nitroConfig.imports.imports ||= [];
360
+ nitroConfig.imports.imports.push({
361
+ name: "useAppConfig",
362
+ from: resolve(distDir, "runtime/utils/app-config"),
363
+ priority: -1
364
+ });
365
+ }
366
+ if (!nitroConfig.errorHandler && (nuxt.options.dev || !nuxt.options.experimental.noVueServer)) nitroConfig.errorHandler = resolve(distDir, "runtime/handlers/error");
367
+ nitroConfig.srcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nitroConfig.srcDir);
368
+ nitroConfig.ignore ||= [];
369
+ nitroConfig.ignore.push(...resolveIgnorePatterns(nitroConfig.srcDir), `!${join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir, "**/*")}`);
370
+ const validManifestKeys = [
371
+ "prerender",
372
+ "redirect",
373
+ "appMiddleware",
374
+ "appLayout",
375
+ "cache",
376
+ "isr",
377
+ "swr"
378
+ ];
379
+ function getRouteRulesRouter() {
380
+ const routeRulesRouter = createRouter();
381
+ if (nuxt._nitro) for (const [route, rules] of Object.entries(nuxt._nitro.options.routeRules)) {
382
+ if (route === "/__nuxt_error") continue;
383
+ if (validManifestKeys.every((key) => !(key in rules))) continue;
384
+ addRoute(routeRulesRouter, void 0, route, rules);
385
+ }
386
+ return routeRulesRouter;
387
+ }
388
+ const cachedMatchers = {};
389
+ addTemplate({
390
+ filename: "route-rules.mjs",
391
+ getContents() {
392
+ const key = hash(nuxt._nitro?.options.routeRules || {});
393
+ if (cachedMatchers[key]) return cachedMatchers[key];
394
+ return cachedMatchers[key] = `
395
+ import { defu } from 'defu'
396
+ const matcher = ${compileRouterToString(getRouteRulesRouter(), "", {
397
+ matchAll: true,
398
+ serialize(routeRules) {
399
+ return `{${Object.entries(routeRules).filter(([name, value]) => value !== void 0 && validManifestKeys.includes(name)).map(([name, value]) => {
400
+ if (name === "redirect") {
401
+ const redirectOptions = value;
402
+ value = typeof redirectOptions === "string" ? redirectOptions : redirectOptions.to;
403
+ }
404
+ if (name === "appMiddleware") {
405
+ const appMiddlewareOptions = value;
406
+ if (typeof appMiddlewareOptions === "string") value = { [appMiddlewareOptions]: true };
407
+ else if (Array.isArray(appMiddlewareOptions)) {
408
+ const normalizedRules = {};
409
+ for (const middleware of appMiddlewareOptions) normalizedRules[middleware] = true;
410
+ value = normalizedRules;
411
+ }
412
+ }
413
+ if (name === "cache" || name === "isr" || name === "swr") {
414
+ name = "payload";
415
+ value = Boolean(value);
416
+ }
417
+ return `${name}: ${JSON.stringify(value)}`;
418
+ }).join(",")}}`;
419
+ }
420
+ })}
421
+ export default (path) => defu({}, ...matcher('', path).map(r => r.data).reverse())
422
+ `;
423
+ }
424
+ });
425
+ if (nuxt.options.experimental.payloadExtraction) {
426
+ if (nuxt.options.dev) nuxt.hook("nitro:config", (nitroConfig) => {
427
+ nitroConfig.prerender ||= {};
428
+ nitroConfig.prerender.routes ||= [];
429
+ nitroConfig.routeRules ||= {};
430
+ for (const route of nitroConfig.prerender.routes) {
431
+ if (!route) continue;
432
+ nitroConfig.routeRules[route] = defu(nitroConfig.routeRules[route], { prerender: true });
433
+ }
434
+ });
435
+ nuxt.hook("nitro:init", (nitro) => {
436
+ nitro.hooks.hook("build:before", (nitro) => {
437
+ for (const [route, value] of Object.entries(nitro.options.routeRules)) if (!route.endsWith("*") && !route.endsWith("/_payload.json")) {
438
+ if (value.isr || value.cache || value.prerender && nuxt.options.dev) {
439
+ const payloadKey = route + "/_payload.json";
440
+ const defaults = {};
441
+ for (const key of [
442
+ "isr",
443
+ "cache",
444
+ ...nuxt.options.dev ? ["prerender"] : []
445
+ ]) if (key in value) defaults[key] = value[key];
446
+ nitro.options.routeRules[payloadKey] = defu(nitro.options.routeRules[payloadKey], defaults);
447
+ }
448
+ }
449
+ });
450
+ });
451
+ }
452
+ if (nuxt.options.experimental.appManifest) {
453
+ const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
454
+ const buildTimestamp = Date.now();
455
+ const manifestPrefix = joinURL(nuxt.options.app.buildAssetsDir, "builds");
456
+ const tempDir = join(nuxt.options.buildDir, "manifest");
457
+ nitroConfig.prerender ||= {};
458
+ nitroConfig.prerender.ignore ||= [];
459
+ nitroConfig.prerender.ignore.push(joinURL(nuxt.options.app.baseURL, manifestPrefix));
460
+ nitroConfig.publicAssets.unshift({
461
+ dir: join(tempDir, "meta"),
462
+ maxAge: 31536e3,
463
+ baseURL: joinURL(manifestPrefix, "meta")
464
+ }, {
465
+ dir: tempDir,
466
+ maxAge: 1,
467
+ baseURL: manifestPrefix
468
+ });
469
+ nuxt.options.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
470
+ if (!nuxt.options.dev) nuxt.hook("build:before", async () => {
471
+ await promises.mkdir(join(tempDir, "meta"), { recursive: true });
472
+ await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify({}));
473
+ });
474
+ nuxt.hook("nitro:config", (config) => {
475
+ config.alias ||= {};
476
+ config.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
477
+ });
478
+ nuxt.hook("nitro:init", (nitro) => {
479
+ nitro.hooks.hook("rollup:before", async (nitro) => {
480
+ const prerenderedRoutes = /* @__PURE__ */ new Set();
481
+ const routeRulesMatcher = getRouteRulesRouter();
482
+ if (nitro._prerenderedRoutes?.length) {
483
+ const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? "/_payload.json" : "/_payload.js";
484
+ for (const route of nitro._prerenderedRoutes) if (!route.error && route.route.endsWith(payloadSuffix)) {
485
+ const url = route.route.slice(0, -payloadSuffix.length) || "/";
486
+ if (!defu({}, ...findAllRoutes(routeRulesMatcher, void 0, url).reverse()).prerender) prerenderedRoutes.add(url);
487
+ }
488
+ }
489
+ const manifest = {
490
+ id: buildId,
491
+ timestamp: buildTimestamp,
492
+ prerendered: nuxt.options.dev ? [] : [...prerenderedRoutes]
493
+ };
494
+ await promises.mkdir(join(tempDir, "meta"), { recursive: true });
495
+ await promises.writeFile(join(tempDir, "latest.json"), JSON.stringify({
496
+ id: buildId,
497
+ timestamp: buildTimestamp
498
+ }));
499
+ await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify(manifest));
500
+ });
501
+ });
502
+ }
503
+ if (!nuxt.options.experimental.appManifest) nuxt.options.alias["#app-manifest"] = mockProxy;
504
+ const FORWARD_SLASH_RE = /\//g;
505
+ if (!nuxt.options.ssr) {
506
+ nitroConfig.virtual["#build/dist/server/server.mjs"] = "export default () => {}";
507
+ if (process.platform === "win32") nitroConfig.virtual["#build/dist/server/server.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default () => {}";
508
+ }
509
+ if (nuxt.options.dev) {
510
+ nitroConfig.virtual["#build/dist/server/styles.mjs"] = "export default {}";
511
+ if (process.platform === "win32") nitroConfig.virtual["#build/dist/server/styles.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default {}";
512
+ }
513
+ nitroConfig.rollupConfig.plugins = await nitroConfig.rollupConfig.plugins || [];
514
+ nitroConfig.rollupConfig.plugins = toArray(nitroConfig.rollupConfig.plugins);
515
+ const sharedDir = withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared));
516
+ const relativeSharedDir = withTrailingSlash(relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, nuxt.options.dir.shared)));
517
+ const sharedPatterns = [
518
+ /^#shared\//,
519
+ new RegExp("^" + escapeRE(sharedDir)),
520
+ new RegExp("^" + escapeRE(relativeSharedDir))
521
+ ];
522
+ nitroConfig.rollupConfig.plugins.push(ImpoundPlugin.rollup({
523
+ cwd: nuxt.options.rootDir,
524
+ include: sharedPatterns,
525
+ patterns: createImportProtectionPatterns(nuxt, { context: "shared" })
526
+ }), ImpoundPlugin.rollup({
527
+ cwd: nuxt.options.rootDir,
528
+ patterns: createImportProtectionPatterns(nuxt, { context: "nitro-app" }),
529
+ exclude: [/node_modules[\\/]nitro(?:pack)?(?:-nightly)?[\\/]|(packages|@nuxt)[\\/]nitro-server(?:-nightly)?[\\/](src|dist)[\\/]runtime[\\/]/, ...sharedPatterns]
530
+ }));
531
+ const isIgnored = createIsIgnored(nuxt);
532
+ nitroConfig.devStorage ??= {};
533
+ nitroConfig.devStorage.root ??= {
534
+ driver: "fs",
535
+ readOnly: true,
536
+ base: nitroConfig.rootDir,
537
+ watchOptions: { ignored: [isIgnored] }
538
+ };
539
+ nitroConfig.devStorage.src ??= {
540
+ driver: "fs",
541
+ readOnly: true,
542
+ base: nitroConfig.srcDir,
543
+ watchOptions: { ignored: [isIgnored] }
544
+ };
545
+ nuxt.options.typescript.hoist.push("nitro/types", "nitro/runtime", "nitropack/types", "nitropack/runtime", "nitropack", "defu", "h3", "consola", "ofetch", "crossws");
546
+ await nuxt.callHook("nitro:config", nitroConfig);
547
+ if (nitroConfig.static && nuxt.options.dev) {
548
+ nitroConfig.routeRules ||= {};
549
+ nitroConfig.routeRules["/**"] = defu(nitroConfig.routeRules["/**"], { prerender: true });
550
+ }
551
+ const excludedAlias = [
552
+ /^@vue\/.*$/,
553
+ "vue",
554
+ /vue-router/,
555
+ "vite/client",
556
+ "#imports",
557
+ "vue-demi",
558
+ /^#app/,
559
+ "~",
560
+ "@",
561
+ "~~",
562
+ "@@"
563
+ ];
564
+ const basePath = nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl ? resolve(nuxt.options.buildDir, nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl) : nuxt.options.buildDir;
565
+ const aliases = nitroConfig.alias;
566
+ const tsConfig = nitroConfig.typescript.tsConfig;
567
+ tsConfig.compilerOptions ||= {};
568
+ tsConfig.compilerOptions.paths ||= {};
569
+ for (const _alias in aliases) {
570
+ const alias = _alias;
571
+ if (excludedAlias.some((pattern) => typeof pattern === "string" ? alias === pattern : pattern.test(alias))) continue;
572
+ if (alias in tsConfig.compilerOptions.paths) continue;
573
+ const absolutePath = resolve(basePath, aliases[alias]);
574
+ const isDirectory = aliases[alias].endsWith("/") || await promises.stat(absolutePath).then((r) => r.isDirectory()).catch(() => null);
575
+ tsConfig.compilerOptions.paths[alias] = [absolutePath];
576
+ if (isDirectory) tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`];
577
+ }
578
+ const nitro = await createNitro(nitroConfig, {
579
+ compatibilityDate: nuxt.options.compatibilityDate,
580
+ dotenv: nuxt.options._loadOptions?.dotenv
581
+ });
582
+ if (nuxt.options.experimental.serverAppConfig === false && nitro.options.imports) {
583
+ nitro.options.imports.presets ||= [];
584
+ nitro.options.imports.presets = nitro.options.imports.presets.map((preset) => typeof preset === "string" || !("imports" in preset) ? preset : {
585
+ ...preset,
586
+ imports: preset.imports.filter((i) => i !== "useAppConfig")
587
+ });
588
+ }
589
+ if (nitro.options.static && nuxt.options.experimental.payloadExtraction === void 0) {
590
+ logger.warn("Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.");
591
+ nuxt.options.experimental.payloadExtraction = true;
592
+ }
593
+ const spaLoadingTemplateFilePath = await spaLoadingTemplatePath(nuxt);
594
+ nuxt.hook("builder:watch", async (_event, relativePath) => {
595
+ if (resolve(nuxt.options.srcDir, relativePath) === spaLoadingTemplateFilePath) await nitro.hooks.callHook("rollup:reload");
596
+ });
597
+ const cacheDir = resolve(nuxt.options.buildDir, "cache/nitro/prerender");
598
+ const cacheDriverPath = join(distDir, "runtime/utils/cache-driver.js");
599
+ await promises.rm(cacheDir, {
600
+ recursive: true,
601
+ force: true
602
+ }).catch(() => {});
603
+ nitro.options._config.storage = defu(nitro.options._config.storage, { "internal:nuxt:prerender": {
604
+ driver: isWindows ? pathToFileURL(cacheDriverPath).href : cacheDriverPath,
605
+ base: cacheDir
606
+ } });
607
+ nuxt._nitro = nitro;
608
+ await nuxt.callHook("nitro:init", nitro);
609
+ nuxt["~runtimeDependencies"] ||= [];
610
+ nuxt["~runtimeDependencies"].push(...runtimeDependencies, "unhead", "@unhead/vue", "@nuxt/devalue", "unstorage", ...nitro.options.inlineDynamicImports ? ["vue", "@vue/server-renderer"] : []);
611
+ nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
612
+ nuxt.hook("close", () => nitro.hooks.callHook("close"));
613
+ nitro.hooks.hook("prerender:routes", (routes) => {
614
+ return nuxt.callHook("prerender:routes", { routes });
615
+ });
616
+ if (nuxt.options.vue.runtimeCompiler) {
617
+ addVitePlugin({
618
+ name: "nuxt:vue:runtime-compiler",
619
+ applyToEnvironment: (environment) => environment.name === "client",
620
+ enforce: "pre",
621
+ resolveId(id, importer) {
622
+ if (id === "vue") return this.resolve("vue/dist/vue.esm-bundler", importer, { skipSelf: true });
623
+ }
624
+ });
625
+ for (const hook of ["webpack:config", "rspack:config"]) nuxt.hook(hook, (configuration) => {
626
+ const clientConfig = configuration.find((config) => config.name === "client");
627
+ if (!clientConfig.resolve) clientConfig.resolve.alias = {};
628
+ if (Array.isArray(clientConfig.resolve.alias)) clientConfig.resolve.alias.push({
629
+ name: "vue",
630
+ alias: "vue/dist/vue.esm-bundler"
631
+ });
632
+ else clientConfig.resolve.alias.vue = "vue/dist/vue.esm-bundler";
633
+ });
634
+ }
635
+ const devMiddlewareHandler = dynamicEventHandler();
636
+ nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
637
+ nitro.options.devHandlers.push(...nuxt.options.devServerHandlers);
638
+ nitro.options.handlers.unshift({
639
+ route: "/__nuxt_error",
640
+ lazy: true,
641
+ handler: resolve(distDir, "runtime/handlers/renderer")
642
+ });
643
+ if (nuxt.options.experimental.chromeDevtoolsProjectSettings) {
644
+ const cacheDir = resolve(nuxt.options.rootDir, "node_modules/.cache/nuxt");
645
+ let projectConfiguration = await readFile(join(cacheDir, "chrome-workspace.json"), "utf-8").then((r) => JSON.parse(r)).catch(() => null);
646
+ if (!projectConfiguration) {
647
+ projectConfiguration = { uuid: randomUUID() };
648
+ await mkdir(cacheDir, { recursive: true });
649
+ await writeFile(join(cacheDir, "chrome-workspace.json"), JSON.stringify(projectConfiguration), "utf-8");
650
+ }
651
+ nitro.options.devHandlers.push({
652
+ route: "/.well-known/appspecific/com.chrome.devtools.json",
653
+ handler: defineEventHandler(() => ({ workspace: {
654
+ ...projectConfiguration,
655
+ root: nuxt.options.rootDir
656
+ } }))
657
+ });
658
+ }
659
+ if (!nuxt.options.dev && nuxt.options.experimental.noVueServer) nitro.hooks.hook("rollup:before", (nitro) => {
660
+ if (nitro.options.preset === "nitro-prerender") {
661
+ nitro.options.errorHandler = resolve(distDir, "runtime/handlers/error");
662
+ return;
663
+ }
664
+ const nuxtErrorHandler = nitro.options.handlers.findIndex((h) => h.route === "/__nuxt_error");
665
+ if (nuxtErrorHandler >= 0) nitro.options.handlers.splice(nuxtErrorHandler, 1);
666
+ nitro.options.renderer = void 0;
667
+ });
668
+ nitro.hooks.hook("types:extend", (types) => {
669
+ types.tsConfig ||= {};
670
+ const rootDirGlob = relativeWithDot(nuxt.options.buildDir, join(nuxt.options.rootDir, "**/*"));
671
+ types.tsConfig.include = types.tsConfig.include?.filter((i) => i !== rootDirGlob);
672
+ });
673
+ nuxt.hook("prepare:types", async (opts) => {
674
+ if (!nuxt.options.dev) {
675
+ await scanHandlers(nitro);
676
+ await writeTypes(nitro);
677
+ }
678
+ opts.tsConfig.exclude ||= [];
679
+ opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nitro.options.output.dir)));
680
+ opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nuxt.options.serverDir)));
681
+ opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
682
+ opts.sharedTsConfig.compilerOptions ||= {};
683
+ opts.sharedTsConfig.compilerOptions.paths ||= {};
684
+ for (const key in nuxt.options.alias) if (nitro.options.alias[key] && nitro.options.alias[key] === nuxt.options.alias[key]) {
685
+ const dirKey = join(key, "*");
686
+ if (opts.tsConfig.compilerOptions?.paths[key]) opts.sharedTsConfig.compilerOptions.paths[key] = opts.tsConfig.compilerOptions.paths[key];
687
+ if (opts.tsConfig.compilerOptions?.paths[dirKey]) opts.sharedTsConfig.compilerOptions.paths[dirKey] = opts.tsConfig.compilerOptions.paths[dirKey];
688
+ }
689
+ });
690
+ if (nitro.options.static) nitro.hooks.hook("prerender:routes", (routes) => {
691
+ for (const route of ["/200.html", "/404.html"]) routes.add(route);
692
+ if (!nuxt.options.ssr) routes.add("/index.html");
693
+ });
694
+ if (!nuxt.options.dev) nitro.hooks.hook("rollup:before", async (nitro) => {
695
+ await copyPublicAssets(nitro);
696
+ await nuxt.callHook("nitro:build:public-assets", nitro);
697
+ });
698
+ async function symlinkDist() {
699
+ if (nitro.options.static) {
700
+ const distDir = resolve(nuxt.options.rootDir, "dist");
701
+ if (!existsSync(distDir)) await promises.symlink(nitro.options.output.publicDir, distDir, "junction").catch(() => {});
702
+ }
703
+ }
704
+ nuxt.hook("build:done", async () => {
705
+ await nuxt.callHook("nitro:build:before", nitro);
706
+ await prepare(nitro);
707
+ if (nuxt.options.dev) return build(nitro);
708
+ await prerender(nitro);
709
+ logger.restoreAll();
710
+ await build(nitro);
711
+ logger.wrapAll();
712
+ await symlinkDist();
713
+ });
714
+ if (nuxt.options.dev) {
715
+ for (const builder of ["webpack", "rspack"]) {
716
+ nuxt.hook(`${builder}:compile`, ({ name, compiler }) => {
717
+ if (name === "server") {
718
+ const memfs = compiler.outputFileSystem;
719
+ nitro.options.virtual["#build/dist/server/server.mjs"] = () => memfs.readFileSync(join(nuxt.options.buildDir, "dist/server/server.mjs"), "utf-8");
720
+ }
721
+ });
722
+ nuxt.hook(`${builder}:compiled`, () => {
723
+ nuxt.server.reload();
724
+ });
725
+ }
726
+ nuxt.hook("vite:compiled", () => {
727
+ nuxt.server.reload();
728
+ });
729
+ nuxt.hook("server:devHandler", (h, options) => {
730
+ devMiddlewareHandler.set(defineEventHandler((event) => {
731
+ if (options.cors(event.path)) {
732
+ if (handleCors(event, nuxt.options.devServer.cors)) return null;
733
+ setHeader(event, "Vary", "Origin");
734
+ }
735
+ return h(event);
736
+ }));
737
+ });
738
+ nuxt.server = createDevServer(nitro);
739
+ const waitUntilCompile = new Promise((resolve) => nitro.hooks.hook("compiled", () => resolve()));
740
+ nuxt.hook("build:done", () => waitUntilCompile);
741
+ }
805
742
  }
806
743
  const RELATIVE_RE = /^([^.])/;
807
744
  function relativeWithDot(from, to) {
808
- return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
745
+ return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
809
746
  }
810
747
  async function spaLoadingTemplatePath(nuxt) {
811
- if (typeof nuxt.options.spaLoadingTemplate === "string") {
812
- return resolve(nuxt.options.srcDir, nuxt.options.spaLoadingTemplate);
813
- }
814
- const possiblePaths = nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.app || "app", "spa-loading-template.html"));
815
- return await findPath(possiblePaths) ?? resolve(nuxt.options.srcDir, nuxt.options.dir?.app || "app", "spa-loading-template.html");
748
+ if (typeof nuxt.options.spaLoadingTemplate === "string") return resolve(nuxt.options.srcDir, nuxt.options.spaLoadingTemplate);
749
+ return await findPath(nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.app || "app", "spa-loading-template.html"))) ?? resolve(nuxt.options.srcDir, nuxt.options.dir?.app || "app", "spa-loading-template.html");
816
750
  }
817
751
  async function spaLoadingTemplate(nuxt) {
818
- if (nuxt.options.spaLoadingTemplate === false) {
819
- return "";
820
- }
821
- const spaLoadingTemplate2 = await spaLoadingTemplatePath(nuxt);
822
- try {
823
- if (existsSync(spaLoadingTemplate2)) {
824
- return readFileSync(spaLoadingTemplate2, "utf-8").trim();
825
- }
826
- } catch {
827
- }
828
- if (nuxt.options.spaLoadingTemplate === true) {
829
- return template();
830
- }
831
- if (nuxt.options.spaLoadingTemplate) {
832
- logger.warn(`Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`);
833
- }
834
- return "";
752
+ if (nuxt.options.spaLoadingTemplate === false) return "";
753
+ const spaLoadingTemplate = await spaLoadingTemplatePath(nuxt);
754
+ try {
755
+ if (existsSync(spaLoadingTemplate)) return readFileSync(spaLoadingTemplate, "utf-8").trim();
756
+ } catch {}
757
+ if (nuxt.options.spaLoadingTemplate === true) return template();
758
+ if (nuxt.options.spaLoadingTemplate) logger.warn(`Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`);
759
+ return "";
835
760
  }
836
-
837
761
  export { bundle };