Socket
Socket
Sign inDemoInstall

vite

Package Overview
Dependencies
Maintainers
5
Versions
569
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite - npm Package Compare versions

Comparing version 6.0.0-alpha.18 to 6.0.0-alpha.19

dist/node/chunks/dep-bCS_cgqC.js

4

client.d.ts

@@ -57,2 +57,6 @@ /// <reference path="./types/importMeta.d.ts" />

}
declare module '*.bmp' {
const src: string
export default src
}
declare module '*.png' {

@@ -59,0 +63,0 @@ const src: string

510

dist/node/cli.js
import path from 'node:path';
import fs from 'node:fs';
import fs__default from 'node:fs';
import { performance } from 'node:perf_hooks';
import { EventEmitter } from 'events';
import { I as colors, A as createLogger, r as resolveConfig } from './chunks/dep-DXWVQosX.js';
import { I as colors, A as createLogger, r as resolveConfig } from './chunks/dep-BWEMV5Th.js';
import { VERSION } from './constants.js';

@@ -15,3 +15,5 @@ import 'node:fs/promises';

import 'fs';
import 'assert';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';

@@ -36,3 +38,2 @@ import 'node:http';

import 'node:worker_threads';
import 'node:events';
import 'crypto';

@@ -46,2 +47,3 @@ import 'querystring';

import 'tls';
import 'assert';
import 'node:zlib';

@@ -662,289 +664,277 @@

const cli = cac('vite');
const cli = cac("vite");
let profileSession = global.__vite_profile_session;
let profileCount = 0;
const stopProfiler = (log) => {
if (!profileSession)
return;
return new Promise((res, rej) => {
profileSession.post('Profiler.stop', (err, { profile }) => {
// Write profile to disk, upload, etc.
if (!err) {
const outPath = path.resolve(`./vite-profile-${profileCount++}.cpuprofile`);
fs.writeFileSync(outPath, JSON.stringify(profile));
log(colors.yellow(`CPU profile written to ${colors.white(colors.dim(outPath))}`));
profileSession = undefined;
res();
}
else {
rej(err);
}
});
if (!profileSession) return;
return new Promise((res, rej) => {
profileSession.post("Profiler.stop", (err, { profile }) => {
if (!err) {
const outPath = path.resolve(
`./vite-profile-${profileCount++}.cpuprofile`
);
fs__default.writeFileSync(outPath, JSON.stringify(profile));
log(
colors.yellow(
`CPU profile written to ${colors.white(colors.dim(outPath))}`
)
);
profileSession = void 0;
res();
} else {
rej(err);
}
});
});
};
const filterDuplicateOptions = (options) => {
for (const [key, value] of Object.entries(options)) {
if (Array.isArray(value)) {
options[key] = value[value.length - 1];
}
for (const [key, value] of Object.entries(options)) {
if (Array.isArray(value)) {
options[key] = value[value.length - 1];
}
}
};
/**
* removing global flags before passing as command specific sub-configs
*/
function cleanGlobalCLIOptions(options) {
const ret = { ...options };
delete ret['--'];
delete ret.c;
delete ret.config;
delete ret.base;
delete ret.l;
delete ret.logLevel;
delete ret.clearScreen;
delete ret.d;
delete ret.debug;
delete ret.f;
delete ret.filter;
delete ret.m;
delete ret.mode;
// convert the sourcemap option to a boolean if necessary
if ('sourcemap' in ret) {
const sourcemap = ret.sourcemap;
ret.sourcemap =
sourcemap === 'true'
? true
: sourcemap === 'false'
? false
: ret.sourcemap;
}
return ret;
const ret = { ...options };
delete ret["--"];
delete ret.c;
delete ret.config;
delete ret.base;
delete ret.l;
delete ret.logLevel;
delete ret.clearScreen;
delete ret.d;
delete ret.debug;
delete ret.f;
delete ret.filter;
delete ret.m;
delete ret.mode;
if ("sourcemap" in ret) {
const sourcemap = ret.sourcemap;
ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
}
return ret;
}
/**
* removing builder flags before passing as command specific sub-configs
*/
function cleanBuilderCLIOptions(options) {
const ret = { ...options };
delete ret.app;
return ret;
const ret = { ...options };
delete ret.app;
return ret;
}
/**
* host may be a number (like 0), should convert to string
*/
const convertHost = (v) => {
if (typeof v === 'number') {
return String(v);
}
return v;
if (typeof v === "number") {
return String(v);
}
return v;
};
/**
* base may be a number (like 0), should convert to empty string
*/
const convertBase = (v) => {
if (v === 0) {
return '';
if (v === 0) {
return "";
}
return v;
};
cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
type: [convertBase]
}).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--open [path]", `[boolean | string] open browser on startup`).option("--cors", `[boolean] enable CORS`).option("--strictPort", `[boolean] exit if specified port is already in use`).option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(async (root, options) => {
filterDuplicateOptions(options);
const { createServer } = await import('./chunks/dep-BWEMV5Th.js').then(function (n) { return n.M; });
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
server: cleanGlobalCLIOptions(options)
});
if (!server.httpServer) {
throw new Error("HTTP server not available");
}
return v;
};
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('--base <path>', `[string] public base path (default: /)`, {
type: [convertBase],
})
.option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
.option('-f, --filter <filter>', `[string] filter debug logs`)
.option('-m, --mode <mode>', `[string] set env mode`);
// dev
cli
.command('[root]', 'start dev server') // default command
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port <port>', `[number] specify port`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
.action(async (root, options) => {
filterDuplicateOptions(options);
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await import('./chunks/dep-DXWVQosX.js').then(function (n) { return n.M; });
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
server: cleanGlobalCLIOptions(options),
});
if (!server.httpServer) {
throw new Error('HTTP server not available');
}
await server.listen();
const info = server.config.logger.info;
const viteStartTime = global.__vite_start_time ?? false;
const startupDurationString = viteStartTime
? colors.dim(`ready in ${colors.reset(colors.bold(Math.ceil(performance.now() - viteStartTime)))} ms`)
: '';
const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
info(`\n ${colors.green(`${colors.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, {
clear: !hasExistingLogs,
});
server.printUrls();
const customShortcuts = [];
if (profileSession) {
customShortcuts.push({
key: 'p',
description: 'start/stop the profiler',
async action(server) {
if (profileSession) {
await stopProfiler(server.config.logger.info);
}
else {
const inspector = await import('node:inspector').then((r) => r.default);
await new Promise((res) => {
profileSession = new inspector.Session();
profileSession.connect();
profileSession.post('Profiler.enable', () => {
profileSession.post('Profiler.start', () => {
server.config.logger.info('Profiler started');
res();
});
});
});
}
},
await server.listen();
const info = server.config.logger.info;
const viteStartTime = global.__vite_start_time ?? false;
const startupDurationString = viteStartTime ? colors.dim(
`ready in ${colors.reset(
colors.bold(Math.ceil(performance.now() - viteStartTime))
)} ms`
) : "";
const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
info(
`
${colors.green(
`${colors.bold("VITE")} v${VERSION}`
)} ${startupDurationString}
`,
{
clear: !hasExistingLogs
}
);
server.printUrls();
const customShortcuts = [];
if (profileSession) {
customShortcuts.push({
key: "p",
description: "start/stop the profiler",
async action(server2) {
if (profileSession) {
await stopProfiler(server2.config.logger.info);
} else {
const inspector = await import('node:inspector').then(
(r) => r.default
);
await new Promise((res) => {
profileSession = new inspector.Session();
profileSession.connect();
profileSession.post("Profiler.enable", () => {
profileSession.post("Profiler.start", () => {
server2.config.logger.info("Profiler started");
res();
});
});
});
}
}
server.bindCLIShortcuts({ print: true, customShortcuts });
});
}
catch (e) {
const logger = createLogger(options.logLevel);
logger.error(colors.red(`error when starting dev server:\n${e.stack}`), {
error: e,
});
stopProfiler(logger.info);
process.exit(1);
}
server.bindCLIShortcuts({ print: true, customShortcuts });
} catch (e) {
const logger = createLogger(options.logLevel);
logger.error(colors.red(`error when starting dev server:
${e.stack}`), {
error: e
});
stopProfiler(logger.info);
process.exit(1);
}
});
// build
cli
.command('build [root]', 'build for production')
.option('--target <target>', `[string] transpile target (default: 'modules')`)
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.option('--assetsDir <dir>', `[string] directory under outDir to place assets in (default: assets)`)
.option('--assetsInlineLimit <number>', `[number] static asset base64 inline threshold in bytes (default: 4096)`)
.option('--ssr [entry]', `[string] build specified entry for server-side rendering`)
.option('--sourcemap [output]', `[boolean | "inline" | "hidden"] output source maps for build (default: false)`)
.option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` +
`or specify minifier to use (default: esbuild)`)
.option('--manifest [name]', `[boolean | string] emit build manifest json`)
.option('--ssrManifest [name]', `[boolean | string] emit ssr manifest json`)
.option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
.option('--environment [name]', `[string] build a single environment`)
.option('--app', `[boolean] same as builder.entireApp`)
.action(async (root, options) => {
cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option(
"--assetsDir <dir>",
`[string] directory under outDir to place assets in (default: assets)`
).option(
"--assetsInlineLimit <number>",
`[number] static asset base64 inline threshold in bytes (default: 4096)`
).option(
"--ssr [entry]",
`[string] build specified entry for server-side rendering`
).option(
"--sourcemap [output]",
`[boolean | "inline" | "hidden"] output source maps for build (default: false)`
).option(
"--minify [minifier]",
`[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
).option("--manifest [name]", `[boolean | string] emit build manifest json`).option("--ssrManifest [name]", `[boolean | string] emit ssr manifest json`).option(
"--emptyOutDir",
`[boolean] force empty outDir when it's outside of root`
).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--environment [name]", `[string] build a single environment`).option("--app", `[boolean] same as builder.entireApp`).action(
async (root, options) => {
filterDuplicateOptions(options);
const { createBuilder, buildEnvironment } = await import('./chunks/dep-DXWVQosX.js').then(function (n) { return n.N; });
const buildOptions = cleanGlobalCLIOptions(cleanBuilderCLIOptions(options));
const { createBuilder, buildEnvironment } = await import('./chunks/dep-BWEMV5Th.js').then(function (n) { return n.N; });
const buildOptions = cleanGlobalCLIOptions(
cleanBuilderCLIOptions(options)
);
const config = {
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions,
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions
};
try {
const builder = await createBuilder(config);
// TODO: Backward compatibility with lib and single environment build
// Ideally we would move to only building the entire app with this command
if (builder.config.build.lib) {
await buildEnvironment(builder.config, builder.environments.client, builder.config.build.lib);
}
else if (builder.config.builder.entireApp || options.app) {
await builder.buildApp();
}
else {
const ssr = !!builder.config.build.ssr;
const environment = builder.environments[ssr ? 'ssr' : 'client'];
await builder.build(environment);
}
const builder = await createBuilder(config);
if (builder.config.build.lib) {
await buildEnvironment(
builder.config,
builder.environments.client,
builder.config.build.lib
);
} else if (builder.config.builder.entireApp || options.app) {
await builder.buildApp();
} else {
const ssr = !!builder.config.build.ssr;
const environment = builder.environments[ssr ? "ssr" : "client"];
await builder.build(environment);
}
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error during build:
${e.stack}`),
{ error: e }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
catch (e) {
createLogger(options.logLevel).error(colors.red(`error during build:\n${e.stack}`), { error: e });
process.exit(1);
}
finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
});
// optimize
cli
.command('optimize [root]', 'pre-bundle dependencies')
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
.action(async (root, options) => {
}
);
cli.command("optimize [root]", "pre-bundle dependencies").option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(
async (root, options) => {
filterDuplicateOptions(options);
const { optimizeDeps } = await import('./chunks/dep-DXWVQosX.js').then(function (n) { return n.L; });
const { optimizeDeps } = await import('./chunks/dep-BWEMV5Th.js').then(function (n) { return n.L; });
try {
const config = await resolveConfig({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
mode: options.mode,
}, 'serve');
await optimizeDeps(config, options.force, true);
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
mode: options.mode
},
"serve"
);
await optimizeDeps(config, options.force, true);
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when optimizing deps:
${e.stack}`),
{ error: e }
);
process.exit(1);
}
catch (e) {
createLogger(options.logLevel).error(colors.red(`error when optimizing deps:\n${e.stack}`), { error: e });
process.exit(1);
}
});
// preview
cli
.command('preview [root]', 'locally preview production build')
.option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port <port>', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.action(async (root, options) => {
}
);
cli.command("preview [root]", "locally preview production build").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--open [path]", `[boolean | string] open browser on startup`).option("--outDir <dir>", `[string] output directory (default: dist)`).action(
async (root, options) => {
filterDuplicateOptions(options);
const { preview } = await import('./chunks/dep-DXWVQosX.js').then(function (n) { return n.O; });
const { preview } = await import('./chunks/dep-BWEMV5Th.js').then(function (n) { return n.O; });
try {
const server = await preview({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
mode: options.mode,
build: {
outDir: options.outDir,
},
preview: {
port: options.port,
strictPort: options.strictPort,
host: options.host,
open: options.open,
},
});
server.printUrls();
server.bindCLIShortcuts({ print: true });
const server = await preview({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
mode: options.mode,
build: {
outDir: options.outDir
},
preview: {
port: options.port,
strictPort: options.strictPort,
host: options.host,
open: options.open
}
});
server.printUrls();
server.bindCLIShortcuts({ print: true });
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when starting preview server:
${e.stack}`),
{ error: e }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
catch (e) {
createLogger(options.logLevel).error(colors.red(`error when starting preview server:\n${e.stack}`), { error: e });
process.exit(1);
}
finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
});
}
);
cli.help();

@@ -951,0 +941,0 @@ cli.version(VERSION);

@@ -5,63 +5,64 @@ import path, { resolve } from 'node:path';

const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)).toString());
const { version } = JSON.parse(
readFileSync(new URL("../../package.json", import.meta.url)).toString()
);
const ROLLUP_HOOKS = [
'buildStart',
'buildEnd',
'renderStart',
'renderError',
'renderChunk',
'writeBundle',
'generateBundle',
'banner',
'footer',
'augmentChunkHash',
'outputOptions',
'renderDynamicImport',
'resolveFileUrl',
'resolveImportMeta',
'intro',
'outro',
'closeBundle',
'closeWatcher',
'load',
'moduleParsed',
'watchChange',
'resolveDynamicImport',
'resolveId',
'shouldTransformCachedModule',
'transform',
"buildStart",
"buildEnd",
"renderStart",
"renderError",
"renderChunk",
"writeBundle",
"generateBundle",
"banner",
"footer",
"augmentChunkHash",
"outputOptions",
"renderDynamicImport",
"resolveFileUrl",
"resolveImportMeta",
"intro",
"outro",
"closeBundle",
"closeWatcher",
"load",
"moduleParsed",
"watchChange",
"resolveDynamicImport",
"resolveId",
"shouldTransformCachedModule",
"transform"
];
const VERSION = version;
const DEFAULT_MAIN_FIELDS = [
'browser',
'module',
'jsnext:main',
'jsnext',
"browser",
"module",
"jsnext:main",
// moment still uses this...
"jsnext"
];
// Baseline support browserslist
// "defaults and supports es6-module and supports es6-module-dynamic-import"
// Higher browser versions may be needed for extra features.
const ESBUILD_MODULES_TARGET = [
'es2020',
'edge88',
'firefox78',
'chrome87',
'safari14',
"es2020",
// support import.meta.url
"edge88",
"firefox78",
"chrome87",
"safari14"
];
const DEFAULT_EXTENSIONS = [
'.mjs',
'.js',
'.mts',
'.ts',
'.jsx',
'.tsx',
'.json',
".mjs",
".js",
".mts",
".ts",
".jsx",
".tsx",
".json"
];
const DEFAULT_CONFIG_FILES = [
'vite.config.js',
'vite.config.mjs',
'vite.config.ts',
'vite.config.cjs',
'vite.config.mts',
'vite.config.cts',
"vite.config.js",
"vite.config.mjs",
"vite.config.ts",
"vite.config.cjs",
"vite.config.mts",
"vite.config.cts"
];

@@ -72,5 +73,2 @@ const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;

const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
/**
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
*/
const FS_PREFIX = `/@fs/`;

@@ -80,60 +78,59 @@ const CLIENT_PUBLIC_PATH = `/@vite/client`;

const VITE_PACKAGE_DIR = resolve(
// import.meta.url is `dist/node/constants.js` after bundle
fileURLToPath(import.meta.url), '../../..');
const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs');
const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs');
// import.meta.url is `dist/node/constants.js` after bundle
fileURLToPath(import.meta.url),
"../../.."
);
const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
// ** READ THIS ** before editing `KNOWN_ASSET_TYPES`.
// If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it
// to the TypeScript declaration file `packages/vite/client.d.ts` and
// add a mime type to the `registerCustomMime` in
// `packages/vite/src/node/plugin/assets.ts` if mime type cannot be
// looked up by mrmime.
const KNOWN_ASSET_TYPES = [
// images
'apng',
'png',
'jpe?g',
'jfif',
'pjpeg',
'pjp',
'gif',
'svg',
'ico',
'webp',
'avif',
// media
'mp4',
'webm',
'ogg',
'mp3',
'wav',
'flac',
'aac',
'opus',
'mov',
'm4a',
'vtt',
// fonts
'woff2?',
'eot',
'ttf',
'otf',
// other
'webmanifest',
'pdf',
'txt',
// images
"apng",
"bmp",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
// media
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"opus",
"mov",
"m4a",
"vtt",
// fonts
"woff2?",
"eot",
"ttf",
"otf",
// other
"webmanifest",
"pdf",
"txt"
];
const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
const DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`
);
const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
const loopbackHosts = new Set([
'localhost',
'127.0.0.1',
'::1',
'0000:0000:0000:0000:0000:0000:0000:0001',
const loopbackHosts = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"::1",
"0000:0000:0000:0000:0000:0000:0000:0001"
]);
const wildcardHosts = new Set([
'0.0.0.0',
'::',
'0000:0000:0000:0000:0000:0000:0000:0000',
const wildcardHosts = /* @__PURE__ */ new Set([
"0.0.0.0",
"::",
"0000:0000:0000:0000:0000:0000:0000:0000"
]);

@@ -143,4 +140,4 @@ const DEFAULT_DEV_PORT = 5173;

const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
const METADATA_FILENAME = '_metadata.json';
const METADATA_FILENAME = "_metadata.json";
export { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, CSS_LANGS_RE, DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_DEV_PORT, DEFAULT_EXTENSIONS, DEFAULT_MAIN_FIELDS, DEFAULT_PREVIEW_PORT, DEP_VERSION_RE, ENV_ENTRY, ENV_PUBLIC_PATH, ESBUILD_MODULES_TARGET, FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES, METADATA_FILENAME, OPTIMIZABLE_ENTRY_RE, ROLLUP_HOOKS, SPECIAL_QUERY_RE, VERSION, VITE_PACKAGE_DIR, loopbackHosts, wildcardHosts };
export { parseAst, parseAstAsync } from 'rollup/parseAst';
import { i as isInNodeModules, a as arraify } from './chunks/dep-DXWVQosX.js';
export { B as BuildEnvironment, D as DevEnvironment, S as ServerHMRConnector, b as build, j as buildErrorMessage, e as createBuilder, x as createFilter, f as createIdResolver, A as createLogger, k as createNodeDevEnvironment, c as createServer, n as createServerModuleRunner, d as defineConfig, m as fetchModule, g as formatPostcssSourceMap, F as isFileLoadingAllowed, E as isFileServingAllowed, l as loadConfigFromFile, G as loadEnv, w as mergeAlias, v as mergeConfig, q as moduleRunnerTransform, u as normalizePath, o as optimizeDeps, h as preprocessCSS, p as preview, r as resolveConfig, H as resolveEnvPrefix, y as rollupVersion, C as searchForWorkspaceRoot, z as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-DXWVQosX.js';
import { i as isInNodeModules, a as arraify } from './chunks/dep-BWEMV5Th.js';
export { B as BuildEnvironment, D as DevEnvironment, S as ServerHMRConnector, b as build, j as buildErrorMessage, e as createBuilder, x as createFilter, f as createIdResolver, A as createLogger, k as createNodeDevEnvironment, c as createServer, n as createServerModuleRunner, d as defineConfig, m as fetchModule, g as formatPostcssSourceMap, F as isFileLoadingAllowed, E as isFileServingAllowed, l as loadConfigFromFile, G as loadEnv, w as mergeAlias, v as mergeConfig, q as moduleRunnerTransform, u as normalizePath, o as optimizeDeps, h as preprocessCSS, p as preview, r as resolveConfig, H as resolveEnvPrefix, y as rollupVersion, C as searchForWorkspaceRoot, z as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-BWEMV5Th.js';
export { VERSION as version } from './constants.js';

@@ -16,4 +16,5 @@ export { version as esbuildVersion } from 'esbuild';

import 'fs';
import 'events';
import 'assert';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';

@@ -24,2 +25,3 @@ import 'node:http';

import 'net';
import 'events';
import 'url';

@@ -38,3 +40,2 @@ import 'http';

import 'node:worker_threads';
import 'node:events';
import 'crypto';

@@ -48,159 +49,140 @@ import 'querystring';

import 'tls';
import 'assert';
import 'node:zlib';
// This file will be built for both ESM and CJS. Avoid relying on other modules as possible.
// copy from constants.ts
const CSS_LANGS_RE =
// eslint-disable-next-line regexp/no-unused-capturing-group
/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
const CSS_LANGS_RE = (
// eslint-disable-next-line regexp/no-unused-capturing-group
/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
);
const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
// Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7
// We don't recommend using this strategy as a general solution moving forward
// splitVendorChunk is a simple index/vendor strategy that was used in Vite
// until v2.8. It is exposed to let people continue to use it in case it was
// working well for their setups.
// The cache needs to be reset on buildStart for watch mode to work correctly
// Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife'
/**
* @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
*/
class SplitVendorChunkCache {
cache;
constructor() {
this.cache = new Map();
}
reset() {
this.cache = new Map();
}
cache;
constructor() {
this.cache = /* @__PURE__ */ new Map();
}
reset() {
this.cache = /* @__PURE__ */ new Map();
}
}
/**
* @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
*/
function splitVendorChunk(options = {}) {
const cache = options.cache ?? new SplitVendorChunkCache();
return (id, { getModuleInfo }) => {
if (isInNodeModules(id) &&
!isCSSRequest(id) &&
staticImportedByEntry(id, getModuleInfo, cache.cache)) {
return 'vendor';
}
};
const cache = options.cache ?? new SplitVendorChunkCache();
return (id, { getModuleInfo }) => {
if (isInNodeModules(id) && !isCSSRequest(id) && staticImportedByEntry(id, getModuleInfo, cache.cache)) {
return "vendor";
}
};
}
function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
if (cache.has(id)) {
return cache.get(id);
}
if (importStack.includes(id)) {
// circular deps!
cache.set(id, false);
return false;
}
const mod = getModuleInfo(id);
if (!mod) {
cache.set(id, false);
return false;
}
if (mod.isEntry) {
cache.set(id, true);
return true;
}
const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
cache.set(id, someImporterIs);
return someImporterIs;
if (cache.has(id)) {
return cache.get(id);
}
if (importStack.includes(id)) {
cache.set(id, false);
return false;
}
const mod = getModuleInfo(id);
if (!mod) {
cache.set(id, false);
return false;
}
if (mod.isEntry) {
cache.set(id, true);
return true;
}
const someImporterIs = mod.importers.some(
(importer) => staticImportedByEntry(
importer,
getModuleInfo,
cache,
importStack.concat(id)
)
);
cache.set(id, someImporterIs);
return someImporterIs;
}
/**
* @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
*/
function splitVendorChunkPlugin() {
const caches = [];
function createSplitVendorChunk(output, config) {
const cache = new SplitVendorChunkCache();
caches.push(cache);
const build = config.build ?? {};
const format = output?.format;
if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') {
return splitVendorChunk({ cache });
}
const caches = [];
function createSplitVendorChunk(output, config) {
const cache = new SplitVendorChunkCache();
caches.push(cache);
const build = config.build ?? {};
const format = output?.format;
if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
return splitVendorChunk({ cache });
}
return {
name: 'vite:split-vendor-chunk',
config(config) {
let outputs = config?.build?.rollupOptions?.output;
if (outputs) {
outputs = arraify(outputs);
for (const output of outputs) {
const viteManualChunks = createSplitVendorChunk(output, config);
if (viteManualChunks) {
if (output.manualChunks) {
if (typeof output.manualChunks === 'function') {
const userManualChunks = output.manualChunks;
output.manualChunks = (id, api) => {
return userManualChunks(id, api) ?? viteManualChunks(id, api);
};
}
else {
// else, leave the object form of manualChunks untouched, as
// we can't safely replicate rollup handling.
// eslint-disable-next-line no-console
console.warn("(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead.");
}
}
else {
output.manualChunks = viteManualChunks;
}
}
}
}
else {
return {
build: {
rollupOptions: {
output: {
manualChunks: createSplitVendorChunk({}, config),
},
},
},
}
return {
name: "vite:split-vendor-chunk",
config(config) {
let outputs = config?.build?.rollupOptions?.output;
if (outputs) {
outputs = arraify(outputs);
for (const output of outputs) {
const viteManualChunks = createSplitVendorChunk(output, config);
if (viteManualChunks) {
if (output.manualChunks) {
if (typeof output.manualChunks === "function") {
const userManualChunks = output.manualChunks;
output.manualChunks = (id, api) => {
return userManualChunks(id, api) ?? viteManualChunks(id, api);
};
} else {
console.warn(
"(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."
);
}
} else {
output.manualChunks = viteManualChunks;
}
},
buildStart() {
caches.forEach((cache) => cache.reset());
},
};
}
}
} else {
return {
build: {
rollupOptions: {
output: {
manualChunks: createSplitVendorChunk({}, config)
}
}
}
};
}
},
buildStart() {
caches.forEach((cache) => cache.reset());
}
};
}
class RemoteEnvironmentTransport {
options;
constructor(options) {
this.options = options;
}
register(environment) {
this.options.onMessage(async (data) => {
if (typeof data !== 'object' || !data || !data.__v)
return;
const method = data.m;
const parameters = data.a;
try {
const result = await environment[method](...parameters);
this.options.send({
__v: true,
r: result,
i: data.i,
});
}
catch (error) {
this.options.send({
__v: true,
e: {
name: error.name,
message: error.message,
stack: error.stack,
},
i: data.i,
});
}
constructor(options) {
this.options = options;
}
register(environment) {
this.options.onMessage(async (data) => {
if (typeof data !== "object" || !data || !data.__v) return;
const method = data.m;
const parameters = data.a;
try {
const result = await environment[method](...parameters);
this.options.send({
__v: true,
r: result,
i: data.i
});
}
} catch (error) {
this.options.send({
__v: true,
e: {
name: error.name,
message: error.message,
stack: error.stack
},
i: data.i
});
}
});
}
}
export { RemoteEnvironmentTransport, isCSSRequest, splitVendorChunk, splitVendorChunkPlugin };

@@ -125,2 +125,3 @@ import { ModuleNamespace, ViteHotContext } from '../../types/hot.js';

private readonly resetSourceMapSupport?;
private readonly root;
private destroyed;

@@ -147,2 +148,4 @@ constructor(options: ModuleRunnerOptions, evaluator: ModuleEvaluator, debug?: ModuleRunnerDebugger | undefined);

private processImport;
private isCircularModule;
private isCircularImport;
private cachedRequest;

@@ -149,0 +152,0 @@ private cachedModule;

@@ -78,3 +78,7 @@ const VALID_ID_PREFIX = "/@id/", NULL_BYTE_PLACEHOLDER = "__x00__";

return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
}, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), CHAR_FORWARD_SLASH = 47, CHAR_BACKWARD_SLASH = 92, percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
};
function normalizeAbsoluteUrl(url, root) {
return url = slash(url), url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url.startsWith(root) && (url = url.slice(root.length - 1)), url;
}
const decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), CHAR_FORWARD_SLASH = 47, CHAR_BACKWARD_SLASH = 92, percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
function encodePathChars(filepath) {

@@ -202,3 +206,9 @@ return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf(`

class DecodedMap {
map;
constructor(map, from) {
this.map = map;
const { mappings, names, sources } = map;
this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map(
(s) => posixResolve(s || "", from)
);
}
_encoded;

@@ -211,7 +221,2 @@ _decoded;

resolvedSources;
constructor(map, from) {
this.map = map;
const { mappings, names, sources } = map;
this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map((s) => posixResolve(s || "", from));
}
}

@@ -229,3 +234,5 @@ function memoizedState() {

}
const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(
`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
);
class ModuleCacheMap extends Map {

@@ -282,4 +289,3 @@ root;

const id = this.normalize(_id);
if (invalidated.has(id))
continue;
if (invalidated.has(id)) continue;
invalidated.add(id);

@@ -297,4 +303,3 @@ const mod = super.get(id);

const id = this.normalize(_id);
if (invalidated.has(id))
continue;
if (invalidated.has(id)) continue;
invalidated.add(id);

@@ -308,9 +313,8 @@ const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);

const mod = this.get(moduleId);
if (mod.map)
return mod.map;
if (!mod.meta || !("code" in mod.meta))
return null;
const mapString = mod.meta.code.match(MODULE_RUNNER_SOURCEMAPPING_REGEXP)?.[1];
if (!mapString)
return null;
if (mod.map) return mod.map;
if (!mod.meta || !("code" in mod.meta)) return null;
const mapString = mod.meta.code.match(
MODULE_RUNNER_SOURCEMAPPING_REGEXP
)?.[1];
if (!mapString) return null;
const baseFile = mod.meta.file || moduleId.split("?")[0];

@@ -320,6 +324,5 @@ return mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), baseFile), mod.map;

}
const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test"]);
const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test", "node:sqlite"]);
function normalizeModuleId(file, root) {
if (prefixedBuiltins.has(file))
return file;
if (prefixedBuiltins.has(file)) return file;
let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");

@@ -329,5 +332,2 @@ return unixFile.startsWith(root) && (unixFile = unixFile.slice(root.length - 1)), unixFile.replace(/^file:\//, "/");

class HMRContext {
hmrClient;
ownerPath;
newListeners;
constructor(hmrClient, ownerPath) {

@@ -341,6 +341,10 @@ this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});

const listeners = hmrClient.customListenersMap.get(event);
listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
listeners && hmrClient.customListenersMap.set(
event,
listeners.filter((l) => !staleFns.includes(l))
);
}
this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
}
newListeners;
get data() {

@@ -381,3 +385,5 @@ return this.hmrClient.dataMap.get(this.ownerPath);

message
}), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
}), this.hmrClient.logger.debug(
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
);
}

