@nuxt/nitro-server 3.20.2 → 3.21.0

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