nitro-nightly 3.0.1-20251217-221413-0e6f159e → 3.0.1-20251217-223946-1ee0b5b8

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