@nuxt/cli-nightly 3.29.4-20251021-192254-70dcc9b → 3.30.0-20251027-201254-c23e915

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.
@@ -0,0 +1,931 @@
1
+ import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, t as cwdArgs } from "./_shared-C3vB2YLc.mjs";
2
+ import { t as logger } from "./logger-Dk0gkCkX.mjs";
3
+ import { n as clearDir } from "./fs-ewAp6tjM.mjs";
4
+ import { t as loadKit } from "./kit-xFxVGu6d.mjs";
5
+ import { t as overrideEnv } from "./env-Dz4K_NkM.mjs";
6
+ import process from "node:process";
7
+ import { defineCommand } from "citty";
8
+ import { defu as defu$1 } from "defu";
9
+ import { promises } from "node:fs";
10
+ import { join, resolve } from "pathe";
11
+ import { FastResponse, FastURL, serve } from "srvx";
12
+
13
+ //#region ../../node_modules/.pnpm/rou3@0.7.8/node_modules/rou3/dist/index.mjs
14
+ const NullProtoObj = /* @__PURE__ */ (() => {
15
+ const e = function() {};
16
+ return e.prototype = Object.create(null), Object.freeze(e.prototype), e;
17
+ })();
18
+ /**
19
+ * Create a new router context.
20
+ */
21
+ function createRouter() {
22
+ return {
23
+ root: { key: "" },
24
+ static: new NullProtoObj()
25
+ };
26
+ }
27
+ function splitPath(path) {
28
+ const [_, ...s] = path.split("/");
29
+ return s[s.length - 1] === "" ? s.slice(0, -1) : s;
30
+ }
31
+ function getMatchParams(segments, paramsMap) {
32
+ const params = new NullProtoObj();
33
+ for (const [index, name] of paramsMap) {
34
+ const segment = index < 0 ? segments.slice(-1 * index).join("/") : segments[index];
35
+ if (typeof name === "string") params[name] = segment;
36
+ else {
37
+ const match = segment.match(name);
38
+ if (match) for (const key in match.groups) params[key] = match.groups[key];
39
+ }
40
+ }
41
+ return params;
42
+ }
43
+ /**
44
+ * Add a route to the router context.
45
+ */
46
+ function addRoute(ctx, method = "", path, data) {
47
+ method = method.toUpperCase();
48
+ if (path.charCodeAt(0) !== 47) path = `/${path}`;
49
+ const segments = splitPath(path);
50
+ let node = ctx.root;
51
+ let _unnamedParamIndex = 0;
52
+ const paramsMap = [];
53
+ const paramsRegexp = [];
54
+ for (let i = 0; i < segments.length; i++) {
55
+ const segment = segments[i];
56
+ if (segment.startsWith("**")) {
57
+ if (!node.wildcard) node.wildcard = { key: "**" };
58
+ node = node.wildcard;
59
+ paramsMap.push([
60
+ -i,
61
+ segment.split(":")[1] || "_",
62
+ segment.length === 2
63
+ ]);
64
+ break;
65
+ }
66
+ if (segment === "*" || segment.includes(":")) {
67
+ if (!node.param) node.param = { key: "*" };
68
+ node = node.param;
69
+ if (segment === "*") paramsMap.push([
70
+ i,
71
+ `_${_unnamedParamIndex++}`,
72
+ true
73
+ ]);
74
+ else if (segment.includes(":", 1)) {
75
+ const regexp = getParamRegexp(segment);
76
+ paramsRegexp[i] = regexp;
77
+ node.hasRegexParam = true;
78
+ paramsMap.push([
79
+ i,
80
+ regexp,
81
+ false
82
+ ]);
83
+ } else paramsMap.push([
84
+ i,
85
+ segment.slice(1),
86
+ false
87
+ ]);
88
+ continue;
89
+ }
90
+ const child = node.static?.[segment];
91
+ if (child) node = child;
92
+ else {
93
+ const staticNode = { key: segment };
94
+ if (!node.static) node.static = new NullProtoObj();
95
+ node.static[segment] = staticNode;
96
+ node = staticNode;
97
+ }
98
+ }
99
+ const hasParams = paramsMap.length > 0;
100
+ if (!node.methods) node.methods = new NullProtoObj();
101
+ node.methods[method] ??= [];
102
+ node.methods[method].push({
103
+ data: data || null,
104
+ paramsRegexp,
105
+ paramsMap: hasParams ? paramsMap : void 0
106
+ });
107
+ if (!hasParams) ctx.static[path] = node;
108
+ }
109
+ function getParamRegexp(segment) {
110
+ const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\.");
111
+ return /* @__PURE__ */ new RegExp(`^${regex}$`);
112
+ }
113
+ /**
114
+ * Find a route by path.
115
+ */
116
+ function findRoute(ctx, method = "", path, opts) {
117
+ if (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);
118
+ const staticNode = ctx.static[path];
119
+ if (staticNode && staticNode.methods) {
120
+ const staticMatch = staticNode.methods[method] || staticNode.methods[""];
121
+ if (staticMatch !== void 0) return staticMatch[0];
122
+ }
123
+ const segments = splitPath(path);
124
+ const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];
125
+ if (match === void 0) return;
126
+ if (opts?.params === false) return match;
127
+ return {
128
+ data: match.data,
129
+ params: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0
130
+ };
131
+ }
132
+ function _lookupTree(ctx, node, method, segments, index) {
133
+ if (index === segments.length) {
134
+ if (node.methods) {
135
+ const match = node.methods[method] || node.methods[""];
136
+ if (match) return match;
137
+ }
138
+ if (node.param && node.param.methods) {
139
+ const match = node.param.methods[method] || node.param.methods[""];
140
+ if (match) {
141
+ const pMap = match[0].paramsMap;
142
+ if (pMap?.[pMap?.length - 1]?.[2]) return match;
143
+ }
144
+ }
145
+ if (node.wildcard && node.wildcard.methods) {
146
+ const match = node.wildcard.methods[method] || node.wildcard.methods[""];
147
+ if (match) {
148
+ const pMap = match[0].paramsMap;
149
+ if (pMap?.[pMap?.length - 1]?.[2]) return match;
150
+ }
151
+ }
152
+ return;
153
+ }
154
+ const segment = segments[index];
155
+ if (node.static) {
156
+ const staticChild = node.static[segment];
157
+ if (staticChild) {
158
+ const match = _lookupTree(ctx, staticChild, method, segments, index + 1);
159
+ if (match) return match;
160
+ }
161
+ }
162
+ if (node.param) {
163
+ const match = _lookupTree(ctx, node.param, method, segments, index + 1);
164
+ if (match) {
165
+ if (node.param.hasRegexParam) {
166
+ const exactMatch = match.find((m) => m.paramsRegexp[index]?.test(segment)) || match.find((m) => !m.paramsRegexp[index]);
167
+ return exactMatch ? [exactMatch] : void 0;
168
+ }
169
+ return match;
170
+ }
171
+ }
172
+ if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""];
173
+ }
174
+ function routeToRegExp(route = "/") {
175
+ const reSegments = [];
176
+ let idCtr = 0;
177
+ for (const segment of route.split("/")) {
178
+ if (!segment) continue;
179
+ if (segment === "*") reSegments.push(`(?<_${idCtr++}>[^/]*)`);
180
+ else if (segment.startsWith("**")) reSegments.push(segment === "**" ? "?(?<_>.*)" : `?(?<${segment.slice(3)}>.+)`);
181
+ else if (segment.includes(":")) reSegments.push(segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."));
182
+ else reSegments.push(segment);
183
+ }
184
+ return /* @__PURE__ */ new RegExp(`^/${reSegments.join("/")}/?$`);
185
+ }
186
+
187
+ //#endregion
188
+ //#region ../../node_modules/.pnpm/h3@2.0.1-rc.4_crossws@0.4.1_srvx@0.8.16_/node_modules/h3/dist/h3.mjs
189
+ const kEventNS = "h3.internal.event.";
190
+ const kEventRes = /* @__PURE__ */ Symbol.for(`${kEventNS}res`);
191
+ const kEventResHeaders = /* @__PURE__ */ Symbol.for(`${kEventNS}res.headers`);
192
+ var H3Event = class {
193
+ /**
194
+ * Access to the H3 application instance.
195
+ */
196
+ app;
197
+ /**
198
+ * Incoming HTTP request info.
199
+ *
200
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
201
+ */
202
+ req;
203
+ /**
204
+ * Access to the parsed request URL.
205
+ *
206
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL)
207
+ */
208
+ url;
209
+ /**
210
+ * Event context.
211
+ */
212
+ context;
213
+ /**
214
+ * @internal
215
+ */
216
+ static __is_event__ = true;
217
+ constructor(req, context, app) {
218
+ this.context = context || req.context || new NullProtoObj();
219
+ this.req = req;
220
+ this.app = app;
221
+ const _url = req._url;
222
+ this.url = _url && _url instanceof URL ? _url : new FastURL(req.url);
223
+ }
224
+ /**
225
+ * Prepared HTTP response.
226
+ */
227
+ get res() {
228
+ return this[kEventRes] ||= new H3EventResponse();
229
+ }
230
+ /**
231
+ * Access to runtime specific additional context.
232
+ *
233
+ */
234
+ get runtime() {
235
+ return this.req.runtime;
236
+ }
237
+ /**
238
+ * Tell the runtime about an ongoing operation that shouldn't close until the promise resolves.
239
+ */
240
+ waitUntil(promise) {
241
+ this.req.waitUntil?.(promise);
242
+ }
243
+ toString() {
244
+ return `[${this.req.method}] ${this.req.url}`;
245
+ }
246
+ toJSON() {
247
+ return this.toString();
248
+ }
249
+ /**
250
+ * Access to the raw Node.js req/res objects.
251
+ *
252
+ * @deprecated Use `event.runtime.{node|deno|bun|...}.` instead.
253
+ */
254
+ get node() {
255
+ return this.req.runtime?.node;
256
+ }
257
+ /**
258
+ * Access to the incoming request headers.
259
+ *
260
+ * @deprecated Use `event.req.headers` instead.
261
+ *
262
+ */
263
+ get headers() {
264
+ return this.req.headers;
265
+ }
266
+ /**
267
+ * Access to the incoming request url (pathname+search).
268
+ *
269
+ * @deprecated Use `event.url.pathname + event.url.search` instead.
270
+ *
271
+ * Example: `/api/hello?name=world`
272
+ * */
273
+ get path() {
274
+ return this.url.pathname + this.url.search;
275
+ }
276
+ /**
277
+ * Access to the incoming request method.
278
+ *
279
+ * @deprecated Use `event.req.method` instead.
280
+ */
281
+ get method() {
282
+ return this.req.method;
283
+ }
284
+ };
285
+ var H3EventResponse = class {
286
+ status;
287
+ statusText;
288
+ get headers() {
289
+ return this[kEventResHeaders] ||= new Headers();
290
+ }
291
+ };
292
+ const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
293
+ /**
294
+ * Make sure the status message is safe to use in a response.
295
+ *
296
+ * Allowed characters: horizontal tabs, spaces or visible ascii characters: https://www.rfc-editor.org/rfc/rfc7230#section-3.1.2
297
+ */
298
+ function sanitizeStatusMessage(statusMessage = "") {
299
+ return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
300
+ }
301
+ /**
302
+ * Make sure the status code is a valid HTTP status code.
303
+ */
304
+ function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
305
+ if (!statusCode) return defaultStatusCode;
306
+ if (typeof statusCode === "string") statusCode = +statusCode;
307
+ if (statusCode < 100 || statusCode > 599) return defaultStatusCode;
308
+ return statusCode;
309
+ }
310
+ /**
311
+ * HTTPError
312
+ */
313
+ var HTTPError = class HTTPError$1 extends Error {
314
+ get name() {
315
+ return "HTTPError";
316
+ }
317
+ /**
318
+ * HTTP status code in range [200...599]
319
+ */
320
+ status;
321
+ /**
322
+ * HTTP status text
323
+ *
324
+ * **NOTE:** This should be short (max 512 to 1024 characters).
325
+ * Allowed characters are tabs, spaces, visible ASCII characters, and extended characters (byte value 128–255).
326
+ *
327
+ * **TIP:** Use `message` for longer error descriptions in JSON body.
328
+ */
329
+ statusText;
330
+ /**
331
+ * Additional HTTP headers to be sent in error response.
332
+ */
333
+ headers;
334
+ /**
335
+ * Original error object that caused this error.
336
+ */
337
+ cause;
338
+ /**
339
+ * Additional data attached in the error JSON body under `data` key.
340
+ */
341
+ data;
342
+ /**
343
+ * Additional top level JSON body properties to attach in the error JSON body.
344
+ */
345
+ body;
346
+ /**
347
+ * Flag to indicate that the error was not handled by the application.
348
+ *
349
+ * Unhandled error stack trace, data and message are hidden in non debug mode for security reasons.
350
+ */
351
+ unhandled;
352
+ /**
353
+ * Check if the input is an instance of HTTPError using its constructor name.
354
+ *
355
+ * It is safer than using `instanceof` because it works across different contexts (e.g., if the error was thrown in a different module).
356
+ */
357
+ static isError(input) {
358
+ return input instanceof Error && input?.name === "HTTPError";
359
+ }
360
+ /**
361
+ * Create a new HTTPError with the given status code and optional status text and details.
362
+ *
363
+ * @example
364
+ *
365
+ * HTTPError.status(404)
366
+ * HTTPError.status(418, "I'm a teapot")
367
+ * HTTPError.status(403, "Forbidden", { message: "Not authenticated" })
368
+ */
369
+ static status(status, statusText, details) {
370
+ return new HTTPError$1({
371
+ ...details,
372
+ statusText,
373
+ status
374
+ });
375
+ }
376
+ constructor(arg1, arg2) {
377
+ let messageInput;
378
+ let details;
379
+ if (typeof arg1 === "string") {
380
+ messageInput = arg1;
381
+ details = arg2;
382
+ } else details = arg1;
383
+ const status = sanitizeStatusCode(details?.status || (details?.cause)?.status || details?.status || details?.statusCode, 500);
384
+ const statusText = sanitizeStatusMessage(details?.statusText || (details?.cause)?.statusText || details?.statusText || details?.statusMessage);
385
+ const message = messageInput || details?.message || (details?.cause)?.message || details?.statusText || details?.statusMessage || [
386
+ "HTTPError",
387
+ status,
388
+ statusText
389
+ ].filter(Boolean).join(" ");
390
+ super(message, { cause: details });
391
+ this.cause = details;
392
+ Error.captureStackTrace?.(this, this.constructor);
393
+ this.status = status;
394
+ this.statusText = statusText || void 0;
395
+ const rawHeaders = details?.headers || (details?.cause)?.headers;
396
+ this.headers = rawHeaders ? new Headers(rawHeaders) : void 0;
397
+ this.unhandled = details?.unhandled ?? (details?.cause)?.unhandled ?? void 0;
398
+ this.data = details?.data;
399
+ this.body = details?.body;
400
+ }
401
+ /**
402
+ * @deprecated Use `status`
403
+ */
404
+ get statusCode() {
405
+ return this.status;
406
+ }
407
+ /**
408
+ * @deprecated Use `statusText`
409
+ */
410
+ get statusMessage() {
411
+ return this.statusText;
412
+ }
413
+ toJSON() {
414
+ const unhandled = this.unhandled;
415
+ return {
416
+ status: this.status,
417
+ statusText: this.statusText,
418
+ unhandled,
419
+ message: unhandled ? "HTTPError" : this.message,
420
+ data: unhandled ? void 0 : this.data,
421
+ ...unhandled ? void 0 : this.body
422
+ };
423
+ }
424
+ };
425
+ function isJSONSerializable(value, _type) {
426
+ if (value === null || value === void 0) return true;
427
+ if (_type !== "object") return _type === "boolean" || _type === "number" || _type === "string";
428
+ if (typeof value.toJSON === "function") return true;
429
+ if (Array.isArray(value)) return true;
430
+ if (typeof value.pipe === "function" || typeof value.pipeTo === "function") return false;
431
+ if (value instanceof NullProtoObj) return true;
432
+ const proto = Object.getPrototypeOf(value);
433
+ return proto === Object.prototype || proto === null;
434
+ }
435
+ const kNotFound = /* @__PURE__ */ Symbol.for("h3.notFound");
436
+ const kHandled = /* @__PURE__ */ Symbol.for("h3.handled");
437
+ function toResponse(val, event, config = {}) {
438
+ if (typeof val?.then === "function") return (val.catch?.((error) => error) || Promise.resolve(val)).then((resolvedVal) => toResponse(resolvedVal, event, config));
439
+ const response = prepareResponse(val, event, config);
440
+ if (typeof response?.then === "function") return toResponse(response, event, config);
441
+ const { onResponse: onResponse$1 } = config;
442
+ return onResponse$1 ? Promise.resolve(onResponse$1(response, event)).then(() => response) : response;
443
+ }
444
+ var HTTPResponse = class {
445
+ #headers;
446
+ #init;
447
+ body;
448
+ constructor(body, init) {
449
+ this.body = body;
450
+ this.#init = init;
451
+ }
452
+ get status() {
453
+ return this.#init?.status || 200;
454
+ }
455
+ get statusText() {
456
+ return this.#init?.statusText || "OK";
457
+ }
458
+ get headers() {
459
+ return this.#headers ||= new Headers(this.#init?.headers);
460
+ }
461
+ };
462
+ function prepareResponse(val, event, config, nested) {
463
+ if (val === kHandled) return new FastResponse(null);
464
+ if (val === kNotFound) val = new HTTPError({
465
+ status: 404,
466
+ message: `Cannot find any route matching [${event.req.method}] ${event.url}`
467
+ });
468
+ if (val && val instanceof Error) {
469
+ const isHTTPError = HTTPError.isError(val);
470
+ const error = isHTTPError ? val : new HTTPError(val);
471
+ if (!isHTTPError) {
472
+ error.unhandled = true;
473
+ if (val?.stack) error.stack = val.stack;
474
+ }
475
+ if (error.unhandled && !config.silent) console.error(error);
476
+ const { onError: onError$1 } = config;
477
+ return onError$1 && !nested ? Promise.resolve(onError$1(error, event)).catch((error$1) => error$1).then((newVal) => prepareResponse(newVal ?? val, event, config, true)) : errorResponse(error, config.debug);
478
+ }
479
+ const preparedRes = event[kEventRes];
480
+ const preparedHeaders = preparedRes?.[kEventResHeaders];
481
+ if (!(val instanceof Response)) {
482
+ const res = prepareResponseBody(val, event, config);
483
+ const status = res.status || preparedRes?.status;
484
+ return new FastResponse(nullBody(event.req.method, status) ? null : res.body, {
485
+ status,
486
+ statusText: res.statusText || preparedRes?.statusText,
487
+ headers: res.headers && preparedHeaders ? mergeHeaders$1(res.headers, preparedHeaders) : res.headers || preparedHeaders
488
+ });
489
+ }
490
+ if (!preparedHeaders || nested || !val.ok) return val;
491
+ try {
492
+ mergeHeaders$1(val.headers, preparedHeaders, val.headers);
493
+ return val;
494
+ } catch {
495
+ return new FastResponse(nullBody(event.req.method, val.status) ? null : val.body, {
496
+ status: val.status,
497
+ statusText: val.statusText,
498
+ headers: mergeHeaders$1(val.headers, preparedHeaders)
499
+ });
500
+ }
501
+ }
502
+ function mergeHeaders$1(base, overrides, target = new Headers(base)) {
503
+ for (const [name, value] of overrides) if (name === "set-cookie") target.append(name, value);
504
+ else target.set(name, value);
505
+ return target;
506
+ }
507
+ const frozenHeaders = () => {
508
+ throw new Error("Headers are frozen");
509
+ };
510
+ var FrozenHeaders = class extends Headers {
511
+ constructor(init) {
512
+ super(init);
513
+ this.set = this.append = this.delete = frozenHeaders;
514
+ }
515
+ };
516
+ const emptyHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-length": "0" });
517
+ const jsonHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-type": "application/json;charset=UTF-8" });
518
+ function prepareResponseBody(val, event, config) {
519
+ if (val === null || val === void 0) return {
520
+ body: "",
521
+ headers: emptyHeaders
522
+ };
523
+ const valType = typeof val;
524
+ if (valType === "string") return { body: val };
525
+ if (val instanceof Uint8Array) {
526
+ event.res.headers.set("content-length", val.byteLength.toString());
527
+ return { body: val };
528
+ }
529
+ if (val instanceof HTTPResponse || val?.constructor?.name === "HTTPResponse") return val;
530
+ if (isJSONSerializable(val, valType)) return {
531
+ body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
532
+ headers: jsonHeaders
533
+ };
534
+ if (valType === "bigint") return {
535
+ body: val.toString(),
536
+ headers: jsonHeaders
537
+ };
538
+ if (val instanceof Blob) {
539
+ const headers = new Headers({
540
+ "content-type": val.type,
541
+ "content-length": val.size.toString()
542
+ });
543
+ let filename = val.name;
544
+ if (filename) {
545
+ filename = encodeURIComponent(filename);
546
+ headers.set("content-disposition", `filename="${filename}"; filename*=UTF-8''${filename}`);
547
+ }
548
+ return {
549
+ body: val.stream(),
550
+ headers
551
+ };
552
+ }
553
+ if (valType === "symbol") return { body: val.toString() };
554
+ if (valType === "function") return { body: `${val.name}()` };
555
+ return { body: val };
556
+ }
557
+ function nullBody(method, status) {
558
+ return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
559
+ }
560
+ function errorResponse(error, debug) {
561
+ return new FastResponse(JSON.stringify({
562
+ ...error.toJSON(),
563
+ stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
564
+ }, void 0, debug ? 2 : void 0), {
565
+ status: error.status,
566
+ statusText: error.statusText,
567
+ headers: error.headers ? mergeHeaders$1(jsonHeaders, error.headers) : new Headers(jsonHeaders)
568
+ });
569
+ }
570
+ function normalizeMiddleware(input, opts = {}) {
571
+ const matcher = createMatcher(opts);
572
+ if (!matcher && (input.length > 1 || input.constructor?.name === "AsyncFunction")) return input;
573
+ return (event, next) => {
574
+ if (matcher && !matcher(event)) return next();
575
+ const res = input(event, next);
576
+ return res === void 0 || res === kNotFound ? next() : res;
577
+ };
578
+ }
579
+ function createMatcher(opts) {
580
+ if (!opts.route && !opts.method && !opts.match) return void 0;
581
+ const routeMatcher = opts.route ? routeToRegExp(opts.route) : void 0;
582
+ const method = opts.method?.toUpperCase();
583
+ return function _middlewareMatcher(event) {
584
+ if (method && event.req.method !== method) return false;
585
+ if (opts.match && !opts.match(event)) return false;
586
+ if (!routeMatcher) return true;
587
+ const match = event.url.pathname.match(routeMatcher);
588
+ if (!match) return false;
589
+ if (match.groups) event.context.middlewareParams = {
590
+ ...event.context.middlewareParams,
591
+ ...match.groups
592
+ };
593
+ return true;
594
+ };
595
+ }
596
+ function callMiddleware(event, middleware, handler, index = 0) {
597
+ if (index === middleware.length) return handler(event);
598
+ const fn = middleware[index];
599
+ let nextCalled;
600
+ let nextResult;
601
+ const next = () => {
602
+ if (nextCalled) return nextResult;
603
+ nextCalled = true;
604
+ nextResult = callMiddleware(event, middleware, handler, index + 1);
605
+ return nextResult;
606
+ };
607
+ const ret = fn(event, next);
608
+ return is404(ret) ? next() : typeof ret?.then === "function" ? ret.then((resolved) => is404(resolved) ? next() : resolved) : ret;
609
+ }
610
+ function is404(val) {
611
+ return val === void 0 || val === kNotFound || val?.status === 404 && val instanceof Response;
612
+ }
613
+ /**
614
+ * Convert input into a web [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request).
615
+ *
616
+ * If input is a relative URL, it will be normalized into a full path based on headers.
617
+ *
618
+ * If input is already a Request and no options are provided, it will be returned as-is.
619
+ */
620
+ function toRequest(input, options) {
621
+ if (typeof input === "string") {
622
+ let url = input;
623
+ if (url[0] === "/") {
624
+ const headers = options?.headers ? new Headers(options.headers) : void 0;
625
+ const host = headers?.get("host") || "localhost";
626
+ url = `${headers?.get("x-forwarded-proto") === "https" ? "https" : "http"}://${host}${url}`;
627
+ }
628
+ return new Request(url, options);
629
+ } else if (options || input instanceof URL) return new Request(input, options);
630
+ return input;
631
+ }
632
+ function defineHandler(input) {
633
+ if (typeof input === "function") return handlerWithFetch(input);
634
+ const handler = input.handler || (input.fetch ? function _fetchHandler(event) {
635
+ return input.fetch(event.req);
636
+ } : NoHandler);
637
+ return Object.assign(handlerWithFetch(input.middleware?.length ? function _handlerMiddleware(event) {
638
+ return callMiddleware(event, input.middleware, handler);
639
+ } : handler), input);
640
+ }
641
+ function handlerWithFetch(handler) {
642
+ if ("fetch" in handler) return handler;
643
+ return Object.assign(handler, { fetch: (req) => {
644
+ if (typeof req === "string") req = new URL(req, "http://_");
645
+ if (req instanceof URL) req = new Request(req);
646
+ const event = new H3Event(req);
647
+ try {
648
+ return Promise.resolve(toResponse(handler(event), event));
649
+ } catch (error) {
650
+ return Promise.resolve(toResponse(error, event));
651
+ }
652
+ } });
653
+ }
654
+ function defineLazyEventHandler(loader) {
655
+ let handler;
656
+ let promise;
657
+ const resolveLazyHandler = () => {
658
+ if (handler) return Promise.resolve(handler);
659
+ return promise ??= Promise.resolve(loader()).then((r) => {
660
+ handler = toEventHandler(r) || toEventHandler(r.default);
661
+ if (typeof handler !== "function") throw new TypeError("Invalid lazy handler", { cause: { resolved: r } });
662
+ return handler;
663
+ });
664
+ };
665
+ return defineHandler(function lazyHandler(event) {
666
+ return handler ? handler(event) : resolveLazyHandler().then((r) => r(event));
667
+ });
668
+ }
669
+ function toEventHandler(handler) {
670
+ if (typeof handler === "function") return handler;
671
+ if (typeof handler?.handler === "function") return handler.handler;
672
+ if (typeof handler?.fetch === "function") return function _fetchHandler(event) {
673
+ return handler.fetch(event.req);
674
+ };
675
+ }
676
+ const NoHandler = () => kNotFound;
677
+ const H3Core = /* @__PURE__ */ (() => {
678
+ const HTTPMethods = [
679
+ "GET",
680
+ "POST",
681
+ "PUT",
682
+ "DELETE",
683
+ "PATCH",
684
+ "HEAD",
685
+ "OPTIONS",
686
+ "CONNECT",
687
+ "TRACE"
688
+ ];
689
+ class H3Core$1 {
690
+ _middleware;
691
+ _routes = [];
692
+ config;
693
+ constructor(config = {}) {
694
+ this._middleware = [];
695
+ this.config = config;
696
+ this.fetch = this.fetch.bind(this);
697
+ this.request = this.request.bind(this);
698
+ this.handler = this.handler.bind(this);
699
+ config.plugins?.forEach((plugin) => plugin(this));
700
+ }
701
+ fetch(request) {
702
+ return this._request(request);
703
+ }
704
+ request(_req, _init, context) {
705
+ return this._request(toRequest(_req, _init), context);
706
+ }
707
+ _request(request, context) {
708
+ const event = new H3Event(request, context, this);
709
+ let handlerRes;
710
+ try {
711
+ if (this.config.onRequest) {
712
+ const hookRes = this.config.onRequest(event);
713
+ handlerRes = typeof hookRes?.then === "function" ? hookRes.then(() => this.handler(event)) : this.handler(event);
714
+ } else handlerRes = this.handler(event);
715
+ } catch (error) {
716
+ handlerRes = Promise.reject(error);
717
+ }
718
+ return toResponse(handlerRes, event, this.config);
719
+ }
720
+ /**
721
+ * Immediately register an H3 plugin.
722
+ */
723
+ register(plugin) {
724
+ plugin(this);
725
+ return this;
726
+ }
727
+ _findRoute(_event) {}
728
+ _addRoute(_route) {
729
+ this._routes.push(_route);
730
+ }
731
+ _getMiddleware(_event, route) {
732
+ return route?.data.middleware ? [...this._middleware, ...route.data.middleware] : this._middleware;
733
+ }
734
+ handler(event) {
735
+ const route = this._findRoute(event);
736
+ if (route) {
737
+ event.context.params = route.params;
738
+ event.context.matchedRoute = route.data;
739
+ }
740
+ const routeHandler = route?.data.handler || NoHandler;
741
+ const middleware = this._getMiddleware(event, route);
742
+ return middleware.length > 0 ? callMiddleware(event, middleware, routeHandler) : routeHandler(event);
743
+ }
744
+ mount(base, input) {
745
+ if ("handler" in input) {
746
+ if (input._middleware.length > 0) this._middleware.push((event, next) => {
747
+ return event.url.pathname.startsWith(base) ? callMiddleware(event, input._middleware, next) : next();
748
+ });
749
+ for (const r of input._routes) this._addRoute({
750
+ ...r,
751
+ route: base + r.route
752
+ });
753
+ } else {
754
+ const fetchHandler = "fetch" in input ? input.fetch : input;
755
+ this.all(`${base}/**`, function _mountedMiddleware(event) {
756
+ const url = new URL(event.url);
757
+ url.pathname = url.pathname.slice(base.length) || "/";
758
+ return fetchHandler(new Request(url, event.req));
759
+ });
760
+ }
761
+ return this;
762
+ }
763
+ all(route, handler, opts) {
764
+ return this.on("", route, handler, opts);
765
+ }
766
+ on(method, route, handler, opts) {
767
+ const _method = (method || "").toUpperCase();
768
+ route = new URL(route, "http://_").pathname;
769
+ this._addRoute({
770
+ method: _method,
771
+ route,
772
+ handler: toEventHandler(handler),
773
+ middleware: opts?.middleware,
774
+ meta: {
775
+ ...handler.meta,
776
+ ...opts?.meta
777
+ }
778
+ });
779
+ return this;
780
+ }
781
+ _normalizeMiddleware(fn, _opts) {
782
+ return fn;
783
+ }
784
+ use(arg1, arg2, arg3) {
785
+ let route;
786
+ let fn;
787
+ let opts;
788
+ if (typeof arg1 === "string") {
789
+ route = arg1;
790
+ fn = arg2;
791
+ opts = arg3;
792
+ } else {
793
+ fn = arg1;
794
+ opts = arg2;
795
+ }
796
+ this._middleware.push(this._normalizeMiddleware(fn, {
797
+ ...opts,
798
+ route
799
+ }));
800
+ return this;
801
+ }
802
+ }
803
+ for (const method of HTTPMethods) H3Core$1.prototype[method.toLowerCase()] = function(route, handler, opts) {
804
+ return this.on(method, route, handler, opts);
805
+ };
806
+ return H3Core$1;
807
+ })();
808
+ var H3 = class extends H3Core {
809
+ /** @internal */
810
+ _rou3;
811
+ constructor(config = {}) {
812
+ super(config);
813
+ this._rou3 = createRouter();
814
+ }
815
+ _findRoute(_event) {
816
+ return findRoute(this._rou3, _event.req.method, _event.url.pathname);
817
+ }
818
+ _addRoute(_route) {
819
+ addRoute(this._rou3, _route.method, _route.route, _route);
820
+ super._addRoute(_route);
821
+ }
822
+ _normalizeMiddleware(fn, opts) {
823
+ return normalizeMiddleware(fn, opts);
824
+ }
825
+ };
826
+ const lazyEventHandler = defineLazyEventHandler;
827
+
828
+ //#endregion
829
+ //#region ../nuxi/src/commands/analyze.ts
830
+ const indexHtml = `
831
+ <!DOCTYPE html>
832
+ <html lang="en">
833
+ <head>
834
+ <meta charset="utf-8">
835
+ <title>Nuxt Bundle Stats (experimental)</title>
836
+ </head>
837
+ <h1>Nuxt Bundle Stats (experimental)</h1>
838
+ <ul>
839
+ <li>
840
+ <a href="/nitro">Nitro server bundle stats</a>
841
+ </li>
842
+ <li>
843
+ <a href="/client">Client bundle stats</a>
844
+ </li>
845
+ </ul>
846
+ </html>
847
+ `.trim();
848
+ var analyze_default = defineCommand({
849
+ meta: {
850
+ name: "analyze",
851
+ description: "Build nuxt and analyze production bundle (experimental)"
852
+ },
853
+ args: {
854
+ ...cwdArgs,
855
+ ...logLevelArgs,
856
+ ...legacyRootDirArgs,
857
+ ...dotEnvArgs,
858
+ ...extendsArgs,
859
+ name: {
860
+ type: "string",
861
+ description: "Name of the analysis",
862
+ default: "default",
863
+ valueHint: "name"
864
+ },
865
+ serve: {
866
+ type: "boolean",
867
+ description: "Serve the analysis results",
868
+ negativeDescription: "Skip serving the analysis results",
869
+ default: true
870
+ }
871
+ },
872
+ async run(ctx) {
873
+ overrideEnv("production");
874
+ const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
875
+ const name = ctx.args.name || "default";
876
+ const slug = name.trim().replace(/[^\w-]/g, "_");
877
+ const startTime = Date.now();
878
+ const { loadNuxt, buildNuxt } = await loadKit(cwd);
879
+ const nuxt = await loadNuxt({
880
+ cwd,
881
+ dotenv: {
882
+ cwd,
883
+ fileName: ctx.args.dotenv
884
+ },
885
+ overrides: defu$1(ctx.data?.overrides, {
886
+ ...ctx.args.extends && { extends: ctx.args.extends },
887
+ build: { analyze: { enabled: true } },
888
+ vite: { build: { rollupOptions: { output: {
889
+ chunkFileNames: "_nuxt/[name].js",
890
+ entryFileNames: "_nuxt/[name].js"
891
+ } } } },
892
+ logLevel: ctx.args.logLevel
893
+ })
894
+ });
895
+ const analyzeDir = nuxt.options.analyzeDir;
896
+ const buildDir = nuxt.options.buildDir;
897
+ const outDir = nuxt.options.nitro.output?.dir || join(nuxt.options.rootDir, ".output");
898
+ nuxt.options.build.analyze = defu$1(nuxt.options.build.analyze, { filename: join(analyzeDir, "client.html") });
899
+ await clearDir(analyzeDir);
900
+ await buildNuxt(nuxt);
901
+ const meta = {
902
+ name,
903
+ slug,
904
+ startTime,
905
+ endTime: Date.now(),
906
+ analyzeDir,
907
+ buildDir,
908
+ outDir
909
+ };
910
+ await nuxt.callHook("build:analyze:done", meta);
911
+ await promises.writeFile(join(analyzeDir, "meta.json"), JSON.stringify(meta, null, 2), "utf-8");
912
+ logger.info(`Analyze results are available at: \`${analyzeDir}\``);
913
+ logger.warn("Do not deploy analyze results! Use `nuxi build` before deploying.");
914
+ if (ctx.args.serve !== false && !process.env.CI) {
915
+ const app = new H3();
916
+ const opts = { headers: { "content-type": "text/html" } };
917
+ const serveFile = (filePath) => lazyEventHandler(async () => {
918
+ const contents = await promises.readFile(filePath, "utf-8");
919
+ return () => new Response(contents, opts);
920
+ });
921
+ logger.info("Starting stats server...");
922
+ app.use("/client", serveFile(join(analyzeDir, "client.html")));
923
+ app.use("/nitro", serveFile(join(analyzeDir, "nitro.html")));
924
+ app.use(() => new Response(indexHtml, opts));
925
+ await serve(app).serve();
926
+ }
927
+ }
928
+ });
929
+
930
+ //#endregion
931
+ export { analyze_default as default };