@@ -406,3 +412,5 @@ on(event, cb) {

send(event, data) {
this.hmrClient.messenger.send(JSON.stringify({ type: "custom", event, data }));
this.hmrClient.messenger.send(
JSON.stringify({ type: "custom", event, data })
);
}

@@ -422,3 +430,2 @@ acceptDeps(deps, callback = () => {

class HMRMessenger {
connection;
constructor(connection) {

@@ -436,4 +443,5 @@ this.connection = connection;

class HMRClient {
logger;
importUpdatedModule;
constructor(logger, connection, importUpdatedModule) {
this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
}
hotModulesMap = /* @__PURE__ */ new Map();

@@ -446,5 +454,2 @@ disposeMap = /* @__PURE__ */ new Map();

messenger;
constructor(logger, connection, importUpdatedModule) {
this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
}
async notifyListeners(event, data) {

@@ -461,7 +466,8 @@ const cbs = this.customListenersMap.get(event);

async prunePaths(paths) {
await Promise.all(paths.map((path) => {
const disposer = this.disposeMap.get(path);
if (disposer)
return disposer(this.dataMap.get(path));
})), paths.forEach((path) => {
await Promise.all(
paths.map((path) => {
const disposer = this.disposeMap.get(path);
if (disposer) return disposer(this.dataMap.get(path));
})
), paths.forEach((path) => {
const fn = this.pruneMap.get(path);

@@ -472,3 +478,5 @@ fn && fn(this.dataMap.get(path));

warnFailedUpdate(err, path) {
err.message.includes("fetch") || this.logger.error(err), this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
err.message.includes("fetch") || this.logger.error(err), this.logger.error(
`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}

@@ -494,3 +502,5 @@ updateQueue = [];

let fetchedModule;
const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(
({ deps }) => deps.includes(acceptedPath)
);
if (isSelfUpdate || qualifiedCallbacks.length > 0) {

@@ -507,3 +517,5 @@ const disposer = this.disposeMap.get(acceptedPath);

for (const { deps, fn } of qualifiedCallbacks)
fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;

@@ -519,3 +531,5 @@ this.logger.debug(`hot updated: ${loggedPath}`);

const lastBinding = missingBindings[missingBindings.length - 1];
throw moduleType === "module" ? new SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`) : new SyntaxError(`[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
throw moduleType === "module" ? new SyntaxError(
`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
) : new SyntaxError(`[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

@@ -549,7 +563,9 @@

case "update":
await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
if (update.type === "js-update")
return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
hmrClient.logger.error("css hmr is not supported in runner mode.");
})), await hmrClient.notifyListeners("vite:afterUpdate", payload);
await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
payload.updates.map(async (update) => {
if (update.type === "js-update")
return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
hmrClient.logger.error("css hmr is not supported in runner mode.");
})
), await hmrClient.notifyListeners("vite:afterUpdate", payload);
break;

@@ -561,5 +577,7 @@ case "custom": {

case "full-reload": {
const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
if (!clearEntrypoints.size)
break;
const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? getModulesEntrypoints(
runner,
getModulesByFile(runner, slash(triggeredBy))
) : findAllEntrypoints(runner);
if (!clearEntrypoints.size) break;
hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.moduleCache.clear();

@@ -576,5 +594,7 @@ for (const id of clearEntrypoints)

const err = payload.err;
hmrClient.logger.error(`Internal Server Error
hmrClient.logger.error(
`Internal Server Error
${err.message}
${err.stack}`);
${err.stack}`
);
break;

@@ -615,4 +635,3 @@ }

for (const moduleId of modules) {
if (visited.has(moduleId))
continue;
if (visited.has(moduleId)) continue;
visited.add(moduleId);

@@ -637,7 +656,8 @@ const module = runner.moduleCache.getByModuleId(moduleId);

const result = handler(...args);
if (result)
return result;
if (result) return result;
}
return null;
}, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
}, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
retrieveSourceMapHandlers
);
let overridden = !1;

@@ -652,4 +672,3 @@ const originalPrepare = Error.prepareStackTrace;

function supportRelativeURL(file, url) {
if (!file)
return url;
if (!file) return url;
const dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir);

@@ -673,4 +692,3 @@ let protocol = match ? match[0] : "";

function retrieveFile(path) {
if (path in fileContentsCache)
return fileContentsCache[path];
if (path in fileContentsCache) return fileContentsCache[path];
const content = retrieveFileFromHandlers(path);

@@ -681,8 +699,6 @@ return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;

const fileData = retrieveFile(source);
if (!fileData)
return null;
if (!fileData) return null;
const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
let lastMatch, match;
for (; match = re.exec(fileData); )
lastMatch = match;
for (; match = re.exec(fileData); ) lastMatch = match;
return lastMatch ? lastMatch[1] : null;

@@ -693,7 +709,5 @@ }

const urlAndMap = retrieveSourceMapFromHandlers(source);
if (urlAndMap)
return urlAndMap;
if (urlAndMap) return urlAndMap;
let sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL)
return null;
if (!sourceMappingURL) return null;
let sourceMapData;

@@ -711,4 +725,3 @@ if (reSourceMap.test(sourceMappingURL)) {

function mapSourcePosition(position) {
if (!position.source)
return position;
if (!position.source) return position;
let sourceMap = getRunnerSourceMap(position);

@@ -721,3 +734,6 @@ if (sourceMap || (sourceMap = sourceMapCache[position.source]), !sourceMap) {

url,
map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
map: new DecodedMap(
typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map,
url
)
};

@@ -741,3 +757,6 @@ const contents = sourceMap.map?.map.sourcesContent;

if (originalPosition && originalPosition.source != null)
return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
return originalPosition.source = supportRelativeURL(
sourceMap.url,
originalPosition.source
), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
}

@@ -776,3 +795,5 @@ return position;

const isConstructor = this.isConstructor();
if (!(this.isToplevel() || isConstructor)) {
if (this.isToplevel() || isConstructor)
isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
else {
let typeName = this.getTypeName();

@@ -782,3 +803,3 @@ typeName === "[object Object]" && (typeName = "null");

functionName ? (typeName && functionName.indexOf(typeName) !== 0 && (line += `${typeName}.`), line += functionName, methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1 && (line += ` [as ${methodName}]`)) : line += `${typeName}.${methodName || "<anonymous>"}`;
} else isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
}
return addSuffix && (line += ` (${fileLocation})`), line;

@@ -840,14 +861,27 @@ }

if (typeof process > "u")
throw new TypeError(`Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`);
throw new TypeError(
`Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`
);
if (typeof process.setSourceMapsEnabled != "function")
throw new TypeError(`Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`);
throw new TypeError(
`Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`
);
const isEnabledAlready = process.sourceMapsEnabled ?? !1;
return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
}
return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
return interceptStackTrace(
runner,
typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0
);
}
class ModuleRunner {
options;
evaluator;
debug;
constructor(options, evaluator, debug) {
this.options = options, this.evaluator = evaluator, this.debug = debug;
const root = this.options.root;
this.root = root[root.length - 1] === "/" ? root : `${root}/`, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), this.transport = options.transport, typeof options.hmr == "object" && (this.hmrClient = new HMRClient(
options.hmr.logger === !1 ? silentConsole : options.hmr.logger || hmrLogger,
options.hmr.connection,
({ acceptedPath }) => this.import(acceptedPath)
), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
}
/**

@@ -863,3 +897,5 @@ * Holds the cache of modules

get(_, p) {
throw new Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
throw new Error(
`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`
);
}

@@ -869,6 +905,4 @@ });

resetSourceMapSupport;
root;
destroyed = !1;
constructor(options, evaluator, debug) {
this.options = options, this.evaluator = evaluator, this.debug = debug, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), this.transport = options.transport, typeof options.hmr == "object" && (this.hmrClient = new HMRClient(options.hmr.logger === !1 ? silentConsole : options.hmr.logger || hmrLogger, options.hmr.connection, ({ acceptedPath }) => this.import(acceptedPath)), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
}
/**

@@ -905,7 +939,3 @@ * URL to execute. Accepts file path, server path or id relative to the root.

normalizeEntryUrl(url) {
if (url[0] === ".")
return url;
url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url = slash(url);
const _root = this.options.root, root = _root[_root.length - 1] === "/" ? _root : `${_root}/`;
return url.startsWith(root) ? url.slice(root.length - 1) : url[0] === "/" ? url : wrapId(url);
return url[0] === "." ? url : (url = normalizeAbsoluteUrl(url, this.root), url[0] === "/" ? url : wrapId(url));
}

@@ -918,5 +948,25 @@ processImport(exports, fetchResult, metadata) {

}
async cachedRequest(id, mod, callstack = [], metadata) {
const meta = mod.meta, moduleId = meta.id, { imports, importers } = mod, importee = callstack[callstack.length - 1];
if (importee && importers.add(importee), (callstack.includes(moduleId) || Array.from(imports.values()).some((i) => importers.has(i))) && mod.exports)
isCircularModule(mod) {
for (const importedFile of mod.imports)
if (mod.importers.has(importedFile))
return !0;
return !1;
}
isCircularImport(importers, moduleId, visited = /* @__PURE__ */ new Set()) {
for (const importer of importers) {
if (visited.has(importer))
continue;
if (visited.add(importer), importer === moduleId)
return !0;
const mod = this.moduleCache.getByModuleId(
importer
);
if (mod.importers.size && this.isCircularImport(mod.importers, moduleId, visited))
return !0;
}
return !1;
}
async cachedRequest(id, mod_, callstack = [], metadata) {
const mod = mod_, meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports)
return this.processImport(mod.exports, meta, metadata);

@@ -928,4 +978,6 @@ let debugTimer;

`)}`;
this.debug(`[module runner] module ${moduleId} takes over 2s to load.
${getStack()}`);
this.debug(
`[module runner] module ${moduleId} takes over 2s to load.
${getStack()}`
);
}, 2e3));

@@ -944,3 +996,3 @@ try {

throw new Error("Vite module runner has been destroyed.");
this.debug?.("[module runner] fetching", url);
this.debug?.("[module runner] fetching", url), url = normalizeAbsoluteUrl(url, this.root);
const normalized = this.urlToIdMap.get(url);

@@ -957,3 +1009,5 @@ let cachedModule = normalized && this.moduleCache.getByModuleId(normalized);

if (!cachedModule || !cachedModule.meta)
throw new Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
throw new Error(
`Module "${url}" was mistakenly invalidated during fetch phase.`
);
return cachedModule;

@@ -983,3 +1037,5 @@ }

const importer = callstack[callstack.length - 2];
throw new Error(`[module runner] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`);
throw new Error(
`[module runner] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`
);
}

@@ -992,3 +1048,5 @@ const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {

resolve(id2, parent) {
throw new Error('[module runner] "import.meta.resolve" is not supported.');
throw new Error(
'[module runner] "import.meta.resolve" is not supported.'
);
},

@@ -1051,3 +1109,9 @@ // should be replaced during transformation

'"use strict";' + code
)(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey]), Object.seal(context[ssrModuleExportsKey]);
)(
context[ssrModuleExportsKey],
context[ssrImportMetaKey],
context[ssrImportKey],
context[ssrDynamicImportKey],
context[ssrExportAllKey]
), Object.seal(context[ssrModuleExportsKey]);
}

@@ -1059,8 +1123,5 @@ runExternalModule(filepath) {

class RemoteRunnerTransport {
options;
rpcPromises = /* @__PURE__ */ new Map();
constructor(options) {
this.options = options, this.options.onMessage(async (data) => {
if (typeof data != "object" || !data || !data.__v)
return;
if (typeof data != "object" || !data || !data.__v) return;
const promise = this.rpcPromises.get(data.i);

@@ -1070,2 +1131,3 @@ promise && (promise.timeoutId && clearTimeout(promise.timeoutId), this.rpcPromises.delete(data.i), data.e ? promise.reject(data.e) : promise.resolve(data.r));

}
rpcPromises = /* @__PURE__ */ new Map();
resolve(method, ...args) {

@@ -1082,3 +1144,7 @@ const promiseId = nanoid();

timeout > 0 && (timeoutId = setTimeout(() => {
this.rpcPromises.delete(promiseId), reject(new Error(`${method}(${args.map((arg) => JSON.stringify(arg)).join(", ")}) timed out after ${timeout}ms`));
this.rpcPromises.delete(promiseId), reject(
new Error(
`${method}(${args.map((arg) => JSON.stringify(arg)).join(", ")}) timed out after ${timeout}ms`
)
);
}, timeout), timeoutId?.unref?.()), this.rpcPromises.set(promiseId, { resolve: resolve2, reject, timeoutId });

@@ -1094,4 +1160,3 @@ });

let id = "", i = size;
for (; i--; )
id += urlAlphabet[Math.random() * 64 | 0];
for (; i--; ) id += urlAlphabet[Math.random() * 64 | 0];
return id;

@@ -1098,0 +1163,0 @@ }

{
"name": "vite",
"version": "6.0.0-alpha.18",
"version": "6.0.0-alpha.19",
"type": "module",

@@ -76,3 +76,3 @@ "license": "MIT",

"esbuild": "^0.21.3",
"postcss": "^8.4.38",
"postcss": "^8.4.39",
"rollup": "^4.13.0"

@@ -85,11 +85,10 @@ },

"@ampproject/remapping": "^2.3.0",
"@babel/parser": "^7.24.6",
"@babel/parser": "^7.24.8",
"@jridgewell/trace-mapping": "^0.3.25",
"@polka/compression": "^1.0.0-next.25",
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-commonjs": "^25.0.8",
"@rollup/plugin-commonjs": "^26.0.1",
"@rollup/plugin-dynamic-import-vars": "^2.1.2",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "15.2.3",
"@rollup/plugin-typescript": "^11.1.6",
"@rollup/pluginutils": "^5.1.0",

@@ -109,3 +108,3 @@ "@types/escape-html": "^1.0.4",

"dotenv-expand": "^11.0.6",
"es-module-lexer": "^1.5.3",
"es-module-lexer": "^1.5.4",
"escape-html": "^1.0.3",

@@ -116,7 +115,7 @@ "estree-walker": "^3.0.3",

"http-proxy": "^1.18.1",
"launch-editor-middleware": "^2.6.1",
"launch-editor-middleware": "^2.8.0",
"lightningcss": "^1.25.1",
"magic-string": "^0.30.10",
"micromatch": "^4.0.7",
"mlly": "^1.7.0",
"mlly": "^1.7.1",
"mrmime": "^2.0.0",

@@ -135,4 +134,4 @@ "open": "^8.4.2",

"rollup-plugin-esbuild": "^6.1.1",
"rollup-plugin-license": "^3.4.0",
"sass": "^1.77.4",
"rollup-plugin-license": "^3.5.2",
"sass": "^1.77.8",
"sirv": "^2.0.4",

@@ -142,7 +141,7 @@ "source-map-support": "^0.5.21",

"strip-literal": "^2.1.0",
"tsconfck": "^3.1.0",
"tslib": "^2.6.2",
"tsconfck": "^3.1.1",
"tslib": "^2.6.3",
"types": "link:./types",
"ufo": "^1.5.3",
"ws": "^8.17.0"
"ufo": "^1.5.4",
"ws": "^8.18.0"
},

@@ -182,8 +181,8 @@ "peerDependencies": {

"scripts": {
"dev": "rimraf dist && pnpm run build-bundle -w",
"dev": "tsx scripts/dev.ts",
"build": "rimraf dist && run-s build-bundle build-types",
"build-bundle": "rollup --config rollup.config.ts --configPlugin typescript",
"build-bundle": "rollup --config rollup.config.ts --configPlugin esbuild",
"build-types": "run-s build-types-temp build-types-roll build-types-check",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp -p src/node",
"build-types-roll": "rollup --config rollup.dts.config.ts --configPlugin typescript && rimraf temp",
"build-types-roll": "rollup --config rollup.dts.config.ts --configPlugin esbuild && rimraf temp",
"build-types-check": "tsc --project tsconfig.check.json",

@@ -190,0 +189,0 @@ "typecheck": "tsc --noEmit && tsc --noEmit -p src/node",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc