nitro-nightly 3.0.1-20260119-145349-d0c4950f → 3.0.1-20260120-020848-6786d069
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.
- package/dist/_build/rolldown.mjs +13 -8
- package/dist/_build/vite.build.mjs +1 -1
- package/dist/_chunks/dev.mjs +5 -3
- package/dist/_chunks/nitro.mjs +24 -1183
- package/dist/_chunks/nitro2.mjs +248 -91
- package/dist/_chunks/nitro3.mjs +2696 -0
- package/dist/_chunks/nitro4.mjs +176 -0
- package/dist/_chunks/nitro5.mjs +733 -0
- package/dist/_chunks/nitro6.mjs +1458 -0
- package/dist/_chunks/nitro7.mjs +7561 -0
- package/dist/_chunks/nitro8.mjs +3524 -0
- package/dist/_chunks/nitro9.mjs +1729 -0
- package/dist/_libs/_.mjs +3 -0
- package/dist/_libs/_2.mjs +3 -0
- package/dist/_libs/_3.mjs +4 -0
- package/dist/_libs/_4.mjs +6 -0
- package/dist/_libs/_5.mjs +3 -0
- package/dist/_libs/_6.mjs +3 -0
- package/dist/_libs/acorn+confbox+js-tokens+magic-string+mlly+pkg-types+sourcemap-codec+strip-literal+unimport.mjs +8900 -0
- package/dist/_libs/{c12.mjs → c12+dotenv+rc9.mjs} +12 -105
- package/dist/_libs/{chokidar.mjs → chokidar+readdirp.mjs} +2 -9
- package/dist/_libs/confbox+exsolve+pkg-types.mjs +1249 -0
- package/dist/_libs/confbox.mjs +70 -2488
- package/dist/_libs/confbox2.mjs +786 -0
- package/dist/_libs/confbox3.mjs +404 -0
- package/dist/_libs/confbox4.mjs +3 -0
- package/dist/_libs/estree-walker+unimport.mjs +378 -0
- package/dist/_libs/fdir+picomatch+tinyglobby.mjs +2471 -0
- package/dist/_libs/gen-mapping+remapping+resolve-uri+trace-mapping+unimport+unplugin+unplugin-utils+webpack-virtual-modules.mjs +2150 -0
- package/dist/_libs/giget+node-fetch-native.mjs +2692 -0
- package/dist/_libs/httpxy.mjs +1 -6
- package/dist/_libs/local-pkg+quansync+unimport.mjs +1526 -0
- package/dist/_libs/nypm+tinyexec.mjs +858 -0
- package/dist/_libs/pathe.mjs +164 -0
- package/dist/_libs/perfect-debounce.mjs +89 -0
- package/dist/_libs/{@rollup/plugin-inject.mjs → plugin-alias+plugin-inject.mjs} +65 -2
- package/dist/_libs/std-env.mjs +158 -0
- package/dist/_libs/unimport.mjs +5 -1781
- package/dist/_libs/vite-plugin-fullstack.mjs +26 -0
- package/dist/_presets.mjs +8 -3
- package/dist/builder.mjs +8 -6
- package/dist/cli/_chunks/build.mjs +1 -1
- package/dist/cli/_chunks/dev.mjs +3 -2
- package/dist/cli/_chunks/list.mjs +1 -1
- package/dist/cli/_chunks/prepare.mjs +1 -1
- package/dist/cli/_chunks/run.mjs +1 -1
- package/dist/cli/index.mjs +1 -1
- package/dist/types/index.d.mts +2410 -1174
- package/dist/vite.d.mts +13 -13
- package/dist/vite.mjs +640 -16
- package/package.json +9 -9
- package/dist/_build/common.mjs +0 -24931
- package/dist/_build/rollup.mjs +0 -201
- package/dist/_chunks/utils.mjs +0 -254
- package/dist/_common.mjs +0 -45
- package/dist/_libs/@hiogawa/vite-plugin-fullstack.mjs +0 -652
- package/dist/_libs/@jridgewell/gen-mapping.mjs +0 -448
- package/dist/_libs/@jridgewell/remapping.mjs +0 -117
- package/dist/_libs/@rollup/plugin-alias.mjs +0 -64
- package/dist/_libs/@rollup/plugin-commonjs.mjs +0 -1300
- package/dist/_libs/@rollup/plugin-json.mjs +0 -36
- package/dist/_libs/@rollup/plugin-node-resolve.mjs +0 -1972
- package/dist/_libs/escape-string-regexp.mjs +0 -8
- package/dist/_libs/estree-walker.mjs +0 -187
- package/dist/_libs/giget.mjs +0 -3550
- package/dist/_libs/klona.mjs +0 -38
- package/dist/_libs/rou3.mjs +0 -322
- package/dist/_libs/tsconfck.mjs +0 -832
- package/dist/_libs/ultrahtml.mjs +0 -138
- package/dist/cli/_chunks/task.mjs +0 -16
package/dist/_chunks/nitro.mjs
CHANGED
|
@@ -1,1191 +1,32 @@
|
|
|
1
|
-
import { Dt as resolveModulePath, Ft as relative, It as resolve, Nt as join, Ot as resolveModuleURL, ct as resolveNitroPath, et as scanUnprefixedPublicAssets, ft as a, lt as writeFile$1, nt as src_default, p as runParallel, pt as d, rt as build, st as prettyPath, tt as compressPublicAssets, vt as findWorkspaceDir } from "../_build/common.mjs";
|
|
2
|
-
import { o as watchConfig, r as loadConfig } from "../_libs/c12.mjs";
|
|
3
|
-
import { n as resolveCompatibilityDates, r as resolveCompatibilityDatesFromEnv } from "../_libs/compatx.mjs";
|
|
4
|
-
import { t as klona } from "../_libs/klona.mjs";
|
|
5
|
-
import { t as escapeStringRegexp } from "../_libs/escape-string-regexp.mjs";
|
|
6
|
-
import { n as parse, t as TSConfckCache } from "../_libs/tsconfck.mjs";
|
|
7
|
-
import { n as scanHandlers, t as scanAndSyncOptions } from "./nitro2.mjs";
|
|
8
|
-
import { a as findRoute, i as findAllRoutes, n as addRoute, r as createRouter, t as compileRouterToString } from "../_libs/rou3.mjs";
|
|
9
|
-
import { n as z, t as P } from "../_libs/ultrahtml.mjs";
|
|
10
1
|
import { createRequire } from "node:module";
|
|
11
|
-
import consola$1, { consola } from "consola";
|
|
12
|
-
import { Hookable, createDebugger } from "hookable";
|
|
13
|
-
import { existsSync } from "node:fs";
|
|
14
|
-
import { readFile } from "node:fs/promises";
|
|
15
|
-
import { pathToFileURL } from "node:url";
|
|
16
|
-
import { defu } from "defu";
|
|
17
|
-
import { joinURL, parseURL, withBase, withLeadingSlash, withQuery, withTrailingSlash, withoutBase, withoutTrailingSlash } from "ufo";
|
|
18
|
-
import { runtimeDir } from "nitro/meta";
|
|
19
|
-
import { colors } from "consola/utils";
|
|
20
|
-
import { hash } from "ohash";
|
|
21
|
-
import http from "node:http";
|
|
22
|
-
import { toRequest } from "h3";
|
|
23
2
|
|
|
24
|
-
//#region
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
features: {},
|
|
42
|
-
experimental: {},
|
|
43
|
-
future: {},
|
|
44
|
-
storage: {},
|
|
45
|
-
devStorage: {},
|
|
46
|
-
publicAssets: [],
|
|
47
|
-
serverAssets: [],
|
|
48
|
-
plugins: [],
|
|
49
|
-
tasks: {},
|
|
50
|
-
scheduledTasks: {},
|
|
51
|
-
imports: false,
|
|
52
|
-
virtual: {},
|
|
53
|
-
compressPublicAssets: false,
|
|
54
|
-
ignore: [],
|
|
55
|
-
wasm: {},
|
|
56
|
-
dev: false,
|
|
57
|
-
devServer: { watch: [] },
|
|
58
|
-
watchOptions: { ignoreInitial: true },
|
|
59
|
-
devProxy: {},
|
|
60
|
-
logging: {
|
|
61
|
-
compressedSizes: true,
|
|
62
|
-
buildSuccess: true
|
|
63
|
-
},
|
|
64
|
-
baseURL: process.env.NITRO_APP_BASE_URL || "/",
|
|
65
|
-
handlers: [],
|
|
66
|
-
devHandlers: [],
|
|
67
|
-
errorHandler: void 0,
|
|
68
|
-
routes: {},
|
|
69
|
-
routeRules: {},
|
|
70
|
-
prerender: {
|
|
71
|
-
autoSubfolderIndex: true,
|
|
72
|
-
concurrency: 1,
|
|
73
|
-
interval: 0,
|
|
74
|
-
retry: 3,
|
|
75
|
-
retryDelay: 500,
|
|
76
|
-
failOnError: false,
|
|
77
|
-
crawlLinks: false,
|
|
78
|
-
ignore: [],
|
|
79
|
-
routes: []
|
|
80
|
-
},
|
|
81
|
-
builder: void 0,
|
|
82
|
-
moduleSideEffects: ["unenv/polyfill/"],
|
|
83
|
-
replace: {},
|
|
84
|
-
node: true,
|
|
85
|
-
sourcemap: false,
|
|
86
|
-
traceDeps: [],
|
|
87
|
-
typescript: {
|
|
88
|
-
strict: true,
|
|
89
|
-
generateRuntimeConfigTypes: false,
|
|
90
|
-
generateTsConfig: false,
|
|
91
|
-
tsconfigPath: "tsconfig.json",
|
|
92
|
-
tsConfig: void 0
|
|
93
|
-
},
|
|
94
|
-
hooks: {},
|
|
95
|
-
commands: {},
|
|
96
|
-
framework: {
|
|
97
|
-
name: "nitro",
|
|
98
|
-
version: ""
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/config/resolvers/assets.ts
|
|
104
|
-
async function resolveAssetsOptions(options) {
|
|
105
|
-
for (const publicAsset of options.publicAssets) {
|
|
106
|
-
publicAsset.dir = resolve(options.rootDir, publicAsset.dir);
|
|
107
|
-
publicAsset.baseURL = withLeadingSlash(withoutTrailingSlash(publicAsset.baseURL || "/"));
|
|
108
|
-
}
|
|
109
|
-
for (const dir of [options.rootDir, ...options.scanDirs]) {
|
|
110
|
-
const publicDir = resolve(dir, "public");
|
|
111
|
-
if (!existsSync(publicDir)) continue;
|
|
112
|
-
if (options.publicAssets.some((asset) => asset.dir === publicDir)) continue;
|
|
113
|
-
options.publicAssets.push({ dir: publicDir });
|
|
114
|
-
}
|
|
115
|
-
for (const serverAsset of options.serverAssets) serverAsset.dir = resolve(options.rootDir, serverAsset.dir);
|
|
116
|
-
options.serverAssets.push({
|
|
117
|
-
baseName: "server",
|
|
118
|
-
dir: resolve(options.rootDir, "assets")
|
|
119
|
-
});
|
|
120
|
-
for (const asset of options.publicAssets) {
|
|
121
|
-
asset.baseURL = asset.baseURL || "/";
|
|
122
|
-
const isTopLevel = asset.baseURL === "/";
|
|
123
|
-
asset.fallthrough = asset.fallthrough ?? isTopLevel;
|
|
124
|
-
const routeRule = options.routeRules[asset.baseURL + "/**"];
|
|
125
|
-
asset.maxAge = (routeRule?.cache)?.maxAge ?? asset.maxAge ?? 0;
|
|
126
|
-
if (asset.maxAge && !asset.fallthrough) options.routeRules[asset.baseURL + "/**"] = defu(routeRule, { headers: { "cache-control": `public, max-age=${asset.maxAge}, immutable` } });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/config/resolvers/compatibility.ts
|
|
132
|
-
async function resolveCompatibilityOptions(options) {
|
|
133
|
-
options.compatibilityDate = resolveCompatibilityDatesFromEnv(options.compatibilityDate);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
//#endregion
|
|
137
|
-
//#region src/config/resolvers/database.ts
|
|
138
|
-
async function resolveDatabaseOptions(options) {
|
|
139
|
-
if (options.experimental.database && options.imports) {
|
|
140
|
-
options.imports.presets ??= [];
|
|
141
|
-
options.imports.presets.push({
|
|
142
|
-
from: "nitro/database",
|
|
143
|
-
imports: ["useDatabase"]
|
|
144
|
-
});
|
|
145
|
-
if (options.dev && !options.database && !options.devDatabase) options.devDatabase = { default: {
|
|
146
|
-
connector: "sqlite",
|
|
147
|
-
options: { cwd: options.rootDir }
|
|
148
|
-
} };
|
|
149
|
-
else if (options.node && !options.database) options.database = { default: {
|
|
150
|
-
connector: "sqlite",
|
|
151
|
-
options: {}
|
|
152
|
-
} };
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
//#endregion
|
|
157
|
-
//#region src/config/resolvers/export-conditions.ts
|
|
158
|
-
async function resolveExportConditionsOptions(options) {
|
|
159
|
-
options.exportConditions = _resolveExportConditions(options.exportConditions || [], {
|
|
160
|
-
dev: options.dev,
|
|
161
|
-
node: options.node,
|
|
162
|
-
wasm: options.wasm !== false
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
function _resolveExportConditions(conditions, opts) {
|
|
166
|
-
const resolvedConditions = [];
|
|
167
|
-
resolvedConditions.push(opts.dev ? "development" : "production");
|
|
168
|
-
resolvedConditions.push(...conditions);
|
|
169
|
-
if (opts.node) resolvedConditions.push("node");
|
|
170
|
-
else resolvedConditions.push("wintercg", "worker", "web", "browser", "workerd", "edge-light", "netlify", "edge-routine", "deno");
|
|
171
|
-
if (opts.wasm) resolvedConditions.push("wasm", "unwasm");
|
|
172
|
-
resolvedConditions.push("import", "default", "module");
|
|
173
|
-
if ("Bun" in globalThis) resolvedConditions.push("bun");
|
|
174
|
-
else if ("Deno" in globalThis) resolvedConditions.push("deno");
|
|
175
|
-
return resolvedConditions.filter((c, i) => resolvedConditions.indexOf(c) === i);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
//#endregion
|
|
179
|
-
//#region src/config/resolvers/imports.ts
|
|
180
|
-
async function resolveImportsOptions(options) {
|
|
181
|
-
if (options.imports === false) return;
|
|
182
|
-
options.imports.presets ??= [];
|
|
183
|
-
options.imports.dirs ??= [];
|
|
184
|
-
options.imports.dirs.push(...options.scanDirs.map((dir) => join(dir, "utils/**/*")));
|
|
185
|
-
if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) {
|
|
186
|
-
options.imports.exclude.push(/[/\\]\.git[/\\]/);
|
|
187
|
-
options.imports.exclude.push(options.buildDir);
|
|
188
|
-
const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean);
|
|
189
|
-
options.imports.exclude.push(scanDirsInNodeModules.length > 0 ? /* @__PURE__ */ new RegExp(`node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeStringRegexp(dir)).join("|")})`) : /[/\\]node_modules[/\\]/);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
//#endregion
|
|
194
|
-
//#region src/config/resolvers/open-api.ts
|
|
195
|
-
async function resolveOpenAPIOptions(options) {
|
|
196
|
-
if (!options.experimental.openAPI) return;
|
|
197
|
-
if (!options.dev && !options.openAPI?.production) return;
|
|
198
|
-
const shouldPrerender = !options.dev && options.openAPI?.production === "prerender";
|
|
199
|
-
const handlersEnv = shouldPrerender ? "prerender" : "";
|
|
200
|
-
const prerenderRoutes = [];
|
|
201
|
-
const jsonRoute = options.openAPI?.route || "/_openapi.json";
|
|
202
|
-
prerenderRoutes.push(jsonRoute);
|
|
203
|
-
options.handlers.push({
|
|
204
|
-
route: jsonRoute,
|
|
205
|
-
env: handlersEnv,
|
|
206
|
-
handler: join(runtimeDir, "internal/routes/openapi")
|
|
207
|
-
});
|
|
208
|
-
if (options.openAPI?.ui?.scalar !== false) {
|
|
209
|
-
const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar";
|
|
210
|
-
prerenderRoutes.push(scalarRoute);
|
|
211
|
-
options.handlers.push({
|
|
212
|
-
route: options.openAPI?.ui?.scalar?.route || "/_scalar",
|
|
213
|
-
env: handlersEnv,
|
|
214
|
-
handler: join(runtimeDir, "internal/routes/scalar")
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
if (options.openAPI?.ui?.swagger !== false) {
|
|
218
|
-
const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger";
|
|
219
|
-
prerenderRoutes.push(swaggerRoute);
|
|
220
|
-
options.handlers.push({
|
|
221
|
-
route: swaggerRoute,
|
|
222
|
-
env: handlersEnv,
|
|
223
|
-
handler: join(runtimeDir, "internal/routes/swagger")
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
if (shouldPrerender) {
|
|
227
|
-
options.prerender ??= {};
|
|
228
|
-
options.prerender.routes ??= [];
|
|
229
|
-
options.prerender.routes.push(...prerenderRoutes);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
//#endregion
|
|
234
|
-
//#region src/config/resolvers/tsconfig.ts
|
|
235
|
-
async function resolveTsconfig(options) {
|
|
236
|
-
const root = resolve(options.rootDir || ".") + "/";
|
|
237
|
-
if (!options.typescript.tsConfig) options.typescript.tsConfig = await loadTsconfig(root);
|
|
238
|
-
if (options.experimental.tsconfigPaths && options.typescript.tsConfig.compilerOptions?.paths) options.alias = {
|
|
239
|
-
...tsConfigToAliasObj(options.typescript.tsConfig, root),
|
|
240
|
-
...options.alias
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
async function loadTsconfig(root) {
|
|
244
|
-
const opts = {
|
|
245
|
-
root,
|
|
246
|
-
cache: loadTsconfig["__cache"] ??= new TSConfckCache(),
|
|
247
|
-
ignoreNodeModules: true
|
|
248
|
-
};
|
|
249
|
-
const tsConfigPath = join(root, "tsconfig.json");
|
|
250
|
-
const parsed = await parse(tsConfigPath, opts).catch(() => void 0);
|
|
251
|
-
if (!parsed) return {};
|
|
252
|
-
const { tsconfig, tsconfigFile } = parsed;
|
|
253
|
-
tsconfig.compilerOptions ??= {};
|
|
254
|
-
if (!tsconfig.compilerOptions.baseUrl) tsconfig.compilerOptions.baseUrl = resolve(tsconfigFile, "..");
|
|
255
|
-
return tsconfig;
|
|
256
|
-
}
|
|
257
|
-
function tsConfigToAliasObj(tsconfig, root) {
|
|
258
|
-
const compilerOptions = tsconfig?.compilerOptions;
|
|
259
|
-
if (!compilerOptions?.paths) return {};
|
|
260
|
-
const paths = compilerOptions.paths;
|
|
261
|
-
const alias = {};
|
|
262
|
-
for (const [key, targets] of Object.entries(paths)) {
|
|
263
|
-
let source = key;
|
|
264
|
-
let target = targets?.[0];
|
|
265
|
-
if (!target) continue;
|
|
266
|
-
if (source.includes("*") || target.includes("*")) {
|
|
267
|
-
source = source.replace(/\/\*$/, "");
|
|
268
|
-
target = target.replace(/\/\*$/, "");
|
|
269
|
-
if (source.includes("*") || target.includes("*")) continue;
|
|
270
|
-
}
|
|
271
|
-
if (target.startsWith(".")) {
|
|
272
|
-
if (!compilerOptions.baseUrl) continue;
|
|
273
|
-
target = resolve(root, compilerOptions.baseUrl, target) + (key.endsWith("*") ? "/" : "");
|
|
274
|
-
}
|
|
275
|
-
alias[source] = target;
|
|
276
|
-
}
|
|
277
|
-
return alias;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
//#endregion
|
|
281
|
-
//#region src/config/resolvers/paths.ts
|
|
282
|
-
const RESOLVE_EXTENSIONS = [
|
|
283
|
-
".ts",
|
|
284
|
-
".js",
|
|
285
|
-
".mts",
|
|
286
|
-
".mjs",
|
|
287
|
-
".tsx",
|
|
288
|
-
".jsx"
|
|
289
|
-
];
|
|
290
|
-
async function resolvePathOptions(options) {
|
|
291
|
-
options.rootDir = resolve(options.rootDir || ".") + "/";
|
|
292
|
-
options.buildDir = resolve(options.rootDir, options.buildDir || ".") + "/";
|
|
293
|
-
options.workspaceDir ||= await findWorkspaceDir(options.rootDir).catch(() => options.rootDir) + "/";
|
|
294
|
-
if (options.srcDir) {
|
|
295
|
-
if (options.serverDir === void 0) options.serverDir = options.srcDir;
|
|
296
|
-
consola$1.warn(`"srcDir" option is deprecated. Please use "serverDir" instead.`);
|
|
297
|
-
}
|
|
298
|
-
if (options.serverDir !== false) {
|
|
299
|
-
if (options.serverDir === true) options.serverDir = "server";
|
|
300
|
-
options.serverDir = resolve(options.rootDir, options.serverDir || ".") + "/";
|
|
301
|
-
}
|
|
302
|
-
options.alias ??= {};
|
|
303
|
-
if (!options.static && !options.entry) throw new Error(`Nitro entry is missing! Is "${options.preset}" preset correct?`);
|
|
304
|
-
if (options.entry) options.entry = resolveNitroPath(options.entry, options);
|
|
305
|
-
options.output.dir = resolveNitroPath(options.output.dir || NitroDefaults.output.dir, options, options.rootDir) + "/";
|
|
306
|
-
options.output.publicDir = resolveNitroPath(options.output.publicDir || NitroDefaults.output.publicDir, options, options.rootDir) + "/";
|
|
307
|
-
options.output.serverDir = resolveNitroPath(options.output.serverDir || NitroDefaults.output.serverDir, options, options.rootDir) + "/";
|
|
308
|
-
options.plugins = options.plugins.map((p) => resolveNitroPath(p, options));
|
|
309
|
-
if (options.serverDir) options.scanDirs.unshift(options.serverDir);
|
|
310
|
-
options.scanDirs = options.scanDirs.map((dir) => resolve(options.rootDir, dir));
|
|
311
|
-
options.scanDirs = [...new Set(options.scanDirs.map((dir) => dir + "/"))];
|
|
312
|
-
options.handlers = options.handlers.map((h) => {
|
|
313
|
-
return {
|
|
314
|
-
...h,
|
|
315
|
-
handler: resolveNitroPath(h.handler, options)
|
|
316
|
-
};
|
|
317
|
-
});
|
|
318
|
-
options.routes = Object.fromEntries(Object.entries(options.routes).map(([route, h]) => {
|
|
319
|
-
if (typeof h === "string") h = { handler: h };
|
|
320
|
-
h.handler = resolveNitroPath(h.handler, options);
|
|
321
|
-
return [route, h];
|
|
322
|
-
}));
|
|
323
|
-
if (options.serverEntry !== false) {
|
|
324
|
-
if (typeof options?.serverEntry === "string") options.serverEntry = { handler: options.serverEntry };
|
|
325
|
-
if (options.serverEntry?.handler) options.serverEntry.handler = resolveNitroPath(options.serverEntry.handler, options);
|
|
326
|
-
else {
|
|
327
|
-
const detected = resolveModulePath("./server", {
|
|
328
|
-
try: true,
|
|
329
|
-
from: options.rootDir,
|
|
330
|
-
extensions: RESOLVE_EXTENSIONS.flatMap((ext) => [ext, `.node${ext}`])
|
|
331
|
-
});
|
|
332
|
-
if (detected) {
|
|
333
|
-
options.serverEntry ??= { handler: "" };
|
|
334
|
-
options.serverEntry.handler = detected;
|
|
335
|
-
consola$1.info(`Detected \`${prettyPath(detected)}\` as server entry.`);
|
|
3
|
+
//#region rolldown:runtime
|
|
4
|
+
var __create = Object.create;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
7
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
9
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
10
|
+
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
14
|
+
key = keys[i];
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
16
|
+
__defProp(to, key, {
|
|
17
|
+
get: ((k) => from[k]).bind(null, key),
|
|
18
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
19
|
+
});
|
|
336
20
|
}
|
|
337
21
|
}
|
|
338
|
-
if (options.serverEntry?.handler && !options.serverEntry?.format) {
|
|
339
|
-
const isNode = /\.(node)\.\w+$/.test(options.serverEntry.handler);
|
|
340
|
-
options.serverEntry.format = isNode ? "node" : "web";
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
if (options.renderer === false) options.renderer = void 0;
|
|
344
|
-
else {
|
|
345
|
-
if (options.renderer?.handler) options.renderer.handler = resolveModulePath(resolveNitroPath(options.renderer?.handler, options), {
|
|
346
|
-
from: [options.rootDir, ...options.scanDirs],
|
|
347
|
-
extensions: RESOLVE_EXTENSIONS
|
|
348
|
-
});
|
|
349
|
-
if (options.renderer?.template) options.renderer.template = resolveModulePath(resolveNitroPath(options.renderer?.template, options), {
|
|
350
|
-
from: [options.rootDir, ...options.scanDirs],
|
|
351
|
-
extensions: [".html"]
|
|
352
|
-
});
|
|
353
|
-
else if (!options.renderer?.handler) {
|
|
354
|
-
const defaultIndex = resolveModulePath("./index.html", {
|
|
355
|
-
from: [options.rootDir, ...options.scanDirs],
|
|
356
|
-
extensions: [".html"],
|
|
357
|
-
try: true
|
|
358
|
-
});
|
|
359
|
-
if (defaultIndex) {
|
|
360
|
-
options.renderer ??= {};
|
|
361
|
-
options.renderer.template = defaultIndex;
|
|
362
|
-
consola$1.info(`Using \`${prettyPath(defaultIndex)}\` as renderer template.`);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
if (options.renderer?.template && !options.renderer?.handler) {
|
|
366
|
-
options.renderer ??= {};
|
|
367
|
-
options.renderer.handler = join(runtimeDir, "internal/routes/renderer-template" + (options.dev ? ".dev" : ""));
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
//#endregion
|
|
373
|
-
//#region src/config/resolvers/route-rules.ts
|
|
374
|
-
async function resolveRouteRulesOptions(options) {
|
|
375
|
-
options.routeRules = normalizeRouteRules(options);
|
|
376
|
-
}
|
|
377
|
-
function normalizeRouteRules(config) {
|
|
378
|
-
const normalizedRules = {};
|
|
379
|
-
for (let path in config.routeRules) {
|
|
380
|
-
const routeConfig = config.routeRules[path];
|
|
381
|
-
path = withLeadingSlash(path);
|
|
382
|
-
const routeRules = {
|
|
383
|
-
...routeConfig,
|
|
384
|
-
redirect: void 0,
|
|
385
|
-
proxy: void 0
|
|
386
|
-
};
|
|
387
|
-
if (routeConfig.redirect) {
|
|
388
|
-
routeRules.redirect = {
|
|
389
|
-
to: "/",
|
|
390
|
-
status: 307,
|
|
391
|
-
...typeof routeConfig.redirect === "string" ? { to: routeConfig.redirect } : routeConfig.redirect
|
|
392
|
-
};
|
|
393
|
-
if (path.endsWith("/**")) routeRules.redirect._redirectStripBase = path.slice(0, -3);
|
|
394
|
-
}
|
|
395
|
-
if (routeConfig.proxy) {
|
|
396
|
-
routeRules.proxy = typeof routeConfig.proxy === "string" ? { to: routeConfig.proxy } : routeConfig.proxy;
|
|
397
|
-
if (path.endsWith("/**")) routeRules.proxy._proxyStripBase = path.slice(0, -3);
|
|
398
|
-
}
|
|
399
|
-
if (routeConfig.cors) routeRules.headers = {
|
|
400
|
-
"access-control-allow-origin": "*",
|
|
401
|
-
"access-control-allow-methods": "*",
|
|
402
|
-
"access-control-allow-headers": "*",
|
|
403
|
-
"access-control-max-age": "0",
|
|
404
|
-
...routeRules.headers
|
|
405
|
-
};
|
|
406
|
-
if (routeConfig.swr) {
|
|
407
|
-
routeRules.cache = routeRules.cache || {};
|
|
408
|
-
routeRules.cache.swr = true;
|
|
409
|
-
if (typeof routeConfig.swr === "number") routeRules.cache.maxAge = routeConfig.swr;
|
|
410
|
-
}
|
|
411
|
-
if (routeConfig.cache === false) routeRules.cache = false;
|
|
412
|
-
normalizedRules[path] = routeRules;
|
|
413
|
-
}
|
|
414
|
-
return normalizedRules;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
//#endregion
|
|
418
|
-
//#region src/config/resolvers/runtime-config.ts
|
|
419
|
-
async function resolveRuntimeConfigOptions(options) {
|
|
420
|
-
options.runtimeConfig = normalizeRuntimeConfig(options);
|
|
421
|
-
}
|
|
422
|
-
function normalizeRuntimeConfig(config) {
|
|
423
|
-
provideFallbackValues(config.runtimeConfig || {});
|
|
424
|
-
const runtimeConfig = defu(config.runtimeConfig, {
|
|
425
|
-
app: { baseURL: config.baseURL },
|
|
426
|
-
nitro: {
|
|
427
|
-
envExpansion: config.experimental?.envExpansion,
|
|
428
|
-
openAPI: config.openAPI
|
|
429
|
-
}
|
|
430
|
-
});
|
|
431
|
-
runtimeConfig.nitro ??= {};
|
|
432
|
-
runtimeConfig.nitro.routeRules = config.routeRules;
|
|
433
|
-
checkSerializableRuntimeConfig(runtimeConfig);
|
|
434
|
-
return runtimeConfig;
|
|
435
|
-
}
|
|
436
|
-
function provideFallbackValues(obj) {
|
|
437
|
-
for (const key in obj) if (obj[key] === void 0 || obj[key] === null) obj[key] = "";
|
|
438
|
-
else if (typeof obj[key] === "object") provideFallbackValues(obj[key]);
|
|
439
|
-
}
|
|
440
|
-
function checkSerializableRuntimeConfig(obj, path = []) {
|
|
441
|
-
if (isPrimitiveValue(obj)) return;
|
|
442
|
-
for (const key in obj) {
|
|
443
|
-
const value = obj[key];
|
|
444
|
-
if (value === null || value === void 0 || isPrimitiveValue(value)) continue;
|
|
445
|
-
if (Array.isArray(value)) for (const [index, item] of value.entries()) checkSerializableRuntimeConfig(item, [...path, `${key}[${index}]`]);
|
|
446
|
-
else if (typeof value === "object" && value.constructor === Object && (!value.constructor?.name || value.constructor.name === "Object")) checkSerializableRuntimeConfig(value, [...path, key]);
|
|
447
|
-
else console.warn(`Runtime config option \`${[...path, key].join(".")}\` may not be able to be serialized.`);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
function isPrimitiveValue(value) {
|
|
451
|
-
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
//#endregion
|
|
455
|
-
//#region src/config/resolvers/storage.ts
|
|
456
|
-
async function resolveStorageOptions(options) {}
|
|
457
|
-
|
|
458
|
-
//#endregion
|
|
459
|
-
//#region src/config/resolvers/url.ts
|
|
460
|
-
async function resolveURLOptions(options) {
|
|
461
|
-
options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL));
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
//#endregion
|
|
465
|
-
//#region src/config/resolvers/error.ts
|
|
466
|
-
async function resolveErrorOptions(options) {
|
|
467
|
-
if (!options.errorHandler) options.errorHandler = [];
|
|
468
|
-
else if (!Array.isArray(options.errorHandler)) options.errorHandler = [options.errorHandler];
|
|
469
|
-
options.errorHandler = options.errorHandler.map((h) => resolveNitroPath(h, options));
|
|
470
|
-
options.errorHandler.push(join(runtimeDir, `internal/error/${options.dev ? "dev" : "prod"}`));
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
//#endregion
|
|
474
|
-
//#region src/config/resolvers/unenv.ts
|
|
475
|
-
const common = {
|
|
476
|
-
meta: {
|
|
477
|
-
name: "nitro-common",
|
|
478
|
-
url: import.meta.url
|
|
479
|
-
},
|
|
480
|
-
alias: {
|
|
481
|
-
"buffer/": "node:buffer",
|
|
482
|
-
"buffer/index": "node:buffer",
|
|
483
|
-
"buffer/index.js": "node:buffer",
|
|
484
|
-
"string_decoder/": "node:string_decoder",
|
|
485
|
-
"process/": "node:process"
|
|
486
22
|
}
|
|
23
|
+
return to;
|
|
487
24
|
};
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
inject: {
|
|
494
|
-
global: "unenv/polyfill/globalthis",
|
|
495
|
-
process: "node:process",
|
|
496
|
-
Buffer: ["node:buffer", "Buffer"],
|
|
497
|
-
clearImmediate: ["node:timers", "clearImmediate"],
|
|
498
|
-
setImmediate: ["node:timers", "setImmediate"],
|
|
499
|
-
performance: "unenv/polyfill/performance",
|
|
500
|
-
PerformanceObserver: ["node:perf_hooks", "PerformanceObserver"],
|
|
501
|
-
BroadcastChannel: ["node:worker_threads", "BroadcastChannel"]
|
|
502
|
-
},
|
|
503
|
-
polyfill: [
|
|
504
|
-
"unenv/polyfill/globalthis-global",
|
|
505
|
-
"unenv/polyfill/process",
|
|
506
|
-
"unenv/polyfill/buffer",
|
|
507
|
-
"unenv/polyfill/timers"
|
|
508
|
-
]
|
|
509
|
-
};
|
|
510
|
-
async function resolveUnenv(options) {
|
|
511
|
-
options.unenv ??= [];
|
|
512
|
-
if (!Array.isArray(options.unenv)) options.unenv = [options.unenv];
|
|
513
|
-
options.unenv = options.unenv.filter(Boolean);
|
|
514
|
-
if (!options.node) options.unenv.unshift(nodeless);
|
|
515
|
-
options.unenv.unshift(common);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
//#endregion
|
|
519
|
-
//#region src/config/resolvers/builder.ts
|
|
520
|
-
const VALID_BUILDERS = [
|
|
521
|
-
"rolldown",
|
|
522
|
-
"rollup",
|
|
523
|
-
"vite"
|
|
524
|
-
];
|
|
525
|
-
async function resolveBuilder(options) {
|
|
526
|
-
options.builder ??= process.env.NITRO_BUILDER;
|
|
527
|
-
if (options.builder) {
|
|
528
|
-
if (!VALID_BUILDERS.includes(options.builder)) throw new Error(`Invalid nitro builder "${options.builder}". Valid builders are: ${VALID_BUILDERS.join(", ")}.`);
|
|
529
|
-
const pkg = options.builder;
|
|
530
|
-
if (!isPkgInstalled(pkg, options.rootDir)) {
|
|
531
|
-
if (!await consola$1.prompt(`Nitro builder package \`${pkg}\` is not installed. Would you like to install it?`, {
|
|
532
|
-
type: "confirm",
|
|
533
|
-
default: true,
|
|
534
|
-
cancel: "null"
|
|
535
|
-
})) throw new Error(`Nitro builder package "${options.builder}" is not installed. Please install it in your project dependencies.`);
|
|
536
|
-
await installPkg(pkg, options.rootDir);
|
|
537
|
-
}
|
|
538
|
-
return;
|
|
539
|
-
}
|
|
540
|
-
for (const pkg of [
|
|
541
|
-
"rolldown",
|
|
542
|
-
"rollup",
|
|
543
|
-
"vite"
|
|
544
|
-
]) if (isPkgInstalled(pkg, options.rootDir)) {
|
|
545
|
-
options.builder = pkg;
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
const pkgToInstall = await consola$1.prompt(`No nitro builder specified. Which builder would you like to install?`, {
|
|
549
|
-
type: "select",
|
|
550
|
-
cancel: "null",
|
|
551
|
-
options: VALID_BUILDERS.map((b) => ({
|
|
552
|
-
label: b,
|
|
553
|
-
value: b
|
|
554
|
-
}))
|
|
555
|
-
});
|
|
556
|
-
if (!pkgToInstall) throw new Error(`No nitro builder specified. Please install one of the following packages: ${VALID_BUILDERS.join(", ")} and set it as the builder in your nitro config or via the NITRO_BUILDER environment variable.`);
|
|
557
|
-
await installPkg(pkgToInstall, options.rootDir);
|
|
558
|
-
options.builder = pkgToInstall;
|
|
559
|
-
}
|
|
560
|
-
const require = createRequire(process.cwd() + "/_index.js");
|
|
561
|
-
function isPkgInstalled(pkg, root) {
|
|
562
|
-
try {
|
|
563
|
-
require.resolve(pkg, { paths: [root] });
|
|
564
|
-
return true;
|
|
565
|
-
} catch {
|
|
566
|
-
return false;
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
async function installPkg(pkg, root) {
|
|
570
|
-
const { addDevDependency } = await import("../_libs/giget.mjs").then((n) => n.i);
|
|
571
|
-
return addDevDependency(pkg, { cwd: root });
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
//#endregion
|
|
575
|
-
//#region src/config/loader.ts
|
|
576
|
-
const configResolvers = [
|
|
577
|
-
resolveCompatibilityOptions,
|
|
578
|
-
resolveTsconfig,
|
|
579
|
-
resolvePathOptions,
|
|
580
|
-
resolveImportsOptions,
|
|
581
|
-
resolveRouteRulesOptions,
|
|
582
|
-
resolveDatabaseOptions,
|
|
583
|
-
resolveExportConditionsOptions,
|
|
584
|
-
resolveRuntimeConfigOptions,
|
|
585
|
-
resolveOpenAPIOptions,
|
|
586
|
-
resolveURLOptions,
|
|
587
|
-
resolveAssetsOptions,
|
|
588
|
-
resolveStorageOptions,
|
|
589
|
-
resolveErrorOptions,
|
|
590
|
-
resolveUnenv,
|
|
591
|
-
resolveBuilder
|
|
592
|
-
];
|
|
593
|
-
async function loadOptions(configOverrides = {}, opts = {}) {
|
|
594
|
-
const options = await _loadUserConfig(configOverrides, opts);
|
|
595
|
-
for (const resolver of configResolvers) await resolver(options);
|
|
596
|
-
return options;
|
|
597
|
-
}
|
|
598
|
-
async function _loadUserConfig(configOverrides = {}, opts = {}) {
|
|
599
|
-
configOverrides = klona(configOverrides);
|
|
600
|
-
globalThis.defineNitroConfig = globalThis.defineNitroConfig || ((c) => c);
|
|
601
|
-
let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE;
|
|
602
|
-
const { resolvePreset } = await import("../_presets.mjs");
|
|
603
|
-
let preset = configOverrides.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET;
|
|
604
|
-
const _dotenv = opts.dotenv ?? (configOverrides.dev && { fileName: [".env", ".env.local"] });
|
|
605
|
-
const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({
|
|
606
|
-
name: "nitro",
|
|
607
|
-
cwd: configOverrides.rootDir,
|
|
608
|
-
dotenv: _dotenv,
|
|
609
|
-
extend: { extendKey: ["extends", "preset"] },
|
|
610
|
-
defaults: NitroDefaults,
|
|
611
|
-
jitiOptions: { alias: {
|
|
612
|
-
nitropack: "nitro/config",
|
|
613
|
-
"nitro/config": "nitro/config"
|
|
614
|
-
} },
|
|
615
|
-
async overrides({ rawConfigs }) {
|
|
616
|
-
const getConf = (key) => configOverrides[key] ?? rawConfigs.main?.[key] ?? rawConfigs.rc?.[key] ?? rawConfigs.packageJson?.[key];
|
|
617
|
-
if (!compatibilityDate) compatibilityDate = getConf("compatibilityDate");
|
|
618
|
-
const framework = getConf("framework");
|
|
619
|
-
const isCustomFramework = framework?.name && framework.name !== "nitro";
|
|
620
|
-
if (!preset) preset = getConf("preset");
|
|
621
|
-
if (configOverrides.dev) preset = preset && preset !== "nitro-dev" ? await resolvePreset(preset, {
|
|
622
|
-
static: getConf("static"),
|
|
623
|
-
dev: true,
|
|
624
|
-
compatibilityDate: compatibilityDate || "latest"
|
|
625
|
-
}).then((p) => p?._meta?.name || "nitro-dev").catch(() => "nitro-dev") : "nitro-dev";
|
|
626
|
-
else if (!preset) preset = await resolvePreset("", {
|
|
627
|
-
static: getConf("static"),
|
|
628
|
-
dev: false,
|
|
629
|
-
compatibilityDate: compatibilityDate || "latest"
|
|
630
|
-
}).then((p) => p?._meta?.name);
|
|
631
|
-
return {
|
|
632
|
-
...configOverrides,
|
|
633
|
-
preset,
|
|
634
|
-
typescript: {
|
|
635
|
-
generateRuntimeConfigTypes: !isCustomFramework,
|
|
636
|
-
...getConf("typescript"),
|
|
637
|
-
...configOverrides.typescript
|
|
638
|
-
}
|
|
639
|
-
};
|
|
640
|
-
},
|
|
641
|
-
async resolve(id) {
|
|
642
|
-
const preset$1 = await resolvePreset(id, {
|
|
643
|
-
static: configOverrides.static,
|
|
644
|
-
compatibilityDate: compatibilityDate || "latest",
|
|
645
|
-
dev: configOverrides.dev
|
|
646
|
-
});
|
|
647
|
-
if (preset$1) return { config: klona(preset$1) };
|
|
648
|
-
},
|
|
649
|
-
...opts.c12
|
|
650
|
-
});
|
|
651
|
-
const options = klona(loadedConfig.config);
|
|
652
|
-
options._config = configOverrides;
|
|
653
|
-
options._c12 = loadedConfig;
|
|
654
|
-
options.preset = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || preset;
|
|
655
|
-
options.compatibilityDate = resolveCompatibilityDates(compatibilityDate, options.compatibilityDate);
|
|
656
|
-
if (options.dev && options.preset !== "nitro-dev") consola$1.info(`Using \`${options.preset}\` emulation in development mode.`);
|
|
657
|
-
return options;
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
//#endregion
|
|
661
|
-
//#region src/config/update.ts
|
|
662
|
-
async function updateNitroConfig(nitro, config) {
|
|
663
|
-
nitro.options.routeRules = normalizeRouteRules(config.routeRules ? config : nitro.options);
|
|
664
|
-
nitro.options.runtimeConfig = normalizeRuntimeConfig(config.runtimeConfig ? config : nitro.options);
|
|
665
|
-
await nitro.hooks.callHook("rollup:reload");
|
|
666
|
-
consola$1.success("Nitro config hot reloaded!");
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
//#endregion
|
|
670
|
-
//#region src/module.ts
|
|
671
|
-
async function installModules(nitro) {
|
|
672
|
-
const _modules = [...nitro.options.modules || []];
|
|
673
|
-
const modules = await Promise.all(_modules.map((mod) => _resolveNitroModule(mod, nitro.options)));
|
|
674
|
-
const _installedURLs = /* @__PURE__ */ new Set();
|
|
675
|
-
for (const mod of modules) {
|
|
676
|
-
if (mod._url) {
|
|
677
|
-
if (_installedURLs.has(mod._url)) continue;
|
|
678
|
-
_installedURLs.add(mod._url);
|
|
679
|
-
}
|
|
680
|
-
await mod.setup(nitro);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
async function _resolveNitroModule(mod, nitroOptions) {
|
|
684
|
-
let _url;
|
|
685
|
-
if (typeof mod === "string") mod = await import(resolveModuleURL(mod, {
|
|
686
|
-
from: [nitroOptions.rootDir],
|
|
687
|
-
extensions: [
|
|
688
|
-
".mjs",
|
|
689
|
-
".cjs",
|
|
690
|
-
".js",
|
|
691
|
-
".mts",
|
|
692
|
-
".cts",
|
|
693
|
-
".ts"
|
|
694
|
-
]
|
|
695
|
-
})).then((m) => m.default || m);
|
|
696
|
-
if (typeof mod === "function") mod = { setup: mod };
|
|
697
|
-
if ("nitro" in mod) mod = mod.nitro;
|
|
698
|
-
if (!mod.setup) throw new Error("Invalid Nitro module: missing setup() function.");
|
|
699
|
-
return {
|
|
700
|
-
_url,
|
|
701
|
-
...mod
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
//#endregion
|
|
706
|
-
//#region src/routing.ts
|
|
707
|
-
const isGlobalMiddleware = (h) => !h.method && (!h.route || h.route === "/**");
|
|
708
|
-
function initNitroRouting(nitro) {
|
|
709
|
-
const envConditions = new Set([
|
|
710
|
-
nitro.options.dev ? "dev" : "prod",
|
|
711
|
-
nitro.options.preset,
|
|
712
|
-
nitro.options.preset === "nitro-prerender" ? "prerender" : void 0
|
|
713
|
-
].filter(Boolean));
|
|
714
|
-
const matchesEnv = (h) => {
|
|
715
|
-
const envs = (Array.isArray(h.env) ? h.env : [h.env]).filter(Boolean);
|
|
716
|
-
return envs.length === 0 || envs.some((env) => envConditions.has(env));
|
|
717
|
-
};
|
|
718
|
-
const routes = new Router(nitro.options.baseURL);
|
|
719
|
-
const routeRules = new Router(nitro.options.baseURL);
|
|
720
|
-
const globalMiddleware = [];
|
|
721
|
-
const routedMiddleware = new Router(nitro.options.baseURL);
|
|
722
|
-
const sync = () => {
|
|
723
|
-
routeRules._update(Object.entries(nitro.options.routeRules).map(([route, data]) => ({
|
|
724
|
-
route,
|
|
725
|
-
method: "",
|
|
726
|
-
data: {
|
|
727
|
-
...data,
|
|
728
|
-
_route: route
|
|
729
|
-
}
|
|
730
|
-
})));
|
|
731
|
-
const _routes = [
|
|
732
|
-
...Object.entries(nitro.options.routes).flatMap(([route, handler]) => {
|
|
733
|
-
if (typeof handler === "string") handler = { handler };
|
|
734
|
-
return {
|
|
735
|
-
...handler,
|
|
736
|
-
route,
|
|
737
|
-
middleware: false
|
|
738
|
-
};
|
|
739
|
-
}),
|
|
740
|
-
...nitro.options.handlers,
|
|
741
|
-
...nitro.scannedHandlers
|
|
742
|
-
].filter((h) => h && !h.middleware && matchesEnv(h));
|
|
743
|
-
if (nitro.options.serverEntry && nitro.options.serverEntry.handler) _routes.push({
|
|
744
|
-
route: "/**",
|
|
745
|
-
lazy: false,
|
|
746
|
-
format: nitro.options.serverEntry.format,
|
|
747
|
-
handler: nitro.options.serverEntry.handler
|
|
748
|
-
});
|
|
749
|
-
if (nitro.options.renderer?.handler) _routes.push({
|
|
750
|
-
route: "/**",
|
|
751
|
-
lazy: true,
|
|
752
|
-
handler: nitro.options.renderer?.handler
|
|
753
|
-
});
|
|
754
|
-
routes._update(_routes.map((h) => ({
|
|
755
|
-
...h,
|
|
756
|
-
method: h.method || "",
|
|
757
|
-
data: handlerWithImportHash(h)
|
|
758
|
-
})), { merge: true });
|
|
759
|
-
const _middleware = [...nitro.scannedHandlers, ...nitro.options.handlers].filter((h) => h && h.middleware && matchesEnv(h));
|
|
760
|
-
if (nitro.options.serveStatic) _middleware.unshift({
|
|
761
|
-
route: "/**",
|
|
762
|
-
middleware: true,
|
|
763
|
-
handler: join(runtimeDir, "internal/static")
|
|
764
|
-
});
|
|
765
|
-
globalMiddleware.splice(0, globalMiddleware.length, ..._middleware.filter((h) => isGlobalMiddleware(h)).map((m) => handlerWithImportHash(m)));
|
|
766
|
-
routedMiddleware._update(_middleware.filter((h) => !isGlobalMiddleware(h)).map((h) => ({
|
|
767
|
-
...h,
|
|
768
|
-
method: h.method || "",
|
|
769
|
-
data: handlerWithImportHash(h)
|
|
770
|
-
})));
|
|
771
|
-
};
|
|
772
|
-
nitro.routing = Object.freeze({
|
|
773
|
-
sync,
|
|
774
|
-
routes,
|
|
775
|
-
routeRules,
|
|
776
|
-
globalMiddleware,
|
|
777
|
-
routedMiddleware
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
function handlerWithImportHash(h) {
|
|
781
|
-
const id = (h.lazy ? "_lazy_" : "_") + hash(h.handler).replace(/-/g, "").slice(0, 6);
|
|
782
|
-
return {
|
|
783
|
-
...h,
|
|
784
|
-
_importHash: id
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
var Router = class {
|
|
788
|
-
_routes;
|
|
789
|
-
_router;
|
|
790
|
-
_compiled;
|
|
791
|
-
_baseURL;
|
|
792
|
-
constructor(baseURL) {
|
|
793
|
-
this._update([]);
|
|
794
|
-
this._baseURL = baseURL || "";
|
|
795
|
-
if (this._baseURL.endsWith("/")) this._baseURL = this._baseURL.slice(0, -1);
|
|
796
|
-
}
|
|
797
|
-
get routes() {
|
|
798
|
-
return this._routes;
|
|
799
|
-
}
|
|
800
|
-
_update(routes, opts) {
|
|
801
|
-
this._routes = routes;
|
|
802
|
-
this._router = createRouter();
|
|
803
|
-
this._compiled = void 0;
|
|
804
|
-
for (const route of routes) addRoute(this._router, route.method, this._baseURL + route.route, route.data);
|
|
805
|
-
if (opts?.merge) mergeCatchAll(this._router);
|
|
806
|
-
}
|
|
807
|
-
hasRoutes() {
|
|
808
|
-
return this._routes.length > 0;
|
|
809
|
-
}
|
|
810
|
-
compileToString(opts) {
|
|
811
|
-
const key = opts ? hash(opts) : "";
|
|
812
|
-
this._compiled ||= {};
|
|
813
|
-
if (this._compiled[key]) return this._compiled[key];
|
|
814
|
-
this._compiled[key] = compileRouterToString(this._router, void 0, opts);
|
|
815
|
-
if (this.routes.length === 1 && this.routes[0].route === "/**" && this.routes[0].method === "") {
|
|
816
|
-
const data = (opts?.serialize || JSON.stringify)(this.routes[0].data);
|
|
817
|
-
let retCode = `{data,params:{"_":p.slice(1)}}`;
|
|
818
|
-
if (opts?.matchAll) retCode = `[${retCode}]`;
|
|
819
|
-
this._compiled[key] = `/* @__PURE__ */ (() => {const data=${data};return ((_m, p)=>{return ${retCode};})})()`;
|
|
820
|
-
}
|
|
821
|
-
return this._compiled[key];
|
|
822
|
-
}
|
|
823
|
-
match(method, path) {
|
|
824
|
-
return findRoute(this._router, method, path)?.data;
|
|
825
|
-
}
|
|
826
|
-
matchAll(method, path) {
|
|
827
|
-
return findAllRoutes(this._router, method, path).map((route) => route.data);
|
|
828
|
-
}
|
|
829
|
-
};
|
|
830
|
-
function mergeCatchAll(router) {
|
|
831
|
-
const handlers = router.root?.wildcard?.methods?.[""];
|
|
832
|
-
if (!handlers || handlers.length < 2) return;
|
|
833
|
-
handlers.splice(0, handlers.length, {
|
|
834
|
-
...handlers[0],
|
|
835
|
-
data: handlers.map((h) => h.data)
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
//#endregion
|
|
840
|
-
//#region src/global.ts
|
|
841
|
-
const nitroInstances = globalThis.__nitro_instances__ ||= [];
|
|
842
|
-
const globalKey = "__nitro_builder__";
|
|
843
|
-
function registerNitroInstance(nitro) {
|
|
844
|
-
if (nitroInstances.includes(nitro)) return;
|
|
845
|
-
globalInit();
|
|
846
|
-
nitroInstances.unshift(nitro);
|
|
847
|
-
nitro.hooks.hookOnce("close", () => {
|
|
848
|
-
nitroInstances.splice(nitroInstances.indexOf(nitro), 1);
|
|
849
|
-
if (nitroInstances.length === 0) delete globalThis[globalKey];
|
|
850
|
-
});
|
|
851
|
-
}
|
|
852
|
-
function globalInit() {
|
|
853
|
-
if (globalThis[globalKey]) return;
|
|
854
|
-
globalThis[globalKey] = { async fetch(req) {
|
|
855
|
-
for (let r = 0; r < 10 && nitroInstances.length === 0; r++) await new Promise((resolve$1) => setTimeout(resolve$1, 300));
|
|
856
|
-
const nitro = nitroInstances[0];
|
|
857
|
-
if (!nitro) throw new Error("No Nitro instance is running.");
|
|
858
|
-
return nitro.fetch(req);
|
|
859
|
-
} };
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
//#endregion
|
|
863
|
-
//#region src/nitro.ts
|
|
864
|
-
async function createNitro(config = {}, opts = {}) {
|
|
865
|
-
const nitro = {
|
|
866
|
-
options: await loadOptions(config, opts),
|
|
867
|
-
hooks: new Hookable(),
|
|
868
|
-
vfs: /* @__PURE__ */ new Map(),
|
|
869
|
-
routing: {},
|
|
870
|
-
logger: consola.withTag("nitro"),
|
|
871
|
-
scannedHandlers: [],
|
|
872
|
-
fetch: () => {
|
|
873
|
-
throw new Error("no dev server attached!");
|
|
874
|
-
},
|
|
875
|
-
close: () => Promise.resolve(nitro.hooks.callHook("close")),
|
|
876
|
-
async updateConfig(config$1) {
|
|
877
|
-
updateNitroConfig(nitro, config$1);
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
registerNitroInstance(nitro);
|
|
881
|
-
initNitroRouting(nitro);
|
|
882
|
-
await scanAndSyncOptions(nitro);
|
|
883
|
-
if (nitro.options.debug) createDebugger(nitro.hooks, { tag: "nitro" });
|
|
884
|
-
if (nitro.options.logLevel !== void 0) nitro.logger.level = nitro.options.logLevel;
|
|
885
|
-
nitro.hooks.addHooks(nitro.options.hooks);
|
|
886
|
-
await installModules(nitro);
|
|
887
|
-
if (nitro.options.imports) {
|
|
888
|
-
const { createUnimport } = await import("../_build/common.mjs").then((n) => n.v);
|
|
889
|
-
nitro.unimport = createUnimport(nitro.options.imports);
|
|
890
|
-
await nitro.unimport.init();
|
|
891
|
-
nitro.options.virtual["#imports"] = () => nitro.unimport?.toExports() || "";
|
|
892
|
-
nitro.options.virtual["#nitro"] = "export * from \"#imports\"";
|
|
893
|
-
}
|
|
894
|
-
await scanHandlers(nitro);
|
|
895
|
-
nitro.routing.sync();
|
|
896
|
-
return nitro;
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
//#endregion
|
|
900
|
-
//#region src/prerender/utils.ts
|
|
901
|
-
const allowedExtensions = new Set(["", ".json"]);
|
|
902
|
-
const linkParents = /* @__PURE__ */ new Map();
|
|
903
|
-
const HTML_ENTITIES = {
|
|
904
|
-
"<": "<",
|
|
905
|
-
">": ">",
|
|
906
|
-
"&": "&",
|
|
907
|
-
"'": "'",
|
|
908
|
-
""": "\""
|
|
909
|
-
};
|
|
910
|
-
function escapeHtml(text) {
|
|
911
|
-
return text.replace(/&(lt|gt|amp|apos|quot);/g, (ch) => HTML_ENTITIES[ch] || ch);
|
|
912
|
-
}
|
|
913
|
-
async function extractLinks(html, from, res, crawlLinks) {
|
|
914
|
-
const links = [];
|
|
915
|
-
const _links = [];
|
|
916
|
-
if (crawlLinks) await z(P(html), (node) => {
|
|
917
|
-
if (!node.attributes?.href) return;
|
|
918
|
-
const link = escapeHtml(node.attributes.href);
|
|
919
|
-
if (!decodeURIComponent(link).startsWith("#") && allowedExtensions.has(getExtension(link))) _links.push(link);
|
|
920
|
-
});
|
|
921
|
-
const header = res.headers.get("x-nitro-prerender") || "";
|
|
922
|
-
_links.push(...header.split(",").map((i) => decodeURIComponent(i.trim())));
|
|
923
|
-
for (const link of _links.filter(Boolean)) {
|
|
924
|
-
const _link = parseURL(link);
|
|
925
|
-
if (_link.protocol || _link.host) continue;
|
|
926
|
-
if (!_link.pathname.startsWith("/")) {
|
|
927
|
-
const fromURL = new URL(from, "http://localhost");
|
|
928
|
-
_link.pathname = new URL(_link.pathname, fromURL).pathname;
|
|
929
|
-
}
|
|
930
|
-
links.push(_link.pathname + _link.search);
|
|
931
|
-
}
|
|
932
|
-
for (const link of links) {
|
|
933
|
-
const _parents = linkParents.get(link);
|
|
934
|
-
if (_parents) _parents.add(from);
|
|
935
|
-
else linkParents.set(link, new Set([from]));
|
|
936
|
-
}
|
|
937
|
-
return links;
|
|
938
|
-
}
|
|
939
|
-
const EXT_REGEX = /\.[\da-z]+$/;
|
|
940
|
-
function getExtension(link) {
|
|
941
|
-
return (parseURL(link).pathname.match(EXT_REGEX) || [])[0] || "";
|
|
942
|
-
}
|
|
943
|
-
function formatPrerenderRoute(route) {
|
|
944
|
-
let str = ` ├─ ${route.route} (${route.generateTimeMS}ms)`;
|
|
945
|
-
if (route.error) {
|
|
946
|
-
const parents = linkParents.get(route.route);
|
|
947
|
-
const errorColor = colors[route.error.status === 404 ? "yellow" : "red"];
|
|
948
|
-
const errorLead = parents?.size ? "├──" : "└──";
|
|
949
|
-
str += `\n │ ${errorLead} ${errorColor(route.error.message)}`;
|
|
950
|
-
if (parents?.size) str += `\n${[...parents.values()].map((link) => ` │ └── Linked from ${link}`).join("\n")}`;
|
|
951
|
-
}
|
|
952
|
-
if (route.skip) str += colors.gray(" (skipped)");
|
|
953
|
-
return colors.gray(str);
|
|
954
|
-
}
|
|
955
|
-
function matchesIgnorePattern(path, pattern) {
|
|
956
|
-
if (typeof pattern === "string") return path.startsWith(pattern);
|
|
957
|
-
if (typeof pattern === "function") return pattern(path) === true;
|
|
958
|
-
if (pattern instanceof RegExp) return pattern.test(path);
|
|
959
|
-
return false;
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
//#endregion
|
|
963
|
-
//#region src/prerender/prerender.ts
|
|
964
|
-
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
|
|
965
|
-
async function prerender(nitro) {
|
|
966
|
-
if (nitro.options.noPublicDir) {
|
|
967
|
-
nitro.logger.warn("Skipping prerender since `noPublicDir` option is enabled.");
|
|
968
|
-
return;
|
|
969
|
-
}
|
|
970
|
-
if (nitro.options.builder === "vite") {
|
|
971
|
-
nitro.logger.warn("Skipping prerender since not supported with vite builder yet...");
|
|
972
|
-
return;
|
|
973
|
-
}
|
|
974
|
-
const routes = new Set(nitro.options.prerender.routes);
|
|
975
|
-
const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path$1, options]) => options.prerender && !path$1.includes("*")).map((e) => e[0]);
|
|
976
|
-
for (const route of prerenderRulePaths) routes.add(route);
|
|
977
|
-
await nitro.hooks.callHook("prerender:routes", routes);
|
|
978
|
-
if (routes.size === 0) if (nitro.options.prerender.crawlLinks) routes.add("/");
|
|
979
|
-
else return;
|
|
980
|
-
nitro.logger.info("Initializing prerenderer");
|
|
981
|
-
nitro._prerenderedRoutes = [];
|
|
982
|
-
nitro._prerenderMeta = nitro._prerenderMeta || {};
|
|
983
|
-
const prerendererConfig = {
|
|
984
|
-
...nitro.options._config,
|
|
985
|
-
static: false,
|
|
986
|
-
rootDir: nitro.options.rootDir,
|
|
987
|
-
logLevel: 0,
|
|
988
|
-
preset: "nitro-prerender"
|
|
989
|
-
};
|
|
990
|
-
await nitro.hooks.callHook("prerender:config", prerendererConfig);
|
|
991
|
-
const nitroRenderer = await createNitro(prerendererConfig);
|
|
992
|
-
const prerenderStartTime = Date.now();
|
|
993
|
-
await nitro.hooks.callHook("prerender:init", nitroRenderer);
|
|
994
|
-
let path = relative(nitro.options.output.dir, nitro.options.output.publicDir);
|
|
995
|
-
if (!path.startsWith(".")) path = `./${path}`;
|
|
996
|
-
nitroRenderer.options.commands.preview = `npx serve ${path}`;
|
|
997
|
-
nitroRenderer.options.output.dir = nitro.options.output.dir;
|
|
998
|
-
await build(nitroRenderer);
|
|
999
|
-
const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs";
|
|
1000
|
-
const prerenderer = await import(pathToFileURL(resolve(nitroRenderer.options.output.serverDir, serverFilename)).href).then((m) => m.default);
|
|
1001
|
-
const routeRules = createRouter();
|
|
1002
|
-
for (const [route, rules] of Object.entries(nitro.options.routeRules)) addRoute(routeRules, void 0, route, rules);
|
|
1003
|
-
const _getRouteRules = (path$1) => defu({}, ...findAllRoutes(routeRules, void 0, path$1).map((r) => r.data).reverse());
|
|
1004
|
-
const generatedRoutes = /* @__PURE__ */ new Set();
|
|
1005
|
-
const failedRoutes = /* @__PURE__ */ new Set();
|
|
1006
|
-
const skippedRoutes = /* @__PURE__ */ new Set();
|
|
1007
|
-
const displayedLengthWarns = /* @__PURE__ */ new Set();
|
|
1008
|
-
const publicAssetBases = nitro.options.publicAssets.filter((a$1) => !!a$1.baseURL && a$1.baseURL !== "/" && !a$1.fallthrough).map((a$1) => withTrailingSlash(a$1.baseURL));
|
|
1009
|
-
const scannedPublicAssets = nitro.options.prerender.ignoreUnprefixedPublicAssets ? new Set(await scanUnprefixedPublicAssets(nitro)) : /* @__PURE__ */ new Set();
|
|
1010
|
-
const canPrerender = (route = "/") => {
|
|
1011
|
-
if (generatedRoutes.has(route) || skippedRoutes.has(route)) return false;
|
|
1012
|
-
if (nitro.options.prerender.ignore) {
|
|
1013
|
-
for (const pattern of nitro.options.prerender.ignore) if (matchesIgnorePattern(route, pattern)) return false;
|
|
1014
|
-
}
|
|
1015
|
-
if (publicAssetBases.some((base) => route.startsWith(base))) return false;
|
|
1016
|
-
if (scannedPublicAssets.has(route)) return false;
|
|
1017
|
-
if (_getRouteRules(route).prerender === false) return false;
|
|
1018
|
-
return true;
|
|
1019
|
-
};
|
|
1020
|
-
const canWriteToDisk = (route) => {
|
|
1021
|
-
if (route.route.includes("?")) return false;
|
|
1022
|
-
const FS_MAX_SEGMENT = 255;
|
|
1023
|
-
const FS_MAX_PATH_PUBLIC_HTML = 1024 - (nitro.options.output.publicDir.length + 10);
|
|
1024
|
-
if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) {
|
|
1025
|
-
displayedLengthWarns.add(route);
|
|
1026
|
-
const _route = route.route.slice(0, 60) + "...";
|
|
1027
|
-
if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) nitro.logger.warn(`Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`);
|
|
1028
|
-
else {
|
|
1029
|
-
nitro.logger.warn(`Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`);
|
|
1030
|
-
return false;
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
return true;
|
|
1034
|
-
};
|
|
1035
|
-
const generateRoute = async (route) => {
|
|
1036
|
-
const start = Date.now();
|
|
1037
|
-
route = decodeURI(route);
|
|
1038
|
-
if (!canPrerender(route)) {
|
|
1039
|
-
skippedRoutes.add(route);
|
|
1040
|
-
return;
|
|
1041
|
-
}
|
|
1042
|
-
generatedRoutes.add(route);
|
|
1043
|
-
const _route = { route };
|
|
1044
|
-
const encodedRoute = encodeURI(route);
|
|
1045
|
-
const req = toRequest(withBase(encodedRoute, nitro.options.baseURL), { headers: [["x-nitro-prerender", encodedRoute]] });
|
|
1046
|
-
const res = await prerenderer.fetch(req);
|
|
1047
|
-
let dataBuff = Buffer.from(await res.arrayBuffer());
|
|
1048
|
-
Object.defineProperty(_route, "contents", {
|
|
1049
|
-
get: () => {
|
|
1050
|
-
return dataBuff ? dataBuff.toString("utf8") : void 0;
|
|
1051
|
-
},
|
|
1052
|
-
set(value) {
|
|
1053
|
-
if (dataBuff) dataBuff = Buffer.from(value);
|
|
1054
|
-
}
|
|
1055
|
-
});
|
|
1056
|
-
Object.defineProperty(_route, "data", {
|
|
1057
|
-
get: () => {
|
|
1058
|
-
return dataBuff ? dataBuff.buffer : void 0;
|
|
1059
|
-
},
|
|
1060
|
-
set(value) {
|
|
1061
|
-
if (dataBuff) dataBuff = Buffer.from(value);
|
|
1062
|
-
}
|
|
1063
|
-
});
|
|
1064
|
-
if (![200, ...[
|
|
1065
|
-
301,
|
|
1066
|
-
302,
|
|
1067
|
-
303,
|
|
1068
|
-
304,
|
|
1069
|
-
307,
|
|
1070
|
-
308
|
|
1071
|
-
]].includes(res.status)) {
|
|
1072
|
-
_route.error = /* @__PURE__ */ new Error(`[${res.status}] ${res.statusText}`);
|
|
1073
|
-
_route.error.status = res.status;
|
|
1074
|
-
_route.error.statusText = res.statusText;
|
|
1075
|
-
}
|
|
1076
|
-
_route.generateTimeMS = Date.now() - start;
|
|
1077
|
-
const contentType = res.headers.get("content-type") || "";
|
|
1078
|
-
const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8"));
|
|
1079
|
-
const routeWithIndex = route.endsWith("/") ? route + "index" : route;
|
|
1080
|
-
const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html";
|
|
1081
|
-
_route.fileName = withoutBase(isImplicitHTML ? htmlPath : routeWithIndex, nitro.options.baseURL);
|
|
1082
|
-
const inferredContentType = src_default.getType(_route.fileName) || "text/plain";
|
|
1083
|
-
_route.contentType = contentType || inferredContentType;
|
|
1084
|
-
await nitro.hooks.callHook("prerender:generate", _route, nitro);
|
|
1085
|
-
if (_route.contentType !== inferredContentType) {
|
|
1086
|
-
nitro._prerenderMeta[_route.fileName] ||= {};
|
|
1087
|
-
nitro._prerenderMeta[_route.fileName].contentType = _route.contentType;
|
|
1088
|
-
}
|
|
1089
|
-
if (_route.error) failedRoutes.add(_route);
|
|
1090
|
-
if (_route.skip || _route.error) {
|
|
1091
|
-
await nitro.hooks.callHook("prerender:route", _route);
|
|
1092
|
-
nitro.logger.log(formatPrerenderRoute(_route));
|
|
1093
|
-
dataBuff = void 0;
|
|
1094
|
-
return _route;
|
|
1095
|
-
}
|
|
1096
|
-
if (canWriteToDisk(_route)) {
|
|
1097
|
-
await writeFile$1(join(nitro.options.output.publicDir, _route.fileName), dataBuff);
|
|
1098
|
-
nitro._prerenderedRoutes.push(_route);
|
|
1099
|
-
} else _route.skip = true;
|
|
1100
|
-
if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) {
|
|
1101
|
-
const extractedLinks = await extractLinks(dataBuff.toString("utf8"), route, res, nitro.options.prerender.crawlLinks ?? false);
|
|
1102
|
-
for (const _link of extractedLinks) if (canPrerender(_link)) routes.add(_link);
|
|
1103
|
-
}
|
|
1104
|
-
await nitro.hooks.callHook("prerender:route", _route);
|
|
1105
|
-
nitro.logger.log(formatPrerenderRoute(_route));
|
|
1106
|
-
dataBuff = void 0;
|
|
1107
|
-
return _route;
|
|
1108
|
-
};
|
|
1109
|
-
nitro.logger.info(nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`);
|
|
1110
|
-
await runParallel(routes, generateRoute, {
|
|
1111
|
-
concurrency: nitro.options.prerender.concurrency || 1,
|
|
1112
|
-
interval: nitro.options.prerender.interval
|
|
1113
|
-
});
|
|
1114
|
-
await prerenderer.close();
|
|
1115
|
-
await nitro.hooks.callHook("prerender:done", {
|
|
1116
|
-
prerenderedRoutes: nitro._prerenderedRoutes,
|
|
1117
|
-
failedRoutes: [...failedRoutes]
|
|
1118
|
-
});
|
|
1119
|
-
if (nitro.options.prerender.failOnError && failedRoutes.size > 0) {
|
|
1120
|
-
nitro.logger.log("\nErrors prerendering:");
|
|
1121
|
-
for (const route of failedRoutes) nitro.logger.log(formatPrerenderRoute(route));
|
|
1122
|
-
nitro.logger.log("");
|
|
1123
|
-
throw new Error("Exiting due to prerender errors.");
|
|
1124
|
-
}
|
|
1125
|
-
const prerenderTimeInMs = Date.now() - prerenderStartTime;
|
|
1126
|
-
nitro.logger.info(`Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`);
|
|
1127
|
-
if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro);
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
//#endregion
|
|
1131
|
-
//#region src/task.ts
|
|
1132
|
-
/** @experimental */
|
|
1133
|
-
async function runTask(taskEvent, opts) {
|
|
1134
|
-
return await (await _getTasksContext(opts)).devFetch(`/_nitro/tasks/${taskEvent.name}`, {
|
|
1135
|
-
method: "POST",
|
|
1136
|
-
body: taskEvent
|
|
1137
|
-
});
|
|
1138
|
-
}
|
|
1139
|
-
/** @experimental */
|
|
1140
|
-
async function listTasks(opts) {
|
|
1141
|
-
return (await (await _getTasksContext(opts)).devFetch("/_nitro/tasks")).tasks;
|
|
1142
|
-
}
|
|
1143
|
-
const _devHint = `(is dev server running?)`;
|
|
1144
|
-
async function _getTasksContext(opts) {
|
|
1145
|
-
const buildInfoPath = resolve(resolve(resolve(process.cwd(), opts?.cwd || "."), opts?.buildDir || "node_modules/.nitro"), "nitro.dev.json");
|
|
1146
|
-
if (!existsSync(buildInfoPath)) throw new Error(`Missing info file: \`${buildInfoPath}\` ${_devHint}`);
|
|
1147
|
-
const buildInfo = JSON.parse(await readFile(buildInfoPath, "utf8"));
|
|
1148
|
-
if (!buildInfo.dev?.pid || !buildInfo.dev?.workerAddress) throw new Error(`Missing dev server info in: \`${buildInfoPath}\` ${_devHint}`);
|
|
1149
|
-
if (!_pidIsRunning(buildInfo.dev.pid)) throw new Error(`Dev server is not running (pid: ${buildInfo.dev.pid})`);
|
|
1150
|
-
const baseURL = `http://${buildInfo.dev.workerAddress.host || "localhost"}:${buildInfo.dev.workerAddress.port || "3000"}`;
|
|
1151
|
-
const socketPath = buildInfo.dev.workerAddress.socketPath;
|
|
1152
|
-
const devFetch = (path, options) => {
|
|
1153
|
-
return new Promise((resolve$1, reject) => {
|
|
1154
|
-
let url = withBase(path, baseURL);
|
|
1155
|
-
if (options?.query) url = withQuery(url, options.query);
|
|
1156
|
-
const request = http.request(url, {
|
|
1157
|
-
socketPath,
|
|
1158
|
-
method: options?.method,
|
|
1159
|
-
headers: {
|
|
1160
|
-
Accept: "application/json",
|
|
1161
|
-
"Content-Type": "application/json"
|
|
1162
|
-
}
|
|
1163
|
-
}, (response) => {
|
|
1164
|
-
if (!response.statusCode || response.statusCode >= 400 && response.statusCode < 600) {
|
|
1165
|
-
reject(new Error(response.statusMessage));
|
|
1166
|
-
return;
|
|
1167
|
-
}
|
|
1168
|
-
let data = "";
|
|
1169
|
-
response.on("data", (chunk) => data += chunk).on("end", () => resolve$1(JSON.parse(data))).on("error", (e) => reject(e));
|
|
1170
|
-
});
|
|
1171
|
-
request.on("error", (e) => reject(e));
|
|
1172
|
-
if (options?.body) request.write(JSON.stringify(options.body));
|
|
1173
|
-
request.end();
|
|
1174
|
-
});
|
|
1175
|
-
};
|
|
1176
|
-
return {
|
|
1177
|
-
buildInfo,
|
|
1178
|
-
devFetch
|
|
1179
|
-
};
|
|
1180
|
-
}
|
|
1181
|
-
function _pidIsRunning(pid) {
|
|
1182
|
-
try {
|
|
1183
|
-
process.kill(pid, 0);
|
|
1184
|
-
return true;
|
|
1185
|
-
} catch {
|
|
1186
|
-
return false;
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
25
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
26
|
+
value: mod,
|
|
27
|
+
enumerable: true
|
|
28
|
+
}) : target, mod));
|
|
29
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
1189
30
|
|
|
1190
31
|
//#endregion
|
|
1191
|
-
export {
|
|
32
|
+
export { __require as n, __toESM as r, __commonJSMin as t };
|