nitro-nightly 3.0.1-20260106-182834-5019d347 → 3.0.1-20260106-205209-b085a480

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 (85) hide show
  1. package/dist/_build/common.mjs +24899 -0
  2. package/dist/_build/rolldown.mjs +5 -18
  3. package/dist/_build/rollup.mjs +5 -52
  4. package/dist/_build/vite.build.mjs +2 -21
  5. package/dist/{_dev.mjs → _chunks/dev.mjs} +4 -7
  6. package/dist/{_nitro.mjs → _chunks/nitro.mjs} +16 -195
  7. package/dist/_chunks/nitro2.mjs +101 -0
  8. package/dist/_chunks/utils.mjs +278 -0
  9. package/dist/_libs/@hiogawa/vite-plugin-fullstack.mjs +32 -4
  10. package/dist/_libs/@jridgewell/gen-mapping.mjs +304 -2
  11. package/dist/_libs/@jridgewell/remapping.mjs +1 -2
  12. package/dist/_libs/@rollup/plugin-commonjs.mjs +75 -31
  13. package/dist/_libs/@rollup/plugin-inject.mjs +1 -3
  14. package/dist/_libs/@rollup/plugin-json.mjs +1 -1
  15. package/dist/_libs/@rollup/plugin-node-resolve.mjs +1111 -7
  16. package/dist/_libs/c12.mjs +597 -41
  17. package/dist/_libs/chokidar.mjs +235 -2
  18. package/dist/_libs/confbox.mjs +454 -1476
  19. package/dist/_libs/estree-walker.mjs +1 -144
  20. package/dist/_libs/giget.mjs +2235 -1377
  21. package/dist/_libs/httpxy.mjs +1 -1
  22. package/dist/_libs/unimport.mjs +1547 -1772
  23. package/dist/_presets.mjs +3 -9
  24. package/dist/builder.mjs +7 -12
  25. package/dist/cli/_chunks/build.mjs +1 -1
  26. package/dist/cli/_chunks/dev.mjs +3 -5
  27. package/dist/cli/_chunks/list.mjs +1 -1
  28. package/dist/cli/_chunks/prepare.mjs +1 -1
  29. package/dist/cli/_chunks/run.mjs +1 -1
  30. package/dist/types/index.d.mts +4 -4
  31. package/dist/vite.mjs +14 -1128
  32. package/package.json +2 -2
  33. package/dist/_build/shared.mjs +0 -60
  34. package/dist/_build/shared2.mjs +0 -40
  35. package/dist/_build/shared3.mjs +0 -68
  36. package/dist/_libs/@jridgewell/resolve-uri.mjs +0 -166
  37. package/dist/_libs/@jridgewell/sourcemap-codec.mjs +0 -167
  38. package/dist/_libs/@jridgewell/trace-mapping.mjs +0 -141
  39. package/dist/_libs/@rolldown/pluginutils.mjs +0 -31
  40. package/dist/_libs/@rollup/plugin-replace.mjs +0 -104
  41. package/dist/_libs/@rollup/pluginutils.mjs +0 -241
  42. package/dist/_libs/acorn.mjs +0 -5034
  43. package/dist/_libs/commondir.mjs +0 -22
  44. package/dist/_libs/deepmerge.mjs +0 -86
  45. package/dist/_libs/dot-prop.mjs +0 -138
  46. package/dist/_libs/dotenv.mjs +0 -345
  47. package/dist/_libs/duplexer.mjs +0 -71
  48. package/dist/_libs/etag.mjs +0 -80
  49. package/dist/_libs/exsolve.mjs +0 -1007
  50. package/dist/_libs/fdir.mjs +0 -514
  51. package/dist/_libs/function-bind.mjs +0 -63
  52. package/dist/_libs/gzip-size.mjs +0 -21
  53. package/dist/_libs/hasown.mjs +0 -14
  54. package/dist/_libs/is-core-module.mjs +0 -220
  55. package/dist/_libs/is-module.mjs +0 -13
  56. package/dist/_libs/is-reference.mjs +0 -33
  57. package/dist/_libs/js-tokens.mjs +0 -382
  58. package/dist/_libs/knitwork.mjs +0 -124
  59. package/dist/_libs/local-pkg.mjs +0 -125
  60. package/dist/_libs/magic-string.mjs +0 -939
  61. package/dist/_libs/mime.mjs +0 -1391
  62. package/dist/_libs/mlly.mjs +0 -1415
  63. package/dist/_libs/node-fetch-native.mjs +0 -7
  64. package/dist/_libs/nypm.mjs +0 -239
  65. package/dist/_libs/path-parse.mjs +0 -47
  66. package/dist/_libs/pathe.mjs +0 -202
  67. package/dist/_libs/perfect-debounce.mjs +0 -89
  68. package/dist/_libs/picomatch.mjs +0 -1673
  69. package/dist/_libs/pkg-types.mjs +0 -197
  70. package/dist/_libs/pretty-bytes.mjs +0 -116
  71. package/dist/_libs/quansync.mjs +0 -90
  72. package/dist/_libs/rc9.mjs +0 -136
  73. package/dist/_libs/readdirp.mjs +0 -237
  74. package/dist/_libs/resolve.mjs +0 -689
  75. package/dist/_libs/std-env.mjs +0 -158
  76. package/dist/_libs/strip-literal.mjs +0 -51
  77. package/dist/_libs/tinyexec.mjs +0 -627
  78. package/dist/_libs/tinyglobby.mjs +0 -292
  79. package/dist/_libs/unplugin-utils.mjs +0 -61
  80. package/dist/_libs/unplugin.mjs +0 -1225
  81. package/dist/_libs/untyped.mjs +0 -271
  82. package/dist/_libs/unwasm.mjs +0 -5895
  83. package/dist/_libs/webpack-virtual-modules.mjs +0 -272
  84. package/dist/_nitro2.mjs +0 -303
  85. /package/dist/{_rolldown.mjs → _common.mjs} +0 -0
package/dist/vite.mjs CHANGED
@@ -1,1141 +1,27 @@
1
- import { i as __toESM } from "./_rolldown.mjs";
2
- import { a as isAbsolute$1, l as relative$1, n as basename$1, o as join$1, r as dirname$1, s as normalize$1, u as resolve$1 } from "./_libs/pathe.mjs";
3
- import "./_libs/dotenv.mjs";
4
- import { t as resolveModulePath } from "./_libs/exsolve.mjs";
5
- import { t as debounce } from "./_libs/perfect-debounce.mjs";
1
+ import "./_common.mjs";
2
+ import { Et as resolveModulePath, Ft as resolve$1, Mt as join$1, Ot as basename$1, Pt as relative$1, Q as copyPublicAssets, Z as prepare, a as libChunkName, dt as a, i as getChunkName, jt as isAbsolute$1, kt as dirname$1, m as writeBuildInfo, n as baseBuildPlugins, o as baseBuildConfig, ot as prettyPath, p as getBuildInfo, r as NODE_MODULES_RE, ut as T } from "./_build/common.mjs";
3
+ import { s as debounce } from "./_libs/c12.mjs";
6
4
  import { t as formatCompatibilityDate } from "./_libs/compatx.mjs";
