@nuxt/nitro-server4.6.477.7 kB
import { performance } from "node:perf_hooks";
import { fileURLToPath, pathToFileURL } from "node:url";
import { existsSync, mkdirSync, promises, readFileSync, writeFileSync } from "node:fs";
import { cpus } from "node:os";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { addRoute, createRouter, findAllRoutes, routeNodeKeys } from "rou3";
import { compileRouterToString } from "rou3/compiler";
import { dirname, isAbsolute, join, normalize, relative, resolve } from "pathe";
import { joinURL, withTrailingSlash, withoutTrailingSlash } from "ufo";
import nuxtPkg from "nuxt/package.json" with { type: "json" };
import { build, copyPublicAssets, createDevServer, createNitro, prepare, prerender, writeTypes } from "nitropack";
import { addPlugin, addTemplate, addTypeTemplate, addVitePlugin, ensureDependencyInstalled, findPath, getAddDependencyCommand, getDirectory, getLayerDirectories, logger, resolveAlias, resolveIgnorePatterns, resolveNuxtModule, resolveTypePaths } from "@nuxt/kit";
import { bundlerDiagnostics, getServerRuntime, kServerApi, setServerBuild } from "@nuxt/kit/internal";
import escapeRE from "escape-string-regexp";
import { defu } from "defu";
import { defineEventHandler, dynamicEventHandler, getRequestHeader, getRequestHost, getRequestIP, getRequestProtocol, getRequestURL, handleCors, readRawBody, setHeader, setResponseStatus } from "h3";
import { isWindows } from "std-env";
import { rou3PatternToURLPattern } from "unrouting";
import { ImpoundPlugin } from "impound";
import { resolveModulePath } from "exsolve";
import { runtimeDependencies } from "nitropack/runtime/meta";
import { matchesGlob } from "node:path";
import { isLoopbackAddress } from "nuxt/internal/dev/peer";
// package.json
var version = "4.6.4";
// src/utils.ts
const TEMPLATE_PARAM_RE = /\{\{ ?([\w.]+) ?\}\}/g;
/**
* Resolve the `{{ path.to.option }}` placeholders in a Nitro command against the Nitro
* options, as paths relative to the output directory the command runs in.
*/
function resolveNitroCommand(command, options) {
if (!command?.includes("{{")) return command;
return command.replace(TEMPLATE_PARAM_RE, (_, key) => {
const value = key.split(".").reduce((obj, segment) => obj?.[segment], options);
return typeof value === "string" && value ? relative(options.output.dir, value) || "." : key;
});
}
function toArray(value) {
return Array.isArray(value) ? value : [value];
}
const NUXT_DIST_RE = /\/node_modules\/nuxt(?:3|-nightly)?\/dist\//;
function isNuxtDistId(id) {
return NUXT_DIST_RE.test(normalize(id));
}
const NODE_MODULES_RE = /\/node_modules\//g;
/**
* Build the regex Nitro uses to skip transforming files under `node_modules`,
* while still transforming files that belong to layers that happen to live
* inside a `node_modules` directory.
*
* Layer paths can contain multiple `/node_modules/` segments (nested npm
* installs; pnpm's `.pnpm/<id>/node_modules/<name>` store). The exclude
* pattern is `node_modules/(?!<alts>)` evaluated at every `node_modules/`
* boundary, so we push the suffix at each boundary to make the lookahead
* fail wherever the layer's own files live.
*/
function getLayerNodeModulesExcludePattern(layerRoots) {
const excludePaths = [];
for (const layerRoot of layerRoots) {
const root = layerRoot.replace(/\/$/, "");
NODE_MODULES_RE.lastIndex = 0;
let match;
while (match = NODE_MODULES_RE.exec(root)) {
const suffix = root.slice(match.index + match[0].length);
if (suffix) excludePaths.push(escapeRE(suffix));
NODE_MODULES_RE.lastIndex = match.index + 1;
}
}
return excludePaths.length ? new RegExp(`node_modules\\/(?!${excludePaths.join("|")})`) : /node_modules/;
}
/**
* Convert a `build.transpile` entry into a Nitro `externals.inline` entry. An absolute
* directory matches its own files but not the dependencies installed beneath it.
*/
function toTranspileNoExternal(entry) {
if (!isAbsolute(entry)) return entry;
const dir = escapeRE(normalize(entry)).replace(/\//g, "[\\\\/]");
return new RegExp(`^${dir}(?!.*[\\\\/]node_modules[\\\\/])`);
}
/**
* Convert Nuxt's gitignore-style ignore patterns into globs for the unstorage `fs` driver,
* which matches them against the absolute path of a directory it walks into and against the
* bare name of a file it lists, so a pattern has to be written to match both.
*
* 1. A gitignore pattern without a slash matches at any depth, so it is prefixed with `**\/`,
* which matches an absolute path and a bare name alike.
* 2. A pattern containing a slash is anchored, so it is resolved against `base`. Such a
* pattern can only prune a directory, as a file is matched by name alone.
* 3. A trailing slash (directory-only) has no meaning.
* 4. Re-inclusion cannot be expressed in a flat list of globs at all, we drop whatever
* a negated pattern would 'undo'.
*
* Rules are order-sensitive (the last one to match a path wins), so a negated pattern
* only drops the patterns declared before it.
*/
function toFsDriverIgnorePatterns(patterns, base) {
const globs = [];
for (const pattern of patterns) {
const negated = pattern[0] === "!";
const glob = toFsDriverGlob(negated ? pattern.slice(1) : pattern, base);
if (!glob) continue;
if (!negated) {
if (!globs.includes(glob)) globs.push(glob);
continue;
}
for (let i = globs.length - 1; i >= 0; i--) {
const ignored = globs[i];
if (matchesGlob(glob, ignored) || matchesGlob(ignored, glob)) globs.splice(i, 1);
}
}
return globs;
}
function toFsDriverGlob(pattern, base) {
const trimmed = pattern.replace(/\/+$/, "");
if (trimmed.startsWith("**/")) return trimmed;
const glob = trimmed.replace(/^\//, "");
if (!glob || glob.startsWith("../")) return;
return trimmed.includes("/") ? join(base, glob) : `**/${glob}`;
}
let _distDir = dirname(fileURLToPath(import.meta.url));
if (/(?:chunks|shared)$/.test(_distDir)) _distDir = dirname(_distDir);
const distDir = _distDir;
// src/dev-request.ts
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"[::1]",
"::1"
]);
/** Whether the connected peer is a loopback address. */
function isLoopbackPeer(event) {
return isLoopbackAddress(getRequestIP(event));
}
/**
* Header-based same-origin/allowed-host gate shared by dev-only handlers.
*
* A request with no `Sec-Fetch-Site`, `Origin` or `Referer` cannot be a
* cross-site browser request, so it is treated as local; this is the deliberate
* CSRF behaviour relied on by other dev handlers. Endpoints that disclose
* sensitive local state to non-browser clients must additionally require
* {@link isLoopbackPeer}, since these headers are all attacker-controlled over a
* direct connection.
*/
function isLocalDevRequest(event, allowedHosts) {
const hostHeader = getRequestHeader(event, "host");
if (allowedHosts !== true) {
const host = hostHeader?.split(":")[0];
if (!host || !allowedHosts.has(host)) return false;
}
const site = getRequestHeader(event, "sec-fetch-site");
if (site !== void 0) return site === "same-origin" || site === "none";
const initiator = getRequestHeader(event, "origin") || getRequestHeader(event, "referer");
if (!initiator) return true;
try {
return new URL(initiator).host === hostHeader;
} catch {
return false;
}
}
// src/templates/spa-loading-icon.ts
const template = () => {
return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" fill=\"none\" class=\"nuxt-spa-loading\" viewBox=\"0 0 37 25\"><path d=\"M24.236 22.006h10.742L25.563 5.822l-8.979 14.31a4 4 0 0 1-3.388 1.874H2.978l11.631-20 5.897 10.567\"/></svg><style>.nuxt-spa-loading{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)}.nuxt-spa-loading>path{fill:none;stroke:#00dc82;stroke-width:4px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:128;stroke-dashoffset:128px;animation:nuxt-spa-loading-move 3s linear infinite}@keyframes nuxt-spa-loading-move{to{stroke-dashoffset:-128px}}</style>";
};
// ../nuxt/src/core/plugins/import-protection.ts
function createImportProtectionPatterns(nuxt, options) {
const patterns = [];
const context = contextFlags[options.context];
patterns.push([
/^(nuxt|nuxt3|nuxt-nightly)$/,
`\`nuxt\` or \`nuxt-nightly\` cannot be imported directly in ${context}.`,
options.context === "nuxt-app" ? ["Import runtime Nuxt composables from `#app` or `#imports` instead."] : ["Use `#app` or `#imports` for runtime composables in your Vue app code."]
]);
patterns.push([
/^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/,
"Importing directly from a `nuxt.config` file is not allowed.",
[
"Use `useRuntimeConfig()` to access runtime config in your app.",
"Use `useAppConfig()` to access config that doesn't need to be changed at runtime.",
"Use a Nuxt module to access build-time configuration."
]
]);
patterns.push([/(^|node_modules\/)@vue\/composition-api/]);
for (const mod of nuxt.options._installedModules) if (mod.entryPath) patterns.push([
new RegExp(`^${escapeRE(mod.entryPath)}$`),
"Importing directly from module entry-points is not allowed.",
["Import from the module's runtime directory instead (e.g. `my-module/runtime/...`)."]
]);
for (const i of [
/(^|node_modules\/)@nuxt\/(kit|test-utils)/,
/(^|node_modules\/)@nuxt\/cli(?:-nightly)?(?:$|\/)(?!runtime\/)/,
/(^|node_modules\/)nuxi/,
/(^|node_modules\/)nitropack(?:-nightly)?(?:$|\/)(?!(?:dist\/)?(?:node_modules|presets|runtime|types))/,
/(^|node_modules\/)nitro(?:-nightly)?\/(builder|meta|vite|tsconfig)/,
/(^|node_modules\/)nuxt\/(config|kit|schema)/
]) patterns.push([
i,
`This module cannot be imported in ${context}.`,
["These are build-time only packages and cannot be used at runtime."]
]);
if (options.context === "nitro-app" || options.context === "shared") for (const i of ["#app", /^#build(\/|$)/]) patterns.push([
i,
`Vue app aliases are not allowed in ${context}.`,
["Move this code to your Vue app directory or use a shared utility."]
]);
if (options.context === "nuxt-app" || options.context === "shared") {
const serverRelative = escapeRE(relative(nuxt.options.rootDir, resolve(nuxt.options.srcDir, nuxt.options.serverDir || "server")));
patterns.push([
new RegExp("^" + serverRelative + "\\/(api|routes|middleware|plugins)\\/"),
`Importing from server is not allowed in ${context}.`,
["Use `$fetch()` or `useFetch()` to fetch data from server routes.", "Move shared logic to the `shared/` directory."]
]);
patterns.push([
/^#server(\/|$)/,
`Server aliases are not allowed in ${context}.`,
["Use `$fetch()` or `useFetch()` to call server endpoints.", "Move shared logic to the `shared/` directory."]
]);
patterns.push([
/^nuxt\/(?:server|internal\/server-app-config)$/,
`\`nuxt/server\` cannot be imported in ${context}.`,
["Import runtime Nuxt composables from `#app` or `#imports` instead.", "Use `$fetch()` or `useFetch()` to call server endpoints."]
]);
}
return patterns;
}
const contextFlags = {
"nitro-app": "server runtime",
"nuxt-app": "the Vue part of your app",
"shared": "the #shared directory"
};
// ../nuxt/src/core/utils/index.ts
/**
* Decode a route path for route-rule matching, returning it unchanged if it is not
* percent-encoded or cannot be decoded. Reserved characters (`%2F`, `%3F`, …) are
* left encoded, so decoding cannot introduce additional path segments. Only the path
* portion is decoded; a query string, if present, is left untouched to avoid
* double-decoding it.
*/
function decodeRoutePath(path) {
if (!path.includes("%")) return path;
const queryIndex = path.indexOf("?");
const pathname = queryIndex === -1 ? path : path.slice(0, queryIndex);
try {
return queryIndex === -1 ? decodeURI(pathname) : decodeURI(pathname) + path.slice(queryIndex);
} catch {
return path;
}
}
/**
* Case-fold a decoded route path so that two paths fold to the same text exactly when a
* case-insensitive vue-router route (a regex with the `i` flag but not `u`) treats them as
* equal: each UTF-16 code unit is folded to the lower-case form of its upper-case form.
*/
function foldRouteCase(path) {
return path.replace(/[A-Z]+|[^\0-\x7F]/g, (char) => {
if (char.charCodeAt(0) < 128) return char.toLowerCase();
const upper = char.toUpperCase();
if (upper.length !== 1 || upper.charCodeAt(0) < 128) return char;
const lower = upper.toLowerCase();
return lower.length === 1 && lower.toUpperCase() === upper ? lower : upper;
});
}
/**
* Collect the route rules `match` returns for a route path and, if its path portion contains
* an encoded slash (`%2F`), for the path with each encoded slash as a separator, since a page
* route param spanning several segments decodes to the same value either way. Rules keep the
* order `match` returns them in, and rules matched only through encoded slashes come last.
*
* Inlined by source into compiled matchers, so it must not reference anything outside itself.
*
* @internal
*/
function matchAllRouteRules(match, path) {
const matches = match(path);
if (typeof path !== "string") return matches;
const split = path.replace(/^[^?]*/, (pathname) => pathname.replace(/%2f/gi, "/"));
if (split === path) return matches;
for (const rules of match(split)) if (!matches.includes(rules)) matches.push(rules);
return matches;
}
/**
* Resolve the `.` and `..` segments of a route path, including their percent-encoded
* spellings (`%2e`), as a URL parser does. Only the path portion is resolved; a query
* string, if present, is left untouched.
*/
function resolveRoutePathDotSegments(path) {
const queryIndex = path.indexOf("?");
const pathname = queryIndex === -1 ? path : path.slice(0, queryIndex);
if (!/(?:^|\/)(?:\.|%2e)/i.test(pathname)) return path;
const input = pathname.split("/");
const output = [];
const root = pathname.startsWith("/") ? 1 : 0;
for (const [i, segment] of input.entries()) {
const dots = /^(?:\.|%2e)(\.|%2e)?$/i.exec(segment);
if (!dots) {
output.push(segment);
continue;
}
if (dots[1] && output.length > root) output.pop();
if (i === input.length - 1) output.push("");
}
const resolved = output.join("/");
return queryIndex === -1 ? resolved : resolved + path.slice(queryIndex);
}
// ../nuxt/src/core/utils/route-rules.ts
/**
* Normalise a route-rule key or lookup path: resolve `.` and `..` segments, decode
* percent-encoding, then case-fold (see {@link foldRouteCase}) when `fold` is set. Keys are
* matched in decoded form so that a rule may be authored either decoded (`/测试`, the usual
* case) or encoded (`/%E6%B5%8B%E8%AF%95`, the form the page route and the request path take). Dot segments
* are resolved before decoding, so a double-encoded `%252e` stays a literal segment.
* Decoding must precede case folding, or a percent-encoded non-ASCII character would never
* fold.
*
* @internal
*/
function normalizeRouteRulePath(path, fold) {
const decoded = decodeRoutePath(resolveRoutePathDotSegments(path));
return fold ? foldRouteCase(decoded) : decoded;
}
/**
* Normalise a route-rule key as {@link normalizeRouteRulePath} does, except for its regex
* constraints (`:id(\\D+)`), which are never folded, and in which a percent-encoded character
* decodes to a literal match of that character rather than to regex syntax.
*
* @internal
*/
function normalizeRouteRuleKey(key, fold) {
return splitRouteConstraints(key).map((part) => part.constraint ? decodeRouteConstraint(part.text) : normalizeRouteRulePath(part.text, fold)).join("");
}
const ENCODED_RUN_RE = /(?:%[\da-f]{2})+/gi;
const REGEX_SYNTAX_RE = /[\\^$.*+?()[\]{}|-]/g;
function decodeRouteConstraint(constraint) {
return constraint.replace(ENCODED_RUN_RE, (encoded) => decodeRoutePath(encoded).replace(REGEX_SYNTAX_RE, "\\$&"));
}
function splitRouteConstraints(pattern) {
const parts = [];
let start = 0;
let depth = 0;
let inClass = false;
for (let i = 0; i < pattern.length; i++) {
const char = pattern[i];
if (char === "\\") {
i++;
continue;
}
if (depth === 0) {
if (char === "(") {
parts.push({
text: pattern.slice(start, i),
constraint: false
});
start = i;
depth = 1;
}
continue;
}
if (inClass) inClass = char !== "]";
else if (char === "[") inClass = true;
else if (char === "(") depth++;
else if (char === ")" && --depth === 0) {
parts.push({
text: pattern.slice(start, i + 1),
constraint: true
});
start = i + 1;
}
}
parts.push({
text: pattern.slice(start),
constraint: depth > 0
});
return parts;
}
/**
* Expand `appMiddleware` given as a name or a list of names into the record the server
* runtime accepts. Matching entries are replaced, not mutated.
*
* @internal
*/
function normalizeAppMiddlewareRules(routeRules) {
for (const route in routeRules) {
const appMiddleware = routeRules[route]?.appMiddleware;
if (typeof appMiddleware !== "string" && !Array.isArray(appMiddleware)) continue;
routeRules[route] = {
...routeRules[route],
appMiddleware: Object.fromEntries([appMiddleware].flat().map((name) => [name, true]))
};
}
}
/**
* Resolve the route rules that apply to `path`, merged most-specific-last.
*
* The router is expected to have been built with keys normalised by
* {@link normalizeRouteRuleKey} under the same `fold`, so that lookups match them.
*
* @internal
*/
function resolveRouteRules(router, path, fold) {
return defu({}, ...matchAllRouteRules((path) => router.matchAll("", normalizeRouteRulePath(path, fold)), path).reverse());
}
/**
* Build a route-rules router: patterns are registered under `baseURL`, and a lookup resolves
* every pattern it matches, least specific first.
*
* @internal
*/
function createRouteRulesRouter(routes, baseURL) {
const base = baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL;
const router = createRouter();
for (const route of routes) addRoute(router, route.method || "", base + route.route, route.data);
return {
routes,
matchAll: (method, path) => findAllRoutes(router, method, path).map((route) => route.data),
compileToString(options) {
if (base || routes.length !== 1 || routes[0].route !== "/**" || !!routes[0].method) return compileRouterToString(router, void 0, options);
const data = (options?.serialize || JSON.stringify)(routes[0].data);
const match = `{data,params:{"_":p.slice(1)}}`;
return `/* @__PURE__ */ (() => {const data=${data};return ((_m, p)=>(${options?.matchAll ? `[${match}]` : match}));})()`;
}
};
}
/**
* Source of the `normalizePath` and `matchAllRouteRules` helpers a compiled matcher looks rules
* up through: `decodeRoutePath`, `resolveRoutePathDotSegments`, `foldRouteCase` and
* `matchAllRouteRules` are inlined by source so that the runtime lookup and the build-time key
* normalisation cannot drift apart.
*
* @internal
*/
const normalizePathCode = [
`const decodeRoutePath = ${decodeRoutePath.toString()}`,
`const resolveRoutePathDotSegments = ${resolveRoutePathDotSegments.toString()}`,
`const foldRouteCase = ${foldRouteCase.toString()}`,
`const matchAllRouteRules = ${matchAllRouteRules.toString()}`,
`const normalizePath = (path, fold) => {`,
` if (typeof path !== 'string') { return path }`,
` const decoded = decodeRoutePath(resolveRoutePathDotSegments(path))`,
` return fold ? foldRouteCase(decoded) : decoded`,
`}`
].join("\n");
/**
* Build a route-rules router whose keys are normalised by {@link normalizeRouteRuleKey},
* mirroring the normalised lookup path used at runtime.
*
* `onDuplicate` is called when two distinct keys normalise onto the same path; the later
* key wins.
*
* @internal
*/
function createNormalizedRouteRulesRouter(routes, baseURL, fold, onDuplicate) {
const normalizedKeys = /* @__PURE__ */ new Map();
return createRouteRulesRouter(routes.map((route) => {
if (typeof route.route !== "string") return route;
const key = normalizeRouteRuleKey(route.route, fold);
const existing = normalizedKeys.get(key);
if (existing !== void 0 && existing !== route.route) onDuplicate?.(existing, route.route, key);
normalizedKeys.set(key, route.route);
return {
...route,
route: key
};
}), normalizeRouteRulePath(String(baseURL || ""), fold));
}
// src/route-rules.ts
const DYNAMIC_SEGMENT_RE = /^(?::[$\w]+|\*)$/;
function conflictsWithin(segments, name, index) {
return segments.some((segment, i) => i !== index && segment.match(/^:([$\w]+)/)?.[1] === name && (i < index || !DYNAMIC_SEGMENT_RE.test(segment)));
}
/**
* Rename dynamic segments in route rule keys, in place, so sibling segments share a single name.
* `radix3` keys dynamic segments without their placeholder name, so `/:slug/about` and
* `/:locale/:slug/about` collide and one silently loses its rules.
*
* @internal
*/
function unifyDynamicRouteRuleSegments(routeRules) {
const unifiedNames = /* @__PURE__ */ new Map();
const unified = [];
let clashed = false;
for (const [route, rules] of Object.entries(routeRules)) {
const segments = route.split("/");
const renames = /* @__PURE__ */ new Map();
for (let index = 1; index < segments.length; index++) {
const segment = segments[index];
if (!DYNAMIC_SEGMENT_RE.test(segment)) continue;
const group = segments.slice(0, index).join("/");
let name = unifiedNames.get(group);
if (!name) {
name = segment === "*" ? `_${index}` : segment.slice(1);
while (conflictsWithin(segments, name, index)) name += "_";
unifiedNames.set(group, name);
}
if (segment === `:${name}` || conflictsWithin(segments, name, index)) continue;
clashed = true;
segments[index] = `:${name}`;
if (segment !== "*") renames.set(segment.slice(1), name);
}
if (renames.size) for (const key of ["redirect", "proxy"]) {
const target = rules[key];
if (target?.to) target.to = target.to.replace(/\/:([$\w]+)/g, (match, name) => renames.has(name) ? `/:${renames.get(name)}` : match);
}
unified.push([segments.join("/"), rules]);
}
if (!clashed) return;
for (const route of Object.keys(routeRules)) delete routeRules[route];
for (const [route, rules] of unified) routeRules[route] = route in routeRules ? defu(rules, routeRules[route]) : rules;
}
// src/runtime/utils/event.ts
const ENC_PIPE_RE = /%7C/g;
const ENC_BRACKET_OPEN_RE = /%5B/g;
const ENC_BRACKET_CLOSE_RE = /%5D/g;
const ENC_ENC_SLASH_RE = /%252F/gi;
const HASH_RE = /#/g;
const QUESTION_MARK_RE = /\?/g;
function encodeEventPath(path) {
const queryIndex = path.indexOf("?");
if (queryIndex === -1) return encodeVueRouterPath(path);
return encodeVueRouterPath(path.slice(0, queryIndex)) + path.slice(queryIndex);
}
function encodeVueRouterPath(path) {
return encodeURI(path).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]").replace(HASH_RE, "%23").replace(QUESTION_MARK_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F");
}
/**
* The response headers of an h3 v1 event, in the shape the renderer writes them in.
*
* Backed by the node response rather than a copy of it, so a header the app sets through
* h3 and a header the renderer sets are the same header, and both are sent.
*/
var NodeResponseHeaders = class {
res;
constructor(res) {
this.res = res;
}
get(name) {
const value = this.res.getHeader(name);
if (value === void 0) return null;
return Array.isArray(value) ? value.join(", ") : String(value);
}
has(name) {
return this.res.hasHeader(name);
}
set(name, value) {
this.res.setHeader(name, value);
}
append(name, value) {
const existing = this.res.getHeader(name);
if (existing === void 0) {
this.res.setHeader(name, value);
return;
}
this.res.setHeader(name, Array.isArray(existing) ? [...existing, value] : [String(existing), value]);
}
delete(name) {
this.res.removeHeader(name);
}
getSetCookie() {
const value = this.res.getHeader("set-cookie");
if (value === void 0) return [];
return Array.isArray(value) ? value.map(String) : [String(value)];
}
*entries() {
const headers = this.res.getHeaders();
for (const name of Object.keys(headers).sort()) {
const value = headers[name];
if (value === void 0) continue;
if (name === "set-cookie" && Array.isArray(value)) for (const entry of value) yield [name, entry];
else yield [name, Array.isArray(value) ? value.join(", ") : String(value)];
}
}
*keys() {
for (const [name] of this.entries()) yield name;
}
*values() {
for (const [, value] of this.entries()) yield value;
}
forEach(callback, thisArg) {
for (const [name, value] of this.entries()) callback.call(thisArg, value, name, this);
}
[Symbol.iterator]() {
return this.entries();
}
};
const WEB_PROPERTIES = /* @__PURE__ */ new Set([
"req",
"res",
"url",
"~app"
]);
const PAYLOAD_METHODS = /* @__PURE__ */ new Set([
"PATCH",
"POST",
"PUT",
"DELETE"
]);
const BODY_READ_METHODS = /* @__PURE__ */ new Set([
"arrayBuffer",
"blob",
"bytes",
"formData",
"json",
"text"
]);
const RAW_BODY = Symbol.for("h3RawBody");
const requestBodies = /* @__PURE__ */ new WeakMap();
/**
* The request in the web-standard shape, with every read of its body served from the bytes
* h3 v1 caches on the node request.
*
* A body read here and a `readBody(event)` elsewhere in the same request therefore resolve
* to the same bytes whichever happens first, and reading the request twice - directly, from
* a clone, or as a stream - resolves the same bytes each time rather than the second read
* finding a stream the first has drained.
*/
function toWebRequest(event) {
const existing = event.web?.request;
if (existing) return existing;
const method = event.method;
const url = getRequestURL(event, { xForwardedProto: false });
if (!PAYLOAD_METHODS.has(method)) return new Request(url, {
method,
headers: event.headers,
signal: toRequestSignal(event)
});
const request = new Request(url, {
method,
headers: event.headers,
body: getRequestBody(event).stream(),
signal: toRequestSignal(event),
duplex: "half"
});
const copy = () => getRequestBody(event).read().then((body) => new Response(body, { headers: request.headers }));
const buffered = new Proxy(request, { get(target, property) {
if (property === "bodyUsed") return false;
if (property === "body") return getRequestBody(event).stream();
if (property === "clone") return () => buffered;
if (typeof property === "string" && BODY_READ_METHODS.has(property)) return () => copy().then((response) => response[property]());
const value = Reflect.get(target, property, target);
return typeof value === "function" ? value.bind(target) : value;
} });
return buffered;
}
/**
* Aborts when the client disconnects before the response is finished, the same moment an h3 v1
* handler would catch with `event.node.req.on('close')`.
*/
function toRequestSignal(event) {
const controller = new AbortController();
const res = event.node?.res;
if (typeof res?.once === "function") res.once("close", () => {
if (!res.writableFinished) controller.abort();
});
return controller.signal;
}
/**
* The body of the request, shared by every view of it and by h3's own body helpers.
*
* An unread node request is read incrementally, only as far as a read of the body has
* requested, and the chunks are kept so that later reads resolve the same bytes. A body h3
* has already read, or one the request carries in memory, is served from h3.
*/
function getRequestBody(event) {
const req = event.node.req;
let body = requestBodies.get(req);
if (!body) {
const hasBody = Number.parseInt(req.headers["content-length"] || "") || /\bchunked\b/i.test(String(req.headers["transfer-encoding"] ?? ""));
const readByH3 = event._requestBody || req[RAW_BODY] || req.rawBody || req.body;
body = hasBody && !readByH3 ? toIncrementalBody(req) : toRawBody(event);
requestBodies.set(req, body);
}
return body;
}
function toRawBody(event) {
const read = () => readRawBody(event, false).then((body) => body ? new Uint8Array(body) : /* @__PURE__ */ new Uint8Array());
return {
read,
stream: () => new ReadableStream({ async pull(controller) {
const body = await read();
if (body.byteLength) controller.enqueue(body);
controller.close();
} }, { highWaterMark: 0 })
};
}
function toIncrementalBody(req) {
const chunks = [];
let source;
let done = false;
let pending;
const readChunk = () => pending ??= (source ??= req[Symbol.asyncIterator]()).next().then((result) => {
if (result.done) done = true;
else chunks.push(result.value);
}).finally(() => {
pending = void 0;
});
const readAll = async () => {
while (!done) await readChunk();
return Buffer.concat(chunks);
};
Object.defineProperty(req, RAW_BODY, {
configurable: true,
get: readAll
});
return {
read: () => readAll().then((body) => new Uint8Array(body)),
stream: () => {
let index = 0;
return new ReadableStream({ async pull(controller) {
while (index >= chunks.length && !done) await readChunk();
if (index < chunks.length) controller.enqueue(new Uint8Array(chunks[index++]));
else controller.close();
} }, { highWaterMark: 0 });
}
};
}
const portableEvents = /* @__PURE__ */ new WeakMap();
/**
* The event a `nuxt/server` handler is given, in the web-standard shape.
*
* Both shapes are served from one object: `req`, `res`, `url` and `~app` resolve to the web
* view, everything else to the h3 v1 event, so h3's own helpers work on it too (they read
* `event.node`, not its deprecated `req`/`res` aliases). Cached per event, with the web view
* built on first access. `resolveURL` replaces how `url` is derived from the event's path.
*/
function toPortableEvent(event, resolveURL) {
const cached = portableEvents.get(event);
if (cached) return cached;
let web;
const portable = new Proxy(event, {
get(target, property) {
if (property === "~portable") return true;
return WEB_PROPERTIES.has(property) ? (web ??= toWebView(event, resolveURL))[property] : Reflect.get(target, property, target);
},
set(target, property, value) {
if (property === "url") {
(web ??= toWebView(event, resolveURL)).url = value;
return true;
}
return Reflect.set(target, property, value, target);
},
has(target, property) {
return WEB_PROPERTIES.has(property) || Reflect.has(target, property);
}
});
portableEvents.set(event, portable);
return portable;
}
function resolveEventURL(event) {
const url = new URL(`${getRequestProtocol(event, { xForwardedProto: false })}://${getRequestHost(event)}`);
const path = encodeEventPath(event.path);
const queryIndex = path.indexOf("?");
url.pathname = queryIndex === -1 ? path : path.slice(0, queryIndex);
url.search = queryIndex === -1 ? "" : path.slice(queryIndex);
url.hash = "";
return url;
}
/**
* Describe an h3 v1 event in the web-standard shape, rather than adapting it in place:
* `event.req` and `event.res` already name the node request and response, and that is the
* shape `useRequestEvent()` and the render hooks must keep seeing.
*
* Everything is resolved on access, and the response is backed by the node response rather
* than a copy of it, so a header the application sets through h3 and a header the renderer
* sets are the same header.
*/
function toWebView(event, resolveURL = () => resolveEventURL(event)) {
const node = event.node;
let request;
let url;
const res = {
get status() {
return node.res.statusCode;
},
set status(status) {
node.res.statusCode = status;
},
get statusText() {
return node.res.statusMessage;
},
set statusText(statusText) {
node.res.statusMessage = statusText;
},
headers: new NodeResponseHeaders(node.res)
};
const requestEvent = {
context: event.context,
res,
get req() {
return request ??= toWebRequest(event);
},
get url() {
return url ??= resolveURL();
},
set url(value) {
url = value;
event._path = node.req.url = value.pathname + value.search;
}
};
requestEvent["~app"] = event;
return requestEvent;
}
// src/registrations.ts
/** Add the dev server handlers that nitro does not already hold a copy of from its config. */
function addDevServerHandlers(nitroHandlers, handlers) {
const registered = new Set(nitroHandlers.map((entry) => entry.handler));
for (const entry of handlers) if (!registered.has(entry.handler)) nitroHandlers.push(entry);
}
/** The dev server handlers, with each `nuxt` variant given a `RequestEvent`. */
function toPortableDevHandlers(handlers) {
return handlers.map((entry) => {
const handler = entry.handler;
if (entry[kServerApi] !== "nuxt" || typeof handler !== "function") return entry;
return {
...entry,
handler: defineEventHandler((event) => handler(toPortableEvent(event, () => getRequestURL(event, { xForwardedProto: false }))))
};
});
}
/**
* Write the server plugins gathered on `nuxt.options._serverPlugins`, which carry the server
* API each was registered for, into the plain paths nitro takes.
*/
function collectServerRegistrations(nuxt, nitroConfig) {
nitroConfig.plugins ||= [];
for (const entry of nuxt.options._serverPlugins || []) {
const path = normalize(resolveAlias(entry.plugin, nuxt.options.alias));
if (!nitroConfig.plugins.includes(path)) nitroConfig.plugins.push(path);
}
}
// src/templates.ts
/**
* Hands the response types nitro scanned into its own `InternalApi` to Nuxt's typed `$fetch`.
*
* Emitted rather than declared in this package's own augments, because with
* `experimental.routeTypedFetch` requests are typed from the generated route set instead, and a
* route described both ways on one interface is an error.
*/
const nitroInternalApiTemplate = {
filename: "types/nitro-internal-api.d.ts",
dependsOn: [],
getContents({ nuxt }) {
if (nuxt.options.experimental.routeTypedFetch) return "export {}\n";
return `
import type { InternalApi } from 'nitropack/types'
declare module '@nuxt/schema' {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ServerRoutes extends InternalApi {}
}
declare module 'nuxt/schema' {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface ServerRoutes extends InternalApi {}
}
`;
}
};
const nitroSchemaTemplate = {
filename: "types/nitro-nuxt.d.ts",
dependsOn: [],
async getContents({ nuxt }) {
const references = [];
const declarations = [];
await nuxt.callHook("nitro:prepare:types", {
references,
declarations
});
const typesDir = join(nuxt.options.buildDir, "types");
return `
${[...references.map((ref) => renderReference(ref, typesDir)), ...declarations].join("\n")}
import type { RouteRuleConfigExtensions, RuntimeConfig, RuntimeConfigApp } from 'nuxt/schema'
import type { H3Event } from 'h3'
import type { DevServerLog, NuxtIslandContext, NuxtIslandResponse, NuxtRenderChunkContext, NuxtRenderCloseContext, NuxtRenderHTMLContext, NuxtRenderRouteContext } from '#app/types'
declare module 'nitropack' {
interface NitroRuntimeConfig extends RuntimeConfig {}
interface NitroRuntimeConfigApp extends RuntimeConfigApp {}
interface NitroRouteConfig extends RouteRuleConfigExtensions {}
interface NitroRouteConfig {
ssr?: boolean
streaming?: boolean
noScripts?: boolean
/** @deprecated Use \`noScripts\` instead */
experimentalNoScripts?: boolean
}
interface NitroRouteRules {
ssr?: boolean
streaming?: boolean
noScripts?: boolean
/** @deprecated Use \`noScripts\` instead */
experimentalNoScripts?: boolean
appMiddleware?: Record<string, boolean>
appLayout?: string | false
}
interface NitroRuntimeHooks {
'dev:ssr-logs': (ctx: { logs: DevServerLog[], path: string }) => void | Promise<void>
'render:html': (htmlContext: NuxtRenderHTMLContext, context: { event: H3Event, streaming?: boolean }) => void | Promise<void>
'render:html:chunk': (chunkContext: NuxtRenderChunkContext, context: { event: H3Event }) => void | Promise<void>
'render:html:close': (closeContext: NuxtRenderCloseContext, context: { event: H3Event }) => void | Promise<void>
'render:route': (renderRouteContext: NuxtRenderRouteContext, context: { event: H3Event }) => void | Promise<void>
'render:island': (islandResponse: NuxtIslandResponse, context: { event: H3Event, islandContext: NuxtIslandContext }) => void | Promise<void>
}
}
declare module 'nitropack/types' {
interface NitroRuntimeConfig extends RuntimeConfig {}
interface NitroRuntimeConfigApp extends RuntimeConfigApp {}
interface NitroRouteConfig extends RouteRuleConfigExtensions {}
interface NitroRouteConfig {
ssr?: boolean
streaming?: boolean
noScripts?: boolean
/** @deprecated Use \`noScripts\` instead */
experimentalNoScripts?: boolean
}
interface NitroRouteRules {
ssr?: boolean
streaming?: boolean
noScripts?: boolean
/** @deprecated Use \`noScripts\` instead */
experimentalNoScripts?: boolean
appMiddleware?: Record<string, boolean>
appLayout?: string | false
}
interface NitroRuntimeHooks {
'dev:ssr-logs': (ctx: { logs: DevServerLog[], path: string }) => void | Promise<void>
'render:html': (htmlContext: NuxtRenderHTMLContext, context: { event: H3Event, streaming?: boolean }) => void | Promise<void>
'render:html:chunk': (chunkContext: NuxtRenderChunkContext, context: { event: H3Event }) => void | Promise<void>
'render:html:close': (closeContext: NuxtRenderCloseContext, context: { event: H3Event }) => void | Promise<void>
'render:route': (renderRouteContext: NuxtRenderRouteContext, context: { event: H3Event }) => void | Promise<void>
'render:island': (islandResponse: NuxtIslandResponse, context: { event: H3Event, islandContext: NuxtIslandContext }) => void | Promise<void>
}
}
`;
}
};
function renderReference(ref, baseDir) {
return `/// <reference ${"path" in ref ? `path="${isAbsolute(ref.path) ? relative(baseDir, ref.path) : ref.path}"` : `types="${ref.types}"`} />`;
}
// src/index.ts
/** Subpath the request-shape extractors are imported from in generated declarations. */
const REQUEST_TYPES_MODULE = "@nuxt/nitro-server/request-types";
const UNHEAD_IMPORT_RE = /^unhead(?:\/|$)/;
const logLevelMapReverse = {
silent: 0,
info: 3,
verbose: 3
};
async function bundle(nuxt) {
const errorPageOption = nuxt.options.experimental.prerenderErrorPages;
const errorPages = errorPageOption === true ? [404] : errorPageOption || [];
const layerDirs = getLayerDirectories(nuxt);
const excludePattern = [getLayerNodeModulesExcludePattern(layerDirs.map((dirs) => dirs.root))];
const layerPublicAssetsDirs = [];
for (const dirs of layerDirs) if (existsSync(dirs.public)) layerPublicAssetsDirs.push({ dir: dirs.public });
const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
const moduleEntryPaths = [];
for (const m of nuxt.options._installedModules) {
const path = m.meta?.rawPath || m.entryPath;
if (path) moduleEntryPaths.push(getDirectory(path));
}
const modules = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
addTemplate(nitroSchemaTemplate);
addTypeTemplate(nitroInternalApiTemplate);
const importDirs = /* @__PURE__ */ new Set();
if (nuxt.options.nitro.imports !== false && nuxt.options.imports.scan !== false) for (const layer of nuxt.options._layers) {
if (layer.config?.imports?.scan === false) continue;
importDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "utils"));
importDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "types"));
importDirs.add(resolve(layer.config.serverDir ?? resolve(layer.config.rootDir, "server"), "types"));
}
nuxt.hook("nitro:init", (nitro) => {
const dirs = nitro.options.imports === false ? void 0 : nitro.options.imports.dirs;
if (!dirs?.length) return;
const layers = nuxt.options._layers;
const layerRoots = layers.map((layer, index) => [withTrailingSlash(layer.config.rootDir), index]).sort(([a], [b]) => b.length - a.length);
const layerOf = (dir) => {
const path = withTrailingSlash(typeof dir === "string" ? dir : dir.glob);
return layerRoots.find(([root]) => path.startsWith(root))?.[1] ?? layers.length;
};
dirs.sort((a, b) => layerOf(b) - layerOf(a));
});
nuxt.options.nitro.plugins ||= [];
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins.map((plugin) => plugin ? resolveAlias(plugin, nuxt.options.alias) : plugin);
nuxt.options.nitro.plugins.unshift(resolve(distDir, "runtime/plugins/route-rules"));
for (const asset of [...nuxt.options.nitro.publicAssets || [], ...nuxt.options.nitro.serverAssets || []]) if (asset?.dir) asset.dir = resolveAlias(asset.dir, nuxt.options.alias);
const nitroSrcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nuxt.options.nitro.srcDir || nuxt.options.serverDir);
for (const asset of [...nuxt.options.nitro.publicAssets || [], ...nuxt.options.nitro.serverAssets || []]) {
if (!asset?.dir || isAbsolute(asset.dir)) continue;
if (!existsSync(resolve(nitroSrcDir, asset.dir))) {
const rootRelative = resolve(nuxt.options.rootDir, asset.dir);
if (existsSync(rootRelative)) asset.dir = rootRelative;
}
}
for (const asset of nuxt.options.nitro.publicAssets || []) {
if (!asset?.dir) continue;
const dir = resolve(nitroSrcDir, asset.dir);
const isGenerated = !relative(nuxt.options.buildDir, dir).startsWith("..");
if (!existsSync(dir) && !isGenerated) bundlerDiagnostics.NUXT_B7023({
dir,
baseURL: joinURL("/", asset.baseURL || "/", "**"),
resolvedFrom: "your server directory and then your project root"
});
}
if (nuxt.options.dev) {
nuxt.options.nitro.virtual = defu(nuxt.options.nitro.virtual, { "#internal/dev-server-logs-options": () => [`export const rootDir = ${JSON.stringify(nuxt.options.rootDir)};`, `export const srcDir = ${JSON.stringify(nuxt.options.srcDir)};`].join("\n") });
nuxt.options.nitro.externals = defu(nuxt.options.nitro.externals, { inline: [/#internal\/dev-server-logs-options/] });
addPlugin(resolve(nuxt.options.appDir, "plugins/dev-error-overlay.client"));
}
if (nuxt.options.dev && nuxt.options.features.devLogs) {
addPlugin(resolve(nuxt.options.appDir, "plugins/dev-server-logs"));
nuxt.options.nitro.plugins.push(resolve(distDir, "runtime/plugins/dev-server-logs"));
}
const clientOnlyApp = !nuxt.options.ssr;
if (nuxt.options.experimental.componentIslands) {
const islandHandlerPath = JSON.stringify(resolve(distDir, "runtime/handlers/island"));
const h3Path = JSON.stringify(resolve(distDir, "h3"));
const ISLAND_RENDERER_KEY = "#internal/nuxt/island-renderer.mjs";
nuxt.options.nitro.virtual ||= {};
nuxt.options.nitro.virtual[ISLAND_RENDERER_KEY] = () => {
if (nuxt.options.dev || nuxt.options.experimental.componentIslands !== "auto" || nuxt.apps.default?.pages?.some((p) => p.mode === "server") || nuxt.apps.default?.components?.some((c) => c.mode === "server" && !nuxt.apps.default?.components.some((other) => other.pascalName === c.pascalName && other.mode === "client"))) return `export { default } from ${islandHandlerPath}`;
return `import { defineEventHandler } from ${h3Path}; export default defineEventHandler(() => {});`;
};
nuxt.options.serverHandlers.push({
route: "/__nuxt_island/**",
handler: "#internal/nuxt/island-renderer.mjs"
});
if (clientOnlyApp && nuxt.options.experimental.componentIslands !== "auto") {
nuxt.options.ssr = true;
nuxt.options.routeRules ||= {};
nuxt.options.routeRules["/**"] = defu(nuxt.options.routeRules["/**"], { ssr: false });
}
}
const mockProxy = resolveModulePath("mocked-exports/proxy", { from: import.meta.url });
const typesDir = nuxt.options.typesDir || nuxt.options.buildDir;
const typesServerTsConfigPath = join(typesDir, "tsconfig.server.json");
const serverTsConfigPath = !nuxt.options._prepare && !nuxt.options.dev && typesDir !== nuxt.options.buildDir && existsSync(typesServerTsConfigPath) ? join(nuxt.options.buildDir, "tsconfig.server.json") : typesServerTsConfigPath;
const h3Entry = resolveModulePath("h3", { from: import.meta.url });
const h3PackageJson = resolveModulePath("h3/package.json", { from: import.meta.url });
const globalCompilerOptions = { ...nuxt.options.typescript?.tsConfig?.compilerOptions };
delete globalCompilerOptions.types;
delete globalCompilerOptions.paths;
delete globalCompilerOptions.noEmit;
const globalTypescriptDefaults = { typescript: { tsConfig: { compilerOptions: globalCompilerOptions } } };
const serverRuntime = getServerRuntime({
unheadOptions: "#internal/unhead-options.mjs",
headConfig: "#internal/unhead.config.mjs",
prelude: `import { componentIslands as _componentIslands, componentIslandsActive as _componentIslandsActive } from '#internal/nuxt.config.mjs'`,
overrides: async () => {
const hasCachedRoutes = Object.values(nitro.options.routeRules).some((r) => r.isr || r.cache);
const noScriptsPatterns = [...new Set(Object.entries(nitro.options.routeRules).filter(([_route, rules]) => rules.noScripts).map(([route]) => rou3PatternToURLPattern(route, { wildcard: "segment" }).pattern))];
const pagePatterns = nitro.options._noScriptsPagePatterns ?? [];
const early404Patterns = nitro.options._early404PagePatterns ?? [];
const noSSRRoutes = [
"/index.html",
"/200.html",
"/404.html"
].filter((route) => !errorPages.includes(Number(route.slice(1, -5))));
return {
NUXT_PRERENDER_ERROR_PAGES: JSON.stringify(errorPages),
NUXT_PRERENDER_NO_SSR_ROUTES: JSON.stringify(noSSRRoutes),
NUXT_NO_SCRIPTS_PATTERNS: JSON.stringify(noScriptsPatterns),
NUXT_HAS_NO_SCRIPTS_ROUTES: String(noScriptsPatterns.length > 0),
NUXT_PAGE_PATTERNS: JSON.stringify(pagePatterns),
NUXT_EARLY_404: String(early404Patterns.length > 0),
NUXT_PAGE_MATCHER: compilePageMatcher(early404Patterns),
NUXT_RUNTIME_PAYLOAD_EXTRACTION: String(hasCachedRoutes),
spaTemplate: JSON.stringify(await spaLoadingTemplate(nuxt)),
componentIslands: "_componentIslands",
componentIslandsActive: "_componentIslandsActive"
};
}
}, nuxt);
const nitroConfig = defu(nuxt.options.nitro, globalTypescriptDefaults, {
debug: nuxt.options.debug ? nuxt.options.debug.nitro : false,
rootDir: nuxt.options.rootDir,
workspaceDir: nuxt.options.workspaceDir,
srcDir: nuxt.options.serverDir,
dev: nuxt.options.dev,
buildDir: nuxt.options.buildDir,
experimental: {
asyncContext: nuxt.options.experimental.asyncContext,
typescriptBundlerResolution: nuxt.options.future.typescriptBundlerResolution || nuxt.options.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler" || nuxt.options.typescript.serverTsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler"
},
framework: {
name: "nuxt",
version: nuxtPkg.version || version
},
imports: {
autoImport: nuxt.options.imports.autoImport,
dirs: [...importDirs],
imports: [
{
as: "__buildAssetsURL",
name: "buildAssetsURL",
from: resolve(distDir, "runtime/utils/paths")
},
{
as: "__publicAssetsURL",
name: "publicAssetsURL",
from: resolve(distDir, "runtime/utils/paths")
},
{
as: "defineAppConfig",
name: "defineAppConfig",
from: resolve(distDir, "runtime/utils/config"),
priority: -1
}
],
presets: nuxt.options.experimental.nitroAutoImports ? [{
from: "h3",
imports: ["H3Event", "H3Error"]
}, {
from: "h3",
type: true,
imports: [
"EventHandler",
"EventHandlerRequest",
"EventHandlerResponse",
"EventHandlerObject",
"H3EventContext"
]
}] : [],
exclude: [...excludePattern, /[\\/]\.git[\\/]/]
},
esbuild: { options: { exclude: excludePattern } },
analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) ? {
template: "treemap",
projectRoot: nuxt.options.rootDir,
filename: join(nuxt.options.analyzeDir, "{name}.html")
} : false,
scanDirs: layerDirs.map((dirs) => dirs.server),
renderer: resolve(distDir, "runtime/handlers/renderer"),
nodeModulesDirs: nuxt.options.modulesDir,
baseURL: nuxt.options.app.baseURL,
virtual: {
"#internal/nuxt.config.mjs": () => nuxt.vfs["#build/nuxt.config.mjs"] || "",
"#internal/nuxt/app-config": () => nuxt.vfs["#build/app.config.mjs"]?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, "") || "",
"#internal/nuxt/error-channel": () => nuxt.options.dev ? `export * from ${JSON.stringify(resolve(distDir, "runtime/utils/error-channel"))}` : "export {}",
"#internal/nuxt/nitro-config.mjs": () => [
`export const NUXT_ERROR_CHANNEL = ${JSON.stringify(nuxt.options.devServer.errorChannel)}`,
`export const NUXT_DEV_LOGS = ${!!nuxt.options.features.devLogs}`,
`export const NUXT_ASYNC_CONTEXT = ${!!nuxt.options.experimental.asyncContext}`,
`export const NUXT_SHARED_DATA = ${!!nuxt.options.experimental.sharedPrerenderData}`
].join("\n"),
"#internal/nuxt/route-rules.mjs": () => [
normalizePathCode,
`export const normalizeRouteRulePath = path => normalizePath(path, ${!nuxt.options.router.options.sensitive})`,
`export { matchAllRouteRules }`
].join("\n")
},
routeRules: {
...typeof nuxt.options.experimental.ssrStreaming === "object" && nuxt.options.experimental.ssrStreaming.enabled ? { "/**": { streaming: true } } : {},
"/__nuxt_error": { cache: false }
},
typescript: {
strict: true,
generateTsConfig: true,
tsconfigPath: serverTsConfigPath,
tsConfig: {
compilerOptions: {
lib: [
"esnext",
"webworker",
"dom.iterable"
],
skipLibCheck: true,
noUncheckedIndexedAccess: true,
allowArbitraryExtensions: true,
allowImportingTsExtensions: true
},
include: [
join(typesDir, "types/nitro-nuxt.d.ts"),
...modules.flatMap((m) => {
const moduleDir = relativeWithDot(typesDir, m);
return [join(moduleDir, "runtime/server"), join(moduleDir, "dist/runtime/server")];
}),
...layerDirs.map((dirs) => relativeWithDot(typesDir, join(dirs.server, "**/*"))),
...layerDirs.map((dirs) => relativeWithDot(typesDir, join(dirs.shared, "**/*.d.ts")))
],
exclude: [...nuxt.options.modulesDir.map((m) => relativeWithDot(typesDir, m)), relativeWithDot(typesDir, resolve(nuxt.options.rootDir, "dist"))]
}
},
publicAssets: [nuxt.options.dev ? { dir: resolve(nuxt.options.buildDir, "dist/client") } : {
dir: join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir),
maxAge: 31536e3,
baseURL: nuxt.options.app.buildAssetsDir
}, ...layerPublicAssetsDirs],
prerender: {
ignoreUnprefixedPublicAssets: true,
failOnError: true,
concurrency: cpus().length * 4 || 4,
routes: [].concat(nuxt.options.generate.routes)
},
sourceMap: nuxt.options.sourcemap.server,
externals: {
inline: [
...nuxt.options.dev ? [] : [
...nuxt.options.experimental.externalVue ? [] : ["vue", "@vue/"],
"@nuxt/",
nuxt.options.buildDir
],
...nuxt.options.build.transpile.filter((i) => typeof i === "string").map(toTranspileNoExternal),
isNuxtDistId,
distDir,
...layerDirs.map((dirs) => join(dirs.app, "app.config"))
],
traceInclude: [...nuxt.options.vue.runtimeCompiler && !nuxt.options.experimental.externalVue ? [...nuxt.options.modulesDir.reduce((targets, path) => {
const serverRendererPath = resolve(path, "vue/server-renderer/index.js");
if (existsSync(serverRendererPath)) targets.push(serverRendererPath);
return targets;
}, [])] : []]
},
alias: {
...nuxt.options.vue.runtimeCompiler || nuxt.options.experimental.externalVue ? {} : {
"estree-walker": mockProxy,
"@babel/parser": mockProxy,
"@vue/compiler-core": mockProxy,
"@vue/compiler-dom": mockProxy,
"@vue/compiler-ssr": mockProxy
},
"@vue/devtools-api": resolveModulePath("vue-devtools-stub", { from: import.meta.url }),
"h3": h3Entry,
"h3/package.json": h3PackageJson,
...nuxt.options.alias,
"#internal/nuxt/paths": resolve(distDir, "runtime/utils/paths")
},
replace: {
"__VUE_OPTIONS_API__": String(!!nuxt.options.vue.optionsApi),
"__VUE_PROD_DEVTOOLS__": String(false),
"__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": String(!!nuxt.options.debug && !!nuxt.options.debug.hydration),
"import.meta.test": String(!!nuxt.options.test)
},
rollupConfig: {
output: { generatedCode: { symbols: true } },
plugins: []
},
logLevel: logLevelMapReverse[nuxt.options.logLevel]
});
if (nuxt.options.experimental.serverAppConfig === true && nitroConfig.imports) {
nitroConfig.imports.imports ||= [];
nitroConfig.imports.imports.push({
name: "useAppConfig",
from: resolve(distDir, "runtime/utils/app-config"),
priority: 20
});
}
if (!nitroConfig.errorHandler && (nuxt.options.dev || !nuxt.options.experimental.noVueServer)) nitroConfig.errorHandler = resolve(distDir, "runtime/handlers/error");
nitroConfig.srcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nitroConfig.srcDir);
nitroConfig.ignore ||= [];
nitroConfig.ignore.push(...resolveIgnorePatterns(nitroConfig.srcDir), `!${join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir, "**/*")}`);
nuxt.hook("nitro:init", (nitro) => {
nitro.hooks.hook("build:before", (nitro) => {
unifyDynamicRouteRuleSegments(nitro.options.routeRules);
});
});
if (nuxt.options.experimental.payloadExtraction) {
if (nuxt.options.dev) nuxt.hook("nitro:config", (nitroConfig) => {
nitroConfig.prerender ||= {};
nitroConfig.prerender.routes ||= [];
nitroConfig.routeRules ||= {};
for (const route of nitroConfig.prerender.routes) {
if (!route) continue;
nitroConfig.routeRules[route] = defu(nitroConfig.routeRules[route], { prerender: true });
}
});
nuxt.hook("nitro:init", (nitro) => {
nitro.hooks.hook("build:before", (nitro) => {
for (const [route, value] of Object.entries(nitro.options.routeRules)) if (!route.endsWith("*") && !route.endsWith("/_payload.json")) {
if (value.ssr === false) continue;
if (value.isr || value.cache || value.prerender && nuxt.options.dev) {
const payloadKey = (route === "/" ? "" : route) + "/_payload.json";
const defaults = { ssr: true };
for (const key of [
"isr",
"cache",
...nuxt.options.dev ? ["prerender"] : []
]) if (key in value) defaults[key] = value[key];
nitro.options.routeRules[payloadKey] = defu(nitro.options.routeRules[payloadKey], defaults);
}
}
});
});
}
if (nuxt.options.experimental.appManifest) {
const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
const buildTimestamp = Date.now();
const manifestPrefix = joinURL(nuxt.options.app.buildAssetsDir, "builds");
const tempDir = join(nuxt.options.buildDir, "manifest");
nitroConfig.prerender ||= {};
nitroConfig.prerender.ignore ||= [];
nitroConfig.prerender.ignore.push(joinURL(nuxt.options.app.baseURL, manifestPrefix));
nitroConfig.publicAssets.unshift({
dir: join(tempDir, "meta"),
maxAge: 31536e3,
baseURL: joinURL(manifestPrefix, "meta")
}, {
dir: tempDir,
maxAge: 1,
baseURL: manifestPrefix
});
nuxt.options.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
addTemplate({
filename: "types/app-manifest.d.ts",
dependsOn: [],
getContents: () => "declare const manifest: { id: string, timestamp: number, prerendered: string[] }\nexport default manifest\n"
});
nuxt.hook("prepare:types", ({ tsConfig }) => {
tsConfig.compilerOptions ||= {};
tsConfig.compilerOptions.paths ||= {};
tsConfig.compilerOptions.paths["#app-manifest"] = [relativeWithDot(typesDir, resolve(nuxt.options.buildDir, "types/app-manifest"))];
});
if (!nuxt.options._prepare && !nuxt.options.dev) nuxt.hook("build:before", async () => {
await promises.mkdir(join(tempDir, "meta"), { recursive: true });
await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify({}));
});
nuxt.hook("nitro:config", (config) => {
config.alias ||= {};
config.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
});
nuxt.hook("nitro:init", (nitro) => {
nitro.hooks.hook("rollup:before", async (nitro) => {
const prerenderedRoutes = /* @__PURE__ */ new Set();
const fold = !nuxt.options.router.options.sensitive;
const routeRulesMatcher = createNormalizedRouteRulesRouter(Object.entries(nitro.options.routeRules).map(([route, data]) => ({
route,
data
})), "", fold);
if (nitro._prerenderedRoutes?.length) {
const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? "/_payload.json" : "/_payload.js";
for (const route of nitro._prerenderedRoutes) if (!route.error && route.route.endsWith(payloadSuffix)) {
const url = route.route.slice(0, -payloadSuffix.length) || "/";
if (!resolveRouteRules(routeRulesMatcher, url, fold).prerender) prerenderedRoutes.add(url);
}
}
const manifest = {
id: buildId,
timestamp: buildTimestamp,
prerendered: nuxt.options.dev ? [] : [...prerenderedRoutes].sort()
};
await promises.mkdir(join(tempDir, "meta"), { recursive: true });
await promises.writeFile(join(tempDir, "latest.json"), JSON.stringify({
id: buildId,
timestamp: buildTimestamp
}));
await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify(manifest));
});
});
}
if (!nuxt.options.experimental.appManifest) nuxt.options.alias["#app-manifest"] = mockProxy;
for (const [specifier, module] of Object.entries(serverRuntime.modules)) nitroConfig.virtual[specifier] = () => module.code();
const nitroDecoratorSetup = /* @__PURE__ */ new WeakMap();
const setupNitroDecorators = (nitroConfig) => {
const existingSetup = nitroDecoratorSetup.get(nitroConfig);
if (existingSetup) return existingSetup;
const setup = (async () => {
const result = await ensureDependencyInstalled([
"@rollup/plugin-babel",
"@babel/plugin-proposal-decorators",
"@babel/plugin-syntax-typescript"
], {
rootDir: nuxt.options.rootDir,
searchPaths: nuxt.options.modulesDir,
from: import.meta.url
});
if (result !== true) bundlerDiagnostics.NUXT_B7009({
deps: result.map((d) => `\`${d}\``).join(" and "),
installCommand: await getAddDependencyCommand(result, nuxt.options.rootDir, { dev: true })
});
if (result === true) {
const { babel } = await import("@rollup/plugin-babel");
nitroConfig.rollupConfig.plugins = toArray(await nitroConfig.rollupConfig.plugins || []);
nitroConfig.rollupConfig.plugins.unshift(babel({
babelHelpers: "bundled",
configFile: false,
extensions: [
".ts",
".js",
".mjs",
".mts"
],
plugins: [["@babel/plugin-syntax-typescript", { isTSX: false }], ["@babel/plugin-proposal-decorators", { version: "2023-11" }]]
}), babel({
babelHelpers: "bundled",
configFile: false,
extensions: [".tsx", ".jsx"],
plugins: [["@babel/plugin-syntax-typescript", { isTSX: true }], ["@babel/plugin-proposal-decorators", { version: "2023-11" }]]
}));
}
})();
nitroDecoratorSetup.set(nitroConfig, setup);
setup.catch(() => nitroDecoratorSetup.delete(nitroConfig));
return setup;
};
if (nuxt.options.experimental.decorators) {
if (nuxt.options.dev) nuxt.hook("nitro:build:before", (nitro) => setupNitroDecorators(nitro.options));
else await setupNitroDecorators(nitroConfig);
}
nitroConfig.rollupConfig.plugins = await nitroConfig.rollupConfig.plugins || [];
nitroConfig.rollupConfig.plugins = toArray(nitroConfig.rollupConfig.plugins);
const sharedDir = withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared));
const relativeSharedDir = withTrailingSlash(relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, nuxt.options.dir.shared)));
const sharedPatterns = [
/^#shared\//,
new RegExp("^" + escapeRE(sharedDir)),
new RegExp("^" + escapeRE(relativeSharedDir))
];
const trace = nuxt.options.dev ? true : "lazy";
nitroConfig.rollupConfig.plugins.push(ImpoundPlugin.rollup({
cwd: nuxt.options.rootDir,
trace,
matchers: [{
include: sharedPatterns,
patterns: createImportProtectionPatterns(nuxt, { context: "shared" })
}, {
patterns: createImportProtectionPatterns(nuxt, { context: "nitro-app" }),
exclude: [/node_modules[\\/]nitro(?:pack)?(?:-nightly)?[\\/]|(packages|@nuxt)[\\/]nitro-server(?:-nightly)?[\\/](src|dist)[\\/]runtime[\\/]/, ...sharedPatterns]
}]
}));
const nuxtRuntimeImporter = join(nuxt.options.appDir, "index.js");
nitroConfig.rollupConfig.plugins.push({
name: "nuxt:unhead:dedupe",
resolveId(id, importer, options) {
if (!importer || !UNHEAD_IMPORT_RE.test(id)) return;
return this.resolve(id, nuxtRuntimeImporter, {
...options,
skipSelf: true
});
}
});
const devStorageIgnore = (mountBase, relativeTo) => toFsDriverIgnorePatterns(["**/node_modules", ...resolveIgnorePatterns(relativeTo)], mountBase);
nitroConfig.devStorage ??= {};
nitroConfig.devStorage.root ??= {
driver: "fs",
readOnly: true,
base: nitroConfig.rootDir,
ignore: devStorageIgnore(nitroConfig.rootDir)
};
nitroConfig.devStorage.src ??= {
driver: "fs",
readOnly: true,
base: nitroConfig.srcDir,
ignore: devStorageIgnore(nitroConfig.srcDir, nitroConfig.srcDir)
};
const cacheDriverPath = join(distDir, "runtime/utils/cache-driver.mjs");
const cacheDriverOption = isWindows ? pathToFileURL(cacheDriverPath).href : cacheDriverPath;
nuxt.options.typescript.hoist.push("nitro/types", "nitro/runtime", "defu", "consola", "ofetch");
const [ownTypePaths, ownNodeTypePaths] = await Promise.all([resolveOwnTypePaths(h3PackageJson), resolveOwnTypePaths(h3PackageJson, { entry: true })]);
nitroConfig.typescript.tsConfig.compilerOptions ||= {};
nitroConfig.typescript.tsConfig.compilerOptions.paths = {
...nitroConfig.typescript.tsConfig.compilerOptions.paths,
...ownTypePaths
};
await nuxt.callHook("nitro:config", nitroConfig);
normalizeAppMiddlewareRules(nitroConfig.routeRules);
collectServerRegistrations(nuxt, nitroConfig);
if (!nuxt.options.experimental.nitroAutoImports && nitroConfig.imports) {
const presetCount = nitroConfig.imports.presets?.length ?? 0;
nitroConfig.modules = [(nitro) => {
if (nitro.options.imports) nitro.options.imports.presets.splice(presetCount);
}, ...nitroConfig.modules || []];
}
if (nitroConfig.static && nuxt.options.dev) {
nitroConfig.routeRules ||= {};
nitroConfig.routeRules["/**"] = defu(nitroConfig.routeRules["/**"], { prerender: true });
}
const excludedAlias = [
/^@vue\/.*$/,
"vue",
/vue-router/,
"vite/client",
"#imports",
"vue-demi",
/^#app/,
"~",
"@",
"~~",
"@@",
"h3",
"h3/package.json"
];
const isV5OrHigher = nuxt.options.future.compatibilityVersion >= 5;
const baseUrl = isV5OrHigher ? void 0 : nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl;
const basePath = baseUrl ? resolve(typesDir, baseUrl) : typesDir;
const aliases = nitroConfig.alias;
const importPaths = nuxt.options.modulesDir.map((d) => pathToFileURL(withTrailingSlash(d)));
const tsConfig = nitroConfig.typescript.tsConfig;
tsConfig.compilerOptions ||= {};
if (isV5OrHigher) Reflect.deleteProperty(tsConfig.compilerOptions, "baseUrl");
tsConfig.compilerOptions.paths ||= {};
for (const _alias in aliases) {
const alias = _alias;
if (excludedAlias.some((pattern) => typeof pattern === "string" ? alias === pattern : pattern.test(alias))) continue;
if (alias in tsConfig.compilerOptions.paths) continue;
let absolutePath = resolve(basePath, aliases[alias]);
let stats = await promises.stat(absolutePath).catch(() => null);
if (!stats) {
const resolvedModule = resolveModulePath(aliases[alias], {
try: true,
from: importPaths,
extensions: [
...nuxt.options.extensions,
".d.ts",
".d.mts",
".d.cts"
]
});
if (resolvedModule) {
absolutePath = resolvedModule;
stats = await promises.stat(resolvedModule).catch(() => null);
}
}
const isDirectory = aliases[alias].endsWith("/") || stats?.isDirectory();
tsConfig.compilerOptions.paths[alias] = [absolutePath];
if (isDirectory) tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`];
}
const appDir = nuxt.options.alias["#app"];
if (appDir) {
tsConfig.compilerOptions.paths["#app/island-hash"] ||= [resolve(appDir, "island-hash")];
tsConfig.compilerOptions.paths["#app/island-props"] ||= [resolve(appDir, "island-props")];
tsConfig.compilerOptions.paths["#app/internal/*"] ||= [resolve(appDir, "internal/*")];
tsConfig.compilerOptions.paths["#app/types"] ||= [resolve(appDir, "types")];
}
nuxt._perf?.startPhase("nitro:createNitro");
const nitro = await createNitro(nitroConfig, {
compatibilityDate: nuxt.options.compatibilityDate,
dotenv: nuxt.options._loadOptions?.dotenv
});
nuxt._perf?.endPhase("nitro:createNitro");
if (nuxt.options.experimental.serverAppConfig === false && nitro.options.imports) {
nitro.options.imports.presets ||= [];
nitro.options.imports.presets = nitro.options.imports.presets.map((preset) => typeof preset === "string" || !("imports" in preset) ? preset : {
...preset,
imports: preset.imports.filter((i) => i !== "useAppConfig")
});
}
if (!clientOnlyApp && nitro.options.static && nuxt.options.experimental.payloadExtraction === false) bundlerDiagnostics.NUXT_B7015();
const spaLoadingTemplateFilePath = await spaLoadingTemplatePath(nuxt);
nuxt.hook("builder:watch", async (_event, relativePath) => {
if (resolve(nuxt.options.srcDir, relativePath) === spaLoadingTemplateFilePath) await nitro.hooks.callHook("rollup:reload");
});
const cacheDir = resolve(nuxt.options.buildDir, "cache/nitro/prerender");
await promises.rm(cacheDir, {
recursive: true,
force: true
}).catch(() => {});
nitro.options._config.storage = defu(nitro.options._config.storage, { "internal:nuxt:prerender": {
driver: cacheDriverOption,
base: cacheDir
} });
nuxt._nitro = nitro;
setServerBuild({
name: "nitro",
label: "Nitro",
target: () => nitro.options.preset,
targetLabel: "preset",
output: {
dir: () => withoutTrailingSlash(nitro.options.output.dir),
publicDir: () => withoutTrailingSlash(nitro.options.output.publicDir)
},
capabilities: {
server: true,
dev: true
},
buildsSeparately: true,
runtime: {
runtimeConfig: "nitropack/runtime",
server: resolve(distDir, "runtime/server")
},
preview: { command: () => resolveNitroCommand(nitro.options.commands.preview, nitro.options) }
}, nuxt);
await nuxt.callHook("nitro:init", nitro);
if (nuxt._perf) nitro.hooks.hook("rollup:before", (_nitro, rollupConfig) => {
const plugins = rollupConfig.plugins || [];
for (const plugin of plugins) {
if (!plugin || !plugin.name) continue;
const pluginName = `nitro:${plugin.name}`;
for (const hookName of [
"transform",
"resolveId",
"load"
]) {
const original = plugin[hookName];
if (typeof original !== "function") continue;
plugin[hookName] = function(...args) {
const start = performance.now();
const record = () => nuxt._perf?.recordBundlerPluginHook(pluginName, hookName, performance.now() - start, start);
try {
const result = original.apply(this, args);
if (result && typeof result === "object" && "then" in result) return result.finally(record);
record();
return result;
} catch (err) {
record();
throw err;
}
};
}
}
});
nuxt["~runtimeDependencies"] ||= [];
nuxt["~runtimeDependencies"].push(...runtimeDependencies, "unhead", "@unhead/vue", "@nuxt/devalue", "unstorage", ...nitro.options.inlineDynamicImports ? ["vue", "@vue/server-renderer"] : []);
addVitePlugin({
name: "nuxt:nitro:ssr-conditions",
configEnvironment(name, config) {
if (name === "ssr") {
config.resolve ||= {};
config.resolve.conditions = [...nitro.options.exportConditions || [], "import"];
}
}
});
addVitePlugin({
name: "nuxt:nitro:vue-feature-flags",
applyToEnvironment: (environment) => environment.name === "ssr" && environment.config.isProduction,
configResolved(config) {
for (const key in config.define) if (key.startsWith("__VUE")) nitro.options.replace[key] = config.define[key];
}
});
nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
nuxt.hook("close", () => nitro.hooks.callHook("close"));
nitro.hooks.hook("prerender:routes", (routes) => {
return nuxt.callHook("prerender:routes", { routes });
});
if (nuxt.options.vue.runtimeCompiler) {
addVitePlugin({
name: "nuxt:vue:runtime-compiler",
applyToEnvironment: (environment) => environment.name === "client",
enforce: "pre",
resolveId(id, importer) {
if (id === "vue") return this.resolve("vue/dist/vue.esm-bundler", importer, { skipSelf: true });
}
});
for (const hook of ["webpack:config", "rspack:config"]) nuxt.hook(hook, (configuration) => {
const clientConfig = configuration.find((config) => config.name === "client");
if (!clientConfig.resolve) clientConfig.resolve.alias = {};
if (Array.isArray(clientConfig.resolve.alias)) clientConfig.resolve.alias.push({
name: "vue",
alias: "vue/dist/vue.esm-bundler"
});
else clientConfig.resolve.alias.vue = "vue/dist/vue.esm-bundler";
});
}
const devMiddlewareHandler = dynamicEventHandler();
nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
addDevServerHandlers(nitro.options.devHandlers, nuxt.options.devServerHandlers);
nitro.options.devHandlers = toPortableDevHandlers(nitro.options.devHandlers);
if (nuxt.options.dev) {
nitro.options.plugins.push(resolve(distDir, "runtime/plugins/dev-errors"));
nitro.options.handlers.unshift({
route: joinURL(nuxt.options.devServer.errorChannel, "**"),
lazy: true,
handler: resolve(distDir, "runtime/handlers/error-channel")
});
}
nitro.options.handlers.unshift({
route: "/__nuxt_error",
lazy: true,
handler: resolve(distDir, "runtime/handlers/renderer")
});
if (nuxt.options.experimental.chromeDevtoolsProjectSettings) {
const cacheDir = resolve(nuxt.options.rootDir, "node_modules/.cache/nuxt");
let projectConfiguration = await readFile(join(cacheDir, "chrome-workspace.json"), "utf-8").then((r) => JSON.parse(r)).catch(() => null);
if (!projectConfiguration) {
projectConfiguration = { uuid: randomUUID() };
await mkdir(cacheDir, { recursive: true });
await writeFile(join(cacheDir, "chrome-workspace.json"), JSON.stringify(projectConfiguration), "utf-8");
}
nitro.options.devHandlers.push({
route: "/.well-known/appspecific/com.chrome.devtools.json",
handler: defineEventHandler((event) => {
if (!isLoopbackPeer(event) || !isLocalDevRequest(event, getDevHandlerAllowedHosts(nuxt))) {
setResponseStatus(event, 403);
return "Forbidden";
}
return { workspace: {
...projectConfiguration,
root: nuxt.options.rootDir
} };
})
});
}
if (!nuxt.options.dev && nuxt.options.experimental.noVueServer) nitro.hooks.hook("rollup:before", (nitro) => {
if (nitro.options.preset === "nitro-prerender") {
nitro.options.errorHandler = resolve(distDir, "runtime/handlers/error");
return;
}
const nuxtErrorHandler = nitro.options.handlers.findIndex((h) => h.route === "/__nuxt_error");
if (nuxtErrorHandler >= 0) nitro.options.handlers.splice(nuxtErrorHandler, 1);
nitro.options.renderer = void 0;
});
nuxt.hook("server:routes", (routes, context) => {
context.requestTypes = {
module: REQUEST_TYPES_MODULE,
body: "RequestBodyOf",
query: "RequestQueryOf"
};
for (const handler of [...nitro.scannedHandlers, ...nitro.options.handlers]) {
if (!handler.route) continue;
for (const nodeKey of routeNodeKeys(handler.route)) routes.push({
segments: toRouteSegments(nodeKey),
route: handler.route,
method: handler.method,
handler: handler.handler,
middleware: handler.middleware
});
}
});
if (nuxt.options.dev) nitro.hooks.hook("types:extend", async () => {
await nuxt.callHook("builder:generateApp", { filter: (template) => template.filename === "server-routes.d.ts" });
});
nitro.hooks.hook("types:extend", (types) => {
types.tsConfig ||= {};
const rootDirGlob = relativeWithDot(typesDir, join(nuxt.options.rootDir, "**/*"));
types.tsConfig.include = types.tsConfig.include?.filter((i) => i !== rootDirGlob);
});
nuxt.hook("prepare:types", async (opts) => {
await writeTypes(nitro);
opts.tsConfig.exclude ||= [];
opts.tsConfig.exclude.push(relative(typesDir, resolve(nuxt.options.rootDir, nitro.options.output.dir)));
opts.tsConfig.exclude.push(relative(typesDir, resolve(nuxt.options.rootDir, nuxt.options.serverDir)));
opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
opts.tsConfig.compilerOptions ||= {};
opts.tsConfig.compilerOptions.paths ||= {};
opts.tsConfig.compilerOptions.paths[REQUEST_TYPES_MODULE] = [resolve(distDir, "request-types")];
Object.assign(opts.tsConfig.compilerOptions.paths, ownTypePaths);
opts.nodeTsConfig.compilerOptions ||= {};
opts.nodeTsConfig.compilerOptions.paths ||= {};
Object.assign(opts.nodeTsConfig.compilerOptions.paths, ownNodeTypePaths);
opts.sharedTsConfig.compilerOptions ||= {};
opts.sharedTsConfig.compilerOptions.paths ||= {};
for (const key in nuxt.options.alias) if (nitro.options.alias[key] && nitro.options.alias[key] === nuxt.options.alias[key]) {
const dirKey = join(key, "*");
if (opts.tsConfig.compilerOptions?.paths[key]) opts.sharedTsConfig.compilerOptions.paths[key] = opts.tsConfig.compilerOptions.paths[key];
if (opts.tsConfig.compilerOptions?.paths[dirKey]) opts.sharedTsConfig.compilerOptions.paths[dirKey] = opts.tsConfig.compilerOptions.paths[dirKey];
}
Object.assign(opts.sharedTsConfig.compilerOptions.paths, ownTypePaths);
});
if (nitro.options.static) nitro.hooks.hook("prerender:routes", (routes) => {
for (const route of ["/200.html", "/404.html"]) routes.add(route);
for (const status of errorPages) routes.add(`/${status}.html`);
if (clientOnlyApp) routes.add("/index.html");
});
if (!nuxt.options.dev) nitro.hooks.hook("rollup:before", async (nitro) => {
await copyPublicAssets(nitro);
await nuxt.callHook("nitro:build:public-assets", nitro);
});
async function symlinkDist() {
if (nitro.options.static) {
const distDir = resolve(nuxt.options.rootDir, "dist");
if (!existsSync(distDir)) await promises.symlink(nitro.options.output.publicDir, distDir, "junction").catch(() => {});
}
}
let waitUntilCompile;
if (nuxt.options.dev) {
let nitroBuilt = false;
const diskServerEntry = join(nuxt.options.buildDir, "dist/server/server.dev.mjs");
nitro.options.rollupConfig = defu(nitro.options.rollupConfig, { external: [/server\.dev\.mjs/] });
for (const builder of ["webpack", "rspack"]) {
nuxt.hook(`${builder}:compile`, ({ name, compiler }) => {
if (name === "server") nitro.options.virtual["nuxt/internal/entry"] = () => {
const memfs = compiler.outputFileSystem;
mkdirSync(join(nuxt.options.buildDir, "dist/server"), { recursive: true });
writeFileSync(diskServerEntry, memfs.readFileSync(join(nuxt.options.buildDir, "dist/server/server.mjs"), "utf-8"));
return `export { default } from ${JSON.stringify(pathToFileURL(diskServerEntry).href + "?v=" + Date.now())}`;
};
});
nuxt.hook(`${builder}:compiled`, () => {
if (nitroBuilt) nitro.hooks.callHook("rollup:reload");
});
}
nuxt.hook("vite:compiled", () => {
nuxt.server.reload();
});
nuxt.hook("server:devHandler", (h, options) => {
devMiddlewareHandler.set(defineEventHandler((event) => {
if (options.cors(event.path)) {
if (handleCors(event, nuxt.options.devServer.cors)) return null;
setHeader(event, "Vary", "Origin");
}
return h(event);
}));
});
nuxt.server = createDevServer(nitro);
waitUntilCompile = new Promise((resolve) => nitro.hooks.hook("compiled", () => {
nitroBuilt = true;
resolve();
}));
}
nuxt.hook("build:done", async () => {
nuxt._perf?.startPhase("nitro:build");
try {
await nuxt.callHook("nitro:build:before", nitro);
await prepare(nitro);
if (nuxt.options.dev) {
await build(nitro);
await waitUntilCompile;
return;
}
await prerender(nitro);
logger.restoreAll();
try {
await build(nitro);
} finally {
logger.wrapAll();
}
await symlinkDist();
} finally {
nuxt._perf?.endPhase("nitro:build");
}
});
}
const RELATIVE_RE = /^([^.])/;
function relativeWithDot(from, to) {
return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
}
async function spaLoadingTemplatePath(nuxt) {
if (typeof nuxt.options.spaLoadingTemplate === "string") return resolve(nuxt.options.srcDir, nuxt.options.spaLoadingTemplate);
const possiblePaths = nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.app || "app", "spa-loading-template.html"));
return await findPath(possiblePaths) ?? resolve(nuxt.options.srcDir, nuxt.options.dir?.app || "app", "spa-loading-template.html");
}
function getDevHandlerAllowedHosts(nuxt) {
const sources = [nuxt.options.devServer.allowedHosts, nuxt.options.vite?.server?.allowedHosts];
if (sources.includes(true)) return true;
const hosts = new Set(LOOPBACK_HOSTS);
for (const host of sources.flatMap((allowedHosts) => Array.isArray(allowedHosts) ? allowedHosts : [])) if (typeof host === "string" && host) hosts.add(host);
return hosts;
}
async function spaLoadingTemplate(nuxt) {
if (nuxt.options.spaLoadingTemplate === false) return "";
const spaLoadingTemplate = await spaLoadingTemplatePath(nuxt);
try {
if (existsSync(spaLoadingTemplate)) return readFileSync(spaLoadingTemplate, "utf-8").trim();
} catch {}
if (nuxt.options.spaLoadingTemplate === true) return template();
if (nuxt.options.spaLoadingTemplate) bundlerDiagnostics.NUXT_B7016({ path: nuxt.options.spaLoadingTemplate });
return "";
}
/**
* Compile page route patterns into a static matcher expression, so the renderer
* needs no runtime router construction.
*/
function compilePageMatcher(patterns) {
if (!patterns.length) return "undefined";
const router = createRouter();
for (const pattern of patterns) addRoute(router, "", pattern, 1);
return `/* @__PURE__ */ (() => {const foldRouteCase = ${foldRouteCase.toString()};const match = ${compileRouterToString(router)};return (method, path) => match(method, foldRouteCase(path));})()`;
}
/**
* Splits a rou3 node key, in which `*` marks a single matched segment and `**` the remaining
* ones, into the segments Nuxt emits types from. Consecutive static parts are kept together so
* the generated tree stays shallow.
*/
function toRouteSegments(nodeKey) {
const segments = [];
let staticValue = "";
for (const part of nodeKey.split("/")) {
if (!part) continue;
if (part !== "*" && part !== "**") {
staticValue += `/${part}`;
continue;
}
if (staticValue) {
segments.push({
type: "static",
value: staticValue
});
staticValue = "";
}
segments.push(part === "*" ? { type: "dynamic" } : { type: "wildcard" });
}
if (staticValue) segments.push({
type: "static",
value: staticValue
});
return segments.length ? segments : [{
type: "static",
value: "/"
}];
}
async function resolveOwnTypePaths(h3PackageJson, options) {
const [own, crossws] = await Promise.all([resolveTypePaths([
"nitropack/types",
"nitropack/runtime",
"nitropack",
"h3"
], [fileURLToPath(new URL(".", import.meta.url))], options), resolveTypePaths(["crossws"], [dirname(h3PackageJson)], options)]);
return Object.fromEntries([...own, ...crossws].map(([pkg, path]) => [pkg, [path]]));
}
export { bundle };
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.