nitro-nightly 3.0.260429-beta → 3.0.260522-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/THIRD-PARTY-LICENSES.md.gz +0 -0
  2. package/dist/_build/common.mjs +119 -21
  3. package/dist/_build/rolldown.mjs +6 -6
  4. package/dist/_build/rollup.mjs +11 -11
  5. package/dist/_build/vite.build.mjs +3 -3
  6. package/dist/_build/vite.dev.mjs +149 -0
  7. package/dist/_build/vite.env.mjs +177 -0
  8. package/dist/_chunks/nitro.mjs +239 -12
  9. package/dist/_chunks/nitro2.mjs +117 -90
  10. package/dist/_chunks/utils.mjs +4 -4
  11. package/dist/_common.mjs +1 -1
  12. package/dist/_dev.d.mts +1 -1
  13. package/dist/_dev.mjs +5 -5
  14. package/dist/_libs/c12+rc9.mjs +11 -10
  15. package/dist/_libs/c12+readdirp+chokidar.d.mts +7 -8
  16. package/dist/_libs/citty.mjs +1 -1
  17. package/dist/_libs/common.d.mts +37 -0
  18. package/dist/_libs/commondir+is-reference.mjs +3 -3
  19. package/dist/_libs/compatx.d.mts +1 -1
  20. package/dist/_libs/compatx.mjs +1 -1
  21. package/dist/_libs/estree+pluginutils.d.mts +1 -1
  22. package/dist/_libs/estree-walker.mjs +1 -1
  23. package/dist/_libs/hasown+resolve+deepmerge.mjs +15 -15
  24. package/dist/_libs/httpxy.d.mts +1 -1
  25. package/dist/_libs/httpxy.mjs +8 -4
  26. package/dist/_libs/jsonc-parser+workers-utils.d.mts +1579 -0
  27. package/dist/_libs/klona.mjs +1 -1
  28. package/dist/_libs/magic-string.d.mts +1 -1
  29. package/dist/_libs/mlly.d.mts +1 -1
  30. package/dist/_libs/nypm+tinyexec.mjs +92 -99
  31. package/dist/_libs/openapi-types.d.mts +730 -0
  32. package/dist/_libs/perfect-debounce.mjs +1 -1
  33. package/dist/_libs/pkg-types.d.mts +1 -1
  34. package/dist/_libs/plugin-alias.mjs +2 -2
  35. package/dist/_libs/plugin-inject.mjs +3 -3
  36. package/dist/_libs/plugin-json.mjs +2 -2
  37. package/dist/_libs/pluginutils.mjs +16 -5
  38. package/dist/_libs/readdirp+chokidar.mjs +2 -2
  39. package/dist/_libs/remapping.mjs +2 -2
  40. package/dist/_libs/resolve-uri+gen-mapping.mjs +2 -5
  41. package/dist/_libs/rou3.d.mts +1 -1
  42. package/dist/_libs/rou3.mjs +1 -1
  43. package/dist/_libs/std-env.d.mts +1 -1
  44. package/dist/_libs/tsconfck.mjs +1 -1
  45. package/dist/_libs/ultrahtml.mjs +1 -1
  46. package/dist/_libs/{unimport+unplugin+oxc-parser.mjs → unimport+unplugin.mjs} +18 -8
  47. package/dist/_libs/unplugin+unimport.d.mts +3 -3
  48. package/dist/_libs/unwasm.d.mts +1 -1
  49. package/dist/_presets.mjs +117 -91
  50. package/dist/builder.d.mts +1 -1
  51. package/dist/builder.mjs +3 -3
  52. package/dist/cli/_chunks/build.mjs +3 -3
  53. package/dist/cli/_chunks/common.mjs +1 -1
  54. package/dist/cli/_chunks/deploy.mjs +2 -2
  55. package/dist/cli/_chunks/dev.mjs +4 -4
  56. package/dist/cli/_chunks/docs.mjs +1 -1
  57. package/dist/cli/_chunks/list.mjs +2 -2
  58. package/dist/cli/_chunks/prepare.mjs +3 -3
  59. package/dist/cli/_chunks/preview.mjs +4 -4
  60. package/dist/cli/_chunks/run.mjs +2 -2
  61. package/dist/cli/_chunks/task.mjs +1 -1
  62. package/dist/cli/index.mjs +1 -1
  63. package/dist/docs/1.deploy/2.providers/2.aws-amplify.md +3 -3
  64. package/dist/docs/1.deploy/2.providers/21.vercel.md +6 -0
  65. package/dist/docs/3.examples/27.vite-ssr-tsr-react.md +1 -1
  66. package/dist/presets/vercel/runtime/queue.dev.mjs +41 -0
  67. package/dist/runtime/internal/app.mjs +4 -111
  68. package/dist/runtime/virtual/app.d.mts +4 -0
  69. package/dist/runtime/virtual/app.mjs +32 -0
  70. package/dist/types/index.d.mts +21 -1756
  71. package/dist/vite.mjs +23 -337
  72. package/package.json +37 -39
  73. package/dist/THIRD-PARTY-LICENSES.md +0 -1676
  74. package/dist/_chunks/nitro3.mjs +0 -136
  75. package/dist/_chunks/nitro4.mjs +0 -127