7
- import { i as a, r as T, t as A } from "./_libs/std-env.mjs";
8
- import { a as copyPublicAssets, i as prepare, s as createNitro } from "./_nitro.mjs";
5
+ import { i as createNitro } from "./_chunks/nitro.mjs";
9
6
  import "./_libs/tsconfck.mjs";
10
- import { n as prettyPath } from "./_build/shared2.mjs";
11
- import "./_libs/fdir.mjs";
12
- import { t as glob } from "./_libs/tinyglobby.mjs";
13
- import { i as scanHandlers } from "./_nitro2.mjs";
14
- import { t as src_default } from "./_libs/mime.mjs";
15
- import "./_libs/acorn.mjs";
16
- import { i as genSafeVariableName, t as genImport } from "./_libs/knitwork.mjs";
17
- import "./_libs/@jridgewell/sourcemap-codec.mjs";
18
- import "./_libs/js-tokens.mjs";
19
- import { n as writeBuildInfo, t as getBuildInfo } from "./_build/shared3.mjs";
20
- import { i as NodeEnvRunner, r as NitroDevApp } from "./_dev.mjs";
7
+ import { n as scanHandlers } from "./_chunks/nitro2.mjs";
8
+ import { i as NodeEnvRunner, r as NitroDevApp } from "./_chunks/dev.mjs";
21
9
  import { a as watch$1 } from "./_libs/chokidar.mjs";
10
+ import "./_chunks/utils.mjs";
22
11
  import { t as alias } from "./_libs/@rollup/plugin-alias.mjs";
23
- import "./_libs/@rollup/pluginutils.mjs";
24
12
  import { t as inject } from "./_libs/@rollup/plugin-inject.mjs";
25
- import { t as require_etag } from "./_libs/etag.mjs";
26
- import { t as replace } from "./_libs/@rollup/plugin-replace.mjs";
27
- import { t as unwasm } from "./_libs/unwasm.mjs";
28
13
  import { r as assetsPlugin } from "./_libs/@hiogawa/vite-plugin-fullstack.mjs";
29
- import { builtinModules, createRequire } from "node:module";
30
14
  import consola$1 from "consola";
31
- import { existsSync, promises, watch } from "node:fs";
15
+ import { existsSync, watch } from "node:fs";
32
16
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
33
- import { pathToFileURL } from "node:url";
34
17
  import { join, resolve } from "node:path";
35
18
  import { defu } from "defu";
36
- import { joinURL, withTrailingSlash } from "ufo";
37
- import { pkgDir, presetsDir, runtimeDependencies, runtimeDir } from "nitro/meta";
19
+ import { runtimeDependencies, runtimeDir } from "nitro/meta";
38
20
  import { colors } from "consola/utils";
39
- import { hash } from "ohash";
40
- import { camelCase } from "scule";
41
21
  import { NodeRequest, sendNodeResponse } from "srvx/node";
42
- import { defineEnv } from "unenv";
43
- import { connectors } from "db0";
44
- import { RENDER_CONTEXT_KEYS, compileTemplateToString, hasTemplateSyntax } from "rendu";
45
- import { builtinDrivers, normalizeKey } from "unstorage";
46
- import { transformSync } from "oxc-transform";
47
- import { NodeNativePackages } from "nf3";
48
22
  import { DevEnvironment } from "vite";
49
23
  import { spawn } from "node:child_process";
50
24
 
