Sign In

nitro

Package Overview
Dependencies
Maintainers
1
Versions
375
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nitro - npm Package Compare versions

Comparing version
3.0.1-alpha.0
to
3.0.1-alpha.1
+68
dist/_build/common.mjs
import { O as relative$1, k as resolve$1, w as join$1 } from "../_libs/c12.mjs";
import { i as writeFile$1 } from "../_chunks/C7CbzoI1.mjs";
import { dirname } from "node:path";
import { mkdir, readFile, stat } from "node:fs/promises";
import { version } from "nitro/meta";
//#region src/presets/_types.gen.ts
const presetsWithConfig = [
"awsAmplify",
"awsLambda",
"azure",
"cloudflare",
"firebase",
"netlify",
"vercel"
];
//#endregion
//#region src/build/info.ts
const NITRO_WELLKNOWN_DIR = "node_modules/.nitro";
async function getBuildInfo(root) {
const outputDir = await findLastBuildDir(root);
if (!await stat(outputDir).then((s) => s.isDirectory()).catch(() => false)) return {};
return {
outputDir,
buildInfo: await readFile(resolve$1(outputDir, "nitro.json"), "utf8").then(JSON.parse).catch(() => void 0)
};
}
async function findLastBuildDir(root) {
const lastBuildLink = join$1(root, NITRO_WELLKNOWN_DIR, "last-build.json");
return await readFile(lastBuildLink, "utf8").then(JSON.parse).then((data) => resolve$1(lastBuildLink, data.outputDir || "../../../.output")).catch(() => resolve$1(root, ".output"));
}
async function writeBuildInfo(nitro) {
const buildInfoPath = resolve$1(nitro.options.output.dir, "nitro.json");
const buildInfo = {
date: (/* @__PURE__ */ new Date()).toJSON(),
preset: nitro.options.preset,
framework: nitro.options.framework,
versions: { nitro: version },
commands: {
preview: nitro.options.commands.preview,
deploy: nitro.options.commands.deploy
},
config: { ...Object.fromEntries(presetsWithConfig.map((key) => [key, nitro.options[key]])) }
};
await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2), true);
const lastBuild = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "last-build.json");
await mkdir(dirname(lastBuild), { recursive: true });
await writeFile$1(lastBuild, JSON.stringify({ outputDir: relative$1(lastBuild, nitro.options.output.dir) }));
return buildInfo;
}
async function writeDevBuildInfo(nitro, addr) {
const buildInfoPath = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "nitro.dev.json");
const buildInfo = {
date: (/* @__PURE__ */ new Date()).toJSON(),
preset: nitro.options.preset,
framework: nitro.options.framework,
versions: { nitro: version },
dev: {
pid: process.pid,
workerAddress: addr
}
};
await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2));
}
//#endregion
export { writeBuildInfo as n, writeDevBuildInfo as r, getBuildInfo as t };
import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
import { O as relative, k as resolve, w as join, x as dirname } from "../_libs/c12.mjs";
import { i as unplugin } from "../_libs/unimport.mjs";
import { t as glob } from "../_libs/tinyglobby.mjs";
import { t as src_default } from "../_libs/mime.mjs";
import { i as genSafeVariableName, t as genImport } from "../_libs/knitwork.mjs";
import { t as unwasm } from "../_libs/unwasm.mjs";
import { t as replace } from "../_libs/plugin-replace.mjs";
import { t as require_etag } from "../_libs/etag.mjs";
import { camelCase } from "scule";
import { promises } from "node:fs";
import { joinURL, withTrailingSlash } from "ufo";
import { readFile } from "node:fs/promises";
import { defu } from "defu";
import { pkgDir, runtimeDependencies, runtimeDir } from "nitro/meta";
import { hash } from "ohash";
import { defineEnv } from "unenv";
import { connectors } from "db0";
import { transform } from "oxc-transform";
import { builtinDrivers, normalizeKey } from "unstorage";
import { rollupNodeFileTrace } from "nf3";
import { RENDER_CONTEXT_KEYS, compileTemplateToString, hasTemplateSyntax } from "rendu";
//#region src/build/config.ts
function baseBuildConfig(nitro) {
const presetsDir$1 = resolve(runtimeDir, "../presets");
const extensions = [
".ts",
".mjs",
".js",
".json",
".node",
".tsx",
".jsx"
];
const isNodeless = nitro.options.node === false;
const importMetaInjections = {
dev: nitro.options.dev,
preset: nitro.options.preset,
prerender: nitro.options.preset === "nitro-prerender",
nitro: true,
server: true,
client: false,
baseURL: nitro.options.baseURL,
_asyncContext: nitro.options.experimental.asyncContext,
_tasks: nitro.options.experimental.tasks
};
const replacements = {
...Object.fromEntries(Object.entries(importMetaInjections).map(([key, val]) => [`import.meta.${key}`, JSON.stringify(val)])),
...nitro.options.replace
};
const noExternal = [
"#",
"~",
"@/",
"~~",
"@@/",
"virtual:",
"nitro",
pkgDir,
nitro.options.serverDir,
nitro.options.buildDir,
dirname(nitro.options.entry),
...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [],
...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"),
...nitro.options.dev || nitro.options.preset === "nitro-prerender" ? [] : runtimeDependencies
].filter(Boolean);
const { env } = defineEnv({
nodeCompat: isNodeless,
resolve: true,
presets: nitro.options.unenv,
overrides: { alias: nitro.options.alias }
});
return {
presetsDir: presetsDir$1,
extensions,
isNodeless,
replacements,
env,
aliases: resolveAliases({ ...env.alias }),
noExternal
};
}
function resolveAliases(_aliases) {
const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length));
for (const key in aliases) for (const alias in aliases) {
if (![
"~",
"@",
"#"
].includes(alias[0])) continue;
if (alias === "@" && !aliases[key].startsWith("@/")) continue;
if (aliases[key].startsWith(alias)) aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
return aliases;
}
//#endregion
//#region src/build/plugins/virtual.ts
const PREFIX = "\0virtual:";
function virtual(modules, cache = {}, opts) {
const _modules = /* @__PURE__ */ new Map();
for (const [id, mod] of Object.entries(modules)) {
cache[id] = mod;
_modules.set(id, mod);
_modules.set(resolve(id), mod);
}
return {
name: "virtual",
resolveId(id, importer) {
if (id in modules) return {
id: PREFIX + id,
...opts
};
if (importer) {
const resolved = resolve(dirname(importer.startsWith(PREFIX) ? importer.slice(9) : importer), id);
if (_modules.has(resolved)) return PREFIX + resolved;
}
return null;
},
async load(id) {
if (!id.startsWith(PREFIX)) return null;
const idNoPrefix = id.slice(9);
if (!_modules.has(idNoPrefix)) return null;
let m = _modules.get(idNoPrefix);
if (typeof m === "function") m = await m();
if (!m) return null;
cache[id.replace(PREFIX, "")] = m;
return {
code: m,
map: null
};
}
};
}
//#endregion
//#region src/build/plugins/database.ts
function database(nitro) {
if (!nitro.options.experimental.database) return virtual({ "#nitro-internal-virtual/database": () => {
return `export const connectionConfigs = {};`;
} }, nitro.vfs);
const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database;
const connectorsNames = [...new Set(Object.values(dbConfigs || {}).map((config) => config?.connector))].filter(Boolean);
for (const name of connectorsNames) if (!connectors[name]) throw new Error(`Database connector "${name}" is invalid.`);
return virtual({ "#nitro-internal-virtual/database": () => {
return `
${connectorsNames.map((name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`).join("\n")}
export const connectionConfigs = {
${Object.entries(dbConfigs || {}).map(([name, { connector, options }]) => `${name}: {
connector: ${camelCase(connector)}Connector,
options: ${JSON.stringify(options)}
}`).join(",\n")}
};
`;
} }, nitro.vfs);
}
//#endregion
//#region src/build/plugins/routing.ts
const RuntimeRouteRules = [
"headers",
"redirect",
"proxy",
"cache"
];
function routing(nitro) {
return virtual({
"#nitro-internal-virtual/routing": () => {
const allHandlers = uniqueBy([
...Object.values(nitro.routing.routes.routes).flatMap((h) => h.data),
...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data),
...nitro.routing.globalMiddleware
], "_importHash");
return `
import * as __routeRules__ from "nitro/~internal/runtime/route-rules";
import * as srvxNode from "srvx/node"
import * as h3 from "h3";
export const findRouteRules = ${nitro.routing.routeRules.compileToString({
serialize: serializeRouteRule,
matchAll: true
})}
const multiHandler = (...handlers) => {
const final = handlers.pop()
const middleware = handlers.filter(Boolean).map(h => h3.toMiddleware(h));
return (ev) => h3.callMiddleware(ev, middleware, final);
}
${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "${h.handler}";`).join("\n")}
${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")}
export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({
serialize: serializeHandler,
matchAll: true
})};
export const globalMiddleware = [
${nitro.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `h3.toEventHandler(${h._importHash})`).join(",")}
].filter(Boolean);
`;
},
"#nitro-internal-virtual/routing-meta": () => {
const routeHandlers = uniqueBy(Object.values(nitro.routing.routes.routes).flatMap((h) => h.data), "_importHash");
return `
${routeHandlers.map((h) => `import ${h._importHash}Meta from "${h.handler}?meta";`).join("\n")}
export const handlersMeta = [
${routeHandlers.map((h) => `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(h.method?.toLowerCase())}, meta: ${h._importHash}Meta }`).join(",\n")}
];
`.trim();
}
}, nitro.vfs);
}
function uniqueBy(arr, key) {
return [...new Map(arr.map((item) => [item[key], item])).values()];
}
function serializeHandler(h) {
const meta = Array.isArray(h) ? h[0] : h;
return `{${[
`route:${JSON.stringify(meta.route)}`,
meta.method && `method:${JSON.stringify(meta.method)}`,
meta.meta && `meta:${JSON.stringify(meta.meta)}`,
`handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
].filter(Boolean).join(",")}}`;
}
function serializeHandlerFn(h) {
let code = h._importHash;
if (!h.lazy) {
if (h.format === "node") code = `srvxNode.toFetchHandler(${code})`;
code = `h3.toEventHandler(${code})`;
}
return code;
}
function serializeRouteRule(h) {
return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => {
return `{${[
`name:${JSON.stringify(name)}`,
`route:${JSON.stringify(h._route)}`,
h._method && `method:${JSON.stringify(h._method)}`,
RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`,
`options:${JSON.stringify(options)}`
].filter(Boolean).join(",")}}`;
}).join(",")}]`;
}
//#endregion
//#region src/build/plugins/route-meta.ts
const virtualPrefix = "\0nitro-handler-meta:";
function routeMeta(nitro) {
return {
name: "nitro:route-meta",
async resolveId(id, importer, resolveOpts) {
if (id.startsWith("\0")) return;
if (id.endsWith(`?meta`)) {
const resolved = await this.resolve(id.replace(`?meta`, ``), importer, resolveOpts);
if (!resolved) return;
return virtualPrefix + resolved.id;
}
},
load(id) {
if (id.startsWith(virtualPrefix)) return readFile(id.slice(20), { encoding: "utf8" });
},
async transform(code, id) {
if (!id.startsWith(virtualPrefix)) return;
let meta = null;
try {
const jsCode = transform(id, code).code;
const ast = this.parse(jsCode);
for (const node of ast.body) if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) {
meta = astToObject(node.expression.arguments[0]);
break;
}
} catch (error) {
nitro.logger.warn(`[handlers-meta] Cannot extra route meta for: ${id}: ${error}`);
}
return {
code: `export default ${JSON.stringify(meta)};`,
map: null
};
}
};
}
function astToObject(node) {
switch (node.type) {
case "ObjectExpression": {
const obj = {};
for (const prop of node.properties) if (prop.type === "Property") {
const key = prop.key.name ?? prop.key.value;
obj[key] = astToObject(prop.value);
}
return obj;
}
case "ArrayExpression": return node.elements.map((el) => astToObject(el)).filter(Boolean);
case "Literal": return node.value;
}
}
//#endregion
//#region src/build/plugins/server-main.ts
function serverMain(nitro) {
return {
name: "nitro:server-main",
renderChunk(code, chunk) {
if (chunk.isEntry) return {
code: `globalThis.__nitro_main__ = import.meta.url; ${code}`,
map: null
};
}
};
}
//#endregion
//#region src/build/plugins/public-assets.ts
var import_etag$1 = /* @__PURE__ */ __toESM(require_etag(), 1);
const readAssetHandler = {
true: "node",
node: "node",
false: "null",
deno: "deno",
inline: "inline"
};
function publicAssets(nitro) {
return virtual({
"#nitro-internal-virtual/public-assets-data": async () => {
const assets = {};
const files = await glob("**", {
cwd: nitro.options.output.publicDir,
absolute: false,
dot: true
});
for (const id of files) {
let mimeType = src_default.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
if (mimeType.startsWith("text")) mimeType += "; charset=utf-8";
const fullPath = resolve(nitro.options.output.publicDir, id);
const assetData = await promises.readFile(fullPath);
const etag = (0, import_etag$1.default)(assetData);
const stat$1 = await promises.stat(fullPath);
const assetId = joinURL(nitro.options.baseURL, decodeURIComponent(id));
let encoding;
if (id.endsWith(".gz")) encoding = "gzip";
else if (id.endsWith(".br")) encoding = "br";
assets[assetId] = {
type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType,
encoding,
etag,
mtime: stat$1.mtime.toJSON(),
size: stat$1.size,
path: relative(nitro.options.output.serverDir, fullPath),
data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
};
}
return `export default ${JSON.stringify(assets, null, 2)};`;
},
"#nitro-internal-virtual/public-assets-node": () => {
return `
import { promises as fsp } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve, dirname } from 'node:path'
import assets from '#nitro-internal-virtual/public-assets-data'
export function readAsset (id) {
const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__))
return fsp.readFile(resolve(serverDir, assets[id].path))
}`;
},
"#nitro-internal-virtual/public-assets-deno": () => {
return `
import assets from '#nitro-internal-virtual/public-assets-data'
export function readAsset (id) {
// https://deno.com/deploy/docs/serve-static-assets
const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
return Deno.readFile(path);
}`;
},
"#nitro-internal-virtual/public-assets-null": () => {
return `
export function readAsset (id) {
return Promise.resolve(null);
}`;
},
"#nitro-internal-virtual/public-assets-inline": () => {
return `
import assets from '#nitro-internal-virtual/public-assets-data'
export function readAsset (id) {
if (!assets[id]) { return undefined }
if (assets[id]._data) { return assets[id]._data }
if (!assets[id].data) { return assets[id].data }
assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
return assets[id]._data
}`;
},
"#nitro-internal-virtual/public-assets": () => {
const publicAssetBases = Object.fromEntries(nitro.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [withTrailingSlash(joinURL(nitro.options.baseURL, dir.baseURL || "/")), { maxAge: dir.maxAge }]));
return `
import assets from '#nitro-internal-virtual/public-assets-data'
export { readAsset } from "${`#nitro-internal-virtual/public-assets-${readAssetHandler[nitro.options.serveStatic] || "null"}`}"
export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
export function isPublicAssetURL(id = '') {
if (assets[id]) {
return true
}
for (const base in publicAssetBases) {
if (id.startsWith(base)) { return true }
}
return false
}
export function getPublicAssetMeta(id = '') {
for (const base in publicAssetBases) {
if (id.startsWith(base)) { return publicAssetBases[base] }
}
return {}
}
export function getAsset (id) {
return assets[id]
}
`;
}
}, nitro.vfs);
}
//#endregion
//#region src/build/plugins/server-assets.ts
var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
function serverAssets(nitro) {
if (nitro.options.dev || nitro.options.preset === "nitro-prerender") return virtual({ "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) }, nitro.vfs);
return virtual({ "#nitro-internal-virtual/server-assets": async () => {
const assets = {};
for (const asset of nitro.options.serverAssets) {
const files = await glob(asset.pattern || "**/*", {
cwd: asset.dir,
absolute: false,
ignore: asset.ignore
});
for (const _id of files) {
const fsPath = resolve(asset.dir, _id);
const id = asset.baseName + "/" + _id;
assets[id] = {
fsPath,
meta: {}
};
let type = src_default.getType(id) || "text/plain";
if (type.startsWith("text")) type += "; charset=utf-8";
const etag = (0, import_etag.default)(await promises.readFile(fsPath));
const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
assets[id].meta = {
type,
etag,
mtime
};
}
}
return getAssetProd(assets);
} }, nitro.vfs);
}
function getAssetsDev(nitro) {
return `
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/fs'
const serverAssets = ${JSON.stringify(nitro.options.serverAssets)}
export const assets = createStorage()
for (const asset of serverAssets) {
assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
}`;
}
function getAssetProd(assets) {
return `
const _assets = {\n${Object.entries(assets).map(([id, asset]) => ` [${JSON.stringify(normalizeKey(id))}]: {\n import: () => import(${JSON.stringify("raw:" + asset.fsPath)}).then(r => r.default || r),\n meta: ${JSON.stringify(asset.meta)}\n }`).join(",\n")}\n}
const normalizeKey = ${normalizeKey.toString()}
export const assets = {
getKeys() {
return Promise.resolve(Object.keys(_assets))
},
hasItem (id) {
id = normalizeKey(id)
return Promise.resolve(id in _assets)
},
getItem (id) {
id = normalizeKey(id)
return Promise.resolve(_assets[id] ? _assets[id].import() : null)
},
getMeta (id) {
id = normalizeKey(id)
return Promise.resolve(_assets[id] ? _assets[id].meta : {})
}
}
`;
}
//#endregion
//#region src/build/plugins/storage.ts
function storage(nitro) {
const mounts = [];
const storageMounts = nitro.options.dev || nitro.options.preset === "nitro-prerender" ? {
...nitro.options.storage,
...nitro.options.devStorage
} : nitro.options.storage;
for (const path in storageMounts) {
const mount = storageMounts[path];
mounts.push({
path,
driver: builtinDrivers[mount.driver] || mount.driver,
opts: mount
});
}
const driverImports = [...new Set(mounts.map((m) => m.driver))];
return virtual({ "#nitro-internal-virtual/storage": `
import { createStorage } from 'unstorage'
import { assets } from '#nitro-internal-virtual/server-assets'
${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
export function initStorage() {
const storage = createStorage({})
storage.mount('/assets', assets)
${mounts.map((m) => `storage.mount('${m.path}', ${genSafeVariableName(m.driver)}(${JSON.stringify(m.opts)}))`).join("\n")}
return storage
}
` }, nitro.vfs);
}
//#endregion
//#region src/build/plugins/error-handler.ts
function errorHandler(nitro) {
return virtual({ "#nitro-internal-virtual/error-handler": () => {
const errorHandlers = Array.isArray(nitro.options.errorHandler) ? nitro.options.errorHandler : [nitro.options.errorHandler];
const builtinHandler = join(runtimeDir, `internal/error/${nitro.options.dev ? "dev" : "prod"}`);
return `
${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")}
const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}];
import { defaultHandler } from "${builtinHandler}";
export default async function(error, event) {
for (const handler of errorHandlers) {
try {
const response = await handler(error, event, { defaultHandler });
if (response) {
return response;
}
} catch(error) {
// Handler itself thrown, log and continue
console.error(error);
}
}
// H3 will handle fallback
}
`;
} }, nitro.vfs);
}
//#endregion
//#region src/build/plugins/renderer-template.ts
function rendererTemplate(nitro) {
return virtual({ "#nitro-internal-virtual/renderer-template": async () => {
const template = nitro.options.renderer?.template;
if (typeof template !== "string") return `
export const rendererTemplate = () => '<!-- renderer.template is not set -->';
export const rendererTemplateFile = undefined;
export const isStaticTemplate = true;`;
if (nitro.options.dev) return `
import { readFile } from 'node:fs/promises';
export const rendererTemplate = () => readFile(${JSON.stringify(template)}, "utf8");
export const rendererTemplateFile = ${JSON.stringify(template)};
export const isStaticTemplate = ${JSON.stringify(nitro.options.renderer?.static)};
`;
else {
const html = await readFile(template, "utf8");
if (nitro.options.renderer?.static ?? !hasTemplateSyntax(html)) return `
import { HTTPResponse } from "h3";
export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } });
`;
else return `
import { renderToResponse } from 'rendu'
import { serverFetch } from 'nitro/app'
const template = ${compileTemplateToString(html, { contextKeys: [...RENDER_CONTEXT_KEYS] })};
export const rendererTemplate = (request) => renderToResponse(template, { request, context: { serverFetch } })
`;
}
} }, nitro.vfs);
}
//#endregion
//#region src/build/plugins/feature-flags.ts
function featureFlags(nitro) {
return virtual({ "#nitro-internal-virtual/feature-flags": () => {
const featureFlags$1 = {
hasRoutes: nitro.routing.routes.hasRoutes(),
hasRouteRules: nitro.routing.routeRules.hasRoutes(),
hasRoutedMiddleware: nitro.routing.routedMiddleware.hasRoutes(),
hasGlobalMiddleware: nitro.routing.globalMiddleware.length > 0,
hasPlugins: nitro.options.plugins.length > 0,
hasHooks: nitro.options.features?.runtimeHooks ?? nitro.options.plugins.length > 0,
hasWebSocket: nitro.options.features?.websocket ?? nitro.options.experimental.websocket ?? false
};
return Object.entries(featureFlags$1).map(([key, value]) => `export const ${key} = ${Boolean(value)};`).join("\n");
} }, nitro.vfs);
}
//#endregion
//#region src/build/plugins/resolve.ts
const subpathMap = {
"nitro/h3": "h3",
"nitro/deps/h3": "h3",
"nitro/deps/ofetch": "ofetch"
};
function nitroResolveIds() {
return {
name: "nitro:resolve-ids",
resolveId: {
order: "pre",
handler(id, importer, rOpts) {
if (importer && importer.startsWith("\0virtual:#nitro-internal-virtual")) return this.resolve(id, runtimeDir, { skipSelf: true });
const mappedId = subpathMap[id];
if (mappedId) return this.resolve(mappedId, runtimeDir, { skipSelf: true });
}
}
};
}
//#endregion
//#region src/build/plugins/sourcemap-min.ts
function sourcemapMinify() {
return {
name: "nitro:sourcemap-minify",
generateBundle(_options, bundle) {
for (const [key, asset] of Object.entries(bundle)) {
if (!key.endsWith(".map") || !("source" in asset) || typeof asset.source !== "string") continue;
const sourcemap = JSON.parse(asset.source);
delete sourcemap.sourcesContent;
delete sourcemap.x_google_ignoreList;
if ((sourcemap.sources || []).some((s) => s.includes("node_modules"))) sourcemap.mappings = "";
asset.source = JSON.stringify(sourcemap);
}
}
};
}
//#endregion
//#region src/build/plugins/raw.ts
const HELPER_ID = "virtual:raw-helpers";
const RESOLVED_RAW_PREFIX = "virtual:raw:";
function raw() {
return {
name: "raw",
resolveId: {
order: "pre",
async handler(id, importer, resolveOpts) {
if (id === HELPER_ID) return id;
if (id.startsWith("raw:")) return { id: RESOLVED_RAW_PREFIX + (await this.resolve(id.slice(4), importer, resolveOpts))?.id };
}
},
load: {
order: "pre",
handler(id) {
if (id === HELPER_ID) return getHelpers();
if (id.startsWith(RESOLVED_RAW_PREFIX)) return promises.readFile(id.slice(12), isBinary(id) ? "binary" : "utf8");
}
},
transform: {
order: "pre",
handler(code, id) {
if (!id.startsWith(RESOLVED_RAW_PREFIX)) return;
if (isBinary(id)) return {
code: `import {base64ToUint8Array } from "${HELPER_ID}" \n export default base64ToUint8Array("${Buffer.from(code, "binary").toString("base64")}")`,
map: null
};
return {
code: `export default ${JSON.stringify(code)}`,
map: null,
moduleType: "js"
};
}
}
};
}
function isBinary(id) {
const idMime = src_default.getType(id) || "";
if (idMime.startsWith("text/")) return false;
if (/application\/(json|sql|xml|yaml)/.test(idMime)) return false;
return true;
}
function getHelpers() {
return String.raw`
export function base64ToUint8Array(str) {
const data = atob(str);
const size = data.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = data.charCodeAt(i);
}
return bytes;
}
`;
}
//#endregion
//#region src/build/plugins/runtime-config.ts
function runtimeConfig(nitro) {
return virtual({ "#nitro-internal-virtual/runtime-config": () => {
return `export const runtimeConfig = ${JSON.stringify(nitro.options.runtimeConfig || {})};`;
} }, nitro.vfs);
}
//#endregion
//#region src/build/plugins.ts
function baseBuildPlugins(nitro, base) {
const plugins = [];
if (nitro.options.imports) plugins.push(unplugin.rollup(nitro.options.imports));
if (nitro.options.experimental.wasm) plugins.push(unwasm(nitro.options.wasm || {}));
plugins.push(serverMain(nitro));
const nitroPlugins = [...new Set(nitro.options.plugins)];
plugins.push(virtual({ "#nitro-internal-virtual/plugins": `
${nitroPlugins.map((plugin) => `import _${hash(plugin).replace(/-/g, "")} from '${plugin}';`).join("\n")}
export const plugins = [
${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")}
]
` }, nitro.vfs));
plugins.push(featureFlags(nitro));
plugins.push(nitroResolveIds());
plugins.push(serverAssets(nitro));
plugins.push(publicAssets(nitro));
plugins.push(storage(nitro));
plugins.push(database(nitro));
plugins.push(routing(nitro));
plugins.push(raw());
if (nitro.options.experimental.openAPI) plugins.push(routeMeta(nitro));
plugins.push(runtimeConfig(nitro));
plugins.push(errorHandler(nitro));
plugins.push(virtual({ "#nitro-internal-pollyfills": base.env.polyfill.map((p) => `import '${p}';`).join("\n") || `/* No polyfills */` }, nitro.vfs, { moduleSideEffects: true }));
plugins.push(virtual(nitro.options.virtual, nitro.vfs));
if (nitro.options.renderer?.template) plugins.push(rendererTemplate(nitro));
plugins.push(replace({
preventAssignment: true,
values: base.replacements
}));
if (!nitro.options.noExternals) plugins.push(rollupNodeFileTrace(defu(nitro.options.externals, {
outDir: nitro.options.output.serverDir,
moduleDirectories: nitro.options.nodeModulesDirs,
external: nitro.options.nodeModulesDirs,
inline: [...base.noExternal],
traceOptions: {
base: "/",
processCwd: nitro.options.rootDir,
exportsOnly: true
},
traceAlias: {
"h3-nightly": "h3",
...nitro.options.externals?.traceAlias
},
exportConditions: nitro.options.exportConditions,
writePackageJson: true
})));
if (nitro.options.sourcemap && !nitro.options.dev && nitro.options.experimental.sourcemapMinify !== false) plugins.push(sourcemapMinify());
return plugins;
}
//#endregion
export { baseBuildConfig as n, baseBuildPlugins as t };
import { O as relative, T as normalize, n as debounce, w as join } from "../_libs/c12.mjs";
import "../_libs/gen-mapping.mjs";
import "../_libs/magic-string.mjs";
import "../_libs/acorn.mjs";
import "../_libs/confbox.mjs";
import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs";
import "../_libs/js-tokens.mjs";
import "../_libs/strip-literal.mjs";
import "../_libs/unimport.mjs";
import "../_libs/picomatch.mjs";
import "../_libs/fdir.mjs";
import "../_libs/tinyglobby.mjs";
import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
import "../_libs/std-env.mjs";
import "../_libs/dot-prop.mjs";
import "../_chunks/C7CbzoI1.mjs";
import { i as scanHandlers, n as writeTypes } from "../_chunks/ANM1K1bE.mjs";
import "../_libs/mime.mjs";
import "../_libs/pathe.mjs";
import "../_libs/untyped.mjs";
import "../_libs/knitwork.mjs";
import { n as writeBuildInfo } from "./common.mjs";
import { i as watch$1 } from "../_libs/chokidar.mjs";
import "../_libs/estree-walker.mjs";
import "../_libs/plugin-commonjs.mjs";
import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs";
import "../_libs/remapping.mjs";
import "../_libs/unwasm.mjs";
import "../_libs/plugin-replace.mjs";
import "../_libs/etag.mjs";
import "../_libs/duplexer.mjs";
import "../_libs/gzip-size.mjs";
import "../_libs/pretty-bytes.mjs";
import { t as generateFSTree } from "../_chunks/BX9-zVkM.mjs";
import { builtinModules } from "node:module";
import { watch } from "node:fs";
import { defu } from "defu";
import { runtimeDir } from "nitro/meta";
//#region src/build/rolldown/config.ts
const getRolldownConfig = (nitro) => {
const base = baseBuildConfig(nitro);
const chunkNamePrefixes = [
[runtimeDir, "nitro"],
[base.presetsDir, "nitro"],
["\0raw:", "raw"],
["\0nitro-wasm:", "wasm"],
["\0", "virtual"]
];
const tsc = nitro.options.typescript.tsConfig?.compilerOptions;
let config = {
cwd: nitro.options.rootDir,
input: nitro.options.entry,
external: [
...base.env.external,
...builtinModules,
...builtinModules.map((m) => `node:${m}`)
],
plugins: [...baseBuildPlugins(nitro, base)],
resolve: {
alias: base.aliases,
extensions: base.extensions,
mainFields: ["main"],
conditionNames: nitro.options.exportConditions
},
transform: {
inject: base.env.inject,
jsx: {
runtime: tsc?.jsx === "react" ? "classic" : "automatic",
pragma: tsc?.jsxFactory,
pragmaFrag: tsc?.jsxFragmentFactory,
importSource: tsc?.jsxImportSource,
development: nitro.options.dev
}
},
onwarn(warning, warn) {
if (!["CIRCULAR_DEPENDENCY", "EVAL"].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) warn(warning);
},
treeshake: { moduleSideEffects(id) {
return nitro.options.moduleSideEffects.some((p) => id.startsWith(p));
} },
output: {
dir: nitro.options.output.serverDir,
entryFileNames: "index.mjs",
minify: nitro.options.minify,
chunkFileNames(chunk) {
const id = normalize(chunk.moduleIds.at(-1) || "");
for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`;
const routeHandler = nitro.options.handlers.find((h) => id.startsWith(h.handler)) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
if (routeHandler?.route) return `chunks/routes${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "").replace(/[^a-zA-Z0-9/_-]/g, "_") || "/"}/[name].mjs`;
if (Object.entries(nitro.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`;
return `chunks/_/[name].mjs`;
},
inlineDynamicImports: nitro.options.inlineDynamicImports,
format: "esm",
exports: "auto",
intro: "",
outro: "",
sanitizeFileName: sanitizeFilePath,
sourcemap: nitro.options.sourcemap,
sourcemapIgnoreList(relativePath) {
return relativePath.includes("node_modules");
}
}
};
config = defu(nitro.options.rollupConfig, config);
return config;
};
//#endregion
//#region src/build/rolldown/dev.ts
async function watchDev(nitro, config) {
const rolldown = await import("rolldown");
let watcher;
async function load() {
if (watcher) await watcher.close();
await scanHandlers(nitro);
nitro.routing.sync();
watcher = startWatcher(nitro, config);
await writeTypes(nitro);
}
const reload = debounce(load);
const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
join(dir, nitro.options.apiDir || "api"),
join(dir, nitro.options.routesDir || "routes"),
join(dir, "middleware"),
join(dir, "plugins"),
join(dir, "modules")
]);
const watchReloadEvents = new Set([
"add",
"addDir",
"unlink",
"unlinkDir"
]);
const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event) => {
if (watchReloadEvents.has(event)) reload();
});
const rootDirWatcher = watch(nitro.options.rootDir, { persistent: false }, (_event, filename) => {
if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
});
nitro.hooks.hook("close", () => {
watcher.close();
scanDirsWatcher.close();
rootDirWatcher.close();
});
nitro.hooks.hook("rollup:reload", () => reload());
await load();
function startWatcher(nitro$1, config$1) {
const watcher$1 = rolldown.watch(config$1);
let start;
watcher$1.on("event", (event) => {
switch (event.code) {
case "START":
start = Date.now();
nitro$1.logger.info(`Starting dev watcher (builder: \`rolldown\`, preset: \`${nitro$1.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro$1.options.compatibilityDate)}\`)`);
nitro$1.hooks.callHook("dev:start");
break;
case "BUNDLE_END":
nitro$1.hooks.callHook("compiled", nitro$1);
if (nitro$1.options.logging.buildSuccess) nitro$1.logger.success(`Server built`, start ? `in ${Date.now() - start}ms` : "");
nitro$1.hooks.callHook("dev:reload");
break;
case "ERROR": nitro$1.hooks.callHook("dev:error", event.error);
}
});
return watcher$1;
}
}
//#endregion
//#region src/build/rolldown/prod.ts
async function buildProduction(nitro, config) {
const rolldown = await import("rolldown");
const buildStartTime = Date.now();
await scanHandlers(nitro);
await writeTypes(nitro);
if (!nitro.options.static) {
nitro.logger.info(`Building server (builder: \`rolldown\`, preset: \`${nitro.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro.options.compatibilityDate)}\`)`);
await (await rolldown.rolldown(config)).write(config.output);
}
const buildInfo = await writeBuildInfo(nitro);
if (!nitro.options.static) {
if (nitro.options.logging.buildSuccess) nitro.logger.success(`Server built in ${Date.now() - buildStartTime}ms`);
if (nitro.options.logLevel > 1) process.stdout.write(await generateFSTree(nitro.options.output.serverDir, { compressedSizes: nitro.options.logging.compressedSizes }) || "");
}
await nitro.hooks.callHook("compiled", nitro);
const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input) => {
return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
};
if (buildInfo.commands.preview) nitro.logger.success(`You can preview this build using \`${rewriteRelativePaths(buildInfo.commands.preview)}\``);
if (buildInfo.commands.deploy) nitro.logger.success(`You can deploy this build using \`${rewriteRelativePaths(buildInfo.commands.deploy)}\``);
}
//#endregion
//#region src/build/rolldown/build.ts
async function rolldownBuild(nitro) {
await nitro.hooks.callHook("build:before", nitro);
const config = getRolldownConfig(nitro);
await nitro.hooks.callHook("rollup:before", nitro, config);
return nitro.options.dev ? watchDev(nitro, config) : buildProduction(nitro, config);
}
//#endregion
export { rolldownBuild };
import { C as isAbsolute, O as relative, T as normalize, n as debounce, w as join } from "../_libs/c12.mjs";
import "../_libs/gen-mapping.mjs";
import "../_libs/magic-string.mjs";
import "../_libs/acorn.mjs";
import "../_libs/confbox.mjs";
import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs";
import "../_libs/js-tokens.mjs";
import "../_libs/strip-literal.mjs";
import "../_libs/unimport.mjs";
import "../_libs/picomatch.mjs";
import "../_libs/fdir.mjs";
import "../_libs/tinyglobby.mjs";
import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
import "../_libs/std-env.mjs";
import "../_libs/dot-prop.mjs";
import "../_chunks/C7CbzoI1.mjs";
import { i as scanHandlers, n as writeTypes } from "../_chunks/ANM1K1bE.mjs";
import "../_libs/mime.mjs";
import "../_libs/pathe.mjs";
import "../_libs/untyped.mjs";
import "../_libs/knitwork.mjs";
import { n as writeBuildInfo } from "./common.mjs";
import { i as watch$1 } from "../_libs/chokidar.mjs";
import { t as alias } from "../_libs/plugin-alias.mjs";
import "../_libs/estree-walker.mjs";
import { t as commonjs } from "../_libs/plugin-commonjs.mjs";
import { t as inject } from "../_libs/plugin-inject.mjs";
import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs";
import "../_libs/remapping.mjs";
import "../_libs/unwasm.mjs";
import "../_libs/plugin-replace.mjs";
import "../_libs/etag.mjs";
import "../_libs/duplexer.mjs";
import "../_libs/gzip-size.mjs";
import "../_libs/pretty-bytes.mjs";
import { t as generateFSTree } from "../_chunks/BX9-zVkM.mjs";
import "../_libs/commondir.mjs";
import "../_libs/is-reference.mjs";
import { t as json } from "../_libs/plugin-json.mjs";
import "../_libs/deepmerge.mjs";
import "../_libs/is-module.mjs";
import { t as nodeResolve } from "../_libs/plugin-node-resolve.mjs";
import "../_libs/path-parse.mjs";
import "../_libs/function-bind.mjs";
import "../_libs/hasown.mjs";
import "../_libs/is-core-module.mjs";
import { watch } from "node:fs";
import { defu } from "defu";
import { runtimeDir } from "nitro/meta";
import { transform } from "oxc-transform";
import { minify } from "oxc-minify";
//#region src/build/plugins/oxc.ts
function oxc(options) {
const filter = (id) => !/node_modules/.test(id) && /\.[mj]?[jt]sx?$/.test(id);
return {
name: "nitro:oxc",
async transform(code, id) {
if (!filter(id)) return null;
return transform(id, code, {
sourcemap: options.sourcemap,
...options.transform
});
},
async renderChunk(code, chunk) {
if (options.minify) return minify(chunk.fileName, code, {
sourcemap: options.sourcemap,
...typeof options.minify === "object" ? options.minify : {}
});
return null;
}
};
}
//#endregion
//#region src/build/rollup/config.ts
const getRollupConfig = (nitro) => {
const base = baseBuildConfig(nitro);
const chunkNamePrefixes = [
[runtimeDir, "nitro"],
[base.presetsDir, "nitro"],
["\0raw:", "raw"],
["\0nitro-wasm:", "wasm"],
["\0", "virtual"]
];
function getChunkGroup(id) {
if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) return "nitro";
}
const tsc = nitro.options.typescript.tsConfig?.compilerOptions;
let config = {
input: nitro.options.entry,
external: [...base.env.external],
plugins: [
...baseBuildPlugins(nitro, base),
oxc({
sourcemap: !!nitro.options.sourcemap,
minify: nitro.options.minify ? { ...nitro.options.oxc?.minify } : false,
transform: {
target: "esnext",
cwd: nitro.options.rootDir,
...nitro.options.oxc?.transform,
jsx: {
runtime: tsc?.jsx === "react" ? "classic" : "automatic",
pragma: tsc?.jsxFactory,
pragmaFrag: tsc?.jsxFragmentFactory,
importSource: tsc?.jsxImportSource,
development: nitro.options.dev,
...nitro.options.oxc?.transform?.jsx
}
}
}),
alias({ entries: base.aliases }),
nodeResolve({
extensions: base.extensions,
preferBuiltins: !!nitro.options.node,
rootDir: nitro.options.rootDir,
modulePaths: nitro.options.nodeModulesDirs,
mainFields: ["main"],
exportConditions: nitro.options.exportConditions
}),
commonjs({ ...nitro.options.commonJS }),
json(),
inject(base.env.inject)
],
onwarn(warning, rollupWarn) {
if (![
"EVAL",
"CIRCULAR_DEPENDENCY",
"THIS_IS_UNDEFINED"
].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) rollupWarn(warning);
},
treeshake: { moduleSideEffects(id) {
return nitro.options.moduleSideEffects.some((p) => id.startsWith(p));
} },
output: {
dir: nitro.options.output.serverDir,
entryFileNames: "index.mjs",
chunkFileNames(chunk) {
const id = normalize(chunk.moduleIds.at(-1) || "");
for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`;
const routeHandler = nitro.options.handlers.find((h) => id.startsWith(h.handler)) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
if (routeHandler?.route) return `chunks/routes${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/"}/[name].mjs`;
if (Object.entries(nitro.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`;
return `chunks/_/[name].mjs`;
},
manualChunks(id) {
return getChunkGroup(id);
},
inlineDynamicImports: nitro.options.inlineDynamicImports,
format: "esm",
exports: "auto",
intro: "",
outro: "",
generatedCode: { constBindings: true },
sanitizeFileName: sanitizeFilePath,
sourcemap: nitro.options.sourcemap,
sourcemapExcludeSources: true,
sourcemapIgnoreList(relativePath) {
return relativePath.includes("node_modules");
}
}
};
config = defu(nitro.options.rollupConfig, config);
if (config.output.inlineDynamicImports) delete config.output.manualChunks;
return config;
};
//#endregion
//#region src/build/rollup/error.ts
function formatRollupError(_error) {
try {
const logs = [_error.toString()];
const errors = _error?.errors || [_error];
for (const error of errors) {
const id = error.path || error.id || _error.id;
let path = isAbsolute(id) ? relative(process.cwd(), id) : id;
const location = error.loc;
if (location) path += `:${location.line}:${location.column}`;
const text = error.frame;
logs.push(`Rollup error while processing \`${path}\`` + text ? "\n\n" + text : "");
}
return logs.join("\n");
} catch {
return _error?.toString();
}
}
//#endregion
//#region src/build/rollup/dev.ts
async function watchDev(nitro, rollupConfig) {
const rollup = await import("rollup");
let rollupWatcher;
async function load() {
if (rollupWatcher) await rollupWatcher.close();
await scanHandlers(nitro);
nitro.routing.sync();
rollupWatcher = startRollupWatcher(nitro, rollupConfig);
await writeTypes(nitro);
}
const reload = debounce(load);
const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
join(dir, nitro.options.apiDir || "api"),
join(dir, nitro.options.routesDir || "routes"),
join(dir, "middleware"),
join(dir, "plugins"),
join(dir, "modules")
]);
const watchReloadEvents = new Set([
"add",
"addDir",
"unlink",
"unlinkDir"
]);
const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path, stat) => {
if (watchReloadEvents.has(event)) reload();
});
const rootDirWatcher = watch(nitro.options.rootDir, { persistent: false }, (_event, filename) => {
if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
});
nitro.hooks.hook("close", () => {
rollupWatcher.close();
scanDirsWatcher.close();
rootDirWatcher.close();
});
nitro.hooks.hook("rollup:reload", () => reload());
await load();
function startRollupWatcher(nitro$1, rollupConfig$1) {
const watcher = rollup.watch(defu(rollupConfig$1, { watch: { chokidar: nitro$1.options.watchOptions } }));
let start;
watcher.on("event", (event) => {
switch (event.code) {
case "START":
start = Date.now();
nitro$1.logger.info(`Starting dev watcher (builder: \`rollup\`, preset: \`${nitro$1.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro$1.options.compatibilityDate)}\`)`);
nitro$1.hooks.callHook("dev:start");
break;
case "BUNDLE_END":
nitro$1.hooks.callHook("compiled", nitro$1);
if (nitro$1.options.logging.buildSuccess) nitro$1.logger.success(`Server built`, start ? `in ${Date.now() - start}ms` : "");
nitro$1.hooks.callHook("dev:reload");
break;
case "ERROR":
nitro$1.logger.error(formatRollupError(event.error));
nitro$1.hooks.callHook("dev:error", event.error);
}
});
return watcher;
}
}
//#endregion
//#region src/build/rollup/prod.ts
async function buildProduction(nitro, rollupConfig) {
const rollup = await import("rollup");
const buildStartTime = Date.now();
await scanHandlers(nitro);
await writeTypes(nitro);
if (!nitro.options.static) {
nitro.logger.info(`Building server (builder: \`rollup\`, preset: \`${nitro.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro.options.compatibilityDate)}\`)`);
await (await rollup.rollup(rollupConfig).catch((error) => {
nitro.logger.error(formatRollupError(error));
throw error;
})).write(rollupConfig.output);
}
const buildInfo = await writeBuildInfo(nitro);
if (!nitro.options.static) {
if (nitro.options.logging.buildSuccess) nitro.logger.success(`Server built in ${Date.now() - buildStartTime}ms`);
if (nitro.options.logLevel > 1) process.stdout.write(await generateFSTree(nitro.options.output.serverDir, { compressedSizes: nitro.options.logging.compressedSizes }) || "");
}
await nitro.hooks.callHook("compiled", nitro);
const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input) => {
return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
};
if (buildInfo.commands.preview) nitro.logger.success(`You can preview this build using \`${rewriteRelativePaths(buildInfo.commands.preview)}\``);
if (buildInfo.commands.deploy) nitro.logger.success(`You can deploy this build using \`${rewriteRelativePaths(buildInfo.commands.deploy)}\``);
}
//#endregion
//#region src/build/rollup/build.ts
async function rollupBuild(nitro) {
await nitro.hooks.callHook("build:before", nitro);
const config = getRollupConfig(nitro);
await nitro.hooks.callHook("rollup:before", nitro, config);
return nitro.options.dev ? watchDev(nitro, config) : buildProduction(nitro, config);
}
//#endregion
export { rollupBuild };
import "../_libs/c12.mjs";
import "../_libs/gen-mapping.mjs";
import "../_libs/magic-string.mjs";
import "../_libs/acorn.mjs";
import "../_libs/confbox.mjs";
import "../_libs/local-pkg.mjs";
import "../_libs/js-tokens.mjs";
import "../_libs/strip-literal.mjs";
import "../_libs/unimport.mjs";
import "../_libs/picomatch.mjs";
import "../_libs/fdir.mjs";
import "../_libs/tinyglobby.mjs";
import "../_libs/compatx.mjs";
import "../_libs/klona.mjs";
import { r as a } from "../_libs/std-env.mjs";
import "../_chunks/B-D1JOIz.mjs";
import "../_libs/escape-string-regexp.mjs";
import "../_libs/tsconfck.mjs";
import "../_libs/dot-prop.mjs";
import "../_chunks/C7CbzoI1.mjs";
import "../_chunks/ANM1K1bE.mjs";
import "../_libs/rou3.mjs";
import "../_libs/mime.mjs";
import "../_libs/pathe.mjs";
import "../_libs/untyped.mjs";
import "../_libs/knitwork.mjs";
import "./common.mjs";
import "../_libs/httpxy.mjs";
import "../_dev.mjs";
import "../_libs/chokidar.mjs";
import "../_libs/ultrahtml.mjs";
import "../_libs/plugin-alias.mjs";
import "../_libs/estree-walker.mjs";
import "../_libs/plugin-commonjs.mjs";
import "../_libs/plugin-inject.mjs";
import "./common2.mjs";
import "../_libs/remapping.mjs";
import "../_libs/unwasm.mjs";
import "../_libs/plugin-replace.mjs";
import "../_libs/etag.mjs";
import { t as nitro } from "./vite.plugin.mjs";
import "../_libs/vite-plugin-fullstack.mjs";
//#region src/build/vite/build.ts
async function viteBuild(nitro$1) {
if (nitro$1.options.dev) throw new Error("Nitro dev CLI does not supports vite. Please use `vite dev` instead.");
const { createBuilder } = nitro$1.options.builder === "rolldown-vite" ? await import("rolldown-vite").catch(() => import("vite")) : await import("vite");
await (await createBuilder({
base: nitro$1.options.rootDir,
plugins: [await nitro({ _nitro: nitro$1 })],
logLevel: a ? "warn" : void 0
})).buildApp();
}
//#endregion
export { viteBuild };
import { C as isAbsolute$1, O as relative$1, T as normalize$1, b as basename$1, h as resolveModulePath, k as resolve$1, n as debounce, w as join$1, x as dirname$1 } from "../_libs/c12.mjs";
import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs";
import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
import { n as T, r as a } from "../_libs/std-env.mjs";
import { a as createNitro, n as prepare, r as copyPublicAssets } from "../_chunks/B-D1JOIz.mjs";
import { n as prettyPath } from "../_chunks/C7CbzoI1.mjs";
import { i as scanHandlers } from "../_chunks/ANM1K1bE.mjs";
import { n as writeBuildInfo, t as getBuildInfo } from "./common.mjs";
import { i as NodeDevWorker, r as NitroDevApp } from "../_dev.mjs";
import { i as watch$1 } from "../_libs/chokidar.mjs";
import { t as alias } from "../_libs/plugin-alias.mjs";
import { t as inject } from "../_libs/plugin-inject.mjs";
import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs";
import { t as assetsPlugin } from "../_libs/vite-plugin-fullstack.mjs";
import consola$1 from "consola";
import { join, resolve } from "node:path";
import { existsSync, watch } from "node:fs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { defu } from "defu";
import { runtimeDependencies, runtimeDir } from "nitro/meta";
import { colors } from "consola/utils";
import { NodeRequest, sendNodeResponse } from "srvx/node";
import { DevEnvironment } from "vite";
import { spawn } from "node:child_process";
//#region src/build/vite/rollup.ts
/**
* Removed from base rollup config:
* - nodeResolve
* - commonjs
* - esbuild
* - sourcemapMinify
* - json
* - raw
*
* TODO: Reuse with rollup:
* - chunkFileNames
* - moduleSideEffects
*/
const getViteRollupConfig = (ctx) => {
const nitro$1 = ctx.nitro;
const base = baseBuildConfig(nitro$1);
const chunkNamePrefixes = [
[runtimeDir, "nitro"],
[base.presetsDir, "nitro"],
["\0nitro-wasm:", "wasm"],
["\0", "virtual"]
];
function getChunkGroup(id) {
if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) return "nitro";
}
let config = {
input: nitro$1.options.entry,
external: [...base.env.external],
plugins: [
ctx.pluginConfig.experimental?.vite?.virtualBundle && virtualBundlePlugin(ctx._serviceBundles),
...baseBuildPlugins(nitro$1, base),
alias({ entries: base.aliases }),
!ctx._isRolldown && inject(base.env.inject)
].filter(Boolean),
...ctx._isRolldown ? { transform: { inject: base.env.inject } } : {},
treeshake: { moduleSideEffects(id) {
return nitro$1.options.moduleSideEffects.some((p) => id.startsWith(p));
} },
output: {
dir: nitro$1.options.output.serverDir,
entryFileNames: "index.mjs",
chunkFileNames(chunk) {
const id = normalize$1(chunk.moduleIds.at(-1) || "");
for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`;
const routeHandler = nitro$1.options.handlers.find((h) => id.startsWith(h.handler)) || nitro$1.scannedHandlers.find((h) => id.startsWith(h.handler));
if (routeHandler?.route) return `chunks/routes/${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "").replace(/[^a-zA-Z0-9/_-]/g, "_") || "/"}/[name].mjs`.replace(/\/+/g, "/");
if (Object.entries(nitro$1.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`;
return `chunks/_/[name].mjs`;
},
manualChunks(id) {
return getChunkGroup(id);
},
inlineDynamicImports: nitro$1.options.inlineDynamicImports,
format: "esm",
exports: "auto",
intro: "",
outro: "",
generatedCode: { ...ctx._isRolldown ? {} : { constBindings: true } },
sanitizeFileName: sanitizeFilePath,
...ctx._isRolldown ? {} : { sourcemapExcludeSources: true },
sourcemapIgnoreList(relativePath) {
return relativePath.includes("node_modules");
}
}
};
config = defu(nitro$1.options.rollupConfig, config);
if (config.output.inlineDynamicImports) delete config.output.manualChunks;
return {
config,
base
};
};
function virtualBundlePlugin(bundles) {
let _modules = null;
const getModules = () => {
if (_modules) return _modules;
_modules = /* @__PURE__ */ new Map();
for (const bundle of Object.values(bundles)) for (const [fileName, content] of Object.entries(bundle)) if (content.type === "chunk") {
const virtualModule = {
code: content.code,
map: null
};
const maybeMap = bundle[`${fileName}.map`];
if (maybeMap && maybeMap.type === "asset") virtualModule.map = maybeMap.source;
_modules.set(fileName, virtualModule);
_modules.set(resolve$1(fileName), virtualModule);
}
return _modules;
};
return {
name: "virtual-bundle",
resolveId(id, importer) {
const modules = getModules();
if (modules.has(id)) return resolve$1(id);
if (importer) {
const resolved = resolve$1(dirname$1(importer), id);
if (modules.has(resolved)) return resolved;
}
return null;
},
load(id) {
const m = getModules().get(id);
if (!m) return null;
return m;
}
};
}
//#endregion
//#region src/build/vite/prod.ts
const BuilderNames = {
nitro: colors.magenta("Nitro"),
client: colors.green("Client"),
ssr: colors.blue("SSR")
};
async function buildEnvironments(ctx, builder) {
const nitro$1 = ctx.nitro;
for (const [envName, env] of Object.entries(builder.environments)) {
const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1));
if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) {
if (![
"nitro",
"ssr",
"client"
].includes(envName)) nitro$1.logger.info(env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`);
continue;
}
if (!a && !T) console.log();
nitro$1.logger.start(`Building [${fmtName}]`);
await builder.build(env);
}
const nitroOptions = ctx.nitro.options;
const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input;
if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) {
const outputPath = resolve$1(nitroOptions.output.publicDir, basename$1(clientInput));
if (existsSync(outputPath)) {
const html = await readFile(outputPath, "utf8").then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`));
await rm(outputPath);
const tmp = resolve$1(nitroOptions.buildDir, "vite/index.html");
await mkdir(dirname$1(tmp), { recursive: true });
await writeFile(tmp, html, "utf8");
nitroOptions.renderer.template = tmp;
}
}
await builder.writeAssetsManifest?.();
if (!a && !T) console.log();
const buildInfo = [["preset", nitro$1.options.preset], ["compatibility", formatCompatibilityDate(nitro$1.options.compatibilityDate)]].filter((e) => e[1]);
nitro$1.logger.start(`Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`);
await copyPublicAssets(nitro$1);
const assetDirs = new Set(Object.values(builder.environments).filter((env) => env.config.consumer === "client").map((env) => env.config.build.assetsDir).filter(Boolean));
for (const assetsDir of assetDirs) {
if (!existsSync(resolve$1(nitro$1.options.output.publicDir, assetsDir))) continue;
const rule = ctx.nitro.options.routeRules[`/${assetsDir}/**`] ??= {};
if (!rule.headers?.["cache-control"]) rule.headers = {
...rule.headers,
"cache-control": `public, max-age=31536000, immutable`
};
}
ctx.nitro.routing.sync();
await builder.build(builder.environments.nitro);
await nitro$1.close();
await nitro$1.hooks.callHook("compiled", nitro$1);
await writeBuildInfo(nitro$1);
const rOutput = relative$1(process.cwd(), nitro$1.options.output.dir);
const rewriteRelativePaths = (input) => {
return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
};
if (!a && !T) console.log();
if (nitro$1.options.commands.preview) nitro$1.logger.success(`You can preview this build using \`${rewriteRelativePaths(nitro$1.options.commands.preview)}\``);
if (nitro$1.options.commands.deploy) nitro$1.logger.success(`You can deploy this build using \`${rewriteRelativePaths(nitro$1.options.commands.deploy)}\``);
}
function prodSetup(ctx) {
return `
function lazyService(loader) {
let promise, mod
return {
fetch(req) {
if (mod) { return mod.fetch(req) }
if (!promise) {
promise = loader().then(_mod => (mod = _mod.default || _mod))
}
return promise.then(mod => mod.fetch(req))
}
}
}
const services = {
${Object.keys(ctx.services).map((name) => {
let entry;
if (ctx.pluginConfig.experimental?.vite?.virtualBundle) entry = ctx._entryPoints[name];
else entry = resolve$1(ctx.nitro.options.buildDir, "vite/services", name, ctx._entryPoints[name]);
return [name, entry];
}).map(([name, entry]) => `[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`).join(",\n")}
};
globalThis.__nitro_vite_envs__ = services;
`;
}
//#endregion
//#region src/build/vite/dev.ts
function createFetchableDevEnvironment(name, config, devServer, entry) {
return new FetchableDevEnvironment(name, config, {
hot: true,
transport: createTransport(name, devServer)
}, devServer, entry);
}
var FetchableDevEnvironment = class extends DevEnvironment {
devServer;
constructor(name, config, context, devServer, entry) {
super(name, config, context);
this.devServer = devServer;
this.devServer.sendMessage({
type: "custom",
event: "nitro:vite-env",
data: {
name,
entry
}
});
}
async dispatchFetch(request) {
return this.devServer.fetch(request);
}
async init(...args) {
await this.devServer.init?.();
return super.init(...args);
}
};
function createTransport(name, hooks) {
const listeners = /* @__PURE__ */ new WeakMap();
return {
send: (data) => hooks.sendMessage({
...data,
viteEnv: name
}),
on: (event, handler) => {
if (event === "connection") return;
const listener = (value) => {
if (value?.type === "custom" && value.event === event && value.viteEnv === name) handler(value.data, { send: (payload) => hooks.sendMessage({
...payload,
viteEnv: name
}) });
};
listeners.set(handler, listener);
hooks.onMessage(listener);
},
off: (event, handler) => {
if (event === "connection") return;
const listener = listeners.get(handler);
if (listener) {
hooks.offMessage(listener);
listeners.delete(handler);
}
}
};
}
async function configureViteDevServer(ctx, server) {
const nitro$1 = ctx.nitro;
const nitroEnv$1 = server.environments.nitro;
const nitroConfigFile = nitro$1.options._c12.configFile;
if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile);
if (nitro$1.options.features.websocket ?? nitro$1.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => {
if (req.url?.startsWith("/?token")) return;
ctx.devWorker?.upgrade(req, socket, head);
});
const reload = debounce(async () => {
await scanHandlers(nitro$1);
nitro$1.routing.sync();
nitroEnv$1.moduleGraph.invalidateAll();
nitroEnv$1.hot.send({ type: "full-reload" });
});
const scanDirs = nitro$1.options.scanDirs.flatMap((dir) => [
join$1(dir, nitro$1.options.apiDir || "api"),
join$1(dir, nitro$1.options.routesDir || "routes"),
join$1(dir, "middleware"),
join$1(dir, "plugins"),
join$1(dir, "modules")
]);
const watchReloadEvents = new Set([
"add",
"addDir",
"unlink",
"unlinkDir"
]);
const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path$1, stat$1) => {
if (watchReloadEvents.has(event)) reload();
});
const rootDirWatcher = watch(nitro$1.options.rootDir, { persistent: false }, (_event, filename) => {
if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
});
nitro$1.hooks.hook("close", () => {
scanDirsWatcher.close();
rootDirWatcher.close();
});
const hostIPC = { async transformHTML(html) {
return server.transformIndexHtml("/", html).then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`));
} };
nitroEnv$1.devServer.onMessage(async (payload) => {
if (payload.type === "custom" && payload.event === "nitro:vite-invoke") {
const res = await hostIPC[payload.data.name](payload.data.data).then((data) => ({ data })).catch((error) => ({ error }));
nitroEnv$1.devServer.sendMessage({
type: "custom",
event: "nitro:vite-invoke-response",
data: {
id: payload.data.id,
data: res
}
});
}
});
const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
if (/^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled) return next();
nodeReq._nitroHandled = true;
const req = new NodeRequest({
req: nodeReq,
res: nodeRes
});
const devAppRes = await ctx.devApp.fetch(req);
if (nodeRes.writableEnded || nodeRes.headersSent) return;
if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes);
const envRes = await nitroEnv$1.dispatchFetch(req);
if (nodeRes.writableEnded || nodeRes.headersSent) return;
if (envRes.status !== 404) return await sendNodeResponse(nodeRes, envRes);
return next();
};
server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
const fetchDest = req.headers["sec-fetch-dest"];
if (fetchDest) res.setHeader("vary", "sec-fetch-dest");
if (!((req.url || "").match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] || "") && (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest))) nitroDevMiddleware(req, res, next);
else next();
});
return () => {
server.middlewares.use(nitroDevMiddleware);
};
}
//#endregion
//#region src/build/vite/env.ts
function createDevWorker(ctx) {
return new NodeDevWorker({
name: "nitro-vite",
entry: resolve(runtimeDir, "internal/vite/dev-worker.mjs"),
hooks: {},
data: {
server: true,
globals: { __NITRO_RUNTIME_CONFIG__: ctx.nitro.options.runtimeConfig }
}
});
}
function createNitroEnvironment(ctx) {
return {
consumer: "server",
build: {
rollupOptions: ctx.rollupConfig.config,
minify: ctx.nitro.options.minify,
emptyOutDir: false,
sourcemap: ctx.nitro.options.sourcemap,
commonjsOptions: { ...ctx.nitro.options.commonJS }
},
resolve: {
noExternal: ctx.nitro.options.dev ? [...ctx.rollupConfig.base.noExternal, ...runtimeDependencies] : true,
conditions: ctx.nitro.options.exportConditions,
externalConditions: ctx.nitro.options.exportConditions
},
dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, resolve(runtimeDir, "internal/vite/dev-entry.mjs")) }
};
}
function createServiceEnvironment(ctx, name, serviceConfig) {
return {
consumer: "server",
build: {
rollupOptions: { input: serviceConfig.entry },
minify: ctx.nitro.options.minify,
sourcemap: ctx.nitro.options.sourcemap,
outDir: join(ctx.nitro.options.buildDir, "vite/services", name),
emptyOutDir: true
},
resolve: {
conditions: ctx.nitro.options.exportConditions,
externalConditions: ctx.nitro.options.exportConditions
},
dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, tryResolve(serviceConfig.entry)) }
};
}
function createServiceEnvironments(ctx) {
return Object.fromEntries(Object.entries(ctx.services).map(([name, config]) => [name, createServiceEnvironment(ctx, name, config)]));
}
function tryResolve(id) {
if (/^[~#/\0]/.test(id) || isAbsolute$1(id)) return id;
return resolveModulePath(id, {
suffixes: ["", "/index"],
extensions: [
"",
".ts",
".mjs",
".cjs",
".js",
".mts",
".cts"
],
try: true
}) || id;
}
//#endregion
//#region src/build/vite/preview.ts
function nitroPreviewPlugin(ctx) {
return {
name: "nitro:preview",
apply: (_config, configEnv) => !!configEnv.isPreview,
config(config) {
return { preview: { port: config.preview?.port || 3e3 } };
},
async configurePreviewServer(server) {
const { outputDir, buildInfo } = await getBuildInfo(server.config.root);
if (!buildInfo) throw this.error("Cannot load nitro build info. Make sure to build first.");
const info = [
["Build Directory:", prettyPath(outputDir)],
["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()],
["Nitro Version:", buildInfo.versions.nitro],
["Nitro Preset:", buildInfo.preset],
buildInfo.framework?.name !== "nitro" && ["Framework:", buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")]
].filter((i) => i && i[1]);
consola$1.box({
title: " [Build Info] ",
message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n")
});
if (!buildInfo.commands?.preview) {
consola$1.warn("No nitro build preview command found for this preset.");
return;
}
const dotEnvEntries = await loadPreviewDotEnv(server.config.root);
if (dotEnvEntries.length > 0) consola$1.box({
title: " [Environment Variables] ",
message: [
"Loaded variables from .env files (preview mode only).",
"Set platform environment variables for production:",
...dotEnvEntries.map(([key, val]) => ` - ${key}`)
].join("\n")
});
const [command, ...args] = buildInfo.commands.preview.split(" ");
consola$1.info(`Spawning preview server...`);
consola$1.info(buildInfo.commands?.preview);
console.log("");
const { getRandomPort } = await import("get-port-please");
const randomPort = await getRandomPort();
const child = spawn(command, args, {
stdio: "inherit",
cwd: outputDir,
env: {
...process.env,
...Object.fromEntries(dotEnvEntries),
PORT: String(randomPort)
}
});
for (const sig of ["SIGINT", "SIGHUP"]) process.once(sig, () => {
consola$1.info(`Stopping preview server...`);
if (child.killed === false) {
child.kill(sig);
process.exit();
}
});
child.on("exit", (code) => {
if (code && code !== 0) consola$1.error(`[nitro] Preview server exited with code ${code}`);
});
const { createProxyServer } = await import("../cli/_chunks/dist3.mjs");
const proxy = createProxyServer({ target: `http://localhost:${randomPort}` });
server.middlewares.use((req, res, next) => {
if (child && !child.killed) proxy.web(req, res).catch(next);
else res.end(`Nitro preview server is not running.`);
});
}
};
}
async function loadPreviewDotEnv(root) {
const { loadDotenv } = await import("../cli/_chunks/dist2.mjs");
const env = await loadDotenv({
cwd: root,
fileName: [
".env.preview",
".env.production",
".env"
]
});
return Object.entries(env).filter(([_key, val]) => val);
}
//#endregion
//#region src/build/vite/plugin.ts
const DEFAULT_EXTENSIONS = [
".ts",
".js",
".mts",
".mjs",
".tsx",
".jsx"
];
const debug = process.env.NITRO_DEBUG ? (...args) => console.log("[nitro]", ...args) : () => {};
function nitro(pluginConfig = {}) {
const ctx = createContext(pluginConfig);
return [
nitroInit(ctx),
nitroEnv(ctx),
nitroMain(ctx),
nitroPrepare(ctx),
nitroService(ctx),
nitroPreviewPlugin(ctx),
pluginConfig.experimental?.vite?.assetsImport !== false && assetsPlugin({ experimental: { clientBuildFallback: false } })
].filter(Boolean);
}
function nitroInit(ctx) {
return {
name: "nitro:init",
sharedDuringBuild: true,
apply: (_config, configEnv) => !configEnv.isPreview,
async config(config, configEnv) {
ctx._isRolldown = !!this.meta.rolldownVersion;
if (!ctx._initialized) {
debug("[init] Initializing nitro");
ctx._initialized = true;
await setupNitroContext(ctx, configEnv, config);
}
},
applyToEnvironment(env) {
if (env.name === "nitro" && ctx.nitro?.options.dev) {
debug("[init] Adding rollup plugins for dev");
return [...ctx.rollupConfig?.config.plugins || []];
}
}
};
}
function nitroEnv(ctx) {
return {
name: "nitro:env",
sharedDuringBuild: true,
apply: (_config, configEnv) => !configEnv.isPreview,
async config(userConfig, _configEnv) {
debug("[env] Extending config (environments)");
const environments = {
...createServiceEnvironments(ctx),
nitro: createNitroEnvironment(ctx)
};
environments.client = {
consumer: userConfig.environments?.client?.consumer ?? "client",
build: { rollupOptions: { input: userConfig.environments?.client?.build?.rollupOptions?.input ?? useNitro(ctx).options.renderer?.template } }
};
debug("[env] Environments:", Object.keys(environments).join(", "));
return { environments };
},
configEnvironment(name, config) {
if (config.consumer === "client") {
debug("[env] Configuring client environment", name === "client" ? "" : ` (${name})`);
config.build.emptyOutDir = false;
config.build.outDir = useNitro(ctx).options.output.publicDir;
} else if (ctx.pluginConfig.experimental?.vite?.virtualBundle && name in (ctx.services || {})) {
debug("[env] Configuring service environment for virtual:", name);
config.build ??= {};
config.build.write = config.build.write ?? false;
}
}
};
}
function nitroMain(ctx) {
return {
name: "nitro:main",
sharedDuringBuild: true,
apply: (_config, configEnv) => !configEnv.isPreview,
async config(userConfig, _configEnv) {
debug("[main] Extending config (appType, resolve, server)");
if (!ctx.rollupConfig) throw new Error("Nitro rollup config is not initialized yet.");
return {
appType: userConfig.appType || "custom",
resolve: { alias: ctx.rollupConfig.base.aliases },
builder: { sharedConfigBuild: true },
experimental: { enableNativePlugin: false },
server: {
port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || useNitro(ctx).options.devServer?.port || 3e3,
cors: false
}
};
},
buildApp: {
order: "post",
handler(builder) {
debug("[main] Building environments");
return buildEnvironments(ctx, builder);
}
},
generateBundle: { handler(_options, bundle) {
const environment = this.environment;
debug("[main] Generating manifest and entry points for environment:", environment.name);
const isRegisteredService = Object.keys(ctx.services).includes(environment.name);
let entryFile;
for (const [_name, file] of Object.entries(bundle)) if (file.type === "chunk" && isRegisteredService && file.isEntry) if (entryFile === void 0) entryFile = file.fileName;
else this.warn(`Multiple entry points found for service "${environment.name}"`);
if (isRegisteredService) {
if (entryFile === void 0) this.error(`No entry point found for service "${this.environment.name}".`);
ctx._entryPoints[this.environment.name] = entryFile;
ctx._serviceBundles[this.environment.name] = bundle;
}
} },
configureServer: (server) => {
debug("[main] Configuring dev server");
return configureViteDevServer(ctx, server);
},
async hotUpdate({ server, modules, timestamp }) {
const env = this.environment;
if (ctx.pluginConfig.experimental?.vite.serverReload === false || env.config.consumer === "client") return;
const clientEnvs = Object.values(server.environments).filter((env$1) => env$1.config.consumer === "client");
let hasServerOnlyModule = false;
const invalidated = /* @__PURE__ */ new Set();
for (const mod of modules) if (mod.id && !clientEnvs.some((env$1) => env$1.moduleGraph.getModuleById(mod.id))) {
hasServerOnlyModule = true;
env.moduleGraph.invalidateModule(mod, invalidated, timestamp, false);
}
if (hasServerOnlyModule) {
env.hot.send({ type: "full-reload" });
server.ws.send({ type: "full-reload" });
return [];
}
}
};
}
function nitroPrepare(ctx) {
return {
name: "nitro:prepare",
sharedDuringBuild: true,
applyToEnvironment: (env) => env.name === "nitro",
buildApp: {
order: "pre",
async handler() {
debug("[prepare] Preparing output directory");
const nitro$1 = ctx.nitro;
await prepare(nitro$1);
}
}
};
}
function nitroService(ctx) {
return {
name: "nitro:service",
enforce: "pre",
sharedDuringBuild: true,
applyToEnvironment: (env) => env.name === "nitro",
resolveId: { async handler(id) {
if (id === "#nitro-vite-setup") return {
id,
moduleSideEffects: true
};
} },
load: { async handler(id) {
if (id === "#nitro-vite-setup") return prodSetup(ctx);
} }
};
}
function createContext(pluginConfig) {
return {
pluginConfig,
services: {},
_entryPoints: {},
_serviceBundles: {}
};
}
function useNitro(ctx) {
if (!ctx.nitro) throw new Error("Nitro instance is not initialized yet.");
return ctx.nitro;
}
async function setupNitroContext(ctx, configEnv, userConfig) {
const nitroConfig = {
dev: configEnv.command === "serve",
rootDir: userConfig.root,
...defu(ctx.pluginConfig, ctx.pluginConfig.config, userConfig.nitro)
};
nitroConfig.modules ??= [];
for (const plugin of flattenPlugins(userConfig.plugins || [])) if (plugin.nitro) nitroConfig.modules.push(plugin.nitro);
nitroConfig.builder = ctx._isRolldown ? "rolldown-vite" : "vite";
debug("[init] Using builder:", nitroConfig.builder);
ctx.nitro = ctx.pluginConfig._nitro || await createNitro(nitroConfig);
ctx.nitro.options.builder = ctx._isRolldown ? "rolldown-vite" : "vite";
if (!ctx.services?.ssr) if (userConfig.environments?.ssr === void 0) {
const ssrEntry = resolveModulePath("./entry-server", {
from: [
"app",
"src",
""
].flatMap((d) => [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs].map((s) => join$1(s, d) + "/")),
extensions: DEFAULT_EXTENSIONS,
try: true
});
if (ssrEntry) {
ctx.services.ssr = { entry: ssrEntry };
ctx.nitro.logger.info(`Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`);
}
} else {
let ssrEntry = getEntry(userConfig.environments.ssr.build?.rollupOptions?.input);
if (typeof ssrEntry === "string") {
ssrEntry = resolveModulePath(ssrEntry, {
from: [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs],
extensions: DEFAULT_EXTENSIONS,
suffixes: ["", "/index"],
try: true
}) || ssrEntry;
ctx.services.ssr = { entry: ssrEntry };
}
}
if (!ctx.nitro.options.renderer?.handler && !ctx.nitro.options.renderer?.template && ctx.services.ssr?.entry) {
ctx.nitro.options.renderer ??= {};
ctx.nitro.options.renderer.handler = resolve$1(runtimeDir, "internal/vite/ssr-renderer");
ctx.nitro.routing.sync();
}
const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve$1(ctx.nitro.options.buildDir, "vite/public");
ctx.nitro.options.publicAssets.push({
dir: publicDistDir,
maxAge: 0,
baseURL: "/",
fallthrough: true
});
if (!ctx.nitro.options.dev) ctx.nitro.options.unenv.push({
meta: { name: "nitro-vite" },
polyfill: ["#nitro-vite-setup"]
});
await ctx.nitro.hooks.callHook("build:before", ctx.nitro);
ctx.rollupConfig = await getViteRollupConfig(ctx);
await ctx.nitro.hooks.callHook("rollup:before", ctx.nitro, ctx.rollupConfig.config);
if (ctx.nitro.options.dev && !ctx.devWorker) {
ctx.devWorker = createDevWorker(ctx);
ctx.nitro.fetch = (req) => ctx.devWorker.fetch(req);
}
if (ctx.nitro.options.dev && !ctx.devApp) ctx.devApp = new NitroDevApp(ctx.nitro);
}
function getEntry(input) {
if (typeof input === "string") return input;
else if (Array.isArray(input) && input.length > 0) return input[0];
else if (input && "index" in input) return input.index;
}
function flattenPlugins(plugins) {
return plugins.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise));
}
//#endregion
export { nitro as t };
import { i as __toESM } from "./Bqks5huO.mjs";
import { C as isAbsolute, O as relative, h as resolveModulePath, k as resolve, w as join, x as dirname } from "../_libs/c12.mjs";
import { c as parseNodeModulePath, s as lookupNodeModuleSubpath } from "../_libs/local-pkg.mjs";
import { o as toExports } from "../_libs/unimport.mjs";
import { t as glob } from "../_libs/tinyglobby.mjs";
import { i as writeFile, r as resolveNitroPath, t as isDirectory } from "./C7CbzoI1.mjs";
import { t as resolveAlias } from "../_libs/pathe.mjs";
import { n as resolveSchema, t as generateTypes } from "../_libs/untyped.mjs";
import { existsSync, promises } from "node:fs";
import { withBase, withLeadingSlash, withoutTrailingSlash } from "ufo";
import { defu } from "defu";
import { runtimeDir } from "nitro/meta";
//#region src/scan.ts
const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
const suffixRegex = /(\.(?<method>connect|delete|get|head|options|patch|post|put|trace))?(\.(?<env>dev|prod|prerender))?$/;
async function scanAndSyncOptions(nitro) {
const scannedPlugins = await scanPlugins(nitro);
for (const plugin of scannedPlugins) if (!nitro.options.plugins.includes(plugin)) nitro.options.plugins.push(plugin);
if (nitro.options.experimental.tasks) {
const scannedTasks = await scanTasks(nitro);
for (const scannedTask of scannedTasks) if (scannedTask.name in nitro.options.tasks) {
if (!nitro.options.tasks[scannedTask.name].handler) nitro.options.tasks[scannedTask.name].handler = scannedTask.handler;
} else nitro.options.tasks[scannedTask.name] = {
handler: scannedTask.handler,
description: ""
};
}
const scannedModules = await scanModules(nitro);
nitro.options.modules = nitro.options.modules || [];
for (const modPath of scannedModules) if (!nitro.options.modules.includes(modPath)) nitro.options.modules.push(modPath);
}
async function scanHandlers(nitro) {
const middleware = await scanMiddleware(nitro);
const handlers = await Promise.all([scanServerRoutes(nitro, nitro.options.apiDir || "api", nitro.options.apiBaseURL || "/api"), scanServerRoutes(nitro, nitro.options.routesDir || "routes")]).then((r) => r.flat());
nitro.scannedHandlers = [...middleware, ...handlers.filter((h, index, array) => {
return array.findIndex((h2) => h.route === h2.route && h.method === h2.method && h.env === h2.env) === index;
})];
return handlers;
}
async function scanMiddleware(nitro) {
return (await scanFiles(nitro, "middleware")).map((file) => {
return {
route: "/**",
middleware: true,
handler: file.fullPath
};
});
}
async function scanServerRoutes(nitro, dir, prefix = "/") {
return (await scanFiles(nitro, dir)).map((file) => {
let route = file.path.replace(/\.[A-Za-z]+$/, "").replace(/\(([^(/\\]+)\)[/\\]/g, "").replace(/\[\.{3}]/g, "**").replace(/\[\.{3}(\w+)]/g, "**:$1").replace(/\[([^/\]]+)]/g, ":$1");
route = withLeadingSlash(withoutTrailingSlash(withBase(route, prefix)));
const suffixMatch = route.match(suffixRegex);
let method;
let env;
if (suffixMatch?.index && suffixMatch?.index >= 0) {
route = route.slice(0, suffixMatch.index);
method = suffixMatch.groups?.method;
env = suffixMatch.groups?.env;
}
route = route.replace(/\/index$/, "") || "/";
return {
handler: file.fullPath,
lazy: true,
middleware: false,
route,
method,
env
};
});
}
async function scanPlugins(nitro) {
return (await scanFiles(nitro, "plugins")).map((f) => f.fullPath);
}
async function scanTasks(nitro) {
return (await scanFiles(nitro, "tasks")).map((f) => {
return {
name: f.path.replace(/\/index$/, "").replace(/\.[A-Za-z]+$/, "").replace(/\//g, ":"),
handler: f.fullPath
};
});
}
async function scanModules(nitro) {
return (await scanFiles(nitro, "modules")).map((f) => f.fullPath);
}
async function scanFiles(nitro, name) {
return await Promise.all(nitro.options.scanDirs.map((dir) => scanDir(nitro, dir, name))).then((r) => r.flat());
}
async function scanDir(nitro, dir, name) {
return (await glob(join(name, GLOB_SCAN_PATTERN), {
cwd: dir,
dot: true,
ignore: nitro.options.ignore,
absolute: true
}).catch((error) => {
if (error?.code === "ENOTDIR") {
nitro.logger.warn(`Ignoring \`${join(dir, name)}\`. It must be a directory.`);
return [];
}
throw error;
})).map((fullPath) => {
return {
fullPath,
path: relative(join(dir, name), fullPath)
};
}).sort((a, b) => a.path.localeCompare(b.path));
}
//#endregion
//#region src/build/types.ts
async function writeTypes(nitro) {
const types = { routes: {} };
const generatedTypesDir = resolve(nitro.options.rootDir, nitro.options.typescript.generatedTypesDir || "node_modules/.nitro/types");
const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers];
for (const mw of middleware) {
if (typeof mw.handler !== "string" || !mw.route) continue;
const relativePath = relative(generatedTypesDir, resolveNitroPath(mw.handler, nitro.options)).replace(/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/, "");
const method = mw.method || "default";
types.routes[mw.route] ??= {};
types.routes[mw.route][method] ??= [];
types.routes[mw.route][method].push(`Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`);
}
let autoImportedTypes = [];
let autoImportExports = "";
if (nitro.unimport) {
await nitro.unimport.init();
const allImports = await nitro.unimport.getImports();
autoImportExports = toExports(allImports).replace(/#internal\/nitro/g, relative(generatedTypesDir, runtimeDir));
const resolvedImportPathMap = /* @__PURE__ */ new Map();
for (const i of allImports) {
const from = i.typeFrom || i.from;
if (resolvedImportPathMap.has(from)) continue;
let path = resolveAlias(from, nitro.options.alias);
if (!isAbsolute(path)) {
const resolvedPath = resolveModulePath(from, {
try: true,
from: nitro.options.nodeModulesDirs,
conditions: [
"type",
"node",
"import"
],
suffixes: ["", "/index"],
extensions: [
".mjs",
".cjs",
".js",
".mts",
".cts",
".ts"
]
});
if (resolvedPath) {
const { dir, name } = parseNodeModulePath(resolvedPath);
if (!dir || !name) path = resolvedPath;
else path = join(dir, name, await lookupNodeModuleSubpath(resolvedPath) || "");
}
}
if (existsSync(path) && !await isDirectory(path)) path = path.replace(/\.[a-z]+$/, "");
if (isAbsolute(path)) path = relative(generatedTypesDir, path);
resolvedImportPathMap.set(from, path);
}
autoImportedTypes = [nitro.options.imports && nitro.options.imports.autoImport !== false ? (await nitro.unimport.generateTypeDeclarations({
exportHelper: false,
resolvePath: (i) => {
const from = i.typeFrom || i.from;
return resolvedImportPathMap.get(from) ?? from;
}
})).trim() : ""];
}
const generateRoutes = () => [
"// Generated by nitro",
"import type { Serialize, Simplify } from \"nitro/types\";",
"declare module \"nitro/types\" {",
" type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T",
" interface InternalApi {",
...Object.entries(types.routes).map(([path, methods]) => [
` '${path}': {`,
...Object.entries(methods).map(([method, types$1]) => ` '${method}': ${types$1.join(" | ")}`),
" }"
].join("\n")),
" }",
"}",
"export {}"
];
const config = [
"// Generated by nitro",
`declare module "nitro/types" {`,
nitro.options.typescript.generateRuntimeConfigTypes ? generateTypes(await resolveSchema(Object.fromEntries(Object.entries(nitro.options.runtimeConfig).filter(([key]) => !["app", "nitro"].includes(key)))), {
interfaceName: "NitroRuntimeConfig",
addExport: false,
addDefaults: false,
allowExtraKeys: false,
indentation: 2
}) : "",
`}`,
"export {}"
];
const declarations = [
"/// <reference path=\"./nitro-routes.d.ts\" />",
"/// <reference path=\"./nitro-config.d.ts\" />",
"/// <reference path=\"./nitro-imports.d.ts\" />"
];
const buildFiles = [];
buildFiles.push({
path: join(generatedTypesDir, "nitro-routes.d.ts"),
contents: () => generateRoutes().join("\n")
});
buildFiles.push({
path: join(generatedTypesDir, "nitro-config.d.ts"),
contents: config.join("\n")
});
buildFiles.push({
path: join(generatedTypesDir, "nitro-imports.d.ts"),
contents: [...autoImportedTypes, autoImportExports || "export {}"].join("\n")
});
buildFiles.push({
path: join(generatedTypesDir, "nitro.d.ts"),
contents: declarations.join("\n")
});
if (nitro.options.typescript.generateTsConfig) {
const tsConfigPath = resolve(generatedTypesDir, nitro.options.typescript.tsconfigPath);
const tsconfigDir = dirname(tsConfigPath);
const tsConfig = defu(nitro.options.typescript.tsConfig, {
compilerOptions: {
esModuleInterop: true,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
target: "ESNext",
allowJs: true,
resolveJsonModule: true,
moduleDetection: "force",
isolatedModules: true,
verbatimModuleSyntax: true,
allowImportingTsExtensions: true,
strict: nitro.options.typescript.strict,
noUncheckedIndexedAccess: true,
noImplicitOverride: true,
forceConsistentCasingInFileNames: true,
module: "Preserve",
jsx: "preserve",
jsxFactory: "h",
jsxFragmentFactory: "Fragment",
paths: { "#imports": [relativeWithDot(tsconfigDir, join(generatedTypesDir, "nitro-imports"))] }
},
include: [
relativeWithDot(tsconfigDir, join(generatedTypesDir, "nitro.d.ts")).replace(/^(?=[^.])/, "./"),
join(relativeWithDot(tsconfigDir, nitro.options.rootDir), "**/*"),
...!nitro.options.serverDir || nitro.options.serverDir === nitro.options.rootDir ? [] : [join(relativeWithDot(tsconfigDir, nitro.options.serverDir), "**/*")]
]
});
for (const alias in tsConfig.compilerOptions.paths) {
const paths = await Promise.all(tsConfig.compilerOptions.paths[alias].map(async (path) => {
if (!isAbsolute(path)) return path;
return relativeWithDot(tsconfigDir, (await promises.stat(path).catch(() => null))?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, "") : path);
}));
tsConfig.compilerOptions.paths[alias] = [...new Set(paths)];
}
tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p))];
if (tsConfig.exclude) tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p))];
types.tsConfig = tsConfig;
buildFiles.push({
path: tsConfigPath,
contents: () => JSON.stringify(tsConfig, null, 2)
});
}
await nitro.hooks.callHook("types:extend", types);
await Promise.all(buildFiles.map(async (file) => {
await writeFile(resolve(generatedTypesDir, file.path), typeof file.contents === "string" ? file.contents : file.contents());
}));
}
const RELATIVE_RE = /^\.{1,2}\//;
function relativeWithDot(from, to) {
const rel = relative(from, to);
return RELATIVE_RE.test(rel) ? rel : "./" + rel;
}
//#endregion
//#region src/utils/parallel.ts
async function runParallel(inputs, cb, opts) {
const tasks = /* @__PURE__ */ new Set();
function queueNext() {
const route = inputs.values().next().value;
if (!route) return;
inputs.delete(route);
const task = (opts.interval ? new Promise((resolve$1) => setTimeout(resolve$1, opts.interval)) : Promise.resolve()).then(() => cb(route)).catch((error) => {
console.error(error);
});
tasks.add(task);
return task.then(() => {
tasks.delete(task);
if (inputs.size > 0) return refillQueue();
});
}
function refillQueue() {
const workers = Math.min(opts.concurrency - tasks.size, inputs.size);
return Promise.all(Array.from({ length: workers }, () => queueNext()));
}
await refillQueue();
}
//#endregion
export { scanHandlers as i, writeTypes as n, scanAndSyncOptions as r, runParallel as t };
import { i as __toESM } from "./Bqks5huO.mjs";
import { O as relative, T as normalize, g as resolveModuleURL, h as resolveModulePath, i as loadConfig, k as resolve, l as findWorkspaceDir, t as watchConfig, w as join } from "../_libs/c12.mjs";
import { a as createUnimport } from "../_libs/unimport.mjs";
import { t as glob } from "../_libs/tinyglobby.mjs";
import { n as resolveCompatibilityDates, r as resolveCompatibilityDatesFromEnv } from "../_libs/compatx.mjs";
import { t as klona } from "../_libs/klona.mjs";
import { i as d, r as a } from "../_libs/std-env.mjs";
import { t as escapeStringRegexp } from "../_libs/escape-string-regexp.mjs";
import { n as parse, t as TSConfckCache } from "../_libs/tsconfck.mjs";
import { i as writeFile$1, n as prettyPath, r as resolveNitroPath, t as isDirectory } from "./C7CbzoI1.mjs";
import { i as scanHandlers, r as scanAndSyncOptions, t as runParallel } from "./ANM1K1bE.mjs";
import { a as findRoute, i as findAllRoutes, n as addRoute, r as createRouter, t as compileRouterToString } from "../_libs/rou3.mjs";
import { t as src_default } from "../_libs/mime.mjs";
import { n as z, t as P } from "../_libs/ultrahtml.mjs";
import { createRequire } from "node:module";
import consola$1, { consola } from "consola";
import { Hookable, createDebugger } from "hookable";
import { existsSync, promises } from "node:fs";
import { joinURL, parseURL, withBase, withLeadingSlash, withTrailingSlash, withoutBase, withoutTrailingSlash } from "ufo";
import { pathToFileURL } from "node:url";
import fsp, { readFile } from "node:fs/promises";
import { defu } from "defu";
import { pkgDir, runtimeDir } from "nitro/meta";
import { colors } from "consola/utils";
import { ofetch } from "ofetch";
import { hash } from "ohash";
import zlib from "node:zlib";
import { toRequest } from "h3";
//#region src/config/defaults.ts
const NitroDefaults = {
compatibilityDate: "latest",
debug: d,
logLevel: a ? 1 : 3,
runtimeConfig: {
app: {},
nitro: {}
},
serverDir: false,
scanDirs: [],
buildDir: `node_modules/.nitro`,
output: {
dir: "{{ rootDir }}/.output",
serverDir: "{{ output.dir }}/server",
publicDir: "{{ output.dir }}/public"
},
features: {},
experimental: {},
future: {},
storage: {},
devStorage: {},
publicAssets: [],
serverAssets: [],
plugins: [],
tasks: {},
scheduledTasks: {},
imports: false,
virtual: {},
compressPublicAssets: false,
ignore: [],
dev: false,
devServer: { watch: [] },
watchOptions: { ignoreInitial: true },
devProxy: {},
logging: {
compressedSizes: true,
buildSuccess: true
},
baseURL: process.env.NITRO_APP_BASE_URL || "/",
handlers: [],
devHandlers: [],
errorHandler: void 0,
routes: {},
routeRules: {},
prerender: {
autoSubfolderIndex: true,
concurrency: 1,
interval: 0,
retry: 3,
retryDelay: 500,
failOnError: false,
crawlLinks: false,
ignore: [],
routes: []
},
builder: void 0,
moduleSideEffects: ["unenv/polyfill/"],
replace: {},
node: true,
sourcemap: false,
typescript: {
strict: true,
generateRuntimeConfigTypes: false,
generateTsConfig: false,
tsconfigPath: "tsconfig.json",
tsConfig: void 0
},
nodeModulesDirs: [],
hooks: {},
commands: {},
framework: {
name: "nitro",
version: ""
}
};
//#endregion
//#region src/config/resolvers/assets.ts
async function resolveAssetsOptions(options) {
for (const publicAsset of options.publicAssets) {
publicAsset.dir = resolve(options.rootDir, publicAsset.dir);
publicAsset.baseURL = withLeadingSlash(withoutTrailingSlash(publicAsset.baseURL || "/"));
}
for (const dir of [options.rootDir, ...options.scanDirs]) {
const publicDir = resolve(dir, "public");
if (!existsSync(publicDir)) continue;
if (options.publicAssets.some((asset) => asset.dir === publicDir)) continue;
options.publicAssets.push({ dir: publicDir });
}
for (const serverAsset of options.serverAssets) serverAsset.dir = resolve(options.rootDir, serverAsset.dir);
options.serverAssets.push({
baseName: "server",
dir: resolve(options.rootDir, "assets")
});
for (const asset of options.publicAssets) {
asset.baseURL = asset.baseURL || "/";
const isTopLevel = asset.baseURL === "/";
asset.fallthrough = asset.fallthrough ?? isTopLevel;
const routeRule = options.routeRules[asset.baseURL + "/**"];
asset.maxAge = (routeRule?.cache)?.maxAge ?? asset.maxAge ?? 0;
if (asset.maxAge && !asset.fallthrough) options.routeRules[asset.baseURL + "/**"] = defu(routeRule, { headers: { "cache-control": `public, max-age=${asset.maxAge}, immutable` } });
}
}
//#endregion
//#region src/config/resolvers/compatibility.ts
async function resolveCompatibilityOptions(options) {
options.compatibilityDate = resolveCompatibilityDatesFromEnv(options.compatibilityDate);
}
//#endregion
//#region src/config/resolvers/database.ts
async function resolveDatabaseOptions(options) {
if (options.experimental.database && options.imports) {
options.imports.presets.push({
from: "nitro/database",
imports: ["useDatabase"]
});
if (options.dev && !options.database && !options.devDatabase) options.devDatabase = { default: {
connector: "sqlite",
options: { cwd: options.rootDir }
} };
else if (options.node && !options.database) options.database = { default: {
connector: "sqlite",
options: {}
} };
}
}
//#endregion
//#region src/config/resolvers/export-conditions.ts
async function resolveExportConditionsOptions(options) {
options.exportConditions = _resolveExportConditions(options.exportConditions || [], {
dev: options.dev,
node: options.node,
wasm: options.experimental.wasm
});
}
function _resolveExportConditions(conditions, opts) {
const resolvedConditions = [];
resolvedConditions.push(opts.dev ? "development" : "production");
resolvedConditions.push(...conditions);
if (opts.node) resolvedConditions.push("node");
else resolvedConditions.push("wintercg", "worker", "web", "browser", "workerd", "edge-light", "netlify", "edge-routine", "deno");
if (opts.wasm) resolvedConditions.push("wasm", "unwasm");
resolvedConditions.push("import", "default");
if ("Bun" in globalThis) resolvedConditions.push("bun");
else if ("Deno" in globalThis) resolvedConditions.push("deno");
return resolvedConditions.filter((c, i) => resolvedConditions.indexOf(c) === i);
}
//#endregion
//#region src/config/resolvers/imports.ts
async function resolveImportsOptions(options) {
if (options.imports === false) return;
options.imports.presets ??= [];
options.imports.dirs ??= [];
options.imports.dirs.push(...options.scanDirs.map((dir) => join(dir, "utils/**/*")));
if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) {
options.imports.exclude.push(/[/\\]\.git[/\\]/);
options.imports.exclude.push(options.buildDir);
const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean);
options.imports.exclude.push(scanDirsInNodeModules.length > 0 ? /* @__PURE__ */ new RegExp(`node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeStringRegexp(dir)).join("|")})`) : /[/\\]node_modules[/\\]/);
}
}
//#endregion
//#region src/config/resolvers/open-api.ts
async function resolveOpenAPIOptions(options) {
if (!options.experimental.openAPI) return;
if (!options.dev && !options.openAPI?.production) return;
const shouldPrerender = !options.dev && options.openAPI?.production === "prerender";
const handlersEnv = shouldPrerender ? "prerender" : "";
const prerenderRoutes = [];
const jsonRoute = options.openAPI?.route || "/_openapi.json";
prerenderRoutes.push(jsonRoute);
options.handlers.push({
route: jsonRoute,
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/openapi")
});
if (options.openAPI?.ui?.scalar !== false) {
const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar";
prerenderRoutes.push(scalarRoute);
options.handlers.push({
route: options.openAPI?.ui?.scalar?.route || "/_scalar",
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/scalar")
});
}
if (options.openAPI?.ui?.swagger !== false) {
const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger";
prerenderRoutes.push(swaggerRoute);
options.handlers.push({
route: swaggerRoute,
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/swagger")
});
}
if (shouldPrerender) {
options.prerender ??= {};
options.prerender.routes ??= [];
options.prerender.routes.push(...prerenderRoutes);
}
}
//#endregion
//#region src/config/resolvers/tsconfig.ts
async function resolveTsconfig(options) {
const root = resolve(options.rootDir || ".") + "/";
if (!options.typescript.tsConfig) options.typescript.tsConfig = await loadTsconfig(root);
if (options.experimental.tsconfigPaths !== false && options.typescript.tsConfig.compilerOptions?.paths) options.alias = {
...tsConfigToAliasObj(options.typescript.tsConfig, root),
...options.alias
};
}
async function loadTsconfig(root) {
const opts = {
root,
cache: loadTsconfig["__cache"] ??= new TSConfckCache(),
ignoreNodeModules: true
};
const tsConfigPath = join(root, "tsconfig.json");
const parsed = await parse(tsConfigPath, opts).catch(() => void 0);
if (!parsed) return {};
const { tsconfig, tsconfigFile } = parsed;
tsconfig.compilerOptions ??= {};
if (!tsconfig.compilerOptions.baseUrl) tsconfig.compilerOptions.baseUrl = resolve(tsconfigFile, "..");
return tsconfig;
}
function tsConfigToAliasObj(tsconfig, root) {
const compilerOptions = tsconfig?.compilerOptions;
if (!compilerOptions?.paths) return {};
const paths = compilerOptions.paths;
const alias = {};
for (const [key, targets] of Object.entries(paths)) {
let source = key;
let target = targets?.[0];
if (!target) continue;
if (source.includes("*") || target.includes("*")) {
source = source.replace(/\/\*$/, "");
target = target.replace(/\/\*$/, "");
if (source.includes("*") || target.includes("*")) continue;
}
if (target.startsWith(".")) {
if (!compilerOptions.baseUrl) continue;
target = resolve(root, compilerOptions.baseUrl, target) + (key.endsWith("*") ? "/" : "");
}
alias[source] = target;
}
return alias;
}
//#endregion
//#region src/config/resolvers/paths.ts
const RESOLVE_EXTENSIONS = [
".ts",
".js",
".mts",
".mjs",
".tsx",
".jsx"
];
async function resolvePathOptions(options) {
options.rootDir = resolve(options.rootDir || ".") + "/";
options.buildDir = resolve(options.rootDir, options.buildDir || ".") + "/";
options.workspaceDir ||= await findWorkspaceDir(options.rootDir).catch(() => options.rootDir) + "/";
if (options.srcDir) {
if (options.serverDir === void 0) options.serverDir = options.srcDir;
consola$1.warn(`"srcDir" option is deprecated. Please use "serverDir" instead.`);
}
if (options.serverDir !== false) {
if (options.serverDir === true) options.serverDir = "server";
options.serverDir = resolve(options.rootDir, options.serverDir || ".") + "/";
}
options.alias ??= {};
if (!options.static && !options.entry) throw new Error(`Nitro entry is missing! Is "${options.preset}" preset correct?`);
if (options.entry) options.entry = resolveNitroPath(options.entry, options);
options.output.dir = resolveNitroPath(options.output.dir || NitroDefaults.output.dir, options, options.rootDir) + "/";
options.output.publicDir = resolveNitroPath(options.output.publicDir || NitroDefaults.output.publicDir, options, options.rootDir) + "/";
options.output.serverDir = resolveNitroPath(options.output.serverDir || NitroDefaults.output.serverDir, options, options.rootDir) + "/";
options.nodeModulesDirs.push(resolve(options.rootDir, "node_modules"));
options.nodeModulesDirs.push(resolve(options.workspaceDir, "node_modules"));
options.nodeModulesDirs.push(resolve(pkgDir, "dist/node_modules"));
options.nodeModulesDirs.push(resolve(pkgDir, "node_modules"));
options.nodeModulesDirs.push(resolve(pkgDir, ".."));
options.nodeModulesDirs = [...new Set(options.nodeModulesDirs.map((dir) => resolve(options.rootDir, dir) + "/"))];
options.plugins = options.plugins.map((p) => resolveNitroPath(p, options));
if (options.serverDir) options.scanDirs.unshift(options.serverDir);
options.scanDirs = options.scanDirs.map((dir) => resolve(options.rootDir, dir));
options.scanDirs = [...new Set(options.scanDirs.map((dir) => dir + "/"))];
options.handlers = options.handlers.map((h) => {
return {
...h,
handler: resolveNitroPath(h.handler, options)
};
});
options.routes = Object.fromEntries(Object.entries(options.routes).map(([route, h]) => {
if (typeof h === "string") h = { handler: h };
h.handler = resolveNitroPath(h.handler, options);
return [route, h];
}));
if (!options.routes["/**"] && !options.handlers.some((h) => h.route === "/**")) {
const serverEntry = resolveModulePath("./server", {
from: [options.rootDir, ...options.scanDirs],
extensions: RESOLVE_EXTENSIONS,
try: true
});
if (serverEntry) {
if (!(options.handlers.some((h) => h.handler === serverEntry) || Object.values(options.routes).some((r) => r.handler === serverEntry))) {
options.routes["/**"] = { handler: serverEntry };
consola$1.info(`Using \`${prettyPath(serverEntry)}\` as default route handler.`);
}
}
}
if (options.renderer?.handler) options.renderer.handler = resolveModulePath(resolveNitroPath(options.renderer?.handler, options), {
from: [options.rootDir, ...options.scanDirs],
extensions: RESOLVE_EXTENSIONS
});
if (options.renderer?.template) options.renderer.template = resolveModulePath(resolveNitroPath(options.renderer?.template, options), {
from: [options.rootDir, ...options.scanDirs],
extensions: [".html"]
});
else if (!options.renderer?.handler) {
const defaultIndex = resolveModulePath("./index.html", {
from: [options.rootDir, ...options.scanDirs],
extensions: [".html"],
try: true
});
if (defaultIndex) {
options.renderer ??= {};
options.renderer.template = defaultIndex;
consola$1.info(`Using \`${prettyPath(defaultIndex)}\` as renderer template.`);
}
}
if (options.renderer?.template && !options.renderer?.handler) {
options.renderer ??= {};
options.renderer.handler = join(runtimeDir, "internal/routes/renderer-template" + (options.dev ? ".dev" : ""));
}
}
//#endregion
//#region src/config/resolvers/route-rules.ts
async function resolveRouteRulesOptions(options) {
options.routeRules = normalizeRouteRules(options);
}
function normalizeRouteRules(config) {
const normalizedRules = {};
for (let path in config.routeRules) {
const routeConfig = config.routeRules[path];
path = withLeadingSlash(path);
const routeRules = {
...routeConfig,
redirect: void 0,
proxy: void 0
};
if (routeConfig.redirect) {
routeRules.redirect = {
to: "/",
status: 307,
...typeof routeConfig.redirect === "string" ? { to: routeConfig.redirect } : routeConfig.redirect
};
if (path.endsWith("/**")) routeRules.redirect._redirectStripBase = path.slice(0, -3);
}
if (routeConfig.proxy) {
routeRules.proxy = typeof routeConfig.proxy === "string" ? { to: routeConfig.proxy } : routeConfig.proxy;
if (path.endsWith("/**")) routeRules.proxy._proxyStripBase = path.slice(0, -3);
}
if (routeConfig.cors) routeRules.headers = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "*",
"access-control-allow-headers": "*",
"access-control-max-age": "0",
...routeRules.headers
};
if (routeConfig.swr) {
routeRules.cache = routeRules.cache || {};
routeRules.cache.swr = true;
if (typeof routeConfig.swr === "number") routeRules.cache.maxAge = routeConfig.swr;
}
if (routeConfig.cache === false) routeRules.cache = false;
normalizedRules[path] = routeRules;
}
return normalizedRules;
}
//#endregion
//#region src/config/resolvers/runtime-config.ts
async function resolveRuntimeConfigOptions(options) {
options.runtimeConfig = normalizeRuntimeConfig(options);
}
function normalizeRuntimeConfig(config) {
provideFallbackValues(config.runtimeConfig || {});
const runtimeConfig = defu(config.runtimeConfig, {
app: { baseURL: config.baseURL },
nitro: {
envExpansion: config.experimental?.envExpansion,
openAPI: config.openAPI
}
});
runtimeConfig.nitro.routeRules = config.routeRules;
checkSerializableRuntimeConfig(runtimeConfig);
return runtimeConfig;
}
function provideFallbackValues(obj) {
for (const key in obj) if (obj[key] === void 0 || obj[key] === null) obj[key] = "";
else if (typeof obj[key] === "object") provideFallbackValues(obj[key]);
}
function checkSerializableRuntimeConfig(obj, path = []) {
if (isPrimitiveValue(obj)) return;
for (const key in obj) {
const value = obj[key];
if (value === null || value === void 0 || isPrimitiveValue(value)) continue;
if (Array.isArray(value)) for (const [index, item] of value.entries()) checkSerializableRuntimeConfig(item, [...path, `${key}[${index}]`]);
else if (typeof value === "object" && value.constructor === Object && (!value.constructor?.name || value.constructor.name === "Object")) checkSerializableRuntimeConfig(value, [...path, key]);
else console.warn(`Runtime config option \`${[...path, key].join(".")}\` may not be able to be serialized.`);
}
}
function isPrimitiveValue(value) {
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
}
//#endregion
//#region src/config/resolvers/storage.ts
async function resolveStorageOptions(options) {}
//#endregion
//#region src/config/resolvers/url.ts
async function resolveURLOptions(options) {
options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL));
}
//#endregion
//#region src/config/resolvers/error.ts
async function resolveErrorOptions(options) {
if (!options.errorHandler) options.errorHandler = [];
else if (!Array.isArray(options.errorHandler)) options.errorHandler = [options.errorHandler];
options.errorHandler = options.errorHandler.map((h) => resolveNitroPath(h, options));
options.errorHandler.push(join(runtimeDir, `internal/error/${options.dev ? "dev" : "prod"}`));
}
//#endregion
//#region src/config/resolvers/unenv.ts
const common = {
meta: {
name: "nitro-common",
url: import.meta.url
},
alias: {
"buffer/": "node:buffer",
"buffer/index": "node:buffer",
"buffer/index.js": "node:buffer",
"string_decoder/": "node:string_decoder",
"process/": "node:process"
}
};
const nodeless = {
meta: {
name: "nitro-nodeless",
url: import.meta.url
},
inject: {
global: "unenv/polyfill/globalthis",
process: "node:process",
Buffer: ["node:buffer", "Buffer"],
clearImmediate: ["node:timers", "clearImmediate"],
setImmediate: ["node:timers", "setImmediate"],
performance: "unenv/polyfill/performance",
PerformanceObserver: ["node:perf_hooks", "PerformanceObserver"],
BroadcastChannel: ["node:worker_threads", "BroadcastChannel"]
},
polyfill: [
"unenv/polyfill/globalthis-global",
"unenv/polyfill/process",
"unenv/polyfill/buffer",
"unenv/polyfill/timers"
]
};
async function resolveUnenv(options) {
options.unenv ??= [];
if (!Array.isArray(options.unenv)) options.unenv = [options.unenv];
options.unenv = options.unenv.filter(Boolean);
if (!options.node) options.unenv.unshift(nodeless);
options.unenv.unshift(common);
}
//#endregion
//#region src/config/resolvers/builder.ts
const VALID_BUILDERS = [
"rollup",
"rolldown",
"vite",
"rolldown-vite"
];
async function resolveBuilder(options) {
options.builder ??= process.env.NITRO_BUILDER;
if (options.builder) {
if (!VALID_BUILDERS.includes(options.builder)) throw new Error(`Invalid nitro builder "${options.builder}". Valid builders are: ${VALID_BUILDERS.join(", ")}.`);
const pkg = options.builder === "rolldown-vite" ? "vite" : options.builder;
if (!isPkgInstalled(pkg, options.rootDir)) {
if (!await consola$1.prompt(`Nitro builder package \`${pkg}\` is not installed. Would you like to install it?`, {
type: "confirm",
default: true,
cancel: "null"
})) throw new Error(`Nitro builder package "${options.builder}" is not installed. Please install it in your project dependencies.`);
await installPkg(pkg, options.rootDir);
}
return;
}
for (const pkg of [
"rolldown",
"rollup",
"vite"
]) if (isPkgInstalled(pkg, options.rootDir)) {
options.builder = pkg;
return;
}
const pkgToInstall = await consola$1.prompt(`No nitro builder specified. Which builder would you like to install?`, {
type: "select",
cancel: "null",
options: VALID_BUILDERS.map((b) => ({
label: b,
value: b
}))
});
if (!pkgToInstall) throw new Error(`No nitro builder specified. Please install one of the following packages: ${VALID_BUILDERS.join(", ")} and set it as the builder in your nitro config or via the NITRO_BUILDER environment variable.`);
await installPkg(pkgToInstall, options.rootDir);
options.builder = pkgToInstall;
}
const require = createRequire(process.cwd() + "/_index.js");
function isPkgInstalled(pkg, root) {
try {
require.resolve(pkg, { paths: [root] });
return true;
} catch {
return false;
}
}
async function installPkg(pkg, root) {
const { addDevDependency } = await import("../cli/_chunks/dist4.mjs");
return addDevDependency(pkg === "rolldown-vite" ? "vite@npm:rolldown-vite" : pkg, { cwd: root });
}
//#endregion
//#region src/config/loader.ts
const configResolvers = [
resolveCompatibilityOptions,
resolveTsconfig,
resolvePathOptions,
resolveImportsOptions,
resolveRouteRulesOptions,
resolveDatabaseOptions,
resolveExportConditionsOptions,
resolveRuntimeConfigOptions,
resolveOpenAPIOptions,
resolveURLOptions,
resolveAssetsOptions,
resolveStorageOptions,
resolveErrorOptions,
resolveUnenv,
resolveBuilder
];
async function loadOptions(configOverrides = {}, opts = {}) {
const options = await _loadUserConfig(configOverrides, opts);
for (const resolver of configResolvers) await resolver(options);
return options;
}
async function _loadUserConfig(configOverrides = {}, opts = {}) {
configOverrides = klona(configOverrides);
globalThis.defineNitroConfig = globalThis.defineNitroConfig || ((c) => c);
let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE;
const { resolvePreset } = await import("../_presets.mjs");
let preset = configOverrides.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET;
const _dotenv = opts.dotenv ?? (configOverrides.dev && { fileName: [".env", ".env.local"] });
const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({
name: "nitro",
cwd: configOverrides.rootDir,
dotenv: _dotenv,
extend: { extendKey: ["extends", "preset"] },
defaults: NitroDefaults,
jitiOptions: { alias: {
nitropack: "nitro/config",
"nitro/config": "nitro/config"
} },
async overrides({ rawConfigs }) {
const getConf = (key) => configOverrides[key] ?? rawConfigs.main?.[key] ?? rawConfigs.rc?.[key] ?? rawConfigs.packageJson?.[key];
if (!compatibilityDate) compatibilityDate = getConf("compatibilityDate");
const framework = getConf("framework");
const isCustomFramework = framework?.name && framework.name !== "nitro";
if (!preset) preset = getConf("preset");
if (configOverrides.dev) preset = preset && preset !== "nitro-dev" ? await resolvePreset(preset, {
static: getConf("static"),
dev: true,
compatibilityDate: compatibilityDate || "latest"
}).then((p) => p?._meta?.name || "nitro-dev").catch(() => "nitro-dev") : "nitro-dev";
else if (!preset) preset = await resolvePreset("", {
static: getConf("static"),
dev: false,
compatibilityDate: compatibilityDate || "latest"
}).then((p) => p?._meta?.name);
return {
...configOverrides,
preset,
typescript: {
generateRuntimeConfigTypes: !isCustomFramework,
...getConf("typescript"),
...configOverrides.typescript
}
};
},
async resolve(id) {
const preset$1 = await resolvePreset(id, {
static: configOverrides.static,
compatibilityDate: compatibilityDate || "latest",
dev: configOverrides.dev
});
if (preset$1) return { config: klona(preset$1) };
},
...opts.c12
});
const options = klona(loadedConfig.config);
options._config = configOverrides;
options._c12 = loadedConfig;
options.preset = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || preset;
options.compatibilityDate = resolveCompatibilityDates(compatibilityDate, options.compatibilityDate);
if (options.dev && options.preset !== "nitro-dev") consola$1.info(`Using \`${options.preset}\` emulation in development mode.`);
return options;
}
//#endregion
//#region src/config/update.ts
async function updateNitroConfig(nitro, config) {
nitro.options.routeRules = normalizeRouteRules(config.routeRules ? config : nitro.options);
nitro.options.runtimeConfig = normalizeRuntimeConfig(config.runtimeConfig ? config : nitro.options);
await nitro.hooks.callHook("rollup:reload");
consola$1.success("Nitro config hot reloaded!");
}
//#endregion
//#region src/module.ts
async function installModules(nitro) {
const _modules = [...nitro.options.modules || []];
const modules = await Promise.all(_modules.map((mod) => _resolveNitroModule(mod, nitro.options)));
const _installedURLs = /* @__PURE__ */ new Set();
for (const mod of modules) {
if (mod._url) {
if (_installedURLs.has(mod._url)) continue;
_installedURLs.add(mod._url);
}
await mod.setup(nitro);
}
}
async function _resolveNitroModule(mod, nitroOptions) {
let _url;
if (typeof mod === "string") mod = await import(resolveModuleURL(mod, {
from: [nitroOptions.rootDir],
extensions: [
".mjs",
".cjs",
".js",
".mts",
".cts",
".ts"
]
})).then((m) => m.default || m);
if (typeof mod === "function") mod = { setup: mod };
if ("nitro" in mod) mod = mod.nitro;
if (!mod.setup) throw new Error("Invalid Nitro module: missing setup() function.");
return {
_url,
...mod
};
}
//#endregion
//#region src/task.ts
/** @experimental */
async function runTask(taskEvent, opts) {
return await (await _getTasksContext(opts)).devFetch(`/_nitro/tasks/${taskEvent.name}`, {
method: "POST",
body: taskEvent
});
}
/** @experimental */
async function listTasks(opts) {
return (await (await _getTasksContext(opts)).devFetch("/_nitro/tasks")).tasks;
}
function addNitroTasksVirtualFile(nitro) {
nitro.options.virtual["#nitro-internal-virtual/tasks"] = () => {
const _scheduledTasks = Object.entries(nitro.options.scheduledTasks || {}).map(([cron, _tasks]) => {
return {
cron,
tasks: (Array.isArray(_tasks) ? _tasks : [_tasks]).filter((name) => {
if (!nitro.options.tasks[name]) {
nitro.logger.warn(`Scheduled task \`${name}\` is not defined!`);
return false;
}
return true;
})
};
}).filter((e) => e.tasks.length > 0);
const scheduledTasks = _scheduledTasks.length > 0 ? _scheduledTasks : false;
return `
export const scheduledTasks = ${JSON.stringify(scheduledTasks)};
export const tasks = {
${Object.entries(nitro.options.tasks).map(([name, task]) => `"${name}": {
meta: {
description: ${JSON.stringify(task.description)},
},
resolve: ${task.handler ? `() => import("${normalize(task.handler)}").then(r => r.default || r)` : "undefined"},
}`).join(",\n")}
};`;
};
}
const _devHint = `(is dev server running?)`;
async function _getTasksContext(opts) {
const buildInfoPath = resolve(resolve(resolve(process.cwd(), opts?.cwd || "."), opts?.buildDir || "node_modules/.nitro"), "nitro.dev.json");
if (!existsSync(buildInfoPath)) throw new Error(`Missing info file: \`${buildInfoPath}\` ${_devHint}`);
const buildInfo = JSON.parse(await readFile(buildInfoPath, "utf8"));
if (!buildInfo.dev?.pid || !buildInfo.dev?.workerAddress) throw new Error(`Missing dev server info in: \`${buildInfoPath}\` ${_devHint}`);
if (!_pidIsRunning(buildInfo.dev.pid)) throw new Error(`Dev server is not running (pid: ${buildInfo.dev.pid})`);
return {
buildInfo,
devFetch: ofetch.create({
baseURL: `http://${buildInfo.dev.workerAddress.host || "localhost"}:${buildInfo.dev.workerAddress.port || "3000"}`,
socketPath: buildInfo.dev.workerAddress.socketPath
})
};
}
function _pidIsRunning(pid) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
//#endregion
//#region src/routing.ts
const isGlobalMiddleware = (h) => !h.method && (!h.route || h.route === "/**");
function initNitroRouting(nitro) {
const envConditions = new Set([
nitro.options.dev ? "dev" : "prod",
nitro.options.preset,
nitro.options.preset === "nitro-prerender" ? "prerender" : void 0
].filter(Boolean));
const matchesEnv = (h) => {
const envs = (Array.isArray(h.env) ? h.env : [h.env]).filter(Boolean);
return envs.length === 0 || envs.some((env) => envConditions.has(env));
};
const routes = new Router(nitro.options.baseURL);
const routeRules = new Router(nitro.options.baseURL);
const globalMiddleware = [];
const routedMiddleware = new Router(nitro.options.baseURL);
const sync = () => {
routeRules._update(Object.entries(nitro.options.routeRules).map(([route, data]) => ({
route,
method: "",
data: {
...data,
_route: route
}
})));
const _routes = [
...Object.entries(nitro.options.routes).flatMap(([route, handler]) => {
if (typeof handler === "string") handler = { handler };
return {
...handler,
route,
middleware: false
};
}),
...nitro.options.handlers,
...nitro.scannedHandlers
].filter((h) => h && !h.middleware && matchesEnv(h));
if (nitro.options.renderer?.handler) _routes.push({
route: "/**",
lazy: true,
handler: nitro.options.renderer?.handler
});
routes._update(_routes.map((h) => ({
...h,
method: h.method || "",
data: handlerWithImportHash(h)
})), { merge: true });
const _middleware = [...nitro.scannedHandlers, ...nitro.options.handlers].filter((h) => h && h.middleware && matchesEnv(h));
if (nitro.options.serveStatic) _middleware.unshift({
route: "/**",
middleware: true,
handler: join(runtimeDir, "internal/static")
});
globalMiddleware.splice(0, globalMiddleware.length, ..._middleware.filter((h) => isGlobalMiddleware(h)).map((m) => handlerWithImportHash(m)));
routedMiddleware._update(_middleware.filter((h) => !isGlobalMiddleware(h)).map((h) => ({
...h,
method: h.method || "",
data: handlerWithImportHash(h)
})));
};
nitro.routing = Object.freeze({
sync,
routes,
routeRules,
globalMiddleware,
routedMiddleware
});
}
function handlerWithImportHash(h) {
const id = (h.lazy ? "_lazy_" : "_") + hash(h.handler).replace(/-/g, "").slice(0, 6);
return {
...h,
_importHash: id
};
}
var Router = class {
_routes;
_router;
_compiled;
_baseURL;
constructor(baseURL) {
this._update([]);
this._baseURL = baseURL || "";
if (this._baseURL.endsWith("/")) this._baseURL = this._baseURL.slice(0, -1);
}
get routes() {
return this._routes;
}
_update(routes, opts) {
this._routes = routes;
this._router = createRouter();
this._compiled = void 0;
for (const route of routes) addRoute(this._router, route.method, this._baseURL + route.route, route.data);
if (opts?.merge) mergeCatchAll(this._router);
}
hasRoutes() {
return this._routes.length > 0;
}
compileToString(opts) {
if (this._compiled) return this._compiled;
this._compiled = compileRouterToString(this._router, void 0, opts);
if (this.routes.length === 1 && this.routes[0].route === "/**" && this.routes[0].method === "") this._compiled = `/* @__PURE__ */ (() => {const data=${(opts?.serialize || JSON.stringify)(this.routes[0].data)};return ((_m, p)=>{return {data,params:{"_":p.slice(1)}};})})()`;
return this._compiled;
}
match(method, path) {
return findRoute(this._router, method, path)?.data;
}
matchAll(method, path) {
return findAllRoutes(this._router, method, path).map((route) => route.data);
}
};
function mergeCatchAll(router) {
const handlers = router.root?.wildcard?.methods?.[""];
if (!handlers || handlers.length < 2) return;
handlers.splice(0, handlers.length, {
...handlers[0],
data: handlers.map((h) => h.data)
});
}
//#endregion
//#region src/global.ts
const nitroInstances = globalThis.__nitro_instances__ ||= [];
const globalKey = "__nitro_builder__";
function registerNitroInstance(nitro) {
if (nitroInstances.includes(nitro)) return;
globalInit();
nitroInstances.unshift(nitro);
nitro.hooks.hookOnce("close", () => {
nitroInstances.splice(nitroInstances.indexOf(nitro), 1);
if (nitroInstances.length === 0) delete globalThis[globalKey];
});
}
function globalInit() {
if (globalThis[globalKey]) return;
globalThis[globalKey] = { async fetch(req) {
for (let r = 0; r < 10 && nitroInstances.length === 0; r++) await new Promise((resolve$1) => setTimeout(resolve$1, 300));
const nitro = nitroInstances[0];
if (!nitro) throw new Error("No Nitro instance is running.");
return nitro.fetch(req);
} };
}
//#endregion
//#region src/nitro.ts
async function createNitro(config = {}, opts = {}) {
const nitro = {
options: await loadOptions(config, opts),
hooks: new Hookable(),
vfs: {},
routing: {},
logger: consola.withTag("nitro"),
scannedHandlers: [],
fetch: () => {
throw new Error("no dev server attached!");
},
close: () => Promise.resolve(nitro.hooks.callHook("close")),
async updateConfig(config$1) {
updateNitroConfig(nitro, config$1);
}
};
registerNitroInstance(nitro);
initNitroRouting(nitro);
await scanAndSyncOptions(nitro);
if (nitro.options.debug) createDebugger(nitro.hooks, { tag: "nitro" });
if (nitro.options.logLevel !== void 0) nitro.logger.level = nitro.options.logLevel;
nitro.hooks.addHooks(nitro.options.hooks);
addNitroTasksVirtualFile(nitro);
await installModules(nitro);
if (nitro.options.imports) {
nitro.unimport = createUnimport(nitro.options.imports);
await nitro.unimport.init();
nitro.options.virtual["#imports"] = () => nitro.unimport?.toExports() || "";
nitro.options.virtual["#nitro"] = "export * from \"#imports\"";
}
await scanHandlers(nitro);
nitro.routing.sync();
return nitro;
}
//#endregion
//#region src/build/build.ts
async function build(nitro) {
switch (nitro.options.builder) {
case "rollup": {
const { rollupBuild } = await import("../_build/rollup.mjs");
return rollupBuild(nitro);
}
case "rolldown": {
const { rolldownBuild } = await import("../_build/rolldown.mjs");
return rolldownBuild(nitro);
}
case "vite":
case "rolldown-vite": {
const { viteBuild } = await import("../_build/vite.build.mjs");
return viteBuild(nitro);
}
default: throw new Error(`Unknown builder: ${nitro.options.builder}`);
}
}
//#endregion
//#region src/utils/compress.ts
async function compressPublicAssets(nitro) {
const publicFiles = await glob("**", {
cwd: nitro.options.output.publicDir,
absolute: false,
dot: true,
ignore: ["**/*.gz", "**/*.br"]
});
await Promise.all(publicFiles.map(async (fileName) => {
const filePath = resolve(nitro.options.output.publicDir, fileName);
if (existsSync(filePath + ".gz") || existsSync(filePath + ".br")) return;
const mimeType = src_default.getType(fileName) || "text/plain";
const fileContents = await fsp.readFile(filePath);
if (fileContents.length < 1024 || fileName.endsWith(".map") || !isCompressibleMime(mimeType)) return;
const { gzip, brotli } = nitro.options.compressPublicAssets || {};
const encodings = [gzip !== false && "gzip", brotli !== false && "br"].filter(Boolean);
await Promise.all(encodings.map(async (encoding) => {
const compressedPath = filePath + ("." + (encoding === "gzip" ? "gz" : "br"));
if (existsSync(compressedPath)) return;
const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION };
const brotliOptions = {
[zlib.constants.BROTLI_PARAM_MODE]: isTextMime(mimeType) ? zlib.constants.BROTLI_MODE_TEXT : zlib.constants.BROTLI_MODE_GENERIC,
[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length
};
const compressedBuff = await new Promise((resolve$1, reject) => {
const cb = (error, result) => error ? reject(error) : resolve$1(result);
if (encoding === "gzip") zlib.gzip(fileContents, gzipOptions, cb);
else zlib.brotliCompress(fileContents, brotliOptions, cb);
});
await fsp.writeFile(compressedPath, compressedBuff);
}));
}));
}
function isTextMime(mimeType) {
return /text|javascript|json|xml/.test(mimeType);
}
const COMPRESSIBLE_MIMES_RE = new Set([
"application/dash+xml",
"application/eot",
"application/font",
"application/font-sfnt",
"application/javascript",
"application/json",
"application/opentype",
"application/otf",
"application/pdf",
"application/pkcs7-mime",
"application/protobuf",
"application/rss+xml",
"application/truetype",
"application/ttf",
"application/vnd.apple.mpegurl",
"application/vnd.mapbox-vector-tile",
"application/vnd.ms-fontobject",
"application/wasm",
"application/xhtml+xml",
"application/xml",
"application/x-font-opentype",
"application/x-font-truetype",
"application/x-font-ttf",
"application/x-httpd-cgi",
"application/x-javascript",
"application/x-mpegurl",
"application/x-opentype",
"application/x-otf",
"application/x-perl",
"application/x-ttf",
"font/eot",
"font/opentype",
"font/otf",
"font/ttf",
"image/svg+xml",
"text/css",
"text/csv",
"text/html",
"text/javascript",
"text/js",
"text/plain",
"text/richtext",
"text/tab-separated-values",
"text/xml",
"text/x-component",
"text/x-java-source",
"text/x-script",
"vnd.apple.mpegurl"
]);
function isCompressibleMime(mimeType) {
return COMPRESSIBLE_MIMES_RE.has(mimeType);
}
//#endregion
//#region src/build/assets.ts
const NEGATION_RE = /^(!?)(.*)$/;
const PARENT_DIR_GLOB_RE = /!?\.\.\//;
async function scanUnprefixedPublicAssets(nitro) {
const scannedPaths = [];
for (const asset of nitro.options.publicAssets) {
if (asset.baseURL && asset.baseURL !== "/" && !asset.fallthrough) continue;
if (!await isDirectory(asset.dir)) continue;
const publicAssets = await glob(getIncludePatterns(nitro, asset.dir), {
cwd: asset.dir,
absolute: false,
dot: true
});
scannedPaths.push(...publicAssets.map((file) => join(asset.baseURL || "/", file)));
}
return scannedPaths;
}
async function copyPublicAssets(nitro) {
if (nitro.options.noPublicDir) return;
for (const asset of nitro.options.publicAssets) {
const assetDir = asset.dir;
const dstDir = join(nitro.options.output.publicDir, asset.baseURL);
if (await isDirectory(assetDir)) {
const publicAssets = await glob(getIncludePatterns(nitro, assetDir), {
cwd: assetDir,
absolute: false,
dot: true
});
await Promise.all(publicAssets.map(async (file) => {
const src = join(assetDir, file);
const dst = join(dstDir, file);
if (!existsSync(dst)) await promises.cp(src, dst);
}));
}
}
if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro);
nitro.logger.success("Generated public " + prettyPath(nitro.options.output.publicDir));
}
function getIncludePatterns(nitro, assetDir) {
return ["**", ...nitro.options.ignore.map((p) => {
const [_, negation, pattern] = p.match(NEGATION_RE) || [];
return (negation ? "" : "!") + (pattern.startsWith("*") ? pattern : relative(assetDir, resolve(nitro.options.rootDir, pattern)));
})].filter((p) => !PARENT_DIR_GLOB_RE.test(p));
}
//#endregion
//#region src/build/prepare.ts
async function prepare(nitro) {
await prepareDir(nitro.options.output.dir);
if (!nitro.options.noPublicDir) await prepareDir(nitro.options.output.publicDir);
if (!nitro.options.static) await prepareDir(nitro.options.output.serverDir);
}
async function prepareDir(dir) {
await fsp.rm(dir, {
recursive: true,
force: true
});
await fsp.mkdir(dir, { recursive: true });
}
//#endregion
//#region src/prerender/utils.ts
const allowedExtensions = new Set(["", ".json"]);
const linkParents = /* @__PURE__ */ new Map();
const HTML_ENTITIES = {
"&lt;": "<",
"&gt;": ">",
"&amp;": "&",
"&apos;": "'",
"&quot;": "\""
};
function escapeHtml(text) {
return text.replace(/&(lt|gt|amp|apos|quot);/g, (ch) => HTML_ENTITIES[ch] || ch);
}
async function extractLinks(html, from, res, crawlLinks) {
const links = [];
const _links = [];
if (crawlLinks) await z(P(html), (node) => {
if (!node.attributes?.href) return;
const link = escapeHtml(node.attributes.href);
if (!decodeURIComponent(link).startsWith("#") && allowedExtensions.has(getExtension(link))) _links.push(link);
});
const header = res.headers.get("x-nitro-prerender") || "";
_links.push(...header.split(",").map((i) => decodeURIComponent(i.trim())));
for (const link of _links.filter(Boolean)) {
const _link = parseURL(link);
if (_link.protocol || _link.host) continue;
if (!_link.pathname.startsWith("/")) {
const fromURL = new URL(from, "http://localhost");
_link.pathname = new URL(_link.pathname, fromURL).pathname;
}
links.push(_link.pathname + _link.search);
}
for (const link of links) {
const _parents = linkParents.get(link);
if (_parents) _parents.add(from);
else linkParents.set(link, new Set([from]));
}
return links;
}
const EXT_REGEX = /\.[\da-z]+$/;
function getExtension(link) {
return (parseURL(link).pathname.match(EXT_REGEX) || [])[0] || "";
}
function formatPrerenderRoute(route) {
let str = ` ├─ ${route.route} (${route.generateTimeMS}ms)`;
if (route.error) {
const parents = linkParents.get(route.route);
const errorColor = colors[route.error.status === 404 ? "yellow" : "red"];
const errorLead = parents?.size ? "├──" : "└──";
str += `\n │ ${errorLead} ${errorColor(route.error.message)}`;
if (parents?.size) str += `\n${[...parents.values()].map((link) => ` │ └── Linked from ${link}`).join("\n")}`;
}
if (route.skip) str += colors.gray(" (skipped)");
return colors.gray(str);
}
function matchesIgnorePattern(path, pattern) {
if (typeof pattern === "string") return path.startsWith(pattern);
if (typeof pattern === "function") return pattern(path) === true;
if (pattern instanceof RegExp) return pattern.test(path);
return false;
}
//#endregion
//#region src/prerender/prerender.ts
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
async function prerender(nitro) {
if (nitro.options.noPublicDir) {
nitro.logger.warn("Skipping prerender since `noPublicDir` option is enabled.");
return;
}
if (nitro.options.builder === "vite") {
nitro.logger.warn("Skipping prerender since not supported with vite builder yet...");
return;
}
const routes = new Set(nitro.options.prerender.routes);
const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path$1, options]) => options.prerender && !path$1.includes("*")).map((e) => e[0]);
for (const route of prerenderRulePaths) routes.add(route);
await nitro.hooks.callHook("prerender:routes", routes);
if (routes.size === 0) if (nitro.options.prerender.crawlLinks) routes.add("/");
else return;
nitro.logger.info("Initializing prerenderer");
nitro._prerenderedRoutes = [];
nitro._prerenderMeta = nitro._prerenderMeta || {};
const prerendererConfig = {
...nitro.options._config,
static: false,
rootDir: nitro.options.rootDir,
logLevel: 0,
preset: "nitro-prerender"
};
await nitro.hooks.callHook("prerender:config", prerendererConfig);
const nitroRenderer = await createNitro(prerendererConfig);
const prerenderStartTime = Date.now();
await nitro.hooks.callHook("prerender:init", nitroRenderer);
let path = relative(nitro.options.output.dir, nitro.options.output.publicDir);
if (!path.startsWith(".")) path = `./${path}`;
nitroRenderer.options.commands.preview = `npx serve ${path}`;
nitroRenderer.options.output.dir = nitro.options.output.dir;
await build(nitroRenderer);
const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs";
const prerenderer = await import(pathToFileURL(resolve(nitroRenderer.options.output.serverDir, serverFilename)).href).then((m) => m.default);
const routeRules = createRouter();
for (const [route, rules] of Object.entries(nitro.options.routeRules)) addRoute(routeRules, void 0, route, rules);
const _getRouteRules = (path$1) => defu({}, ...findAllRoutes(routeRules, void 0, path$1).map((r) => r.data).reverse());
const generatedRoutes = /* @__PURE__ */ new Set();
const failedRoutes = /* @__PURE__ */ new Set();
const skippedRoutes = /* @__PURE__ */ new Set();
const displayedLengthWarns = /* @__PURE__ */ new Set();
const publicAssetBases = nitro.options.publicAssets.filter((a$1) => !!a$1.baseURL && a$1.baseURL !== "/" && !a$1.fallthrough).map((a$1) => withTrailingSlash(a$1.baseURL));
const scannedPublicAssets = nitro.options.prerender.ignoreUnprefixedPublicAssets ? new Set(await scanUnprefixedPublicAssets(nitro)) : /* @__PURE__ */ new Set();
const canPrerender = (route = "/") => {
if (generatedRoutes.has(route) || skippedRoutes.has(route)) return false;
for (const pattern of nitro.options.prerender.ignore) if (matchesIgnorePattern(route, pattern)) return false;
if (publicAssetBases.some((base) => route.startsWith(base))) return false;
if (scannedPublicAssets.has(route)) return false;
if (_getRouteRules(route).prerender === false) return false;
return true;
};
const canWriteToDisk = (route) => {
if (route.route.includes("?")) return false;
const FS_MAX_SEGMENT = 255;
const FS_MAX_PATH_PUBLIC_HTML = 1024 - (nitro.options.output.publicDir.length + 10);
if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) {
displayedLengthWarns.add(route);
const _route = route.route.slice(0, 60) + "...";
if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) nitro.logger.warn(`Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`);
else {
nitro.logger.warn(`Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`);
return false;
}
}
return true;
};
const generateRoute = async (route) => {
const start = Date.now();
route = decodeURI(route);
if (!canPrerender(route)) {
skippedRoutes.add(route);
return;
}
generatedRoutes.add(route);
const _route = { route };
const encodedRoute = encodeURI(route);
const req = toRequest(withBase(encodedRoute, nitro.options.baseURL), { headers: [["x-nitro-prerender", encodedRoute]] });
const res = await prerenderer.fetch(req);
let dataBuff = Buffer.from(await res.arrayBuffer());
Object.defineProperty(_route, "contents", {
get: () => {
return dataBuff ? dataBuff.toString("utf8") : void 0;
},
set(value) {
if (dataBuff) dataBuff = Buffer.from(value);
}
});
Object.defineProperty(_route, "data", {
get: () => {
return dataBuff ? dataBuff.buffer : void 0;
},
set(value) {
if (dataBuff) dataBuff = Buffer.from(value);
}
});
if (![200, ...[
301,
302,
303,
304,
307,
308
]].includes(res.status)) {
_route.error = /* @__PURE__ */ new Error(`[${res.status}] ${res.statusText}`);
_route.error.status = res.status;
_route.error.statusText = res.statusText;
}
_route.generateTimeMS = Date.now() - start;
const contentType = res.headers.get("content-type") || "";
const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8"));
const routeWithIndex = route.endsWith("/") ? route + "index" : route;
const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html";
_route.fileName = withoutBase(isImplicitHTML ? htmlPath : routeWithIndex, nitro.options.baseURL);
const inferredContentType = src_default.getType(_route.fileName) || "text/plain";
_route.contentType = contentType || inferredContentType;
await nitro.hooks.callHook("prerender:generate", _route, nitro);
if (_route.contentType !== inferredContentType) {
nitro._prerenderMeta[_route.fileName] ||= {};
nitro._prerenderMeta[_route.fileName].contentType = _route.contentType;
}
if (_route.error) failedRoutes.add(_route);
if (_route.skip || _route.error) {
await nitro.hooks.callHook("prerender:route", _route);
nitro.logger.log(formatPrerenderRoute(_route));
dataBuff = void 0;
return _route;
}
if (canWriteToDisk(_route)) {
await writeFile$1(join(nitro.options.output.publicDir, _route.fileName), dataBuff);
nitro._prerenderedRoutes.push(_route);
} else _route.skip = true;
if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) {
const extractedLinks = await extractLinks(dataBuff.toString("utf8"), route, res, nitro.options.prerender.crawlLinks);
for (const _link of extractedLinks) if (canPrerender(_link)) routes.add(_link);
}
await nitro.hooks.callHook("prerender:route", _route);
nitro.logger.log(formatPrerenderRoute(_route));
dataBuff = void 0;
return _route;
};
nitro.logger.info(nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`);
await runParallel(routes, generateRoute, {
concurrency: nitro.options.prerender.concurrency,
interval: nitro.options.prerender.interval
});
await prerenderer.close();
await nitro.hooks.callHook("prerender:done", {
prerenderedRoutes: nitro._prerenderedRoutes,
failedRoutes: [...failedRoutes]
});
if (nitro.options.prerender.failOnError && failedRoutes.size > 0) {
nitro.logger.log("\nErrors prerendering:");
for (const route of failedRoutes) nitro.logger.log(formatPrerenderRoute(route));
nitro.logger.log("");
throw new Error("Exiting due to prerender errors.");
}
const prerenderTimeInMs = Date.now() - prerenderStartTime;
nitro.logger.info(`Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`);
if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro);
}
//#endregion
export { createNitro as a, loadOptions as c, build as i, prepare as n, listTasks as o, copyPublicAssets as r, runTask as s, prerender as t };
import { createRequire } from "node:module";
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
//#endregion
export { __toESM as i, __require as n, __toDynamicImportESM as r, __commonJS as t };
import { O as relative, k as resolve, x as dirname } from "../_libs/c12.mjs";
import { t as glob } from "../_libs/tinyglobby.mjs";
import { r as a } from "../_libs/std-env.mjs";
import { t as runParallel } from "./ANM1K1bE.mjs";
import { t as gzipSize } from "../_libs/gzip-size.mjs";
import { t as prettyBytes } from "../_libs/pretty-bytes.mjs";
import { promises } from "node:fs";
import { colors } from "consola/utils";
//#region src/utils/fs-tree.ts
async function generateFSTree(dir, options = {}) {
if (a) return;
const files = await glob("**/*.*", {
cwd: dir,
ignore: ["*.map"]
});
const items = [];
await runParallel(new Set(files), async (file) => {
const path = resolve(dir, file);
const src = await promises.readFile(path);
const size = src.byteLength;
const gzip = options.compressedSizes ? await gzipSize(src) : 0;
items.push({
file,
path,
size,
gzip
});
}, { concurrency: 10 });
items.sort((a$1, b) => a$1.path.localeCompare(b.path));
let totalSize = 0;
let totalGzip = 0;
let totalNodeModulesSize = 0;
let totalNodeModulesGzip = 0;
let treeText = "";
for (const [index, item] of items.entries()) {
let dir$1 = dirname(item.file);
if (dir$1 === ".") dir$1 = "";
const rpath = relative(process.cwd(), item.path);
const treeChar = index === items.length - 1 ? "└─" : "├─";
if (item.file.includes("node_modules")) {
totalNodeModulesSize += item.size;
totalNodeModulesGzip += item.gzip;
continue;
}
treeText += colors.gray(` ${treeChar} ${rpath} (${prettyBytes(item.size)})`);
if (options.compressedSizes) treeText += colors.gray(` (${prettyBytes(item.gzip)} gzip)`);
treeText += "\n";
totalSize += item.size;
totalGzip += item.gzip;
}
treeText += `${colors.cyan("Σ Total size:")} ${prettyBytes(totalSize + totalNodeModulesSize)}`;
if (options.compressedSizes) treeText += ` (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)`;
treeText += "\n";
return treeText;
}
//#endregion
export { generateFSTree as t };
import { O as relative, k as resolve, x as dirname } from "../_libs/c12.mjs";
import { t as getProperty } from "../_libs/dot-prop.mjs";
import consola$1 from "consola";
import { mkdir, stat, writeFile } from "node:fs/promises";
import { colors } from "consola/utils";
//#region src/utils/fs.ts
function prettyPath(p, highlight = true) {
p = relative(process.cwd(), p);
return highlight ? colors.cyan(p) : p;
}
function resolveNitroPath(path, nitroOptions, base) {
if (typeof path !== "string") throw new TypeError("Invalid path: " + path);
path = _compilePathTemplate(path)(nitroOptions);
for (const base$1 in nitroOptions.alias) if (path.startsWith(base$1)) path = nitroOptions.alias[base$1] + path.slice(base$1.length);
return resolve(base || nitroOptions.rootDir, path);
}
function _compilePathTemplate(contents) {
return (params) => contents.replace(/{{ ?([\w.]+) ?}}/g, (_, match) => {
const val = getProperty(params, match);
if (!val) consola$1.warn(`cannot resolve template param '${match}' in ${contents.slice(0, 20)}`);
return val || `${match}`;
});
}
async function writeFile$1(file, contents, log = false) {
await mkdir(dirname(file), { recursive: true });
await writeFile(file, contents, typeof contents === "string" ? "utf8" : void 0);
if (log) consola$1.info("Generated", prettyPath(file));
}
async function isDirectory(path) {
try {
return (await stat(path)).isDirectory();
} catch {
return false;
}
}
//#endregion
export { writeFile$1 as i, prettyPath as n, resolveNitroPath as r, isDirectory as t };
import { HTTPHandler } from "h3";
import { Nitro } from "nitro/types";
//#region src/dev/app.d.ts
declare class NitroDevApp {
#private;
nitro: Nitro;
fetch: (req: Request) => Response | Promise<Response>;
constructor(nitro: Nitro, catchAllHandler?: HTTPHandler);
}
//#endregion
export { NitroDevApp as t };
import { S as extname$1, k as resolve$1, n as debounce, w as join$1 } from "./_libs/c12.mjs";
import { n as T, r as a } from "./_libs/std-env.mjs";
import { t as src_default } from "./_libs/mime.mjs";
import { r as writeDevBuildInfo } from "./_build/common.mjs";
import { n as createProxyServer } from "./_libs/httpxy.mjs";
import { i as watch$1 } from "./_libs/chokidar.mjs";
import consola$1 from "consola";
import { dirname, resolve } from "node:path";
import { createReadStream, existsSync } from "node:fs";
import { joinURL } from "ufo";
import { readFile, rm, stat } from "node:fs/promises";
import { createBrotliCompress, createGzip } from "node:zlib";
import { Worker } from "node:worker_threads";
import { H3, HTTPError, defineHandler, fromNodeHandler, getRequestIP, getRequestURL, serveStatic, toEventHandler } from "h3";
import { Agent } from "undici";
import { serve } from "srvx/node";
import { ErrorParser } from "youch-core";
import { Youch } from "youch";
import { SourceMapConsumer } from "source-map";
import { FastResponse } from "srvx";
//#region src/dev/proxy.ts
function createHTTPProxy(defaults = {}) {
const proxy = createProxyServer(defaults);
proxy.on("proxyReq", (proxyReq, req) => {
if (!proxyReq.hasHeader("x-forwarded-for")) {
const address = req.socket.remoteAddress;
if (address) proxyReq.appendHeader("x-forwarded-for", address);
}
if (!proxyReq.hasHeader("x-forwarded-port")) {
if (req?.socket?.localPort) proxyReq.setHeader("x-forwarded-port", req.socket.localPort);
}
if (!proxyReq.hasHeader("x-forwarded-Proto")) {
const encrypted = (req?.connection)?.encrypted;
proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http");
}
});
return {
proxy,
async handleEvent(event, opts) {
try {
return await fromNodeHandler((req, res) => proxy.web(req, res, opts))(event);
} catch (error) {
event.res.headers.set("refresh", "3");
throw new HTTPError({
status: 503,
message: "Dev server is unavailable.",
cause: error
});
}
}
};
}
function fetchAddress(addr, input, inputInit) {
let url;
let init;
if (input instanceof Request) {
url = new URL(input.url);
init = {
method: input.method,
headers: input.headers,
body: input.body,
...inputInit
};
} else {
url = new URL(input);
init = inputInit;
}
init = {
duplex: "half",
redirect: "manual",
...init
};
if (addr.socketPath) {
url.protocol = "http:";
return fetch(url, {
...init,
...fetchSocketOptions(addr.socketPath)
});
}
const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`;
const outURL = new URL(url.pathname + url.search, origin);
return fetch(outURL, init);
}
function fetchSocketOptions(socketPath) {
if ("Bun" in globalThis) return { unix: socketPath };
if ("Deno" in globalThis) return { client: Deno.createHttpClient({
transport: "unix",
path: socketPath
}) };
return { dispatcher: new Agent({ connect: { socketPath } }) };
}
//#endregion
//#region src/dev/worker.ts
var NodeDevWorker = class {
closed = false;
#name;
#entry;
#data;
#hooks;
#worker;
#address;
#proxy;
#messageListeners;
constructor(opts) {
this.#name = opts.name;
this.#entry = opts.entry;
this.#data = opts.data;
this.#hooks = opts.hooks;
this.#proxy = createHTTPProxy();
this.#messageListeners = /* @__PURE__ */ new Set();
this.#initWorker();
}
get ready() {
return Boolean(!this.closed && this.#address && this.#proxy && this.#worker);
}
async fetch(input, init) {
for (let i = 0; i < 5 && !(this.#address && this.#proxy); i++) await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i)));
if (!(this.#address && this.#proxy)) return new Response("Dev worker is unavailable", { status: 503 });
return fetchAddress(this.#address, input, init);
}
upgrade(req, socket, head) {
if (!this.ready) return;
return this.#proxy.proxy.ws(req, socket, {
target: this.#address,
xfwd: true
}, head).catch((error) => {
consola$1.error("WebSocket proxy error:", error);
});
}
sendMessage(message) {
if (!this.#worker) throw new Error("Dev worker should be initialized before sending messages.");
this.#worker.postMessage(message);
}
onMessage(listener) {
this.#messageListeners.add(listener);
}
offMessage(listener) {
this.#messageListeners.delete(listener);
}
async close(cause) {
if (this.closed) return;
this.closed = true;
this.#hooks.onClose?.(this, cause);
this.#hooks = {};
const onError = (error) => consola$1.error(error);
await this.#closeWorker().catch(onError);
await this.#closeProxy().catch(onError);
await this.#closeSocket().catch(onError);
}
[Symbol.for("nodejs.util.inspect.custom")]() {
const status = this.closed ? "closed" : this.ready ? "ready" : "pending";
return `NodeDevWorker#${this.#name}(${status})`;
}
#initWorker() {
if (!existsSync(this.#entry)) {
this.close(`worker entry not found in "${this.#entry}".`);
return;
}
const worker = new Worker(this.#entry, {
env: { ...process.env },
workerData: {
name: this.#name,
...this.#data
}
});
worker.once("exit", (code) => {
worker._exitCode = code;
this.close(`worker exited with code ${code}`);
});
worker.once("error", (error) => {
consola$1.error(`Worker error:`, error);
this.close(error);
});
worker.on("message", (message) => {
if (message?.address) {
this.#address = message.address;
this.#hooks.onReady?.(this, this.#address);
}
for (const listener of this.#messageListeners) listener(message);
});
this.#worker = worker;
}
async #closeProxy() {
this.#proxy?.proxy?.close(() => {});
this.#proxy = void 0;
}
async #closeSocket() {
const socketPath = this.#address?.socketPath;
if (socketPath && socketPath[0] !== "\0" && !socketPath.startsWith(String.raw`\\.\pipe`)) await rm(socketPath).catch(() => {});
this.#address = void 0;
}
async #closeWorker() {
if (!this.#worker) return;
this.#worker.postMessage({ event: "shutdown" });
if (!this.#worker._exitCode && !a && !T) await new Promise((resolve$2) => {
const gracefulShutdownTimeoutMs = Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 5e3;
const timeout = setTimeout(() => {
if (process.env.DEBUG) consola$1.warn(`force closing dev worker...`);
}, gracefulShutdownTimeoutMs);
this.#worker?.on("message", (message) => {
if (message.event === "exit") {
clearTimeout(timeout);
resolve$2();
}
});
});
this.#worker.removeAllListeners();
await this.#worker.terminate().catch((error) => {
consola$1.error(error);
});
this.#worker = void 0;
}
};
//#endregion
//#region src/dev/vfs.ts
function createVFSHandler(nitro) {
return defineHandler(async (event) => {
const { socket } = event.runtime?.node?.req || {};
const ip = getRequestIP(event, { xForwardedFor: !socket?.remoteAddress && !socket?.localAddress && Object.keys(socket?.address?.() || {}).length === 0 && socket?.readable && socket?.writable && !socket?.remotePort });
if (!(ip && /^::1$|^127\.\d+\.\d+\.\d+$/.test(ip))) throw new HTTPError({
statusText: `Forbidden IP: "${ip || "?"}"`,
status: 403
});
const vfsEntries = {
...nitro.vfs,
...nitro.options.virtual
};
const url = event.context.params?._ || "";
const isJson = url.endsWith(".json") || event.req.headers.get("accept")?.includes("application/json");
const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || "");
if (id && !(id in vfsEntries)) throw new HTTPError({
message: "File not found",
status: 404
});
let content = id ? vfsEntries[id] : void 0;
if (typeof content === "function") content = await content();
if (isJson) return {
rootDir: nitro.options.rootDir,
entries: Object.keys(vfsEntries).map((id$1) => ({
id: id$1,
path: "/_vfs.json/" + encodeURIComponent(id$1)
})),
current: id ? {
id,
content
} : null
};
const directories = { [nitro.options.rootDir]: {} };
const fpaths = Object.keys(vfsEntries);
for (const item of fpaths) {
const segments = item.replace(nitro.options.rootDir, "").split("/").filter(Boolean);
let currentDir = item.startsWith(nitro.options.rootDir) ? directories[nitro.options.rootDir] : directories;
for (const segment of segments) {
if (!currentDir[segment]) currentDir[segment] = {};
currentDir = currentDir[segment];
}
}
const generateHTML = (directory, path$1 = []) => Object.entries(directory).map(([fname, value = {}]) => {
const subpath = [...path$1, fname];
const key = subpath.join("/");
const encodedUrl = encodeURIComponent(key);
const linkClass = url === `/${encodedUrl}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200";
return Object.keys(value).length === 0 ? `
<li class="flex flex-nowrap">
<a href="/_vfs/${encodedUrl}" class="w-full text-sm px-2 py-1 border-b border-gray-10 ${linkClass}">
${fname}
</a>
</li>
` : `
<li>
<details ${url.startsWith(`/${encodedUrl}`) ? "open" : ""}>
<summary class="w-full text-sm px-2 py-1 border-b border-gray-10 hover:bg-gray-800 text-gray-200">
${fname}
</summary>
<ul class="ml-4">
${generateHTML(value, subpath)}
</ul>
</details>
</li>
`;
}).join("");
const rootDirectory = directories[nitro.options.rootDir];
delete directories[nitro.options.rootDir];
const files = `
<div class="h-full overflow-auto border-r border-gray:10">
<p class="text-white text-bold text-center py-1 opacity-50">Virtual Files</p>
<ul class="flex flex-col">${generateHTML(rootDirectory, [nitro.options.rootDir]) + generateHTML(directories)}</ul>
</div>
`;
const file = id ? editorTemplate({
readOnly: true,
language: id.endsWith("html") ? "html" : "javascript",
theme: "vs-dark",
value: content,
wordWrap: "wordWrapColumn",
wordWrapColumn: 80
}) : `
<div class="w-full h-full flex opacity-50">
<h1 class="text-white m-auto">Select a virtual file to inspect</h1>
</div>
`;
event.res.headers.set("Content-Type", "text/html; charset=utf-8");
return `
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" />
<link rel="stylesheet" data-name="vs/editor/editor.main" href="${vsUrl}/editor/editor.main.min.css">
<script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"><\/script>
<style>
html {
background: #1E1E1E;
color: white;
}
[un-cloak] {
display: none;
}
</style>
</head>
<body class="bg-[#1E1E1E]">
<div un-cloak class="h-screen grid grid-cols-[300px_1fr]">
${files}
${file}
</div>
</body>
</html>`;
});
}
const monacoUrl = `https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.30.0/min`;
const vsUrl = `${monacoUrl}/vs`;
const editorTemplate = (options) => `
<div id="editor" class="min-h-screen w-full h-full"></div>
<script src="${vsUrl}/loader.min.js"><\/script>
<script>
require.config({ paths: { vs: '${vsUrl}' } })
const proxy = URL.createObjectURL(new Blob([\`
self.MonacoEnvironment = { baseUrl: '${monacoUrl}' }
importScripts('${vsUrl}/base/worker/workerMain.min.js')
\`], { type: 'text/javascript' }))
window.MonacoEnvironment = { getWorkerUrl: () => proxy }
setTimeout(() => {
require(['vs/editor/editor.main'], function () {
monaco.editor.create(document.getElementById('editor'), ${JSON.stringify(options)})
})
}, 0);
<\/script>
`;
//#endregion
//#region src/runtime/internal/error/utils.ts
function defineNitroErrorHandler(handler) {
return handler;
}
//#endregion
//#region src/runtime/internal/error/dev.ts
var dev_default = defineNitroErrorHandler(async function defaultNitroErrorHandler(error, event) {
const res = await defaultHandler(error, event);
return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res);
});
async function defaultHandler(error, event, opts) {
const isSensitive = error.unhandled;
const status = error.status || 500;
const url = getRequestURL(event, {
xForwardedHost: true,
xForwardedProto: true
});
if (status === 404) {
const baseURL = import.meta.baseURL || "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) return {
status: 302,
statusText: "Found",
headers: { location: `${baseURL}${url.pathname.slice(1)}${url.search}` },
body: `Redirecting...`
};
}
await loadStackTrace(error).catch(consola$1.error);
const youch = new Youch();
if (isSensitive && !opts?.silent) {
const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), ".");
consola$1.error(`[request error] ${tags} [${event.req.method}] ${url}\n\n`, ansiError);
}
const useJSON = opts?.json || !event.req.headers.get("accept")?.includes("text/html");
const headers = {
"content-type": useJSON ? "application/json" : "text/html",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"referrer-policy": "no-referrer",
"content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';"
};
if (status === 404 || !event.res.headers.has("cache-control")) headers["cache-control"] = "no-cache";
const body = useJSON ? {
error: true,
url,
status,
statusText: error.statusText,
message: error.message,
data: error.data,
stack: error.stack?.split("\n").map((line) => line.trim())
} : await youch.toHTML(error, { request: {
url: url.href,
method: event.req.method,
headers: Object.fromEntries(event.req.headers.entries())
} });
return {
status,
statusText: error.statusText,
headers,
body
};
}
async function loadStackTrace(error) {
if (!(error instanceof Error)) return;
const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error);
const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n");
Object.defineProperty(error, "stack", { value: stack });
if (error.cause) await loadStackTrace(error.cause).catch(consola$1.error);
}
async function sourceLoader(frame) {
if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") return;
if (frame.type === "app") {
const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {});
if (rawSourceMap) {
const originalPosition = (await new SourceMapConsumer(rawSourceMap)).originalPositionFor({
line: frame.lineNumber,
column: frame.columnNumber
});
if (originalPosition.source && originalPosition.line) {
frame.fileName = resolve(dirname(frame.fileName), originalPosition.source);
frame.lineNumber = originalPosition.line;
frame.columnNumber = originalPosition.column || 0;
}
}
}
const contents = await readFile(frame.fileName, "utf8").catch(() => {});
return contents ? { contents } : void 0;
}
function fmtFrame(frame) {
if (frame.type === "native") return frame.raw;
const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`;
return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`;
}
//#endregion
//#region src/dev/app.ts
var NitroDevApp = class {
nitro;
fetch;
constructor(nitro, catchAllHandler) {
this.nitro = nitro;
const app = this.#createApp(catchAllHandler);
this.fetch = app.fetch.bind(app);
}
#createApp(catchAllHandler) {
const app = new H3({
debug: true,
onError: async (error, event) => {
const errorHandler = this.nitro.options.devErrorHandler || dev_default;
await loadStackTrace(error).catch(() => {});
return errorHandler(error, event, { defaultHandler });
}
});
for (const h of this.nitro.options.devHandlers) {
const handler = toEventHandler(h.handler);
if (!handler) {
this.nitro.logger.warn("Invalid dev handler:", h);
continue;
}
if (h.middleware || !h.route) if (h.route) app.use(h.route, handler, { method: h.method });
else app.use(handler, { method: h.method });
else app.on(h.method || "", h.route, handler, { meta: h.meta });
}
app.get("/_vfs/**", createVFSHandler(this.nitro));
for (const asset of this.nitro.options.publicAssets) {
const assetBase = joinURL(this.nitro.options.baseURL, asset.baseURL || "/");
app.use(joinURL(assetBase, "**"), (event) => serveStaticDir(event, {
dir: asset.dir,
base: assetBase,
fallthrough: asset.fallthrough
}));
}
const routes = Object.keys(this.nitro.options.devProxy).sort().reverse();
for (const route of routes) {
let opts = this.nitro.options.devProxy[route];
if (typeof opts === "string") opts = { target: opts };
const proxy = createHTTPProxy(opts);
app.all(route, proxy.handleEvent);
}
if (catchAllHandler) app.all("/**", catchAllHandler);
return app;
}
};
function serveStaticDir(event, opts) {
const dir = resolve$1(opts.dir) + "/";
const r = (id) => {
if (!id.startsWith(opts.base) || !extname$1(id)) return;
const resolved = join$1(dir, id.slice(opts.base.length));
if (resolved.startsWith(dir)) return resolved;
};
return serveStatic(event, {
fallthrough: opts.fallthrough,
getMeta: async (id) => {
const path$1 = r(id);
if (!path$1) return;
const s = await stat(path$1).catch(() => null);
if (!s?.isFile()) return;
const ext = extname$1(path$1);
return {
size: s.size,
mtime: s.mtime,
type: src_default.getType(ext) || "application/octet-stream"
};
},
getContents(id) {
const path$1 = r(id);
if (!path$1) return;
const stream = createReadStream(path$1);
const acceptEncoding = event.req.headers.get("accept-encoding") || "";
if (acceptEncoding.includes("br")) {
event.res.headers.set("Content-Encoding", "br");
event.res.headers.delete("Content-Length");
event.res.headers.set("Vary", "Accept-Encoding");
return stream.pipe(createBrotliCompress());
} else if (acceptEncoding.includes("gzip")) {
event.res.headers.set("Content-Encoding", "gzip");
event.res.headers.delete("Content-Length");
event.res.headers.set("Vary", "Accept-Encoding");
return stream.pipe(createGzip());
}
return stream;
}
});
}
//#endregion
//#region src/dev/server.ts
function createDevServer(nitro) {
return new NitroDevServer(nitro);
}
var NitroDevServer = class NitroDevServer extends NitroDevApp {
#entry;
#workerData = {};
#listeners = [];
#watcher;
#workers = [];
#workerIdCtr = 0;
#workerError;
#building = true;
#buildError;
#messageListeners = /* @__PURE__ */ new Set();
constructor(nitro) {
super(nitro, async (event) => {
const worker = await this.#getWorker();
if (!worker) return this.#generateError();
return worker.fetch(event.req);
});
for (const key of Object.getOwnPropertyNames(NitroDevServer.prototype)) {
const value = this[key];
if (typeof value === "function" && key !== "constructor") this[key] = value.bind(this);
}
nitro.fetch = this.fetch.bind(this);
this.#entry = resolve$1(nitro.options.output.dir, nitro.options.output.serverDir, "index.mjs");
nitro.hooks.hook("close", () => this.close());
nitro.hooks.hook("dev:start", () => {
this.#building = true;
this.#buildError = void 0;
});
nitro.hooks.hook("dev:reload", (payload) => {
this.#buildError = void 0;
this.#building = false;
if (payload?.entry) this.#entry = payload.entry;
if (payload?.workerData) this.#workerData = payload.workerData;
this.reload();
});
nitro.hooks.hook("dev:error", (cause) => {
this.#buildError = cause;
this.#building = false;
for (const worker of this.#workers) worker.close();
});
if (nitro.options.devServer.watch.length > 0) {
const debouncedReload = debounce(() => this.reload());
this.#watcher = watch$1(nitro.options.devServer.watch, nitro.options.watchOptions);
this.#watcher.on("add", debouncedReload).on("change", debouncedReload);
}
}
async upgrade(req, socket, head) {
const worker = await this.#getWorker();
if (!worker) throw new HTTPError({
status: 503,
statusText: "No worker available."
});
return worker.upgrade(req, socket, head);
}
listen(opts) {
const server = serve({
...opts,
fetch: this.fetch,
gracefulShutdown: false
});
this.#listeners.push(server);
if (server.node?.server) server.node.server.on("upgrade", (req, sock, head) => this.upgrade(req, sock, head));
return server;
}
async close() {
await Promise.all([
Promise.all(this.#listeners.map((l) => l.close())).then(() => {
this.#listeners = [];
}),
Promise.all(this.#workers.map((w) => w.close())).then(() => {
this.#workers = [];
}),
Promise.resolve(this.#watcher?.close()).then(() => {
this.#watcher = void 0;
})
].map((p) => p.catch((error) => {
consola$1.error(error);
})));
}
reload() {
for (const worker$1 of this.#workers) worker$1.close();
const worker = new NodeDevWorker({
name: `Nitro_${this.#workerIdCtr++}`,
entry: this.#entry,
data: {
...this.#workerData,
globals: {
__NITRO_RUNTIME_CONFIG__: this.nitro.options.runtimeConfig,
...this.#workerData.globals
}
},
hooks: {
onClose: (worker$1, cause) => {
this.#workerError = cause;
const index = this.#workers.indexOf(worker$1);
if (index !== -1) this.#workers.splice(index, 1);
},
onReady: async (_worker, addr) => {
writeDevBuildInfo(this.nitro, addr).catch(() => {});
}
}
});
if (!worker.closed) {
for (const listener of this.#messageListeners) worker.onMessage(listener);
this.#workers.unshift(worker);
}
}
sendMessage(message) {
for (const worker of this.#workers) if (!worker.closed) worker.sendMessage(message);
}
onMessage(listener) {
this.#messageListeners.add(listener);
for (const worker of this.#workers) worker.onMessage(listener);
}
offMessage(listener) {
this.#messageListeners.delete(listener);
for (const worker of this.#workers) worker.offMessage(listener);
}
async #getWorker() {
let retry = 0;
const maxRetries = a || T ? 100 : 10;
while (this.#building || ++retry < maxRetries) {
if ((this.#workers.length === 0 || this.#buildError) && !this.#building) return;
const activeWorker = this.#workers.find((w) => w.ready);
if (activeWorker) return activeWorker;
await new Promise((resolve$2) => setTimeout(resolve$2, 600));
}
}
#generateError() {
const error = this.#buildError || this.#workerError;
if (error) {
try {
error.unhandled = false;
let id = error.id || error.path;
if (id) {
const cause = error.errors?.[0];
const loc = error.location || error.loc || cause?.location || cause?.loc;
if (loc) id += `:${loc.line}:${loc.column}`;
error.stack = (error.stack || "").replace(/(^\s*at\s+.+)/m, ` at ${id}\n$1`);
}
} catch {}
return new HTTPError(error);
}
return new Response(JSON.stringify({
error: "Dev server is unavailable.",
hint: "Please reload the page and check the console for errors if the issue persists."
}, null, 2), {
status: 503,
statusText: "Dev server is unavailable",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store",
Refresh: "3"
}
});
}
};
//#endregion
export { NodeDevWorker as i, createDevServer as n, NitroDevApp as r, NitroDevServer as t };

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { join, relative, resolve, sep } from "node:path";
import { lstat, readdir, realpath, stat } from "node:fs/promises";
import { stat as stat$1, unwatchFile, watch, watchFile } from "fs";
import * as sysPath from "path";
import { type } from "os";
import { lstat as lstat$1, open, readdir as readdir$1, realpath as realpath$1, stat as stat$2 } from "fs/promises";
import { EventEmitter } from "events";
import { Readable } from "node:stream";
//#region node_modules/.pnpm/readdirp@4.1.2/node_modules/readdirp/esm/index.js
const EntryTypes = {
FILE_TYPE: "files",
DIR_TYPE: "directories",
FILE_DIR_TYPE: "files_directories",
EVERYTHING_TYPE: "all"
};
const defaultOptions = {
root: ".",
fileFilter: (_entryInfo) => true,
directoryFilter: (_entryInfo) => true,
type: EntryTypes.FILE_TYPE,
lstat: false,
depth: 2147483648,
alwaysStat: false,
highWaterMark: 4096
};
Object.freeze(defaultOptions);
const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
const NORMAL_FLOW_ERRORS = new Set([
"ENOENT",
"EPERM",
"EACCES",
"ELOOP",
RECURSIVE_ERROR_CODE
]);
const ALL_TYPES = [
EntryTypes.DIR_TYPE,
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE,
EntryTypes.FILE_TYPE
];
const DIR_TYPES = new Set([
EntryTypes.DIR_TYPE,
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE
]);
const FILE_TYPES = new Set([
EntryTypes.EVERYTHING_TYPE,
EntryTypes.FILE_DIR_TYPE,
EntryTypes.FILE_TYPE
]);
const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
const wantBigintFsStats = process.platform === "win32";
const emptyFn = (_entryInfo) => true;
const normalizeFilter = (filter) => {
if (filter === void 0) return emptyFn;
if (typeof filter === "function") return filter;
if (typeof filter === "string") {
const fl = filter.trim();
return (entry) => entry.basename === fl;
}
if (Array.isArray(filter)) {
const trItems = filter.map((item) => item.trim());
return (entry) => trItems.some((f) => entry.basename === f);
}
return emptyFn;
};
/** Readable readdir stream, emitting new files as they're being listed. */
var ReaddirpStream = class extends Readable {
constructor(options = {}) {
super({
objectMode: true,
autoDestroy: true,
highWaterMark: options.highWaterMark
});
const opts = {
...defaultOptions,
...options
};
const { root, type: type$1 } = opts;
this._fileFilter = normalizeFilter(opts.fileFilter);
this._directoryFilter = normalizeFilter(opts.directoryFilter);
const statMethod = opts.lstat ? lstat : stat;
if (wantBigintFsStats) this._stat = (path$2) => statMethod(path$2, { bigint: true });
else this._stat = statMethod;
this._maxDepth = opts.depth ?? defaultOptions.depth;
this._wantsDir = type$1 ? DIR_TYPES.has(type$1) : false;
this._wantsFile = type$1 ? FILE_TYPES.has(type$1) : false;
this._wantsEverything = type$1 === EntryTypes.EVERYTHING_TYPE;
this._root = resolve(root);
this._isDirent = !opts.alwaysStat;
this._statsProp = this._isDirent ? "dirent" : "stats";
this._rdOptions = {
encoding: "utf8",
withFileTypes: this._isDirent
};
this.parents = [this._exploreDir(root, 1)];
this.reading = false;
this.parent = void 0;
}
async _read(batch) {
if (this.reading) return;
this.reading = true;
try {
while (!this.destroyed && batch > 0) {
const par = this.parent;
const fil = par && par.files;
if (fil && fil.length > 0) {
const { path: path$2, depth } = par;
const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path$2));
const awaited = await Promise.all(slice);
for (const entry of awaited) {
if (!entry) continue;
if (this.destroyed) return;
const entryType = await this._getEntryType(entry);
if (entryType === "directory" && this._directoryFilter(entry)) {
if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
if (this._wantsDir) {
this.push(entry);
batch--;
}
} else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
if (this._wantsFile) {
this.push(entry);
batch--;
}
}
}
} else {
const parent = this.parents.pop();
if (!parent) {
this.push(null);
break;
}
this.parent = await parent;
if (this.destroyed) return;
}
}
} catch (error) {
this.destroy(error);
} finally {
this.reading = false;
}
}
async _exploreDir(path$2, depth) {
let files;
try {
files = await readdir(path$2, this._rdOptions);
} catch (error) {
this._onError(error);
}
return {
files,
depth,
path: path$2
};
}
async _formatEntry(dirent, path$2) {
let entry;
const basename$2 = this._isDirent ? dirent.name : dirent;
try {
const fullPath = resolve(join(path$2, basename$2));
entry = {
path: relative(this._root, fullPath),
fullPath,
basename: basename$2
};
entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
} catch (err) {
this._onError(err);
return;
}
return entry;
}
_onError(err) {
if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
else this.destroy(err);
}
async _getEntryType(entry) {
if (!entry && this._statsProp in entry) return "";
const stats = entry[this._statsProp];
if (stats.isFile()) return "file";
if (stats.isDirectory()) return "directory";
if (stats && stats.isSymbolicLink()) {
const full = entry.fullPath;
try {
const entryRealPath = await realpath(full);
const entryRealPathStats = await lstat(entryRealPath);
if (entryRealPathStats.isFile()) return "file";
if (entryRealPathStats.isDirectory()) {
const len = entryRealPath.length;
if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
recursiveError.code = RECURSIVE_ERROR_CODE;
return this._onError(recursiveError);
}
return "directory";
}
} catch (error) {
this._onError(error);
return "";
}
}
}
_includeAsFile(entry) {
const stats = entry && entry[this._statsProp];
return stats && this._wantsEverything && !stats.isDirectory();
}
};
/**
* Streaming version: Reads all files and directories in given root recursively.
* Consumes ~constant small amount of RAM.
* @param root Root directory
* @param options Options to specify root (start directory), filters and recursion depth
*/
function readdirp(root, options = {}) {
let type$1 = options.entryType || options.type;
if (type$1 === "both") type$1 = EntryTypes.FILE_DIR_TYPE;
if (type$1) options.type = type$1;
if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
else if (type$1 && !ALL_TYPES.includes(type$1)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
options.root = root;
return new ReaddirpStream(options);
}
//#endregion
//#region node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/handler.js
const STR_DATA = "data";
const STR_END = "end";
const STR_CLOSE = "close";
const EMPTY_FN = () => {};
const pl = process.platform;
const isWindows = pl === "win32";
const isMacos = pl === "darwin";
const isLinux = pl === "linux";
const isFreeBSD = pl === "freebsd";
const isIBMi = type() === "OS400";
const EVENTS = {
ALL: "all",
READY: "ready",
ADD: "add",
CHANGE: "change",
ADD_DIR: "addDir",
UNLINK: "unlink",
UNLINK_DIR: "unlinkDir",
RAW: "raw",
ERROR: "error"
};
const EV = EVENTS;
const THROTTLE_MODE_WATCH = "watch";
const statMethods = {
lstat: lstat$1,
stat: stat$2
};
const KEY_LISTENERS = "listeners";
const KEY_ERR = "errHandlers";
const KEY_RAW = "rawEmitters";
const HANDLER_KEYS = [
KEY_LISTENERS,
KEY_ERR,
KEY_RAW
];
const binaryExtensions = new Set([
"3dm",
"3ds",
"3g2",
"3gp",
"7z",
"a",
"aac",
"adp",
"afdesign",
"afphoto",
"afpub",
"ai",
"aif",
"aiff",
"alz",
"ape",
"apk",
"appimage",
"ar",
"arj",
"asf",
"au",
"avi",
"bak",
"baml",
"bh",
"bin",
"bk",
"bmp",
"btif",
"bz2",
"bzip2",
"cab",
"caf",
"cgm",
"class",
"cmx",
"cpio",
"cr2",
"cur",
"dat",
"dcm",
"deb",
"dex",
"djvu",
"dll",
"dmg",
"dng",
"doc",
"docm",
"docx",
"dot",
"dotm",
"dra",
"DS_Store",
"dsk",
"dts",
"dtshd",
"dvb",
"dwg",
"dxf",
"ecelp4800",
"ecelp7470",
"ecelp9600",
"egg",
"eol",
"eot",
"epub",
"exe",
"f4v",
"fbs",
"fh",
"fla",
"flac",
"flatpak",
"fli",
"flv",
"fpx",
"fst",
"fvt",
"g3",
"gh",
"gif",
"graffle",
"gz",
"gzip",
"h261",
"h263",
"h264",
"icns",
"ico",
"ief",
"img",
"ipa",
"iso",
"jar",
"jpeg",
"jpg",
"jpgv",
"jpm",
"jxr",
"key",
"ktx",
"lha",
"lib",
"lvp",
"lz",
"lzh",
"lzma",
"lzo",
"m3u",
"m4a",
"m4v",
"mar",
"mdi",
"mht",
"mid",
"midi",
"mj2",
"mka",
"mkv",
"mmr",
"mng",
"mobi",
"mov",
"movie",
"mp3",
"mp4",
"mp4a",
"mpeg",
"mpg",
"mpga",
"mxu",
"nef",
"npx",
"numbers",
"nupkg",
"o",
"odp",
"ods",
"odt",
"oga",
"ogg",
"ogv",
"otf",
"ott",
"pages",
"pbm",
"pcx",
"pdb",
"pdf",
"pea",
"pgm",
"pic",
"png",
"pnm",
"pot",
"potm",
"potx",
"ppa",
"ppam",
"ppm",
"pps",
"ppsm",
"ppsx",
"ppt",
"pptm",
"pptx",
"psd",
"pya",
"pyc",
"pyo",
"pyv",
"qt",
"rar",
"ras",
"raw",
"resources",
"rgb",
"rip",
"rlc",
"rmf",
"rmvb",
"rpm",
"rtf",
"rz",
"s3m",
"s7z",
"scpt",
"sgi",
"shar",
"snap",
"sil",
"sketch",
"slk",
"smv",
"snk",
"so",
"stl",
"suo",
"sub",
"swf",
"tar",
"tbz",
"tbz2",
"tga",
"tgz",
"thmx",
"tif",
"tiff",
"tlz",
"ttc",
"ttf",
"txz",
"udf",
"uvh",
"uvi",
"uvm",
"uvp",
"uvs",
"uvu",
"viv",
"vob",
"war",
"wav",
"wax",
"wbmp",
"wdp",
"weba",
"webm",
"webp",
"whl",
"wim",
"wm",
"wma",
"wmv",
"wmx",
"woff",
"woff2",
"wrm",
"wvx",
"xbm",
"xif",
"xla",
"xlam",
"xls",
"xlsb",
"xlsm",
"xlsx",
"xlt",
"xltm",
"xltx",
"xm",
"xmind",
"xpi",
"xpm",
"xwd",
"xz",
"z",
"zip",
"zipx"
]);
const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
const foreach = (val, fn) => {
if (val instanceof Set) val.forEach(fn);
else fn(val);
};
const addAndConvert = (main, prop, item) => {
let container = main[prop];
if (!(container instanceof Set)) main[prop] = container = new Set([container]);
container.add(item);
};
const clearItem = (cont) => (key) => {
const set = cont[key];
if (set instanceof Set) set.clear();
else delete cont[key];
};
const delFromSet = (main, prop, item) => {
const container = main[prop];
if (container instanceof Set) container.delete(item);
else if (container === item) delete main[prop];
};
const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
const FsWatchInstances = /* @__PURE__ */ new Map();
/**
* Instantiates the fs_watch interface
* @param path to be watched
* @param options to be passed to fs_watch
* @param listener main event handler
* @param errHandler emits info about errors
* @param emitRaw emits raw event data
* @returns {NativeFsWatcher}
*/
function createFsWatchInstance(path$2, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path$2);
emitRaw(rawEvent, evPath, { watchedPath: path$2 });
if (evPath && path$2 !== evPath) fsWatchBroadcast(sysPath.resolve(path$2, evPath), KEY_LISTENERS, sysPath.join(path$2, evPath));
};
try {
return watch(path$2, { persistent: options.persistent }, handleEvent);
} catch (error) {
errHandler(error);
return;
}
}
/**
* Helper for passing fs_watch event data to a collection of listeners
* @param fullPath absolute path bound to fs_watch instance
*/
const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[listenerType], (listener) => {
listener(val1, val2, val3);
});
};
/**
* Instantiates the fs_watch interface or binds listeners
* to an existing one covering the same file system entry
* @param path
* @param fullPath absolute path
* @param options to be passed to fs_watch
* @param handlers container for event listener functions
*/
const setFsWatchListener = (path$2, fullPath, options, handlers) => {
const { listener, errHandler, rawEmitter } = handlers;
let cont = FsWatchInstances.get(fullPath);
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(path$2, options, listener, errHandler, rawEmitter);
if (!watcher) return;
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(path$2, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
if (!watcher) return;
watcher.on(EV.ERROR, async (error) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
if (cont) cont.watcherUnusable = true;
if (isWindows && error.code === "EPERM") try {
await (await open(path$2, "r")).close();
broadcastErr(error);
} catch (err) {}
else broadcastErr(error);
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
cont.watcher.close();
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = void 0;
Object.freeze(cont);
}
};
};
const FsWatchFileInstances = /* @__PURE__ */ new Map();
/**
* Instantiates the fs_watchFile interface or binds listeners
* to an existing one covering the same file system entry
* @param path to be watched
* @param fullPath absolute path
* @param options options to be passed to fs_watchFile
* @param handlers container for event listener functions
* @returns closer
*/
const setFsWatchFileListener = (path$2, fullPath, options, handlers) => {
const { listener, rawEmitter } = handlers;
let cont = FsWatchFileInstances.get(fullPath);
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
unwatchFile(fullPath);
cont = void 0;
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: watchFile(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter$1) => {
rawEmitter$1(EV.CHANGE, fullPath, {
curr,
prev
});
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener$1) => listener$1(path$2, curr));
})
};
FsWatchFileInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
unwatchFile(fullPath);
cont.options = cont.watcher = void 0;
Object.freeze(cont);
}
};
};
/**
* @mixin
*/
var NodeFsHandler = class {
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error) => fsW._handleError(error);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param path to file or dir
* @param listener on fs change
* @returns closer for the watcher instance
*/
_watchWithNodeFs(path$2, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path$2);
const basename$2 = sysPath.basename(path$2);
this.fsw._getWatchedDir(directory).add(basename$2);
const absolutePath = sysPath.resolve(path$2);
const options = { persistent: opts.persistent };
if (!listener) listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename$2) ? opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path$2, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else closer = setFsWatchListener(path$2, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @returns closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) return;
const dirname$2 = sysPath.dirname(file);
const basename$2 = sysPath.basename(file);
const parent = this.fsw._getWatchedDir(dirname$2);
let prevStats = stats;
if (parent.has(basename$2)) return;
const listener = async (path$2, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) try {
const newStats$1 = await stat$2(file);
if (this.fsw.closed) return;
const at = newStats$1.atimeMs;
const mt = newStats$1.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats$1);
if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats$1.ino) {
this.fsw._closeFile(path$2);
prevStats = newStats$1;
const closer$1 = this._watchWithNodeFs(file, listener);
if (closer$1) this.fsw._addPathCloser(path$2, closer$1);
} else prevStats = newStats$1;
} catch (error) {
this.fsw._remove(dirname$2, basename$2);
}
else if (parent.has(basename$2)) {
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
prevStats = newStats;
}
};
const closer = this._watchWithNodeFs(file, listener);
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV.ADD, file, 0)) return;
this.fsw._emit(EV.ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param entry returned by readdirp
* @param directory path of dir being read
* @param path of this item
* @param item basename of this item
* @returns true if no more processing is needed for this entry.
*/
async _handleSymlink(entry, directory, path$2, item) {
if (this.fsw.closed) return;
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await realpath$1(path$2);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.CHANGE, path$2, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.ADD, path$2, entry.stats);
}
this.fsw._emitReady();
return true;
}
if (this.fsw._symlinkPaths.has(full)) return true;
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
directory = sysPath.join(directory, "");
throttler = this.fsw._throttle("readdir", directory, 1e3);
if (!throttler) return;
const previous = this.fsw._getWatchedDir(wh.path);
const current = /* @__PURE__ */ new Set();
let stream = this.fsw._readdirp(directory, {
fileFilter: (entry) => wh.filterPath(entry),
directoryFilter: (entry) => wh.filterDir(entry)
});
if (!stream) return;
stream.on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream = void 0;
return;
}
const item = entry.path;
let path$2 = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path$2, item)) return;
if (this.fsw.closed) {
stream = void 0;
return;
}
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
path$2 = sysPath.join(dir, sysPath.relative(dir, path$2));
this._addToNodeFs(path$2, initialAdd, wh, depth + 1);
}
}).on(EV.ERROR, this._boundHandleError);
return new Promise((resolve$2, reject) => {
if (!stream) return reject();
stream.once(STR_END, () => {
if (this.fsw.closed) {
stream = void 0;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve$2(void 0);
previous.getChildren().filter((item) => {
return item !== directory && !current.has(item);
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream = void 0;
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
});
});
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param dir fs path
* @param stats
* @param initialAdd
* @param depth relative to user-supplied path
* @param target child path targeted for watch
* @param wh Common watch helpers for this path
* @param realpath
* @returns closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath$2) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
parentDir.add(sysPath.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath$2)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats$1) => {
if (stats$1 && stats$1.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param path to file or ir
* @param initialAdd was the file added at watch instantiation?
* @param priorWh depth relative to user-supplied path
* @param depth Child path actually targeted for watch
* @param target Child path actually targeted for watch
*/
async _addToNodeFs(path$2, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path$2) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path$2);
if (priorWh) {
wh.filterPath = (entry) => priorWh.filterPath(entry);
wh.filterDir = (entry) => priorWh.filterDir(entry);
}
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks;
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path$2);
const targetPath = follow ? await realpath$1(path$2) : path$2;
if (this.fsw.closed) return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
if (this.fsw.closed) return;
if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await realpath$1(path$2) : path$2;
if (this.fsw.closed) return;
const parent = sysPath.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV.ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path$2, wh, targetPath);
if (this.fsw.closed) return;
if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath.resolve(path$2), targetPath);
} else closer = this._handleFile(wh.watchPath, stats, initialAdd);
ready();
if (closer) this.fsw._addPathCloser(path$2, closer);
return false;
} catch (error) {
if (this.fsw._handleError(error)) {
ready();
return path$2;
}
}
}
};
//#endregion
//#region node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
const SLASH = "/";
const SLASH_SLASH = "//";
const ONE_DOT = ".";
const TWO_DOTS = "..";
const STRING_TYPE = "string";
const BACK_SLASH_RE = /\\/g;
const DOUBLE_SLASH_RE = /\/\//;
const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
const REPLACER_RE = /^\.[/\\]/;
function arrify(item) {
return Array.isArray(item) ? item : [item];
}
const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
function createPattern(matcher) {
if (typeof matcher === "function") return matcher;
if (typeof matcher === "string") return (string) => matcher === string;
if (matcher instanceof RegExp) return (string) => matcher.test(string);
if (typeof matcher === "object" && matcher !== null) return (string) => {
if (matcher.path === string) return true;
if (matcher.recursive) {
const relative$2 = sysPath.relative(matcher.path, string);
if (!relative$2) return false;
return !relative$2.startsWith("..") && !sysPath.isAbsolute(relative$2);
}
return false;
};
return () => false;
}
function normalizePath(path$2) {
if (typeof path$2 !== "string") throw new Error("string expected");
path$2 = sysPath.normalize(path$2);
path$2 = path$2.replace(/\\/g, "/");
let prepend = false;
if (path$2.startsWith("//")) prepend = true;
const DOUBLE_SLASH_RE$1 = /\/\//;
while (path$2.match(DOUBLE_SLASH_RE$1)) path$2 = path$2.replace(DOUBLE_SLASH_RE$1, "/");
if (prepend) path$2 = "/" + path$2;
return path$2;
}
function matchPatterns(patterns, testString, stats) {
const path$2 = normalizePath(testString);
for (let index = 0; index < patterns.length; index++) {
const pattern = patterns[index];
if (pattern(path$2, stats)) return true;
}
return false;
}
function anymatch(matchers, testString) {
if (matchers == null) throw new TypeError("anymatch: specify first argument");
const patterns = arrify(matchers).map((matcher) => createPattern(matcher));
if (testString == null) return (testString$1, stats) => {
return matchPatterns(patterns, testString$1, stats);
};
return matchPatterns(patterns, testString);
}
const unifyPaths = (paths_) => {
const paths = arrify(paths_).flat();
if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
return paths.map(normalizePathToUnix);
};
const toUnix = (string) => {
let str = string.replace(BACK_SLASH_RE, SLASH);
let prepend = false;
if (str.startsWith(SLASH_SLASH)) prepend = true;
while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
if (prepend) str = SLASH + str;
return str;
};
const normalizePathToUnix = (path$2) => toUnix(sysPath.normalize(toUnix(path$2)));
const normalizeIgnored = (cwd = "") => (path$2) => {
if (typeof path$2 === "string") return normalizePathToUnix(sysPath.isAbsolute(path$2) ? path$2 : sysPath.join(cwd, path$2));
else return path$2;
};
const getAbsolutePath = (path$2, cwd) => {
if (sysPath.isAbsolute(path$2)) return path$2;
return sysPath.join(cwd, path$2);
};
const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
/**
* Directory entry.
*/
var DirEntry = class {
constructor(dir, removeWatcher) {
this.path = dir;
this._removeWatcher = removeWatcher;
this.items = /* @__PURE__ */ new Set();
}
add(item) {
const { items } = this;
if (!items) return;
if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
}
async remove(item) {
const { items } = this;
if (!items) return;
items.delete(item);
if (items.size > 0) return;
const dir = this.path;
try {
await readdir$1(dir);
} catch (err) {
if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
}
}
has(item) {
const { items } = this;
if (!items) return;
return items.has(item);
}
getChildren() {
const { items } = this;
if (!items) return [];
return [...items.values()];
}
dispose() {
this.items.clear();
this.path = "";
this._removeWatcher = EMPTY_FN;
this.items = EMPTY_SET;
Object.freeze(this);
}
};
const STAT_METHOD_F = "stat";
const STAT_METHOD_L = "lstat";
var WatchHelper = class {
constructor(path$2, follow, fsw) {
this.fsw = fsw;
const watchPath = path$2;
this.path = path$2 = path$2.replace(REPLACER_RE, "");
this.watchPath = watchPath;
this.fullWatchPath = sysPath.resolve(watchPath);
this.dirParts = [];
this.dirParts.forEach((parts) => {
if (parts.length > 1) parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
entryPath(entry) {
return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));
}
filterPath(entry) {
const { stats } = entry;
if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
const resolvedPath = this.entryPath(entry);
return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
}
filterDir(entry) {
return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
}
};
/**
* Watches files & directories for changes. Emitted events:
* `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
*
* new FSWatcher()
* .add(directories)
* .on('add', path => log('File', path, 'was added'))
*/
var FSWatcher = class extends EventEmitter {
constructor(_opts = {}) {
super();
this.closed = false;
this._closers = /* @__PURE__ */ new Map();
this._ignoredPaths = /* @__PURE__ */ new Set();
this._throttled = /* @__PURE__ */ new Map();
this._streams = /* @__PURE__ */ new Set();
this._symlinkPaths = /* @__PURE__ */ new Map();
this._watched = /* @__PURE__ */ new Map();
this._pendingWrites = /* @__PURE__ */ new Map();
this._pendingUnlinks = /* @__PURE__ */ new Map();
this._readyCount = 0;
this._readyEmitted = false;
const awf = _opts.awaitWriteFinish;
const DEF_AWF = {
stabilityThreshold: 2e3,
pollInterval: 100
};
const opts = {
persistent: true,
ignoreInitial: false,
ignorePermissionErrors: false,
interval: 100,
binaryInterval: 300,
followSymlinks: true,
usePolling: false,
atomic: true,
..._opts,
ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? {
...DEF_AWF,
...awf
} : false
};
if (isIBMi) opts.usePolling = true;
if (opts.atomic === void 0) opts.atomic = !opts.usePolling;
const envPoll = process.env.CHOKIDAR_USEPOLLING;
if (envPoll !== void 0) {
const envLower = envPoll.toLowerCase();
if (envLower === "false" || envLower === "0") opts.usePolling = false;
else if (envLower === "true" || envLower === "1") opts.usePolling = true;
else opts.usePolling = !!envLower;
}
const envInterval = process.env.CHOKIDAR_INTERVAL;
if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
process.nextTick(() => this.emit(EVENTS.READY));
}
};
this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
this._boundRemove = this._remove.bind(this);
this.options = opts;
this._nodeFsHandler = new NodeFsHandler(this);
Object.freeze(opts);
}
_addIgnoredPath(matcher) {
if (isMatcherObject(matcher)) {
for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
}
this._ignoredPaths.add(matcher);
}
_removeIgnoredPath(matcher) {
this._ignoredPaths.delete(matcher);
if (typeof matcher === "string") {
for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
}
}
/**
* Adds paths to be watched on an existing FSWatcher instance.
* @param paths_ file or file list. Other arguments are unused
*/
add(paths_, _origAdd, _internal) {
const { cwd } = this.options;
this.closed = false;
this._closePromise = void 0;
let paths = unifyPaths(paths_);
if (cwd) paths = paths.map((path$2) => {
return getAbsolutePath(path$2, cwd);
});
paths.forEach((path$2) => {
this._removeIgnoredPath(path$2);
});
this._userIgnored = void 0;
if (!this._readyCount) this._readyCount = 0;
this._readyCount += paths.length;
Promise.all(paths.map(async (path$2) => {
const res = await this._nodeFsHandler._addToNodeFs(path$2, !_internal, void 0, 0, _origAdd);
if (res) this._emitReady();
return res;
})).then((results) => {
if (this.closed) return;
results.forEach((item) => {
if (item) this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
});
});
return this;
}
/**
* Close watchers or start ignoring events from specified paths.
*/
unwatch(paths_) {
if (this.closed) return this;
const paths = unifyPaths(paths_);
const { cwd } = this.options;
paths.forEach((path$2) => {
if (!sysPath.isAbsolute(path$2) && !this._closers.has(path$2)) {
if (cwd) path$2 = sysPath.join(cwd, path$2);
path$2 = sysPath.resolve(path$2);
}
this._closePath(path$2);
this._addIgnoredPath(path$2);
if (this._watched.has(path$2)) this._addIgnoredPath({
path: path$2,
recursive: true
});
this._userIgnored = void 0;
});
return this;
}
/**
* Close watchers and remove all listeners from watched paths.
*/
close() {
if (this._closePromise) return this._closePromise;
this.closed = true;
this.removeAllListeners();
const closers = [];
this._closers.forEach((closerList) => closerList.forEach((closer) => {
const promise = closer();
if (promise instanceof Promise) closers.push(promise);
}));
this._streams.forEach((stream) => stream.destroy());
this._userIgnored = void 0;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach((dirent) => dirent.dispose());
this._closers.clear();
this._watched.clear();
this._streams.clear();
this._symlinkPaths.clear();
this._throttled.clear();
this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
return this._closePromise;
}
/**
* Expose list of watched paths
* @returns for chaining
*/
getWatched() {
const watchList = {};
this._watched.forEach((entry, dir) => {
const index = (this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir) || ONE_DOT;
watchList[index] = entry.getChildren().sort();
});
return watchList;
}
emitWithAll(event, args) {
this.emit(event, ...args);
if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
}
/**
* Normalize and emit events.
* Calling _emit DOES NOT MEAN emit() would be called!
* @param event Type of event
* @param path File or directory path
* @param stats arguments to be passed with event
* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
async _emit(event, path$2, stats) {
if (this.closed) return;
const opts = this.options;
if (isWindows) path$2 = sysPath.normalize(path$2);
if (opts.cwd) path$2 = sysPath.relative(opts.cwd, path$2);
const args = [path$2];
if (stats != null) args.push(stats);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path$2))) {
pw.lastChange = /* @__PURE__ */ new Date();
return this;
}
if (opts.atomic) {
if (event === EVENTS.UNLINK) {
this._pendingUnlinks.set(path$2, [event, ...args]);
setTimeout(() => {
this._pendingUnlinks.forEach((entry, path$3) => {
this.emit(...entry);
this.emit(EVENTS.ALL, ...entry);
this._pendingUnlinks.delete(path$3);
});
}, typeof opts.atomic === "number" ? opts.atomic : 100);
return this;
}
if (event === EVENTS.ADD && this._pendingUnlinks.has(path$2)) {
event = EVENTS.CHANGE;
this._pendingUnlinks.delete(path$2);
}
}
if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
const awfEmit = (err, stats$1) => {
if (err) {
event = EVENTS.ERROR;
args[0] = err;
this.emitWithAll(event, args);
} else if (stats$1) {
if (args.length > 1) args[1] = stats$1;
else args.push(stats$1);
this.emitWithAll(event, args);
}
};
this._awaitWriteFinish(path$2, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EVENTS.CHANGE) {
if (!this._throttle(EVENTS.CHANGE, path$2, 50)) return this;
}
if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
const fullPath = opts.cwd ? sysPath.join(opts.cwd, path$2) : path$2;
let stats$1;
try {
stats$1 = await stat$2(fullPath);
} catch (err) {}
if (!stats$1 || this.closed) return;
args.push(stats$1);
}
this.emitWithAll(event, args);
return this;
}
/**
* Common handler for errors
* @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
_handleError(error) {
const code = error && error.code;
if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error);
return error || this.closed;
}
/**
* Helper utility for throttling
* @param actionType type being throttled
* @param path being acted upon
* @param timeout duration of time to suppress duplicate actions
* @returns tracking object or false if action should be suppressed
*/
_throttle(actionType, path$2, timeout) {
if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
const action = this._throttled.get(actionType);
if (!action) throw new Error("invalid throttle");
const actionPath = action.get(path$2);
if (actionPath) {
actionPath.count++;
return false;
}
let timeoutObject;
const clear = () => {
const item = action.get(path$2);
const count = item ? item.count : 0;
action.delete(path$2);
clearTimeout(timeoutObject);
if (item) clearTimeout(item.timeoutObject);
return count;
};
timeoutObject = setTimeout(clear, timeout);
const thr = {
timeoutObject,
clear,
count: 0
};
action.set(path$2, thr);
return thr;
}
_incrReadyCount() {
return this._readyCount++;
}
/**
* Awaits write operation to finish.
* Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
* @param path being acted upon
* @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
* @param event
* @param awfEmit Callback to be called when ready for event to be emitted.
*/
_awaitWriteFinish(path$2, threshold, event, awfEmit) {
const awf = this.options.awaitWriteFinish;
if (typeof awf !== "object") return;
const pollInterval = awf.pollInterval;
let timeoutHandler;
let fullPath = path$2;
if (this.options.cwd && !sysPath.isAbsolute(path$2)) fullPath = sysPath.join(this.options.cwd, path$2);
const now = /* @__PURE__ */ new Date();
const writes = this._pendingWrites;
function awaitWriteFinishFn(prevStat) {
stat$1(fullPath, (err, curStat) => {
if (err || !writes.has(path$2)) {
if (err && err.code !== "ENOENT") awfEmit(err);
return;
}
const now$1 = Number(/* @__PURE__ */ new Date());
if (prevStat && curStat.size !== prevStat.size) writes.get(path$2).lastChange = now$1;
if (now$1 - writes.get(path$2).lastChange >= threshold) {
writes.delete(path$2);
awfEmit(void 0, curStat);
} else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
});
}
if (!writes.has(path$2)) {
writes.set(path$2, {
lastChange: now,
cancelWait: () => {
writes.delete(path$2);
clearTimeout(timeoutHandler);
return event;
}
});
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
}
}
/**
* Determines whether user has asked to ignore this path.
*/
_isIgnored(path$2, stats) {
if (this.options.atomic && DOT_RE.test(path$2)) return true;
if (!this._userIgnored) {
const { cwd } = this.options;
const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd));
this._userIgnored = anymatch([...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored], void 0);
}
return this._userIgnored(path$2, stats);
}
_isntIgnored(path$2, stat$3) {
return !this._isIgnored(path$2, stat$3);
}
/**
* Provides a set of common helpers and properties relating to symlink handling.
* @param path file or directory pattern being watched
*/
_getWatchHelpers(path$2) {
return new WatchHelper(path$2, this.options.followSymlinks, this);
}
/**
* Provides directory tracking objects
* @param directory path of the directory
*/
_getWatchedDir(directory) {
const dir = sysPath.resolve(directory);
if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
return this._watched.get(dir);
}
/**
* Check for read permissions: https://stackoverflow.com/a/11781404/1358405
*/
_hasReadPermissions(stats) {
if (this.options.ignorePermissionErrors) return true;
return Boolean(Number(stats.mode) & 256);
}
/**
* Handles emitting unlink events for
* files and directories, and via recursion, for
* files and directories within directories that are unlinked
* @param directory within which the following item is located
* @param item base path of item/directory
*/
_remove(directory, item, isDirectory) {
const path$2 = sysPath.join(directory, item);
const fullPath = sysPath.resolve(path$2);
isDirectory = isDirectory != null ? isDirectory : this._watched.has(path$2) || this._watched.has(fullPath);
if (!this._throttle("remove", path$2, 100)) return;
if (!isDirectory && this._watched.size === 1) this.add(directory, item, true);
this._getWatchedDir(path$2).getChildren().forEach((nested) => this._remove(path$2, nested));
const parent = this._getWatchedDir(directory);
const wasTracked = parent.has(item);
parent.remove(item);
if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
let relPath = path$2;
if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path$2);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return;
}
this._watched.delete(path$2);
this._watched.delete(fullPath);
const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
if (wasTracked && !this._isIgnored(path$2)) this._emit(eventName, path$2);
this._closePath(path$2);
}
/**
* Closes all watchers for a path
*/
_closePath(path$2) {
this._closeFile(path$2);
const dir = sysPath.dirname(path$2);
this._getWatchedDir(dir).remove(sysPath.basename(path$2));
}
/**
* Closes only file-specific watchers
*/
_closeFile(path$2) {
const closers = this._closers.get(path$2);
if (!closers) return;
closers.forEach((closer) => closer());
this._closers.delete(path$2);
}
_addPathCloser(path$2, closer) {
if (!closer) return;
let list = this._closers.get(path$2);
if (!list) {
list = [];
this._closers.set(path$2, list);
}
list.push(closer);
}
_readdirp(root, opts) {
if (this.closed) return;
let stream = readdirp(root, {
type: EVENTS.ALL,
alwaysStat: true,
lstat: true,
...opts,
depth: 0
});
this._streams.add(stream);
stream.once(STR_CLOSE, () => {
stream = void 0;
});
stream.once(STR_END, () => {
if (stream) {
this._streams.delete(stream);
stream = void 0;
}
});
return stream;
}
};
/**
* Instantiates watcher with paths to be tracked.
* @param paths file / directory paths
* @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
* @returns an instance of FSWatcher for chaining.
* @example
* const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
* watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
*/
function watch$1(paths, options = {}) {
const watcher = new FSWatcher(options);
watcher.add(paths);
return watcher;
}
var esm_default = {
watch: watch$1,
FSWatcher
};
//#endregion
export { watch$1 as i, WatchHelper as n, esm_default as r, FSWatcher as t };
import consola$1 from "consola";
import { colors } from "consola/utils";
//#region node_modules/.pnpm/citty@0.1.6/node_modules/citty/dist/index.mjs
function toArray(val) {
if (Array.isArray(val)) return val;
return val === void 0 ? [] : [val];
}
function formatLineColumns(lines, linePrefix = "") {
const maxLengh = [];
for (const line of lines) for (const [i, element] of line.entries()) maxLengh[i] = Math.max(maxLengh[i] || 0, element.length);
return lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLengh[i])).join(" ")).join("\n");
}
function resolveValue(input) {
return typeof input === "function" ? input() : input;
}
var CLIError = class extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = "CLIError";
}
};
const NUMBER_CHAR_RE = /\d/;
const STR_SPLITTERS = [
"-",
"_",
"/",
"."
];
function isUppercase(char = "") {
if (NUMBER_CHAR_RE.test(char)) return;
return char !== char.toLowerCase();
}
function splitByCase(str, separators) {
const splitters = separators ?? STR_SPLITTERS;
const parts = [];
if (!str || typeof str !== "string") return parts;
let buff = "";
let previousUpper;
let previousSplitter;
for (const char of str) {
const isSplitter = splitters.includes(char);
if (isSplitter === true) {
parts.push(buff);
buff = "";
previousUpper = void 0;
continue;
}
const isUpper = isUppercase(char);
if (previousSplitter === false) {
if (previousUpper === false && isUpper === true) {
parts.push(buff);
buff = char;
previousUpper = isUpper;
continue;
}
if (previousUpper === true && isUpper === false && buff.length > 1) {
const lastChar = buff.at(-1);
parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
buff = lastChar + char;
previousUpper = isUpper;
continue;
}
}
buff += char;
previousUpper = isUpper;
previousSplitter = isSplitter;
}
parts.push(buff);
return parts;
}
function upperFirst(str) {
return str ? str[0].toUpperCase() + str.slice(1) : "";
}
function lowerFirst(str) {
return str ? str[0].toLowerCase() + str.slice(1) : "";
}
function pascalCase(str, opts) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join("") : "";
}
function camelCase(str, opts) {
return lowerFirst(pascalCase(str || "", opts));
}
function kebabCase(str, joiner) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? "-") : "";
}
function toArr(any) {
return any == void 0 ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
let x;
const old = out[key];
const nxt = ~opts.string.indexOf(key) ? val == void 0 || val === true ? "" : String(val) : typeof val === "boolean" ? val : ~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
out[key] = old == void 0 ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
}
function parseRawArgs(args = [], opts = {}) {
let k;
let arr;
let arg;
let name;
let val;
const out = { _: [] };
let i = 0;
let j = 0;
let idx = 0;
const len = args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
for (i = opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i = opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i = 0; i < len; i++) {
arg = args[i];
if (arg === "--") {
out._ = out._.concat(args.slice(++i));
break;
}
for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
if (j === 0) out._.push(arg);
else if (arg.substring(j, j + 3) === "no-") {
name = arg.slice(Math.max(0, j + 3));
if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
out[name] = false;
} else {
for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
name = arg.substring(j, idx);
val = arg.slice(Math.max(0, ++idx)) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
arr = j === 2 ? [name] : name;
for (idx = 0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
toVal(out, name, idx + 1 < arr.length || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
}
if (alibi) for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) out[arr.shift()] = out[k];
}
return out;
}
function parseArgs(rawArgs, argsDef) {
const parseOptions = {
boolean: [],
string: [],
mixed: [],
alias: {},
default: {}
};
const args = resolveArgs(argsDef);
for (const arg of args) {
if (arg.type === "positional") continue;
if (arg.type === "string") parseOptions.string.push(arg.name);
else if (arg.type === "boolean") parseOptions.boolean.push(arg.name);
if (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;
if (arg.alias) parseOptions.alias[arg.name] = arg.alias;
}
const parsed = parseRawArgs(rawArgs, parseOptions);
const [ ...positionalArguments] = parsed._;
const parsedArgsProxy = new Proxy(parsed, { get(target, prop) {
return target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];
} });
for (const [, arg] of args.entries()) if (arg.type === "positional") {
const nextPositionalArgument = positionalArguments.shift();
if (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;
else if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, "EARG");
else parsedArgsProxy[arg.name] = arg.default;
} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, "EARG");
return parsedArgsProxy;
}
function resolveArgs(argsDef) {
const args = [];
for (const [name, argDef] of Object.entries(argsDef || {})) args.push({
...argDef,
name,
alias: toArray(argDef.alias)
});
return args;
}
function defineCommand(def) {
return def;
}
async function runCommand(cmd, opts) {
const cmdArgs = await resolveValue(cmd.args || {});
const parsedArgs = parseArgs(opts.rawArgs, cmdArgs);
const context = {
rawArgs: opts.rawArgs,
args: parsedArgs,
data: opts.data,
cmd
};
if (typeof cmd.setup === "function") await cmd.setup(context);
let result;
try {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = opts.rawArgs.findIndex((arg) => !arg.startsWith("-"));
const subCommandName = opts.rawArgs[subCommandArgIndex];
if (subCommandName) {
if (!subCommands[subCommandName]) throw new CLIError(`Unknown command \`${subCommandName}\``, "E_UNKNOWN_COMMAND");
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) await runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });
} else if (!cmd.run) throw new CLIError(`No command specified.`, "E_NO_COMMAND");
}
if (typeof cmd.run === "function") result = await cmd.run(context);
} finally {
if (typeof cmd.cleanup === "function") await cmd.cleanup(context);
}
return { result };
}
async function resolveSubCommand(cmd, rawArgs, parent) {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = rawArgs.findIndex((arg) => !arg.startsWith("-"));
const subCommandName = rawArgs[subCommandArgIndex];
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);
}
return [cmd, parent];
}
async function showUsage(cmd, parent) {
try {
consola$1.log(await renderUsage(cmd, parent) + "\n");
} catch (error) {
consola$1.error(error);
}
}
async function renderUsage(cmd, parent) {
const cmdMeta = await resolveValue(cmd.meta || {});
const cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));
const parentMeta = await resolveValue(parent?.meta || {});
const commandName = `${parentMeta.name ? `${parentMeta.name} ` : ""}` + (cmdMeta.name || process.argv[1]);
const argLines = [];
const posLines = [];
const commandsLines = [];
const usageLine = [];
for (const arg of cmdArgs) if (arg.type === "positional") {
const name = arg.name.toUpperCase();
const isRequired = arg.required !== false && arg.default === void 0;
const defaultHint = arg.default ? `="${arg.default}"` : "";
posLines.push([
"`" + name + defaultHint + "`",
arg.description || "",
arg.valueHint ? `<${arg.valueHint}>` : ""
]);
usageLine.push(isRequired ? `<${name}>` : `[${name}]`);
} else {
const isRequired = arg.required === true && arg.default === void 0;
const argStr = (arg.type === "boolean" && arg.default === true ? [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(", ") : [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(", ")) + (arg.type === "string" && (arg.valueHint || arg.default) ? `=${arg.valueHint ? `<${arg.valueHint}>` : `"${arg.default || ""}"`}` : "");
argLines.push(["`" + argStr + (isRequired ? " (required)" : "") + "`", arg.description || ""]);
if (isRequired) usageLine.push(argStr);
}
if (cmd.subCommands) {
const commandNames = [];
const subCommands = await resolveValue(cmd.subCommands);
for (const [name, sub] of Object.entries(subCommands)) {
const meta = await resolveValue((await resolveValue(sub))?.meta);
commandsLines.push([`\`${name}\``, meta?.description || ""]);
commandNames.push(name);
}
usageLine.push(commandNames.join("|"));
}
const usageLines = [];
const version = cmdMeta.version || parentMeta.version;
usageLines.push(colors.gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`), "");
const hasOptions = argLines.length > 0 || posLines.length > 0;
usageLines.push(`${colors.underline(colors.bold("USAGE"))} \`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}\``, "");
if (posLines.length > 0) {
usageLines.push(colors.underline(colors.bold("ARGUMENTS")), "");
usageLines.push(formatLineColumns(posLines, " "));
usageLines.push("");
}
if (argLines.length > 0) {
usageLines.push(colors.underline(colors.bold("OPTIONS")), "");
usageLines.push(formatLineColumns(argLines, " "));
usageLines.push("");
}
if (commandsLines.length > 0) {
usageLines.push(colors.underline(colors.bold("COMMANDS")), "");
usageLines.push(formatLineColumns(commandsLines, " "));
usageLines.push("", `Use \`${commandName} <command> --help\` for more information about a command.`);
}
return usageLines.filter((l) => typeof l === "string").join("\n");
}
async function runMain(cmd, opts = {}) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
const showUsage$1 = opts.showUsage || showUsage;
try {
if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
const meta = typeof cmd.meta === "function" ? await cmd.meta() : await cmd.meta;
if (!meta?.version) throw new CLIError("No version specified", "E_NO_VERSION");
consola$1.log(meta.version);
} else await runCommand(cmd, { rawArgs });
} catch (error) {
const isCLIError = error instanceof CLIError;
if (!isCLIError) consola$1.error(error, "\n");
if (isCLIError) await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
consola$1.error(error.message);
process.exit(1);
}
}
//#endregion
export { runMain as n, defineCommand as t };
import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js
var require_commondir = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js": ((exports, module) => {
var path = __require("path");
module.exports = function(basedir, relfiles) {
if (relfiles) var files = relfiles.map(function(r) {
return path.resolve(basedir, r);
});
else var files = basedir;
var res = files.slice(1).reduce(function(ps, file) {
if (!file.match(/^([A-Za-z]:)?\/|\\/)) throw new Error("relative path without a basedir");
var xs = file.split(/\/+|\\+/);
for (var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++);
return ps.slice(0, i);
}, files[0].split(/\/+|\\+/));
return res.length > 1 ? res.join("/") : "/";
};
}) });
//#endregion
export { require_commondir as t };
//#region node_modules/.pnpm/compatx@0.2.0/node_modules/compatx/dist/index.mjs
const platforms = [
"aws",
"azure",
"cloudflare",
"deno",
"firebase",
"netlify",
"vercel"
];
function resolveCompatibilityDates(input, defaults) {
const dates = { default: "" };
const _defaults = typeof defaults === "string" ? { default: defaults } : defaults || {};
for (const [key, value] of Object.entries(_defaults)) if (value) dates[key] = formatDate(value);
const _input = typeof input === "string" ? { default: input } : input || {};
for (const [key, value] of Object.entries(_input)) if (value) dates[key] = formatDate(value);
dates.default = formatDate(dates.default || "") || Object.values(dates).sort().pop() || "";
return dates;
}
function resolveCompatibilityDatesFromEnv(overridesInput) {
const defaults = { default: process.env.COMPATIBILITY_DATE ? formatDate(process.env.COMPATIBILITY_DATE) : void 0 };
for (const platform of platforms) {
const envName = `COMPATIBILITY_DATE_${platform.toUpperCase()}`;
const env = process.env[envName];
if (env) defaults[platform] = formatDate(env);
}
return resolveCompatibilityDates(overridesInput, defaults);
}
function formatCompatibilityDate(input) {
const dates = resolveCompatibilityDates(input);
if (Object.entries(dates).length === 0) return "-";
return [`${dates["default"]}`, ...Object.entries(dates).filter(([key, value]) => key !== "default" && value && value !== dates["default"]).map(([key, value]) => `${key}: ${value}`)].join(", ");
}
function formatDate(date) {
const d = normalizeDate(date);
if (Number.isNaN(d.getDate())) return "";
return `${d.getFullYear().toString()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`;
}
function normalizeDate(date) {
if (date instanceof Date) return date;
if (date === "latest") return /* @__PURE__ */ new Date();
return new Date(date);
}
//#endregion
export { resolveCompatibilityDates as n, resolveCompatibilityDatesFromEnv as r, formatCompatibilityDate as t };

Sorry, the diff of this file is too big to display

import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js
var require_cjs = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js": ((exports, module) => {
var isMergeableObject = function isMergeableObject$1(value) {
return isNonNullObject(value) && !isSpecial(value);
};
function isNonNullObject(value) {
return !!value && typeof value === "object";
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
}
var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.element") : 60103;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE;
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {};
}
function cloneUnlessOtherwiseSpecified(value, options) {
return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options);
});
}
function getMergeFunction(key, options) {
if (!options.customMerge) return deepmerge;
var customMerge = options.customMerge(key);
return typeof customMerge === "function" ? customMerge : deepmerge;
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return Object.propertyIsEnumerable.call(target, symbol);
}) : [];
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
function propertyIsOnObject(object, property) {
try {
return property in object;
} catch (_) {
return false;
}
}
function propertyIsUnsafe(target, key) {
return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
getKeys(source).forEach(function(key) {
if (propertyIsUnsafe(target, key)) return;
if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
else destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
});
return destination;
}
function deepmerge(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
var sourceIsArray = Array.isArray(source);
if (!(sourceIsArray === Array.isArray(target))) return cloneUnlessOtherwiseSpecified(source, options);
else if (sourceIsArray) return options.arrayMerge(target, source, options);
else return mergeObject(target, source, options);
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) throw new Error("first argument should be an array");
return array.reduce(function(prev, next) {
return deepmerge(prev, next, options);
}, {});
};
var deepmerge_1 = deepmerge;
module.exports = deepmerge_1;
}) });
//#endregion
export { require_cjs as t };
//#region node_modules/.pnpm/dot-prop@10.1.0/node_modules/dot-prop/index.js
const isObject = (value) => {
const type = typeof value;
return value !== null && (type === "object" || type === "function");
};
const disallowedKeys = new Set([
"__proto__",
"prototype",
"constructor"
]);
const MAX_ARRAY_INDEX = 1e6;
const isDigit = (character) => character >= "0" && character <= "9";
function shouldCoerceToNumber(segment) {
if (segment === "0") return true;
if (/^[1-9]\d*$/.test(segment)) {
const parsedNumber = Number.parseInt(segment, 10);
return parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX;
}
return false;
}
function processSegment(segment, parts) {
if (disallowedKeys.has(segment)) return false;
if (segment && shouldCoerceToNumber(segment)) parts.push(Number.parseInt(segment, 10));
else parts.push(segment);
return true;
}
function parsePath(path) {
if (typeof path !== "string") throw new TypeError(`Expected a string, got ${typeof path}`);
const parts = [];
let currentSegment = "";
let currentPart = "start";
let isEscaping = false;
let position = 0;
for (const character of path) {
position++;
if (isEscaping) {
currentSegment += character;
isEscaping = false;
continue;
}
if (character === "\\") {
if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`);
if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`);
isEscaping = true;
currentPart = currentPart === "start" ? "property" : currentPart;
continue;
}
switch (character) {
case ".":
if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`);
if (currentPart === "indexEnd") {
currentPart = "property";
break;
}
if (!processSegment(currentSegment, parts)) return [];
currentSegment = "";
currentPart = "property";
break;
case "[":
if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`);
if (currentPart === "indexEnd") {
currentPart = "index";
break;
}
if (currentPart === "property" || currentPart === "start") {
if ((currentSegment || currentPart === "property") && !processSegment(currentSegment, parts)) return [];
currentSegment = "";
}
currentPart = "index";
break;
case "]":
if (currentPart === "index") {
if (currentSegment === "") {
currentSegment = (parts.pop() || "") + "[]";
currentPart = "property";
} else {
const parsedNumber = Number.parseInt(currentSegment, 10);
if (!Number.isNaN(parsedNumber) && Number.isFinite(parsedNumber) && parsedNumber >= 0 && parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX && currentSegment === String(parsedNumber)) parts.push(parsedNumber);
else parts.push(currentSegment);
currentSegment = "";
currentPart = "indexEnd";
}
break;
}
if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`);
currentSegment += character;
break;
default:
if (currentPart === "index" && !isDigit(character)) throw new Error(`Invalid character '${character}' in an index at position ${position}`);
if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`);
if (currentPart === "start") currentPart = "property";
currentSegment += character;
}
}
if (isEscaping) currentSegment += "\\";
switch (currentPart) {
case "property":
if (!processSegment(currentSegment, parts)) return [];
break;
case "index": throw new Error("Index was not closed");
case "start":
parts.push("");
break;
}
return parts;
}
function normalizePath(path) {
if (typeof path === "string") return parsePath(path);
if (Array.isArray(path)) {
const normalized = [];
for (const [index, segment] of path.entries()) {
if (typeof segment !== "string" && typeof segment !== "number") throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`);
if (typeof segment === "number" && !Number.isFinite(segment)) throw new TypeError(`Path segment at index ${index} must be a finite number, got ${segment}`);
if (disallowedKeys.has(segment)) return [];
if (typeof segment === "string" && shouldCoerceToNumber(segment)) normalized.push(Number.parseInt(segment, 10));
else normalized.push(segment);
}
return normalized;
}
return [];
}
function getProperty(object, path, value) {
if (!isObject(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value;
const pathArray = normalizePath(path);
if (pathArray.length === 0) return value;
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
object = object[key];
if (object === void 0 || object === null) {
if (index !== pathArray.length - 1) return value;
break;
}
}
return object === void 0 ? value : object;
}
//#endregion
export { getProperty as t };
import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/duplexer@0.1.2/node_modules/duplexer/index.js
var require_duplexer = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/duplexer@0.1.2/node_modules/duplexer/index.js": ((exports, module) => {
var Stream = __require("stream");
var writeMethods = [
"write",
"end",
"destroy"
];
var readMethods = ["resume", "pause"];
var readEvents = ["data", "close"];
var slice = Array.prototype.slice;
module.exports = duplex;
function forEach(arr, fn) {
if (arr.forEach) return arr.forEach(fn);
for (var i = 0; i < arr.length; i++) fn(arr[i], i);
}
function duplex(writer, reader) {
var stream = new Stream();
var ended = false;
forEach(writeMethods, proxyWriter);
forEach(readMethods, proxyReader);
forEach(readEvents, proxyStream);
reader.on("end", handleEnd);
writer.on("drain", function() {
stream.emit("drain");
});
writer.on("error", reemit);
reader.on("error", reemit);
stream.writable = writer.writable;
stream.readable = reader.readable;
return stream;
function proxyWriter(methodName) {
stream[methodName] = method;
function method() {
return writer[methodName].apply(writer, arguments);
}
}
function proxyReader(methodName) {
stream[methodName] = method;
function method() {
stream.emit(methodName);
var func = reader[methodName];
if (func) return func.apply(reader, arguments);
reader.emit(methodName);
}
}
function proxyStream(methodName) {
reader.on(methodName, reemit$1);
function reemit$1() {
var args = slice.call(arguments);
args.unshift(methodName);
stream.emit.apply(stream, args);
}
}
function handleEnd() {
if (ended) return;
ended = true;
var args = slice.call(arguments);
args.unshift("end");
stream.emit.apply(stream, args);
}
function reemit(err) {
stream.emit("error", err);
}
}
}) });
//#endregion
export { require_duplexer as t };
//#region node_modules/.pnpm/escape-string-regexp@5.0.0/node_modules/escape-string-regexp/index.js
function escapeStringRegexp(string) {
if (typeof string !== "string") throw new TypeError("Expected a string");
return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}
//#endregion
export { escapeStringRegexp as t };
//#region node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/esm/estree-walker.js
/** @typedef { import('estree').BaseNode} BaseNode */
/** @typedef {{
skip: () => void;
remove: () => void;
replace: (node: BaseNode) => void;
}} WalkerContext */
var WalkerBase$1 = class {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {BaseNode | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
*
* @param {any} parent
* @param {string} prop
* @param {number} index
* @param {BaseNode} node
*/
replace(parent, prop, index, node) {
if (parent) if (index !== null) parent[prop][index] = node;
else parent[prop] = node;
}
/**
*
* @param {any} parent
* @param {string} prop
* @param {number} index
*/
remove(parent, prop, index) {
if (parent) if (index !== null) parent[prop].splice(index, 1);
else delete parent[prop];
}
};
/** @typedef { import('estree').BaseNode} BaseNode */
/** @typedef { import('./walker.js').WalkerContext} WalkerContext */
/** @typedef {(
* this: WalkerContext,
* node: BaseNode,
* parent: BaseNode,
* key: string,
* index: number
* ) => void} SyncHandler */
var SyncWalker$1 = class extends WalkerBase$1 {
/**
*
* @param {SyncHandler} enter
* @param {SyncHandler} leave
*/
constructor(enter, leave) {
super();
/** @type {SyncHandler} */
this.enter = enter;
/** @type {SyncHandler} */
this.leave = leave;
}
/**
*
* @param {BaseNode} node
* @param {BaseNode} parent
* @param {string} [prop]
* @param {number} [index]
* @returns {BaseNode}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) this.remove(parent, prop, index);
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = node[key];
if (typeof value !== "object") continue;
else if (Array.isArray(value)) {
for (let i = 0; i < value.length; i += 1) if (value[i] !== null && typeof value[i].type === "string") {
if (!this.visit(value[i], node, key, i)) i--;
}
} else if (value !== null && typeof value.type === "string") this.visit(value, node, key, null);
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) this.remove(parent, prop, index);
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
/** @typedef { import('estree').BaseNode} BaseNode */
/** @typedef { import('./sync.js').SyncHandler} SyncHandler */
/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
/**
*
* @param {BaseNode} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {BaseNode}
*/
function walk$1(ast, { enter, leave }) {
return new SyncWalker$1(enter, leave).visit(ast, null);
}
//#endregion
//#region node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
var WalkerBase = class {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) if (index != null)
/** @type {Array<Node>} */ parent[prop][index] = node;
else
/** @type {Node} */ parent[prop] = node;
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) if (index !== null && index !== void 0)
/** @type {Array<Node>} */ parent[prop].splice(index, 1);
else delete parent[prop];
}
};
//#endregion
//#region node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
var SyncWalker = class extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) this.remove(parent, prop, index);
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = value;
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) i--;
}
}
} else if (isNode(value)) this.visit(value, node, key, null);
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) this.remove(parent, prop, index);
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
//#endregion
//#region node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
function walk(ast, { enter, leave }) {
return new SyncWalker(enter, leave).visit(ast, null);
}
//#endregion
export { walk$1 as n, walk as t };
import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
/*!
* etag
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*/
var require_etag = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js": ((exports, module) => {
/**
* Module exports.
* @public
*/
module.exports = etag;
/**
* Module dependencies.
* @private
*/
var crypto = __require("crypto");
var Stats = __require("fs").Stats;
/**
* Module variables.
* @private
*/
var toString = Object.prototype.toString;
/**
* Generate an entity tag.
*
* @param {Buffer|string} entity
* @return {string}
* @private
*/
function entitytag(entity) {
if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"";
var hash = crypto.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash + "\"";
}
/**
* Create a simple ETag.
*
* @param {string|Buffer|Stats} entity
* @param {object} [options]
* @param {boolean} [options.weak]
* @return {String}
* @public
*/
function etag(entity, options) {
if (entity == null) throw new TypeError("argument entity is required");
var isStats = isstats(entity);
var weak = options && typeof options.weak === "boolean" ? options.weak : isStats;
if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
var tag = isStats ? stattag(entity) : entitytag(entity);
return weak ? "W/" + tag : tag;
}
/**
* Determine if object is a Stats object.
*
* @param {object} obj
* @return {boolean}
* @api private
*/
function isstats(obj) {
if (typeof Stats === "function" && obj instanceof Stats) return true;
return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
}
/**
* Generate a tag for a stat.
*
* @param {object} stat
* @return {string}
* @private
*/
function stattag(stat) {
var mtime = stat.mtime.getTime().toString(16);
return "\"" + stat.size.toString(16) + "-" + mtime + "\"";
}
}) });
//#endregion
export { require_etag as t };
import * as nativeFs$1 from "fs";
import { basename, dirname, normalize, relative, resolve, sep } from "path";
import { createRequire } from "module";
//#region node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.3/node_modules/fdir/dist/index.mjs
var __require = /* @__PURE__ */ createRequire(import.meta.url);
function cleanPath(path$1) {
let normalized = normalize(path$1);
if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
return normalized;
}
const SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path$1, separator) {
return path$1.replace(SLASHES_REGEX, separator);
}
const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
function isRootDirectory(path$1) {
return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
}
function normalizePath(path$1, options) {
const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
if (resolvePaths) path$1 = resolve(path$1);
if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
if (path$1 === ".") return "";
return convertSlashes(path$1[path$1.length - 1] !== pathSeparator ? path$1 + pathSeparator : path$1, pathSeparator);
}
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
function joinPathWithRelativePath(root, options) {
return function(filename, directoryPath) {
if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename;
else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
};
}
function joinPath(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
function build$7(root, options) {
const { relativePaths, includeBasePath } = options;
return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
}
function pushDirectoryWithRelativePath(root) {
return function(directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function(directoryPath, paths, filters) {
const relativePath = directoryPath.substring(root.length) || ".";
if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
};
}
const pushDirectory = (directoryPath, paths) => {
paths.push(directoryPath || ".");
};
const pushDirectoryFilter = (directoryPath, paths, filters) => {
const path$1 = directoryPath || ".";
if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
};
const empty$2 = () => {};
function build$6(root, options) {
const { includeDirs, filters, relativePaths } = options;
if (!includeDirs) return empty$2;
if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
return filters && filters.length ? pushDirectoryFilter : pushDirectory;
}
const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
if (filters.every((filter) => filter(filename, false))) counts.files++;
};
const pushFileFilter = (filename, paths, _counts, filters) => {
if (filters.every((filter) => filter(filename, false))) paths.push(filename);
};
const pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
};
const pushFile = (filename, paths) => {
paths.push(filename);
};
const empty$1 = () => {};
function build$5(options) {
const { excludeFiles, filters, onlyCounts } = options;
if (excludeFiles) return empty$1;
if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
else if (onlyCounts) return pushFileCount;
else return pushFile;
}
const getArray = (paths) => {
return paths;
};
const getArrayGroup = () => {
return [""].slice(0, 0);
};
function build$4(options) {
return options.group ? getArrayGroup : getArray;
}
const groupFiles = (groups, directory, files) => {
groups.push({
directory,
files,
dir: directory
});
};
const empty = () => {};
function build$3(options) {
return options.group ? groupFiles : empty;
}
const resolveSymlinksAsync = function(path$1, state, callback$1) {
const { queue, fs, options: { suppressErrors } } = state;
queue.enqueue();
fs.realpath(path$1, (error, resolvedPath) => {
if (error) return queue.dequeue(suppressErrors ? null : error, state);
fs.stat(resolvedPath, (error$1, stat$1) => {
if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
callback$1(stat$1, resolvedPath);
queue.dequeue(null, state);
});
});
};
const resolveSymlinks = function(path$1, state, callback$1) {
const { queue, fs, options: { suppressErrors } } = state;
queue.enqueue();
try {
const resolvedPath = fs.realpathSync(path$1);
const stat$1 = fs.statSync(resolvedPath);
if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
callback$1(stat$1, resolvedPath);
} catch (e) {
if (!suppressErrors) throw e;
}
};
function build$2(options, isSynchronous) {
if (!options.resolveSymlinks || options.excludeSymlinks) return null;
return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
function isRecursive(path$1, resolved, state) {
if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
let parent = dirname(path$1);
let depth = 1;
while (parent !== state.root && depth < 2) {
const resolvedPath = state.symlinks.get(parent);
if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth++;
else parent = dirname(parent);
}
state.symlinks.set(path$1, resolved);
return depth > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}
const onlyCountsSync = (state) => {
return state.counts;
};
const groupsSync = (state) => {
return state.groups;
};
const defaultSync = (state) => {
return state.paths;
};
const limitFilesSync = (state) => {
return state.paths.slice(0, state.options.maxFiles);
};
const onlyCountsAsync = (state, error, callback$1) => {
report(error, callback$1, state.counts, state.options.suppressErrors);
return null;
};
const defaultAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths, state.options.suppressErrors);
return null;
};
const limitFilesAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
return null;
};
const groupsAsync = (state, error, callback$1) => {
report(error, callback$1, state.groups, state.options.suppressErrors);
return null;
};
function report(error, callback$1, output, suppressErrors) {
if (error && !suppressErrors) callback$1(error, output);
else callback$1(null, output);
}
function build$1(options, isSynchronous) {
const { onlyCounts, group, maxFiles } = options;
if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
else if (group) return isSynchronous ? groupsSync : groupsAsync;
else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
else return isSynchronous ? defaultSync : defaultAsync;
}
const readdirOpts = { withFileTypes: true };
const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
state.queue.enqueue();
if (currentDepth < 0) return state.queue.dequeue(null, state);
const { fs } = state;
state.visited.push(crawlPath);
state.counts.directories++;
fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback$1(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
const { fs } = state;
if (currentDepth < 0) return;
state.visited.push(crawlPath);
state.counts.directories++;
let entries = [];
try {
entries = fs.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback$1(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
var Queue = class {
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
this.count++;
return this.count;
}
dequeue(error, output) {
if (this.onQueueEmpty && (--this.count <= 0 || error)) {
this.onQueueEmpty(error, output);
if (error) {
output.controller.abort();
this.onQueueEmpty = void 0;
}
}
}
};
var Counter = class {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
};
/**
* AbortController is not supported on Node 14 so we use this until we can drop
* support for Node 14.
*/
var Aborter = class {
aborted = false;
abort() {
this.aborted = true;
}
};
var Walker = class {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback$1) {
this.isSynchronous = !callback$1;
this.callbackInvoker = build$1(options, this.isSynchronous);
this.root = normalizePath(root, options);
this.state = {
root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
paths: [""].slice(0, 0),
groups: [],
counts: new Counter(),
options,
queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
symlinks: /* @__PURE__ */ new Map(),
visited: [""].slice(0, 0),
controller: new Aborter(),
fs: options.fs || nativeFs$1
};
this.joinPath = build$7(this.root, options);
this.pushDirectory = build$6(this.root, options);
this.pushFile = build$5(options);
this.getArray = build$4(options);
this.groupFiles = build$3(options);
this.resolveSymlink = build$2(options, this.isSynchronous);
this.walkDirectory = build(this.isSynchronous);
}
start() {
this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth) => {
const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
const files = this.getArray(this.state.paths);
for (let i = 0; i < entries.length; ++i) {
const entry = entries[i];
if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
const filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
} else if (entry.isDirectory()) {
let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path$1)) continue;
this.pushDirectory(path$1, paths, filters);
this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk);
} else if (this.resolveSymlink && entry.isSymbolicLink()) {
let path$1 = joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path$1, this.state, (stat$1, resolvedPath) => {
if (stat$1.isDirectory()) {
resolvedPath = normalizePath(resolvedPath, this.state.options);
if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk);
} else {
resolvedPath = useRealPaths ? resolvedPath : path$1;
const filename = basename(resolvedPath);
const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath$1);
this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
};
function promise(root, options) {
return new Promise((resolve$1, reject) => {
callback(root, options, (err, output) => {
if (err) return reject(err);
resolve$1(output);
});
});
}
function callback(root, options, callback$1) {
new Walker(root, options, callback$1).start();
}
function sync(root, options) {
return new Walker(root, options).start();
}
var APIBuilder = class {
constructor(root, options) {
this.root = root;
this.options = options;
}
withPromise() {
return promise(this.root, this.options);
}
withCallback(cb) {
callback(this.root, this.options, cb);
}
sync() {
return sync(this.root, this.options);
}
};
let pm = null;
/* c8 ignore next 6 */
try {
__require.resolve("picomatch");
pm = __require("picomatch");
} catch {}
var Builder = class {
globCache = {};
options = {
maxDepth: Infinity,
suppressErrors: true,
pathSeparator: sep,
filters: []
};
globFunction;
constructor(options) {
this.options = {
...this.options,
...options
};
this.globFunction = this.options.globFunction;
}
group() {
this.options.group = true;
return this;
}
withPathSeparator(separator) {
this.options.pathSeparator = separator;
return this;
}
withBasePath() {
this.options.includeBasePath = true;
return this;
}
withRelativePaths() {
this.options.relativePaths = true;
return this;
}
withDirs() {
this.options.includeDirs = true;
return this;
}
withMaxDepth(depth) {
this.options.maxDepth = depth;
return this;
}
withMaxFiles(limit) {
this.options.maxFiles = limit;
return this;
}
withFullPaths() {
this.options.resolvePaths = true;
this.options.includeBasePath = true;
return this;
}
withErrors() {
this.options.suppressErrors = false;
return this;
}
withSymlinks({ resolvePaths = true } = {}) {
this.options.resolveSymlinks = true;
this.options.useRealPaths = resolvePaths;
return this.withFullPaths();
}
withAbortSignal(signal) {
this.options.signal = signal;
return this;
}
normalize() {
this.options.normalizePath = true;
return this;
}
filter(predicate) {
this.options.filters.push(predicate);
return this;
}
onlyDirs() {
this.options.excludeFiles = true;
this.options.includeDirs = true;
return this;
}
exclude(predicate) {
this.options.exclude = predicate;
return this;
}
onlyCounts() {
this.options.onlyCounts = true;
return this;
}
crawl(root) {
return new APIBuilder(root || ".", this.options);
}
withGlobFunction(fn) {
this.globFunction = fn;
return this;
}
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
/* c8 ignore next 4 */
crawlWithOptions(root, options) {
this.options = {
...this.options,
...options
};
return new APIBuilder(root || ".", this.options);
}
glob(...patterns) {
if (this.globFunction) return this.globWithOptions(patterns);
return this.globWithOptions(patterns, ...[{ dot: true }]);
}
globWithOptions(patterns, ...options) {
const globFn = this.globFunction || pm;
/* c8 ignore next 5 */
if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
var isMatch = this.globCache[patterns.join("\0")];
if (!isMatch) {
isMatch = globFn(patterns, ...options);
this.globCache[patterns.join("\0")] = isMatch;
}
this.options.filters.push((path$1) => isMatch(path$1));
return this;
}
};
//#endregion
export { Builder as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js
var require_implementation = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js": ((exports, module) => {
var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = "[object Function]";
var concatty = function concatty$1(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) arr[i] = a[i];
for (var j = 0; j < b.length; j += 1) arr[j + a.length] = b[j];
return arr;
};
var slicy = function slicy$1(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) arr[j] = arrLike[i];
return arr;
};
var joiny = function(arr, joiner) {
var str = "";
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) str += joiner;
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== "function" || toStr.apply(target) !== funcType) throw new TypeError(ERROR_MESSAGE + target);
var args = slicy(arguments, 1);
var bound;
var binder = function() {
if (this instanceof bound) {
var result = target.apply(this, concatty(args, arguments));
if (Object(result) === result) return result;
return this;
}
return target.apply(that, concatty(args, arguments));
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) boundArgs[i] = "$" + i;
bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
if (target.prototype) {
var Empty = function Empty$1() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
}) });
//#endregion
//#region node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js
var require_function_bind = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js": ((exports, module) => {
var implementation = require_implementation();
module.exports = Function.prototype.bind || implementation;
}) });
//#endregion
export { require_function_bind as t };
//#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function decodeInteger(reader, relative) {
let value = 0;
let shift = 0;
let integer = 0;
do {
integer = charToInt[reader.next()];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) value = -2147483648 | -value;
return relative + value;
}
function encodeInteger(builder, num, relative) {
let delta = num - relative;
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
do {
let clamped = delta & 31;
delta >>>= 5;
if (delta > 0) clamped |= 32;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max) return false;
return reader.peek() !== comma;
}
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
} } : { decode(buf) {
let out = "";
for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
return out;
} };
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
};
var StringReader = class {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(";");
const line = [];
let sorted = true;
let lastCol = 0;
genColumn = 0;
while (reader.pos < semi) {
let seg;
genColumn = decodeInteger(reader, genColumn);
if (genColumn < lastCol) sorted = false;
lastCol = genColumn;
if (hasMoreVlq(reader, semi)) {
sourcesIndex = decodeInteger(reader, sourcesIndex);
sourceLine = decodeInteger(reader, sourceLine);
sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(reader, semi)) {
namesIndex = decodeInteger(reader, namesIndex);
seg = [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn,
namesIndex
];
} else seg = [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn
];
} else seg = [genColumn];
line.push(seg);
reader.pos++;
}
if (!sorted) sort(line);
decoded.push(line);
reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
return a[0] - b[0];
}
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) writer.write(semicolon);
if (line.length === 0) continue;
let genColumn = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (j > 0) writer.write(comma);
genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) continue;
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
sourceLine = encodeInteger(writer, segment[2], sourceLine);
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) continue;
namesIndex = encodeInteger(writer, segment[4], namesIndex);
}
}
return writer.flush();
}
//#endregion
//#region node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
const schemeRegex = /^[\w+.-]+:\/\//;
/**
* Matches the parts of a URL:
* 1. Scheme, including ":", guaranteed.
* 2. User/password, including "@", optional.
* 3. Host, guaranteed.
* 4. Port, including ":", optional.
* 5. Path, including "/", optional.
* 6. Query, including "?", optional.
* 7. Hash, including "#", optional.
*/
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
/**
* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
*
* 1. Host, optional.
* 2. Path, which may include "/", guaranteed.
* 3. Query, including "?", optional.
* 4. Hash, including "#", optional.
*/
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
return input.startsWith("//");
}
function isAbsolutePath(input) {
return input.startsWith("/");
}
function isFileUrl(input) {
return input.startsWith("file:");
}
function isRelative(input) {
return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
const match = urlRegex.exec(input);
return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
}
function parseFileUrl(input) {
const match = fileRegex.exec(input);
const path = match[2];
return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
}
function makeUrl(scheme, user, host, port, path, query, hash) {
return {
scheme,
user,
host,
port,
path,
query,
hash,
type: 7
};
}
function parseUrl(input) {
if (isSchemeRelativeUrl(input)) {
const url$1 = parseAbsoluteUrl("http:" + input);
url$1.scheme = "";
url$1.type = 6;
return url$1;
}
if (isAbsolutePath(input)) {
const url$1 = parseAbsoluteUrl("http://foo.com" + input);
url$1.scheme = "";
url$1.host = "";
url$1.type = 5;
return url$1;
}
if (isFileUrl(input)) return parseFileUrl(input);
if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
const url = parseAbsoluteUrl("http://foo.com/" + input);
url.scheme = "";
url.host = "";
url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
return url;
}
function stripPathFilename(path) {
if (path.endsWith("/..")) return path;
const index = path.lastIndexOf("/");
return path.slice(0, index + 1);
}
function mergePaths(url, base) {
normalizePath(base, base.type);
if (url.path === "/") url.path = base.path;
else url.path = stripPathFilename(base.path) + url.path;
}
/**
* The path can have empty directories "//", unneeded parents "foo/..", or current directory
* "foo/.". We need to normalize to a standard representation.
*/
function normalizePath(url, type) {
const rel = type <= 4;
const pieces = url.path.split("/");
let pointer = 1;
let positive = 0;
let addTrailingSlash = false;
for (let i = 1; i < pieces.length; i++) {
const piece = pieces[i];
if (!piece) {
addTrailingSlash = true;
continue;
}
addTrailingSlash = false;
if (piece === ".") continue;
if (piece === "..") {
if (positive) {
addTrailingSlash = true;
positive--;
pointer--;
} else if (rel) pieces[pointer++] = piece;
continue;
}
pieces[pointer++] = piece;
positive++;
}
let path = "";
for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
url.path = path;
}
/**
* Attempts to resolve `input` URL/path relative to `base`.
*/
function resolve(input, base) {
if (!input && !base) return "";
const url = parseUrl(input);
let inputType = url.type;
if (base && inputType !== 7) {
const baseUrl = parseUrl(base);
const baseType = baseUrl.type;
switch (inputType) {
case 1: url.hash = baseUrl.hash;
case 2: url.query = baseUrl.query;
case 3:
case 4: mergePaths(url, baseUrl);
case 5:
url.user = baseUrl.user;
url.host = baseUrl.host;
url.port = baseUrl.port;
case 6: url.scheme = baseUrl.scheme;
}
if (baseType > inputType) inputType = baseType;
}
normalizePath(url, inputType);
const queryHash = url.query + url.hash;
switch (inputType) {
case 2:
case 3: return queryHash;
case 4: {
const path = url.path.slice(1);
if (!path) return queryHash || ".";
if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
return path + queryHash;
}
case 5: return url.path + queryHash;
default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
}
}
//#endregion
//#region node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
function stripFilename(path) {
if (!path) return "";
const index = path.lastIndexOf("/");
return path.slice(0, index + 1);
}
function resolver(mapUrl, sourceRoot) {
const from = stripFilename(mapUrl);
const prefix = sourceRoot ? sourceRoot + "/" : "";
return (source) => resolve(prefix + (source || ""), from);
}
var COLUMN$1 = 0;
function maybeSort(mappings, owned) {
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
if (unsortedIndex === mappings.length) return mappings;
if (!owned) mappings = mappings.slice();
for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
return mappings.length;
}
function isSorted(line) {
for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
return true;
}
function sortSegments(line, owned) {
if (!owned) line = line.slice();
return line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[COLUMN$1] - b[COLUMN$1];
}
var found = false;
function binarySearch(haystack, needle, low, high) {
while (low <= high) {
const mid = low + (high - low >> 1);
const cmp = haystack[mid][COLUMN$1] - needle;
if (cmp === 0) {
found = true;
return mid;
}
if (cmp < 0) low = mid + 1;
else high = mid - 1;
}
found = false;
return low - 1;
}
function upperBound(haystack, needle, index) {
for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$1] !== needle) break;
return index;
}
function lowerBound(haystack, needle, index) {
for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$1] !== needle) break;
return index;
}
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function memoizedBinarySearch(haystack, needle, state, key) {
const { lastKey, lastNeedle, lastIndex } = state;
let low = 0;
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
return lastIndex;
}
if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
else high = lastIndex;
}
state.lastKey = key;
state.lastNeedle = needle;
return state.lastIndex = binarySearch(haystack, needle, low, high);
}
function parse(map) {
return typeof map === "string" ? JSON.parse(map) : map;
}
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
var TraceMap = class {
constructor(map, mapUrl) {
const isString = typeof map === "string";
if (!isString && map._decodedMemo) return map;
const parsed = parse(map);
const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
this.version = version;
this.file = file;
this.names = names || [];
this.sourceRoot = sourceRoot;
this.sources = sources;
this.sourcesContent = sourcesContent;
this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
const resolve$1 = resolver(mapUrl, sourceRoot);
this.resolvedSources = sources.map(resolve$1);
const { mappings } = parsed;
if (typeof mappings === "string") {
this._encoded = mappings;
this._decoded = void 0;
} else if (Array.isArray(mappings)) {
this._encoded = void 0;
this._decoded = maybeSort(mappings, isString);
} else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
this._decodedMemo = memoizedState();
this._bySources = void 0;
this._bySourceMemos = void 0;
}
};
function cast$1(map) {
return map;
}
function decodedMappings(map) {
var _a;
return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
}
function traceSegment(map, line, column) {
const decoded = decodedMappings(map);
if (line >= decoded.length) return null;
const segments = decoded[line];
const index = traceSegmentInternal(segments, cast$1(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
return index === -1 ? null : segments[index];
}
function traceSegmentInternal(segments, memo, line, column, bias) {
let index = memoizedBinarySearch(segments, column, memo, line);
if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
else if (bias === LEAST_UPPER_BOUND) index++;
if (index === -1 || index === segments.length) return -1;
return index;
}
//#endregion
//#region node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
var SetArray = class {
constructor() {
this._indexes = { __proto__: null };
this.array = [];
}
};
function cast(set) {
return set;
}
function get(setarr, key) {
return cast(setarr)._indexes[key];
}
function put(setarr, key) {
const index = get(setarr, key);
if (index !== void 0) return index;
const { array, _indexes: indexes } = cast(setarr);
return indexes[key] = array.push(key) - 1;
}
function remove(setarr, key) {
const index = get(setarr, key);
if (index === void 0) return;
const { array, _indexes: indexes } = cast(setarr);
for (let i = index + 1; i < array.length; i++) {
const k = array[i];
array[i - 1] = k;
indexes[k]--;
}
indexes[key] = void 0;
array.pop();
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var NO_NAME = -1;
var GenMapping = class {
constructor({ file, sourceRoot } = {}) {
this._names = new SetArray();
this._sources = new SetArray();
this._sourcesContent = [];
this._mappings = [];
this.file = file;
this.sourceRoot = sourceRoot;
this._ignoreList = new SetArray();
}
};
function cast2(map) {
return map;
}
var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
};
function setSourceContent(map, source, content) {
const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map);
const index = put(sources, source);
sourcesContent[index] = content;
}
function setIgnore(map, source, ignore = true) {
const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map);
const index = put(sources, source);
if (index === sourcesContent.length) sourcesContent[index] = null;
if (ignore) put(ignoreList, index);
else remove(ignoreList, index);
}
function toDecodedMap(map) {
const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
removeEmptyFinalLines(mappings);
return {
version: 3,
file: map.file || void 0,
names: names.array,
sourceRoot: map.sourceRoot || void 0,
sources: sources.array,
sourcesContent,
mappings,
ignoreList: ignoreList.array
};
}
function toEncodedMap(map) {
const decoded = toDecodedMap(map);
return Object.assign({}, decoded, { mappings: encode(decoded.mappings) });
}
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
const line = getIndex(mappings, genLine);
const index = getColumnIndex(line, genColumn);
if (!source) {
if (skipable && skipSourceless(line, index)) return;
return insert(line, index, [genColumn]);
}
assert(sourceLine);
assert(sourceColumn);
const sourcesIndex = put(sources, source);
const namesIndex = name ? put(names, name) : NO_NAME;
if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
return insert(line, index, name ? [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn,
namesIndex
] : [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn
]);
}
function assert(_val) {}
function getIndex(arr, index) {
for (let i = arr.length; i <= index; i++) arr[i] = [];
return arr[index];
}
function getColumnIndex(line, genColumn) {
let index = line.length;
for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break;
return index;
}
function insert(array, index, value) {
for (let i = array.length; i > index; i--) array[i] = array[i - 1];
array[index] = value;
}
function removeEmptyFinalLines(mappings) {
const { length } = mappings;
let len = length;
for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
if (len < length) mappings.length = len;
}
function skipSourceless(line, index) {
if (index === 0) return true;
return line[index - 1].length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
if (index === 0) return false;
const prev = line[index - 1];
if (prev.length === 1) return false;
return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
}
//#endregion
export { toDecodedMap as a, decodedMappings as c, setSourceContent as i, traceSegment as l, maybeAddSegment as n, toEncodedMap as o, setIgnore as r, TraceMap as s, GenMapping as t, encode as u };

Sorry, the diff of this file is too big to display

import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
import { t as require_duplexer } from "./duplexer.mjs";
import fs from "node:fs";
import { promisify } from "node:util";
import zlib from "node:zlib";
import "node:stream";
//#region node_modules/.pnpm/gzip-size@7.0.0/node_modules/gzip-size/index.js
var import_duplexer = /* @__PURE__ */ __toESM(require_duplexer(), 1);
const getOptions = (options) => ({
level: 9,
...options
});
const gzip = promisify(zlib.gzip);
async function gzipSize(input, options) {
if (!input) return 0;
return (await gzip(input, getOptions(options))).length;
}
//#endregion
export { gzipSize as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
import { t as require_function_bind } from "./function-bind.mjs";
//#region node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js
var require_hasown = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js": ((exports, module) => {
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = require_function_bind();
/** @type {import('.')} */
module.exports = bind.call(call, $hasOwn);
}) });
//#endregion
export { require_hasown as t };
import http from "node:http";
import https from "node:https";
import { EventEmitter } from "node:events";
//#region node_modules/.pnpm/httpxy@0.1.7/node_modules/httpxy/dist/index.mjs
const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
const isSSL = /^https|wss/;
function setupOutgoing(outgoing, options, req, forward) {
outgoing.port = options[forward || "target"].port || (isSSL.test(options[forward || "target"].protocol) ? 443 : 80);
for (const e of [
"host",
"hostname",
"socketPath",
"pfx",
"key",
"passphrase",
"cert",
"ca",
"ciphers",
"secureProtocol"
]) outgoing[e] = options[forward || "target"][e];
outgoing.method = options.method || req.method;
outgoing.headers = { ...req.headers };
if (options.headers) outgoing.headers = {
...outgoing.headers,
...options.headers
};
if (options.auth) outgoing.auth = options.auth;
if (options.ca) outgoing.ca = options.ca;
if (isSSL.test(options[forward || "target"].protocol)) outgoing.rejectUnauthorized = options.secure === void 0 ? true : options.secure;
outgoing.agent = options.agent || false;
outgoing.localAddress = options.localAddress;
if (!outgoing.agent) {
outgoing.headers = outgoing.headers || {};
if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) outgoing.headers.connection = "close";
}
const target = options[forward || "target"];
const targetPath = target && options.prependPath !== false ? target.pathname || target.path || "" : "";
const parsed = new URL(req.url, "http://localhost");
let outgoingPath = options.toProxy ? req.url : parsed.pathname + parsed.search || "";
outgoingPath = options.ignorePath ? "" : outgoingPath;
outgoing.path = joinURL(targetPath, outgoingPath);
if (options.changeOrigin) outgoing.headers.host = requiresPort(outgoing.port, options[forward || "target"].protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
return outgoing;
}
function joinURL(base, path) {
if (!base || base === "/") return path || "/";
if (!path || path === "/") return base || "/";
const baseHasTrailing = base[base.length - 1] === "/";
const pathHasLeading = path[0] === "/";
if (baseHasTrailing && pathHasLeading) return base + path.slice(1);
if (!baseHasTrailing && !pathHasLeading) return base + "/" + path;
return base + path;
}
function setupSocket(socket) {
socket.setTimeout(0);
socket.setNoDelay(true);
socket.setKeepAlive(true, 0);
return socket;
}
function getPort(req) {
const res = req.headers.host ? req.headers.host.match(/:(\d+)/) : "";
if (res) return res[1];
return hasEncryptedConnection(req) ? "443" : "80";
}
function hasEncryptedConnection(req) {
return Boolean(req.connection.encrypted || req.connection.pair);
}
function rewriteCookieProperty(header, config, property) {
if (Array.isArray(header)) return header.map(function(headerElement) {
return rewriteCookieProperty(headerElement, config, property);
});
return header.replace(new RegExp(String.raw`(;\s*` + property + "=)([^;]+)", "i"), function(match, prefix, previousValue) {
let newValue;
if (previousValue in config) newValue = config[previousValue];
else if ("*" in config) newValue = config["*"];
else return match;
return newValue ? prefix + newValue : "";
});
}
function hasPort(host) {
return !!~host.indexOf(":");
}
function requiresPort(_port, _protocol) {
const protocol = _protocol.split(":")[0];
const port = +_port;
if (!port) return false;
switch (protocol) {
case "http":
case "ws": return port !== 80;
case "https":
case "wss": return port !== 443;
case "ftp": return port !== 21;
case "gopher": return port !== 70;
case "file": return false;
}
return port !== 0;
}
function defineProxyMiddleware(m) {
return m;
}
function defineProxyOutgoingMiddleware(m) {
return m;
}
const redirectRegex = /^201|30([1278])$/;
const webOutgoingMiddleware = [
defineProxyOutgoingMiddleware((req, res, proxyRes) => {
if (req.httpVersion === "1.0") delete proxyRes.headers["transfer-encoding"];
}),
defineProxyOutgoingMiddleware((req, res, proxyRes) => {
if (req.httpVersion === "1.0") proxyRes.headers.connection = req.headers.connection || "close";
else if (req.httpVersion !== "2.0" && !proxyRes.headers.connection) proxyRes.headers.connection = req.headers.connection || "keep-alive";
}),
defineProxyOutgoingMiddleware((req, res, proxyRes, options) => {
if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers.location && redirectRegex.test(String(proxyRes.statusCode))) {
const target = new URL(options.target);
const u = new URL(proxyRes.headers.location);
if (target.host !== u.host) return;
if (options.hostRewrite) u.host = options.hostRewrite;
else if (options.autoRewrite) u.host = req.headers.host;
if (options.protocolRewrite) u.protocol = options.protocolRewrite;
proxyRes.headers.location = u.toString();
}
}),
defineProxyOutgoingMiddleware((req, res, proxyRes, options) => {
let rewriteCookieDomainConfig = options.cookieDomainRewrite;
let rewriteCookiePathConfig = options.cookiePathRewrite;
const preserveHeaderKeyCase = options.preserveHeaderKeyCase;
let rawHeaderKeyMap;
const setHeader = function(key, header) {
if (header === void 0) return;
if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") header = rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") header = rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
res.setHeader(String(key).trim(), header);
};
if (typeof rewriteCookieDomainConfig === "string") rewriteCookieDomainConfig = { "*": rewriteCookieDomainConfig };
if (typeof rewriteCookiePathConfig === "string") rewriteCookiePathConfig = { "*": rewriteCookiePathConfig };
if (preserveHeaderKeyCase && proxyRes.rawHeaders !== void 0) {
rawHeaderKeyMap = {};
for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
const key = proxyRes.rawHeaders[i];
rawHeaderKeyMap[key.toLowerCase()] = key;
}
}
for (let key of Object.keys(proxyRes.headers)) {
const header = proxyRes.headers[key];
if (preserveHeaderKeyCase && rawHeaderKeyMap) key = rawHeaderKeyMap[key] || key;
setHeader(key, header);
}
}),
defineProxyOutgoingMiddleware((req, res, proxyRes) => {
if (proxyRes.statusMessage) {
res.statusCode = proxyRes.statusCode;
res.statusMessage = proxyRes.statusMessage;
} else res.statusCode = proxyRes.statusCode;
})
];
const nativeAgents = {
http,
https
};
const webIncomingMiddleware = [
defineProxyMiddleware((req) => {
if ((req.method === "DELETE" || req.method === "OPTIONS") && !req.headers["content-length"]) {
req.headers["content-length"] = "0";
delete req.headers["transfer-encoding"];
}
}),
defineProxyMiddleware((req, res, options) => {
if (options.timeout) req.socket.setTimeout(options.timeout);
}),
defineProxyMiddleware((req, res, options) => {
if (!options.xfwd) return;
const encrypted = req.isSpdy || hasEncryptedConnection(req);
const values = {
for: req.connection.remoteAddress || req.socket.remoteAddress,
port: getPort(req),
proto: encrypted ? "https" : "http"
};
for (const header of [
"for",
"port",
"proto"
]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers.host || "";
}),
defineProxyMiddleware((req, res, options, server, head, callback) => {
server.emit("start", req, res, options.target || options.forward);
const agents = nativeAgents;
const http$1 = agents.http;
const https$1 = agents.https;
if (options.forward) {
const forwardReq = (options.forward.protocol === "https:" ? https$1 : http$1).request(setupOutgoing(options.ssl || {}, options, req, "forward"));
const forwardError = createErrorHandler(forwardReq, options.forward);
req.on("error", forwardError);
forwardReq.on("error", forwardError);
(options.buffer || req).pipe(forwardReq);
if (!options.target) {
res.end();
return;
}
}
const proxyReq = (options.target.protocol === "https:" ? https$1 : http$1).request(setupOutgoing(options.ssl || {}, options, req));
proxyReq.on("socket", (socket) => {
if (server && !proxyReq.getHeader("expect")) server.emit("proxyReq", proxyReq, req, res, options);
});
if (options.proxyTimeout) proxyReq.setTimeout(options.proxyTimeout, function() {
proxyReq.abort();
});
req.on("aborted", function() {
proxyReq.abort();
});
const proxyError = createErrorHandler(proxyReq, options.target);
req.on("error", proxyError);
proxyReq.on("error", proxyError);
function createErrorHandler(proxyReq2, url) {
return function proxyError2(err) {
if (req.socket.destroyed && err.code === "ECONNRESET") {
server.emit("econnreset", err, req, res, url);
return proxyReq2.abort();
}
if (callback) callback(err, req, res, url);
else server.emit("error", err, req, res, url);
};
}
(options.buffer || req).pipe(proxyReq);
proxyReq.on("response", function(proxyRes) {
if (server) server.emit("proxyRes", proxyRes, req, res);
if (!res.headersSent && !options.selfHandleResponse) {
for (const pass of webOutgoingMiddleware) if (pass(req, res, proxyRes, options)) break;
}
if (res.finished) {
if (server) server.emit("end", req, res, proxyRes);
} else {
res.on("close", function() {
proxyRes.destroy();
});
proxyRes.on("end", function() {
if (server) server.emit("end", req, res, proxyRes);
});
if (!options.selfHandleResponse) proxyRes.pipe(res);
}
});
})
];
const websocketIncomingMiddleware = [
defineProxyMiddleware((req, socket) => {
if (req.method !== "GET" || !req.headers.upgrade) {
socket.destroy();
return true;
}
if (req.headers.upgrade.toLowerCase() !== "websocket") {
socket.destroy();
return true;
}
}),
defineProxyMiddleware((req, socket, options) => {
if (!options.xfwd) return;
const values = {
for: req.connection.remoteAddress || req.socket.remoteAddress,
port: getPort(req),
proto: hasEncryptedConnection(req) ? "wss" : "ws"
};
for (const header of [
"for",
"port",
"proto"
]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
}),
defineProxyMiddleware((req, socket, options, server, head, callback) => {
const createHttpHeader = function(line, headers) {
return Object.keys(headers).reduce(function(head2, key) {
const value = headers[key];
if (!Array.isArray(value)) {
head2.push(key + ": " + value);
return head2;
}
for (const element of value) head2.push(key + ": " + element);
return head2;
}, [line]).join("\r\n") + "\r\n\r\n";
};
setupSocket(socket);
if (head && head.length > 0) socket.unshift(head);
const proxyReq = (isSSL.test(options.target.protocol) ? https : http).request(setupOutgoing(options.ssl || {}, options, req));
if (server) server.emit("proxyReqWs", proxyReq, req, socket, options, head);
proxyReq.on("error", onOutgoingError);
proxyReq.on("response", function(res) {
if (!res.upgrade) {
socket.write(createHttpHeader("HTTP/" + res.httpVersion + " " + res.statusCode + " " + res.statusMessage, res.headers));
res.pipe(socket);
}
});
proxyReq.on("upgrade", function(proxyRes, proxySocket, proxyHead) {
proxySocket.on("error", onOutgoingError);
proxySocket.on("end", function() {
server.emit("close", proxyRes, proxySocket, proxyHead);
});
socket.on("error", function() {
proxySocket.end();
});
setupSocket(proxySocket);
if (proxyHead && proxyHead.length > 0) proxySocket.unshift(proxyHead);
socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
proxySocket.pipe(socket).pipe(proxySocket);
server.emit("open", proxySocket);
server.emit("proxySocket", proxySocket);
});
proxyReq.end();
function onOutgoingError(err) {
if (callback) callback(err, req, socket);
else server.emit("error", err, req, socket);
socket.end();
}
})
];
var ProxyServer = class extends EventEmitter {
_server;
_webPasses = [...webIncomingMiddleware];
_wsPasses = [...websocketIncomingMiddleware];
options;
web;
ws;
/**
* Creates the proxy server with specified options.
* @param options - Config object passed to the proxy
*/
constructor(options = {}) {
super();
this.options = options || {};
this.options.prependPath = options.prependPath !== false;
this.web = _createProxyFn("web", this);
this.ws = _createProxyFn("ws", this);
}
/**
* A function that wraps the object in a webserver, for your convenience
* @param port - Port to listen on
* @param hostname - The hostname to listen on
*/
listen(port, hostname) {
const closure = (req, res) => {
this.web(req, res);
};
this._server = this.options.ssl ? https.createServer(this.options.ssl, closure) : http.createServer(closure);
if (this.options.ws) this._server.on("upgrade", (req, socket, head) => {
this._ws(req, socket, head);
});
this._server.listen(port, hostname);
return this;
}
/**
* A function that closes the inner webserver and stops listening on given port
*/
close(callback) {
if (this._server) this._server.close((...args) => {
this._server = void 0;
if (callback) Reflect.apply(callback, void 0, args);
});
}
before(type, passName, pass) {
if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
const passes = type === "ws" ? this._wsPasses : this._webPasses;
let i = false;
for (const [idx, v] of passes.entries()) if (v.name === passName) i = idx;
if (i === false) throw new Error("No such pass");
passes.splice(i, 0, pass);
}
after(type, passName, pass) {
if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
const passes = type === "ws" ? this._wsPasses : this._webPasses;
let i = false;
for (const [idx, v] of passes.entries()) if (v.name === passName) i = idx;
if (i === false) throw new Error("No such pass");
passes.splice(i++, 0, pass);
}
};
function createProxyServer(options = {}) {
return new ProxyServer(options);
}
function _createProxyFn(type, server) {
return function(req, res, opts, head) {
const requestOptions = {
...opts,
...server.options
};
for (const key of ["target", "forward"]) if (typeof requestOptions[key] === "string") requestOptions[key] = new URL(requestOptions[key]);
if (!requestOptions.target && !requestOptions.forward) return this.emit("error", /* @__PURE__ */ new Error("Must provide a proper URL as target"));
let _resolve;
let _reject;
const callbackPromise = new Promise((resolve, reject) => {
_resolve = resolve;
_reject = reject;
});
res.on("close", () => {
_resolve();
});
res.on("error", (error) => {
_reject(error);
});
for (const pass of type === "ws" ? server._wsPasses : server._webPasses) if (pass(req, res, requestOptions, server, head, (error) => {
_reject(error);
})) {
_resolve();
break;
}
return callbackPromise;
};
}
//#endregion
export { createProxyServer as n, ProxyServer as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
import { t as require_hasown } from "./hasown.mjs";
//#region node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/core.json
var require_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/core.json": ((exports, module) => {
module.exports = {
"assert": true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
"async_hooks": ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
"buffer_ieee754": ">= 0.5 && < 0.9.7",
"buffer": true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
"child_process": true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
"cluster": ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
"console": true,
"node:console": [">= 14.18 && < 15", ">= 16"],
"constants": true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
"crypto": true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
"_debug_agent": ">= 1 && < 8",
"_debugger": "< 8",
"dgram": true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
"diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
"dns": true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
"domain": ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
"events": true,
"node:events": [">= 14.18 && < 15", ">= 16"],
"freelist": "< 6",
"fs": true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
"_http_agent": ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
"_http_client": ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
"_http_common": ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
"_http_incoming": ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
"_http_outgoing": ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
"_http_server": ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
"http": true,
"node:http": [">= 14.18 && < 15", ">= 16"],
"http2": ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
"https": true,
"node:https": [">= 14.18 && < 15", ">= 16"],
"inspector": ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
"_linklist": "< 8",
"module": true,
"node:module": [">= 14.18 && < 15", ">= 16"],
"net": true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
"os": true,
"node:os": [">= 14.18 && < 15", ">= 16"],
"path": true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
"perf_hooks": ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
"process": ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
"punycode": ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
"querystring": true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
"readline": true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
"repl": true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
"node:sea": [">= 20.12 && < 21", ">= 21.7"],
"smalloc": ">= 0.11.5 && < 3",
"node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
"_stream_duplex": ">= 0.9.4",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
"_stream_transform": ">= 0.9.4",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
"_stream_wrap": ">= 1.4.1",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
"_stream_passthrough": ">= 0.9.4",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
"_stream_readable": ">= 0.9.4",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
"_stream_writable": ">= 0.9.4",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
"stream": true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
"string_decoder": true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
"sys": [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [
">= 18.17 && < 19",
">= 19.9",
">= 20"
],
"test/mock_loader": ">= 22.3 && < 22.7",
"node:test/mock_loader": ">= 22.3 && < 22.7",
"node:test": [">= 16.17 && < 17", ">= 18"],
"timers": true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
"_tls_common": ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
"_tls_legacy": ">= 0.11.3 && < 10",
"_tls_wrap": ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
"tls": true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
"trace_events": ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
"tty": true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
"url": true,
"node:url": [">= 14.18 && < 15", ">= 16"],
"util": true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8": ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
"vm": true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
"wasi": [
">= 13.4 && < 13.5",
">= 18.17 && < 19",
">= 20"
],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
"worker_threads": ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
"zlib": ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}) });
//#endregion
//#region node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/index.js
var require_is_core_module = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/index.js": ((exports, module) => {
var hasOwn = require_hasown();
function specifierIncluded(current, specifier) {
var nodeParts = current.split(".");
var parts = specifier.split(" ");
var op = parts.length > 1 ? parts[0] : "=";
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split(".");
for (var i = 0; i < 3; ++i) {
var cur = parseInt(nodeParts[i] || 0, 10);
var ver = parseInt(versionParts[i] || 0, 10);
if (cur === ver) continue;
if (op === "<") return cur < ver;
if (op === ">=") return cur >= ver;
return false;
}
return op === ">=";
}
function matchesRange(current, range) {
var specifiers = range.split(/ ?&& ?/);
if (specifiers.length === 0) return false;
for (var i = 0; i < specifiers.length; ++i) if (!specifierIncluded(current, specifiers[i])) return false;
return true;
}
function versionIncluded(nodeVersion, specifierValue) {
if (typeof specifierValue === "boolean") return specifierValue;
var current = typeof nodeVersion === "undefined" ? process.versions && process.versions.node : nodeVersion;
if (typeof current !== "string") throw new TypeError(typeof nodeVersion === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required");
if (specifierValue && typeof specifierValue === "object") {
for (var i = 0; i < specifierValue.length; ++i) if (matchesRange(current, specifierValue[i])) return true;
return false;
}
return matchesRange(current, specifierValue);
}
var data = require_core();
module.exports = function isCore(x, nodeVersion) {
return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]);
};
}) });
//#endregion
export { require_is_core_module as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/is-module@1.0.0/node_modules/is-module/index.js
var require_is_module = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-module@1.0.0/node_modules/is-module/index.js": ((exports, module) => {
var ES6ImportExportRegExp = /(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/;
var ES6AliasRegExp = /(?:^\s*|[}{\(\);,\n]\s*)(export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)"))/;
module.exports = function(sauce) {
return ES6ImportExportRegExp.test(sauce) || ES6AliasRegExp.test(sauce);
};
}) });
//#endregion
export { require_is_module as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js
var require_is_reference = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js": ((exports, module) => {
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = global || self, global.isReference = factory());
})(exports, (function() {
function isReference(node, parent) {
if (node.type === "MemberExpression") return !node.computed && isReference(node.object, node);
if (node.type === "Identifier") {
if (!parent) return true;
switch (parent.type) {
case "MemberExpression": return parent.computed || node === parent.object;
case "MethodDefinition": return parent.computed;
case "FieldDefinition": return parent.computed || node === parent.value;
case "Property": return parent.computed || node === parent.value;
case "ExportSpecifier":
case "ImportSpecifier": return node === parent.local;
case "LabeledStatement":
case "BreakStatement":
case "ContinueStatement": return false;
default: return true;
}
}
return false;
}
return isReference;
}));
}) });
//#endregion
export { require_is_reference as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js
var require_js_tokens = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js": ((exports, module) => {
var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy;
StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
HashbangComment = /^#!.*/;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
module.exports = function* (input, { jsx = false } = {}) {
var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
({length} = input);
lastIndex = 0;
lastSignificantToken = "";
stack = [{ tag: "JS" }];
braces = [];
parenNesting = 0;
postfixIncDec = false;
if (match = HashbangComment.exec(input)) {
yield {
type: "HashbangComment",
value: match[0]
};
lastIndex = match[0].length;
}
while (lastIndex < length) {
mode = stack[stack.length - 1];
switch (mode.tag) {
case "JS":
case "JSNonExpressionParen":
case "InterpolationInTemplate":
case "InterpolationInJSX":
if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
RegularExpressionLiteral.lastIndex = lastIndex;
if (match = RegularExpressionLiteral.exec(input)) {
lastIndex = RegularExpressionLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "RegularExpressionLiteral",
value: match[0],
closed: match[1] !== void 0 && match[1] !== "\\"
};
continue;
}
}
Punctuator.lastIndex = lastIndex;
if (match = Punctuator.exec(input)) {
punctuator = match[0];
nextLastIndex = Punctuator.lastIndex;
nextLastSignificantToken = punctuator;
switch (punctuator) {
case "(":
if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({
tag: "JSNonExpressionParen",
nesting: parenNesting
});
parenNesting++;
postfixIncDec = false;
break;
case ")":
parenNesting--;
postfixIncDec = true;
if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
stack.pop();
nextLastSignificantToken = "?NonExpressionParenEnd";
postfixIncDec = false;
}
break;
case "{":
Punctuator.lastIndex = 0;
isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
braces.push(isExpression);
postfixIncDec = false;
break;
case "}":
switch (mode.tag) {
case "InterpolationInTemplate":
if (braces.length === mode.nesting) {
Template.lastIndex = lastIndex;
match = Template.exec(input);
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
postfixIncDec = false;
yield {
type: "TemplateMiddle",
value: match[0]
};
} else {
stack.pop();
postfixIncDec = true;
yield {
type: "TemplateTail",
value: match[0],
closed: match[1] === "`"
};
}
continue;
}
break;
case "InterpolationInJSX": if (braces.length === mode.nesting) {
stack.pop();
lastIndex += 1;
lastSignificantToken = "}";
yield {
type: "JSXPunctuator",
value: "}"
};
continue;
}
}
postfixIncDec = braces.pop();
nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
break;
case "]":
postfixIncDec = true;
break;
case "++":
case "--":
nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
break;
case "<":
if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
stack.push({ tag: "JSXTag" });
lastIndex += 1;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: punctuator
};
continue;
}
postfixIncDec = false;
break;
default: postfixIncDec = false;
}
lastIndex = nextLastIndex;
lastSignificantToken = nextLastSignificantToken;
yield {
type: "Punctuator",
value: punctuator
};
continue;
}
Identifier.lastIndex = lastIndex;
if (match = Identifier.exec(input)) {
lastIndex = Identifier.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "for":
case "if":
case "while":
case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword";
}
lastSignificantToken = nextLastSignificantToken;
postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
yield {
type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
value: match[0]
};
continue;
}
StringLiteral.lastIndex = lastIndex;
if (match = StringLiteral.exec(input)) {
lastIndex = StringLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "StringLiteral",
value: match[0],
closed: match[2] !== void 0
};
continue;
}
NumericLiteral.lastIndex = lastIndex;
if (match = NumericLiteral.exec(input)) {
lastIndex = NumericLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield {
type: "NumericLiteral",
value: match[0]
};
continue;
}
Template.lastIndex = lastIndex;
if (match = Template.exec(input)) {
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
stack.push({
tag: "InterpolationInTemplate",
nesting: braces.length
});
postfixIncDec = false;
yield {
type: "TemplateHead",
value: match[0]
};
} else {
postfixIncDec = true;
yield {
type: "NoSubstitutionTemplate",
value: match[0],
closed: match[1] === "`"
};
}
continue;
}
break;
case "JSXTag":
case "JSXTagEnd":
JSXPunctuator.lastIndex = lastIndex;
if (match = JSXPunctuator.exec(input)) {
lastIndex = JSXPunctuator.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "<":
stack.push({ tag: "JSXTag" });
break;
case ">":
stack.pop();
if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
nextLastSignificantToken = "?JSX";
postfixIncDec = true;
} else stack.push({ tag: "JSXChildren" });
break;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
nextLastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
break;
case "/": if (lastSignificantToken === "<") {
stack.pop();
if (stack[stack.length - 1].tag === "JSXChildren") stack.pop();
stack.push({ tag: "JSXTagEnd" });
}
}
lastSignificantToken = nextLastSignificantToken;
yield {
type: "JSXPunctuator",
value: match[0]
};
continue;
}
JSXIdentifier.lastIndex = lastIndex;
if (match = JSXIdentifier.exec(input)) {
lastIndex = JSXIdentifier.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXIdentifier",
value: match[0]
};
continue;
}
JSXString.lastIndex = lastIndex;
if (match = JSXString.exec(input)) {
lastIndex = JSXString.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXString",
value: match[0],
closed: match[2] !== void 0
};
continue;
}
break;
case "JSXChildren":
JSXText.lastIndex = lastIndex;
if (match = JSXText.exec(input)) {
lastIndex = JSXText.lastIndex;
lastSignificantToken = match[0];
yield {
type: "JSXText",
value: match[0]
};
continue;
}
switch (input[lastIndex]) {
case "<":
stack.push({ tag: "JSXTag" });
lastIndex++;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: "<"
};
continue;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
lastIndex++;
lastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
yield {
type: "JSXPunctuator",
value: "{"
};
continue;
}
}
WhiteSpace.lastIndex = lastIndex;
if (match = WhiteSpace.exec(input)) {
lastIndex = WhiteSpace.lastIndex;
yield {
type: "WhiteSpace",
value: match[0]
};
continue;
}
LineTerminatorSequence.lastIndex = lastIndex;
if (match = LineTerminatorSequence.exec(input)) {
lastIndex = LineTerminatorSequence.lastIndex;
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
yield {
type: "LineTerminatorSequence",
value: match[0]
};
continue;
}
MultiLineComment.lastIndex = lastIndex;
if (match = MultiLineComment.exec(input)) {
lastIndex = MultiLineComment.lastIndex;
if (Newline.test(match[0])) {
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
}
yield {
type: "MultiLineComment",
value: match[0],
closed: match[1] !== void 0
};
continue;
}
SingleLineComment.lastIndex = lastIndex;
if (match = SingleLineComment.exec(input)) {
lastIndex = SingleLineComment.lastIndex;
postfixIncDec = false;
yield {
type: "SingleLineComment",
value: match[0]
};
continue;
}
firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
lastIndex += firstCodePoint.length;
lastSignificantToken = firstCodePoint;
postfixIncDec = false;
yield {
type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
value: firstCodePoint
};
}
};
}) });
//#endregion
export { require_js_tokens as t };
//#region node_modules/.pnpm/klona@2.0.6/node_modules/klona/full/index.mjs
function set(obj, key, val) {
if (typeof val.value === "object") val.value = klona(val.value);
if (!val.enumerable || val.get || val.set || !val.configurable || !val.writable || key === "__proto__") Object.defineProperty(obj, key, val);
else obj[key] = val.value;
}
function klona(x) {
if (typeof x !== "object") return x;
var i = 0, k, list, tmp, str = Object.prototype.toString.call(x);
if (str === "[object Object]") tmp = Object.create(x.__proto__ || null);
else if (str === "[object Array]") tmp = Array(x.length);
else if (str === "[object Set]") {
tmp = /* @__PURE__ */ new Set();
x.forEach(function(val) {
tmp.add(klona(val));
});
} else if (str === "[object Map]") {
tmp = /* @__PURE__ */ new Map();
x.forEach(function(val, key) {
tmp.set(klona(key), klona(val));
});
} else if (str === "[object Date]") tmp = /* @__PURE__ */ new Date(+x);
else if (str === "[object RegExp]") tmp = new RegExp(x.source, x.flags);
else if (str === "[object DataView]") tmp = new x.constructor(klona(x.buffer));
else if (str === "[object ArrayBuffer]") tmp = x.slice(0);
else if (str.slice(-6) === "Array]") tmp = new x.constructor(x);
if (tmp) {
for (list = Object.getOwnPropertySymbols(x); i < list.length; i++) set(tmp, list[i], Object.getOwnPropertyDescriptor(x, list[i]));
for (i = 0, list = Object.getOwnPropertyNames(x); i < list.length; i++) {
if (Object.hasOwnProperty.call(tmp, k = list[i]) && tmp[k] === x[k]) continue;
set(tmp, k, Object.getOwnPropertyDescriptor(x, k));
}
}
return tmp || x;
}
//#endregion
export { klona as t };
//#region node_modules/.pnpm/knitwork@1.2.0/node_modules/knitwork/dist/index.mjs
function genString(input, options = {}) {
const str = JSON.stringify(input);
if (!options.singleQuotes) return str;
return `'${escapeString(str).slice(1, -1)}'`;
}
const NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/;
const QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g;
const BACKSLASH_RE = /\\/g;
function escapeString(id) {
if (!NEEDS_ESCAPE_RE.test(id)) return id;
return id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1");
}
function genSafeVariableName(name) {
if (reservedNames.has(name)) return `_${name}`;
return name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0));
}
const reservedNames = /* @__PURE__ */ new Set([
"Infinity",
"NaN",
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"undefined",
"var",
"void",
"while",
"with",
"yield"
]);
function _genStatement(type, specifier, names, options = {}) {
const specifierString = genString(specifier, options);
if (!names) return `${type} ${specifierString};`;
const nameArray = Array.isArray(names);
const namesString = (nameArray ? names : [names]).map((index) => {
if (typeof index === "string") return { name: index };
if (index.name === index.as) index = { name: index.name };
return index;
}).map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", ");
if (nameArray) return `${type} { ${namesString} } from ${genString(specifier, options)}${_genImportAttributes(type, options)};`;
return `${type} ${namesString} from ${genString(specifier, options)}${_genImportAttributes(type, options)};`;
}
function _genImportAttributes(type, options) {
if (type === "import type" || type === "export type") return "";
if (typeof options.attributes?.type === "string") return ` with { type: ${genString(options.attributes.type)} }`;
if (typeof options.assert?.type === "string") return ` assert { type: ${genString(options.assert.type)} }`;
return "";
}
function genImport(specifier, imports, options = {}) {
return _genStatement("import", specifier, imports, options);
}
function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = true) {
if (lines.length === 0) return delimiters;
const [start, end] = delimiters;
return `${start}
` + lines.join(withComma ? ",\n" : "\n") + `
${indent}${end}`;
}
const VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/;
function genObjectKey(key) {
return VALID_IDENTIFIER_RE.test(key) ? key : genString(key);
}
function genObjectFromRaw(object, indent = "", options = {}) {
return genObjectFromRawEntries(Object.entries(object), indent, options);
}
function genArrayFromRaw(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`), indent, "[]");
}
function genObjectFromRawEntries(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(array.map(([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`), indent, "{}");
}
function genRawValue(value, indent = "", options = {}) {
if (value === void 0) return "undefined";
if (value === null) return "null";
if (Array.isArray(value)) return genArrayFromRaw(value, indent, options);
if (value && typeof value === "object") return genObjectFromRaw(value, indent, options);
if (options.preserveTypes && typeof value !== "function") return JSON.stringify(value);
return value.toString();
}
//#endregion
export { genString as a, genSafeVariableName as i, genObjectFromRaw as n, genObjectKey as r, genImport as t };
import { C as isAbsolute$1, T as normalize$1, k as resolve$2, w as join$1 } from "./c12.mjs";
import { r as tokenizer } from "./acorn.mjs";
import { a as h, o as x } from "./confbox.mjs";
import { builtinModules, createRequire } from "node:module";
import path, { dirname, join, win32 } from "node:path";
import process$1 from "node:process";
import fs, { promises, realpathSync, statSync } from "node:fs";
import { joinURL } from "ufo";
import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
import assert from "node:assert";
import v8 from "node:v8";
import { format, inspect } from "node:util";
import fsp from "node:fs/promises";
//#region node_modules/.pnpm/pkg-types@1.3.1/node_modules/pkg-types/dist/index.mjs
const defaultFindOptions = {
startingFrom: ".",
rootPattern: /^node_modules$/,
reverse: false,
test: (filePath) => {
try {
if (statSync(filePath).isFile()) return true;
} catch {}
}
};
async function findFile(filename, _options = {}) {
const filenames = Array.isArray(filename) ? filename : [filename];
const options = {
...defaultFindOptions,
..._options
};
const basePath = resolve$2(options.startingFrom);
const leadingSlash = basePath[0] === "/";
const segments = basePath.split("/").filter(Boolean);
if (leadingSlash) segments[0] = "/" + segments[0];
let root = segments.findIndex((r) => r.match(options.rootPattern));
if (root === -1) root = 0;
if (options.reverse) for (let index = root + 1; index <= segments.length; index++) for (const filename2 of filenames) {
const filePath = join$1(...segments.slice(0, index), filename2);
if (await options.test(filePath)) return filePath;
}
else for (let index = segments.length; index > root; index--) for (const filename2 of filenames) {
const filePath = join$1(...segments.slice(0, index), filename2);
if (await options.test(filePath)) return filePath;
}
throw new Error(`Cannot find matching ${filename} in ${options.startingFrom} or parent directories`);
}
function findNearestFile(filename, _options = {}) {
return findFile(filename, _options);
}
const FileCache = /* @__PURE__ */ new Map();
async function readPackageJSON(id, options = {}) {
const resolvedPath = await resolvePackageJSON(id, options);
const cache$1 = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache;
if (options.cache && cache$1.has(resolvedPath)) return cache$1.get(resolvedPath);
const blob = await promises.readFile(resolvedPath, "utf8");
let parsed;
try {
parsed = x(blob);
} catch {
parsed = h(blob);
}
cache$1.set(resolvedPath, parsed);
return parsed;
}
async function resolvePackageJSON(id = process.cwd(), options = {}) {
return findNearestFile("package.json", {
startingFrom: isAbsolute$1(id) ? id : await resolvePath(id, options),
...options
});
}
//#endregion
//#region node_modules/.pnpm/mlly@1.8.0/node_modules/mlly/dist/index.mjs
const BUILTIN_MODULES = new Set(builtinModules);
function normalizeSlash(path$1) {
return path$1.replace(/\\/g, "/");
}
function matchAll(regex, string, addition) {
const matches = [];
for (const match of string.matchAll(regex)) matches.push({
...addition,
...match.groups,
code: match[0],
start: match.index,
end: (match.index || 0) + match[0].length
});
return matches;
}
function clearImports(imports) {
return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
}
function getImportNames(cleanedImports) {
const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
return {
namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1],
defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0
};
}
/**
* @typedef ErrnoExceptionFields
* @property {number | undefined} [errnode]
* @property {string | undefined} [code]
* @property {string | undefined} [path]
* @property {string | undefined} [syscall]
* @property {string | undefined} [url]
*
* @typedef {Error & ErrnoExceptionFields} ErrnoException
*/
const own$1 = {}.hasOwnProperty;
const classRegExp = /^([A-Z][a-z\d]*)+$/;
const kTypes = new Set([
"string",
"function",
"number",
"object",
"Function",
"Object",
"boolean",
"bigint",
"symbol"
]);
const codes = {};
/**
* Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
* We cannot use Intl.ListFormat because it's not available in
* --without-intl builds.
*
* @param {Array<string>} array
* An array of strings.
* @param {string} [type]
* The list type to be inserted before the last element.
* @returns {string}
*/
function formatList(array, type = "and") {
return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
}
/** @type {Map<string, MessageFunction | string>} */
const messages = /* @__PURE__ */ new Map();
const nodeInternalPrefix = "__node_internal_";
/** @type {number} */
let userStackTraceLimit;
codes.ERR_INVALID_ARG_TYPE = createError(
"ERR_INVALID_ARG_TYPE",
/**
* @param {string} name
* @param {Array<string> | string} expected
* @param {unknown} actual
*/
(name, expected, actual) => {
assert(typeof name === "string", "'name' must be a string");
if (!Array.isArray(expected)) expected = [expected];
let message = "The ";
if (name.endsWith(" argument")) message += `${name} `;
else {
const type = name.includes(".") ? "property" : "argument";
message += `"${name}" ${type} `;
}
message += "must be ";
/** @type {Array<string>} */
const types = [];
/** @type {Array<string>} */
const instances = [];
/** @type {Array<string>} */
const other = [];
for (const value of expected) {
assert(typeof value === "string", "All expected entries have to be of type string");
if (kTypes.has(value)) types.push(value.toLowerCase());
else if (classRegExp.exec(value) === null) {
assert(value !== "object", "The value \"object\" should be written as \"Object\"");
other.push(value);
} else instances.push(value);
}
if (instances.length > 0) {
const pos = types.indexOf("object");
if (pos !== -1) {
types.slice(pos, 1);
instances.push("Object");
}
}
if (types.length > 0) {
message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
if (instances.length > 0 || other.length > 0) message += " or ";
}
if (instances.length > 0) {
message += `an instance of ${formatList(instances, "or")}`;
if (other.length > 0) message += " or ";
}
if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
else {
if (other[0].toLowerCase() !== other[0]) message += "an ";
message += `${other[0]}`;
}
message += `. Received ${determineSpecificType(actual)}`;
return message;
},
TypeError
);
codes.ERR_INVALID_MODULE_SPECIFIER = createError(
"ERR_INVALID_MODULE_SPECIFIER",
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request, reason, base = void 0) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
},
TypeError
);
codes.ERR_INVALID_PACKAGE_CONFIG = createError(
"ERR_INVALID_PACKAGE_CONFIG",
/**
* @param {string} path
* @param {string} [base]
* @param {string} [message]
*/
(path$1, base, message) => {
return `Invalid package config ${path$1}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
},
Error
);
codes.ERR_INVALID_PACKAGE_TARGET = createError(
"ERR_INVALID_PACKAGE_TARGET",
/**
* @param {string} packagePath
* @param {string} key
* @param {unknown} target
* @param {boolean} [isImport=false]
* @param {string} [base]
*/
(packagePath, key, target, isImport = false, base = void 0) => {
const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
if (key === ".") {
assert(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
}
return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
},
Error
);
codes.ERR_MODULE_NOT_FOUND = createError(
"ERR_MODULE_NOT_FOUND",
/**
* @param {string} path
* @param {string} base
* @param {boolean} [exactUrl]
*/
(path$1, base, exactUrl = false) => {
return `Cannot find ${exactUrl ? "module" : "package"} '${path$1}' imported from ${base}`;
},
Error
);
codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
/**
* @param {string} specifier
* @param {string} packagePath
* @param {string} base
*/
(specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
},
TypeError
);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
"ERR_PACKAGE_PATH_NOT_EXPORTED",
/**
* @param {string} packagePath
* @param {string} subpath
* @param {string} [base]
*/
(packagePath, subpath, base = void 0) => {
if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
},
Error
);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
"ERR_UNKNOWN_FILE_EXTENSION",
/**
* @param {string} extension
* @param {string} path
*/
(extension, path$1) => {
return `Unknown file extension "${extension}" for ${path$1}`;
},
TypeError
);
codes.ERR_INVALID_ARG_VALUE = createError(
"ERR_INVALID_ARG_VALUE",
/**
* @param {string} name
* @param {unknown} value
* @param {string} [reason='is invalid']
*/
(name, value, reason = "is invalid") => {
let inspected = inspect(value);
if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
},
TypeError
);
/**
* Utility function for registering the error codes. Only used here. Exported
* *only* to allow for testing.
* @param {string} sym
* @param {MessageFunction | string} value
* @param {ErrorConstructor} constructor
* @returns {new (...parameters: Array<any>) => Error}
*/
function createError(sym, value, constructor) {
messages.set(sym, value);
return makeNodeErrorWithCode(constructor, sym);
}
/**
* @param {ErrorConstructor} Base
* @param {string} key
* @returns {ErrorConstructor}
*/
function makeNodeErrorWithCode(Base, key) {
return NodeError;
/**
* @param {Array<unknown>} parameters
*/
function NodeError(...parameters) {
const limit = Error.stackTraceLimit;
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
const error = new Base();
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
const message = getMessage(key, parameters, error);
Object.defineProperties(error, {
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
}
});
captureLargerStackTrace(error);
error.code = key;
return error;
}
}
/**
* @returns {boolean}
*/
function isErrorStackTraceLimitWritable() {
try {
if (v8.startupSnapshot.isBuildingSnapshot()) return false;
} catch {}
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
if (desc === void 0) return Object.isExtensible(Error);
return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
}
/**
* This function removes unnecessary frames from Node.js core errors.
* @template {(...parameters: unknown[]) => unknown} T
* @param {T} wrappedFunction
* @returns {T}
*/
function hideStackFrames(wrappedFunction) {
const hidden = nodeInternalPrefix + wrappedFunction.name;
Object.defineProperty(wrappedFunction, "name", { value: hidden });
return wrappedFunction;
}
const captureLargerStackTrace = hideStackFrames(
/**
* @param {Error} error
* @returns {Error}
*/
function(error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
return error;
}
);
/**
* @param {string} key
* @param {Array<unknown>} parameters
* @param {Error} self
* @returns {string}
*/
function getMessage(key, parameters, self) {
const message = messages.get(key);
assert(message !== void 0, "expected `message` to be found");
if (typeof message === "function") {
assert(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
return Reflect.apply(message, self, parameters);
}
const regex = /%[dfijoOs]/g;
let expectedLength = 0;
while (regex.exec(message) !== null) expectedLength++;
assert(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
if (parameters.length === 0) return message;
parameters.unshift(message);
return Reflect.apply(format, null, parameters);
}
/**
* Determine the specific type of a value for type-mismatch errors.
* @param {unknown} value
* @returns {string}
*/
function determineSpecificType(value) {
if (value === null || value === void 0) return String(value);
if (typeof value === "function" && value.name) return `function ${value.name}`;
if (typeof value === "object") {
if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
return `${inspect(value, { depth: -1 })}`;
}
let inspected = inspect(value, { colors: false });
if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
return `type ${typeof value} (${inspected})`;
}
const hasOwnProperty$1 = {}.hasOwnProperty;
const { ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 } = codes;
/** @type {Map<string, PackageConfig>} */
const cache = /* @__PURE__ */ new Map();
/**
* @param {string} jsonPath
* @param {{specifier: URL | string, base?: URL}} options
* @returns {PackageConfig}
*/
function read(jsonPath, { base, specifier }) {
const existing = cache.get(jsonPath);
if (existing) return existing;
/** @type {string | undefined} */
let string;
try {
string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
} catch (error) {
const exception = error;
if (exception.code !== "ENOENT") throw exception;
}
/** @type {PackageConfig} */
const result = {
exists: false,
pjsonPath: jsonPath,
main: void 0,
name: void 0,
type: "none",
exports: void 0,
imports: void 0
};
if (string !== void 0) {
/** @type {Record<string, unknown>} */
let parsed;
try {
parsed = JSON.parse(string);
} catch (error_) {
const cause = error_;
const error = new ERR_INVALID_PACKAGE_CONFIG$1(jsonPath, (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier), cause.message);
error.cause = cause;
throw error;
}
result.exists = true;
if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") result.name = parsed.name;
if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") result.main = parsed.main;
if (hasOwnProperty$1.call(parsed, "exports")) result.exports = parsed.exports;
if (hasOwnProperty$1.call(parsed, "imports")) result.imports = parsed.imports;
if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) result.type = parsed.type;
}
cache.set(jsonPath, result);
return result;
}
/**
* @param {URL | string} resolved
* @returns {PackageConfig}
*/
function getPackageScopeConfig(resolved) {
let packageJSONUrl = new URL("package.json", resolved);
while (true) {
if (packageJSONUrl.pathname.endsWith("node_modules/package.json")) break;
const packageConfig = read(fileURLToPath(packageJSONUrl), { specifier: resolved });
if (packageConfig.exists) return packageConfig;
const lastPackageJSONUrl = packageJSONUrl;
packageJSONUrl = new URL("../package.json", packageJSONUrl);
if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
}
return {
pjsonPath: fileURLToPath(packageJSONUrl),
exists: false,
type: "none"
};
}
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
* @returns {PackageType}
*/
function getPackageType(url) {
return getPackageScopeConfig(url).type;
}
const { ERR_UNKNOWN_FILE_EXTENSION } = codes;
const hasOwnProperty = {}.hasOwnProperty;
/** @type {Record<string, string>} */
const extensionFormatMap = {
__proto__: null,
".cjs": "commonjs",
".js": "module",
".json": "json",
".mjs": "module"
};
/**
* @param {string | null} mime
* @returns {string | null}
*/
function mimeToFormat(mime) {
if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return "module";
if (mime === "application/json") return "json";
return null;
}
/**
* @callback ProtocolHandler
* @param {URL} parsed
* @param {{parentURL: string, source?: Buffer}} context
* @param {boolean} ignoreErrors
* @returns {string | null | void}
*/
/**
* @type {Record<string, ProtocolHandler>}
*/
const protocolHandlers = {
__proto__: null,
"data:": getDataProtocolModuleFormat,
"file:": getFileProtocolModuleFormat,
"http:": getHttpProtocolModuleFormat,
"https:": getHttpProtocolModuleFormat,
"node:"() {
return "builtin";
}
};
/**
* @param {URL} parsed
*/
function getDataProtocolModuleFormat(parsed) {
const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [
null,
null,
null
];
return mimeToFormat(mime);
}
/**
* Returns the file extension from a URL.
*
* Should give similar result to
* `require('node:path').extname(require('node:url').fileURLToPath(url))`
* when used with a `file:` URL.
*
* @param {URL} url
* @returns {string}
*/
function extname$2(url) {
const pathname = url.pathname;
let index = pathname.length;
while (index--) {
const code = pathname.codePointAt(index);
if (code === 47) return "";
if (code === 46) return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
}
return "";
}
/**
* @type {ProtocolHandler}
*/
function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
const value = extname$2(url);
if (value === ".js") {
const packageType = getPackageType(url);
if (packageType !== "none") return packageType;
return "commonjs";
}
if (value === "") {
const packageType = getPackageType(url);
if (packageType === "none" || packageType === "commonjs") return "commonjs";
return "module";
}
const format$1 = extensionFormatMap[value];
if (format$1) return format$1;
if (ignoreErrors) return;
throw new ERR_UNKNOWN_FILE_EXTENSION(value, fileURLToPath(url));
}
function getHttpProtocolModuleFormat() {}
/**
* @param {URL} url
* @param {{parentURL: string}} context
* @returns {string | null}
*/
function defaultGetFormatWithoutErrors(url, context) {
const protocol = url.protocol;
if (!hasOwnProperty.call(protocolHandlers, protocol)) return null;
return protocolHandlers[protocol](url, context, true) || null;
}
const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
const { ERR_INVALID_MODULE_SPECIFIER, ERR_INVALID_PACKAGE_CONFIG, ERR_INVALID_PACKAGE_TARGET, ERR_MODULE_NOT_FOUND, ERR_PACKAGE_IMPORT_NOT_DEFINED, ERR_PACKAGE_PATH_NOT_EXPORTED, ERR_UNSUPPORTED_DIR_IMPORT, ERR_UNSUPPORTED_RESOLVE_REQUEST } = codes;
const own = {}.hasOwnProperty;
const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
const deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
const invalidPackageNameRegEx = /^\.|%|\\/;
const patternRegEx = /\*/g;
const encodedSeparatorRegEx = /%2f|%5c/i;
/** @type {Set<string>} */
const emittedPackageWarnings = /* @__PURE__ */ new Set();
const doubleSlashRegEx = /[/\\]{2}/;
/**
*
* @param {string} target
* @param {string} request
* @param {string} match
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} base
* @param {boolean} isTarget
*/
function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
if (process$1.noDeprecation) return;
const pjsonPath = fileURLToPath(packageJsonUrl);
const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
process$1.emitWarning(`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}.`, "DeprecationWarning", "DEP0166");
}
/**
* @param {URL} url
* @param {URL} packageJsonUrl
* @param {URL} base
* @param {string} [main]
* @returns {void}
*/
function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
if (process$1.noDeprecation) return;
if (defaultGetFormatWithoutErrors(url, { parentURL: base.href }) !== "module") return;
const urlPath = fileURLToPath(url.href);
const packagePath = fileURLToPath(new URL$1(".", packageJsonUrl));
const basePath = fileURLToPath(base);
if (!main) process$1.emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
else if (path.resolve(packagePath, main) !== urlPath) process$1.emitWarning(`Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
}
/**
* @param {string} path
* @returns {Stats | undefined}
*/
function tryStatSync(path$1) {
try {
return statSync(path$1);
} catch {}
}
/**
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
* 2. TRY(M, M.js, M.json, M.node)
* 3. TRY(M/index.js, M/index.json, M/index.node)
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
* 5. NOT_FOUND
*
* @param {URL} url
* @returns {boolean}
*/
function fileExists(url) {
const stats = statSync(url, { throwIfNoEntry: false });
const isFile = stats ? stats.isFile() : void 0;
return isFile === null || isFile === void 0 ? false : isFile;
}
/**
* @param {URL} packageJsonUrl
* @param {PackageConfig} packageConfig
* @param {URL} base
* @returns {URL}
*/
function legacyMainResolve(packageJsonUrl, packageConfig, base) {
/** @type {URL | undefined} */
let guess;
if (packageConfig.main !== void 0) {
guess = new URL$1(packageConfig.main, packageJsonUrl);
if (fileExists(guess)) return guess;
const tries$1 = [
`./${packageConfig.main}.js`,
`./${packageConfig.main}.json`,
`./${packageConfig.main}.node`,
`./${packageConfig.main}/index.js`,
`./${packageConfig.main}/index.json`,
`./${packageConfig.main}/index.node`
];
let i$1 = -1;
while (++i$1 < tries$1.length) {
guess = new URL$1(tries$1[i$1], packageJsonUrl);
if (fileExists(guess)) break;
guess = void 0;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
}
const tries = [
"./index.js",
"./index.json",
"./index.node"
];
let i = -1;
while (++i < tries.length) {
guess = new URL$1(tries[i], packageJsonUrl);
if (fileExists(guess)) break;
guess = void 0;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
throw new ERR_MODULE_NOT_FOUND(fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
}
/**
* @param {URL} resolved
* @param {URL} base
* @param {boolean} [preserveSymlinks]
* @returns {URL}
*/
function finalizeResolution(resolved, base, preserveSymlinks) {
if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, "must not include encoded \"/\" or \"\\\" characters", fileURLToPath(base));
/** @type {string} */
let filePath;
try {
filePath = fileURLToPath(resolved);
} catch (error) {
const cause = error;
Object.defineProperty(cause, "input", { value: String(resolved) });
Object.defineProperty(cause, "module", { value: String(base) });
throw cause;
}
const stats = tryStatSync(filePath.endsWith("/") ? filePath.slice(-1) : filePath);
if (stats && stats.isDirectory()) {
const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base));
error.url = String(resolved);
throw error;
}
if (!stats || !stats.isFile()) {
const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && fileURLToPath(base), true);
error.url = String(resolved);
throw error;
}
{
const real = realpathSync(filePath);
const { search, hash } = resolved;
resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? "/" : ""));
resolved.search = search;
resolved.hash = hash;
}
return resolved;
}
/**
* @param {string} specifier
* @param {URL | undefined} packageJsonUrl
* @param {URL} base
* @returns {Error}
*/
function importNotDefined(specifier, packageJsonUrl, base) {
return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
}
/**
* @param {string} subpath
* @param {URL} packageJsonUrl
* @param {URL} base
* @returns {Error}
*/
function exportsNotFound(subpath, packageJsonUrl, base) {
return new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, base && fileURLToPath(base));
}
/**
* @param {string} request
* @param {string} match
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} [base]
* @returns {never}
*/
function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
throw new ERR_INVALID_MODULE_SPECIFIER(request, `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJsonUrl)}`, base && fileURLToPath(base));
}
/**
* @param {string} subpath
* @param {unknown} target
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} [base]
* @returns {Error}
*/
function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
return new ERR_INVALID_PACKAGE_TARGET(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, target, internal, base && fileURLToPath(base));
}
/**
* @param {string} target
* @param {string} subpath
* @param {string} match
* @param {URL} packageJsonUrl
* @param {URL} base
* @param {boolean} pattern
* @param {boolean} internal
* @param {boolean} isPathMap
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
if (subpath !== "" && !pattern && target[target.length - 1] !== "/") throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (!target.startsWith("./")) {
if (internal && !target.startsWith("../") && !target.startsWith("/")) {
let isURL = false;
try {
new URL$1(target);
isURL = true;
} catch {}
if (!isURL) return packageResolve(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target + subpath, packageJsonUrl, conditions);
}
throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
}
if (invalidSegmentRegEx.exec(target.slice(2)) !== null) if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
if (!isPathMap) {
const request = pattern ? match.replace("*", () => subpath) : match + subpath;
emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, true);
}
} else throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
const resolved = new URL$1(target, packageJsonUrl);
const resolvedPath = resolved.pathname;
const packagePath = new URL$1(".", packageJsonUrl).pathname;
if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (subpath === "") return resolved;
if (invalidSegmentRegEx.exec(subpath) !== null) {
const request = pattern ? match.replace("*", () => subpath) : match + subpath;
if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
if (!isPathMap) emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, false);
} else throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
}
if (pattern) return new URL$1(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath));
return new URL$1(subpath, resolved);
}
/**
* @param {string} key
* @returns {boolean}
*/
function isArrayIndex(key) {
const keyNumber = Number(key);
if (`${keyNumber}` !== key) return false;
return keyNumber >= 0 && keyNumber < 4294967295;
}
/**
* @param {URL} packageJsonUrl
* @param {unknown} target
* @param {string} subpath
* @param {string} packageSubpath
* @param {URL} base
* @param {boolean} pattern
* @param {boolean} internal
* @param {boolean} isPathMap
* @param {Set<string> | undefined} conditions
* @returns {URL | null}
*/
function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
if (typeof target === "string") return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions);
if (Array.isArray(target)) {
/** @type {Array<unknown>} */
const targetList = target;
if (targetList.length === 0) return null;
/** @type {ErrnoException | null | undefined} */
let lastException;
let i = -1;
while (++i < targetList.length) {
const targetItem = targetList[i];
/** @type {URL | null} */
let resolveResult;
try {
resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
} catch (error) {
const exception = error;
lastException = exception;
if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
throw error;
}
if (resolveResult === void 0) continue;
if (resolveResult === null) {
lastException = null;
continue;
}
return resolveResult;
}
if (lastException === void 0 || lastException === null) return null;
throw lastException;
}
if (typeof target === "object" && target !== null) {
const keys = Object.getOwnPropertyNames(target);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
if (isArrayIndex(key)) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain numeric property keys.");
}
i = -1;
while (++i < keys.length) {
const key = keys[i];
if (key === "default" || conditions && conditions.has(key)) {
const conditionalTarget = target[key];
const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
if (resolveResult === void 0) continue;
return resolveResult;
}
}
return null;
}
if (target === null) return null;
throw invalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base);
}
/**
* @param {unknown} exports
* @param {URL} packageJsonUrl
* @param {URL} base
* @returns {boolean}
*/
function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
if (typeof exports === "string" || Array.isArray(exports)) return true;
if (typeof exports !== "object" || exports === null) return false;
const keys = Object.getOwnPropertyNames(exports);
let isConditionalSugar = false;
let i = 0;
let keyIndex = -1;
while (++keyIndex < keys.length) {
const key = keys[keyIndex];
const currentIsConditionalSugar = key === "" || key[0] !== ".";
if (i++ === 0) isConditionalSugar = currentIsConditionalSugar;
else if (isConditionalSugar !== currentIsConditionalSugar) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.");
}
return isConditionalSugar;
}
/**
* @param {string} match
* @param {URL} pjsonUrl
* @param {URL} base
*/
function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
if (process$1.noDeprecation) return;
const pjsonPath = fileURLToPath(pjsonUrl);
if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
emittedPackageWarnings.add(pjsonPath + "|" + match);
process$1.emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, "DeprecationWarning", "DEP0155");
}
/**
* @param {URL} packageJsonUrl
* @param {string} packageSubpath
* @param {Record<string, unknown>} packageConfig
* @param {URL} base
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
let exports = packageConfig.exports;
if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = { ".": exports };
if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
const target = exports[packageSubpath];
const resolveResult = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, false, conditions);
if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
return resolveResult;
}
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(exports);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
if (packageSubpath.endsWith("/")) emitTrailingSlashPatternDeprecation(packageSubpath, packageJsonUrl, base);
const patternTrailer = key.slice(patternIndex + 1);
if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = packageSubpath.slice(patternIndex, packageSubpath.length - patternTrailer.length);
}
}
}
if (bestMatch) {
const target = exports[bestMatch];
const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, false, packageSubpath.endsWith("/"), conditions);
if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
return resolveResult;
}
throw exportsNotFound(packageSubpath, packageJsonUrl, base);
}
/**
* @param {string} a
* @param {string} b
*/
function patternKeyCompare(a, b) {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
if (baseLengthA > baseLengthB) return -1;
if (baseLengthB > baseLengthA) return 1;
if (aPatternIndex === -1) return 1;
if (bPatternIndex === -1) return -1;
if (a.length > b.length) return -1;
if (b.length > a.length) return 1;
return 0;
}
/**
* @param {string} name
* @param {URL} base
* @param {Set<string>} [conditions]
* @returns {URL}
*/
function packageImportsResolve(name, base, conditions) {
if (name === "#" || name.startsWith("#/") || name.endsWith("/")) throw new ERR_INVALID_MODULE_SPECIFIER(name, "is not a valid internal imports specifier name", fileURLToPath(base));
/** @type {URL | undefined} */
let packageJsonUrl;
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) if (own.call(imports, name) && !name.includes("*")) {
const resolveResult = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, false, conditions);
if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
} else {
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(imports);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
const patternTrailer = key.slice(patternIndex + 1);
if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = name.slice(patternIndex, name.length - patternTrailer.length);
}
}
}
if (bestMatch) {
const target = imports[bestMatch];
const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, true, false, conditions);
if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
}
}
}
throw importNotDefined(name, packageJsonUrl, base);
}
/**
* @param {string} specifier
* @param {URL} base
*/
function parsePackageName(specifier, base) {
let separatorIndex = specifier.indexOf("/");
let validPackageName = true;
let isScoped = false;
if (specifier[0] === "@") {
isScoped = true;
if (separatorIndex === -1 || specifier.length === 0) validPackageName = false;
else separatorIndex = specifier.indexOf("/", separatorIndex + 1);
}
const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
if (invalidPackageNameRegEx.exec(packageName) !== null) validPackageName = false;
if (!validPackageName) throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", fileURLToPath(base));
return {
packageName,
packageSubpath: "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex)),
isScoped
};
}
/**
* @param {string} specifier
* @param {URL} base
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function packageResolve(specifier, base, conditions) {
if (builtinModules.includes(specifier)) return new URL$1("node:" + specifier);
const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
const packageConfig = getPackageScopeConfig(base);
/* c8 ignore next 16 */
if (packageConfig.exists) {
const packageJsonUrl$1 = pathToFileURL(packageConfig.pjsonPath);
if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl$1, packageSubpath, packageConfig, base, conditions);
}
let packageJsonUrl = new URL$1("./node_modules/" + packageName + "/package.json", base);
let packageJsonPath = fileURLToPath(packageJsonUrl);
/** @type {string} */
let lastPath;
do {
const stat$1 = tryStatSync(packageJsonPath.slice(0, -13));
if (!stat$1 || !stat$1.isDirectory()) {
lastPath = packageJsonPath;
packageJsonUrl = new URL$1((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl);
packageJsonPath = fileURLToPath(packageJsonUrl);
continue;
}
const packageConfig$1 = read(packageJsonPath, {
base,
specifier
});
if (packageConfig$1.exports !== void 0 && packageConfig$1.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig$1, base, conditions);
if (packageSubpath === ".") return legacyMainResolve(packageJsonUrl, packageConfig$1, base);
return new URL$1(packageSubpath, packageJsonUrl);
} while (packageJsonPath.length !== lastPath.length);
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false);
}
/**
* @param {string} specifier
* @returns {boolean}
*/
function isRelativeSpecifier(specifier) {
if (specifier[0] === ".") {
if (specifier.length === 1 || specifier[1] === "/") return true;
if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) return true;
}
return false;
}
/**
* @param {string} specifier
* @returns {boolean}
*/
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === "") return false;
if (specifier[0] === "/") return true;
return isRelativeSpecifier(specifier);
}
/**
* The “Resolver Algorithm Specification” as detailed in the Node docs (which is
* sync and slightly lower-level than `resolve`).
*
* @param {string} specifier
* `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
* @param {URL} base
* Full URL (to a file) that `specifier` is resolved relative from.
* @param {Set<string>} [conditions]
* Conditions.
* @param {boolean} [preserveSymlinks]
* Keep symlinks instead of resolving them.
* @returns {URL}
* A URL object to the found thing.
*/
function moduleResolve(specifier, base, conditions, preserveSymlinks) {
const protocol = base.protocol;
const isRemote = protocol === "data:" || protocol === "http:" || protocol === "https:";
/** @type {URL | undefined} */
let resolved;
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) try {
resolved = new URL$1(specifier, base);
} catch (error_) {
const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
error.cause = error_;
throw error;
}
else if (protocol === "file:" && specifier[0] === "#") resolved = packageImportsResolve(specifier, base, conditions);
else try {
resolved = new URL$1(specifier);
} catch (error_) {
if (isRemote && !builtinModules.includes(specifier)) {
const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
error.cause = error_;
throw error;
}
resolved = packageResolve(specifier, base, conditions);
}
assert(resolved !== void 0, "expected to be defined");
if (resolved.protocol !== "file:") return resolved;
return finalizeResolution(resolved, base);
}
function fileURLToPath$1(id) {
if (typeof id === "string" && !id.startsWith("file://")) return normalizeSlash(id);
return normalizeSlash(fileURLToPath(id));
}
function pathToFileURL$1(id) {
return pathToFileURL(fileURLToPath$1(id)).toString();
}
const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g;
function sanitizeURIComponent(name = "", replacement = "_") {
return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement);
}
function sanitizeFilePath(filePath = "") {
return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/");
}
function normalizeid(id) {
if (typeof id !== "string") id = id.toString();
if (/(?:node|data|http|https|file):/.test(id)) return id;
if (BUILTIN_MODULES.has(id)) return "node:" + id;
return "file://" + encodeURI(normalizeSlash(id));
}
async function loadURL(url) {
return await promises.readFile(fileURLToPath$1(url), "utf8");
}
const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
const DEFAULT_EXTENSIONS = [
".mjs",
".cjs",
".js",
".json"
];
const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
"ERR_MODULE_NOT_FOUND",
"ERR_UNSUPPORTED_DIR_IMPORT",
"MODULE_NOT_FOUND",
"ERR_PACKAGE_PATH_NOT_EXPORTED"
]);
function _tryModuleResolve(id, url, conditions) {
try {
return moduleResolve(id, url, conditions);
} catch (error) {
if (!NOT_FOUND_ERRORS.has(error?.code)) throw error;
}
}
function _resolve$1(id, options = {}) {
if (typeof id !== "string") if (id instanceof URL) id = fileURLToPath$1(id);
else throw new TypeError("input must be a `string` or `URL`");
if (/(?:node|data|http|https):/.test(id)) return id;
if (BUILTIN_MODULES.has(id)) return "node:" + id;
if (id.startsWith("file://")) id = fileURLToPath$1(id);
if (isAbsolute$1(id)) try {
if (statSync(id).isFile()) return pathToFileURL$1(id);
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
if (_urls.length === 0) _urls.push(new URL(pathToFileURL$1(process.cwd())));
const urls = [..._urls];
for (const url of _urls) if (url.protocol === "file:") urls.push(new URL("./", url), new URL(joinURL(url.pathname, "_index.js"), url), new URL("node_modules", url));
let resolved;
for (const url of urls) {
resolved = _tryModuleResolve(id, url, conditionsSet);
if (resolved) break;
for (const prefix of ["", "/index"]) {
for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
resolved = _tryModuleResolve(joinURL(id, prefix) + extension, url, conditionsSet);
if (resolved) break;
}
if (resolved) break;
}
if (resolved) break;
}
if (!resolved) {
const error = /* @__PURE__ */ new Error(`Cannot find module ${id} imported from ${urls.join(", ")}`);
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
return pathToFileURL$1(resolved);
}
function resolveSync(id, options) {
return _resolve$1(id, options);
}
function resolve$1(id, options) {
try {
return Promise.resolve(resolveSync(id, options));
} catch (error) {
return Promise.reject(error);
}
}
function resolvePathSync(id, options) {
return fileURLToPath$1(resolveSync(id, options));
}
function resolvePath(id, options) {
try {
return Promise.resolve(resolvePathSync(id, options));
} catch (error) {
return Promise.reject(error);
}
}
const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/;
function parseNodeModulePath(path$1) {
if (!path$1) return {};
path$1 = normalize$1(fileURLToPath$1(path$1));
const match = NODE_MODULES_RE.exec(path$1);
if (!match) return {};
const [, dir, name, subpath] = match;
return {
dir,
name,
subpath: subpath ? `.${subpath}` : void 0
};
}
async function lookupNodeModuleSubpath(path$1) {
path$1 = normalize$1(fileURLToPath$1(path$1));
const { name, subpath } = parseNodeModulePath(path$1);
if (!name || !subpath) return subpath;
const { exports } = await readPackageJSON(path$1).catch(() => {}) || {};
if (exports) {
const resolvedSubpath = _findSubpath(subpath, exports);
if (resolvedSubpath) return resolvedSubpath;
}
return subpath;
}
function _findSubpath(subpath, exports) {
if (typeof exports === "string") exports = { ".": exports };
if (!subpath.startsWith(".")) subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`;
if (subpath in (exports || {})) return subpath;
return _flattenExports(exports).find((p) => p.fsPath === subpath)?.subpath;
}
function _flattenExports(exports = {}, parentSubpath = "./") {
return Object.entries(exports).flatMap(([key, value]) => {
const [subpath, condition] = key.startsWith(".") ? [key.slice(1), void 0] : ["", key];
const _subPath = joinURL(parentSubpath, subpath);
if (typeof value === "string") return [{
subpath: _subPath,
fsPath: value,
condition
}];
else return _flattenExports(value, _subPath);
});
}
const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
const EXPORT_DECAL_RE = /\bexport\s+(?<declaration>(?:async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?<name>[\w$]+)(?<extraNames>.*,\s*[\s\w:[\]{}]*[\w$\]}]+)*/g;
const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?<declaration>(?:interface|type|declare (?:async function|function|let|const enum|const|enum|var|class)))\s+(?<name>[\w$]+)/g;
const EXPORT_NAMED_RE = /\bexport\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_NAMED_DESTRUCT = /\bexport\s+(?:let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm;
const EXPORT_STAR_RE = /\bexport\s*\*(?:\s*as\s+(?<name>[\w$]+)\s+)?\s*(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?<defaultName>.*)/g;
const EXPORT_DEFAULT_CLASS_RE = /\bexport\s+default\s+(?<declaration>class)\s+(?<name>[\w$]+)/g;
const TYPE_RE = /^\s*?type\s/;
function findStaticImports(code) {
return _filterStatement(_tryGetLocations(code, "import"), matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }));
}
function parseStaticImport(matched) {
const cleanedImports = clearImports(matched.imports);
const namedImports = {};
const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
for (const namedImport of _matches) {
const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
const source = _match?.[1] || namedImport.trim();
const importName = _match?.[2] || source;
if (source && !TYPE_RE.test(source)) namedImports[source] = importName;
}
const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
return {
...matched,
defaultImport,
namespacedImport,
namedImports
};
}
function findExports(code) {
const declaredExports = matchAll(EXPORT_DECAL_RE, code, { type: "declaration" });
for (const declaredExport of declaredExports) {
if (/^export\s+(?:async\s+)?function/.test(declaredExport.code)) continue;
const extraNamesStr = declaredExport.extraNames;
if (extraNamesStr) {
const extraNames = matchAll(/({.*?})|(\[.*?])|(,\s*(?<name>\w+))/g, extraNamesStr, {}).map((m) => m.name).filter(Boolean);
declaredExport.names = [declaredExport.name, ...extraNames];
}
delete declaredExport.extraNames;
}
const namedExports = normalizeNamedExports(matchAll(EXPORT_NAMED_RE, code, { type: "named" }));
const destructuredExports = matchAll(EXPORT_NAMED_DESTRUCT, code, { type: "named" });
for (const namedExport of destructuredExports) {
namedExport.exports = namedExport.exports1 || namedExport.exports2;
namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim());
}
const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, {
type: "default",
name: "default"
});
const defaultClassExports = matchAll(EXPORT_DEFAULT_CLASS_RE, code, { type: "declaration" });
const starExports = matchAll(EXPORT_STAR_RE, code, { type: "star" });
const exports = normalizeExports([
...declaredExports,
...namedExports,
...destructuredExports,
...defaultExport,
...defaultClassExports,
...starExports
]);
if (exports.length === 0) return [];
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) return [];
return _filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
const nextExport = exports2[index + 1];
return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
});
}
function findTypeExports(code) {
const declaredExports = matchAll(EXPORT_DECAL_TYPE_RE, code, { type: "declaration" });
const namedExports = normalizeNamedExports(matchAll(EXPORT_NAMED_TYPE_RE, code, { type: "named" }));
const exports = normalizeExports([...declaredExports, ...namedExports]);
if (exports.length === 0) return [];
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) return [];
return _filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
const nextExport = exports2[index + 1];
return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
});
}
function normalizeExports(exports) {
for (const exp of exports) {
if (!exp.name && exp.names && exp.names.length === 1) exp.name = exp.names[0];
if (exp.name === "default" && exp.type !== "default") {
exp._type = exp.type;
exp.type = "default";
}
if (!exp.names && exp.name) exp.names = [exp.name];
if (exp.type === "declaration" && exp.declaration) exp.declarationType = exp.declaration.replace(/^declare\s*/, "");
}
return exports;
}
function normalizeNamedExports(namedExports) {
for (const namedExport of namedExports) namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim());
return namedExports;
}
async function resolveModuleExportNames(id, options) {
const url = await resolvePath(id, options);
const exports = findExports(await loadURL(url));
const exportNames = new Set(exports.flatMap((exp) => exp.names).filter(Boolean));
for (const exp of exports) {
if (exp.type !== "star" || !exp.specifier) continue;
const subExports = await resolveModuleExportNames(exp.specifier, {
...options,
url
});
for (const subExport of subExports) exportNames.add(subExport);
}
return [...exportNames];
}
function _filterStatement(locations, statements) {
return statements.filter((exp) => {
return !locations || locations.some((location) => {
return exp.start <= location.start && exp.end >= location.end;
});
});
}
function _tryGetLocations(code, label) {
try {
return _getLocations(code, label);
} catch {}
}
function _getLocations(code, label) {
const tokens = tokenizer(code, {
ecmaVersion: "latest",
sourceType: "module",
allowHashBang: true,
allowAwaitOutsideFunction: true,
allowImportExportEverywhere: true
});
const locations = [];
for (const token of tokens) if (token.type.label === label) locations.push({
start: token.start,
end: token.end
});
return locations;
}
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;
const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
function hasESMSyntax(code, opts = {}) {
if (opts.stripComments) code = code.replace(COMMENT_RE, "");
return ESM_RE.test(code);
}
function hasCJSSyntax(code, opts = {}) {
if (opts.stripComments) code = code.replace(COMMENT_RE, "");
return CJS_RE.test(code);
}
function detectSyntax(code, opts = {}) {
if (opts.stripComments) code = code.replace(COMMENT_RE, "");
const hasESM = hasESMSyntax(code, {});
const hasCJS = hasCJSSyntax(code, {});
return {
hasESM,
hasCJS,
isMixed: hasESM && hasCJS
};
}
//#endregion
//#region node_modules/.pnpm/quansync@0.2.11/node_modules/quansync/dist/index.mjs
const GET_IS_ASYNC = Symbol.for("quansync.getIsAsync");
var QuansyncError = class extends Error {
constructor(message = "Unexpected promise in sync context") {
super(message);
this.name = "QuansyncError";
}
};
function isThenable(value) {
return value && typeof value === "object" && typeof value.then === "function";
}
function isQuansyncGenerator(value) {
return value && typeof value === "object" && typeof value[Symbol.iterator] === "function" && "__quansync" in value;
}
function fromObject(options) {
const generator = function* (...args) {
if (yield GET_IS_ASYNC) return yield options.async.apply(this, args);
return options.sync.apply(this, args);
};
function fn(...args) {
const iter = generator.apply(this, args);
iter.then = (...thenArgs) => options.async.apply(this, args).then(...thenArgs);
iter.__quansync = true;
return iter;
}
fn.sync = options.sync;
fn.async = options.async;
return fn;
}
function fromPromise(promise) {
return fromObject({
async: () => Promise.resolve(promise),
sync: () => {
if (isThenable(promise)) throw new QuansyncError();
return promise;
}
});
}
function unwrapYield(value, isAsync) {
if (value === GET_IS_ASYNC) return isAsync;
if (isQuansyncGenerator(value)) return isAsync ? iterateAsync(value) : iterateSync(value);
if (!isAsync && isThenable(value)) throw new QuansyncError();
return value;
}
const DEFAULT_ON_YIELD = (value) => value;
function iterateSync(generator, onYield = DEFAULT_ON_YIELD) {
let current = generator.next();
while (!current.done) try {
current = generator.next(unwrapYield(onYield(current.value, false)));
} catch (err) {
current = generator.throw(err);
}
return unwrapYield(current.value);
}
async function iterateAsync(generator, onYield = DEFAULT_ON_YIELD) {
let current = generator.next();
while (!current.done) try {
current = generator.next(await unwrapYield(onYield(current.value, true), true));
} catch (err) {
current = generator.throw(err);
}
return current.value;
}
function fromGeneratorFn(generatorFn, options) {
return fromObject({
name: generatorFn.name,
async(...args) {
return iterateAsync(generatorFn.apply(this, args), options?.onYield);
},
sync(...args) {
return iterateSync(generatorFn.apply(this, args), options?.onYield);
}
});
}
function quansync$1(input, options) {
if (isThenable(input)) return fromPromise(input);
if (typeof input === "function") return fromGeneratorFn(input, options);
else return fromObject(input);
}
const getIsAsync = quansync$1({
async: () => Promise.resolve(true),
sync: () => false
});
//#endregion
//#region node_modules/.pnpm/quansync@0.2.11/node_modules/quansync/dist/macro.mjs
const quansync = quansync$1;
//#endregion
//#region node_modules/.pnpm/local-pkg@1.1.2/node_modules/local-pkg/dist/index.mjs
const toPath = (urlOrPath) => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
async function findUp$1(name, { cwd: cwd$1 = process$1.cwd(), type = "file", stopAt } = {}) {
let directory = path.resolve(toPath(cwd$1) ?? "");
const { root } = path.parse(directory);
stopAt = path.resolve(directory, toPath(stopAt ?? root));
const isAbsoluteName = path.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path.join(directory, name);
try {
const stats = await fsp.stat(filePath);
if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) return filePath;
} catch {}
if (directory === stopAt || directory === root) break;
directory = path.dirname(directory);
}
}
function findUpSync(name, { cwd: cwd$1 = process$1.cwd(), type = "file", stopAt } = {}) {
let directory = path.resolve(toPath(cwd$1) ?? "");
const { root } = path.parse(directory);
stopAt = path.resolve(directory, toPath(stopAt) ?? root);
const isAbsoluteName = path.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path.join(directory, name);
try {
const stats = fs.statSync(filePath, { throwIfNoEntry: false });
if (type === "file" && stats?.isFile() || type === "directory" && stats?.isDirectory()) return filePath;
} catch {}
if (directory === stopAt || directory === root) break;
directory = path.dirname(directory);
}
}
function _resolve(path$1, options = {}) {
if (options.platform === "auto" || !options.platform) options.platform = process$1.platform === "win32" ? "win32" : "posix";
if (process$1.versions.pnp) {
const paths = options.paths || [];
if (paths.length === 0) paths.push(process$1.cwd());
const targetRequire = createRequire(import.meta.url);
try {
return targetRequire.resolve(path$1, { paths });
} catch {}
}
const modulePath = resolvePathSync(path$1, { url: options.paths });
if (options.platform === "win32") return win32.normalize(modulePath);
return modulePath;
}
function resolveModule(name, options = {}) {
try {
return _resolve(name, options);
} catch {
return;
}
}
function getPackageJsonPath(name, options = {}) {
const entry = resolvePackage(name, options);
if (!entry) return;
return searchPackageJSON(entry);
}
const readFile$1 = quansync({
async: (id) => fs.promises.readFile(id, "utf8"),
sync: (id) => fs.readFileSync(id, "utf8")
});
const getPackageInfo = quansync(function* (name, options = {}) {
const packageJsonPath = getPackageJsonPath(name, options);
if (!packageJsonPath) return;
const packageJson = JSON.parse(yield readFile$1(packageJsonPath));
return {
name,
version: packageJson.version,
rootPath: dirname(packageJsonPath),
packageJsonPath,
packageJson
};
});
const getPackageInfoSync = getPackageInfo.sync;
function resolvePackage(name, options = {}) {
try {
return _resolve(`${name}/package.json`, options);
} catch {}
try {
return _resolve(name, options);
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND") console.error(e);
return false;
}
}
function searchPackageJSON(dir) {
let packageJsonPath;
while (true) {
if (!dir) return;
const newDir = dirname(dir);
if (newDir === dir) return;
dir = newDir;
packageJsonPath = join(dir, "package.json");
if (fs.existsSync(packageJsonPath)) break;
}
return packageJsonPath;
}
const findUp = quansync({
sync: findUpSync,
async: findUp$1
});
const loadPackageJSON = quansync(function* (cwd$1 = process$1.cwd()) {
const path$1 = yield findUp("package.json", { cwd: cwd$1 });
if (!path$1 || !fs.existsSync(path$1)) return null;
return JSON.parse(yield readFile$1(path$1));
});
const loadPackageJSONSync = loadPackageJSON.sync;
const isPackageListed = quansync(function* (name, cwd$1) {
const pkg = (yield loadPackageJSON(cwd$1)) || {};
return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
});
const isPackageListedSync = isPackageListed.sync;
//#endregion
export { findStaticImports as a, parseNodeModulePath as c, resolveModuleExportNames as d, sanitizeFilePath as f, findExports as i, parseStaticImport as l, detectSyntax as n, findTypeExports as o, fileURLToPath$1 as r, lookupNodeModuleSubpath as s, resolveModule as t, resolve$1 as u };
import { u as encode } from "./gen-mapping.mjs";
//#region node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
var BitSet = class BitSet {
constructor(arg) {
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
}
add(n$1) {
this.bits[n$1 >> 5] |= 1 << (n$1 & 31);
}
has(n$1) {
return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31));
}
};
var Chunk = class Chunk {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
this.previous = null;
this.next = null;
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
reset() {
this.intro = "";
this.outro = "";
if (this.edited) {
this.content = this.original;
this.storeName = false;
this.edited = false;
}
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else this.content = originalBefore;
newChunk.next = this.next;
if (newChunk.next) newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", void 0, true);
if (this.edited) this.edit(trimmed, this.storeName, true);
}
return true;
} else {
this.edit("", void 0, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) newChunk.edit(trimmed, this.storeName, true);
this.edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
}
}
};
function getBtoa() {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
else return () => {
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
};
}
const btoa = /* @__PURE__ */ getBtoa();
var SourceMap = class {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
}
};
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) return null;
if (tabbed.length >= spaced.length) return " ";
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i = fromParts.length;
while (i--) fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
const toString = Object.prototype.toString;
function isObject(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j = lineOffsets.length;
while (i < j) {
const m = i + j >> 1;
if (index < lineOffsets[m]) j = m;
else i = m + 1;
}
const line = i - 1;
return {
line,
column: index - lineOffsets[line]
};
};
}
const wordRegex = /\w/;
var Mappings = class {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const contentLengthMinusOne = content.length - 1;
let contentLineEnd = content.indexOf("\n", 0);
let previousContentLineEnd = -1;
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
const segment$1 = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment$1.push(nameIndex);
this.rawSegments.push(segment$1);
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
previousContentLineEnd = contentLineEnd;
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
}
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment.push(nameIndex);
this.rawSegments.push(segment);
this.advance(content.slice(previousContentLineEnd + 1));
} else if (this.pending) {
this.rawSegments.push(this.pending);
this.advance(content);
}
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
charInHiresBoundary = false;
} else {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
if (!charInHiresBoundary) {
this.rawSegments.push(segment);
charInHiresBoundary = true;
}
} else {
this.rawSegments.push(segment);
charInHiresBoundary = false;
}
else this.rawSegments.push(segment);
}
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str) return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
const n = "\n";
const warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class MagicString {
constructor(string, options = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: {
writable: true,
value: string
},
outro: {
writable: true,
value: ""
},
intro: {
writable: true,
value: ""
},
firstChunk: {
writable: true,
value: chunk
},
lastChunk: {
writable: true,
value: chunk
},
lastSearchedChunk: {
writable: true,
value: chunk
},
byStart: {
writable: true,
value: {}
},
byEnd: {
writable: true,
value: {}
},
filename: {
writable: true,
value: options.filename
},
indentExclusionRanges: {
writable: true,
value: options.indentExclusionRanges
},
sourcemapLocations: {
writable: true,
value: new BitSet()
},
storedNames: {
writable: true,
value: {}
},
indentStr: {
writable: true,
value: void 0
},
ignoreList: {
writable: true,
value: options.ignoreList
},
offset: {
writable: true,
value: options.offset || 0
}
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.appendLeft(content);
else this.intro += content;
return this;
}
appendRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.appendRight(content);
else this.outro += content;
return this;
}
clone() {
const cloned = new MagicString(this.original, {
filename: this.filename,
offset: this.offset
});
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options) {
options = options || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options.hires);
const locate = getLocator(this.original);
if (this.intro) mappings.advance(this.intro);
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length) mappings.advance(chunk.intro);
if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
if (chunk.outro.length) mappings.advance(chunk.outro);
});
if (this.outro) mappings.advance(this.outro);
return {
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
sourcesContent: options.includeContent ? [this.original] : void 0,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
_ensureindentStr() {
if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
}
_getRawIndentString() {
this._ensureindentStr();
return this.indentStr;
}
getIndentString() {
this._ensureindentStr();
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options) {
const pattern = /^[^\r\n]/gm;
if (isObject(indentStr)) {
options = indentStr;
indentStr = void 0;
}
if (indentStr === void 0) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "") return this;
options = options || {};
const isExcluded = {};
if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
});
let shouldIndentNextCharacter = options.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") shouldIndentNextCharacter = true;
else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) chunk.prependRight(indentStr);
else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
start = start + this.offset;
end = end + this.offset;
index = index + this.offset;
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk) return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft) oldLeft.next = oldRight;
if (oldRight) oldRight.previous = oldLeft;
if (newLeft) newLeft.next = first;
if (newRight) newRight.previous = last;
if (!first.previous) this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft) this.firstChunk = first;
if (!newRight) this.lastChunk = last;
return this;
}
overwrite(start, end, content, options) {
options = options || {};
return this.update(start, end, content, {
...options,
overwrite: !options.contentOnly
});
}
update(start, end, content, options) {
start = start + this.offset;
end = end + this.offset;
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (end > this.original.length) throw new Error("end is out of bounds");
if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
this._split(start);
this._split(end);
if (options === true) {
if (!warned.storeName) {
console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
warned.storeName = true;
}
options = { storeName: true };
}
const storeName = options !== void 0 ? options.storeName : false;
const overwrite = options !== void 0 ? options.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, !overwrite);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.prependLeft(content);
else this.intro = content + this.intro;
return this;
}
prependRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.prependRight(content);
else this.outro = content + this.outro;
return this;
}
remove(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
reset(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.reset();
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length) return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length) return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length - this.offset) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) return result;
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
if (containsEnd) break;
chunk = chunk.next;
}
return result;
}
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index]) return;
let chunk = this.lastSearchedChunk;
let previousChunk = chunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index)) return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
if (chunk === previousChunk) return;
previousChunk = chunk;
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk) this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = /* @__PURE__ */ new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = /* @__PURE__ */ new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
_replaceRegexp(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
if (i === "$") return "$";
if (i === "&") return match[0];
if (+i < match.length) return match[+i];
return `$${i}`;
});
else return replacement(...match, match.index, str, match.groups);
}
function matchAll(re, str) {
let match;
const matches = [];
while (match = re.exec(str)) matches.push(match);
return matches;
}
if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
if (match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
});
else {
const match = this.original.match(searchValue);
if (match && match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
}
return this;
}
_replaceString(string, replacement) {
const { original } = this;
const index = original.indexOf(string);
if (index !== -1) {
if (typeof replacement === "function") replacement = replacement(string, index, original);
if (string !== replacement) this.overwrite(index, index + string.length, replacement);
}
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string, replacement) {
const { original } = this;
const stringLength = string.length;
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
const previous = original.slice(index, index + stringLength);
let _replacement = replacement;
if (typeof replacement === "function") _replacement = replacement(previous, index, original);
if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
}
return this;
}
replaceAll(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
return this._replaceRegexp(searchValue, replacement);
}
};
//#endregion
export { MagicString as t };
//#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/other.js
const types$1 = {
"application/prs.cww": ["cww"],
"application/prs.xsf+xml": ["xsf"],
"application/vnd.1000minds.decision-model+xml": ["1km"],
"application/vnd.3gpp.pic-bw-large": ["plb"],
"application/vnd.3gpp.pic-bw-small": ["psb"],
"application/vnd.3gpp.pic-bw-var": ["pvb"],
"application/vnd.3gpp2.tcap": ["tcap"],
"application/vnd.3m.post-it-notes": ["pwn"],
"application/vnd.accpac.simply.aso": ["aso"],
"application/vnd.accpac.simply.imp": ["imp"],
"application/vnd.acucobol": ["acu"],
"application/vnd.acucorp": ["atc", "acutc"],
"application/vnd.adobe.air-application-installer-package+zip": ["air"],
"application/vnd.adobe.formscentral.fcdt": ["fcdt"],
"application/vnd.adobe.fxp": ["fxp", "fxpl"],
"application/vnd.adobe.xdp+xml": ["xdp"],
"application/vnd.adobe.xfdf": ["*xfdf"],
"application/vnd.age": ["age"],
"application/vnd.ahead.space": ["ahead"],
"application/vnd.airzip.filesecure.azf": ["azf"],
"application/vnd.airzip.filesecure.azs": ["azs"],
"application/vnd.amazon.ebook": ["azw"],
"application/vnd.americandynamics.acc": ["acc"],
"application/vnd.amiga.ami": ["ami"],
"application/vnd.android.package-archive": ["apk"],
"application/vnd.anser-web-certificate-issue-initiation": ["cii"],
"application/vnd.anser-web-funds-transfer-initiation": ["fti"],
"application/vnd.antix.game-component": ["atx"],
"application/vnd.apple.installer+xml": ["mpkg"],
"application/vnd.apple.keynote": ["key"],
"application/vnd.apple.mpegurl": ["m3u8"],
"application/vnd.apple.numbers": ["numbers"],
"application/vnd.apple.pages": ["pages"],
"application/vnd.apple.pkpass": ["pkpass"],
"application/vnd.aristanetworks.swi": ["swi"],
"application/vnd.astraea-software.iota": ["iota"],
"application/vnd.audiograph": ["aep"],
"application/vnd.autodesk.fbx": ["fbx"],
"application/vnd.balsamiq.bmml+xml": ["bmml"],
"application/vnd.blueice.multipass": ["mpm"],
"application/vnd.bmi": ["bmi"],
"application/vnd.businessobjects": ["rep"],
"application/vnd.chemdraw+xml": ["cdxml"],
"application/vnd.chipnuts.karaoke-mmd": ["mmd"],
"application/vnd.cinderella": ["cdy"],
"application/vnd.citationstyles.style+xml": ["csl"],
"application/vnd.claymore": ["cla"],
"application/vnd.cloanto.rp9": ["rp9"],
"application/vnd.clonk.c4group": [
"c4g",
"c4d",
"c4f",
"c4p",
"c4u"
],
"application/vnd.cluetrust.cartomobile-config": ["c11amc"],
"application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"],
"application/vnd.commonspace": ["csp"],
"application/vnd.contact.cmsg": ["cdbcmsg"],
"application/vnd.cosmocaller": ["cmc"],
"application/vnd.crick.clicker": ["clkx"],
"application/vnd.crick.clicker.keyboard": ["clkk"],
"application/vnd.crick.clicker.palette": ["clkp"],
"application/vnd.crick.clicker.template": ["clkt"],
"application/vnd.crick.clicker.wordbank": ["clkw"],
"application/vnd.criticaltools.wbs+xml": ["wbs"],
"application/vnd.ctc-posml": ["pml"],
"application/vnd.cups-ppd": ["ppd"],
"application/vnd.curl.car": ["car"],
"application/vnd.curl.pcurl": ["pcurl"],
"application/vnd.dart": ["dart"],
"application/vnd.data-vision.rdz": ["rdz"],
"application/vnd.dbf": ["dbf"],
"application/vnd.dcmp+xml": ["dcmp"],
"application/vnd.dece.data": [
"uvf",
"uvvf",
"uvd",
"uvvd"
],
"application/vnd.dece.ttml+xml": ["uvt", "uvvt"],
"application/vnd.dece.unspecified": ["uvx", "uvvx"],
"application/vnd.dece.zip": ["uvz", "uvvz"],
"application/vnd.denovo.fcselayout-link": ["fe_launch"],
"application/vnd.dna": ["dna"],
"application/vnd.dolby.mlp": ["mlp"],
"application/vnd.dpgraph": ["dpg"],
"application/vnd.dreamfactory": ["dfac"],
"application/vnd.ds-keypoint": ["kpxx"],
"application/vnd.dvb.ait": ["ait"],
"application/vnd.dvb.service": ["svc"],
"application/vnd.dynageo": ["geo"],
"application/vnd.ecowin.chart": ["mag"],
"application/vnd.enliven": ["nml"],
"application/vnd.epson.esf": ["esf"],
"application/vnd.epson.msf": ["msf"],
"application/vnd.epson.quickanime": ["qam"],
"application/vnd.epson.salt": ["slt"],
"application/vnd.epson.ssf": ["ssf"],
"application/vnd.eszigno3+xml": ["es3", "et3"],
"application/vnd.ezpix-album": ["ez2"],
"application/vnd.ezpix-package": ["ez3"],
"application/vnd.fdf": ["*fdf"],
"application/vnd.fdsn.mseed": ["mseed"],
"application/vnd.fdsn.seed": ["seed", "dataless"],
"application/vnd.flographit": ["gph"],
"application/vnd.fluxtime.clip": ["ftc"],
"application/vnd.framemaker": [
"fm",
"frame",
"maker",
"book"
],
"application/vnd.frogans.fnc": ["fnc"],
"application/vnd.frogans.ltf": ["ltf"],
"application/vnd.fsc.weblaunch": ["fsc"],
"application/vnd.fujitsu.oasys": ["oas"],
"application/vnd.fujitsu.oasys2": ["oa2"],
"application/vnd.fujitsu.oasys3": ["oa3"],
"application/vnd.fujitsu.oasysgp": ["fg5"],
"application/vnd.fujitsu.oasysprs": ["bh2"],
"application/vnd.fujixerox.ddd": ["ddd"],
"application/vnd.fujixerox.docuworks": ["xdw"],
"application/vnd.fujixerox.docuworks.binder": ["xbd"],
"application/vnd.fuzzysheet": ["fzs"],
"application/vnd.genomatix.tuxedo": ["txd"],
"application/vnd.geogebra.file": ["ggb"],
"application/vnd.geogebra.slides": ["ggs"],
"application/vnd.geogebra.tool": ["ggt"],
"application/vnd.geometry-explorer": ["gex", "gre"],
"application/vnd.geonext": ["gxt"],
"application/vnd.geoplan": ["g2w"],
"application/vnd.geospace": ["g3w"],
"application/vnd.gmx": ["gmx"],
"application/vnd.google-apps.document": ["gdoc"],
"application/vnd.google-apps.drawing": ["gdraw"],
"application/vnd.google-apps.form": ["gform"],
"application/vnd.google-apps.jam": ["gjam"],
"application/vnd.google-apps.map": ["gmap"],
"application/vnd.google-apps.presentation": ["gslides"],
"application/vnd.google-apps.script": ["gscript"],
"application/vnd.google-apps.site": ["gsite"],
"application/vnd.google-apps.spreadsheet": ["gsheet"],
"application/vnd.google-earth.kml+xml": ["kml"],
"application/vnd.google-earth.kmz": ["kmz"],
"application/vnd.gov.sk.xmldatacontainer+xml": ["xdcf"],
"application/vnd.grafeq": ["gqf", "gqs"],
"application/vnd.groove-account": ["gac"],
"application/vnd.groove-help": ["ghf"],
"application/vnd.groove-identity-message": ["gim"],
"application/vnd.groove-injector": ["grv"],
"application/vnd.groove-tool-message": ["gtm"],
"application/vnd.groove-tool-template": ["tpl"],
"application/vnd.groove-vcard": ["vcg"],
"application/vnd.hal+xml": ["hal"],
"application/vnd.handheld-entertainment+xml": ["zmm"],
"application/vnd.hbci": ["hbci"],
"application/vnd.hhe.lesson-player": ["les"],
"application/vnd.hp-hpgl": ["hpgl"],
"application/vnd.hp-hpid": ["hpid"],
"application/vnd.hp-hps": ["hps"],
"application/vnd.hp-jlyt": ["jlt"],
"application/vnd.hp-pcl": ["pcl"],
"application/vnd.hp-pclxl": ["pclxl"],
"application/vnd.hydrostatix.sof-data": ["sfd-hdstx"],
"application/vnd.ibm.minipay": ["mpy"],
"application/vnd.ibm.modcap": [
"afp",
"listafp",
"list3820"
],
"application/vnd.ibm.rights-management": ["irm"],
"application/vnd.ibm.secure-container": ["sc"],
"application/vnd.iccprofile": ["icc", "icm"],
"application/vnd.igloader": ["igl"],
"application/vnd.immervision-ivp": ["ivp"],
"application/vnd.immervision-ivu": ["ivu"],
"application/vnd.insors.igm": ["igm"],
"application/vnd.intercon.formnet": ["xpw", "xpx"],
"application/vnd.intergeo": ["i2g"],
"application/vnd.intu.qbo": ["qbo"],
"application/vnd.intu.qfx": ["qfx"],
"application/vnd.ipunplugged.rcprofile": ["rcprofile"],
"application/vnd.irepository.package+xml": ["irp"],
"application/vnd.is-xpr": ["xpr"],
"application/vnd.isac.fcs": ["fcs"],
"application/vnd.jam": ["jam"],
"application/vnd.jcp.javame.midlet-rms": ["rms"],
"application/vnd.jisp": ["jisp"],
"application/vnd.joost.joda-archive": ["joda"],
"application/vnd.kahootz": ["ktz", "ktr"],
"application/vnd.kde.karbon": ["karbon"],
"application/vnd.kde.kchart": ["chrt"],
"application/vnd.kde.kformula": ["kfo"],
"application/vnd.kde.kivio": ["flw"],
"application/vnd.kde.kontour": ["kon"],
"application/vnd.kde.kpresenter": ["kpr", "kpt"],
"application/vnd.kde.kspread": ["ksp"],
"application/vnd.kde.kword": ["kwd", "kwt"],
"application/vnd.kenameaapp": ["htke"],
"application/vnd.kidspiration": ["kia"],
"application/vnd.kinar": ["kne", "knp"],
"application/vnd.koan": [
"skp",
"skd",
"skt",
"skm"
],
"application/vnd.kodak-descriptor": ["sse"],
"application/vnd.las.las+xml": ["lasxml"],
"application/vnd.llamagraphics.life-balance.desktop": ["lbd"],
"application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"],
"application/vnd.lotus-1-2-3": ["123"],
"application/vnd.lotus-approach": ["apr"],
"application/vnd.lotus-freelance": ["pre"],
"application/vnd.lotus-notes": ["nsf"],
"application/vnd.lotus-organizer": ["org"],
"application/vnd.lotus-screencam": ["scm"],
"application/vnd.lotus-wordpro": ["lwp"],
"application/vnd.macports.portpkg": ["portpkg"],
"application/vnd.mapbox-vector-tile": ["mvt"],
"application/vnd.mcd": ["mcd"],
"application/vnd.medcalcdata": ["mc1"],
"application/vnd.mediastation.cdkey": ["cdkey"],
"application/vnd.mfer": ["mwf"],
"application/vnd.mfmp": ["mfm"],
"application/vnd.micrografx.flo": ["flo"],
"application/vnd.micrografx.igx": ["igx"],
"application/vnd.mif": ["mif"],
"application/vnd.mobius.daf": ["daf"],
"application/vnd.mobius.dis": ["dis"],
"application/vnd.mobius.mbk": ["mbk"],
"application/vnd.mobius.mqy": ["mqy"],
"application/vnd.mobius.msl": ["msl"],
"application/vnd.mobius.plc": ["plc"],
"application/vnd.mobius.txf": ["txf"],
"application/vnd.mophun.application": ["mpn"],
"application/vnd.mophun.certificate": ["mpc"],
"application/vnd.mozilla.xul+xml": ["xul"],
"application/vnd.ms-artgalry": ["cil"],
"application/vnd.ms-cab-compressed": ["cab"],
"application/vnd.ms-excel": [
"xls",
"xlm",
"xla",
"xlc",
"xlt",
"xlw"
],
"application/vnd.ms-excel.addin.macroenabled.12": ["xlam"],
"application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"],
"application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"],
"application/vnd.ms-excel.template.macroenabled.12": ["xltm"],
"application/vnd.ms-fontobject": ["eot"],
"application/vnd.ms-htmlhelp": ["chm"],
"application/vnd.ms-ims": ["ims"],
"application/vnd.ms-lrm": ["lrm"],
"application/vnd.ms-officetheme": ["thmx"],
"application/vnd.ms-outlook": ["msg"],
"application/vnd.ms-pki.seccat": ["cat"],
"application/vnd.ms-pki.stl": ["*stl"],
"application/vnd.ms-powerpoint": [
"ppt",
"pps",
"pot"
],
"application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"],
"application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"],
"application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"],
"application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"],
"application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"],
"application/vnd.ms-project": ["*mpp", "mpt"],
"application/vnd.ms-visio.viewer": ["vdx"],
"application/vnd.ms-word.document.macroenabled.12": ["docm"],
"application/vnd.ms-word.template.macroenabled.12": ["dotm"],
"application/vnd.ms-works": [
"wps",
"wks",
"wcm",
"wdb"
],
"application/vnd.ms-wpl": ["wpl"],
"application/vnd.ms-xpsdocument": ["xps"],
"application/vnd.mseq": ["mseq"],
"application/vnd.musician": ["mus"],
"application/vnd.muvee.style": ["msty"],
"application/vnd.mynfc": ["taglet"],
"application/vnd.nato.bindingdataobject+xml": ["bdo"],
"application/vnd.neurolanguage.nlu": ["nlu"],
"application/vnd.nitf": ["ntf", "nitf"],
"application/vnd.noblenet-directory": ["nnd"],
"application/vnd.noblenet-sealer": ["nns"],
"application/vnd.noblenet-web": ["nnw"],
"application/vnd.nokia.n-gage.ac+xml": ["*ac"],
"application/vnd.nokia.n-gage.data": ["ngdat"],
"application/vnd.nokia.n-gage.symbian.install": ["n-gage"],
"application/vnd.nokia.radio-preset": ["rpst"],
"application/vnd.nokia.radio-presets": ["rpss"],
"application/vnd.novadigm.edm": ["edm"],
"application/vnd.novadigm.edx": ["edx"],
"application/vnd.novadigm.ext": ["ext"],
"application/vnd.oasis.opendocument.chart": ["odc"],
"application/vnd.oasis.opendocument.chart-template": ["otc"],
"application/vnd.oasis.opendocument.database": ["odb"],
"application/vnd.oasis.opendocument.formula": ["odf"],
"application/vnd.oasis.opendocument.formula-template": ["odft"],
"application/vnd.oasis.opendocument.graphics": ["odg"],
"application/vnd.oasis.opendocument.graphics-template": ["otg"],
"application/vnd.oasis.opendocument.image": ["odi"],
"application/vnd.oasis.opendocument.image-template": ["oti"],
"application/vnd.oasis.opendocument.presentation": ["odp"],
"application/vnd.oasis.opendocument.presentation-template": ["otp"],
"application/vnd.oasis.opendocument.spreadsheet": ["ods"],
"application/vnd.oasis.opendocument.spreadsheet-template": ["ots"],
"application/vnd.oasis.opendocument.text": ["odt"],
"application/vnd.oasis.opendocument.text-master": ["odm"],
"application/vnd.oasis.opendocument.text-template": ["ott"],
"application/vnd.oasis.opendocument.text-web": ["oth"],
"application/vnd.olpc-sugar": ["xo"],
"application/vnd.oma.dd2+xml": ["dd2"],
"application/vnd.openblox.game+xml": ["obgx"],
"application/vnd.openofficeorg.extension": ["oxt"],
"application/vnd.openstreetmap.data+xml": ["osm"],
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"],
"application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"],
"application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"],
"application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"],
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
"application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"],
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"],
"application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"],
"application/vnd.osgeo.mapguide.package": ["mgp"],
"application/vnd.osgi.dp": ["dp"],
"application/vnd.osgi.subsystem": ["esa"],
"application/vnd.palm": [
"pdb",
"pqa",
"oprc"
],
"application/vnd.pawaafile": ["paw"],
"application/vnd.pg.format": ["str"],
"application/vnd.pg.osasli": ["ei6"],
"application/vnd.picsel": ["efif"],
"application/vnd.pmi.widget": ["wg"],
"application/vnd.pocketlearn": ["plf"],
"application/vnd.powerbuilder6": ["pbd"],
"application/vnd.previewsystems.box": ["box"],
"application/vnd.procrate.brushset": ["brushset"],
"application/vnd.procreate.brush": ["brush"],
"application/vnd.procreate.dream": ["drm"],
"application/vnd.proteus.magazine": ["mgz"],
"application/vnd.publishare-delta-tree": ["qps"],
"application/vnd.pvi.ptid1": ["ptid"],
"application/vnd.pwg-xhtml-print+xml": ["xhtm"],
"application/vnd.quark.quarkxpress": [
"qxd",
"qxt",
"qwd",
"qwt",
"qxl",
"qxb"
],
"application/vnd.rar": ["rar"],
"application/vnd.realvnc.bed": ["bed"],
"application/vnd.recordare.musicxml": ["mxl"],
"application/vnd.recordare.musicxml+xml": ["musicxml"],
"application/vnd.rig.cryptonote": ["cryptonote"],
"application/vnd.rim.cod": ["cod"],
"application/vnd.rn-realmedia": ["rm"],
"application/vnd.rn-realmedia-vbr": ["rmvb"],
"application/vnd.route66.link66+xml": ["link66"],
"application/vnd.sailingtracker.track": ["st"],
"application/vnd.seemail": ["see"],
"application/vnd.sema": ["sema"],
"application/vnd.semd": ["semd"],
"application/vnd.semf": ["semf"],
"application/vnd.shana.informed.formdata": ["ifm"],
"application/vnd.shana.informed.formtemplate": ["itp"],
"application/vnd.shana.informed.interchange": ["iif"],
"application/vnd.shana.informed.package": ["ipk"],
"application/vnd.simtech-mindmapper": ["twd", "twds"],
"application/vnd.smaf": ["mmf"],
"application/vnd.smart.teacher": ["teacher"],
"application/vnd.software602.filler.form+xml": ["fo"],
"application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"],
"application/vnd.spotfire.dxp": ["dxp"],
"application/vnd.spotfire.sfs": ["sfs"],
"application/vnd.stardivision.calc": ["sdc"],
"application/vnd.stardivision.draw": ["sda"],
"application/vnd.stardivision.impress": ["sdd"],
"application/vnd.stardivision.math": ["smf"],
"application/vnd.stardivision.writer": ["sdw", "vor"],
"application/vnd.stardivision.writer-global": ["sgl"],
"application/vnd.stepmania.package": ["smzip"],
"application/vnd.stepmania.stepchart": ["sm"],
"application/vnd.sun.wadl+xml": ["wadl"],
"application/vnd.sun.xml.calc": ["sxc"],
"application/vnd.sun.xml.calc.template": ["stc"],
"application/vnd.sun.xml.draw": ["sxd"],
"application/vnd.sun.xml.draw.template": ["std"],
"application/vnd.sun.xml.impress": ["sxi"],
"application/vnd.sun.xml.impress.template": ["sti"],
"application/vnd.sun.xml.math": ["sxm"],
"application/vnd.sun.xml.writer": ["sxw"],
"application/vnd.sun.xml.writer.global": ["sxg"],
"application/vnd.sun.xml.writer.template": ["stw"],
"application/vnd.sus-calendar": ["sus", "susp"],
"application/vnd.svd": ["svd"],
"application/vnd.symbian.install": ["sis", "sisx"],
"application/vnd.syncml+xml": ["xsm"],
"application/vnd.syncml.dm+wbxml": ["bdm"],
"application/vnd.syncml.dm+xml": ["xdm"],
"application/vnd.syncml.dmddf+xml": ["ddf"],
"application/vnd.tao.intent-module-archive": ["tao"],
"application/vnd.tcpdump.pcap": [
"pcap",
"cap",
"dmp"
],
"application/vnd.tmobile-livetv": ["tmo"],
"application/vnd.trid.tpt": ["tpt"],
"application/vnd.triscape.mxs": ["mxs"],
"application/vnd.trueapp": ["tra"],
"application/vnd.ufdl": ["ufd", "ufdl"],
"application/vnd.uiq.theme": ["utz"],
"application/vnd.umajin": ["umj"],
"application/vnd.unity": ["unityweb"],
"application/vnd.uoml+xml": ["uoml", "uo"],
"application/vnd.vcx": ["vcx"],
"application/vnd.visio": [
"vsd",
"vst",
"vss",
"vsw",
"vsdx",
"vtx"
],
"application/vnd.visionary": ["vis"],
"application/vnd.vsf": ["vsf"],
"application/vnd.wap.wbxml": ["wbxml"],
"application/vnd.wap.wmlc": ["wmlc"],
"application/vnd.wap.wmlscriptc": ["wmlsc"],
"application/vnd.webturbo": ["wtb"],
"application/vnd.wolfram.player": ["nbp"],
"application/vnd.wordperfect": ["wpd"],
"application/vnd.wqd": ["wqd"],
"application/vnd.wt.stf": ["stf"],
"application/vnd.xara": ["xar"],
"application/vnd.xfdl": ["xfdl"],
"application/vnd.yamaha.hv-dic": ["hvd"],
"application/vnd.yamaha.hv-script": ["hvs"],
"application/vnd.yamaha.hv-voice": ["hvp"],
"application/vnd.yamaha.openscoreformat": ["osf"],
"application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"],
"application/vnd.yamaha.smaf-audio": ["saf"],
"application/vnd.yamaha.smaf-phrase": ["spf"],
"application/vnd.yellowriver-custom-menu": ["cmp"],
"application/vnd.zul": ["zir", "zirz"],
"application/vnd.zzazz.deck+xml": ["zaz"],
"application/x-7z-compressed": ["7z"],
"application/x-abiword": ["abw"],
"application/x-ace-compressed": ["ace"],
"application/x-apple-diskimage": ["*dmg"],
"application/x-arj": ["arj"],
"application/x-authorware-bin": [
"aab",
"x32",
"u32",
"vox"
],
"application/x-authorware-map": ["aam"],
"application/x-authorware-seg": ["aas"],
"application/x-bcpio": ["bcpio"],
"application/x-bdoc": ["*bdoc"],
"application/x-bittorrent": ["torrent"],
"application/x-blender": ["blend"],
"application/x-blorb": ["blb", "blorb"],
"application/x-bzip": ["bz"],
"application/x-bzip2": ["bz2", "boz"],
"application/x-cbr": [
"cbr",
"cba",
"cbt",
"cbz",
"cb7"
],
"application/x-cdlink": ["vcd"],
"application/x-cfs-compressed": ["cfs"],
"application/x-chat": ["chat"],
"application/x-chess-pgn": ["pgn"],
"application/x-chrome-extension": ["crx"],
"application/x-cocoa": ["cco"],
"application/x-compressed": ["*rar"],
"application/x-conference": ["nsc"],
"application/x-cpio": ["cpio"],
"application/x-csh": ["csh"],
"application/x-debian-package": ["*deb", "udeb"],
"application/x-dgc-compressed": ["dgc"],
"application/x-director": [
"dir",
"dcr",
"dxr",
"cst",
"cct",
"cxt",
"w3d",
"fgd",
"swa"
],
"application/x-doom": ["wad"],
"application/x-dtbncx+xml": ["ncx"],
"application/x-dtbook+xml": ["dtb"],
"application/x-dtbresource+xml": ["res"],
"application/x-dvi": ["dvi"],
"application/x-envoy": ["evy"],
"application/x-eva": ["eva"],
"application/x-font-bdf": ["bdf"],
"application/x-font-ghostscript": ["gsf"],
"application/x-font-linux-psf": ["psf"],
"application/x-font-pcf": ["pcf"],
"application/x-font-snf": ["snf"],
"application/x-font-type1": [
"pfa",
"pfb",
"pfm",
"afm"
],
"application/x-freearc": ["arc"],
"application/x-futuresplash": ["spl"],
"application/x-gca-compressed": ["gca"],
"application/x-glulx": ["ulx"],
"application/x-gnumeric": ["gnumeric"],
"application/x-gramps-xml": ["gramps"],
"application/x-gtar": ["gtar"],
"application/x-hdf": ["hdf"],
"application/x-httpd-php": ["php"],
"application/x-install-instructions": ["install"],
"application/x-ipynb+json": ["ipynb"],
"application/x-iso9660-image": ["*iso"],
"application/x-iwork-keynote-sffkey": ["*key"],
"application/x-iwork-numbers-sffnumbers": ["*numbers"],
"application/x-iwork-pages-sffpages": ["*pages"],
"application/x-java-archive-diff": ["jardiff"],
"application/x-java-jnlp-file": ["jnlp"],
"application/x-keepass2": ["kdbx"],
"application/x-latex": ["latex"],
"application/x-lua-bytecode": ["luac"],
"application/x-lzh-compressed": ["lzh", "lha"],
"application/x-makeself": ["run"],
"application/x-mie": ["mie"],
"application/x-mobipocket-ebook": ["*prc", "mobi"],
"application/x-ms-application": ["application"],
"application/x-ms-shortcut": ["lnk"],
"application/x-ms-wmd": ["wmd"],
"application/x-ms-wmz": ["wmz"],
"application/x-ms-xbap": ["xbap"],
"application/x-msaccess": ["mdb"],
"application/x-msbinder": ["obd"],
"application/x-mscardfile": ["crd"],
"application/x-msclip": ["clp"],
"application/x-msdos-program": ["*exe"],
"application/x-msdownload": [
"*exe",
"*dll",
"com",
"bat",
"*msi"
],
"application/x-msmediaview": [
"mvb",
"m13",
"m14"
],
"application/x-msmetafile": [
"*wmf",
"*wmz",
"*emf",
"emz"
],
"application/x-msmoney": ["mny"],
"application/x-mspublisher": ["pub"],
"application/x-msschedule": ["scd"],
"application/x-msterminal": ["trm"],
"application/x-mswrite": ["wri"],
"application/x-netcdf": ["nc", "cdf"],
"application/x-ns-proxy-autoconfig": ["pac"],
"application/x-nzb": ["nzb"],
"application/x-perl": ["pl", "pm"],
"application/x-pilot": ["*prc", "*pdb"],
"application/x-pkcs12": ["p12", "pfx"],
"application/x-pkcs7-certificates": ["p7b", "spc"],
"application/x-pkcs7-certreqresp": ["p7r"],
"application/x-rar-compressed": ["*rar"],
"application/x-redhat-package-manager": ["rpm"],
"application/x-research-info-systems": ["ris"],
"application/x-sea": ["sea"],
"application/x-sh": ["sh"],
"application/x-shar": ["shar"],
"application/x-shockwave-flash": ["swf"],
"application/x-silverlight-app": ["xap"],
"application/x-sql": ["*sql"],
"application/x-stuffit": ["sit"],
"application/x-stuffitx": ["sitx"],
"application/x-subrip": ["srt"],
"application/x-sv4cpio": ["sv4cpio"],
"application/x-sv4crc": ["sv4crc"],
"application/x-t3vm-image": ["t3"],
"application/x-tads": ["gam"],
"application/x-tar": ["tar"],
"application/x-tcl": ["tcl", "tk"],
"application/x-tex": ["tex"],
"application/x-tex-tfm": ["tfm"],
"application/x-texinfo": ["texinfo", "texi"],
"application/x-tgif": ["*obj"],
"application/x-ustar": ["ustar"],
"application/x-virtualbox-hdd": ["hdd"],
"application/x-virtualbox-ova": ["ova"],
"application/x-virtualbox-ovf": ["ovf"],
"application/x-virtualbox-vbox": ["vbox"],
"application/x-virtualbox-vbox-extpack": ["vbox-extpack"],
"application/x-virtualbox-vdi": ["vdi"],
"application/x-virtualbox-vhd": ["vhd"],
"application/x-virtualbox-vmdk": ["vmdk"],
"application/x-wais-source": ["src"],
"application/x-web-app-manifest+json": ["webapp"],
"application/x-x509-ca-cert": [
"der",
"crt",
"pem"
],
"application/x-xfig": ["fig"],
"application/x-xliff+xml": ["*xlf"],
"application/x-xpinstall": ["xpi"],
"application/x-xz": ["xz"],
"application/x-zip-compressed": ["*zip"],
"application/x-zmachine": [
"z1",
"z2",
"z3",
"z4",
"z5",
"z6",
"z7",
"z8"
],
"audio/vnd.dece.audio": ["uva", "uvva"],
"audio/vnd.digital-winds": ["eol"],
"audio/vnd.dra": ["dra"],
"audio/vnd.dts": ["dts"],
"audio/vnd.dts.hd": ["dtshd"],
"audio/vnd.lucent.voice": ["lvp"],
"audio/vnd.ms-playready.media.pya": ["pya"],
"audio/vnd.nuera.ecelp4800": ["ecelp4800"],
"audio/vnd.nuera.ecelp7470": ["ecelp7470"],
"audio/vnd.nuera.ecelp9600": ["ecelp9600"],
"audio/vnd.rip": ["rip"],
"audio/x-aac": ["*aac"],
"audio/x-aiff": [
"aif",
"aiff",
"aifc"
],
"audio/x-caf": ["caf"],
"audio/x-flac": ["flac"],
"audio/x-m4a": ["*m4a"],
"audio/x-matroska": ["mka"],
"audio/x-mpegurl": ["m3u"],
"audio/x-ms-wax": ["wax"],
"audio/x-ms-wma": ["wma"],
"audio/x-pn-realaudio": ["ram", "ra"],
"audio/x-pn-realaudio-plugin": ["rmp"],
"audio/x-realaudio": ["*ra"],
"audio/x-wav": ["*wav"],
"chemical/x-cdx": ["cdx"],
"chemical/x-cif": ["cif"],
"chemical/x-cmdf": ["cmdf"],
"chemical/x-cml": ["cml"],
"chemical/x-csml": ["csml"],
"chemical/x-xyz": ["xyz"],
"image/prs.btif": ["btif", "btf"],
"image/prs.pti": ["pti"],
"image/vnd.adobe.photoshop": ["psd"],
"image/vnd.airzip.accelerator.azv": ["azv"],
"image/vnd.blockfact.facti": ["facti"],
"image/vnd.dece.graphic": [
"uvi",
"uvvi",
"uvg",
"uvvg"
],
"image/vnd.djvu": ["djvu", "djv"],
"image/vnd.dvb.subtitle": ["*sub"],
"image/vnd.dwg": ["dwg"],
"image/vnd.dxf": ["dxf"],
"image/vnd.fastbidsheet": ["fbs"],
"image/vnd.fpx": ["fpx"],
"image/vnd.fst": ["fst"],
"image/vnd.fujixerox.edmics-mmr": ["mmr"],
"image/vnd.fujixerox.edmics-rlc": ["rlc"],
"image/vnd.microsoft.icon": ["ico"],
"image/vnd.ms-dds": ["dds"],
"image/vnd.ms-modi": ["mdi"],
"image/vnd.ms-photo": ["wdp"],
"image/vnd.net-fpx": ["npx"],
"image/vnd.pco.b16": ["b16"],
"image/vnd.tencent.tap": ["tap"],
"image/vnd.valve.source.texture": ["vtf"],
"image/vnd.wap.wbmp": ["wbmp"],
"image/vnd.xiff": ["xif"],
"image/vnd.zbrush.pcx": ["pcx"],
"image/x-3ds": ["3ds"],
"image/x-adobe-dng": ["dng"],
"image/x-cmu-raster": ["ras"],
"image/x-cmx": ["cmx"],
"image/x-freehand": [
"fh",
"fhc",
"fh4",
"fh5",
"fh7"
],
"image/x-icon": ["*ico"],
"image/x-jng": ["jng"],
"image/x-mrsid-image": ["sid"],
"image/x-ms-bmp": ["*bmp"],
"image/x-pcx": ["*pcx"],
"image/x-pict": ["pic", "pct"],
"image/x-portable-anymap": ["pnm"],
"image/x-portable-bitmap": ["pbm"],
"image/x-portable-graymap": ["pgm"],
"image/x-portable-pixmap": ["ppm"],
"image/x-rgb": ["rgb"],
"image/x-tga": ["tga"],
"image/x-xbitmap": ["xbm"],
"image/x-xpixmap": ["xpm"],
"image/x-xwindowdump": ["xwd"],
"message/vnd.wfa.wsc": ["wsc"],
"model/vnd.bary": ["bary"],
"model/vnd.cld": ["cld"],
"model/vnd.collada+xml": ["dae"],
"model/vnd.dwf": ["dwf"],
"model/vnd.gdl": ["gdl"],
"model/vnd.gtw": ["gtw"],
"model/vnd.mts": ["*mts"],
"model/vnd.opengex": ["ogex"],
"model/vnd.parasolid.transmit.binary": ["x_b"],
"model/vnd.parasolid.transmit.text": ["x_t"],
"model/vnd.pytha.pyox": ["pyo", "pyox"],
"model/vnd.sap.vds": ["vds"],
"model/vnd.usda": ["usda"],
"model/vnd.usdz+zip": ["usdz"],
"model/vnd.valve.source.compiled-map": ["bsp"],
"model/vnd.vtu": ["vtu"],
"text/prs.lines.tag": ["dsc"],
"text/vnd.curl": ["curl"],
"text/vnd.curl.dcurl": ["dcurl"],
"text/vnd.curl.mcurl": ["mcurl"],
"text/vnd.curl.scurl": ["scurl"],
"text/vnd.dvb.subtitle": ["sub"],
"text/vnd.familysearch.gedcom": ["ged"],
"text/vnd.fly": ["fly"],
"text/vnd.fmi.flexstor": ["flx"],
"text/vnd.graphviz": ["gv"],
"text/vnd.in3d.3dml": ["3dml"],
"text/vnd.in3d.spot": ["spot"],
"text/vnd.sun.j2me.app-descriptor": ["jad"],
"text/vnd.wap.wml": ["wml"],
"text/vnd.wap.wmlscript": ["wmls"],
"text/x-asm": ["s", "asm"],
"text/x-c": [
"c",
"cc",
"cxx",
"cpp",
"h",
"hh",
"dic"
],
"text/x-component": ["htc"],
"text/x-fortran": [
"f",
"for",
"f77",
"f90"
],
"text/x-handlebars-template": ["hbs"],
"text/x-java-source": ["java"],
"text/x-lua": ["lua"],
"text/x-markdown": ["mkd"],
"text/x-nfo": ["nfo"],
"text/x-opml": ["opml"],
"text/x-org": ["*org"],
"text/x-pascal": ["p", "pas"],
"text/x-processing": ["pde"],
"text/x-sass": ["sass"],
"text/x-scss": ["scss"],
"text/x-setext": ["etx"],
"text/x-sfv": ["sfv"],
"text/x-suse-ymp": ["ymp"],
"text/x-uuencode": ["uu"],
"text/x-vcalendar": ["vcs"],
"text/x-vcard": ["vcf"],
"video/vnd.dece.hd": ["uvh", "uvvh"],
"video/vnd.dece.mobile": ["uvm", "uvvm"],
"video/vnd.dece.pd": ["uvp", "uvvp"],
"video/vnd.dece.sd": ["uvs", "uvvs"],
"video/vnd.dece.video": ["uvv", "uvvv"],
"video/vnd.dvb.file": ["dvb"],
"video/vnd.fvt": ["fvt"],
"video/vnd.mpegurl": ["mxu", "m4u"],
"video/vnd.ms-playready.media.pyv": ["pyv"],
"video/vnd.uvvu.mp4": ["uvu", "uvvu"],
"video/vnd.vivo": ["viv"],
"video/x-f4v": ["f4v"],
"video/x-fli": ["fli"],
"video/x-flv": ["flv"],
"video/x-m4v": ["m4v"],
"video/x-matroska": [
"mkv",
"mk3d",
"mks"
],
"video/x-mng": ["mng"],
"video/x-ms-asf": ["asf", "asx"],
"video/x-ms-vob": ["vob"],
"video/x-ms-wm": ["wm"],
"video/x-ms-wmv": ["wmv"],
"video/x-ms-wmx": ["wmx"],
"video/x-ms-wvx": ["wvx"],
"video/x-msvideo": ["avi"],
"video/x-sgi-movie": ["movie"],
"video/x-smv": ["smv"],
"x-conference/x-cooltalk": ["ice"]
};
Object.freeze(types$1);
var other_default = types$1;
//#endregion
//#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/standard.js
const types = {
"application/andrew-inset": ["ez"],
"application/appinstaller": ["appinstaller"],
"application/applixware": ["aw"],
"application/appx": ["appx"],
"application/appxbundle": ["appxbundle"],
"application/atom+xml": ["atom"],
"application/atomcat+xml": ["atomcat"],
"application/atomdeleted+xml": ["atomdeleted"],
"application/atomsvc+xml": ["atomsvc"],
"application/atsc-dwd+xml": ["dwd"],
"application/atsc-held+xml": ["held"],
"application/atsc-rsat+xml": ["rsat"],
"application/automationml-aml+xml": ["aml"],
"application/automationml-amlx+zip": ["amlx"],
"application/bdoc": ["bdoc"],
"application/calendar+xml": ["xcs"],
"application/ccxml+xml": ["ccxml"],
"application/cdfx+xml": ["cdfx"],
"application/cdmi-capability": ["cdmia"],
"application/cdmi-container": ["cdmic"],
"application/cdmi-domain": ["cdmid"],
"application/cdmi-object": ["cdmio"],
"application/cdmi-queue": ["cdmiq"],
"application/cpl+xml": ["cpl"],
"application/cu-seeme": ["cu"],
"application/cwl": ["cwl"],
"application/dash+xml": ["mpd"],
"application/dash-patch+xml": ["mpp"],
"application/davmount+xml": ["davmount"],
"application/dicom": ["dcm"],
"application/docbook+xml": ["dbk"],
"application/dssc+der": ["dssc"],
"application/dssc+xml": ["xdssc"],
"application/ecmascript": ["ecma"],
"application/emma+xml": ["emma"],
"application/emotionml+xml": ["emotionml"],
"application/epub+zip": ["epub"],
"application/exi": ["exi"],
"application/express": ["exp"],
"application/fdf": ["fdf"],
"application/fdt+xml": ["fdt"],
"application/font-tdpfr": ["pfr"],
"application/geo+json": ["geojson"],
"application/gml+xml": ["gml"],
"application/gpx+xml": ["gpx"],
"application/gxf": ["gxf"],
"application/gzip": ["gz"],
"application/hjson": ["hjson"],
"application/hyperstudio": ["stk"],
"application/inkml+xml": ["ink", "inkml"],
"application/ipfix": ["ipfix"],
"application/its+xml": ["its"],
"application/java-archive": [
"jar",
"war",
"ear"
],
"application/java-serialized-object": ["ser"],
"application/java-vm": ["class"],
"application/javascript": ["*js"],
"application/json": ["json", "map"],
"application/json5": ["json5"],
"application/jsonml+json": ["jsonml"],
"application/ld+json": ["jsonld"],
"application/lgr+xml": ["lgr"],
"application/lost+xml": ["lostxml"],
"application/mac-binhex40": ["hqx"],
"application/mac-compactpro": ["cpt"],
"application/mads+xml": ["mads"],
"application/manifest+json": ["webmanifest"],
"application/marc": ["mrc"],
"application/marcxml+xml": ["mrcx"],
"application/mathematica": [
"ma",
"nb",
"mb"
],
"application/mathml+xml": ["mathml"],
"application/mbox": ["mbox"],
"application/media-policy-dataset+xml": ["mpf"],
"application/mediaservercontrol+xml": ["mscml"],
"application/metalink+xml": ["metalink"],
"application/metalink4+xml": ["meta4"],
"application/mets+xml": ["mets"],
"application/mmt-aei+xml": ["maei"],
"application/mmt-usd+xml": ["musd"],
"application/mods+xml": ["mods"],
"application/mp21": ["m21", "mp21"],
"application/mp4": [
"*mp4",
"*mpg4",
"mp4s",
"m4p"
],
"application/msix": ["msix"],
"application/msixbundle": ["msixbundle"],
"application/msword": ["doc", "dot"],
"application/mxf": ["mxf"],
"application/n-quads": ["nq"],
"application/n-triples": ["nt"],
"application/node": ["cjs"],
"application/octet-stream": [
"bin",
"dms",
"lrf",
"mar",
"so",
"dist",
"distz",
"pkg",
"bpk",
"dump",
"elc",
"deploy",
"exe",
"dll",
"deb",
"dmg",
"iso",
"img",
"msi",
"msp",
"msm",
"buffer"
],
"application/oda": ["oda"],
"application/oebps-package+xml": ["opf"],
"application/ogg": ["ogx"],
"application/omdoc+xml": ["omdoc"],
"application/onenote": [
"onetoc",
"onetoc2",
"onetmp",
"onepkg",
"one",
"onea"
],
"application/oxps": ["oxps"],
"application/p2p-overlay+xml": ["relo"],
"application/patch-ops-error+xml": ["xer"],
"application/pdf": ["pdf"],
"application/pgp-encrypted": ["pgp"],
"application/pgp-keys": ["asc"],
"application/pgp-signature": ["sig", "*asc"],
"application/pics-rules": ["prf"],
"application/pkcs10": ["p10"],
"application/pkcs7-mime": ["p7m", "p7c"],
"application/pkcs7-signature": ["p7s"],
"application/pkcs8": ["p8"],
"application/pkix-attr-cert": ["ac"],
"application/pkix-cert": ["cer"],
"application/pkix-crl": ["crl"],
"application/pkix-pkipath": ["pkipath"],
"application/pkixcmp": ["pki"],
"application/pls+xml": ["pls"],
"application/postscript": [
"ai",
"eps",
"ps"
],
"application/provenance+xml": ["provx"],
"application/pskc+xml": ["pskcxml"],
"application/raml+yaml": ["raml"],
"application/rdf+xml": ["rdf", "owl"],
"application/reginfo+xml": ["rif"],
"application/relax-ng-compact-syntax": ["rnc"],
"application/resource-lists+xml": ["rl"],
"application/resource-lists-diff+xml": ["rld"],
"application/rls-services+xml": ["rs"],
"application/route-apd+xml": ["rapd"],
"application/route-s-tsid+xml": ["sls"],
"application/route-usd+xml": ["rusd"],
"application/rpki-ghostbusters": ["gbr"],
"application/rpki-manifest": ["mft"],
"application/rpki-roa": ["roa"],
"application/rsd+xml": ["rsd"],
"application/rss+xml": ["rss"],
"application/rtf": ["rtf"],
"application/sbml+xml": ["sbml"],
"application/scvp-cv-request": ["scq"],
"application/scvp-cv-response": ["scs"],
"application/scvp-vp-request": ["spq"],
"application/scvp-vp-response": ["spp"],
"application/sdp": ["sdp"],
"application/senml+xml": ["senmlx"],
"application/sensml+xml": ["sensmlx"],
"application/set-payment-initiation": ["setpay"],
"application/set-registration-initiation": ["setreg"],
"application/shf+xml": ["shf"],
"application/sieve": ["siv", "sieve"],
"application/smil+xml": ["smi", "smil"],
"application/sparql-query": ["rq"],
"application/sparql-results+xml": ["srx"],
"application/sql": ["sql"],
"application/srgs": ["gram"],
"application/srgs+xml": ["grxml"],
"application/sru+xml": ["sru"],
"application/ssdl+xml": ["ssdl"],
"application/ssml+xml": ["ssml"],
"application/swid+xml": ["swidtag"],
"application/tei+xml": ["tei", "teicorpus"],
"application/thraud+xml": ["tfi"],
"application/timestamped-data": ["tsd"],
"application/toml": ["toml"],
"application/trig": ["trig"],
"application/ttml+xml": ["ttml"],
"application/ubjson": ["ubj"],
"application/urc-ressheet+xml": ["rsheet"],
"application/urc-targetdesc+xml": ["td"],
"application/voicexml+xml": ["vxml"],
"application/wasm": ["wasm"],
"application/watcherinfo+xml": ["wif"],
"application/widget": ["wgt"],
"application/winhlp": ["hlp"],
"application/wsdl+xml": ["wsdl"],
"application/wspolicy+xml": ["wspolicy"],
"application/xaml+xml": ["xaml"],
"application/xcap-att+xml": ["xav"],
"application/xcap-caps+xml": ["xca"],
"application/xcap-diff+xml": ["xdf"],
"application/xcap-el+xml": ["xel"],
"application/xcap-ns+xml": ["xns"],
"application/xenc+xml": ["xenc"],
"application/xfdf": ["xfdf"],
"application/xhtml+xml": ["xhtml", "xht"],
"application/xliff+xml": ["xlf"],
"application/xml": [
"xml",
"xsl",
"xsd",
"rng"
],
"application/xml-dtd": ["dtd"],
"application/xop+xml": ["xop"],
"application/xproc+xml": ["xpl"],
"application/xslt+xml": ["*xsl", "xslt"],
"application/xspf+xml": ["xspf"],
"application/xv+xml": [
"mxml",
"xhvml",
"xvml",
"xvm"
],
"application/yang": ["yang"],
"application/yin+xml": ["yin"],
"application/zip": ["zip"],
"application/zip+dotlottie": ["lottie"],
"audio/3gpp": ["*3gpp"],
"audio/aac": ["adts", "aac"],
"audio/adpcm": ["adp"],
"audio/amr": ["amr"],
"audio/basic": ["au", "snd"],
"audio/midi": [
"mid",
"midi",
"kar",
"rmi"
],
"audio/mobile-xmf": ["mxmf"],
"audio/mp3": ["*mp3"],
"audio/mp4": [
"m4a",
"mp4a",
"m4b"
],
"audio/mpeg": [
"mpga",
"mp2",
"mp2a",
"mp3",
"m2a",
"m3a"
],
"audio/ogg": [
"oga",
"ogg",
"spx",
"opus"
],
"audio/s3m": ["s3m"],
"audio/silk": ["sil"],
"audio/wav": ["wav"],
"audio/wave": ["*wav"],
"audio/webm": ["weba"],
"audio/xm": ["xm"],
"font/collection": ["ttc"],
"font/otf": ["otf"],
"font/ttf": ["ttf"],
"font/woff": ["woff"],
"font/woff2": ["woff2"],
"image/aces": ["exr"],
"image/apng": ["apng"],
"image/avci": ["avci"],
"image/avcs": ["avcs"],
"image/avif": ["avif"],
"image/bmp": ["bmp", "dib"],
"image/cgm": ["cgm"],
"image/dicom-rle": ["drle"],
"image/dpx": ["dpx"],
"image/emf": ["emf"],
"image/fits": ["fits"],
"image/g3fax": ["g3"],
"image/gif": ["gif"],
"image/heic": ["heic"],
"image/heic-sequence": ["heics"],
"image/heif": ["heif"],
"image/heif-sequence": ["heifs"],
"image/hej2k": ["hej2"],
"image/ief": ["ief"],
"image/jaii": ["jaii"],
"image/jais": ["jais"],
"image/jls": ["jls"],
"image/jp2": ["jp2", "jpg2"],
"image/jpeg": [
"jpg",
"jpeg",
"jpe"
],
"image/jph": ["jph"],
"image/jphc": ["jhc"],
"image/jpm": ["jpm", "jpgm"],
"image/jpx": ["jpx", "jpf"],
"image/jxl": ["jxl"],
"image/jxr": ["jxr"],
"image/jxra": ["jxra"],
"image/jxrs": ["jxrs"],
"image/jxs": ["jxs"],
"image/jxsc": ["jxsc"],
"image/jxsi": ["jxsi"],
"image/jxss": ["jxss"],
"image/ktx": ["ktx"],
"image/ktx2": ["ktx2"],
"image/pjpeg": ["jfif"],
"image/png": ["png"],
"image/sgi": ["sgi"],
"image/svg+xml": ["svg", "svgz"],
"image/t38": ["t38"],
"image/tiff": ["tif", "tiff"],
"image/tiff-fx": ["tfx"],
"image/webp": ["webp"],
"image/wmf": ["wmf"],
"message/disposition-notification": ["disposition-notification"],
"message/global": ["u8msg"],
"message/global-delivery-status": ["u8dsn"],
"message/global-disposition-notification": ["u8mdn"],
"message/global-headers": ["u8hdr"],
"message/rfc822": [
"eml",
"mime",
"mht",
"mhtml"
],
"model/3mf": ["3mf"],
"model/gltf+json": ["gltf"],
"model/gltf-binary": ["glb"],
"model/iges": ["igs", "iges"],
"model/jt": ["jt"],
"model/mesh": [
"msh",
"mesh",
"silo"
],
"model/mtl": ["mtl"],
"model/obj": ["obj"],
"model/prc": ["prc"],
"model/step": [
"step",
"stp",
"stpnc",
"p21",
"210"
],
"model/step+xml": ["stpx"],
"model/step+zip": ["stpz"],
"model/step-xml+zip": ["stpxz"],
"model/stl": ["stl"],
"model/u3d": ["u3d"],
"model/vrml": ["wrl", "vrml"],
"model/x3d+binary": ["*x3db", "x3dbz"],
"model/x3d+fastinfoset": ["x3db"],
"model/x3d+vrml": ["*x3dv", "x3dvz"],
"model/x3d+xml": ["x3d", "x3dz"],
"model/x3d-vrml": ["x3dv"],
"text/cache-manifest": ["appcache", "manifest"],
"text/calendar": ["ics", "ifb"],
"text/coffeescript": ["coffee", "litcoffee"],
"text/css": ["css"],
"text/csv": ["csv"],
"text/html": [
"html",
"htm",
"shtml"
],
"text/jade": ["jade"],
"text/javascript": ["js", "mjs"],
"text/jsx": ["jsx"],
"text/less": ["less"],
"text/markdown": ["md", "markdown"],
"text/mathml": ["mml"],
"text/mdx": ["mdx"],
"text/n3": ["n3"],
"text/plain": [
"txt",
"text",
"conf",
"def",
"list",
"log",
"in",
"ini"
],
"text/richtext": ["rtx"],
"text/rtf": ["*rtf"],
"text/sgml": ["sgml", "sgm"],
"text/shex": ["shex"],
"text/slim": ["slim", "slm"],
"text/spdx": ["spdx"],
"text/stylus": ["stylus", "styl"],
"text/tab-separated-values": ["tsv"],
"text/troff": [
"t",
"tr",
"roff",
"man",
"me",
"ms"
],
"text/turtle": ["ttl"],
"text/uri-list": [
"uri",
"uris",
"urls"
],
"text/vcard": ["vcard"],
"text/vtt": ["vtt"],
"text/wgsl": ["wgsl"],
"text/xml": ["*xml"],
"text/yaml": ["yaml", "yml"],
"video/3gpp": ["3gp", "3gpp"],
"video/3gpp2": ["3g2"],
"video/h261": ["h261"],
"video/h263": ["h263"],
"video/h264": ["h264"],
"video/iso.segment": ["m4s"],
"video/jpeg": ["jpgv"],
"video/jpm": ["*jpm", "*jpgm"],
"video/mj2": ["mj2", "mjp2"],
"video/mp2t": [
"ts",
"m2t",
"m2ts",
"mts"
],
"video/mp4": [
"mp4",
"mp4v",
"mpg4"
],
"video/mpeg": [
"mpeg",
"mpg",
"mpe",
"m1v",
"m2v"
],
"video/ogg": ["ogv"],
"video/quicktime": ["qt", "mov"],
"video/webm": ["webm"]
};
Object.freeze(types);
var standard_default = types;
//#endregion
//#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet = void 0 && (void 0).__classPrivateFieldGet || function(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;
var Mime = class {
constructor(...args) {
_Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
_Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
_Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
for (const arg of args) this.define(arg);
}
define(typeMap, force = false) {
for (let [type, extensions] of Object.entries(typeMap)) {
type = type.toLowerCase();
extensions = extensions.map((ext) => ext.toLowerCase());
if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
let first = true;
for (let extension of extensions) {
const starred = extension.startsWith("*");
extension = starred ? extension.slice(1) : extension;
allExtensions?.add(extension);
if (first) __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
first = false;
if (starred) continue;
const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
if (currentType && currentType != type && !force) throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
__classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
}
}
return this;
}
getType(path) {
if (typeof path !== "string") return null;
const last = path.replace(/^.*[/\\]/s, "").toLowerCase();
const ext = last.replace(/^.*\./s, "").toLowerCase();
const hasPath = last.length < path.length;
if (!(ext.length < last.length - 1) && hasPath) return null;
return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
}
getExtension(type) {
if (typeof type !== "string") return null;
type = type?.split?.(";")[0];
return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
}
getAllExtensions(type) {
if (typeof type !== "string") return null;
return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
}
_freeze() {
this.define = () => {
throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
};
Object.freeze(this);
for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) Object.freeze(extensions);
return this;
}
_getTestState() {
return {
types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
};
}
};
_Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
var Mime_default = Mime;
//#endregion
//#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/index.js
var src_default = new Mime_default(standard_default, other_default)._freeze();
//#endregion
export { src_default as t };
import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs";
import { i as require_node_fetch_native_DhEqb06g, r as require_node } from "./giget.mjs";
//#region node_modules/.pnpm/node-fetch-native@1.6.7/node_modules/node-fetch-native/dist/chunks/multipart-parser.cjs
var require_multipart_parser = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/node-fetch-native@1.6.7/node_modules/node-fetch-native/dist/chunks/multipart-parser.cjs": ((exports) => {
var y = Object.defineProperty;
var c = (R, o) => y(R, "name", {
value: o,
configurable: !0
});
const node = require_node();
__require("node:http"), __require("node:https"), __require("node:zlib"), __require("node:stream"), __require("node:buffer"), __require("node:util"), require_node_fetch_native_DhEqb06g(), __require("node:url"), __require("node:net"), __require("node:fs"), __require("node:path");
let s = 0;
const S = {
START_BOUNDARY: s++,
HEADER_FIELD_START: s++,
HEADER_FIELD: s++,
HEADER_VALUE_START: s++,
HEADER_VALUE: s++,
HEADER_VALUE_ALMOST_DONE: s++,
HEADERS_ALMOST_DONE: s++,
PART_DATA_START: s++,
PART_DATA: s++,
END: s++
};
let f = 1;
const F = {
PART_BOUNDARY: f,
LAST_BOUNDARY: f *= 2
}, LF = 10, CR = 13, SPACE = 32, HYPHEN = 45, COLON = 58, A = 97, Z = 122, lower = c((R) => R | 32, "lower"), noop = c(() => {}, "noop"), g = class g$1 {
constructor(o) {
this.index = 0, this.flags = 0, this.onHeaderEnd = noop, this.onHeaderField = noop, this.onHeadersEnd = noop, this.onHeaderValue = noop, this.onPartBegin = noop, this.onPartData = noop, this.onPartEnd = noop, this.boundaryChars = {}, o = `\r
--` + o;
const t = new Uint8Array(o.length);
for (let n = 0; n < o.length; n++) t[n] = o.charCodeAt(n), this.boundaryChars[t[n]] = !0;
this.boundary = t, this.lookbehind = new Uint8Array(this.boundary.length + 8), this.state = S.START_BOUNDARY;
}
write(o) {
let t = 0;
const n = o.length;
let E = this.index, { lookbehind: l, boundary: h, boundaryChars: H, index: e, state: a, flags: d } = this;
const b = this.boundary.length, m = b - 1, O = o.length;
let r, P;
const u = c((D) => {
this[D + "Mark"] = t;
}, "mark"), i = c((D) => {
delete this[D + "Mark"];
}, "clear"), T = c((D, p, _, N) => {
(p === void 0 || p !== _) && this[D](N && N.subarray(p, _));
}, "callback"), L = c((D, p) => {
const _ = D + "Mark";
_ in this && (p ? (T(D, this[_], t, o), delete this[_]) : (T(D, this[_], o.length, o), this[_] = 0));
}, "dataCallback");
for (t = 0; t < n; t++) switch (r = o[t], a) {
case S.START_BOUNDARY:
if (e === h.length - 2) {
if (r === HYPHEN) d |= F.LAST_BOUNDARY;
else if (r !== CR) return;
e++;
break;
} else if (e - 1 === h.length - 2) {
if (d & F.LAST_BOUNDARY && r === HYPHEN) a = S.END, d = 0;
else if (!(d & F.LAST_BOUNDARY) && r === LF) e = 0, T("onPartBegin"), a = S.HEADER_FIELD_START;
else return;
break;
}
r !== h[e + 2] && (e = -2), r === h[e + 2] && e++;
break;
case S.HEADER_FIELD_START: a = S.HEADER_FIELD, u("onHeaderField"), e = 0;
case S.HEADER_FIELD:
if (r === CR) {
i("onHeaderField"), a = S.HEADERS_ALMOST_DONE;
break;
}
if (e++, r === HYPHEN) break;
if (r === COLON) {
if (e === 1) return;
L("onHeaderField", !0), a = S.HEADER_VALUE_START;
break;
}
if (P = lower(r), P < A || P > Z) return;
break;
case S.HEADER_VALUE_START:
if (r === SPACE) break;
u("onHeaderValue"), a = S.HEADER_VALUE;
case S.HEADER_VALUE:
r === CR && (L("onHeaderValue", !0), T("onHeaderEnd"), a = S.HEADER_VALUE_ALMOST_DONE);
break;
case S.HEADER_VALUE_ALMOST_DONE:
if (r !== LF) return;
a = S.HEADER_FIELD_START;
break;
case S.HEADERS_ALMOST_DONE:
if (r !== LF) return;
T("onHeadersEnd"), a = S.PART_DATA_START;
break;
case S.PART_DATA_START: a = S.PART_DATA, u("onPartData");
case S.PART_DATA:
if (E = e, e === 0) {
for (t += m; t < O && !(o[t] in H);) t += b;
t -= m, r = o[t];
}
if (e < h.length) h[e] === r ? (e === 0 && L("onPartData", !0), e++) : e = 0;
else if (e === h.length) e++, r === CR ? d |= F.PART_BOUNDARY : r === HYPHEN ? d |= F.LAST_BOUNDARY : e = 0;
else if (e - 1 === h.length) if (d & F.PART_BOUNDARY) {
if (e = 0, r === LF) {
d &= ~F.PART_BOUNDARY, T("onPartEnd"), T("onPartBegin"), a = S.HEADER_FIELD_START;
break;
}
} else d & F.LAST_BOUNDARY && r === HYPHEN ? (T("onPartEnd"), a = S.END, d = 0) : e = 0;
if (e > 0) l[e - 1] = r;
else if (E > 0) {
const D = new Uint8Array(l.buffer, l.byteOffset, l.byteLength);
T("onPartData", 0, E, D), E = 0, u("onPartData"), t--;
}
break;
case S.END: break;
default: throw new Error(`Unexpected state entered: ${a}`);
}
L("onHeaderField"), L("onHeaderValue"), L("onPartData"), this.index = e, this.state = a, this.flags = d;
}
end() {
if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) this.onPartEnd();
else if (this.state !== S.END) throw new Error("MultipartParser.end(): stream ended unexpectedly");
}
};
c(g, "MultipartParser");
let MultipartParser = g;
function _fileName(R) {
const o = R.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
if (!o) return;
const t = o[2] || o[3] || "";
let n = t.slice(t.lastIndexOf("\\") + 1);
return n = n.replace(/%22/g, "\""), n = n.replace(/&#(\d{4});/g, (E, l) => String.fromCharCode(l)), n;
}
c(_fileName, "_fileName");
async function toFormData(R, o) {
if (!/multipart/i.test(o)) throw new TypeError("Failed to fetch");
const t = o.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
if (!t) throw new TypeError("no or bad content-type header, no multipart boundary");
const n = new MultipartParser(t[1] || t[2]);
let E, l, h, H, e, a;
const d = [], b = new node.FormData(), m = c((i) => {
h += u.decode(i, { stream: !0 });
}, "onPartData"), O = c((i) => {
d.push(i);
}, "appendToFile"), r = c(() => {
const i = new node.File(d, a, { type: e });
b.append(H, i);
}, "appendFileToFormData"), P = c(() => {
b.append(H, h);
}, "appendEntryToFormData"), u = new TextDecoder("utf-8");
u.decode(), n.onPartBegin = function() {
n.onPartData = m, n.onPartEnd = P, E = "", l = "", h = "", H = "", e = "", a = null, d.length = 0;
}, n.onHeaderField = function(i) {
E += u.decode(i, { stream: !0 });
}, n.onHeaderValue = function(i) {
l += u.decode(i, { stream: !0 });
}, n.onHeaderEnd = function() {
if (l += u.decode(), E = E.toLowerCase(), E === "content-disposition") {
const i = l.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
i && (H = i[2] || i[3] || ""), a = _fileName(l), a && (n.onPartData = O, n.onPartEnd = r);
} else E === "content-type" && (e = l);
l = "", E = "";
};
for await (const i of R) n.write(i);
return n.end(), b;
}
c(toFormData, "toFormData"), exports.toFormData = toFormData;
}) });
//#endregion
export { require_multipart_parser as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js
var require_path_parse = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js": ((exports, module) => {
var isWindows = process.platform === "win32";
var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
var win32 = {};
function win32SplitPath(filename) {
return splitWindowsRe.exec(filename).slice(1);
}
win32.parse = function(pathString) {
if (typeof pathString !== "string") throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 5) throw new TypeError("Invalid path '" + pathString + "'");
return {
root: allParts[1],
dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
var posix = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
posix.parse = function(pathString) {
if (typeof pathString !== "string") throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 5) throw new TypeError("Invalid path '" + pathString + "'");
return {
root: allParts[1],
dir: allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
if (isWindows) module.exports = win32.parse;
else module.exports = posix.parse;
module.exports.posix = posix.parse;
module.exports.win32 = win32.parse;
}) });
//#endregion
export { require_path_parse as t };
import { E as normalizeWindowsPath, w as join } from "./c12.mjs";
//#region node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/utils.mjs
const pathSeparators = /* @__PURE__ */ new Set([
"/",
"\\",
void 0
]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) return _aliases;
const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b)));
for (const key in aliases) for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) continue;
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) continue;
if (hasTrailingSlash(_path[(hasTrailingSlash(alias) ? alias.slice(0, -1) : alias).length])) return join(to, _path.slice(alias.length));
}
return _path;
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
//#endregion
export { resolveAlias as t };
import { t as __commonJS } from "../_chunks/Bqks5huO.mjs";
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js
var require_constants = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js": ((exports, module) => {
const WIN_SLASH = "\\\\/";
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
* Posix glob regex
*/
const DOT_LITERAL = "\\.";
const PLUS_LITERAL = "\\+";
const QMARK_LITERAL = "\\?";
const SLASH_LITERAL = "\\/";
const ONE_CHAR = "(?=.)";
const QMARK = "[^/]";
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!${START_ANCHOR}${DOTS_SLASH})`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`,
NO_DOTS_SLASH: `(?!${DOTS_SLASH})`,
QMARK_NO_DOT: `[^.${SLASH_LITERAL}]`,
STAR: `${QMARK}*?`,
START_ANCHOR,
SEP: "/"
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: "\\"
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE$1 = {
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
REPLACEMENTS: {
__proto__: null,
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
CHAR_0: 48,
CHAR_9: 57,
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_LEFT_PARENTHESES: 40,
CHAR_RIGHT_PARENTHESES: 41,
CHAR_ASTERISK: 42,
CHAR_AMPERSAND: 38,
CHAR_AT: 64,
CHAR_BACKWARD_SLASH: 92,
CHAR_CARRIAGE_RETURN: 13,
CHAR_CIRCUMFLEX_ACCENT: 94,
CHAR_COLON: 58,
CHAR_COMMA: 44,
CHAR_DOT: 46,
CHAR_DOUBLE_QUOTE: 34,
CHAR_EQUAL: 61,
CHAR_EXCLAMATION_MARK: 33,
CHAR_FORM_FEED: 12,
CHAR_FORWARD_SLASH: 47,
CHAR_GRAVE_ACCENT: 96,
CHAR_HASH: 35,
CHAR_HYPHEN_MINUS: 45,
CHAR_LEFT_ANGLE_BRACKET: 60,
CHAR_LEFT_CURLY_BRACE: 123,
CHAR_LEFT_SQUARE_BRACKET: 91,
CHAR_LINE_FEED: 10,
CHAR_NO_BREAK_SPACE: 160,
CHAR_PERCENT: 37,
CHAR_PLUS: 43,
CHAR_QUESTION_MARK: 63,
CHAR_RIGHT_ANGLE_BRACKET: 62,
CHAR_RIGHT_CURLY_BRACE: 125,
CHAR_RIGHT_SQUARE_BRACKET: 93,
CHAR_SEMICOLON: 59,
CHAR_SINGLE_QUOTE: 39,
CHAR_SPACE: 32,
CHAR_TAB: 9,
CHAR_UNDERSCORE: 95,
CHAR_VERTICAL_LINE: 124,
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
extglobChars(chars) {
return {
"!": {
type: "negate",
open: "(?:(?!(?:",
close: `))${chars.STAR})`
},
"?": {
type: "qmark",
open: "(?:",
close: ")?"
},
"+": {
type: "plus",
open: "(?:",
close: ")+"
},
"*": {
type: "star",
open: "(?:",
close: ")*"
},
"@": {
type: "at",
open: "(?:",
close: ")"
}
};
},
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
}) });
//#endregion
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js
var require_utils = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js": ((exports) => {
const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports.isWindows = () => {
if (typeof navigator !== "undefined" && navigator.platform) {
const platform = navigator.platform.toLowerCase();
return platform === "win32" || platform === "windows";
}
if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
return false;
};
exports.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
return match === "\\" ? "" : match;
});
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
let output = `${options.contains ? "" : "^"}(?:${input})${options.contains ? "" : "$"}`;
if (state.negated === true) output = `(?:^(?!${output}).*$)`;
return output;
};
exports.basename = (path, { windows } = {}) => {
const segs = path.split(windows ? /[\\/]/ : "/");
const last = segs[segs.length - 1];
if (last === "") return segs[segs.length - 2];
return last;
};
}) });
//#endregion
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js
var require_scan = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js": ((exports, module) => {
const utils$3 = require_utils();
const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
const isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = (token) => {
if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan$1 = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = {
value: "",
depth: 0,
isGlob: false
};
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = {
value: "",
depth: 0,
isGlob: false
};
if (finished === true) continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) continue;
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) continue;
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = "";
let glob = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = "";
glob = str;
} else base = str;
if (base && base !== "" && base !== "/" && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
}
if (opts.unescape === true) {
if (glob) glob = utils$3.removeBackslashes(glob);
if (base && backslashes === true) base = utils$3.removeBackslashes(base);
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) tokens.push(token);
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else tokens[idx].value = value;
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") parts.push(value);
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan$1;
}) });
//#endregion
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js
var require_parse = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js": ((exports, module) => {
const constants$1 = require_constants();
const utils$2 = require_utils();
/**
* Constants
*/
const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
/**
* Helpers
*/
const expandRange = (args, options) => {
if (typeof options.expandRange === "function") return options.expandRange(...args, options);
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v) => utils$2.escapeRegex(v)).join("..");
}
return value;
};
/**
* Create the message for a syntax error
*/
const syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
/**
* Parse the given input string.
* @param {String} input
* @param {Object} options
* @return {Object}
*/
const parse$1 = (input, options) => {
if (typeof input !== "string") throw new TypeError("Expected a string");
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
const bos = {
type: "bos",
value: "",
output: opts.prepend || ""
};
const tokens = [bos];
const capture = opts.capture ? "" : "?:";
const PLATFORM_CHARS = constants$1.globChars(opts.windows);
const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK: QMARK$1, QMARK_NO_DOT, STAR, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS;
const globstar = (opts$1) => {
return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
};
const nodot = opts.dot ? "" : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
if (opts.capture) star = `(${star})`;
if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
const state = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: "",
output: "",
prefix: "",
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
input = utils$2.removePrefix(input, state);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
/**
* Tokenizing helpers
*/
const eos = () => state.index === len - 1;
const peek = state.peek = (n = 1) => input[state.index + n];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume = (value$1 = "", num = 0) => {
state.consumed += value$1;
state.index += num;
};
const append = (token) => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) return false;
state.negated = true;
state.start++;
return true;
};
const increment = (type) => {
state[type]++;
stack.push(type);
};
const decrement = (type) => {
state[type]--;
stack.pop();
};
/**
* Push tokens onto the tokens array. This helper speeds up
* tokenizing by 1) helping us avoid backtracking as much as possible,
* and 2) helping us avoid creating extra tokens when consecutive
* characters are plain text. This improves performance and simplifies
* lookbehinds.
*/
const push = (tok) => {
if (prev.type === "globstar") {
const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star;
state.output += prev.output;
}
}
if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
if (tok.value || tok.output) append(tok);
if (prev && prev.type === "text" && tok.type === "text") {
prev.output = (prev.output || prev.value) + tok.value;
prev.value += tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value$1) => {
const token = {
...EXTGLOB_CHARS[value$1],
conditions: 1,
inner: ""
};
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? "(" : "") + token.open;
increment("parens");
push({
type,
value: value$1,
output: state.output ? "" : ONE_CHAR$1
});
push({
type: "paren",
extglob: true,
value: advance(),
output
});
extglobs.push(token);
};
const extglobClose = (token) => {
let output = token.close + (opts.capture ? ")" : "");
let rest;
if (token.type === "negate") {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse$1(rest, {
...options,
fastpaths: false
}).output})${extglobStar})`;
if (token.prev.type === "bos") state.negatedExtglob = true;
}
push({
type: "paren",
extglob: true,
value,
output
});
decrement("parens");
};
/**
* Fast paths
*/
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m;
}
if (first === "?") {
if (esc) return esc + first + (rest ? QMARK$1.repeat(rest.length) : "");
if (index === 0) return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "");
return QMARK$1.repeat(chars.length);
}
if (first === ".") return DOT_LITERAL$1.repeat(chars.length);
if (first === "*") {
if (esc) return esc + first + (rest ? star : "");
return star;
}
return esc ? m : `\\${m}`;
});
if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
else output = output.replace(/\\+/g, (m) => {
return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
});
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
state.output = utils$2.wrapOutput(output, state, options);
return state;
}
/**
* Tokenize input until we reach end-of-string
*/
while (!eos()) {
value = advance();
if (value === "\0") continue;
/**
* Escaped characters
*/
if (value === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) continue;
if (next === "." || next === ";") continue;
if (!next) {
value += "\\";
push({
type: "text",
value
});
continue;
}
const match = /^\\+/.exec(remaining());
let slashes = 0;
if (match && match[0].length > 2) {
slashes = match[0].length;
state.index += slashes;
if (slashes % 2 !== 0) value += "\\";
}
if (opts.unescape === true) value = advance();
else value += advance();
if (state.brackets === 0) {
push({
type: "text",
value
});
continue;
}
}
/**
* If we're inside a regex character class, continue
* until we reach the closing bracket.
*/
if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value === ":") {
const inner = prev.value.slice(1);
if (inner.includes("[")) {
prev.posix = true;
if (inner.includes(":")) {
const idx = prev.value.lastIndexOf("[");
const pre = prev.value.slice(0, idx);
const posix = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)];
if (posix) {
prev.value = pre + posix;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1;
continue;
}
}
}
}
if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
prev.value += value;
append({ value });
continue;
}
/**
* If we're inside a quoted string, continue
* until we reach the closing double quote.
*/
if (state.quotes === 1 && value !== "\"") {
value = utils$2.escapeRegex(value);
prev.value += value;
append({ value });
continue;
}
/**
* Double quotes
*/
if (value === "\"") {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) push({
type: "text",
value
});
continue;
}
/**
* Parentheses
*/
if (value === "(") {
increment("parens");
push({
type: "paren",
value
});
continue;
}
if (value === ")") {
if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({
type: "paren",
value,
output: state.parens ? ")" : "\\)"
});
decrement("parens");
continue;
}
/**
* Square brackets
*/
if (value === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
value = `\\${value}`;
} else increment("brackets");
push({
type: "bracket",
value
});
continue;
}
if (value === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push({
type: "text",
value,
output: `\\${value}`
});
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
push({
type: "text",
value,
output: `\\${value}`
});
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
prev.value += value;
append({ value });
if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue;
const escaped = utils$2.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
/**
* Braces
*/
if (value === "{" && opts.nobrace !== true) {
increment("braces");
const open = {
type: "brace",
value,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open);
push(open);
continue;
}
if (value === "}") {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({
type: "text",
value,
output: value
});
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === "brace") break;
if (arr[i].type !== "dots") range.unshift(arr[i].value);
}
output = expandRange(range, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value = output = "\\}";
state.output = out;
for (const t of toks) state.output += t.output || t.value;
}
push({
type: "brace",
value,
output
});
decrement("braces");
braces.pop();
continue;
}
/**
* Pipes
*/
if (value === "|") {
if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
push({
type: "text",
value
});
continue;
}
/**
* Commas
*/
if (value === ",") {
let output = value;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push({
type: "comma",
value,
output
});
continue;
}
/**
* Slashes
*/
if (value === "/") {
if (prev.type === "dot" && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = "";
state.output = "";
tokens.pop();
prev = bos;
continue;
}
push({
type: "slash",
value,
output: SLASH_LITERAL$1
});
continue;
}
/**
* Dots
*/
if (value === ".") {
if (state.braces > 0 && prev.type === "dot") {
if (prev.value === ".") prev.output = DOT_LITERAL$1;
const brace = braces[braces.length - 1];
prev.type = "dots";
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({
type: "text",
value,
output: DOT_LITERAL$1
});
continue;
}
push({
type: "dot",
value,
output: DOT_LITERAL$1
});
continue;
}
/**
* Question marks
*/
if (value === "?") {
if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value;
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
push({
type: "text",
value,
output
});
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push({
type: "qmark",
value,
output: QMARK_NO_DOT
});
continue;
}
push({
type: "qmark",
value,
output: QMARK$1
});
continue;
}
/**
* Exclamation
*/
if (value === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
/**
* Plus
*/
if (value === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push({
type: "plus",
value,
output: PLUS_LITERAL$1
});
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push({
type: "plus",
value
});
continue;
}
push({
type: "plus",
value: PLUS_LITERAL$1
});
continue;
}
/**
* Plain text
*/
if (value === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push({
type: "at",
extglob: true,
value,
output: ""
});
continue;
}
push({
type: "text",
value
});
continue;
}
/**
* Plain text
*/
if (value !== "*") {
if (value === "$" || value === "^") value = `\\${value}`;
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state.index += match[0].length;
}
push({
type: "text",
value
});
continue;
}
/**
* Stars
*/
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume(value);
continue;
}
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === "slash" || prior.type === "bos";
const afterStar = before && (before.type === "star" || before.type === "globstar");
if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
push({
type: "star",
value,
output: ""
});
continue;
}
const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
push({
type: "star",
value,
output: ""
});
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state.index + 4];
if (after && after !== "/") break;
rest = rest.slice(3);
consume("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== void 0 ? "|$" : "";
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`;
prev.value += value;
state.output += prior.output + prev.output;
state.globstar = true;
consume(value + advance());
push({
type: "slash",
value: "/",
output: ""
});
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`;
state.output = prev.output;
state.globstar = true;
consume(value + advance());
push({
type: "slash",
value: "/",
output: ""
});
continue;
}
state.output = state.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value;
state.output += prev.output;
state.globstar = true;
consume(value);
continue;
}
const token = {
type: "star",
value,
output: star
};
if (opts.bash === true) {
token.output = ".*?";
if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
push(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
token.output = value;
push(token);
continue;
}
if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state.output += ONE_CHAR$1;
prev.output += ONE_CHAR$1;
}
}
push(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils$2.escapeLast(state.output, "[");
decrement("brackets");
}
while (state.parens > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils$2.escapeLast(state.output, "(");
decrement("parens");
}
while (state.braces > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils$2.escapeLast(state.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
type: "maybe_slash",
value: "",
output: `${SLASH_LITERAL$1}?`
});
if (state.backtrack === true) {
state.output = "";
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
if (token.suffix) state.output += token.suffix;
}
}
return state;
};
/**
* Fast paths for creating regular expressions for common glob patterns.
* This can significantly speed up processing and has very little downside
* impact when none of the fast paths match.
*/
parse$1.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
input = REPLACEMENTS[input] || input;
const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR: START_ANCHOR$1 } = constants$1.globChars(opts.windows);
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? "" : "?:";
const state = {
negated: false,
prefix: ""
};
let star = opts.bash === true ? ".*?" : STAR;
if (opts.capture) star = `(${star})`;
const globstar = (opts$1) => {
if (opts$1.noglobstar === true) return star;
return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
};
const create = (str) => {
switch (str) {
case "*": return `${nodot}${ONE_CHAR$1}${star}`;
case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
case "**": return nodot + globstar(opts);
case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match) return;
const source$1 = create(match[1]);
if (!source$1) return;
return source$1 + DOT_LITERAL$1 + match[2];
}
}
};
let source = create(utils$2.removePrefix(input, state));
if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`;
return source;
};
module.exports = parse$1;
}) });
//#endregion
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js
var require_picomatch$1 = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js": ((exports, module) => {
const scan = require_scan();
const parse = require_parse();
const utils$1 = require_utils();
const constants = require_constants();
const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
/**
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch(glob[, options]);
*
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
* @api public
*/
const picomatch$1 = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch$1(input, options, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state$1 = isMatch(str);
if (state$1) return state$1;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
const opts = options || {};
const posix = opts.windows;
const regex = isState ? picomatch$1.compileRe(glob, options) : picomatch$1.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = {
...options,
ignore: null,
onMatch: null,
onResult: null
};
isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch$1.test(input, regex, options, {
glob,
posix
});
const result = {
glob,
state,
regex,
posix,
input,
output,
match,
isMatch
};
if (typeof opts.onResult === "function") opts.onResult(result);
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === "function") opts.onIgnore(result);
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === "function") opts.onMatch(result);
return returnObject ? result : true;
};
if (returnState) matcher.state = state;
return matcher;
};
/**
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
* ```
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
* @api public
*/
picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== "string") throw new TypeError("Expected input to be a string");
if (input === "") return {
isMatch: false,
output: ""
};
const opts = options || {};
const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
let match = input === glob;
let output = match && format ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$1.matchBase(input, regex, options, posix);
else match = regex.exec(output);
return {
isMatch: Boolean(match),
match,
output
};
};
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
picomatch$1.matchBase = (input, glob, options) => {
return (glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options)).test(utils$1.basename(input));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
picomatch$1.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map((p) => picomatch$1.parse(p, options));
return parse(pattern, {
...options,
fastpaths: false
});
};
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
picomatch$1.scan = (input, options) => scan(input, options);
/**
* Compile a regular expression from the `state` object returned by the
* [parse()](#parse) method.
*
* @param {Object} `state`
* @param {Object} `options`
* @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
* @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* @return {RegExp}
* @api public
*/
picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) return state.output;
const opts = options || {};
const prepend = opts.contains ? "" : "^";
const append = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) source = `^(?!${source}).*$`;
const regex = picomatch$1.toRegex(source, options);
if (returnState === true) regex.state = state;
return regex;
};
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
let parsed = {
negated: false,
fastpaths: true
};
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
if (!parsed.output) parsed = parse(input, options);
return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
};
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
picomatch$1.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
/**
* Picomatch constants.
* @return {Object}
*/
picomatch$1.constants = constants;
/**
* Expose "picomatch"
*/
module.exports = picomatch$1;
}) });
//#endregion
//#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js
var require_picomatch = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js": ((exports, module) => {
const pico = require_picomatch$1();
const utils = require_utils();
function picomatch(glob, options, returnState = false) {
if (options && (options.windows === null || options.windows === void 0)) options = {
...options,
windows: utils.isWindows()
};
return pico(glob, options, returnState);
}
Object.assign(picomatch, pico);
module.exports = picomatch;
}) });
//#endregion
export { require_picomatch as t };
import path from "node:path";
//#region node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.53.2/node_modules/@rollup/plugin-alias/dist/index.js
function matches(pattern, importee) {
if (pattern instanceof RegExp) return pattern.test(importee);
if (importee.length < pattern.length) return false;
if (importee === pattern) return true;
return importee.startsWith(pattern + "/");
}
function getEntries({ entries, customResolver }) {
if (!entries) return [];
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) return entries.map((entry) => {
return {
find: entry.find,
replacement: entry.replacement,
resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
};
});
return Object.entries(entries).map(([key, value]) => {
return {
find: key,
replacement: value,
resolverFunction: resolverFunctionFromOptions
};
});
}
function getHookFunction(hook) {
if (typeof hook === "function") return hook;
if (hook && "handler" in hook && typeof hook.handler === "function") return hook.handler;
return null;
}
function resolveCustomResolver(customResolver) {
if (typeof customResolver === "function") return customResolver;
if (customResolver) return getHookFunction(customResolver.resolveId);
return null;
}
function alias(options = {}) {
const entries = getEntries(options);
if (entries.length === 0) return {
name: "alias",
resolveId: () => null
};
return {
name: "alias",
async buildStart(inputOptions) {
await Promise.all([...Array.isArray(options.entries) ? options.entries : [], options].map(({ customResolver }) => customResolver && getHookFunction(customResolver.buildStart)?.call(this, inputOptions)));
},
resolveId(importee, importer, resolveOptions) {
const matchedEntry = entries.find((entry) => matches(entry.find, importee));
if (!matchedEntry) return null;
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
if (resolved) return resolved;
if (!path.isAbsolute(updatedId)) this.warn(`rewrote ${importee} to ${updatedId} but was not an absolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`);
return { id: updatedId };
});
}
};
}
//#endregion
export { alias as t };

Sorry, the diff of this file is too big to display

import { t as MagicString } from "./magic-string.mjs";
import { n as walk } from "./estree-walker.mjs";
import { a as makeLegalIdentifier, n as attachScopes, r as createFilter } from "./plugin-commonjs.mjs";
import { sep } from "path";
//#region node_modules/.pnpm/@rollup+plugin-inject@5.0.5_rollup@4.53.2/node_modules/@rollup/plugin-inject/dist/es/index.js
var escape = function(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
};
var isReference = function(node, parent) {
if (node.type === "MemberExpression") return !node.computed && isReference(node.object, node);
if (node.type === "Identifier") {
if (parent.type === "MemberExpression") return parent.computed || node === parent.object;
if (parent.type === "Property" && node !== parent.value) return false;
if (parent.type === "MethodDefinition") return false;
if (parent.type === "ExportSpecifier" && node !== parent.local) return false;
if (parent.type === "ImportSpecifier" && node === parent.imported) return false;
return true;
}
return false;
};
var flatten = function(startNode) {
var parts = [];
var node = startNode;
while (node.type === "MemberExpression") {
parts.unshift(node.property.name);
node = node.object;
}
var name = node.name;
parts.unshift(name);
return {
name,
keypath: parts.join(".")
};
};
function inject(options) {
if (!options) throw new Error("Missing options");
var filter = createFilter(options.include, options.exclude);
var modules = options.modules;
if (!modules) {
modules = Object.assign({}, options);
delete modules.include;
delete modules.exclude;
delete modules.sourceMap;
delete modules.sourcemap;
}
var modulesMap = new Map(Object.entries(modules));
if (sep !== "/") modulesMap.forEach(function(mod, key) {
modulesMap.set(key, Array.isArray(mod) ? [mod[0].split(sep).join("/"), mod[1]] : mod.split(sep).join("/"));
});
var firstpass = new RegExp("(?:" + Array.from(modulesMap.keys()).map(escape).join("|") + ")", "g");
var sourceMap = options.sourceMap !== false && options.sourcemap !== false;
return {
name: "inject",
transform: function transform(code, id) {
if (!filter(id)) return null;
if (code.search(firstpass) === -1) return null;
if (sep !== "/") id = id.split(sep).join("/");
var ast = null;
try {
ast = this.parse(code);
} catch (err) {
this.warn({
code: "PARSE_ERROR",
message: "rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include"
});
}
if (!ast) return null;
var imports = /* @__PURE__ */ new Set();
ast.body.forEach(function(node) {
if (node.type === "ImportDeclaration") node.specifiers.forEach(function(specifier) {
imports.add(specifier.local.name);
});
});
var scope = attachScopes(ast, "scope");
var magicString = new MagicString(code);
var newImports = /* @__PURE__ */ new Map();
function handleReference(node, name, keypath) {
var mod = modulesMap.get(keypath);
if (mod && !imports.has(name) && !scope.contains(name)) {
if (typeof mod === "string") mod = [mod, "default"];
if (mod[0] === id) return false;
var hash = keypath + ":" + mod[0] + ":" + mod[1];
var importLocalName = name === keypath ? name : makeLegalIdentifier("$inject_" + keypath);
if (!newImports.has(hash)) {
var modName = mod[0].replace(/[''\\]/g, "\\$&");
if (mod[1] === "*") newImports.set(hash, "import * as " + importLocalName + " from '" + modName + "';");
else newImports.set(hash, "import { " + mod[1] + " as " + importLocalName + " } from '" + modName + "';");
}
if (name !== keypath) magicString.overwrite(node.start, node.end, importLocalName, { storeName: true });
return true;
}
return false;
}
walk(ast, {
enter: function enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
if (node.scope) scope = node.scope;
if (node.type === "Property" && node.shorthand && node.value.type === "Identifier") {
var name = node.key.name;
handleReference(node, name, name);
this.skip();
return;
}
if (isReference(node, parent)) {
var ref$1 = flatten(node);
var name$1 = ref$1.name;
var keypath = ref$1.keypath;
if (handleReference(node, name$1, keypath)) this.skip();
}
},
leave: function leave(node) {
if (node.scope) scope = scope.parent;
}
});
if (newImports.size === 0) return {
code,
ast,
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
var importBlock = Array.from(newImports.values()).join("\n\n");
magicString.prepend(importBlock + "\n\n");
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
};
}
//#endregion
export { inject as t };
import { i as dataToEsm, r as createFilter } from "./plugin-commonjs.mjs";
//#region node_modules/.pnpm/@rollup+plugin-json@6.1.0_rollup@4.53.2/node_modules/@rollup/plugin-json/dist/es/index.js
function json(options) {
if (options === void 0) options = {};
var filter = createFilter(options.include, options.exclude);
var indent = "indent" in options ? options.indent : " ";
return {
name: "json",
transform: function transform(code, id) {
if (id.slice(-5) !== ".json" || !filter(id)) return null;
try {
return {
code: dataToEsm(JSON.parse(code), {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
includeArbitraryNames: options.includeArbitraryNames,
indent
}),
map: { mappings: "" }
};
} catch (err) {
this.error({
message: "Could not parse JSON file",
id,
cause: err
});
return null;
}
}
};
}
//#endregion
export { json as t };
import { i as __toESM, n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs";
import { r as createFilter } from "./plugin-commonjs.mjs";
import { t as require_cjs } from "./deepmerge.mjs";
import { t as require_is_module } from "./is-module.mjs";
import { t as require_path_parse } from "./path-parse.mjs";
import { t as require_is_core_module } from "./is-core-module.mjs";
import nativeFs, { realpathSync } from "fs";
import path, { dirname, extname, normalize, resolve, sep } from "path";
import { fileURLToPath, pathToFileURL } from "url";
import { builtinModules } from "module";
import { promisify } from "util";
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/homedir.js
var require_homedir = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/homedir.js": ((exports, module) => {
var os = __require("os");
module.exports = os.homedir || function homedir$2() {
var home = process.env.HOME;
var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
if (process.platform === "win32") return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
if (process.platform === "darwin") return home || (user ? "/Users/" + user : null);
if (process.platform === "linux") return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null);
return home || null;
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/caller.js
var require_caller = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/caller.js": ((exports, module) => {
module.exports = function() {
var origPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack$1) {
return stack$1;
};
var stack = (/* @__PURE__ */ new Error()).stack;
Error.prepareStackTrace = origPrepareStackTrace;
return stack[2].getFileName();
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/node-modules-paths.js
var require_node_modules_paths = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/node-modules-paths.js": ((exports, module) => {
var path$3 = __require("path");
var parse = path$3.parse || require_path_parse();
var driveLetterRegex = /^([A-Za-z]:)/;
var uncPathRegex = /^\\\\/;
var getNodeModulesDirs = function getNodeModulesDirs$1(absoluteStart, modules) {
var prefix = "/";
if (driveLetterRegex.test(absoluteStart)) prefix = "";
else if (uncPathRegex.test(absoluteStart)) prefix = "\\\\";
var paths = [absoluteStart];
var parsed = parse(absoluteStart);
while (parsed.dir !== paths[paths.length - 1]) {
paths.push(parsed.dir);
parsed = parse(parsed.dir);
}
return paths.reduce(function(dirs, aPath) {
return dirs.concat(modules.map(function(moduleDir) {
return path$3.resolve(prefix, aPath, moduleDir);
}));
}, []);
};
module.exports = function nodeModulesPaths$2(start, opts, request) {
var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
if (opts && typeof opts.paths === "function") return opts.paths(request, start, function() {
return getNodeModulesDirs(start, modules);
}, opts);
var dirs = getNodeModulesDirs(start, modules);
return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/normalize-options.js
var require_normalize_options = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/normalize-options.js": ((exports, module) => {
module.exports = function(x, opts) {
/**
* This file is purposefully a passthrough. It's expected that third-party
* environments will override it at runtime in order to inject special logic
* into `resolve` (by manipulating the options). One such example is the PnP
* code path in Yarn.
*/
return opts || {};
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/async.js
var require_async = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/async.js": ((exports, module) => {
var fs$1 = __require("fs");
var getHomedir$1 = require_homedir();
var path$2 = __require("path");
var caller$1 = require_caller();
var nodeModulesPaths$1 = require_node_modules_paths();
var normalizeOptions$1 = require_normalize_options();
var isCore$1 = require_is_core_module();
var realpathFS$1 = process.platform !== "win32" && fs$1.realpath && typeof fs$1.realpath.native === "function" ? fs$1.realpath.native : fs$1.realpath;
var relativePathRegex$1 = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/;
var windowsDriveRegex$1 = /^\w:[/\\]*$/;
var nodeModulesRegex$1 = /[/\\]node_modules[/\\]*$/;
var homedir$1 = getHomedir$1();
var defaultPaths$1 = function() {
return [path$2.join(homedir$1, ".node_modules"), path$2.join(homedir$1, ".node_libraries")];
};
var defaultIsFile$1 = function isFile(file, cb) {
fs$1.stat(file, function(err, stat$2) {
if (!err) return cb(null, stat$2.isFile() || stat$2.isFIFO());
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
return cb(err);
});
};
var defaultIsDir$1 = function isDirectory(dir, cb) {
fs$1.stat(dir, function(err, stat$2) {
if (!err) return cb(null, stat$2.isDirectory());
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
return cb(err);
});
};
var defaultRealpath = function realpath$1(x, cb) {
realpathFS$1(x, function(realpathErr, realPath) {
if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr);
else cb(null, realpathErr ? x : realPath);
});
};
var maybeRealpath = function maybeRealpath$1(realpath$1, x, opts, cb) {
if (opts && opts.preserveSymlinks === false) realpath$1(x, cb);
else cb(null, x);
};
var defaultReadPackage = function defaultReadPackage$1(readFile$2, pkgfile, cb) {
readFile$2(pkgfile, function(readFileErr, body) {
if (readFileErr) cb(readFileErr);
else try {
cb(null, JSON.parse(body));
} catch (jsonErr) {
cb(null);
}
});
};
var getPackageCandidates$1 = function getPackageCandidates$2(x, start, opts) {
var dirs = nodeModulesPaths$1(start, opts, x);
for (var i = 0; i < dirs.length; i++) dirs[i] = path$2.join(dirs[i], x);
return dirs;
};
module.exports = function resolve$2(x, options, callback) {
var cb = callback;
var opts = options;
if (typeof options === "function") {
cb = opts;
opts = {};
}
if (typeof x !== "string") {
var err = /* @__PURE__ */ new TypeError("Path must be a string.");
return process.nextTick(function() {
cb(err);
});
}
opts = normalizeOptions$1(x, opts);
var isFile = opts.isFile || defaultIsFile$1;
var isDirectory = opts.isDirectory || defaultIsDir$1;
var readFile$2 = opts.readFile || fs$1.readFile;
var realpath$1 = opts.realpath || defaultRealpath;
var readPackage = opts.readPackage || defaultReadPackage;
if (opts.readFile && opts.readPackage) {
var conflictErr = /* @__PURE__ */ new TypeError("`readFile` and `readPackage` are mutually exclusive.");
return process.nextTick(function() {
cb(conflictErr);
});
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path$2.dirname(caller$1());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths$1();
maybeRealpath(realpath$1, path$2.resolve(basedir), opts, function(err$1, realStart) {
if (err$1) cb(err$1);
else init(realStart);
});
var res;
function init(basedir$1) {
if (relativePathRegex$1.test(x)) {
res = path$2.resolve(basedir$1, x);
if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
if (x.slice(-1) === "/" && res === basedir$1) loadAsDirectory(res, opts.package, onfile);
else loadAsFile(res, opts.package, onfile);
} else if (includeCoreModules && isCore$1(x)) return cb(null, x);
else loadNodeModules(x, basedir$1, function(err$1, n, pkg) {
if (err$1) cb(err$1);
else if (n) return maybeRealpath(realpath$1, n, opts, function(err$2, realN) {
if (err$2) cb(err$2);
else cb(null, realN, pkg);
});
else {
var moduleError = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb(moduleError);
}
});
}
function onfile(err$1, m, pkg) {
if (err$1) cb(err$1);
else if (m) cb(null, m, pkg);
else loadAsDirectory(res, function(err$2, d, pkg$1) {
if (err$2) cb(err$2);
else if (d) maybeRealpath(realpath$1, d, opts, function(err$3, realD) {
if (err$3) cb(err$3);
else cb(null, realD, pkg$1);
});
else {
var moduleError = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb(moduleError);
}
});
}
function loadAsFile(x$1, thePackage, callback$1) {
var loadAsFilePackage = thePackage;
var cb$1 = callback$1;
if (typeof loadAsFilePackage === "function") {
cb$1 = loadAsFilePackage;
loadAsFilePackage = void 0;
}
load([""].concat(extensions), x$1, loadAsFilePackage);
function load(exts, x$2, loadPackage) {
if (exts.length === 0) return cb$1(null, void 0, loadPackage);
var file = x$2 + exts[0];
var pkg = loadPackage;
if (pkg) onpkg(null, pkg);
else loadpkg(path$2.dirname(file), onpkg);
function onpkg(err$1, pkg_, dir) {
pkg = pkg_;
if (err$1) return cb$1(err$1);
if (dir && pkg && opts.pathFilter) {
var rfile = path$2.relative(dir, file);
var rel = rfile.slice(0, rfile.length - exts[0].length);
var r = opts.pathFilter(pkg, x$2, rel);
if (r) return load([""].concat(extensions.slice()), path$2.resolve(dir, r), pkg);
}
isFile(file, onex);
}
function onex(err$1, ex) {
if (err$1) return cb$1(err$1);
if (ex) return cb$1(null, file, pkg);
load(exts.slice(1), x$2, pkg);
}
}
}
function loadpkg(dir, cb$1) {
if (dir === "" || dir === "/") return cb$1(null);
if (process.platform === "win32" && windowsDriveRegex$1.test(dir)) return cb$1(null);
if (nodeModulesRegex$1.test(dir)) return cb$1(null);
maybeRealpath(realpath$1, dir, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return loadpkg(path$2.dirname(dir), cb$1);
var pkgfile = path$2.join(pkgdir, "package.json");
isFile(pkgfile, function(err$1, ex) {
if (!ex) return loadpkg(path$2.dirname(dir), cb$1);
readPackage(readFile$2, pkgfile, function(err$2, pkgParam) {
if (err$2) cb$1(err$2);
var pkg = pkgParam;
if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, pkgfile);
cb$1(null, pkg, dir);
});
});
});
}
function loadAsDirectory(x$1, loadAsDirectoryPackage, callback$1) {
var cb$1 = callback$1;
var fpkg = loadAsDirectoryPackage;
if (typeof fpkg === "function") {
cb$1 = fpkg;
fpkg = opts.package;
}
maybeRealpath(realpath$1, x$1, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return cb$1(unwrapErr);
var pkgfile = path$2.join(pkgdir, "package.json");
isFile(pkgfile, function(err$1, ex) {
if (err$1) return cb$1(err$1);
if (!ex) return loadAsFile(path$2.join(x$1, "index"), fpkg, cb$1);
readPackage(readFile$2, pkgfile, function(err$2, pkgParam) {
if (err$2) return cb$1(err$2);
var pkg = pkgParam;
if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, pkgfile);
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = /* @__PURE__ */ new TypeError("package “" + pkg.name + "” `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
return cb$1(mainError);
}
if (pkg.main === "." || pkg.main === "./") pkg.main = "index";
loadAsFile(path$2.resolve(x$1, pkg.main), pkg, function(err$3, m, pkg$1) {
if (err$3) return cb$1(err$3);
if (m) return cb$1(null, m, pkg$1);
if (!pkg$1) return loadAsFile(path$2.join(x$1, "index"), pkg$1, cb$1);
loadAsDirectory(path$2.resolve(x$1, pkg$1.main), pkg$1, function(err$4, n, pkg$2) {
if (err$4) return cb$1(err$4);
if (n) return cb$1(null, n, pkg$2);
loadAsFile(path$2.join(x$1, "index"), pkg$2, cb$1);
});
});
return;
}
loadAsFile(path$2.join(x$1, "/index"), pkg, cb$1);
});
});
});
}
function processDirs(cb$1, dirs) {
if (dirs.length === 0) return cb$1(null, void 0);
var dir = dirs[0];
isDirectory(path$2.dirname(dir), isdir);
function isdir(err$1, isdir$1) {
if (err$1) return cb$1(err$1);
if (!isdir$1) return processDirs(cb$1, dirs.slice(1));
loadAsFile(dir, opts.package, onfile$1);
}
function onfile$1(err$1, m, pkg) {
if (err$1) return cb$1(err$1);
if (m) return cb$1(null, m, pkg);
loadAsDirectory(dir, opts.package, ondir);
}
function ondir(err$1, n, pkg) {
if (err$1) return cb$1(err$1);
if (n) return cb$1(null, n, pkg);
processDirs(cb$1, dirs.slice(1));
}
}
function loadNodeModules(x$1, start, cb$1) {
var thunk = function() {
return getPackageCandidates$1(x$1, start, opts);
};
processDirs(cb$1, packageIterator ? packageIterator(x$1, start, thunk, opts) : thunk());
}
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.json
var require_core$1 = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.json": ((exports, module) => {
module.exports = {
"assert": true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
"async_hooks": ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
"buffer_ieee754": ">= 0.5 && < 0.9.7",
"buffer": true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
"child_process": true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
"cluster": ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
"console": true,
"node:console": [">= 14.18 && < 15", ">= 16"],
"constants": true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
"crypto": true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
"_debug_agent": ">= 1 && < 8",
"_debugger": "< 8",
"dgram": true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
"diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
"dns": true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
"domain": ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
"events": true,
"node:events": [">= 14.18 && < 15", ">= 16"],
"freelist": "< 6",
"fs": true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
"_http_agent": ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
"_http_client": ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
"_http_common": ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
"_http_incoming": ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
"_http_outgoing": ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
"_http_server": ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
"http": true,
"node:http": [">= 14.18 && < 15", ">= 16"],
"http2": ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
"https": true,
"node:https": [">= 14.18 && < 15", ">= 16"],
"inspector": ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
"_linklist": "< 8",
"module": true,
"node:module": [">= 14.18 && < 15", ">= 16"],
"net": true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
"os": true,
"node:os": [">= 14.18 && < 15", ">= 16"],
"path": true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
"perf_hooks": ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
"process": ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
"punycode": ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
"querystring": true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
"readline": true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
"repl": true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
"node:sea": [">= 20.12 && < 21", ">= 21.7"],
"smalloc": ">= 0.11.5 && < 3",
"node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
"_stream_duplex": ">= 0.9.4",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
"_stream_transform": ">= 0.9.4",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
"_stream_wrap": ">= 1.4.1",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
"_stream_passthrough": ">= 0.9.4",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
"_stream_readable": ">= 0.9.4",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
"_stream_writable": ">= 0.9.4",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
"stream": true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
"string_decoder": true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
"sys": [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [
">= 18.17 && < 19",
">= 19.9",
">= 20"
],
"test/mock_loader": ">= 22.3 && < 22.7",
"node:test/mock_loader": ">= 22.3 && < 22.7",
"node:test": [">= 16.17 && < 17", ">= 18"],
"timers": true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
"_tls_common": ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
"_tls_legacy": ">= 0.11.3 && < 10",
"_tls_wrap": ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
"tls": true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
"trace_events": ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
"tty": true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
"url": true,
"node:url": [">= 14.18 && < 15", ">= 16"],
"util": true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8": ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
"vm": true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
"wasi": [
">= 13.4 && < 13.5",
">= 18.17 && < 19",
">= 20"
],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
"worker_threads": ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
"zlib": ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.js
var require_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.js": ((exports, module) => {
var isCoreModule$1 = require_is_core_module();
var data = require_core$1();
var core = {};
for (var mod in data) if (Object.prototype.hasOwnProperty.call(data, mod)) core[mod] = isCoreModule$1(mod);
module.exports = core;
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/is-core.js
var require_is_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/is-core.js": ((exports, module) => {
var isCoreModule = require_is_core_module();
module.exports = function isCore$2(x) {
return isCoreModule(x);
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/sync.js
var require_sync = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/sync.js": ((exports, module) => {
var isCore = require_is_core_module();
var fs = __require("fs");
var path$1 = __require("path");
var getHomedir = require_homedir();
var caller = require_caller();
var nodeModulesPaths = require_node_modules_paths();
var normalizeOptions = require_normalize_options();
var realpathFS = process.platform !== "win32" && fs.realpathSync && typeof fs.realpathSync.native === "function" ? fs.realpathSync.native : fs.realpathSync;
var relativePathRegex = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/;
var windowsDriveRegex = /^\w:[/\\]*$/;
var nodeModulesRegex = /[/\\]node_modules[/\\]*$/;
var homedir = getHomedir();
var defaultPaths = function() {
return [path$1.join(homedir, ".node_modules"), path$1.join(homedir, ".node_libraries")];
};
var defaultIsFile = function isFile(file) {
try {
var stat$2 = fs.statSync(file, { throwIfNoEntry: false });
} catch (e) {
if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
throw e;
}
return !!stat$2 && (stat$2.isFile() || stat$2.isFIFO());
};
var defaultIsDir = function isDirectory(dir) {
try {
var stat$2 = fs.statSync(dir, { throwIfNoEntry: false });
} catch (e) {
if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
throw e;
}
return !!stat$2 && stat$2.isDirectory();
};
var defaultRealpathSync = function realpathSync$1(x) {
try {
return realpathFS(x);
} catch (realpathErr) {
if (realpathErr.code !== "ENOENT") throw realpathErr;
}
return x;
};
var maybeRealpathSync = function maybeRealpathSync$1(realpathSync$1, x, opts) {
if (opts && opts.preserveSymlinks === false) return realpathSync$1(x);
return x;
};
var defaultReadPackageSync = function defaultReadPackageSync$1(readFileSync$1, pkgfile) {
var body = readFileSync$1(pkgfile);
try {
return JSON.parse(body);
} catch (jsonErr) {}
};
var getPackageCandidates = function getPackageCandidates$2(x, start, opts) {
var dirs = nodeModulesPaths(start, opts, x);
for (var i = 0; i < dirs.length; i++) dirs[i] = path$1.join(dirs[i], x);
return dirs;
};
module.exports = function resolveSync(x, options) {
if (typeof x !== "string") throw new TypeError("Path must be a string.");
var opts = normalizeOptions(x, options);
var isFile = opts.isFile || defaultIsFile;
var readFileSync$1 = opts.readFileSync || fs.readFileSync;
var isDirectory = opts.isDirectory || defaultIsDir;
var realpathSync$1 = opts.realpathSync || defaultRealpathSync;
var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
if (opts.readFileSync && opts.readPackageSync) throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path$1.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths();
var absoluteStart = maybeRealpathSync(realpathSync$1, path$1.resolve(basedir), opts);
if (relativePathRegex.test(x)) {
var res = path$1.resolve(absoluteStart, x);
if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
var m = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m) return maybeRealpathSync(realpathSync$1, m, opts);
} else if (includeCoreModules && isCore(x)) return x;
else {
var n = loadNodeModulesSync(x, absoluteStart);
if (n) return maybeRealpathSync(realpathSync$1, n, opts);
}
var err = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'");
err.code = "MODULE_NOT_FOUND";
throw err;
function loadAsFileSync(x$1) {
var pkg = loadpkg(path$1.dirname(x$1));
if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
var rfile = path$1.relative(pkg.dir, x$1);
var r = opts.pathFilter(pkg.pkg, x$1, rfile);
if (r) x$1 = path$1.resolve(pkg.dir, r);
}
if (isFile(x$1)) return x$1;
for (var i = 0; i < extensions.length; i++) {
var file = x$1 + extensions[i];
if (isFile(file)) return file;
}
}
function loadpkg(dir) {
if (dir === "" || dir === "/") return;
if (process.platform === "win32" && windowsDriveRegex.test(dir)) return;
if (nodeModulesRegex.test(dir)) return;
var pkgfile = path$1.join(maybeRealpathSync(realpathSync$1, dir, opts), "package.json");
if (!isFile(pkgfile)) return loadpkg(path$1.dirname(dir));
var pkg = readPackageSync(readFileSync$1, pkgfile);
if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, dir);
return {
pkg,
dir
};
}
function loadAsDirectorySync(x$1) {
var pkgfile = path$1.join(maybeRealpathSync(realpathSync$1, x$1, opts), "/package.json");
if (isFile(pkgfile)) {
try {
var pkg = readPackageSync(readFileSync$1, pkgfile);
} catch (e) {}
if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, x$1);
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = /* @__PURE__ */ new TypeError("package “" + pkg.name + "” `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
throw mainError;
}
if (pkg.main === "." || pkg.main === "./") pkg.main = "index";
try {
var m$1 = loadAsFileSync(path$1.resolve(x$1, pkg.main));
if (m$1) return m$1;
var n$1 = loadAsDirectorySync(path$1.resolve(x$1, pkg.main));
if (n$1) return n$1;
} catch (e) {}
}
}
return loadAsFileSync(path$1.join(x$1, "/index"));
}
function loadNodeModulesSync(x$1, start) {
var thunk = function() {
return getPackageCandidates(x$1, start, opts);
};
var dirs = packageIterator ? packageIterator(x$1, start, thunk, opts) : thunk();
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
if (isDirectory(path$1.dirname(dir))) {
var m$1 = loadAsFileSync(dir);
if (m$1) return m$1;
var n$1 = loadAsDirectorySync(dir);
if (n$1) return n$1;
}
}
}
};
}) });
//#endregion
//#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/index.js
var require_resolve = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/index.js": ((exports, module) => {
var async = require_async();
async.core = require_core();
async.isCore = require_is_core();
async.sync = require_sync();
module.exports = async;
}) });
//#endregion
//#region node_modules/.pnpm/@rollup+plugin-node-resolve@16.0.3_rollup@4.53.2/node_modules/@rollup/plugin-node-resolve/dist/es/index.js
var import_cjs = /* @__PURE__ */ __toESM(require_cjs(), 1);
var import_is_module = /* @__PURE__ */ __toESM(require_is_module(), 1);
var import_resolve = /* @__PURE__ */ __toESM(require_resolve(), 1);
var version = "16.0.3";
var peerDependencies = { rollup: "^2.78.0||^3.0.0||^4.0.0" };
promisify(nativeFs.access);
const readFile$1 = promisify(nativeFs.readFile);
const realpath = promisify(nativeFs.realpath);
const stat$1 = promisify(nativeFs.stat);
async function fileExists(filePath) {
try {
return (await stat$1(filePath)).isFile();
} catch {
return false;
}
}
async function resolveSymlink(path$4) {
return await fileExists(path$4) ? realpath(path$4) : path$4;
}
const onError = (error) => {
if (error.code === "ENOENT") return false;
throw error;
};
const makeCache = (fn) => {
const cache = /* @__PURE__ */ new Map();
const wrapped = async (param, done) => {
if (cache.has(param) === false) cache.set(param, fn(param).catch((err) => {
cache.delete(param);
throw err;
}));
try {
return done(null, await cache.get(param));
} catch (error) {
return done(error);
}
};
wrapped.clear = () => cache.clear();
return wrapped;
};
const isDirCached = makeCache(async (file) => {
try {
return (await stat$1(file)).isDirectory();
} catch (error) {
return onError(error);
}
});
const isFileCached = makeCache(async (file) => {
try {
return (await stat$1(file)).isFile();
} catch (error) {
return onError(error);
}
});
const readCachedFile = makeCache(readFile$1);
function handleDeprecatedOptions(opts) {
const warnings = [];
if (opts.customResolveOptions) {
const { customResolveOptions } = opts;
if (customResolveOptions.moduleDirectory) {
opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory) ? customResolveOptions.moduleDirectory : [customResolveOptions.moduleDirectory];
warnings.push("node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.");
}
if (customResolveOptions.preserveSymlinks) throw new Error("node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.");
[
"basedir",
"package",
"extensions",
"includeCoreModules",
"readFile",
"isFile",
"isDirectory",
"realpath",
"packageFilter",
"pathFilter",
"paths",
"packageIterator"
].forEach((resolveOption) => {
if (customResolveOptions[resolveOption]) throw new Error(`node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`);
});
}
return { warnings };
}
function getPackageName(id) {
if (id.startsWith(".") || id.startsWith("/")) return null;
const split = id.split("/");
if (split[0][0] === "@") return `${split[0]}/${split[1]}`;
return split[0];
}
function getMainFields(options) {
let mainFields;
if (options.mainFields) ({mainFields} = options);
else mainFields = ["module", "main"];
if (options.browser && mainFields.indexOf("browser") === -1) return ["browser"].concat(mainFields);
if (!mainFields.length) throw new Error("Please ensure at least one `mainFields` value is specified");
return mainFields;
}
function getPackageInfo(options) {
const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides, rootDir, ignoreSideEffectsForRoot } = options;
let { pkgPath } = options;
if (cache.has(pkgPath)) return cache.get(pkgPath);
if (!preserveSymlinks) pkgPath = realpathSync(pkgPath);
const pkgRoot = dirname(pkgPath);
const packageInfo = {
packageJson: { ...pkg },
packageJsonPath: pkgPath,
root: pkgRoot,
resolvedMainField: "main",
browserMappedMain: false,
resolvedEntryPoint: ""
};
let overriddenMain = false;
for (let i = 0; i < mainFields.length; i++) {
const field = mainFields[i];
if (typeof pkg[field] === "string") {
pkg.main = pkg[field];
packageInfo.resolvedMainField = field;
overriddenMain = true;
break;
}
}
const internalPackageInfo = {
cachedPkg: pkg,
hasModuleSideEffects: () => null,
hasPackageEntry: overriddenMain !== false || mainFields.indexOf("main") !== -1,
packageBrowserField: useBrowserOverrides && typeof pkg.browser === "object" && Object.keys(pkg.browser).reduce((browser, key) => {
let resolved = pkg.browser[key];
if (resolved && resolved[0] === ".") resolved = resolve(pkgRoot, resolved);
browser[key] = resolved;
if (key[0] === ".") {
const absoluteKey = resolve(pkgRoot, key);
browser[absoluteKey] = resolved;
if (!extname(key)) extensions.reduce((subBrowser, ext) => {
subBrowser[absoluteKey + ext] = subBrowser[key];
return subBrowser;
}, browser);
}
return browser;
}, {}),
packageInfo
};
const browserMap = internalPackageInfo.packageBrowserField;
if (useBrowserOverrides && typeof pkg.browser === "object" && browserMap.hasOwnProperty(pkg.main)) {
packageInfo.resolvedEntryPoint = browserMap[pkg.main];
packageInfo.browserMappedMain = true;
} else {
packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || "index.js");
packageInfo.browserMappedMain = false;
}
if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) {
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === "boolean") internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
else if (Array.isArray(packageSideEffects)) internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects.map((sideEffect) => {
if (sideEffect.includes("/")) return sideEffect;
return `**/${sideEffect}`;
}), null, { resolve: pkgRoot });
}
cache.set(pkgPath, internalPackageInfo);
return internalPackageInfo;
}
function normalizeInput(input) {
if (Array.isArray(input)) return input;
else if (typeof input === "object") return Object.values(input);
return [input];
}
function isModuleDir(current, moduleDirs) {
return moduleDirs.some((dir) => current.endsWith(dir));
}
async function findPackageJson(base, moduleDirs) {
const { root } = path.parse(base);
let current = base;
while (current !== root && !isModuleDir(current, moduleDirs)) {
const pkgJsonPath = path.join(current, "package.json");
if (await fileExists(pkgJsonPath)) {
const pkgJsonString = nativeFs.readFileSync(pkgJsonPath, "utf-8");
return {
pkgJson: JSON.parse(pkgJsonString),
pkgPath: current,
pkgJsonPath
};
}
current = path.resolve(current, "..");
}
return null;
}
function isUrl(str) {
try {
return !!new URL(str);
} catch (_) {
return false;
}
}
/**
* Conditions is an export object where all keys are conditions like 'node' (aka do not with '.')
*/
function isConditions(exports) {
return typeof exports === "object" && Object.keys(exports).every((k) => !k.startsWith("."));
}
/**
* Mappings is an export object where all keys start with '.
*/
function isMappings(exports) {
return typeof exports === "object" && !isConditions(exports);
}
/**
* Check for mixed exports, which are exports where some keys start with '.' and some do not
*/
function isMixedExports(exports) {
const keys = Object.keys(exports);
return keys.some((k) => k.startsWith(".")) && keys.some((k) => !k.startsWith("."));
}
function createBaseErrorMsg(importSpecifier, importer) {
return `Could not resolve import "${importSpecifier}" in ${importer}`;
}
function createErrorMsg(context, reason, isImports) {
const { importSpecifier, importer, pkgJsonPath } = context;
return `${createBaseErrorMsg(importSpecifier, importer)} using ${isImports ? "imports" : "exports"} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ""}`;
}
var ResolveError = class extends Error {};
var InvalidConfigurationError = class extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, `Invalid "exports" field. ${reason}`));
}
};
var InvalidModuleSpecifierError = class extends ResolveError {
constructor(context, isImports, reason) {
super(createErrorMsg(context, reason, isImports));
}
};
var InvalidPackageTargetError = class extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, reason));
}
};
/**
* Check for invalid path segments
*/
function includesInvalidSegments(pathSegments, moduleDirs) {
const invalidSegments = [
"",
".",
"..",
...moduleDirs
];
return pathSegments.some((v) => invalidSegments.includes(v) || invalidSegments.includes(decodeURI(v)));
}
async function resolvePackageTarget(context, { target, patternMatch, isImports }) {
if (typeof target === "string") {
if (!target.startsWith("./")) {
if (!isImports || ["/", "../"].some((p) => target.startsWith(p)) || isUrl(target)) throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
if (typeof patternMatch === "string") {
const result$1 = await context.resolveId(target.replace(/\*/g, patternMatch), context.pkgURL.href);
return result$1 ? pathToFileURL(result$1.location).href : null;
}
const result = await context.resolveId(target, context.pkgURL.href);
return result ? pathToFileURL(result.location).href : null;
}
if (context.allowExportsFolderMapping) target = target.replace(/\/$/, "/*");
{
const pathSegments = target.split(/\/|\\/);
const firstDot = pathSegments.indexOf(".");
firstDot !== -1 && pathSegments.slice(firstDot);
if (firstDot !== -1 && firstDot < pathSegments.length - 1 && includesInvalidSegments(pathSegments.slice(firstDot + 1), context.moduleDirs)) throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
}
const resolvedTarget = new URL(target, context.pkgURL);
if (!resolvedTarget.href.startsWith(context.pkgURL.href)) throw new InvalidPackageTargetError(context, `Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`);
if (!patternMatch) return resolvedTarget;
if (includesInvalidSegments(patternMatch.split(/\/|\\/), context.moduleDirs)) throw new InvalidModuleSpecifierError(context);
return resolvedTarget.href.replace(/\*/g, patternMatch);
}
if (Array.isArray(target)) {
if (target.length === 0) return null;
let lastError = null;
for (const item of target) try {
const resolved = await resolvePackageTarget(context, {
target: item,
patternMatch,
isImports
});
if (resolved !== void 0) return resolved;
} catch (error) {
if (!(error instanceof InvalidPackageTargetError)) throw error;
else lastError = error;
}
if (lastError) throw lastError;
return null;
}
if (target && typeof target === "object") {
for (const [key, value] of Object.entries(target)) if (key === "default" || context.conditions.includes(key)) {
const resolved = await resolvePackageTarget(context, {
target: value,
patternMatch,
isImports
});
if (resolved !== void 0) return resolved;
}
return;
}
if (target === null) return null;
throw new InvalidPackageTargetError(context, `Invalid exports field.`);
}
/**
* Implementation of Node's `PATTERN_KEY_COMPARE` function
*/
function nodePatternKeyCompare(keyA, keyB) {
const baseLengthA = keyA.includes("*") ? keyA.indexOf("*") + 1 : keyA.length;
const rval = (keyB.includes("*") ? keyB.indexOf("*") + 1 : keyB.length) - baseLengthA;
if (rval !== 0) return rval;
if (!keyA.includes("*")) return 1;
if (!keyB.includes("*")) return -1;
return keyB.length - keyA.length;
}
async function resolvePackageImportsExports(context, { matchKey, matchObj, isImports }) {
if (!matchKey.includes("*") && matchKey in matchObj) {
const target = matchObj[matchKey];
return await resolvePackageTarget(context, {
target,
patternMatch: "",
isImports
});
}
const expansionKeys = Object.keys(matchObj).filter((k) => k.endsWith("/") || k.includes("*")).sort(nodePatternKeyCompare);
for (const expansionKey of expansionKeys) {
const indexOfAsterisk = expansionKey.indexOf("*");
const patternBase = indexOfAsterisk === -1 ? expansionKey : expansionKey.substring(0, indexOfAsterisk);
if (matchKey.startsWith(patternBase) && matchKey !== patternBase) {
const patternTrailer = indexOfAsterisk !== -1 ? expansionKey.substring(indexOfAsterisk + 1) : "";
if (patternTrailer.length === 0 || matchKey.endsWith(patternTrailer) && matchKey.length >= expansionKey.length) {
const target = matchObj[expansionKey];
return await resolvePackageTarget(context, {
target,
patternMatch: matchKey.substring(patternBase.length, matchKey.length - patternTrailer.length),
isImports
});
}
}
}
throw new InvalidModuleSpecifierError(context, isImports);
}
/**
* Implementation of PACKAGE_EXPORTS_RESOLVE
*/
async function resolvePackageExports(context, subpath, exports) {
if (isMixedExports(exports)) throw new InvalidConfigurationError(context, "All keys must either start with ./, or without one.");
if (subpath === ".") {
let mainExport;
if (typeof exports === "string" || Array.isArray(exports) || isConditions(exports)) mainExport = exports;
else if (isMappings(exports)) mainExport = exports["."];
if (mainExport) {
const resolved = await resolvePackageTarget(context, {
target: mainExport,
patternMatch: "",
isImports: false
});
if (resolved) return resolved;
}
} else if (isMappings(exports)) {
const resolvedMatch = await resolvePackageImportsExports(context, {
matchKey: subpath,
matchObj: exports,
isImports: false
});
if (resolvedMatch) return resolvedMatch;
}
throw new InvalidModuleSpecifierError(context);
}
async function resolvePackageImports({ importSpecifier, importer, moduleDirs, conditions, resolveId }) {
const result = await findPackageJson(importer, moduleDirs);
if (!result) throw new Error(`${createBaseErrorMsg(importSpecifier, importer)}. Could not find a parent package.json.`);
const { pkgPath, pkgJsonPath, pkgJson } = result;
const context = {
importer,
importSpecifier,
moduleDirs,
pkgURL: pathToFileURL(`${pkgPath}/`),
pkgJsonPath,
conditions,
resolveId
};
if (!importSpecifier.startsWith("#")) throw new InvalidModuleSpecifierError(context, true, "Invalid import specifier.");
if (importSpecifier === "#" || importSpecifier.startsWith("#/")) throw new InvalidModuleSpecifierError(context, true, "Invalid import specifier.");
const { imports } = pkgJson;
if (!imports) throw new InvalidModuleSpecifierError(context, true);
return resolvePackageImportsExports(context, {
matchKey: importSpecifier,
matchObj: imports,
isImports: true
});
}
const resolveImportPath = promisify(import_resolve.default);
const readFile = promisify(nativeFs.readFile);
async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) {
if (importer) {
const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories);
if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) return selfPackageJsonResult;
}
try {
const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
return {
pkgJsonPath,
pkgJson: JSON.parse(await readFile(pkgJsonPath, "utf-8")),
pkgPath: dirname(pkgJsonPath)
};
} catch (_) {
return null;
}
}
async function resolveIdClassic({ importSpecifier, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot }) {
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField} = info);
return info.cachedPkg;
};
const resolveOptions = {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
};
let location;
try {
location = await resolveImportPath(importSpecifier, resolveOptions);
} catch (error) {
if (error.code !== "MODULE_NOT_FOUND") throw error;
return null;
}
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
async function resolveWithExportMap({ importer, importSpecifier, exportConditions, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot, allowExportsFolderMapping }) {
if (importSpecifier.startsWith("#")) {
const resolveResult = await resolvePackageImports({
importSpecifier,
importer,
moduleDirs: moduleDirectories,
conditions: exportConditions,
resolveId(id) {
return resolveImportSpecifiers({
importer,
importSpecifierList: [id],
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot,
allowExportsFolderMapping
});
}
});
if (resolveResult == null) throw new ResolveError(`Could not resolve import "${importSpecifier}" in ${importer} using imports.`);
const location = fileURLToPath(resolveResult);
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false,
packageInfo: void 0
};
}
const pkgName = getPackageName(importSpecifier);
if (pkgName) {
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField} = info);
return info.cachedPkg;
};
const result = await getPackageJson(importer, pkgName, {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
}, moduleDirectories);
if (result && result.pkgJson.exports) {
const { pkgJson, pkgJsonPath } = result;
const subpath = pkgName === importSpecifier ? "." : `.${importSpecifier.substring(pkgName.length)}`;
const location = fileURLToPath(await resolvePackageExports({
importer,
importSpecifier,
moduleDirs: moduleDirectories,
pkgURL: pathToFileURL(pkgJsonPath.replace("package.json", "")),
pkgJsonPath,
allowExportsFolderMapping,
conditions: exportConditions
}, subpath, pkgJson.exports));
if (location) return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
}
return null;
}
async function resolveWithClassic({ importer, importSpecifierList, exportConditions, warn, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot }) {
for (let i = 0; i < importSpecifierList.length; i++) {
const result = await resolveIdClassic({
importer,
importSpecifier: importSpecifierList[i],
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
if (result) return result;
}
return null;
}
async function resolveImportSpecifiers({ importer, importSpecifierList, exportConditions, warn, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot, allowExportsFolderMapping }) {
try {
const exportMapRes = await resolveWithExportMap({
importer,
importSpecifier: importSpecifierList[0],
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot,
allowExportsFolderMapping
});
if (exportMapRes) return exportMapRes;
} catch (error) {
if (error instanceof ResolveError) {
warn(error);
return null;
}
throw error;
}
return resolveWithClassic({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
}
const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
function validateVersion(actualVersion, peerDependencyVersion) {
let minMajor = Infinity;
let minMinor = Infinity;
let minPatch = Infinity;
let foundVersion;
while (foundVersion = versionRegexp.exec(peerDependencyVersion)) {
const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number);
if (foundMajor < minMajor) {
minMajor = foundMajor;
minMinor = foundMinor;
minPatch = foundPatch;
}
}
if (!actualVersion) throw new Error(`Insufficient Rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch}.`);
const [major, minor, patch] = actualVersion.split(".").map(Number);
if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) throw new Error(`Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch} but found rollup@${actualVersion}.`);
}
const ES6_BROWSER_EMPTY = "\0node-resolve:empty.js";
const deepFreeze = (object) => {
Object.freeze(object);
for (const value of Object.values(object)) if (typeof value === "object" && !Object.isFrozen(value)) deepFreeze(value);
return object;
};
const baseConditions = ["default", "module"];
const baseConditionsEsm = [...baseConditions, "import"];
const baseConditionsCjs = [...baseConditions, "require"];
const defaults = {
dedupe: [],
extensions: [
".mjs",
".js",
".json",
".node"
],
resolveOnly: [],
moduleDirectories: ["node_modules"],
modulePaths: [],
ignoreSideEffectsForRoot: false,
allowExportsFolderMapping: true
};
const nodeImportPrefix = /^node:/;
const DEFAULTS = deepFreeze((0, import_cjs.default)({}, defaults));
function nodeResolve(opts = {}) {
const { warnings } = handleDeprecatedOptions(opts);
const options = {
...defaults,
...opts
};
const { extensions, jail, moduleDirectories, modulePaths, ignoreSideEffectsForRoot } = options;
const exportConditions = options.exportConditions || [];
const devProdCondition = exportConditions.includes("development") || exportConditions.includes("production") ? [] : [process.env.NODE_ENV && process.env.NODE_ENV !== "production" ? "development" : "production"];
const conditionsEsm = [
...baseConditionsEsm,
...exportConditions,
...devProdCondition
];
const conditionsCjs = [
...baseConditionsCjs,
...exportConditions,
...devProdCondition
];
const packageInfoCache = /* @__PURE__ */ new Map();
const idToPackageInfo = /* @__PURE__ */ new Map();
const mainFields = getMainFields(options);
const useBrowserOverrides = mainFields.indexOf("browser") !== -1;
const isPreferBuiltinsSet = Object.prototype.hasOwnProperty.call(options, "preferBuiltins");
const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = resolve(options.rootDir || process.cwd());
let { dedupe } = options;
let rollupOptions;
if (moduleDirectories.some((name) => name.includes("/"))) throw new Error("`moduleDirectories` option must only contain directory names. If you want to load modules from somewhere not supported by the default module resolution algorithm, see `modulePaths`.");
if (typeof dedupe !== "function") dedupe = (importee) => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
const allowPatterns = (patterns) => {
const regexPatterns = patterns.map((pattern) => {
if (pattern instanceof RegExp) return pattern;
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&");
return /* @__PURE__ */ new RegExp(`^${normalized}$`);
});
return (id) => !regexPatterns.length || regexPatterns.some((pattern) => pattern.test(id));
};
const resolveOnly = typeof options.resolveOnly === "function" ? options.resolveOnly : allowPatterns(options.resolveOnly);
const browserMapCache = /* @__PURE__ */ new Map();
let preserveSymlinks;
const resolveLikeNode = async (context, importee, importer, custom) => {
const [importPath, params] = importee.split("?");
const importSuffix = `${params ? `?${params}` : ""}`;
importee = importPath;
const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = resolve(baseDir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) return { id: ES6_BROWSER_EMPTY };
const browserImportee = importee[0] !== "." && browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`];
if (browserImportee) importee = browserImportee;
}
const parts = importee.split(/[/\\]/);
let id = parts.shift();
let isRelativeImport = false;
if (id[0] === "@" && parts.length > 0) id += `/${parts.shift()}`;
else if (id[0] === ".") {
id = resolve(baseDir, importee);
isRelativeImport = true;
}
if (!isRelativeImport && !resolveOnly(id)) {
if (normalizeInput(rollupOptions.input).includes(importee)) return null;
return false;
}
const importSpecifierList = [importee];
if (importer === void 0 && importee[0] && !importee[0].match(/^\.?\.?\//)) importSpecifierList.push(`./${importee}`);
if (importer && /\.(ts|mts|cts|tsx)$/.test(importer)) {
for (const [importeeExt, resolvedExt] of [
[".js", ".ts"],
[".js", ".tsx"],
[".jsx", ".tsx"],
[".mjs", ".mts"],
[".cjs", ".cts"]
]) if (importee.endsWith(importeeExt) && extensions.includes(resolvedExt)) importSpecifierList.push(importee.slice(0, -importeeExt.length) + resolvedExt);
}
const warn = (...args) => context.warn(...args);
const exportConditions$1 = custom && custom["node-resolve"] && custom["node-resolve"].isRequire ? conditionsCjs : conditionsEsm;
if (useBrowserOverrides && !exportConditions$1.includes("browser")) exportConditions$1.push("browser");
const resolvedWithoutBuiltins = await resolveImportSpecifiers({
importer,
importSpecifierList,
exportConditions: exportConditions$1,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot,
allowExportsFolderMapping: options.allowExportsFolderMapping
});
const importeeIsBuiltin = builtinModules.includes(importee.replace(nodeImportPrefix, ""));
const preferImporteeIsBuiltin = typeof preferBuiltins === "function" ? preferBuiltins(importee) : preferBuiltins;
const resolved = importeeIsBuiltin && preferImporteeIsBuiltin ? {
packageInfo: void 0,
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false
} : resolvedWithoutBuiltins;
if (!resolved) return null;
const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
let { location } = resolved;
if (packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
if (!packageBrowserField[location]) {
browserMapCache.set(location, packageBrowserField);
return { id: ES6_BROWSER_EMPTY };
}
location = packageBrowserField[location];
}
browserMapCache.set(location, packageBrowserField);
}
if (hasPackageEntry && !preserveSymlinks) {
if (await fileExists(location)) location = await realpath(location);
}
idToPackageInfo.set(location, packageInfo);
if (hasPackageEntry) {
if (importeeIsBuiltin && preferImporteeIsBuiltin) {
if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) context.warn({
message: `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning.or passing a function to 'preferBuiltins' to provide more fine-grained control over which built-in modules to prefer.`,
pluginCode: "PREFER_BUILTINS"
});
return false;
} else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) return null;
}
if (options.modulesOnly && await fileExists(location)) {
if ((0, import_is_module.default)(await readFile$1(location, "utf-8"))) return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
return null;
}
return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
};
return {
name: "node-resolve",
version,
buildStart(buildOptions) {
validateVersion(this.meta.rollupVersion, peerDependencies.rollup);
rollupOptions = buildOptions;
for (const warning of warnings) this.warn(warning);
({preserveSymlinks} = buildOptions);
},
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
resolveId: {
order: "post",
async handler(importee, importer, resolveOptions) {
if (importee === ES6_BROWSER_EMPTY) return importee;
if (importee && importee.includes("\0")) return null;
const { custom = {} } = resolveOptions;
const { "node-resolve": { resolved: alreadyResolved } = {} } = custom;
if (alreadyResolved) return alreadyResolved;
if (importer && importer.includes("\0")) importer = void 0;
const resolved = await resolveLikeNode(this, importee, importer, custom);
if (resolved) {
const resolvedResolved = await this.resolve(resolved.id, importer, {
...resolveOptions,
skipSelf: false,
custom: {
...custom,
"node-resolve": {
...custom["node-resolve"],
resolved,
importee
}
}
});
if (resolvedResolved) {
if (resolvedResolved.external) return false;
if (resolvedResolved.id !== resolved.id) return resolvedResolved;
return {
...resolved,
meta: resolvedResolved.meta
};
}
}
return resolved;
}
},
load(importee) {
if (importee === ES6_BROWSER_EMPTY) return "export default {};";
return null;
},
getPackageInfoForId(id) {
return idToPackageInfo.get(id);
}
};
}
//#endregion
export { nodeResolve as t };
import { t as MagicString } from "./magic-string.mjs";
import { r as createFilter } from "./plugin-commonjs.mjs";
//#region node_modules/.pnpm/@rollup+plugin-replace@6.0.3_rollup@4.53.2/node_modules/@rollup/plugin-replace/dist/es/index.js
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === "function") return functionOrValue;
return function() {
return functionOrValue;
};
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) return Object.assign({}, options.values);
var values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
delete values.objectGuards;
delete values.preventAssignment;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce(function(fns, key) {
var functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
var objKeyRegEx = /^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/;
function expandTypeofReplacements(replacements) {
Object.keys(replacements).forEach(function(key) {
var objMatch = key.match(objKeyRegEx);
if (!objMatch) return;
var dotIndex = objMatch[1].length;
do {
replacements["typeof " + key.slice(0, dotIndex)] = "\"object\"";
dotIndex = key.indexOf(".", dotIndex + 1);
} while (dotIndex !== -1);
});
}
function replace(options) {
if (options === void 0) options = {};
var filter = createFilter(options.include, options.exclude);
var delimiters = options.delimiters;
if (delimiters === void 0) delimiters = ["(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])", "(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)"];
var preventAssignment = options.preventAssignment;
var objectGuards = options.objectGuards;
var replacements = getReplacements(options);
if (objectGuards) expandTypeofReplacements(replacements);
var functionValues = mapToFunctions(replacements);
var keys = Object.keys(functionValues).sort(longest).map(escape);
var lookbehind = preventAssignment ? "(?<!\\b(?:const|let|var)\\s*)" : "";
var lookahead = preventAssignment ? "(?!\\s*=[^=])" : "";
var pattern = new RegExp("" + lookbehind + delimiters[0] + "(" + keys.join("|") + ")" + delimiters[1] + lookahead, "g");
return {
name: "replace",
buildStart: function buildStart() {
if (![true, false].includes(preventAssignment)) this.warn({ message: "@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`." });
},
renderChunk: function renderChunk(code, chunk) {
var id = chunk.fileName;
if (!keys.length) return null;
if (!filter(id)) return null;
return executeReplacement(code, id);
},
transform: function transform(code, id) {
if (!keys.length) return null;
if (!filter(id)) return null;
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
var magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) return null;
var result = { code: magicString.toString() };
if (isSourceMapEnabled()) result.map = magicString.generateMap({ hires: true });
return result;
}
function codeHasReplacements(code, id, magicString) {
var result = false;
var match;
while (match = pattern.exec(code)) {
result = true;
var start = match.index;
var end = start + match[0].length;
var replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}
//#endregion
export { replace as t };
//#region node_modules/.pnpm/pretty-bytes@7.1.0/node_modules/pretty-bytes/index.js
const BYTE_UNITS = [
"B",
"kB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"
];
const BIBYTE_UNITS = [
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB"
];
const BIT_UNITS = [
"b",
"kbit",
"Mbit",
"Gbit",
"Tbit",
"Pbit",
"Ebit",
"Zbit",
"Ybit"
];
const BIBIT_UNITS = [
"b",
"kibit",
"Mibit",
"Gibit",
"Tibit",
"Pibit",
"Eibit",
"Zibit",
"Yibit"
];
const toLocaleString = (number, locale, options) => {
let result = number;
if (typeof locale === "string" || Array.isArray(locale)) result = number.toLocaleString(locale, options);
else if (locale === true || options !== void 0) result = number.toLocaleString(void 0, options);
return result;
};
const log10 = (numberOrBigInt) => {
if (typeof numberOrBigInt === "number") return Math.log10(numberOrBigInt);
const string = numberOrBigInt.toString(10);
return string.length + Math.log10(`0.${string.slice(0, 15)}`);
};
const log = (numberOrBigInt) => {
if (typeof numberOrBigInt === "number") return Math.log(numberOrBigInt);
return log10(numberOrBigInt) * Math.log(10);
};
const divide = (numberOrBigInt, divisor) => {
if (typeof numberOrBigInt === "number") return numberOrBigInt / divisor;
const integerPart = numberOrBigInt / BigInt(divisor);
const remainder = numberOrBigInt % BigInt(divisor);
return Number(integerPart) + Number(remainder) / divisor;
};
const applyFixedWidth = (result, fixedWidth) => {
if (fixedWidth === void 0) return result;
if (typeof fixedWidth !== "number" || !Number.isSafeInteger(fixedWidth) || fixedWidth < 0) throw new TypeError(`Expected fixedWidth to be a non-negative integer, got ${typeof fixedWidth}: ${fixedWidth}`);
if (fixedWidth === 0) return result;
return result.length < fixedWidth ? result.padStart(fixedWidth, " ") : result;
};
const buildLocaleOptions = (options) => {
const { minimumFractionDigits, maximumFractionDigits } = options;
if (minimumFractionDigits === void 0 && maximumFractionDigits === void 0) return;
return {
...minimumFractionDigits !== void 0 && { minimumFractionDigits },
...maximumFractionDigits !== void 0 && { maximumFractionDigits },
roundingMode: "trunc"
};
};
function prettyBytes(number, options) {
if (typeof number !== "bigint" && !Number.isFinite(number)) throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
options = {
bits: false,
binary: false,
space: true,
nonBreakingSpace: false,
...options
};
const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS;
const separator = options.space ? options.nonBreakingSpace ? "\xA0" : " " : "";
const isZero = typeof number === "number" ? number === 0 : number === 0n;
if (options.signed && isZero) return applyFixedWidth(` 0${separator}${UNITS[0]}`, options.fixedWidth);
const isNegative = number < 0;
const prefix = isNegative ? "-" : options.signed ? "+" : "";
if (isNegative) number = -number;
const localeOptions = buildLocaleOptions(options);
let result;
if (number < 1) result = prefix + toLocaleString(number, options.locale, localeOptions) + separator + UNITS[0];
else {
const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1);
number = divide(number, (options.binary ? 1024 : 1e3) ** exponent);
if (!localeOptions) {
const minPrecision = Math.max(3, Math.floor(number).toString().length);
number = number.toPrecision(minPrecision);
}
const numberString = toLocaleString(Number(number), options.locale, localeOptions);
const unit = UNITS[exponent];
result = prefix + numberString + separator + unit;
}
return applyFixedWidth(result, options.fixedWidth);
}
//#endregion
export { prettyBytes as t };
import { a as toDecodedMap, c as decodedMappings, i as setSourceContent, l as traceSegment, n as maybeAddSegment, o as toEncodedMap, r as setIgnore, s as TraceMap, t as GenMapping } from "./gen-mapping.mjs";
//#region node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs
var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
var EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content, ignore) {
return {
source,
line,
column,
name,
content,
ignore
};
}
function Source(map, sources, source, content, ignore) {
return {
map,
sources,
source,
content,
ignore
};
}
function MapSource(map, sources) {
return Source(map, sources, "", null, false);
}
function OriginalSource(source, content, ignore) {
return Source(null, EMPTY_SOURCES, source, content, ignore);
}
function traceMappings(tree) {
const gen = new GenMapping({ file: tree.map.file });
const { sources: rootSources, map } = tree;
const rootNames = map.names;
const rootMappings = decodedMappings(map);
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
const genCol = segment[0];
let traced = SOURCELESS_MAPPING;
if (segment.length !== 1) {
const source2 = rootSources[segment[1]];
traced = originalPositionFor(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
if (traced == null) continue;
}
const { column, line, name, content, source, ignore } = traced;
maybeAddSegment(gen, i, genCol, source, line, column, name);
if (source && content != null) setSourceContent(gen, source, content);
if (ignore) setIgnore(gen, source, true);
}
}
return gen;
}
function originalPositionFor(source, line, column, name) {
if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore);
const segment = traceSegment(source.map, line, column);
if (segment == null) return null;
if (segment.length === 1) return SOURCELESS_MAPPING;
return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
}
function asArray(value) {
if (Array.isArray(value)) return value;
return [value];
}
function buildSourceMapTree(input, loader) {
const maps = asArray(input).map((m) => new TraceMap(m, ""));
const map = maps.pop();
for (let i = 0; i < maps.length; i++) if (maps[i].sources.length > 1) throw new Error(`Transformation map ${i} must have exactly one source file.
Did you specify these with the most recent transformation maps first?`);
let tree = build(map, loader, "", 0);
for (let i = maps.length - 1; i >= 0; i--) tree = MapSource(maps[i], [tree]);
return tree;
}
function build(map, loader, importer, importerDepth) {
const { resolvedSources, sourcesContent, ignoreList } = map;
const depth = importerDepth + 1;
return MapSource(map, resolvedSources.map((sourceFile, i) => {
const ctx = {
importer,
depth,
source: sourceFile || "",
content: void 0,
ignore: void 0
};
const sourceMap = loader(ctx.source, ctx);
const { source, content, ignore } = ctx;
if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);
return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false);
}));
}
var SourceMap = class {
constructor(map, options) {
const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
this.version = out.version;
this.file = out.file;
this.mappings = out.mappings;
this.names = out.names;
this.ignoreList = out.ignoreList;
this.sourceRoot = out.sourceRoot;
this.sources = out.sources;
if (!options.excludeContent) this.sourcesContent = out.sourcesContent;
}
toString() {
return JSON.stringify(this);
}
};
function remapping(input, loader, options) {
const opts = typeof options === "object" ? options : {
excludeContent: !!options,
decodedMappings: false
};
return new SourceMap(traceMappings(buildSourceMapTree(input, loader)), opts);
}
//#endregion
export { remapping as t };
//#region node_modules/.pnpm/rou3@0.7.10/node_modules/rou3/dist/index.mjs
const NullProtoObj = /* @__PURE__ */ (() => {
const e = function() {};
return e.prototype = Object.create(null), Object.freeze(e.prototype), e;
})();
/**
* Create a new router context.
*/
function createRouter() {
return {
root: { key: "" },
static: new NullProtoObj()
};
}
function splitPath(path) {
const [_, ...s] = path.split("/");
return s[s.length - 1] === "" ? s.slice(0, -1) : s;
}
function getMatchParams(segments, paramsMap) {
const params = new NullProtoObj();
for (const [index, name] of paramsMap) {
const segment = index < 0 ? segments.slice(-1 * index).join("/") : segments[index];
if (typeof name === "string") params[name] = segment;
else {
const match = segment.match(name);
if (match) for (const key in match.groups) params[key] = match.groups[key];
}
}
return params;
}
/**
* Add a route to the router context.
*/
function addRoute(ctx, method = "", path, data) {
method = method.toUpperCase();
if (path.charCodeAt(0) !== 47) path = `/${path}`;
const segments = splitPath(path);
let node = ctx.root;
let _unnamedParamIndex = 0;
const paramsMap = [];
const paramsRegexp = [];
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
if (segment.startsWith("**")) {
if (!node.wildcard) node.wildcard = { key: "**" };
node = node.wildcard;
paramsMap.push([
-i,
segment.split(":")[1] || "_",
segment.length === 2
]);
break;
}
if (segment === "*" || segment.includes(":")) {
if (!node.param) node.param = { key: "*" };
node = node.param;
if (segment === "*") paramsMap.push([
i,
`_${_unnamedParamIndex++}`,
true
]);
else if (segment.includes(":", 1)) {
const regexp = getParamRegexp(segment);
paramsRegexp[i] = regexp;
node.hasRegexParam = true;
paramsMap.push([
i,
regexp,
false
]);
} else paramsMap.push([
i,
segment.slice(1),
false
]);
continue;
}
const child = node.static?.[segment];
if (child) node = child;
else {
const staticNode = { key: segment };
if (!node.static) node.static = new NullProtoObj();
node.static[segment] = staticNode;
node = staticNode;
}
}
const hasParams = paramsMap.length > 0;
if (!node.methods) node.methods = new NullProtoObj();
node.methods[method] ??= [];
node.methods[method].push({
data: data || null,
paramsRegexp,
paramsMap: hasParams ? paramsMap : void 0
});
if (!hasParams) ctx.static[path] = node;
}
function getParamRegexp(segment) {
const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\.");
return /* @__PURE__ */ new RegExp(`^${regex}$`);
}
/**
* Find a route by path.
*/
function findRoute(ctx, method = "", path, opts) {
if (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);
const staticNode = ctx.static[path];
if (staticNode && staticNode.methods) {
const staticMatch = staticNode.methods[method] || staticNode.methods[""];
if (staticMatch !== void 0) return staticMatch[0];
}
const segments = splitPath(path);
const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];
if (match === void 0) return;
if (opts?.params === false) return match;
return {
data: match.data,
params: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0
};
}
function _lookupTree(ctx, node, method, segments, index) {
if (index === segments.length) {
if (node.methods) {
const match = node.methods[method] || node.methods[""];
if (match) return match;
}
if (node.param && node.param.methods) {
const match = node.param.methods[method] || node.param.methods[""];
if (match) {
const pMap = match[0].paramsMap;
if (pMap?.[pMap?.length - 1]?.[2]) return match;
}
}
if (node.wildcard && node.wildcard.methods) {
const match = node.wildcard.methods[method] || node.wildcard.methods[""];
if (match) {
const pMap = match[0].paramsMap;
if (pMap?.[pMap?.length - 1]?.[2]) return match;
}
}
return;
}
const segment = segments[index];
if (node.static) {
const staticChild = node.static[segment];
if (staticChild) {
const match = _lookupTree(ctx, staticChild, method, segments, index + 1);
if (match) return match;
}
}
if (node.param) {
const match = _lookupTree(ctx, node.param, method, segments, index + 1);
if (match) {
if (node.param.hasRegexParam) {
const exactMatch = match.find((m) => m.paramsRegexp[index]?.test(segment)) || match.find((m) => !m.paramsRegexp[index]);
return exactMatch ? [exactMatch] : void 0;
}
return match;
}
}
if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""];
}
/**
* Find all route patterns that match the given path.
*/
function findAllRoutes(ctx, method = "", path, opts) {
if (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);
const segments = splitPath(path);
const matches = _findAll(ctx, ctx.root, method, segments, 0);
if (opts?.params === false) return matches;
return matches.map((m) => {
return {
data: m.data,
params: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0
};
});
}
function _findAll(ctx, node, method, segments, index, matches = []) {
const segment = segments[index];
if (node.wildcard && node.wildcard.methods) {
const match = node.wildcard.methods[method] || node.wildcard.methods[""];
if (match) matches.push(...match);
}
if (node.param) {
_findAll(ctx, node.param, method, segments, index + 1, matches);
if (index === segments.length && node.param.methods) {
const match = node.param.methods[method] || node.param.methods[""];
if (match) {
const pMap = match[0].paramsMap;
if (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match);
}
}
}
const staticChild = node.static?.[segment];
if (staticChild) _findAll(ctx, staticChild, method, segments, index + 1, matches);
if (index === segments.length && node.methods) {
const match = node.methods[method] || node.methods[""];
if (match) matches.push(...match);
}
return matches;
}
//#endregion
//#region node_modules/.pnpm/rou3@0.7.10/node_modules/rou3/dist/compiler.mjs
/**
* Compile the router instance into a compact runnable code.
*
* **IMPORTANT:** Route data must be serializable to JSON (i.e., no functions or classes) or implement the `toJSON()` method to render custom code or you can pass custom `serialize` function in options.
*
* @example
* import { createRouter, addRoute } from "rou3";
* import { compileRouterToString } from "rou3/compiler";
* const router = createRouter();
* // [add some routes with serializable data]
* const compilerCode = compileRouterToString(router, "findRoute");
* // "const findRoute=(m, p) => {}"
*/
function compileRouterToString(router, functionName, opts) {
const ctx = {
opts: opts || {},
router,
data: [],
compileToString: true
};
let compiled = `(m,p)=>{${compileRouteMatch(ctx)}}`;
if (ctx.data.length > 0) compiled = `/* @__PURE__ */ (() => { ${`const ${ctx.data.map((v, i) => `$${i}=${v}`).join(",")};`}; return ${compiled}})()`;
return functionName ? `const ${functionName}=${compiled};` : compiled;
}
function compileRouteMatch(ctx) {
let code = "";
const staticNodes = /* @__PURE__ */ new Set();
for (const key in ctx.router.static) {
const node = ctx.router.static[key];
if (node?.methods) {
staticNodes.add(node);
code += `if(p===${JSON.stringify(key.replace(/\/$/, "") || "/")}){${compileMethodMatch(ctx, node.methods, [], -1)}}`;
}
}
const match = compileNode(ctx, ctx.router.root, [], 0, staticNodes);
if (match) code += `let s=p.split("/"),l=s.length-1;${match}`;
if (!code) return ctx.opts?.matchAll ? `return [];` : "";
return `${ctx.opts?.matchAll ? `let r=[];` : ""}if(p.charCodeAt(p.length-1)===47)p=p.slice(0,-1)||"/";${code}${ctx.opts?.matchAll ? "return r;" : ""}`;
}
function compileMethodMatch(ctx, methods, params, currentIdx) {
let code = "";
for (const key in methods) {
const matchers = methods[key];
if (matchers && matchers?.length > 0) {
if (key !== "") code += `if(m==="${key}")${matchers.length > 1 ? "{" : ""}`;
const _matchers = matchers.map((m) => compileFinalMatch(ctx, m, currentIdx, params)).sort((a, b) => b.weight - a.weight);
for (const matcher of _matchers) code += matcher.code;
if (key !== "") code += matchers.length > 1 ? "}" : "";
}
}
return code;
}
function compileFinalMatch(ctx, data, currentIdx, params) {
let ret = `{data:${serializeData(ctx, data.data)}`;
const conditions = [];
const { paramsMap, paramsRegexp } = data;
if (paramsMap && paramsMap.length > 0) {
if (!paramsMap[paramsMap.length - 1][2] && currentIdx !== -1) conditions.push(`l>=${currentIdx}`);
for (let i = 0; i < paramsRegexp.length; i++) {
const regexp = paramsRegexp[i];
if (!regexp) continue;
conditions.push(`${regexp.toString()}.test(s[${i + 1}])`);
}
ret += ",params:{";
for (let i = 0; i < paramsMap.length; i++) {
const map = paramsMap[i];
ret += typeof map[1] === "string" ? `${JSON.stringify(map[1])}:${params[i]},` : `...(${map[1].toString()}.exec(${params[i]}))?.groups,`;
}
ret += "}";
}
return {
code: (conditions.length > 0 ? `if(${conditions.join("&&")})` : "") + (ctx.opts?.matchAll ? `r.unshift(${ret}});` : `return ${ret}};`),
weight: conditions.length
};
}
function compileNode(ctx, node, params, startIdx, staticNodes) {
let code = "";
if (node.methods && !staticNodes.has(node)) {
const match = compileMethodMatch(ctx, node.methods, params, node.key === "*" ? startIdx : -1);
if (match) {
const hasLastOptionalParam = node.key === "*";
code += `if(l===${startIdx}${hasLastOptionalParam ? `||l===${startIdx - 1}` : ""}){${match}}`;
}
}
if (node.static) for (const key in node.static) {
const match = compileNode(ctx, node.static[key], params, startIdx + 1, staticNodes);
if (match) code += `if(s[${startIdx + 1}]===${JSON.stringify(key)}){${match}}`;
}
if (node.param) {
const match = compileNode(ctx, node.param, [...params, `s[${startIdx + 1}]`], startIdx + 1, staticNodes);
if (match) code += match;
}
if (node.wildcard) {
const { wildcard } = node;
if (wildcard.static || wildcard.param || wildcard.wildcard) throw new Error("Compiler mode does not support patterns after wildcard");
if (wildcard.methods) {
const match = compileMethodMatch(ctx, wildcard.methods, [...params, `s.slice(${startIdx + 1}).join('/')`], startIdx);
if (match) code += match;
}
}
return code;
}
function serializeData(ctx, value) {
if (ctx.compileToString) if (ctx.opts?.serialize) value = ctx.opts.serialize(value);
else if (typeof value?.toJSON === "function") value = value.toJSON();
else value = JSON.stringify(value);
let index = ctx.data.indexOf(value);
if (index === -1) {
ctx.data.push(value);
index = ctx.data.length - 1;
}
return `$${index}`;
}
//#endregion
export { findRoute as a, findAllRoutes as i, addRoute as n, createRouter as r, compileRouterToString as t };
//#region node_modules/.pnpm/std-env@3.10.0/node_modules/std-env/dist/index.mjs
const r = Object.create(null), i = (e) => globalThis.process?.env || import.meta.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (e ? r : globalThis), o = new Proxy(r, {
get(e, s) {
return i()[s] ?? r[s];
},
has(e, s) {
return s in i() || s in r;
},
set(e, s, E) {
const B = i(!0);
return B[s] = E, !0;
},
deleteProperty(e, s) {
if (!s) return !1;
const E = i(!0);
return delete E[s], !0;
},
ownKeys() {
const e = i(!0);
return Object.keys(e);
}
}), t = typeof process < "u" && process.env && process.env.NODE_ENV || "", f = [
["APPVEYOR"],
[
"AWS_AMPLIFY",
"AWS_APP_ID",
{ ci: !0 }
],
["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"],
["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"],
["APPCIRCLE", "AC_APPCIRCLE"],
["BAMBOO", "bamboo_planKey"],
["BITBUCKET", "BITBUCKET_COMMIT"],
["BITRISE", "BITRISE_IO"],
["BUDDY", "BUDDY_WORKSPACE_ID"],
["BUILDKITE"],
["CIRCLE", "CIRCLECI"],
["CIRRUS", "CIRRUS_CI"],
[
"CLOUDFLARE_PAGES",
"CF_PAGES",
{ ci: !0 }
],
[
"CLOUDFLARE_WORKERS",
"WORKERS_CI",
{ ci: !0 }
],
["CODEBUILD", "CODEBUILD_BUILD_ARN"],
["CODEFRESH", "CF_BUILD_ID"],
["DRONE"],
["DRONE", "DRONE_BUILD_EVENT"],
["DSARI"],
["GITHUB_ACTIONS"],
["GITLAB", "GITLAB_CI"],
["GITLAB", "CI_MERGE_REQUEST_ID"],
["GOCD", "GO_PIPELINE_LABEL"],
["LAYERCI"],
["HUDSON", "HUDSON_URL"],
["JENKINS", "JENKINS_URL"],
["MAGNUM"],
["NETLIFY"],
[
"NETLIFY",
"NETLIFY_LOCAL",
{ ci: !1 }
],
["NEVERCODE"],
["RENDER"],
["SAIL", "SAILCI"],
["SEMAPHORE"],
["SCREWDRIVER"],
["SHIPPABLE"],
["SOLANO", "TDDIUM"],
["STRIDER"],
["TEAMCITY", "TEAMCITY_VERSION"],
["TRAVIS"],
["VERCEL", "NOW_BUILDER"],
[
"VERCEL",
"VERCEL",
{ ci: !1 }
],
[
"VERCEL",
"VERCEL_ENV",
{ ci: !1 }
],
["APPCENTER", "APPCENTER_BUILD_ID"],
[
"CODESANDBOX",
"CODESANDBOX_SSE",
{ ci: !1 }
],
[
"CODESANDBOX",
"CODESANDBOX_HOST",
{ ci: !1 }
],
["STACKBLITZ"],
["STORMKIT"],
["CLEAVR"],
["ZEABUR"],
[
"CODESPHERE",
"CODESPHERE_APP_ID",
{ ci: !0 }
],
["RAILWAY", "RAILWAY_PROJECT_ID"],
["RAILWAY", "RAILWAY_SERVICE_ID"],
["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"],
[
"FIREBASE_APP_HOSTING",
"FIREBASE_APP_HOSTING",
{ ci: !0 }
]
];
function b() {
if (globalThis.process?.env) for (const e of f) {
const s = e[1] || e[0];
if (globalThis.process?.env[s]) return {
name: e[0].toLowerCase(),
...e[2]
};
}
return globalThis.process?.env?.SHELL === "/bin/jsh" && globalThis.process?.versions?.webcontainer ? {
name: "stackblitz",
ci: !1
} : {
name: "",
ci: !1
};
}
const l = b(), p = l.name;
function n(e) {
return e ? e !== "false" : !1;
}
const I = globalThis.process?.platform || "", T = n(o.CI) || l.ci !== !1, R = n(globalThis.process?.stdout && globalThis.process?.stdout.isTTY), U = typeof window < "u", d = n(o.DEBUG), a = t === "test" || n(o.TEST), g = t === "production", h = t === "dev" || t === "development", v = n(o.MINIMAL) || T || a || !R, A = /^win/i.test(I), M = /^linux/i.test(I), m = /^darwin/i.test(I), Y = !n(o.NO_COLOR) && (n(o.FORCE_COLOR) || (R || A) && o.TERM !== "dumb" || T), C = (globalThis.process?.versions?.node || "").replace(/^v/, "") || null, V = Number(C?.split(".")[0]) || null, W = globalThis.process || Object.create(null), _ = { versions: {} }, y = new Proxy(W, { get(e, s) {
if (s === "env") return o;
if (s in e) return e[s];
if (s in _) return _[s];
} }), O = globalThis.process?.release?.name === "node", c = !!globalThis.Bun || !!globalThis.process?.versions?.bun, D = !!globalThis.Deno, L = !!globalThis.fastly, S = !!globalThis.Netlify, u = !!globalThis.EdgeRuntime, N = globalThis.navigator?.userAgent === "Cloudflare-Workers", F = [
[S, "netlify"],
[u, "edge-light"],
[N, "workerd"],
[L, "fastly"],
[D, "deno"],
[c, "bun"],
[O, "node"]
];
function G() {
const e = F.find((s) => s[0]);
if (e) return { name: e[1] };
}
const P = G(), K = P?.name || "";
//#endregion
export { p as a, d as i, T as n, a as r, K as t };
import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
import { t as require_js_tokens } from "./js-tokens.mjs";
//#region node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs
var import_js_tokens = /* @__PURE__ */ __toESM(require_js_tokens(), 1);
const FILL_COMMENT = " ";
function stripLiteralFromToken(token, fillChar, filter) {
if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length);
if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT);
if (token.type === "StringLiteral") {
if (!token.closed) return token.value;
const body = token.value.slice(1, -1);
if (filter(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1];
}
if (token.type === "NoSubstitutionTemplate") {
const body = token.value.slice(1, -1);
if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``;
}
if (token.type === "RegularExpressionLiteral") {
const body = token.value;
if (filter(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`);
}
if (token.type === "TemplateHead") {
const body = token.value.slice(1, -2);
if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`;
}
if (token.type === "TemplateTail") {
const body = token.value.slice(0, -2);
if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``;
}
if (token.type === "TemplateMiddle") {
const body = token.value.slice(1, -2);
if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`;
}
return token.value;
}
function optionsWithDefaults(options) {
return {
fillChar: options?.fillChar ?? " ",
filter: options?.filter ?? (() => true)
};
}
function stripLiteral(code, options) {
let result = "";
const _options = optionsWithDefaults(options);
for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter);
return result;
}
//#endregion
export { stripLiteral as t };
import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
import { t as require_picomatch } from "./picomatch.mjs";
import { t as Builder } from "./fdir.mjs";
import nativeFs from "fs";
import path, { posix } from "path";
import { fileURLToPath } from "url";
//#region node_modules/.pnpm/tinyglobby@0.2.15/node_modules/tinyglobby/dist/index.mjs
var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
const isReadonlyArray = Array.isArray;
const isWin = process.platform === "win32";
const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
function getPartialMatcher(patterns, options = {}) {
const patternsCount = patterns.length;
const patternsParts = Array(patternsCount);
const matchers = Array(patternsCount);
const globstarEnabled = !options.noglobstar;
for (let i = 0; i < patternsCount; i++) {
const parts = splitPattern(patterns[i]);
patternsParts[i] = parts;
const partsCount = parts.length;
const partMatchers = Array(partsCount);
for (let j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
matchers[i] = partMatchers;
}
return (input) => {
const inputParts = input.split("/");
if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
for (let i = 0; i < patterns.length; i++) {
const patternParts = patternsParts[i];
const matcher = matchers[i];
const inputPatternCount = inputParts.length;
const minParts = Math.min(inputPatternCount, patternParts.length);
let j = 0;
while (j < minParts) {
const part = patternParts[j];
if (part.includes("/")) return true;
if (!matcher[j](inputParts[j])) break;
if (globstarEnabled && part === "**") return true;
j++;
}
if (j === inputPatternCount) return true;
}
return false;
};
}
/* node:coverage ignore next 2 */
const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
function buildFormat(cwd, root, absolute) {
if (cwd === root || root.startsWith(`${cwd}/`)) {
if (absolute) {
const start = isRoot(cwd) ? cwd.length : cwd.length + 1;
return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
}
const prefix = root.slice(cwd.length + 1);
if (prefix) return (p, isDir) => {
if (p === ".") return prefix;
const result = `${prefix}/${p}`;
return isDir ? result.slice(0, -1) : result;
};
return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
}
if (absolute) return (p) => posix.relative(cwd, p) || ".";
return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
}
function buildRelative(cwd, root) {
if (root.startsWith(`${cwd}/`)) {
const prefix = root.slice(cwd.length + 1);
return (p) => `${prefix}/${p}`;
}
return (p) => {
const result = posix.relative(cwd, `${root}/${p}`);
if (p.endsWith("/") && result !== "") return `${result}/`;
return result || ".";
};
}
const splitPatternOptions = { parts: true };
function splitPattern(path$1) {
var _result$parts;
const result = import_picomatch.default.scan(path$1, splitPatternOptions);
return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1];
}
const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
const escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
/**
* Escapes a path's special characters depending on the platform.
* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
*/
/* node:coverage ignore next */
const escapePath = isWin ? escapeWin32Path : escapePosixPath;
/**
* Checks if a pattern has dynamic parts.
*
* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
*
* - Doesn't necessarily return `false` on patterns that include `\`.
* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
*
* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
*/
function isDynamicPattern(pattern, options) {
if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
const scan = import_picomatch.default.scan(pattern);
return scan.isGlob || scan.negated;
}
function log(...tasks) {
console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
}
const PARENT_DIRECTORY = /^(\/?\.\.)+/;
const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
const BACKSLASHES = /\\/g;
function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
let result = pattern;
if (pattern.endsWith("/")) result = pattern.slice(0, -1);
if (!result.endsWith("*") && expandDirectories) result += "/**";
const escapedCwd = escapePath(cwd);
if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
else result = posix.normalize(result);
const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
const parts = splitPattern(result);
if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
const n = (parentDirectoryMatch[0].length + 1) / 3;
let i = 0;
const cwdParts = escapedCwd.split("/");
while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
i++;
}
const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
props.root = potentialRoot;
props.depthOffset = -n + i;
}
}
if (!isIgnore && props.depthOffset >= 0) {
var _props$commonPath;
(_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
const newCommonPath = [];
const length = Math.min(props.commonPath.length, parts.length);
for (let i = 0; i < length; i++) {
const part = parts[i];
if (part === "**" && !parts[i + 1]) {
newCommonPath.pop();
break;
}
if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
newCommonPath.push(part);
}
props.depthOffset = newCommonPath.length;
props.commonPath = newCommonPath;
props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
}
return result;
}
function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) {
if (typeof patterns === "string") patterns = [patterns];
if (typeof ignore === "string") ignore = [ignore];
const matchPatterns = [];
const ignorePatterns = [];
for (const pattern of ignore) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
}
for (const pattern of patterns) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
}
return {
match: matchPatterns,
ignore: ignorePatterns
};
}
function formatPaths(paths, relative$1) {
for (let i = paths.length - 1; i >= 0; i--) {
const path$1 = paths[i];
paths[i] = relative$1(path$1);
}
return paths;
}
function normalizeCwd(cwd) {
if (!cwd) return process.cwd().replace(BACKSLASHES, "/");
if (cwd instanceof URL) return fileURLToPath(cwd).replace(BACKSLASHES, "/");
return path.resolve(cwd).replace(BACKSLASHES, "/");
}
function getCrawler(patterns, inputOptions = {}) {
const options = process.env.TINYGLOBBY_DEBUG ? {
...inputOptions,
debug: true
} : inputOptions;
const cwd = normalizeCwd(options.cwd);
if (options.debug) log("globbing with:", {
patterns,
options,
cwd
});
if (Array.isArray(patterns) && patterns.length === 0) return [{
sync: () => [],
withPromise: async () => []
}, false];
const props = {
root: cwd,
commonPath: null,
depthOffset: 0
};
const processed = processPatterns({
...options,
patterns
}, cwd, props);
if (options.debug) log("internal processing patterns:", processed);
const matchOptions = {
dot: options.dot,
nobrace: options.braceExpansion === false,
nocase: options.caseSensitiveMatch === false,
noextglob: options.extglob === false,
noglobstar: options.globstar === false,
posix: true
};
const matcher = (0, import_picomatch.default)(processed.match, {
...matchOptions,
ignore: processed.ignore
});
const ignore = (0, import_picomatch.default)(processed.ignore, matchOptions);
const partialMatcher = getPartialMatcher(processed.match, matchOptions);
const format = buildFormat(cwd, props.root, options.absolute);
const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true);
const fdirOptions = {
filters: [options.debug ? (p, isDirectory) => {
const path$1 = format(p, isDirectory);
const matches = matcher(path$1);
if (matches) log(`matched ${path$1}`);
return matches;
} : (p, isDirectory) => matcher(format(p, isDirectory))],
exclude: options.debug ? (_, p) => {
const relativePath = formatExclude(p, true);
const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
if (skipped) log(`skipped ${p}`);
else log(`crawling ${p}`);
return skipped;
} : (_, p) => {
const relativePath = formatExclude(p, true);
return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
},
fs: options.fs ? {
readdir: options.fs.readdir || nativeFs.readdir,
readdirSync: options.fs.readdirSync || nativeFs.readdirSync,
realpath: options.fs.realpath || nativeFs.realpath,
realpathSync: options.fs.realpathSync || nativeFs.realpathSync,
stat: options.fs.stat || nativeFs.stat,
statSync: options.fs.statSync || nativeFs.statSync
} : void 0,
pathSeparator: "/",
relativePaths: true,
resolveSymlinks: true,
signal: options.signal
};
if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
if (options.absolute) {
fdirOptions.relativePaths = false;
fdirOptions.resolvePaths = true;
fdirOptions.includeBasePath = true;
}
if (options.followSymbolicLinks === false) {
fdirOptions.resolveSymlinks = false;
fdirOptions.excludeSymlinks = true;
}
if (options.onlyDirectories) {
fdirOptions.excludeFiles = true;
fdirOptions.includeDirs = true;
} else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
props.root = props.root.replace(BACKSLASHES, "");
const root = props.root;
if (options.debug) log("internal properties:", props);
const relative$1 = cwd !== root && !options.absolute && buildRelative(cwd, props.root);
return [new Builder(fdirOptions).crawl(root), relative$1];
}
async function glob(patternsOrOptions, options) {
if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
const opts = isModern ? options : patternsOrOptions;
const [crawler, relative$1] = getCrawler(isModern ? patternsOrOptions : patternsOrOptions.patterns, opts);
if (!relative$1) return crawler.withPromise();
return formatPaths(await crawler.withPromise(), relative$1);
}
//#endregion
export { glob as t };
import path from "node:path";
import fs, { promises } from "node:fs";
import { createRequire } from "module";
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/util.js
const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g");
const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g");
/** @type {Map<string,RegExp>}*/
const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
const GLOB_ALL_PATTERN = `**/*`;
const TS_EXTENSIONS = [
".ts",
".tsx",
".mts",
".cts"
];
const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
".js",
".jsx",
".mjs",
".cjs"
]);
const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`;
const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`;
const IS_POSIX = path.posix.sep === path.sep;
/**
* @template T
* @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
*/
function makePromise() {
let resolve$1, reject;
return {
promise: new Promise((res, rej) => {
resolve$1 = res;
reject = rej;
}),
resolve: resolve$1,
reject
};
}
/**
* @param {string} filename
* @param {import('./cache.js').TSConfckCache} [cache]
* @returns {Promise<string|void>}
*/
async function resolveTSConfigJson(filename, cache) {
if (path.extname(filename) !== ".json") return;
const tsconfig = path.resolve(filename);
if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) return tsconfig;
return promises.stat(tsconfig).then((stat) => {
if (stat.isFile() || stat.isFIFO()) return tsconfig;
else throw new Error(`${filename} exists but is not a regular file.`);
});
}
/**
*
* @param {string} dir an absolute directory path
* @returns {boolean} if dir path includes a node_modules segment
*/
const isInNodeModules = IS_POSIX ? (dir) => dir.includes("/node_modules/") : (dir) => dir.match(/[/\\]node_modules[/\\]/);
/**
* convert posix separator to native separator
*
* eg.
* windows: C:/foo/bar -> c:\foo\bar
* linux: /foo/bar -> /foo/bar
*
* @param {string} filename with posix separators
* @returns {string} filename with native separators
*/
const posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, path.sep);
/**
* convert native separator to posix separator
*
* eg.
* windows: C:\foo\bar -> c:/foo/bar
* linux: /foo/bar -> /foo/bar
*
* @param {string} filename - filename with native separators
* @returns {string} filename with posix separators
*/
const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep);
/**
* converts params to native separator, resolves path and converts native back to posix
*
* needed on windows to handle posix paths in tsconfig
*
* @param dir {string|null} directory to resolve from
* @param filename {string} filename or pattern to resolve
* @returns string
*/
const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename)));
/**
*
* @param {import('./public.d.ts').TSConfckParseResult} result
* @param {import('./public.d.ts').TSConfckParseOptions} [options]
* @returns {string[]}
*/
function resolveReferencedTSConfigFiles(result, options) {
const dir = path.dirname(result.tsconfigFile);
return result.tsconfig.references.map((ref) => {
return resolve2posix(dir, ref.path.endsWith(".json") ? ref.path : path.join(ref.path, options?.configName ?? "tsconfig.json"));
});
}
/**
* @param {string} filename
* @param {import('./public.d.ts').TSConfckParseResult} result
* @returns {import('./public.d.ts').TSConfckParseResult}
*/
function resolveSolutionTSConfig(filename, result) {
const extensions = result.tsconfig.compilerOptions?.allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
if (result.referenced && extensions.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
const solutionTSConfig = result.referenced.find((referenced) => isIncluded(filename, referenced));
if (solutionTSConfig) return solutionTSConfig;
}
return result;
}
/**
*
* @param {string} filename
* @param {import('./public.d.ts').TSConfckParseResult} result
* @returns {boolean}
*/
function isIncluded(filename, result) {
const dir = native2posix(path.dirname(result.tsconfigFile));
const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
const absoluteFilename = resolve2posix(null, filename);
if (files.includes(filename)) return true;
const allowJs = result.tsconfig.compilerOptions?.allowJs;
if (isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
return false;
}
/**
* test filenames agains glob patterns in tsconfig
*
* @param filename {string} posix style abolute path to filename to test
* @param dir {string} posix style absolute path to directory of tsconfig containing patterns
* @param patterns {string[]} glob patterns to match against
* @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
* @returns {boolean} true when at least one pattern matches filename
*/
function isGlobMatch(filename, dir, patterns, allowJs) {
const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
return patterns.some((pattern) => {
let lastWildcardIndex = pattern.length;
let hasWildcard = false;
let hasExtension = false;
let hasSlash = false;
let lastSlashIndex = -1;
for (let i = pattern.length - 1; i > -1; i--) {
const c = pattern[i];
if (!hasWildcard) {
if (c === "*" || c === "?") {
lastWildcardIndex = i;
hasWildcard = true;
}
}
if (!hasSlash) {
if (c === ".") hasExtension = true;
else if (c === "/") {
lastSlashIndex = i;
hasSlash = true;
}
}
if (hasWildcard && hasSlash) break;
}
if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
lastWildcardIndex = pattern.length - 1;
hasWildcard = true;
}
if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
const resolvedPattern = resolve2posix(dir, pattern);
let firstWildcardIndex = -1;
for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
firstWildcardIndex = i;
hasWildcard = true;
break;
}
if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
if (!hasWildcard) return filename === resolvedPattern;
else if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
const regex = pattern2regex(resolvedPattern, allowJs);
PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
return regex.test(filename);
});
}
/**
* @param {string} resolvedPattern
* @param {boolean} allowJs
* @returns {RegExp}
*/
function pattern2regex(resolvedPattern, allowJs) {
let regexStr = "^";
for (let i = 0; i < resolvedPattern.length; i++) {
const char = resolvedPattern[i];
if (char === "?") {
regexStr += "[^\\/]";
continue;
}
if (char === "*") {
if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
i += 2;
regexStr += "(?:[^\\/]*\\/)*";
continue;
}
regexStr += "[^\\/]*";
continue;
}
if ("/.+^${}()|[]\\".includes(char)) regexStr += `\\`;
regexStr += char;
}
if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
regexStr += "$";
return new RegExp(regexStr);
}
/**
* replace tokens like ${configDir}
* @param {import('./public.d.ts').TSConfckParseResult} result
*/
function replaceTokens(result) {
if (result.tsconfig) result.tsconfig = JSON.parse(JSON.stringify(result.tsconfig).replaceAll(/"\${configDir}/g, `"${native2posix(path.dirname(result.tsconfigFile))}`));
}
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/find.js
/**
* find the closest tsconfig.json file
*
* @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
* @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
* @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
*/
async function find(filename, options) {
let dir = path.dirname(path.resolve(filename));
if (options?.ignoreNodeModules && isInNodeModules(dir)) return null;
const cache = options?.cache;
const configName = options?.configName ?? "tsconfig.json";
if (cache?.hasConfigPath(dir, configName)) return cache.getConfigPath(dir, configName);
const { promise, resolve: resolve$1, reject } = makePromise();
if (options?.root && !path.isAbsolute(options.root)) options.root = path.resolve(options.root);
findUp(dir, {
promise,
resolve: resolve$1,
reject
}, options);
return promise;
}
/**
*
* @param {string} dir
* @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
* @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
*/
function findUp(dir, { resolve: resolve$1, reject, promise }, options) {
const { cache, root, configName } = options ?? {};
if (cache) if (cache.hasConfigPath(dir, configName)) {
let cached;
try {
cached = cache.getConfigPath(dir, configName);
} catch (e) {
reject(e);
return;
}
if (cached?.then) cached.then(resolve$1).catch(reject);
else resolve$1(cached);
} else cache.setConfigPath(dir, promise, configName);
const tsconfig = path.join(dir, options?.configName ?? "tsconfig.json");
fs.stat(tsconfig, (err, stats) => {
if (stats && (stats.isFile() || stats.isFIFO())) resolve$1(tsconfig);
else if (err?.code !== "ENOENT") reject(err);
else {
let parent;
if (root === dir || (parent = path.dirname(dir)) === dir) resolve$1(null);
else findUp(parent, {
promise,
resolve: resolve$1,
reject
}, options);
}
});
}
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/find-all.js
/**
* @typedef WalkState
* @interface
* @property {string[]} files - files
* @property {number} calls - number of ongoing calls
* @property {(dir: string)=>boolean} skip - function to skip dirs
* @property {boolean} err - error flag
* @property {string[]} configNames - config file names
*/
const sep$1 = path.sep;
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/to-json.js
/**
* convert content of tsconfig.json to regular json
*
* @param {string} tsconfigJson - content of tsconfig.json
* @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
*/
function toJson(tsconfigJson) {
const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
if (stripped.trim() === "") return "{}";
else return stripped;
}
/**
* replace dangling commas from pseudo-json string with single space
* implementation heavily inspired by strip-json-comments
*
* @param {string} pseudoJson
* @returns {string}
*/
function stripDanglingComma(pseudoJson) {
let insideString = false;
let offset = 0;
let result = "";
let danglingCommaPos = null;
for (let i = 0; i < pseudoJson.length; i++) {
const currentCharacter = pseudoJson[i];
if (currentCharacter === "\"") {
if (!isEscaped(pseudoJson, i)) insideString = !insideString;
}
if (insideString) {
danglingCommaPos = null;
continue;
}
if (currentCharacter === ",") {
danglingCommaPos = i;
continue;
}
if (danglingCommaPos) {
if (currentCharacter === "}" || currentCharacter === "]") {
result += pseudoJson.slice(offset, danglingCommaPos) + " ";
offset = danglingCommaPos + 1;
danglingCommaPos = null;
} else if (!currentCharacter.match(/\s/)) danglingCommaPos = null;
}
}
return result + pseudoJson.substring(offset);
}
/**
*
* @param {string} jsonString
* @param {number} quotePosition
* @returns {boolean}
*/
function isEscaped(jsonString, quotePosition) {
let index = quotePosition - 1;
let backslashCount = 0;
while (jsonString[index] === "\\") {
index -= 1;
backslashCount += 1;
}
return Boolean(backslashCount % 2);
}
/**
*
* @param {string} string
* @param {number?} start
* @param {number?} end
*/
function strip(string, start, end) {
return string.slice(start, end).replace(/\S/g, " ");
}
const singleComment = Symbol("singleComment");
const multiComment = Symbol("multiComment");
/**
* @param {string} jsonString
* @returns {string}
*/
function stripJsonComments(jsonString) {
let isInsideString = false;
/** @type {false | symbol} */
let isInsideComment = false;
let offset = 0;
let result = "";
for (let index = 0; index < jsonString.length; index++) {
const currentCharacter = jsonString[index];
const nextCharacter = jsonString[index + 1];
if (!isInsideComment && currentCharacter === "\"") {
if (!isEscaped(jsonString, index)) isInsideString = !isInsideString;
}
if (isInsideString) continue;
if (!isInsideComment && currentCharacter + nextCharacter === "//") {
result += jsonString.slice(offset, index);
offset = index;
isInsideComment = singleComment;
index++;
} else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
index++;
isInsideComment = false;
result += strip(jsonString, offset, index);
offset = index;
} else if (isInsideComment === singleComment && currentCharacter === "\n") {
isInsideComment = false;
result += strip(jsonString, offset, index);
offset = index;
} else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
result += jsonString.slice(offset, index);
offset = index;
isInsideComment = multiComment;
index++;
} else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
index++;
isInsideComment = false;
result += strip(jsonString, offset, index + 1);
offset = index + 1;
}
}
return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
}
/**
* @param {string} string
* @returns {string}
*/
function stripBom(string) {
if (string.charCodeAt(0) === 65279) return string.slice(1);
return string;
}
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/parse.js
const not_found_result = {
tsconfigFile: null,
tsconfig: {}
};
/**
* parse the closest tsconfig.json file
*
* @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
* @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
* @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
* @throws {TSConfckParseError}
*/
async function parse(filename, options) {
/** @type {import('./cache.js').TSConfckCache} */
const cache = options?.cache;
if (cache?.hasParseResult(filename)) return getParsedDeep(filename, cache, options);
const { resolve: resolve$1, reject, promise } = makePromise();
cache?.setParseResult(filename, promise, true);
try {
let tsconfigFile = await resolveTSConfigJson(filename, cache) || await find(filename, options);
if (!tsconfigFile) {
resolve$1(not_found_result);
return promise;
}
let result;
if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) result = await getParsedDeep(tsconfigFile, cache, options);
else {
result = await parseFile(tsconfigFile, cache, filename === tsconfigFile);
await Promise.all([parseExtends(result, cache), parseReferences(result, options)]);
}
replaceTokens(result);
resolve$1(resolveSolutionTSConfig(filename, result));
} catch (e) {
reject(e);
}
return promise;
}
/**
* ensure extends and references are parsed
*
* @param {string} filename - cached file
* @param {import('./cache.js').TSConfckCache} cache - cache
* @param {import('./public.d.ts').TSConfckParseOptions} options - options
*/
async function getParsedDeep(filename, cache, options) {
const result = await cache.getParseResult(filename);
if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
const promise = Promise.all([parseExtends(result, cache), parseReferences(result, options)]).then(() => result);
cache.setParseResult(filename, promise, true);
return promise;
}
return result;
}
/**
*
* @param {string} tsconfigFile - path to tsconfig file
* @param {import('./cache.js').TSConfckCache} [cache] - cache
* @param {boolean} [skipCache] - skip cache
* @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
*/
async function parseFile(tsconfigFile, cache, skipCache) {
if (!skipCache && cache?.hasParseResult(tsconfigFile) && !cache.getParseResult(tsconfigFile)._isRootFile_) return cache.getParseResult(tsconfigFile);
const promise = promises.readFile(tsconfigFile, "utf-8").then(toJson).then((json) => {
const parsed = JSON.parse(json);
applyDefaults(parsed, tsconfigFile);
return {
tsconfigFile,
tsconfig: normalizeTSConfig(parsed, path.dirname(tsconfigFile))
};
}).catch((e) => {
throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e}`, "PARSE_FILE", tsconfigFile, e);
});
if (!skipCache && (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_)) cache?.setParseResult(tsconfigFile, promise);
return promise;
}
/**
* normalize to match the output of ts.parseJsonConfigFileContent
*
* @param {any} tsconfig - typescript tsconfig output
* @param {string} dir - directory
*/
function normalizeTSConfig(tsconfig, dir) {
const baseUrl = tsconfig.compilerOptions?.baseUrl;
if (baseUrl && !baseUrl.startsWith("${") && !path.isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
return tsconfig;
}
/**
*
* @param {import('./public.d.ts').TSConfckParseResult} result
* @param {import('./public.d.ts').TSConfckParseOptions} [options]
* @returns {Promise<void>}
*/
async function parseReferences(result, options) {
if (!result.tsconfig.references) return;
const referencedFiles = resolveReferencedTSConfigFiles(result, options);
const referenced = await Promise.all(referencedFiles.map((file) => parseFile(file, options?.cache)));
await Promise.all(referenced.map((ref) => parseExtends(ref, options?.cache)));
referenced.forEach((ref) => {
ref.solution = result;
replaceTokens(ref);
});
result.referenced = referenced;
}
/**
* @param {import('./public.d.ts').TSConfckParseResult} result
* @param {import('./cache.js').TSConfckCache}[cache]
* @returns {Promise<void>}
*/
async function parseExtends(result, cache) {
if (!result.tsconfig.extends) return;
/** @type {import('./public.d.ts').TSConfckParseResult[]} */
const extended = [{
tsconfigFile: result.tsconfigFile,
tsconfig: JSON.parse(JSON.stringify(result.tsconfig))
}];
let pos = 0;
/** @type {string[]} */
const extendsPath = [];
let currentBranchDepth = 0;
while (pos < extended.length) {
const extending = extended[pos];
extendsPath.push(extending.tsconfigFile);
if (extending.tsconfig.extends) {
currentBranchDepth += 1;
/** @type {string[]} */
let resolvedExtends;
if (!Array.isArray(extending.tsconfig.extends)) resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
else resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
const circularExtends = resolvedExtends.find((tsconfigFile) => extendsPath.includes(tsconfigFile));
if (circularExtends) throw new TSConfckParseError(`Circular dependency in "extends": ${extendsPath.concat([circularExtends]).join(" -> ")}`, "EXTENDS_CIRCULAR", result.tsconfigFile);
extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file) => parseFile(file, cache))));
} else {
extendsPath.splice(-currentBranchDepth);
currentBranchDepth = 0;
}
pos = pos + 1;
}
result.extended = extended;
for (const ext of result.extended.slice(1)) extendTSConfig(result, ext);
}
/**
*
* @param {string} extended
* @param {string} from
* @returns {string}
*/
function resolveExtends(extended, from) {
if ([".", ".."].includes(extended)) extended = extended + "/tsconfig.json";
const req = createRequire(from);
let error;
try {
return req.resolve(extended);
} catch (e) {
error = e;
}
if (extended[0] !== "." && !path.isAbsolute(extended)) try {
return req.resolve(`${extended}/tsconfig.json`);
} catch (e) {
error = e;
}
throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error);
}
const EXTENDABLE_KEYS = [
"compilerOptions",
"files",
"include",
"exclude",
"watchOptions",
"compileOnSave",
"typeAcquisition",
"buildOptions"
];
/**
*
* @param {import('./public.d.ts').TSConfckParseResult} extending
* @param {import('./public.d.ts').TSConfckParseResult} extended
* @returns void
*/
function extendTSConfig(extending, extended) {
const extendingConfig = extending.tsconfig;
const extendedConfig = extended.tsconfig;
const relativePath = native2posix(path.relative(path.dirname(extending.tsconfigFile), path.dirname(extended.tsconfigFile)));
for (const key of Object.keys(extendedConfig).filter((key$1) => EXTENDABLE_KEYS.includes(key$1))) if (key === "compilerOptions") {
if (!extendingConfig.compilerOptions) extendingConfig.compilerOptions = {};
for (const option of Object.keys(extendedConfig.compilerOptions)) {
if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) continue;
extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath);
}
} else if (extendingConfig[key] === void 0) if (key === "watchOptions") {
extendingConfig.watchOptions = {};
for (const option of Object.keys(extendedConfig.watchOptions)) extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath);
} else extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
}
const REBASE_KEYS = [
"files",
"include",
"exclude",
"baseUrl",
"rootDir",
"rootDirs",
"typeRoots",
"outDir",
"outFile",
"declarationDir",
"excludeDirectories",
"excludeFiles"
];
/** @typedef {string | string[]} PathValue */
/**
*
* @param {string} key
* @param {PathValue} value
* @param {string} prependPath
* @returns {PathValue}
*/
function rebaseRelative(key, value, prependPath) {
if (!REBASE_KEYS.includes(key)) return value;
if (Array.isArray(value)) return value.map((x) => rebasePath(x, prependPath));
else return rebasePath(value, prependPath);
}
/**
*
* @param {string} value
* @param {string} prependPath
* @returns {string}
*/
function rebasePath(value, prependPath) {
if (path.isAbsolute(value) || value.startsWith("${configDir}")) return value;
else return path.posix.normalize(path.posix.join(prependPath, value));
}
var TSConfckParseError = class TSConfckParseError extends Error {
/**
* error code
* @type {string}
*/
code;
/**
* error cause
* @type { Error | undefined}
*/
cause;
/**
* absolute path of tsconfig file where the error happened
* @type {string}
*/
tsconfigFile;
/**
*
* @param {string} message - error message
* @param {string} code - error code
* @param {string} tsconfigFile - path to tsconfig file
* @param {Error?} cause - cause of this error
*/
constructor(message, code, tsconfigFile, cause) {
super(message);
Object.setPrototypeOf(this, TSConfckParseError.prototype);
this.name = TSConfckParseError.name;
this.code = code;
this.cause = cause;
this.tsconfigFile = tsconfigFile;
}
};
/**
*
* @param {any} tsconfig
* @param {string} tsconfigFile
*/
function applyDefaults(tsconfig, tsconfigFile) {
if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = {
...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
...tsconfig.compilerOptions
};
}
const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
noEmit: true
};
/**
* @param {string} configFileName
*/
function isJSConfig(configFileName) {
return path.basename(configFileName) === "jsconfig.json";
}
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/parse-native.js
/** @typedef TSDiagnosticError {
code: number;
category: number;
messageText: string;
start?: number;
} TSDiagnosticError */
//#endregion
//#region node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/cache.js
/** @template T */
var TSConfckCache = class {
/**
* clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
*/
clear() {
this.#configPaths.clear();
this.#parsed.clear();
}
/**
* has cached closest config for files in dir
* @param {string} dir
* @param {string} [configName=tsconfig.json]
* @returns {boolean}
*/
hasConfigPath(dir, configName = "tsconfig.json") {
return this.#configPaths.has(`${dir}/${configName}`);
}
/**
* get cached closest tsconfig for files in dir
* @param {string} dir
* @param {string} [configName=tsconfig.json]
* @returns {Promise<string|null>|string|null}
* @throws {unknown} if cached value is an error
*/
getConfigPath(dir, configName = "tsconfig.json") {
const key = `${dir}/${configName}`;
const value = this.#configPaths.get(key);
if (value == null || value.length || value.then) return value;
else throw value;
}
/**
* has parsed tsconfig for file
* @param {string} file
* @returns {boolean}
*/
hasParseResult(file) {
return this.#parsed.has(file);
}
/**
* get parsed tsconfig for file
* @param {string} file
* @returns {Promise<T>|T}
* @throws {unknown} if cached value is an error
*/
getParseResult(file) {
const value = this.#parsed.get(file);
if (value.then || value.tsconfig) return value;
else throw value;
}
/**
* @internal
* @private
* @param file
* @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile()
* @param {Promise<T>} result
*/
setParseResult(file, result, isRootFile = false) {
Object.defineProperty(result, "_isRootFile_", {
value: isRootFile,
writable: false,
enumerable: false,
configurable: false
});
this.#parsed.set(file, result);
result.then((parsed) => {
if (this.#parsed.get(file) === result) this.#parsed.set(file, parsed);
}).catch((e) => {
if (this.#parsed.get(file) === result) this.#parsed.set(file, e);
});
}
/**
* @internal
* @private
* @param {string} dir
* @param {Promise<string|null>} configPath
* @param {string} [configName=tsconfig.json]
*/
setConfigPath(dir, configPath, configName = "tsconfig.json") {
const key = `${dir}/${configName}`;
this.#configPaths.set(key, configPath);
configPath.then((path$1) => {
if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, path$1);
}).catch((e) => {
if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, e);
});
}
/**
* map directories to their closest tsconfig.json
* @internal
* @private
* @type{Map<string,(Promise<string|null>|string|null)>}
*/
#configPaths = /* @__PURE__ */ new Map();
/**
* map files to their parsed tsconfig result
* @internal
* @private
* @type {Map<string,(Promise<T>|T)> }
*/
#parsed = /* @__PURE__ */ new Map();
};
//#endregion
export { parse as n, TSConfckCache as t };
//#region node_modules/.pnpm/ultrahtml@1.6.0/node_modules/ultrahtml/dist/index.js
var S = Symbol("Fragment"), D = new Set([
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr"
]), x = new Set(["script", "style"]), o = /(?:<(\/?)([a-zA-Z][a-zA-Z0-9\:-]*)(?:\s([^>]*?))?((?:\s*\/)?)>|(<\!\-\-)([\s\S]*?)(\-\->)|(<\!)([\s\S]*?)(>))/gm, b = /[\@\.a-z0-9_\:\-]/i;
function I(e) {
let t = {};
if (e) {
let i = "none", r, n = "", a, l;
for (let c = 0; c < e.length; c++) {
let d = e[c];
i === "none" ? b.test(d) ? (r && (t[r] = n, r = void 0, n = ""), a = c, i = "key") : d === "=" && r && (i = "value") : i === "key" ? b.test(d) || (r = e.substring(a, c), d === "=" ? i = "value" : i = "none") : d === l && c > 0 && e[c - 1] !== "\\" ? l && (n = e.substring(a, c), l = void 0, i = "none") : (d === "\"" || d === "'") && !l && (a = c + 1, l = d);
}
i === "key" && a != null && a < e.length && (r = e.substring(a, e.length)), r && (t[r] = n);
}
return t;
}
function P(e) {
let t = typeof e == "string" ? e : e.value, i, r, n, a, l, c, d, m, s, u = [];
o.lastIndex = 0, r = i = {
type: 0,
children: []
};
let g = 0;
function h() {
a = t.substring(g, o.lastIndex - n[0].length), a && r.children.push({
type: 2,
value: a,
parent: r
});
}
for (; n = o.exec(t);) {
if (c = n[5] || n[8], d = n[6] || n[9], m = n[7] || n[10], x.has(r.name) && n[2] !== r.name) {
l = o.lastIndex - n[0].length, r.children.length > 0 && (r.children[0].value += n[0]);
continue;
} else if (c === "<!--") {
if (l = o.lastIndex - n[0].length, x.has(r.name)) continue;
s = {
type: 3,
value: d,
parent: r,
loc: [{
start: l,
end: l + c.length
}, {
start: o.lastIndex - m.length,
end: o.lastIndex
}]
}, u.push(s), s.parent.children.push(s);
} else if (c === "<!") l = o.lastIndex - n[0].length, s = {
type: 4,
value: d,
parent: r,
loc: [{
start: l,
end: l + c.length
}, {
start: o.lastIndex - m.length,
end: o.lastIndex
}]
}, u.push(s), s.parent.children.push(s);
else if (n[1] !== "/") if (h(), x.has(r.name)) {
g = o.lastIndex, h();
continue;
} else s = {
type: 1,
name: n[2] + "",
attributes: I(n[3]),
parent: r,
children: [],
loc: [{
start: o.lastIndex - n[0].length,
end: o.lastIndex
}]
}, u.push(s), s.parent.children.push(s), n[4] && n[4].indexOf("/") > -1 || D.has(s.name) ? (s.loc[1] = s.loc[0], s.isSelfClosingTag = !0) : r = s;
else h(), n[2] + "" === r.name ? (s = r, r = s.parent, s.loc.push({
start: o.lastIndex - n[0].length,
end: o.lastIndex
}), a = t.substring(s.loc[0].end, s.loc[1].start), s.children.length === 0 && s.children.push({
type: 2,
value: a,
parent: r
})) : n[2] + "" === u[u.length - 1].name && u[u.length - 1].isSelfClosingTag === !0 && (s = u[u.length - 1], s.loc.push({
start: o.lastIndex - n[0].length,
end: o.lastIndex
}));
g = o.lastIndex;
}
return a = t.slice(g), r.children.push({
type: 2,
value: a,
parent: r
}), i;
}
var T = class {
constructor(t) {
this.callback = t;
}
async visit(t, i, r) {
if (await this.callback(t, i, r), Array.isArray(t.children)) {
let n = [];
for (let a = 0; a < t.children.length; a++) {
let l = t.children[a];
n.push(this.visit(l, t, a));
}
await Promise.all(n);
}
}
}, O = class {
constructor(t) {
this.callback = t;
}
visit(t, i, r) {
if (this.callback(t, i, r), Array.isArray(t.children)) for (let n = 0; n < t.children.length; n++) {
let a = t.children[n];
this.visit(a, t, n);
}
}
}, p = Symbol("HTMLString"), M = Symbol("AttrString"), f = Symbol("RenderFn");
function z(e, t) {
return new T(t).visit(e);
}
//#endregion
export { z as n, P as t };

Sorry, the diff of this file is too big to display

import { r as genObjectKey } from "./knitwork.mjs";
import "scule";
//#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.Br_uXjZG.mjs
function getType(val) {
const type = typeof val;
if (type === "undefined" || val === null) return;
if (Array.isArray(val)) return "array";
return type;
}
function isObject(val) {
return val !== null && !Array.isArray(val) && typeof val === "object";
}
function nonEmpty(arr) {
return arr.filter(Boolean);
}
function unique(arr) {
return [...new Set(arr)];
}
function joinPath(a, b = "", sep = ".") {
return a ? a + sep + b : b;
}
function setValue(obj, path, val) {
const keys = path.split(".");
const _key = keys.pop();
for (const key of keys) {
if (!obj || typeof obj !== "object") return;
if (!(key in obj)) obj[key] = {};
obj = obj[key];
}
if (_key) {
if (!obj || typeof obj !== "object") return;
obj[_key] = val;
}
}
function getValue(obj, path) {
for (const key of path.split(".")) {
if (!obj || typeof obj !== "object" || !(key in obj)) return;
obj = obj[key];
}
return obj;
}
function normalizeTypes(val) {
const arr = unique(val.filter(Boolean));
if (arr.length === 0 || arr.includes("any")) return;
return arr.length > 1 ? arr : arr[0];
}
//#endregion
//#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.BTwOq8Jl.mjs
async function resolveSchema(obj, defaults, options = {}) {
return await _resolveSchema(obj, "", {
root: obj,
defaults,
resolveCache: {},
ignoreDefaults: !!options.ignoreDefaults
});
}
async function _resolveSchema(input, id, ctx) {
if (id in ctx.resolveCache) return ctx.resolveCache[id];
const schemaId = "#" + id.replace(/\./g, "/");
if (!isObject(input)) {
const safeInput = Array.isArray(input) ? [...input] : input;
const schema2 = {
type: getType(input),
id: schemaId,
default: ctx.ignoreDefaults ? void 0 : safeInput
};
normalizeSchema(schema2, { ignoreDefaults: ctx.ignoreDefaults });
ctx.resolveCache[id] = schema2;
if (ctx.defaults && getValue(ctx.defaults, id) === void 0) setValue(ctx.defaults, id, schema2.default);
return schema2;
}
const node = { ...input };
const schema = ctx.resolveCache[id] = {
...node.$schema,
id: schemaId
};
for (const key in node) {
if (key === "$resolve" || key === "$schema" || key === "$default") continue;
schema.properties = schema.properties || {};
if (!schema.properties[key]) {
const child = schema.properties[key] = await _resolveSchema(node[key], joinPath(id, key), ctx);
if (Array.isArray(child.tags) && child.tags.includes("@required")) {
schema.required = schema.required || [];
if (!schema.required.includes(key)) schema.required.push(key);
}
}
}
if (!ctx.ignoreDefaults) {
if (ctx.defaults) schema.default = getValue(ctx.defaults, id);
if (schema.default === void 0 && "$default" in node) schema.default = node.$default;
if (typeof node.$resolve === "function") schema.default = await node.$resolve(schema.default, async (key) => {
return (await _resolveSchema(getValue(ctx.root, key), key, ctx)).default;
});
}
if (ctx.defaults) setValue(ctx.defaults, id, schema.default);
if (!schema.type) schema.type = getType(schema.default) || (schema.properties ? "object" : "any");
normalizeSchema(schema, { ignoreDefaults: ctx.ignoreDefaults });
if (ctx.defaults && getValue(ctx.defaults, id) === void 0) setValue(ctx.defaults, id, schema.default);
return schema;
}
function normalizeSchema(schema, options) {
if (schema.type === "array" && !("items" in schema)) {
schema.items = { type: nonEmpty(unique(schema.default.map((i) => getType(i)))) };
if (schema.items.type) {
if (schema.items.type.length === 0) schema.items.type = "any";
else if (schema.items.type.length === 1) schema.items.type = schema.items.type[0];
}
}
if (!options.ignoreDefaults && schema.default === void 0 && ("properties" in schema || schema.type === "object" || schema.type === "any")) {
const propsWithDefaults = Object.entries(schema.properties || {}).filter(([, prop]) => "default" in prop).map(([key, value]) => [key, value.default]);
schema.default = Object.fromEntries(propsWithDefaults);
}
}
//#endregion
//#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/index.mjs
const GenerateTypesDefaults = {
interfaceName: "Untyped",
addExport: true,
addDefaults: true,
allowExtraKeys: void 0,
partial: false,
indentation: 0
};
const TYPE_MAP = {
array: "any[]",
bigint: "bigint",
boolean: "boolean",
number: "number",
object: "",
any: "any",
string: "string",
symbol: "Symbol",
function: "Function"
};
const SCHEMA_KEYS = /* @__PURE__ */ new Set([
"items",
"default",
"resolve",
"properties",
"title",
"description",
"$schema",
"type",
"tsType",
"markdownType",
"tags",
"args",
"id",
"returns"
]);
const DECLARATION_RE = /typeof import\(["'](?<source>[^)]+)["']\)(\.(?<type>\w+)|\[["'](?<type1>\w+)["']])/g;
function extractTypeImports(declarations) {
const typeImports = {};
const aliases = /* @__PURE__ */ new Set();
const imports = [];
for (const match of declarations.matchAll(DECLARATION_RE)) {
const { source, type1, type = type1 } = match.groups || {};
typeImports[source] = typeImports[source] || /* @__PURE__ */ new Set();
typeImports[source].add(type);
}
for (const source in typeImports) {
const sourceImports = [];
for (const type of typeImports[source]) {
let count = 0;
let alias = type;
while (aliases.has(alias)) alias = `${type}${count++}`;
aliases.add(alias);
sourceImports.push(alias === type ? type : `${type} as ${alias}`);
declarations = declarations.replace(new RegExp(`typeof import\\(['"]${source}['"]\\)(\\.${type}|\\[['"]${type}['"]\\])`, "g"), alias);
}
imports.push(`import type { ${sourceImports.join(", ")} } from '${source}'`);
}
return [...imports, declarations].join("\n");
}
function generateTypes(schema, opts = {}) {
opts = {
...GenerateTypesDefaults,
...opts
};
const baseIden = " ".repeat(opts.indentation || 0);
const interfaceCode = `interface ${opts.interfaceName} {
` + _genTypes(schema, baseIden + " ", opts).map((l) => l.trim().length > 0 ? l : "").join("\n") + `
${baseIden}}`;
if (!opts.addExport) return baseIden + interfaceCode;
return extractTypeImports(baseIden + `export ${interfaceCode}`);
}
function _genTypes(schema, spaces, opts) {
const buff = [];
if (!schema) return buff;
for (const key in schema.properties) {
const val = schema.properties[key];
buff.push(...generateJSDoc(val, opts));
if (val.tsType) buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${val.tsType},
`);
else if (val.type === "object") buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`, ..._genTypes(val, spaces, opts), "},\n");
else {
let type;
if (val.type === "array") type = `Array<${getTsType(val.items || [], opts)}>`;
else if (val.type === "function") type = genFunctionType(val, opts);
else type = getTsType(val, opts);
buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${type},
`);
}
}
if (buff.length > 0) {
const last = buff.pop() || "";
buff.push(last.slice(0, Math.max(0, last.length - 1)));
}
if (opts.allowExtraKeys === true || buff.length === 0 && opts.allowExtraKeys !== false) buff.push("[key: string]: any");
return buff.flatMap((l) => l.split("\n")).map((l) => spaces + l);
}
function getTsType(type, opts) {
if (Array.isArray(type)) return [normalizeTypes(type.map((t) => getTsType(t, opts)))].flat().join("|") || "any";
if (!type) return "any";
if (type.tsType) return type.tsType;
if (!type.type) return "any";
if (Array.isArray(type.type)) return type.type.map((t) => {
if (t === "object" && type.type.length > 1) return `{
` + _genTypes(type, " ", opts).join("\n") + `
}`;
return TYPE_MAP[t];
}).join("|");
if (type.type === "array") return `Array<${getTsType(type.items || [], opts)}>`;
if (type.type === "object") return `{
` + _genTypes(type, " ", opts).join("\n") + `
}`;
return TYPE_MAP[type.type] || type.type;
}
function genFunctionType(schema, opts) {
return `(${genFunctionArgs(schema.args, opts)}) => ${getTsType(schema.returns || [], opts)}`;
}
function genFunctionArgs(args, opts) {
return args?.map((arg) => {
let argStr = arg.name;
if (arg.optional || arg.default) argStr += "?";
if (arg.type || arg.tsType) argStr += `: ${getTsType(arg, opts)}`;
return argStr;
}).join(", ") || "";
}
function generateJSDoc(schema, opts) {
opts.defaultDescription = opts.defaultDescription || opts.defaultDescrption;
let buff = [];
if (schema.title) buff.push(schema.title, "");
if (schema.description) buff.push(schema.description, "");
else if (opts.defaultDescription && schema.type !== "object") buff.push(opts.defaultDescription, "");
if (opts.addDefaults && schema.type !== "object" && schema.type !== "any" && !(Array.isArray(schema.default) && schema.default.length === 0)) {
const stringified = JSON.stringify(schema.default);
if (stringified) buff.push(`@default ${stringified.replace(/\*\//g, String.raw`*\/`)}`);
}
for (const key in schema) if (!SCHEMA_KEYS.has(key)) buff.push("", `@${key} ${schema[key]}`);
if (Array.isArray(schema.tags)) {
for (const tag of schema.tags) if (tag !== "@untyped") buff.push("", tag);
}
buff = buff.flatMap((i) => i.split("\n"));
if (buff.length > 0) return buff.length === 1 ? ["/** " + buff[0] + " */"] : [
"/**",
...buff.map((i) => ` * ${i}`),
"*/"
];
return [];
}
function isRequired(schema, key, opts) {
if (Array.isArray(schema.required) && schema.required.includes(key)) return true;
return !opts.partial;
}
//#endregion
export { resolveSchema as n, generateTypes as t };

Sorry, the diff of this file is too big to display

import { t as MagicString } from "./magic-string.mjs";
import { t as stripLiteral } from "./strip-literal.mjs";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import assert from "node:assert";
import "srvx/node";
import { createHash } from "node:crypto";
import { isCSSRequest, normalizePath } from "vite";
import assert$1 from "node:assert/strict";
//#region node_modules/.pnpm/@pi0+vite-plugin-fullstack@0.0.5-pr-1297_vite@7.2.2_@types+node@24.10.0_jiti@2.6.1_ligh_420de11c17db6dc1bb00fb6cc17e9a42/node_modules/@pi0/vite-plugin-fullstack/dist/index.js
function parseIdQuery(id) {
if (!id.includes("?")) return {
filename: id,
query: {}
};
const [filename, rawQuery] = id.split(`?`, 2);
return {
filename,
query: Object.fromEntries(new URLSearchParams(rawQuery))
};
}
function toAssetsVirtual(options) {
return `virtual:fullstack/assets?${new URLSearchParams(options)}&lang.js`;
}
function parseAssetsVirtual(id) {
if (id.startsWith("\0virtual:fullstack/assets?")) return parseIdQuery(id).query;
}
function createVirtualPlugin(name, load) {
name = "virtual:" + name;
return {
name: `rsc:virtual-${name}`,
resolveId: { handler(source, _importer, _options) {
return source === name ? "\0" + name : void 0;
} },
load: { handler(id, options) {
if (id === "\0" + name) return load.apply(this, [id, options]);
} }
};
}
function normalizeRelativePath(s) {
s = normalizePath(s);
return s[0] === "." ? s : "./" + s;
}
function hashString(v) {
return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
}
const VALID_ID_PREFIX = `/@id/`;
const NULL_BYTE_PLACEHOLDER = `__x00__`;
const FS_PREFIX = `/@fs/`;
function wrapId(id) {
return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
}
function withTrailingSlash(path$1) {
if (path$1[path$1.length - 1] !== "/") return `${path$1}/`;
return path$1;
}
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path$1) {
const file = cleanUrl(path$1);
return {
file,
postfix: path$1.slice(file.length)
};
}
const windowsSlashRE = /\\/g;
function slash(p) {
return p.replace(windowsSlashRE, "/");
}
const isWindows = typeof process !== "undefined" && process.platform === "win32";
function injectQuery(url, queryToInject) {
const { file, postfix } = splitFileAndPostfix(url);
return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
}
function normalizeResolvedIdToUrl(environment, url, resolved) {
const root = environment.config.root;
const depsOptimizer = environment.depsOptimizer;
if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length);
else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id);
else url = resolved.id;
if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id);
return url;
}
function normalizeViteImportAnalysisUrl(environment, id) {
let url = normalizeResolvedIdToUrl(environment, id, { id });
if (environment.config.consumer === "client") {
const mod = environment.moduleGraph.getModuleById(id);
if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
}
return url;
}
function evalValue(rawValue) {
return new Function(`
var console, exports, global, module, process, require
return (\n${rawValue}\n)
`)();
}
const directRequestRE = /(\?|&)direct=?(?:&|$)/;
function assetsPlugin(pluginOpts) {
let server;
let resolvedConfig;
const importAssetsMetaMap = {};
const bundleMap = {};
async function processAssetsImport(ctx, id, options) {
if (ctx.environment.mode === "dev") {
const result = {
entry: void 0,
js: [],
css: []
};
const environment = server.environments[options.environment];
assert$1(environment, `Unknown environment: ${options.environment}`);
if (options.environment === "client") result.entry = normalizeViteImportAnalysisUrl(environment, id);
if (environment.name !== "client") {
const collected = await collectCss(environment, id, { eager: pluginOpts?.experimental?.devEagerTransform ?? true });
result.css = collected.hrefs.map((href, i) => ({
href,
"data-vite-dev-id": collected.ids[i]
}));
}
return JSON.stringify(result);
} else {
const map = importAssetsMetaMap[options.environment] ??= {};
const meta = {
id,
key: path.relative(resolvedConfig.root, id),
importerEnvironment: ctx.environment.name,
isEntry: !!(map[id]?.isEntry || options.isEntry)
};
map[id] = meta;
return `__assets_manifest[${JSON.stringify(options.environment)}][${JSON.stringify(meta.key)}]`;
}
}
let writeAssetsManifestCalled = false;
async function writeAssetsManifest(builder) {
if (writeAssetsManifestCalled) return;
writeAssetsManifestCalled = true;
const manifest = {};
for (const [environmentName, metas] of Object.entries(importAssetsMetaMap)) {
const bundle = bundleMap[environmentName];
const assetDepsMap = collectAssetDeps(bundle);
for (const [id, meta] of Object.entries(metas)) {
const found = assetDepsMap[id];
if (!found) {
builder.config.logger.error(`[vite-plugin-fullstack] failed to find built chunk for ${meta.id} imported by ${meta.importerEnvironment} environment`);
return;
}
const result = {
js: [],
css: []
};
const { chunk, deps } = found;
if (environmentName === "client") {
result.entry = `/${chunk.fileName}`;
result.js = deps.js.map((fileName) => ({ href: `/${fileName}` }));
}
result.css = deps.css.map((fileName) => ({ href: `/${fileName}` }));
if (!builder.environments[environmentName].config.build.cssCodeSplit) {
const singleCss = Object.values(bundle).find((v) => v.type === "asset" && v.originalFileNames.includes("style.css"));
if (singleCss) result.css.push({ href: `/${singleCss.fileName}` });
}
(manifest[environmentName] ??= {})[meta.key] = result;
}
}
const importerEnvironments = new Set(Object.values(importAssetsMetaMap).flatMap((metas) => Object.values(metas)).flatMap((meta) => meta.importerEnvironment));
for (const environmentName of importerEnvironments) {
const outDir = builder.environments[environmentName].config.build.outDir;
fs.writeFileSync(path.join(outDir, BUILD_ASSETS_MANIFEST_NAME), `export default ${JSON.stringify(manifest, null, 2)};`);
const clientOutDir = builder.environments["client"].config.build.outDir;
for (const asset of Object.values(bundleMap[environmentName])) if (asset.type === "asset") {
const srcFile = path.join(outDir, asset.fileName);
const destFile = path.join(clientOutDir, asset.fileName);
fs.mkdirSync(path.dirname(destFile), { recursive: true });
fs.copyFileSync(srcFile, destFile);
}
}
}
return [
{
name: "fullstack:assets",
sharedDuringBuild: true,
configureServer(server_) {
server = server_;
},
configResolved(config) {
resolvedConfig = config;
},
configEnvironment(name) {
if ((pluginOpts?.serverEnvironments ?? ["ssr"]).includes(name)) return { build: { emitAssets: true } };
},
transform: { async handler(code, id, _options) {
if (!code.includes("import.meta.vite.assets")) return;
const output = new MagicString(code);
const strippedCode = stripLiteral(code);
const newImports = /* @__PURE__ */ new Set();
for (const match of code.matchAll(/import\.meta\.vite\.assets\(([\s\S]*?)\)/dg)) {
const [start, end] = match.indices[0];
if (!strippedCode.slice(start, end).includes("import.meta.vite.assets")) continue;
if (this.environment.name === "client") {
const replacement$1 = `(${JSON.stringify(EMPTY_ASSETS)})`;
output.update(start, end, replacement$1);
continue;
}
const argCode = match[1].trim();
const options = {
import: id,
environment: void 0,
asEntry: false
};
if (argCode) {
const argValue = evalValue(argCode);
Object.assign(options, argValue);
}
const environments = options.environment ? [options.environment] : ["client", this.environment.name];
const importedNames = [];
for (const environment of environments) {
const importSource = toAssetsVirtual({
import: options.import,
importer: id,
environment,
entry: options.asEntry ? "1" : ""
});
const importedName = `__assets_${hashString(importSource)}`;
newImports.add(`;import ${importedName} from ${JSON.stringify(importSource)};\n`);
importedNames.push(importedName);
}
let replacement = importedNames[0];
if (importedNames.length > 1) {
newImports.add(`;import * as __assets_runtime from "virtual:fullstack/runtime";\n`);
replacement = `__assets_runtime.mergeAssets(${importedNames.join(", ")})`;
}
output.update(start, end, `(${replacement})`);
}
if (output.hasChanged()) {
for (const newImport of newImports) output.append(newImport);
return {
code: output.toString(),
map: output.generateMap({ hires: "boundary" })
};
}
} },
resolveId: { handler(source) {
if (source.startsWith("virtual:fullstack/assets?")) return "\0" + source;
if (source === "virtual:fullstack/assets-manifest") {
assert$1.notEqual(this.environment.name, "client");
assert$1.equal(this.environment.mode, "build");
return {
id: source,
external: true
};
}
if (source === "virtual:fullstack/runtime") return { id: source };
} },
load: { async handler(id) {
if (id === "virtual:fullstack/runtime") return runtimeUtils();
const parsed = parseAssetsVirtual(id);
if (!parsed) return;
assert$1.notEqual(this.environment.name, "client");
const resolved = await this.resolve(parsed.import, parsed.importer);
assert$1(resolved, `Failed to resolve: ${parsed.import}`);
const s = new MagicString("");
const code = await processAssetsImport(this, resolved.id, {
environment: parsed.environment,
isEntry: !!parsed.entry
});
s.append(`export default ${code};\n`);
if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`);
return s.toString();
} },
renderChunk(code, chunk) {
if (code.includes("virtual:fullstack/assets-manifest")) {
const replacement = normalizeRelativePath(path.relative(path.join(chunk.fileName, ".."), BUILD_ASSETS_MANIFEST_NAME));
code = code.replaceAll("virtual:fullstack/assets-manifest", () => replacement);
return { code };
}
},
writeBundle(_options, bundle) {
bundleMap[this.environment.name] = bundle;
},
buildStart() {
if (this.environment.mode == "build" && this.environment.name === "client") {
if (importAssetsMetaMap["client"]) {
for (const meta of Object.values(importAssetsMetaMap["client"])) if (meta.isEntry) this.emitFile({
type: "chunk",
id: meta.id,
preserveSignature: "exports-only"
});
}
}
},
buildApp: {
order: "pre",
async handler(builder) {
builder.writeAssetsManifest = async () => {
await writeAssetsManifest(builder);
};
}
}
},
{
name: "fullstack:write-assets-manifest-post",
buildApp: {
order: "post",
async handler(builder) {
await builder.writeAssetsManifest();
}
}
},
{
name: "fullstack:assets-query",
sharedDuringBuild: true,
resolveId: {
order: "pre",
handler(source) {
const { query } = parseIdQuery(source);
if (typeof query["assets"] !== "undefined") {
if (this.environment.name === "client") return `\0virtual:fullstack/empty-assets`;
}
if (source === "virtual:fullstack/runtime") return source;
}
},
load: { async handler(id) {
if (id === "\0virtual:fullstack/empty-assets") return `export default ${JSON.stringify(EMPTY_ASSETS)}`;
if (id === "virtual:fullstack/runtime") return runtimeUtils();
const { filename, query } = parseIdQuery(id);
const value = query["assets"];
if (typeof value !== "undefined") {
const s = new MagicString("");
const codes = [];
if (value) {
const code = await processAssetsImport(this, filename, {
environment: value,
isEntry: value === "client"
});
codes.push(code);
} else {
const code1 = await processAssetsImport(this, filename, {
environment: "client",
isEntry: false
});
const code2 = await processAssetsImport(this, filename, {
environment: this.environment.name,
isEntry: false
});
codes.push(code1, code2);
}
s.append(`
import * as __assets_runtime from "virtual:fullstack/runtime";\n
export default __assets_runtime.mergeAssets(${codes.join(", ")});
`);
if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`);
return {
code: s.toString(),
moduleSideEffects: false
};
}
} },
hotUpdate(ctx) {
if (this.environment.name === "rsc") {
const mods = collectModuleDependents(ctx.modules);
for (const mod of mods) if (mod.id) {
const ids = [
`${mod.id}?assets`,
`${mod.id}?assets=client`,
`${mod.id}?assets=${this.environment.name}`
];
for (const id of ids) invalidteModuleById(this.environment, id);
}
}
}
},
{
...createVirtualPlugin("fullstack/client-fallback", () => "export {}"),
configEnvironment: {
order: "post",
handler(name, config, _env) {
if (name === "client") {
if ((pluginOpts?.experimental?.clientBuildFallback ?? true) && !config.build?.rollupOptions?.input) return { build: { rollupOptions: { input: { __fallback: "virtual:fullstack/client-fallback" } } } };
}
}
},
generateBundle(_optoins, bundle) {
if (this.environment.name !== "client") return;
for (const [k, v] of Object.entries(bundle)) if (v.type === "chunk" && v.name === "__fallback") delete bundle[k];
}
},
patchViteClientPlugin(),
patchVueScopeCssHmr(),
patchCssLinkSelfAccept()
];
}
const EMPTY_ASSETS = {
js: [],
css: []
};
const BUILD_ASSETS_MANIFEST_NAME = "__fullstack_assets_manifest.js";
async function collectCss(environment, entryId, options) {
const visited = /* @__PURE__ */ new Set();
const cssIds = /* @__PURE__ */ new Set();
async function recurse(id) {
if (visited.has(id) || parseAssetsVirtual(id) || "assets" in parseIdQuery(id).query) return;
visited.add(id);
const mod = environment.moduleGraph.getModuleById(id);
if (!mod) return;
if (options.eager && !mod?.transformResult) try {
await environment.transformRequest(id);
} catch (e) {
console.error(`[collectCss] Failed to transform '${id}'`, e);
}
for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) {
if (hasSpecialCssQuery(next.id)) continue;
cssIds.add(next.id);
} else await recurse(next.id);
}
await recurse(entryId);
const hrefs = [...cssIds].map((id) => normalizeViteImportAnalysisUrl(environment, id));
return {
ids: [...cssIds],
hrefs
};
}
function invalidteModuleById(environment, id) {
const mod = environment.moduleGraph.getModuleById(id);
if (mod) environment.moduleGraph.invalidateModule(mod);
return mod;
}
function collectModuleDependents(mods) {
const visited = /* @__PURE__ */ new Set();
function recurse(mod) {
if (visited.has(mod)) return;
visited.add(mod);
for (const importer of mod.importers) recurse(importer);
}
for (const mod of mods) recurse(mod);
return [...visited];
}
function hasSpecialCssQuery(id) {
return /[?&](url|inline|raw)(\b|=|&|$)/.test(id);
}
function collectAssetDeps(bundle) {
const chunkToDeps = /* @__PURE__ */ new Map();
for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunkToDeps.set(chunk, collectAssetDepsInner(chunk.fileName, bundle));
const idToDeps = {};
for (const [chunk, deps] of chunkToDeps.entries()) for (const id of chunk.moduleIds) idToDeps[id] = {
chunk,
deps
};
return idToDeps;
}
function collectAssetDepsInner(fileName, bundle) {
const visited = /* @__PURE__ */ new Set();
const css = [];
function recurse(k) {
if (visited.has(k)) return;
visited.add(k);
const v = bundle[k];
assert$1(v, `Not found '${k}' in the bundle`);
if (v.type === "chunk") {
css.push(...v.viteMetadata?.importedCss ?? []);
for (const k2 of v.imports) if (k2 in bundle) recurse(k2);
}
}
recurse(fileName);
return {
js: [...visited],
css: [...new Set(css)]
};
}
function patchViteClientPlugin() {
const viteClientPath = normalizePath(fileURLToPath(import.meta.resolve("vite/dist/client/client.mjs")));
function endIndexOf(code, searchValue) {
const i = code.lastIndexOf(searchValue);
return i === -1 ? i : i + searchValue.length;
}
return {
name: "fullstack:patch-vite-client",
transform: { handler(code, id) {
if (id === viteClientPath) {
if (code.includes("linkSheetsMap")) return;
const s = new MagicString(code);
s.prependLeft(code.indexOf("const sheetsMap"), `\
const linkSheetsMap = new Map();
document
.querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]')
.forEach((el) => {
linkSheetsMap.set(el.getAttribute('data-vite-dev-id'), el)
});
`);
s.appendLeft(endIndexOf(code, `function updateStyle(id, content) {`), `if (linkSheetsMap.has(id)) { return }`);
s.appendLeft(endIndexOf(code, `function removeStyle(id) {`), `
const link = linkSheetsMap.get(id);
if (link) {
document
.querySelectorAll(
'link[rel="stylesheet"][data-vite-dev-id]',
)
.forEach((el) => {
if (el.getAttribute('data-vite-dev-id') === id) {
el.remove()
}
})
linkSheetsMap.delete(id)
}
`);
return s.toString();
}
} }
};
}
function patchVueScopeCssHmr() {
return {
name: "fullstack:patch-vue-scoped-css-hmr",
configureServer(server) {
server.middlewares.use((req, _res, next) => {
if (req.headers.accept?.includes("text/css") && req.url?.includes("&lang.css=")) req.url = req.url.replace("&lang.css=", "?lang.css");
next();
});
}
};
}
function patchCssLinkSelfAccept() {
return {
name: "fullstack:patch-css-link-self-accept",
apply: "serve",
transform: {
order: "post",
handler(_code, id, _options) {
if (this.environment.name === "client" && this.environment.mode === "dev" && isCSSRequest(id) && directRequestRE.test(id)) {
const mod = this.environment.moduleGraph.getModuleById(id);
if (mod && !mod.isSelfAccepting) mod.isSelfAccepting = true;
}
}
}
};
}
function runtimeUtils() {
return `
export function mergeAssets(...args) {
const js = uniqBy(args.flatMap((h) => h.js), (a) => a.href);
const css = uniqBy(args.flatMap((h) => h.css), (a) => a.href);
const entry = args.filter((arg) => arg.entry)?.[0]?.entry;
const raw = { entry, js, css };
return { ...raw, merge: (...args$1) => mergeAssets(raw, ...args$1) };
}
function uniqBy(array, key) {
const seen = new Set();
return array.filter((item) => {
const k = key(item);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}`;
}
//#endregion
export { assetsPlugin as t };
import { O as relative$1, _ as h, c as findNearestFile, d as readGitConfig, f as readPackageJSON, h as resolveModulePath, k as resolve$1, s as findFile, w as join$1, x as dirname$1 } from "./_libs/c12.mjs";
import "./_libs/acorn.mjs";
import { n as gr, t as Q } from "./_libs/confbox.mjs";
import { r as fileURLToPath } from "./_libs/local-pkg.mjs";
import "./_libs/picomatch.mjs";
import "./_libs/fdir.mjs";
import { t as glob } from "./_libs/tinyglobby.mjs";
import { r as resolveCompatibilityDatesFromEnv, t as formatCompatibilityDate } from "./_libs/compatx.mjs";
import { a as p, r as a, t as K } from "./_libs/std-env.mjs";
import "./_libs/dot-prop.mjs";
import { i as writeFile$2 } from "./_chunks/C7CbzoI1.mjs";
import consola$1 from "consola";
import { dirname, extname, relative, resolve } from "node:path";
import { kebabCase } from "scule";
import { existsSync, promises } from "node:fs";
import { hasProtocol, joinURL, withLeadingSlash, withTrailingSlash, withoutLeadingSlash } from "ufo";
import fsp, { readFile, writeFile } from "node:fs/promises";
import { defu } from "defu";
import { presetsDir, runtimeDir, version } from "nitro/meta";
import { colors } from "consola/utils";
//#region src/presets/_utils/preset.ts
function defineNitroPreset(preset, meta) {
if (typeof preset !== "function" && preset.entry && preset.entry.startsWith(".")) preset.entry = resolve(presetsDir, preset.entry);
return {
...preset,
_meta: meta
};
}
//#endregion
//#region src/presets/_nitro/base-worker.ts
const baseWorker = defineNitroPreset({
entry: null,
node: false,
minify: true,
noExternals: true,
rollupConfig: { output: {
format: "iife",
generatedCode: { symbols: true }
} },
inlineDynamicImports: true
}, { name: "base-worker" });
var base_worker_default = [baseWorker];
//#endregion
//#region src/presets/_nitro/nitro-dev.ts
const nitroDev = defineNitroPreset({
entry: "./_nitro/runtime/nitro-dev",
output: {
dir: "{{ buildDir }}/dev",
serverDir: "{{ buildDir }}/dev",
publicDir: "{{ buildDir }}/dev"
},
handlers: [{
route: "/_nitro/tasks/**",
lazy: true,
handler: join$1(runtimeDir, "internal/routes/dev-tasks")
}],
externals: { noTrace: true },
serveStatic: true,
inlineDynamicImports: true,
sourcemap: true
}, {
name: "nitro-dev",
dev: true
});
var nitro_dev_default = [nitroDev];
//#endregion
//#region src/presets/_nitro/nitro-prerender.ts
const nitroPrerender = defineNitroPreset({
entry: "./_nitro/runtime/nitro-prerenderer",
serveStatic: true,
output: { serverDir: "{{ buildDir }}/prerender" },
externals: { noTrace: true }
}, { name: "nitro-prerender" });
var nitro_prerender_default = [nitroPrerender];
//#endregion
//#region src/presets/_nitro/preset.ts
var preset_default = [
...base_worker_default,
...nitro_dev_default,
...nitro_prerender_default
];
//#endregion
//#region src/presets/_static/preset.ts
const _static = defineNitroPreset({
static: true,
output: {
dir: "{{ rootDir }}/.output",
publicDir: "{{ output.dir }}/public"
},
prerender: { crawlLinks: true },
commands: { preview: "npx serve ./public" }
}, {
name: "static",
static: true
});
const githubPages = defineNitroPreset({
extends: "static",
commands: { deploy: "npx gh-pages --dotfiles -d ./public" },
prerender: { routes: ["/", "/404.html"] },
hooks: { async compiled(nitro) {
await fsp.writeFile(join$1(nitro.options.output.publicDir, ".nojekyll"), "");
} }
}, {
name: "github-pages",
static: true
});
const gitlabPages = defineNitroPreset({
extends: "static",
prerender: { routes: ["/", "/404.html"] }
}, {
name: "gitlab-pages",
static: true
});
var preset_default$1 = [
_static,
githubPages,
gitlabPages
];
//#endregion
//#region src/presets/alwaysdata/preset.ts
const alwaysdata = defineNitroPreset({
extends: "node-server",
serveStatic: true,
commands: { deploy: "rsync -rRt --info=progress2 ./ [account]@ssh-[account].alwaysdata.net:www/my-app" }
}, { name: "alwaysdata" });
var preset_default$2 = [alwaysdata];
//#endregion
//#region src/presets/aws-amplify/utils.ts
async function writeAmplifyFiles(nitro) {
const outDir = nitro.options.output.dir;
const routes = [];
let hasWildcardPublicAsset = false;
if (nitro.options.awsAmplify?.imageOptimization && !nitro.options.static) {
const { path: path$1, cacheControl } = nitro.options.awsAmplify?.imageOptimization || {};
if (path$1) routes.push({
path: path$1,
target: {
kind: "ImageOptimization",
cacheControl
}
});
}
const computeTarget = nitro.options.static ? { kind: "Static" } : {
kind: "Compute",
src: "default"
};
for (const publicAsset of nitro.options.publicAssets) {
if (!publicAsset.baseURL || publicAsset.baseURL === "/") {
hasWildcardPublicAsset = true;
continue;
}
routes.push({
path: `${publicAsset.baseURL.replace(/\/$/, "")}/*`,
target: {
kind: "Static",
cacheControl: publicAsset.maxAge > 0 ? `public, max-age=${publicAsset.maxAge}, immutable` : void 0
},
fallback: publicAsset.fallthrough ? computeTarget : void 0
});
}
if (hasWildcardPublicAsset && !nitro.options.static) routes.push({
path: "/*.*",
target: { kind: "Static" },
fallback: computeTarget
});
routes.push({
path: "/*",
target: computeTarget,
fallback: hasWildcardPublicAsset && nitro.options.awsAmplify?.catchAllStaticFallback ? { kind: "Static" } : void 0
});
for (const route of routes) if (route.path !== "/*") route.path = joinURL(nitro.options.baseURL, route.path);
const deployManifest = {
version: 1,
routes,
imageSettings: nitro.options.awsAmplify?.imageSettings || void 0,
computeResources: nitro.options.static ? void 0 : [{
name: "default",
entrypoint: "server.js",
runtime: nitro.options.awsAmplify?.runtime || "nodejs20.x"
}],
framework: {
name: nitro.options.framework.name || "nitro",
version: nitro.options.framework.version || "0.0.0"
}
};
await writeFile(resolve(outDir, "deploy-manifest.json"), JSON.stringify(deployManifest, null, 2));
if (!nitro.options.static) await writeFile(resolve(outDir, "compute/default/server.js"), `import("./index.mjs")`);
}
//#endregion
//#region src/presets/aws-amplify/preset.ts
const awsAmplify = defineNitroPreset({
entry: "./aws-amplify/runtime/aws-amplify",
serveStatic: true,
output: {
dir: "{{ rootDir }}/.amplify-hosting",
serverDir: "{{ output.dir }}/compute/default",
publicDir: "{{ output.dir }}/static{{ baseURL }}"
},
commands: { preview: "node ./compute/default/server.js" },
hooks: { async compiled(nitro) {
await writeAmplifyFiles(nitro);
} }
}, {
name: "aws-amplify",
stdName: "aws_amplify"
});
var preset_default$3 = [awsAmplify];
//#endregion
//#region src/presets/aws-lambda/preset.ts
const awsLambda = defineNitroPreset({
entry: "./aws-lambda/runtime/aws-lambda",
awsLambda: { streaming: false },
hooks: { "rollup:before": (nitro, rollupConfig) => {
if (nitro.options.awsLambda?.streaming) rollupConfig.input += "-streaming";
} }
}, { name: "aws-lambda" });
var preset_default$4 = [awsLambda];
//#endregion
//#region src/presets/_utils/fs.ts
function prettyPath(p$1, highlight = true) {
p$1 = relative$1(process.cwd(), p$1);
return highlight ? colors.cyan(p$1) : p$1;
}
async function writeFile$1(file, contents, log = false) {
await fsp.mkdir(dirname$1(file), { recursive: true });
await fsp.writeFile(file, contents, typeof contents === "string" ? "utf8" : void 0);
if (log) consola$1.info("Generated", prettyPath(file));
}
//#endregion
//#region src/presets/azure/utils.ts
async function writeSWARoutes(nitro) {
const host = { version: "2.0" };
const supportedNodeVersions = new Set(["20", "22"]);
let nodeVersion = "18";
try {
const currentNodeVersion = JSON.parse(await fsp.readFile(join$1(nitro.options.rootDir, "package.json"), "utf8")).engines.node;
if (supportedNodeVersions.has(currentNodeVersion)) nodeVersion = currentNodeVersion;
} catch {
const currentNodeVersion = process.versions.node.slice(0, 2);
if (supportedNodeVersions.has(currentNodeVersion)) nodeVersion = currentNodeVersion;
}
const config = {
...nitro.options.azure?.config,
routes: [],
platform: {
apiRuntime: `node:${nodeVersion}`,
...nitro.options.azure?.config?.platform
},
navigationFallback: {
rewrite: "/api/server",
...nitro.options.azure?.config?.navigationFallback
}
};
const routeFiles = nitro._prerenderedRoutes || [];
const indexFileExists = routeFiles.some((route) => route.fileName === "/index.html");
if (!indexFileExists) config.routes.unshift({
route: "/index.html",
redirect: "/"
}, {
route: "/",
rewrite: "/api/server"
});
const suffix = 11;
for (const { fileName } of routeFiles) {
if (!fileName || !fileName.endsWith("/index.html")) continue;
config.routes.unshift({
route: fileName.slice(0, -suffix) || "/",
rewrite: fileName
});
}
for (const { fileName } of routeFiles) {
if (!fileName || !fileName.endsWith(".html") || fileName.endsWith("index.html")) continue;
const route = fileName.slice(0, -5);
const existingRouteIndex = config.routes.findIndex((_route) => _route.route === route);
if (existingRouteIndex !== -1) config.routes.splice(existingRouteIndex, 1);
config.routes.unshift({
route,
rewrite: fileName
});
}
if (nitro.options.azure?.config && "routes" in nitro.options.azure.config && Array.isArray(nitro.options.azure.config.routes)) for (const customRoute of nitro.options.azure.config.routes.reverse()) {
const existingRouteMatchIndex = config.routes.findIndex((value) => value.route === customRoute.route);
if (existingRouteMatchIndex === -1) config.routes.unshift(customRoute);
else config.routes[existingRouteMatchIndex] = customRoute;
}
await writeFile$1(resolve$1(nitro.options.output.serverDir, "function.json"), JSON.stringify({
entryPoint: "handle",
bindings: [{
authLevel: "anonymous",
type: "httpTrigger",
direction: "in",
name: "req",
route: "{*url}",
methods: [
"delete",
"get",
"head",
"options",
"patch",
"post",
"put"
]
}, {
type: "http",
direction: "out",
name: "res"
}]
}, null, 2));
await writeFile$1(resolve$1(nitro.options.output.serverDir, "../host.json"), JSON.stringify(host, null, 2));
await writeFile$1(resolve$1(nitro.options.output.serverDir, "../package.json"), JSON.stringify({ private: true }));
await writeFile$1(resolve$1(nitro.options.rootDir, "staticwebapp.config.json"), JSON.stringify(config, null, 2));
if (!indexFileExists) {
const relativePrefix = nitro.options.baseURL.split("/").filter(Boolean).map(() => "..").join("/");
await writeFile$1(resolve$1(nitro.options.output.publicDir, relativePrefix ? `${relativePrefix}/index.html` : "index.html"), "");
}
}
//#endregion
//#region src/presets/azure/preset.ts
const azureSWA = defineNitroPreset({
entry: "./azure/runtime/azure-swa",
output: {
serverDir: "{{ output.dir }}/server/functions",
publicDir: "{{ output.dir }}/public/{{ baseURL }}"
},
commands: { preview: "npx @azure/static-web-apps-cli start ./public --api-location ./server" },
hooks: { async compiled(ctx) {
await writeSWARoutes(ctx);
} }
}, {
name: "azure-swa",
stdName: "azure_static"
});
var preset_default$5 = [azureSWA];
//#endregion
//#region src/presets/bun/preset.ts
const bun = defineNitroPreset({
entry: "./bun/runtime/bun",
serveStatic: true,
exportConditions: [
"bun",
"node",
"import",
"default"
],
commands: { preview: "bun run ./server/index.mjs" }
}, { name: "bun" });
var preset_default$6 = [bun];
//#endregion
//#region src/presets/cleavr/preset.ts
const cleavr = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, {
name: "cleavr",
stdName: "cleavr"
});
var preset_default$7 = [cleavr];
//#endregion
//#region src/presets/cloudflare/unenv/node-compat.ts
const builtnNodeModules$1 = [
"node:_http_agent",
"node:_http_client",
"node:_http_common",
"node:_http_incoming",
"node:_http_outgoing",
"node:_http_server",
"node:_stream_duplex",
"node:_stream_passthrough",
"node:_stream_readable",
"node:_stream_transform",
"node:_stream_writable",
"node:_tls_common",
"node:_tls_wrap",
"node:assert",
"node:assert/strict",
"node:async_hooks",
"node:buffer",
"node:constants",
"node:crypto",
"node:diagnostics_channel",
"node:dns",
"node:dns/promises",
"node:events",
"node:fs",
"node:fs/promises",
"node:http",
"node:http2",
"node:https",
"node:module",
"node:net",
"node:os",
"node:path",
"node:path/posix",
"node:path/win32",
"node:process",
"node:querystring",
"node:stream",
"node:stream/consumers",
"node:stream/promises",
"node:stream/web",
"node:string_decoder",
"node:test",
"node:timers",
"node:timers/promises",
"node:tls",
"node:url",
"node:util",
"node:util/types",
"node:zlib"
];
//#endregion
//#region src/presets/cloudflare/unenv/preset.ts
const unencCfNodeCompat = {
meta: { name: "nitro:cloudflare-node-compat" },
external: builtnNodeModules$1,
alias: { ...Object.fromEntries(builtnNodeModules$1.flatMap((m) => [[m, m], [m.replace("node:", ""), m]])) },
inject: {
global: "unenv/polyfill/globalthis",
process: "node:process",
clearImmediate: ["node:timers", "clearImmediate"],
setImmediate: ["node:timers", "setImmediate"],
Buffer: ["node:buffer", "Buffer"]
}
};
const unenvCfExternals = {
meta: { name: "nitro:cloudflare-externals" },
external: [
"cloudflare:email",
"cloudflare:sockets",
"cloudflare:workers",
"cloudflare:workflows"
]
};
//#endregion
//#region src/presets/cloudflare/utils.ts
async function writeCFRoutes(nitro) {
const _cfPagesConfig = nitro.options.cloudflare?.pages || {};
const routes = {
version: _cfPagesConfig.routes?.version || 1,
include: _cfPagesConfig.routes?.include || ["/*"],
exclude: _cfPagesConfig.routes?.exclude || []
};
const writeRoutes = () => writeFile$1(resolve$1(nitro.options.output.dir, "_routes.json"), JSON.stringify(routes, void 0, 2), true);
if (_cfPagesConfig.defaultRoutes === false) {
await writeRoutes();
return;
}
const explicitPublicAssets = nitro.options.publicAssets.filter((dir, index, array) => {
if (dir.fallthrough || !dir.baseURL) return false;
const normalizedBase = withoutLeadingSlash(dir.baseURL);
return !array.some((otherDir, otherIndex) => otherIndex !== index && normalizedBase.startsWith(withoutLeadingSlash(withTrailingSlash(otherDir.baseURL))));
});
routes.exclude.push(...explicitPublicAssets.map((asset) => joinURL(nitro.options.baseURL, asset.baseURL || "/", "*")).sort(comparePaths));
const publicAssetFiles = await glob("**", {
cwd: nitro.options.output.dir,
absolute: false,
dot: true,
ignore: [
"_worker.js",
"_worker.js.map",
"nitro.json",
...routes.exclude.map((path$1) => withoutLeadingSlash(path$1.replace(/\/\*$/, "/**")))
]
});
routes.exclude.push(...publicAssetFiles.map((i) => withLeadingSlash(i).replace(/\/index\.html$/, "").replace(/\.html$/, "") || "/").sort(comparePaths));
routes.exclude.splice(100 - routes.include.length);
await writeRoutes();
}
function comparePaths(a$1, b) {
return a$1.split("/").length - b.split("/").length || a$1.localeCompare(b);
}
async function writeCFHeaders(nitro, outdir) {
const headersPath = join$1(outdir === "public" ? nitro.options.output.publicDir : nitro.options.output.dir, "_headers");
const contents = [];
const rules = Object.entries(nitro.options.routeRules).sort((a$1, b) => b[0].split(/\/(?!\*)/).length - a$1[0].split(/\/(?!\*)/).length);
for (const [path$1, routeRules] of rules.filter(([_, routeRules$1]) => routeRules$1.headers)) {
const headers = [joinURL(nitro.options.baseURL, path$1.replace("/**", "/*")), ...Object.entries({ ...routeRules.headers }).map(([header, value]) => ` ${header}: ${value}`)].join("\n");
contents.push(headers);
}
if (existsSync(headersPath)) {
const currentHeaders = await readFile(headersPath, "utf8");
if (/^\/\* /m.test(currentHeaders)) {
nitro.logger.info("Not adding Nitro fallback to `_headers` (as an existing fallback was found).");
return;
}
nitro.logger.info("Adding Nitro fallback to `_headers` to handle all unmatched routes.");
contents.unshift(currentHeaders);
}
await writeFile$1(headersPath, contents.join("\n"), true);
}
async function writeCFPagesRedirects(nitro) {
const redirectsPath = join$1(nitro.options.output.dir, "_redirects");
const contents = [existsSync(join$1(nitro.options.output.publicDir, "404.html")) ? `${joinURL(nitro.options.baseURL, "/*")} ${joinURL(nitro.options.baseURL, "/404.html")} 404` : ""];
const rules = Object.entries(nitro.options.routeRules).sort((a$1, b) => a$1[0].split(/\/(?!\*)/).length - b[0].split(/\/(?!\*)/).length);
for (const [key, routeRules] of rules.filter(([_, routeRules$1]) => routeRules$1.redirect)) {
const code = routeRules.redirect.status;
const from = joinURL(nitro.options.baseURL, key.replace("/**", "/*"));
const to = hasProtocol(routeRules.redirect.to, { acceptRelative: true }) ? routeRules.redirect.to : joinURL(nitro.options.baseURL, routeRules.redirect.to);
contents.unshift(`${from}\t${to}\t${code}`);
}
if (existsSync(redirectsPath)) {
const currentRedirects = await readFile(redirectsPath, "utf8");
if (/^\/\* /m.test(currentRedirects)) {
nitro.logger.info("Not adding Nitro fallback to `_redirects` (as an existing fallback was found).");
return;
}
nitro.logger.info("Adding Nitro fallback to `_redirects` to handle all unmatched routes.");
contents.unshift(currentRedirects);
}
await writeFile$1(redirectsPath, contents.join("\n"), true);
}
async function enableNodeCompat(nitro) {
nitro.options.cloudflare ??= {};
nitro.options.cloudflare.deployConfig ??= true;
nitro.options.cloudflare.nodeCompat ??= true;
if (nitro.options.cloudflare.nodeCompat) nitro.options.unenv.push(unencCfNodeCompat);
}
const extensionParsers = {
".json": h,
".jsonc": h,
".toml": Q
};
async function readWranglerConfig(nitro) {
const configPath = await findNearestFile([
"wrangler.json",
"wrangler.jsonc",
"wrangler.toml"
], { startingFrom: nitro.options.rootDir }).catch(() => void 0);
if (!configPath) return {};
const userConfigText = await readFile(configPath, "utf8");
const parser = extensionParsers[extname(configPath)];
if (!parser) throw new Error(`Unsupported config file format: ${configPath}`);
return {
configPath,
config: parser(userConfigText)
};
}
async function writeWranglerConfig(nitro, cfTarget) {
if (!nitro.options.cloudflare?.deployConfig) return;
const wranglerConfigDir = nitro.options.output.serverDir;
const wranglerConfigPath = join$1(wranglerConfigDir, "wrangler.json");
const defaults = {};
const overrides = {};
defaults.compatibility_date = nitro.options.compatibilityDate.cloudflare || nitro.options.compatibilityDate.default;
if (cfTarget === "pages") overrides.pages_build_output_dir = relative(wranglerConfigDir, nitro.options.output.dir);
else {
overrides.main = relative(wranglerConfigDir, join$1(nitro.options.output.serverDir, "index.mjs"));
overrides.assets = {
binding: "ASSETS",
directory: relative(wranglerConfigDir, resolve$1(nitro.options.output.publicDir, "..".repeat(nitro.options.baseURL.split("/").filter(Boolean).length)))
};
}
const { config: userConfig = {} } = await readWranglerConfig(nitro);
const ctxConfig = nitro.options.cloudflare?.wrangler || {};
for (const key in overrides) if (key in userConfig || key in ctxConfig) nitro.logger.warn(`[cloudflare] Wrangler config \`${key}\`${key in ctxConfig ? "set by config or modules" : ""} is overridden and will be ignored.`);
const wranglerConfig = defu(overrides, ctxConfig, userConfig, defaults);
if (!wranglerConfig.name) {
wranglerConfig.name = await generateWorkerName(nitro);
nitro.logger.info(`Using auto generated worker name: \`${wranglerConfig.name}\``);
}
wranglerConfig.compatibility_flags ??= [];
if (nitro.options.cloudflare?.nodeCompat && !wranglerConfig.compatibility_flags.includes("nodejs_compat")) wranglerConfig.compatibility_flags.push("nodejs_compat");
if (cfTarget === "module") {
if (wranglerConfig.no_bundle === void 0) wranglerConfig.no_bundle = true;
wranglerConfig.rules ??= [];
if (!wranglerConfig.rules.some((rule) => rule.type === "ESModule")) wranglerConfig.rules.push({
type: "ESModule",
globs: ["**/*.mjs", "**/*.js"]
});
}
await writeFile$1(wranglerConfigPath, JSON.stringify(wranglerConfig, null, 2), true);
const configPath = join$1(nitro.options.rootDir, ".wrangler/deploy/config.json");
await writeFile$1(configPath, JSON.stringify({ configPath: relative(dirname(configPath), wranglerConfigPath) }), true);
}
async function generateWorkerName(nitro) {
const gitRepo = (await readGitConfig(nitro.options.rootDir).catch(() => void 0))?.remote?.origin?.url?.replace(/\.git$/, "").match(/[/:]([^/]+\/[^/]+)$/)?.[1];
const pkgName = (await readPackageJSON(nitro.options.rootDir).catch(() => void 0))?.name;
const subpath = relative(nitro.options.workspaceDir, nitro.options.rootDir);
return `${gitRepo || pkgName}/${subpath}`.toLowerCase().replace(/[^a-zA-Z0-9-]/g, "-").replace(/-$/, "");
}
//#endregion
//#region src/presets/cloudflare/dev.ts
async function cloudflareDevModule(nitro) {
if (!nitro.options.dev) return;
nitro.options.unenv.push({
meta: { name: "nitro:cloudflare-dev" },
alias: { "cloudflare:workers": resolve(presetsDir, "cloudflare/runtime/shims/workers.dev.mjs") }
});
if (!await resolveModulePath("wrangler", {
from: nitro.options.nodeModulesDirs,
try: true
})) {
nitro.logger.warn("Wrangler is not installed. Please install it using `npx nypm i wrangler` to enable dev emulation.");
return;
}
const config = {
...nitro.options.cloudflareDev,
...nitro.options.cloudflare?.dev
};
let configPath = config.configPath;
if (!configPath) configPath = await findFile([
"wrangler.json",
"wrangler.jsonc",
"wrangler.toml"
], { startingFrom: nitro.options.rootDir }).catch(() => void 0);
const persistDir = resolve(nitro.options.rootDir, config.persistDir || ".wrangler/state/v3");
const gitIgnorePath = await findFile(".gitignore", { startingFrom: nitro.options.rootDir }).catch(() => void 0);
if (gitIgnorePath && persistDir === ".wrangler/state/v3") {
const gitIgnore = await promises.readFile(gitIgnorePath, "utf8");
if (!gitIgnore.includes(".wrangler/state/v3")) await promises.writeFile(gitIgnorePath, gitIgnore + "\n.wrangler/state/v3\n").catch(() => {});
}
nitro.options.runtimeConfig.wrangler = {
...nitro.options.runtimeConfig.wrangler,
configPath,
persistDir,
environment: config.environment
};
nitro.options.externals.inline = nitro.options.externals.inline || [];
nitro.options.externals.inline.push(fileURLToPath(new URL("runtime/", import.meta.url)));
nitro.options.plugins = nitro.options.plugins || [];
nitro.options.plugins.unshift(resolveModulePath("./cloudflare/runtime/plugin.dev", {
from: presetsDir,
extensions: [".mjs", ".ts"]
}));
}
//#endregion
//#region src/presets/cloudflare/preset.ts
const cloudflarePages = defineNitroPreset({
extends: "base-worker",
entry: "./cloudflare/runtime/cloudflare-pages",
exportConditions: ["workerd"],
minify: false,
commands: {
preview: "npx wrangler --cwd ./ pages dev",
deploy: "npx wrangler --cwd ./ pages deploy"
},
output: {
dir: "{{ rootDir }}/dist",
publicDir: "{{ output.dir }}/{{ baseURL }}",
serverDir: "{{ output.dir }}/_worker.js"
},
alias: { _mime: "mime/index.js" },
wasm: {
lazy: false,
esmImport: true
},
rollupConfig: { output: {
entryFileNames: "index.js",
format: "esm",
inlineDynamicImports: false
} },
hooks: {
"build:before": async (nitro) => {
nitro.options.unenv.push(unenvCfExternals);
await enableNodeCompat(nitro);
},
async compiled(nitro) {
await writeWranglerConfig(nitro, "pages");
await writeCFRoutes(nitro);
await writeCFHeaders(nitro, "output");
await writeCFPagesRedirects(nitro);
}
}
}, {
name: "cloudflare-pages",
stdName: "cloudflare_pages"
});
const cloudflarePagesStatic = defineNitroPreset({
extends: "static",
output: {
dir: "{{ rootDir }}/dist",
publicDir: "{{ output.dir }}/{{ baseURL }}"
},
commands: {
preview: "npx wrangler --cwd ./ pages dev",
deploy: "npx wrangler --cwd ./ pages deploy"
},
hooks: { async compiled(nitro) {
await writeCFHeaders(nitro, "output");
await writeCFPagesRedirects(nitro);
} }
}, {
name: "cloudflare-pages-static",
stdName: "cloudflare_pages",
static: true
});
const cloudflareDev = defineNitroPreset({
extends: "nitro-dev",
modules: [cloudflareDevModule]
}, {
name: "cloudflare-dev",
aliases: [
"cloudflare-module",
"cloudflare-durable",
"cloudflare-pages"
],
compatibilityDate: "2025-07-13",
dev: true
});
const cloudflareModule = defineNitroPreset({
extends: "base-worker",
entry: "./cloudflare/runtime/cloudflare-module",
output: { publicDir: "{{ output.dir }}/public/{{ baseURL }}" },
exportConditions: ["workerd"],
minify: false,
commands: {
preview: "npx wrangler --cwd ./ dev",
deploy: "npx wrangler --cwd ./ deploy"
},
rollupConfig: { output: {
format: "esm",
exports: "named",
inlineDynamicImports: false
} },
wasm: {
lazy: false,
esmImport: true
},
hooks: {
"build:before": async (nitro) => {
nitro.options.unenv.push(unenvCfExternals);
await enableNodeCompat(nitro);
},
async compiled(nitro) {
await writeWranglerConfig(nitro, "module");
await writeCFHeaders(nitro, "public");
await writeFile$1(resolve$1(nitro.options.output.dir, "package.json"), JSON.stringify({
private: true,
main: "./server/index.mjs"
}, null, 2));
await writeFile$1(resolve$1(nitro.options.output.dir, "package-lock.json"), JSON.stringify({ lockfileVersion: 1 }, null, 2));
}
}
}, {
name: "cloudflare-module",
stdName: "cloudflare_workers"
});
const cloudflareDurable = defineNitroPreset({
extends: "cloudflare-module",
entry: "./cloudflare/runtime/cloudflare-durable"
}, { name: "cloudflare-durable" });
var preset_default$8 = [
cloudflarePages,
cloudflarePagesStatic,
cloudflareModule,
cloudflareDurable,
cloudflareDev
];
//#endregion
//#region src/presets/deno/unenv/node-compat.ts
const builtnNodeModules = [
"node:_http_agent",
"node:_http_common",
"node:_http_outgoing",
"node:_http_server",
"node:_stream_duplex",
"node:_stream_passthrough",
"node:_stream_readable",
"node:_stream_transform",
"node:_stream_writable",
"node:_tls_common",
"node:_tls_wrap",
"node:assert",
"node:assert/strict",
"node:async_hooks",
"node:buffer",
"node:child_process",
"node:cluster",
"node:console",
"node:constants",
"node:crypto",
"node:dgram",
"node:diagnostics_channel",
"node:dns",
"node:dns/promises",
"node:domain",
"node:events",
"node:fs",
"node:fs/promises",
"node:http",
"node:http2",
"node:https",
"node:inspector",
"node:inspector/promises",
"node:module",
"node:net",
"node:os",
"node:path",
"node:path/posix",
"node:path/win32",
"node:perf_hooks",
"node:process",
"node:punycode",
"node:querystring",
"node:readline",
"node:readline/promises",
"node:repl",
"node:sqlite",
"node:stream",
"node:stream/consumers",
"node:stream/promises",
"node:stream/web",
"node:string_decoder",
"node:sys",
"node:test",
"node:timers",
"node:timers/promises",
"node:tls",
"node:trace_events",
"node:tty",
"node:url",
"node:util",
"node:util/types",
"node:v8",
"node:vm",
"node:wasi",
"node:worker_threads",
"node:zlib"
];
//#endregion
//#region src/presets/deno/unenv/preset.ts
const unenvDeno = {
meta: { name: "nitro:deno" },
external: builtnNodeModules.map((m) => `node:${m}`),
alias: { ...Object.fromEntries(builtnNodeModules.flatMap((m) => [[m, m], [m.replace("node:", ""), m]])) },
inject: {
global: "unenv/polyfill/globalthis",
process: "node:process",
clearImmediate: ["node:timers", "clearImmediate"],
setImmediate: ["node:timers", "setImmediate"],
Buffer: ["node:buffer", "Buffer"]
}
};
//#endregion
//#region src/presets/deno/preset.ts
const denoDeploy = defineNitroPreset({
entry: "./deno/runtime/deno-deploy",
exportConditions: ["deno"],
node: false,
noExternals: true,
serveStatic: "deno",
commands: {
preview: "",
deploy: "cd ./ && deployctl deploy --project=<project_name> server/index.ts"
},
unenv: unenvDeno,
rollupConfig: {
preserveEntrySignatures: false,
external: (id) => id.startsWith("https://") || id.startsWith("node:"),
output: {
entryFileNames: "index.ts",
manualChunks: (id) => "index",
format: "esm"
}
}
}, { name: "deno-deploy" });
const denoServer = defineNitroPreset({
entry: "./deno/runtime/deno-server",
serveStatic: true,
exportConditions: ["deno"],
commands: { preview: "deno -A ./server/index.mjs" },
rollupConfig: {
external: (id) => id.startsWith("https://"),
output: { hoistTransitiveImports: false }
},
hooks: { async compiled(nitro) {
await writeFile$1(resolve$1(nitro.options.output.dir, "deno.json"), JSON.stringify({ tasks: { start: "deno run -A ./server/index.mjs" } }, null, 2));
} }
}, {
aliases: ["deno"],
name: "deno-server"
});
var preset_default$9 = [denoDeploy, denoServer];
//#endregion
//#region src/presets/digitalocean/preset.ts
const digitalOcean = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "digital-ocean" });
var preset_default$10 = [digitalOcean];
//#endregion
//#region src/presets/firebase/preset.ts
const firebaseAppHosting = defineNitroPreset({
extends: "node-server",
serveStatic: true,
hooks: { async compiled(nitro) {
const serverEntry = join$1(nitro.options.output.serverDir, "index.mjs");
await writeFile$1(join$1(nitro.options.rootDir, ".apphosting/bundle.yaml"), gr({
version: "v1",
runConfig: {
runCommand: `node ${relative$1(nitro.options.rootDir, serverEntry)}`,
...nitro.options.firebase?.appHosting
},
metadata: {
framework: nitro.options.framework.name || "nitro",
frameworkVersion: nitro.options.framework.version || "2.x",
adapterPackageName: "nitro",
adapterVersion: version
},
outputFiles: { serverApp: { include: [relative$1(nitro.options.rootDir, nitro.options.output.dir)] } }
}), true);
} }
}, {
name: "firebase-app-hosting",
stdName: "firebase_app_hosting"
});
var preset_default$11 = [firebaseAppHosting];
//#endregion
//#region src/presets/flightcontrol/preset.ts
const flightControl = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "flight-control" });
var preset_default$12 = [flightControl];
//#endregion
//#region src/presets/genezio/preset.ts
const genezio = defineNitroPreset({ extends: "aws_lambda" }, { name: "genezio" });
var preset_default$13 = [genezio];
//#endregion
//#region src/presets/heroku/preset.ts
const heroku = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "heroku" });
var preset_default$14 = [heroku];
//#endregion
//#region src/presets/iis/utils.ts
async function writeIISFiles(nitro) {
await writeFile$1(resolve$1(nitro.options.output.dir, "web.config"), await iisXmlTemplate(nitro));
}
async function writeIISNodeFiles(nitro) {
await writeFile$1(resolve$1(nitro.options.output.dir, "web.config"), await iisnodeXmlTemplate(nitro));
await writeFile$1(resolve$1(nitro.options.output.dir, "index.js"), `
if (process.env.PORT.startsWith('\\\\')) {
process.env.NITRO_UNIX_SOCKET = process.env.PORT
delete process.env.PORT
}
import('./server/index.mjs');
`);
}
async function iisnodeXmlTemplate(nitro) {
const path$1 = resolve$1(nitro.options.rootDir, "web.config");
const originalString = `<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/Azure/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<handlers>
<!-- Indicates that the index.js file is a Node.js site to be handled by the iisnode module -->
<add name="iisnode" path="index.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^index.js/debug[/]?" />
</rule>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{PATH_INFO}" />
</rule>
<!-- All other URLs are mapped to the Node.js site entrypoint -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True" />
</conditions>
<action type="Rewrite" url="index.js" />
</rule>
</rules>
</rewrite>
<!-- 'bin' directory has no special meaning in Node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin" />
</hiddenSegments>
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
See https://github.com/Azure/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<iisnode
watchedFiles="index.js"
node_env="production"
debuggingEnabled="false"
loggingEnabled="false"
/>
</system.webServer>
</configuration>
`;
if (existsSync(path$1)) {
const fileString = await readFile(path$1, "utf8");
const originalWebConfig = await parseXmlDoc(originalString);
const fileWebConfig = await parseXmlDoc(fileString);
if (nitro.options.iis?.mergeConfig && !nitro.options.iis.overrideConfig) return buildNewXmlDoc(defu(fileWebConfig, originalWebConfig));
if (nitro.options.iis?.overrideConfig) return buildNewXmlDoc({ ...fileWebConfig });
}
return originalString;
}
async function iisXmlTemplate(nitro) {
const path$1 = resolve$1(nitro.options.rootDir, "web.config");
const originalString = `<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
</handlers>
<httpPlatform stdoutLogEnabled="true" stdoutLogFile=".\\logs\\node.log" startupTimeLimit="20" processPath="C:\\Program Files\\nodejs\\node.exe" arguments=".\\server\\index.mjs">
<environmentVariables>
<environmentVariable name="PORT" value="%HTTP_PLATFORM_PORT%" />
<environmentVariable name="NODE_ENV" value="Production" />
</environmentVariables>
</httpPlatform>
</system.webServer>
</configuration>
`;
if (existsSync(path$1)) {
const fileString = await readFile(path$1, "utf8");
const originalWebConfig = await parseXmlDoc(originalString);
const fileWebConfig = await parseXmlDoc(fileString);
if (nitro.options.iis?.mergeConfig && !nitro.options.iis.overrideConfig) return buildNewXmlDoc(defu(fileWebConfig, originalWebConfig));
if (nitro.options.iis?.overrideConfig) return buildNewXmlDoc({ ...fileWebConfig });
}
return originalString;
}
async function parseXmlDoc(xml) {
const { Parser } = await import("xml2js");
if (xml === void 0 || !xml) return {};
const parser = new Parser({ explicitArray: false });
let parsedRecord = {};
parser.parseString(xml, (_, r) => {
parsedRecord = r;
});
return parsedRecord;
}
async function buildNewXmlDoc(xmlObj) {
const { Builder } = await import("xml2js");
return new Builder().buildObject({ ...xmlObj });
}
//#endregion
//#region src/presets/iis/preset.ts
const iisHandler = defineNitroPreset({
extends: "node-server",
serveStatic: true,
hooks: { async compiled(nitro) {
await writeIISFiles(nitro);
} }
}, { name: "iis-handler" });
const iisNode = defineNitroPreset({
extends: "node-server",
serveStatic: true,
hooks: { async compiled(nitro) {
await writeIISNodeFiles(nitro);
} }
}, { name: "iis-node" });
var preset_default$15 = [iisHandler, iisNode];
//#endregion
//#region src/presets/koyeb/preset.ts
const koyeb = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "koyeb" });
var preset_default$16 = [koyeb];
//#endregion
//#region src/presets/netlify/utils.ts
async function writeRedirects(nitro) {
const redirectsPath = join$1(nitro.options.output.publicDir, "_redirects");
let contents = "";
if (nitro.options.static) {
const staticFallback = existsSync(join$1(nitro.options.output.publicDir, "404.html")) ? "/* /404.html 404" : "";
contents += staticFallback;
}
const rules = Object.entries(nitro.options.routeRules).sort((a$1, b) => a$1[0].split(/\/(?!\*)/).length - b[0].split(/\/(?!\*)/).length);
for (const [key, routeRules] of rules.filter(([_, routeRules$1]) => routeRules$1.redirect)) {
let code = routeRules.redirect.status;
if (code === 307) code = 302;
if (code === 308) code = 301;
contents = `${key.replace("/**", "/*")}\t${routeRules.redirect.to.replace("/**", "/:splat")}\t${code}\n` + contents;
}
if (existsSync(redirectsPath)) {
const currentRedirects = await promises.readFile(redirectsPath, "utf8");
if (/^\/\* /m.test(currentRedirects)) {
nitro.logger.info("Not adding Nitro fallback to `_redirects` (as an existing fallback was found).");
return;
}
nitro.logger.info("Adding Nitro fallback to `_redirects` to handle all unmatched routes.");
contents = currentRedirects + "\n" + contents;
}
await promises.writeFile(redirectsPath, contents);
}
async function writeHeaders(nitro) {
const headersPath = join$1(nitro.options.output.publicDir, "_headers");
let contents = "";
const rules = Object.entries(nitro.options.routeRules).sort((a$1, b) => b[0].split(/\/(?!\*)/).length - a$1[0].split(/\/(?!\*)/).length);
for (const [path$1, routeRules] of rules.filter(([_, routeRules$1]) => routeRules$1.headers)) {
const headers = [path$1.replace("/**", "/*"), ...Object.entries({ ...routeRules.headers }).map(([header, value]) => ` ${header}: ${value}`)].join("\n");
contents += headers + "\n";
}
if (existsSync(headersPath)) {
const currentHeaders = await promises.readFile(headersPath, "utf8");
if (/^\/\* /m.test(currentHeaders)) {
nitro.logger.info("Not adding Nitro fallback to `_headers` (as an existing fallback was found).");
return;
}
nitro.logger.info("Adding Nitro fallback to `_headers` to handle all unmatched routes.");
contents = currentHeaders + "\n" + contents;
}
await promises.writeFile(headersPath, contents);
}
function getStaticPaths(publicAssets, baseURL) {
return ["/.netlify/*", ...publicAssets.filter((a$1) => a$1.fallthrough !== true && a$1.baseURL && a$1.baseURL !== "/").map((a$1) => joinURL(baseURL, a$1.baseURL, "*"))];
}
function generateNetlifyFunction(nitro) {
return `
export { default } from "./main.mjs";
export const config = {
name: "server handler",
generator: "${getGeneratorString(nitro)}",
path: "/*",
nodeBundler: "none",
includedFiles: ["**"],
excludedPath: ${JSON.stringify(getStaticPaths(nitro.options.publicAssets, nitro.options.baseURL))},
preferStatic: true,
};
`.trim();
}
function getGeneratorString(nitro) {
return `${nitro.options.framework.name}@${nitro.options.framework.version}`;
}
//#endregion
//#region src/presets/netlify/preset.ts
const netlify = defineNitroPreset({
entry: "./netlify/runtime/netlify",
output: {
dir: "{{ rootDir }}/.netlify/functions-internal",
publicDir: "{{ rootDir }}/dist/{{ baseURL }}"
},
prerender: { autoSubfolderIndex: false },
rollupConfig: { output: { entryFileNames: "main.mjs" } },
hooks: { async compiled(nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
await promises.writeFile(join$1(nitro.options.output.dir, "server", "server.mjs"), generateNetlifyFunction(nitro));
if (nitro.options.netlify) {
const configPath = join$1(nitro.options.output.dir, "../deploy/v1/config.json");
await promises.mkdir(dirname$1(configPath), { recursive: true });
await promises.writeFile(configPath, JSON.stringify(nitro.options.netlify), "utf8");
}
} }
}, {
name: "netlify",
stdName: "netlify"
});
const netlifyEdge = defineNitroPreset({
extends: "base-worker",
entry: "./netlify/runtime/netlify-edge",
exportConditions: ["netlify"],
output: {
serverDir: "{{ rootDir }}/.netlify/edge-functions/server",
publicDir: "{{ rootDir }}/dist/{{ baseURL }}"
},
prerender: { autoSubfolderIndex: false },
rollupConfig: { output: {
entryFileNames: "server.js",
format: "esm"
} },
unenv: unenvDeno,
hooks: { async compiled(nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
const manifest = {
version: 1,
functions: [{
path: "/*",
excludedPath: getStaticPaths(nitro.options.publicAssets, nitro.options.baseURL),
name: "edge server handler",
function: "server",
generator: getGeneratorString(nitro)
}]
};
const manifestPath = join$1(nitro.options.rootDir, ".netlify/edge-functions/manifest.json");
await promises.mkdir(dirname$1(manifestPath), { recursive: true });
await promises.writeFile(manifestPath, JSON.stringify(manifest, null, 2));
} }
}, { name: "netlify-edge" });
const netlifyStatic = defineNitroPreset({
extends: "static",
output: {
dir: "{{ rootDir }}/dist",
publicDir: "{{ rootDir }}/dist/{{ baseURL }}"
},
prerender: { autoSubfolderIndex: false },
commands: { preview: "npx serve ./" },
hooks: { async compiled(nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
} }
}, {
name: "netlify-static",
stdName: "netlify",
static: true
});
var preset_default$17 = [
netlify,
netlifyEdge,
netlifyStatic
];
//#endregion
//#region src/presets/node/cluster.ts
const nodeCluster = defineNitroPreset({
extends: "node-server",
serveStatic: true,
entry: "./node/runtime/node-cluster",
rollupConfig: { output: { entryFileNames: "worker.mjs" } },
hooks: { async compiled(nitro) {
await writeFile$2(resolve$1(nitro.options.output.serverDir, "index.mjs"), nodeClusterEntry());
} }
}, { name: "node-cluster" });
function nodeClusterEntry() {
return `
import cluster from "node:cluster";
import os from "node:os";
if (cluster.isPrimary) {
const numberOfWorkers =
Number.parseInt(process.env.NITRO_CLUSTER_WORKERS || "") ||
(os.cpus().length > 0 ? os.cpus().length : 1);
for (let i = 0; i < numberOfWorkers; i++) {
cluster.fork({
WORKER_ID: i + 1,
});
}
} else {
import("./worker.mjs").catch((error) => {
console.error(error);
process.exit(1);
});
}
`;
}
//#endregion
//#region src/presets/node/preset.ts
const nodeServer = defineNitroPreset({
entry: "./node/runtime/node-server",
serveStatic: true,
commands: { preview: "node ./server/index.mjs" }
}, {
name: "node-server",
aliases: ["node"]
});
const nodeMiddleware = defineNitroPreset({ entry: "./node/runtime/node-middleware" }, { name: "node-middleware" });
var preset_default$18 = [
nodeServer,
nodeCluster,
nodeMiddleware
];
//#endregion
//#region src/presets/platform.sh/preset.ts
const platformSh = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "platform-sh" });
var preset_default$19 = [platformSh];
//#endregion
//#region src/presets/render.com/preset.ts
const renderCom = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "render-com" });
var preset_default$20 = [renderCom];
//#endregion
//#region src/presets/standard/preset.ts
const standard = defineNitroPreset({
entry: "./standard/runtime/server",
serveStatic: false,
exportConditions: ["import", "default"],
output: { publicDir: "{{ output.dir }}/public/{{ baseURL }}" },
commands: { preview: "npx srvx --prod ./" },
alias: {
srvx: "srvx/generic",
"srvx/bun": "srvx/bun",
"srvx/deno": "srvx/deno",
"srvx/node": "srvx/node",
"srvx/generic": "srvx/generic"
}
}, { name: "standard" });
var preset_default$21 = [standard];
//#endregion
//#region src/presets/stormkit/preset.ts
const stormkit = defineNitroPreset({
entry: "./stormkit/runtime/stormkit",
output: {
dir: "{{ rootDir }}/.stormkit",
publicDir: "{{ rootDir }}/.stormkit/public/{{ baseURL }}"
}
}, {
name: "stormkit",
stdName: "stormkit"
});
var preset_default$22 = [stormkit];
//#endregion
//#region src/presets/vercel/utils.ts
const SUPPORTED_NODE_VERSIONS = [20, 22];
const FALLBACK_ROUTE = "/__server";
const ISR_SUFFIX = "-isr";
const SAFE_FS_CHAR_RE = /[^a-zA-Z0-9_.[\]/]/g;
function getSystemNodeVersion() {
const systemNodeVersion = Number.parseInt(process.versions.node.split(".")[0]);
return Number.isNaN(systemNodeVersion) ? 22 : systemNodeVersion;
}
async function generateFunctionFiles(nitro) {
const o11Routes = getObservabilityRoutes(nitro);
const buildConfigPath = resolve$1(nitro.options.output.dir, "config.json");
const buildConfig = generateBuildConfig(nitro, o11Routes);
await writeFile$1(buildConfigPath, JSON.stringify(buildConfig, null, 2));
const functionConfigPath = resolve$1(nitro.options.output.serverDir, ".vc-config.json");
const functionConfig = {
handler: "index.mjs",
launcherType: "Nodejs",
shouldAddHelpers: false,
supportsResponseStreaming: true,
...nitro.options.vercel?.functions
};
await writeFile$1(functionConfigPath, JSON.stringify(functionConfig, null, 2));
for (const [key, value] of Object.entries(nitro.options.routeRules)) {
if (!value.isr) continue;
const funcPrefix = resolve$1(nitro.options.output.serverDir, "..", normalizeRouteDest(key) + ISR_SUFFIX);
await fsp.mkdir(dirname$1(funcPrefix), { recursive: true });
await fsp.symlink("./" + relative$1(dirname$1(funcPrefix), nitro.options.output.serverDir), funcPrefix + ".func", "junction");
await writePrerenderConfig(funcPrefix + ".prerender-config.json", value.isr, nitro.options.vercel?.config?.bypassToken);
}
if (o11Routes.length === 0) return;
const _getRouteRules = (path$1) => defu({}, ...nitro.routing.routeRules.matchAll("", path$1).reverse());
for (const route of o11Routes) {
if (_getRouteRules(route.src).isr) continue;
const funcPrefix = resolve$1(nitro.options.output.serverDir, "..", route.dest);
await fsp.mkdir(dirname$1(funcPrefix), { recursive: true });
await fsp.symlink("./" + relative$1(dirname$1(funcPrefix), nitro.options.output.serverDir), funcPrefix + ".func", "junction");
}
}
async function generateStaticFiles(nitro) {
const buildConfigPath = resolve$1(nitro.options.output.dir, "config.json");
const buildConfig = generateBuildConfig(nitro);
await writeFile$1(buildConfigPath, JSON.stringify(buildConfig, null, 2));
}
function generateBuildConfig(nitro, o11Routes) {
const rules = Object.entries(nitro.options.routeRules).sort((a$1, b) => b[0].split(/\/(?!\*)/).length - a$1[0].split(/\/(?!\*)/).length);
const config = defu(nitro.options.vercel?.config, {
version: 3,
overrides: { ...Object.fromEntries((nitro._prerenderedRoutes?.filter((r) => r.fileName !== r.route) || []).map(({ route, fileName }) => [withoutLeadingSlash(fileName), { path: route.replace(/^\//, "") }])) },
routes: [
...rules.filter(([_, routeRules]) => routeRules.redirect || routeRules.headers).map(([path$1, routeRules]) => {
let route = { src: path$1.replace("/**", "/(.*)") };
if (routeRules.redirect) route = defu(route, {
status: routeRules.redirect.status,
headers: { Location: routeRules.redirect.to.replace("/**", "/$1") }
});
if (routeRules.headers) route = defu(route, { headers: routeRules.headers });
return route;
}),
...nitro.options.publicAssets.filter((asset) => !asset.fallthrough).map((asset) => joinURL(nitro.options.baseURL, asset.baseURL || "/")).map((baseURL) => ({
src: baseURL + "(.*)",
headers: { "cache-control": "public,max-age=31536000,immutable" },
continue: true
})),
{ handle: "filesystem" }
]
});
if (nitro.options.static) return config;
config.routes.push(...nitro.options.routeRules["/"]?.isr ? [{
src: "(?<url>/)",
dest: `/index${ISR_SUFFIX}?url=$url`
}] : [], ...rules.filter(([key, value]) => value.isr !== void 0 && key !== "/").map(([key, value]) => {
const src = key.replace(/^(.*)\/\*\*/, "(?<url>$1/.*)");
if (value.isr === false) return {
src,
dest: FALLBACK_ROUTE
};
return {
src,
dest: withLeadingSlash(normalizeRouteDest(key) + ISR_SUFFIX + "?url=$url")
};
}), ...(o11Routes || []).map((route) => ({
src: joinURL(nitro.options.baseURL, route.src),
dest: withLeadingSlash(route.dest)
})), ...nitro.options.routeRules["/**"]?.isr ? [] : [{
src: "/(.*)",
dest: FALLBACK_ROUTE
}]);
return config;
}
function deprecateSWR(nitro) {
if (nitro.options.future.nativeSWR) return;
let hasLegacyOptions = false;
for (const [_key, value] of Object.entries(nitro.options.routeRules)) {
if (_hasProp(value, "isr")) continue;
if (value.cache === false) value.isr = false;
if (_hasProp(value, "static")) {
value.isr = !value.static;
hasLegacyOptions = true;
}
if (value.cache && _hasProp(value.cache, "swr")) {
value.isr = value.cache.swr;
hasLegacyOptions = true;
}
}
if (hasLegacyOptions && !a) nitro.logger.warn("Nitro now uses `isr` option to configure ISR behavior on Vercel. Backwards-compatible support for `static` and `swr` options within the Vercel Build Options API will be removed in the future versions. Set `future.nativeSWR: true` nitro config disable this warning.");
}
async function resolveVercelRuntime(nitro) {
let runtime = nitro.options.vercel?.functions?.runtime;
if (runtime) return runtime;
if ((await readVercelConfig(nitro.options.rootDir)).bunVersion || "Bun" in globalThis) runtime = "bun1.x";
else {
const systemNodeVersion = getSystemNodeVersion();
runtime = `nodejs${SUPPORTED_NODE_VERSIONS.find((version$1) => version$1 >= systemNodeVersion) ?? SUPPORTED_NODE_VERSIONS.at(-1)}.x`;
}
nitro.options.vercel ??= {};
nitro.options.vercel.functions ??= {};
nitro.options.vercel.functions.runtime = runtime;
return runtime;
}
async function readVercelConfig(rootDir) {
const vercelConfigPath = resolve$1(rootDir, "vercel.json");
return await fsp.readFile(vercelConfigPath).then((config) => JSON.parse(config.toString())).catch(() => ({}));
}
function _hasProp(obj, prop) {
return obj && typeof obj === "object" && prop in obj;
}
function getObservabilityRoutes(nitro) {
if ((nitro.options.compatibilityDate.vercel || nitro.options.compatibilityDate.default) < "2025-07-15") return [];
const routePatterns = [...new Set([...nitro.options.ssrRoutes || [], ...[...nitro.scannedHandlers, ...nitro.options.handlers].filter((h$1) => !h$1.middleware && h$1.route).map((h$1) => h$1.route)])];
const staticRoutes = [];
const dynamicRoutes = [];
const catchAllRoutes = [];
for (const route of routePatterns) if (route.includes("**")) catchAllRoutes.push(route);
else if (route.includes(":") || route.includes("*")) dynamicRoutes.push(route);
else staticRoutes.push(route);
return [
...normalizeRoutes(staticRoutes),
...normalizeRoutes(dynamicRoutes),
...normalizeRoutes(catchAllRoutes)
];
}
function normalizeRoutes(routes) {
return routes.sort((a$1, b) => b.localeCompare(a$1)).map((route) => ({
src: normalizeRouteSrc(route),
dest: normalizeRouteDest(route)
}));
}
function normalizeRouteSrc(route) {
let idCtr = 0;
return route.split("/").map((segment) => {
if (segment.startsWith("**")) return segment === "**" ? "(?:.*)" : `?(?<${namedGroup(segment.slice(3))}>.+)`;
if (segment === "*") return `(?<_${idCtr++}>[^/]*)`;
if (segment.includes(":")) return segment.replace(/:(\w+)/g, (_, id) => `(?<${namedGroup(id)}>[^/]+)`).replace(/\./g, String.raw`\.`);
return segment;
}).join("/");
}
function namedGroup(input = "") {
if (/\d/.test(input[0])) input = `_${input}`;
return input.replace(/[^a-zA-Z0-9_]/g, "") || "_";
}
function normalizeRouteDest(route) {
return route.split("/").slice(1).map((segment) => {
if (segment.startsWith("**")) return `[...${segment.replace(/[*:]/g, "")}]`;
if (segment === "*") return "[-]";
if (segment.startsWith(":")) return `[${segment.slice(1)}]`;
if (segment.includes(":")) return `[${segment.replace(/:/g, "_")}]`;
return segment;
}).map((segment) => segment.replace(SAFE_FS_CHAR_RE, "-")).join("/") || "index";
}
async function writePrerenderConfig(filename, isrConfig, bypassToken) {
if (typeof isrConfig === "number") isrConfig = { expiration: isrConfig };
else if (isrConfig === true) isrConfig = { expiration: false };
else isrConfig = { ...isrConfig };
const prerenderConfig = {
expiration: isrConfig.expiration ?? false,
bypassToken,
...isrConfig
};
await writeFile$1(filename, JSON.stringify(prerenderConfig, null, 2));
}
//#endregion
//#region src/presets/vercel/preset.ts
const vercel = defineNitroPreset({
entry: "./vercel/runtime/vercel.{format}",
output: {
dir: "{{ rootDir }}/.vercel/output",
serverDir: "{{ output.dir }}/functions/__server.func",
publicDir: "{{ output.dir }}/static/{{ baseURL }}"
},
commands: {
preview: "",
deploy: "npx vercel deploy --prebuilt"
},
hooks: {
"build:before": async (nitro) => {
const logger = nitro.logger.withTag("vercel");
const runtime = await resolveVercelRuntime(nitro);
if (runtime.startsWith("bun") && !nitro.options.exportConditions.includes("bun")) nitro.options.exportConditions.push("bun");
logger.info(`Using \`${runtime}\` runtime.`);
let serverFormat = nitro.options.vercel?.entryFormat;
if (!serverFormat) serverFormat = nitro.routing.routes.routes.flatMap((r) => r.data).some((h$1) => h$1.format === "node") ? "node" : "web";
logger.info(`Using \`${serverFormat}\` entry format.`);
nitro.options.entry = nitro.options.entry.replace("{format}", serverFormat);
},
"rollup:before": (nitro) => {
deprecateSWR(nitro);
},
async compiled(nitro) {
await generateFunctionFiles(nitro);
}
}
}, {
name: "vercel",
stdName: "vercel"
});
const vercelStatic = defineNitroPreset({
extends: "static",
output: {
dir: "{{ rootDir }}/.vercel/output",
publicDir: "{{ output.dir }}/static/{{ baseURL }}"
},
commands: { preview: "npx serve ./static" },
hooks: {
"rollup:before": (nitro) => {
deprecateSWR(nitro);
},
async compiled(nitro) {
await generateStaticFiles(nitro);
}
}
}, {
name: "vercel-static",
stdName: "vercel",
static: true
});
var preset_default$23 = [vercel, vercelStatic];
//#endregion
//#region src/presets/winterjs/preset.ts
const winterjs = defineNitroPreset({
extends: "base-worker",
entry: "./winterjs/runtime/winterjs",
minify: false,
serveStatic: "inline",
wasm: { lazy: true },
commands: { preview: "wasmer run wasmer/winterjs --forward-host-env --net --mapdir app:./ app/server/index.mjs" }
}, { name: "winterjs" });
var preset_default$24 = [winterjs];
//#endregion
//#region src/presets/zeabur/preset.ts
const zeabur = defineNitroPreset({
entry: "./zeabur/runtime/zeabur",
output: {
dir: "{{ rootDir }}/.zeabur/output",
serverDir: "{{ output.dir }}/functions/__nitro.func",
publicDir: "{{ output.dir }}/static"
},
hooks: { async compiled(nitro) {
await writeFile$1(resolve$1(nitro.options.output.dir, "config.json"), JSON.stringify({
containerized: false,
routes: [{
src: ".*",
dest: "/__nitro"
}]
}, null, 2));
for (const [key, value] of Object.entries(nitro.options.routeRules)) {
if (!value.isr) continue;
const funcPrefix = resolve$1(nitro.options.output.serverDir, ".." + key);
await fsp.mkdir(dirname$1(funcPrefix), { recursive: true });
await fsp.symlink("./" + relative$1(dirname$1(funcPrefix), nitro.options.output.serverDir), funcPrefix + ".func", "junction");
await writeFile$1(funcPrefix + ".prerender-config.json", JSON.stringify({ type: "Prerender" }));
}
} }
}, {
name: "zeabur",
stdName: "zeabur"
});
const zeaburStatic = defineNitroPreset({
extends: "static",
output: {
dir: "{{ rootDir }}/.zeabur/output",
publicDir: "{{ output.dir }}/static"
},
commands: { preview: "npx serve ./static" }
}, {
name: "zeabur-static",
static: true
});
var preset_default$25 = [zeabur, zeaburStatic];
//#endregion
//#region src/presets/zerops/preset.ts
const zerops = defineNitroPreset({
extends: "node-server",
serveStatic: true
}, { name: "zerops" });
const zeropsStatic = defineNitroPreset({
extends: "static",
output: {
dir: "{{ rootDir }}/.zerops/output",
publicDir: "{{ output.dir }}/static"
}
}, {
name: "zerops-static",
static: true
});
var preset_default$26 = [zerops, zeropsStatic];
//#endregion
//#region src/presets/_all.gen.ts
var _all_gen_default = [
...preset_default,
...preset_default$1,
...preset_default$2,
...preset_default$3,
...preset_default$4,
...preset_default$5,
...preset_default$6,
...preset_default$7,
...preset_default$8,
...preset_default$9,
...preset_default$10,
...preset_default$11,
...preset_default$12,
...preset_default$13,
...preset_default$14,
...preset_default$15,
...preset_default$16,
...preset_default$17,
...preset_default$18,
...preset_default$19,
...preset_default$20,
...preset_default$21,
...preset_default$22,
...preset_default$23,
...preset_default$24,
...preset_default$25,
...preset_default$26
];
//#endregion
//#region src/presets/_resolve.ts
const _stdProviderMap = {
aws_amplify: "aws",
azure_static: "azure",
cloudflare_pages: "cloudflare"
};
async function resolvePreset(name, opts = {}) {
if (name === ".") return;
const _name = kebabCase(name) || p;
const _compatDates = opts.compatibilityDate ? resolveCompatibilityDatesFromEnv(opts.compatibilityDate) : false;
const matches = _all_gen_default.filter((preset$1) => {
if (![
preset$1._meta.name,
preset$1._meta.stdName,
...preset$1._meta.aliases || []
].filter(Boolean).includes(_name)) return false;
if (opts.dev && !preset$1._meta.dev || !opts.dev && preset$1._meta.dev) return false;
if (_compatDates) {
const _date = _compatDates[_stdProviderMap[preset$1._meta.stdName]] || _compatDates[preset$1._meta.stdName] || _compatDates[preset$1._meta.name] || _compatDates.default;
if (_date && preset$1._meta.compatibilityDate && new Date(preset$1._meta.compatibilityDate) > new Date(_date)) return false;
}
return true;
}).sort((a$1, b) => {
const aDate = new Date(a$1._meta.compatibilityDate || 0);
return new Date(b._meta.compatibilityDate || 0) > aDate ? 1 : -1;
});
const preset = matches.find((p$1) => (p$1._meta.static || false) === (opts?.static || false)) || matches[0];
if (typeof preset === "function") return preset();
if (!name && !preset) {
if (opts?.static) return resolvePreset("static", opts);
return resolvePreset({
deno: "deno",
bun: "bun"
}[K] || "node", opts);
}
if (name && !preset) {
const options = _all_gen_default.filter((p$1) => p$1._meta.name === name || p$1._meta.stdName === name || p$1._meta.aliases?.includes(name)).sort((a$1, b) => (a$1._meta.compatibilityDate || 0) > (b._meta.compatibilityDate || 0) ? 1 : -1);
if (options.length > 0) {
let msg = `Preset "${name}" cannot be resolved with current compatibilityDate: ${formatCompatibilityDate(_compatDates || "")}.\n\n`;
for (const option of options) msg += `\n- ${option._meta.name} (requires compatibilityDate >= ${option._meta.compatibilityDate})`;
const err = new Error(msg);
Error.captureStackTrace?.(err, resolvePreset);
throw err;
}
}
return preset;
}
//#endregion
export { resolvePreset };
import { t as NitroDevApp } from "./_dev.mjs";
import { IncomingMessage, OutgoingMessage } from "node:http";
import { Duplex } from "node:stream";
import { Server, ServerOptions } from "srvx";
import { DevMessageListener, DevRPCHooks, LoadConfigOptions, Nitro, NitroBuildInfo, NitroConfig, NitroOptions, TaskEvent, TaskRunnerOptions } from "nitro/types";
//#region src/nitro.d.ts
declare function createNitro(config?: NitroConfig, opts?: LoadConfigOptions): Promise<Nitro>;
//#endregion
//#region src/config/loader.d.ts
declare function loadOptions(configOverrides?: NitroConfig, opts?: LoadConfigOptions): Promise<NitroOptions>;
//#endregion
//#region src/build/build.d.ts
declare function build(nitro: Nitro): Promise<void>;
//#endregion
//#region src/build/assets.d.ts
declare function copyPublicAssets(nitro: Nitro): Promise<void>;
//#endregion
//#region src/build/prepare.d.ts
declare function prepare(nitro: Nitro): Promise<void>;
//#endregion
//#region src/build/types.d.ts
declare function writeTypes(nitro: Nitro): Promise<void>;
//#endregion
//#region src/build/info.d.ts
declare function getBuildInfo(root: string): Promise<{
outputDir?: undefined;
buildInfo?: undefined;
} | {
outputDir: string;
buildInfo?: NitroBuildInfo;
}>;
//#endregion
//#region src/dev/server.d.ts
declare function createDevServer(nitro: Nitro): NitroDevServer;
declare class NitroDevServer extends NitroDevApp implements DevRPCHooks {
#private;
constructor(nitro: Nitro);
upgrade(req: IncomingMessage, socket: OutgoingMessage<IncomingMessage> | Duplex, head: any): Promise<any>;
listen(opts?: Partial<Omit<ServerOptions, "fetch">>): Server;
close(): Promise<void>;
reload(): void;
sendMessage(message: unknown): void;
onMessage(listener: DevMessageListener): void;
offMessage(listener: DevMessageListener): void;
}
//#endregion
//#region src/prerender/prerender.d.ts
declare function prerender(nitro: Nitro): Promise<void>;
//#endregion
//#region src/task.d.ts
/** @experimental */
declare function runTask(taskEvent: TaskEvent, opts?: TaskRunnerOptions): Promise<{
result: unknown;
}>;
/** @experimental */
declare function listTasks(opts?: TaskRunnerOptions): Promise<Record<string, {
meta: {
description: string;
};
}>>;
//#endregion
export { build, copyPublicAssets, createDevServer, createNitro, getBuildInfo, listTasks, loadOptions, prepare, prerender, runTask, writeTypes };
import "./_libs/c12.mjs";
import "./_libs/gen-mapping.mjs";
import "./_libs/magic-string.mjs";
import "./_libs/acorn.mjs";
import "./_libs/confbox.mjs";
import "./_libs/local-pkg.mjs";
import "./_libs/js-tokens.mjs";
import "./_libs/strip-literal.mjs";
import "./_libs/unimport.mjs";
import "./_libs/picomatch.mjs";
import "./_libs/fdir.mjs";
import "./_libs/tinyglobby.mjs";
import "./_libs/compatx.mjs";
import "./_libs/klona.mjs";
import "./_libs/std-env.mjs";
import { a as createNitro, c as loadOptions, i as build, n as prepare, o as listTasks, r as copyPublicAssets, s as runTask, t as prerender } from "./_chunks/B-D1JOIz.mjs";
import "./_libs/escape-string-regexp.mjs";
import "./_libs/tsconfck.mjs";
import "./_libs/dot-prop.mjs";
import "./_chunks/C7CbzoI1.mjs";
import { n as writeTypes } from "./_chunks/ANM1K1bE.mjs";
import "./_libs/rou3.mjs";
import "./_libs/mime.mjs";
import "./_libs/pathe.mjs";
import "./_libs/untyped.mjs";
import "./_libs/knitwork.mjs";
import { t as getBuildInfo } from "./_build/common.mjs";
import "./_libs/httpxy.mjs";
import { n as createDevServer } from "./_dev.mjs";
import "./_libs/chokidar.mjs";
import "./_libs/ultrahtml.mjs";
export { build, copyPublicAssets, createDevServer, createNitro, getBuildInfo, listTasks, loadOptions, prepare, prerender, runTask, writeTypes };
import { k as resolve } from "../../_libs/c12.mjs";
import { t as defineCommand } from "../../_libs/citty.mjs";
import { t as commonArgs } from "./common.mjs";
import { build, copyPublicAssets, createNitro, prepare, prerender } from "nitro/builder";
//#region src/cli/commands/build.ts
var build_default = defineCommand({
meta: {
name: "build",
description: "Build nitro project for production"
},
args: {
...commonArgs,
minify: {
type: "boolean",
description: "Minify the output (overrides preset defaults you can also use `--no-minify` to disable)."
},
preset: {
type: "string",
description: "The build preset to use (you can also use `NITRO_PRESET` environment variable)."
},
builder: {
type: "string",
description: "The builder to use (you can also use `NITRO_BUILDER` environment variable)."
},
compatibilityDate: {
type: "string",
description: "The date to use for preset compatibility (you can also use `NITRO_COMPATIBILITY_DATE` environment variable)."
}
},
async run({ args }) {
const nitro = await createNitro({
rootDir: resolve(args.dir || args._dir || "."),
dev: false,
minify: args.minify,
preset: args.preset,
builder: args.builder
}, { compatibilityDate: args.compatibilityDate });
await prepare(nitro);
await copyPublicAssets(nitro);
await prerender(nitro);
await build(nitro);
await nitro.close();
}
});
//#endregion
export { build_default as default };
//#region src/cli/common.ts
const commonArgs = {
dir: {
type: "string",
description: "project root directory"
},
_dir: {
type: "positional",
default: ".",
description: "project root directory (prefer using `--dir`)"
}
};
//#endregion
export { commonArgs as t };
import "../../_libs/c12.mjs";
import "../../_libs/gen-mapping.mjs";
import "../../_libs/magic-string.mjs";
import "../../_libs/acorn.mjs";
import "../../_libs/confbox.mjs";
import "../../_libs/local-pkg.mjs";
import "../../_libs/js-tokens.mjs";
import "../../_libs/strip-literal.mjs";
import { n as detectImportsAcorn, r as traveseScopes, t as createVirtualImportsAcronWalker } from "../../_libs/unimport.mjs";
import "../../_libs/estree-walker.mjs";
export { createVirtualImportsAcronWalker, detectImportsAcorn, traveseScopes };
import { k as resolve } from "../../_libs/c12.mjs";
import "../../_libs/std-env.mjs";
import "../../_libs/dot-prop.mjs";
import "../../_chunks/C7CbzoI1.mjs";
import "../../_libs/mime.mjs";
import "../../_build/common.mjs";
import "../../_libs/httpxy.mjs";
import { t as NitroDevServer } from "../../_dev.mjs";
import "../../_libs/chokidar.mjs";
import { t as defineCommand } from "../../_libs/citty.mjs";
import { t as commonArgs } from "./common.mjs";
import { consola } from "consola";
import { build, createNitro, prepare } from "nitro/builder";
//#region src/cli/commands/dev.ts
const hmrKeyRe = /^runtimeConfig\.|routeRules\./;
var dev_default = defineCommand({
meta: {
name: "dev",
description: "Start the development server"
},
args: {
...commonArgs,
port: {
type: "string",
description: "specify port"
},
host: {
type: "string",
description: "specify hostname "
}
},
async run({ args }) {
const rootDir = resolve(args.dir || args._dir || ".");
let nitro;
const reload = async () => {
if (nitro) {
consola.info("Restarting dev server...");
if ("unwatch" in nitro.options._c12) await nitro.options._c12.unwatch();
await nitro.close();
}
nitro = await createNitro({
rootDir,
dev: true,
_cli: { command: "dev" }
}, {
watch: true,
c12: { async onUpdate({ getDiff, newConfig }) {
const diff = getDiff();
if (diff.length === 0) return;
consola.info("Nitro config updated:\n" + diff.map((entry) => ` ${entry.toString()}`).join("\n"));
await (diff.every((e) => hmrKeyRe.test(e.key)) ? nitro.updateConfig(newConfig.config || {}) : reload());
} }
});
nitro.hooks.hookOnce("restart", reload);
await new NitroDevServer(nitro).listen({
port: args.port,
hostname: args.host
});
await prepare(nitro);
await build(nitro);
};
await reload();
}
});
//#endregion
export { dev_default as default };
import { c as findNearestFile, d as readGitConfig, f as readPackageJSON, l as findWorkspaceDir, m as resolvePackageJSON, p as resolveGitConfig, s as findFile, u as parseGitConfig } from "../../_libs/c12.mjs";
export { findFile, findNearestFile, findWorkspaceDir, parseGitConfig, readGitConfig, readPackageJSON, resolveGitConfig, resolvePackageJSON };
import { a as loadDotenv, i as loadConfig, o as setupDotenv, r as SUPPORTED_EXTENSIONS, t as watchConfig } from "../../_libs/c12.mjs";
export { SUPPORTED_EXTENSIONS, loadConfig, loadDotenv, setupDotenv, watchConfig };
import { n as createProxyServer, t as ProxyServer } from "../../_libs/httpxy.mjs";
export { ProxyServer, createProxyServer };
import "../../_libs/c12.mjs";
import { a as addDependency, c as installDependencies, l as packageManagers, o as addDevDependency, s as detectPackageManager } from "../../_libs/giget.mjs";
export { addDependency, addDevDependency, detectPackageManager, installDependencies, packageManagers };
import "../../_libs/c12.mjs";
import { n as registryProvider, t as downloadTemplate } from "../../_libs/giget.mjs";
export { downloadTemplate, registryProvider };
import { i as watch, n as WatchHelper, r as esm_default, t as FSWatcher } from "../../_libs/chokidar.mjs";
export { FSWatcher, WatchHelper, esm_default as default, watch };
import "../../_libs/c12.mjs";
import { i as Cu } from "../../_libs/confbox.mjs";
export { Cu as parseJSON5 };
import { _ as h } from "../../_libs/c12.mjs";
import "../../_libs/confbox.mjs";
export { h as parseJSONC };
import { k as resolve } from "../../_libs/c12.mjs";
import { t as defineCommand } from "../../_libs/citty.mjs";
import { consola } from "consola";
import { listTasks, loadOptions } from "nitro/builder";
//#region src/cli/commands/task/list.ts
var list_default = defineCommand({
meta: {
name: "run",
description: "List available tasks (experimental)"
},
args: { dir: {
type: "string",
description: "project root directory"
} },
async run({ args }) {
const cwd = resolve(args.dir || args.cwd || ".");
const tasks = await listTasks({
cwd,
buildDir: (await loadOptions({ rootDir: cwd }).catch(() => void 0))?.buildDir || ".nitro"
});
for (const [name, task] of Object.entries(tasks)) consola.log(` - \`${name}\`${task.meta?.description ? ` - ${task.meta.description}` : ""}`);
}
});
//#endregion
export { list_default as default };
import "../../_libs/giget.mjs";
import { t as require_multipart_parser } from "../../_libs/node-fetch-native.mjs";
export default require_multipart_parser();
export { };
import { k as resolve } from "../../_libs/c12.mjs";
import { t as defineCommand } from "../../_libs/citty.mjs";
import { t as commonArgs } from "./common.mjs";
import { createNitro, writeTypes } from "nitro/builder";
//#region src/cli/commands/prepare.ts
var prepare_default = defineCommand({
meta: {
name: "prepare",
description: "Generate types for the project"
},
args: { ...commonArgs },
async run({ args }) {
await writeTypes(await createNitro({ rootDir: resolve(args.dir || args._dir || ".") }));
}
});
//#endregion
export { prepare_default as default };
import { k as resolve } from "../../_libs/c12.mjs";
import { t as defineCommand } from "../../_libs/citty.mjs";
import { consola } from "consola";
import destr from "destr";
import { loadOptions, runTask } from "nitro/builder";
//#region src/cli/commands/task/run.ts
var run_default = defineCommand({
meta: {
name: "run",
description: "Run a runtime task in the currently running dev server (experimental)"
},
args: {
name: {
type: "positional",
description: "task name",
required: true
},
dir: {
type: "string",
description: "project root directory"
},
payload: {
type: "string",
description: "payload json to pass to the task"
}
},
async run({ args }) {
const cwd = resolve(args.dir || args.cwd || ".");
const options = await loadOptions({ rootDir: cwd }).catch(() => void 0);
consola.info(`Running task \`${args.name}\`...`);
let payload = destr(args.payload || "{}");
if (typeof payload !== "object") {
consola.error(`Invalid payload: \`${args.payload}\` (it should be a valid JSON object)`);
payload = void 0;
}
try {
const { result } = await runTask({
name: args.name,
context: {},
payload
}, {
cwd,
buildDir: options?.buildDir || ".nitro"
});
consola.success("Result:", result);
} catch (error) {
consola.error(`Failed to run task \`${args.name}\`: ${error}`);
process.exit(1);
}
}
});
//#endregion
export { run_default as default };
import { t as defineCommand } from "../../_libs/citty.mjs";
//#region src/cli/commands/task/index.ts
var task_default = defineCommand({
meta: {
name: "task",
description: "Operate in nitro tasks (experimental)"
},
subCommands: {
list: () => import("./list.mjs").then((r) => r.default),
run: () => import("./run.mjs").then((r) => r.default)
}
});
//#endregion
export { task_default as default };
import "../../_libs/c12.mjs";
import { t as Q } from "../../_libs/confbox.mjs";
export { Q as parseTOML };
import "../../_libs/c12.mjs";
import { n as gr, r as mr } from "../../_libs/confbox.mjs";
export { mr as parseYAML, gr as stringifyYAML };
function parse(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
const obj = {};
const opt = options || {};
const dec = opt.decode || decode;
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
let endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (opt?.filter && !opt?.filter(key)) {
index = endIdx + 1;
continue;
}
if (void 0 === obj[key]) {
let val = str.slice(eqIdx + 1, endIdx).trim();
if (val.codePointAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function decode(str) {
return str.includes("%") ? decodeURIComponent(str) : str;
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch {
return str;
}
}
const fieldContentRegExp = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
function serialize(name, value, options) {
const opt = options || {};
const enc = opt.encode || encodeURIComponent;
if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}
const encodedValue = enc(value);
if (encodedValue && !fieldContentRegExp.test(encodedValue)) {
throw new TypeError("argument val is invalid");
}
let str = name + "=" + encodedValue;
if (void 0 !== opt.maxAge && opt.maxAge !== null) {
const maxAge = opt.maxAge - 0;
if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}
str += "; Max-Age=" + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}
str += "; Domain=" + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}
str += "; Path=" + opt.path;
}
if (opt.expires) {
if (!isDate(opt.expires) || Number.isNaN(opt.expires.valueOf())) {
throw new TypeError("option expires is invalid");
}
str += "; Expires=" + opt.expires.toUTCString();
}
if (opt.httpOnly) {
str += "; HttpOnly";
}
if (opt.secure) {
str += "; Secure";
}
if (opt.priority) {
const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case "low": {
str += "; Priority=Low";
break;
}
case "medium": {
str += "; Priority=Medium";
break;
}
case "high": {
str += "; Priority=High";
break;
}
default: {
throw new TypeError("option priority is invalid");
}
}
}
if (opt.sameSite) {
const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true: {
str += "; SameSite=Strict";
break;
}
case "lax": {
str += "; SameSite=Lax";
break;
}
case "strict": {
str += "; SameSite=Strict";
break;
}
case "none": {
str += "; SameSite=None";
break;
}
default: {
throw new TypeError("option sameSite is invalid");
}
}
}
if (opt.partitioned) {
str += "; Partitioned";
}
return str;
}
function isDate(val) {
return Object.prototype.toString.call(val) === "[object Date]" || val instanceof Date;
}
function parseSetCookie(setCookieValue, options) {
const parts = (setCookieValue || "").split(";").filter((str) => typeof str === "string" && !!str.trim());
const nameValuePairStr = parts.shift() || "";
const parsed = _parseNameValuePair(nameValuePairStr);
const name = parsed.name;
let value = parsed.value;
try {
value = options?.decode === false ? value : (options?.decode || decodeURIComponent)(value);
} catch {
}
const cookie = {
name,
value
};
for (const part of parts) {
const sides = part.split("=");
const partKey = (sides.shift() || "").trimStart().toLowerCase();
const partValue = sides.join("=");
switch (partKey) {
case "expires": {
cookie.expires = new Date(partValue);
break;
}
case "max-age": {
cookie.maxAge = Number.parseInt(partValue, 10);
break;
}
case "secure": {
cookie.secure = true;
break;
}
case "httponly": {
cookie.httpOnly = true;
break;
}
case "samesite": {
cookie.sameSite = partValue;
break;
}
default: {
cookie[partKey] = partValue;
}
}
}
return cookie;
}
function _parseNameValuePair(nameValuePairStr) {
let name = "";
let value = "";
const nameValueArr = nameValuePairStr.split("=");
if (nameValueArr.length > 1) {
name = nameValueArr.shift();
value = nameValueArr.join("=");
} else {
value = nameValuePairStr;
}
return { name, value };
}
function splitSetCookieString(cookiesString) {
if (Array.isArray(cookiesString)) {
return cookiesString.flatMap((c) => splitSetCookieString(c));
}
if (typeof cookiesString !== "string") {
return [];
}
const cookiesStrings = [];
let pos = 0;
let start;
let ch;
let lastComma;
let nextStart;
let cookiesSeparatorFound;
const skipWhitespace = () => {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
};
const notSpecialChar = () => {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
};
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
cookiesSeparatorFound = true;
pos = nextStart;
cookiesStrings.push(cookiesString.slice(start, lastComma));
start = pos;
} else {
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.slice(start));
}
}
return cookiesStrings;
}
export { parse, parseSetCookie, serialize, splitSetCookieString };
{
"name": "cookie-es",
"version": "2.0.0",
"repository": "unjs/cookie-es",
"license": "MIT",
"sideEffects": false,
"type": "module",
"exports": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"types": "./dist/index.d.mts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"dev": "vitest --coverage",
"lint": "eslint --cache . && prettier -c src test",
"lint:fix": "automd && eslint --cache . --fix && prettier -c src test -w",
"release": "pnpm test && pnpm build && changelogen --release --push && npm publish",
"test": "pnpm lint && vitest run --coverage"
},
"devDependencies": {
"@types/node": "^22.13.5",
"@vitest/coverage-v8": "^3.0.7",
"automd": "^0.4.0",
"changelogen": "^0.6.0",
"eslint": "^9.21.0",
"eslint-config-unjs": "^0.4.2",
"prettier": "^3.5.2",
"typescript": "^5.7.3",
"unbuild": "^3.5.0",
"vitest": "^3.0.7"
},
"packageManager": "pnpm@10.5.2"
}
import { FastResponse } from "srvx";
//#region src/parser.ts
function parseTemplate(template) {
if (!template) return [];
template = template.replace(/<script\s+server\s*>([\s\S]*?)<\/script>/gi, (_m, code) => `<?js${code}?>`);
template = template.replace(/{{\s*(.+)\s*}}|{{{\s*(.+)\s*}}}/g, (_m, code) => {
if (code[0] === "{") return `<?=${code.slice(1, -1).trim()}?>`;
return `<?=htmlspecialchars(${code.trim()})?>`;
});
const tokens = [];
const re = /<\?(?:js)?(?<equals>=)?(?<value>[\s\S]*?)\?>/g;
let cursor = 0;
let match;
while (match = re.exec(template)) {
const { equals, value } = match.groups || {};
const matchStart = match.index;
const matchEnd = matchStart + match[0].length;
if (matchStart > cursor) {
const textContent = template.slice(cursor, matchStart);
if (textContent) tokens.push({
type: "text",
contents: textContent
});
}
if (equals) tokens.push({
type: "expr",
contents: value || ""
});
else tokens.push({
type: "code",
contents: value || ""
});
cursor = matchEnd;
}
if (cursor < template.length) {
const remainingText = template.slice(cursor);
if (remainingText) tokens.push({
type: "text",
contents: remainingText
});
}
return tokens;
}
/**
* Check if a template string contains template syntax.
*/
function hasTemplateSyntax(template) {
return /(?:<script\s+server\s*>[\s\S]*?<\/script>)|(?:<\?(?:js)?=?[\s\S]*?\?>)|(?:\{\{[\s\S]*?\}\})/i.test(template);
}
//#endregion
//#region src/_runtime.ts
function runtimeStream(body) {
return `const __chunks__ = [];const echo = (chunk) => { __chunks__.push(chunk); };${body};
function concatStreams(chunks) {
const encoder = new TextEncoder();
return new ReadableStream({
async pull(controller) {
for (let chunk of chunks) {
if (typeof chunk === 'function'){
chunk = chunk();
}
if (chunk instanceof Promise) {
chunk = await chunk;
if (!chunk) continue;
if (chunk instanceof Response){
chunk = chunk.body;
}
if (!(chunk instanceof ReadableStream)) {
controller.enqueue(chunk instanceof Uint8Array ? chunk : encoder.encode(chunk));
continue;
}
}
if (chunk instanceof ReadableStream) {
const reader = chunk.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
controller.enqueue(value);
}
reader.releaseLock();
} else {
controller.enqueue(chunk instanceof Uint8Array ? chunk : encoder.encode(chunk));
}
}
controller.close();
},
});
}
return concatStreams(__chunks__);
`;
}
function runtimeText(body) {
return `const __chunks__ = [];const echo = (chunk) => { __chunks__.push(chunk); };${body};
let __out__ = "";
for(let chunk of __chunks__){
if (typeof chunk === 'function'){
chunk = chunk();
}
if (chunk instanceof Promise){
chunk = await chunk;
}
if (chunk instanceof Response){
chunk = chunk.body;
}
if (chunk instanceof ReadableStream){
const reader = chunk.getReader();
while(true){
const {value, done} = await reader.read();
if(done) break;
__out__ += typeof value === "string" ? value : new TextDecoder().decode(value);
}
reader.releaseLock();
} else {
__out__ += typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
}
}
return __out__;
`;
}
//#endregion
//#region src/compiler.ts
/**
* Compile a template string into a render function.
*
* @example
* ```ts
* import { compileTemplate } from "rendu";
*
* const template = `
* <h1>{{ title }}</h1>
* <ul>
* <? for (const item of items) { ?>
* <li>{{ item }}</li>
* <? } ?>
* </ul>
* `;
*
* const render = compileTemplate(template, { stream: false });
*
* const html = await render({ title: "My List", items: ["Item 1", "Item 2", "Item 3"] });
* console.log(html);
* // Output:
* // <h1>My List</h1>
* // <ul>
* // <li>Item 1</li>
* // <li>Item 2</li>
* // <li>Item 3</li>
* // </ul>
* ```
*/
function compileTemplate(template, opts = {}) {
const body = compileTemplateToString(template, opts, false);
const sourcemaps = opts.filename ? `\n//# sourceURL=${opts.filename}` : "";
try {
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
return new AsyncFunction("__context__", body + sourcemaps);
} catch (error) {
throw new SyntaxError(`Template syntax error: ${error.message}`, {});
}
}
/**
* Compile a template string into a render function code string.
*
* **Note:** This function is for advanced use cases where you need the generated code as a string.
*/
function compileTemplateToString(template, opts, asyncWrapper) {
const parts = [];
const tokens = parseTemplate(template);
for (const token of tokens) switch (token.type) {
case "text":
if (opts.preserveLines) for (const line of token.contents.split("\n")) parts.push(`echo(${JSON.stringify(line + "\n")})\n`);
else parts.push(`echo(${JSON.stringify(token.contents)})`);
break;
case "expr":
parts.push(`echo(${token.contents})`);
break;
case "code":
parts.push(token.contents);
break;
}
let body = parts.join(opts.preserveLines ? ";" : "\n");
body = opts.contextKeys ? `const {${opts.contextKeys.join(",")}}=__context__;${body}` : `with(__context__){${body}}`;
body = opts.stream === false ? runtimeText(body) : runtimeStream(body);
return asyncWrapper === false ? body : `(async (__context__) => {${body}})`;
}
//#endregion
//#region node_modules/.pnpm/cookie-es@2.0.0/node_modules/cookie-es/dist/index.mjs
function parse(str, options) {
if (typeof str !== "string") throw new TypeError("argument str must be a string");
const obj = {};
const opt = options || {};
const dec = opt.decode || decode;
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) break;
let endIdx = str.indexOf(";", index);
if (endIdx === -1) endIdx = str.length;
else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (opt?.filter && !opt?.filter(key)) {
index = endIdx + 1;
continue;
}
if (void 0 === obj[key]) {
let val = str.slice(eqIdx + 1, endIdx).trim();
if (val.codePointAt(0) === 34) val = val.slice(1, -1);
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function decode(str) {
return str.includes("%") ? decodeURIComponent(str) : str;
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch {
return str;
}
}
const fieldContentRegExp = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
function serialize(name, value, options) {
const opt = options || {};
const enc = opt.encode || encodeURIComponent;
if (typeof enc !== "function") throw new TypeError("option encode is invalid");
if (!fieldContentRegExp.test(name)) throw new TypeError("argument name is invalid");
const encodedValue = enc(value);
if (encodedValue && !fieldContentRegExp.test(encodedValue)) throw new TypeError("argument val is invalid");
let str = name + "=" + encodedValue;
if (void 0 !== opt.maxAge && opt.maxAge !== null) {
const maxAge = opt.maxAge - 0;
if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) throw new TypeError("option maxAge is invalid");
str += "; Max-Age=" + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) throw new TypeError("option domain is invalid");
str += "; Domain=" + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) throw new TypeError("option path is invalid");
str += "; Path=" + opt.path;
}
if (opt.expires) {
if (!isDate(opt.expires) || Number.isNaN(opt.expires.valueOf())) throw new TypeError("option expires is invalid");
str += "; Expires=" + opt.expires.toUTCString();
}
if (opt.httpOnly) str += "; HttpOnly";
if (opt.secure) str += "; Secure";
if (opt.priority) switch (typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default: throw new TypeError("option priority is invalid");
}
if (opt.sameSite) switch (typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite) {
case true:
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "strict":
str += "; SameSite=Strict";
break;
case "none":
str += "; SameSite=None";
break;
default: throw new TypeError("option sameSite is invalid");
}
if (opt.partitioned) str += "; Partitioned";
return str;
}
function isDate(val) {
return Object.prototype.toString.call(val) === "[object Date]" || val instanceof Date;
}
//#endregion
//#region src/render.ts
/**
* Renders an HTML template to a Response object.
*
* @example
* ```ts
* import { compileTemplate, renderToResponse } from "rendu";
*
* const render = compileTemplate(template, { stream: true });
*
* const response = await renderToResponse(render, { request });
* ```
* @param htmlTemplate The compiled HTML template.
* @param opts Options for rendering.
* @returns A Response object.
*/
async function renderToResponse(htmlTemplate, opts) {
const ctx = createRenderContext(opts);
const body = await htmlTemplate(ctx);
if (body instanceof Response) return body;
return new FastResponse(body, {
status: ctx.$RESPONSE.status,
statusText: ctx.$RESPONSE.statusText,
headers: ctx.$RESPONSE.headers
});
}
const RENDER_CONTEXT_KEYS = [
"htmlspecialchars",
"setCookie",
"redirect",
"$REQUEST",
"$METHOD",
"$URL",
"$HEADERS",
"$COOKIES",
"$RESPONSE"
];
function createRenderContext(options) {
const url = new URL(options.request?.url || "http://_");
const response = {
status: 200,
statusText: "OK",
headers: new Headers({ "Content-Type": "text/html ; charset=utf-8" })
};
const $COOKIES = lazyCookies(options.request);
const setCookie = (name, value, sOpts = {}) => {
response.headers.append("Set-Cookie", serialize(name, value, sOpts));
};
const redirect = (to, status = 302) => {
response.status = status;
response.headers.set("Location", to);
};
return {
...options.context,
htmlspecialchars,
setCookie,
redirect,
$REQUEST: options.request,
$METHOD: options.request?.method,
$URL: url,
$HEADERS: options.request?.headers,
$COOKIES,
$RESPONSE: response
};
}
function lazyCookies(req) {
if (!req) return {};
let parsed;
return new Proxy(Object.freeze(Object.create(null)), { get(_, prop) {
if (typeof prop !== "string") return void 0;
parsed ??= parse(req.headers.get("cookie") || "");
return parsed[prop];
} });
}
function htmlspecialchars(s) {
const htmlSpecialCharsMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&#39;"
};
return String(s).replace(/[&<>"']/g, (c) => htmlSpecialCharsMap[c] || c);
}
//#endregion
export { RENDER_CONTEXT_KEYS, compileTemplate, compileTemplateToString, createRenderContext, hasTemplateSyntax, renderToResponse };
{
"name": "rendu",
"version": "0.0.7",
"description": "",
"repository": "h3js/rendu",
"license": "MIT",
"sideEffects": false,
"type": "module",
"exports": {
".": "./dist/index.mjs"
},
"types": "./dist/index.d.mts",
"bin": "./dist/cli.mjs",
"files": [
"dist"
],
"scripts": {
"build": "obuild",
"dev": "vitest dev",
"lint": "eslint . && prettier -c .",
"lint:fix": "automd && eslint . --fix && prettier -w .",
"prepack": "pnpm build",
"play": "pnpm rendu playground",
"release": "pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags",
"rendu": "node ./src/cli.ts",
"test": "pnpm lint && pnpm test:types && vitest run --coverage",
"test:types": "tsc --noEmit --skipLibCheck"
},
"dependencies": {
"srvx": "^0.9.1"
},
"devDependencies": {
"@types/node": "^24.9.1",
"@vitest/coverage-v8": "^4.0.4",
"automd": "^0.4.2",
"changelogen": "^0.6.2",
"cookie-es": "^2.0.0",
"eslint": "^9.38.0",
"eslint-config-unjs": "^0.5.0",
"obuild": "^0.3.0",
"prettier": "^3.6.2",
"rendu": "^0.0.6",
"typescript": "^5.9.3",
"vitest": "^4.0.4"
},
"packageManager": "pnpm@10.19.0"
}
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/layout/main.ts
var Layout = class extends BaseComponent {
cssFile = new URL("./layout/style.css", publicDirURL);
scriptFile = new URL("./layout/script.js", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${props.title}</title>
<!-- STYLES -->
<!-- GLOBAL SCRIPT -->
</head>
<body>
<div id="layout">
${await props.children()}
</div>
<!-- SCRIPTS -->
</body>
</html>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
return `
${await props.children()}
`;
}
};
export {
Layout
};
import {
colors,
htmlEscape
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_stack/main.ts
import { dump, themes } from "@poppinss/dumper/html";
import { dump as dumpCli } from "@poppinss/dumper/console";
var CHEVIRON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" width="24" height="24" stroke-width="2">
<path d="M6 9l6 6l6 -6"></path>
</svg>`;
var EDITORS = {
textmate: "txmt://open?url=file://%f&line=%l",
macvim: "mvim://open?url=file://%f&line=%l",
emacs: "emacs://open?url=file://%f&line=%l",
sublime: "subl://open?url=file://%f&line=%l",
phpstorm: "phpstorm://open?file=%f&line=%l",
atom: "atom://core/open/file?filename=%f&line=%l",
vscode: "vscode://file/%f:%l"
};
var ErrorStack = class extends BaseComponent {
cssFile = new URL("./error_stack/style.css", publicDirURL);
scriptFile = new URL("./error_stack/script.js", publicDirURL);
/**
* Returns the file's relative name from the CWD
*/
#getRelativeFileName(filePath) {
return filePath.replace(`${process.cwd()}/`, "");
}
/**
* Returns the index of the frame that should be expanded by
* default
*/
#getFirstExpandedFrameIndex(frames) {
let expandAtIndex = frames.findIndex((frame) => frame.type === "app");
if (expandAtIndex === -1) {
expandAtIndex = frames.findIndex((frame) => frame.type === "module");
}
return expandAtIndex;
}
/**
* Returns the link to open the file within known code
* editors
*/
#getEditorLink(ide, frame) {
const editorURL = EDITORS[ide] || ide;
if (!editorURL || frame.type === "native") {
return {
text: this.#getRelativeFileName(frame.fileName)
};
}
return {
href: editorURL.replace("%f", frame.fileName).replace("%l", String(frame.lineNumber)),
text: this.#getRelativeFileName(frame.fileName)
};
}
/**
* Returns the HTML fragment for the frame location
*/
#renderFrameLocation(frame, ide) {
const { text, href } = this.#getEditorLink(ide, frame);
const fileName = `<a${href ? ` href="${href}"` : ""} class="stack-frame-filepath" title="${text}">
${htmlEscape(text)}
</a>`;
const functionName = frame.functionName ? `<span>in <code title="${frame.functionName}">
${htmlEscape(frame.functionName)}
</code></span>` : "";
const loc = `<span>at line <code>${frame.lineNumber}:${frame.columnNumber}</code></span>`;
if (frame.type !== "native" && frame.source) {
return `<button class="stack-frame-location">
${fileName} ${functionName} ${loc}
</button>`;
}
return `<div class="stack-frame-location">
${fileName} ${functionName} ${loc}
</div>`;
}
/**
* Returns HTML fragment for the stack frame
*/
async #renderStackFrame(frame, index, expandAtIndex, props) {
const label = frame.type === "app" ? '<span class="frame-label">In App</span>' : "";
const expandedClass = expandAtIndex === index ? " expanded" : "";
const toggleButton = frame.type !== "native" && frame.source ? `<button class="stack-frame-toggle-indicator">${CHEVIRON}</button>` : "";
return `<li class="stack-frame stack-frame-${frame.type}${expandedClass}">
<div class="stack-frame-contents">
${this.#renderFrameLocation(frame, props.ide)}
<div class="stack-frame-extras">
${label}
${toggleButton}
</div>
</div>
<div class="stack-frame-source">
${await props.sourceCodeRenderer(props.error, frame)}
</div>
</li>`;
}
/**
* Returns the ANSI output to print the stack frame on the
* terminal
*/
async #printStackFrame(frame, index, expandAtIndex, props) {
const fileName = this.#getRelativeFileName(frame.fileName);
const loc = `${fileName}:${frame.lineNumber}:${frame.columnNumber}`;
if (index === expandAtIndex) {
const functionName2 = frame.functionName ? `at ${frame.functionName} ` : "";
const codeSnippet = await props.sourceCodeRenderer(props.error, frame);
return ` \u2043 ${functionName2}${colors.yellow(`(${loc})`)}${codeSnippet}`;
}
if (frame.type === "native") {
const functionName2 = frame.functionName ? `at ${colors.italic(frame.functionName)} ` : "";
return colors.dim(` \u2043 ${functionName2}(${colors.italic(loc)})`);
}
const functionName = frame.functionName ? `at ${frame.functionName} ` : "";
return ` \u2043 ${functionName}${colors.yellow(`(${loc})`)}`;
}
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#renderStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
return `<section>
<div class="card">
<div class="card-heading">
<div>
<h3 class="card-title">
Stack Trace
</h3>
</div>
</div>
<div class="card-body">
<div id="stack-frames-wrapper">
<div id="stack-frames-header">
<div id="all-frames-toggle-wrapper">
<label id="all-frames-toggle">
<input type="checkbox" />
<span> View All Frames </span>
</label>
</div>
<div>
<div class="toggle-switch">
<button id="formatted-frames-toggle" class="active"> Pretty </button>
<button id="raw-frames-toggle"> Raw </button>
</div>
</div>
</div>
<div id="stack-frames-body">
<div id="stack-frames-formatted" class="visible">
<ul id="stack-frames">
${frames.join("\n")}
</ul>
</div>
<div id="stack-frames-raw">
${dump(props.error.raw, {
styles: themes.cssVariables,
expand: true,
cspNonce: props.cspNonce,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}
</div>
</div>
<div>
</div>
</div>
</section>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
const displayRaw = process.env.YOUCH_RAW;
if (displayRaw) {
const depth = Number.isNaN(Number(displayRaw)) ? 2 : Number(displayRaw);
return `
${colors.red("[RAW]")}
${dumpCli(props.error.raw, {
depth,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}`;
}
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#printStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
if (frames.length) {
return `
${frames.join("\n")}`;
}
return "";
}
};
export {
ErrorStack
};
// Shim for "cloudflare:workers" import in dev environment
// unenv shim respects __env__
export { env } from "unenv/node/internal/process/env";
export async function waitUntil(promise) {
await globalThis.__wait_until__?.(promise);
}
export function withEnv(newEnv, fn) {
throw new Error("cf.withEnv is not implemented in dev env currently.");
}
class NotImplemented {
constructor() {
throw new Error("Not implemented in dev env currently.");
}
}
export class DurableObject extends NotImplemented {}
export class RpcPromise extends NotImplemented {}
export class RpcProperty extends NotImplemented {}
export class RpcStub extends NotImplemented {}
export class RpcTarget extends NotImplemented {}
export class ServiceStub extends NotImplemented {}
export class WorkerEntrypoint extends NotImplemented {}
export class WorkflowEntrypoint extends NotImplemented {}
import "#nitro-internal-pollyfills";
import type { NodeServerRequest, NodeServerResponse } from "srvx";
export default function nodeHandler(req: NodeServerRequest, res: NodeServerResponse);
import "#nitro-internal-pollyfills";
import { toNodeHandler } from "srvx/node";
import { useNitroApp } from "nitro/app";
const nitroApp = useNitroApp();
const handler = toNodeHandler(nitroApp.fetch);
export default function nodeHandler(req, res) {
const query = req.headers["x-now-route-matches"];
if (query) {
const url = new URLSearchParams(query).get("url");
if (url) {
req.url = decodeURIComponent(url);
}
}
return handler(req, res);
}
import "#nitro-internal-pollyfills";
import type { ServerRequest } from "srvx";
declare const _default: {
fetch(req: ServerRequest, context: {
waitUntil: (promise: Promise<any>) => void;
});
};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/app";
const nitroApp = useNitroApp();
export default { fetch(req, context) {
// Check for ISR request
const query = req.headers.get("x-now-route-matches");
if (query) {
const urlParam = new URLSearchParams(query).get("url");
if (urlParam) {
const url = new URL(decodeURIComponent(urlParam), req.url).href;
req = new Request(url, req);
}
}
// srvx compatibility
req.runtime ??= { name: "vercel" };
// @ts-expect-error (add to srvx types)
req.runtime.vercel = { context };
req.waitUntil = context?.waitUntil;
return nitroApp.fetch(req);
} };
export { useNitroApp, useNitroHooks, serverFetch, fetch } from "./internal/app.mjs";
export { useNitroApp, useNitroHooks, serverFetch, fetch } from "./internal/app.mjs";
export { defineCachedFunction, defineCachedHandler } from "./internal/cache.mjs";
export { defineCachedFunction, defineCachedHandler } from "./internal/cache.mjs";
import type { NitroConfig } from "nitro/types";
export declare function defineConfig(config: Omit<NitroConfig, "rootDir">): Omit<NitroConfig, "rootDir">;
export { defineConfig as defineNitroConfig };
export function defineConfig(config) {
return config;
}
export { defineConfig as defineNitroConfig };
export { useRequest } from "./internal/context.mjs";
export { useRequest } from "./internal/context.mjs";
export { useDatabase } from "./internal/database.mjs";
export { useDatabase } from "./internal/database.mjs";
export declare function trapUnhandledErrors();
import { useNitroApp } from "../app.mjs";
function _captureError(error, type) {
console.error(`[${type}]`, error);
useNitroApp().captureError?.(error, { tags: [type] });
}
export function trapUnhandledErrors() {
process.on("unhandledRejection", (error) => _captureError(error, "unhandledRejection"));
process.on("uncaughtException", (error) => _captureError(error, "uncaughtException"));
}
export declare const version: string;
export declare const pkgDir: string;
export declare const runtimeDir: string;
export declare const presetsDir: string;
export declare const runtimeDependencies: string[];
import { fileURLToPath } from "node:url";
import packageJson from "../../package.json" with { type: "json" };
export const version = packageJson.version;
const resolve = (path) => fileURLToPath(new URL(path, import.meta.url));
export const pkgDir = /* @__PURE__ */ resolve("../../");
export const runtimeDir = /* @__PURE__ */ resolve("./");
export const presetsDir = /* @__PURE__ */ resolve("../presets/");
export const runtimeDependencies = [
"crossws",
"croner",
"db0",
"defu",
"destr",
"h3",
"rou3",
"hookable",
"ofetch",
"ohash",
"rendu",
"scule",
"srvx",
"ufo",
"unctx",
"unenv",
"unstorage"
];
// Config
import type { NitroConfig } from "nitro/types";
import type { ServerRequestContext } from "srvx";
import { type H3EventContext } from "h3";
export declare function defineConfig(config: Omit<NitroConfig, "rootDir">): Omit<NitroConfig, "rootDir">;
// Type (only) helpers
export { defineNitroPlugin as definePlugin } from "./internal/plugin.mjs";
export { defineRouteMeta } from "./internal/meta.mjs";
export { defineNitroErrorHandler as defineErrorHandler } from "./internal/error/utils.mjs";
// Runtime
export declare function serverFetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>;
export declare function fetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>;
import { toRequest } from "h3";
export function defineConfig(config) {
return config;
}
// Type (only) helpers
export { defineNitroPlugin as definePlugin } from "./internal/plugin.mjs";
export { defineRouteMeta } from "./internal/meta.mjs";
export { defineNitroErrorHandler as defineErrorHandler } from "./internal/error/utils.mjs";
// Runtime
export function serverFetch(resource, init, context) {
const nitro = globalThis.__nitro__ || globalThis.__nitro_builder__;
if (!nitro) {
return Promise.reject(new Error("Nitro instance is not available."));
}
const req = toRequest(resource, init);
req.context = {
...req.context,
...context
};
try {
return Promise.resolve(nitro.fetch(req));
} catch (error) {
return Promise.reject(error);
}
}
export function fetch(resource, init, context) {
if (typeof resource === "string" && resource.charCodeAt(0) === 47) {
return serverFetch(resource, init, context);
}
resource = resource._request || resource;
return globalThis.fetch(resource, init);
}
export { useRuntimeConfig } from "./internal/runtime-config.mjs";
export { useRuntimeConfig } from "./internal/runtime-config.mjs";
export { useStorage } from "./internal/storage.mjs";
export { useStorage } from "./internal/storage.mjs";
export { defineTask, runTask } from "./internal/task.mjs";
export { defineTask, runTask } from "./internal/task.mjs";
type FetchableEnv = {
fetch: (request: Request) => Response | Promise<Response>;
};
declare global {
var __nitro_vite_envs__: Record<string, FetchableEnv>;
}
export declare function fetchViteEnv(viteEnvName: string, input: RequestInfo | URL, init?: RequestInit);
export {};
import { HTTPError, toRequest } from "h3";
export function fetchViteEnv(viteEnvName, input, init) {
const envs = globalThis.__nitro_vite_envs__ || {};
const viteEnv = envs[viteEnvName];
if (!viteEnv) {
throw HTTPError.status(404);
}
return Promise.resolve(viteEnv.fetch(toRequest(input, init)));
}
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"moduleDetection": "force",
"isolatedModules": true,
"verbatimModuleSyntax": true,
"allowJs": true,
"allowImportingTsExtensions": true,
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true,
"noUnusedLocals": true
}
}
+1
-1

@@ -1,1 +0,1 @@

export { };
#!/usr/bin/env node
import consola from 'consola';
import { colors } from 'consola/utils';
import { version } from 'nitro/meta';
import { n as runMain, t as defineCommand } from "../_libs/citty.mjs";
import { version } from "nitro/meta";
function toArray(val) {
if (Array.isArray(val)) {
return val;
}
return val === void 0 ? [] : [val];
}
function formatLineColumns(lines, linePrefix = "") {
const maxLengh = [];
for (const line of lines) {
for (const [i, element] of line.entries()) {
maxLengh[i] = Math.max(maxLengh[i] || 0, element.length);
}
}
return lines.map(
(l) => l.map(
(c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLengh[i])
).join(" ")
).join("\n");
}
function resolveValue(input) {
return typeof input === "function" ? input() : input;
}
class CLIError extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = "CLIError";
}
}
//#region src/cli/index.ts
runMain(defineCommand({
meta: {
name: "nitro",
description: "Nitro CLI",
version
},
subCommands: {
dev: () => import("./_chunks/dev.mjs").then((r) => r.default),
build: () => import("./_chunks/build.mjs").then((r) => r.default),
prepare: () => import("./_chunks/prepare.mjs").then((r) => r.default),
task: () => import("./_chunks/task.mjs").then((r) => r.default)
}
}));
const NUMBER_CHAR_RE = /\d/;
const STR_SPLITTERS = ["-", "_", "/", "."];
function isUppercase(char = "") {
if (NUMBER_CHAR_RE.test(char)) {
return void 0;
}
return char !== char.toLowerCase();
}
function splitByCase(str, separators) {
const splitters = STR_SPLITTERS;
const parts = [];
if (!str || typeof str !== "string") {
return parts;
}
let buff = "";
let previousUpper;
let previousSplitter;
for (const char of str) {
const isSplitter = splitters.includes(char);
if (isSplitter === true) {
parts.push(buff);
buff = "";
previousUpper = void 0;
continue;
}
const isUpper = isUppercase(char);
if (previousSplitter === false) {
if (previousUpper === false && isUpper === true) {
parts.push(buff);
buff = char;
previousUpper = isUpper;
continue;
}
if (previousUpper === true && isUpper === false && buff.length > 1) {
const lastChar = buff.at(-1);
parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
buff = lastChar + char;
previousUpper = isUpper;
continue;
}
}
buff += char;
previousUpper = isUpper;
previousSplitter = isSplitter;
}
parts.push(buff);
return parts;
}
function upperFirst(str) {
return str ? str[0].toUpperCase() + str.slice(1) : "";
}
function lowerFirst(str) {
return str ? str[0].toLowerCase() + str.slice(1) : "";
}
function pascalCase(str, opts) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(p)).join("") : "";
}
function camelCase(str, opts) {
return lowerFirst(pascalCase(str || ""));
}
function kebabCase(str, joiner) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join("-") : "";
}
function toArr(any) {
return any == void 0 ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
let x;
const old = out[key];
const nxt = ~opts.string.indexOf(key) ? val == void 0 || val === true ? "" : String(val) : typeof val === "boolean" ? val : ~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
out[key] = old == void 0 ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
}
function parseRawArgs(args = [], opts = {}) {
let k;
let arr;
let arg;
let name;
let val;
const out = { _: [] };
let i = 0;
let j = 0;
let idx = 0;
const len = args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i = 0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i = opts.boolean.length; i-- > 0; ) {
arr = opts.alias[opts.boolean[i]] || [];
for (j = arr.length; j-- > 0; ) {
opts.boolean.push(arr[j]);
}
}
for (i = opts.string.length; i-- > 0; ) {
arr = opts.alias[opts.string[i]] || [];
for (j = arr.length; j-- > 0; ) {
opts.string.push(arr[j]);
}
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i = 0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i = 0; i < len; i++) {
arg = args[i];
if (arg === "--") {
out._ = out._.concat(args.slice(++i));
break;
}
for (j = 0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) {
break;
}
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === "no-") {
name = arg.slice(Math.max(0, j + 3));
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx = j + 1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) {
break;
}
}
name = arg.substring(j, idx);
val = arg.slice(Math.max(0, ++idx)) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
arr = j === 2 ? [name] : name;
for (idx = 0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) {
return opts.unknown("-".repeat(j) + name);
}
toVal(out, name, idx + 1 < arr.length || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}
function parseArgs(rawArgs, argsDef) {
const parseOptions = {
boolean: [],
string: [],
mixed: [],
alias: {},
default: {}
};
const args = resolveArgs(argsDef);
for (const arg of args) {
if (arg.type === "positional") {
continue;
}
if (arg.type === "string") {
parseOptions.string.push(arg.name);
} else if (arg.type === "boolean") {
parseOptions.boolean.push(arg.name);
}
if (arg.default !== void 0) {
parseOptions.default[arg.name] = arg.default;
}
if (arg.alias) {
parseOptions.alias[arg.name] = arg.alias;
}
}
const parsed = parseRawArgs(rawArgs, parseOptions);
const [...positionalArguments] = parsed._;
const parsedArgsProxy = new Proxy(parsed, {
get(target, prop) {
return target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];
}
});
for (const [, arg] of args.entries()) {
if (arg.type === "positional") {
const nextPositionalArgument = positionalArguments.shift();
if (nextPositionalArgument !== void 0) {
parsedArgsProxy[arg.name] = nextPositionalArgument;
} else if (arg.default === void 0 && arg.required !== false) {
throw new CLIError(
`Missing required positional argument: ${arg.name.toUpperCase()}`,
"EARG"
);
} else {
parsedArgsProxy[arg.name] = arg.default;
}
} else if (arg.required && parsedArgsProxy[arg.name] === void 0) {
throw new CLIError(`Missing required argument: --${arg.name}`, "EARG");
}
}
return parsedArgsProxy;
}
function resolveArgs(argsDef) {
const args = [];
for (const [name, argDef] of Object.entries(argsDef || {})) {
args.push({
...argDef,
name,
alias: toArray(argDef.alias)
});
}
return args;
}
function defineCommand(def) {
return def;
}
async function runCommand(cmd, opts) {
const cmdArgs = await resolveValue(cmd.args || {});
const parsedArgs = parseArgs(opts.rawArgs, cmdArgs);
const context = {
rawArgs: opts.rawArgs,
args: parsedArgs,
data: opts.data,
cmd
};
if (typeof cmd.setup === "function") {
await cmd.setup(context);
}
let result;
try {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = opts.rawArgs.findIndex(
(arg) => !arg.startsWith("-")
);
const subCommandName = opts.rawArgs[subCommandArgIndex];
if (subCommandName) {
if (!subCommands[subCommandName]) {
throw new CLIError(
`Unknown command \`${subCommandName}\``,
"E_UNKNOWN_COMMAND"
);
}
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) {
await runCommand(subCommand, {
rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1)
});
}
} else if (!cmd.run) {
throw new CLIError(`No command specified.`, "E_NO_COMMAND");
}
}
if (typeof cmd.run === "function") {
result = await cmd.run(context);
}
} finally {
if (typeof cmd.cleanup === "function") {
await cmd.cleanup(context);
}
}
return { result };
}
async function resolveSubCommand(cmd, rawArgs, parent) {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = rawArgs.findIndex((arg) => !arg.startsWith("-"));
const subCommandName = rawArgs[subCommandArgIndex];
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) {
return resolveSubCommand(
subCommand,
rawArgs.slice(subCommandArgIndex + 1),
cmd
);
}
}
return [cmd, parent];
}
async function showUsage(cmd, parent) {
try {
consola.log(await renderUsage(cmd, parent) + "\n");
} catch (error) {
consola.error(error);
}
}
async function renderUsage(cmd, parent) {
const cmdMeta = await resolveValue(cmd.meta || {});
const cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));
const parentMeta = await resolveValue(parent?.meta || {});
const commandName = `${parentMeta.name ? `${parentMeta.name} ` : ""}` + (cmdMeta.name || process.argv[1]);
const argLines = [];
const posLines = [];
const commandsLines = [];
const usageLine = [];
for (const arg of cmdArgs) {
if (arg.type === "positional") {
const name = arg.name.toUpperCase();
const isRequired = arg.required !== false && arg.default === void 0;
const defaultHint = arg.default ? `="${arg.default}"` : "";
posLines.push([
"`" + name + defaultHint + "`",
arg.description || "",
arg.valueHint ? `<${arg.valueHint}>` : ""
]);
usageLine.push(isRequired ? `<${name}>` : `[${name}]`);
} else {
const isRequired = arg.required === true && arg.default === void 0;
const argStr = (arg.type === "boolean" && arg.default === true ? [
...(arg.alias || []).map((a) => `--no-${a}`),
`--no-${arg.name}`
].join(", ") : [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(
", "
)) + (arg.type === "string" && (arg.valueHint || arg.default) ? `=${arg.valueHint ? `<${arg.valueHint}>` : `"${arg.default || ""}"`}` : "");
argLines.push([
"`" + argStr + (isRequired ? " (required)" : "") + "`",
arg.description || ""
]);
if (isRequired) {
usageLine.push(argStr);
}
}
}
if (cmd.subCommands) {
const commandNames = [];
const subCommands = await resolveValue(cmd.subCommands);
for (const [name, sub] of Object.entries(subCommands)) {
const subCmd = await resolveValue(sub);
const meta = await resolveValue(subCmd?.meta);
commandsLines.push([`\`${name}\``, meta?.description || ""]);
commandNames.push(name);
}
usageLine.push(commandNames.join("|"));
}
const usageLines = [];
const version = cmdMeta.version || parentMeta.version;
usageLines.push(
colors.gray(
`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`
),
""
);
const hasOptions = argLines.length > 0 || posLines.length > 0;
usageLines.push(
`${colors.underline(colors.bold("USAGE"))} \`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}\``,
""
);
if (posLines.length > 0) {
usageLines.push(colors.underline(colors.bold("ARGUMENTS")), "");
usageLines.push(formatLineColumns(posLines, " "));
usageLines.push("");
}
if (argLines.length > 0) {
usageLines.push(colors.underline(colors.bold("OPTIONS")), "");
usageLines.push(formatLineColumns(argLines, " "));
usageLines.push("");
}
if (commandsLines.length > 0) {
usageLines.push(colors.underline(colors.bold("COMMANDS")), "");
usageLines.push(formatLineColumns(commandsLines, " "));
usageLines.push(
"",
`Use \`${commandName} <command> --help\` for more information about a command.`
);
}
return usageLines.filter((l) => typeof l === "string").join("\n");
}
async function runMain(cmd, opts = {}) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
const showUsage$1 = opts.showUsage || showUsage;
try {
if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
const meta = typeof cmd.meta === "function" ? await cmd.meta() : await cmd.meta;
if (!meta?.version) {
throw new CLIError("No version specified", "E_NO_VERSION");
}
consola.log(meta.version);
} else {
await runCommand(cmd, { rawArgs });
}
} catch (error) {
const isCLIError = error instanceof CLIError;
if (!isCLIError) {
consola.error(error, "\n");
}
if (isCLIError) {
await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
}
consola.error(error.message);
process.exit(1);
}
}
const main = defineCommand({
meta: {
name: "nitro",
description: "Nitro CLI",
version: version
},
subCommands: {
dev: () => import('./dev.mjs').then((r) => r.default),
build: () => import('./build.mjs').then((r) => r.default),
prepare: () => import('./prepare.mjs').then((r) => r.default),
task: () => import('./index2.mjs').then((r) => r.default)
}
});
runMain(main);
export { defineCommand as d };
//#endregion
export { };

@@ -627,3 +627,3 @@ import {

font-size: 15px;
overflow-x: scroll;
overflow-x: auto;
position:relative;

@@ -630,0 +630,0 @@ z-index:99999;

{
"name": "@poppinss/dumper",
"version": "0.6.4",
"version": "0.6.5",
"description": "Pretty print JavaScript data types in the terminal and the browser",

@@ -5,0 +5,0 @@ "main": "build/index.js",

@@ -334,3 +334,3 @@ import { keysOf } from './utilities.js';

export function isClass(value) {
return isFunction(value) && value.toString().startsWith('class ');
return isFunction(value) && /^class(\s+|{)/.test(value.toString());
}

@@ -337,0 +337,0 @@ export function isDataView(value) {

{
"name": "@sindresorhus/is",
"version": "7.1.0",
"version": "7.1.1",
"description": "Type check values",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -1,4 +0,4 @@

var Xt=Object.defineProperty;var w=t=>e=>{var s=t[e];if(s)return s();throw new Error("Module not found in bundle: "+e)};var a=(t,e)=>()=>(t&&(e=t(t=0)),e);var p=(t,e)=>{for(var s in e)Xt(t,s,{get:e[s],enumerable:!0})};var P={};p(P,{default:()=>Wt});var Wt,F=a(()=>{Wt=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var $={};p($,{default:()=>T});var M,T,f=a(()=>{M={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},T=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[M]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},M]});var v={};p(v,{default:()=>jt});var jt,B=a(()=>{jt=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var G={};p(G,{default:()=>Kt});var Kt,H=a(()=>{Kt=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var k={};p(k,{default:()=>Vt});var Vt,_=a(()=>{Vt=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var z={};p(z,{default:()=>qt});var qt,Y=a(()=>{qt=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var Z={};p(Z,{default:()=>I});var I,N=a(()=>{I=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var X={};p(X,{default:()=>Qt});var Qt,W=a(()=>{f();Qt=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...T]});var j={};p(j,{default:()=>Jt});var Jt,K=a(()=>{N();Jt=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...I,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var V={};p(V,{default:()=>te});var te,q=a(()=>{te=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var J={};p(J,{default:()=>A,name:()=>E,properties:()=>l,xmlElement:()=>o});var Q,ee,E,l,o,A,R=a(()=>{Q=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",ee=Q+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",E=`[${Q}][${ee}]*`,l=`\\s*(\\s+${E}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,o={match:RegExp(`<[/!?]?${E}${l}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${E}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(E,"g")}]},A=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},o,{type:"str",match:RegExp(`<\\?${E}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${E}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var tt={};p(tt,{default:()=>ae});var ae,et=a(()=>{R();ae=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${l}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},o]},{match:RegExp(`<script${l}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},o]},...A]});var pe,u,d=a(()=>{pe=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],u=t=>pe.map(([e,...s])=>[e,s.reduce((c,[m,n])=>c+[...t.matchAll(m)].length*n,0)]).filter(([e,s])=>s>20).sort((e,s)=>s[1]-e[1])[0]?.[0]||"plain"});var at={};p(at,{default:()=>se});var se,pt=a(()=>{d();se=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:u}]});var st={};p(st,{default:()=>ce});var ce,ct=a(()=>{ce=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var nt={};p(nt,{default:()=>ne});var ne,mt=a(()=>{ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var rt={};p(rt,{default:()=>O});var O,L=a(()=>{O=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ot={};p(ot,{default:()=>me,type:()=>re});var me,re,Et=a(()=>{me=[{match:new class{exec(t){let e=this.lastIndex,s,c=m=>{for(;++e<t.length-2;)if(t[e]=="{")c();else if(t[e]=="}")return};for(;e<t.length;++e)if(t[e-1]!="\\"&&t[e]=="$"&&t[e+1]=="{")return s=e++,c(e),this.lastIndex=e+1,{index:s,0:t.slice(s,e+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],re="str"});var lt={};p(lt,{default:()=>x,type:()=>oe});var x,oe,S=a(()=>{x=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],oe="cmnt"});var ut={};p(ut,{default:()=>Ee,type:()=>le});var Ee,le,ht=a(()=>{S();Ee=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...x],le="cmnt"});var it={};p(it,{default:()=>ue});var ue,gt=a(()=>{ue=[{type:"var",match:/("|')?[a-zA-Z]\w*\1(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var dt={};p(dt,{default:()=>C});var C,D=a(()=>{d();C=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:t=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:t.split(`
`)[0].slice(3)||u(t)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/_[^_]*_|\*[^*]*\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"oper",match:/\[[^\]]*]/g},{type:"func",match:/\([^)]*\)/g}]});var bt={};p(bt,{default:()=>he});var he,yt=a(()=>{D();d();he=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:u}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:u}]},...C]});var Tt={};p(Tt,{default:()=>ie});var ie,ft=a(()=>{ie=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var It={};p(It,{default:()=>ge});var ge,Nt=a(()=>{ge=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var At={};p(At,{default:()=>de});var de,Rt=a(()=>{de=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Ot={};p(Ot,{default:()=>be});var be,Lt=a(()=>{be=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var xt={};p(xt,{default:()=>ye});var ye,St=a(()=>{ye=[{expand:"strDouble"}]});var Ct={};p(Ct,{default:()=>Te});var Te,Dt=a(()=>{Te=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*\()/g},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var wt={};p(wt,{default:()=>fe,type:()=>Ie});var fe,Ie,Ut=a(()=>{fe=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ie="oper"});var Pt={};p(Pt,{default:()=>Ne});var Ne,Ft=a(()=>{Ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var Mt={};p(Mt,{default:()=>Ae});var Ae,$t=a(()=>{Ae=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var vt={};p(vt,{default:()=>Re});var Re,Bt=a(()=>{Re=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Gt={};p(Gt,{default:()=>Oe});var Oe,Ht=a(()=>{L();Oe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...O]});var kt={};p(kt,{default:()=>Le});var Le,_t=a(()=>{Le=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var zt={};p(zt,{default:()=>xe});var xe,Yt=a(()=>{xe=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var U={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var Se=w({"./languages/asm.js":()=>Promise.resolve().then(()=>(F(),P)),"./languages/bash.js":()=>Promise.resolve().then(()=>(f(),$)),"./languages/bf.js":()=>Promise.resolve().then(()=>(B(),v)),"./languages/c.js":()=>Promise.resolve().then(()=>(H(),G)),"./languages/css.js":()=>Promise.resolve().then(()=>(_(),k)),"./languages/csv.js":()=>Promise.resolve().then(()=>(Y(),z)),"./languages/diff.js":()=>Promise.resolve().then(()=>(N(),Z)),"./languages/docker.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/git.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/go.js":()=>Promise.resolve().then(()=>(q(),V)),"./languages/html.js":()=>Promise.resolve().then(()=>(et(),tt)),"./languages/http.js":()=>Promise.resolve().then(()=>(pt(),at)),"./languages/ini.js":()=>Promise.resolve().then(()=>(ct(),st)),"./languages/java.js":()=>Promise.resolve().then(()=>(mt(),nt)),"./languages/js.js":()=>Promise.resolve().then(()=>(L(),rt)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(Et(),ot)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(ht(),ut)),"./languages/json.js":()=>Promise.resolve().then(()=>(gt(),it)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/log.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Nt(),It)),"./languages/make.js":()=>Promise.resolve().then(()=>(Rt(),At)),"./languages/md.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/pl.js":()=>Promise.resolve().then(()=>(Lt(),Ot)),"./languages/plain.js":()=>Promise.resolve().then(()=>(St(),xt)),"./languages/py.js":()=>Promise.resolve().then(()=>(Dt(),Ct)),"./languages/regex.js":()=>Promise.resolve().then(()=>(Ut(),wt)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Ft(),Pt)),"./languages/sql.js":()=>Promise.resolve().then(()=>($t(),Mt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(S(),lt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(Bt(),vt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Ht(),Gt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(_t(),kt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(R(),J)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Yt(),zt))});var b={},Ce=(t="")=>t.replaceAll("&","&#38;").replaceAll?.("<","&lt;").replaceAll?.(">","&gt;"),De=(t,e)=>e?`<span class="shj-syn-${e}">${t}</span>`:t;async function Zt(t,e,s){try{let c,m,n={},i,r=[],h=0,y=typeof e=="string"?await(b[e]??(b[e]=Se(`./languages/${e}.js`))):e,g=[...typeof e=="string"?y.default:e.sub];for(;h<t.length;){for(n.index=null,c=g.length;c-- >0;){if(m=g[c].expand?U[g[c].expand]:g[c],r[c]===void 0||r[c].match.index<h){if(m.match.lastIndex=h,i=m.match.exec(t),i===null){g.splice(c,1),r.splice(c,1);continue}r[c]={match:i,lastIndex:m.match.lastIndex}}r[c].match[0]&&(r[c].match.index<=n.index||n.index===null)&&(n={part:m,index:r[c].match.index,match:r[c].match[0],end:r[c].lastIndex})}if(n.index===null)break;s(t.slice(h,n.index),y.type),h=n.end,n.part.sub?await Zt(n.match,typeof n.part.sub=="string"?n.part.sub:typeof n.part.sub=="function"?n.part.sub(n.match):n.part,s):s(n.match,n.part.type)}s(t.slice(h,t.length),y.type)}catch{s(t)}}async function we(t,e,s=!0,c={}){let m="";return await Zt(t,e,(n,i)=>m+=De(Ce(n),i)),s?`<div><div class="shj-numbers">${"<div></div>".repeat(!c.hideLineNumbers&&t.split(`
var Xt=Object.defineProperty;var w=t=>e=>{var s=t[e];if(s)return s();throw new Error("Module not found in bundle: "+e)};var a=(t,e)=>()=>(t&&(e=t(t=0)),e);var p=(t,e)=>{for(var s in e)Xt(t,s,{get:e[s],enumerable:!0})};var P={};p(P,{default:()=>Wt});var Wt,F=a(()=>{Wt=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var $={};p($,{default:()=>T});var M,T,f=a(()=>{M={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},T=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[M]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},M]});var v={};p(v,{default:()=>jt});var jt,B=a(()=>{jt=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var G={};p(G,{default:()=>Kt});var Kt,H=a(()=>{Kt=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var k={};p(k,{default:()=>Vt});var Vt,z=a(()=>{Vt=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var _={};p(_,{default:()=>qt});var qt,Y=a(()=>{qt=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var Z={};p(Z,{default:()=>I});var I,N=a(()=>{I=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var X={};p(X,{default:()=>Qt});var Qt,W=a(()=>{f();Qt=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...T]});var j={};p(j,{default:()=>Jt});var Jt,K=a(()=>{N();Jt=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...I,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var V={};p(V,{default:()=>te});var te,q=a(()=>{te=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var J={};p(J,{default:()=>A,name:()=>E,properties:()=>l,xmlElement:()=>o});var Q,ee,E,l,o,A,R=a(()=>{Q=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",ee=Q+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",E=`[${Q}][${ee}]*`,l=`\\s*(\\s+${E}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,o={match:RegExp(`<[/!?]?${E}${l}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${E}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(E,"g")}]},A=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},o,{type:"str",match:RegExp(`<\\?${E}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${E}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var tt={};p(tt,{default:()=>ae});var ae,et=a(()=>{R();ae=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${l}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},o]},{match:RegExp(`<script${l}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},o]},...A]});var pe,u,d=a(()=>{pe=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],u=t=>pe.map(([e,...s])=>[e,s.reduce((c,[m,n])=>c+[...t.matchAll(m)].length*n,0)]).filter(([e,s])=>s>20).sort((e,s)=>s[1]-e[1])[0]?.[0]||"plain"});var at={};p(at,{default:()=>se});var se,pt=a(()=>{d();se=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:u}]});var st={};p(st,{default:()=>ce});var ce,ct=a(()=>{ce=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var nt={};p(nt,{default:()=>ne});var ne,mt=a(()=>{ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var rt={};p(rt,{default:()=>O});var O,L=a(()=>{O=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ot={};p(ot,{default:()=>me,type:()=>re});var me,re,Et=a(()=>{me=[{match:new class{exec(t){let e=this.lastIndex,s,c=m=>{for(;++e<t.length-2;)if(t[e]=="{")c();else if(t[e]=="}")return};for(;e<t.length;++e)if(t[e-1]!="\\"&&t[e]=="$"&&t[e+1]=="{")return s=e++,c(e),this.lastIndex=e+1,{index:s,0:t.slice(s,e+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],re="str"});var lt={};p(lt,{default:()=>x,type:()=>oe});var x,oe,S=a(()=>{x=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],oe="cmnt"});var ut={};p(ut,{default:()=>Ee,type:()=>le});var Ee,le,ht=a(()=>{S();Ee=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...x],le="cmnt"});var it={};p(it,{default:()=>ue});var ue,gt=a(()=>{ue=[{type:"var",match:/(("|')((?!\2)[^\r\n\\]|\\[^])*\2|[a-zA-Z]\w*)(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var dt={};p(dt,{default:()=>C});var C,D=a(()=>{d();C=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:t=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:t.split(`
`)[0].slice(3)||u(t)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var bt={};p(bt,{default:()=>he});var he,yt=a(()=>{D();d();he=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:u}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:u}]},...C]});var Tt={};p(Tt,{default:()=>ie});var ie,ft=a(()=>{ie=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var It={};p(It,{default:()=>ge});var ge,Nt=a(()=>{ge=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var At={};p(At,{default:()=>de});var de,Rt=a(()=>{de=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Ot={};p(Ot,{default:()=>be});var be,Lt=a(()=>{be=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var xt={};p(xt,{default:()=>ye});var ye,St=a(()=>{ye=[{expand:"strDouble"}]});var Ct={};p(Ct,{default:()=>Te});var Te,Dt=a(()=>{Te=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var wt={};p(wt,{default:()=>fe,type:()=>Ie});var fe,Ie,Ut=a(()=>{fe=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ie="oper"});var Pt={};p(Pt,{default:()=>Ne});var Ne,Ft=a(()=>{Ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var Mt={};p(Mt,{default:()=>Ae});var Ae,$t=a(()=>{Ae=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var vt={};p(vt,{default:()=>Re});var Re,Bt=a(()=>{Re=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Gt={};p(Gt,{default:()=>Oe});var Oe,Ht=a(()=>{L();Oe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...O]});var kt={};p(kt,{default:()=>Le});var Le,zt=a(()=>{Le=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var _t={};p(_t,{default:()=>xe});var xe,Yt=a(()=>{xe=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var U={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var Se=w({"./languages/asm.js":()=>Promise.resolve().then(()=>(F(),P)),"./languages/bash.js":()=>Promise.resolve().then(()=>(f(),$)),"./languages/bf.js":()=>Promise.resolve().then(()=>(B(),v)),"./languages/c.js":()=>Promise.resolve().then(()=>(H(),G)),"./languages/css.js":()=>Promise.resolve().then(()=>(z(),k)),"./languages/csv.js":()=>Promise.resolve().then(()=>(Y(),_)),"./languages/diff.js":()=>Promise.resolve().then(()=>(N(),Z)),"./languages/docker.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/git.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/go.js":()=>Promise.resolve().then(()=>(q(),V)),"./languages/html.js":()=>Promise.resolve().then(()=>(et(),tt)),"./languages/http.js":()=>Promise.resolve().then(()=>(pt(),at)),"./languages/ini.js":()=>Promise.resolve().then(()=>(ct(),st)),"./languages/java.js":()=>Promise.resolve().then(()=>(mt(),nt)),"./languages/js.js":()=>Promise.resolve().then(()=>(L(),rt)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(Et(),ot)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(ht(),ut)),"./languages/json.js":()=>Promise.resolve().then(()=>(gt(),it)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/log.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Nt(),It)),"./languages/make.js":()=>Promise.resolve().then(()=>(Rt(),At)),"./languages/md.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/pl.js":()=>Promise.resolve().then(()=>(Lt(),Ot)),"./languages/plain.js":()=>Promise.resolve().then(()=>(St(),xt)),"./languages/py.js":()=>Promise.resolve().then(()=>(Dt(),Ct)),"./languages/regex.js":()=>Promise.resolve().then(()=>(Ut(),wt)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Ft(),Pt)),"./languages/sql.js":()=>Promise.resolve().then(()=>($t(),Mt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(S(),lt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(Bt(),vt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Ht(),Gt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(zt(),kt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(R(),J)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Yt(),_t))});var b={},Ce=(t="")=>t.replaceAll("&","&#38;").replaceAll?.("<","&lt;").replaceAll?.(">","&gt;"),De=(t,e)=>e?`<span class="shj-syn-${e}">${t}</span>`:t;async function Zt(t,e,s){try{let c,m,n={},i,r=[],h=0,y=typeof e=="string"?await(b[e]??(b[e]=Se(`./languages/${e}.js`))):e,g=[...typeof e=="string"?y.default:e.sub];for(;h<t.length;){for(n.index=null,c=g.length;c-- >0;){if(m=g[c].expand?U[g[c].expand]:g[c],r[c]===void 0||r[c].match.index<h){if(m.match.lastIndex=h,i=m.match.exec(t),i===null){g.splice(c,1),r.splice(c,1);continue}r[c]={match:i,lastIndex:m.match.lastIndex}}r[c].match[0]&&(r[c].match.index<=n.index||n.index===null)&&(n={part:m,index:r[c].match.index,match:r[c].match[0],end:r[c].lastIndex})}if(n.index===null)break;s(t.slice(h,n.index),y.type),h=n.end,n.part.sub?await Zt(n.match,typeof n.part.sub=="string"?n.part.sub:typeof n.part.sub=="function"?n.part.sub(n.match):n.part,s):s(n.match,n.part.type)}s(t.slice(h,t.length),y.type)}catch{s(t)}}async function we(t,e,s=!0,c={}){let m="";return await Zt(t,e,(n,i)=>m+=De(Ce(n),i)),s?`<div><div class="shj-numbers">${"<div></div>".repeat(!c.hideLineNumbers&&t.split(`
`).length)}</div><div>${m}</div></div>`:m}async function Ue(t,e=t.className.match(/shj-lang-([\w-]+)/)?.[1],s,c){let m=t.textContent;s??(s=`${t.tagName=="CODE"?"in":m.split(`
`).length<2?"one":"multi"}line`),t.dataset.lang=e,t.className=`${[...t.classList].filter(n=>!n.startsWith("shj-")).join(" ")} shj-lang-${e} shj-${s}`,t.innerHTML=await we(m,e,s=="multiline",c)}var Ke=async t=>Promise.all(Array.from(document.querySelectorAll('[class*="shj-lang-"]')).map(e=>Ue(e,void 0,void 0,t))),Ve=(t,e)=>{b[t]=e};export{Ke as highlightAll,Ue as highlightElement,we as highlightText,Ve as loadLanguage,Zt as tokenize};

@@ -1,2 +0,2 @@

var te=Object.defineProperty;var d=p=>t=>{var s=p[t];if(s)return s();throw new Error("Module not found in bundle: "+t)};var e=(p,t)=>()=>(p&&(t=p(p=0)),t);var a=(p,t)=>{for(var s in t)te(p,s,{get:t[s],enumerable:!0})};var B={};a(B,{default:()=>ee});var ee,G=e(()=>{ee=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var H={};a(H,{default:()=>I});var k,I,N=e(()=>{k={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},I=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[k]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},k]});var z={};a(z,{default:()=>ae});var ae,_=e(()=>{ae=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var Y={};a(Y,{default:()=>pe});var pe,Z=e(()=>{pe=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var X={};a(X,{default:()=>ne});var ne,W=e(()=>{ne=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var j={};a(j,{default:()=>se});var se,K=e(()=>{se=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var V={};a(V,{default:()=>A});var A,R=e(()=>{A=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var q={};a(q,{default:()=>re});var re,Q=e(()=>{N();re=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...I]});var J={};a(J,{default:()=>ce});var ce,tt=e(()=>{R();ce=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...A,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var et={};a(et,{default:()=>me});var me,at=e(()=>{me=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var nt={};a(nt,{default:()=>O,name:()=>u,properties:()=>E,xmlElement:()=>l});var pt,oe,u,E,l,O,x=e(()=>{pt=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",oe=pt+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",u=`[${pt}][${oe}]*`,E=`\\s*(\\s+${u}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,l={match:RegExp(`<[/!?]?${u}${E}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${u}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(u,"g")}]},O=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},l,{type:"str",match:RegExp(`<\\?${u}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${u}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var st={};a(st,{default:()=>le});var le,rt=e(()=>{x();le=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${E}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},l]},{match:RegExp(`<script${E}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},l]},...O]});var ue,i,b=e(()=>{ue=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],i=p=>ue.map(([t,...s])=>[t,s.reduce((r,[m,c])=>r+[...p.matchAll(m)].length*c,0)]).filter(([t,s])=>s>20).sort((t,s)=>s[1]-t[1])[0]?.[0]||"plain"});var ct={};a(ct,{default:()=>Ee});var Ee,mt=e(()=>{b();Ee=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:i}]});var ot={};a(ot,{default:()=>ie});var ie,lt=e(()=>{ie=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var ut={};a(ut,{default:()=>he});var he,Et=e(()=>{he=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var it={};a(it,{default:()=>L});var L,S=e(()=>{L=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ht={};a(ht,{default:()=>ge,type:()=>de});var ge,de,gt=e(()=>{ge=[{match:new class{exec(p){let t=this.lastIndex,s,r=m=>{for(;++t<p.length-2;)if(p[t]=="{")r();else if(p[t]=="}")return};for(;t<p.length;++t)if(p[t-1]!="\\"&&p[t]=="$"&&p[t+1]=="{")return s=t++,r(t),this.lastIndex=t+1,{index:s,0:p.slice(s,t+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],de="str"});var dt={};a(dt,{default:()=>C,type:()=>be});var C,be,D=e(()=>{C=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],be="cmnt"});var bt={};a(bt,{default:()=>ye,type:()=>Te});var ye,Te,yt=e(()=>{D();ye=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...C],Te="cmnt"});var Tt={};a(Tt,{default:()=>fe});var fe,ft=e(()=>{fe=[{type:"var",match:/("|')?[a-zA-Z]\w*\1(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var It={};a(It,{default:()=>w});var w,U=e(()=>{b();w=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:p=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:p.split(`
`)[0].slice(3)||i(p)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/_[^_]*_|\*[^*]*\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"oper",match:/\[[^\]]*]/g},{type:"func",match:/\([^)]*\)/g}]});var Nt={};a(Nt,{default:()=>Ie});var Ie,At=e(()=>{U();b();Ie=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:i}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:i}]},...w]});var Rt={};a(Rt,{default:()=>Ne});var Ne,Ot=e(()=>{Ne=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var xt={};a(xt,{default:()=>Ae});var Ae,Lt=e(()=>{Ae=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var St={};a(St,{default:()=>Re});var Re,Ct=e(()=>{Re=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Dt={};a(Dt,{default:()=>Oe});var Oe,wt=e(()=>{Oe=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var Ut={};a(Ut,{default:()=>xe});var xe,Pt=e(()=>{xe=[{expand:"strDouble"}]});var Ft={};a(Ft,{default:()=>Le});var Le,Mt=e(()=>{Le=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*\()/g},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var $t={};a($t,{default:()=>Se,type:()=>Ce});var Se,Ce,vt=e(()=>{Se=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ce="oper"});var Bt={};a(Bt,{default:()=>De});var De,Gt=e(()=>{De=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var kt={};a(kt,{default:()=>we});var we,Ht=e(()=>{we=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var zt={};a(zt,{default:()=>Ue});var Ue,_t=e(()=>{Ue=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Yt={};a(Yt,{default:()=>Pe});var Pe,Zt=e(()=>{S();Pe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...L]});var Xt={};a(Xt,{default:()=>Fe});var Fe,Wt=e(()=>{Fe=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var jt={};a(jt,{default:()=>Me});var Me,Kt=e(()=>{Me=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var Vt={};a(Vt,{default:()=>n});var n,y=e(()=>{n={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",gray:"\x1B[90m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"}});var qt={};a(qt,{default:()=>ve});var ve,Qt=e(()=>{y();ve={deleted:n.red,var:n.red,err:n.red,kwd:n.magenta,num:n.yellow,class:n.yellow,cmnt:n.gray,insert:n.green,str:n.green,bool:n.cyan,type:n.blue,oper:n.blue,section:n.magenta,func:n.blue}});var M={};a(M,{default:()=>Be});var Be,$=e(()=>{y();Be={deleted:n.red,var:n.red,err:n.red,kwd:n.red,num:n.yellow,class:n.yellow,cmnt:n.gray,insert:n.green,str:n.green,bool:n.cyan,type:n.blue,oper:n.blue,section:n.magenta,func:n.magenta}});var v={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var $e=d({"./languages/asm.js":()=>Promise.resolve().then(()=>(G(),B)),"./languages/bash.js":()=>Promise.resolve().then(()=>(N(),H)),"./languages/bf.js":()=>Promise.resolve().then(()=>(_(),z)),"./languages/c.js":()=>Promise.resolve().then(()=>(Z(),Y)),"./languages/css.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/csv.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/diff.js":()=>Promise.resolve().then(()=>(R(),V)),"./languages/docker.js":()=>Promise.resolve().then(()=>(Q(),q)),"./languages/git.js":()=>Promise.resolve().then(()=>(tt(),J)),"./languages/go.js":()=>Promise.resolve().then(()=>(at(),et)),"./languages/html.js":()=>Promise.resolve().then(()=>(rt(),st)),"./languages/http.js":()=>Promise.resolve().then(()=>(mt(),ct)),"./languages/ini.js":()=>Promise.resolve().then(()=>(lt(),ot)),"./languages/java.js":()=>Promise.resolve().then(()=>(Et(),ut)),"./languages/js.js":()=>Promise.resolve().then(()=>(S(),it)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(gt(),ht)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/json.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(At(),Nt)),"./languages/log.js":()=>Promise.resolve().then(()=>(Ot(),Rt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Lt(),xt)),"./languages/make.js":()=>Promise.resolve().then(()=>(Ct(),St)),"./languages/md.js":()=>Promise.resolve().then(()=>(U(),It)),"./languages/pl.js":()=>Promise.resolve().then(()=>(wt(),Dt)),"./languages/plain.js":()=>Promise.resolve().then(()=>(Pt(),Ut)),"./languages/py.js":()=>Promise.resolve().then(()=>(Mt(),Ft)),"./languages/regex.js":()=>Promise.resolve().then(()=>(vt(),$t)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Gt(),Bt)),"./languages/sql.js":()=>Promise.resolve().then(()=>(Ht(),kt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(_t(),zt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Zt(),Yt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(Wt(),Xt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(x(),nt)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Kt(),jt))});var P={};async function F(p,t,s){try{let r,m,c={},T,o=[],h=0,f=typeof t=="string"?await(P[t]??(P[t]=$e(`./languages/${t}.js`))):t,g=[...typeof t=="string"?f.default:t.sub];for(;h<p.length;){for(c.index=null,r=g.length;r-- >0;){if(m=g[r].expand?v[g[r].expand]:g[r],o[r]===void 0||o[r].match.index<h){if(m.match.lastIndex=h,T=m.match.exec(p),T===null){g.splice(r,1),o.splice(r,1);continue}o[r]={match:T,lastIndex:m.match.lastIndex}}o[r].match[0]&&(o[r].match.index<=c.index||c.index===null)&&(c={part:m,index:o[r].match.index,match:o[r].match[0],end:o[r].lastIndex})}if(c.index===null)break;s(p.slice(h,c.index),f.type),h=c.end,c.part.sub?await F(c.match,typeof c.part.sub=="string"?c.part.sub:typeof c.part.sub=="function"?c.part.sub(c.match):c.part,s):s(c.match,c.part.type)}s(p.slice(h,p.length),f.type)}catch{s(p)}}var Ge=d({"./themes/atom-dark.js":()=>Promise.resolve().then(()=>(Qt(),qt)),"./themes/default.js":()=>Promise.resolve().then(()=>($(),M)),"./themes/termcolor.js":()=>Promise.resolve().then(()=>(y(),Vt))});var Jt=Promise.resolve().then(()=>($(),M)),ke=async(p,t)=>{let s="",r=(await Jt).default;return await F(p,t,(m,c)=>s+=c?`${r[c]??""}${m}\x1B[0m`:m),s},la=async(p,t)=>console.log(await ke(p,t)),ua=async p=>Jt=Ge(`./themes/${p}.js`);export{ke as highlightText,la as printHighlight,ua as setTheme};
var te=Object.defineProperty;var d=n=>t=>{var s=n[t];if(s)return s();throw new Error("Module not found in bundle: "+t)};var e=(n,t)=>()=>(n&&(t=n(n=0)),t);var a=(n,t)=>{for(var s in t)te(n,s,{get:t[s],enumerable:!0})};var B={};a(B,{default:()=>ee});var ee,G=e(()=>{ee=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var H={};a(H,{default:()=>I});var k,I,N=e(()=>{k={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},I=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[k]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},k]});var z={};a(z,{default:()=>ae});var ae,_=e(()=>{ae=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var Y={};a(Y,{default:()=>ne});var ne,Z=e(()=>{ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var X={};a(X,{default:()=>pe});var pe,W=e(()=>{pe=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var j={};a(j,{default:()=>se});var se,K=e(()=>{se=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var V={};a(V,{default:()=>A});var A,R=e(()=>{A=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var q={};a(q,{default:()=>re});var re,Q=e(()=>{N();re=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...I]});var J={};a(J,{default:()=>ce});var ce,tt=e(()=>{R();ce=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...A,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var et={};a(et,{default:()=>me});var me,at=e(()=>{me=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var pt={};a(pt,{default:()=>O,name:()=>u,properties:()=>E,xmlElement:()=>l});var nt,oe,u,E,l,O,x=e(()=>{nt=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",oe=nt+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",u=`[${nt}][${oe}]*`,E=`\\s*(\\s+${u}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,l={match:RegExp(`<[/!?]?${u}${E}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${u}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(u,"g")}]},O=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},l,{type:"str",match:RegExp(`<\\?${u}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${u}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var st={};a(st,{default:()=>le});var le,rt=e(()=>{x();le=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${E}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},l]},{match:RegExp(`<script${E}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},l]},...O]});var ue,i,b=e(()=>{ue=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],i=n=>ue.map(([t,...s])=>[t,s.reduce((r,[m,c])=>r+[...n.matchAll(m)].length*c,0)]).filter(([t,s])=>s>20).sort((t,s)=>s[1]-t[1])[0]?.[0]||"plain"});var ct={};a(ct,{default:()=>Ee});var Ee,mt=e(()=>{b();Ee=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:i}]});var ot={};a(ot,{default:()=>ie});var ie,lt=e(()=>{ie=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var ut={};a(ut,{default:()=>he});var he,Et=e(()=>{he=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var it={};a(it,{default:()=>L});var L,S=e(()=>{L=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ht={};a(ht,{default:()=>ge,type:()=>de});var ge,de,gt=e(()=>{ge=[{match:new class{exec(n){let t=this.lastIndex,s,r=m=>{for(;++t<n.length-2;)if(n[t]=="{")r();else if(n[t]=="}")return};for(;t<n.length;++t)if(n[t-1]!="\\"&&n[t]=="$"&&n[t+1]=="{")return s=t++,r(t),this.lastIndex=t+1,{index:s,0:n.slice(s,t+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],de="str"});var dt={};a(dt,{default:()=>C,type:()=>be});var C,be,D=e(()=>{C=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],be="cmnt"});var bt={};a(bt,{default:()=>ye,type:()=>Te});var ye,Te,yt=e(()=>{D();ye=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...C],Te="cmnt"});var Tt={};a(Tt,{default:()=>fe});var fe,ft=e(()=>{fe=[{type:"var",match:/(("|')((?!\2)[^\r\n\\]|\\[^])*\2|[a-zA-Z]\w*)(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var It={};a(It,{default:()=>w});var w,U=e(()=>{b();w=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:n=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:n.split(`
`)[0].slice(3)||i(n)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var Nt={};a(Nt,{default:()=>Ie});var Ie,At=e(()=>{U();b();Ie=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:i}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:i}]},...w]});var Rt={};a(Rt,{default:()=>Ne});var Ne,Ot=e(()=>{Ne=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var xt={};a(xt,{default:()=>Ae});var Ae,Lt=e(()=>{Ae=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var St={};a(St,{default:()=>Re});var Re,Ct=e(()=>{Re=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Dt={};a(Dt,{default:()=>Oe});var Oe,wt=e(()=>{Oe=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var Ut={};a(Ut,{default:()=>xe});var xe,Pt=e(()=>{xe=[{expand:"strDouble"}]});var Ft={};a(Ft,{default:()=>Le});var Le,Mt=e(()=>{Le=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var $t={};a($t,{default:()=>Se,type:()=>Ce});var Se,Ce,vt=e(()=>{Se=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ce="oper"});var Bt={};a(Bt,{default:()=>De});var De,Gt=e(()=>{De=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var kt={};a(kt,{default:()=>we});var we,Ht=e(()=>{we=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var zt={};a(zt,{default:()=>Ue});var Ue,_t=e(()=>{Ue=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Yt={};a(Yt,{default:()=>Pe});var Pe,Zt=e(()=>{S();Pe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...L]});var Xt={};a(Xt,{default:()=>Fe});var Fe,Wt=e(()=>{Fe=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var jt={};a(jt,{default:()=>Me});var Me,Kt=e(()=>{Me=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var Vt={};a(Vt,{default:()=>p});var p,y=e(()=>{p={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",gray:"\x1B[90m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"}});var qt={};a(qt,{default:()=>ve});var ve,Qt=e(()=>{y();ve={deleted:p.red,var:p.red,err:p.red,kwd:p.magenta,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.blue}});var M={};a(M,{default:()=>Be});var Be,$=e(()=>{y();Be={deleted:p.red,var:p.red,err:p.red,kwd:p.red,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.magenta}});var v={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var $e=d({"./languages/asm.js":()=>Promise.resolve().then(()=>(G(),B)),"./languages/bash.js":()=>Promise.resolve().then(()=>(N(),H)),"./languages/bf.js":()=>Promise.resolve().then(()=>(_(),z)),"./languages/c.js":()=>Promise.resolve().then(()=>(Z(),Y)),"./languages/css.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/csv.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/diff.js":()=>Promise.resolve().then(()=>(R(),V)),"./languages/docker.js":()=>Promise.resolve().then(()=>(Q(),q)),"./languages/git.js":()=>Promise.resolve().then(()=>(tt(),J)),"./languages/go.js":()=>Promise.resolve().then(()=>(at(),et)),"./languages/html.js":()=>Promise.resolve().then(()=>(rt(),st)),"./languages/http.js":()=>Promise.resolve().then(()=>(mt(),ct)),"./languages/ini.js":()=>Promise.resolve().then(()=>(lt(),ot)),"./languages/java.js":()=>Promise.resolve().then(()=>(Et(),ut)),"./languages/js.js":()=>Promise.resolve().then(()=>(S(),it)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(gt(),ht)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/json.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(At(),Nt)),"./languages/log.js":()=>Promise.resolve().then(()=>(Ot(),Rt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Lt(),xt)),"./languages/make.js":()=>Promise.resolve().then(()=>(Ct(),St)),"./languages/md.js":()=>Promise.resolve().then(()=>(U(),It)),"./languages/pl.js":()=>Promise.resolve().then(()=>(wt(),Dt)),"./languages/plain.js":()=>Promise.resolve().then(()=>(Pt(),Ut)),"./languages/py.js":()=>Promise.resolve().then(()=>(Mt(),Ft)),"./languages/regex.js":()=>Promise.resolve().then(()=>(vt(),$t)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Gt(),Bt)),"./languages/sql.js":()=>Promise.resolve().then(()=>(Ht(),kt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(_t(),zt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Zt(),Yt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(Wt(),Xt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(x(),pt)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Kt(),jt))});var P={};async function F(n,t,s){try{let r,m,c={},T,o=[],h=0,f=typeof t=="string"?await(P[t]??(P[t]=$e(`./languages/${t}.js`))):t,g=[...typeof t=="string"?f.default:t.sub];for(;h<n.length;){for(c.index=null,r=g.length;r-- >0;){if(m=g[r].expand?v[g[r].expand]:g[r],o[r]===void 0||o[r].match.index<h){if(m.match.lastIndex=h,T=m.match.exec(n),T===null){g.splice(r,1),o.splice(r,1);continue}o[r]={match:T,lastIndex:m.match.lastIndex}}o[r].match[0]&&(o[r].match.index<=c.index||c.index===null)&&(c={part:m,index:o[r].match.index,match:o[r].match[0],end:o[r].lastIndex})}if(c.index===null)break;s(n.slice(h,c.index),f.type),h=c.end,c.part.sub?await F(c.match,typeof c.part.sub=="string"?c.part.sub:typeof c.part.sub=="function"?c.part.sub(c.match):c.part,s):s(c.match,c.part.type)}s(n.slice(h,n.length),f.type)}catch{s(n)}}var Ge=d({"./themes/atom-dark.js":()=>Promise.resolve().then(()=>(Qt(),qt)),"./themes/default.js":()=>Promise.resolve().then(()=>($(),M)),"./themes/termcolor.js":()=>Promise.resolve().then(()=>(y(),Vt))});var Jt=Promise.resolve().then(()=>($(),M)),ke=async(n,t)=>{let s="",r=(await Jt).default;return await F(n,t,(m,c)=>s+=c?`${r[c]??""}${m}\x1B[0m`:m),s},la=async(n,t)=>console.log(await ke(n,t)),ua=async n=>Jt=Ge(`./themes/${n}.js`);export{ke as highlightText,la as printHighlight,ua as setTheme};
{
"name": "@speed-highlight/core",
"version": "1.2.7",
"version": "1.2.12",
"description": "🌈 Light, fast, and easy to use, dependencies free javascript syntax highlighter, with automatic language detection",

@@ -51,3 +51,7 @@ "main": "./dist/index.js",

],
"author": "matubu",
"author": {
"name": "matubu",
"email": "hi@mathias.ninja",
"url": "https://mathias.ninja"
},
"license": "CC0-1.0",

@@ -57,3 +61,3 @@ "homepage": "https://github.com/speed-highlight/core#readme",

"@semantic-release/git": "^10.0.1",
"esbuild": "^0.21.5",
"esbuild": "^0.25.0",
"lightningcss-cli": "^1.25.1",

@@ -60,0 +64,0 @@ "semantic-release": "^24.0.0",

@@ -0,290 +1,267 @@

//#region src/utils.ts
function flatHooks(configHooks, hooks = {}, parentName) {
for (const key in configHooks) {
const subHook = configHooks[key];
const name = parentName ? `${parentName}:${key}` : key;
if (typeof subHook === "object" && subHook !== null) {
flatHooks(subHook, hooks, name);
} else if (typeof subHook === "function") {
hooks[name] = subHook;
}
}
return hooks;
for (const key in configHooks) {
const subHook = configHooks[key];
const name = parentName ? `${parentName}:${key}` : key;
if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks, name);
else if (typeof subHook === "function") hooks[name] = subHook;
}
return hooks;
}
function mergeHooks(...hooks) {
const finalHooks = {};
for (const hook of hooks) {
const flatenHook = flatHooks(hook);
for (const key in flatenHook) {
if (finalHooks[key]) {
finalHooks[key].push(flatenHook[key]);
} else {
finalHooks[key] = [flatenHook[key]];
}
}
}
for (const key in finalHooks) {
if (finalHooks[key].length > 1) {
const array = finalHooks[key];
finalHooks[key] = (...arguments_) => serial(array, (function_) => function_(...arguments_));
} else {
finalHooks[key] = finalHooks[key][0];
}
}
return finalHooks;
const finalHooks = {};
for (const hook of hooks) {
const flatenHook = flatHooks(hook);
for (const key in flatenHook) if (finalHooks[key]) finalHooks[key].push(flatenHook[key]);
else finalHooks[key] = [flatenHook[key]];
}
for (const key in finalHooks) if (finalHooks[key].length > 1) {
const array = finalHooks[key];
finalHooks[key] = (...arguments_) => serial(array, (function_) => function_(...arguments_));
} else finalHooks[key] = finalHooks[key][0];
return finalHooks;
}
function serial(tasks, function_) {
return tasks.reduce(
(promise, task) => promise.then(() => function_(task)),
Promise.resolve()
);
return tasks.reduce((promise, task) => promise.then(() => function_(task)), Promise.resolve());
}
const defaultTask = { run: (function_) => function_() };
const _createTask = () => defaultTask;
const createTask = typeof console.createTask !== "undefined" ? console.createTask : _createTask;
const createTask = /* @__PURE__ */ (() => {
if (console.createTask) return console.createTask;
const defaultTask = { run: (fn) => fn() };
return () => defaultTask;
})();
function callHooks(hooks, args, startIndex, task) {
for (let i = startIndex; i < hooks.length; i += 1) try {
const result = task ? task.run(() => hooks[i](...args)) : hooks[i](...args);
if (result instanceof Promise) return result.then(() => callHooks(hooks, args, i + 1, task));
} catch (error) {
return Promise.reject(error);
}
}
function serialTaskCaller(hooks, args) {
const name = args.shift();
const task = createTask(name);
return hooks.reduce(
(promise, hookFunction) => promise.then(() => task.run(() => hookFunction(...args))),
Promise.resolve()
);
if (hooks.length > 0) return callHooks(hooks, args, 0, createTask(args.shift()));
}
function parallelTaskCaller(hooks, args) {
const name = args.shift();
const task = createTask(name);
return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
if (hooks.length > 0) {
const task = createTask(args.shift());
return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
}
}
/** @deprecated */
function serialCaller(hooks, arguments_) {
return hooks.reduce(
(promise, hookFunction) => promise.then(() => hookFunction(...arguments_ || [])),
Promise.resolve()
);
return hooks.reduce((promise, hookFunction) => promise.then(() => hookFunction(...arguments_ || [])), Promise.resolve());
}
/** @deprecated */
function parallelCaller(hooks, args) {
return Promise.all(hooks.map((hook) => hook(...args || [])));
return Promise.all(hooks.map((hook) => hook(...args || [])));
}
function callEachWith(callbacks, arg0) {
for (const callback of [...callbacks]) {
callback(arg0);
}
for (const callback of [...callbacks]) callback(arg0);
}
class Hookable {
constructor() {
this._hooks = {};
this._before = void 0;
this._after = void 0;
this._deprecatedMessages = void 0;
this._deprecatedHooks = {};
this.hook = this.hook.bind(this);
this.callHook = this.callHook.bind(this);
this.callHookWith = this.callHookWith.bind(this);
}
hook(name, function_, options = {}) {
if (!name || typeof function_ !== "function") {
return () => {
};
}
const originalName = name;
let dep;
while (this._deprecatedHooks[name]) {
dep = this._deprecatedHooks[name];
name = dep.to;
}
if (dep && !options.allowDeprecated) {
let message = dep.message;
if (!message) {
message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
}
if (!this._deprecatedMessages) {
this._deprecatedMessages = /* @__PURE__ */ new Set();
}
if (!this._deprecatedMessages.has(message)) {
console.warn(message);
this._deprecatedMessages.add(message);
}
}
if (!function_.name) {
try {
Object.defineProperty(function_, "name", {
get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
configurable: true
});
} catch {
}
}
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(function_);
return () => {
if (function_) {
this.removeHook(name, function_);
function_ = void 0;
}
};
}
hookOnce(name, function_) {
let _unreg;
let _function = (...arguments_) => {
if (typeof _unreg === "function") {
_unreg();
}
_unreg = void 0;
_function = void 0;
return function_(...arguments_);
};
_unreg = this.hook(name, _function);
return _unreg;
}
removeHook(name, function_) {
if (this._hooks[name]) {
const index = this._hooks[name].indexOf(function_);
if (index !== -1) {
this._hooks[name].splice(index, 1);
}
if (this._hooks[name].length === 0) {
delete this._hooks[name];
}
}
}
deprecateHook(name, deprecated) {
this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
const _hooks = this._hooks[name] || [];
delete this._hooks[name];
for (const hook of _hooks) {
this.hook(name, hook);
}
}
deprecateHooks(deprecatedHooks) {
Object.assign(this._deprecatedHooks, deprecatedHooks);
for (const name in deprecatedHooks) {
this.deprecateHook(name, deprecatedHooks[name]);
}
}
addHooks(configHooks) {
const hooks = flatHooks(configHooks);
const removeFns = Object.keys(hooks).map(
(key) => this.hook(key, hooks[key])
);
return () => {
for (const unreg of removeFns.splice(0, removeFns.length)) {
unreg();
}
};
}
removeHooks(configHooks) {
const hooks = flatHooks(configHooks);
for (const key in hooks) {
this.removeHook(key, hooks[key]);
}
}
removeAllHooks() {
for (const key in this._hooks) {
delete this._hooks[key];
}
}
callHook(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(serialTaskCaller, name, ...arguments_);
}
callHookParallel(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(parallelTaskCaller, name, ...arguments_);
}
callHookWith(caller, name, ...arguments_) {
const event = this._before || this._after ? { name, args: arguments_, context: {} } : void 0;
if (this._before) {
callEachWith(this._before, event);
}
const result = caller(
name in this._hooks ? [...this._hooks[name]] : [],
arguments_
);
if (result instanceof Promise) {
return result.finally(() => {
if (this._after && event) {
callEachWith(this._after, event);
}
});
}
if (this._after && event) {
callEachWith(this._after, event);
}
return result;
}
beforeEach(function_) {
this._before = this._before || [];
this._before.push(function_);
return () => {
if (this._before !== void 0) {
const index = this._before.indexOf(function_);
if (index !== -1) {
this._before.splice(index, 1);
}
}
};
}
afterEach(function_) {
this._after = this._after || [];
this._after.push(function_);
return () => {
if (this._after !== void 0) {
const index = this._after.indexOf(function_);
if (index !== -1) {
this._after.splice(index, 1);
}
}
};
}
}
//#endregion
//#region src/hookable.ts
var Hookable = class {
_hooks;
_before;
_after;
_deprecatedHooks;
_deprecatedMessages;
constructor() {
this._hooks = {};
this._before = void 0;
this._after = void 0;
this._deprecatedMessages = void 0;
this._deprecatedHooks = {};
this.hook = this.hook.bind(this);
this.callHook = this.callHook.bind(this);
this.callHookWith = this.callHookWith.bind(this);
}
hook(name, function_, options = {}) {
if (!name || typeof function_ !== "function") return () => {};
const originalName = name;
let dep;
while (this._deprecatedHooks[name]) {
dep = this._deprecatedHooks[name];
name = dep.to;
}
if (dep && !options.allowDeprecated) {
let message = dep.message;
if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
if (!this._deprecatedMessages.has(message)) {
console.warn(message);
this._deprecatedMessages.add(message);
}
}
if (!function_.name) try {
Object.defineProperty(function_, "name", {
get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
configurable: true
});
} catch {}
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(function_);
return () => {
if (function_) {
this.removeHook(name, function_);
function_ = void 0;
}
};
}
hookOnce(name, function_) {
let _unreg;
let _function = (...arguments_) => {
if (typeof _unreg === "function") _unreg();
_unreg = void 0;
_function = void 0;
return function_(...arguments_);
};
_unreg = this.hook(name, _function);
return _unreg;
}
removeHook(name, function_) {
const hooks = this._hooks[name];
if (hooks) {
const index = hooks.indexOf(function_);
if (index !== -1) hooks.splice(index, 1);
if (hooks.length === 0) this._hooks[name] = void 0;
}
}
deprecateHook(name, deprecated) {
this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
const _hooks = this._hooks[name] || [];
this._hooks[name] = void 0;
for (const hook of _hooks) this.hook(name, hook);
}
deprecateHooks(deprecatedHooks) {
for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
}
addHooks(configHooks) {
const hooks = flatHooks(configHooks);
const removeFns = Object.keys(hooks).map((key) => this.hook(key, hooks[key]));
return () => {
for (const unreg of removeFns) unreg();
removeFns.length = 0;
};
}
removeHooks(configHooks) {
const hooks = flatHooks(configHooks);
for (const key in hooks) this.removeHook(key, hooks[key]);
}
removeAllHooks() {
this._hooks = {};
}
callHook(name, ...args) {
return this.callHookWith(serialTaskCaller, name, args);
}
callHookParallel(name, ...args) {
return this.callHookWith(parallelTaskCaller, name, args);
}
callHookWith(caller, name, args) {
const event = this._before || this._after ? {
name,
args,
context: {}
} : void 0;
if (this._before) callEachWith(this._before, event);
const _args = args?.length ? [name, ...args] : [name];
const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], _args);
if (result instanceof Promise) return result.finally(() => {
if (this._after && event) callEachWith(this._after, event);
});
if (this._after && event) callEachWith(this._after, event);
return result;
}
beforeEach(function_) {
this._before = this._before || [];
this._before.push(function_);
return () => {
if (this._before !== void 0) {
const index = this._before.indexOf(function_);
if (index !== -1) this._before.splice(index, 1);
}
};
}
afterEach(function_) {
this._after = this._after || [];
this._after.push(function_);
return () => {
if (this._after !== void 0) {
const index = this._after.indexOf(function_);
if (index !== -1) this._after.splice(index, 1);
}
};
}
};
function createHooks() {
return new Hookable();
return new Hookable();
}
var HookableCore = class {
_hooks;
constructor() {
this._hooks = {};
}
hook(name, fn) {
if (!name || typeof fn !== "function") return () => {};
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(fn);
return () => {
if (fn) {
this.removeHook(name, fn);
fn = void 0;
}
};
}
removeHook(name, function_) {
const hooks = this._hooks[name];
if (hooks) {
const index = hooks.indexOf(function_);
if (index !== -1) hooks.splice(index, 1);
if (hooks.length === 0) this._hooks[name] = void 0;
}
}
callHook(name, ...args) {
const hooks = this._hooks[name];
if (!hooks || hooks.length === 0) return;
return callHooks(hooks, args, 0);
}
};
//#endregion
//#region src/debugger.ts
const isBrowser = typeof window !== "undefined";
/** Start debugging hook names and timing in console */
function createDebugger(hooks, _options = {}) {
const options = {
inspect: isBrowser,
group: isBrowser,
filter: () => true,
..._options
};
const _filter = options.filter;
const filter = typeof _filter === "string" ? (name) => name.startsWith(_filter) : _filter;
const _tag = options.tag ? `[${options.tag}] ` : "";
const logPrefix = (event) => _tag + event.name + "".padEnd(event._id, "\0");
const _idCtr = {};
const unsubscribeBefore = hooks.beforeEach((event) => {
if (filter !== void 0 && !filter(event.name)) {
return;
}
_idCtr[event.name] = _idCtr[event.name] || 0;
event._id = _idCtr[event.name]++;
console.time(logPrefix(event));
});
const unsubscribeAfter = hooks.afterEach((event) => {
if (filter !== void 0 && !filter(event.name)) {
return;
}
if (options.group) {
console.groupCollapsed(event.name);
}
if (options.inspect) {
console.timeLog(logPrefix(event), event.args);
} else {
console.timeEnd(logPrefix(event));
}
if (options.group) {
console.groupEnd();
}
_idCtr[event.name]--;
});
return {
/** Stop debugging and remove listeners */
close: () => {
unsubscribeBefore();
unsubscribeAfter();
}
};
const options = {
inspect: isBrowser,
group: isBrowser,
filter: () => true,
..._options
};
const _filter = options.filter;
const filter = typeof _filter === "string" ? (name) => name.startsWith(_filter) : _filter;
const _tag = options.tag ? `[${options.tag}] ` : "";
const logPrefix = (event) => _tag + event.name + "".padEnd(event._id, "\0");
const _idCtr = {};
const unsubscribeBefore = hooks.beforeEach((event) => {
if (filter !== void 0 && !filter(event.name)) return;
_idCtr[event.name] = _idCtr[event.name] || 0;
event._id = _idCtr[event.name]++;
console.time(logPrefix(event));
});
const unsubscribeAfter = hooks.afterEach((event) => {
if (filter !== void 0 && !filter(event.name)) return;
if (options.group) console.groupCollapsed(event.name);
if (options.inspect) console.timeLog(logPrefix(event), event.args);
else console.timeEnd(logPrefix(event));
if (options.group) console.groupEnd();
_idCtr[event.name]--;
});
return { close: () => {
unsubscribeBefore();
unsubscribeAfter();
} };
}
export { Hookable, createDebugger, createHooks, flatHooks, mergeHooks, parallelCaller, serial, serialCaller };
//#endregion
export { Hookable, HookableCore, createDebugger, createHooks, flatHooks, mergeHooks, parallelCaller, serial, serialCaller };
{
"name": "hookable",
"version": "5.5.3",
"version": "6.0.0-rc.1",
"description": "Awaitable hook system",

@@ -14,37 +14,40 @@ "keywords": [

"license": "MIT",
"sideEffects": false,
"type": "module",
"exports": {
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs"
".": "./dist/index.mjs"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"main": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"files": [
"dist"
],
"devDependencies": {
"@types/node": "^18.15.11",
"@vitest/coverage-c8": "^0.29.8",
"changelogen": "^0.5.2",
"eslint": "^8.37.0",
"eslint-config-unjs": "^0.1.0",
"expect-type": "^0.15.0",
"prettier": "^2.8.7",
"typescript": "^5.0.2",
"unbuild": "^1.1.2",
"vite": "^4.2.1",
"vitest": "^0.29.8"
},
"packageManager": "pnpm@8.0.0",
"scripts": {
"build": "unbuild",
"bench": "node --expose-gc --allow-natives-syntax test/bench.ts",
"build": "obuild src/index.ts",
"dev": "vitest",
"lint": "eslint --cache --ext .ts,.js,.mjs,.cjs . && prettier -c src test",
"lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w",
"lint": "eslint --cache . && prettier -c src test",
"lint:fix": "eslint --cache . --fix && prettier -c src test -w",
"prepublish": "pnpm build",
"release": "pnpm test && pnpm build && changelogen --release --push && pnpm publish",
"release": "pnpm test && pnpm build && changelogen --release --prerelease --publish --publishTag rc --push",
"test": "pnpm lint && vitest run --coverage",
"test:types": "tsc --noEmit"
}
},
"devDependencies": {
"@types/node": "^24.9.1",
"@vitest/coverage-v8": "^4.0.3",
"changelogen": "^0.6.2",
"esbuild": "^0.25.11",
"eslint": "^9.38.0",
"eslint-config-unjs": "^0.5.0",
"expect-type": "^1.2.2",
"hookable-prev": "npm:hookable@^5.0.0",
"mitata": "^1.0.34",
"obuild": "^0.3.0",
"prettier": "^3.6.2",
"typescript": "^5.9.3",
"vite": "^7.1.12",
"vitest": "^4.0.3"
},
"packageManager": "pnpm@10.19.0"
}
import {
Layout
} from "./chunk-VE4LENUR.js";
} from "./chunk-F4I6KX4R.js";
import {

@@ -15,3 +15,3 @@ ErrorCause

ErrorStack
} from "./chunk-JAN2TFI2.js";
} from "./chunk-YYEJ3AGB.js";
import {

@@ -30,3 +30,3 @@ ErrorStackSource

// src/youch.ts
import cookie from "cookie";
import { parse } from "cookie-es";
import { ErrorParser } from "youch-core";

@@ -93,2 +93,3 @@

let customInjectedStyles = "";
let globalScript = "";
const styles = [];

@@ -105,6 +106,13 @@ const scripts = [];

this.#scripts.forEach((bucket, name) => {
if (name === "global") {
globalScript = `<script id="${name}-script"${cspNonceAttr}>${bucket}</script>`;
}
scripts.push(`<script id="${name}-script"${cspNonceAttr}>${bucket}</script>`);
});
return { styles: `${styles.join("\n")}
${customInjectedStyles}`, scripts: scripts.join("\n") };
return {
styles: `${styles.join("\n")}
${customInjectedStyles}`,
scripts: scripts.join("\n"),
globalScript
};
}

@@ -199,4 +207,4 @@ /**

});
const { scripts, styles } = this.#getStylesAndScripts(props.cspNonce);
return html.replace("<!-- STYLES -->", styles).replace("<!-- SCRIPTS -->", scripts);
const { globalScript, scripts, styles } = this.#getStylesAndScripts(props.cspNonce);
return html.replace("<!-- STYLES -->", styles).replace("<!-- SCRIPTS -->", scripts).replace("<!-- GLOBAL SCRIPT -->", globalScript);
}

@@ -286,3 +294,3 @@ /**

key,
value: key === "cookie" ? { ...cookie.parse(value) } : value
value: key === "cookie" ? { ...parse(value) } : value
};

@@ -289,0 +297,0 @@ })

@@ -47,29 +47,27 @@ function showFormattedFrames(button) {

onContentLoaded(() => {
document.querySelector('#formatted-frames-toggle').addEventListener('click', function () {
showFormattedFrames(this)
document.querySelector('#formatted-frames-toggle').addEventListener('click', function () {
showFormattedFrames(this)
})
document.querySelector('#raw-frames-toggle').addEventListener('click', function () {
showRawFrames(this)
})
document
.querySelector('#all-frames-toggle input[type="checkbox"]')
.addEventListener('change', function () {
toggleAllFrames()
})
document.querySelector('#raw-frames-toggle').addEventListener('click', function () {
showRawFrames(this)
})
document
.querySelector('#all-frames-toggle input[type="checkbox"]')
.addEventListener('change', function () {
toggleAllFrames()
})
document.querySelectorAll('button[class="stack-frame-location"]').forEach((sfl) => {
sfl.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
return
}
toggleFrameSource(e.target.closest('li'))
})
document.querySelectorAll('button[class="stack-frame-location"]').forEach((sfl) => {
sfl.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
return
}
toggleFrameSource(e.target.closest('li'))
})
})
document.querySelectorAll('button[class="stack-frame-toggle-indicator"]').forEach((sfl) => {
sfl.addEventListener('click', function (e) {
toggleFrameSource(e.target.closest('li'))
})
document.querySelectorAll('button[class="stack-frame-toggle-indicator"]').forEach((sfl) => {
sfl.addEventListener('click', function (e) {
toggleFrameSource(e.target.closest('li'))
})
})

@@ -11,3 +11,2 @@ function toggleTheme(input) {

onContentLoaded(() => {
document.querySelector('#toggle-theme-checkbox').checked = usesDarkMode()

@@ -17,2 +16,1 @@ document.querySelector('#toggle-theme-checkbox').addEventListener('change', function () {

})
})

@@ -12,10 +12,2 @@ function usesDarkMode() {

function onContentLoaded(listener) {
if (document.readyState !== 'loading') {
listener()
return
}
document.addEventListener('DOMContentLoaded', listener)
}
document.documentElement.classList.add(usesDarkMode() ? 'dark' : 'light')

@@ -136,2 +136,4 @@ * {

--unknown-label-fg-color: #7b3814;
color-scheme: only light;
}

@@ -259,2 +261,4 @@

--unknown-label-fg-color: #94e2d5;
color-scheme: dark;
}

@@ -261,0 +265,0 @@

{
"name": "youch",
"description": "Pretty print JavaScript errors on the Web and the Terminal",
"version": "4.1.0-beta.11",
"version": "4.1.0-beta.12",
"type": "module",

@@ -37,4 +37,4 @@ "files": [

"@adonisjs/tsconfig": "^2.0.0-next.0",
"@aws-sdk/client-s3": "^3.850.0",
"@aws-sdk/s3-request-presigner": "^3.850.0",
"@aws-sdk/client-s3": "^3.922.0",
"@aws-sdk/s3-request-presigner": "^3.922.0",
"@japa/assert": "^4.1.1",

@@ -44,28 +44,27 @@ "@japa/expect": "^3.0.6",

"@japa/file-system": "^2.3.2",
"@japa/runner": "^4.3.0",
"@japa/runner": "^4.4.0",
"@japa/snapshot": "^2.0.9",
"@poppinss/exception": "^1.2.2",
"@poppinss/ts-exec": "^1.4.0",
"@poppinss/ts-exec": "^1.4.1",
"@release-it/conventional-changelog": "^10.0.1",
"@types/cookie": "^1.0.0",
"@types/jsdom": "^21.1.7",
"@types/node": "^24.1.0",
"@types/pg": "^8.15.4",
"axios": "^1.11.0",
"@types/jsdom": "^27.0.0",
"@types/node": "^24.10.0",
"@types/pg": "^8.15.6",
"axios": "^1.13.1",
"c8": "^10.1.3",
"copyfiles": "^2.4.1",
"eslint": "^9.32.0",
"eslint": "^9.39.0",
"flydrive": "^1.3.0",
"jsdom": "^26.1.0",
"jsdom": "^27.1.0",
"pg": "^8.16.3",
"prettier": "^3.6.2",
"release-it": "^19.0.4",
"release-it": "^19.0.5",
"tsup": "^8.5.0",
"typescript": "^5.8.3"
"typescript": "^5.9.3"
},
"dependencies": {
"@poppinss/colors": "^4.1.5",
"@poppinss/dumper": "^0.6.4",
"@speed-highlight/core": "^1.2.7",
"cookie": "^1.0.2",
"@poppinss/dumper": "^0.6.5",
"@speed-highlight/core": "^1.2.9",
"cookie-es": "^2.0.0",
"youch-core": "^0.3.3"

@@ -72,0 +71,0 @@ },

import "#nitro-internal-pollyfills";
export {};
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { trapUnhandledNodeErrors } from "nitro/runtime/internal";
import { startScheduleRunner } from "nitro/runtime/internal";
import { Server } from "node:http";
import nodeCrypto from "node:crypto";
import { parentPort, threadId } from "node:worker_threads";

@@ -11,53 +7,63 @@ import wsAdapter from "crossws/adapters/node";

import { getSocketAddress, isSocketSupported } from "get-port-please";
if (!globalThis.crypto) {
globalThis.crypto = nodeCrypto;
}
trapUnhandledNodeErrors();
import { useNitroApp, useNitroHooks } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
// Listen for shutdown signal from runner
parentPort?.on("message", (msg) => {
if (msg && msg.event === "shutdown") {
shutdown();
}
if (msg && msg.event === "shutdown") {
shutdown();
}
});
const nitroApp = useNitroApp();
const nitroHooks = useNitroHooks();
trapUnhandledErrors();
const server = new Server(toNodeHandler(nitroApp.fetch));
let listener;
listen().catch((error) => {
console.error("Dev worker failed to listen:", error);
return shutdown();
console.error("Dev worker failed to listen:", error);
return shutdown();
});
if (import.meta._websocket) {
const { handleUpgrade } = wsAdapter(nitroApp.h3App.websocket);
server.on("upgrade", handleUpgrade);
// https://crossws.unjs.io/adapters/node
if (hasWebSocket) {
const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });
server.on("upgrade", handleUpgrade);
}
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
startScheduleRunner();
}
// --- utils ---
async function listen() {
const listenAddr = await isSocketSupported() ? getSocketAddress({
name: `nitro-dev-${threadId}`,
pid: true,
random: true
}) : { port: 0, host: "localhost" };
return new Promise((resolve, reject) => {
try {
listener = server.listen(listenAddr, () => {
const address = server.address();
parentPort?.postMessage({
event: "listen",
address: typeof address === "string" ? { socketPath: address } : { host: "localhost", port: address?.port }
});
resolve();
});
} catch (error) {
reject(error);
}
});
const listenAddr = await isSocketSupported() ? getSocketAddress({
name: `nitro-dev-${threadId}`,
pid: true,
random: true
}) : {
port: 0,
host: "localhost"
};
return new Promise((resolve, reject) => {
try {
listener = server.listen(listenAddr, () => {
const address = server.address();
parentPort?.postMessage({
event: "listen",
address: typeof address === "string" ? { socketPath: address } : {
host: "localhost",
port: address?.port
}
});
resolve();
});
} catch (error) {
reject(error);
}
});
}
async function shutdown() {
server.closeAllConnections?.();
await Promise.all([
new Promise((resolve) => listener?.close(resolve)),
nitroApp.hooks.callHook("close").catch(console.error)
]);
parentPort?.postMessage({ event: "exit" });
server.closeAllConnections?.();
await Promise.all([new Promise((resolve) => listener?.close(resolve)), nitroHooks.callHook("close")]).catch(console.error);
parentPort?.postMessage({ event: "exit" });
}
import "#nitro-internal-pollyfills";
export declare const appFetch: any;
export declare const closePrerenderer: () => any;
declare const _default: {};
export default _default;
import "#nitro-internal-pollyfills";
import consola from "consola";
import { useNitroApp } from "nitro/runtime";
import { trapUnhandledNodeErrors } from "nitro/runtime/internal";
import { useNitroApp, useNitroHooks } from "nitro/app";
const nitroApp = useNitroApp();
export const appFetch = nitroApp.fetch;
export const closePrerenderer = () => nitroApp.hooks.callHook("close");
nitroApp.hooks.hook("error", (error, context) => {
if (!error.unhandled && error.status >= 500 && context.event?.req?.headers instanceof Headers && context.event.req.headers.get("x-nitro-prerender")) {
consola.error(
`[prerender error]`,
`[${context.event.req.method}]`,
`[${context.event.req.url}]`,
error
);
}
const nitroHooks = useNitroHooks();
export default {
fetch: nitroApp.fetch,
close: () => nitroHooks.callHook("close")
};
nitroHooks.hook("error", (error, context) => {
if (!error.unhandled && error.status >= 500 && context.event?.req?.headers instanceof Headers && context.event.req.headers.get("x-nitro-prerender")) {
consola.error(`[prerender error]`, `[${context.event.req.method}]`, `[${context.event.req.url}]`, error);
}
});
trapUnhandledNodeErrors();
import "#nitro-internal-pollyfills";
export {};
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets";
const nitroApp = useNitroApp();
// @ts-expect-error
addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (isPublicAssetURL(url.pathname) || url.pathname.includes("/_server/")) {
return;
}
const req = event.request;
req.runtime ??= { name: "service-worker" };
req.runtime.serviceWorker ??= { event };
req.waitUntil = event.waitUntil.bind(event);
event.respondWith(nitroApp.fetch(req));
const url = new URL(event.request.url);
if (isPublicAssetURL(url.pathname) || url.pathname.includes("/_server/")) {
return;
}
// srvx compatibility
const req = event.request;
req.runtime ??= { name: "service-worker" };
// @ts-expect-error (add to srvx types)
req.runtime.serviceWorker ??= { event };
req.waitUntil = event.waitUntil.bind(event);
event.respondWith(nitroApp.fetch(req));
});
self.addEventListener("install", () => {
self.skipWaiting();
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
event.waitUntil(self.clients.claim());
});
import "#nitro-internal-pollyfills";
export {};
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { Server } from "node:http";

@@ -7,8 +7,9 @@ import { toNodeHandler } from "srvx/node";

const server = new Server(toNodeHandler(nitroApp.fetch));
// @ts-ignore
server.listen(3e3, (err) => {
if (err) {
console.error(err);
} else {
console.log(`Listening on http://localhost:3000 (AWS Amplify Hosting)`);
}
if (err) {
console.error(err);
} else {
console.log(`Listening on http://localhost:3000 (AWS Amplify Hosting)`);
}
});
import type { APIGatewayProxyEvent, APIGatewayProxyEventV2 } from "aws-lambda";
import type { ServerRequest } from "srvx";
// Incoming (AWS => Web)
export declare function awsRequest(event: APIGatewayProxyEvent | APIGatewayProxyEventV2, context: unknown): ServerRequest;
export declare function awsResponseHeaders(response: Response): {
headers: any;
cookies: string[];
multiValueHeaders: {
"set-cookie": string[];
};
} | {
headers: any;
cookies?: undefined;
multiValueHeaders?: undefined;
};
// Outgoing (Web => AWS)
export declare function awsResponseHeaders(response: Response);
// AWS Lambda proxy integrations requires base64 encoded buffers
// binaryMediaTypes should be */*
// see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html
export declare function awsResponseBody(response: Response): Promise<{
body: string;
isBase64Encoded?: boolean;
body: string;
isBase64Encoded?: boolean;
}>;
import { stringifyQuery } from "ufo";
// Incoming (AWS => Web)
export function awsRequest(event, context) {
const method = awsEventMethod(event);
const url = awsEventURL(event);
const headers = awsEventHeaders(event);
const body = awsEventBody(event);
const req = new Request(url, { method, headers, body });
req.runtime ??= { name: "aws-lambda" };
req.runtime.aws ??= { event, context };
return new Request(url, { method, headers, body });
const method = awsEventMethod(event);
const url = awsEventURL(event);
const headers = awsEventHeaders(event);
const body = awsEventBody(event);
const req = new Request(url, {
method,
headers,
body
});
// srvx compatibility
req.runtime ??= { name: "aws-lambda" };
// @ts-expect-error (add to srvx types)
req.runtime.aws ??= {
event,
context
};
return new Request(url, {
method,
headers,
body
});
}
function awsEventMethod(event) {
return event.httpMethod || event.requestContext?.http?.method || "GET";
return event.httpMethod || event.requestContext?.http?.method || "GET";
}
function awsEventURL(event) {
const hostname = event.headers.host || event.headers.Host || event.requestContext?.domainName || ".";
const path = event.path || event.rawPath;
const query = awsEventQuery(event);
const protocol = (event.headers["X-Forwarded-Proto"] || event.headers["x-forwarded-proto"]) === "http" ? "http" : "https";
return new URL(
`${path}${query ? `?${query}` : ""}`,
`${protocol}://${hostname}`
);
const hostname = event.headers.host || event.headers.Host || event.requestContext?.domainName || ".";
const path = event.path || event.rawPath;
const query = awsEventQuery(event);
const protocol = (event.headers["X-Forwarded-Proto"] || event.headers["x-forwarded-proto"]) === "http" ? "http" : "https";
return new URL(`${path}${query ? `?${query}` : ""}`, `${protocol}://${hostname}`);
}
function awsEventQuery(event) {
if (typeof event.rawQueryString === "string") {
return event.rawQueryString;
}
const queryObj = {
...event.queryStringParameters,
...event.multiValueQueryStringParameters
};
return stringifyQuery(queryObj);
if (typeof event.rawQueryString === "string") {
return event.rawQueryString;
}
const queryObj = {
...event.queryStringParameters,
...event.multiValueQueryStringParameters
};
return stringifyQuery(queryObj);
}
function awsEventHeaders(event) {
const headers = new Headers();
for (const [key, value] of Object.entries(event.headers)) {
if (value) {
headers.set(key, value);
}
}
if ("cookies" in event && event.cookies) {
for (const cookie of event.cookies) {
headers.append("cookie", cookie);
}
}
return headers;
const headers = new Headers();
for (const [key, value] of Object.entries(event.headers)) {
if (value) {
headers.set(key, value);
}
}
if ("cookies" in event && event.cookies) {
for (const cookie of event.cookies) {
headers.append("cookie", cookie);
}
}
return headers;
}
function awsEventBody(event) {
if (!event.body) {
return void 0;
}
if (event.isBase64Encoded) {
return Buffer.from(event.body || "", "base64");
}
return event.body;
if (!event.body) {
return undefined;
}
if (event.isBase64Encoded) {
return Buffer.from(event.body || "", "base64");
}
return event.body;
}
// Outgoing (Web => AWS)
export function awsResponseHeaders(response) {
const headers = /* @__PURE__ */ Object.create(null);
for (const [key, value] of response.headers) {
if (value) {
headers[key] = Array.isArray(value) ? value.join(",") : String(value);
}
}
const cookies = response.headers.getSetCookie();
return cookies.length > 0 ? {
headers,
cookies,
// ApiGateway v2
multiValueHeaders: { "set-cookie": cookies }
// ApiGateway v1
} : { headers };
const headers = Object.create(null);
for (const [key, value] of response.headers) {
if (value) {
headers[key] = Array.isArray(value) ? value.join(",") : String(value);
}
}
const cookies = response.headers.getSetCookie();
return cookies.length > 0 ? {
headers,
cookies,
multiValueHeaders: { "set-cookie": cookies }
} : { headers };
}
// AWS Lambda proxy integrations requires base64 encoded buffers
// binaryMediaTypes should be */*
// see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html
export async function awsResponseBody(response) {
if (!response.body) {
return { body: "" };
}
const buffer = await toBuffer(response.body);
const contentType = response.headers.get("content-type") || "";
return isTextType(contentType) ? { body: buffer.toString("utf8") } : { body: buffer.toString("base64"), isBase64Encoded: true };
if (!response.body) {
return { body: "" };
}
const buffer = await toBuffer(response.body);
const contentType = response.headers.get("content-type") || "";
return isTextType(contentType) ? { body: buffer.toString("utf8") } : {
body: buffer.toString("base64"),
isBase64Encoded: true
};
}
function isTextType(contentType = "") {
return /^text\/|\/(javascript|json|xml)|utf-?8/i.test(contentType);
return /^text\/|\/(javascript|json|xml)|utf-?8/i.test(contentType);
}
function toBuffer(data) {
return new Promise((resolve, reject) => {
const chunks = [];
data.pipeTo(
new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
}
})
).catch(reject);
});
return new Promise((resolve, reject) => {
const chunks = [];
data.pipeTo(new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
}
})).catch(reject);
});
}
import "#nitro-internal-pollyfills";
import type { APIGatewayProxyEventV2 } from "aws-lambda";
export declare const handler: import("aws-lambda").StreamifyHandler<APIGatewayProxyEventV2, void>;
export declare const handler: unknown;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { awsRequest, awsResponseHeaders } from "./_utils.mjs";
const nitroApp = useNitroApp();
export const handler = awslambda.streamifyResponse(
async (event, responseStream, context) => {
const request = awsRequest(event, context);
const response = await nitroApp.fetch(request);
response.headers.set("transfer-encoding", "chunked");
const httpResponseMetadata = {
statusCode: response.status,
...awsResponseHeaders(response)
};
if (response.body) {
const writer = awslambda.HttpResponseStream.from(
// @ts-expect-error TODO: IMPORTANT! It should be a Writable according to the aws-lambda types
responseStream,
httpResponseMetadata
);
const reader = response.body.getReader();
await streamToNodeStream(reader, responseStream);
writer.end();
}
}
);
export const handler = awslambda.streamifyResponse(async (event, responseStream, context) => {
const request = awsRequest(event, context);
const response = await nitroApp.fetch(request);
response.headers.set("transfer-encoding", "chunked");
const httpResponseMetadata = {
statusCode: response.status,
...awsResponseHeaders(response)
};
if (response.body) {
const writer = awslambda.HttpResponseStream.from(
// @ts-expect-error TODO: IMPORTANT! It should be a Writable according to the aws-lambda types
responseStream,
httpResponseMetadata
);
const reader = response.body.getReader();
await streamToNodeStream(reader, responseStream);
writer.end();
}
});
async function streamToNodeStream(reader, writer) {
let readResult = await reader.read();
while (!readResult.done) {
writer.write(readResult.value);
readResult = await reader.read();
}
writer.end();
let readResult = await reader.read();
while (!readResult.done) {
writer.write(readResult.value);
readResult = await reader.read();
}
writer.end();
}
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { awsRequest, awsResponseHeaders, awsResponseBody } from "./_utils.mjs";
const nitroApp = useNitroApp();
export async function handler(event, context) {
const request = awsRequest(event, context);
const response = await nitroApp.fetch(request);
return {
statusCode: response.status,
...awsResponseHeaders(response),
...await awsResponseBody(response)
};
const request = awsRequest(event, context);
const response = await nitroApp.fetch(request);
return {
statusCode: response.status,
...awsResponseHeaders(response),
...await awsResponseBody(response)
};
}
import { parse } from "cookie-es";
export function getAzureParsedCookiesFromHeaders(headers) {
const setCookieHeader = headers.getSetCookie();
if (setCookieHeader.length === 0) {
return [];
}
const azureCookies = [];
for (const setCookieStr of setCookieHeader) {
const setCookie = Object.entries(parse(setCookieStr));
if (setCookie.length === 0) {
continue;
}
const [[key, value], ..._setCookieOptions] = setCookie;
const setCookieOptions = Object.fromEntries(
_setCookieOptions.map(([k, v]) => [k.toLowerCase(), v])
);
const cookieObject = {
name: key,
value,
domain: setCookieOptions.domain,
path: setCookieOptions.path,
expires: parseNumberOrDate(setCookieOptions.expires),
sameSite: setCookieOptions.samesite,
maxAge: parseNumber(setCookieOptions["max-age"]),
secure: setCookieStr.includes("Secure") ? true : void 0,
httpOnly: setCookieStr.includes("HttpOnly") ? true : void 0
};
azureCookies.push(cookieObject);
}
return azureCookies;
const setCookieHeader = headers.getSetCookie();
if (setCookieHeader.length === 0) {
return [];
}
const azureCookies = [];
for (const setCookieStr of setCookieHeader) {
const setCookie = Object.entries(parse(setCookieStr));
if (setCookie.length === 0) {
continue;
}
const [[key, value], ..._setCookieOptions] = setCookie;
const setCookieOptions = Object.fromEntries(_setCookieOptions.map(([k, v]) => [k.toLowerCase(), v]));
const cookieObject = {
name: key,
value,
domain: setCookieOptions.domain,
path: setCookieOptions.path,
expires: parseNumberOrDate(setCookieOptions.expires),
sameSite: setCookieOptions.samesite,
maxAge: parseNumber(setCookieOptions["max-age"]),
secure: setCookieStr.includes("Secure") ? true : undefined,
httpOnly: setCookieStr.includes("HttpOnly") ? true : undefined
};
azureCookies.push(cookieObject);
}
return azureCookies;
}
function parseNumberOrDate(expires) {
const expiresAsNumber = parseNumber(expires);
if (expiresAsNumber !== void 0) {
return expiresAsNumber;
}
const expiresAsDate = new Date(expires);
if (!Number.isNaN(expiresAsDate.getTime())) {
return expiresAsDate;
}
const expiresAsNumber = parseNumber(expires);
if (expiresAsNumber !== undefined) {
return expiresAsNumber;
}
// Convert to Date if possible
const expiresAsDate = new Date(expires);
if (!Number.isNaN(expiresAsDate.getTime())) {
return expiresAsDate;
}
}
function parseNumber(maxAge) {
if (!maxAge) {
return void 0;
}
const maxAgeAsNumber = Number(maxAge);
if (!Number.isNaN(maxAgeAsNumber)) {
return maxAgeAsNumber;
}
if (!maxAge) {
return undefined;
}
// Convert to number if possible
const maxAgeAsNumber = Number(maxAge);
if (!Number.isNaN(maxAgeAsNumber)) {
return maxAgeAsNumber;
}
}
import "#nitro-internal-pollyfills";
import type { HttpRequest, HttpResponse } from "@azure/functions";
export declare function handle(context: {
res: HttpResponse;
}, req: HttpRequest): Promise<void>;
res: HttpResponse;
}, req: HttpRequest);
import "#nitro-internal-pollyfills";
import { parseURL } from "ufo";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { getAzureParsedCookiesFromHeaders } from "./_utils.mjs";
const nitroApp = useNitroApp();
export async function handle(context, req) {
let url;
if (req.headers["x-ms-original-url"]) {
const parsedURL = parseURL(req.headers["x-ms-original-url"]);
url = parsedURL.pathname + parsedURL.search;
} else {
url = "/api/" + (req.params.url || "");
}
const response = await nitroApp.fetch(url, {
method: req.method || void 0,
// https://github.com/Azure/azure-functions-nodejs-worker/issues/294
// https://github.com/Azure/azure-functions-host/issues/293
body: req.bufferBody ?? req.rawBody
});
context.res = {
status: response.status,
body: response.body,
cookies: getAzureParsedCookiesFromHeaders(response.headers),
headers: Object.fromEntries(
[...response.headers.entries()].filter(([key]) => key !== "set-cookie")
)
};
let url;
if (req.headers["x-ms-original-url"]) {
// This URL has been proxied as there was no static file matching it.
const parsedURL = parseURL(req.headers["x-ms-original-url"]);
url = parsedURL.pathname + parsedURL.search;
} else {
// Because Azure SWA handles /api/* calls differently they
// never hit the proxy and we have to reconstitute the URL.
url = "/api/" + (req.params.url || "");
}
const request = new Request(url, {
method: req.method || undefined,
body: req.bufferBody ?? req.rawBody
});
const response = await nitroApp.fetch(request);
// (v3 - current) https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=typescript%2Cwindows%2Cazure-cli&pivots=nodejs-model-v3#http-response
// (v4) https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=typescript%2Cwindows%2Cazure-cli&pivots=nodejs-model-v4#http-response
context.res = {
status: response.status,
body: response.body,
cookies: getAzureParsedCookiesFromHeaders(response.headers),
headers: Object.fromEntries([...response.headers.entries()].filter(([key]) => key !== "set-cookie"))
};
}
import "#nitro-internal-pollyfills";
declare const _default: {};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { startScheduleRunner } from "nitro/runtime/internal";
import { serve } from "srvx/bun";
import wsAdapter from "crossws/adapters/bun";
import { useNitroApp } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const cert = process.env.NITRO_SSL_CERT;
const key = process.env.NITRO_SSL_KEY;
// const socketPath = process.env.NITRO_UNIX_SOCKET; // TODO
const nitroApp = useNitroApp();
const ws = import.meta._websocket ? (
// @ts-expect-error
wsAdapter(nitroApp.h3App.websocket)
) : void 0;
const server = Bun.serve({
port: process.env.NITRO_PORT || process.env.PORT || 3e3,
hostname: process.env.NITRO_HOST || process.env.HOST,
websocket: import.meta._websocket ? ws.websocket : void 0,
async fetch(bunReq, server2) {
const req = bunReq;
req.runtime ??= { name: "bun" };
req.runtime.bun ??= { server: server2 };
if (import.meta._websocket && req.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(req, server2);
}
return nitroApp.fetch(req);
}
let _fetch = nitroApp.fetch;
const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined;
if (hasWebSocket) {
_fetch = (req) => {
if (req.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(req, req.runtime.bun.server);
}
return nitroApp.fetch(req);
};
}
serve({
port,
hostname: host,
tls: cert && key ? {
cert,
key
} : undefined,
fetch: _fetch,
bun: { websocket: hasWebSocket ? ws?.websocket : undefined }
});
console.log(`Listening on ${server.url}...`);
trapUnhandledErrors();
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
startScheduleRunner();
}
export default {};

@@ -6,9 +6,12 @@ import "#nitro-internal-pollyfills";

export declare function createHandler<Env>(hooks: {
fetch: (...params: [
...Parameters<NonNullable<ExportedHandler<Env>["fetch"]>>,
url: URL,
cfContextExtras: any
]) => MaybePromise<Response | CF.Response | undefined>;
}): ExportedHandler<Env>;
export declare function fetchHandler(cfReq: Request | CF.Request, env: unknown, context: CF.ExecutionContext | DurableObjectState, url: URL | undefined, nitroApp: any, ctxExt: any): Promise<Response>;
fetch: (...params: [...Parameters<NonNullable<ExportedHandler<Env>["fetch"]>>, url: URL, cfContextExtras: any]) => MaybePromise<Response | CF.Response | undefined>;
}): {
fetch(request, env, context);
scheduled(controller, env, context);
email(message, env, context);
queue(batch, env, context);
tail(traces, env, context);
trace(traces, env, context);
};
export declare function fetchHandler(cfReq: Request | CF.Request, env: unknown, context: CF.ExecutionContext | DurableObjectState, url: URL, nitroApp, ctxExt: any);
export {};
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { runCronTasks } from "nitro/runtime/internal";
import { runCronTasks } from "nitro/~internal/runtime/task";
import { useNitroApp, useNitroHooks } from "nitro/app";
export function createHandler(hooks) {
const nitroApp = useNitroApp();
return {
async fetch(request, env, context) {
const ctxExt = {};
const url = new URL(request.url);
if (hooks.fetch) {
const res = await hooks.fetch(request, env, context, url, ctxExt);
if (res) {
return res;
}
}
return fetchHandler(request, env, context, url, nitroApp, ctxExt);
},
scheduled(controller, env, context) {
globalThis.__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:scheduled", {
controller,
env,
context
})
);
if (import.meta._tasks) {
context.waitUntil(
runCronTasks(controller.cron, {
context: {
cloudflare: {
env,
context
}
},
payload: {}
})
);
}
},
email(message, env, context) {
globalThis.__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:email", {
message,
event: message,
// backward compat
env,
context
})
);
},
queue(batch, env, context) {
globalThis.__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:queue", {
batch,
event: batch,
env,
context
})
);
},
tail(traces, env, context) {
globalThis.__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:tail", {
traces,
env,
context
})
);
},
trace(traces, env, context) {
globalThis.__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:trace", {
traces,
env,
context
})
);
}
};
const nitroApp = useNitroApp();
const nitroHooks = useNitroHooks();
return {
async fetch(request, env, context) {
const ctxExt = {};
const url = new URL(request.url);
// Preset-specific logic
if (hooks.fetch) {
const res = await hooks.fetch(request, env, context, url, ctxExt);
if (res) {
return res;
}
}
return fetchHandler(request, env, context, url, nitroApp, ctxExt);
},
scheduled(controller, env, context) {
globalThis.__env__ = env;
context.waitUntil(nitroHooks.callHook("cloudflare:scheduled", {
controller,
env,
context
}));
if (import.meta._tasks) {
context.waitUntil(runCronTasks(controller.cron, {
context: { cloudflare: {
env,
context
} },
payload: {}
}));
}
},
email(message, env, context) {
globalThis.__env__ = env;
context.waitUntil(nitroHooks.callHook("cloudflare:email", {
message,
event: message,
env,
context
}));
},
queue(batch, env, context) {
globalThis.__env__ = env;
context.waitUntil(nitroHooks.callHook("cloudflare:queue", {
batch,
event: batch,
env,
context
}));
},
tail(traces, env, context) {
globalThis.__env__ = env;
context.waitUntil(nitroHooks.callHook("cloudflare:tail", {
traces,
env,
context
}));
},
trace(traces, env, context) {
globalThis.__env__ = env;
context.waitUntil(nitroHooks.callHook("cloudflare:trace", {
traces,
env,
context
}));
}
};
}
export async function fetchHandler(cfReq, env, context, url = new URL(cfReq.url), nitroApp = useNitroApp(), ctxExt) {
globalThis.__env__ = env;
const req = cfReq;
req.runtime ??= { name: "cloudflare" };
req.runtime.cloudflare ??= { context, env };
req.waitUntil = context.waitUntil.bind(context);
return nitroApp.fetch(req);
// Expose latest env to the global context
globalThis.__env__ = env;
// srvx compatibility
const req = cfReq;
req.runtime ??= { name: "cloudflare" };
req.runtime.cloudflare ??= {
context,
env
};
req.waitUntil = context.waitUntil.bind(context);
return nitroApp.fetch(req);
}
import "#nitro-internal-pollyfills";
import type * as CF from "@cloudflare/workers-types";
import { DurableObject } from "cloudflare:workers";
declare const DURABLE_BINDING = "$DurableObject";
interface Env {
ASSETS?: {
fetch: typeof CF.fetch;
};
[DURABLE_BINDING]?: CF.DurableObjectNamespace;
}
declare const _default: CF.ExportedHandler<Env, unknown, unknown>;
declare const _default;
export default _default;
export declare class $DurableObject extends DurableObject {
constructor(state: DurableObjectState, env: Record<string, any>);
fetch(request: Request): Promise<Response>;
alarm(): void | Promise<void>;
webSocketMessage(client: WebSocket, message: ArrayBuffer | string): Promise<void>;
webSocketClose(client: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
constructor(state: DurableObjectState, env: Record<string, any>);
fetch(request: Request);
alarm(): void | Promise<void>;
webSocketMessage(client: WebSocket, message: ArrayBuffer | string);
webSocketClose(client: WebSocket, code: number, reason: string, wasClean: boolean);
}
import "#nitro-internal-pollyfills";
import { DurableObject } from "cloudflare:workers";
import wsAdapter from "crossws/adapters/cloudflare";
import { useNitroApp } from "nitro/runtime";
import { createHandler, fetchHandler } from "./_module-handler.mjs";
import { useNitroApp, useNitroHooks } from "nitro/app";
import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets";
import { createHandler, fetchHandler } from "./_module-handler.mjs";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const DURABLE_BINDING = "$DurableObject";
const DURABLE_INSTANCE = "server";
const nitroApp = useNitroApp();
const nitroHooks = useNitroHooks();
const getDurableStub = (env) => {
const binding = env[DURABLE_BINDING];
if (!binding) {
throw new Error(
`Durable Object binding "${DURABLE_BINDING}" not available.`
);
}
const id = binding.idFromName(DURABLE_INSTANCE);
return binding.get(id);
const binding = env[DURABLE_BINDING];
if (!binding) {
throw new Error(`Durable Object binding "${DURABLE_BINDING}" not available.`);
}
const id = binding.idFromName(DURABLE_INSTANCE);
return binding.get(id);
};
const ws = import.meta._websocket ? wsAdapter({
// TODO!
// ...nitroApp.h3App.websocket,
instanceName: DURABLE_INSTANCE,
bindingName: DURABLE_BINDING
}) : void 0;
export default createHandler({
fetch(request, env, context, url, ctxExt) {
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(request);
}
ctxExt.durableFetch = (req = request) => getDurableStub(env).fetch(req);
if (import.meta._websocket && request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request, env, context);
}
}
});
const ws = hasWebSocket ? wsAdapter({
resolve: resolveWebsocketHooks,
instanceName: DURABLE_INSTANCE,
bindingName: DURABLE_BINDING
}) : undefined;
export default createHandler({ fetch(request, env, context, url, ctxExt) {
// Static assets fallback (optional binding)
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(request);
}
// Expose stub fetch to the context
ctxExt.durableFetch = (req = request) => getDurableStub(env).fetch(req);
// Websocket upgrade
// https://crossws.unjs.io/adapters/cloudflare#durable-objects
if (hasWebSocket && request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request, env, context);
}
} });
export class $DurableObject extends DurableObject {
constructor(state, env) {
super(state, env);
state.waitUntil(
nitroApp.hooks.callHook("cloudflare:durable:init", this, {
state,
env
})
);
if (import.meta._websocket) {
ws.handleDurableInit(this, state, env);
}
}
fetch(request) {
if (import.meta._websocket && request.headers.get("upgrade") === "websocket") {
return ws.handleDurableUpgrade(this, request);
}
const url = new URL(request.url);
return fetchHandler(request, this.env, this.ctx, url, nitroApp, {
durable: this
});
}
alarm() {
this.ctx.waitUntil(
nitroApp.hooks.callHook("cloudflare:durable:alarm", this)
);
}
async webSocketMessage(client, message) {
if (import.meta._websocket) {
return ws.handleDurableMessage(this, client, message);
}
}
async webSocketClose(client, code, reason, wasClean) {
if (import.meta._websocket) {
return ws.handleDurableClose(this, client, code, reason, wasClean);
}
}
constructor(state, env) {
super(state, env);
state.waitUntil(nitroHooks.callHook("cloudflare:durable:init", this, {
state,
env
}));
if (hasWebSocket) {
ws.handleDurableInit(this, state, env);
}
}
fetch(request) {
if (hasWebSocket && request.headers.get("upgrade") === "websocket") {
return ws.handleDurableUpgrade(this, request);
}
// Main handler
const url = new URL(request.url);
return fetchHandler(request, this.env, this.ctx, url, nitroApp, { durable: this });
}
alarm() {
this.ctx.waitUntil(nitroHooks.callHook("cloudflare:durable:alarm", this));
}
async webSocketMessage(client, message) {
if (hasWebSocket) {
return ws.handleDurableMessage(this, client, message);
}
}
async webSocketClose(client, code, reason, wasClean) {
if (hasWebSocket) {
return ws.handleDurableClose(this, client, code, reason, wasClean);
}
}
}
import "#nitro-internal-pollyfills";
import type { fetch } from "@cloudflare/workers-types";
interface Env {
ASSETS?: {
fetch: typeof fetch;
};
}
declare const _default: import("@cloudflare/workers-types").ExportedHandler<Env, unknown, unknown>;
declare const _default;
export default _default;
import "#nitro-internal-pollyfills";
import wsAdapter from "crossws/adapters/cloudflare";
import { useNitroApp } from "nitro/runtime";
import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets";
import { createHandler } from "./_module-handler.mjs";
const nitroApp = useNitroApp();
const ws = import.meta._websocket ? (
// @ts-expect-error
wsAdapter(nitroApp.h3App.websocket)
) : void 0;
export default createHandler({
fetch(request, env, context, url) {
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(request);
}
if (import.meta._websocket && request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request, env, context);
}
}
});
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined;
export default createHandler({ fetch(request, env, context, url) {
// Static assets fallback (optional binding)
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(request);
}
// Websocket upgrade
// https://crossws.unjs.io/adapters/cloudflare
if (hasWebSocket && request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request, env, context);
}
} });
import "#nitro-internal-pollyfills";
import type { Request as CFRequest, EventContext, ExecutionContext } from "@cloudflare/workers-types";
/**
* Reference: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#parameters
*/
* Reference: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#parameters
*/
interface CFPagesEnv {
ASSETS: {
fetch: (request: CFRequest) => Promise<Response>;
};
CF_PAGES: "1";
CF_PAGES_BRANCH: string;
CF_PAGES_COMMIT_SHA: string;
CF_PAGES_URL: string;
[key: string]: any;
ASSETS: {
fetch: (request: CFRequest) => Promise<Response>;
};
CF_PAGES: "1";
CF_PAGES_BRANCH: string;
CF_PAGES_COMMIT_SHA: string;
CF_PAGES_URL: string;
[key: string]: any;
}
declare const _default: {
fetch(cfReq: CFRequest, env: CFPagesEnv, context: EventContext<CFPagesEnv, string, any>): Promise<any>;
scheduled(event: any, env: CFPagesEnv, context: ExecutionContext): void;
fetch(cfReq: CFRequest, env: CFPagesEnv, context: EventContext<CFPagesEnv, string, any>);
scheduled(event: any, env: CFPagesEnv, context: ExecutionContext);
};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { runCronTasks } from "nitro/runtime/internal";
import wsAdapter from "crossws/adapters/cloudflare";
import { useNitroApp } from "nitro/app";
import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets";
import wsAdapter from "crossws/adapters/cloudflare";
import { runCronTasks } from "nitro/~internal/runtime/task";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const nitroApp = useNitroApp();
const ws = import.meta._websocket ? (
// @ts-expect-error
wsAdapter(nitroApp.h3App.websocket)
) : void 0;
const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined;
export default {
async fetch(cfReq, env, context) {
const req = cfReq;
req.runtime ??= { name: "cloudflare" };
req.runtime.cloudflare ??= { context, env };
req.waitUntil = context.waitUntil.bind(context);
if (import.meta._websocket && cfReq.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(
cfReq,
env,
context
);
}
const url = new URL(cfReq.url);
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(cfReq);
}
globalThis.__env__ = env;
return nitroApp.fetch(req);
},
scheduled(event, env, context) {
if (import.meta._tasks) {
globalThis.__env__ = env;
context.waitUntil(
runCronTasks(event.cron, {
context: {
cloudflare: {
env,
context
}
},
payload: {}
})
);
}
}
async fetch(cfReq, env, context) {
// srvx compatibility
const req = cfReq;
req.runtime ??= { name: "cloudflare" };
req.runtime.cloudflare ??= {
context,
env
};
req.waitUntil = context.waitUntil.bind(context);
// Websocket upgrade
// https://crossws.unjs.io/adapters/cloudflare
if (hasWebSocket && cfReq.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(cfReq, env, context);
}
const url = new URL(cfReq.url);
if (env.ASSETS && isPublicAssetURL(url.pathname)) {
return env.ASSETS.fetch(cfReq);
}
// Expose latest env to the global context
globalThis.__env__ = env;
return nitroApp.fetch(req);
},
scheduled(event, env, context) {
if (import.meta._tasks) {
globalThis.__env__ = env;
context.waitUntil(runCronTasks(event.cron, {
context: { cloudflare: {
env,
context
} },
payload: {}
}));
}
}
};
import type { NitroAppPlugin } from "nitro/types";
declare const _default: NitroAppPlugin;
export default _default;
declare const cloudflareDevPlugin: NitroAppPlugin;
export default cloudflareDevPlugin;

@@ -1,89 +0,96 @@

const _proxy = _getPlatformProxy().catch((error) => {
console.error("Failed to initialize wrangler bindings proxy", error);
return _createStubProxy();
}).then((proxy) => {
globalThis.__env__ = proxy.env;
return proxy;
import { useRuntimeConfig } from "nitro/runtime-config";
const proxy = await _getPlatformProxy().catch((error) => {
console.error("Failed to initialize wrangler bindings proxy", error);
return _createStubProxy();
});
globalThis.__env__ = _proxy.then((proxy) => proxy.env);
export default (function(nitroApp) {
nitroApp.hooks.hook("request", async (event) => {
event.req.context ??= {};
const proxy = await _proxy;
event.req.context.cf = proxy.cf;
event.req.context.waitUntil = proxy.ctx.waitUntil.bind(proxy.ctx);
const request = new Request(event.req.url);
request.cf = proxy.cf;
event.req.context.cloudflare = {
...event.req.context.cloudflare,
request,
env: proxy.env,
context: proxy.ctx
};
});
nitroApp.hooks._hooks.request.unshift(nitroApp.hooks._hooks.request.pop());
nitroApp.hooks.hook("close", () => {
return _proxy?.then((proxy) => proxy.dispose);
});
});
globalThis.__env__ = proxy.env;
globalThis.__wait_until__ = proxy.ctx.waitUntil.bind(proxy.ctx);
const cloudflareDevPlugin = function(nitroApp) {
nitroApp.hooks.hook("request", async (event) => {
event.req.context ??= {};
// Inject the various cf values from the proxy in event and event.context
event.req.context.cf = proxy.cf;
event.req.context.waitUntil = proxy.ctx.waitUntil.bind(proxy.ctx);
const request = event.req;
request.cf = proxy.cf;
event.req.context.cloudflare = {
...event.req.context.cloudflare,
request,
env: proxy.env,
context: proxy.ctx
};
// Replicate Nitro production behavior
// https://github.com/unjs/nitro/blob/main/src/runtime/entries/cloudflare-pages.ts#L55
// https://github.com/unjs/nitro/blob/main/src/runtime/app.ts#L120
// TODO: Update for v3
// (event.node.req as any).__unenv__ = {
// ...(event.node.req as any).__unenv__,
// waitUntil: event.context.waitUntil,
// };
});
// https://github.com/pi0/nitro-cloudflare-dev/issues/5
// https://github.com/unjs/hookable/issues/98
// @ts-expect-error
nitroApp.hooks._hooks.request.unshift(nitroApp.hooks._hooks.request.pop());
// Dispose proxy when Nitro is closed
nitroApp.hooks.hook("close", () => {
return proxy?.dispose();
});
};
export default cloudflareDevPlugin;
async function _getPlatformProxy() {
const { useRuntimeConfig } = await import("nitro/runtime");
const pkg = "wrangler";
const { getPlatformProxy } = await import(
/* @vite-ignore */
pkg
).catch(
() => {
throw new Error(
"Package `wrangler` not found, please install it with: `npx nypm@latest add -D wrangler`"
);
}
);
const runtimeConfig = useRuntimeConfig();
const proxyOptions = {
configPath: runtimeConfig.wrangler.configPath,
persist: { path: runtimeConfig.wrangler.persistDir }
};
if (runtimeConfig.wrangler.environment) {
proxyOptions.environment = runtimeConfig.wrangler.environment;
}
const proxy = await getPlatformProxy(proxyOptions);
return proxy;
const pkg = "wrangler";
const { getPlatformProxy } = await import(
/* @vite-ignore */
pkg
).catch(() => {
throw new Error("Package `wrangler` not found, please install it with: `npx nypm@latest add -D wrangler`");
});
const runtimeConfig = useRuntimeConfig();
const proxyOptions = {
configPath: runtimeConfig.wrangler.configPath,
persist: { path: runtimeConfig.wrangler.persistDir }
};
// TODO: investigate why
// https://github.com/pi0/nitro-cloudflare-dev/issues/51
if (runtimeConfig.wrangler.environment) {
proxyOptions.environment = runtimeConfig.wrangler.environment;
}
const proxy = await getPlatformProxy(proxyOptions);
return proxy;
}
function _createStubProxy() {
return {
env: {},
cf: {},
ctx: {
waitUntil() {
},
passThroughOnException() {
},
props: {}
},
caches: {
open() {
const result = Promise.resolve(new _CacheStub());
return result;
},
get default() {
return new _CacheStub();
}
},
dispose: () => Promise.resolve()
};
return {
env: {},
cf: {},
ctx: {
waitUntil() {},
passThroughOnException() {},
props: {}
},
caches: {
open() {
const result = Promise.resolve(new _CacheStub());
return result;
},
get default() {
return new _CacheStub();
}
},
dispose: () => Promise.resolve()
};
}
class _CacheStub {
delete() {
const result = Promise.resolve(false);
return result;
}
match() {
const result = Promise.resolve(void 0);
return result;
}
put() {
const result = Promise.resolve();
return result;
}
delete() {
const result = Promise.resolve(false);
return result;
}
match() {
const result = Promise.resolve(undefined);
return result;
}
put() {
const result = Promise.resolve();
return result;
}
}
import "#nitro-internal-pollyfills";
import type { Deno as _Deno } from "@deno/types";
declare global {
var Deno: typeof _Deno;
}
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import wsAdapter from "crossws/adapters/deno";
import { useNitroApp } from "nitro/app";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const nitroApp = useNitroApp();
const ws = import.meta._websocket ? (
// @ts-expect-error
wsAdapter(nitroApp.h3App.websocket)
) : void 0;
const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined;
// TODO: Migrate to srvx to provide request IP
Deno.serve((denoReq, info) => {
const req = denoReq;
req.runtime ??= { name: "deno" };
req.runtime.deno ??= { info };
if (import.meta._websocket && req.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(req, info);
}
return nitroApp.fetch(req);
// srvx compatibility
const req = denoReq;
req.runtime ??= { name: "deno" };
req.runtime.deno ??= { info };
// TODO: Support remoteAddr
// https://crossws.unjs.io/adapters/deno
if (hasWebSocket && req.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(req, info);
}
return nitroApp.fetch(req);
});
import "#nitro-internal-pollyfills";
declare global {
const Deno: typeof import("@deno/types").Deno;
}
declare const _default: {};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useRuntimeConfig } from "nitro/runtime";
import { startScheduleRunner } from "nitro/runtime/internal";
import { serve } from "srvx/deno";
import wsAdapter from "crossws/adapters/deno";
import destr from "destr";
import { useNitroApp } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const cert = process.env.NITRO_SSL_CERT;
const key = process.env.NITRO_SSL_KEY;
// const socketPath = process.env.NITRO_UNIX_SOCKET; // TODO
const nitroApp = useNitroApp();
if (Deno.env.get("DEBUG")) {
addEventListener(
"unhandledrejection",
(event) => console.error("[unhandledRejection]", event.reason)
);
addEventListener(
"error",
(event) => console.error("[uncaughtException]", event.error)
);
} else {
addEventListener(
"unhandledrejection",
(err) => console.error("[unhandledRejection] " + err)
);
addEventListener(
"error",
(event) => console.error("[uncaughtException] " + event.error)
);
let _fetch = nitroApp.fetch;
if (hasWebSocket) {
const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });
_fetch = (req) => {
if (req.headers.get("upgrade") === "websocket") {
return handleUpgrade(req, req.runtime.deno.info);
}
return nitroApp.fetch(req);
};
}
const serveOptions = {
key: Deno.env.get("NITRO_SSL_KEY"),
cert: Deno.env.get("NITRO_SSL_CERT"),
port: destr(Deno.env.get("NITRO_PORT") || Deno.env.get("PORT")) || 3e3,
hostname: Deno.env.get("NITRO_HOST") || Deno.env.get("HOST"),
onListen: (opts) => {
const baseURL = (useRuntimeConfig().app.baseURL || "").replace(/\/$/, "");
const url = `${opts.hostname}:${opts.port}${baseURL}`;
console.log(`Listening ${url}`);
}
};
if (!serveOptions.key || !serveOptions.cert) {
delete serveOptions.key;
delete serveOptions.cert;
}
Deno.serve(serveOptions, handler);
const ws = import.meta._websocket ? (
// @ts-expect-error
wsAdapter(nitroApp.h3App.websocket)
) : void 0;
async function handler(denoReq, info) {
const req = denoReq;
req.runtime ??= { name: "deno" };
req.runtime.deno ??= { info };
if (import.meta._websocket && req.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(req, info);
}
return nitroApp.fetch(req);
}
serve({
port,
hostname: host,
tls: cert && key ? {
cert,
key
} : undefined,
fetch: _fetch
});
trapUnhandledErrors();
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
startScheduleRunner();
}
export default {};
import "#nitro-internal-pollyfills";
import type { Context } from "@netlify/edge-functions";
export default function netlifyEdge(netlifyReq: Request, context: Context): Promise<any>;
// https://docs.netlify.com/edge-functions/api/
export default function netlifyEdge(netlifyReq: Request, context: Context);
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets";
const nitroApp = useNitroApp();
// https://docs.netlify.com/edge-functions/api/
export default async function netlifyEdge(netlifyReq, context) {
const req = netlifyReq;
req.runtime ??= { name: "netlify-edge" };
req.runtime.netlify ??= { context };
const url = new URL(req.url);
if (isPublicAssetURL(url.pathname)) {
return;
}
if (!req.headers.has("x-forwarded-proto") && url.protocol === "https:") {
req.headers.set("x-forwarded-proto", "https");
}
return nitroApp.fetch(req);
// srvx compatibility
const req = netlifyReq;
req.runtime ??= { name: "netlify-edge" };
// @ts-expect-error (add to srvx types)
req.runtime.netlify ??= { context };
const url = new URL(req.url);
if (isPublicAssetURL(url.pathname)) {
return;
}
if (!req.headers.has("x-forwarded-proto") && url.protocol === "https:") {
req.headers.set("x-forwarded-proto", "https");
}
return nitroApp.fetch(req);
}
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
const nitroApp = useNitroApp();
const ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
const handler = async (req) => {
const response = await nitroApp.fetch(req);
const isr = (req.context?.routeRules || {})?.isr?.options;
if (isr) {
const maxAge = typeof isr === "number" ? isr : ONE_YEAR_IN_SECONDS;
const revalidateDirective = typeof isr === "number" ? `stale-while-revalidate=${ONE_YEAR_IN_SECONDS}` : "must-revalidate";
if (!response.headers.has("Cache-Control")) {
response.headers.set(
"Cache-Control",
"public, max-age=0, must-revalidate"
);
}
response.headers.set(
"Netlify-CDN-Cache-Control",
`public, max-age=${maxAge}, ${revalidateDirective}, durable`
);
}
return response;
const response = await nitroApp.fetch(req);
const isr = (req.context?.routeRules || {})?.isr?.options;
if (isr) {
const maxAge = typeof isr === "number" ? isr : ONE_YEAR_IN_SECONDS;
const revalidateDirective = typeof isr === "number" ? `stale-while-revalidate=${ONE_YEAR_IN_SECONDS}` : "must-revalidate";
if (!response.headers.has("Cache-Control")) {
response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
}
response.headers.set("Netlify-CDN-Cache-Control", `public, max-age=${maxAge}, ${revalidateDirective}, durable`);
}
return response;
};
export default handler;

@@ -1,1 +0,3 @@

export {};
import "#nitro-internal-pollyfills";
declare const _default: {};
export default _default;

@@ -0,58 +1,54 @@

import "#nitro-internal-pollyfills";
import cluster from "node:cluster";
import os from "node:os";
import {
getGracefulShutdownConfig,
trapUnhandledNodeErrors
} from "nitro/runtime/internal";
function runMaster() {
const numberOfWorkers = Number.parseInt(process.env.NITRO_CLUSTER_WORKERS || "") || (os.cpus().length > 0 ? os.cpus().length : 1);
for (let i = 0; i < numberOfWorkers; i++) {
cluster.fork();
}
let isShuttingDown = false;
cluster.on("exit", () => {
if (!isShuttingDown) {
cluster.fork();
}
});
const shutdownConfig = getGracefulShutdownConfig();
if (!shutdownConfig.disabled) {
async function onShutdown() {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
await new Promise((resolve) => {
const timeout = setTimeout(() => {
console.warn("Timeout reached for graceful shutdown. Forcing exit.");
resolve();
}, shutdownConfig.timeout);
cluster.on("exit", () => {
if (Object.values(cluster.workers || {}).every((w) => !w || w.isDead())) {
clearTimeout(timeout);
resolve();
} else {
}
});
});
if (shutdownConfig.forceExit) {
process.exit(0);
}
}
for (const signal of shutdownConfig.signals) {
process.once(signal, onShutdown);
}
}
import { NodeRequest, serve } from "srvx/node";
import wsAdapter from "crossws/adapters/node";
import { useNitroApp } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const cert = process.env.NITRO_SSL_CERT;
const key = process.env.NITRO_SSL_KEY;
// const socketPath = process.env.NITRO_UNIX_SOCKET; // TODO
const clusterId = cluster.isWorker && process.env.WORKER_ID;
if (clusterId) {
console.log(`Worker #${clusterId} started`);
}
function runWorker() {
import("./node-server.mjs").catch((error) => {
console.error(error);
process.exit(1);
});
const nitroApp = useNitroApp();
const server = serve({
port,
hostname: host,
tls: cert && key ? {
cert,
key
} : undefined,
node: { exclusive: false },
silent: clusterId ? clusterId !== "1" : undefined,
fetch: nitroApp.fetch
});
if (hasWebSocket) {
const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });
server.node.server.on("upgrade", (req, socket, head) => {
handleUpgrade(
req,
socket,
head,
// @ts-expect-error (upgrade is not typed)
new NodeRequest({
req,
upgrade: {
socket,
head
}
})
);
});
}
trapUnhandledNodeErrors();
if (cluster.isPrimary) {
runMaster();
} else {
runWorker();
trapUnhandledErrors();
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
}
export default {};
import "#nitro-internal-pollyfills";
export declare const middleware: any;
/** @experimental */
export declare const websocket: undefined;
export declare const middleware: unknown;
export declare const handleUpgrade: unknown;
import "#nitro-internal-pollyfills";
import { toNodeHandler } from "srvx/node";
import { useNitroApp } from "nitro/runtime";
import {
startScheduleRunner,
trapUnhandledNodeErrors
} from "nitro/runtime/internal";
import wsAdapter from "crossws/adapters/node";
import { useNitroApp } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const nitroApp = useNitroApp();
export const middleware = toNodeHandler(nitroApp.fetch);
export const websocket = import.meta._websocket ? void 0 : void 0;
trapUnhandledNodeErrors();
const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined;
export const handleUpgrade = ws?.handleUpgrade;
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
startScheduleRunner();
}
import "#nitro-internal-pollyfills";
import { Server as HttpServer } from "node:http";
import { Server as HttpsServer } from "node:https";
import { NodeRequest, serve } from "srvx/node";
import wsAdapter from "crossws/adapters/node";
import destr from "destr";
import { toNodeHandler } from "srvx/node";
import { useNitroApp, useRuntimeConfig } from "nitro/runtime";
import {
setupGracefulShutdown,
startScheduleRunner,
trapUnhandledNodeErrors
} from "nitro/runtime/internal";
import { useNitroApp } from "nitro/app";
import { startScheduleRunner } from "nitro/~internal/runtime/task";
import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const cert = process.env.NITRO_SSL_CERT;
const key = process.env.NITRO_SSL_KEY;
// const socketPath = process.env.NITRO_UNIX_SOCKET; // TODO
const nitroApp = useNitroApp();
const server = cert && key ? new HttpsServer({ key, cert }, toNodeHandler(nitroApp.fetch)) : new HttpServer(toNodeHandler(nitroApp.fetch));
const port = destr(process.env.NITRO_PORT || process.env.PORT) || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const path = process.env.NITRO_UNIX_SOCKET;
const listener = server.listen(path ? { path } : { port, host }, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
const protocol = cert && key ? "https" : "http";
const addressInfo = listener.address();
if (typeof addressInfo === "string") {
console.log(`Listening on unix socket ${addressInfo}`);
return;
}
const baseURL = (useRuntimeConfig().app.baseURL || "").replace(/\/$/, "");
const url = `${protocol}://${addressInfo.family === "IPv6" ? `[${addressInfo.address}]` : addressInfo.address}:${addressInfo.port}${baseURL}`;
console.log(`Listening on ${url}`);
const server = serve({
port,
hostname: host,
tls: cert && key ? {
cert,
key
} : undefined,
fetch: nitroApp.fetch
});
trapUnhandledNodeErrors();
setupGracefulShutdown(listener, nitroApp);
if (import.meta._websocket) {
const { handleUpgrade } = wsAdapter(nitroApp.h3App.websocket);
server.on("upgrade", handleUpgrade);
if (hasWebSocket) {
const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });
server.node.server.on("upgrade", (req, socket, head) => {
handleUpgrade(
req,
socket,
head,
// @ts-expect-error (upgrade is not typed)
new NodeRequest({
req,
upgrade: {
socket,
head
}
})
);
});
}
trapUnhandledErrors();
// Scheduled tasks
if (import.meta._tasks) {
startScheduleRunner();
startScheduleRunner();
}
export default {};
import "#nitro-internal-pollyfills";
declare const _default: {
fetch: any;
};
declare const _default: {};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
const nitroApp = useNitroApp();
export default {
fetch: nitroApp.fetch
};
export default { fetch: nitroApp.fetch };
import "#nitro-internal-pollyfills";
import type { Handler } from "aws-lambda";
type StormkitEvent = {
url: string;
path: string;
method: string;
body?: string;
query?: Record<string, Array<string>>;
headers?: Record<string, string>;
rawHeaders?: Array<string>;
url: string;
path: string;
method: string;
body?: string;
query?: Record<string, Array<string>>;
headers?: Record<string, string>;
rawHeaders?: Array<string>;
};
type StormkitResponse = {
headers?: Record<string, string>;
body?: string;
buffer?: string;
statusCode: number;
errorMessage?: string;
errorStack?: string;
headers?: Record<string, string>;
body?: string;
buffer?: string;
statusCode: number;
errorMessage?: string;
errorStack?: string;
};
export declare const handler: Handler<StormkitEvent, StormkitResponse>;
export {};
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { awsResponseBody } from "../../aws-lambda/runtime/_utils.mjs";
const nitroApp = useNitroApp();
export const handler = async function(event, context) {
const req = new Request(event.url, {
method: event.method || "GET",
headers: event.headers,
body: event.body
});
req.runtime ??= { name: "stormkit" };
req.runtime.stormkit ??= { event, context };
const response = await nitroApp.fetch(req);
const { body, isBase64Encoded } = await awsResponseBody(response);
return {
statusCode: response.status,
headers: normalizeOutgoingHeaders(response.headers),
[isBase64Encoded ? "buffer" : "body"]: body
};
const req = new Request(event.url, {
method: event.method || "GET",
headers: event.headers,
body: event.body
});
// srvx compatibility
req.runtime ??= { name: "stormkit" };
// @ts-expect-error (add to srvx types)
req.runtime.stormkit ??= {
event,
context
};
const response = await nitroApp.fetch(req);
const { body, isBase64Encoded } = await awsResponseBody(response);
return {
statusCode: response.status,
headers: normalizeOutgoingHeaders(response.headers),
[isBase64Encoded ? "buffer" : "body"]: body
};
};
function normalizeOutgoingHeaders(headers) {
return Object.fromEntries(
Object.entries(headers).map(([k, v]) => [
k,
Array.isArray(v) ? v.join(",") : String(v)
])
);
return Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : String(v)]));
}

@@ -0,1 +1,3 @@

// @ts-nocheck TODO: Remove after removing polyfills
import "#nitro-internal-pollyfills";
export {};

@@ -0,87 +1,91 @@

// @ts-nocheck TODO: Remove after removing polyfills
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
import { hasProtocol, joinURL } from "ufo";
const nitroApp = useNitroApp();
// Use plain handler as winterjs Web API is incomplete
// TODO: Migrate to toWebHandler
const _handler = toPlainHandler(nitroApp.h3App);
async function _handleEvent(event) {
try {
const res = await _handler({
path: event.request.url.pathname + (event.request.url.search ? `?${event.request.url.search}` : ""),
method: event.request.getMethod() || "GET",
body: event.request.body,
headers: event.request.headers,
context: {
waitUntil: (promise) => event.waitUntil(promise),
_platform: {
winterjs: {
event
}
}
}
});
const body = typeof res.body === "string" ? res.body : await toBuffer(res.body);
return new Response(body, {
status: res.status,
statusText: res.statusText,
headers: res.headers
});
} catch (error) {
const errString = error?.message + "\n" + error?.stack;
console.error(errString);
return new Response(errString, { status: 500 });
}
try {
const res = await _handler({
path: event.request.url.pathname + (event.request.url.search ? `?${event.request.url.search}` : ""),
method: event.request.getMethod() || "GET",
body: event.request.body,
headers: event.request.headers,
context: {
waitUntil: (promise) => event.waitUntil(promise),
_platform: { winterjs: { event } }
}
});
const body = typeof res.body === "string" ? res.body : await toBuffer(res.body);
return new Response(body, {
status: res.status,
statusText: res.statusText,
headers: res.headers
});
} catch (error) {
const errString = error?.message + "\n" + error?.stack;
console.error(errString);
return new Response(errString, { status: 500 });
}
}
addEventListener("fetch", async (event) => {
event.respondWith(await _handleEvent(event));
event.respondWith(await _handleEvent(event));
});
// ------------------------------
// Polyfills for missing APIs
// ------------------------------
function toBuffer(data) {
return new Promise((resolve, reject) => {
const chunks = [];
data.pipeTo(
new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
}
})
).catch(reject);
});
return new Promise((resolve, reject) => {
const chunks = [];
data.pipeTo(new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
}
})).catch(reject);
});
}
// Headers.entries
if (!Headers.prototype.entries) {
Headers.prototype.entries = function() {
return [...this];
};
// @ts-ignore
Headers.prototype.entries = function() {
return [...this];
};
}
// URL.pathname
if (!URL.prototype.pathname) {
Object.defineProperty(URL.prototype, "pathname", {
get() {
return this.path || "/";
}
});
Object.defineProperty(URL.prototype, "pathname", { get() {
return this.path || "/";
} });
}
// URL constructor (relative support)
const _URL = globalThis.URL;
globalThis.URL = class URL2 extends _URL {
constructor(url, base) {
if (!base || hasProtocol(url)) {
super(url);
return;
}
super(joinURL(base, url));
}
globalThis.URL = class URL extends _URL {
constructor(url, base) {
if (!base || hasProtocol(url)) {
super(url);
return;
}
super(joinURL(base, url));
}
};
// Response (avoid Promise body)
const _Response = globalThis.Response;
globalThis.Response = class Response2 extends _Response {
_body;
constructor(body, init) {
super(body, init);
this._body = body;
}
get body() {
return this._body;
}
globalThis.Response = class Response extends _Response {
_body;
constructor(body, init) {
super(body, init);
this._body = body;
}
get body() {
// TODO: Return ReadableStream (should be iterable)
return this._body;
}
};
import "#nitro-internal-pollyfills";
declare const _default: any;
declare const _default;
export default _default;
import "#nitro-internal-pollyfills";
import { toNodeHandler } from "srvx/node";
import { useNitroApp } from "nitro/runtime";
import { useNitroApp } from "nitro/app";
export default toNodeHandler(useNitroApp().fetch);

@@ -1,2 +0,12 @@

import type { NitroApp } from "nitro/types";
import type { NitroApp, NitroRuntimeHooks } from "nitro/types";
import type { ServerRequest, ServerRequestContext } from "srvx";
import type { H3EventContext, WebSocketHooks } from "h3";
import { HookableCore } from "hookable";
declare global {
var __nitro__: NitroApp | undefined;
}
export declare function useNitroApp(): NitroApp;
export declare function useNitroHooks(): HookableCore<NitroRuntimeHooks>;
export declare function serverFetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>;
export declare function resolveWebsocketHooks(req: ServerRequest): Promise<Partial<WebSocketHooks>>;
export declare function fetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>;
import { H3Core, toRequest } from "h3";
import { createHooks } from "hookable";
import { HookableCore } from "hookable";
import { nitroAsyncContext } from "./context.mjs";
// IMPORTANT: virtual imports and user code should be imported last to avoid initialization order issues
import errorHandler from "#nitro-internal-virtual/error-handler";
import { plugins } from "#nitro-internal-virtual/plugins";
import {
findRoute,
findRouteRules,
globalMiddleware,
findRoutedMiddleware
} from "#nitro-internal-virtual/routing";
import { findRoute, findRouteRules, globalMiddleware, findRoutedMiddleware } from "#nitro-internal-virtual/routing";
import { hasRouteRules, hasRoutedMiddleware, hasGlobalMiddleware, hasRoutes, hasHooks, hasPlugins } from "#nitro-internal-virtual/feature-flags";
export function useNitroApp() {
return useNitroApp.__instance__ ??= initNitroApp();
return useNitroApp.__instance__ ??= initNitroApp();
}
export function useNitroHooks() {
const nitroApp = useNitroApp();
const hooks = nitroApp.hooks;
if (hooks) {
return hooks;
}
return nitroApp.hooks = new HookableCore();
}
export function serverFetch(resource, init, context) {
const req = toRequest(resource, init);
req.context = {
...req.context,
...context
};
const appHandler = useNitroApp().fetch;
try {
return Promise.resolve(appHandler(req));
} catch (error) {
return Promise.reject(error);
}
}
export async function resolveWebsocketHooks(req) {
// https://github.com/h3js/h3/blob/c11ca743d476e583b3b47de1717e6aae92114357/src/utils/ws.ts#L37
const hooks = (await serverFetch(req)).crossws;
return hooks || {};
}
export function fetch(resource, init, context) {
if (typeof resource === "string" && resource.charCodeAt(0) === 47) {
return serverFetch(resource, init, context);
}
resource = resource._request || resource;
return fetch(resource, init);
}
function initNitroApp() {
const nitroApp = createNitroApp();
for (const plugin of plugins) {
try {
plugin(nitroApp);
} catch (error) {
nitroApp.captureError(error, { tags: ["plugin"] });
throw error;
}
}
return nitroApp;
const nitroApp = createNitroApp();
if (hasPlugins) {
for (const plugin of plugins) {
try {
plugin(nitroApp);
} catch (error) {
nitroApp.captureError?.(error, { tags: ["plugin"] });
throw error;
}
}
}
globalThis.__nitro__ = nitroApp;
return nitroApp;
}
function createNitroApp() {
const hooks = createHooks();
const captureError = (error, errorCtx) => {
const promise = hooks.callHookParallel("error", error, errorCtx).catch((hookError) => {
console.error("Error while capturing another error", hookError);
});
if (errorCtx?.event) {
const errors = errorCtx.event.req.context?.nitro?.errors;
if (errors) {
errors.push({ error, context: errorCtx });
}
if (typeof errorCtx.event.req.waitUntil === "function") {
errorCtx.event.req.waitUntil(promise);
}
}
};
const h3App = createH3App(captureError);
let fetchHandler = async (req) => {
req.context ??= {};
req.context.nitro = req.context.nitro || { errors: [] };
const event = { req };
const nitroApp = useNitroApp();
await nitroApp.hooks.callHook("request", event).catch((error) => {
captureError(error, { event, tags: ["request"] });
});
const response = await h3App.request(req, void 0, req.context);
await nitroApp.hooks.callHook("response", response, event).catch((error) => {
captureError(error, { event, tags: ["request", "response"] });
});
return response;
};
if (import.meta._asyncContext) {
const originalFetchHandler = fetchHandler;
fetchHandler = (req) => {
const asyncCtx = { request: req };
return nitroAsyncContext.callAsync(
asyncCtx,
() => originalFetchHandler(req)
);
};
}
const requestHandler = (input, init, context) => {
const req = toRequest(input, init);
req.context = { ...req.context, ...context };
return Promise.resolve(fetchHandler(req));
};
const originalFetch = globalThis.fetch;
const nitroFetch = (input, init) => {
if (typeof input === "string" && input.startsWith("/")) {
return requestHandler(input, init);
}
if (input instanceof Request && "_request" in input) {
input = input._request;
}
return originalFetch(input, init);
};
globalThis.fetch = nitroFetch;
const app = {
_h3: h3App,
hooks,
fetch: requestHandler,
captureError
};
return app;
const hooks = hasHooks ? new HookableCore() : undefined;
const captureError = (error, errorCtx) => {
const promise = hasHooks && hooks.callHook("error", error, errorCtx)?.catch?.((hookError) => {
console.error("Error while capturing another error", hookError);
});
if (errorCtx?.event) {
const errors = errorCtx.event.req.context?.nitro?.errors;
if (errors) {
errors.push({
error,
context: errorCtx
});
}
if (hasHooks && typeof errorCtx.event.req.waitUntil === "function") {
errorCtx.event.req.waitUntil(promise);
}
}
};
const h3App = createH3App({ onError(error, event) {
hasHooks && captureError(error, { event });
return errorHandler(error, event);
} });
if (hasHooks) {
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"]
});
});
};
}
let appHandler = (req) => {
req.context ||= {};
req.context.nitro = req.context.nitro || { errors: [] };
return h3App.fetch(req);
};
// Experimental async context support
if (import.meta._asyncContext) {
const originalHandler = appHandler;
appHandler = (req) => {
const asyncCtx = { request: req };
return nitroAsyncContext.callAsync(asyncCtx, () => originalHandler(req));
};
}
const app = {
fetch: appHandler,
h3: h3App,
hooks,
captureError
};
return app;
}
function createH3App(captureError) {
const DEBUG_MODE = ["1", "true", "TRUE"].includes(process.env.DEBUG + "");
const h3App = new H3Core({
debug: DEBUG_MODE,
onError: (error, event) => {
captureError(error, { event, tags: ["request"] });
return errorHandler(error, event);
}
});
h3App._findRoute = (event) => findRoute(event.req.method, event.url.pathname);
h3App._getMiddleware = (event, route) => {
const pathname = event.url.pathname;
const method = event.req.method;
const { routeRules, routeRuleMiddleware } = getRouteRules(method, pathname);
event.context.routeRules = routeRules;
return [
...routeRuleMiddleware,
...globalMiddleware,
...findRoutedMiddleware(method, pathname).map((r) => r.data),
...route?.data?.middleware || []
].filter(Boolean);
};
return h3App;
function createH3App(config) {
// Create H3 app
const h3App = new H3Core(config);
// Compiled route matching
hasRoutes && (h3App["~findRoute"] = (event) => findRoute(event.req.method, event.url.pathname));
hasGlobalMiddleware && h3App["~middleware"].push(...globalMiddleware);
if (hasRouteRules || hasRoutedMiddleware) {
h3App["~getMiddleware"] = (event, route) => {
const needsRouting = hasRouteRules || hasRoutedMiddleware;
const pathname = needsRouting ? event.url.pathname : undefined;
const method = needsRouting ? event.req.method : undefined;
const middleware = [];
if (hasRouteRules) {
const routeRules = getRouteRules(method, pathname);
event.context.routeRules = routeRules?.routeRules;
if (routeRules?.routeRuleMiddleware.length) {
middleware.push(...routeRules.routeRuleMiddleware);
}
}
hasGlobalMiddleware && middleware.push(...h3App["~middleware"]);
hasRoutedMiddleware && middleware.push(...findRoutedMiddleware(method, pathname).map((r) => r.data));
if (hasRoutes && route?.data?.middleware?.length) {
middleware.push(...route.data.middleware);
}
return middleware;
};
}
return h3App;
}
function getRouteRules(method, pathname) {
const m = findRouteRules(method, pathname);
if (!m?.length) {
return { routeRuleMiddleware: [] };
}
const routeRules = {};
for (const layer of m) {
for (const rule of layer.data) {
const currentRule = routeRules[rule.name];
if (currentRule) {
if (rule.options === false) {
delete routeRules[rule.name];
continue;
}
if (typeof currentRule.options === "object" && typeof rule.options === "object") {
currentRule.options = { ...currentRule.options, ...rule.options };
} else {
currentRule.options = rule.options;
}
currentRule.route = rule.route;
currentRule.params = { ...currentRule.params, ...layer.params };
} else if (rule.options !== false) {
routeRules[rule.name] = { ...rule, params: layer.params };
}
}
}
const middleware = [];
for (const rule of Object.values(routeRules)) {
if (rule.options === false || !rule.handler) {
continue;
}
middleware.push(rule.handler(rule));
}
return {
routeRules,
routeRuleMiddleware: middleware
};
const m = findRouteRules(method, pathname);
if (!m?.length) {
return { routeRuleMiddleware: [] };
}
const routeRules = {};
for (const layer of m) {
for (const rule of layer.data) {
const currentRule = routeRules[rule.name];
if (currentRule) {
if (rule.options === false) {
// Remove/Reset existing rule with `false` value
delete routeRules[rule.name];
continue;
}
if (typeof currentRule.options === "object" && typeof rule.options === "object") {
// Merge nested rule objects
currentRule.options = {
...currentRule.options,
...rule.options
};
} else {
// Override rule if non object
currentRule.options = rule.options;
}
// Routing (route and params)
currentRule.route = rule.route;
currentRule.params = {
...currentRule.params,
...layer.params
};
} else if (rule.options !== false) {
routeRules[rule.name] = {
...rule,
params: layer.params
};
}
}
}
const middleware = [];
for (const rule of Object.values(routeRules)) {
if (rule.options === false || !rule.handler) {
continue;
}
middleware.push(rule.handler(rule));
}
return {
routeRules,
routeRuleMiddleware: middleware
};
}
import type { EventHandler } from "h3";
import type { CacheOptions, CachedEventHandlerOptions } from "nitro/types";
export declare function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(fn: (...args: ArgsT) => T | Promise<T>, opts?: CacheOptions<T, ArgsT>): (...args: ArgsT) => Promise<T>;
export declare function cachedFunction<T, ArgsT extends unknown[] = any[]>(fn: (...args: ArgsT) => T | Promise<T>, opts?: CacheOptions<T>): (...args: ArgsT) => Promise<T | undefined>;
export declare function defineCachedEventHandler(handler: EventHandler, opts?: CachedEventHandlerOptions): EventHandler;
export declare const cachedEventHandler: typeof defineCachedEventHandler;
export declare const defineCachedHandler: typeof defineCachedEventHandler;
export declare function defineCachedFunction<
T,
ArgsT extends unknown[] = any[]
>(fn: (...args: ArgsT) => T | Promise<T>, opts?: CacheOptions<T, ArgsT>): (...args: ArgsT) => Promise<T>;
export declare function cachedFunction<
T,
ArgsT extends unknown[] = any[]
>(fn: (...args: ArgsT) => T | Promise<T>, opts?: CacheOptions<T>): (...args: ArgsT) => Promise<T | undefined>;
export declare function defineCachedHandler(handler: EventHandler, opts?: CachedEventHandlerOptions): EventHandler;

@@ -8,230 +8,259 @@ import { defineHandler, handleCacheHeaders, isHTTPEvent, toResponse } from "h3";

function defaultCacheOptions() {
return {
name: "_",
base: "/cache",
swr: true,
maxAge: 1
};
return {
name: "_",
base: "/cache",
swr: true,
maxAge: 1
};
}
export function defineCachedFunction(fn, opts = {}) {
opts = { ...defaultCacheOptions(), ...opts };
const pending = {};
const group = opts.group || "nitro/functions";
const name = opts.name || fn.name || "_";
const integrity = opts.integrity || hash([fn, opts]);
const validate = opts.validate || ((entry) => entry.value !== void 0);
async function get(key, resolver, shouldInvalidateCache, event) {
const cacheKey = [opts.base, group, name, key + ".json"].filter(Boolean).join(":").replace(/:\/$/, ":index");
let entry = await useStorage().getItem(cacheKey).catch((error) => {
console.error(`[cache] Cache read error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
}) || {};
if (typeof entry !== "object") {
entry = {};
const error = new Error("Malformed data read from cache.");
console.error("[cache]", error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
}
const ttl = (opts.maxAge ?? 0) * 1e3;
if (ttl) {
entry.expires = Date.now() + ttl;
}
const expired = shouldInvalidateCache || entry.integrity !== integrity || ttl && Date.now() - (entry.mtime || 0) > ttl || validate(entry) === false;
const _resolve = async () => {
const isPending = pending[key];
if (!isPending) {
if (entry.value !== void 0 && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
entry.value = void 0;
entry.integrity = void 0;
entry.mtime = void 0;
entry.expires = void 0;
}
pending[key] = Promise.resolve(resolver());
}
try {
entry.value = await pending[key];
} catch (error) {
if (!isPending) {
delete pending[key];
}
throw error;
}
if (!isPending) {
entry.mtime = Date.now();
entry.integrity = integrity;
delete pending[key];
if (validate(entry) !== false) {
let setOpts;
if (opts.maxAge && !opts.swr) {
setOpts = { ttl: opts.maxAge };
}
const promise = useStorage().setItem(cacheKey, entry, setOpts).catch((error) => {
console.error(`[cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
if (typeof event?.req?.waitUntil === "function") {
event.req.waitUntil(promise);
}
}
}
};
const _resolvePromise = expired ? _resolve() : Promise.resolve();
if (entry.value === void 0) {
await _resolvePromise;
} else if (expired && event && event.req.waitUntil) {
event.req.waitUntil(_resolvePromise);
}
if (opts.swr && validate(entry) !== false) {
_resolvePromise.catch((error) => {
console.error(`[cache] SWR handler error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
return entry;
}
return _resolvePromise.then(() => entry);
}
return async (...args) => {
const shouldBypassCache = await opts.shouldBypassCache?.(...args);
if (shouldBypassCache) {
return fn(...args);
}
const key = await (opts.getKey || getKey)(...args);
const shouldInvalidateCache = await opts.shouldInvalidateCache?.(...args);
const entry = await get(
key,
() => fn(...args),
shouldInvalidateCache,
args[0] && isHTTPEvent(args[0]) ? args[0] : void 0
);
let value = entry.value;
if (opts.transform) {
value = await opts.transform(entry, ...args) || value;
}
return value;
};
opts = {
...defaultCacheOptions(),
...opts
};
const pending = {};
// Normalize cache params
const group = opts.group || "nitro/functions";
const name = opts.name || fn.name || "_";
const integrity = opts.integrity || hash([fn, opts]);
const validate = opts.validate || ((entry) => entry.value !== undefined);
async function get(key, resolver, shouldInvalidateCache, event) {
// Use extension for key to avoid conflicting with parent namespace (foo/bar and foo/bar/baz)
const cacheKey = [
opts.base,
group,
name,
key + ".json"
].filter(Boolean).join(":").replace(/:\/$/, ":index");
let entry = await useStorage().getItem(cacheKey).catch((error) => {
console.error(`[cache] Cache read error.`, error);
useNitroApp().captureError?.(error, {
event,
tags: ["cache"]
});
}) || {};
// https://github.com/nitrojs/nitro/issues/2160
if (typeof entry !== "object") {
entry = {};
const error = new Error("Malformed data read from cache.");
console.error("[cache]", error);
useNitroApp().captureError?.(error, {
event,
tags: ["cache"]
});
}
const ttl = (opts.maxAge ?? 0) * 1e3;
if (ttl) {
entry.expires = Date.now() + ttl;
}
const expired = shouldInvalidateCache || entry.integrity !== integrity || ttl && Date.now() - (entry.mtime || 0) > ttl || validate(entry) === false;
const _resolve = async () => {
const isPending = pending[key];
if (!isPending) {
if (entry.value !== undefined && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
// Remove cached entry to prevent using expired cache on concurrent requests
entry.value = undefined;
entry.integrity = undefined;
entry.mtime = undefined;
entry.expires = undefined;
}
pending[key] = Promise.resolve(resolver());
}
try {
entry.value = await pending[key];
} catch (error) {
// Make sure entries that reject get removed.
if (!isPending) {
delete pending[key];
}
// Re-throw error to make sure the caller knows the task failed.
throw error;
}
if (!isPending) {
// Update mtime, integrity + validate and set the value in cache only the first time the request is made.
entry.mtime = Date.now();
entry.integrity = integrity;
delete pending[key];
if (validate(entry) !== false) {
let setOpts;
if (opts.maxAge && !opts.swr) {
setOpts = { ttl: opts.maxAge };
}
const promise = useStorage().setItem(cacheKey, entry, setOpts).catch((error) => {
console.error(`[cache] Cache write error.`, error);
useNitroApp().captureError?.(error, {
event,
tags: ["cache"]
});
});
if (typeof event?.req?.waitUntil === "function") {
event.req.waitUntil(promise);
}
}
}
};
const _resolvePromise = expired ? _resolve() : Promise.resolve();
if (entry.value === undefined) {
await _resolvePromise;
} else if (expired && event && event.req.waitUntil) {
event.req.waitUntil(_resolvePromise);
}
if (opts.swr && validate(entry) !== false) {
_resolvePromise.catch((error) => {
console.error(`[cache] SWR handler error.`, error);
useNitroApp().captureError?.(error, {
event,
tags: ["cache"]
});
});
return entry;
}
return _resolvePromise.then(() => entry);
}
return async (...args) => {
const shouldBypassCache = await opts.shouldBypassCache?.(...args);
if (shouldBypassCache) {
return fn(...args);
}
const key = await (opts.getKey || getKey)(...args);
const shouldInvalidateCache = await opts.shouldInvalidateCache?.(...args);
const entry = await get(key, () => fn(...args), shouldInvalidateCache, args[0] && isHTTPEvent(args[0]) ? args[0] : undefined);
let value = entry.value;
if (opts.transform) {
value = await opts.transform(entry, ...args) || value;
}
return value;
};
}
export function cachedFunction(fn, opts = {}) {
return defineCachedFunction(fn, opts);
return defineCachedFunction(fn, opts);
}
function getKey(...args) {
return args.length > 0 ? hash(args) : "";
return args.length > 0 ? hash(args) : "";
}
function escapeKey(key) {
return String(key).replace(/\W/g, "");
return String(key).replace(/\W/g, "");
}
export function defineCachedEventHandler(handler, opts = defaultCacheOptions()) {
const variableHeaderNames = (opts.varies || []).filter(Boolean).map((h) => h.toLowerCase()).sort();
const _opts = {
...opts,
shouldBypassCache: (event) => {
return event.req.method !== "GET" && event.req.method !== "HEAD";
},
getKey: async (event) => {
const customKey = await opts.getKey?.(event);
if (customKey) {
return escapeKey(customKey);
}
const _path = event.url.pathname + event.url.search;
let _pathname;
try {
_pathname = escapeKey(decodeURI(parseURL(_path).pathname)).slice(0, 16) || "index";
} catch {
_pathname = "-";
}
const _hashedPath = `${_pathname}.${hash(_path)}`;
const _headers = variableHeaderNames.map((header) => [header, event.req.headers.get(header)]).map(([name, value]) => `${escapeKey(name)}.${hash(value)}`);
return [_hashedPath, ..._headers].join(":");
},
validate: (entry) => {
if (!entry.value) {
return false;
}
if (entry.value.status >= 400) {
return false;
}
if (entry.value.body === void 0) {
return false;
}
if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") {
return false;
}
return true;
},
group: opts.group || "nitro/handlers",
integrity: opts.integrity || hash([handler, opts])
};
const _cachedHandler = cachedFunction(
async (event) => {
const filteredHeaders = [...event.req.headers.entries()].filter(
([key]) => !variableHeaderNames.includes(key.toLowerCase())
);
try {
const originalReq = event.req;
event.req = new Request(event.req.url, {
method: event.req.method,
headers: filteredHeaders
});
event.req.runtime = originalReq.runtime;
event.req.waitUntil = originalReq.waitUntil;
} catch (error) {
console.error("[cache] Failed to filter headers:", error);
}
const rawValue = await handler(event);
const res = await toResponse(rawValue, event);
const body = await res.text();
if (!res.headers.has("etag")) {
res.headers.set("etag", `W/"${hash(body)}"`);
}
if (!res.headers.has("last-modified")) {
res.headers.set("last-modified", (/* @__PURE__ */ new Date()).toUTCString());
}
const cacheControl = [];
if (opts.swr) {
if (opts.maxAge) {
cacheControl.push(`s-maxage=${opts.maxAge}`);
}
if (opts.staleMaxAge) {
cacheControl.push(`stale-while-revalidate=${opts.staleMaxAge}`);
} else {
cacheControl.push("stale-while-revalidate");
}
} else if (opts.maxAge) {
cacheControl.push(`max-age=${opts.maxAge}`);
}
if (cacheControl.length > 0) {
res.headers.set("cache-control", cacheControl.join(", "));
}
const cacheEntry = {
status: res.status,
statusText: res.statusText,
headers: Object.fromEntries(res.headers.entries()),
body
};
return cacheEntry;
},
_opts
);
return defineHandler(async (event) => {
if (opts.headersOnly) {
if (handleCacheHeaders(event, { maxAge: opts.maxAge })) {
return;
}
return handler(event);
}
const response = await _cachedHandler(event);
if (handleCacheHeaders(event, {
modifiedTime: new Date(response.headers["last-modified"]),
etag: response.headers.etag,
maxAge: opts.maxAge
})) {
return;
}
return new FastResponse(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
});
export function defineCachedHandler(handler, opts = defaultCacheOptions()) {
const variableHeaderNames = (opts.varies || []).filter(Boolean).map((h) => h.toLowerCase()).sort();
const _opts = {
...opts,
shouldBypassCache: (event) => {
return event.req.method !== "GET" && event.req.method !== "HEAD";
},
getKey: async (event) => {
// Custom user-defined key
const customKey = await opts.getKey?.(event);
if (customKey) {
return escapeKey(customKey);
}
// Auto-generated key
const _path = event.url.pathname + event.url.search;
let _pathname;
try {
_pathname = escapeKey(decodeURI(parseURL(_path).pathname)).slice(0, 16) || "index";
} catch {
_pathname = "-";
}
const _hashedPath = `${_pathname}.${hash(_path)}`;
const _headers = variableHeaderNames.map((header) => [header, event.req.headers.get(header)]).map(([name, value]) => `${escapeKey(name)}.${hash(value)}`);
return [_hashedPath, ..._headers].join(":");
},
validate: (entry) => {
if (!entry.value) {
return false;
}
if (entry.value.status >= 400) {
return false;
}
if (entry.value.body === undefined) {
return false;
}
// https://github.com/nitrojs/nitro/pull/1857
if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") {
return false;
}
return true;
},
group: opts.group || "nitro/handlers",
integrity: opts.integrity || hash([handler, opts])
};
const _cachedHandler = cachedFunction(async (event) => {
// Filter non variable headers
const filteredHeaders = [...event.req.headers.entries()].filter(([key]) => !variableHeaderNames.includes(key.toLowerCase()));
try {
const originalReq = event.req;
// @ts-expect-error assigning to publicly readonly property
event.req = new Request(event.req.url, {
method: event.req.method,
headers: filteredHeaders
});
// Inherit srvx context
event.req.runtime = originalReq.runtime;
event.req.waitUntil = originalReq.waitUntil;
} catch (error) {
console.error("[cache] Failed to filter headers:", error);
}
// Call handler
const rawValue = await handler(event);
const res = await toResponse(rawValue, event);
// Stringified body
// TODO: support binary responses
const body = await res.text();
if (!res.headers.has("etag")) {
res.headers.set("etag", `W/"${hash(body)}"`);
}
if (!res.headers.has("last-modified")) {
res.headers.set("last-modified", new Date().toUTCString());
}
const cacheControl = [];
if (opts.swr) {
if (opts.maxAge) {
cacheControl.push(`s-maxage=${opts.maxAge}`);
}
if (opts.staleMaxAge) {
cacheControl.push(`stale-while-revalidate=${opts.staleMaxAge}`);
} else {
cacheControl.push("stale-while-revalidate");
}
} else if (opts.maxAge) {
cacheControl.push(`max-age=${opts.maxAge}`);
}
if (cacheControl.length > 0) {
res.headers.set("cache-control", cacheControl.join(", "));
}
const cacheEntry = {
status: res.status,
statusText: res.statusText,
headers: Object.fromEntries(res.headers.entries()),
body
};
return cacheEntry;
}, _opts);
return defineHandler(async (event) => {
// Headers-only mode
if (opts.headersOnly) {
// TODO: Send SWR too
if (handleCacheHeaders(event, { maxAge: opts.maxAge })) {
return;
}
return handler(event);
}
// Call with cache
const response = await _cachedHandler(event);
// Check for cache headers
if (handleCacheHeaders(event, {
modifiedTime: new Date(response.headers["last-modified"]),
etag: response.headers.etag,
maxAge: opts.maxAge
})) {
return;
}
// Send Response
return new FastResponse(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
});
}
export const cachedEventHandler = defineCachedEventHandler;
export const defineCachedHandler = defineCachedEventHandler;
import type { ServerRequest } from "srvx";
export declare const nitroAsyncContext: import("unctx/index").UseContext<NitroAsyncContext>;
export declare const nitroAsyncContext: unknown;
/**
*
* Access to the current Nitro request.
*
* @experimental
* - Requires `experimental.asyncContext: true` config to work.
* - Works in Node.js and limited runtimes only
*
*/
*
* Access to the current Nitro request.
*
* @experimental
* - Requires `experimental.asyncContext: true` config to work.
* - Works in Node.js and limited runtimes only
*
*/
export declare function useRequest(): ServerRequest;

@@ -5,14 +5,21 @@ import { AsyncLocalStorage } from "node:async_hooks";

export const nitroAsyncContext = /* @__PURE__ */ (() => getContext("nitro-app", {
asyncContext: import.meta._asyncContext,
AsyncLocalStorage: import.meta._asyncContext ? AsyncLocalStorage : void 0
asyncContext: import.meta._asyncContext,
AsyncLocalStorage: import.meta._asyncContext ? AsyncLocalStorage : undefined
}))();
/**
*
* Access to the current Nitro request.
*
* @experimental
* - Requires `experimental.asyncContext: true` config to work.
* - Works in Node.js and limited runtimes only
*
*/
export function useRequest() {
try {
return nitroAsyncContext.use().request;
} catch {
const hint = import.meta._asyncContext ? "Note: This is an experimental feature and might be broken on non-Node.js environments." : "Enable the experimental flag using `experimental.asyncContext: true`.";
throw new HTTPError({
message: `Nitro request context is not available. ${hint}`
});
}
try {
return nitroAsyncContext.use().request;
} catch {
const hint = import.meta._asyncContext ? "Note: This is an experimental feature and might be broken on non-Node.js environments." : "Enable the experimental flag using `experimental.asyncContext: true`.";
throw new HTTPError({ message: `Nitro request context is not available. ${hint}` });
}
}
import { createDatabase } from "db0";
import { connectionConfigs } from "#nitro-internal-virtual/database";
const instances = /* @__PURE__ */ Object.create(null);
const instances = Object.create(null);
export function useDatabase(name = "default") {
if (instances[name]) {
return instances[name];
}
if (!connectionConfigs[name]) {
throw new Error(`Database connection "${name}" not configured.`);
}
return instances[name] = createDatabase(
connectionConfigs[name].connector(connectionConfigs[name].options || {})
);
if (instances[name]) {
return instances[name];
}
if (!connectionConfigs[name]) {
throw new Error(`Database connection "${name}" not configured.`);
}
return instances[name] = createDatabase(connectionConfigs[name].connector(connectionConfigs[name].options || {}));
}
import type { HTTPError, HTTPEvent } from "h3";
import type { InternalHandlerResponse } from "./utils.mjs";
declare const _default: NitroErrorHandler;
declare const _default;
export default _default;
export declare function defaultHandler(error: HTTPError, event: HTTPEvent, opts?: {
silent?: boolean;
json?: boolean;
silent?: boolean;
json?: boolean;
}): Promise<InternalHandlerResponse>;
export declare function loadStackTrace(error: any): Promise<void>;
// ---- Source Map support ----
export declare function loadStackTrace(error: any);

@@ -10,114 +10,115 @@ import { getRequestURL } from "h3";

import { FastResponse } from "srvx";
export default defineNitroErrorHandler(
async function defaultNitroErrorHandler(error, event) {
const res = await defaultHandler(error, event);
return new FastResponse(
typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2),
res
);
}
);
export default defineNitroErrorHandler(async function defaultNitroErrorHandler(error, event) {
const res = await defaultHandler(error, event);
return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res);
});
export async function defaultHandler(error, event, opts) {
const isSensitive = error.unhandled;
const status = error.status || 500;
const url = getRequestURL(event, { xForwardedHost: true, xForwardedProto: true });
if (status === 404) {
const baseURL = import.meta.baseURL || "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) {
const redirectTo = `${baseURL}${url.pathname.slice(1)}${url.search}`;
return {
status: 302,
statusText: "Found",
headers: { location: redirectTo },
body: `Redirecting...`
};
}
}
await loadStackTrace(error).catch(consola.error);
const youch = new Youch();
if (isSensitive && !opts?.silent) {
const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), ".");
consola.error(
`[request error] ${tags} [${event.req.method}] ${url}
`,
ansiError
);
}
const useJSON = opts?.json || !event.req.headers.get("accept")?.includes("text/html");
const headers = {
"content-type": useJSON ? "application/json" : "text/html",
// Prevent browser from guessing the MIME types of resources.
"x-content-type-options": "nosniff",
// Prevent error page from being embedded in an iframe
"x-frame-options": "DENY",
// Prevent browsers from sending the Referer header
"referrer-policy": "no-referrer",
// Disable the execution of any js
"content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';"
};
if (status === 404 || !event.res.headers.has("cache-control")) {
headers["cache-control"] = "no-cache";
}
const body = useJSON ? {
error: true,
url,
status,
statusText: error.statusText,
message: error.message,
data: error.data,
stack: error.stack?.split("\n").map((line) => line.trim())
} : await youch.toHTML(error, {
request: {
url: url.href,
method: event.req.method,
headers: Object.fromEntries(event.req.headers.entries())
}
});
return {
status,
statusText: error.statusText,
headers,
body
};
const isSensitive = error.unhandled;
const status = error.status || 500;
// prettier-ignore
const url = getRequestURL(event, {
xForwardedHost: true,
xForwardedProto: true
});
// Redirects with base URL
if (status === 404) {
const baseURL = import.meta.baseURL || "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) {
const redirectTo = `${baseURL}${url.pathname.slice(1)}${url.search}`;
return {
status: 302,
statusText: "Found",
headers: { location: redirectTo },
body: `Redirecting...`
};
}
}
// Load stack trace with source maps
await loadStackTrace(error).catch(consola.error);
// https://github.com/poppinss/youch
const youch = new Youch();
// Console output
if (isSensitive && !opts?.silent) {
// prettier-ignore
const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), ".");
consola.error(`[request error] ${tags} [${event.req.method}] ${url}\n\n`, ansiError);
}
// Use HTML response only when user-agent expects it (browsers)
const useJSON = opts?.json || !event.req.headers.get("accept")?.includes("text/html");
// Prepare headers
const headers = {
"content-type": useJSON ? "application/json" : "text/html",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"referrer-policy": "no-referrer",
"content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';"
};
if (status === 404 || !event.res.headers.has("cache-control")) {
headers["cache-control"] = "no-cache";
}
// Prepare body
const body = useJSON ? {
error: true,
url,
status,
statusText: error.statusText,
message: error.message,
data: error.data,
stack: error.stack?.split("\n").map((line) => line.trim())
} : await youch.toHTML(error, { request: {
url: url.href,
method: event.req.method,
headers: Object.fromEntries(event.req.headers.entries())
} });
return {
status,
statusText: error.statusText,
headers,
body
};
}
// ---- Source Map support ----
export async function loadStackTrace(error) {
if (!(error instanceof Error)) {
return;
}
const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error);
const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n");
Object.defineProperty(error, "stack", { value: stack });
if (error.cause) {
await loadStackTrace(error.cause).catch(consola.error);
}
if (!(error instanceof Error)) {
return;
}
const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error);
const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n");
Object.defineProperty(error, "stack", { value: stack });
if (error.cause) {
await loadStackTrace(error.cause).catch(consola.error);
}
}
async function sourceLoader(frame) {
if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") {
return;
}
if (frame.type === "app") {
const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {
});
if (rawSourceMap) {
const consumer = await new SourceMapConsumer(rawSourceMap);
const originalPosition = consumer.originalPositionFor({ line: frame.lineNumber, column: frame.columnNumber });
if (originalPosition.source && originalPosition.line) {
frame.fileName = resolve(dirname(frame.fileName), originalPosition.source);
frame.lineNumber = originalPosition.line;
frame.columnNumber = originalPosition.column || 0;
}
}
}
const contents = await readFile(frame.fileName, "utf8").catch(() => {
});
return contents ? { contents } : void 0;
if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") {
return;
}
if (frame.type === "app") {
// prettier-ignore
const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {});
if (rawSourceMap) {
const consumer = await new SourceMapConsumer(rawSourceMap);
// prettier-ignore
const originalPosition = consumer.originalPositionFor({
line: frame.lineNumber,
column: frame.columnNumber
});
if (originalPosition.source && originalPosition.line) {
// prettier-ignore
frame.fileName = resolve(dirname(frame.fileName), originalPosition.source);
frame.lineNumber = originalPosition.line;
frame.columnNumber = originalPosition.column || 0;
}
}
}
const contents = await readFile(frame.fileName, "utf8").catch(() => {});
return contents ? { contents } : undefined;
}
function fmtFrame(frame) {
if (frame.type === "native") {
return frame.raw;
}
const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`;
return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`;
if (frame.type === "native") {
return frame.raw;
}
const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`;
return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`;
}
import type { HTTPError, HTTPEvent } from "h3";
import type { InternalHandlerResponse } from "./utils.mjs";
declare const _default: NitroErrorHandler;
export default _default;
import type { NitroErrorHandler } from "nitro/types";
declare const errorHandler: NitroErrorHandler;
export default errorHandler;
export declare function defaultHandler(error: HTTPError, event: HTTPEvent, opts?: {
silent?: boolean;
json?: boolean;
silent?: boolean;
json?: boolean;
}): InternalHandlerResponse;

@@ -1,62 +0,54 @@

import { getRequestURL } from "h3";
import { defineNitroErrorHandler } from "./utils.mjs";
import { FastResponse } from "srvx";
export default defineNitroErrorHandler(
function defaultNitroErrorHandler(error, event) {
const res = defaultHandler(error, event);
return new FastResponse(JSON.stringify(res.body, null, 2), res);
}
);
const errorHandler = (error, event) => {
const res = defaultHandler(error, event);
return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res);
};
export default errorHandler;
export function defaultHandler(error, event, opts) {
const isSensitive = error.unhandled;
const status = error.status || 500;
const url = getRequestURL(event, { xForwardedHost: true, xForwardedProto: true });
if (status === 404) {
const baseURL = import.meta.baseURL || "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) {
const redirectTo = `${baseURL}${url.pathname.slice(1)}${url.search}`;
return {
status: 302,
statusText: "Found",
headers: { location: redirectTo },
body: `Redirecting...`
};
}
}
if (isSensitive && !opts?.silent) {
const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
console.error(
`[request error] ${tags} [${event.req.method}] ${url}
`,
error
);
}
const headers = {
"content-type": "application/json",
// Prevent browser from guessing the MIME types of resources.
"x-content-type-options": "nosniff",
// Prevent error page from being embedded in an iframe
"x-frame-options": "DENY",
// Prevent browsers from sending the Referer header
"referrer-policy": "no-referrer",
// Disable the execution of any js
"content-security-policy": "script-src 'none'; frame-ancestors 'none';"
};
if (status === 404 || !event.res.headers.has("cache-control")) {
headers["cache-control"] = "no-cache";
}
const body = {
error: true,
url: url.href,
status,
statusText: error.statusText,
message: isSensitive ? "Server Error" : error.message,
data: isSensitive ? void 0 : error.data
};
return {
status,
statusText: error.statusText,
headers,
body
};
const isSensitive = error.unhandled;
const status = error.status || 500;
const url = event.url || new URL(event.req.url);
if (status === 404) {
const baseURL = import.meta.baseURL || "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) {
const redirectTo = `${baseURL}${url.pathname.slice(1)}${url.search}`;
return {
status: 302,
statusText: "Found",
headers: { location: redirectTo },
body: `Redirecting...`
};
}
}
// Console output
if (isSensitive && !opts?.silent) {
// prettier-ignore
const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
console.error(`[request error] ${tags} [${event.req.method}] ${url}\n`, error);
}
// Send response
const headers = {
"content-type": "application/json",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"referrer-policy": "no-referrer",
"content-security-policy": "script-src 'none'; frame-ancestors 'none';"
};
if (status === 404 || !event.res.headers.has("cache-control")) {
headers["cache-control"] = "no-cache";
}
const body = {
error: true,
url: url.href,
status,
statusText: error.statusText,
message: isSensitive ? "Server Error" : error.message,
data: isSensitive ? undefined : error.data
};
return {
status,
statusText: error.statusText,
headers,
body
};
}
import type { NitroErrorHandler } from "nitro/types";
export declare function defineNitroErrorHandler(handler: NitroErrorHandler): NitroErrorHandler;
export type InternalHandlerResponse = {
status: number;
statusText: string | undefined;
headers: Record<string, string>;
body: string | Record<string, any>;
status: number;
statusText: string | undefined;
headers: Record<string, string>;
body: string | Record<string, any>;
};
export function defineNitroErrorHandler(handler) {
return handler;
return handler;
}
import type { NitroRouteMeta } from "nitro/types";
export declare function defineRouteMeta(meta: NitroRouteMeta): NitroRouteMeta;
export declare function defineRouteMeta(meta: NitroRouteMeta);
export function defineRouteMeta(meta) {
return meta;
return meta;
}
import type { NitroAppPlugin } from "nitro/types";
export declare function defineNitroPlugin(def: NitroAppPlugin): NitroAppPlugin;
export declare const nitroPlugin: typeof defineNitroPlugin;
export declare function defineNitroPlugin(def: NitroAppPlugin);
export declare const nitroPlugin: unknown;
export function defineNitroPlugin(def) {
return def;
return def;
}
export const nitroPlugin = defineNitroPlugin;

@@ -1,8 +0,8 @@

import type { Middleware } from "h3";
import type { MatchedRouteRule, NitroRouteRules } from "nitro/types";
type RouteRuleCtor<T extends keyof NitroRouteRules> = (m: MatchedRouteRule<T>) => Middleware;
export declare const headers: RouteRuleCtor<"headers">;
export declare const redirect: RouteRuleCtor<"redirect">;
export declare const proxy: RouteRuleCtor<"proxy">;
export declare const cache: RouteRuleCtor<"cache">;
export {};
// Headers route rule
export declare const headers: unknown;
// Redirect route rule
export declare const redirect: unknown;
// Proxy route rule
export declare const proxy: unknown;
// Cache route rule
export declare const cache: unknown;
import { proxyRequest, redirect as sendRedirect } from "h3";
import { joinURL, withQuery, withoutBase } from "ufo";
import { defineCachedEventHandler } from "./cache.mjs";
import { defineCachedHandler } from "./cache.mjs";
// Headers route rule
export const headers = ((m) => function headersRouteRule(event) {
for (const [key, value] of Object.entries(m.options || {})) {
event.res.headers.set(key, value);
}
for (const [key, value] of Object.entries(m.options || {})) {
event.res.headers.set(key, value);
}
});
// Redirect route rule
export const redirect = ((m) => function redirectRouteRule(event) {
let target = m.options?.to;
if (!target) {
return;
}
if (target.endsWith("/**")) {
let targetPath = event.url.pathname + event.url.search;
const strpBase = m.options._redirectStripBase;
if (strpBase) {
targetPath = withoutBase(targetPath, strpBase);
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.url.search) {
target = withQuery(target, Object.fromEntries(event.url.searchParams));
}
return sendRedirect(target, m.options?.status);
let target = m.options?.to;
if (!target) {
return;
}
if (target.endsWith("/**")) {
let targetPath = event.url.pathname + event.url.search;
const strpBase = m.options._redirectStripBase;
if (strpBase) {
targetPath = withoutBase(targetPath, strpBase);
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.url.search) {
target = withQuery(target, Object.fromEntries(event.url.searchParams));
}
return sendRedirect(target, m.options?.status);
});
// Proxy route rule
export const proxy = ((m) => function proxyRouteRule(event) {
let target = m.options?.to;
if (!target) {
return;
}
if (target.endsWith("/**")) {
let targetPath = event.url.pathname + event.url.search;
const strpBase = m.options._proxyStripBase;
if (strpBase) {
targetPath = withoutBase(targetPath, strpBase);
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.url.search) {
target = withQuery(target, Object.fromEntries(event.url.searchParams));
}
return proxyRequest(event, target, {
...m.options
});
let target = m.options?.to;
if (!target) {
return;
}
if (target.endsWith("/**")) {
let targetPath = event.url.pathname + event.url.search;
const strpBase = m.options._proxyStripBase;
if (strpBase) {
targetPath = withoutBase(targetPath, strpBase);
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.url.search) {
target = withQuery(target, Object.fromEntries(event.url.searchParams));
}
return proxyRequest(event, target, { ...m.options });
});
// Cache route rule
export const cache = ((m) => function cacheRouteRule(event, next) {
if (!event.context.matchedRoute) {
return next();
}
const cachedHandlers = globalThis.__nitroCachedHandlers ??= /* @__PURE__ */ new Map();
const { handler, route } = event.context.matchedRoute;
const key = `${m.route}:${route}`;
let cachedHandler = cachedHandlers.get(key);
if (!cachedHandler) {
cachedHandler = defineCachedEventHandler(handler, {
group: "nitro/route-rules",
name: key,
...m.options
});
cachedHandlers.set(key, cachedHandler);
}
return cachedHandler(event);
if (!event.context.matchedRoute) {
return next();
}
const cachedHandlers = globalThis.__nitroCachedHandlers ??= new Map();
const { handler, route } = event.context.matchedRoute;
const key = `${m.route}:${route}`;
let cachedHandler = cachedHandlers.get(key);
if (!cachedHandler) {
cachedHandler = defineCachedHandler(handler, {
group: "nitro/route-rules",
name: key,
...m.options
});
cachedHandlers.set(key, cachedHandler);
}
return cachedHandler(event);
});

@@ -1,3 +0,2 @@

import { H3 } from "h3";
declare const _default: H3;
declare const _default;
export default _default;
import { H3 } from "h3";
import { runTask } from "nitro/runtime";
import { runTask } from "../task.mjs";
import { scheduledTasks, tasks } from "#nitro-internal-virtual/tasks";
export default new H3().get("/_nitro/tasks", async () => {
const _tasks = await Promise.all(
Object.entries(tasks).map(async ([name, task]) => {
const _task = await task.resolve?.();
return [name, { description: _task?.meta?.description }];
})
);
return {
tasks: Object.fromEntries(_tasks),
scheduledTasks
};
const _tasks = await Promise.all(Object.entries(tasks).map(async ([name, task]) => {
const _task = await task.resolve?.();
return [name, { description: _task?.meta?.description }];
}));
return {
tasks: Object.fromEntries(_tasks),
scheduledTasks
};
}).get("/_nitro/tasks/:name", async (event) => {
const name = event.context.params?.name;
const body = await event.req.json().catch(() => ({}));
const payload = {
...Object.fromEntries(event.url.searchParams.entries()),
...body
};
return await runTask(name, { payload });
const name = event.context.params?.name;
const body = await event.req.json().catch(() => ({}));
const payload = {
...Object.fromEntries(event.url.searchParams.entries()),
...body
};
return await runTask(name, { payload });
});
import type { EventHandler } from "h3";
// Served as /_openapi.json
declare const _default: EventHandler;
export default _default;

@@ -6,96 +6,90 @@ import { defineHandler, getRequestURL } from "h3";

import { useRuntimeConfig } from "../runtime-config.mjs";
// Served as /_openapi.json
export default defineHandler((event) => {
const runtimeConfig = useRuntimeConfig();
const base = runtimeConfig.app?.baseURL;
const url = joinURL(getRequestURL(event).origin, base);
const meta = {
title: "Nitro Server Routes",
...runtimeConfig.nitro?.openAPI?.meta
};
const {
paths,
globals: { components, ...globalsRest }
} = getHandlersMeta();
const extensible = Object.fromEntries(
Object.entries(globalsRest).filter(([key]) => key.startsWith("x-"))
);
return {
openapi: "3.1.0",
info: {
title: meta?.title,
version: meta?.version,
description: meta?.description
},
servers: [
{
url,
description: "Local Development Server",
variables: {}
}
],
paths,
components,
...extensible
};
const runtimeConfig = useRuntimeConfig();
const base = runtimeConfig.app?.baseURL;
const url = joinURL(getRequestURL(event).origin, base);
const meta = {
title: "Nitro Server Routes",
...runtimeConfig.nitro?.openAPI?.meta
};
const { paths, globals: { components,...globalsRest } } = getHandlersMeta();
const extensible = Object.fromEntries(Object.entries(globalsRest).filter(([key]) => key.startsWith("x-")));
return {
openapi: "3.1.0",
info: {
title: meta?.title,
version: meta?.version || "1.0.0",
description: meta?.description
},
servers: [{
url,
description: "Local Development Server",
variables: {}
}],
paths,
components,
...extensible
};
});
function getHandlersMeta() {
const paths = {};
let globals = {};
for (const h of handlersMeta) {
const { route, parameters } = normalizeRoute(h.route || "");
const tags = defaultTags(h.route || "");
const method = (h.method || "get").toLowerCase();
const { $global, ...openAPI } = h.meta?.openAPI || {};
const item = {
[method]: {
tags,
parameters,
responses: {
200: { description: "OK" }
},
...openAPI
}
};
if ($global) {
globals = defu($global, globals);
}
if (paths[route] === void 0) {
paths[route] = item;
} else {
Object.assign(paths[route], item);
}
}
return { paths, globals };
const paths = {};
let globals = {};
for (const h of handlersMeta) {
const { route, parameters } = normalizeRoute(h.route || "");
const tags = defaultTags(h.route || "");
const method = (h.method || "get").toLowerCase();
const { $global,...openAPI } = h.meta?.openAPI || {};
const item = { [method]: {
tags,
parameters,
responses: { 200: { description: "OK" } },
...openAPI
} };
if ($global) {
// TODO: Warn on conflicting global definitions?
globals = defu($global, globals);
}
if (paths[route] === undefined) {
paths[route] = item;
} else {
Object.assign(paths[route], item);
}
}
return {
paths,
globals
};
}
function normalizeRoute(_route) {
const parameters = [];
let anonymousCtr = 0;
const route = _route.replace(/:(\w+)/g, (_, name) => `{${name}}`).replace(/\/(\*)\//g, () => `/{param${++anonymousCtr}}/`).replace(/\*\*{/, "{").replace(/\/(\*\*)$/g, () => `/{*param${++anonymousCtr}}`);
const paramMatches = route.matchAll(/{(\*?\w+)}/g);
for (const match of paramMatches) {
const name = match[1];
if (!parameters.some((p) => p.name === name)) {
parameters.push({
name,
in: "path",
required: true,
schema: { type: "string" }
});
}
}
return {
route,
parameters
};
const parameters = [];
let anonymousCtr = 0;
const route = _route.replace(/:(\w+)/g, (_, name) => `{${name}}`).replace(/\/(\*)\//g, () => `/{param${++anonymousCtr}}/`).replace(/\*\*{/, "{").replace(/\/(\*\*)$/g, () => `/{*param${++anonymousCtr}}`);
const paramMatches = route.matchAll(/{(\*?\w+)}/g);
for (const match of paramMatches) {
const name = match[1];
if (!parameters.some((p) => p.name === name)) {
parameters.push({
name,
in: "path",
required: true,
schema: { type: "string" }
});
}
}
return {
route,
parameters
};
}
function defaultTags(route) {
const tags = [];
if (route.startsWith("/api/")) {
tags.push("API Routes");
} else if (route.startsWith("/_")) {
tags.push("Internal");
} else {
tags.push("App Routes");
}
return tags;
const tags = [];
if (route.startsWith("/api/")) {
tags.push("API Routes");
} else if (route.startsWith("/_")) {
tags.push("Internal");
} else {
tags.push("App Routes");
}
return tags;
}
import type { H3Event } from "h3";
export default function renderIndexHTML(event: H3Event): any;
export default function renderIndexHTML(event: H3Event);
import type { H3Event } from "h3";
import { HTTPResponse } from "h3";
export default function renderIndexHTML(event: H3Event): Promise<Response | HTTPResponse>;
export default function renderIndexHTML(event: H3Event);

@@ -1,21 +0,19 @@

import {
rendererTemplate,
rendererTemplateFile
} from "#nitro-internal-virtual/renderer-template";
import { serverFetch } from "../app.mjs";
import { rendererTemplate, rendererTemplateFile, isStaticTemplate } from "#nitro-internal-virtual/renderer-template";
import { HTTPResponse } from "h3";
import { hasTemplateSyntax, renderToResponse, compileTemplate } from "rendu";
export default async function renderIndexHTML(event) {
let html = await rendererTemplate(event.req);
if (globalThis.__transform_html__) {
html = await globalThis.__transform_html__(html);
}
if (!hasTemplateSyntax(html)) {
return new HTTPResponse(html, {
headers: { "content-type": "text/html; charset=utf-8" }
});
}
const template = compileTemplate(html, { filename: rendererTemplateFile });
return renderToResponse(template, {
request: event.req
});
let html = await rendererTemplate(event.req);
if (globalThis.__transform_html__) {
html = await globalThis.__transform_html__(html);
}
const isStatic = isStaticTemplate ?? !hasTemplateSyntax(html);
if (isStatic) {
return new HTTPResponse(html, { headers: { "content-type": "text/html; charset=utf-8" } });
}
const template = compileTemplate(html, { filename: rendererTemplateFile });
return renderToResponse(template, {
request: event.req,
context: { serverFetch }
});
}
import { rendererTemplate } from "#nitro-internal-virtual/renderer-template";
export default function renderIndexHTML(event) {
return rendererTemplate(event.req);
return rendererTemplate(event.req);
}
import { type EventHandler } from "h3";
// Served as /_scalar
declare const _default: EventHandler;
export default _default;
import { defineHandler } from "h3";
import { useRuntimeConfig } from "../runtime-config.mjs";
// Served as /_scalar
export default defineHandler((event) => {
const runtimeConfig = useRuntimeConfig();
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json";
const _config = runtimeConfig.nitro.openAPI?.ui?.scalar;
const scalarConfig = {
..._config,
url: openAPIEndpoint,
// @ts-expect-error (missing types?)
spec: { url: openAPIEndpoint, ..._config?.spec }
};
event.res.headers.set("Content-Type", "text/html");
return (
/* html */
`<!doctype html>
const runtimeConfig = useRuntimeConfig();
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json";
// https://github.com/scalar/scalar
const _config = runtimeConfig.nitro.openAPI?.ui?.scalar;
const scalarConfig = {
..._config,
url: openAPIEndpoint,
spec: {
url: openAPIEndpoint,
..._config?.spec
}
};
// The default page title
event.res.headers.set("Content-Type", "text/html");
return `<!doctype html>
<html lang="en">

@@ -32,12 +35,9 @@ <head>

id="api-reference"
data-configuration="${JSON.stringify(scalarConfig).split('"').join("&quot;")}"
data-configuration="${JSON.stringify(scalarConfig).split("\"").join("&quot;")}"
><\/script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
</body>
</html>`
);
</html>`;
});
const customTheme = (
/* css */
`/* basic theme */
const customTheme = `/* basic theme */
.light-mode,

@@ -194,3 +194,2 @@ .light-mode .dark-mode {

overflow: hidden;
}`
);
}`;
import type { EventHandler } from "h3";
// https://github.com/swagger-api/swagger-ui
declare const _default: EventHandler;
export default _default;
import { defineHandler } from "h3";
import { useRuntimeConfig } from "../runtime-config.mjs";
// https://github.com/swagger-api/swagger-ui
export default defineHandler((event) => {
const runtimeConfig = useRuntimeConfig();
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json";
const CDN_BASE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@^5";
event.res.headers.set("Content-Type", "text/html");
return (
/* html */
`<!doctype html>
const runtimeConfig = useRuntimeConfig();
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json";
const CDN_BASE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@^5";
event.res.headers.set("Content-Type", "text/html");
return `<!doctype html>
<html lang="en">

@@ -42,4 +41,3 @@ <head>

</body>
</html> `
);
</html> `;
});
import type { NitroRuntimeConfig } from "nitro/types";
export declare function useRuntimeConfig(): NitroRuntimeConfig;
type EnvOptions = {
prefix?: string;
altPrefix?: string;
envExpansion?: boolean;
prefix?: string;
altPrefix?: string;
envExpansion?: boolean;
};
export declare function applyEnv(obj: Record<string, any>, opts: EnvOptions, parentKey?: string): Record<string, any>;
export declare function applyEnv(obj: Record<string, any>, opts: EnvOptions, parentKey?: string);
export {};

@@ -0,49 +1,54 @@

import { runtimeConfig } from "#nitro-internal-virtual/runtime-config";
import { snakeCase } from "scule";
export function useRuntimeConfig() {
return useRuntimeConfig._cached ||= getRuntimeConfig();
return useRuntimeConfig._cached ||= getRuntimeConfig();
}
function getRuntimeConfig() {
const runtimeConfig = globalThis.__NITRO_RUNTIME_CONFIG__ || process.env.RUNTIME_CONFIG || {};
const env = globalThis.process?.env || {};
applyEnv(runtimeConfig, {
prefix: "NITRO_",
altPrefix: runtimeConfig.nitro?.envPrefix ?? env?.NITRO_ENV_PREFIX ?? "_",
envExpansion: runtimeConfig.nitro?.envExpansion ?? env?.NITRO_ENV_EXPANSION ?? false
});
return runtimeConfig;
const env = globalThis.process?.env || {};
applyEnv(runtimeConfig, {
prefix: "NITRO_",
altPrefix: runtimeConfig.nitro?.envPrefix ?? env?.NITRO_ENV_PREFIX ?? "_",
envExpansion: Boolean(runtimeConfig.nitro?.envExpansion ?? env?.NITRO_ENV_EXPANSION ?? false)
});
return runtimeConfig;
}
function getEnv(key, opts) {
const envKey = snakeCase(key).toUpperCase();
return process.env[opts.prefix + envKey] ?? process.env[opts.altPrefix + envKey];
const envKey = snakeCase(key).toUpperCase();
return process.env[opts.prefix + envKey] ?? process.env[opts.altPrefix + envKey];
}
function _isObject(input) {
return typeof input === "object" && !Array.isArray(input);
return typeof input === "object" && !Array.isArray(input);
}
export function applyEnv(obj, opts, parentKey = "") {
for (const key in obj) {
const subKey = parentKey ? `${parentKey}_${key}` : key;
const envValue = getEnv(subKey, opts);
if (_isObject(obj[key])) {
if (_isObject(envValue)) {
obj[key] = { ...obj[key], ...envValue };
applyEnv(obj[key], opts, subKey);
} else if (envValue === void 0) {
applyEnv(obj[key], opts, subKey);
} else {
obj[key] = envValue ?? obj[key];
}
} else {
obj[key] = envValue ?? obj[key];
}
if (opts.envExpansion && typeof obj[key] === "string") {
obj[key] = _expandFromEnv(obj[key]);
}
}
return obj;
for (const key in obj) {
const subKey = parentKey ? `${parentKey}_${key}` : key;
const envValue = getEnv(subKey, opts);
if (_isObject(obj[key])) {
// Same as before
if (_isObject(envValue)) {
obj[key] = {
...obj[key],
...envValue
};
applyEnv(obj[key], opts, subKey);
} else if (envValue === undefined) {
applyEnv(obj[key], opts, subKey);
} else {
obj[key] = envValue ?? obj[key];
}
} else {
obj[key] = envValue ?? obj[key];
}
// Experimental env expansion
if (opts.envExpansion && typeof obj[key] === "string") {
obj[key] = _expandFromEnv(obj[key]);
}
}
return obj;
}
const envExpandRx = /\{\{([^{}]*)\}\}/g;
function _expandFromEnv(value) {
return value.replace(envExpandRx, (match, key) => {
return process.env[key] || match;
});
return value.replace(envExpandRx, (match, key) => {
return process.env[key] || match;
});
}
import { HTTPError, defineHandler } from "h3";
import {
decodePath,
joinURL,
withLeadingSlash,
withoutTrailingSlash
} from "ufo";
import {
getAsset,
isPublicAssetURL,
readAsset
} from "#nitro-internal-virtual/public-assets";
const METHODS = /* @__PURE__ */ new Set(["HEAD", "GET"]);
const EncodingMap = { gzip: ".gz", br: ".br" };
import { decodePath, joinURL, withLeadingSlash, withoutTrailingSlash } from "ufo";
import { getAsset, isPublicAssetURL, readAsset } from "#nitro-internal-virtual/public-assets";
const METHODS = new Set(["HEAD", "GET"]);
const EncodingMap = {
gzip: ".gz",
br: ".br"
};
export default defineHandler((event) => {
if (event.req.method && !METHODS.has(event.req.method)) {
return;
}
let id = decodePath(
withLeadingSlash(withoutTrailingSlash(event.url.pathname))
);
let asset;
const encodingHeader = event.req.headers.get("accept-encoding") || "";
const encodings = [
...encodingHeader.split(",").map((e) => EncodingMap[e.trim()]).filter(Boolean).sort(),
""
];
if (encodings.length > 1) {
event.res.headers.append("Vary", "Accept-Encoding");
}
for (const encoding of encodings) {
for (const _id of [id + encoding, joinURL(id, "index.html" + encoding)]) {
const _asset = getAsset(_id);
if (_asset) {
asset = _asset;
id = _id;
break;
}
}
}
if (!asset) {
if (isPublicAssetURL(id)) {
event.res.headers.delete("Cache-Control");
throw new HTTPError({ status: 404 });
}
return;
}
const ifNotMatch = event.req.headers.get("if-none-match") === asset.etag;
if (ifNotMatch) {
event.res.status = 304;
event.res.statusText = "Not Modified";
return "";
}
const ifModifiedSinceH = event.req.headers.get("if-modified-since");
const mtimeDate = new Date(asset.mtime);
if (ifModifiedSinceH && asset.mtime && new Date(ifModifiedSinceH) >= mtimeDate) {
event.res.status = 304;
event.res.statusText = "Not Modified";
return "";
}
if (asset.type) {
event.res.headers.set("Content-Type", asset.type);
}
if (asset.etag && !event.res.headers.has("ETag")) {
event.res.headers.set("ETag", asset.etag);
}
if (asset.mtime && !event.res.headers.has("Last-Modified")) {
event.res.headers.set("Last-Modified", mtimeDate.toUTCString());
}
if (asset.encoding && !event.res.headers.has("Content-Encoding")) {
event.res.headers.set("Content-Encoding", asset.encoding);
}
if (asset.size > 0 && !event.res.headers.has("Content-Length")) {
event.res.headers.set("Content-Length", asset.size.toString());
}
return readAsset(id);
if (event.req.method && !METHODS.has(event.req.method)) {
return;
}
let id = decodePath(withLeadingSlash(withoutTrailingSlash(event.url.pathname)));
let asset;
const encodingHeader = event.req.headers.get("accept-encoding") || "";
const encodings = [...encodingHeader.split(",").map((e) => EncodingMap[e.trim()]).filter(Boolean).sort(), ""];
if (encodings.length > 1) {
event.res.headers.append("Vary", "Accept-Encoding");
}
for (const encoding of encodings) {
for (const _id of [id + encoding, joinURL(id, "index.html" + encoding)]) {
const _asset = getAsset(_id);
if (_asset) {
asset = _asset;
id = _id;
break;
}
}
}
if (!asset) {
if (isPublicAssetURL(id)) {
event.res.headers.delete("Cache-Control");
throw new HTTPError({ status: 404 });
}
return;
}
const ifNotMatch = event.req.headers.get("if-none-match") === asset.etag;
if (ifNotMatch) {
event.res.status = 304;
event.res.statusText = "Not Modified";
return "";
}
const ifModifiedSinceH = event.req.headers.get("if-modified-since");
const mtimeDate = new Date(asset.mtime);
if (ifModifiedSinceH && asset.mtime && new Date(ifModifiedSinceH) >= mtimeDate) {
event.res.status = 304;
event.res.statusText = "Not Modified";
return "";
}
if (asset.type) {
event.res.headers.set("Content-Type", asset.type);
}
if (asset.etag && !event.res.headers.has("ETag")) {
event.res.headers.set("ETag", asset.etag);
}
if (asset.mtime && !event.res.headers.has("Last-Modified")) {
event.res.headers.set("Last-Modified", mtimeDate.toUTCString());
}
if (asset.encoding && !event.res.headers.has("Content-Encoding")) {
event.res.headers.set("Content-Encoding", asset.encoding);
}
if (asset.size > 0 && !event.res.headers.has("Content-Length")) {
event.res.headers.set("Content-Length", asset.size.toString());
}
return readAsset(id);
});
import { prefixStorage } from "unstorage";
import { initStorage } from "#nitro-internal-virtual/storage";
export function useStorage(base = "") {
const storage = useStorage._storage ??= initStorage();
return base ? prefixStorage(storage, base) : storage;
const storage = useStorage._storage ??= initStorage();
return base ? prefixStorage(storage, base) : storage;
}

@@ -5,8 +5,8 @@ import type { Task, TaskContext, TaskPayload, TaskResult } from "nitro/types";

/** @experimental */
export declare function runTask<RT = unknown>(name: string, { payload, context, }?: {
payload?: TaskPayload;
context?: TaskContext;
export declare function runTask<RT = unknown>(name: string, { payload, context }?: {
payload?: TaskPayload;
context?: TaskContext;
}): Promise<TaskResult<RT>>;
/** @experimental */
export declare function startScheduleRunner(): void;
export declare function startScheduleRunner();
/** @experimental */

@@ -16,4 +16,4 @@ export declare function getCronTasks(cron: string): string[];

export declare function runCronTasks(cron: string, ctx: {
payload?: TaskPayload;
context?: TaskContext;
payload?: TaskPayload;
context?: TaskContext;
}): Promise<TaskResult[]>;
import { Cron } from "croner";
import { HTTPError } from "h3";
import { isTest } from "std-env";
import { scheduledTasks, tasks } from "#nitro-internal-virtual/tasks";
/** @experimental */
export function defineTask(def) {
if (typeof def.run !== "function") {
def.run = () => {
throw new TypeError("Task must implement a `run` method!");
};
}
return def;
if (typeof def.run !== "function") {
def.run = () => {
throw new TypeError("Task must implement a `run` method!");
};
}
return def;
}
const __runningTasks__ = {};
export async function runTask(name, {
payload = {},
context = {}
} = {}) {
if (__runningTasks__[name]) {
return __runningTasks__[name];
}
if (!(name in tasks)) {
throw new HTTPError({
message: `Task \`${name}\` is not available!`,
status: 404
});
}
if (!tasks[name].resolve) {
throw new HTTPError({
message: `Task \`${name}\` is not implemented!`,
status: 501
});
}
const handler = await tasks[name].resolve();
const taskEvent = { name, payload, context };
__runningTasks__[name] = handler.run(taskEvent);
try {
const res = await __runningTasks__[name];
return res;
} finally {
delete __runningTasks__[name];
}
/** @experimental */
export async function runTask(name, { payload = {}, context = {} } = {}) {
if (__runningTasks__[name]) {
return __runningTasks__[name];
}
if (!(name in tasks)) {
throw new HTTPError({
message: `Task \`${name}\` is not available!`,
status: 404
});
}
if (!tasks[name].resolve) {
throw new HTTPError({
message: `Task \`${name}\` is not implemented!`,
status: 501
});
}
const handler = await tasks[name].resolve();
const taskEvent = {
name,
payload,
context
};
__runningTasks__[name] = handler.run(taskEvent);
try {
const res = await __runningTasks__[name];
return res;
} finally {
delete __runningTasks__[name];
}
}
/** @experimental */
export function startScheduleRunner() {
if (!scheduledTasks || scheduledTasks.length === 0 || isTest) {
return;
}
const payload = {
scheduledTime: Date.now()
};
for (const schedule of scheduledTasks) {
const cron = new Cron(schedule.cron, async () => {
await Promise.all(
schedule.tasks.map(
(name) => runTask(name, {
payload,
context: {}
}).catch((error) => {
console.error(
`Error while running scheduled task "${name}"`,
error
);
})
)
);
});
}
if (!scheduledTasks || scheduledTasks.length === 0 || process.env.TEST) {
return;
}
const payload = { scheduledTime: Date.now() };
for (const schedule of scheduledTasks) {
new Cron(schedule.cron, async () => {
await Promise.all(schedule.tasks.map((name) => runTask(name, {
payload,
context: {}
}).catch((error) => {
console.error(`Error while running scheduled task "${name}"`, error);
})));
});
}
}
/** @experimental */
export function getCronTasks(cron) {
return (scheduledTasks || []).find((task) => task.cron === cron)?.tasks || [];
return (scheduledTasks || []).find((task) => task.cron === cron)?.tasks || [];
}
/** @experimental */
export function runCronTasks(cron, ctx) {
return Promise.all(getCronTasks(cron).map((name) => runTask(name, ctx)));
return Promise.all(getCronTasks(cron).map((name) => runTask(name, ctx)));
}
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
import wsAdapter from "crossws/adapters/node";
import { useNitroApp } from "nitro/app";
import { resolveWebsocketHooks } from "nitro/~internal/runtime/app";
import { hasWebSocket } from "#nitro-internal-virtual/feature-flags";
const nitroApp = useNitroApp();
export const fetch = nitroApp.fetch;
const ws = hasWebSocket
? wsAdapter({ resolve: resolveWebsocketHooks })
: undefined;
export const handleUpgrade = ws?.handleUpgrade;

@@ -8,6 +8,7 @@ import { parentPort, threadId, workerData } from "node:worker_threads";

const envs = { nitro: undefined, ssr: undefined };
const envs = (globalThis.__nitro_vite_envs__ ??= {
nitro: undefined,
ssr: undefined,
});
globalThis.__nitro_vite_envs__ = envs;
class EnvRunner {

@@ -154,56 +155,2 @@ constructor({ name, entry }) {

// ----- Fetch Handler -----
const originalFetch = globalThis.fetch;
globalThis.fetch = function nitroViteFetch(input, init) {
// Only override if viteEnvName is specified
const viteEnvName = getViteEnv(init) || getViteEnv(input);
if (!viteEnvName) {
return originalFetch(input, init);
}
// Validate viteEnv
const viteEnv = envs[viteEnvName];
if (!viteEnv) {
throw httpError(404, `Unknown vite environment "${viteEnvName}"`);
}
// Normalize input (relative urls)
if (typeof input === "string" && input[0] === "/") {
input = new URL(input, "http://localhost");
}
// Clone headers and set viteEnv header
const headers = new Headers(init?.headers || {});
headers.set("x-vite-env", viteEnvName);
// Normalize to Request
if (
!(input instanceof Request) ||
(init && Object.keys(init).join("") !== "viteEnv")
) {
input = new Request(input, init);
}
// Fetch via vite env
return viteEnv.fetch(input);
};
function getViteEnv(input) {
if (!input || typeof input !== "object") {
return;
}
if ("viteEnv" in input) {
return input.viteEnv;
}
if (input.headers) {
return (
input.headers["x-vite-env"] ||
input.headers.get?.("x-vite-env") ||
(Array.isArray(input.headers) &&
input.headers.find((h) => h[0].toLowerCase() === "x-vite-env")?.[1])
);
}
}
// ----- Server -----

@@ -245,2 +192,7 @@

server.on("upgrade", (req, socket, head) => {
const handleUpgrade = envs["nitro"]?.entry?.handleUpgrade;
handleUpgrade?.(req, socket, head);
});
parentPort.on("message", async (message) => {

@@ -247,0 +199,0 @@ if (message?.type === "full-reload") {

@@ -0,4 +1,6 @@

import { fetchViteEnv } from "nitro/vite/runtime";
/** @param {{ req: Request }} HTTPEvent */
export default function ssrRenderer({ req }) {
return fetch(req, { viteEnv: "ssr" });
return fetchViteEnv("ssr", req);
}

@@ -1,1 +0,1 @@

export { };

@@ -1,59 +0,57 @@

import { PluginOption } from 'vite';
import { NitroConfig, Nitro } from 'nitro/types';
import "./_dev.mjs";
import "unenv";
import { Plugin } from "vite";
import "rollup";
import { Nitro, NitroConfig, NitroModule } from "nitro/types";
//#region src/build/vite/types.d.ts
declare module "vite" {
interface UserConfig {
/**
* Nitro Vite Plugin options.
*/
nitro?: NitroConfig;
}
}
interface NitroPluginConfig {
/** Custom Nitro config */
config?: NitroConfig;
interface UserConfig {
/**
* Fetchable service environments automatically created by the plugin.
*
* **Note:** You can use top level `environments` with same keys to extend environment configurations.
* Nitro Vite Plugin options.
*/
services?: Record<string, ServiceConfig>;
/**
* @internal Pre-initialized Nitro instance.
*/
_nitro?: Nitro;
experimental?: {
/**
* @experimental Use the virtual filesystem for intermediate environment build output files.
* @note This is unsafe if plugins rely on temporary files on the filesystem.
*/
virtualBundle?: boolean;
nitro?: NitroConfig;
}
interface Plugin {
nitro?: NitroModule;
}
}
declare module "rollup" {
interface Plugin {
nitro?: NitroModule;
}
}
interface NitroPluginConfig extends NitroConfig {
/**
* @internal Use preinitialized Nitro instance for the plugin.
*/
_nitro?: Nitro;
experimental?: NitroConfig["experimental"] & {
vite: {
/**
* @experimental Use the virtual filesystem for intermediate environment build output files.
* @note This is unsafe if plugins rely on temporary files on the filesystem.
*/
virtualBundle?: boolean;
/**
* @experimental Enable `?assets` import proposed by https://github.com/vitejs/vite/discussions/20913
* @default true
*/
assetsImport?: boolean;
/**
* Reload the page when a server module is updated.
*
* @default true
*/
serverReload: boolean;
};
};
}
interface ServiceConfig {
/**
* Path to the service entrypoint file.
*
* Services should export a web standard fetch handler function.
*
* Example:
* ```ts
* export default async (req: Request) => {
* return Response.json({ message: "Hello from service!" });
* };
* ```
*/
entry: string;
/**
* Service route.
*
* - If `route` is not set, services are only accessible via `fetch("<url>", { viteEnv: "<name>" })`.
* - `ssr` service is special and defaults to `"/**"` route, meaning it will handle all requests.
*/
route?: string;
entry: string;
}
declare function nitro(pluginConfig?: NitroPluginConfig): PluginOption;
export { nitro };
export type { NitroPluginConfig, ServiceConfig };
//#endregion
//#region src/build/vite/plugin.d.ts
declare function nitro(pluginConfig?: NitroPluginConfig): Plugin[];
//#endregion
export { type NitroPluginConfig, type ServiceConfig, nitro };

@@ -1,68 +0,44 @@

export { n as nitro } from './_chunks/plugin.mjs';
import './_chunks/index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './_chunks/pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './_chunks/app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
import 'nitro/meta';
import 'srvx/node';
import './_chunks/index2.mjs';
import './_chunks/info.mjs';
import 'unenv';
import 'node:buffer';
import 'node:querystring';
import 'constants';
import 'node:crypto';
import 'db0';
import 'esbuild';
import 'nf3';
import 'rendu';
import 'vite';
import 'get-port-please';
import 'node:child_process';
import "./_libs/c12.mjs";
import "./_libs/gen-mapping.mjs";
import "./_libs/magic-string.mjs";
import "./_libs/acorn.mjs";
import "./_libs/confbox.mjs";
import "./_libs/local-pkg.mjs";
import "./_libs/js-tokens.mjs";
import "./_libs/strip-literal.mjs";
import "./_libs/unimport.mjs";
import "./_libs/picomatch.mjs";
import "./_libs/fdir.mjs";
import "./_libs/tinyglobby.mjs";
import "./_libs/compatx.mjs";
import "./_libs/klona.mjs";
import "./_libs/std-env.mjs";
import "./_chunks/B-D1JOIz.mjs";
import "./_libs/escape-string-regexp.mjs";
import "./_libs/tsconfck.mjs";
import "./_libs/dot-prop.mjs";
import "./_chunks/C7CbzoI1.mjs";
import "./_chunks/ANM1K1bE.mjs";
import "./_libs/rou3.mjs";
import "./_libs/mime.mjs";
import "./_libs/pathe.mjs";
import "./_libs/untyped.mjs";
import "./_libs/knitwork.mjs";
import "./_build/common.mjs";
import "./_libs/httpxy.mjs";
import "./_dev.mjs";
import "./_libs/chokidar.mjs";
import "./_libs/ultrahtml.mjs";
import "./_libs/plugin-alias.mjs";
import "./_libs/estree-walker.mjs";
import "./_libs/plugin-commonjs.mjs";
import "./_libs/plugin-inject.mjs";
import "./_build/common2.mjs";
import "./_libs/remapping.mjs";
import "./_libs/unwasm.mjs";
import "./_libs/plugin-replace.mjs";
import "./_libs/etag.mjs";
import { t as nitro } from "./_build/vite.plugin.mjs";
import "./_libs/vite-plugin-fullstack.mjs";
export { nitro };
{
"name": "nitro",
"version": "3.0.1-alpha.0",
"version": "3.0.1-alpha.1",
"description": "Build and Deploy Universal JavaScript Servers",

@@ -10,18 +10,26 @@ "homepage": "https://nitro.build",

"exports": {
".": "./dist/runtime/nitro.mjs",
"./app": "./dist/runtime/app.mjs",
"./builder": "./dist/builder.mjs",
"./cache": "./dist/runtime/cache.mjs",
"./config": "./dist/runtime/config.mjs",
"./context": "./dist/runtime/context.mjs",
"./database": "./dist/runtime/database.mjs",
"./deps/h3": "./lib/deps/h3.mjs",
"./deps/ofetch": "./lib/deps/ofetch.mjs",
"./h3": "./lib/deps/h3.mjs",
"./meta": "./dist/runtime/meta.mjs",
"./package.json": "./package.json",
".": "./dist/index.mjs",
"./config": "./lib/config.mjs",
"./types": "./dist/types/index.d.mts",
"./meta": "./lib/meta.mjs",
"./runtime": "./dist/runtime/index.mjs",
"./runtime/internal": "./dist/runtime/internal/index.mjs",
"./runtime/meta": "./lib/runtime-meta.mjs",
"./runtime-config": "./dist/runtime/runtime-config.mjs",
"./storage": "./dist/runtime/storage.mjs",
"./task": "./dist/runtime/task.mjs",
"./tsconfig": "./lib/tsconfig.json",
"./types": "./dist/types/index.mjs",
"./vite": "./dist/vite.mjs",
"./h3": "./lib/deps/h3.mjs",
"./deps/h3": "./lib/deps/h3.mjs",
"./deps/ofetch": "./lib/deps/ofetch.mjs"
"./vite/runtime": "./dist/runtime/vite-runtime.mjs",
"./~internal/runtime/*": "./dist/runtime/internal/*.mjs"
},
"types": "./lib/index.d.mts",
"bin": {
"nitro": "./dist/cli/index.mjs",
"nitropack": "./dist/cli/index.mjs"
"nitro": "./dist/cli/index.mjs"
},

@@ -33,3 +41,3 @@ "files": [

"scripts": {
"build": "pnpm gen-presets && unbuild",
"build": "pnpm gen-presets && obuild",
"dev": "pnpm -C playground dev",

@@ -39,14 +47,12 @@ "dev:build": "pnpm -C playground build",

"gen-node-compat": "node scripts/gen-node-compat.ts",
"gen-presets": "pnpm jiti scripts/gen-presets.ts",
"gen-presets": "obuild --stub && node ./scripts/gen-presets.ts",
"lint": "eslint --cache . && prettier -c .",
"lint:fix": "automd && eslint --cache --fix . && prettier -w .",
"nitro": "jiti ./src/cli/index.ts",
"prepack": "pnpm build",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"stub": "unbuild --stub",
"test": "pnpm lint && pnpm vitest run",
"test:fixture:types": "pnpm stub && jiti ./test/scripts/gen-fixture-types.ts && cd test/fixture && tsc --noEmit",
"nitro": "node ./src/cli/index.ts",
"release": "pnpm test && pnpm build && changelogen --release --prerelease --push",
"stub": "obuild --stub",
"test": "pnpm lint && pnpm test:types && pnpm test:rollup && pnpm test:rolldown",
"test:rollup": "NITRO_BUILDER=rollup pnpm vitest",
"test:rolldown": "NITRO_BUILDER=rolldown pnpm vitest",
"test:rollup": "NITRO_BUILDER=rollup pnpm vitest",
"test:types": "tsc --noEmit && pnpm test:fixture:types"
"test:types": "tsc --noEmit"
},

@@ -59,18 +65,15 @@ "resolutions": {

"consola": "^3.4.2",
"cookie-es": "^2.0.0",
"crossws": "^0.4.1",
"db0": "^0.3.4",
"esbuild": "^0.25.10",
"fetchdts": "^0.1.7",
"h3": "2.0.1-rc.2",
"h3": "2.0.1-rc.5",
"jiti": "^2.6.1",
"nf3": "^0.1.1",
"ofetch": "^1.4.1",
"nf3": "^0.1.10",
"ofetch": "^2.0.0-alpha.3",
"ohash": "^2.0.11",
"rendu": "^0.0.6",
"rollup": "^4.52.4",
"srvx": "^0.8.15",
"oxc-minify": "^0.96.0",
"oxc-transform": "^0.96.0",
"srvx": "^0.9.5",
"undici": "^7.16.0",
"unenv": "2.0.0-rc.21",
"unstorage": "2.0.0-alpha.3"
"unenv": "^2.0.0-rc.24",
"unstorage": "^2.0.0-alpha.4"
},

@@ -80,28 +83,27 @@ "devDependencies": {

"@azure/static-web-apps-cli": "^2.0.7",
"@cloudflare/workers-types": "^4.20251008.0",
"@cloudflare/workers-types": "^4.20251109.0",
"@deno/types": "^0.0.1",
"@netlify/edge-functions": "^2.18.2",
"@netlify/functions": "^4.2.7",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^28.0.6",
"rollup": "^4.53.2",
"@hiogawa/vite-plugin-fullstack": "npm:@pi0/vite-plugin-fullstack@0.0.5-pr-1297",
"@netlify/edge-functions": "^3.0.2",
"@netlify/functions": "^5.1.0",
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-commonjs": "^29.0.0",
"@rollup/plugin-inject": "^5.0.5",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.2",
"@rollup/plugin-replace": "^6.0.2",
"@rollup/plugin-terser": "^0.4.4",
"@scalar/api-reference": "^1.37.0",
"@types/archiver": "^6.0.3",
"@types/aws-lambda": "^8.10.155",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-replace": "^6.0.3",
"@scalar/api-reference": "^1.39.3",
"@types/aws-lambda": "^8.10.157",
"@types/estree": "^1.0.8",
"@types/etag": "^1.8.4",
"@types/fs-extra": "^11.0.4",
"@types/http-proxy": "^1.17.16",
"@types/node": "^24.7.0",
"@types/http-proxy": "^1.17.17",
"@types/node": "^24.10.0",
"@types/node-fetch": "^2.6.13",
"@types/semver": "^7.7.1",
"@types/serve-static": "^1.15.9",
"@types/xml2js": "^0.4.14",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/coverage-v8": "^4.0.8",
"automd": "^0.4.2",
"c12": "^3.3.0",
"c12": "^3.3.1",
"changelogen": "^0.6.2",

@@ -112,2 +114,3 @@ "chokidar": "^4.0.3",

"confbox": "^0.2.2",
"cookie-es": "^2.0.0",
"croner": "^9.1.0",

@@ -119,3 +122,3 @@ "defu": "^6.1.4",

"escape-string-regexp": "^5.0.0",
"eslint": "^9.37.0",
"eslint": "^9.39.1",
"eslint-config-unjs": "^0.5.0",

@@ -125,15 +128,16 @@ "etag": "^1.8.1",

"expect-type": "^1.2.2",
"exsolve": "^1.0.7",
"exsolve": "^1.0.8",
"fs-extra": "^11.3.2",
"get-port-please": "^3.2.0",
"gzip-size": "^7.0.0",
"hookable": "^5.5.3",
"hookable": "6.0.0-rc.1",
"httpxy": "^0.1.7",
"klona": "^2.0.6",
"knitwork": "^1.2.0",
"magic-string": "^0.30.19",
"magicast": "^0.3.5",
"magic-string": "^0.30.21",
"mime": "^4.1.0",
"miniflare": "^4.20251004.0",
"miniflare": "^4.20251105.0",
"mlly": "^1.8.0",
"nypm": "^0.6.2",
"obuild": "^0.4.1",
"pathe": "^2.0.3",

@@ -145,25 +149,25 @@ "perfect-debounce": "^2.0.0",

"react": "^19.2.0",
"rolldown": "1.0.0-beta.42",
"rou3": "^0.7.7",
"rendu": "^0.0.7",
"rolldown": "^1.0.0-beta.47",
"rolldown-vite": "^7.2.2",
"rou3": "^0.7.10",
"scule": "^1.3.0",
"semver": "^7.7.3",
"serve-placeholder": "^2.0.2",
"serve-static": "^2.2.0",
"source-map": "^0.7.6",
"std-env": "^3.9.0",
"std-env": "^3.10.0",
"tinyglobby": "^0.2.15",
"tsconfck": "^3.1.6",
"typescript": "^5.9.3",
"ufo": "^1.6.1",
"ultrahtml": "^1.6.0",
"unbuild": "^3.6.1",
"uncrypto": "^0.1.3",
"unctx": "^2.4.1",
"unimport": "^5.4.1",
"unplugin-utils": "^0.3.1",
"unimport": "^5.5.0",
"untyped": "^2.0.0",
"unwasm": "^0.3.11",
"vitest": "^3.2.4",
"wrangler": "^4.42.1",
"unwasm": "^0.4.2",
"vitest": "^4.0.8",
"wrangler": "^4.46.0",
"xml2js": "^0.6.2",
"youch": "4.1.0-beta.11",
"youch": "^4.1.0-beta.12",
"youch-core": "^0.3.3"

@@ -174,2 +178,3 @@ },

"vite": "^7",
"rollup": "^4",
"xml2js": "^0.6.2"

@@ -181,2 +186,5 @@ },

},
"rollup": {
"optional": true
},
"vite": {

@@ -189,26 +197,6 @@ "optional": true

},
"packageManager": "pnpm@10.17.1",
"packageManager": "pnpm@10.21.0",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"react",
"@types/react",
"react-dom",
"@algolia/client-search"
]
},
"onlyBuiltDependencies": [
"@parcel/watcher",
"esbuild",
"workerd"
],
"ignoredBuiltDependencies": [
"keytar",
"protobufjs",
"vue-demi"
]
}
}

Sorry, the diff of this file is too big to display

import { n as nitro } from './plugin.mjs';
import './index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
import 'nitro/meta';
import 'srvx/node';
import './index2.mjs';
import './info.mjs';
import 'unenv';
import 'node:buffer';
import 'node:querystring';
import 'constants';
import 'node:crypto';
import 'db0';
import 'esbuild';
import 'nf3';
import 'rendu';
import 'vite';
import 'get-port-please';
import 'node:child_process';
async function viteBuild(nitro$1) {
if (nitro$1.options.dev) {
throw new Error(
"Nitro vite builder is not supported in development mode. Please use `vite dev` instead."
);
}
const { createBuilder } = await import('vite');
const builder = await createBuilder({
base: nitro$1.options.rootDir,
plugins: [nitro({ _nitro: nitro$1 })]
});
await builder.buildApp();
}
export { viteBuild };
import { r as resolveModulePath, s as sanitizeFilePath, a as scanHandlers, f as formatCompatibilityDate } from './index.mjs';
import { runtimeDir } from 'nitro/runtime/meta';
import { b as baseBuildConfig, d as baseBuildPlugins, r as replace, e as writeBuildInfo } from './info.mjs';
import { builtinModules } from 'node:module';
import { defu } from 'defu';
import { n as normalize, j as join, a as relative } from './pathe.M-eThtNZ.mjs';
import { d as debounce, w as watch } from './app.mjs';
import { watch as watch$1 } from 'node:fs';
import { n as nitroServerName, s as snapshot, g as generateFSTree } from './snapshot.mjs';
import { w as writeTypes } from './index3.mjs';
import 'consola';
import 'hookable';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import 'klona/full';
import 'std-env';
import 'ufo';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'url';
import 'module';
import 'consola/utils';
import 'node:zlib';
import 'unenv';
import 'node:buffer';
import 'node:querystring';
import 'constants';
import 'node:crypto';
import 'db0';
import 'esbuild';
import 'nf3';
import 'rendu';
import 'nitro/meta';
import 'node:worker_threads';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'tty';
import 'util';
import 'stream';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import './server.mjs';
import 'srvx/node';
const getRolldownConfig = (nitro) => {
const base = baseBuildConfig(nitro);
const chunkNamePrefixes = [
[nitro.options.buildDir, "build"],
[base.buildServerDir, "app"],
[runtimeDir, "nitro"],
[base.presetsDir, "nitro"],
["\0raw:", "raw"],
["\0nitro-wasm:", "wasm"],
["\0", "virtual"]
];
let config = {
cwd: nitro.options.rootDir,
input: nitro.options.entry,
external: [
...base.env.external,
...builtinModules,
...builtinModules.map((m) => `node:${m}`)
],
plugins: [
...baseBuildPlugins(nitro, base),
// https://github.com/rolldown/rolldown/issues/4257
replace({
preventAssignment: true,
values: base.replacements
})
],
resolve: {
alias: base.aliases,
extensions: base.extensions,
mainFields: ["main"],
// "module" is intentionally not supported because of externals
conditionNames: nitro.options.exportConditions
},
// @ts-expect-error (readonly values)
inject: base.env.inject,
jsx: {
mode: "classic",
factory: nitro.options.esbuild?.options?.jsxFactory,
fragment: nitro.options.esbuild?.options?.jsxFragment
},
onwarn(warning, warn) {
if (!["CIRCULAR_DEPENDENCY", "EVAL"].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) {
warn(warning);
}
},
treeshake: {
moduleSideEffects(id) {
const normalizedId = normalize(id);
const idWithoutNodeModules = normalizedId.split("node_modules/").pop();
if (!idWithoutNodeModules) {
return false;
}
if (normalizedId.startsWith(runtimeDir) || idWithoutNodeModules.startsWith(runtimeDir)) {
return true;
}
return nitro.options.moduleSideEffects.some(
(m) => normalizedId.startsWith(m) || idWithoutNodeModules.startsWith(m)
);
}
},
output: {
dir: nitro.options.output.serverDir,
entryFileNames: "index.mjs",
chunkFileNames(chunk) {
const id = normalize(chunk.moduleIds.at(-1) || "");
for (const [dir, name] of chunkNamePrefixes) {
if (id.startsWith(dir)) {
return `chunks/${name}/[name].mjs`;
}
}
const routeHandler = nitro.options.handlers.find(
(h) => id.startsWith(h.handler)
) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
if (routeHandler?.route) {
const path = routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/";
return `chunks/routes${path}/[name].mjs`;
}
const taskHandler = Object.entries(nitro.options.tasks).find(
([_, task]) => task.handler === id
);
if (taskHandler) {
return `chunks/tasks/[name].mjs`;
}
return `chunks/_/[name].mjs`;
},
inlineDynamicImports: nitro.options.inlineDynamicImports,
format: "esm",
exports: "auto",
intro: "",
outro: "",
sanitizeFileName: sanitizeFilePath,
sourcemap: nitro.options.sourceMap,
sourcemapIgnoreList(relativePath) {
return relativePath.includes("node_modules");
}
}
};
config.plugins.push({
name: "nitro:rolldown-resolves",
async resolveId(id, parent, options) {
if (parent?.startsWith("\0virtual:#nitro-internal-virtual")) {
const internalRes = await this.resolve(id, import.meta.url, {
...options,
custom: { ...options.custom, skipNoExternals: true }
});
if (internalRes) {
return internalRes;
}
return resolveModulePath(id, {
from: [nitro.options.rootDir, import.meta.url],
try: true
}) || resolveModulePath("./" + id, {
from: [nitro.options.rootDir, import.meta.url],
try: true
});
}
}
});
config = defu(nitro.options.rollupConfig, config);
return config;
};
async function watchDev(nitro, config) {
const rolldown = await import('rolldown');
let watcher;
async function load() {
if (watcher) {
await watcher.close();
}
await scanHandlers(nitro);
nitro.routing.sync();
watcher = startWatcher(nitro, config);
await writeTypes(nitro);
}
const reload = debounce(load);
const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
join(dir, nitro.options.apiDir || "api"),
join(dir, nitro.options.routesDir || "routes"),
join(dir, "middleware"),
join(dir, "plugins"),
join(dir, "modules")
]);
const watchReloadEvents = /* @__PURE__ */ new Set(["add", "addDir", "unlink", "unlinkDir"]);
const scanDirsWatcher = watch(scanDirs, {
ignoreInitial: true
}).on("all", (event) => {
if (watchReloadEvents.has(event)) {
reload();
}
});
const srcDirWatcher = watch$1(
nitro.options.srcDir,
{ persistent: false },
(_event, filename) => {
if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) {
reload();
}
}
);
nitro.hooks.hook("close", () => {
watcher.close();
scanDirsWatcher.close();
srcDirWatcher.close();
});
nitro.hooks.hook("rollup:reload", () => reload());
await load();
function startWatcher(nitro2, config2) {
const watcher2 = rolldown.watch(config2);
let start;
watcher2.on("event", (event) => {
switch (event.code) {
case "START": {
start = Date.now();
nitro2.hooks.callHook("dev:start");
break;
}
case "BUNDLE_END": {
nitro2.hooks.callHook("compiled", nitro2);
if (nitro2.options.logging.buildSuccess) {
nitro2.logger.success(
`${nitroServerName(nitro2)} built with rolldown`,
start ? `in ${Date.now() - start}ms` : ""
);
}
nitro2.hooks.callHook("dev:reload");
break;
}
case "ERROR": {
nitro2.hooks.callHook("dev:error", event.error);
}
}
});
return watcher2;
}
}
async function buildProduction(nitro, config) {
const rolldown = await import('rolldown');
await scanHandlers(nitro);
await writeTypes(nitro);
await snapshot(nitro);
if (!nitro.options.static) {
nitro.logger.info(
`Building ${nitroServerName(nitro)} (rolldown, preset: \`${nitro.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro.options.compatibilityDate)}\`)`
);
const build = await rolldown.rolldown(config);
await build.write(config.output);
}
const buildInfo = await writeBuildInfo(nitro);
if (!nitro.options.static) {
if (nitro.options.logging.buildSuccess) {
nitro.logger.success(`${nitroServerName(nitro)} built`);
}
if (nitro.options.logLevel > 1) {
process.stdout.write(
await generateFSTree(nitro.options.output.serverDir, {
compressedSizes: nitro.options.logging.compressedSizes
}) || ""
);
}
}
await nitro.hooks.callHook("compiled", nitro);
const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input) => {
return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
};
if (buildInfo.commands.preview) {
nitro.logger.success(
`You can preview this build using \`${rewriteRelativePaths(
buildInfo.commands.preview
)}\``
);
}
if (buildInfo.commands.deploy) {
nitro.logger.success(
`You can deploy this build using \`${rewriteRelativePaths(
buildInfo.commands.deploy
)}\``
);
}
}
async function rolldownBuild(nitro) {
await nitro.hooks.callHook("build:before", nitro);
const config = getRolldownConfig(nitro);
await nitro.hooks.callHook("rollup:before", nitro, config);
return nitro.options.dev ? watchDev(nitro, config) : buildProduction(nitro, config);
}
export { rolldownBuild };

Sorry, the diff of this file is too big to display

import { g as getMagicString, p as parse } from './index.mjs';
import 'node:path';
import 'node:process';
import 'scule';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'module';
import 'consola/utils';
import 'node:zlib';
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
class WalkerBase {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
/** @type {Array<Node>} */ (parent[prop])[index] = node;
} else {
/** @type {Node} */ (parent[prop]) = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== undefined) {
/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
} else {
delete parent[prop];
}
}
}
}
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
async function detectImportsAcorn(code, ctx, options) {
const s = getMagicString(code);
const map = await ctx.getImportMap();
let matchedImports = [];
const enableAutoImport = options?.autoImport !== false;
const enableTransformVirtualImports = options?.transformVirtualImports !== false && ctx.options.virtualImports?.length;
if (enableAutoImport || enableTransformVirtualImports) {
const ast = parse(s.original, {
sourceType: "module",
ecmaVersion: "latest",
locations: true
});
const virtualImports = createVirtualImportsAcronWalker(map, ctx.options.virtualImports);
const scopes = traveseScopes(
ast,
enableTransformVirtualImports ? virtualImports.walk : {}
);
if (enableAutoImport) {
const identifiers = scopes.unmatched;
matchedImports.push(
...Array.from(identifiers).map((name) => {
const item = map.get(name);
if (item && !item.disabled)
return item;
return null;
}).filter(Boolean)
);
for (const addon of ctx.addons)
matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
}
virtualImports.ranges.forEach(([start, end]) => {
s.remove(start, end);
});
matchedImports.push(...virtualImports.imports);
}
return {
s,
strippedCode: code.toString(),
matchedImports,
isCJSContext: false,
firstOccurrence: 0
// TODO:
};
}
function traveseScopes(ast, additionalWalk) {
const scopes = [];
let scopeCurrent = void 0;
const scopesStack = [];
function pushScope(node) {
scopeCurrent = {
node,
parent: scopeCurrent,
declarations: /* @__PURE__ */ new Set(),
references: /* @__PURE__ */ new Set()
};
scopes.push(scopeCurrent);
scopesStack.push(scopeCurrent);
}
function popScope(node) {
const scope = scopesStack.pop();
if (scope?.node !== node)
throw new Error("Scope mismatch");
scopeCurrent = scopesStack[scopesStack.length - 1];
}
pushScope(void 0);
walk(ast, {
enter(node, parent, prop, index) {
additionalWalk?.enter?.call(this, node, parent, prop, index);
switch (node.type) {
// ====== Declaration ======
case "ImportSpecifier":
case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier":
scopeCurrent.declarations.add(node.local.name);
return;
case "FunctionDeclaration":
case "ClassDeclaration":
if (node.id)
scopeCurrent.declarations.add(node.id.name);
return;
case "VariableDeclarator":
if (node.id.type === "Identifier") {
scopeCurrent.declarations.add(node.id.name);
} else {
walk(node.id, {
enter(node2) {
if (node2.type === "ObjectPattern") {
node2.properties.forEach((i) => {
if (i.type === "Property" && i.value.type === "Identifier")
scopeCurrent.declarations.add(i.value.name);
else if (i.type === "RestElement" && i.argument.type === "Identifier")
scopeCurrent.declarations.add(i.argument.name);
});
} else if (node2.type === "ArrayPattern") {
node2.elements.forEach((i) => {
if (i?.type === "Identifier")
scopeCurrent.declarations.add(i.name);
if (i?.type === "RestElement" && i.argument.type === "Identifier")
scopeCurrent.declarations.add(i.argument.name);
});
}
}
});
}
return;
// ====== Scope ======
case "BlockStatement":
pushScope(node);
return;
// ====== Reference ======
case "Identifier":
switch (parent?.type) {
case "CallExpression":
if (parent.callee === node || parent.arguments.includes(node))
scopeCurrent.references.add(node.name);
return;
case "MemberExpression":
if (parent.object === node)
scopeCurrent.references.add(node.name);
return;
case "VariableDeclarator":
if (parent.init === node)
scopeCurrent.references.add(node.name);
return;
case "SpreadElement":
if (parent.argument === node)
scopeCurrent.references.add(node.name);
return;
case "ClassDeclaration":
if (parent.superClass === node)
scopeCurrent.references.add(node.name);
return;
case "Property":
if (parent.value === node)
scopeCurrent.references.add(node.name);
return;
case "TemplateLiteral":
if (parent.expressions.includes(node))
scopeCurrent.references.add(node.name);
return;
case "AssignmentExpression":
if (parent.right === node)
scopeCurrent.references.add(node.name);
return;
case "IfStatement":
case "WhileStatement":
case "DoWhileStatement":
if (parent.test === node)
scopeCurrent.references.add(node.name);
return;
case "SwitchStatement":
if (parent.discriminant === node)
scopeCurrent.references.add(node.name);
return;
}
if (parent?.type.includes("Expression"))
scopeCurrent.references.add(node.name);
}
},
leave(node, parent, prop, index) {
additionalWalk?.leave?.call(this, node, parent, prop, index);
switch (node.type) {
case "BlockStatement":
popScope(node);
}
}
});
const unmatched = /* @__PURE__ */ new Set();
for (const scope of scopes) {
for (const name of scope.references) {
let defined = false;
let parent = scope;
while (parent) {
if (parent.declarations.has(name)) {
defined = true;
break;
}
parent = parent?.parent;
}
if (!defined)
unmatched.add(name);
}
}
return {
unmatched,
scopes
};
}
function createVirtualImportsAcronWalker(importMap, virtualImports = []) {
const imports = [];
const ranges = [];
return {
imports,
ranges,
walk: {
enter(node) {
if (node.type === "ImportDeclaration") {
if (virtualImports.includes(node.source.value)) {
ranges.push([node.start, node.end]);
node.specifiers.forEach((i) => {
if (i.type === "ImportSpecifier" && i.imported.type === "Identifier") {
const original = importMap.get(i.imported.name);
if (!original)
throw new Error(`[unimport] failed to find "${i.imported.name}" imported from "${node.source.value}"`);
imports.push({
from: original.from,
name: original.name,
as: i.local.name
});
}
});
}
}
}
}
};
}
export { createVirtualImportsAcronWalker, detectImportsAcorn, traveseScopes };

Sorry, the diff of this file is too big to display

import sysPath__default, { sep } from 'path';
import { c as createFilter, a as attachScopes, w as walk, m as makeLegalIdentifier } from './info.mjs';
import { M as MagicString } from './index.mjs';
function matches(pattern, importee) {
if (pattern instanceof RegExp) {
return pattern.test(importee);
}
if (importee.length < pattern.length) {
return false;
}
if (importee === pattern) {
return true;
}
// eslint-disable-next-line prefer-template
return importee.startsWith(pattern + '/');
}
function getEntries({ entries, customResolver }) {
if (!entries) {
return [];
}
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) {
return entries.map((entry) => {
return {
find: entry.find,
replacement: entry.replacement,
resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
};
});
}
return Object.entries(entries).map(([key, value]) => {
return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
});
}
function getHookFunction(hook) {
if (typeof hook === 'function') {
return hook;
}
if (hook && 'handler' in hook && typeof hook.handler === 'function') {
return hook.handler;
}
return null;
}
function resolveCustomResolver(customResolver) {
if (typeof customResolver === 'function') {
return customResolver;
}
if (customResolver) {
return getHookFunction(customResolver.resolveId);
}
return null;
}
function alias(options = {}) {
const entries = getEntries(options);
if (entries.length === 0) {
return {
name: 'alias',
resolveId: () => null
};
}
return {
name: 'alias',
async buildStart(inputOptions) {
await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
},
resolveId(importee, importer, resolveOptions) {
// First match is supposed to be the correct one
const matchedEntry = entries.find((entry) => matches(entry.find, importee));
if (!matchedEntry) {
return null;
}
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) {
return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
}
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
if (resolved)
return resolved;
if (!sysPath__default.isAbsolute(updatedId)) {
this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` +
`This will lead to duplicated modules for the same path. ` +
`To avoid duplicating modules, you should resolve to an absolute path.`);
}
return { id: updatedId };
});
}
};
}
var escape = function (str) { return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); };
var isReference = function (node, parent) {
if (node.type === 'MemberExpression') {
return !node.computed && isReference(node.object, node);
}
if (node.type === 'Identifier') {
// TODO is this right?
if (parent.type === 'MemberExpression') { return parent.computed || node === parent.object; }
// disregard the `bar` in { bar: foo }
if (parent.type === 'Property' && node !== parent.value) { return false; }
// disregard the `bar` in `class Foo { bar () {...} }`
if (parent.type === 'MethodDefinition') { return false; }
// disregard the `bar` in `export { foo as bar }`
if (parent.type === 'ExportSpecifier' && node !== parent.local) { return false; }
// disregard the `bar` in `import { bar as foo }`
if (parent.type === 'ImportSpecifier' && node === parent.imported) {
return false;
}
return true;
}
return false;
};
var flatten = function (startNode) {
var parts = [];
var node = startNode;
while (node.type === 'MemberExpression') {
parts.unshift(node.property.name);
node = node.object;
}
var name = node.name;
parts.unshift(name);
return { name: name, keypath: parts.join('.') };
};
function inject(options) {
if (!options) { throw new Error('Missing options'); }
var filter = createFilter(options.include, options.exclude);
var modules = options.modules;
if (!modules) {
modules = Object.assign({}, options);
delete modules.include;
delete modules.exclude;
delete modules.sourceMap;
delete modules.sourcemap;
}
var modulesMap = new Map(Object.entries(modules));
// Fix paths on Windows
if (sep !== '/') {
modulesMap.forEach(function (mod, key) {
modulesMap.set(
key,
Array.isArray(mod) ? [mod[0].split(sep).join('/'), mod[1]] : mod.split(sep).join('/')
);
});
}
var firstpass = new RegExp(("(?:" + (Array.from(modulesMap.keys()).map(escape).join('|')) + ")"), 'g');
var sourceMap = options.sourceMap !== false && options.sourcemap !== false;
return {
name: 'inject',
transform: function transform(code, id) {
if (!filter(id)) { return null; }
if (code.search(firstpass) === -1) { return null; }
if (sep !== '/') { id = id.split(sep).join('/'); } // eslint-disable-line no-param-reassign
var ast = null;
try {
ast = this.parse(code);
} catch (err) {
this.warn({
code: 'PARSE_ERROR',
message: ("rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include")
});
}
if (!ast) {
return null;
}
var imports = new Set();
ast.body.forEach(function (node) {
if (node.type === 'ImportDeclaration') {
node.specifiers.forEach(function (specifier) {
imports.add(specifier.local.name);
});
}
});
// analyse scopes
var scope = attachScopes(ast, 'scope');
var magicString = new MagicString(code);
var newImports = new Map();
function handleReference(node, name, keypath) {
var mod = modulesMap.get(keypath);
if (mod && !imports.has(name) && !scope.contains(name)) {
if (typeof mod === 'string') { mod = [mod, 'default']; }
// prevent module from importing itself
if (mod[0] === id) { return false; }
var hash = keypath + ":" + (mod[0]) + ":" + (mod[1]);
var importLocalName =
name === keypath ? name : makeLegalIdentifier(("$inject_" + keypath));
if (!newImports.has(hash)) {
// escape apostrophes and backslashes for use in single-quoted string literal
var modName = mod[0].replace(/[''\\]/g, '\\$&');
if (mod[1] === '*') {
newImports.set(hash, ("import * as " + importLocalName + " from '" + modName + "';"));
} else {
newImports.set(hash, ("import { " + (mod[1]) + " as " + importLocalName + " } from '" + modName + "';"));
}
}
if (name !== keypath) {
magicString.overwrite(node.start, node.end, importLocalName, {
storeName: true
});
}
return true;
}
return false;
}
walk(ast, {
enter: function enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
if (node.scope) {
scope = node.scope; // eslint-disable-line prefer-destructuring
}
// special case – shorthand properties. because node.key === node.value,
// we can't differentiate once we've descended into the node
if (node.type === 'Property' && node.shorthand && node.value.type === 'Identifier') {
var ref = node.key;
var name = ref.name;
handleReference(node, name, name);
this.skip();
return;
}
if (isReference(node, parent)) {
var ref$1 = flatten(node);
var name$1 = ref$1.name;
var keypath = ref$1.keypath;
var handled = handleReference(node, name$1, keypath);
if (handled) {
this.skip();
}
}
},
leave: function leave(node) {
if (node.scope) {
scope = scope.parent;
}
}
});
if (newImports.size === 0) {
return {
code: code,
ast: ast,
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
var importBlock = Array.from(newImports.values()).join('\n\n');
magicString.prepend((importBlock + "\n\n"));
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
};
}
export { alias as a, inject as i };
import { i as createNitro, k as addRoute, l as scanUnprefixedPublicAssets, m as compressPublicAssets, n as mime, w as writeFile, o as findAllRoutes, q as createRouter, t as genObjectKey, u as resolveNitroPath, v as toExports, r as resolveModulePath, x as parseNodeModulePath, y as lookupNodeModuleSubpath, z as isDirectory } from './index.mjs';
import { pathToFileURL } from 'node:url';
import { colors } from 'consola/utils';
import { defu } from 'defu';
import { parseURL, withTrailingSlash, withBase, joinURL, withoutBase } from 'ufo';
import { a as relative, r as resolve, j as join, c as normalizeWindowsPath, i as isAbsolute, d as dirname } from './pathe.M-eThtNZ.mjs';
import './server.mjs';
import { existsSync, promises } from 'node:fs';
import { runtimeDir } from 'nitro/runtime/meta';
import 'scule';
async function build(nitro) {
switch (nitro.options.builder) {
case "rollup": {
const { rollupBuild } = await import('./build3.mjs');
return rollupBuild(nitro);
}
case "rolldown": {
const { rolldownBuild } = await import('./build2.mjs');
return rolldownBuild(nitro);
}
case "vite": {
const { viteBuild } = await import('./build.mjs');
return viteBuild(nitro);
}
default: {
throw new Error(`Unknown builder: ${nitro.options.builder}`);
}
}
}
async function runParallel(inputs, cb, opts) {
const tasks = /* @__PURE__ */ new Set();
function queueNext() {
const route = inputs.values().next().value;
if (!route) {
return;
}
inputs.delete(route);
const task = (opts.interval ? new Promise((resolve) => setTimeout(resolve, opts.interval)) : Promise.resolve()).then(() => cb(route)).catch((error) => {
console.error(error);
});
tasks.add(task);
return task.then(() => {
tasks.delete(task);
if (inputs.size > 0) {
return refillQueue();
}
});
}
function refillQueue() {
const workers = Math.min(opts.concurrency - tasks.size, inputs.size);
return Promise.all(Array.from({ length: workers }, () => queueNext()));
}
await refillQueue();
}
var D=new Set(["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),x=new Set(["script","style"]),o=/(?:<(\/?)([a-zA-Z][a-zA-Z0-9\:-]*)(?:\s([^>]*?))?((?:\s*\/)?)>|(<\!\-\-)([\s\S]*?)(\-\->)|(<\!)([\s\S]*?)(>))/gm,b=/[\@\.a-z0-9_\:\-]/i;function I(e){let t={};if(e){let i="none",r,n="",a,l;for(let c=0;c<e.length;c++){let d=e[c];i==="none"?b.test(d)?(r&&(t[r]=n,r=void 0,n=""),a=c,i="key"):d==="="&&r&&(i="value"):i==="key"?b.test(d)||(r=e.substring(a,c),d==="="?i="value":i="none"):d===l&&c>0&&e[c-1]!=="\\"?l&&(n=e.substring(a,c),l=void 0,i="none"):(d==='"'||d==="'")&&!l&&(a=c+1,l=d);}i==="key"&&a!=null&&a<e.length&&(r=e.substring(a,e.length)),r&&(t[r]=n);}return t}function P(e){let t=typeof e=="string"?e:e.value,i,r,n,a,l,c,d,m,s,u=[];o.lastIndex=0,r=i={type:0,children:[]};let g=0;function h(){a=t.substring(g,o.lastIndex-n[0].length),a&&r.children.push({type:2,value:a,parent:r});}for(;n=o.exec(t);){if(c=n[5]||n[8],d=n[6]||n[9],m=n[7]||n[10],x.has(r.name)&&n[2]!==r.name){l=o.lastIndex-n[0].length,r.children.length>0&&(r.children[0].value+=n[0]);continue}else if(c==="<!--"){if(l=o.lastIndex-n[0].length,x.has(r.name))continue;s={type:3,value:d,parent:r,loc:[{start:l,end:l+c.length},{start:o.lastIndex-m.length,end:o.lastIndex}]},u.push(s),s.parent.children.push(s);}else if(c==="<!")l=o.lastIndex-n[0].length,s={type:4,value:d,parent:r,loc:[{start:l,end:l+c.length},{start:o.lastIndex-m.length,end:o.lastIndex}]},u.push(s),s.parent.children.push(s);else if(n[1]!=="/")if(h(),x.has(r.name)){g=o.lastIndex,h();continue}else s={type:1,name:n[2]+"",attributes:I(n[3]),parent:r,children:[],loc:[{start:o.lastIndex-n[0].length,end:o.lastIndex}]},u.push(s),s.parent.children.push(s),n[4]&&n[4].indexOf("/")>-1||D.has(s.name)?(s.loc[1]=s.loc[0],s.isSelfClosingTag=true):r=s;else h(),n[2]+""===r.name?(s=r,r=s.parent,s.loc.push({start:o.lastIndex-n[0].length,end:o.lastIndex}),a=t.substring(s.loc[0].end,s.loc[1].start),s.children.length===0&&s.children.push({type:2,value:a,parent:r})):n[2]+""===u[u.length-1].name&&u[u.length-1].isSelfClosingTag===true&&(s=u[u.length-1],s.loc.push({start:o.lastIndex-n[0].length,end:o.lastIndex}));g=o.lastIndex;}return a=t.slice(g),r.children.push({type:2,value:a,parent:r}),i}var T=class{constructor(t){this.callback=t;}async visit(t,i,r){if(await this.callback(t,i,r),Array.isArray(t.children)){let n=[];for(let a=0;a<t.children.length;a++){let l=t.children[a];n.push(this.visit(l,t,a));}await Promise.all(n);}}};function z(e,t){return new T(t).visit(e)}
const allowedExtensions = /* @__PURE__ */ new Set(["", ".json"]);
const linkParents$1 = /* @__PURE__ */ new Map();
const HTML_ENTITIES = {
"&lt;": "<",
"&gt;": ">",
"&amp;": "&",
"&apos;": "'",
"&quot;": '"'
};
function escapeHtml(text) {
return text.replace(
/&(lt|gt|amp|apos|quot);/g,
(ch) => HTML_ENTITIES[ch] || ch
);
}
async function extractLinks(html, from, res, crawlLinks) {
const links = [];
const _links = [];
if (crawlLinks) {
await z(P(html), (node) => {
if (!node.attributes?.href) {
return;
}
const link = escapeHtml(node.attributes.href);
if (!decodeURIComponent(link).startsWith("#") && allowedExtensions.has(getExtension(link))) {
_links.push(link);
}
});
}
const header = res.headers.get("x-nitro-prerender") || "";
_links.push(...header.split(",").map((i) => decodeURIComponent(i.trim())));
for (const link of _links.filter(Boolean)) {
const _link = parseURL(link);
if (_link.protocol || _link.host) {
continue;
}
if (!_link.pathname.startsWith("/")) {
const fromURL = new URL(from, "http://localhost");
_link.pathname = new URL(_link.pathname, fromURL).pathname;
}
links.push(_link.pathname + _link.search);
}
for (const link of links) {
const _parents = linkParents$1.get(link);
if (_parents) {
_parents.add(from);
} else {
linkParents$1.set(link, /* @__PURE__ */ new Set([from]));
}
}
return links;
}
const EXT_REGEX = /\.[\da-z]+$/;
function getExtension(link) {
const pathname = parseURL(link).pathname;
return (pathname.match(EXT_REGEX) || [])[0] || "";
}
function formatPrerenderRoute(route) {
let str = ` \u251C\u2500 ${route.route} (${route.generateTimeMS}ms)`;
if (route.error) {
const parents = linkParents$1.get(route.route);
const errorColor = colors[route.error.status === 404 ? "yellow" : "red"];
const errorLead = parents?.size ? "\u251C\u2500\u2500" : "\u2514\u2500\u2500";
str += `
\u2502 ${errorLead} ${errorColor(route.error.message)}`;
if (parents?.size) {
str += `
${[...parents.values()].map((link) => ` \u2502 \u2514\u2500\u2500 Linked from ${link}`).join("\n")}`;
}
}
if (route.skip) {
str += colors.gray(" (skipped)");
}
return colors.gray(str);
}
function matchesIgnorePattern(path, pattern) {
if (typeof pattern === "string") {
return path.startsWith(pattern);
}
if (typeof pattern === "function") {
return pattern(path) === true;
}
if (pattern instanceof RegExp) {
return pattern.test(path);
}
return false;
}
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
const linkParents = /* @__PURE__ */ new Map();
async function prerender(nitro) {
if (nitro.options.noPublicDir) {
nitro.logger.warn(
"Skipping prerender since `noPublicDir` option is enabled."
);
return;
}
if (nitro.options.builder === "vite") {
nitro.logger.warn(
"Skipping prerender since not supported with vite builder yet..."
);
return;
}
const routes = new Set(nitro.options.prerender.routes);
const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path2, options]) => options.prerender && !path2.includes("*")).map((e) => e[0]);
for (const route of prerenderRulePaths) {
routes.add(route);
}
await nitro.hooks.callHook("prerender:routes", routes);
if (routes.size === 0) {
if (nitro.options.prerender.crawlLinks) {
routes.add("/");
} else {
return;
}
}
nitro.logger.info("Initializing prerenderer");
nitro._prerenderedRoutes = [];
nitro._prerenderMeta = nitro._prerenderMeta || {};
const prerendererConfig = {
...nitro.options._config,
static: false,
rootDir: nitro.options.rootDir,
logLevel: 0,
preset: "nitro-prerender"
};
await nitro.hooks.callHook("prerender:config", prerendererConfig);
const nitroRenderer = await createNitro(prerendererConfig);
const prerenderStartTime = Date.now();
await nitro.hooks.callHook("prerender:init", nitroRenderer);
let path = relative(nitro.options.output.dir, nitro.options.output.publicDir);
if (!path.startsWith(".")) {
path = `./${path}`;
}
nitroRenderer.options.commands.preview = `npx serve ${path}`;
nitroRenderer.options.output.dir = nitro.options.output.dir;
await build(nitroRenderer);
const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs";
const serverEntrypoint = resolve(
nitroRenderer.options.output.serverDir,
serverFilename
);
const { closePrerenderer, appFetch } = await import(pathToFileURL(serverEntrypoint).href);
const routeRules = createRouter();
for (const [route, rules] of Object.entries(nitro.options.routeRules)) {
addRoute(routeRules, void 0, route, rules);
}
const _getRouteRules = (path2) => defu(
{},
...findAllRoutes(routeRules, void 0, path2).map((r) => r.data).reverse()
);
const generatedRoutes = /* @__PURE__ */ new Set();
const failedRoutes = /* @__PURE__ */ new Set();
const skippedRoutes = /* @__PURE__ */ new Set();
const displayedLengthWarns = /* @__PURE__ */ new Set();
const publicAssetBases = nitro.options.publicAssets.filter(
(a) => !!a.baseURL && a.baseURL !== "/" && !a.fallthrough
).map((a) => withTrailingSlash(a.baseURL));
const scannedPublicAssets = nitro.options.prerender.ignoreUnprefixedPublicAssets ? new Set(await scanUnprefixedPublicAssets(nitro)) : /* @__PURE__ */ new Set();
const canPrerender = (route = "/") => {
if (generatedRoutes.has(route) || skippedRoutes.has(route)) {
return false;
}
for (const pattern of nitro.options.prerender.ignore) {
if (matchesIgnorePattern(route, pattern)) {
return false;
}
}
if (publicAssetBases.some((base) => route.startsWith(base))) {
return false;
}
if (scannedPublicAssets.has(route)) {
return false;
}
if (_getRouteRules(route).prerender === false) {
return false;
}
return true;
};
const canWriteToDisk = (route) => {
if (route.route.includes("?")) {
return false;
}
const FS_MAX_SEGMENT = 255;
const FS_MAX_PATH = 1024;
const FS_MAX_PATH_PUBLIC_HTML = FS_MAX_PATH - (nitro.options.output.publicDir.length + 10);
if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) {
displayedLengthWarns.add(route);
const _route = route.route.slice(0, 60) + "...";
if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) {
nitro.logger.warn(
`Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`
);
} else {
nitro.logger.warn(
`Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`
);
return false;
}
}
return true;
};
const generateRoute = async (route) => {
const start = Date.now();
route = decodeURI(route);
if (!canPrerender(route)) {
skippedRoutes.add(route);
return;
}
generatedRoutes.add(route);
const _route = { route };
const encodedRoute = encodeURI(route);
const res = await appFetch(withBase(encodedRoute, nitro.options.baseURL), {
headers: [["x-nitro-prerender", encodedRoute]]
// TODO
// retry: nitro.options.prerender.retry,
// retryDelay: nitro.options.prerender.retryDelay,
});
let dataBuff = Buffer.from(await res.arrayBuffer());
Object.defineProperty(_route, "contents", {
get: () => {
return dataBuff ? dataBuff.toString("utf8") : void 0;
},
set(value) {
if (dataBuff) {
dataBuff = Buffer.from(value);
}
}
});
Object.defineProperty(_route, "data", {
get: () => {
return dataBuff ? dataBuff.buffer : void 0;
},
set(value) {
if (dataBuff) {
dataBuff = Buffer.from(value);
}
}
});
const redirectCodes = [301, 302, 303, 304, 307, 308];
if (![200, ...redirectCodes].includes(res.status)) {
_route.error = new Error(`[${res.status}] ${res.statusText}`);
_route.error.status = res.status;
_route.error.statusText = res.statusText;
}
_route.generateTimeMS = Date.now() - start;
const contentType = res.headers.get("content-type") || "";
const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8"));
const routeWithIndex = route.endsWith("/") ? route + "index" : route;
const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html";
_route.fileName = withoutBase(
isImplicitHTML ? htmlPath : routeWithIndex,
nitro.options.baseURL
);
const inferredContentType = mime.getType(_route.fileName) || "text/plain";
_route.contentType = contentType || inferredContentType;
await nitro.hooks.callHook("prerender:generate", _route, nitro);
if (_route.contentType !== inferredContentType) {
nitro._prerenderMeta[_route.fileName] ||= {};
nitro._prerenderMeta[_route.fileName].contentType = _route.contentType;
}
if (_route.error) {
failedRoutes.add(_route);
}
if (_route.skip || _route.error) {
await nitro.hooks.callHook("prerender:route", _route);
nitro.logger.log(formatPrerenderRoute(_route));
dataBuff = void 0;
return _route;
}
if (canWriteToDisk(_route)) {
const filePath = join(nitro.options.output.publicDir, _route.fileName);
await writeFile(filePath, dataBuff);
nitro._prerenderedRoutes.push(_route);
} else {
_route.skip = true;
}
if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) {
const extractedLinks = await extractLinks(
dataBuff.toString("utf8"),
route,
res,
nitro.options.prerender.crawlLinks
);
for (const _link of extractedLinks) {
if (canPrerender(_link)) {
routes.add(_link);
}
}
}
await nitro.hooks.callHook("prerender:route", _route);
nitro.logger.log(formatPrerenderRoute(_route));
dataBuff = void 0;
return _route;
};
nitro.logger.info(
nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`
);
await runParallel(routes, generateRoute, {
concurrency: nitro.options.prerender.concurrency,
interval: nitro.options.prerender.interval
});
await closePrerenderer();
await nitro.hooks.callHook("prerender:done", {
prerenderedRoutes: nitro._prerenderedRoutes,
failedRoutes: [...failedRoutes]
});
if (nitro.options.prerender.failOnError && failedRoutes.size > 0) {
nitro.logger.log("\nErrors prerendering:");
for (const route of failedRoutes) {
const parents = linkParents.get(route.route);
parents?.size ? `
${[...parents.values()].map((link) => colors.gray(` \u2502 \u2514\u2500\u2500 Linked from ${link}`)).join("\n")}` : "";
nitro.logger.log(formatPrerenderRoute(route));
}
nitro.logger.log("");
throw new Error("Exiting due to prerender errors.");
}
const prerenderTimeInMs = Date.now() - prerenderStartTime;
nitro.logger.info(
`Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`
);
if (nitro.options.compressPublicAssets) {
await compressPublicAssets(nitro);
}
}
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) {
return _aliases;
}
const aliases = Object.fromEntries(
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
);
for (const key in aliases) {
for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) {
continue;
}
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
}
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path[_alias.length])) {
return join(to, _path.slice(alias.length));
}
}
return _path;
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
function getType(val) {
const type = typeof val;
if (type === "undefined" || val === null) {
return void 0;
}
if (Array.isArray(val)) {
return "array";
}
return type;
}
function isObject(val) {
return val !== null && !Array.isArray(val) && typeof val === "object";
}
function nonEmpty(arr) {
return arr.filter(Boolean);
}
function unique(arr) {
return [...new Set(arr)];
}
function joinPath(a, b = "", sep = ".") {
return a ? a + sep + b : b;
}
function setValue(obj, path, val) {
const keys = path.split(".");
const _key = keys.pop();
for (const key of keys) {
if (!obj || typeof obj !== "object") {
return;
}
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
}
if (_key) {
if (!obj || typeof obj !== "object") {
return;
}
obj[_key] = val;
}
}
function getValue(obj, path) {
for (const key of path.split(".")) {
if (!obj || typeof obj !== "object" || !(key in obj)) {
return;
}
obj = obj[key];
}
return obj;
}
function normalizeTypes(val) {
const arr = unique(val.filter(Boolean));
if (arr.length === 0 || arr.includes("any")) {
return;
}
return arr.length > 1 ? arr : arr[0];
}
async function resolveSchema(obj, defaults, options = {}) {
const schema = await _resolveSchema(obj, "", {
root: obj,
defaults,
resolveCache: {},
ignoreDefaults: !!options.ignoreDefaults
});
return schema;
}
async function _resolveSchema(input, id, ctx) {
if (id in ctx.resolveCache) {
return ctx.resolveCache[id];
}
const schemaId = "#" + id.replace(/\./g, "/");
if (!isObject(input)) {
const safeInput = Array.isArray(input) ? [...input] : input;
const schema2 = {
type: getType(input),
id: schemaId,
default: ctx.ignoreDefaults ? void 0 : safeInput
};
normalizeSchema(schema2, { ignoreDefaults: ctx.ignoreDefaults });
ctx.resolveCache[id] = schema2;
if (ctx.defaults && getValue(ctx.defaults, id) === void 0) {
setValue(ctx.defaults, id, schema2.default);
}
return schema2;
}
const node = { ...input };
const schema = ctx.resolveCache[id] = {
...node.$schema,
id: schemaId
};
for (const key in node) {
if (key === "$resolve" || key === "$schema" || key === "$default") {
continue;
}
schema.properties = schema.properties || {};
if (!schema.properties[key]) {
const child = schema.properties[key] = await _resolveSchema(
node[key],
joinPath(id, key),
ctx
);
if (Array.isArray(child.tags) && child.tags.includes("@required")) {
schema.required = schema.required || [];
if (!schema.required.includes(key)) {
schema.required.push(key);
}
}
}
}
if (!ctx.ignoreDefaults) {
if (ctx.defaults) {
schema.default = getValue(ctx.defaults, id);
}
if (schema.default === void 0 && "$default" in node) {
schema.default = node.$default;
}
if (typeof node.$resolve === "function") {
schema.default = await node.$resolve(schema.default, async (key) => {
return (await _resolveSchema(getValue(ctx.root, key), key, ctx)).default;
});
}
}
if (ctx.defaults) {
setValue(ctx.defaults, id, schema.default);
}
if (!schema.type) {
schema.type = getType(schema.default) || (schema.properties ? "object" : "any");
}
normalizeSchema(schema, { ignoreDefaults: ctx.ignoreDefaults });
if (ctx.defaults && getValue(ctx.defaults, id) === void 0) {
setValue(ctx.defaults, id, schema.default);
}
return schema;
}
function normalizeSchema(schema, options) {
if (schema.type === "array" && !("items" in schema)) {
schema.items = {
type: nonEmpty(unique(schema.default.map((i) => getType(i))))
};
if (schema.items.type) {
if (schema.items.type.length === 0) {
schema.items.type = "any";
} else if (schema.items.type.length === 1) {
schema.items.type = schema.items.type[0];
}
}
}
if (!options.ignoreDefaults && schema.default === void 0 && ("properties" in schema || schema.type === "object" || schema.type === "any")) {
const propsWithDefaults = Object.entries(schema.properties || {}).filter(([, prop]) => "default" in prop).map(([key, value]) => [key, value.default]);
schema.default = Object.fromEntries(propsWithDefaults);
}
}
const GenerateTypesDefaults = {
interfaceName: "Untyped",
addExport: true,
addDefaults: true,
allowExtraKeys: void 0,
partial: false,
indentation: 0
};
const TYPE_MAP = {
array: "any[]",
bigint: "bigint",
boolean: "boolean",
number: "number",
object: "",
// Will be precisely defined
any: "any",
string: "string",
symbol: "Symbol",
function: "Function"
};
const SCHEMA_KEYS = /* @__PURE__ */ new Set([
"items",
"default",
"resolve",
"properties",
"title",
"description",
"$schema",
"type",
"tsType",
"markdownType",
"tags",
"args",
"id",
"returns"
]);
const DECLARATION_RE = /typeof import\(["'](?<source>[^)]+)["']\)(\.(?<type>\w+)|\[["'](?<type1>\w+)["']])/g;
function extractTypeImports(declarations) {
const typeImports = {};
const aliases = /* @__PURE__ */ new Set();
const imports = [];
for (const match of declarations.matchAll(DECLARATION_RE)) {
const { source, type1, type = type1 } = match.groups || {};
typeImports[source] = typeImports[source] || /* @__PURE__ */ new Set();
typeImports[source].add(type);
}
for (const source in typeImports) {
const sourceImports = [];
for (const type of typeImports[source]) {
let count = 0;
let alias = type;
while (aliases.has(alias)) {
alias = `${type}${count++}`;
}
aliases.add(alias);
sourceImports.push(alias === type ? type : `${type} as ${alias}`);
declarations = declarations.replace(
new RegExp(
`typeof import\\(['"]${source}['"]\\)(\\.${type}|\\[['"]${type}['"]\\])`,
"g"
),
alias
);
}
imports.push(
`import type { ${sourceImports.join(", ")} } from '${source}'`
);
}
return [...imports, declarations].join("\n");
}
function generateTypes(schema, opts = {}) {
opts = { ...GenerateTypesDefaults, ...opts };
const baseIden = " ".repeat(opts.indentation || 0);
const interfaceCode = `interface ${opts.interfaceName} {
` + _genTypes(schema, baseIden + " ", opts).map((l) => l.trim().length > 0 ? l : "").join("\n") + `
${baseIden}}`;
if (!opts.addExport) {
return baseIden + interfaceCode;
}
return extractTypeImports(baseIden + `export ${interfaceCode}`);
}
function _genTypes(schema, spaces, opts) {
const buff = [];
if (!schema) {
return buff;
}
for (const key in schema.properties) {
const val = schema.properties[key];
buff.push(...generateJSDoc(val, opts));
if (val.tsType) {
buff.push(
`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${val.tsType},
`
);
} else if (val.type === "object") {
buff.push(
`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`,
..._genTypes(val, spaces, opts),
"},\n"
);
} else {
let type;
if (val.type === "array") {
type = `Array<${getTsType(val.items || [], opts)}>`;
} else if (val.type === "function") {
type = genFunctionType(val, opts);
} else {
type = getTsType(val, opts);
}
buff.push(
`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${type},
`
);
}
}
if (buff.length > 0) {
const last = buff.pop() || "";
buff.push(last.slice(0, Math.max(0, last.length - 1)));
}
if (opts.allowExtraKeys === true || buff.length === 0 && opts.allowExtraKeys !== false) {
buff.push("[key: string]: any");
}
return buff.flatMap((l) => l.split("\n")).map((l) => spaces + l);
}
function getTsType(type, opts) {
if (Array.isArray(type)) {
return [normalizeTypes(type.map((t) => getTsType(t, opts)))].flat().join("|") || "any";
}
if (!type) {
return "any";
}
if (type.tsType) {
return type.tsType;
}
if (!type.type) {
return "any";
}
if (Array.isArray(type.type)) {
return type.type.map((t) => {
if (t === "object" && type.type.length > 1) {
return `{
` + _genTypes(type, " ", opts).join("\n") + `
}`;
}
return TYPE_MAP[t];
}).join("|");
}
if (type.type === "array") {
return `Array<${getTsType(type.items || [], opts)}>`;
}
if (type.type === "object") {
return `{
` + _genTypes(type, " ", opts).join("\n") + `
}`;
}
return TYPE_MAP[type.type] || type.type;
}
function genFunctionType(schema, opts) {
return `(${genFunctionArgs(schema.args, opts)}) => ${getTsType(
schema.returns || [],
opts
)}`;
}
function genFunctionArgs(args, opts) {
return args?.map((arg) => {
let argStr = arg.name;
if (arg.optional || arg.default) {
argStr += "?";
}
if (arg.type || arg.tsType) {
argStr += `: ${getTsType(arg, opts)}`;
}
return argStr;
}).join(", ") || "";
}
function generateJSDoc(schema, opts) {
opts.defaultDescription = opts.defaultDescription || opts.defaultDescrption;
let buff = [];
if (schema.title) {
buff.push(schema.title, "");
}
if (schema.description) {
buff.push(schema.description, "");
} else if (opts.defaultDescription && schema.type !== "object") {
buff.push(opts.defaultDescription, "");
}
if (opts.addDefaults && schema.type !== "object" && schema.type !== "any" && !(Array.isArray(schema.default) && schema.default.length === 0)) {
const stringified = JSON.stringify(schema.default);
if (stringified) {
buff.push(`@default ${stringified.replace(/\*\//g, String.raw`*\/`)}`);
}
}
for (const key in schema) {
if (!SCHEMA_KEYS.has(key)) {
buff.push("", `@${key} ${schema[key]}`);
}
}
if (Array.isArray(schema.tags)) {
for (const tag of schema.tags) {
if (tag !== "@untyped") {
buff.push("", tag);
}
}
}
buff = buff.flatMap((i) => i.split("\n"));
if (buff.length > 0) {
return buff.length === 1 ? ["/** " + buff[0] + " */"] : ["/**", ...buff.map((i) => ` * ${i}`), "*/"];
}
return [];
}
function isRequired(schema, key, opts) {
if (Array.isArray(schema.required) && schema.required.includes(key)) {
return true;
}
return !opts.partial;
}
async function writeTypes(nitro) {
const types = {
routes: {}
};
const typesDir = resolve(nitro.options.buildDir, "types");
const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers];
for (const mw of middleware) {
if (typeof mw.handler !== "string" || !mw.route) {
continue;
}
const relativePath = relative(
typesDir,
resolveNitroPath(mw.handler, nitro.options)
).replace(/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/, "");
const method = mw.method || "default";
types.routes[mw.route] ??= {};
types.routes[mw.route][method] ??= [];
types.routes[mw.route][method].push(
`Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`
);
}
let autoImportedTypes = [];
let autoImportExports = "";
if (nitro.unimport) {
await nitro.unimport.init();
const allImports = await nitro.unimport.getImports();
autoImportExports = toExports(allImports).replace(
/#internal\/nitro/g,
relative(typesDir, runtimeDir)
);
const resolvedImportPathMap = /* @__PURE__ */ new Map();
for (const i of allImports) {
if (resolvedImportPathMap.has(i.from)) {
continue;
}
let path = resolveAlias(i.from, nitro.options.alias);
if (!isAbsolute(path)) {
const resolvedPath = resolveModulePath(i.from, {
try: true,
from: nitro.options.nodeModulesDirs,
conditions: ["type", "node", "import"],
suffixes: ["", "/index"],
extensions: [".mjs", ".cjs", ".js", ".mts", ".cts", ".ts"]
});
if (resolvedPath) {
const { dir, name } = parseNodeModulePath(resolvedPath);
if (!dir || !name) {
path = resolvedPath;
} else {
const subpath = await lookupNodeModuleSubpath(resolvedPath);
path = join(dir, name, subpath || "");
}
}
}
if (existsSync(path) && !await isDirectory(path)) {
path = path.replace(/\.[a-z]+$/, "");
}
if (isAbsolute(path)) {
path = relative(typesDir, path);
}
resolvedImportPathMap.set(i.from, path);
}
autoImportedTypes = [
nitro.options.imports && nitro.options.imports.autoImport !== false ? (await nitro.unimport.generateTypeDeclarations({
exportHelper: false,
resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
})).trim() : ""
];
}
const generateRoutes = () => [
"// Generated by nitro",
'import type { Serialize, Simplify } from "nitro/types";',
'declare module "nitro/types" {',
" type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T",
" interface InternalApi {",
...Object.entries(types.routes).map(
([path, methods]) => [
` '${path}': {`,
...Object.entries(methods).map(
([method, types2]) => ` '${method}': ${types2.join(" | ")}`
),
" }"
].join("\n")
),
" }",
"}",
// Makes this a module for augmentation purposes
"export {}"
];
const config = [
"// Generated by nitro",
/* ts */
`declare module "nitro/types" {`,
nitro.options.typescript.generateRuntimeConfigTypes ? generateTypes(
await resolveSchema(
Object.fromEntries(
Object.entries(nitro.options.runtimeConfig).filter(
([key]) => !["app", "nitro"].includes(key)
)
)
),
{
interfaceName: "NitroRuntimeConfig",
addExport: false,
addDefaults: false,
allowExtraKeys: false,
indentation: 2
}
) : "",
`}`,
// Makes this a module for augmentation purposes
"export {}"
];
const declarations = [
// local nitropack augmentations
'/// <reference path="./nitro-routes.d.ts" />',
'/// <reference path="./nitro-config.d.ts" />',
// global server auto-imports
'/// <reference path="./nitro-imports.d.ts" />'
];
const buildFiles = [];
buildFiles.push({
path: join(typesDir, "nitro-routes.d.ts"),
contents: () => generateRoutes().join("\n")
});
buildFiles.push({
path: join(typesDir, "nitro-config.d.ts"),
contents: config.join("\n")
});
buildFiles.push({
path: join(typesDir, "nitro-imports.d.ts"),
contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
"\n"
)
});
buildFiles.push({
path: join(typesDir, "nitro.d.ts"),
contents: declarations.join("\n")
});
if (nitro.options.typescript.generateTsConfig) {
const tsConfigPath = resolve(
nitro.options.buildDir,
nitro.options.typescript.tsconfigPath
);
const tsconfigDir = dirname(tsConfigPath);
const tsConfig = defu(nitro.options.typescript.tsConfig, {
compilerOptions: {
/* Base options: */
esModuleInterop: true,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
target: "ESNext",
allowJs: true,
resolveJsonModule: true,
moduleDetection: "force",
isolatedModules: true,
verbatimModuleSyntax: true,
allowImportingTsExtensions: true,
/* Strictness */
strict: nitro.options.typescript.strict,
noUncheckedIndexedAccess: true,
noImplicitOverride: true,
forceConsistentCasingInFileNames: true,
/* If NOT transpiling with TypeScript: */
module: "Preserve",
jsx: "preserve",
jsxFactory: "h",
jsxFragmentFactory: "Fragment",
paths: {
"#imports": [
relativeWithDot(tsconfigDir, join(typesDir, "nitro-imports"))
],
...nitro.options.typescript.internalPaths ? {
"nitro/runtime": [
relativeWithDot(tsconfigDir, join(runtimeDir, "index"))
],
"#internal/nitro": [
relativeWithDot(tsconfigDir, join(runtimeDir, "index"))
],
"nitro/runtime/*": [
relativeWithDot(tsconfigDir, join(runtimeDir, "*"))
],
"#internal/nitro/*": [
relativeWithDot(tsconfigDir, join(runtimeDir, "*"))
]
} : {}
}
},
include: [
relativeWithDot(tsconfigDir, join(typesDir, "nitro.d.ts")).replace(
/^(?=[^.])/,
"./"
),
join(relativeWithDot(tsconfigDir, nitro.options.rootDir), "**/*"),
...nitro.options.srcDir === nitro.options.rootDir ? [] : [join(relativeWithDot(tsconfigDir, nitro.options.srcDir), "**/*")]
]
});
for (const alias in tsConfig.compilerOptions.paths) {
const paths = await Promise.all(
tsConfig.compilerOptions.paths[alias].map(async (path) => {
if (!isAbsolute(path)) {
return path;
}
const stats = await promises.stat(path).catch(
() => null
/* file does not exist */
);
return relativeWithDot(
tsconfigDir,
stats?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, "") : path
);
})
);
tsConfig.compilerOptions.paths[alias] = [...new Set(paths)];
}
tsConfig.include = [
...new Set(
tsConfig.include.map(
(p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p
)
)
];
if (tsConfig.exclude) {
tsConfig.exclude = [
...new Set(
tsConfig.exclude.map(
(p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p
)
)
];
}
types.tsConfig = tsConfig;
buildFiles.push({
path: tsConfigPath,
contents: () => JSON.stringify(tsConfig, null, 2)
});
}
await nitro.hooks.callHook("types:extend", types);
await Promise.all(
buildFiles.map(async (file) => {
await writeFile(
resolve(nitro.options.buildDir, file.path),
typeof file.contents === "string" ? file.contents : file.contents()
);
})
);
}
const RELATIVE_RE = /^\.{1,2}\//;
function relativeWithDot(from, to) {
const rel = relative(from, to);
return RELATIVE_RE.test(rel) ? rel : "./" + rel;
}
export { build as b, prerender as p, runParallel as r, writeTypes as w };

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { N } from './index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
function R(C){return C&&C.__esModule&&Object.prototype.hasOwnProperty.call(C,"default")?C.default:C}var O={},M;function Y(){return M||(M=1,O.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,O.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,O.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/),O}var _,U;function T(){if(U)return _;U=1;const C=Y();return _={isSpaceSeparator(r){return typeof r=="string"&&C.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||C.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||C.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}},_}var q,Z;function uu(){if(Z)return q;Z=1;const C=T();let r,s,c,d,h,o,f,S,m;q=function(a,g){r=String(a),s="start",c=[],d=0,h=1,o=0,f=void 0,S=void 0,m=void 0;do f=E(),Q[s]();while(f.type!=="eof");return typeof g=="function"?v({"":m},"",g):m};function v(D,a,g){const y=D[a];if(y!=null&&typeof y=="object")if(Array.isArray(y))for(let P=0;P<y.length;P++){const I=String(P),H=v(y,I,g);H===void 0?delete y[I]:Object.defineProperty(y,I,{value:H,writable:true,enumerable:true,configurable:true});}else for(const P in y){const I=v(y,P,g);I===void 0?delete y[P]:Object.defineProperty(y,P,{value:I,writable:true,enumerable:true,configurable:true});}return g.call(D,a,y)}let t,e,x,w,A;function E(){for(t="default",e="",x=false,w=1;;){A=n();const D=l[t]();if(D)return D}}function n(){if(r[d])return String.fromCodePoint(r.codePointAt(d))}function u(){const D=n();return D===`
`?(h++,o=0):D?o+=D.length:o++,D&&(d+=D.length),D}const l={default(){switch(A){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
`:case "\r":case "\u2028":case "\u2029":u();return;case "/":u(),t="comment";return;case void 0:return u(),F("eof")}if(C.isSpaceSeparator(A)){u();return}return l[s]()},comment(){switch(A){case "*":u(),t="multiLineComment";return;case "/":u(),t="singleLineComment";return}throw B(u())},multiLineComment(){switch(A){case "*":u(),t="multiLineCommentAsterisk";return;case void 0:throw B(u())}u();},multiLineCommentAsterisk(){switch(A){case "*":u();return;case "/":u(),t="default";return;case void 0:throw B(u())}u(),t="multiLineComment";},singleLineComment(){switch(A){case `
`:case "\r":case "\u2028":case "\u2029":u(),t="default";return;case void 0:return u(),F("eof")}u();},value(){switch(A){case "{":case "[":return F("punctuator",u());case "n":return u(),i("ull"),F("null",null);case "t":return u(),i("rue"),F("boolean",true);case "f":return u(),i("alse"),F("boolean",false);case "-":case "+":u()==="-"&&(w=-1),t="sign";return;case ".":e=u(),t="decimalPointLeading";return;case "0":e=u(),t="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":e=u(),t="decimalInteger";return;case "I":return u(),i("nfinity"),F("numeric",1/0);case "N":return u(),i("aN"),F("numeric",NaN);case '"':case "'":x=u()==='"',e="",t="string";return}throw B(u())},identifierNameStartEscape(){if(A!=="u")throw B(u());u();const D=$();switch(D){case "$":case "_":break;default:if(!C.isIdStartChar(D))throw L();break}e+=D,t="identifierName";},identifierName(){switch(A){case "$":case "_":case "\u200C":case "\u200D":e+=u();return;case "\\":u(),t="identifierNameEscape";return}if(C.isIdContinueChar(A)){e+=u();return}return F("identifier",e)},identifierNameEscape(){if(A!=="u")throw B(u());u();const D=$();switch(D){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!C.isIdContinueChar(D))throw L();break}e+=D,t="identifierName";},sign(){switch(A){case ".":e=u(),t="decimalPointLeading";return;case "0":e=u(),t="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":e=u(),t="decimalInteger";return;case "I":return u(),i("nfinity"),F("numeric",w*(1/0));case "N":return u(),i("aN"),F("numeric",NaN)}throw B(u())},zero(){switch(A){case ".":e+=u(),t="decimalPoint";return;case "e":case "E":e+=u(),t="decimalExponent";return;case "x":case "X":e+=u(),t="hexadecimal";return}return F("numeric",w*0)},decimalInteger(){switch(A){case ".":e+=u(),t="decimalPoint";return;case "e":case "E":e+=u(),t="decimalExponent";return}if(C.isDigit(A)){e+=u();return}return F("numeric",w*Number(e))},decimalPointLeading(){if(C.isDigit(A)){e+=u(),t="decimalFraction";return}throw B(u())},decimalPoint(){switch(A){case "e":case "E":e+=u(),t="decimalExponent";return}if(C.isDigit(A)){e+=u(),t="decimalFraction";return}return F("numeric",w*Number(e))},decimalFraction(){switch(A){case "e":case "E":e+=u(),t="decimalExponent";return}if(C.isDigit(A)){e+=u();return}return F("numeric",w*Number(e))},decimalExponent(){switch(A){case "+":case "-":e+=u(),t="decimalExponentSign";return}if(C.isDigit(A)){e+=u(),t="decimalExponentInteger";return}throw B(u())},decimalExponentSign(){if(C.isDigit(A)){e+=u(),t="decimalExponentInteger";return}throw B(u())},decimalExponentInteger(){if(C.isDigit(A)){e+=u();return}return F("numeric",w*Number(e))},hexadecimal(){if(C.isHexDigit(A)){e+=u(),t="hexadecimalInteger";return}throw B(u())},hexadecimalInteger(){if(C.isHexDigit(A)){e+=u();return}return F("numeric",w*Number(e))},string(){switch(A){case "\\":u(),e+=p();return;case '"':if(x)return u(),F("string",e);e+=u();return;case "'":if(!x)return u(),F("string",e);e+=u();return;case `
`:case "\r":throw B(u());case "\u2028":case "\u2029":X(A);break;case void 0:throw B(u())}e+=u();},start(){switch(A){case "{":case "[":return F("punctuator",u())}t="value";},beforePropertyName(){switch(A){case "$":case "_":e=u(),t="identifierName";return;case "\\":u(),t="identifierNameStartEscape";return;case "}":return F("punctuator",u());case '"':case "'":x=u()==='"',t="string";return}if(C.isIdStartChar(A)){e+=u(),t="identifierName";return}throw B(u())},afterPropertyName(){if(A===":")return F("punctuator",u());throw B(u())},beforePropertyValue(){t="value";},afterPropertyValue(){switch(A){case ",":case "}":return F("punctuator",u())}throw B(u())},beforeArrayValue(){if(A==="]")return F("punctuator",u());t="value";},afterArrayValue(){switch(A){case ",":case "]":return F("punctuator",u())}throw B(u())},end(){throw B(u())}};function F(D,a){return {type:D,value:a,line:h,column:o}}function i(D){for(const a of D){if(n()!==a)throw B(u());u();}}function p(){switch(n()){case "b":return u(),"\b";case "f":return u(),"\f";case "n":return u(),`
`;case "r":return u(),"\r";case "t":return u()," ";case "v":return u(),"\v";case "0":if(u(),C.isDigit(n()))throw B(u());return "\0";case "x":return u(),b();case "u":return u(),$();case `
`:case "\u2028":case "\u2029":return u(),"";case "\r":return u(),n()===`
`&&u(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw B(u());case void 0:throw B(u())}return u()}function b(){let D="",a=n();if(!C.isHexDigit(a)||(D+=u(),a=n(),!C.isHexDigit(a)))throw B(u());return D+=u(),String.fromCodePoint(parseInt(D,16))}function $(){let D="",a=4;for(;a-- >0;){const g=n();if(!C.isHexDigit(g))throw B(u());D+=u();}return String.fromCodePoint(parseInt(D,16))}const Q={start(){if(f.type==="eof")throw N();V();},beforePropertyName(){switch(f.type){case "identifier":case "string":S=f.value,s="afterPropertyName";return;case "punctuator":j();return;case "eof":throw N()}},afterPropertyName(){if(f.type==="eof")throw N();s="beforePropertyValue";},beforePropertyValue(){if(f.type==="eof")throw N();V();},beforeArrayValue(){if(f.type==="eof")throw N();if(f.type==="punctuator"&&f.value==="]"){j();return}V();},afterPropertyValue(){if(f.type==="eof")throw N();switch(f.value){case ",":s="beforePropertyName";return;case "}":j();}},afterArrayValue(){if(f.type==="eof")throw N();switch(f.value){case ",":s="beforeArrayValue";return;case "]":j();}},end(){}};function V(){let D;switch(f.type){case "punctuator":switch(f.value){case "{":D={};break;case "[":D=[];break}break;case "null":case "boolean":case "numeric":case "string":D=f.value;break}if(m===void 0)m=D;else {const a=c[c.length-1];Array.isArray(a)?a.push(D):Object.defineProperty(a,S,{value:D,writable:true,enumerable:true,configurable:true});}if(D!==null&&typeof D=="object")c.push(D),Array.isArray(D)?s="beforeArrayValue":s="beforePropertyName";else {const a=c[c.length-1];a==null?s="end":Array.isArray(a)?s="afterArrayValue":s="afterPropertyValue";}}function j(){c.pop();const D=c[c.length-1];D==null?s="end":Array.isArray(D)?s="afterArrayValue":s="afterPropertyValue";}function B(D){return k(D===void 0?`JSON5: invalid end of input at ${h}:${o}`:`JSON5: invalid character '${z(D)}' at ${h}:${o}`)}function N(){return k(`JSON5: invalid end of input at ${h}:${o}`)}function L(){return o-=5,k(`JSON5: invalid identifier character at ${h}:${o}`)}function X(D){console.warn(`JSON5: '${z(D)}' in strings is not valid ECMAScript; consider escaping`);}function z(D){const a={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(a[D])return a[D];if(D<" "){const g=D.charCodeAt(0).toString(16);return "\\x"+("00"+g).substring(g.length)}return D}function k(D){const a=new SyntaxError(D);return a.lineNumber=h,a.columnNumber=o,a}return q}var Du=uu();const eu=R(Du);var J,K;function tu(){if(K)return J;K=1;const C=T();return J=function(s,c,d){const h=[];let o="",f,S,m="",v;if(c!=null&&typeof c=="object"&&!Array.isArray(c)&&(d=c.space,v=c.quote,c=c.replacer),typeof c=="function")S=c;else if(Array.isArray(c)){f=[];for(const E of c){let n;typeof E=="string"?n=E:(typeof E=="number"||E instanceof String||E instanceof Number)&&(n=String(E)),n!==void 0&&f.indexOf(n)<0&&f.push(n);}}return d instanceof Number?d=Number(d):d instanceof String&&(d=String(d)),typeof d=="number"?d>0&&(d=Math.min(10,Math.floor(d)),m=" ".substr(0,d)):typeof d=="string"&&(m=d.substr(0,10)),t("",{"":s});function t(E,n){let u=n[E];switch(u!=null&&(typeof u.toJSON5=="function"?u=u.toJSON5(E):typeof u.toJSON=="function"&&(u=u.toJSON(E))),S&&(u=S.call(n,E,u)),u instanceof Number?u=Number(u):u instanceof String?u=String(u):u instanceof Boolean&&(u=u.valueOf()),u){case null:return "null";case true:return "true";case false:return "false"}if(typeof u=="string")return e(u);if(typeof u=="number")return String(u);if(typeof u=="object")return Array.isArray(u)?A(u):x(u)}function e(E){const n={"'":.1,'"':.2},u={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let l="";for(let i=0;i<E.length;i++){const p=E[i];switch(p){case "'":case '"':n[p]++,l+=p;continue;case "\0":if(C.isDigit(E[i+1])){l+="\\x00";continue}}if(u[p]){l+=u[p];continue}if(p<" "){let b=p.charCodeAt(0).toString(16);l+="\\x"+("00"+b).substring(b.length);continue}l+=p;}const F=v||Object.keys(n).reduce((i,p)=>n[i]<n[p]?i:p);return l=l.replace(new RegExp(F,"g"),u[F]),F+l+F}function x(E){if(h.indexOf(E)>=0)throw TypeError("Converting circular structure to JSON5");h.push(E);let n=o;o=o+m;let u=f||Object.keys(E),l=[];for(const i of u){const p=t(i,E);if(p!==void 0){let b=w(i)+":";m!==""&&(b+=" "),b+=p,l.push(b);}}let F;if(l.length===0)F="{}";else {let i;if(m==="")i=l.join(","),F="{"+i+"}";else {let p=`,
`+o;i=l.join(p),F=`{
`+o+i+`,
`+n+"}";}}return h.pop(),o=n,F}function w(E){if(E.length===0)return e(E);const n=String.fromCodePoint(E.codePointAt(0));if(!C.isIdStartChar(n))return e(E);for(let u=n.length;u<E.length;u++)if(!C.isIdContinueChar(String.fromCodePoint(E.codePointAt(u))))return e(E);return E}function A(E){if(h.indexOf(E)>=0)throw TypeError("Converting circular structure to JSON5");h.push(E);let n=o;o=o+m;let u=[];for(let F=0;F<E.length;F++){const i=t(String(F),E);u.push(i!==void 0?i:"null");}let l;if(u.length===0)l="[]";else if(m==="")l="["+u.join(",")+"]";else {let F=`,
`+o,i=u.join(F);l=`[
`+o+i+`,
`+n+"]";}return h.pop(),o=n,l}},J}var Fu=tu();R(Fu);function Cu(C,r){const s=eu(C,r?.reviver);return N(C,s,r),s}
export { Cu as parseJSON5 };
export { h as parseJSONC } from './index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _UNC_REGEX = /^[/\\]{2}/;
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
const normalize = function(path) {
if (path.length === 0) {
return ".";
}
path = normalizeWindowsPath(path);
const isUNCPath = path.match(_UNC_REGEX);
const isPathAbsolute = isAbsolute(path);
const trailingSeparator = path[path.length - 1] === "/";
path = normalizeString(path, !isPathAbsolute);
if (path.length === 0) {
if (isPathAbsolute) {
return "/";
}
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) {
path += "/";
}
if (_DRIVE_LETTER_RE.test(path)) {
path += "/";
}
if (isUNCPath) {
if (!isPathAbsolute) {
return `//./${path}`;
}
return `//${path}`;
}
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
};
const join = function(...segments) {
let path = "";
for (const seg of segments) {
if (!seg) {
continue;
}
if (path.length > 0) {
const pathTrailing = path[path.length - 1] === "/";
const segLeading = seg[0] === "/";
const both = pathTrailing && segLeading;
if (both) {
path += seg.slice(1);
} else {
path += pathTrailing || segLeading ? seg : `/${seg}`;
}
} else {
path += seg;
}
}
return normalize(path);
};
function cwd() {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd().replace(/\\/g, "/");
}
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd();
if (!path || path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) {
char = path[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path.slice(lastSlash + 1, index)}`;
} else {
res = path.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const extname = function(p) {
if (p === "..") return "";
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
return match && match[1] || "";
};
const relative = function(from, to) {
const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
return _to.join("/");
}
const _fromCopy = [..._from];
for (const segment of _fromCopy) {
if (_to[0] !== segment) {
break;
}
_from.shift();
_to.shift();
}
return [..._from.map(() => ".."), ..._to].join("/");
};
const dirname = function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
segments[0] += "/";
}
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
const basename = function(p, extension) {
const segments = normalizeWindowsPath(p).split("/");
let lastSegment = "";
for (let i = segments.length - 1; i >= 0; i--) {
const val = segments[i];
if (val) {
lastSegment = val;
break;
}
}
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
};
const parse = function(p) {
const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
const base = basename(p);
const extension = extname(base);
return {
root,
dir: dirname(p),
base,
ext: extension,
name: base.slice(0, base.length - extension.length)
};
};
export { relative as a, basename as b, normalizeWindowsPath as c, dirname as d, extname as e, isAbsolute as i, join as j, normalize as n, parse as p, resolve as r };
import { s as sanitizeFilePath, f as formatCompatibilityDate, d as copyPublicAssets, a as scanHandlers, r as resolveModulePath, e as prettyPath, i as createNitro, j as prepare } from './index.mjs';
import { fileURLToPath } from 'node:url';
import { colors } from 'consola/utils';
import { defu } from 'defu';
import 'ufo';
import { existsSync, watch as watch$1 } from 'node:fs';
import { readFile, rm, mkdir, writeFile, readlink } from 'node:fs/promises';
import 'node:zlib';
import 'node:worker_threads';
import consola from 'consola';
import 'std-env';
import 'h3';
import 'undici';
import 'nitro/meta';
import { NodeRequest, sendNodeResponse } from 'srvx/node';
import { d as debounce, w as watch, a as NodeDevWorker, c as createProxyServer, N as NitroDevApp } from './app.mjs';
import 'klona/full';
import { runtimeDir, runtimeDependencies } from 'nitro/runtime/meta';
import 'ofetch';
import { a as alias, i as inject } from './index2.mjs';
import { b as baseBuildConfig, d as baseBuildPlugins, r as replace, e as writeBuildInfo } from './info.mjs';
import { r as resolve, d as dirname, n as normalize, b as basename, a as relative, j as join, i as isAbsolute } from './pathe.M-eThtNZ.mjs';
import 'hookable';
import 'jiti';
import 'klona';
import 'unstorage';
import 'ohash';
import { resolve as resolve$1, join as join$1 } from 'node:path';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import { DevEnvironment } from 'vite';
import { getRandomPort } from 'get-port-please';
import { spawn } from 'node:child_process';
const getViteRollupConfig = (ctx) => {
const nitro = ctx.nitro;
const base = baseBuildConfig(nitro);
const chunkNamePrefixes = [
[nitro.options.buildDir, "build"],
[base.buildServerDir, "app"],
[runtimeDir, "nitro"],
[base.presetsDir, "nitro"],
["\0raw:", "raw"],
["\0nitro-wasm:", "wasm"],
["\0", "virtual"]
];
function getChunkGroup(id) {
if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) {
return "nitro";
}
}
let config = {
input: nitro.options.entry,
external: [...base.env.external],
plugins: [
ctx.pluginConfig.experimental?.virtualBundle && virtualBundlePlugin(ctx._serviceBundles),
...baseBuildPlugins(nitro, base),
alias({ entries: base.aliases }),
replace({ preventAssignment: true, values: base.replacements }),
inject(base.env.inject)
].filter(Boolean),
treeshake: {
moduleSideEffects(id) {
const normalizedId = normalize(id);
const idWithoutNodeModules = normalizedId.split("node_modules/").pop();
if (!idWithoutNodeModules) {
return false;
}
if (normalizedId.startsWith(runtimeDir) || idWithoutNodeModules.startsWith(runtimeDir)) {
return true;
}
return nitro.options.moduleSideEffects.some(
(m) => normalizedId.startsWith(m) || idWithoutNodeModules.startsWith(m)
);
}
},
output: {
dir: nitro.options.output.serverDir,
entryFileNames: "index.mjs",
chunkFileNames(chunk) {
const id = normalize(chunk.moduleIds.at(-1) || "");
for (const [dir, name] of chunkNamePrefixes) {
if (id.startsWith(dir)) {
return `chunks/${name}/[name].mjs`;
}
}
const routeHandler = nitro.options.handlers.find(
(h) => id.startsWith(h.handler)
) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
if (routeHandler?.route) {
const path = routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/";
return `chunks/routes/${path}/[name].mjs`.replace(/\/+/g, "/");
}
const taskHandler = Object.entries(nitro.options.tasks).find(
([_, task]) => task.handler === id
);
if (taskHandler) {
return `chunks/tasks/[name].mjs`;
}
return `chunks/_/[name].mjs`;
},
manualChunks(id) {
return getChunkGroup(id);
},
inlineDynamicImports: nitro.options.inlineDynamicImports,
format: "esm",
exports: "auto",
intro: "",
outro: "",
generatedCode: {
constBindings: true
},
sanitizeFileName: sanitizeFilePath,
sourcemapExcludeSources: true,
sourcemapIgnoreList(relativePath) {
return relativePath.includes("node_modules");
}
}
};
config = defu(nitro.options.rollupConfig, config);
if (config.output.inlineDynamicImports) {
delete config.output.manualChunks;
}
return { config, base };
};
function virtualBundlePlugin(bundles) {
let _modules = null;
const getModules = () => {
if (_modules) {
return _modules;
}
_modules = /* @__PURE__ */ new Map();
for (const bundle of Object.values(bundles)) {
for (const [fileName, content] of Object.entries(bundle)) {
if (content.type === "chunk") {
const virtualModule = {
code: content.code,
map: null
};
const maybeMap = bundle[`${fileName}.map`];
if (maybeMap && maybeMap.type === "asset") {
virtualModule.map = maybeMap.source;
}
_modules.set(fileName, virtualModule);
_modules.set(resolve(fileName), virtualModule);
}
}
}
return _modules;
};
return {
name: "virtual-bundle",
resolveId(id, importer) {
const modules = getModules();
if (modules.has(id)) {
return resolve(id);
}
if (importer) {
const resolved = resolve(dirname(importer), id);
if (modules.has(resolved)) {
return resolved;
}
}
return null;
},
load(id) {
const modules = getModules();
const m = modules.get(id);
if (!m) {
return null;
}
return m;
}
};
}
const BuilderNames = {
nitro: colors.magenta("Nitro"),
client: colors.green("Client"),
ssr: colors.blue("SSR")
};
async function buildEnvironments(ctx, builder) {
const nitro = ctx.nitro;
for (const [envName, env] of Object.entries(builder.environments)) {
const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1));
if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) {
if (!["nitro", "ssr", "client"].includes(envName)) {
nitro.logger.info(
env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`
);
}
continue;
}
console.log();
nitro.logger.start(`Building [${fmtName}]`);
await builder.build(env);
}
const nitroOptions = ctx.nitro.options;
const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input;
if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) {
const outputPath = resolve(
nitroOptions.output.publicDir,
basename(clientInput)
);
if (existsSync(outputPath)) {
const html = await readFile(outputPath, "utf8").then(
(r) => r.replace(
"<!--ssr-outlet-->",
`{{{ fetch($REQUEST, { viteEnv: "ssr" }) }}}`
)
);
await rm(outputPath);
const tmp = resolve(nitroOptions.buildDir, "vite/index.html");
await mkdir(dirname(tmp), { recursive: true });
await writeFile(tmp, html, "utf8");
nitroOptions.renderer.template = tmp;
}
}
console.log();
const buildInfo = [
["preset", nitro.options.preset],
["compatibility", formatCompatibilityDate(nitro.options.compatibilityDate)]
].filter((e) => e[1]);
nitro.logger.start(
`Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`
);
await copyPublicAssets(nitro);
await nitro.hooks.callHook(
"rollup:before",
nitro,
builder.environments.nitro.config.build.rollupOptions
);
await builder.build(builder.environments.nitro);
await nitro.close();
await nitro.hooks.callHook("compiled", nitro);
await writeBuildInfo(nitro);
const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input) => {
return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
};
console.log();
if (nitro.options.commands.preview) {
nitro.logger.success(
`You can preview this build using \`${rewriteRelativePaths(
nitro.options.commands.preview
)}\``
);
}
if (nitro.options.commands.deploy) {
nitro.logger.success(
`You can deploy this build using \`${rewriteRelativePaths(
nitro.options.commands.deploy
)}\``
);
}
}
function prodSetup(ctx) {
const services = ctx.pluginConfig.services || {};
const serviceNames = Object.keys(services);
const serviceEntries = serviceNames.map((name) => {
let entry;
if (ctx.pluginConfig.experimental?.virtualBundle) {
entry = ctx._entryPoints[name];
} else {
entry = resolve(
ctx.nitro.options.buildDir,
"vite/services",
name,
ctx._entryPoints[name]
);
}
return [name, entry];
});
return (
/* js */
`
import { setupVite } from "${resolve(runtimeDir, "internal/vite/prod-setup.mjs")}";
const manifest = ${JSON.stringify(ctx._manifest || {})};
function lazyService(loader) {
let promise, mod
return {
fetch(req) {
if (mod) { return mod.fetch(req) }
if (!promise) {
promise = loader().then(_mod => (mod = _mod.default || _mod))
}
return promise.then(mod => mod.fetch(req))
}
}
}
const services = {
${serviceEntries.map(
([name, entry]) => (
/* js */
`[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`
)
).join(",\n")}
};
setupVite({ manifest, services });
`
);
}
function createFetchableDevEnvironment(name, config, devServer, entry) {
const transport = createTransport(name, devServer);
const context = { hot: true, transport };
return new FetchableDevEnvironment(name, config, context, devServer, entry);
}
class FetchableDevEnvironment extends DevEnvironment {
devServer;
constructor(name, config, context, devServer, entry) {
super(name, config, context);
this.devServer = devServer;
this.devServer.sendMessage({
type: "custom",
event: "nitro:vite-env",
data: { name, entry }
});
}
async dispatchFetch(request) {
return this.devServer.fetch(request);
}
async init(...args) {
await this.devServer.init?.();
return super.init(...args);
}
}
function createTransport(name, hooks) {
const listeners = /* @__PURE__ */ new WeakMap();
return {
send: (data) => hooks.sendMessage({ ...data, viteEnv: name }),
on: (event, handler) => {
if (event === "connection") return;
const listener = (value) => {
if (value?.type === "custom" && value.event === event && value.viteEnv === name) {
handler(value.data, {
send: (payload) => hooks.sendMessage({ ...payload, viteEnv: name })
});
}
};
listeners.set(handler, listener);
hooks.onMessage(listener);
},
off: (event, handler) => {
if (event === "connection") return;
const listener = listeners.get(handler);
if (listener) {
hooks.offMessage(listener);
listeners.delete(handler);
}
}
};
}
async function configureViteDevServer(ctx, server) {
const nitro = ctx.nitro;
const nitroEnv = server.environments.nitro;
const nitroConfigFile = nitro.options._c12.configFile;
if (nitroConfigFile) {
server.config.configFileDependencies.push(nitroConfigFile);
}
const reload = debounce(async () => {
await scanHandlers(nitro);
nitro.routing.sync();
nitroEnv.moduleGraph.invalidateAll();
nitroEnv.hot.send({ type: "full-reload" });
});
const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
join(dir, nitro.options.apiDir || "api"),
join(dir, nitro.options.routesDir || "routes"),
join(dir, "middleware"),
join(dir, "plugins"),
join(dir, "modules")
]);
const watchReloadEvents = /* @__PURE__ */ new Set(["add", "addDir", "unlink", "unlinkDir"]);
const scanDirsWatcher = watch(scanDirs, {
ignoreInitial: true
}).on("all", (event, path, stat) => {
if (watchReloadEvents.has(event)) {
reload();
}
});
const srcDirWatcher = watch$1(
nitro.options.srcDir,
{ persistent: false },
(_event, filename) => {
if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) {
reload();
}
}
);
nitro.hooks.hook("close", () => {
scanDirsWatcher.close();
srcDirWatcher.close();
});
const hostIPC = {
async transformHTML(html) {
return server.transformIndexHtml("/", html).then(
(r) => r.replace(
"<!--ssr-outlet-->",
`{{{ fetch($REQUEST, { viteEnv: "ssr" }) }}}`
)
);
}
};
nitroEnv.devServer.onMessage(async (payload) => {
if (payload.type === "custom" && payload.event === "nitro:vite-invoke") {
const methodName = payload.data.name;
const res = await hostIPC[methodName](payload.data.data).then((data) => ({ data })).catch((error) => ({ error }));
nitroEnv.devServer.sendMessage({
type: "custom",
event: "nitro:vite-invoke-response",
data: { id: payload.data.id, data: res }
});
}
});
const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
if (/^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled) {
return next();
}
nodeReq._nitroHandled = true;
const req = new NodeRequest({ req: nodeReq, res: nodeRes });
const devAppRes = await ctx.devApp.fetch(req);
if (nodeRes.writableEnded || nodeRes.headersSent) {
return;
}
if (devAppRes.status !== 404) {
return await sendNodeResponse(nodeRes, devAppRes);
}
const envRes = await nitroEnv.dispatchFetch(req);
if (nodeRes.writableEnded || nodeRes.headersSent) {
return;
}
if (envRes.status !== 404) {
return await sendNodeResponse(nodeRes, envRes);
}
return next();
};
server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
const fetchDest = req.headers["sec-fetch-dest"];
if (fetchDest) {
res.setHeader("vary", "sec-fetch-dest");
}
if (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest)) {
nitroDevMiddleware(req, res, next);
} else {
next();
}
});
return () => {
server.middlewares.use(nitroDevMiddleware);
};
}
function createDevWorker(ctx) {
return new NodeDevWorker({
name: "nitro-vite",
entry: resolve$1(runtimeDir, "internal/vite/dev-worker.mjs"),
hooks: {},
data: {
server: true,
globals: {
__NITRO_RUNTIME_CONFIG__: ctx.nitro.options.runtimeConfig
}
}
});
}
function createNitroEnvironment(ctx) {
return {
consumer: "server",
build: {
rollupOptions: ctx.rollupConfig.config,
minify: ctx.nitro.options.minify,
emptyOutDir: false,
commonjsOptions: {
strictRequires: "auto",
// TODO: set to true (default) in v3
esmExternals: (id) => !id.startsWith("unenv/"),
requireReturnsDefault: "auto",
...ctx.nitro.options.commonJS
}
},
resolve: {
noExternal: ctx.nitro.options.dev ? (
// Workaround for dev: external dependencies are not resolvable with respect to nodeModulePaths
new RegExp(runtimeDependencies.join("|"))
) : (
// Workaround for build: externals tracing is unstable
ctx.nitro.options.noExternals === false ? void 0 : true
),
// prettier-ignore
conditions: ctx.nitro.options.exportConditions,
externalConditions: ctx.nitro.options.exportConditions
},
dev: {
createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(
envName,
envConfig,
ctx.devWorker,
resolve$1(runtimeDir, "internal/vite/dev-entry.mjs")
)
}
};
}
function createServiceEnvironment(ctx, name, serviceConfig) {
return {
consumer: "server",
build: {
rollupOptions: { input: serviceConfig.entry },
minify: ctx.nitro.options.minify,
outDir: join$1(ctx.nitro.options.buildDir, "vite", "services", name),
emptyOutDir: true
},
resolve: {
noExternal: ctx.nitro.options.dev ? void 0 : true,
conditions: ctx.nitro.options.exportConditions,
externalConditions: ctx.nitro.options.exportConditions
},
dev: {
createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(
envName,
envConfig,
ctx.devWorker,
tryResolve(serviceConfig.entry)
)
}
};
}
function createServiceEnvironments(ctx) {
return Object.fromEntries(
Object.entries(ctx.pluginConfig.services || {}).map(([name, config]) => [
name,
createServiceEnvironment(ctx, name, config)
])
);
}
function tryResolve(id) {
if (/^[~#/\0]/.test(id) || isAbsolute(id)) {
return id;
}
const resolved = resolveModulePath(id, {
suffixes: ["", "/index"],
extensions: ["", ".ts", ".mjs", ".cjs", ".js", ".mts", ".cts"],
try: true
});
return resolved || id;
}
function nitroPreviewPlugin(ctx) {
return {
name: "nitro:preview",
apply: (_config, configEnv) => !!configEnv.isPreview,
config(config) {
return {
preview: {
port: config.preview?.port || 3e3
}
};
},
async configurePreviewServer(server) {
const buildInfoPath = resolve(
server.config.root,
"node_modules/.nitro/last-build",
"nitro.json"
);
if (!existsSync(buildInfoPath)) {
console.warn(
`[nitro] No build found. Please build your project before previewing.`
);
return;
}
const realBuildDir = await readlink("node_modules/.nitro/last-build");
const buildInfo = JSON.parse(
await readFile(buildInfoPath, "utf8")
);
const info = [
["Build Directory:", prettyPath(realBuildDir)],
["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()],
["Nitro Version:", buildInfo.versions.nitro],
["Nitro Preset:", buildInfo.preset],
buildInfo.framework?.name !== "nitro" && [
"Framework:",
buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")
]
].filter((i) => i && i[1]);
consola.box({
title: " [Build Info] ",
message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n")
});
if (!buildInfo.commands?.preview) {
consola.warn("[nitro] No preview command found for this preset..");
return;
}
const randomPort = await getRandomPort();
consola.info(`Spawning preview server...`);
const [command, ...args] = buildInfo.commands.preview.split(" ");
let child;
consola.info(buildInfo.commands?.preview);
child = spawn(command, args, {
stdio: "inherit",
cwd: realBuildDir,
env: {
...process.env,
PORT: String(randomPort)
}
});
process.on("exit", () => {
child?.kill();
child = void 0;
});
child.on("exit", (code) => {
if (code && code !== 0) {
consola.error(`[nitro] Preview server exited with code ${code}`);
}
});
const proxy = createProxyServer({
target: `http://localhost:${randomPort}`
});
server.middlewares.use((req, res, next) => {
if (child && !child.killed) {
proxy.web(req, res).catch(next);
} else {
res.end(`Nitro preview server is not running.`);
}
});
}
};
}
const DEFAULT_EXTENSIONS = [".ts", ".js", ".mts", ".mjs", ".tsx", ".jsx"];
function nitro(pluginConfig = {}) {
const ctx = {
pluginConfig,
_entryPoints: {},
_manifest: {},
_serviceBundles: {}
};
return [
nitroPlugin(ctx),
nitroServicePlugin(ctx),
nitroPreviewPlugin(),
nitroRollupPlugins(ctx)
];
}
function nitroPlugin(ctx) {
return [
{
name: "nitro:main",
// Opt-in this plugin into the shared plugins pipeline
sharedDuringBuild: true,
// Only apply this plugin during build or dev
apply: (config, configEnv) => !configEnv.isPreview,
// Extend vite config before it's resolved
async config(userConfig, configEnv) {
ctx.nitro = ctx.pluginConfig._nitro || await createNitro({
dev: configEnv.mode === "development",
rootDir: userConfig.root,
...defu(ctx.pluginConfig.config, userConfig.nitro)
});
if (!ctx.pluginConfig.services?.ssr) {
ctx.pluginConfig.services ??= {};
if (userConfig.environments?.ssr === void 0) {
const ssrEntry = resolveModulePath("./entry-server", {
from: ["", "app", "src"].flatMap(
(d) => ctx.nitro.options.scanDirs.map((s) => join(s, d) + "/")
),
extensions: DEFAULT_EXTENSIONS,
try: true
});
if (ssrEntry) {
ctx.pluginConfig.services.ssr = { entry: ssrEntry };
ctx.nitro.logger.info(
`Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`
);
}
} else {
let ssrEntry = getEntry(
userConfig.environments.ssr.build?.rollupOptions?.input
);
if (typeof ssrEntry === "string") {
ssrEntry = resolveModulePath(ssrEntry, {
from: ctx.nitro.options.scanDirs,
extensions: DEFAULT_EXTENSIONS,
suffixes: ["", "/index"],
try: true
}) || ssrEntry;
ctx.pluginConfig.services.ssr = { entry: ssrEntry };
} else {
this.error(`Invalid input type for SSR entry point.`);
}
}
}
if (!ctx.nitro.options.renderer?.entry && !ctx.nitro.options.renderer?.template && ctx.pluginConfig.services.ssr?.entry) {
ctx.nitro.options.renderer ??= {};
ctx.nitro.options.renderer.entry = resolve(
runtimeDir,
"internal/vite/ssr-renderer"
);
}
const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve(ctx.nitro.options.buildDir, "vite/public");
ctx.nitro.options.publicAssets.push({
dir: publicDistDir,
maxAge: 0,
baseURL: "/",
fallthrough: true
});
if (!ctx.nitro.options.dev) {
ctx.nitro.options.unenv.push({
meta: { name: "nitro-vite" },
polyfill: ["#nitro-vite-setup"]
});
}
await ctx.nitro.hooks.callHook("build:before", ctx.nitro);
ctx.rollupConfig = await getViteRollupConfig(ctx);
if (ctx.nitro.options.dev && !ctx.devWorker) {
ctx.devWorker = createDevWorker(ctx);
}
if (ctx.nitro.options.dev && !ctx.devApp) {
ctx.devApp = new NitroDevApp(ctx.nitro);
}
return {
// Don't include HTML middlewares
appType: userConfig.appType || "custom",
// Add Nitro as a Vite environment
environments: {
client: {
consumer: userConfig.environments?.client?.consumer ?? "client",
build: {
rollupOptions: {
input: userConfig.environments?.client?.build?.rollupOptions?.input ?? ctx.nitro.options.renderer?.template
}
}
},
...createServiceEnvironments(ctx),
nitro: createNitroEnvironment(ctx)
},
resolve: {
// TODO: environment specific aliases not working
// https://github.com/vitejs/vite/pull/17583 (seems not effective)
alias: ctx.rollupConfig.base.aliases
},
build: {
// TODO: Support server environment emitted assets
assetsInlineLimit: 4096 * 4
},
builder: {
/// Share the config instance among environments to align with the behavior of dev server
sharedConfigBuild: true
},
server: {
port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || ctx.nitro.options.devServer?.port || 3e3
}
};
},
configResolved(config) {
if (config.command === "build") {
for (const env of Object.values(config.environments)) {
if (env.consumer === "client") {
const { assetsDir } = env.build;
const rule = ctx.nitro.options.routeRules[`/${assetsDir}/**`] ??= {};
if (!rule.headers?.["cache-control"]) {
rule.headers = {
...rule.headers,
"cache-control": `public, max-age=31536000, immutable`
};
}
}
}
}
ctx.nitro.routing.sync();
},
buildApp: {
order: "post",
handler(builder) {
return buildEnvironments(ctx, builder);
}
},
generateBundle: {
handler(_options, bundle) {
const { root } = this.environment.config;
const services = ctx.pluginConfig.services || {};
const serviceNames = Object.keys(services);
const isRegisteredService = serviceNames.includes(
this.environment.name
);
let entryFile;
for (const [_name, file] of Object.entries(bundle)) {
if (file.type === "chunk") {
if (isRegisteredService && file.isEntry) {
if (entryFile !== void 0) {
this.error(
`Multiple entry points found for service "${this.environment.name}". Only one entry point is allowed.`
);
}
entryFile = file.fileName;
}
const filteredModuleIds = file.moduleIds.filter(
(id) => id.startsWith(root)
);
for (const id of filteredModuleIds) {
const originalFile = relative(root, id);
ctx._manifest[originalFile] = { file: file.fileName };
}
}
}
if (isRegisteredService) {
if (entryFile === void 0) {
this.error(
`No entry point found for service "${this.environment.name}".`
);
}
ctx._entryPoints[this.environment.name] = entryFile;
ctx._serviceBundles[this.environment.name] = bundle;
}
}
},
// Modify environment configs before it's resolved.
configEnvironment(name, config) {
if (config.consumer === "client") {
config.build.emptyOutDir = false;
config.build.outDir = ctx.nitro.options.output.publicDir;
}
const services = ctx.pluginConfig.services || {};
const serviceNames = Object.keys(services);
if (serviceNames.includes(name) && ctx.pluginConfig.experimental?.virtualBundle) {
config.build ??= {};
config.build.write = config.build.write ?? false;
}
},
// Extend Vite dev server with Nitro middleware
configureServer: (server) => configureViteDevServer(ctx, server)
},
{
name: "nitro:prepare",
buildApp: {
// clean the output directory before any environment is built
order: "pre",
async handler() {
const nitro2 = ctx.nitro;
await prepare(nitro2);
}
}
}
];
}
function nitroServicePlugin(ctx) {
return {
name: "nitro:service",
enforce: "pre",
// Only apply this plugin to the nitro environment
applyToEnvironment: (env) => env.name === "nitro",
resolveId: {
async handler(id, importer, options) {
if (id === "#nitro-vite-setup") {
return { id, moduleSideEffects: true };
}
if (id === "#nitro-vite-services") {
return id;
}
if (runtimeDependencies.some(
(dep) => id === dep || id.startsWith(`${dep}/`)
)) {
const resolved = await this.resolve(id, importer, {
...options,
skipSelf: true
});
return resolved || resolveModulePath(id, {
from: ctx.nitro.options.nodeModulesDirs,
conditions: ctx.nitro.options.exportConditions,
try: true
});
}
if (importer?.startsWith("\0virtual:#nitro-internal-virtual")) {
const internalRes = await this.resolve(id, import.meta.url, {
...options,
custom: { ...options.custom, skipNoExternals: true }
});
if (internalRes) {
return internalRes;
}
const resolvedFromRoot = await this.resolve(
id,
ctx.nitro.options.rootDir,
{ ...options, custom: { ...options.custom, skipNoExternals: true } }
);
if (resolvedFromRoot) {
return resolvedFromRoot;
}
const ids = [id];
if (!/^[./@#]/.test(id)) {
ids.push(`./${id}`);
}
for (const _id of ids) {
const resolved = resolveModulePath(_id, {
from: process.cwd(),
extensions: DEFAULT_EXTENSIONS,
suffixes: ["", "/index"],
try: true
});
if (resolved) {
return resolved;
}
}
}
}
},
load: {
async handler(id) {
if (id === "#nitro-vite-setup") {
return prodSetup(ctx);
}
}
}
};
}
function nitroRollupPlugins(ctx) {
const createHookCaller = (hook, order) => {
const handler = async function(...args) {
for (const plugin of ctx.rollupConfig.config.plugins) {
if (typeof plugin[hook] !== "function") continue;
const res = await plugin[hook].call(this, ...args);
if (res) {
if (hook === "resolveId" && res.id?.startsWith?.("file://")) {
res.id = fileURLToPath(res.id);
}
return res;
}
}
};
Object.defineProperty(handler, "name", { value: hook });
return order ? { order, handler } : handler;
};
return {
name: "nitro:rollup-hooks",
applyToEnvironment: (env) => env.name === "nitro",
buildStart: createHookCaller("buildStart", "pre"),
resolveId: createHookCaller("resolveId", "pre"),
load: createHookCaller("load", "pre"),
transform: createHookCaller("transform", "post"),
renderChunk: createHookCaller("renderChunk", "post"),
generateBundle: createHookCaller("generateBundle", "post"),
buildEnd: createHookCaller("buildEnd", "post")
};
}
function getEntry(input) {
if (typeof input === "string") {
return input;
} else if (Array.isArray(input) && input.length > 0) {
return input[0];
} else if (input && "index" in input) {
return input.index;
}
}
export { nitro as n };
import { N as NitroDevApp, d as debounce, w as watch, a as NodeDevWorker } from './app.mjs';
import { HTTPError } from 'h3';
import { version } from 'nitro/meta';
import consola from 'consola';
import { writeFile } from 'node:fs/promises';
import { serve } from 'srvx/node';
import { isTest, isCI } from 'std-env';
import { r as resolve } from './pathe.M-eThtNZ.mjs';
function createDevServer(nitro) {
return new NitroDevServer(nitro);
}
class NitroDevServer extends NitroDevApp {
#entry;
#workerData = {};
#listeners = [];
#watcher;
#workers = [];
#workerIdCtr = 0;
#workerError;
#building = true;
// Assume initial build will start soon
#buildError;
#messageListeners = /* @__PURE__ */ new Set();
constructor(nitro) {
super(nitro, async (event) => {
const worker = await this.#getWorker();
if (!worker) {
return this.#generateError();
}
return worker.fetch(event.req);
});
for (const key of Object.getOwnPropertyNames(NitroDevServer.prototype)) {
const value = this[key];
if (typeof value === "function" && key !== "constructor") {
this[key] = value.bind(this);
}
}
this.#entry = resolve(
nitro.options.output.dir,
nitro.options.output.serverDir,
"index.mjs"
);
nitro.hooks.hook("close", () => this.close());
nitro.hooks.hook("dev:start", () => {
this.#building = true;
this.#buildError = void 0;
});
nitro.hooks.hook("dev:reload", (payload) => {
this.#buildError = void 0;
this.#building = false;
if (payload?.entry) {
this.#entry = payload.entry;
}
if (payload?.workerData) {
this.#workerData = payload.workerData;
}
this.reload();
});
nitro.hooks.hook("dev:error", (cause) => {
this.#buildError = cause;
this.#building = false;
for (const worker of this.#workers) {
worker.close();
}
});
if (nitro.options.devServer.watch.length > 0) {
const debouncedReload = debounce(() => this.reload());
this.#watcher = watch(
nitro.options.devServer.watch,
nitro.options.watchOptions
);
this.#watcher.on("add", debouncedReload).on("change", debouncedReload);
}
}
// #region Public Methods
async upgrade(req, socket, head) {
const worker = await this.#getWorker();
if (!worker) {
throw new HTTPError({
status: 503,
statusText: "No worker available."
});
}
return worker.upgrade(req, socket, head);
}
listen(opts) {
const server = serve({
...opts,
fetch: this.fetch
});
this.#listeners.push(server);
if (server.node?.server) {
server.node.server.on(
"upgrade",
(req, sock, head) => this.upgrade(req, sock, head)
);
}
return server;
}
async close() {
await Promise.all(
[
Promise.all(this.#listeners.map((l) => l.close())).then(() => {
this.#listeners = [];
}),
Promise.all(this.#workers.map((w) => w.close())).then(() => {
this.#workers = [];
}),
Promise.resolve(this.#watcher?.close()).then(() => {
this.#watcher = void 0;
})
].map(
(p) => p.catch((error) => {
consola.error(error);
})
)
);
}
reload() {
for (const worker2 of this.#workers) {
worker2.close();
}
const worker = new NodeDevWorker({
name: `Nitro_${this.#workerIdCtr++}`,
entry: this.#entry,
data: {
...this.#workerData,
globals: {
__NITRO_RUNTIME_CONFIG__: this.nitro.options.runtimeConfig,
...this.#workerData.globals
}
},
hooks: {
onClose: (worker2, cause) => {
this.#workerError = cause;
const index = this.#workers.indexOf(worker2);
if (index !== -1) {
this.#workers.splice(index, 1);
}
},
onReady: (worker2, addr) => {
this.#writeBuildInfo(worker2, addr);
}
}
});
if (!worker.closed) {
for (const listener of this.#messageListeners) {
worker.onMessage(listener);
}
this.#workers.unshift(worker);
}
}
sendMessage(message) {
for (const worker of this.#workers) {
if (!worker.closed) {
worker.sendMessage(message);
}
}
}
onMessage(listener) {
this.#messageListeners.add(listener);
for (const worker of this.#workers) {
worker.onMessage(listener);
}
}
offMessage(listener) {
this.#messageListeners.delete(listener);
for (const worker of this.#workers) {
worker.offMessage(listener);
}
}
// #endregion
// #region Private Methods
#writeBuildInfo(_worker, addr) {
const buildInfoPath = resolve(this.nitro.options.buildDir, "nitro.json");
const buildInfo = {
date: (/* @__PURE__ */ new Date()).toJSON(),
preset: this.nitro.options.preset,
framework: this.nitro.options.framework,
versions: {
nitro: version
},
dev: {
pid: process.pid,
workerAddress: addr
}
};
writeFile(buildInfoPath, JSON.stringify(buildInfo, null, 2)).catch(
(error) => {
consola.error(error);
}
);
}
async #getWorker() {
let retry = 0;
const maxRetries = isTest || isCI ? 100 : 10;
while (this.#building || ++retry < maxRetries) {
if ((this.#workers.length === 0 || this.#buildError) && !this.#building) {
return;
}
const activeWorker = this.#workers.find((w) => w.ready);
if (activeWorker) {
return activeWorker;
}
await new Promise((resolve2) => setTimeout(resolve2, 600));
}
}
#generateError() {
const error = this.#buildError || this.#workerError;
if (error) {
try {
error.unhandled = false;
let id = error.id || error.path;
if (id) {
const cause = error.errors?.[0];
const loc = error.location || error.loc || cause?.location || cause?.loc;
if (loc) {
id += `:${loc.line}:${loc.column}`;
}
error.stack = (error.stack || "").replace(
/(^\s*at\s+.+)/m,
` at ${id}
$1`
);
}
} catch {
}
return new HTTPError(error);
}
return new Response(
JSON.stringify(
{
error: "Dev server is unavailable.",
hint: "Please reload the page and check the console for errors if the issue persists."
},
null,
2
),
{
status: 503,
statusText: "Dev server is unavailable",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store",
Refresh: "3"
}
}
);
}
// #endregion
}
export { NitroDevServer as N, createDevServer as c };
import { upperFirst } from 'scule';
import { promises } from 'node:fs';
import { colors } from 'consola/utils';
import { b as glob, c as snapshotStorage } from './index.mjs';
import 'node:stream';
import zlib from 'node:zlib';
import { promisify } from 'node:util';
import 'stream';
import { isTest } from 'std-env';
import { r as runParallel } from './index3.mjs';
import { r as resolve, d as dirname, a as relative, j as join } from './pathe.M-eThtNZ.mjs';
import { mkdir, writeFile } from 'node:fs/promises';
function nitroServerName(nitro) {
return nitro.options.framework.name === "nitro" ? "Nitro Server" : `${upperFirst(nitro.options.framework.name)} Nitro server`;
}
const getOptions = options => ({level: 9, ...options});
const gzip = promisify(zlib.gzip);
async function gzipSize(input, options) {
if (!input) {
return 0;
}
const data = await gzip(input, getOptions(options));
return data.length;
}
const BYTE_UNITS = [
'B',
'kB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB',
];
const BIBYTE_UNITS = [
'B',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
];
const BIT_UNITS = [
'b',
'kbit',
'Mbit',
'Gbit',
'Tbit',
'Pbit',
'Ebit',
'Zbit',
'Ybit',
];
const BIBIT_UNITS = [
'b',
'kibit',
'Mibit',
'Gibit',
'Tibit',
'Pibit',
'Eibit',
'Zibit',
'Yibit',
];
/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
- If locale is true, the system default locale is used for translation.
- If no value for locale is specified, the number is returned unmodified.
*/
const toLocaleString = (number, locale, options) => {
let result = number;
if (typeof locale === 'string' || Array.isArray(locale)) {
result = number.toLocaleString(locale, options);
} else if (locale === true || options !== undefined) {
result = number.toLocaleString(undefined, options);
}
return result;
};
const log10 = numberOrBigInt => {
if (typeof numberOrBigInt === 'number') {
return Math.log10(numberOrBigInt);
}
const string = numberOrBigInt.toString(10);
return string.length + Math.log10(`0.${string.slice(0, 15)}`);
};
const log = numberOrBigInt => {
if (typeof numberOrBigInt === 'number') {
return Math.log(numberOrBigInt);
}
return log10(numberOrBigInt) * Math.log(10);
};
const divide = (numberOrBigInt, divisor) => {
if (typeof numberOrBigInt === 'number') {
return numberOrBigInt / divisor;
}
const integerPart = numberOrBigInt / BigInt(divisor);
const remainder = numberOrBigInt % BigInt(divisor);
return Number(integerPart) + (Number(remainder) / divisor);
};
const applyFixedWidth = (result, fixedWidth) => {
if (fixedWidth === undefined) {
return result;
}
if (typeof fixedWidth !== 'number' || !Number.isSafeInteger(fixedWidth) || fixedWidth < 0) {
throw new TypeError(`Expected fixedWidth to be a non-negative integer, got ${typeof fixedWidth}: ${fixedWidth}`);
}
if (fixedWidth === 0) {
return result;
}
return result.length < fixedWidth ? result.padStart(fixedWidth, ' ') : result;
};
const buildLocaleOptions = options => {
const {minimumFractionDigits, maximumFractionDigits} = options;
if (minimumFractionDigits === undefined && maximumFractionDigits === undefined) {
return undefined;
}
return {
...(minimumFractionDigits !== undefined && {minimumFractionDigits}),
...(maximumFractionDigits !== undefined && {maximumFractionDigits}),
roundingMode: 'trunc',
};
};
function prettyBytes(number, options) {
if (typeof number !== 'bigint' && !Number.isFinite(number)) {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}
options = {
bits: false,
binary: false,
space: true,
nonBreakingSpace: false,
...options,
};
const UNITS = options.bits
? (options.binary ? BIBIT_UNITS : BIT_UNITS)
: (options.binary ? BIBYTE_UNITS : BYTE_UNITS);
const separator = options.space ? (options.nonBreakingSpace ? '\u00A0' : ' ') : '';
// Handle signed zero case
const isZero = typeof number === 'number' ? number === 0 : number === 0n;
if (options.signed && isZero) {
const result = ` 0${separator}${UNITS[0]}`;
return applyFixedWidth(result, options.fixedWidth);
}
const isNegative = number < 0;
const prefix = isNegative ? '-' : (options.signed ? '+' : '');
if (isNegative) {
number = -number;
}
const localeOptions = buildLocaleOptions(options);
let result;
if (number < 1) {
const numberString = toLocaleString(number, options.locale, localeOptions);
result = prefix + numberString + separator + UNITS[0];
} else {
const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1);
number = divide(number, (options.binary ? 1024 : 1000) ** exponent);
if (!localeOptions) {
const minPrecision = Math.max(3, Math.floor(number).toString().length);
number = number.toPrecision(minPrecision);
}
const numberString = toLocaleString(Number(number), options.locale, localeOptions);
const unit = UNITS[exponent];
result = prefix + numberString + separator + unit;
}
return applyFixedWidth(result, options.fixedWidth);
}
async function generateFSTree(dir, options = {}) {
if (isTest) {
return;
}
const files = await glob("**/*.*", { cwd: dir, ignore: ["*.map"] });
const items = [];
await runParallel(
new Set(files),
async (file) => {
const path = resolve(dir, file);
const src = await promises.readFile(path);
const size = src.byteLength;
const gzip = options.compressedSizes ? await gzipSize(src) : 0;
items.push({ file, path, size, gzip });
},
{ concurrency: 10 }
);
items.sort((a, b) => a.path.localeCompare(b.path));
let totalSize = 0;
let totalGzip = 0;
let totalNodeModulesSize = 0;
let totalNodeModulesGzip = 0;
let treeText = "";
for (const [index, item] of items.entries()) {
dirname(item.file);
const rpath = relative(process.cwd(), item.path);
const treeChar = index === items.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
const isNodeModules = item.file.includes("node_modules");
if (isNodeModules) {
totalNodeModulesSize += item.size;
totalNodeModulesGzip += item.gzip;
continue;
}
treeText += colors.gray(
` ${treeChar} ${rpath} (${prettyBytes(item.size)})`
);
if (options.compressedSizes) {
treeText += colors.gray(` (${prettyBytes(item.gzip)} gzip)`);
}
treeText += "\n";
totalSize += item.size;
totalGzip += item.gzip;
}
treeText += `${colors.cyan("\u03A3 Total size:")} ${prettyBytes(
totalSize + totalNodeModulesSize
)}`;
if (options.compressedSizes) {
treeText += ` (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)`;
}
treeText += "\n";
return treeText;
}
async function snapshot(nitro) {
if (nitro.options.bundledStorage.length === 0 || nitro.options.preset === "nitro-prerender") {
return;
}
const storageDir = resolve(nitro.options.buildDir, "snapshot");
nitro.options.serverAssets.push({
baseName: "nitro:bundled",
dir: storageDir
});
const data = await snapshotStorage(nitro);
await Promise.all(
Object.entries(data).map(async ([path, contents]) => {
if (typeof contents !== "string") {
contents = JSON.stringify(contents);
}
const fsPath = join(storageDir, path.replace(/:/g, "/"));
await mkdir(dirname(fsPath), { recursive: true });
await writeFile(fsPath, contents, "utf8");
})
);
}
export { generateFSTree as g, nitroServerName as n, snapshot as s };
import { N } from './index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function v(e,n){let t=e.slice(0,n).split(/\r\n|\n|\r/g);return [t.length,t.pop().length+1]}function C(e,n,t){let l=e.split(/\r\n|\n|\r/g),r="",i=(Math.log10(n+1)|0)+1;for(let o=n-1;o<=n+1;o++){let f=l[o-1];f&&(r+=o.toString().padEnd(i," "),r+=": ",r+=f,r+=`
`,o===n&&(r+=" ".repeat(i+t+2),r+=`^
`));}return r}class c extends Error{line;column;codeblock;constructor(n,t){const[l,r]=v(t.toml,t.ptr),i=C(t.toml,l,r);super(`Invalid TOML document: ${n}
${i}`,t),this.line=l,this.column=r,this.codeblock=i;}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function g(e,n=0,t=e.length){let l=e.indexOf(`
`,n);return e[l-1]==="\r"&&l--,l<=t?l:-1}function y(e,n){for(let t=n;t<e.length;t++){let l=e[t];if(l===`
`)return t;if(l==="\r"&&e[t+1]===`
`)return t+1;if(l<" "&&l!==" "||l==="\x7F")throw new c("control characters are not allowed in comments",{toml:e,ptr:n})}return e.length}function s(e,n,t,l){let r;for(;(r=e[n])===" "||r===" "||!t&&(r===`
`||r==="\r"&&e[n+1]===`
`);)n++;return l||r!=="#"?n:s(e,y(e,n),t)}function A(e,n,t,l,r=false){if(!l)return n=g(e,n),n<0?e.length:n;for(let i=n;i<e.length;i++){let o=e[i];if(o==="#")i=g(e,i);else {if(o===t)return i+1;if(o===l)return i;if(r&&(o===`
`||o==="\r"&&e[i+1]===`
`))return i}}throw new c("cannot find end of structure",{toml:e,ptr:n})}function S(e,n){let t=e[n],l=t===e[n+1]&&e[n+1]===e[n+2]?e.slice(n,n+3):t;n+=l.length-1;do n=e.indexOf(l,++n);while(n>-1&&t!=="'"&&e[n-1]==="\\"&&e[n-2]!=="\\");return n>-1&&(n+=l.length,l.length>1&&(e[n]===t&&n++,e[n]===t&&n++)),n}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/let R=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;class w extends Date{#n=false;#t=false;#e=null;constructor(n){let t=true,l=true,r="Z";if(typeof n=="string"){let i=n.match(R);i?(i[1]||(t=false,n=`0000-01-01T${n}`),l=!!i[2],i[2]&&+i[2]>23?n="":(r=i[3]||null,n=n.toUpperCase(),!r&&l&&(n+="Z"))):n="";}super(n),isNaN(this.getTime())||(this.#n=t,this.#t=l,this.#e=r);}isDateTime(){return this.#n&&this.#t}isLocal(){return !this.#n||!this.#t||!this.#e}isDate(){return this.#n&&!this.#t}isTime(){return this.#t&&!this.#n}isValid(){return this.#n||this.#t}toISOString(){let n=super.toISOString();if(this.isDate())return n.slice(0,10);if(this.isTime())return n.slice(11,23);if(this.#e===null)return n.slice(0,-1);if(this.#e==="Z")return n;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(n,t="Z"){let l=new w(n);return l.#e=t,l}static wrapAsLocalDateTime(n){let t=new w(n);return t.#e=null,t}static wrapAsLocalDate(n){let t=new w(n);return t.#t=false,t.#e=null,t}static wrapAsLocalTime(n){let t=new w(n);return t.#n=false,t.#e=null,t}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/let M=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Z=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,j=/^[+-]?0[0-9_]/,z=/^[0-9a-f]{4,8}$/i,I={b:"\b",t:" ",n:`
`,f:"\f",r:"\r",'"':'"',"\\":"\\"};function $(e,n=0,t=e.length){let l=e[n]==="'",r=e[n++]===e[n]&&e[n]===e[n+1];r&&(t-=2,e[n+=2]==="\r"&&n++,e[n]===`
`&&n++);let i=0,o,f="",a=n;for(;n<t-1;){let u=e[n++];if(u===`
`||u==="\r"&&e[n]===`
`){if(!r)throw new c("newlines are not allowed in strings",{toml:e,ptr:n-1})}else if(u<" "&&u!==" "||u==="\x7F")throw new c("control characters are not allowed in strings",{toml:e,ptr:n-1});if(o){if(o=false,u==="u"||u==="U"){let d=e.slice(n,n+=u==="u"?4:8);if(!z.test(d))throw new c("invalid unicode escape",{toml:e,ptr:i});try{f+=String.fromCodePoint(parseInt(d,16));}catch{throw new c("invalid unicode escape",{toml:e,ptr:i})}}else if(r&&(u===`
`||u===" "||u===" "||u==="\r")){if(n=s(e,n-1,true),e[n]!==`
`&&e[n]!=="\r")throw new c("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});n=s(e,n);}else if(u in I)f+=I[u];else throw new c("unrecognized escape sequence",{toml:e,ptr:i});a=n;}else !l&&u==="\\"&&(i=n-1,o=true,f+=e.slice(a,i));}return f+e.slice(a,t-1)}function F(e,n,t){if(e==="true")return true;if(e==="false")return false;if(e==="-inf")return -1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return 0;let l;if((l=M.test(e))||Z.test(e)){if(j.test(e))throw new c("leading zeroes are not allowed",{toml:n,ptr:t});let i=+e.replace(/_/g,"");if(isNaN(i))throw new c("invalid number",{toml:n,ptr:t});if(l&&!Number.isSafeInteger(i))throw new c("integer value cannot be represented losslessly",{toml:n,ptr:t});return i}let r=new w(e);if(!r.isValid())throw new c("invalid value",{toml:n,ptr:t});return r}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function V(e,n,t,l){let r=e.slice(n,t),i=r.indexOf("#");i>-1&&(y(e,i),r=r.slice(0,i));let o=r.trimEnd();if(!l){let f=r.indexOf(`
`,o.length);if(f>-1)throw new c("newlines are not allowed in inline tables",{toml:e,ptr:n+f})}return [o,i]}function b(e,n,t,l){if(l===0)throw new c("document contains excessively nested structures. aborting.",{toml:e,ptr:n});let r=e[n];if(r==="["||r==="{"){let[f,a]=r==="["?U(e,n,l):K(e,n,l),u=A(e,a,",",t);if(t==="}"){let d=g(e,a,u);if(d>-1)throw new c("newlines are not allowed in inline tables",{toml:e,ptr:d})}return [f,u]}let i;if(r==='"'||r==="'"){i=S(e,n);let f=$(e,n,i);if(t){if(i=s(e,i,t!=="]"),e[i]&&e[i]!==","&&e[i]!==t&&e[i]!==`
`&&e[i]!=="\r")throw new c("unexpected character encountered",{toml:e,ptr:i});i+=+(e[i]===",");}return [f,i]}i=A(e,n,",",t);let o=V(e,n,i-+(e[i-1]===","),t==="]");if(!o[0])throw new c("incomplete key-value declaration: no value specified",{toml:e,ptr:n});return t&&o[1]>-1&&(i=s(e,n+o[1]),i+=+(e[i]===",")),[F(o[0],e,n),i]}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/let G=/^[a-zA-Z0-9-_]+[ \t]*$/;function x(e,n,t="="){let l=n-1,r=[],i=e.indexOf(t,n);if(i<0)throw new c("incomplete key-value: cannot find end of key",{toml:e,ptr:n});do{let o=e[n=++l];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[n+1]&&o===e[n+2])throw new c("multiline strings are not allowed in keys",{toml:e,ptr:n});let f=S(e,n);if(f<0)throw new c("unfinished string encountered",{toml:e,ptr:n});l=e.indexOf(".",f);let a=e.slice(f,l<0||l>i?i:l),u=g(a);if(u>-1)throw new c("newlines are not allowed in keys",{toml:e,ptr:n+l+u});if(a.trimStart())throw new c("found extra tokens after the string part",{toml:e,ptr:f});if(i<f&&(i=e.indexOf(t,f),i<0))throw new c("incomplete key-value: cannot find end of key",{toml:e,ptr:n});r.push($(e,n,f));}else {l=e.indexOf(".",n);let f=e.slice(n,l<0||l>i?i:l);if(!G.test(f))throw new c("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:n});r.push(f.trimEnd());}}while(l+1&&l<i);return [r,s(e,i+1,true,true)]}function K(e,n,t){let l={},r=new Set,i,o=0;for(n++;(i=e[n++])!=="}"&&i;){if(i===`
`)throw new c("newlines are not allowed in inline tables",{toml:e,ptr:n-1});if(i==="#")throw new c("inline tables cannot contain comments",{toml:e,ptr:n-1});if(i===",")throw new c("expected key-value, found comma",{toml:e,ptr:n-1});if(i!==" "&&i!==" "){let f,a=l,u=false,[d,N]=x(e,n-1);for(let m=0;m<d.length;m++){if(m&&(a=u?a[f]:a[f]={}),f=d[m],(u=Object.hasOwn(a,f))&&(typeof a[f]!="object"||r.has(a[f])))throw new c("trying to redefine an already defined value",{toml:e,ptr:n});!u&&f==="__proto__"&&Object.defineProperty(a,f,{enumerable:true,configurable:true,writable:true});}if(u)throw new c("trying to redefine an already defined value",{toml:e,ptr:n});let[_,k]=b(e,N,"}",t-1);r.add(_),a[f]=_,n=k,o=e[n-1]===","?n-1:0;}}if(o)throw new c("trailing commas are not allowed in inline tables",{toml:e,ptr:o});if(!i)throw new c("unfinished table encountered",{toml:e,ptr:n});return [l,n]}function U(e,n,t){let l=[],r;for(n++;(r=e[n++])!=="]"&&r;){if(r===",")throw new c("expected value, found comma",{toml:e,ptr:n-1});if(r==="#")n=y(e,n);else if(r!==" "&&r!==" "&&r!==`
`&&r!=="\r"){let i=b(e,n-1,"]",t-1);l.push(i[0]),n=i[1];}}if(!r)throw new c("unfinished array encountered",{toml:e,ptr:n});return [l,n]}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function p(e,n,t,l){let r=n,i=t,o,f=false,a;for(let u=0;u<e.length;u++){if(u){if(r=f?r[o]:r[o]={},i=(a=i[o]).c,l===0&&(a.t===1||a.t===2))return null;if(a.t===2){let d=r.length-1;r=r[d],i=i[d].c;}}if(o=e[u],(f=Object.hasOwn(r,o))&&i[o]?.t===0&&i[o]?.d)return null;f||(o==="__proto__"&&(Object.defineProperty(r,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:u<e.length-1&&l===2?3:l,d:false,i:0,c:{}});}if(a=i[o],a.t!==l&&!(l===1&&a.t===3)||(l===2&&(a.d||(a.d=true,r[o]=[]),r[o].push(r={}),a.c[a.i++]=a={t:1,d:false,i:0,c:{}}),a.d))return null;if(a.d=true,l===1)r=f?r[o]:r[o]={};else if(l===0&&f)return null;return [o,r,a.c]}function X(e,n){let t=1e3,l={},r={},i=l,o=r;for(let f=s(e,0);f<e.length;){if(e[f]==="["){let a=e[++f]==="[",u=x(e,f+=+a,"]");if(a){if(e[u[1]-1]!=="]")throw new c("expected end of table declaration",{toml:e,ptr:u[1]-1});u[1]++;}let d=p(u[0],l,r,a?2:1);if(!d)throw new c("trying to redefine an already defined table or value",{toml:e,ptr:f});o=d[2],i=d[1],f=u[1];}else {let a=x(e,f),u=p(a[0],i,o,0);if(!u)throw new c("trying to redefine an already defined table or value",{toml:e,ptr:f});let d=b(e,a[1],void 0,t);u[1][u[0]]=d[0],f=d[1];}if(f=s(e,f,true),e[f]&&e[f]!==`
`&&e[f]!=="\r")throw new c("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:f});f=s(e,f);}return l}function Q(e){const n=X(e);return N(e,n,{preserveIndentation:false}),n}
export { Q as parseTOML };
import { C as C$1, N as N$1 } from './index.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */function oe(e){return typeof e>"u"||e===null}function Ge(e){return typeof e=="object"&&e!==null}function We(e){return Array.isArray(e)?e:oe(e)?[]:[e]}function $e(e,n){var i,l,r,u;if(n)for(u=Object.keys(n),i=0,l=u.length;i<l;i+=1)r=u[i],e[r]=n[r];return e}function Qe(e,n){var i="",l;for(l=0;l<n;l+=1)i+=e;return i}function Ve(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Xe=oe,Ze=Ge,ze=We,Je=Qe,en=Ve,nn=$e,y={isNothing:Xe,isObject:Ze,toArray:ze,repeat:Je,isNegativeZero:en,extend:nn};function ue(e,n){var i="",l=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(i+='in "'+e.mark.name+'" '),i+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!n&&e.mark.snippet&&(i+=`
`+e.mark.snippet),l+" "+i):l}function M(e,n){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=n,this.message=ue(this,false),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||"";}M.prototype=Object.create(Error.prototype),M.prototype.constructor=M,M.prototype.toString=function(n){return this.name+": "+ue(this,n)};var w=M;function $(e,n,i,l,r){var u="",o="",f=Math.floor(r/2)-1;return l-n>f&&(u=" ... ",n=l-f+u.length),i-l>f&&(o=" ...",i=l+f-o.length),{str:u+e.slice(n,i).replace(/\t/g,"\u2192")+o,pos:l-n+u.length}}function Q(e,n){return y.repeat(" ",n-e.length)+e}function rn(e,n){if(n=Object.create(n||null),!e.buffer)return null;n.maxLength||(n.maxLength=79),typeof n.indent!="number"&&(n.indent=1),typeof n.linesBefore!="number"&&(n.linesBefore=3),typeof n.linesAfter!="number"&&(n.linesAfter=2);for(var i=/\r?\n|\r|\0/g,l=[0],r=[],u,o=-1;u=i.exec(e.buffer);)r.push(u.index),l.push(u.index+u[0].length),e.position<=u.index&&o<0&&(o=l.length-2);o<0&&(o=l.length-1);var f="",c,a,t=Math.min(e.line+n.linesAfter,r.length).toString().length,p=n.maxLength-(n.indent+t+3);for(c=1;c<=n.linesBefore&&!(o-c<0);c++)a=$(e.buffer,l[o-c],r[o-c],e.position-(l[o]-l[o-c]),p),f=y.repeat(" ",n.indent)+Q((e.line-c+1).toString(),t)+" | "+a.str+`
`+f;for(a=$(e.buffer,l[o],r[o],e.position,p),f+=y.repeat(" ",n.indent)+Q((e.line+1).toString(),t)+" | "+a.str+`
`,f+=y.repeat("-",n.indent+t+3+a.pos)+`^
`,c=1;c<=n.linesAfter&&!(o+c>=r.length);c++)a=$(e.buffer,l[o+c],r[o+c],e.position-(l[o]-l[o+c]),p),f+=y.repeat(" ",n.indent)+Q((e.line+c+1).toString(),t)+" | "+a.str+`
`;return f.replace(/\n$/,"")}var ln=rn,on=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],un=["scalar","sequence","mapping"];function fn(e){var n={};return e!==null&&Object.keys(e).forEach(function(i){e[i].forEach(function(l){n[String(l)]=i;});}),n}function cn(e,n){if(n=n||{},Object.keys(n).forEach(function(i){if(on.indexOf(i)===-1)throw new w('Unknown option "'+i+'" is met in definition of "'+e+'" YAML type.')}),this.options=n,this.tag=e,this.kind=n.kind||null,this.resolve=n.resolve||function(){return true},this.construct=n.construct||function(i){return i},this.instanceOf=n.instanceOf||null,this.predicate=n.predicate||null,this.represent=n.represent||null,this.representName=n.representName||null,this.defaultStyle=n.defaultStyle||null,this.multi=n.multi||false,this.styleAliases=fn(n.styleAliases||null),un.indexOf(this.kind)===-1)throw new w('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}var C=cn;function fe(e,n){var i=[];return e[n].forEach(function(l){var r=i.length;i.forEach(function(u,o){u.tag===l.tag&&u.kind===l.kind&&u.multi===l.multi&&(r=o);}),i[r]=l;}),i}function an(){var e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},n,i;function l(r){r.multi?(e.multi[r.kind].push(r),e.multi.fallback.push(r)):e[r.kind][r.tag]=e.fallback[r.tag]=r;}for(n=0,i=arguments.length;n<i;n+=1)arguments[n].forEach(l);return e}function V(e){return this.extend(e)}V.prototype.extend=function(n){var i=[],l=[];if(n instanceof C)l.push(n);else if(Array.isArray(n))l=l.concat(n);else if(n&&(Array.isArray(n.implicit)||Array.isArray(n.explicit)))n.implicit&&(i=i.concat(n.implicit)),n.explicit&&(l=l.concat(n.explicit));else throw new w("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");i.forEach(function(u){if(!(u instanceof C))throw new w("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(u.loadKind&&u.loadKind!=="scalar")throw new w("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(u.multi)throw new w("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),l.forEach(function(u){if(!(u instanceof C))throw new w("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var r=Object.create(V.prototype);return r.implicit=(this.implicit||[]).concat(i),r.explicit=(this.explicit||[]).concat(l),r.compiledImplicit=fe(r,"implicit"),r.compiledExplicit=fe(r,"explicit"),r.compiledTypeMap=an(r.compiledImplicit,r.compiledExplicit),r};var pn=V,tn=new C("tag:yaml.org,2002:str",{kind:"scalar",construct:function(e){return e!==null?e:""}}),hn=new C("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return e!==null?e:[]}}),dn=new C("tag:yaml.org,2002:map",{kind:"mapping",construct:function(e){return e!==null?e:{}}}),sn=new pn({explicit:[tn,hn,dn]});function xn(e){if(e===null)return true;var n=e.length;return n===1&&e==="~"||n===4&&(e==="null"||e==="Null"||e==="NULL")}function mn(){return null}function gn(e){return e===null}var An=new C("tag:yaml.org,2002:null",{kind:"scalar",resolve:xn,construct:mn,predicate:gn,represent:{canonical:function(){return "~"},lowercase:function(){return "null"},uppercase:function(){return "NULL"},camelcase:function(){return "Null"},empty:function(){return ""}},defaultStyle:"lowercase"});function vn(e){if(e===null)return false;var n=e.length;return n===4&&(e==="true"||e==="True"||e==="TRUE")||n===5&&(e==="false"||e==="False"||e==="FALSE")}function yn(e){return e==="true"||e==="True"||e==="TRUE"}function Cn(e){return Object.prototype.toString.call(e)==="[object Boolean]"}var _n=new C("tag:yaml.org,2002:bool",{kind:"scalar",resolve:vn,construct:yn,predicate:Cn,represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"});function wn(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function Fn(e){return 48<=e&&e<=55}function bn(e){return 48<=e&&e<=57}function Sn(e){if(e===null)return false;var n=e.length,i=0,l=false,r;if(!n)return false;if(r=e[i],(r==="-"||r==="+")&&(r=e[++i]),r==="0"){if(i+1===n)return true;if(r=e[++i],r==="b"){for(i++;i<n;i++)if(r=e[i],r!=="_"){if(r!=="0"&&r!=="1")return false;l=true;}return l&&r!=="_"}if(r==="x"){for(i++;i<n;i++)if(r=e[i],r!=="_"){if(!wn(e.charCodeAt(i)))return false;l=true;}return l&&r!=="_"}if(r==="o"){for(i++;i<n;i++)if(r=e[i],r!=="_"){if(!Fn(e.charCodeAt(i)))return false;l=true;}return l&&r!=="_"}}if(r==="_")return false;for(;i<n;i++)if(r=e[i],r!=="_"){if(!bn(e.charCodeAt(i)))return false;l=true;}return !(!l||r==="_")}function En(e){var n=e,i=1,l;if(n.indexOf("_")!==-1&&(n=n.replace(/_/g,"")),l=n[0],(l==="-"||l==="+")&&(l==="-"&&(i=-1),n=n.slice(1),l=n[0]),n==="0")return 0;if(l==="0"){if(n[1]==="b")return i*parseInt(n.slice(2),2);if(n[1]==="x")return i*parseInt(n.slice(2),16);if(n[1]==="o")return i*parseInt(n.slice(2),8)}return i*parseInt(n,10)}function Tn(e){return Object.prototype.toString.call(e)==="[object Number]"&&e%1===0&&!y.isNegativeZero(e)}var On=new C("tag:yaml.org,2002:int",{kind:"scalar",resolve:Sn,construct:En,predicate:Tn,represent:{binary:function(e){return e>=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),In=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function kn(e){return !(e===null||!In.test(e)||e[e.length-1]==="_")}function Ln(e){var n,i;return n=e.replace(/_/g,"").toLowerCase(),i=n[0]==="-"?-1:1,"+-".indexOf(n[0])>=0&&(n=n.slice(1)),n===".inf"?i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:n===".nan"?NaN:i*parseFloat(n,10)}var Nn=/^[-+]?[0-9]+e/;function Rn(e,n){var i;if(isNaN(e))switch(n){case "lowercase":return ".nan";case "uppercase":return ".NAN";case "camelcase":return ".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(n){case "lowercase":return ".inf";case "uppercase":return ".INF";case "camelcase":return ".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(n){case "lowercase":return "-.inf";case "uppercase":return "-.INF";case "camelcase":return "-.Inf"}else if(y.isNegativeZero(e))return "-0.0";return i=e.toString(10),Nn.test(i)?i.replace("e",".e"):i}function Dn(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||y.isNegativeZero(e))}var Mn=new C("tag:yaml.org,2002:float",{kind:"scalar",resolve:kn,construct:Ln,predicate:Dn,represent:Rn,defaultStyle:"lowercase"}),Yn=sn.extend({implicit:[An,_n,On,Mn]}),Bn=Yn,ce=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),ae=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function Pn(e){return e===null?false:ce.exec(e)!==null||ae.exec(e)!==null}function jn(e){var n,i,l,r,u,o,f,c=0,a=null,t,p,d;if(n=ce.exec(e),n===null&&(n=ae.exec(e)),n===null)throw new Error("Date resolve error");if(i=+n[1],l=+n[2]-1,r=+n[3],!n[4])return new Date(Date.UTC(i,l,r));if(u=+n[4],o=+n[5],f=+n[6],n[7]){for(c=n[7].slice(0,3);c.length<3;)c+="0";c=+c;}return n[9]&&(t=+n[10],p=+(n[11]||0),a=(t*60+p)*6e4,n[9]==="-"&&(a=-a)),d=new Date(Date.UTC(i,l,r,u,o,f,c)),a&&d.setTime(d.getTime()-a),d}function Hn(e){return e.toISOString()}var Un=new C("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:Pn,construct:jn,instanceOf:Date,represent:Hn});function Kn(e){return e==="<<"||e===null}var qn=new C("tag:yaml.org,2002:merge",{kind:"scalar",resolve:Kn}),X=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
\r`;function Gn(e){if(e===null)return false;var n,i,l=0,r=e.length,u=X;for(i=0;i<r;i++)if(n=u.indexOf(e.charAt(i)),!(n>64)){if(n<0)return false;l+=6;}return l%8===0}function Wn(e){var n,i,l=e.replace(/[\r\n=]/g,""),r=l.length,u=X,o=0,f=[];for(n=0;n<r;n++)n%4===0&&n&&(f.push(o>>16&255),f.push(o>>8&255),f.push(o&255)),o=o<<6|u.indexOf(l.charAt(n));return i=r%4*6,i===0?(f.push(o>>16&255),f.push(o>>8&255),f.push(o&255)):i===18?(f.push(o>>10&255),f.push(o>>2&255)):i===12&&f.push(o>>4&255),new Uint8Array(f)}function $n(e){var n="",i=0,l,r,u=e.length,o=X;for(l=0;l<u;l++)l%3===0&&l&&(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[i&63]),i=(i<<8)+e[l];return r=u%3,r===0?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[i&63]):r===2?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):r===1&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}function Qn(e){return Object.prototype.toString.call(e)==="[object Uint8Array]"}var Vn=new C("tag:yaml.org,2002:binary",{kind:"scalar",resolve:Gn,construct:Wn,predicate:Qn,represent:$n}),Xn=Object.prototype.hasOwnProperty,Zn=Object.prototype.toString;function zn(e){if(e===null)return true;var n=[],i,l,r,u,o,f=e;for(i=0,l=f.length;i<l;i+=1){if(r=f[i],o=false,Zn.call(r)!=="[object Object]")return false;for(u in r)if(Xn.call(r,u))if(!o)o=true;else return false;if(!o)return false;if(n.indexOf(u)===-1)n.push(u);else return false}return true}function Jn(e){return e!==null?e:[]}var ei=new C("tag:yaml.org,2002:omap",{kind:"sequence",resolve:zn,construct:Jn}),ni=Object.prototype.toString;function ii(e){if(e===null)return true;var n,i,l,r,u,o=e;for(u=new Array(o.length),n=0,i=o.length;n<i;n+=1){if(l=o[n],ni.call(l)!=="[object Object]"||(r=Object.keys(l),r.length!==1))return false;u[n]=[r[0],l[r[0]]];}return true}function ri(e){if(e===null)return [];var n,i,l,r,u,o=e;for(u=new Array(o.length),n=0,i=o.length;n<i;n+=1)l=o[n],r=Object.keys(l),u[n]=[r[0],l[r[0]]];return u}var li=new C("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:ii,construct:ri}),oi=Object.prototype.hasOwnProperty;function ui(e){if(e===null)return true;var n,i=e;for(n in i)if(oi.call(i,n)&&i[n]!==null)return false;return true}function fi(e){return e!==null?e:{}}var ci=new C("tag:yaml.org,2002:set",{kind:"mapping",resolve:ui,construct:fi}),pe=Bn.extend({implicit:[Un,qn],explicit:[Vn,ei,li,ci]}),T=Object.prototype.hasOwnProperty,H=1,te=2,he=3,U=4,Z=1,ai=2,de=3,pi=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,ti=/[\x85\u2028\u2029]/,hi=/[,\[\]\{\}]/,se=/^(?:!|!!|![a-z\-]+!)$/i,xe=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function me(e){return Object.prototype.toString.call(e)}function S(e){return e===10||e===13}function I(e){return e===9||e===32}function F(e){return e===9||e===32||e===10||e===13}function k(e){return e===44||e===91||e===93||e===123||e===125}function di(e){var n;return 48<=e&&e<=57?e-48:(n=e|32,97<=n&&n<=102?n-97+10:-1)}function si(e){return e===120?2:e===117?4:e===85?8:0}function xi(e){return 48<=e&&e<=57?e-48:-1}function ge(e){return e===48?"\0":e===97?"\x07":e===98?"\b":e===116||e===9?" ":e===110?`
`:e===118?"\v":e===102?"\f":e===114?"\r":e===101?"\x1B":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"\x85":e===95?"\xA0":e===76?"\u2028":e===80?"\u2029":""}function mi(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}for(var Ae=new Array(256),ve=new Array(256),L=0;L<256;L++)Ae[L]=ge(L)?1:0,ve[L]=ge(L);function gi(e,n){this.input=e,this.filename=n.filename||null,this.schema=n.schema||pe,this.onWarning=n.onWarning||null,this.legacy=n.legacy||false,this.json=n.json||false,this.listener=n.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[];}function ye(e,n){var i={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return i.snippet=ln(i),new w(n,i)}function h(e,n){throw ye(e,n)}function K(e,n){e.onWarning&&e.onWarning.call(null,ye(e,n));}var Ce={YAML:function(n,i,l){var r,u,o;n.version!==null&&h(n,"duplication of %YAML directive"),l.length!==1&&h(n,"YAML directive accepts exactly one argument"),r=/^([0-9]+)\.([0-9]+)$/.exec(l[0]),r===null&&h(n,"ill-formed argument of the YAML directive"),u=parseInt(r[1],10),o=parseInt(r[2],10),u!==1&&h(n,"unacceptable YAML version of the document"),n.version=l[0],n.checkLineBreaks=o<2,o!==1&&o!==2&&K(n,"unsupported YAML version of the document");},TAG:function(n,i,l){var r,u;l.length!==2&&h(n,"TAG directive accepts exactly two arguments"),r=l[0],u=l[1],se.test(r)||h(n,"ill-formed tag handle (first argument) of the TAG directive"),T.call(n.tagMap,r)&&h(n,'there is a previously declared suffix for "'+r+'" tag handle'),xe.test(u)||h(n,"ill-formed tag prefix (second argument) of the TAG directive");try{u=decodeURIComponent(u);}catch{h(n,"tag prefix is malformed: "+u);}n.tagMap[r]=u;}};function O(e,n,i,l){var r,u,o,f;if(n<i){if(f=e.input.slice(n,i),l)for(r=0,u=f.length;r<u;r+=1)o=f.charCodeAt(r),o===9||32<=o&&o<=1114111||h(e,"expected valid JSON character");else pi.test(f)&&h(e,"the stream contains non-printable characters");e.result+=f;}}function _e(e,n,i,l){var r,u,o,f;for(y.isObject(i)||h(e,"cannot merge mappings; the provided source object is unacceptable"),r=Object.keys(i),o=0,f=r.length;o<f;o+=1)u=r[o],T.call(n,u)||(n[u]=i[u],l[u]=true);}function N(e,n,i,l,r,u,o,f,c){var a,t;if(Array.isArray(r))for(r=Array.prototype.slice.call(r),a=0,t=r.length;a<t;a+=1)Array.isArray(r[a])&&h(e,"nested arrays are not supported inside keys"),typeof r=="object"&&me(r[a])==="[object Object]"&&(r[a]="[object Object]");if(typeof r=="object"&&me(r)==="[object Object]"&&(r="[object Object]"),r=String(r),n===null&&(n={}),l==="tag:yaml.org,2002:merge")if(Array.isArray(u))for(a=0,t=u.length;a<t;a+=1)_e(e,n,u[a],i);else _e(e,n,u,i);else !e.json&&!T.call(i,r)&&T.call(n,r)&&(e.line=o||e.line,e.lineStart=f||e.lineStart,e.position=c||e.position,h(e,"duplicated mapping key")),r==="__proto__"?Object.defineProperty(n,r,{configurable:true,enumerable:true,writable:true,value:u}):n[r]=u,delete i[r];return n}function z(e){var n;n=e.input.charCodeAt(e.position),n===10?e.position++:n===13?(e.position++,e.input.charCodeAt(e.position)===10&&e.position++):h(e,"a line break is expected"),e.line+=1,e.lineStart=e.position,e.firstTabInLine=-1;}function v(e,n,i){for(var l=0,r=e.input.charCodeAt(e.position);r!==0;){for(;I(r);)r===9&&e.firstTabInLine===-1&&(e.firstTabInLine=e.position),r=e.input.charCodeAt(++e.position);if(n&&r===35)do r=e.input.charCodeAt(++e.position);while(r!==10&&r!==13&&r!==0);if(S(r))for(z(e),r=e.input.charCodeAt(e.position),l++,e.lineIndent=0;r===32;)e.lineIndent++,r=e.input.charCodeAt(++e.position);else break}return i!==-1&&l!==0&&e.lineIndent<i&&K(e,"deficient indentation"),l}function q(e){var n=e.position,i;return i=e.input.charCodeAt(n),!!((i===45||i===46)&&i===e.input.charCodeAt(n+1)&&i===e.input.charCodeAt(n+2)&&(n+=3,i=e.input.charCodeAt(n),i===0||F(i)))}function J(e,n){n===1?e.result+=" ":n>1&&(e.result+=y.repeat(`
`,n-1));}function Ai(e,n,i){var l,r,u,o,f,c,a,t,p=e.kind,d=e.result,s;if(s=e.input.charCodeAt(e.position),F(s)||k(s)||s===35||s===38||s===42||s===33||s===124||s===62||s===39||s===34||s===37||s===64||s===96||(s===63||s===45)&&(r=e.input.charCodeAt(e.position+1),F(r)||i&&k(r)))return false;for(e.kind="scalar",e.result="",u=o=e.position,f=false;s!==0;){if(s===58){if(r=e.input.charCodeAt(e.position+1),F(r)||i&&k(r))break}else if(s===35){if(l=e.input.charCodeAt(e.position-1),F(l))break}else {if(e.position===e.lineStart&&q(e)||i&&k(s))break;if(S(s))if(c=e.line,a=e.lineStart,t=e.lineIndent,v(e,false,-1),e.lineIndent>=n){f=true,s=e.input.charCodeAt(e.position);continue}else {e.position=o,e.line=c,e.lineStart=a,e.lineIndent=t;break}}f&&(O(e,u,o,false),J(e,e.line-c),u=o=e.position,f=false),I(s)||(o=e.position+1),s=e.input.charCodeAt(++e.position);}return O(e,u,o,false),e.result?true:(e.kind=p,e.result=d,false)}function vi(e,n){var i,l,r;if(i=e.input.charCodeAt(e.position),i!==39)return false;for(e.kind="scalar",e.result="",e.position++,l=r=e.position;(i=e.input.charCodeAt(e.position))!==0;)if(i===39)if(O(e,l,e.position,true),i=e.input.charCodeAt(++e.position),i===39)l=e.position,e.position++,r=e.position;else return true;else S(i)?(O(e,l,r,true),J(e,v(e,false,n)),l=r=e.position):e.position===e.lineStart&&q(e)?h(e,"unexpected end of the document within a single quoted scalar"):(e.position++,r=e.position);h(e,"unexpected end of the stream within a single quoted scalar");}function yi(e,n){var i,l,r,u,o,f;if(f=e.input.charCodeAt(e.position),f!==34)return false;for(e.kind="scalar",e.result="",e.position++,i=l=e.position;(f=e.input.charCodeAt(e.position))!==0;){if(f===34)return O(e,i,e.position,true),e.position++,true;if(f===92){if(O(e,i,e.position,true),f=e.input.charCodeAt(++e.position),S(f))v(e,false,n);else if(f<256&&Ae[f])e.result+=ve[f],e.position++;else if((o=si(f))>0){for(r=o,u=0;r>0;r--)f=e.input.charCodeAt(++e.position),(o=di(f))>=0?u=(u<<4)+o:h(e,"expected hexadecimal character");e.result+=mi(u),e.position++;}else h(e,"unknown escape sequence");i=l=e.position;}else S(f)?(O(e,i,l,true),J(e,v(e,false,n)),i=l=e.position):e.position===e.lineStart&&q(e)?h(e,"unexpected end of the document within a double quoted scalar"):(e.position++,l=e.position);}h(e,"unexpected end of the stream within a double quoted scalar");}function Ci(e,n){var i=true,l,r,u,o=e.tag,f,c=e.anchor,a,t,p,d,s,x=Object.create(null),g,A,b,m;if(m=e.input.charCodeAt(e.position),m===91)t=93,s=false,f=[];else if(m===123)t=125,s=true,f={};else return false;for(e.anchor!==null&&(e.anchorMap[e.anchor]=f),m=e.input.charCodeAt(++e.position);m!==0;){if(v(e,true,n),m=e.input.charCodeAt(e.position),m===t)return e.position++,e.tag=o,e.anchor=c,e.kind=s?"mapping":"sequence",e.result=f,true;i?m===44&&h(e,"expected the node content, but found ','"):h(e,"missed comma between flow collection entries"),A=g=b=null,p=d=false,m===63&&(a=e.input.charCodeAt(e.position+1),F(a)&&(p=d=true,e.position++,v(e,true,n))),l=e.line,r=e.lineStart,u=e.position,R(e,n,H,false,true),A=e.tag,g=e.result,v(e,true,n),m=e.input.charCodeAt(e.position),(d||e.line===l)&&m===58&&(p=true,m=e.input.charCodeAt(++e.position),v(e,true,n),R(e,n,H,false,true),b=e.result),s?N(e,f,x,A,g,b,l,r,u):p?f.push(N(e,null,x,A,g,b,l,r,u)):f.push(g),v(e,true,n),m=e.input.charCodeAt(e.position),m===44?(i=true,m=e.input.charCodeAt(++e.position)):i=false;}h(e,"unexpected end of the stream within a flow collection");}function _i(e,n){var i,l,r=Z,u=false,o=false,f=n,c=0,a=false,t,p;if(p=e.input.charCodeAt(e.position),p===124)l=false;else if(p===62)l=true;else return false;for(e.kind="scalar",e.result="";p!==0;)if(p=e.input.charCodeAt(++e.position),p===43||p===45)Z===r?r=p===43?de:ai:h(e,"repeat of a chomping mode identifier");else if((t=xi(p))>=0)t===0?h(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):o?h(e,"repeat of an indentation width identifier"):(f=n+t-1,o=true);else break;if(I(p)){do p=e.input.charCodeAt(++e.position);while(I(p));if(p===35)do p=e.input.charCodeAt(++e.position);while(!S(p)&&p!==0)}for(;p!==0;){for(z(e),e.lineIndent=0,p=e.input.charCodeAt(e.position);(!o||e.lineIndent<f)&&p===32;)e.lineIndent++,p=e.input.charCodeAt(++e.position);if(!o&&e.lineIndent>f&&(f=e.lineIndent),S(p)){c++;continue}if(e.lineIndent<f){r===de?e.result+=y.repeat(`
`,u?1+c:c):r===Z&&u&&(e.result+=`
`);break}for(l?I(p)?(a=true,e.result+=y.repeat(`
`,u?1+c:c)):a?(a=false,e.result+=y.repeat(`
`,c+1)):c===0?u&&(e.result+=" "):e.result+=y.repeat(`
`,c):e.result+=y.repeat(`
`,u?1+c:c),u=true,o=true,c=0,i=e.position;!S(p)&&p!==0;)p=e.input.charCodeAt(++e.position);O(e,i,e.position,false);}return true}function we(e,n){var i,l=e.tag,r=e.anchor,u=[],o,f=false,c;if(e.firstTabInLine!==-1)return false;for(e.anchor!==null&&(e.anchorMap[e.anchor]=u),c=e.input.charCodeAt(e.position);c!==0&&(e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,h(e,"tab characters must not be used in indentation")),!(c!==45||(o=e.input.charCodeAt(e.position+1),!F(o))));){if(f=true,e.position++,v(e,true,-1)&&e.lineIndent<=n){u.push(null),c=e.input.charCodeAt(e.position);continue}if(i=e.line,R(e,n,he,false,true),u.push(e.result),v(e,true,-1),c=e.input.charCodeAt(e.position),(e.line===i||e.lineIndent>n)&&c!==0)h(e,"bad indentation of a sequence entry");else if(e.lineIndent<n)break}return f?(e.tag=l,e.anchor=r,e.kind="sequence",e.result=u,true):false}function wi(e,n,i){var l,r,u,o,f,c,a=e.tag,t=e.anchor,p={},d=Object.create(null),s=null,x=null,g=null,A=false,b=false,m;if(e.firstTabInLine!==-1)return false;for(e.anchor!==null&&(e.anchorMap[e.anchor]=p),m=e.input.charCodeAt(e.position);m!==0;){if(!A&&e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,h(e,"tab characters must not be used in indentation")),l=e.input.charCodeAt(e.position+1),u=e.line,(m===63||m===58)&&F(l))m===63?(A&&(N(e,p,d,s,x,null,o,f,c),s=x=g=null),b=true,A=true,r=true):A?(A=false,r=true):h(e,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),e.position+=1,m=l;else {if(o=e.line,f=e.lineStart,c=e.position,!R(e,i,te,false,true))break;if(e.line===u){for(m=e.input.charCodeAt(e.position);I(m);)m=e.input.charCodeAt(++e.position);if(m===58)m=e.input.charCodeAt(++e.position),F(m)||h(e,"a whitespace character is expected after the key-value separator within a block mapping"),A&&(N(e,p,d,s,x,null,o,f,c),s=x=g=null),b=true,A=false,r=false,s=e.tag,x=e.result;else if(b)h(e,"can not read an implicit mapping pair; a colon is missed");else return e.tag=a,e.anchor=t,true}else if(b)h(e,"can not read a block mapping entry; a multiline key may not be an implicit key");else return e.tag=a,e.anchor=t,true}if((e.line===u||e.lineIndent>n)&&(A&&(o=e.line,f=e.lineStart,c=e.position),R(e,n,U,true,r)&&(A?x=e.result:g=e.result),A||(N(e,p,d,s,x,g,o,f,c),s=x=g=null),v(e,true,-1),m=e.input.charCodeAt(e.position)),(e.line===u||e.lineIndent>n)&&m!==0)h(e,"bad indentation of a mapping entry");else if(e.lineIndent<n)break}return A&&N(e,p,d,s,x,null,o,f,c),b&&(e.tag=a,e.anchor=t,e.kind="mapping",e.result=p),b}function Fi(e){var n,i=false,l=false,r,u,o;if(o=e.input.charCodeAt(e.position),o!==33)return false;if(e.tag!==null&&h(e,"duplication of a tag property"),o=e.input.charCodeAt(++e.position),o===60?(i=true,o=e.input.charCodeAt(++e.position)):o===33?(l=true,r="!!",o=e.input.charCodeAt(++e.position)):r="!",n=e.position,i){do o=e.input.charCodeAt(++e.position);while(o!==0&&o!==62);e.position<e.length?(u=e.input.slice(n,e.position),o=e.input.charCodeAt(++e.position)):h(e,"unexpected end of the stream within a verbatim tag");}else {for(;o!==0&&!F(o);)o===33&&(l?h(e,"tag suffix cannot contain exclamation marks"):(r=e.input.slice(n-1,e.position+1),se.test(r)||h(e,"named tag handle cannot contain such characters"),l=true,n=e.position+1)),o=e.input.charCodeAt(++e.position);u=e.input.slice(n,e.position),hi.test(u)&&h(e,"tag suffix cannot contain flow indicator characters");}u&&!xe.test(u)&&h(e,"tag name cannot contain such characters: "+u);try{u=decodeURIComponent(u);}catch{h(e,"tag name is malformed: "+u);}return i?e.tag=u:T.call(e.tagMap,r)?e.tag=e.tagMap[r]+u:r==="!"?e.tag="!"+u:r==="!!"?e.tag="tag:yaml.org,2002:"+u:h(e,'undeclared tag handle "'+r+'"'),true}function bi(e){var n,i;if(i=e.input.charCodeAt(e.position),i!==38)return false;for(e.anchor!==null&&h(e,"duplication of an anchor property"),i=e.input.charCodeAt(++e.position),n=e.position;i!==0&&!F(i)&&!k(i);)i=e.input.charCodeAt(++e.position);return e.position===n&&h(e,"name of an anchor node must contain at least one character"),e.anchor=e.input.slice(n,e.position),true}function Si(e){var n,i,l;if(l=e.input.charCodeAt(e.position),l!==42)return false;for(l=e.input.charCodeAt(++e.position),n=e.position;l!==0&&!F(l)&&!k(l);)l=e.input.charCodeAt(++e.position);return e.position===n&&h(e,"name of an alias node must contain at least one character"),i=e.input.slice(n,e.position),T.call(e.anchorMap,i)||h(e,'unidentified alias "'+i+'"'),e.result=e.anchorMap[i],v(e,true,-1),true}function R(e,n,i,l,r){var u,o,f,c=1,a=false,t=false,p,d,s,x,g,A;if(e.listener!==null&&e.listener("open",e),e.tag=null,e.anchor=null,e.kind=null,e.result=null,u=o=f=U===i||he===i,l&&v(e,true,-1)&&(a=true,e.lineIndent>n?c=1:e.lineIndent===n?c=0:e.lineIndent<n&&(c=-1)),c===1)for(;Fi(e)||bi(e);)v(e,true,-1)?(a=true,f=u,e.lineIndent>n?c=1:e.lineIndent===n?c=0:e.lineIndent<n&&(c=-1)):f=false;if(f&&(f=a||r),(c===1||U===i)&&(H===i||te===i?g=n:g=n+1,A=e.position-e.lineStart,c===1?f&&(we(e,A)||wi(e,A,g))||Ci(e,g)?t=true:(o&&_i(e,g)||vi(e,g)||yi(e,g)?t=true:Si(e)?(t=true,(e.tag!==null||e.anchor!==null)&&h(e,"alias node should not have any properties")):Ai(e,g,H===i)&&(t=true,e.tag===null&&(e.tag="?")),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):c===0&&(t=f&&we(e,A))),e.tag===null)e.anchor!==null&&(e.anchorMap[e.anchor]=e.result);else if(e.tag==="?"){for(e.result!==null&&e.kind!=="scalar"&&h(e,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+e.kind+'"'),p=0,d=e.implicitTypes.length;p<d;p+=1)if(x=e.implicitTypes[p],x.resolve(e.result)){e.result=x.construct(e.result),e.tag=x.tag,e.anchor!==null&&(e.anchorMap[e.anchor]=e.result);break}}else if(e.tag!=="!"){if(T.call(e.typeMap[e.kind||"fallback"],e.tag))x=e.typeMap[e.kind||"fallback"][e.tag];else for(x=null,s=e.typeMap.multi[e.kind||"fallback"],p=0,d=s.length;p<d;p+=1)if(e.tag.slice(0,s[p].tag.length)===s[p].tag){x=s[p];break}x||h(e,"unknown tag !<"+e.tag+">"),e.result!==null&&x.kind!==e.kind&&h(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+x.kind+'", not "'+e.kind+'"'),x.resolve(e.result,e.tag)?(e.result=x.construct(e.result,e.tag),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):h(e,"cannot resolve a node with !<"+e.tag+"> explicit tag");}return e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||t}function Ei(e){var n=e.position,i,l,r,u=false,o;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(o=e.input.charCodeAt(e.position))!==0&&(v(e,true,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||o!==37));){for(u=true,o=e.input.charCodeAt(++e.position),i=e.position;o!==0&&!F(o);)o=e.input.charCodeAt(++e.position);for(l=e.input.slice(i,e.position),r=[],l.length<1&&h(e,"directive name must not be less than one character in length");o!==0;){for(;I(o);)o=e.input.charCodeAt(++e.position);if(o===35){do o=e.input.charCodeAt(++e.position);while(o!==0&&!S(o));break}if(S(o))break;for(i=e.position;o!==0&&!F(o);)o=e.input.charCodeAt(++e.position);r.push(e.input.slice(i,e.position));}o!==0&&z(e),T.call(Ce,l)?Ce[l](e,l,r):K(e,'unknown document directive "'+l+'"');}if(v(e,true,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,v(e,true,-1)):u&&h(e,"directives end mark is expected"),R(e,e.lineIndent-1,U,false,true),v(e,true,-1),e.checkLineBreaks&&ti.test(e.input.slice(n,e.position))&&K(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&q(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,v(e,true,-1));return}if(e.position<e.length-1)h(e,"end of the stream or a document separator is expected");else return}function Ti(e,n){e=String(e),n=n||{},e.length!==0&&(e.charCodeAt(e.length-1)!==10&&e.charCodeAt(e.length-1)!==13&&(e+=`
`),e.charCodeAt(0)===65279&&(e=e.slice(1)));var i=new gi(e,n),l=e.indexOf("\0");for(l!==-1&&(i.position=l,h(i,"null byte is not allowed in input")),i.input+="\0";i.input.charCodeAt(i.position)===32;)i.lineIndent+=1,i.position+=1;for(;i.position<i.length-1;)Ei(i);return i.documents}function Oi(e,n){var i=Ti(e,n);if(i.length!==0){if(i.length===1)return i[0];throw new w("expected a single document in the stream, but found more")}}var Ii=Oi,ki={load:Ii},Fe=Object.prototype.toString,be=Object.prototype.hasOwnProperty,ee=65279,Li=9,Y=10,Ni=13,Ri=32,Di=33,Mi=34,ne=35,Yi=37,Bi=38,Pi=39,ji=42,Se=44,Hi=45,G=58,Ui=61,Ki=62,qi=63,Gi=64,Ee=91,Te=93,Wi=96,Oe=123,$i=124,Ie=125,_={};_[0]="\\0",_[7]="\\a",_[8]="\\b",_[9]="\\t",_[10]="\\n",_[11]="\\v",_[12]="\\f",_[13]="\\r",_[27]="\\e",_[34]='\\"',_[92]="\\\\",_[133]="\\N",_[160]="\\_",_[8232]="\\L",_[8233]="\\P";var Qi=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],Vi=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Xi(e,n){var i,l,r,u,o,f,c;if(n===null)return {};for(i={},l=Object.keys(n),r=0,u=l.length;r<u;r+=1)o=l[r],f=String(n[o]),o.slice(0,2)==="!!"&&(o="tag:yaml.org,2002:"+o.slice(2)),c=e.compiledTypeMap.fallback[o],c&&be.call(c.styleAliases,f)&&(f=c.styleAliases[f]),i[o]=f;return i}function Zi(e){var n,i,l;if(n=e.toString(16).toUpperCase(),e<=255)i="x",l=2;else if(e<=65535)i="u",l=4;else if(e<=4294967295)i="U",l=8;else throw new w("code point within a string may not be greater than 0xFFFFFFFF");return "\\"+i+y.repeat("0",l-n.length)+n}var zi=1,B=2;function Ji(e){this.schema=e.schema||pe,this.indent=Math.max(1,e.indent||2),this.noArrayIndent=e.noArrayIndent||false,this.skipInvalid=e.skipInvalid||false,this.flowLevel=y.isNothing(e.flowLevel)?-1:e.flowLevel,this.styleMap=Xi(this.schema,e.styles||null),this.sortKeys=e.sortKeys||false,this.lineWidth=e.lineWidth||80,this.noRefs=e.noRefs||false,this.noCompatMode=e.noCompatMode||false,this.condenseFlow=e.condenseFlow||false,this.quotingType=e.quotingType==='"'?B:zi,this.forceQuotes=e.forceQuotes||false,this.replacer=typeof e.replacer=="function"?e.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null;}function ke(e,n){for(var i=y.repeat(" ",n),l=0,r=-1,u="",o,f=e.length;l<f;)r=e.indexOf(`
`,l),r===-1?(o=e.slice(l),l=f):(o=e.slice(l,r+1),l=r+1),o.length&&o!==`
`&&(u+=i),u+=o;return u}function ie(e,n){return `
`+y.repeat(" ",e.indent*n)}function er(e,n){var i,l,r;for(i=0,l=e.implicitTypes.length;i<l;i+=1)if(r=e.implicitTypes[i],r.resolve(n))return true;return false}function W(e){return e===Ri||e===Li}function P(e){return 32<=e&&e<=126||161<=e&&e<=55295&&e!==8232&&e!==8233||57344<=e&&e<=65533&&e!==ee||65536<=e&&e<=1114111}function Le(e){return P(e)&&e!==ee&&e!==Ni&&e!==Y}function Ne(e,n,i){var l=Le(e),r=l&&!W(e);return (i?l:l&&e!==Se&&e!==Ee&&e!==Te&&e!==Oe&&e!==Ie)&&e!==ne&&!(n===G&&!r)||Le(n)&&!W(n)&&e===ne||n===G&&r}function nr(e){return P(e)&&e!==ee&&!W(e)&&e!==Hi&&e!==qi&&e!==G&&e!==Se&&e!==Ee&&e!==Te&&e!==Oe&&e!==Ie&&e!==ne&&e!==Bi&&e!==ji&&e!==Di&&e!==$i&&e!==Ui&&e!==Ki&&e!==Pi&&e!==Mi&&e!==Yi&&e!==Gi&&e!==Wi}function ir(e){return !W(e)&&e!==G}function j(e,n){var i=e.charCodeAt(n),l;return i>=55296&&i<=56319&&n+1<e.length&&(l=e.charCodeAt(n+1),l>=56320&&l<=57343)?(i-55296)*1024+l-56320+65536:i}function Re(e){var n=/^\n* /;return n.test(e)}var De=1,re=2,Me=3,Ye=4,D=5;function rr(e,n,i,l,r,u,o,f){var c,a=0,t=null,p=false,d=false,s=l!==-1,x=-1,g=nr(j(e,0))&&ir(j(e,e.length-1));if(n||o)for(c=0;c<e.length;a>=65536?c+=2:c++){if(a=j(e,c),!P(a))return D;g=g&&Ne(a,t,f),t=a;}else {for(c=0;c<e.length;a>=65536?c+=2:c++){if(a=j(e,c),a===Y)p=true,s&&(d=d||c-x-1>l&&e[x+1]!==" ",x=c);else if(!P(a))return D;g=g&&Ne(a,t,f),t=a;}d=d||s&&c-x-1>l&&e[x+1]!==" ";}return !p&&!d?g&&!o&&!r(e)?De:u===B?D:re:i>9&&Re(e)?D:o?u===B?D:re:d?Ye:Me}function lr(e,n,i,l,r){e.dump=function(){if(n.length===0)return e.quotingType===B?'""':"''";if(!e.noCompatMode&&(Qi.indexOf(n)!==-1||Vi.test(n)))return e.quotingType===B?'"'+n+'"':"'"+n+"'";var u=e.indent*Math.max(1,i),o=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-u),f=l||e.flowLevel>-1&&i>=e.flowLevel;function c(a){return er(e,a)}switch(rr(n,f,e.indent,o,c,e.quotingType,e.forceQuotes&&!l,r)){case De:return n;case re:return "'"+n.replace(/'/g,"''")+"'";case Me:return "|"+Be(n,e.indent)+Pe(ke(n,u));case Ye:return ">"+Be(n,e.indent)+Pe(ke(or(n,o),u));case D:return '"'+ur(n)+'"';default:throw new w("impossible error: invalid scalar style")}}();}function Be(e,n){var i=Re(e)?String(n):"",l=e[e.length-1]===`
`,r=l&&(e[e.length-2]===`
`||e===`
`),u=r?"+":l?"":"-";return i+u+`
`}function Pe(e){return e[e.length-1]===`
`?e.slice(0,-1):e}function or(e,n){for(var i=/(\n+)([^\n]*)/g,l=function(){var a=e.indexOf(`
`);return a=a!==-1?a:e.length,i.lastIndex=a,je(e.slice(0,a),n)}(),r=e[0]===`
`||e[0]===" ",u,o;o=i.exec(e);){var f=o[1],c=o[2];u=c[0]===" ",l+=f+(!r&&!u&&c!==""?`
`:"")+je(c,n),r=u;}return l}function je(e,n){if(e===""||e[0]===" ")return e;for(var i=/ [^ ]/g,l,r=0,u,o=0,f=0,c="";l=i.exec(e);)f=l.index,f-r>n&&(u=o>r?o:f,c+=`
`+e.slice(r,u),r=u+1),o=f;return c+=`
`,e.length-r>n&&o>r?c+=e.slice(r,o)+`
`+e.slice(o+1):c+=e.slice(r),c.slice(1)}function ur(e){for(var n="",i=0,l,r=0;r<e.length;i>=65536?r+=2:r++)i=j(e,r),l=_[i],!l&&P(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=l||Zi(i);return n}function fr(e,n,i){var l="",r=e.tag,u,o,f;for(u=0,o=i.length;u<o;u+=1)f=i[u],e.replacer&&(f=e.replacer.call(i,String(u),f)),(E(e,n,f,false,false)||typeof f>"u"&&E(e,n,null,false,false))&&(l!==""&&(l+=","+(e.condenseFlow?"":" ")),l+=e.dump);e.tag=r,e.dump="["+l+"]";}function He(e,n,i,l){var r="",u=e.tag,o,f,c;for(o=0,f=i.length;o<f;o+=1)c=i[o],e.replacer&&(c=e.replacer.call(i,String(o),c)),(E(e,n+1,c,true,true,false,true)||typeof c>"u"&&E(e,n+1,null,true,true,false,true))&&((!l||r!=="")&&(r+=ie(e,n)),e.dump&&Y===e.dump.charCodeAt(0)?r+="-":r+="- ",r+=e.dump);e.tag=u,e.dump=r||"[]";}function cr(e,n,i){var l="",r=e.tag,u=Object.keys(i),o,f,c,a,t;for(o=0,f=u.length;o<f;o+=1)t="",l!==""&&(t+=", "),e.condenseFlow&&(t+='"'),c=u[o],a=i[c],e.replacer&&(a=e.replacer.call(i,c,a)),E(e,n,c,false,false)&&(e.dump.length>1024&&(t+="? "),t+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),E(e,n,a,false,false)&&(t+=e.dump,l+=t));e.tag=r,e.dump="{"+l+"}";}function ar(e,n,i,l){var r="",u=e.tag,o=Object.keys(i),f,c,a,t,p,d;if(e.sortKeys===true)o.sort();else if(typeof e.sortKeys=="function")o.sort(e.sortKeys);else if(e.sortKeys)throw new w("sortKeys must be a boolean or a function");for(f=0,c=o.length;f<c;f+=1)d="",(!l||r!=="")&&(d+=ie(e,n)),a=o[f],t=i[a],e.replacer&&(t=e.replacer.call(i,a,t)),E(e,n+1,a,true,true,true)&&(p=e.tag!==null&&e.tag!=="?"||e.dump&&e.dump.length>1024,p&&(e.dump&&Y===e.dump.charCodeAt(0)?d+="?":d+="? "),d+=e.dump,p&&(d+=ie(e,n)),E(e,n+1,t,true,p)&&(e.dump&&Y===e.dump.charCodeAt(0)?d+=":":d+=": ",d+=e.dump,r+=d));e.tag=u,e.dump=r||"{}";}function Ue(e,n,i){var l,r,u,o,f,c;for(r=i?e.explicitTypes:e.implicitTypes,u=0,o=r.length;u<o;u+=1)if(f=r[u],(f.instanceOf||f.predicate)&&(!f.instanceOf||typeof n=="object"&&n instanceof f.instanceOf)&&(!f.predicate||f.predicate(n))){if(i?f.multi&&f.representName?e.tag=f.representName(n):e.tag=f.tag:e.tag="?",f.represent){if(c=e.styleMap[f.tag]||f.defaultStyle,Fe.call(f.represent)==="[object Function]")l=f.represent(n,c);else if(be.call(f.represent,c))l=f.represent[c](n,c);else throw new w("!<"+f.tag+'> tag resolver accepts not "'+c+'" style');e.dump=l;}return true}return false}function E(e,n,i,l,r,u,o){e.tag=null,e.dump=i,Ue(e,i,false)||Ue(e,i,true);var f=Fe.call(e.dump),c=l,a;l&&(l=e.flowLevel<0||e.flowLevel>n);var t=f==="[object Object]"||f==="[object Array]",p,d;if(t&&(p=e.duplicates.indexOf(i),d=p!==-1),(e.tag!==null&&e.tag!=="?"||d||e.indent!==2&&n>0)&&(r=false),d&&e.usedDuplicates[p])e.dump="*ref_"+p;else {if(t&&d&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=true),f==="[object Object]")l&&Object.keys(e.dump).length!==0?(ar(e,n,e.dump,r),d&&(e.dump="&ref_"+p+e.dump)):(cr(e,n,e.dump),d&&(e.dump="&ref_"+p+" "+e.dump));else if(f==="[object Array]")l&&e.dump.length!==0?(e.noArrayIndent&&!o&&n>0?He(e,n-1,e.dump,r):He(e,n,e.dump,r),d&&(e.dump="&ref_"+p+e.dump)):(fr(e,n,e.dump),d&&(e.dump="&ref_"+p+" "+e.dump));else if(f==="[object String]")e.tag!=="?"&&lr(e,e.dump,n,u,c);else {if(f==="[object Undefined]")return false;if(e.skipInvalid)return false;throw new w("unacceptable kind of an object to dump "+f)}e.tag!==null&&e.tag!=="?"&&(a=encodeURI(e.tag[0]==="!"?e.tag.slice(1):e.tag).replace(/!/g,"%21"),e.tag[0]==="!"?a="!"+a:a.slice(0,18)==="tag:yaml.org,2002:"?a="!!"+a.slice(18):a="!<"+a+">",e.dump=a+" "+e.dump);}return true}function pr(e,n){var i=[],l=[],r,u;for(le(e,i,l),r=0,u=l.length;r<u;r+=1)n.duplicates.push(i[l[r]]);n.usedDuplicates=new Array(u);}function le(e,n,i){var l,r,u;if(e!==null&&typeof e=="object")if(r=n.indexOf(e),r!==-1)i.indexOf(r)===-1&&i.push(r);else if(n.push(e),Array.isArray(e))for(r=0,u=e.length;r<u;r+=1)le(e[r],n,i);else for(l=Object.keys(e),r=0,u=l.length;r<u;r+=1)le(e[l[r]],n,i);}function tr(e,n){n=n||{};var i=new Ji(n);i.noRefs||pr(e,i);var l=e;return i.replacer&&(l=i.replacer.call({"":l},"",l)),E(i,0,l,true,true)?i.dump+`
`:""}var hr=tr,dr={dump:hr},sr=ki.load,xr=dr.dump;function mr(e,n){const i=sr(e,n);return N$1(e,i,n),i}function gr(e,n){const i=C$1(e,{}),l=typeof i.indent=="string"?i.indent.length:i.indent,r=xr(e,{indent:l,...n});return i.whitespace.start+r.trim()+i.whitespace.end}
export { mr as parseYAML, gr as stringifyYAML };
import nodeCrypto from 'node:crypto';
import { d as defineCommand } from './index.mjs';
import { createNitro, prepare, copyPublicAssets, prerender, build as build$1 } from 'nitro';
import { c as commonArgs } from './common.mjs';
import { r as resolve } from '../_chunks/pathe.M-eThtNZ.mjs';
import 'consola';
import 'consola/utils';
import 'nitro/meta';
if (!globalThis.crypto) {
globalThis.crypto = nodeCrypto;
}
const build = defineCommand({
meta: {
name: "build",
description: "Build nitro project for production"
},
args: {
...commonArgs,
minify: {
type: "boolean",
description: "Minify the output (overrides preset defaults you can also use `--no-minify` to disable)."
},
preset: {
type: "string",
description: "The build preset to use (you can also use `NITRO_PRESET` environment variable)."
},
compatibilityDate: {
type: "string",
description: "The date to use for preset compatibility (you can also use `NITRO_COMPATIBILITY_DATE` environment variable)."
}
},
async run({ args }) {
const rootDir = resolve(args.dir || args._dir || ".");
const nitro = await createNitro(
{
rootDir,
dev: false,
minify: args.minify,
preset: args.preset
},
{
compatibilityDate: args.compatibilityDate
}
);
await prepare(nitro);
await copyPublicAssets(nitro);
await prerender(nitro);
await build$1(nitro);
await nitro.close();
}
});
export { build as default };
const commonArgs = {
dir: {
type: "string",
description: "project root directory"
},
_dir: {
type: "positional",
default: ".",
description: "project root directory (prefer using `--dir`)"
}
};
export { commonArgs as c };
import { d as defineCommand } from './index.mjs';
import { consola } from 'consola';
import { createNitro, prepare, build } from 'nitro';
import { c as commonArgs } from './common.mjs';
import { N as NitroDevServer } from '../_chunks/server.mjs';
import { r as resolve } from '../_chunks/pathe.M-eThtNZ.mjs';
import 'consola/utils';
import 'nitro/meta';
import '../_chunks/app.mjs';
import 'node:fs';
import 'node:fs/promises';
import 'node:worker_threads';
import 'std-env';
import 'fs';
import 'fs/promises';
import 'events';
import 'path';
import 'node:stream';
import 'node:path';
import 'os';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'crypto';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'srvx/node';
const hmrKeyRe = /^runtimeConfig\.|routeRules\./;
const dev = defineCommand({
meta: {
name: "dev",
description: "Start the development server"
},
args: {
...commonArgs,
port: { type: "string", description: "specify port" },
host: { type: "string", description: "specify hostname " }
},
async run({ args }) {
const rootDir = resolve(args.dir || args._dir || ".");
let nitro;
const reload = async () => {
if (nitro) {
consola.info("Restarting dev server...");
if ("unwatch" in nitro.options._c12) {
await nitro.options._c12.unwatch();
}
await nitro.close();
}
nitro = await createNitro(
{
rootDir,
dev: true,
_cli: { command: "dev" }
},
{
watch: true,
c12: {
async onUpdate({ getDiff, newConfig }) {
const diff = getDiff();
if (diff.length === 0) {
return;
}
consola.info(
"Nitro config updated:\n" + diff.map((entry) => ` ${entry.toString()}`).join("\n")
);
await (diff.every((e) => hmrKeyRe.test(e.key)) ? nitro.updateConfig(newConfig.config || {}) : reload());
}
}
}
);
nitro.hooks.hookOnce("restart", reload);
const server = new NitroDevServer(nitro);
await server.listen({
port: args.port,
hostname: args.host
});
await prepare(nitro);
await build(nitro);
};
await reload();
}
});
export { dev as default };
import { d as defineCommand } from './index.mjs';
import 'consola';
import 'consola/utils';
import 'nitro/meta';
const index = defineCommand({
meta: {
name: "task",
description: "Operate in nitro tasks (experimental)"
},
subCommands: {
list: () => import('./list.mjs').then((r) => r.default),
run: () => import('./run.mjs').then((r) => r.default)
}
});
export { index as default };
import { d as defineCommand } from './index.mjs';
import { consola } from 'consola';
import { loadOptions, listTasks } from 'nitro';
import { r as resolve } from '../_chunks/pathe.M-eThtNZ.mjs';
import 'consola/utils';
import 'nitro/meta';
const list = defineCommand({
meta: {
name: "run",
description: "List available tasks (experimental)"
},
args: {
dir: {
type: "string",
description: "project root directory"
}
},
async run({ args }) {
const cwd = resolve(args.dir || args.cwd || ".");
const options = await loadOptions({ rootDir: cwd }).catch(() => void 0);
const tasks = await listTasks({
cwd,
buildDir: options?.buildDir || ".nitro"
});
for (const [name, task] of Object.entries(tasks)) {
consola.log(
` - \`${name}\`${task.meta?.description ? ` - ${task.meta.description}` : ""}`
);
}
}
});
export { list as default };
import { d as defineCommand } from './index.mjs';
import { createNitro, writeTypes } from 'nitro';
import { c as commonArgs } from './common.mjs';
import { r as resolve } from '../_chunks/pathe.M-eThtNZ.mjs';
import 'consola';
import 'consola/utils';
import 'nitro/meta';
const prepare = defineCommand({
meta: {
name: "prepare",
description: "Generate types for the project"
},
args: {
...commonArgs
},
async run({ args }) {
const rootDir = resolve(args.dir || args._dir || ".");
const nitro = await createNitro({ rootDir });
await writeTypes(nitro);
}
});
export { prepare as default };
import { d as defineCommand } from './index.mjs';
import { consola } from 'consola';
import destr from 'destr';
import { loadOptions, runTask } from 'nitro';
import { r as resolve } from '../_chunks/pathe.M-eThtNZ.mjs';
import 'consola/utils';
import 'nitro/meta';
const run = defineCommand({
meta: {
name: "run",
description: "Run a runtime task in the currently running dev server (experimental)"
},
args: {
name: {
type: "positional",
description: "task name",
required: true
},
dir: {
type: "string",
description: "project root directory"
},
payload: {
type: "string",
description: "payload json to pass to the task"
}
},
async run({ args }) {
const cwd = resolve(args.dir || args.cwd || ".");
const options = await loadOptions({ rootDir: cwd }).catch(() => void 0);
consola.info(`Running task \`${args.name}\`...`);
let payload = destr(args.payload || "{}");
if (typeof payload !== "object") {
consola.error(
`Invalid payload: \`${args.payload}\` (it should be a valid JSON object)`
);
payload = void 0;
}
try {
const { result } = await runTask(
{
name: args.name,
context: {},
payload
},
{
cwd,
buildDir: options?.buildDir || ".nitro"
}
);
consola.success("Result:", result);
} catch (error) {
consola.error(`Failed to run task \`${args.name}\`: ${error}`);
process.exit(1);
}
}
});
export { run as default };
import { NitroConfig, LoadConfigOptions, Nitro, DevRPCHooks, DevMessageListener, NitroOptions, TaskEvent, TaskRunnerOptions } from 'nitro/types';
import { IncomingMessage, OutgoingMessage } from 'node:http';
import { Duplex } from 'node:stream';
import { ServerOptions, Server } from 'srvx';
import { HTTPHandler } from 'h3';
declare function createNitro(config?: NitroConfig, opts?: LoadConfigOptions): Promise<Nitro>;
declare function prerender(nitro: Nitro): Promise<void>;
declare class NitroDevApp {
#private;
nitro: Nitro;
fetch: (req: Request) => Response | Promise<Response>;
constructor(nitro: Nitro, catchAllHandler?: HTTPHandler);
}
declare function createDevServer(nitro: Nitro): NitroDevServer;
declare class NitroDevServer extends NitroDevApp implements DevRPCHooks {
#private;
constructor(nitro: Nitro);
upgrade(req: IncomingMessage, socket: OutgoingMessage<IncomingMessage> | Duplex, head: any): Promise<void>;
listen(opts?: Partial<Omit<ServerOptions, "fetch">>): Server;
close(): Promise<void>;
reload(): void;
sendMessage(message: unknown): void;
onMessage(listener: DevMessageListener): void;
offMessage(listener: DevMessageListener): void;
}
declare function loadOptions(configOverrides?: NitroConfig, opts?: LoadConfigOptions): Promise<NitroOptions>;
/** @experimental */
declare function runTask(taskEvent: TaskEvent, opts?: TaskRunnerOptions): Promise<{
result: unknown;
}>;
/** @experimental */
declare function listTasks(opts?: TaskRunnerOptions): Promise<Record<string, {
meta: {
description: string;
};
}>>;
declare function build(nitro: Nitro): Promise<void>;
declare function copyPublicAssets(nitro: Nitro): Promise<void>;
declare function prepare(nitro: Nitro): Promise<void>;
declare function writeTypes(nitro: Nitro): Promise<void>;
export { build, copyPublicAssets, createDevServer, createNitro, listTasks, loadOptions, prepare, prerender, runTask, writeTypes };
export { d as copyPublicAssets, i as createNitro, D as listTasks, A as loadOptions, j as prepare, B as runTask } from './_chunks/index.mjs';
export { b as build, p as prerender, w as writeTypes } from './_chunks/index3.mjs';
export { c as createDevServer } from './_chunks/server.mjs';
import 'consola';
import 'hookable';
import 'nitro/runtime/meta';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'node:os';
import 'node:path';
import 'node:assert';
import 'node:process';
import 'node:v8';
import 'node:util';
import 'jiti';
import 'destr';
import 'defu';
import './_chunks/pathe.M-eThtNZ.mjs';
import 'fs';
import 'path';
import 'os';
import 'crypto';
import './_chunks/app.mjs';
import 'node:worker_threads';
import 'std-env';
import 'fs/promises';
import 'events';
import 'node:stream';
import 'h3';
import 'url';
import 'tty';
import 'util';
import 'stream';
import 'ufo';
import 'node:http';
import 'node:https';
import 'node:events';
import 'undici';
import 'youch-core';
import 'youch';
import 'source-map';
import 'srvx';
import 'klona/full';
import 'node:module';
import 'ofetch';
import 'klona';
import 'unstorage';
import 'ohash';
import 'scule';
import 'module';
import 'consola/utils';
import 'node:zlib';
import 'nitro/meta';
import 'srvx/node';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
exports.serialize = serialize;
/**
* RegExp to match cookie-name in RFC 6265 sec 4.1.1
* This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
* which has been replaced by the token definition in RFC 7230 appendix B.
*
* cookie-name = token
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" /
* "*" / "+" / "-" / "." / "^" / "_" /
* "`" / "|" / "~" / DIGIT / ALPHA
*
* Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191
* Allow same range as cookie value, except `=`, which delimits end of name.
*/
const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
/**
* RegExp to match cookie-value in RFC 6265 sec 4.1.1
*
* cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
* cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
* ; US-ASCII characters excluding CTLs,
* ; whitespace DQUOTE, comma, semicolon,
* ; and backslash
*
* Allowing more characters: https://github.com/jshttp/cookie/issues/191
* Comma, backslash, and DQUOTE are not part of the parsing algorithm.
*/
const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
/**
* RegExp to match domain-value in RFC 6265 sec 4.1.1
*
* domain-value = <subdomain>
* ; defined in [RFC1034], Section 3.5, as
* ; enhanced by [RFC1123], Section 2.1
* <subdomain> = <label> | <subdomain> "." <label>
* <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
* Labels must be 63 characters or less.
* 'let-dig' not 'letter' in the first char, per RFC1123
* <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
* <let-dig-hyp> = <let-dig> | "-"
* <let-dig> = <letter> | <digit>
* <letter> = any one of the 52 alphabetic characters A through Z in
* upper case and a through z in lower case
* <digit> = any one of the ten digits 0 through 9
*
* Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
*
* > (Note that a leading %x2E ("."), if present, is ignored even though that
* character is not permitted, but a trailing %x2E ("."), if present, will
* cause the user agent to ignore the attribute.)
*/
const domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
/**
* RegExp to match path-value in RFC 6265 sec 4.1.1
*
* path-value = <any CHAR except CTLs or ";">
* CHAR = %x01-7F
* ; defined in RFC 5234 appendix B.1
*/
const pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
const __toString = Object.prototype.toString;
const NullObject = /* @__PURE__ */ (() => {
const C = function () { };
C.prototype = Object.create(null);
return C;
})();
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*/
function parse(str, options) {
const obj = new NullObject();
const len = str.length;
// RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
if (len < 2)
return obj;
const dec = options?.decode || decode;
let index = 0;
do {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1)
break; // No more cookie pairs.
const colonIdx = str.indexOf(";", index);
const endIdx = colonIdx === -1 ? len : colonIdx;
if (eqIdx > endIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const keyStartIdx = startIndex(str, index, eqIdx);
const keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
const key = str.slice(keyStartIdx, keyEndIdx);
// only assign once
if (obj[key] === undefined) {
let valStartIdx = startIndex(str, eqIdx + 1, endIdx);
let valEndIdx = endIndex(str, endIdx, valStartIdx);
const value = dec(str.slice(valStartIdx, valEndIdx));
obj[key] = value;
}
index = endIdx + 1;
} while (index < len);
return obj;
}
function startIndex(str, index, max) {
do {
const code = str.charCodeAt(index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */)
return index;
} while (++index < max);
return max;
}
function endIndex(str, index, min) {
while (index > min) {
const code = str.charCodeAt(--index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */)
return index + 1;
}
return min;
}
/**
* Serialize data into a cookie header.
*
* Serialize a name value pair into a cookie string suitable for
* http headers. An optional options object specifies cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*/
function serialize(name, val, options) {
const enc = options?.encode || encodeURIComponent;
if (!cookieNameRegExp.test(name)) {
throw new TypeError(`argument name is invalid: ${name}`);
}
const value = enc(val);
if (!cookieValueRegExp.test(value)) {
throw new TypeError(`argument val is invalid: ${val}`);
}
let str = name + "=" + value;
if (!options)
return str;
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) {
throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);
}
str += "; Max-Age=" + options.maxAge;
}
if (options.domain) {
if (!domainValueRegExp.test(options.domain)) {
throw new TypeError(`option domain is invalid: ${options.domain}`);
}
str += "; Domain=" + options.domain;
}
if (options.path) {
if (!pathValueRegExp.test(options.path)) {
throw new TypeError(`option path is invalid: ${options.path}`);
}
str += "; Path=" + options.path;
}
if (options.expires) {
if (!isDate(options.expires) ||
!Number.isFinite(options.expires.valueOf())) {
throw new TypeError(`option expires is invalid: ${options.expires}`);
}
str += "; Expires=" + options.expires.toUTCString();
}
if (options.httpOnly) {
str += "; HttpOnly";
}
if (options.secure) {
str += "; Secure";
}
if (options.partitioned) {
str += "; Partitioned";
}
if (options.priority) {
const priority = typeof options.priority === "string"
? options.priority.toLowerCase()
: undefined;
switch (priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default:
throw new TypeError(`option priority is invalid: ${options.priority}`);
}
}
if (options.sameSite) {
const sameSite = typeof options.sameSite === "string"
? options.sameSite.toLowerCase()
: options.sameSite;
switch (sameSite) {
case true:
case "strict":
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "none":
str += "; SameSite=None";
break;
default:
throw new TypeError(`option sameSite is invalid: ${options.sameSite}`);
}
}
return str;
}
/**
* URL-decode string value. Optimized to skip native call when no %.
*/
function decode(str) {
if (str.indexOf("%") === -1)
return str;
try {
return decodeURIComponent(str);
}
catch (e) {
return str;
}
}
/**
* Determine if value is a Date.
*/
function isDate(val) {
return __toString.call(val) === "[object Date]";
}
//# sourceMappingURL=index.js.map
{
"name": "cookie",
"version": "1.0.2",
"description": "HTTP server cookie parsing and serialization",
"keywords": [
"cookie",
"cookies"
],
"repository": "jshttp/cookie",
"license": "MIT",
"author": "Roman Shtylman <shtylman@gmail.com>",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/"
],
"scripts": {
"bench": "vitest bench",
"build": "ts-scripts build",
"format": "ts-scripts format",
"prepare": "ts-scripts install",
"prepublishOnly": "npm run build",
"specs": "ts-scripts specs",
"test": "ts-scripts test"
},
"devDependencies": {
"@borderless/ts-scripts": "^0.15.0",
"@vitest/coverage-v8": "^2.1.2",
"top-sites": "1.1.194",
"typescript": "^5.6.2",
"vitest": "^2.1.2"
},
"engines": {
"node": ">=18"
},
"ts-scripts": {
"project": "tsconfig.build.json"
}
}
export function klona(x) {
if (typeof x !== 'object') return x;
var k, tmp, str=Object.prototype.toString.call(x);
if (str === '[object Object]') {
if (x.constructor !== Object && typeof x.constructor === 'function') {
tmp = new x.constructor();
for (k in x) {
if (x.hasOwnProperty(k) && tmp[k] !== x[k]) {
tmp[k] = klona(x[k]);
}
}
} else {
tmp = {}; // null
for (k in x) {
if (k === '__proto__') {
Object.defineProperty(tmp, k, {
value: klona(x[k]),
configurable: true,
enumerable: true,
writable: true,
});
} else {
tmp[k] = klona(x[k]);
}
}
}
return tmp;
}
if (str === '[object Array]') {
k = x.length;
for (tmp=Array(k); k--;) {
tmp[k] = klona(x[k]);
}
return tmp;
}
if (str === '[object Set]') {
tmp = new Set;
x.forEach(function (val) {
tmp.add(klona(val));
});
return tmp;
}
if (str === '[object Map]') {
tmp = new Map;
x.forEach(function (val, key) {
tmp.set(klona(key), klona(val));
});
return tmp;
}
if (str === '[object Date]') {
return new Date(+x);
}
if (str === '[object RegExp]') {
tmp = new RegExp(x.source, x.flags);
tmp.lastIndex = x.lastIndex;
return tmp;
}
if (str === '[object DataView]') {
return new x.constructor( klona(x.buffer) );
}
if (str === '[object ArrayBuffer]') {
return x.slice(0);
}
// ArrayBuffer.isView(x)
// ~> `new` bcuz `Buffer.slice` => ref
if (str.slice(-6) === 'Array]') {
return new x.constructor(x);
}
return x;
}
function set(obj, key, val) {
if (typeof val.value === 'object') val.value = klona(val.value);
if (!val.enumerable || val.get || val.set || !val.configurable || !val.writable || key === '__proto__') {
Object.defineProperty(obj, key, val);
} else obj[key] = val.value;
}
export function klona(x) {
if (typeof x !== 'object') return x;
var i=0, k, list, tmp, str=Object.prototype.toString.call(x);
if (str === '[object Object]') {
tmp = Object.create(x.__proto__ || null);
} else if (str === '[object Array]') {
tmp = Array(x.length);
} else if (str === '[object Set]') {
tmp = new Set;
x.forEach(function (val) {
tmp.add(klona(val));
});
} else if (str === '[object Map]') {
tmp = new Map;
x.forEach(function (val, key) {
tmp.set(klona(key), klona(val));
});
} else if (str === '[object Date]') {
tmp = new Date(+x);
} else if (str === '[object RegExp]') {
tmp = new RegExp(x.source, x.flags);
} else if (str === '[object DataView]') {
tmp = new x.constructor( klona(x.buffer) );
} else if (str === '[object ArrayBuffer]') {
tmp = x.slice(0);
} else if (str.slice(-6) === 'Array]') {
// ArrayBuffer.isView(x)
// ~> `new` bcuz `Buffer.slice` => ref
tmp = new x.constructor(x);
}
if (tmp) {
for (list=Object.getOwnPropertySymbols(x); i < list.length; i++) {
set(tmp, list[i], Object.getOwnPropertyDescriptor(x, list[i]));
}
for (i=0, list=Object.getOwnPropertyNames(x); i < list.length; i++) {
if (Object.hasOwnProperty.call(tmp, k=list[i]) && tmp[k] === x[k]) continue;
set(tmp, k, Object.getOwnPropertyDescriptor(x, k));
}
}
return tmp || x;
}
{
"name": "klona",
"version": "2.0.6",
"repository": "lukeed/klona",
"description": "A tiny (240B to 501B) and fast utility to \"deep clone\" Objects, Arrays, Dates, RegExps, and more!",
"module": "dist/index.mjs",
"unpkg": "dist/index.min.js",
"main": "dist/index.js",
"types": "index.d.ts",
"license": "MIT",
"author": {
"name": "Luke Edwards",
"email": "luke.edwards05@gmail.com",
"url": "https://lukeed.com"
},
"files": [
"*.d.ts",
"dist",
"full",
"json",
"lite"
],
"exports": {
".": {
"types": "./index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./json": {
"types": "./index.d.ts",
"import": "./json/index.mjs",
"require": "./json/index.js"
},
"./lite": {
"types": "./index.d.ts",
"import": "./lite/index.mjs",
"require": "./lite/index.js"
},
"./full": {
"types": "./index.d.ts",
"import": "./full/index.mjs",
"require": "./full/index.js"
},
"./package.json": "./package.json"
},
"modes": {
"json": "src/json.js",
"lite": "src/lite.js",
"default": "src/index.js",
"full": "src/full.js"
},
"engines": {
"node": ">= 8"
},
"scripts": {
"build": "bundt",
"pretest": "npm run build",
"postbuild": "echo \"lite full json\" | xargs -n1 cp -v index.d.ts",
"test": "uvu -r esm test -i suites"
},
"keywords": [
"clone",
"copy",
"deep",
"extend",
"recursive",
"object"
],
"devDependencies": {
"bundt": "1.0.2",
"esm": "3.2.25",
"uvu": "0.5.2"
}
}
const r=Object.create(null),i=e=>globalThis.process?.env||import.meta.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?r:globalThis),o=new Proxy(r,{get(e,s){return i()[s]??r[s]},has(e,s){const E=i();return s in E||s in r},set(e,s,E){const B=i(!0);return B[s]=E,!0},deleteProperty(e,s){if(!s)return!1;const E=i(!0);return delete E[s],!0},ownKeys(){const e=i(!0);return Object.keys(e)}}),t=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",f=[["APPVEYOR"],["AWS_AMPLIFY","AWS_APP_ID",{ci:!0}],["AZURE_PIPELINES","SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"],["AZURE_STATIC","INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"],["APPCIRCLE","AC_APPCIRCLE"],["BAMBOO","bamboo_planKey"],["BITBUCKET","BITBUCKET_COMMIT"],["BITRISE","BITRISE_IO"],["BUDDY","BUDDY_WORKSPACE_ID"],["BUILDKITE"],["CIRCLE","CIRCLECI"],["CIRRUS","CIRRUS_CI"],["CLOUDFLARE_PAGES","CF_PAGES",{ci:!0}],["CLOUDFLARE_WORKERS","WORKERS_CI",{ci:!0}],["CODEBUILD","CODEBUILD_BUILD_ARN"],["CODEFRESH","CF_BUILD_ID"],["DRONE"],["DRONE","DRONE_BUILD_EVENT"],["DSARI"],["GITHUB_ACTIONS"],["GITLAB","GITLAB_CI"],["GITLAB","CI_MERGE_REQUEST_ID"],["GOCD","GO_PIPELINE_LABEL"],["LAYERCI"],["HUDSON","HUDSON_URL"],["JENKINS","JENKINS_URL"],["MAGNUM"],["NETLIFY"],["NETLIFY","NETLIFY_LOCAL",{ci:!1}],["NEVERCODE"],["RENDER"],["SAIL","SAILCI"],["SEMAPHORE"],["SCREWDRIVER"],["SHIPPABLE"],["SOLANO","TDDIUM"],["STRIDER"],["TEAMCITY","TEAMCITY_VERSION"],["TRAVIS"],["VERCEL","NOW_BUILDER"],["VERCEL","VERCEL",{ci:!1}],["VERCEL","VERCEL_ENV",{ci:!1}],["APPCENTER","APPCENTER_BUILD_ID"],["CODESANDBOX","CODESANDBOX_SSE",{ci:!1}],["CODESANDBOX","CODESANDBOX_HOST",{ci:!1}],["STACKBLITZ"],["STORMKIT"],["CLEAVR"],["ZEABUR"],["CODESPHERE","CODESPHERE_APP_ID",{ci:!0}],["RAILWAY","RAILWAY_PROJECT_ID"],["RAILWAY","RAILWAY_SERVICE_ID"],["DENO-DEPLOY","DENO_DEPLOYMENT_ID"],["FIREBASE_APP_HOSTING","FIREBASE_APP_HOSTING",{ci:!0}]];function b(){if(globalThis.process?.env)for(const e of f){const s=e[1]||e[0];if(globalThis.process?.env[s])return{name:e[0].toLowerCase(),...e[2]}}return globalThis.process?.env?.SHELL==="/bin/jsh"&&globalThis.process?.versions?.webcontainer?{name:"stackblitz",ci:!1}:{name:"",ci:!1}}const l=b(),p=l.name;function n(e){return e?e!=="false":!1}const I=globalThis.process?.platform||"",T=n(o.CI)||l.ci!==!1,R=n(globalThis.process?.stdout&&globalThis.process?.stdout.isTTY),U=typeof window<"u",d=n(o.DEBUG),a=t==="test"||n(o.TEST),g=t==="production",h=t==="dev"||t==="development",v=n(o.MINIMAL)||T||a||!R,A=/^win/i.test(I),M=/^linux/i.test(I),m=/^darwin/i.test(I),Y=!n(o.NO_COLOR)&&(n(o.FORCE_COLOR)||(R||A)&&o.TERM!=="dumb"||T),C=(globalThis.process?.versions?.node||"").replace(/^v/,"")||null,V=Number(C?.split(".")[0])||null,W=globalThis.process||Object.create(null),_={versions:{}},y=new Proxy(W,{get(e,s){if(s==="env")return o;if(s in e)return e[s];if(s in _)return _[s]}}),O=globalThis.process?.release?.name==="node",c=!!globalThis.Bun||!!globalThis.process?.versions?.bun,D=!!globalThis.Deno,L=!!globalThis.fastly,S=!!globalThis.Netlify,u=!!globalThis.EdgeRuntime,N=globalThis.navigator?.userAgent==="Cloudflare-Workers",F=[[S,"netlify"],[u,"edge-light"],[N,"workerd"],[L,"fastly"],[D,"deno"],[c,"bun"],[O,"node"]];function G(){const e=F.find(s=>s[0]);if(e)return{name:e[1]}}const P=G(),K=P?.name||"";export{o as env,R as hasTTY,U as hasWindow,c as isBun,T as isCI,Y as isColorSupported,d as isDebug,D as isDeno,h as isDevelopment,u as isEdgeLight,L as isFastly,M as isLinux,m as isMacOS,v as isMinimal,S as isNetlify,O as isNode,g as isProduction,a as isTest,A as isWindows,N as isWorkerd,t as nodeENV,V as nodeMajorVersion,C as nodeVersion,I as platform,y as process,p as provider,l as providerInfo,K as runtime,P as runtimeInfo};
{
"name": "std-env",
"version": "3.9.0",
"description": "Runtime agnostic JS utils",
"repository": "unjs/std-env",
"license": "MIT",
"sideEffects": false,
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint . && prettier -c src test",
"lint:fix": "eslint --fix . && prettier -w src test",
"prepack": "unbuild",
"play:bun": "bun playground/bun.ts",
"play:deno": "pnpm build && deno run -A playground/deno.ts",
"play:node": "pnpm build && node playground/node.mjs",
"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
"test": "pnpm lint && pnpm typecheck && vitest run --coverage",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@vitest/coverage-v8": "^3.1.1",
"changelogen": "^0.6.1",
"esbuild": "^0.25.2",
"eslint": "^9.23.0",
"eslint-config-unjs": "^0.4.2",
"jiti": "^2.4.2",
"prettier": "^3.5.3",
"rollup": "^4.39.0",
"typescript": "^5.8.2",
"unbuild": "^3.5.0",
"vitest": "^3.1.1"
},
"packageManager": "pnpm@10.7.1"
}
import {
colors,
htmlEscape
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_stack/main.ts
import { dump, themes } from "@poppinss/dumper/html";
import { dump as dumpCli } from "@poppinss/dumper/console";
var CHEVIRON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" width="24" height="24" stroke-width="2">
<path d="M6 9l6 6l6 -6"></path>
</svg>`;
var EDITORS = {
textmate: "txmt://open?url=file://%f&line=%l",
macvim: "mvim://open?url=file://%f&line=%l",
emacs: "emacs://open?url=file://%f&line=%l",
sublime: "subl://open?url=file://%f&line=%l",
phpstorm: "phpstorm://open?file=%f&line=%l",
atom: "atom://core/open/file?filename=%f&line=%l",
vscode: "vscode://file/%f:%l"
};
var ErrorStack = class extends BaseComponent {
cssFile = new URL("./error_stack/style.css", publicDirURL);
scriptFile = new URL("./error_stack/script.js", publicDirURL);
/**
* Returns the file's relative name from the CWD
*/
#getRelativeFileName(filePath) {
return filePath.replace(`${process.cwd()}/`, "");
}
/**
* Returns the index of the frame that should be expanded by
* default
*/
#getFirstExpandedFrameIndex(frames) {
let expandAtIndex = frames.findIndex((frame) => frame.type === "app");
if (expandAtIndex === -1) {
expandAtIndex = frames.findIndex((frame) => frame.type === "module");
}
return expandAtIndex;
}
/**
* Returns the link to open the file within known code
* editors
*/
#getEditorLink(ide, frame) {
const editorURL = EDITORS[ide] || ide;
if (!editorURL || frame.type === "native") {
return {
text: this.#getRelativeFileName(frame.fileName)
};
}
return {
href: editorURL.replace("%f", frame.fileName).replace("%l", String(frame.lineNumber)),
text: this.#getRelativeFileName(frame.fileName)
};
}
/**
* Returns the HTML fragment for the frame location
*/
#renderFrameLocation(frame, ide) {
const { text, href } = this.#getEditorLink(ide, frame);
const fileName = `<a${href ? ` href="${href}"` : ""} class="stack-frame-filepath" title="${text}">
${htmlEscape(text)}
</a>`;
const functionName = frame.functionName ? `<span>in <code title="${frame.functionName}">
${htmlEscape(frame.functionName)}
</code></span>` : "";
const loc = `<span>at line <code>${frame.lineNumber}:${frame.columnNumber}</code></span>`;
if (frame.type !== "native" && frame.source) {
return `<button class="stack-frame-location">
${fileName} ${functionName} ${loc}
</button>`;
}
return `<div class="stack-frame-location">
${fileName} ${functionName} ${loc}
</div>`;
}
/**
* Returns HTML fragment for the stack frame
*/
async #renderStackFrame(frame, index, expandAtIndex, props) {
const label = frame.type === "app" ? '<span class="frame-label">In App</span>' : "";
const expandedClass = expandAtIndex === index ? " expanded" : "";
const toggleButton = frame.type !== "native" && frame.source ? `<button class="stack-frame-toggle-indicator">${CHEVIRON}</button>` : "";
return `<li class="stack-frame stack-frame-${frame.type}${expandedClass}">
<div class="stack-frame-contents">
${this.#renderFrameLocation(frame, props.ide)}
<div class="stack-frame-extras">
${label}
${toggleButton}
</div>
</div>
<div class="stack-frame-source">
${await props.sourceCodeRenderer(props.error, frame)}
</div>
</li>`;
}
/**
* Returns the ANSI output to print the stack frame on the
* terminal
*/
async #printStackFrame(frame, index, expandAtIndex, props) {
const fileName = this.#getRelativeFileName(frame.fileName);
const loc = `${fileName}:${frame.lineNumber}:${frame.columnNumber}`;
if (index === expandAtIndex) {
const functionName2 = frame.functionName ? `at ${frame.functionName} ` : "";
const codeSnippet = await props.sourceCodeRenderer(props.error, frame);
return ` \u2043 ${functionName2}${colors.yellow(`(${loc})`)}${codeSnippet}`;
}
if (frame.type === "native") {
const functionName2 = frame.functionName ? `at ${colors.italic(frame.functionName)} ` : "";
return colors.dim(` \u2043 ${functionName2}(${colors.italic(loc)})`);
}
const functionName = frame.functionName ? `at ${frame.functionName} ` : "";
return ` \u2043 ${functionName}${colors.yellow(`(${loc})`)}`;
}
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#renderStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
return `<section>
<div class="card">
<div class="card-heading">
<div>
<h3 class="card-title">
Stack Trace
</h3>
</div>
</div>
<div class="card-body">
<div id="stack-frames-wrapper">
<div id="stack-frames-header">
<div id="all-frames-toggle-wrapper">
<label id="all-frames-toggle">
<input type="checkbox" />
<span> View All Frames </span>
</label>
</div>
<div>
<div class="toggle-switch">
<button id="formatted-frames-toggle" class="active"> Pretty </button>
<button id="raw-frames-toggle"> Raw </button>
</div>
</div>
</div>
<div id="stack-frames-body">
<div id="stack-frames-formatted" class="visible">
<ul id="stack-frames">
${frames.join("\n")}
</ul>
</div>
<div id="stack-frames-raw">
${dump(props.error.raw, {
styles: themes.cssVariables,
expand: true,
cspNonce: props.cspNonce,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}
</div>
</div>
<div>
</div>
</div>
</section>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
const displayRaw = process.env.YOUCH_RAW;
if (displayRaw) {
const depth = Number.isNaN(Number(displayRaw)) ? 2 : Number(displayRaw);
return `
${colors.red("[RAW]")}
${dumpCli(props.error.raw, {
depth,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}`;
}
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#printStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
return `
${frames.join("\n")}`;
}
};
export {
ErrorStack
};
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/layout/main.ts
var Layout = class extends BaseComponent {
cssFile = new URL("./layout/style.css", publicDirURL);
scriptFile = new URL("./layout/script.js", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${props.title}</title>
<!-- STYLES -->
<!-- SCRIPTS -->
</head>
<body>
<div id="layout">
${await props.children()}
</div>
</body>
</html>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
return `
${await props.children()}
`;
}
};
export {
Layout
};

Sorry, the diff of this file is too big to display

import "#nitro-internal-pollyfills";
import type { ServerRequest } from "srvx";
declare const _default: {
fetch(req: ServerRequest, context: {
waitUntil: (promise: Promise<any>) => void;
}): any;
};
export default _default;
import "#nitro-internal-pollyfills";
import { useNitroApp } from "nitro/runtime";
const nitroApp = useNitroApp();
export default {
fetch(req, context) {
const isrRoute = req.headers.get("x-now-route-matches");
if (isrRoute) {
const url = new URL(req.url);
url.pathname = decodeURIComponent(isrRoute);
req = new Request(url.toString(), req);
}
req.runtime ??= { name: "vercel" };
req.runtime.vercel = { context };
req.waitUntil = context?.waitUntil;
return nitroApp.fetch(req);
}
};
export { defineNitroPlugin } from "./internal/plugin.mjs";
export { defineRouteMeta } from "./internal/meta.mjs";
export { defineNitroErrorHandler } from "./internal/error/utils.mjs";
export { useRuntimeConfig } from "./internal/runtime-config.mjs";
export { useRequest } from "./internal/context.mjs";
export { defineRenderHandler } from "./internal/renderer.mjs";
export { defineCachedFunction, defineCachedEventHandler, defineCachedHandler, cachedFunction, cachedEventHandler, } from "./internal/cache.mjs";
export { useNitroApp } from "./internal/app.mjs";
export { useStorage } from "./internal/storage.mjs";
export { useDatabase } from "./internal/database.mjs";
export { defineTask, runTask } from "./internal/task.mjs";
export { defineNitroPlugin } from "./internal/plugin.mjs";
export { defineRouteMeta } from "./internal/meta.mjs";
export { defineNitroErrorHandler } from "./internal/error/utils.mjs";
export { useRuntimeConfig } from "./internal/runtime-config.mjs";
export { useRequest } from "./internal/context.mjs";
export { defineRenderHandler } from "./internal/renderer.mjs";
export {
defineCachedFunction,
defineCachedEventHandler,
defineCachedHandler,
cachedFunction,
cachedEventHandler
} from "./internal/cache.mjs";
export { useNitroApp } from "./internal/app.mjs";
export { useStorage } from "./internal/storage.mjs";
export { useDatabase } from "./internal/database.mjs";
export { defineTask, runTask } from "./internal/task.mjs";
declare const _default: NitroAppPlugin;
export default _default;
import { createDebugger } from "hookable";
import { defineNitroPlugin } from "./plugin.mjs";
export default defineNitroPlugin((nitro) => {
createDebugger(nitro.hooks, { tag: "nitro-runtime" });
});
export { trapUnhandledNodeErrors } from "./utils.mjs";
export { startScheduleRunner, runCronTasks } from "./task.mjs";
export { getGracefulShutdownConfig, setupGracefulShutdown } from "./shutdown.mjs";
export { trapUnhandledNodeErrors } from "./utils.mjs";
export { startScheduleRunner, runCronTasks } from "./task.mjs";
export { getGracefulShutdownConfig, setupGracefulShutdown } from "./shutdown.mjs";
/**
* Gracefully shuts down `server` when the process receives
* the passed signals
*
* @param {http.Server} server
* @param {object} opts
* signals: string (each signal separated by SPACE)
* timeout: timeout value for forceful shutdown in ms
* forceExit: force process.exit() - otherwise just let event loop clear
* development: boolean value (if true, no graceful shutdown to speed up development
* preShutdown: optional function. Needs to return a promise. - HTTP sockets are still available and untouched
* onShutdown: optional function. Needs to return a promise.
* finally: optional function, handled at the end of the shutdown.
*/
declare function GracefulShutdown(server: any, opts: any): () => any;
export default GracefulShutdown;
import http from "node:http";
const debug = (...args) => {
};
function GracefulShutdown(server, opts) {
opts = opts || {};
const options = Object.assign(
{
signals: "SIGINT SIGTERM",
timeout: 3e4,
development: false,
forceExit: true,
onShutdown: (signal) => Promise.resolve(signal),
preShutdown: (signal) => Promise.resolve(signal)
},
opts
);
let isShuttingDown = false;
const connections = {};
let connectionCounter = 0;
const secureConnections = {};
let secureConnectionCounter = 0;
let failed = false;
let finalRun = false;
function onceFactory() {
let called = false;
return (emitter, events, callback) => {
function call() {
if (!called) {
called = true;
return Reflect.apply(callback, this, arguments);
}
}
for (const e of events) {
emitter.on(e, call);
}
};
}
const signals = options.signals.split(" ").map((s) => s.trim()).filter((s) => s.length > 0);
const once = onceFactory();
once(process, signals, (signal) => {
debug("received shut down signal", signal);
shutdown(signal).then(() => {
if (options.forceExit) {
process.exit(failed ? 1 : 0);
}
}).catch((error) => {
debug("server shut down error occurred", error);
process.exit(1);
});
});
function isFunction(functionToCheck) {
const getType = Object.prototype.toString.call(functionToCheck);
return /^\[object\s([A-Za-z]+)?Function]$/.test(getType);
}
function destroy(socket, force = false) {
if (socket._isIdle && isShuttingDown || force) {
socket.destroy();
if (socket.server instanceof http.Server) {
delete connections[socket._connectionId];
} else {
delete secureConnections[socket._connectionId];
}
}
}
function destroyAllConnections(force = false) {
debug("Destroy Connections : " + (force ? "forced close" : "close"));
let counter = 0;
let secureCounter = 0;
for (const key of Object.keys(connections)) {
const socket = connections[key];
const serverResponse = socket._httpMessage;
if (serverResponse && !force) {
if (!serverResponse.headersSent) {
serverResponse.setHeader("connection", "close");
}
} else {
counter++;
destroy(socket);
}
}
debug("Connections destroyed : " + counter);
debug("Connection Counter : " + connectionCounter);
for (const key of Object.keys(secureConnections)) {
const socket = secureConnections[key];
const serverResponse = socket._httpMessage;
if (serverResponse && !force) {
if (!serverResponse.headersSent) {
serverResponse.setHeader("connection", "close");
}
} else {
secureCounter++;
destroy(socket);
}
}
debug("Secure Connections destroyed : " + secureCounter);
debug("Secure Connection Counter : " + secureConnectionCounter);
}
server.on("request", (req, res) => {
req.socket._isIdle = false;
if (isShuttingDown && !res.headersSent) {
res.setHeader("connection", "close");
}
res.on("finish", () => {
req.socket._isIdle = true;
destroy(req.socket);
});
});
server.on("connection", (socket) => {
if (isShuttingDown) {
socket.destroy();
} else {
const id = connectionCounter++;
socket._isIdle = true;
socket._connectionId = id;
connections[id] = socket;
socket.once("close", () => {
delete connections[socket._connectionId];
});
}
});
server.on("secureConnection", (socket) => {
if (isShuttingDown) {
socket.destroy();
} else {
const id = secureConnectionCounter++;
socket._isIdle = true;
socket._connectionId = id;
secureConnections[id] = socket;
socket.once("close", () => {
delete secureConnections[socket._connectionId];
});
}
});
process.on("close", () => {
debug("closed");
});
function shutdown(sig) {
function cleanupHttp() {
destroyAllConnections();
debug("Close http server");
return new Promise((resolve, reject) => {
server.close((err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
});
}
debug("shutdown signal - " + sig);
if (options.development) {
debug("DEV-Mode - immediate forceful shutdown");
return process.exit(0);
}
function finalHandler() {
if (!finalRun) {
finalRun = true;
if (options.finally && isFunction(options.finally)) {
debug("executing finally()");
options.finally();
}
}
return Promise.resolve();
}
function waitForReadyToShutDown(totalNumInterval) {
debug(`waitForReadyToShutDown... ${totalNumInterval}`);
if (totalNumInterval === 0) {
debug(
`Could not close connections in time (${options.timeout}ms), will forcefully shut down`
);
return Promise.resolve(true);
}
const allConnectionsClosed = Object.keys(connections).length === 0 && Object.keys(secureConnections).length === 0;
if (allConnectionsClosed) {
debug("All connections closed. Continue to shutting down");
return Promise.resolve(false);
}
debug("Schedule the next waitForReadyToShutdown");
return new Promise((resolve) => {
setTimeout(() => {
resolve(waitForReadyToShutDown(totalNumInterval - 1));
}, 250);
});
}
if (isShuttingDown) {
return Promise.resolve();
}
debug("shutting down");
return options.preShutdown(sig).then(() => {
isShuttingDown = true;
cleanupHttp();
}).then(() => {
const pollIterations = options.timeout ? Math.round(options.timeout / 250) : 0;
return waitForReadyToShutDown(pollIterations);
}).then((force) => {
debug("Do onShutdown now");
if (force) {
destroyAllConnections(force);
}
return options.onShutdown(sig);
}).then(finalHandler).catch((error) => {
const errString = typeof error === "string" ? error : JSON.stringify(error);
debug(errString);
failed = true;
throw errString;
});
}
function shutdownManual() {
return shutdown("manual");
}
return shutdownManual;
}
export default GracefulShutdown;
import { type EventHandler } from "h3";
import type { RenderHandler } from "nitro/types";
export declare function defineRenderHandler(render: RenderHandler): EventHandler;
import { defineHandler } from "h3";
import { useNitroApp } from "./app.mjs";
import { useRuntimeConfig } from "./runtime-config.mjs";
export function defineRenderHandler(render) {
const runtimeConfig = useRuntimeConfig();
return defineHandler(async (event) => {
const nitroApp = useNitroApp();
const ctx = { event, render, response: void 0 };
await nitroApp.hooks.callHook("render:before", ctx);
if (!ctx.response) {
if (event.url.pathname === `${runtimeConfig.app.baseURL}favicon.ico`) {
event.res.headers.set("Content-Type", "image/x-icon");
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
}
ctx.response = await ctx.render(event);
if (!ctx.response) {
const _currentStatus = event.res.status;
event.res.statusText = String(
_currentStatus === 200 ? 500 : _currentStatus
);
return "No response returned from render handler: " + event.url.pathname;
}
}
await nitroApp.hooks.callHook("render:response", ctx.response, ctx);
if (ctx.response.headers) {
for (const [key, value] of Object.entries(ctx.response.headers)) {
event.res.headers.set(key, value);
}
}
if (ctx.response.status || ctx.response.statusText) {
event.res.status = ctx.response.status;
event.res.statusText = ctx.response.statusText;
}
return ctx.response.body;
});
}
import type { Server as HttpServer } from "node:http";
import type { NitroApp } from "nitro/types";
export declare function getGracefulShutdownConfig(): {
disabled: boolean;
signals: string[];
timeout: number;
forceExit: boolean;
};
export declare function setupGracefulShutdown(listener: HttpServer, nitroApp: NitroApp): void;
import gracefulShutdown from "./lib/http-graceful-shutdown.mjs";
export function getGracefulShutdownConfig() {
return {
disabled: !!process.env.NITRO_SHUTDOWN_DISABLED,
signals: (process.env.NITRO_SHUTDOWN_SIGNALS || "SIGTERM SIGINT").split(" ").map((s) => s.trim()),
timeout: Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 3e4,
forceExit: !process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT
};
}
export function setupGracefulShutdown(listener, nitroApp) {
const shutdownConfig = getGracefulShutdownConfig();
if (shutdownConfig.disabled) {
return;
}
gracefulShutdown(listener, {
signals: shutdownConfig.signals.join(" "),
timeout: shutdownConfig.timeout,
forceExit: shutdownConfig.forceExit,
onShutdown: async () => {
await new Promise((resolve) => {
const timeout = setTimeout(() => {
console.warn("Graceful shutdown timeout, force exiting...");
resolve();
}, shutdownConfig.timeout);
nitroApp.hooks.callHook("close").catch((error) => {
console.error(error);
}).finally(() => {
clearTimeout(timeout);
resolve();
});
});
}
});
}
export declare function trapUnhandledNodeErrors(): void;
import { useNitroApp } from "./app.mjs";
function _captureError(error, type) {
console.error(`[${type}]`, error);
useNitroApp().captureError(error, { tags: [type] });
}
export function trapUnhandledNodeErrors() {
process.on(
"unhandledRejection",
(error) => _captureError(error, "unhandledRejection")
);
process.on(
"uncaughtException",
(error) => _captureError(error, "uncaughtException")
);
}
export function setupVite({ manifest, services }: {
manifest: any;
services: any;
}): void;
export function setupVite({ manifest, services }) {
globalThis.__VITE_MANIFEST__ = manifest;
const originalFetch = globalThis.fetch;
globalThis.fetch = function nitroViteFetch(input, init) {
// Only override if viteEnvName is specified
const viteEnvName = getViteEnv(init) || getViteEnv(input);
if (!viteEnvName) {
return originalFetch(input, init);
}
// Validate viteEnv
const viteEnv = services[viteEnvName];
if (!viteEnv) {
throw httpError(404);
}
// Normalize input (relative urls)
if (typeof input === "string" && input[0] === "/") {
input = new URL(input, "http://localhost");
}
// Clone headers and set viteEnv header
const headers = new Headers(init?.headers || {});
headers.set("x-vite-env", viteEnvName);
// Normalize to Request
if (
!(input instanceof Request) ||
(init && Object.keys(init).join("") !== "viteEnv")
) {
input = new Request(input, init);
}
// Fetch via vite env
return viteEnv.fetch(input);
};
}
function getViteEnv(input) {
if (!input || typeof input !== "object") {
return;
}
if ("viteEnv" in input) {
return input.viteEnv;
}
if (input.headers) {
return (
input.headers["x-vite-env"] ||
input.headers.get?.("x-vite-env") ||
(Array.isArray(input.headers) &&
input.headers.find((h) => h[0].toLowerCase() === "x-vite-env")?.[1])
);
}
}
/** @param {{ req: Request }} HTTPEvent */
export default function ssrRenderer({ req }: {
req: Request;
}): Promise<Response>;
import { NitroConfig } from "nitro/types";
export { NitroConfig } from "nitro/types";
declare function defineNitroConfig(
config: Omit<NitroConfig, "rootDir">
): Omit<NitroConfig, "rootDir">;
export { defineNitroConfig };
function defineNitroConfig(config) {
return config;
}
export { defineNitroConfig };
import type { CompatibilityUpdate } from "compatx";
export const version: string;
export const compatibilityChanges: CompatibilityUpdate[];
import packageJson from "../package.json" with { type: "json" };
export const version = packageJson.version;
export const compatibilityChanges = [
{
from: "2024-05-07",
platform: "netlify",
description: "Netlify functions v2",
},
{
from: "2024-09-19",
platform: "cloudflare",
description: "Static assets support for cloudflare-module preset",
},
{
from: "2025-01-30",
platform: "deno",
description: "Deno v2 Node.js compatibility",
},
];
export declare const pkgDir: string;
export declare const runtimeDir: string;
export declare const presetsDir: string;
export declare const subpaths: string[];
export declare const runtimeDependencies: string[];
import { fileURLToPath } from "node:url";
export const pkgDir = fileURLToPath(new URL("..", import.meta.url));
export const runtimeDir = fileURLToPath(
new URL("../dist/runtime/", import.meta.url)
);
export const presetsDir = fileURLToPath(
new URL("../dist/presets/", import.meta.url)
);
export const runtimeDependencies = [
"h3",
"cookie-es",
"defu",
"destr",
"hookable",
"iron-webcrypto",
"klona",
"node-mock-http",
"ofetch",
"ohash",
"pathe",
"rou3",
"srvx",
"scule",
"ufo",
"db0",
"std-env",
"uncrypto",
"unctx",
"unenv",
"unstorage",
"crossws",
"croner",
"rendu",
];

Sorry, the diff of this file is too big to display