nitro-nightly 3.0.1-20251108-165335-a649b96d → 3.0.1-20251108-185438-04c7fe99

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,710 +1,68 @@
1
- import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
2
- import { C as join, D as relative, O as resolve, b as dirname, x as extname } from "../_libs/c12.mjs";
3
- import { i as unplugin } from "../_libs/unimport.mjs";
4
- import { t as glob } from "../_libs/tinyglobby.mjs";
5
- import { t as src_default } from "../_libs/mime.mjs";
6
- import { i as genSafeVariableName, t as genImport } from "../_libs/knitwork.mjs";
7
- import { t as replace } from "../_libs/plugin-replace.mjs";
8
- import { t as rollup } from "../_libs/unwasm.mjs";
9
- import { t as require_etag } from "../_libs/etag.mjs";
10
- import { camelCase } from "scule";
11
- import { promises } from "node:fs";
12
- import { joinURL, withTrailingSlash } from "ufo";
13
- import { readFile } from "node:fs/promises";
14
- import { defu } from "defu";
15
- import { pkgDir, runtimeDependencies, runtimeDir } from "nitro/meta";
16
- import { hash } from "ohash";
17
- import { defineEnv } from "unenv";
18
- import { connectors } from "db0";
19
- import { transform } from "esbuild";
20
- import { builtinDrivers, normalizeKey } from "unstorage";
21
- import { rollupNodeFileTrace } from "nf3";
22
- import { RENDER_CONTEXT_KEYS, compileTemplateToString, hasTemplateSyntax } from "rendu";
23
-
24
- //#region src/build/plugins/replace.ts
25
- const NO_REPLACE_RE = /ROLLUP_NO_REPLACE|\\0raw:/;
26
- function replace$1(options) {
27
- const _plugin = replace(options);
28
- return {
29
- ..._plugin,
30
- renderChunk(code, chunk, options$1) {
31
- if (!NO_REPLACE_RE.test(code)) return _plugin.renderChunk.call(this, code, chunk, options$1);
32
- }
33
- };
34
- }
35
-
36
- //#endregion
37
- //#region src/build/config.ts
38
- function baseBuildConfig(nitro) {
39
- const presetsDir$1 = resolve(runtimeDir, "../presets");
40
- const extensions = [
41
- ".ts",
42
- ".mjs",
43
- ".js",
44
- ".json",
45
- ".node",
46
- ".tsx",
47
- ".jsx"
48
- ];
49
- const isNodeless = nitro.options.node === false;
50
- let NODE_ENV = nitro.options.dev ? "development" : "production";
51
- if (nitro.options.preset === "nitro-prerender") NODE_ENV = "prerender";
52
- const buildEnvVars = {
53
- NODE_ENV,
54
- prerender: nitro.options.preset === "nitro-prerender",
55
- server: true,
56
- client: false,
57
- dev: String(nitro.options.dev),
58
- DEBUG: nitro.options.dev
59
- };
60
- const staticFlags = {
61
- dev: nitro.options.dev,
62
- preset: nitro.options.preset,
63
- prerender: nitro.options.preset === "nitro-prerender",
64
- server: true,
65
- client: false,
66
- nitro: true,
67
- baseURL: nitro.options.baseURL,
68
- "versions.nitro": "",
69
- "versions?.nitro": "",
70
- _asyncContext: nitro.options.experimental.asyncContext,
71
- _websocket: nitro.options.experimental.websocket,
72
- _tasks: nitro.options.experimental.tasks
73
- };
74
- const replacements = {
75
- "typeof window": "\"undefined\"",
76
- _import_meta_url_: "import.meta.url",
77
- "globalThis.process.": "process.",
78
- "process.env.RUNTIME_CONFIG": () => JSON.stringify(nitro.options.runtimeConfig, null, 2),
79
- ...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => [`process.env.${key}`, JSON.stringify(val)])),
80
- ...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => [`import.meta.env.${key}`, JSON.stringify(val)])),
81
- ...Object.fromEntries(Object.entries(staticFlags).map(([key, val]) => [`process.${key}`, JSON.stringify(val)])),
82
- ...Object.fromEntries(Object.entries(staticFlags).map(([key, val]) => [`import.meta.${key}`, JSON.stringify(val)])),
83
- ...nitro.options.replace
84
- };
85
- const { env } = defineEnv({
86
- nodeCompat: isNodeless,
87
- npmShims: true,
88
- resolve: true,
89
- presets: nitro.options.unenv,
90
- overrides: { alias: nitro.options.alias }
91
- });
92
- return {
93
- presetsDir: presetsDir$1,
94
- extensions,
95
- isNodeless,
96
- buildEnvVars,
97
- staticFlags,
98
- replacements,
99
- env,
100
- aliases: resolveAliases({ ...env.alias })
101
- };
102
- }
103
- function resolveAliases(_aliases) {
104
- const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length));
105
- for (const key in aliases) for (const alias in aliases) {
106
- if (![
107
- "~",
108
- "@",
109
- "#"
110
- ].includes(alias[0])) continue;
111
- if (alias === "@" && !aliases[key].startsWith("@/")) continue;
112
- if (aliases[key].startsWith(alias)) aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
113
- }
114
- return aliases;
115
- }
116
-
117
- //#endregion
118
- //#region src/build/plugins/virtual.ts
119
- const PREFIX = "\0virtual:";
120
- function virtual(modules, cache = {}, opts) {
121
- const _modules = /* @__PURE__ */ new Map();
122
- for (const [id, mod] of Object.entries(modules)) {
123
- cache[id] = mod;
124
- _modules.set(id, mod);
125
- _modules.set(resolve(id), mod);
126
- }
127
- return {
128
- name: "virtual",
129
- resolveId(id, importer) {
130
- if (id in modules) return {
131
- id: PREFIX + id,
132
- ...opts
133
- };
134
- if (importer) {
135
- const resolved = resolve(dirname(importer.startsWith(PREFIX) ? importer.slice(9) : importer), id);
136
- if (_modules.has(resolved)) return PREFIX + resolved;
137
- }
138
- return null;
139
- },
140
- async load(id) {
141
- if (!id.startsWith(PREFIX)) return null;
142
- const idNoPrefix = id.slice(9);
143
- if (!_modules.has(idNoPrefix)) return null;
144
- let m = _modules.get(idNoPrefix);
145
- if (typeof m === "function") m = await m();
146
- if (!m) return null;
147
- cache[id.replace(PREFIX, "")] = m;
148
- return {
149
- code: m,
150
- map: null
151
- };
152
- }
153
- };
154
- }
155
-
156
- //#endregion
157
- //#region src/build/plugins/database.ts
158
- function database(nitro) {
159
- if (!nitro.options.experimental.database) return virtual({ "#nitro-internal-virtual/database": () => {
160
- return `export const connectionConfigs = {};`;
161
- } }, nitro.vfs);
162
- const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database;
163
- const connectorsNames = [...new Set(Object.values(dbConfigs || {}).map((config) => config?.connector))].filter(Boolean);
164
- for (const name of connectorsNames) if (!connectors[name]) throw new Error(`Database connector "${name}" is invalid.`);
165
- return virtual({ "#nitro-internal-virtual/database": () => {
166
- return `
167
- ${connectorsNames.map((name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`).join("\n")}
168
-
169
- export const connectionConfigs = {
170
- ${Object.entries(dbConfigs || {}).map(([name, { connector, options }]) => `${name}: {
171
- connector: ${camelCase(connector)}Connector,
172
- options: ${JSON.stringify(options)}
173
- }`).join(",\n")}
174
- };
175
- `;
176
- } }, nitro.vfs);
177
- }
178
-
179
- //#endregion
180
- //#region src/build/plugins/routing.ts
181
- const RuntimeRouteRules = [
182
- "headers",
183
- "redirect",
184
- "proxy",
185
- "cache"
1
+ import { C as join$1, D as relative$1, O as resolve$1 } from "../_libs/c12.mjs";
2
+ import { i as writeFile$1 } from "../_chunks/DTJoprWj.mjs";
3
+ import { dirname } from "node:path";
4
+ import { mkdir, readFile, stat } from "node:fs/promises";
5
+ import { version } from "nitro/meta";
6
+
7
+ //#region src/presets/_types.gen.ts
8
+ const presetsWithConfig = [
9
+ "awsAmplify",
10
+ "awsLambda",
11
+ "azure",
12
+ "cloudflare",
13
+ "firebase",
14
+ "netlify",
15
+ "vercel"
186
16
  ];
187
- function routing(nitro) {
188
- return virtual({
189
- "#nitro-internal-virtual/routing": () => {
190
- const allHandlers = uniqueBy([
191
- ...Object.values(nitro.routing.routes.routes).flatMap((h) => h.data),
192
- ...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data),
193
- ...nitro.routing.globalMiddleware
194
- ], "_importHash");
195
- return `
196
- import * as __routeRules__ from "nitro/~internal/runtime/route-rules";
197
- import * as srvxNode from "srvx/node"
198
- import * as h3 from "h3";
199
-
200
- export const findRouteRules = ${nitro.routing.routeRules.compileToString({
201
- serialize: serializeRouteRule,
202
- matchAll: true
203
- })}
204
-
205
- const multiHandler = (...handlers) => {
206
- const final = handlers.pop()
207
- const middleware = handlers.filter(Boolean).map(h => h3.toMiddleware(h));
208
- return (ev) => h3.callMiddleware(ev, middleware, final);
209
- }
210
-
211
- ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "${h.handler}";`).join("\n")}
212
-
213
- ${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")}
214
-
215
- export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
216
-
217
- export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({
218
- serialize: serializeHandler,
219
- matchAll: true
220
- })};
221
-
222
- export const globalMiddleware = [
223
- ${nitro.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `h3.toEventHandler(${h._importHash})`).join(",")}
224
- ].filter(Boolean);
225
- `;
226
- },
227
- "#nitro-internal-virtual/routing-meta": () => {
228
- const routeHandlers = uniqueBy(Object.values(nitro.routing.routes.routes).flatMap((h) => h.data), "_importHash");
229
- return `
230
- ${routeHandlers.map((h) => `import ${h._importHash}Meta from "${h.handler}?meta";`).join("\n")}
231
- export const handlersMeta = [
232
- ${routeHandlers.map((h) => `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(h.method?.toLowerCase())}, meta: ${h._importHash}Meta }`).join(",\n")}
233
- ];
234
- `.trim();
235
- }
236
- }, nitro.vfs);
237
- }
238
- function uniqueBy(arr, key) {
239
- return [...new Map(arr.map((item) => [item[key], item])).values()];
240
- }
241
- function serializeHandler(h) {
242
- const meta = Array.isArray(h) ? h[0] : h;
243
- return `{${[
244
- `route:${JSON.stringify(meta.route)}`,
245
- meta.method && `method:${JSON.stringify(meta.method)}`,
246
- meta.meta && `meta:${JSON.stringify(meta.meta)}`,
247
- `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
248
- ].filter(Boolean).join(",")}}`;
249
- }
250
- function serializeHandlerFn(h) {
251
- let code = h._importHash;
252
- if (!h.lazy) {
253
- if (h.format === "node") code = `srvxNode.toFetchHandler(${code})`;
254
- code = `h3.toEventHandler(${code})`;
255
- }
256
- return code;
257
- }
258
- function serializeRouteRule(h) {
259
- return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => {
260
- return `{${[
261
- `name:${JSON.stringify(name)}`,
262
- `route:${JSON.stringify(h._route)}`,
263
- h._method && `method:${JSON.stringify(h._method)}`,
264
- RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`,
265
- `options:${JSON.stringify(options)}`
266
- ].filter(Boolean).join(",")}}`;
267
- }).join(",")}]`;
268
- }
269
17
 
270
18
  //#endregion
271
- //#region src/build/plugins/route-meta.ts
272
- const virtualPrefix = "\0nitro-handler-meta:";
273
- const esbuildLoaders = {
274
- ".ts": "ts",
275
- ".js": "js",
276
- ".tsx": "tsx",
277
- ".jsx": "jsx"
278
- };
279
- function routeMeta(nitro) {
19
+ //#region src/build/info.ts
20
+ const NITRO_WELLKNOWN_DIR = "node_modules/.nitro";
21
+ async function getBuildInfo(root) {
22
+ const outputDir = await findLastBuildDir(root);
23
+ if (!await stat(outputDir).then((s) => s.isDirectory()).catch(() => false)) return {};
280
24
  return {
281
- name: "nitro:route-meta",
282
- async resolveId(id, importer, resolveOpts) {
283
- if (id.startsWith("\0")) return;
284
- if (id.endsWith(`?meta`)) {
285
- const resolved = await this.resolve(id.replace(`?meta`, ``), importer, resolveOpts);
286
- if (!resolved) return;
287
- return virtualPrefix + resolved.id;
288
- }
289
- },
290
- load(id) {
291
- if (id.startsWith(virtualPrefix)) return readFile(id.slice(20), { encoding: "utf8" });
292
- },
293
- async transform(code, id) {
294
- if (!id.startsWith(virtualPrefix)) return;
295
- let meta = null;
296
- try {
297
- const jsCode = await transform(code, { loader: esbuildLoaders[extname(id)] }).then((r) => r.code);
298
- const ast = this.parse(jsCode);
299
- 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) {
300
- meta = astToObject(node.expression.arguments[0]);
301
- break;
302
- }
303
- } catch (error) {
304
- nitro.logger.warn(`[handlers-meta] Cannot extra route meta for: ${id}: ${error}`);
305
- }
306
- return {
307
- code: `export default ${JSON.stringify(meta)};`,
308
- map: null
309
- };
310
- }
25
+ outputDir,
26
+ buildInfo: await readFile(resolve$1(outputDir, "nitro.json"), "utf8").then(JSON.parse).catch(() => void 0)
311
27
  };
312
28
  }
313
- function astToObject(node) {
314
- switch (node.type) {
315
- case "ObjectExpression": {
316
- const obj = {};
317
- for (const prop of node.properties) if (prop.type === "Property") {
318
- const key = prop.key.name ?? prop.key.value;
319
- obj[key] = astToObject(prop.value);
320
- }
321
- return obj;
322
- }
323
- case "ArrayExpression": return node.elements.map((el) => astToObject(el)).filter(Boolean);
324
- case "Literal": return node.value;
325
- }
326
- }
327
-
328
- //#endregion
329
- //#region src/build/plugins/server-main.ts
330
- function serverMain(nitro) {
331
- return {
332
- name: "nitro:server-main",
333
- renderChunk(code, chunk) {
334
- if (chunk.isEntry) return {
335
- code: `globalThis.__nitro_main__ = import.meta.url; ${code}`,
336
- map: null
337
- };
338
- }
339
- };
29
+ async function findLastBuildDir(root) {
30
+ const lastBuildLink = join$1(root, NITRO_WELLKNOWN_DIR, "last-build.json");
31
+ return await readFile(lastBuildLink, "utf8").then(JSON.parse).then((data) => resolve$1(lastBuildLink, data.outputDir || "../../../.output")).catch(() => resolve$1(root, ".output"));
340
32
  }
341
-
342
- //#endregion
343
- //#region src/build/plugins/public-assets.ts
344
- var import_etag$1 = /* @__PURE__ */ __toESM(require_etag(), 1);
345
- const readAssetHandler = {
346
- true: "node",
347
- node: "node",
348
- false: "null",
349
- deno: "deno",
350
- inline: "inline"
351
- };
352
- function publicAssets(nitro) {
353
- return virtual({
354
- "#nitro-internal-virtual/public-assets-data": async () => {
355
- const assets = {};
356
- const files = await glob("**", {
357
- cwd: nitro.options.output.publicDir,
358
- absolute: false,
359
- dot: true
360
- });
361
- for (const id of files) {
362
- let mimeType = src_default.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
363
- if (mimeType.startsWith("text")) mimeType += "; charset=utf-8";
364
- const fullPath = resolve(nitro.options.output.publicDir, id);
365
- const assetData = await promises.readFile(fullPath);
366
- const etag = (0, import_etag$1.default)(assetData);
367
- const stat$1 = await promises.stat(fullPath);
368
- const assetId = joinURL(nitro.options.baseURL, decodeURIComponent(id));
369
- let encoding;
370
- if (id.endsWith(".gz")) encoding = "gzip";
371
- else if (id.endsWith(".br")) encoding = "br";
372
- assets[assetId] = {
373
- type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType,
374
- encoding,
375
- etag,
376
- mtime: stat$1.mtime.toJSON(),
377
- size: stat$1.size,
378
- path: relative(nitro.options.output.serverDir, fullPath),
379
- data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
380
- };
381
- }
382
- return `export default ${JSON.stringify(assets, null, 2)};`;
383
- },
384
- "#nitro-internal-virtual/public-assets-node": () => {
385
- return `
386
- import { promises as fsp } from 'node:fs'
387
- import { fileURLToPath } from 'node:url'
388
- import { resolve, dirname } from 'node:path'
389
- import assets from '#nitro-internal-virtual/public-assets-data'
390
- export function readAsset (id) {
391
- const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__))
392
- return fsp.readFile(resolve(serverDir, assets[id].path))
393
- }`;
394
- },
395
- "#nitro-internal-virtual/public-assets-deno": () => {
396
- return `
397
- import assets from '#nitro-internal-virtual/public-assets-data'
398
- export function readAsset (id) {
399
- // https://deno.com/deploy/docs/serve-static-assets
400
- const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
401
- return Deno.readFile(path);
402
- }`;
403
- },
404
- "#nitro-internal-virtual/public-assets-null": () => {
405
- return `
406
- export function readAsset (id) {
407
- return Promise.resolve(null);
408
- }`;
409
- },
410
- "#nitro-internal-virtual/public-assets-inline": () => {
411
- return `
412
- import assets from '#nitro-internal-virtual/public-assets-data'
413
- export function readAsset (id) {
414
- if (!assets[id]) { return undefined }
415
- if (assets[id]._data) { return assets[id]._data }
416
- if (!assets[id].data) { return assets[id].data }
417
- assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
418
- return assets[id]._data
419
- }`;
33
+ async function writeBuildInfo(nitro) {
34
+ const buildInfoPath = resolve$1(nitro.options.output.dir, "nitro.json");
35
+ const buildInfo = {
36
+ date: (/* @__PURE__ */ new Date()).toJSON(),
37
+ preset: nitro.options.preset,
38
+ framework: nitro.options.framework,
39
+ versions: { nitro: version },
40
+ commands: {
41
+ preview: nitro.options.commands.preview,
42
+ deploy: nitro.options.commands.deploy
420
43
  },
421
- "#nitro-internal-virtual/public-assets": () => {
422
- 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 }]));
423
- return `
424
- import assets from '#nitro-internal-virtual/public-assets-data'
425
- export { readAsset } from "${`#nitro-internal-virtual/public-assets-${readAssetHandler[nitro.options.serveStatic] || "null"}`}"
426
- export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
427
-
428
- export function isPublicAssetURL(id = '') {
429
- if (assets[id]) {
430
- return true
431
- }
432
- for (const base in publicAssetBases) {
433
- if (id.startsWith(base)) { return true }
434
- }
435
- return false
436
- }
437
-
438
- export function getPublicAssetMeta(id = '') {
439
- for (const base in publicAssetBases) {
440
- if (id.startsWith(base)) { return publicAssetBases[base] }
441
- }
442
- return {}
443
- }
444
-
445
- export function getAsset (id) {
446
- return assets[id]
447
- }
448
- `;
449
- }
450
- }, nitro.vfs);
451
- }
452
-
453
- //#endregion
454
- //#region src/build/plugins/server-assets.ts
455
- var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
456
- function serverAssets(nitro) {
457
- if (nitro.options.dev || nitro.options.preset === "nitro-prerender") return virtual({ "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) }, nitro.vfs);
458
- return virtual({ "#nitro-internal-virtual/server-assets": async () => {
459
- const assets = {};
460
- for (const asset of nitro.options.serverAssets) {
461
- const files = await glob(asset.pattern || "**/*", {
462
- cwd: asset.dir,
463
- absolute: false,
464
- ignore: asset.ignore
465
- });
466
- for (const _id of files) {
467
- const fsPath = resolve(asset.dir, _id);
468
- const id = asset.baseName + "/" + _id;
469
- assets[id] = {
470
- fsPath,
471
- meta: {}
472
- };
473
- let type = src_default.getType(id) || "text/plain";
474
- if (type.startsWith("text")) type += "; charset=utf-8";
475
- const etag = (0, import_etag.default)(await promises.readFile(fsPath));
476
- const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
477
- assets[id].meta = {
478
- type,
479
- etag,
480
- mtime
481
- };
482
- }
483
- }
484
- return getAssetProd(assets);
485
- } }, nitro.vfs);
486
- }
487
- function getAssetsDev(nitro) {
488
- return `
489
- import { createStorage } from 'unstorage'
490
- import fsDriver from 'unstorage/drivers/fs'
491
-
492
- const serverAssets = ${JSON.stringify(nitro.options.serverAssets)}
493
-
494
- export const assets = createStorage()
495
-
496
- for (const asset of serverAssets) {
497
- assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
498
- }`;
499
- }
500
- function getAssetProd(assets) {
501
- return `
502
- 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}
503
-
504
- const normalizeKey = ${normalizeKey.toString()}
505
-
506
- export const assets = {
507
- getKeys() {
508
- return Promise.resolve(Object.keys(_assets))
509
- },
510
- hasItem (id) {
511
- id = normalizeKey(id)
512
- return Promise.resolve(id in _assets)
513
- },
514
- getItem (id) {
515
- id = normalizeKey(id)
516
- return Promise.resolve(_assets[id] ? _assets[id].import() : null)
517
- },
518
- getMeta (id) {
519
- id = normalizeKey(id)
520
- return Promise.resolve(_assets[id] ? _assets[id].meta : {})
521
- }
522
- }
523
- `;
524
- }
525
-
526
- //#endregion
527
- //#region src/build/plugins/storage.ts
528
- function storage(nitro) {
529
- const mounts = [];
530
- const storageMounts = nitro.options.dev || nitro.options.preset === "nitro-prerender" ? {
531
- ...nitro.options.storage,
532
- ...nitro.options.devStorage
533
- } : nitro.options.storage;
534
- for (const path in storageMounts) {
535
- const mount = storageMounts[path];
536
- mounts.push({
537
- path,
538
- driver: builtinDrivers[mount.driver] || mount.driver,
539
- opts: mount
540
- });
541
- }
542
- const driverImports = [...new Set(mounts.map((m) => m.driver))];
543
- return virtual({ "#nitro-internal-virtual/storage": `
544
- import { createStorage } from 'unstorage'
545
- import { assets } from '#nitro-internal-virtual/server-assets'
546
-
547
- ${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
548
-
549
- export function initStorage() {
550
- const storage = createStorage({})
551
- storage.mount('/assets', assets)
552
- ${mounts.map((m) => `storage.mount('${m.path}', ${genSafeVariableName(m.driver)}(${JSON.stringify(m.opts)}))`).join("\n")}
553
- return storage
554
- }
555
- ` }, nitro.vfs);
556
- }
557
-
558
- //#endregion
559
- //#region src/build/plugins/error-handler.ts
560
- function errorHandler(nitro) {
561
- return virtual({ "#nitro-internal-virtual/error-handler": () => {
562
- const errorHandlers = Array.isArray(nitro.options.errorHandler) ? nitro.options.errorHandler : [nitro.options.errorHandler];
563
- const builtinHandler = join(runtimeDir, `internal/error/${nitro.options.dev ? "dev" : "prod"}`);
564
- return `
565
- ${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")}
566
-
567
- const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}];
568
-
569
- import { defaultHandler } from "${builtinHandler}";
570
-
571
- export default async function(error, event) {
572
- for (const handler of errorHandlers) {
573
- try {
574
- const response = await handler(error, event, { defaultHandler });
575
- if (response) {
576
- return response;
577
- }
578
- } catch(error) {
579
- // Handler itself thrown, log and continue
580
- console.error(error);
581
- }
582
- }
583
- // H3 will handle fallback
584
- }
585
- `;
586
- } }, nitro.vfs);
587
- }
588
-
589
- //#endregion
590
- //#region src/build/plugins/renderer-template.ts
591
- function rendererTemplate(nitro) {
592
- return virtual({ "#nitro-internal-virtual/renderer-template": async () => {
593
- if (typeof nitro.options.renderer?.template !== "string") return `export const rendererTemplate = () => '<!-- renderer.template is not set -->'; export const rendererTemplateFile = undefined;`;
594
- if (nitro.options.dev) return `import { readFile } from 'node:fs/promises';export const rendererTemplate = () => readFile(${JSON.stringify(nitro.options.renderer?.template)}, "utf8"); export const rendererTemplateFile = ${JSON.stringify(nitro.options.renderer?.template)};`;
595
- else {
596
- const html = await readFile(nitro.options.renderer?.template, "utf8");
597
- if (hasTemplateSyntax(html)) return `
598
- import { renderToResponse } from 'rendu'
599
- import { serverFetch } from 'nitro/app'
600
- const template = ${compileTemplateToString(html, { contextKeys: [...RENDER_CONTEXT_KEYS] })};
601
- export const rendererTemplate = (request) => renderToResponse(template, { request, context: { serverFetch } })
602
- `;
603
- else return `
604
- import { HTTPResponse } from "h3";
605
- export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } });
606
- `;
607
- }
608
- } }, nitro.vfs);
609
- }
610
-
611
- //#endregion
612
- //#region src/build/plugins/feature-flags.ts
613
- function featureFlags(nitro) {
614
- return virtual({ "#nitro-internal-virtual/feature-flags": () => {
615
- const featureFlags$1 = {
616
- hasRoutes: nitro.routing.routes.hasRoutes(),
617
- hasRouteRules: nitro.routing.routeRules.hasRoutes(),
618
- hasRoutedMiddleware: nitro.routing.routedMiddleware.hasRoutes(),
619
- hasGlobalMiddleware: nitro.routing.globalMiddleware.length > 0,
620
- hasPlugins: nitro.options.plugins.length > 0,
621
- hasHooks: nitro.options.features?.runtimeHooks ?? nitro.options.plugins.length > 0
622
- };
623
- return Object.entries(featureFlags$1).map(([key, value]) => `export const ${key} = ${Boolean(value)};`).join("\n");
624
- } }, nitro.vfs);
625
- }
626
-
627
- //#endregion
628
- //#region src/build/plugins/resolve.ts
629
- const subpathMap = {
630
- "nitro/h3": "h3",
631
- "nitro/deps/h3": "h3",
632
- "nitro/deps/ofetch": "ofetch"
633
- };
634
- function nitroResolveIds() {
635
- return {
636
- name: "nitro:resolve-ids",
637
- resolveId: {
638
- order: "pre",
639
- handler(id, importer, rOpts) {
640
- if (importer && importer.startsWith("\0virtual:#nitro-internal-virtual")) return this.resolve(id, runtimeDir, { skipSelf: true });
641
- const mappedId = subpathMap[id];
642
- if (mappedId) return this.resolve(mappedId, runtimeDir, { skipSelf: true });
643
- }
44
+ config: { ...Object.fromEntries(presetsWithConfig.map((key) => [key, nitro.options[key]])) }
45
+ };
46
+ await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2), true);
47
+ const lastBuild = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "last-build.json");
48
+ await mkdir(dirname(lastBuild), { recursive: true });
49
+ await writeFile$1(lastBuild, JSON.stringify({ outputDir: relative$1(lastBuild, nitro.options.output.dir) }));
50
+ return buildInfo;
51
+ }
52
+ async function writeDevBuildInfo(nitro, addr) {
53
+ const buildInfoPath = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "nitro.dev.json");
54
+ const buildInfo = {
55
+ date: (/* @__PURE__ */ new Date()).toJSON(),
56
+ preset: nitro.options.preset,
57
+ framework: nitro.options.framework,
58
+ versions: { nitro: version },
59
+ dev: {
60
+ pid: process.pid,
61
+ workerAddress: addr
644
62
  }
645
63
  };
64
+ await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2));
646
65
  }
647
66
 
648
67
  //#endregion
649
- //#region src/build/plugins.ts
650
- function baseBuildPlugins(nitro, base) {
651
- const plugins = [];
652
- if (nitro.options.imports) plugins.push(unplugin.rollup(nitro.options.imports));
653
- if (nitro.options.experimental.wasm) plugins.push(rollup(nitro.options.wasm || {}));
654
- plugins.push(serverMain(nitro));
655
- const nitroPlugins = [...new Set(nitro.options.plugins)];
656
- plugins.push(virtual({ "#nitro-internal-virtual/plugins": `
657
- ${nitroPlugins.map((plugin) => `import _${hash(plugin).replace(/-/g, "")} from '${plugin}';`).join("\n")}
658
-
659
- export const plugins = [
660
- ${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")}
661
- ]
662
- ` }, nitro.vfs));
663
- plugins.push(featureFlags(nitro));
664
- plugins.push(nitroResolveIds());
665
- plugins.push(serverAssets(nitro));
666
- plugins.push(publicAssets(nitro));
667
- plugins.push(storage(nitro));
668
- plugins.push(database(nitro));
669
- plugins.push(routing(nitro));
670
- if (nitro.options.experimental.openAPI) plugins.push(routeMeta(nitro));
671
- plugins.push(errorHandler(nitro));
672
- plugins.push(virtual({ "#nitro-internal-pollyfills": base.env.polyfill.map((p) => `import '${p}';`).join("\n") || `/* No polyfills */` }, nitro.vfs, { moduleSideEffects: true }));
673
- plugins.push(virtual(nitro.options.virtual, nitro.vfs));
674
- if (nitro.options.renderer?.template) plugins.push(rendererTemplate(nitro));
675
- if (!nitro.options.noExternals) plugins.push(rollupNodeFileTrace(defu(nitro.options.externals, {
676
- outDir: nitro.options.output.serverDir,
677
- moduleDirectories: nitro.options.nodeModulesDirs,
678
- external: nitro.options.nodeModulesDirs,
679
- inline: [
680
- "#",
681
- "~",
682
- "@/",
683
- "~~",
684
- "@@/",
685
- "virtual:",
686
- "nitro",
687
- pkgDir,
688
- nitro.options.serverDir,
689
- dirname(nitro.options.entry),
690
- ...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [],
691
- ...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"),
692
- ...nitro.options.dev || nitro.options.preset === "nitro-prerender" ? [] : runtimeDependencies
693
- ].filter(Boolean),
694
- traceOptions: {
695
- base: "/",
696
- processCwd: nitro.options.rootDir,
697
- exportsOnly: true
698
- },
699
- traceAlias: {
700
- "h3-nightly": "h3",
701
- ...nitro.options.externals?.traceAlias
702
- },
703
- exportConditions: nitro.options.exportConditions,
704
- writePackageJson: true
705
- })));
706
- return plugins;
707
- }
708
-
709
- //#endregion
710
- export { baseBuildConfig as n, replace$1 as r, baseBuildPlugins as t };
68
+ export { writeBuildInfo as n, writeDevBuildInfo as r, getBuildInfo as t };