51
- //#region src/utils/regex.ts
52
- function escapeRegExp(string) {
53
- return string.replace(/[-\\^$*+?.()|[\]{}]/g, String.raw`\$&`);
54
- }
55
- function pathRegExp(string) {
56
- if (A) string = string.replace(/\\/g, "/");
57
- let escaped = escapeRegExp(string);
58
- if (A) escaped = escaped.replace(/\//g, String.raw`[/\\]`);
59
- return escaped;
60
- }
61
- function toPathRegExp(input) {
62
- if (input instanceof RegExp) return input;
63
- if (typeof input === "string") return new RegExp(pathRegExp(input));
64
- throw new TypeError("Expected a string or RegExp", { cause: input });
65
- }
66
-
67
- //#endregion
68
- //#region src/build/config.ts
69
- function baseBuildConfig(nitro$1) {
70
- const extensions = [
71
- ".ts",
72
- ".mjs",
73
- ".js",
74
- ".json",
75
- ".node",
76
- ".tsx",
77
- ".jsx"
78
- ];
79
- const isNodeless = nitro$1.options.node === false;
80
- const importMetaInjections = {
81
- dev: nitro$1.options.dev,
82
- preset: nitro$1.options.preset,
83
- prerender: nitro$1.options.preset === "nitro-prerender",
84
- nitro: true,
85
- server: true,
86
- client: false,
87
- baseURL: nitro$1.options.baseURL,
88
- _asyncContext: nitro$1.options.experimental.asyncContext,
89
- _tasks: nitro$1.options.experimental.tasks
90
- };
91
- const replacements = {
92
- ...Object.fromEntries(Object.entries(importMetaInjections).map(([key, val]) => [`import.meta.${key}`, JSON.stringify(val)])),
93
- ...nitro$1.options.replace
94
- };
95
- const { env } = defineEnv({
96
- nodeCompat: isNodeless,
97
- resolve: true,
98
- presets: nitro$1.options.unenv,
99
- overrides: { alias: nitro$1.options.alias }
100
- });
101
- return {
102
- extensions,
103
- isNodeless,
104
- replacements,
105
- env,
106
- aliases: resolveAliases({ ...env.alias }),
107
- noExternal: getNoExternals(nitro$1),
108
- ignoreWarningCodes: new Set([
109
- "EVAL",
110
- "CIRCULAR_DEPENDENCY",
111
- "THIS_IS_UNDEFINED",
112
- "EMPTY_BUNDLE"
113
- ])
114
- };
115
- }
116
- function getNoExternals(nitro$1) {
117
- const noExternal = [
118
- /\.[mc]?tsx?$/,
119
- /^(?:[\0#~.]|virtual:)/,
120
- /* @__PURE__ */ new RegExp("^" + pathRegExp(pkgDir) + "(?!.*node_modules)"),
121
- ...[nitro$1.options.rootDir, ...nitro$1.options.scanDirs.filter((dir) => dir.includes("node_modules") || !dir.startsWith(nitro$1.options.rootDir))].map((dir) => /* @__PURE__ */ new RegExp("^" + pathRegExp(dir) + "(?!.*node_modules)"))
122
- ];
123
- if (nitro$1.options.wasm !== false) noExternal.push(/\.wasm$/);
124
- if (Array.isArray(nitro$1.options.noExternals)) noExternal.push(...nitro$1.options.noExternals.filter(Boolean).map((item) => toPathRegExp(item)));
125
- return noExternal.sort((a$1, b) => a$1.source.length - b.source.length);
126
- }
127
- function resolveAliases(_aliases) {
128
- const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a$1], [b]) => b.split("/").length - a$1.split("/").length || b.length - a$1.length));
129
- for (const key in aliases) for (const alias$1 in aliases) {
130
- if (![
131
- "~",
132
- "@",
133
- "#"
134
- ].includes(alias$1[0])) continue;
135
- if (alias$1 === "@" && !aliases[key].startsWith("@/")) continue;
136
- if (aliases[key].startsWith(alias$1)) aliases[key] = aliases[alias$1] + aliases[key].slice(alias$1.length);
137
- }
138
- return aliases;
139
- }
140
-
141
- //#endregion
142
- //#region src/build/chunks.ts
143
- const virtualRe = /^(?:\0|#|virtual:)/;
144
- const NODE_MODULES_RE$1 = /node_modules[/\\][^.]/;
145
- function libChunkName(id) {
146
- return `_libs/${id.match(/.*(?:[/\\])node_modules(?:[/\\])(?<package>@[^/\\]+[/\\][^/\\]+|[^/\\.][^/\\]*)/)?.groups?.package || "common"}`;
147
- }
148
- function getChunkName(chunk, nitro$1) {
149
- if (chunk.name.startsWith("_libs/")) return `${chunk.name}.mjs`;
150
- if (chunk.name === "rolldown-runtime") return "_rolldown.mjs";
151
- if (chunk.moduleIds.length === 0) return `_chunks/${chunk.name}.mjs`;
152
- const ids = chunk.moduleIds.filter((id) => !virtualRe.test(id));
153
- if (ids.length === 0) {
154
- if (chunk.moduleIds.every((id) => id.includes("virtual:raw"))) return `_raw/[name].mjs`;
155
- return `_virtual/[name].mjs`;
156
- }
157
- if (ids.every((id) => id.endsWith(".wasm"))) return `_wasm/[name].mjs`;
158
- if (ids.every((id) => id.includes("vite/services"))) return `_ssr/[name].mjs`;
159
- if (ids.every((id) => id.startsWith(nitro$1.options.buildDir))) return `_build/[name].mjs`;
160
- if (ids.every((id) => id.startsWith(runtimeDir) || id.startsWith(presetsDir))) return `_nitro/[name].mjs`;
161
- const mainId = ids.at(-1);
162
- if (mainId) {
163
- const routeHandler = nitro$1.routing.routes.routes.flatMap((h) => h.data).find((h) => h.handler === mainId);
164
- if (routeHandler?.route) return `_routes/${routeToFsPath(routeHandler.route)}.mjs`;
165
- if (Object.entries(nitro$1.options.tasks).find(([_, task]) => task.handler === mainId)) return `_tasks/[name].mjs`;
166
- }
167
- return `_chunks/[name].mjs`;
168
- }
169
- function routeToFsPath(route) {
170
- return route.split("/").slice(1).map((s) => `${s.replace(/[:*]+/g, "$").replace(/[^$a-zA-Z0-9_.[\]/]/g, "_")}`).join("/") || "index";
171
- }
172
-
173
- //#endregion
174
- //#region src/build/virtual/database.ts
175
- function database(nitro$1) {
176
- return {
177
- id: "#nitro/virtual/database",
178
- template: () => {
179
- if (!nitro$1.options.experimental.database) return `export const connectionConfigs = {};`;
180
- const dbConfigs = nitro$1.options.dev && nitro$1.options.devDatabase || nitro$1.options.database;
181
- const connectorsNames = [...new Set(Object.values(dbConfigs || {}).map((config) => config?.connector))].filter(Boolean);
182
- for (const name of connectorsNames) if (!connectors[name]) throw new Error(`Database connector "${name}" is invalid.`);
183
- return `
184
- ${connectorsNames.map((name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`).join("\n")}
185
-
186
- export const connectionConfigs = {
187
- ${Object.entries(dbConfigs || {}).filter(([, config]) => !!config?.connector).map(([name, { connector, options }]) => `${name}: {
188
- connector: ${camelCase(connector)}Connector,
189
- options: ${JSON.stringify(options)}
190
- }`).join(",\n")}
191
- };
192
- `;
193
- }
194
- };
195
- }
196
-
197
- //#endregion
198
- //#region src/build/virtual/error-handler.ts
199
- function errorHandler(nitro$1) {
200
- return {
201
- id: "#nitro/virtual/error-handler",
202
- template: () => {
203
- const errorHandlers = Array.isArray(nitro$1.options.errorHandler) ? nitro$1.options.errorHandler : [nitro$1.options.errorHandler];
204
- const builtinHandler = join$1(runtimeDir, `internal/error/${nitro$1.options.dev ? "dev" : "prod"}`);
205
- return `
206
- ${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")}
207
-
208
- const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}];
209
-
210
- import { defaultHandler } from "${builtinHandler}";
211
-
212
- export default async function(error, event) {
213
- for (const handler of errorHandlers) {
214
- try {
215
- const response = await handler(error, event, { defaultHandler });
216
- if (response) {
217
- return response;
218
- }
219
- } catch(error) {
220
- // Handler itself thrown, log and continue
221
- console.error(error);
222
- }
223
- }
224
- // H3 will handle fallback
225
- }
226
- `;
227
- }
228
- };
229
- }
230
-
231
- //#endregion
232
- //#region src/build/virtual/feature-flags.ts
233
- function featureFlags(nitro$1) {
234
- return {
235
- id: "#nitro/virtual/feature-flags",
236
- template: () => {
237
- const featureFlags$1 = {
238
- hasRoutes: nitro$1.routing.routes.hasRoutes(),
239
- hasRouteRules: nitro$1.routing.routeRules.hasRoutes(),
240
- hasRoutedMiddleware: nitro$1.routing.routedMiddleware.hasRoutes(),
241
- hasGlobalMiddleware: nitro$1.routing.globalMiddleware.length > 0,
242
- hasPlugins: nitro$1.options.plugins.length > 0,
243
- hasHooks: nitro$1.options.features?.runtimeHooks ?? nitro$1.options.plugins.length > 0,
244
- hasWebSocket: nitro$1.options.features?.websocket ?? nitro$1.options.experimental.websocket ?? false
245
- };
246
- return Object.entries(featureFlags$1).map(([key, value]) => `export const ${key} = ${Boolean(value)};`).join("\n");
247
- }
248
- };
249
- }
250
-
251
- //#endregion
252
- //#region src/build/virtual/plugins.ts
253
- function plugins(nitro$1) {
254
- return {
255
- id: "#nitro/virtual/plugins",
256
- template: () => {
257
- const nitroPlugins = [...new Set(nitro$1.options.plugins)];
258
- return `
259
- ${nitroPlugins.map((plugin) => `import _${hash(plugin).replace(/-/g, "")} from "${plugin}";`).join("\n")}
260
-
261
- export const plugins = [
262
- ${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")}
263
- ]
264
- `;
265
- }
266
- };
267
- }
268
-
269
- //#endregion
270
- //#region src/build/virtual/polyfills.ts
271
- function polyfills(_nitro, polyfills$1) {
272
- return {
273
- id: "#nitro/virtual/polyfills",
274
- moduleSideEffects: true,
275
- template: () => {
276
- return polyfills$1.map((p) => `import '${p}';`).join("\n") || `/* No polyfills */`;
277
- }
278
- };
279
- }
280
-
281
- //#endregion
282
- //#region src/build/virtual/public-assets.ts
283
- var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
284
- const readAssetHandler = {
285
- true: "node",
286
- node: "node",
287
- false: "null",
288
- deno: "deno",
289
- inline: "inline"
290
- };
291
- function publicAssets(nitro$1) {
292
- return [
293
- {
294
- id: "#nitro/virtual/public-assets-data",
295
- template: async () => {
296
- const assets = {};
297
- const files = await glob("**", {
298
- cwd: nitro$1.options.output.publicDir,
299
- absolute: false,
300
- dot: true
301
- });
302
- for (const id of files) {
303
- let mimeType = src_default.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
304
- if (mimeType.startsWith("text")) mimeType += "; charset=utf-8";
305
- const fullPath = resolve$1(nitro$1.options.output.publicDir, id);
306
- const assetData = await promises.readFile(fullPath);
307
- const etag = (0, import_etag.default)(assetData);
308
- const stat$2 = await promises.stat(fullPath);
309
- const assetId = joinURL(nitro$1.options.baseURL, decodeURIComponent(id));
310
- let encoding;
311
- if (id.endsWith(".gz")) encoding = "gzip";
312
- else if (id.endsWith(".br")) encoding = "br";
313
- assets[assetId] = {
314
- type: nitro$1._prerenderMeta?.[assetId]?.contentType || mimeType,
315
- encoding,
316
- etag,
317
- mtime: stat$2.mtime.toJSON(),
318
- size: stat$2.size,
319
- path: relative$1(nitro$1.options.output.serverDir, fullPath),
320
- data: nitro$1.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
321
- };
322
- }
323
- return `export default ${JSON.stringify(assets, null, 2)};`;
324
- }
325
- },
326
- {
327
- id: "#nitro/virtual/public-assets",
328
- template: () => {
329
- const publicAssetBases = Object.fromEntries(nitro$1.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [withTrailingSlash(joinURL(nitro$1.options.baseURL, dir.baseURL || "/")), { maxAge: dir.maxAge }]));
330
- return `
331
- import assets from '#nitro/virtual/public-assets-data'
332
- export { readAsset } from "${`#nitro/virtual/public-assets-${readAssetHandler[nitro$1.options.serveStatic] || "null"}`}"
333
- export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
334
-
335
- export function isPublicAssetURL(id = '') {
336
- if (assets[id]) {
337
- return true
338
- }
339
- for (const base in publicAssetBases) {
340
- if (id.startsWith(base)) { return true }
341
- }
342
- return false
343
- }
344
-
345
- export function getPublicAssetMeta(id = '') {
346
- for (const base in publicAssetBases) {
347
- if (id.startsWith(base)) { return publicAssetBases[base] }
348
- }
349
- return {}
350
- }
351
-
352
- export function getAsset (id) {
353
- return assets[id]
354
- }
355
- `;
356
- }
357
- },
358
- {
359
- id: "#nitro/virtual/public-assets-node",
360
- template: () => {
361
- return `
362
- import { promises as fsp } from 'node:fs'
363
- import { fileURLToPath } from 'node:url'
364
- import { resolve, dirname } from 'node:path'
365
- import assets from '#nitro/virtual/public-assets-data'
366
- export function readAsset (id) {
367
- const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__))
368
- return fsp.readFile(resolve(serverDir, assets[id].path))
369
- }`;
370
- }
371
- },
372
- {
373
- id: "#nitro/virtual/public-assets-deno",
374
- template: () => {
375
- return `
376
- import assets from '#nitro/virtual/public-assets-data'
377
- export function readAsset (id) {
378
- // https://deno.com/deploy/docs/serve-static-assets
379
- const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
380
- return Deno.readFile(path);
381
- }`;
382
- }
383
- },
384
- {
385
- id: "#nitro/virtual/public-assets-null",
386
- template: () => {
387
- return `
388
- export function readAsset (id) {
389
- return Promise.resolve(null);
390
- }`;
391
- }
392
- },
393
- {
394
- id: "#nitro/virtual/public-assets-inline",
395
- template: () => {
396
- return `
397
- import assets from '#nitro/virtual/public-assets-data'
398
- export function readAsset (id) {
399
- if (!assets[id]) { return undefined }
400
- if (assets[id]._data) { return assets[id]._data }
401
- if (!assets[id].data) { return assets[id].data }
402
- assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
403
- return assets[id]._data
404
- }`;
405
- }
406
- }
407
- ];
408
- }
409
-
410
- //#endregion
411
- //#region src/build/virtual/renderer-template.ts
412
- function rendererTemplate(nitro$1) {
413
- return {
414
- id: "#nitro/virtual/renderer-template",
415
- template: async () => {
416
- const template = nitro$1.options.renderer?.template;
417
- if (typeof template !== "string") return `
418
- export const rendererTemplate = () => '<!-- renderer.template is not set -->';
419
- export const rendererTemplateFile = undefined;
420
- export const isStaticTemplate = true;`;
421
- if (nitro$1.options.dev) return `
422
- import { readFile } from 'node:fs/promises';
423
- export const rendererTemplate = () => readFile(${JSON.stringify(template)}, "utf8");
424
- export const rendererTemplateFile = ${JSON.stringify(template)};
425
- export const isStaticTemplate = ${JSON.stringify(nitro$1.options.renderer?.static)};
426
- `;
427
- else {
428
- const html = await readFile(template, "utf8");
429
- if (nitro$1.options.renderer?.static ?? !hasTemplateSyntax(html)) return `
430
- import { HTTPResponse } from "h3";
431
- export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } });
432
- `;
433
- else return `
434
- import { renderToResponse } from 'rendu'
435
- import { serverFetch } from 'nitro/app'
436
- const template = ${compileTemplateToString(html, { contextKeys: [...RENDER_CONTEXT_KEYS] })};
437
- export const rendererTemplate = (request) => renderToResponse(template, { request, context: { serverFetch } })
438
- `;
439
- }
440
- }
441
- };
442
- }
443
-
444
- //#endregion
445
- //#region src/build/virtual/routing-meta.ts
446
- function routingMeta(nitro$1) {
447
- return {
448
- id: "#nitro/virtual/routing-meta",
449
- template: () => {
450
- const routeHandlers = uniqueBy$1(Object.values(nitro$1.routing.routes.routes).flatMap((h) => h.data), "_importHash");
451
- return `
452
- ${routeHandlers.map((h) => `import ${h._importHash}Meta from "${h.handler}?meta";`).join("\n")}
453
- export const handlersMeta = [
454
- ${routeHandlers.map((h) => `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(h.method?.toLowerCase())}, meta: ${h._importHash}Meta }`).join(",\n")}
455
- ];
456
- `.trim();
457
- }
458
- };
459
- }
460
- function uniqueBy$1(arr, key) {
461
- return [...new Map(arr.map((item) => [item[key], item])).values()];
462
- }
463
-
464
- //#endregion
465
- //#region src/build/virtual/routing.ts
466
- const RuntimeRouteRules = [
467
- "headers",
468
- "redirect",
469
- "proxy",
470
- "cache"
471
- ];
472
- function routing(nitro$1) {
473
- return {
474
- id: "#nitro/virtual/routing",
475
- template: () => {
476
- const allHandlers = uniqueBy([
477
- ...Object.values(nitro$1.routing.routes.routes).flatMap((h) => h.data),
478
- ...Object.values(nitro$1.routing.routedMiddleware.routes).map((h) => h.data),
479
- ...nitro$1.routing.globalMiddleware
480
- ], "_importHash");
481
- return `
482
- import * as __routeRules__ from "#nitro/runtime/route-rules";
483
- import * as srvxNode from "srvx/node"
484
- import * as h3 from "h3";
485
-
486
- export const findRouteRules = ${nitro$1.routing.routeRules.compileToString({
487
- serialize: serializeRouteRule,
488
- matchAll: true
489
- })}
490
-
491
- const multiHandler = (...handlers) => {
492
- const final = handlers.pop()
493
- const middleware = handlers.filter(Boolean).map(h => h3.toMiddleware(h));
494
- return (ev) => h3.callMiddleware(ev, middleware, final);
495
- }
496
-
497
- ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "${h.handler}";`).join("\n")}
498
-
499
- ${allHandlers.filter((h) => h.lazy).map((h) => `const ${h._importHash} = h3.defineLazyEventHandler(() => import("${h.handler}")${h.format === "node" ? ".then(m => srvxNode.toFetchHandler(m.default))" : ""});`).join("\n")}
500
-
501
- export const findRoute = ${nitro$1.routing.routes.compileToString({ serialize: serializeHandler })}
502
-
503
- export const findRoutedMiddleware = ${nitro$1.routing.routedMiddleware.compileToString({
504
- serialize: serializeHandler,
505
- matchAll: true
506
- })};
507
-
508
- export const globalMiddleware = [
509
- ${nitro$1.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `h3.toEventHandler(${h._importHash})`).join(",")}
510
- ].filter(Boolean);
511
- `;
512
- }
513
- };
514
- }
515
- function uniqueBy(arr, key) {
516
- return [...new Map(arr.map((item) => [item[key], item])).values()];
517
- }
518
- function serializeHandler(h) {
519
- const meta = Array.isArray(h) ? h[0] : h;
520
- return `{${[
521
- `route:${JSON.stringify(meta.route)}`,
522
- meta.method && `method:${JSON.stringify(meta.method)}`,
523
- meta.meta && `meta:${JSON.stringify(meta.meta)}`,
524
- `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
525
- ].filter(Boolean).join(",")}}`;
526
- }
527
- function serializeHandlerFn(h) {
528
- let code = h._importHash;
529
- if (!h.lazy) {
530
- if (h.format === "node") code = `srvxNode.toFetchHandler(${code})`;
531
- code = `h3.toEventHandler(${code})`;
532
- }
533
- return code;
534
- }
535
- function serializeRouteRule(h) {
536
- return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => {
537
- return `{${[
538
- `name:${JSON.stringify(name)}`,
539
- `route:${JSON.stringify(h._route)}`,
540
- h._method && `method:${JSON.stringify(h._method)}`,
541
- RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`,
542
- `options:${JSON.stringify(options)}`
543
- ].filter(Boolean).join(",")}}`;
544
- }).join(",")}]`;
545
- }
546
-
547
- //#endregion
548
- //#region src/build/virtual/runtime-config.ts
549
- function runtimeConfig(nitro$1) {
550
- return {
551
- id: "#nitro/virtual/runtime-config",
552
- template: () => {
553
- return `export const runtimeConfig = ${JSON.stringify(nitro$1.options.runtimeConfig || {})};`;
554
- }
555
- };
556
- }
557
-
558
- //#endregion
559
- //#region src/build/virtual/server-assets.ts
560
- function serverAssets(nitro$1) {
561
- return {
562
- id: "#nitro/virtual/server-assets",
563
- template: async () => {
564
- if (nitro$1.options.dev || nitro$1.options.preset === "nitro-prerender") return `
565
- import { createStorage } from 'unstorage'
566
- import fsDriver from 'unstorage/drivers/fs'
567
- const serverAssets = ${JSON.stringify(nitro$1.options.serverAssets)}
568
- export const assets = createStorage()
569
- for (const asset of serverAssets) {
570
- assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
571
- }`;
572
- const assets = {};
573
- for (const asset of nitro$1.options.serverAssets) {
574
- const files = await glob(asset.pattern || "**/*", {
575
- cwd: asset.dir,
576
- absolute: false,
577
- ignore: asset.ignore
578
- });
579
- for (const _id of files) {
580
- const fsPath = resolve$1(asset.dir, _id);
581
- const id = asset.baseName + "/" + _id;
582
- assets[id] = {
583
- fsPath,
584
- meta: {}
585
- };
586
- let type = src_default.getType(id) || "text/plain";
587
- if (type.startsWith("text")) type += "; charset=utf-8";
588
- const etag = (0, import_etag.default)(await promises.readFile(fsPath));
589
- const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
590
- assets[id].meta = {
591
- type,
592
- etag,
593
- mtime
594
- };
595
- }
596
- }
597
- return `
598
- const _assets = {\n${Object.entries(assets).map(([id, asset]) => ` [${JSON.stringify(normalizeKey(id))}]: {\n import: () => import(${JSON.stringify("raw:" + asset.fsPath)}).then(r => r.default || r),\n meta: ${JSON.stringify(asset.meta)}\n }`).join(",\n")}\n}
599
-
600
- const normalizeKey = ${normalizeKey.toString()}
601
-
602
- export const assets = {
603
- getKeys() {
604
- return Promise.resolve(Object.keys(_assets))
605
- },
606
- hasItem (id) {
607
- id = normalizeKey(id)
608
- return Promise.resolve(id in _assets)
609
- },
610
- getItem (id) {
611
- id = normalizeKey(id)
612
- return Promise.resolve(_assets[id] ? _assets[id].import() : null)
613
- },
614
- getMeta (id) {
615
- id = normalizeKey(id)
616
- return Promise.resolve(_assets[id] ? _assets[id].meta : {})
617
- }
618
- }
619
- `;
620
- }
621
- };
622
- }
623
-
624
- //#endregion
625
- //#region src/build/virtual/storage.ts
626
- function storage(nitro$1) {
627
- return {
628
- id: "#nitro/virtual/storage",
629
- template: () => {
630
- const mounts = [];
631
- const storageMounts = nitro$1.options.dev || nitro$1.options.preset === "nitro-prerender" ? {
632
- ...nitro$1.options.storage,
633
- ...nitro$1.options.devStorage
634
- } : nitro$1.options.storage;
635
- for (const path$1 in storageMounts) {
636
- const { driver: driverName, ...driverOpts } = storageMounts[path$1];
637
- mounts.push({
638
- path: path$1,
639
- driver: builtinDrivers[driverName] || driverName,
640
- opts: driverOpts
641
- });
642
- }
643
- return `
644
- import { createStorage } from 'unstorage'
645
- import { assets } from '#nitro/virtual/server-assets'
646
-
647
- ${[...new Set(mounts.map((m) => m.driver))].map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
648
-
649
- export function initStorage() {
650
- const storage = createStorage({})
651
- storage.mount('/assets', assets)
652
- ${mounts.map((m) => `storage.mount('${m.path}', ${genSafeVariableName(m.driver)}(${JSON.stringify(m.opts)}))`).join("\n")}
653
- return storage
654
- }
655
- `;
656
- }
657
- };
658
- }
659
-
660
- //#endregion
661
- //#region src/build/virtual/tasks.ts
662
- function tasks(nitro$1) {
663
- return {
664
- id: "#nitro/virtual/tasks",
665
- template: () => {
666
- const _scheduledTasks = Object.entries(nitro$1.options.scheduledTasks || {}).map(([cron, _tasks]) => {
667
- return {
668
- cron,
669
- tasks: (Array.isArray(_tasks) ? _tasks : [_tasks]).filter((name) => {
670
- if (!nitro$1.options.tasks[name]) {
671
- nitro$1.logger.warn(`Scheduled task \`${name}\` is not defined!`);
672
- return false;
673
- }
674
- return true;
675
- })
676
- };
677
- }).filter((e) => e.tasks.length > 0);
678
- const scheduledTasks = _scheduledTasks.length > 0 ? _scheduledTasks : false;
679
- return `
680
- export const scheduledTasks = ${JSON.stringify(scheduledTasks)};
681
-
682
- export const tasks = {
683
- ${Object.entries(nitro$1.options.tasks).map(([name, task]) => `"${name}": {
684
- meta: {
685
- description: ${JSON.stringify(task.description)},
686
- },
687
- resolve: ${task.handler ? `() => import("${normalize$1(task.handler)}").then(r => r.default || r)` : "undefined"},
688
- }`).join(",\n")}
689
- };`;
690
- }
691
- };
692
- }
693
-
694
- //#endregion
695
- //#region src/build/virtual/_all.ts
696
- function virtualTemplates(nitro$1, _polyfills) {
697
- const nitroTemplates = [
698
- database,
699
- errorHandler,
700
- featureFlags,
701
- plugins,
702
- polyfills,
703
- publicAssets,
704
- rendererTemplate,
705
- routingMeta,
706
- routing,
707
- runtimeConfig,
708
- serverAssets,
709
- storage,
710
- tasks
711
- ].flatMap((t) => t(nitro$1, _polyfills));
712
- const customTemplates = Object.entries(nitro$1.options.virtual).map(([id, template]) => ({
713
- id,
714
- template
715
- }));
716
- return [...nitroTemplates, ...customTemplates];
717
- }
718
-
719
- //#endregion
720
- //#region src/build/plugins/route-meta.ts
721
- const PREFIX$1 = "\0nitro:route-meta:";
722
- function routeMeta(nitro$1) {
723
- return {
724
- name: "nitro:route-meta",
725
- resolveId: {
726
- filter: { id: /^(?!\u0000)(.+)\?meta$/ },
727
- async handler(id, importer, resolveOpts) {
728
- if (id.endsWith("?meta")) {
729
- const resolved = await this.resolve(id.replace("?meta", ""), importer, resolveOpts);
730
- if (!resolved) return;
731
- return PREFIX$1 + resolved.id;
732
- }
733
- }
734
- },
735
- load: {
736
- filter: { id: /* @__PURE__ */ new RegExp(`^${escapeRegExp(PREFIX$1)}`) },
737
- handler(id) {
738
- if (id.startsWith(PREFIX$1)) {
739
- const fullPath = id.slice(18);
740
- if (isAbsolute$1(fullPath)) return readFile(fullPath, { encoding: "utf8" });
741
- else return "export default undefined;";
742
- }
743
- }
744
- },
745
- transform: {
746
- filter: { id: /* @__PURE__ */ new RegExp(`^${escapeRegExp(PREFIX$1)}`) },
747
- async handler(code, id) {
748
- let meta = null;
749
- try {
750
- const transformRes = transformSync(id, code);
751
- if (transformRes.errors?.length > 0) {
752
- for (const error of transformRes.errors) this.warn(error);
753
- return {
754
- code: `export default {};`,
755
- map: null
756
- };
757
- }
758
- const ast = this.parse(transformRes.code);
759
- for (const node of ast.body) if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) {
760
- meta = astToObject(node.expression.arguments[0]);
761
- break;
762
- }
763
- } catch (error) {
764
- nitro$1.logger.warn(`[handlers-meta] Cannot extra route meta for: ${id}: ${error}`);
765
- }
766
- return {
767
- code: `export default ${JSON.stringify(meta)};`,
768
- map: null
769
- };
770
- }
771
- }
772
- };
773
- }
774
- function astToObject(node) {
775
- switch (node.type) {
776
- case "ObjectExpression": {
777
- const obj = {};
778
- for (const prop of node.properties) if (prop.type === "Property") {
779
- const key = prop.key.name ?? prop.key.value;
780
- obj[key] = astToObject(prop.value);
781
- }
782
- return obj;
783
- }
784
- case "ArrayExpression": return node.elements.map((el) => astToObject(el)).filter((obj) => obj !== void 0);
785
- case "Literal": return node.value;
786
- }
787
- }
788
-
789
- //#endregion
790
- //#region src/build/plugins/server-main.ts
791
- function serverMain(nitro$1) {
792
- return {
793
- name: "nitro:server-main",
794
- renderChunk(code, chunk) {
795
- if (chunk.isEntry) return {
796
- code: `globalThis.__nitro_main__ = import.meta.url; ${code}`,
797
- map: null
798
- };
799
- }
800
- };
801
- }
802
-
803
- //#endregion
804
- //#region src/build/plugins/virtual.ts
805
- function virtual(input) {
806
- const modules = /* @__PURE__ */ new Map();
807
- for (const mod of input) {
808
- const render = () => typeof mod.template === "function" ? mod.template() : mod.template;
809
- modules.set(mod.id, {
810
- module: mod,
811
- render
812
- });
813
- }
814
- const include = [/^#nitro\/virtual/];
815
- const extraIds = [...modules.keys()].filter((key) => !key.startsWith("#nitro/virtual"));
816
- if (extraIds.length > 0) include.push(/* @__PURE__ */ new RegExp(`^(${extraIds.map((id) => pathRegExp(id)).join("|")})$`));
817
- return {
818
- name: "nitro:virtual",
819
- api: { modules },
820
- resolveId: {
821
- order: "pre",
822
- filter: { id: include },
823
- handler: (id) => {
824
- const mod = modules.get(id);
825
- if (mod) return {
826
- id,
827
- moduleSideEffects: mod.module.moduleSideEffects ?? false
828
- };
829
- }
830
- },
831
- load: {
832
- order: "pre",
833
- filter: { id: include },
834
- handler: async (id) => {
835
- const mod = modules.get(id);
836
- if (!mod) throw new Error(`Virtual module ${id} not found.`);
837
- return {
838
- code: await mod.render(),
839
- map: null
840
- };
841
- }
842
- }
843
- };
844
- }
845
- function virtualDeps() {
846
- const cache = /* @__PURE__ */ new Map();
847
- return {
848
- name: "nitro:virtual-deps",
849
- resolveId: {
850
- order: "pre",
851
- filter: { id: /* @__PURE__ */ new RegExp(`^(#nitro|${runtimeDependencies.map((dep) => pathRegExp(dep)).join("|")})`) },
852
- handler(id, importer) {
853
- if (!importer || !importer.startsWith("#nitro/virtual")) return;
854
- let resolved = cache.get(id);
855
- if (!resolved) resolved = this.resolve(id, runtimeDir).then((_resolved) => {
856
- cache.set(id, _resolved);
857
- return _resolved;
858
- }).catch((error) => {
859
- cache.delete(id);
860
- throw error;
861
- });
862
- return resolved;
863
- }
864
- }
865
- };
866
- }
867
-
868
- //#endregion
869
- //#region src/build/plugins/sourcemap-min.ts
870
- function sourcemapMinify() {
871
- return {
872
- name: "nitro:sourcemap-minify",
873
- generateBundle(_options, bundle) {
874
- for (const [key, asset] of Object.entries(bundle)) {
875
- if (!key.endsWith(".map") || !("source" in asset) || typeof asset.source !== "string") continue;
876
- const sourcemap = JSON.parse(asset.source);
877
- delete sourcemap.sourcesContent;
878
- delete sourcemap.x_google_ignoreList;
879
- if ((sourcemap.sources || []).some((s) => s.includes("node_modules"))) sourcemap.mappings = "";
880
- asset.source = JSON.stringify(sourcemap);
881
- }
882
- }
883
- };
884
- }
885
-
886
- //#endregion
887
- //#region src/build/plugins/raw.ts
888
- const HELPER_ID = "\0nitro-raw-helpers";
889
- const RESOLVED_PREFIX = "\0nitro:raw:";
890
- const PREFIX = "raw:";
891
- function raw() {
892
- return {
893
- name: "nitro:raw",
894
- resolveId: {
895
- order: "pre",
896
- filter: { id: [/* @__PURE__ */ new RegExp(`^${HELPER_ID}$`), /* @__PURE__ */ new RegExp(`^${PREFIX}`)] },
897
- async handler(id, importer, resolveOpts) {
898
- if (id === HELPER_ID) return id;
899
- if (id.startsWith(PREFIX)) {
900
- const resolvedId = (await this.resolve(id.slice(4), importer, resolveOpts))?.id;
901
- if (!resolvedId) return null;
902
- return { id: RESOLVED_PREFIX + resolvedId };
903
- }
904
- }
905
- },
906
- load: {
907
- order: "pre",
908
- filter: { id: [/* @__PURE__ */ new RegExp(`^${HELPER_ID}$`), /* @__PURE__ */ new RegExp(`^${RESOLVED_PREFIX}`)] },
909
- handler(id) {
910
- if (id === HELPER_ID) return getHelpers();
911
- if (id.startsWith(RESOLVED_PREFIX)) return promises.readFile(id.slice(11), isBinary(id) ? "binary" : "utf8");
912
- }
913
- },
914
- transform: {
915
- order: "pre",
916
- filter: { id: /* @__PURE__ */ new RegExp(`^${RESOLVED_PREFIX}`) },
917
- handler(code, id) {
918
- const path$1 = id.slice(11);
919
- if (isBinary(id)) return {
920
- code: `import {base64ToUint8Array } from "${HELPER_ID}" \n export default base64ToUint8Array("${Buffer.from(code, "binary").toString("base64")}")`,
921
- map: rawAssetMap(path$1)
922
- };
923
- return {
924
- code: `export default ${JSON.stringify(code)}`,
925
- map: rawAssetMap(path$1),
926
- moduleType: "js"
927
- };
928
- }
929
- }
930
- };
931
- }
932
- function isBinary(id) {
933
- const idMime = src_default.getType(id) || "";
934
- if (idMime.startsWith("text/")) return false;
935
- if (/application\/(json|sql|xml|yaml)/.test(idMime)) return false;
936
- return true;
937
- }
938
- function getHelpers() {
939
- return `
940
- export function base64ToUint8Array(str) {
941
- const data = atob(str);
942
- const size = data.length;
943
- const bytes = new Uint8Array(size);
944
- for (let i = 0; i < size; i++) {
945
- bytes[i] = data.charCodeAt(i);
946
- }
947
- return bytes;
948
- }
949
- `;
950
- }
951
- function rawAssetMap(id) {
952
- return {
953
- version: 3,
954
- file: id,
955
- sources: [id],
956
- sourcesContent: [],
957
- names: [],
958
- mappings: ""
959
- };
960
- }
961
-
962
- //#endregion
963
- //#region src/build/plugins/externals.ts
964
- const PLUGIN_NAME = "nitro:externals";
965
- function externals(opts) {
966
- const include = opts?.include ? opts.include.map((p) => toPathRegExp(p)) : void 0;
967
- const exclude = [/^(?:[\0#~.]|[a-z0-9]{2,}:)|\?/, ...(opts?.exclude || []).map((p) => toPathRegExp(p))];
968
- const filter = (id) => {
969
- if (include && !include.some((r) => r.test(id))) return false;
970
- if (exclude.some((r) => r.test(id))) return false;
971
- return true;
972
- };
973
- const tryResolve$1 = (id, from) => resolveModulePath(id, {
974
- try: true,
975
- from: from && isAbsolute$1(from) ? from : opts.rootDir,
976
- conditions: opts.conditions
977
- });
978
- const tracedPaths = /* @__PURE__ */ new Set();
979
- if (include && include.length === 0) return { name: PLUGIN_NAME };
980
- return {
981
- name: PLUGIN_NAME,
982
- resolveId: {
983
- order: "pre",
984
- filter: { id: {
985
- exclude,
986
- include
987
- } },
988
- async handler(id, importer, rOpts) {
989
- if (builtinModules.includes(id)) return {
990
- resolvedBy: PLUGIN_NAME,
991
- external: true,
992
- id: id.includes(":") ? id : `node:${id}`
993
- };
994
- if (rOpts.custom?.["node-resolve"]) return null;
995
- let resolved = await this.resolve(id, importer, rOpts);
996
- const cjsResolved = resolved?.meta?.commonjs?.resolved;
997
- if (cjsResolved) {
998
- if (!filter(cjsResolved.id)) return resolved;
999
- resolved = cjsResolved;
1000
- }
1001
- if (!resolved?.id || !filter(resolved.id)) return resolved;
1002
- let resolvedPath = resolved.id;
1003
- if (!isAbsolute$1(resolvedPath)) resolvedPath = tryResolve$1(resolvedPath, importer) || resolvedPath;
1004
- if (opts.trace) {
1005
- let importId = toImport(id) || toImport(resolvedPath);
1006
- if (!importId) return resolved;
1007
- if (!tryResolve$1(importId, importer)) {
1008
- const guessed = await guessSubpath(resolvedPath, opts.conditions);
1009
- if (!guessed) return resolved;
1010
- importId = guessed;
1011
- }
1012
- tracedPaths.add(resolvedPath);
1013
- return {
1014
- ...resolved,
1015
- resolvedBy: PLUGIN_NAME,
1016
- external: true,
1017
- id: importId
1018
- };
1019
- }
1020
- return {
1021
- ...resolved,
1022
- resolvedBy: PLUGIN_NAME,
1023
- external: true,
1024
- id: isAbsolute$1(resolvedPath) ? pathToFileURL(resolvedPath).href : resolvedPath
1025
- };
1026
- }
1027
- },
1028
- buildEnd: {
1029
- order: "post",
1030
- async handler() {
1031
- if (!opts.trace || tracedPaths.size === 0) return;
1032
- const { traceNodeModules } = await import("nf3");
1033
- const traceTime = Date.now();
1034
- let traceFilesCount = 0;
1035
- let tracedPkgsCount = 0;
1036
- await traceNodeModules([...tracedPaths], {
1037
- ...opts.trace,
1038
- conditions: opts.conditions,
1039
- rootDir: opts.rootDir,
1040
- writePackageJson: true,
1041
- hooks: {
1042
- tracedFiles(result) {
1043
- traceFilesCount = Object.keys(result).length;
1044
- },
1045
- tracedPackages: (pkgs) => {
1046
- tracedPkgsCount = Object.keys(pkgs).length;
1047
- consola$1.info(`Tracing dependencies:\n${Object.entries(pkgs).map(([name, versions]) => `- \`${name}\` (${Object.keys(versions.versions).join(", ")})`).join("\n")}`);
1048
- }
1049
- }
1050
- });
1051
- consola$1.success(`Traced ${tracedPkgsCount} dependencies (${traceFilesCount} files) in ${Date.now() - traceTime}ms.`);
1052
- consola$1.info(`Ensure your production environment matches the builder OS and architecture (\`${process.platform}-${process.arch}\`) to avoid native module issues.`);
1053
- }
1054
- }
1055
- };
1056
- }
1057
- const NODE_MODULES_RE = /^(?<dir>.+[\\/]node_modules[\\/])(?<name>[^@\\/]+|@[^\\/]+[\\/][^\\/]+)(?:[\\/](?<subpath>.+))?$/;
1058
- const IMPORT_RE = /^(?!\.)(?<name>[^@/\\]+|@[^/\\]+[/\\][^/\\]+)(?:[/\\](?<subpath>.+))?$/;
1059
- function toImport(id) {
1060
- if (isAbsolute$1(id)) {
1061
- const { name, subpath } = NODE_MODULES_RE.exec(id)?.groups || {};
1062
- if (name && subpath) return join$1(name, subpath);
1063
- } else if (IMPORT_RE.test(id)) return id;
1064
- }
1065
- function guessSubpath(path$1, conditions) {
1066
- const { dir, name, subpath } = NODE_MODULES_RE.exec(path$1)?.groups || {};
1067
- if (!dir || !name || !subpath) return;
1068
- const exports = getPkgJSON(join$1(dir, name) + "/")?.exports;
1069
- if (!exports || typeof exports !== "object") return;
1070
- for (const e of flattenExports(exports)) {
1071
- if (!conditions.includes(e.condition || "default")) continue;
1072
- if (e.fsPath === subpath) return join$1(name, e.subpath);
1073
- if (e.fsPath.includes("*")) {
1074
- const fsPathRe = /* @__PURE__ */ new RegExp("^" + escapeRegExp(e.fsPath).replace(String.raw`\*`, "(.+?)") + "$");
1075
- if (fsPathRe.test(subpath)) {
1076
- const matched = fsPathRe.exec(subpath)?.[1];
1077
- if (matched) return join$1(name, e.subpath.replace("*", matched));
1078
- }
1079
- }
1080
- }
1081
- }
1082
- function getPkgJSON(dir) {
1083
- const cache = getPkgJSON._cache ||= /* @__PURE__ */ new Map();
1084
- if (cache.has(dir)) return cache.get(dir);
1085
- try {
1086
- const pkg = createRequire(dir)("./package.json");
1087
- cache.set(dir, pkg);
1088
- return pkg;
1089
- } catch {}
1090
- }
1091
- function flattenExports(exports = {}, parentSubpath = "./") {
1092
- return Object.entries(exports).flatMap(([key, value]) => {
1093
- const [subpath, condition] = key.startsWith(".") ? [key.slice(1)] : [void 0, key];
1094
- const _subPath = join$1(parentSubpath, subpath || "");
1095
- if (typeof value === "string") return [{
1096
- subpath: _subPath,
1097
- fsPath: value.replace(/^\.\//, ""),
1098
- condition
1099
- }];
1100
- return typeof value === "object" ? flattenExports(value, _subPath) : [];
1101
- });
1102
- }
1103
-
1104
- //#endregion
1105
- //#region src/build/plugins.ts
1106
- async function baseBuildPlugins(nitro$1, base) {
1107
- const plugins$1 = [];
1108
- const virtualPlugin = virtual(virtualTemplates(nitro$1, [...base.env.polyfill]));
1109
- nitro$1.vfs = virtualPlugin.api.modules;
1110
- plugins$1.push(virtualPlugin, virtualDeps());
1111
- if (nitro$1.options.imports) {
1112
- const unimportPlugin = await import("./_libs/unimport.mjs").then((n) => n.i);
1113
- plugins$1.push(unimportPlugin.default.rollup(nitro$1.options.imports));
1114
- }
1115
- if (nitro$1.options.wasm !== false) plugins$1.push(unwasm(nitro$1.options.wasm || {}));
1116
- plugins$1.push(serverMain(nitro$1));
1117
- plugins$1.push(raw());
1118
- if (nitro$1.options.experimental.openAPI) plugins$1.push(routeMeta(nitro$1));
1119
- plugins$1.push(replace({
1120
- preventAssignment: true,
1121
- values: base.replacements
1122
- }));
1123
- if (nitro$1.options.node && nitro$1.options.noExternals !== true) {
1124
- const isDevOrPrerender = nitro$1.options.dev || nitro$1.options.preset === "nitro-prerender";
1125
- const traceDeps = [...new Set([...NodeNativePackages, ...nitro$1.options.traceDeps || []])];
1126
- plugins$1.push(externals({
1127
- rootDir: nitro$1.options.rootDir,
1128
- conditions: nitro$1.options.exportConditions || ["default"],
1129
- exclude: [...base.noExternal],
1130
- include: isDevOrPrerender ? void 0 : [/* @__PURE__ */ new RegExp(`^(?:${traceDeps.join("|")})|[/\\\\]node_modules[/\\\\](?:${traceDeps.join("|")})(?:[/\\\\])`)],
1131
- trace: isDevOrPrerender ? false : { outDir: nitro$1.options.output.serverDir }
1132
- }));
1133
- }
1134
- if (nitro$1.options.sourcemap && !nitro$1.options.dev && nitro$1.options.experimental.sourcemapMinify !== false) plugins$1.push(sourcemapMinify());
1135
- return plugins$1;
1136
- }
1137
-
1138
- //#endregion
1139
25
  //#region src/build/vite/rollup.ts
1140
26
  const getViteRollupConfig = async (ctx) => {
1141
27
  const nitro$1 = ctx.nitro;
@@ -1160,10 +46,10 @@ const getViteRollupConfig = async (ctx) => {
1160
46
  entryFileNames: "index.mjs",
1161
47
  chunkFileNames: (chunk) => getChunkName(chunk, nitro$1),
1162
48
  ...ctx._isRolldown ? { advancedChunks: { groups: [{
1163
- test: NODE_MODULES_RE$1,
49
+ test: NODE_MODULES_RE,
1164
50
  name: (id) => libChunkName(id)
1165
51
  }] } } : { manualChunks(id) {
1166
- if (NODE_MODULES_RE$1.test(id)) return libChunkName(id);
52
+ if (NODE_MODULES_RE.test(id)) return libChunkName(id);
1167
53
  } },
1168
54
  inlineDynamicImports: nitro$1.options.inlineDynamicImports,
1169
55
  dir: nitro$1.options.output.serverDir,
@@ -1818,9 +704,9 @@ function getEntry(input) {
1818
704
  else if (Array.isArray(input) && input.length > 0) return input[0];
1819
705
  else if (input && "index" in input) return input.index;
1820
706
  }
1821
- function flattenPlugins(plugins$1) {
1822
- return plugins$1.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise));
707
+ function flattenPlugins(plugins) {
708
+ return plugins.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise));
1823
709
  }
1824
710
 
1825
711
  //#endregion
1826
- export { baseBuildConfig as a, libChunkName as i, NODE_MODULES_RE$1 as n, nitro, getChunkName as r, baseBuildPlugins as t };
712
+ export { nitro };