Binary file
@@ -1,4 +1,4 @@
1
- import { i as __toESM$1, n as __exportAll, r as __require$1, t as __commonJSMin } from "../_common.mjs";
1
+ import { __commonJSMin, __exportAll, __require as __require$1, __toESM as __toESM$1 } from "../_common.mjs";
2
2
  import { builtinModules, createRequire } from "node:module";
3
3
  import consola from "consola";
4
4
  import { pkgDir, runtimeDependencies, runtimeDir, version } from "nitro/meta";
@@ -188,7 +188,6 @@ const parse$1 = function(p) {
188
188
  name: base.slice(0, base.length - extension.length)
189
189
  };
190
190
  };
191
- globalThis.process?.platform;
192
191
  const nodeBuiltins = [
193
192
  "_http_agent",
194
193
  "_http_client",
@@ -948,8 +947,8 @@ function moduleResolve$1(specifier, base, conditions, preserveSymlinks) {
948
947
  return finalizeResolution$1(resolved, base, preserveSymlinks);
949
948
  }
950
949
  const DEFAULT_CONDITIONS_SET$2 = /* @__PURE__ */ new Set(["node", "import"]);
951
- const isWindows = process.platform === "win32";
952
- const globalCache = globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map();
950
+ const isWindows = /* @__PURE__ */ (() => process.platform === "win32")();
951
+ const globalCache = /* @__PURE__ */ (() => globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map())();
953
952
  function resolveModuleURL(input, options) {
954
953
  const parsedInput = _parseInput(input);
955
954
  if ("external" in parsedInput) return parsedInput.external;
@@ -4281,7 +4280,7 @@ function toPathRegExp(input) {
4281
4280
  if (typeof input === "string") return new RegExp(pathRegExp(input));
4282
4281
  throw new TypeError("Expected a string or RegExp", { cause: input });
4283
4282
  }
4284
- const isObject$2 = (value) => {
4283
+ const isObject$3 = (value) => {
4285
4284
  const type = typeof value;
4286
4285
  return value !== null && (type === "object" || type === "function");
4287
4286
  };
@@ -4402,7 +4401,7 @@ function normalizePath$3(path) {
4402
4401
  return [];
4403
4402
  }
4404
4403
  function getProperty(object, path, value) {
4405
- if (!isObject$2(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value;
4404
+ if (!isObject$3(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value;
4406
4405
  const pathArray = normalizePath$3(path);
4407
4406
  if (pathArray.length === 0) return value;
4408
4407
  for (let index = 0; index < pathArray.length; index++) {
@@ -15681,6 +15680,9 @@ const BUILTIN_MODULES = new Set(builtinModules);
15681
15680
  function normalizeSlash(path) {
15682
15681
  return path.replace(/\\/g, "/");
15683
15682
  }
15683
+ function isObject$2(value) {
15684
+ return value !== null && typeof value === "object";
15685
+ }
15684
15686
  function matchAll(regex, string, addition) {
15685
15687
  const matches = [];
15686
15688
  for (const match of string.matchAll(regex)) matches.push({
@@ -16739,6 +16741,23 @@ function _isIdentifierBeforeAngleBracket(str, i) {
16739
16741
  const wordStart = j + 1;
16740
16742
  return wordStart < i && /[A-Za-z_$]/.test(str[wordStart]);
16741
16743
  }
16744
+ function interopDefault(sourceModule, opts = {}) {
16745
+ if (!isObject$2(sourceModule) || !("default" in sourceModule)) return sourceModule;
16746
+ const defaultValue = sourceModule.default;
16747
+ if (defaultValue === void 0 || defaultValue === null) return sourceModule;
16748
+ const _defaultType = typeof defaultValue;
16749
+ if (_defaultType !== "object" && !(_defaultType === "function" && !opts.preferNamespace)) return opts.preferNamespace ? sourceModule : defaultValue;
16750
+ for (const key in sourceModule) try {
16751
+ if (!(key in defaultValue)) Object.defineProperty(defaultValue, key, {
16752
+ enumerable: key !== "default",
16753
+ configurable: key !== "default",
16754
+ get() {
16755
+ return sourceModule[key];
16756
+ }
16757
+ });
16758
+ } catch {}
16759
+ return defaultValue;
16760
+ }
16742
16761
  const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
16743
16762
  const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
16744
16763
  const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
@@ -19301,6 +19320,14 @@ function resolveModule(name, options = {}) {
19301
19320
  return;
19302
19321
  }
19303
19322
  }
19323
+ async function importModule(path) {
19324
+ const i = await import(path);
19325
+ if (i) return interopDefault(i);
19326
+ return i;
19327
+ }
19328
+ function isPackageExists(name, options = {}) {
19329
+ return !!resolvePackage(name, options);
19330
+ }
19304
19331
  function getPackageJsonPath(name, options = {}) {
19305
19332
  const entry = resolvePackage(name, options);
19306
19333
  if (!entry) return;
@@ -19359,7 +19386,7 @@ quansync(function* (name, cwd) {
19359
19386
  const pkg = (yield loadPackageJSON(cwd)) || {};
19360
19387
  return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
19361
19388
  }).sync;
19362
- const version$1 = "6.2.0";
19389
+ const version$1 = "6.3.0";
19363
19390
  function configureAddons(opts) {
19364
19391
  const addons = [];
19365
19392
  if (Array.isArray(opts.addons)) addons.push(...opts.addons);
@@ -19455,8 +19482,8 @@ function parseVirtualImportsRegex(strippedCode, importMap, virtualImports) {
19455
19482
  }
19456
19483
  async function detectImports(code, ctx, options) {
19457
19484
  switch (options?.parser) {
19458
- case "acorn": return import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.r).then((r) => r.detectImportsAcorn(code, ctx, options));
19459
- case "oxc": return import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.n).then((r) => r.detectImportsOxc(code, ctx, options));
19485
+ case "acorn": return import("../_libs/unimport+unplugin.mjs").then((n) => n.detect_acorn_exports).then((r) => r.detectImportsAcorn(code, ctx, options));
19486
+ case "oxc": return import("../_libs/unimport+unplugin.mjs").then((n) => n.detect_oxc_exports).then((r) => r.detectImportsOxc(code, ctx, options));
19460
19487
  default: return detectImportsRegex(code, ctx, options);
19461
19488
  }
19462
19489
  }
@@ -19567,7 +19594,8 @@ async function scanFilesFromDir(dir, options) {
19567
19594
  expandDirectories: false
19568
19595
  })).map((i) => normalize$2(i));
19569
19596
  const fileFilter = options?.fileFilter || (() => true);
19570
- const indexOfDirs = (file) => dirGlobs.findIndex((glob2) => import_picomatch.default.isMatch(file, glob2));
19597
+ const dirMatchers = dirGlobs.map((glob2) => (0, import_picomatch.default)(glob2));
19598
+ const indexOfDirs = (file) => dirMatchers.findIndex((match) => match(file));
19571
19599
  return files.reduce((acc, file) => {
19572
19600
  const index = indexOfDirs(file);
19573
19601
  if (acc[index]) acc[index].push(normalize$2(file));
@@ -19578,8 +19606,8 @@ async function scanFilesFromDir(dir, options) {
19578
19606
  async function scanDirExports(dirs, options) {
19579
19607
  const normalizedDirs = normalizeScanDirs(dirs, options);
19580
19608
  const files = await scanFilesFromDir(normalizedDirs, options);
19581
- const includeTypesDirs = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types);
19582
- const isIncludeTypes = (file) => includeTypesDirs.some((dir) => import_picomatch.default.isMatch(file, dir.glob));
19609
+ const includeTypesMatchers = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types).map((dir) => (0, import_picomatch.default)(dir.glob));
19610
+ const isIncludeTypes = (file) => includeTypesMatchers.some((match) => match(file));
19583
19611
  return dedupeDtsExports((await Promise.all(files.map((file) => scanExports(file, isIncludeTypes(file))))).flat());
19584
19612
  }
19585
19613
  function dedupeDtsExports(exports) {
@@ -21104,6 +21132,72 @@ function joinPkgNames(moduleIds) {
21104
21132
  function routeToFsPath(route) {
21105
21133
  return route.split("/").slice(1).map((s) => s.replace(/:(\w+)/g, "[$1]").replace(/\*+/g, "[...]").replace(/[^a-zA-Z0-9_.[\]]/g, "_")).join("/") || "index";
21106
21134
  }
21135
+ function app(nitro) {
21136
+ return {
21137
+ id: "#nitro/virtual/app",
21138
+ template: () => {
21139
+ const hasRoutes = nitro.routing.routes.hasRoutes();
21140
+ const hasRouteRules = nitro.routing.routeRules.hasRoutes();
21141
+ const hasRoutedMiddleware = nitro.routing.routedMiddleware.hasRoutes();
21142
+ const hasGlobalMiddleware = nitro.routing.globalMiddleware.length > 0;
21143
+ const hasPlugins = nitro.options.plugins.length > 0;
21144
+ const hasHooks = nitro.options.features?.runtimeHooks ?? hasPlugins;
21145
+ const hasGetMiddleware = hasRouteRules || hasRoutedMiddleware;
21146
+ const hasAsyncContext = !!nitro.options.experimental.asyncContext;
21147
+ const routingImports = [
21148
+ hasRoutes && "findRoute",
21149
+ hasRoutedMiddleware && "findRoutedMiddleware",
21150
+ hasGlobalMiddleware && "globalMiddleware"
21151
+ ].filter(Boolean);
21152
+ const imports = [];
21153
+ const code = [];
21154
+ imports.push(`import { H3Core } from "h3";`, `import errorHandler from "#nitro/virtual/error-handler";`);
21155
+ code.push(``, `export function createNitroApp() {`);
21156
+ if (hasHooks) {
21157
+ imports.push(`import { HookableCore } from "hookable";`);
21158
+ code.push(` const hooks = new HookableCore();`);
21159
+ }
21160
+ code.push(``, `const captureError = (error, errorCtx) => {`);
21161
+ if (hasHooks) code.push(` const promise = hooks.callHook("error", error, errorCtx)?.catch?.((hookError) => {`, ` console.error("Error while capturing another error", hookError);`, ` });`);
21162
+ code.push(` if (errorCtx?.event) {`, ` const errors = errorCtx.event.req.context?.nitro?.errors;`, ` if (errors) {`, ` errors.push({ error, context: errorCtx });`, ` }`);
21163
+ if (hasHooks) code.push(` if (promise && typeof errorCtx.event.req.waitUntil === "function") {`, ` errorCtx.event.req.waitUntil(promise);`, ` }`);
21164
+ code.push(` }`, ` };`);
21165
+ code.push(``, ` const h3App = createH3App({`, ` onError(error, event) {`);
21166
+ if (hasHooks) code.push(` captureError(error, { event });`);
21167
+ code.push(` return errorHandler(error, event);`, ` },`, ` });`);
21168
+ if (hasHooks) code.push(``, ` h3App.config.onRequest = (event) => {`, ` return hooks.callHook("request", event)?.catch?.((error) => {`, ` captureError(error, { event, tags: ["request"] });`, ` });`, ` };`, ` h3App.config.onResponse = (res, event) => {`, ` return hooks.callHook("response", res, event)?.catch?.((error) => {`, ` captureError(error, { event, tags: ["response"] });`, ` });`, ` };`);
21169
+ code.push(``, ` let appHandler = (req) => {`, ` req.context ||= {};`, ` req.context.nitro = req.context.nitro || { errors: [] };`, ` return h3App.fetch(req);`, ` };`);
21170
+ if (hasAsyncContext) {
21171
+ imports.push(`import { nitroAsyncContext } from "#nitro/runtime/context";`);
21172
+ code.push(``, ` const originalHandler = appHandler;`, ` appHandler = (req) => {`, ` return nitroAsyncContext.callAsync({ request: req }, () => originalHandler(req));`, ` };`);
21173
+ }
21174
+ code.push(``, ` return {`, ` fetch: appHandler,`, ` h3: h3App,`, ` hooks: ${hasHooks ? "hooks" : "undefined"},`, ` captureError,`, ` };`, `}`);
21175
+ code.push(``, `export function initNitroPlugins(app) {`);
21176
+ if (hasPlugins) {
21177
+ imports.push(`import { plugins } from "#nitro/virtual/plugins";`);
21178
+ code.push(` for (const plugin of plugins) {`, ` try {`, ` plugin(app);`, ` } catch (error) {`, ` app.captureError?.(error, { tags: ["plugin"] });`, ` throw error;`, ` }`, ` }`);
21179
+ }
21180
+ code.push(` return app;`, `}`);
21181
+ if (routingImports.length) imports.push(`import { ${routingImports.join(", ")} } from "#nitro/virtual/routing";`);
21182
+ code.push(``, `function createH3App(config) {`, ` const h3App = new H3Core(config);`);
21183
+ if (hasRoutes) code.push(` h3App["~findRoute"] = (event) => findRoute(event.req.method, event.url.pathname);`);
21184
+ if (hasGlobalMiddleware) code.push(` h3App["~middleware"].push(...globalMiddleware);`);
21185
+ if (hasGetMiddleware) {
21186
+ code.push(` h3App["~getMiddleware"] = (event, route) => {`, ` const pathname = event.url.pathname;`, ` const method = event.req.method;`, ` const middleware = [];`);
21187
+ if (hasRouteRules) {
21188
+ imports.push(`import { getRouteRules } from "#nitro/runtime/app";`);
21189
+ code.push(` const routeRules = getRouteRules(method, pathname);`, ` event.context.routeRules = routeRules?.routeRules;`, ` if (routeRules?.routeRuleMiddleware.length) {`, ` middleware.push(...routeRules.routeRuleMiddleware);`, ` }`);
21190
+ }
21191
+ if (hasGlobalMiddleware) code.push(` middleware.push(...h3App["~middleware"]);`);
21192
+ if (hasRoutedMiddleware) code.push(` middleware.push(...findRoutedMiddleware(method, pathname).map((r) => r.data));`);
21193
+ if (hasRoutes) code.push(` if (route?.data?.middleware?.length) {`, ` middleware.push(...route.data.middleware);`, ` }`);
21194
+ code.push(` return middleware;`, ` };`);
21195
+ }
21196
+ code.push(` return h3App;`, `}`);
21197
+ return [...imports, ...code].join("\n");
21198
+ }
21199
+ };
21200
+ }
21107
21201
  function database(nitro) {
21108
21202
  return {
21109
21203
  id: "#nitro/virtual/database",
@@ -21413,10 +21507,11 @@ function routing(nitro) {
21413
21507
  ...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data),
21414
21508
  ...nitro.routing.globalMiddleware
21415
21509
  ], "_importHash");
21510
+ const traceH3 = !!nitro.options.tracingChannel?.h3;
21416
21511
  return `
21417
21512
  import * as __routeRules__ from "#nitro/runtime/route-rules";
21418
21513
  import * as srvxNode from "srvx/node"
21419
- import * as h3 from "h3";
21514
+ import * as h3 from "h3";${traceH3 ? `\nimport { wrapHandlerWithTracing } from "h3/tracing";` : ""}
21420
21515
 
21421
21516
  export const findRouteRules = ${nitro.routing.routeRules.compileToString({
21422
21517
  serialize: serializeRouteRule,
@@ -21433,7 +21528,7 @@ ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "$
21433
21528
 
21434
21529
  ${allHandlers.filter((h) => h.lazy).map((h) => `const ${h._importHash} = h3.defineLazyEventHandler(() => import("${h.handler}")${h.format === "node" ? ".then(m => srvxNode.toFetchHandler(m.default))" : ""});`).join("\n")}
21435
21530
 
21436
- export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
21531
+ export const findRoute = ${nitro.routing.routes.compileToString({ serialize: (h) => serializeHandler(h, { tracing: traceH3 }) })}
21437
21532
 
21438
21533
  export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({
21439
21534
  serialize: serializeHandler,
@@ -21450,13 +21545,14 @@ export const globalMiddleware = [
21450
21545
  function uniqueBy(arr, key) {
21451
21546
  return [...new Map(arr.map((item) => [item[key], item])).values()];
21452
21547
  }
21453
- function serializeHandler(h) {
21548
+ function serializeHandler(h, opts = {}) {
21454
21549
  const meta = Array.isArray(h) ? h[0] : h;
21550
+ const handler = Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h);
21455
21551
  return `{${[
21456
21552
  `route:${JSON.stringify(meta.route)}`,
21457
21553
  meta.method && `method:${JSON.stringify(meta.method)}`,
21458
21554
  meta.meta && `meta:${JSON.stringify(meta.meta)}`,
21459
- `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
21555
+ `handler:${opts.tracing ? `wrapHandlerWithTracing(${handler})` : handler}`
21460
21556
  ].filter(Boolean).join(",")}}`;
21461
21557
  }
21462
21558
  function serializeHandlerFn(h) {
@@ -21640,6 +21736,7 @@ function tracing(nitro) {
21640
21736
  }
21641
21737
  function virtualTemplates(nitro, _polyfills) {
21642
21738
  const nitroTemplates = [
21739
+ app,
21643
21740
  database,
21644
21741
  errorHandler,
21645
21742
  featureFlags,
@@ -27829,7 +27926,7 @@ function unwasm(opts) {
27829
27926
  order: "pre",
27830
27927
  filter: { id: [
27831
27928
  /* @__PURE__ */ new RegExp("^" + escapeRegExp(UMWASM_HELPERS_ID) + "$"),
27832
- /* @__PURE__ */ new RegExp("^" + UNWASM_EXTERNAL_PREFIX),
27929
+ /* @__PURE__ */ new RegExp("^\0unwasm:external:"),
27833
27930
  WASM_ID_RE
27834
27931
  ] },
27835
27932
  async handler(id, importer) {
@@ -28187,10 +28284,11 @@ function externals(opts) {
28187
28284
  if (exclude.some((r) => r.test(id))) return false;
28188
28285
  return true;
28189
28286
  };
28287
+ const resolveConditions = opts.conditions.includes("import") ? opts.conditions : [...opts.conditions, "import"];
28190
28288
  const tryResolve = (id, from) => resolveModulePath(id, {
28191
28289
  try: true,
28192
28290
  from: from && isAbsolute$2(from) ? from : opts.rootDir,
28193
- conditions: opts.conditions
28291
+ conditions: resolveConditions
28194
28292
  });
28195
28293
  const tracedPaths = /* @__PURE__ */ new Set();
28196
28294
  if (opts.trace && !resolved?.includePattern) return { name: PLUGIN_NAME };
@@ -28222,7 +28320,7 @@ function externals(opts) {
28222
28320
  let importId = toImport(id) || toImport(resolvedPath);
28223
28321
  if (!importId) return resolved;
28224
28322
  if (!tryResolve(importId, importer)) {
28225
- const guessed = await guessSubpath(resolvedPath, opts.conditions);
28323
+ const guessed = await guessSubpath(resolvedPath, resolveConditions);
28226
28324
  if (!guessed) return resolved;
28227
28325
  importId = guessed;
28228
28326
  }
@@ -28349,7 +28447,7 @@ async function baseBuildPlugins(nitro, base) {
28349
28447
  nitro.vfs = virtualPlugin.api.modules;
28350
28448
  plugins.push(virtualPlugin, virtualDeps());
28351
28449
  if (nitro.options.imports) {
28352
- const unimportPlugin = await import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.t);
28450
+ const unimportPlugin = await import("../_libs/unimport+unplugin.mjs").then((n) => n.unplugin_exports);
28353
28451
  plugins.push(unimportPlugin.default.rollup(nitro.options.imports));
28354
28452
  }
28355
28453
  if (nitro.options.wasm !== false) plugins.push(unwasm(nitro.options.wasm || {}));
@@ -28400,4 +28498,4 @@ async function oxc(options) {
28400
28498
  }
28401
28499
  };
28402
28500
  }
28403
- export { yaml_exports as $, src_default as A, _$2 as B, decode as C, copyPublicAssets as D, prepare as E, prettyPath as F, findFile$1 as G, m$2 as H, resolveNitroPath as I, readGitConfig as J, findNearestFile$1 as K, writeFile$1 as L, glob as M, require_picomatch as N, scanUnprefixedPublicAssets as O, Builder as P, a$3 as Q, escapeRegExp$1 as R, MagicString as S, parse as T, v$2 as U, f$1 as V, dist_exports$1 as W, i$3 as X, readPackageJSON$1 as Y, toml_exports as Z, writeTypes as _, dataToEsm as a, basename$2 as at, getMagicString as b, walk as c, isAbsolute$2 as ct, libChunkName as d, relative$2 as dt, jsonc_exports as et, baseBuildConfig as f, resolve$3 as ft, writeDevBuildInfo as g, writeBuildInfo as h, createFilter as i, resolveModuleURL as it, build as j, compressPublicAssets as k, NODE_MODULES_RE$1 as l, join$2 as lt, getBuildInfo as m, baseBuildPlugins as n, json5_exports as nt, extractAssignedNames as o, dirname$2 as ot, runParallel as p, findWorkspaceDir as q, attachScopes as r, resolveModulePath as rt, makeLegalIdentifier as s, extname$4 as st, oxc as t, r$5 as tt, getChunkName as u, normalize$2 as ut, dist_exports as v, encode as w, stripLiteral as x, createUnimport as y, R$1 as z };
28501
+ export { Builder, MagicString, NODE_MODULES_RE$1 as NODE_MODULES_RE, R$1 as R, _$2 as _, a$3 as a, attachScopes, baseBuildConfig, baseBuildPlugins, basename$2 as basename, build, compressPublicAssets, copyPublicAssets, createFilter, createUnimport, dataToEsm, decode, dirname$2 as dirname, dist_exports, encode, escapeRegExp$1 as escapeRegExp, extname$4 as extname, extractAssignedNames, f$1 as f, findFile$1 as findFile, findNearestFile$1 as findNearestFile, findWorkspaceDir, getBuildInfo, getChunkName, getMagicString, glob, i$3 as i, importModule, isAbsolute$2 as isAbsolute, isPackageExists, join$2 as join, json5_exports, jsonc_exports, libChunkName, m$2 as m, makeLegalIdentifier, normalize$2 as normalize, oxc, parse, prepare, prettyPath, r$5 as r, readGitConfig, readPackageJSON$1 as readPackageJSON, relative$2 as relative, require_picomatch, resolve$3 as resolve, resolveModulePath, resolveModuleURL, resolveNitroPath, runParallel, scanUnprefixedPublicAssets, src_default, stripLiteral, toml_exports, v$2 as v, walk, writeBuildInfo, writeDevBuildInfo, writeFile$1 as writeFile, writeTypes, yaml_exports };
@@ -1,9 +1,9 @@
1
- import { _ as writeTypes, at as basename, d as libChunkName, dt as relative, f as baseBuildConfig, h as writeBuildInfo, l as NODE_MODULES_RE, lt as join, n as baseBuildPlugins, u as getChunkName } from "./common.mjs";
2
- import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
3
- import { n as scanHandlers } from "../_chunks/nitro2.mjs";
4
- import { n as watch } from "../_libs/readdirp+chokidar.mjs";
5
- import { t as debounce } from "../_libs/perfect-debounce.mjs";
6
- import { n as generateFSTree } from "../_chunks/utils.mjs";
1
+ import { NODE_MODULES_RE, baseBuildConfig, baseBuildPlugins, basename, getChunkName, join, libChunkName, relative, writeBuildInfo, writeTypes } from "./common.mjs";
2
+ import { formatCompatibilityDate } from "../_libs/compatx.mjs";
3
+ import { scanHandlers } from "../_chunks/nitro.mjs";
4
+ import { watch } from "../_libs/readdirp+chokidar.mjs";
5
+ import { debounce } from "../_libs/perfect-debounce.mjs";
6
+ import { generateFSTree } from "../_chunks/utils.mjs";
7
7
  import { builtinModules } from "node:module";
8
8
  import { defu } from "defu";
9
9
  const getRolldownConfig = async (nitro) => {
@@ -1,14 +1,14 @@
1
- import { _ as writeTypes, at as basename, ct as isAbsolute, d as libChunkName, dt as relative, f as baseBuildConfig, h as writeBuildInfo, l as NODE_MODULES_RE, lt as join, n as baseBuildPlugins, t as oxc, u as getChunkName } from "./common.mjs";
2
- import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
3
- import { n as scanHandlers } from "../_chunks/nitro2.mjs";
4
- import { n as watch } from "../_libs/readdirp+chokidar.mjs";
5
- import { t as debounce } from "../_libs/perfect-debounce.mjs";
6
- import { t as alias } from "../_libs/plugin-alias.mjs";
7
- import { n as inject } from "../_libs/plugin-inject.mjs";
8
- import { n as generateFSTree } from "../_chunks/utils.mjs";
9
- import { t as commonjs } from "../_libs/commondir+is-reference.mjs";
10
- import { t as json } from "../_libs/plugin-json.mjs";
11
- import { t as nodeResolve } from "../_libs/hasown+resolve+deepmerge.mjs";
1
+ import { NODE_MODULES_RE, baseBuildConfig, baseBuildPlugins, basename, getChunkName, isAbsolute, join, libChunkName, oxc, relative, writeBuildInfo, writeTypes } from "./common.mjs";
2
+ import { formatCompatibilityDate } from "../_libs/compatx.mjs";
3
+ import { scanHandlers } from "../_chunks/nitro.mjs";
4
+ import { watch } from "../_libs/readdirp+chokidar.mjs";
5
+ import { debounce } from "../_libs/perfect-debounce.mjs";
6
+ import { alias } from "../_libs/plugin-alias.mjs";
7
+ import { inject } from "../_libs/plugin-inject.mjs";
8
+ import { generateFSTree } from "../_chunks/utils.mjs";
9
+ import { commonjs } from "../_libs/commondir+is-reference.mjs";
10
+ import { json } from "../_libs/plugin-json.mjs";
11
+ import { nodeResolve } from "../_libs/hasown+resolve+deepmerge.mjs";
12
12
  import { defu } from "defu";
13
13
  const getRollupConfig = async (nitro) => {
14
14
  const base = baseBuildConfig(nitro);
@@ -1,12 +1,12 @@
1
- import { U as v } from "./common.mjs";
1
+ import { resolveModulePath, v } from "./common.mjs";
2
2
  import { nitro } from "nitro/vite";
3
3
  async function viteBuild(nitro$1) {
4
4
  if (nitro$1.options.dev) throw new Error("Nitro dev CLI does not supports vite. Please use `vite dev` instead.");
5
- const { createBuilder } = await import(nitro$1.options.__vitePkg__ || "vite");
5
+ const { createBuilder } = await import(resolveModulePath(nitro$1.options.__vitePkg__ || "vite", { from: nitro$1.options.rootDir }));
6
6
  const pluginInstance = nitro({ _nitro: nitro$1 });
7
7
  globalThis.__nitro_build__ = true;
8
8
  const builder = await createBuilder({
9
- base: nitro$1.options.rootDir,
9
+ root: nitro$1.options.rootDir,
10
10
  plugins: [pluginInstance],
11
11
  logLevel: v ? "warn" : void 0
12
12
  });
@@ -0,0 +1,149 @@
1
+ import { join } from "./common.mjs";
2
+ import { scanHandlers } from "../_chunks/nitro.mjs";
3
+ import { watch as watch$1 } from "../_libs/readdirp+chokidar.mjs";
4
+ import { debounce } from "../_libs/perfect-debounce.mjs";
5
+ import { getEnvRunner } from "./vite.env.mjs";
6
+ import { watch } from "node:fs";
7
+ import { withBase } from "ufo";
8
+ import { NodeRequest, sendNodeResponse } from "srvx/node";
9
+ import "node:http";
10
+ import { DevEnvironment } from "vite";
11
+ import { createViteHotChannel } from "env-runner/vite";
12
+ const ASSET_EXT_RE = /^(?:[jt]sx?|mjs|cjs|css|s[ac]ss|less|styl|vue|svelte|astro|mdx?|map|wasm|png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp[34]|webm|wav|ogg|m4a)$/i;
13
+ function createFetchableDevEnvironment(name, config, devServer, entry, opts) {
14
+ return new FetchableDevEnvironment(name, config, {
15
+ hot: true,
16
+ transport: createViteHotChannel(devServer, name)
17
+ }, devServer, entry, opts);
18
+ }
19
+ var FetchableDevEnvironment = class extends DevEnvironment {
20
+ devServer;
21
+ #entry;
22
+ #preventExternalize;
23
+ constructor(name, config, context, devServer, entry, opts) {
24
+ super(name, config, context);
25
+ this.devServer = devServer;
26
+ this.#entry = entry;
27
+ this.#preventExternalize = opts?.preventExternalize ?? false;
28
+ }
29
+ async fetchModule(id, importer, options) {
30
+ if (this.#preventExternalize && !id.startsWith("file://") && importer && id[0] !== "." && id[0] !== "/") {
31
+ const resolved = await this.pluginContainer.resolveId(id, importer);
32
+ if (resolved && !resolved.external) return super.fetchModule(resolved.id, importer, options);
33
+ }
34
+ return super.fetchModule(id, importer, options);
35
+ }
36
+ async dispatchFetch(request) {
37
+ return this.devServer.fetch(request);
38
+ }
39
+ async init(...args) {
40
+ await this.devServer.init?.();
41
+ await super.init(...args);
42
+ this.devServer.sendMessage({
43
+ type: "custom",
44
+ event: "nitro:vite-env",
45
+ data: {
46
+ name: this.name,
47
+ entry: this.#entry
48
+ }
49
+ });
50
+ }
51
+ };
52
+ async function configureViteDevServer(ctx, server) {
53
+ const nitro = ctx.nitro;
54
+ const nitroEnv = server.environments.nitro;
55
+ const nitroConfigFile = nitro.options._c12.configFile;
56
+ if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile);
57
+ if (nitro.options.features.websocket ?? nitro.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => {
58
+ if (req.headers["sec-websocket-protocol"]?.startsWith("vite-")) return;
59
+ getEnvRunner(ctx).upgrade?.({ node: {
60
+ req,
61
+ socket,
62
+ head
63
+ } });
64
+ });
65
+ const reload = debounce(async () => {
66
+ await scanHandlers(nitro);
67
+ nitro.routing.sync();
68
+ nitroEnv.moduleGraph.invalidateAll();
69
+ nitroEnv.hot.send({ type: "full-reload" });
70
+ });
71
+ const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
72
+ join(dir, nitro.options.apiDir || "api"),
73
+ join(dir, nitro.options.routesDir || "routes"),
74
+ join(dir, "middleware"),
75
+ join(dir, "plugins"),
76
+ join(dir, "modules")
77
+ ]);
78
+ const watchReloadEvents = new Set([
79
+ "add",
80
+ "addDir",
81
+ "unlink",
82
+ "unlinkDir"
83
+ ]);
84
+ const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path, stat) => {
85
+ if (watchReloadEvents.has(event)) reload();
86
+ });
87
+ const rootDirWatcher = watch(nitro.options.rootDir, { persistent: false }, (_event, filename) => {
88
+ if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
89
+ });
90
+ nitro.hooks.hook("close", () => {
91
+ scanDirsWatcher.close();
92
+ rootDirWatcher.close();
93
+ });
94
+ nitroEnv.devServer.onMessage(async (message) => {
95
+ if (message?.__rpc === "transformHTML") try {
96
+ const html = (await server.transformIndexHtml("/", message.data)).replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`);
97
+ nitroEnv.devServer.sendMessage({
98
+ __rpc_id: message.__rpc_id,
99
+ data: html
100
+ });
101
+ } catch (error) {
102
+ nitroEnv.devServer.sendMessage({
103
+ __rpc_id: message.__rpc_id,
104
+ error: error instanceof Error ? error.message : String(error)
105
+ });
106
+ }
107
+ });
108
+ const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
109
+ if (!nodeReq.url || /^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled || server.middlewares.stack.map((mw) => mw.route).some((base) => base && nodeReq.url.startsWith(base))) return next();
110
+ nodeReq._nitroHandled = true;
111
+ const baseURL = nitro.options.baseURL || "/";
112
+ const originalURL = nodeReq.url;
113
+ if (baseURL !== "/") nodeReq.url = withBase(nodeReq.url, baseURL);
114
+ try {
115
+ const req = new NodeRequest({
116
+ req: nodeReq,
117
+ res: nodeRes
118
+ });
119
+ const devAppRes = await ctx.devApp.fetch(req);
120
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
121
+ if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes);
122
+ const envRes = await nitroEnv.dispatchFetch(req);
123
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
124
+ return await sendNodeResponse(nodeRes, envRes);
125
+ } catch (error) {
126
+ return next(error);
127
+ } finally {
128
+ if (baseURL !== "/") nodeReq.url = originalURL;
129
+ }
130
+ };
131
+ server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
132
+ if (/^\/(?:__|@)/.test(req.url)) return next();
133
+ const match = nitro.routing.routes.match(req.method || "", new URL(withBase(req.url, nitro.options.baseURL), "http://localhost").pathname);
134
+ const matchedHandlers = match ? Array.isArray(match) ? match : [match] : [];
135
+ if (matchedHandlers.some((h) => h?.route && h.route !== "/**" && !h.route.startsWith("/**:"))) return nitroDevMiddleware(req, res, next);
136
+ res.setHeader("vary", "sec-fetch-dest, accept");
137
+ const fetchDest = req.headers["sec-fetch-dest"];
138
+ const ext = req.url.split(/[?#]/, 1)[0].match(/\.([a-z0-9]+)$/i)?.[1];
139
+ const isAssetByExt = !!ext && ASSET_EXT_RE.test(ext) && !/\btext\/html\b/.test(req.headers["accept"] || "");
140
+ const isAsset = typeof fetchDest === "string" && fetchDest !== "empty" ? !/^(?:document|iframe|frame)$/.test(fetchDest) : isAssetByExt;
141
+ if (!isAsset && (matchedHandlers.length > 0 || !ext)) return nitroDevMiddleware(req, res, next);
142
+ if (isAsset) req._nitroHandled = true;
143
+ next();
144
+ });
145
+ return () => {
146
+ server.middlewares.use(nitroDevMiddleware);
147
+ };
148
+ }
149
+ export { configureViteDevServer, createFetchableDevEnvironment };