full site update

This commit is contained in:
2025-07-24 18:46:24 +02:00
parent bfe2b90d8d
commit 37a6e0ab31
6912 changed files with 540482 additions and 361712 deletions

1113
node_modules/vite/LICENSE.md generated vendored

File diff suppressed because it is too large Load Diff

20
node_modules/vite/bin/vite.js generated vendored
View File

@@ -1,11 +1,16 @@
#!/usr/bin/env node
import { performance } from 'node:perf_hooks'
import module from 'node:module'
if (!import.meta.url.includes('node_modules')) {
try {
// only available as dev dependency
await import('source-map-support').then((r) => r.default.install())
} catch (e) {}
} catch {}
process.on('unhandledRejection', (err) => {
throw new Error('UNHANDLED PROMISE REJECTION', { cause: err })
})
}
global.__vite_start_time = performance.now()
@@ -41,6 +46,19 @@ if (debugIndex > 0) {
}
function start() {
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists
module.enableCompileCache?.()
// flush the cache after 10s because the cache is not flushed until process end
// for dev server, the cache is never flushed unless manually flushed because the process.exit is called
// also flushing the cache in SIGINT handler seems to cause the process to hang
setTimeout(() => {
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists
module.flushCompileCache?.()
} catch {}
}, 10 * 1000).unref()
} catch {}
return import('../dist/node/cli.js')
}

23
node_modules/vite/client.d.ts generated vendored
View File

@@ -102,6 +102,14 @@ declare module '*.avif' {
const src: string
export default src
}
declare module '*.cur' {
const src: string
export default src
}
declare module '*.jxl' {
const src: string
export default src
}
// media
declare module '*.mp4' {
@@ -247,6 +255,21 @@ declare module '*?inline' {
export default src
}
declare module '*?no-inline' {
const src: string
export default src
}
declare module '*?url&inline' {
const src: string
export default src
}
declare module '*?url&no-inline' {
const src: string
export default src
}
declare interface VitePreloadErrorEvent extends Event {
payload: Error
}

View File

@@ -56,13 +56,19 @@ class HMRContext {
decline() {
}
invalidate(message) {
const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
this.hmrClient.notifyListeners("vite:invalidate", {
path: this.ownerPath,
message
message,
firstInvalidatedBy
});
this.send("vite:invalidate", {
path: this.ownerPath,
message,
firstInvalidatedBy
});
this.send("vite:invalidate", { path: this.ownerPath, message });
this.hmrClient.logger.debug(
`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
);
}
on(event, cb) {
@@ -91,9 +97,7 @@ class HMRContext {
removeFromMap(this.newListeners);
}
send(event, data) {
this.hmrClient.messenger.send(
JSON.stringify({ type: "custom", event, data })
);
this.hmrClient.send({ type: "custom", event, data });
}
acceptDeps(deps, callback = () => {
}) {
@@ -108,25 +112,10 @@ class HMRContext {
this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
}
}
class HMRMessenger {
constructor(connection) {
this.connection = connection;
this.queue = [];
}
send(message) {
this.queue.push(message);
this.flush();
}
flush() {
if (this.connection.isReady()) {
this.queue.forEach((msg) => this.connection.send(msg));
this.queue = [];
}
}
}
class HMRClient {
constructor(logger, connection, importUpdatedModule) {
constructor(logger, transport, importUpdatedModule) {
this.logger = logger;
this.transport = transport;
this.importUpdatedModule = importUpdatedModule;
this.hotModulesMap = /* @__PURE__ */ new Map();
this.disposeMap = /* @__PURE__ */ new Map();
@@ -136,7 +125,6 @@ class HMRClient {
this.ctxToListenersMap = /* @__PURE__ */ new Map();
this.updateQueue = [];
this.pendingUpdateQueue = false;
this.messenger = new HMRMessenger(connection);
}
async notifyListeners(event, data) {
const cbs = this.customListenersMap.get(event);
@@ -144,6 +132,11 @@ class HMRClient {
await Promise.allSettled(cbs.map((cb) => cb(data)));
}
}
send(payload) {
this.transport.send(payload).catch((err) => {
this.logger.error(err);
});
}
clear() {
this.hotModulesMap.clear();
this.disposeMap.clear();
@@ -154,7 +147,7 @@ class HMRClient {
}
// After an HMR update, some modules are no longer imported on the page
// but they may have left behind side effects that need to be cleaned up
// (.e.g style injections)
// (e.g. style injections)
async prunePaths(paths) {
await Promise.all(
paths.map((path) => {
@@ -170,11 +163,11 @@ class HMRClient {
});
}
warnFailedUpdate(err, path) {
if (!err.message.includes("fetch")) {
if (!(err instanceof Error) || !err.message.includes("fetch")) {
this.logger.error(err);
}
this.logger.error(
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
/**
@@ -194,7 +187,7 @@ class HMRClient {
}
}
async fetchUpdate(update) {
const { path, acceptedPath } = update;
const { path, acceptedPath, firstInvalidatedBy } = update;
const mod = this.hotModulesMap.get(path);
if (!mod) {
return;
@@ -214,17 +207,320 @@ class HMRClient {
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
try {
this.currentFirstInvalidatedBy = firstInvalidatedBy;
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map(
(dep) => dep === acceptedPath ? fetchedModule : void 0
)
);
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
} finally {
this.currentFirstInvalidatedBy = void 0;
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`[vite] hot updated: ${loggedPath}`);
};
}
}
/* @ts-self-types="./index.d.ts" */
let urlAlphabet =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
let nanoid = (size = 21) => {
let id = '';
let i = size | 0;
while (i--) {
id += urlAlphabet[(Math.random() * 64) | 0];
}
return id
};
typeof process !== "undefined" && process.platform === "win32";
function promiseWithResolvers() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
}
function reviveInvokeError(e) {
const error = new Error(e.message || "Unknown invoke error");
Object.assign(error, e, {
// pass the whole error instead of just the stacktrace
// so that it gets formatted nicely with console.log
runnerError: new Error("RunnerError")
});
return error;
}
const createInvokeableTransport = (transport) => {
if (transport.invoke) {
return {
...transport,
async invoke(name, data) {
const result = await transport.invoke({
type: "custom",
event: "vite:invoke",
data: {
id: "send",
name,
data
}
});
if ("error" in result) {
throw reviveInvokeError(result.error);
}
return result.result;
}
};
}
if (!transport.send || !transport.connect) {
throw new Error(
"transport must implement send and connect when invoke is not implemented"
);
}
const rpcPromises = /* @__PURE__ */ new Map();
return {
...transport,
connect({ onMessage, onDisconnection }) {
return transport.connect({
onMessage(payload) {
if (payload.type === "custom" && payload.event === "vite:invoke") {
const data = payload.data;
if (data.id.startsWith("response:")) {
const invokeId = data.id.slice("response:".length);
const promise = rpcPromises.get(invokeId);
if (!promise) return;
if (promise.timeoutId) clearTimeout(promise.timeoutId);
rpcPromises.delete(invokeId);
const { error, result } = data.data;
if (error) {
promise.reject(error);
} else {
promise.resolve(result);
}
return;
}
}
onMessage(payload);
},
onDisconnection
});
},
disconnect() {
rpcPromises.forEach((promise) => {
promise.reject(
new Error(
`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`
)
);
});
rpcPromises.clear();
return transport.disconnect?.();
},
send(data) {
return transport.send(data);
},
async invoke(name, data) {
const promiseId = nanoid();
const wrappedData = {
type: "custom",
event: "vite:invoke",
data: {
name,
id: `send:${promiseId}`,
data
}
};
const sendPromise = transport.send(wrappedData);
const { promise, resolve, reject } = promiseWithResolvers();
const timeout = transport.timeout ?? 6e4;
let timeoutId;
if (timeout > 0) {
timeoutId = setTimeout(() => {
rpcPromises.delete(promiseId);
reject(
new Error(
`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`
)
);
}, timeout);
timeoutId?.unref?.();
}
rpcPromises.set(promiseId, { resolve, reject, name, timeoutId });
if (sendPromise) {
sendPromise.catch((err) => {
clearTimeout(timeoutId);
rpcPromises.delete(promiseId);
reject(err);
});
}
try {
return await promise;
} catch (err) {
throw reviveInvokeError(err);
}
}
};
};
const normalizeModuleRunnerTransport = (transport) => {
const invokeableTransport = createInvokeableTransport(transport);
let isConnected = !invokeableTransport.connect;
let connectingPromise;
return {
...transport,
...invokeableTransport.connect ? {
async connect(onMessage) {
if (isConnected) return;
if (connectingPromise) {
await connectingPromise;
return;
}
const maybePromise = invokeableTransport.connect({
onMessage: onMessage ?? (() => {
}),
onDisconnection() {
isConnected = false;
}
});
if (maybePromise) {
connectingPromise = maybePromise;
await connectingPromise;
connectingPromise = void 0;
}
isConnected = true;
}
} : {},
...invokeableTransport.disconnect ? {
async disconnect() {
if (!isConnected) return;
if (connectingPromise) {
await connectingPromise;
}
isConnected = false;
await invokeableTransport.disconnect();
}
} : {},
async send(data) {
if (!invokeableTransport.send) return;
if (!isConnected) {
if (connectingPromise) {
await connectingPromise;
} else {
throw new Error("send was called before connect");
}
}
await invokeableTransport.send(data);
},
async invoke(name, data) {
if (!isConnected) {
if (connectingPromise) {
await connectingPromise;
} else {
throw new Error("invoke was called before connect");
}
}
return invokeableTransport.invoke(name, data);
}
};
};
const createWebSocketModuleRunnerTransport = (options) => {
const pingInterval = options.pingInterval ?? 3e4;
let ws;
let pingIntervalId;
return {
async connect({ onMessage, onDisconnection }) {
const socket = options.createConnection();
socket.addEventListener("message", async ({ data }) => {
onMessage(JSON.parse(data));
});
let isOpened = socket.readyState === socket.OPEN;
if (!isOpened) {
await new Promise((resolve, reject) => {
socket.addEventListener(
"open",
() => {
isOpened = true;
resolve();
},
{ once: true }
);
socket.addEventListener("close", async () => {
if (!isOpened) {
reject(new Error("WebSocket closed without opened."));
return;
}
onMessage({
type: "custom",
event: "vite:ws:disconnect",
data: { webSocket: socket }
});
onDisconnection();
});
});
}
onMessage({
type: "custom",
event: "vite:ws:connect",
data: { webSocket: socket }
});
ws = socket;
pingIntervalId = setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({ type: "ping" }));
}
}, pingInterval);
},
disconnect() {
clearInterval(pingIntervalId);
ws?.close();
},
send(data) {
ws.send(JSON.stringify(data));
}
};
};
function createHMRHandler(handler) {
const queue = new Queue();
return (payload) => queue.enqueue(() => handler(payload));
}
class Queue {
constructor() {
this.queue = [];
this.pending = false;
}
enqueue(promise) {
return new Promise((resolve, reject) => {
this.queue.push({
promise,
resolve,
reject
});
this.dequeue();
});
}
dequeue() {
if (this.pending) {
return false;
}
const item = this.queue.shift();
if (!item) {
return false;
}
this.pending = true;
item.promise().then(item.resolve).catch(item.reject).finally(() => {
this.pending = false;
this.dequeue();
});
return true;
}
}
const hmrConfigName = __HMR_CONFIG_NAME__;
const base$1 = __BASE__ || "/";
function h(e, attrs = {}, ...children) {
@@ -461,23 +757,21 @@ class ErrorOverlay extends HTMLElement {
fileRE.lastIndex = 0;
while (match = fileRE.exec(text)) {
const { 0: file, index } = match;
if (index != null) {
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement("a");
link.textContent = file;
link.className = "file-link";
link.onclick = () => {
fetch(
new URL(
`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url
)
);
};
el.appendChild(link);
curIndex += frag.length + file.length;
}
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement("a");
link.textContent = file;
link.className = "file-link";
link.onclick = () => {
fetch(
new URL(
`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url
)
);
};
el.appendChild(link);
curIndex += frag.length + file.length;
}
}
}
@@ -500,69 +794,68 @@ const hmrPort = __HMR_PORT__;
const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
const directSocketHost = __HMR_DIRECT_TARGET__;
const base = __BASE__ || "/";
const hmrTimeout = __HMR_TIMEOUT__;
const wsToken = __WS_TOKEN__;
let socket;
try {
let fallback;
if (!hmrPort) {
fallback = () => {
socket = setupWebSocket(socketProtocol, directSocketHost, () => {
const currentScriptHostURL = new URL(import.meta.url);
const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
console.error(
`[vite] failed to connect to websocket.
const transport = normalizeModuleRunnerTransport(
(() => {
let wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () => new WebSocket(
`${socketProtocol}://${socketHost}?token=${wsToken}`,
"vite-hmr"
),
pingInterval: hmrTimeout
});
return {
async connect(handlers) {
try {
await wsTransport.connect(handlers);
} catch (e) {
if (!hmrPort) {
wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () => new WebSocket(
`${socketProtocol}://${directSocketHost}?token=${wsToken}`,
"vite-hmr"
),
pingInterval: hmrTimeout
});
try {
await wsTransport.connect(handlers);
console.info(
"[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error."
);
} catch (e2) {
if (e2 instanceof Error && e2.message.includes("WebSocket closed without opened.")) {
const currentScriptHostURL = new URL(import.meta.url);
const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
console.error(
`[vite] failed to connect to websocket.
your current setup:
(browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)
(browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)
Check out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .`
);
});
socket.addEventListener(
"open",
() => {
console.info(
"[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error."
);
},
{ once: true }
);
);
}
}
return;
}
console.error(`[vite] failed to connect to websocket (${e}). `);
throw e;
}
},
async disconnect() {
await wsTransport.disconnect();
},
send(data) {
wsTransport.send(data);
}
};
}
socket = setupWebSocket(socketProtocol, socketHost, fallback);
} catch (error) {
console.error(`[vite] failed to connect to websocket (${error}). `);
}
function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) {
const socket2 = new WebSocket(
`${protocol}://${hostAndPath}?token=${wsToken}`,
"vite-hmr"
);
let isOpened = false;
socket2.addEventListener(
"open",
() => {
isOpened = true;
notifyListeners("vite:ws:connect", { webSocket: socket2 });
},
{ once: true }
);
socket2.addEventListener("message", async ({ data }) => {
handleMessage(JSON.parse(data));
})()
);
let willUnload = false;
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
willUnload = true;
});
socket2.addEventListener("close", async ({ wasClean }) => {
if (wasClean) return;
if (!isOpened && onCloseWithoutOpen) {
onCloseWithoutOpen();
return;
}
notifyListeners("vite:ws:disconnect", { webSocket: socket2 });
if (hasDocument) {
console.log(`[vite] server connection lost. Polling for restart...`);
await waitForSuccessfulPing(protocol, hostAndPath);
location.reload();
}
});
return socket2;
}
function cleanUrl(pathname) {
const url = new URL(pathname, "http://vite.dev");
@@ -585,11 +878,11 @@ const debounceReload = (time) => {
};
const pageReload = debounceReload(50);
const hmrClient = new HMRClient(
console,
{
isReady: () => socket && socket.readyState === 1,
send: (message) => socket.send(message)
error: (err) => console.error("[vite]", err),
debug: (...msg) => console.debug("[vite]", ...msg)
},
transport,
async function importUpdatedModule({
acceptedPath,
timestamp,
@@ -612,19 +905,14 @@ const hmrClient = new HMRClient(
return await importPromise;
}
);
transport.connect(createHMRHandler(handleMessage));
async function handleMessage(payload) {
switch (payload.type) {
case "connected":
console.debug(`[vite] connected.`);
hmrClient.messenger.flush();
setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send('{"type":"ping"}');
}
}, __HMR_TIMEOUT__);
break;
case "update":
notifyListeners("vite:beforeUpdate", payload);
await hmrClient.notifyListeners("vite:beforeUpdate", payload);
if (hasDocument) {
if (isFirstUpdate && hasErrorOverlay()) {
location.reload();
@@ -667,14 +955,24 @@ async function handleMessage(payload) {
});
})
);
notifyListeners("vite:afterUpdate", payload);
await hmrClient.notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
notifyListeners(payload.event, payload.data);
await hmrClient.notifyListeners(payload.event, payload.data);
if (payload.event === "vite:ws:disconnect") {
if (hasDocument && !willUnload) {
console.log(`[vite] server connection lost. Polling for restart...`);
const socket = payload.data.webSocket;
const url = new URL(socket.url);
url.search = "";
await waitForSuccessfulPing(url.href);
location.reload();
}
}
break;
}
case "full-reload":
notifyListeners("vite:beforeFullReload", payload);
await hmrClient.notifyListeners("vite:beforeFullReload", payload);
if (hasDocument) {
if (payload.path && payload.path.endsWith(".html")) {
const pagePath = decodeURI(location.pathname);
@@ -689,11 +987,11 @@ async function handleMessage(payload) {
}
break;
case "prune":
notifyListeners("vite:beforePrune", payload);
await hmrClient.notifyListeners("vite:beforePrune", payload);
await hmrClient.prunePaths(payload.paths);
break;
case "error": {
notifyListeners("vite:error", payload);
await hmrClient.notifyListeners("vite:error", payload);
if (hasDocument) {
const err = payload.err;
if (enableOverlay) {
@@ -708,20 +1006,23 @@ ${err.stack}`
}
break;
}
case "ping":
break;
default: {
const check = payload;
return check;
}
}
}
function notifyListeners(event, data) {
hmrClient.notifyListeners(event, data);
}
const enableOverlay = __HMR_ENABLE_OVERLAY__;
const hasDocument = "document" in globalThis;
function createErrorOverlay(err) {
clearErrorOverlay();
document.body.appendChild(new ErrorOverlay(err));
const { customElements } = globalThis;
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId);
document.body.appendChild(new ErrorOverlayConstructor(err));
}
}
function clearErrorOverlay() {
document.querySelectorAll(overlayId).forEach((n) => n.close());
@@ -729,23 +1030,27 @@ function clearErrorOverlay() {
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length;
}
async function waitForSuccessfulPing(socketProtocol2, hostAndPath, ms = 1e3) {
const pingHostProtocol = socketProtocol2 === "wss" ? "https" : "http";
const ping = async () => {
try {
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
mode: "no-cors",
headers: {
// Custom headers won't be included in a request with no-cors so (ab)use one of the
// safelisted headers to identify the ping request
Accept: "text/x-vite-ping"
}
});
return true;
} catch {
}
return false;
};
async function waitForSuccessfulPing(socketUrl, ms = 1e3) {
async function ping() {
const socket = new WebSocket(socketUrl, "vite-ping");
return new Promise((resolve) => {
function onOpen() {
resolve(true);
close();
}
function onError() {
resolve(false);
close();
}
function close() {
socket.removeEventListener("open", onOpen);
socket.removeEventListener("error", onError);
socket.close();
}
socket.addEventListener("open", onOpen);
socket.addEventListener("error", onError);
});
}
if (await ping()) {
return;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,3 @@
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);

View File

@@ -1,16 +1,10 @@
import { C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import { P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import require$$0 from 'path';
import require$$0__default from 'fs';
import { l as lib } from './dep-IQS-Za7F.js';
import { l as lib } from './dep-3RmXg9uo.js';
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
const __require = __cjs_createRequire(import.meta.url);
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
@@ -190,160 +184,6 @@ var applyStyles$1 = function applyStyles(bundle, styles) {
});
};
var readCache$1 = {exports: {}};
var pify$2 = {exports: {}};
var processFn = function (fn, P, opts) {
return function () {
var that = this;
var args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P(function (resolve, reject) {
args.push(function (err, result) {
if (err) {
reject(err);
} else if (opts.multiArgs) {
var results = new Array(arguments.length - 1);
for (var i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
fn.apply(that, args);
});
};
};
var pify$1 = pify$2.exports = function (obj, P, opts) {
if (typeof P !== 'function') {
opts = P;
P = Promise;
}
opts = opts || {};
opts.exclude = opts.exclude || [/.+Sync$/];
var filter = function (key) {
var match = function (pattern) {
return typeof pattern === 'string' ? key === pattern : pattern.test(key);
};
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
var ret = typeof obj === 'function' ? function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, P, opts).apply(this, arguments);
} : {};
return Object.keys(obj).reduce(function (ret, key) {
var x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
return ret;
}, ret);
};
pify$1.all = pify$1;
var pifyExports = pify$2.exports;
var fs = require$$0__default;
var path$3 = require$$0;
var pify = pifyExports;
var stat = pify(fs.stat);
var readFile = pify(fs.readFile);
var resolve = path$3.resolve;
var cache = Object.create(null);
function convert(content, encoding) {
if (Buffer.isEncoding(encoding)) {
return content.toString(encoding);
}
return content;
}
readCache$1.exports = function (path, encoding) {
path = resolve(path);
return stat(path).then(function (stats) {
var item = cache[path];
if (item && item.mtime.getTime() === stats.mtime.getTime()) {
return convert(item.content, encoding);
}
return readFile(path).then(function (data) {
cache[path] = {
mtime: stats.mtime,
content: data
};
return convert(data, encoding);
});
}).catch(function (err) {
cache[path] = null;
return Promise.reject(err);
});
};
readCache$1.exports.sync = function (path, encoding) {
path = resolve(path);
try {
var stats = fs.statSync(path);
var item = cache[path];
if (item && item.mtime.getTime() === stats.mtime.getTime()) {
return convert(item.content, encoding);
}
var data = fs.readFileSync(path);
cache[path] = {
mtime: stats.mtime,
content: data
};
return convert(data, encoding);
} catch (err) {
cache[path] = null;
throw err;
}
};
readCache$1.exports.get = function (path, encoding) {
path = resolve(path);
if (cache[path]) {
return convert(cache[path].content, encoding);
}
return null;
};
readCache$1.exports.clear = function () {
cache = Object.create(null);
};
var readCacheExports = readCache$1.exports;
const anyDataURLRegexp = /^data:text\/css(?:;(base64|plain))?,/i;
const base64DataURLRegexp = /^data:text\/css;base64,/i;
const plainDataURLRegexp = /^data:text\/css;plain,/i;
@@ -372,17 +212,6 @@ var dataUrl = {
contents,
};
const readCache = readCacheExports;
const dataURL$1 = dataUrl;
var loadContent$1 = function loadContent(filename) {
if (dataURL$1.isValid(filename)) {
return dataURL$1.contents(filename)
}
return readCache(filename, "utf-8")
};
// external tooling
const valueParser = lib;
@@ -920,7 +749,7 @@ const path = require$$0;
const applyConditions = applyConditions$1;
const applyRaws = applyRaws$1;
const applyStyles = applyStyles$1;
const loadContent = loadContent$1;
const loadContent = () => "";
const parseStyles = parseStyles_1;
const resolveId = (id) => id;

File diff suppressed because one or more lines are too long

View File

@@ -1,19 +1,11 @@
import { D as commonjsGlobal, C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import require$$0__default from 'fs';
import { Q as commonjsGlobal, P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import require$$0$2 from 'fs';
import require$$0 from 'postcss';
import require$$0$1 from 'path';
import require$$3 from 'crypto';
import require$$0$2 from 'util';
import { l as lib } from './dep-IQS-Za7F.js';
import require$$1 from 'util';
import { l as lib } from './dep-3RmXg9uo.js';
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
@@ -396,9 +388,6 @@ var localsConvention = {};
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
@@ -733,7 +722,7 @@ function baseToString(value) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
}
/**
@@ -748,7 +737,7 @@ function baseToString(value) {
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
return (false && end >= length) ? array : baseSlice(array, start, end);
}
/**
@@ -1470,7 +1459,7 @@ function requireWasmHash () {
// 64 is the maximum chunk size for every possible wasm hash implementation
// 4 is the maximum number of bytes per char for string encoding (max is utf-8)
// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
class WasmHash {
/**
@@ -2035,12 +2024,17 @@ function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
digestType === "base49" ||
digestType === "base52" ||
digestType === "base58" ||
digestType === "base62"
digestType === "base62" ||
digestType === "base64safe"
) {
return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
} else {
return hash.digest(digestType || "hex").substr(0, maxLength);
return encodeBufferToBase(
hash.digest(),
digestType === "base64safe" ? 64 : digestType.substr(4),
maxLength
);
}
return hash.digest(digestType || "hex").substr(0, maxLength);
}
var getHashDigest_1 = getHashDigest$1;
@@ -2096,9 +2090,10 @@ function interpolateName$1(loaderContext, name, options = {}) {
directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
}
if (directory.length === 1) {
if (directory.length <= 1) {
directory = "";
} else if (directory.length > 1) {
} else {
// directory.length > 1
folder = path$1.basename(directory);
}
}
@@ -2121,7 +2116,7 @@ function interpolateName$1(loaderContext, name, options = {}) {
// `hash` and `contenthash` are same in `loader-utils` context
// let's keep `hash` for backward compatibility
.replace(
/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
(all, hashType, digestType, maxLength) =>
getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
);
@@ -2650,6 +2645,9 @@ types.UNIVERSAL = UNIVERSAL;
_proto.prepend = function prepend(selector) {
selector.parent = this;
this.nodes.unshift(selector);
for (var id in this.indexes) {
this.indexes[id]++;
}
return this;
};
_proto.at = function at(index) {
@@ -2686,29 +2684,39 @@ types.UNIVERSAL = UNIVERSAL;
return this.removeAll();
};
_proto.insertAfter = function insertAfter(oldNode, newNode) {
var _this$nodes;
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex + 1, 0, newNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
resetNode.push(arguments[i]);
}
(_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex <= index) {
this.indexes[id] = index + 1;
if (oldIndex < index) {
this.indexes[id] = index + arguments.length - 1;
}
}
return this;
};
_proto.insertBefore = function insertBefore(oldNode, newNode) {
var _this$nodes2;
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex, 0, newNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
resetNode.push(arguments[i]);
}
(_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index <= oldIndex) {
this.indexes[id] = index + 1;
if (index >= oldIndex) {
this.indexes[id] = index + arguments.length - 1;
}
}
return this;
@@ -2734,7 +2742,7 @@ types.UNIVERSAL = UNIVERSAL;
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
@@ -3402,7 +3410,7 @@ var attribute$1 = {};
* For Node.js, simply re-export the core `util.deprecate` function.
*/
var node = require$$0$2.deprecate;
var node = require$$1.deprecate;
(function (exports) {
@@ -4752,7 +4760,7 @@ tokenTypes.combinator = combinator$1;
}
// We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
if (nodes.length > 0) {
var last = this.current.last;
@@ -5631,8 +5639,40 @@ const selectorParser$1 = distExports;
const valueParser = lib;
const { extractICSS } = src$4;
const IGNORE_FILE_MARKER = "cssmodules-pure-no-check";
const IGNORE_NEXT_LINE_MARKER = "cssmodules-pure-ignore";
const isSpacing = (node) => node.type === "combinator" && node.value === " ";
const isPureCheckDisabled = (root) => {
for (const node of root.nodes) {
if (node.type !== "comment") {
return false;
}
if (node.text.trim().startsWith(IGNORE_FILE_MARKER)) {
return true;
}
}
return false;
};
function getIgnoreComment(node) {
if (!node.parent) {
return;
}
const indexInParent = node.parent.index(node);
for (let i = indexInParent - 1; i >= 0; i--) {
const prevNode = node.parent.nodes[i];
if (prevNode.type === "comment") {
if (prevNode.text.trimStart().startsWith(IGNORE_NEXT_LINE_MARKER)) {
return prevNode;
}
} else {
break;
}
}
}
function normalizeNodeArray(nodes) {
const array = [];
@@ -5652,6 +5692,8 @@ function normalizeNodeArray(nodes) {
return array;
}
const isPureSelectorSymbol = Symbol("is-pure-selector");
function localizeNode(rule, mode, localAliasMap) {
const transform = (node, context) => {
if (context.ignoreNextSpacing && !isSpacing(node)) {
@@ -5859,7 +5901,7 @@ function localizeNode(rule, mode, localAliasMap) {
}
case "nesting": {
if (node.value === "&") {
context.hasLocals = true;
context.hasLocals = rule.parent[isPureSelectorSymbol];
}
}
}
@@ -5965,7 +6007,7 @@ function localizeDeclarationValues(localize, declaration, context) {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: localize && !context.global,
localizeNextItem: localize,
localAliasMap: context.localAliasMap,
};
nodes[index] = localizeDeclNode(node, subContext);
@@ -5974,24 +6016,20 @@ function localizeDeclarationValues(localize, declaration, context) {
declaration.value = valueNodes.toString();
}
function localizeDeclaration(declaration, context) {
const isAnimation = /animation$/i.test(declaration.prop);
// letter
// An uppercase letter or a lowercase letter.
//
// ident-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
//
// ident code point
// An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
if (isAnimation) {
// letter
// An uppercase letter or a lowercase letter.
//
// ident-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
//
// ident code point
// An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
// We don't validate `hex digits`, because we don't need it, it is work of linters.
const validIdent =
/^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
// We don't validate `hex digits`, because we don't need it, it is work of linters.
const validIdent =
/^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
/*
/*
The spec defines some keywords that you can use to describe properties such as the timing
function. These are still valid animation names, so as long as there is a property that accepts
a keyword, it is given priority. Only when all the properties that can take a keyword are
@@ -6002,38 +6040,43 @@ function localizeDeclaration(declaration, context) {
The animation will repeat an infinite number of times from the first argument, and will have an
animation name of infinite from the second.
*/
const animationKeywords = {
// animation-direction
$normal: 1,
$reverse: 1,
$alternate: 1,
"$alternate-reverse": 1,
// animation-fill-mode
$forwards: 1,
$backwards: 1,
$both: 1,
// animation-iteration-count
$infinite: 1,
// animation-play-state
$paused: 1,
$running: 1,
// animation-timing-function
$ease: 1,
"$ease-in": 1,
"$ease-out": 1,
"$ease-in-out": 1,
$linear: 1,
"$step-end": 1,
"$step-start": 1,
// Special
$none: Infinity, // No matter how many times you write none, it will never be an animation name
// Global values
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
$revert: Infinity,
"$revert-layer": Infinity,
};
const animationKeywords = {
// animation-direction
$normal: 1,
$reverse: 1,
$alternate: 1,
"$alternate-reverse": 1,
// animation-fill-mode
$forwards: 1,
$backwards: 1,
$both: 1,
// animation-iteration-count
$infinite: 1,
// animation-play-state
$paused: 1,
$running: 1,
// animation-timing-function
$ease: 1,
"$ease-in": 1,
"$ease-out": 1,
"$ease-in-out": 1,
$linear: 1,
"$step-end": 1,
"$step-start": 1,
// Special
$none: Infinity, // No matter how many times you write none, it will never be an animation name
// Global values
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
$revert: Infinity,
"$revert-layer": Infinity,
};
function localizeDeclaration(declaration, context) {
const isAnimation = /animation(-name)?$/i.test(declaration.prop);
if (isAnimation) {
let parsedAnimationKeywords = {};
const valueNodes = valueParser(declaration.value).walk((node) => {
// If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
@@ -6041,9 +6084,28 @@ function localizeDeclaration(declaration, context) {
parsedAnimationKeywords = {};
return;
}
// Do not handle nested functions
else if (node.type === "function") {
} else if (
node.type === "function" &&
node.value.toLowerCase() === "local" &&
node.nodes.length === 1
) {
node.type = "word";
node.value = node.nodes[0].value;
return localizeDeclNode(node, {
options: context.options,
global: context.global,
localizeNextItem: true,
localAliasMap: context.localAliasMap,
});
} else if (node.type === "function") {
// replace `animation: global(example)` with `animation-name: example`
if (node.value.toLowerCase() === "global" && node.nodes.length === 1) {
node.type = "word";
node.value = node.nodes[0].value;
}
// Do not handle nested functions
return false;
}
// Ignore all except word
@@ -6070,14 +6132,12 @@ function localizeDeclaration(declaration, context) {
}
}
const subContext = {
return localizeDeclNode(node, {
options: context.options,
global: context.global,
localizeNextItem: shouldParseAnimationName && !context.global,
localAliasMap: context.localAliasMap,
};
return localizeDeclNode(node, subContext);
});
});
declaration.value = valueNodes.toString();
@@ -6085,19 +6145,35 @@ function localizeDeclaration(declaration, context) {
return;
}
const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
if (isAnimationName) {
return localizeDeclarationValues(true, declaration, context);
}
const hasUrl = /url\(/i.test(declaration.value);
if (hasUrl) {
if (/url\(/i.test(declaration.value)) {
return localizeDeclarationValues(false, declaration, context);
}
}
const isPureSelector = (context, rule) => {
if (!rule.parent || rule.type === "root") {
return !context.hasPureGlobals;
}
if (rule.type === "rule" && rule[isPureSelectorSymbol]) {
return rule[isPureSelectorSymbol] || isPureSelector(context, rule.parent);
}
return !context.hasPureGlobals || isPureSelector(context, rule.parent);
};
const isNodeWithoutDeclarations = (rule) => {
if (rule.nodes.length > 0) {
return !rule.nodes.every(
(item) =>
item.type === "rule" ||
(item.type === "atrule" && !isNodeWithoutDeclarations(item))
);
}
return true;
};
src$2.exports = (options = {}) => {
if (
options &&
@@ -6122,6 +6198,7 @@ src$2.exports = (options = {}) => {
return {
Once(root) {
const { icssImports } = extractICSS(root, false);
const enforcePureMode = pureMode && !isPureCheckDisabled(root);
Object.keys(icssImports).forEach((key) => {
Object.keys(icssImports[key]).forEach((prop) => {
@@ -6141,10 +6218,15 @@ src$2.exports = (options = {}) => {
let globalKeyframes = globalMode;
if (globalMatch) {
if (pureMode) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
if (enforcePureMode) {
const ignoreComment = getIgnoreComment(atRule);
if (!ignoreComment) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
} else {
ignoreComment.remove();
}
}
atRule.params = globalMatch[1];
globalKeyframes = true;
@@ -6168,6 +6250,14 @@ src$2.exports = (options = {}) => {
});
} else if (/scope$/i.test(atRule.name)) {
if (atRule.params) {
const ignoreComment = pureMode
? getIgnoreComment(atRule)
: undefined;
if (ignoreComment) {
ignoreComment.remove();
}
atRule.params = atRule.params
.split("to")
.map((item) => {
@@ -6181,7 +6271,11 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
if (pureMode && context.hasPureGlobals) {
if (
enforcePureMode &&
context.hasPureGlobals &&
!ignoreComment
) {
throw atRule.error(
'Selector in at-rule"' +
selector +
@@ -6232,13 +6326,28 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
if (pureMode && context.hasPureGlobals) {
const ignoreComment = enforcePureMode
? getIgnoreComment(rule)
: undefined;
const isNotPure = enforcePureMode && !isPureSelector(context, rule);
if (
isNotPure &&
isNodeWithoutDeclarations(rule) &&
!ignoreComment
) {
throw rule.error(
'Selector "' +
rule.selector +
'" is not pure ' +
"(pure selectors must contain at least one local class or id)"
);
} else if (ignoreComment) {
ignoreComment.remove();
}
if (pureMode) {
rule[isPureSelectorSymbol] = !isNotPure;
}
rule.selector = context.selector;
@@ -6977,7 +7086,7 @@ function makePlugin(opts) {
};
}
var _fs = require$$0__default;
var _fs = require$$0$2;
var _fs2 = fs;

124
node_modules/vite/dist/node/cli.js generated vendored
View File

@@ -2,23 +2,22 @@ import path from 'node:path';
import fs__default from 'node:fs';
import { performance } from 'node:perf_hooks';
import { EventEmitter } from 'events';
import { B as colors, v as createLogger, r as resolveConfig } from './chunks/dep-C6uTJdX2.js';
import { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-DBxKXgDP.js';
import { VERSION } from './constants.js';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:module';
import 'node:crypto';
import 'tty';
import 'path';
import 'picomatch';
import 'esbuild';
import 'path';
import 'fs';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'url';
@@ -27,22 +26,26 @@ import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
import 'crypto';
import 'vite/module-runner';
import 'rollup/parseAst';
import 'node:buffer';
import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'node:buffer';
import 'rollup/parseAst';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'zlib';
import 'buffer';
import 'assert';
import 'node:querystring';
import 'node:zlib';
function toArr(any) {
@@ -690,7 +693,7 @@ const filterDuplicateOptions = (options) => {
}
}
};
function cleanOptions(options) {
function cleanGlobalCLIOptions(options) {
const ret = { ...options };
delete ret["--"];
delete ret.c;
@@ -699,16 +702,27 @@ function cleanOptions(options) {
delete ret.l;
delete ret.logLevel;
delete ret.clearScreen;
delete ret.configLoader;
delete ret.d;
delete ret.debug;
delete ret.f;
delete ret.filter;
delete ret.m;
delete ret.mode;
delete ret.w;
if ("sourcemap" in ret) {
const sourcemap = ret.sourcemap;
ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
}
if ("watch" in ret) {
const watch = ret.watch;
ret.watch = watch ? {} : void 0;
}
return ret;
}
function cleanBuilderCLIOptions(options) {
const ret = { ...options };
delete ret.app;
return ret;
}
const convertHost = (v) => {
@@ -725,29 +739,34 @@ const convertBase = (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`);
}).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option(
"--configLoader <loader>",
`[string] use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`
).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-C6uTJdX2.js').then(function (n) { return n.F; });
const { createServer } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.S; });
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
server: cleanOptions(options)
server: cleanGlobalCLIOptions(options),
forceOptimizeDeps: options.force
});
if (!server.httpServer) {
throw new Error("HTTP server not available");
}
await server.listen();
const info = server.config.logger.info;
const modeString = options.mode && options.mode !== "development" ? ` ${colors.bgGreen(` ${colors.bold(options.mode)} `)}` : "";
const viteStartTime = global.__vite_start_time ?? false;
const startupDurationString = viteStartTime ? colors.dim(
`ready in ${colors.reset(
@@ -759,7 +778,7 @@ cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--
`
${colors.green(
`${colors.bold("VITE")} v${VERSION}`
)} ${startupDurationString}
)}${modeString} ${startupDurationString}
`,
{
clear: !hasExistingLogs
@@ -821,44 +840,56 @@ cli.command("build [root]", "build for production").option("--target <target>",
).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`).action(async (root, options) => {
filterDuplicateOptions(options);
const { build } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.G; });
const buildOptions = cleanOptions(options);
try {
await build({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions
});
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error during build:
${e.stack}`),
{ error: e }
).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(
async (root, options) => {
filterDuplicateOptions(options);
const { createBuilder } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.T; });
const buildOptions = cleanGlobalCLIOptions(
cleanBuilderCLIOptions(options)
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
try {
const inlineConfig = {
root,
base: options.base,
mode: options.mode,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions,
...options.app ? { builder: {} } : {}
};
const builder = await createBuilder(inlineConfig, null);
await builder.buildApp();
} 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));
}
}
});
cli.command("optimize [root]", "pre-bundle dependencies").option(
);
cli.command(
"optimize [root]",
"pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)"
).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-C6uTJdX2.js').then(function (n) { return n.E; });
const { optimizeDeps } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.R; });
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode
},
@@ -878,12 +909,13 @@ ${e.stack}`),
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-C6uTJdX2.js').then(function (n) { return n.H; });
const { preview } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.U; });
try {
const server = await preview({
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode,
build: {

View File

@@ -5,6 +5,35 @@ import { readFileSync } from 'node:fs';
const { version } = JSON.parse(
readFileSync(new URL("../../package.json", import.meta.url)).toString()
);
const ROLLUP_HOOKS = [
"options",
"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",
"onLog"
];
const VERSION = version;
const DEFAULT_MAIN_FIELDS = [
"browser",
@@ -13,23 +42,25 @@ const DEFAULT_MAIN_FIELDS = [
// moment still uses this...
"jsnext"
];
const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(
DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser")
);
const DEV_PROD_CONDITION = `development|production`;
const DEFAULT_CONDITIONS = ["module", "browser", "node", DEV_PROD_CONDITION];
const DEFAULT_CLIENT_CONDITIONS = Object.freeze(
DEFAULT_CONDITIONS.filter((c) => c !== "node")
);
const DEFAULT_SERVER_CONDITIONS = Object.freeze(
DEFAULT_CONDITIONS.filter((c) => c !== "browser")
);
const ESBUILD_MODULES_TARGET = [
"es2020",
// support import.meta.url
"edge88",
"firefox78",
"chrome87",
"safari14"
];
const DEFAULT_EXTENSIONS = [
".mjs",
".js",
".mts",
".ts",
".jsx",
".tsx",
".json"
];
const DEFAULT_CONFIG_FILES = [
"vite.config.js",
"vite.config.mjs",
@@ -67,6 +98,8 @@ const KNOWN_ASSET_TYPES = [
"ico",
"webp",
"avif",
"cur",
"jxl",
// media
"mp4",
"webm",
@@ -90,7 +123,8 @@ const KNOWN_ASSET_TYPES = [
"txt"
];
const DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`,
"i"
);
const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
const loopbackHosts = /* @__PURE__ */ new Set([
@@ -109,5 +143,7 @@ const DEFAULT_PREVIEW_PORT = 4173;
const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
const METADATA_FILENAME = "_metadata.json";
const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
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, SPECIAL_QUERY_RE, VERSION, VITE_PACKAGE_DIR, defaultAllowedOrigins, loopbackHosts, wildcardHosts };
export { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, CSS_LANGS_RE, DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE, DEFAULT_CLIENT_CONDITIONS, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_CONFIG_FILES, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_SERVER_CONDITIONS, DEFAULT_SERVER_MAIN_FIELDS, DEP_VERSION_RE, DEV_PROD_CONDITION, ENV_ENTRY, ENV_PUBLIC_PATH, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, 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, defaultAllowedOrigins, loopbackHosts, wildcardHosts };

2481
node_modules/vite/dist/node/index.d.ts generated vendored

File diff suppressed because it is too large Load Diff

171
node_modules/vite/dist/node/index.js generated vendored
View File

@@ -1,26 +1,24 @@
export { parseAst, parseAstAsync } from 'rollup/parseAst';
import { i as isInNodeModules, a as arraify } from './chunks/dep-C6uTJdX2.js';
export { b as build, g as buildErrorMessage, k as createFilter, v as createLogger, c as createServer, d as defineConfig, h as fetchModule, f as formatPostcssSourceMap, y as isFileLoadingAllowed, x as isFileServingAllowed, l as loadConfigFromFile, z as loadEnv, j as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, e as preprocessCSS, p as preview, r as resolveConfig, A as resolveEnvPrefix, q as rollupVersion, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-C6uTJdX2.js';
export { VERSION as version } from './constants.js';
import { a as arraify, i as isInNodeModules, D as DevEnvironment } from './chunks/dep-DBxKXgDP.js';
export { B as BuildEnvironment, f as build, m as buildErrorMessage, g as createBuilder, F as createFilter, h as createIdResolver, I as createLogger, n as createRunnableDevEnvironment, c as createServer, y as createServerHotChannel, w as createServerModuleRunner, x as createServerModuleRunnerTransport, d as defineConfig, v as fetchModule, j as formatPostcssSourceMap, L as isFileLoadingAllowed, K as isFileServingAllowed, q as isRunnableDevEnvironment, l as loadConfigFromFile, M as loadEnv, E as mergeAlias, C as mergeConfig, z as moduleRunnerTransform, A as normalizePath, o as optimizeDeps, p as perEnvironmentPlugin, b as perEnvironmentState, k as preprocessCSS, e as preview, r as resolveConfig, N as resolveEnvPrefix, G as rollupVersion, u as runnerImport, J as searchForWorkspaceRoot, H as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-DBxKXgDP.js';
export { defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, VERSION as version } from './constants.js';
export { version as esbuildVersion } from 'esbuild';
import { existsSync, readFileSync } from 'node:fs';
import { ViteRuntime, ESModulesRunner } from 'vite/runtime';
import 'node:fs/promises';
import 'node:fs';
import 'node:path';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:perf_hooks';
import 'node:module';
import 'node:crypto';
import 'tty';
import 'picomatch';
import 'path';
import 'fs';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'events';
@@ -30,21 +28,25 @@ import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
import 'crypto';
import 'vite/module-runner';
import 'node:buffer';
import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'node:buffer';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'zlib';
import 'buffer';
import 'assert';
import 'node:querystring';
import 'node:zlib';
const CSS_LANGS_RE = (
@@ -103,7 +105,7 @@ function splitVendorChunkPlugin() {
const cache = new SplitVendorChunkCache();
caches.push(cache);
const build = config.build ?? {};
const format = output?.format;
const format = output.format;
if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
return splitVendorChunk({ cache });
}
@@ -111,7 +113,7 @@ function splitVendorChunkPlugin() {
return {
name: "vite:split-vendor-chunk",
config(config) {
let outputs = config?.build?.rollupOptions?.output;
let outputs = config.build?.rollupOptions?.output;
if (outputs) {
outputs = arraify(outputs);
for (const output of outputs) {
@@ -151,111 +153,42 @@ function splitVendorChunkPlugin() {
};
}
class ServerHMRBroadcasterClient {
constructor(hmrChannel) {
this.hmrChannel = hmrChannel;
function createFetchableDevEnvironment(name, config, context) {
if (typeof Request === "undefined" || typeof Response === "undefined") {
throw new TypeError(
"FetchableDevEnvironment requires a global `Request` and `Response` object."
);
}
send(...args) {
let payload;
if (typeof args[0] === "string") {
payload = {
type: "custom",
event: args[0],
data: args[1]
};
} else {
payload = args[0];
}
if (payload.type !== "custom") {
throw new Error(
"Cannot send non-custom events from the client to the server."
);
}
this.hmrChannel.send(payload);
if (!context.handleRequest) {
throw new TypeError(
"FetchableDevEnvironment requires a `handleRequest` method during initialisation."
);
}
return new FetchableDevEnvironment(name, config, context);
}
class ServerHMRConnector {
handlers = [];
hmrChannel;
hmrClient;
connected = false;
constructor(server) {
const hmrChannel = server.hot?.channels.find(
(c) => c.name === "ssr"
);
if (!hmrChannel) {
throw new Error(
"Your version of Vite doesn't support HMR during SSR. Please, use Vite 5.1 or higher."
function isFetchableDevEnvironment(environment) {
return environment instanceof FetchableDevEnvironment;
}
class FetchableDevEnvironment extends DevEnvironment {
_handleRequest;
constructor(name, config, context) {
super(name, config, context);
this._handleRequest = context.handleRequest;
}
async dispatchFetch(request) {
if (!(request instanceof Request)) {
throw new TypeError(
"FetchableDevEnvironment `dispatchFetch` must receive a `Request` object."
);
}
this.hmrClient = new ServerHMRBroadcasterClient(hmrChannel);
hmrChannel.api.outsideEmitter.on("send", (payload) => {
this.handlers.forEach((listener) => listener(payload));
});
this.hmrChannel = hmrChannel;
}
isReady() {
return this.connected;
}
send(message) {
const payload = JSON.parse(message);
this.hmrChannel.api.innerEmitter.emit(
payload.event,
payload.data,
this.hmrClient
);
}
onUpdate(handler) {
this.handlers.push(handler);
handler({ type: "connected" });
this.connected = true;
const response = await this._handleRequest(request);
if (!(response instanceof Response)) {
throw new TypeError(
"FetchableDevEnvironment `context.handleRequest` must return a `Response` object."
);
}
return response;
}
}
function createHMROptions(server, options) {
if (server.config.server.hmr === false || options.hmr === false) {
return false;
}
const connection = new ServerHMRConnector(server);
return {
connection,
logger: options.hmr?.logger
};
}
const prepareStackTrace = {
retrieveFile(id) {
if (existsSync(id)) {
return readFileSync(id, "utf-8");
}
}
};
function resolveSourceMapOptions(options) {
if (options.sourcemapInterceptor != null) {
if (options.sourcemapInterceptor === "prepareStackTrace") {
return prepareStackTrace;
}
if (typeof options.sourcemapInterceptor === "object") {
return { ...prepareStackTrace, ...options.sourcemapInterceptor };
}
return options.sourcemapInterceptor;
}
if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) {
return "node";
}
return prepareStackTrace;
}
async function createViteRuntime(server, options = {}) {
const hmr = createHMROptions(server, options);
return new ViteRuntime(
{
...options,
root: server.config.root,
fetchModule: server.ssrFetchModule,
hmr,
sourcemapInterceptor: resolveSourceMapOptions(options)
},
options.runner || new ESModulesRunner()
);
}
export { ServerHMRConnector, createViteRuntime, isCSSRequest, splitVendorChunk, splitVendorChunkPlugin };
export { DevEnvironment, createFetchableDevEnvironment, isCSSRequest, isFetchableDevEnvironment, splitVendorChunk, splitVendorChunkPlugin };

290
node_modules/vite/dist/node/module-runner.d.ts generated vendored Normal file
View File

@@ -0,0 +1,290 @@
import { ModuleNamespace, ViteHotContext } from '../../types/hot.js';
import { Update, HotPayload } from '../../types/hmrPayload.js';
import { InferCustomEventPayload } from '../../types/customEvent.js';
import { N as NormalizedModuleRunnerTransport, E as ExternalFetchResult, V as ViteFetchResult, M as ModuleRunnerTransport, F as FetchFunctionOptions, a as FetchResult } from './moduleRunnerTransport.d-DJ_mE5sf.js';
export { b as ModuleRunnerTransportHandlers, c as createWebSocketModuleRunnerTransport } from './moduleRunnerTransport.d-DJ_mE5sf.js';
interface SourceMapLike {
version: number;
mappings?: string;
names?: string[];
sources?: string[];
sourcesContent?: string[];
}
declare class DecodedMap {
map: SourceMapLike;
_encoded: string;
_decoded: undefined | number[][][];
_decodedMemo: Stats;
url: string;
version: number;
names: string[];
resolvedSources: string[];
constructor(map: SourceMapLike, from: string);
}
interface Stats {
lastKey: number;
lastNeedle: number;
lastIndex: number;
}
type CustomListenersMap = Map<string, ((data: any) => void)[]>;
interface HotModule {
id: string;
callbacks: HotCallback[];
}
interface HotCallback {
deps: string[];
fn: (modules: Array<ModuleNamespace | undefined>) => void;
}
interface HMRLogger {
error(msg: string | Error): void;
debug(...msg: unknown[]): void;
}
declare class HMRClient {
logger: HMRLogger;
private transport;
private importUpdatedModule;
hotModulesMap: Map<string, HotModule>;
disposeMap: Map<string, (data: any) => void | Promise<void>>;
pruneMap: Map<string, (data: any) => void | Promise<void>>;
dataMap: Map<string, any>;
customListenersMap: CustomListenersMap;
ctxToListenersMap: Map<string, CustomListenersMap>;
currentFirstInvalidatedBy: string | undefined;
constructor(logger: HMRLogger, transport: NormalizedModuleRunnerTransport, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<void>;
send(payload: HotPayload): void;
clear(): void;
prunePaths(paths: string[]): Promise<void>;
protected warnFailedUpdate(err: Error, path: string | string[]): void;
private updateQueue;
private pendingUpdateQueue;
/**
* buffer multiple hot updates triggered by the same src change
* so that they are invoked in the same order they were sent.
* (otherwise the order may be inconsistent because of the http request round trip)
*/
queueUpdate(payload: Update): Promise<void>;
private fetchUpdate;
}
interface DefineImportMetadata {
/**
* Imported names before being transformed to `ssrImportKey`
*
* import foo, { bar as baz, qux } from 'hello'
* => ['default', 'bar', 'qux']
*
* import * as namespace from 'world
* => undefined
*/
importedNames?: string[];
}
interface SSRImportMetadata extends DefineImportMetadata {
isDynamicImport?: boolean;
}
declare const ssrModuleExportsKey = "__vite_ssr_exports__";
declare const ssrImportKey = "__vite_ssr_import__";
declare const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
declare const ssrExportAllKey = "__vite_ssr_exportAll__";
declare const ssrImportMetaKey = "__vite_ssr_import_meta__";
interface ModuleRunnerDebugger {
(formatter: unknown, ...args: unknown[]): void;
}
declare class ModuleRunner {
options: ModuleRunnerOptions;
evaluator: ModuleEvaluator;
private debug?;
evaluatedModules: EvaluatedModules;
hmrClient?: HMRClient;
private readonly envProxy;
private readonly transport;
private readonly resetSourceMapSupport?;
private readonly concurrentModuleNodePromises;
private closed;
constructor(options: ModuleRunnerOptions, evaluator?: ModuleEvaluator, debug?: ModuleRunnerDebugger | undefined);
/**
* URL to execute. Accepts file path, server path or id relative to the root.
*/
import<T = any>(url: string): Promise<T>;
/**
* Clear all caches including HMR listeners.
*/
clearCache(): void;
/**
* Clears all caches, removes all HMR listeners, and resets source map support.
* This method doesn't stop the HMR connection.
*/
close(): Promise<void>;
/**
* Returns `true` if the runtime has been closed by calling `close()` method.
*/
isClosed(): boolean;
private processImport;
private isCircularModule;
private isCircularImport;
private cachedRequest;
private cachedModule;
private getModuleInformation;
protected directRequest(url: string, mod: EvaluatedModuleNode, _callstack: string[]): Promise<any>;
}
interface RetrieveFileHandler {
(path: string): string | null | undefined | false;
}
interface RetrieveSourceMapHandler {
(path: string): null | {
url: string;
map: any;
};
}
interface InterceptorOptions {
retrieveFile?: RetrieveFileHandler;
retrieveSourceMap?: RetrieveSourceMapHandler;
}
interface ModuleRunnerImportMeta extends ImportMeta {
url: string;
env: ImportMetaEnv;
hot?: ViteHotContext;
[key: string]: any;
}
interface ModuleRunnerContext {
[ssrModuleExportsKey]: Record<string, any>;
[ssrImportKey]: (id: string, metadata?: DefineImportMetadata) => Promise<any>;
[ssrDynamicImportKey]: (id: string, options?: ImportCallOptions) => Promise<any>;
[ssrExportAllKey]: (obj: any) => void;
[ssrImportMetaKey]: ModuleRunnerImportMeta;
}
interface ModuleEvaluator {
/**
* Number of prefixed lines in the transformed code.
*/
startOffset?: number;
/**
* Run code that was transformed by Vite.
* @param context Function context
* @param code Transformed code
* @param module The module node
*/
runInlinedModule(context: ModuleRunnerContext, code: string, module: Readonly<EvaluatedModuleNode>): Promise<any>;
/**
* Run externalized module.
* @param file File URL to the external module
*/
runExternalModule(file: string): Promise<any>;
}
type ResolvedResult = (ExternalFetchResult | ViteFetchResult) & {
url: string;
id: string;
};
type FetchFunction = (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
interface ModuleRunnerHmr {
/**
* Configure HMR logger.
*/
logger?: false | HMRLogger;
}
interface ModuleRunnerOptions {
/**
* Root of the project
* @deprecated not used and to be removed
*/
root?: string;
/**
* A set of methods to communicate with the server.
*/
transport: ModuleRunnerTransport;
/**
* Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
* Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
* You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
*/
sourcemapInterceptor?: false | 'node' | 'prepareStackTrace' | InterceptorOptions;
/**
* Disable HMR or configure HMR options.
*
* @default true
*/
hmr?: boolean | ModuleRunnerHmr;
/**
* Custom module cache. If not provided, creates a separate module cache for each ModuleRunner instance.
*/
evaluatedModules?: EvaluatedModules;
}
interface ImportMetaEnv {
[key: string]: any;
BASE_URL: string;
MODE: string;
DEV: boolean;
PROD: boolean;
SSR: boolean;
}
declare class EvaluatedModuleNode {
id: string;
url: string;
importers: Set<string>;
imports: Set<string>;
evaluated: boolean;
meta: ResolvedResult | undefined;
promise: Promise<any> | undefined;
exports: any | undefined;
file: string;
map: DecodedMap | undefined;
constructor(id: string, url: string);
}
declare class EvaluatedModules {
readonly idToModuleMap: Map<string, EvaluatedModuleNode>;
readonly fileToModulesMap: Map<string, Set<EvaluatedModuleNode>>;
readonly urlToIdModuleMap: Map<string, EvaluatedModuleNode>;
/**
* Returns the module node by the resolved module ID. Usually, module ID is
* the file system path with query and/or hash. It can also be a virtual module.
*
* Module runner graph will have 1 to 1 mapping with the server module graph.
* @param id Resolved module ID
*/
getModuleById(id: string): EvaluatedModuleNode | undefined;
/**
* Returns all modules related to the file system path. Different modules
* might have different query parameters or hash, so it's possible to have
* multiple modules for the same file.
* @param file The file system path of the module
*/
getModulesByFile(file: string): Set<EvaluatedModuleNode> | undefined;
/**
* Returns the module node by the URL that was used in the import statement.
* Unlike module graph on the server, the URL is not resolved and is used as is.
* @param url Server URL that was used in the import statement
*/
getModuleByUrl(url: string): EvaluatedModuleNode | undefined;
/**
* Ensure that module is in the graph. If the module is already in the graph,
* it will return the existing module node. Otherwise, it will create a new
* module node and add it to the graph.
* @param id Resolved module ID
* @param url URL that was used in the import statement
*/
ensureModule(id: string, url: string): EvaluatedModuleNode;
invalidateModule(node: EvaluatedModuleNode): void;
/**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* @param id Resolved module ID
*/
getModuleSourceMapById(id: string): DecodedMap | null;
clear(): void;
}
declare class ESModulesEvaluator implements ModuleEvaluator {
readonly startOffset: number;
runInlinedModule(context: ModuleRunnerContext, code: string): Promise<any>;
runExternalModule(filepath: string): Promise<any>;
}
export { ESModulesEvaluator, EvaluatedModuleNode, EvaluatedModules, FetchFunctionOptions, FetchResult, ModuleRunner, ModuleRunnerTransport, ssrDynamicImportKey, ssrExportAllKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };
export type { FetchFunction, HMRLogger, InterceptorOptions, ModuleEvaluator, ModuleRunnerContext, ModuleRunnerHmr, ModuleRunnerImportMeta, ModuleRunnerOptions, ResolvedResult, SSRImportMetadata };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,87 @@
import { HotPayload } from '../../types/hmrPayload.js';
interface FetchFunctionOptions {
cached?: boolean;
startOffset?: number;
}
type FetchResult = CachedFetchResult | ExternalFetchResult | ViteFetchResult;
interface CachedFetchResult {
/**
* If module cached in the runner, we can just confirm
* it wasn't invalidated on the server side.
*/
cache: true;
}
interface ExternalFetchResult {
/**
* The path to the externalized module starting with file://,
* by default this will be imported via a dynamic "import"
* instead of being transformed by vite and loaded with vite runner
*/
externalize: string;
/**
* Type of the module. Will be used to determine if import statement is correct.
* For example, if Vite needs to throw an error if variable is not actually exported
*/
type: 'module' | 'commonjs' | 'builtin' | 'network';
}
interface ViteFetchResult {
/**
* Code that will be evaluated by vite runner
* by default this will be wrapped in an async function
*/
code: string;
/**
* File path of the module on disk.
* This will be resolved as import.meta.url/filename
* Will be equal to `null` for virtual modules
*/
file: string | null;
/**
* Module ID in the server module graph.
*/
id: string;
/**
* Module URL used in the import.
*/
url: string;
/**
* Invalidate module on the client side.
*/
invalidate: boolean;
}
type InvokeMethods = {
fetchModule: (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
};
type ModuleRunnerTransportHandlers = {
onMessage: (data: HotPayload) => void;
onDisconnection: () => void;
};
/**
* "send and connect" or "invoke" must be implemented
*/
interface ModuleRunnerTransport {
connect?(handlers: ModuleRunnerTransportHandlers): Promise<void> | void;
disconnect?(): Promise<void> | void;
send?(data: HotPayload): Promise<void> | void;
invoke?(data: HotPayload): Promise<{
result: any;
} | {
error: any;
}>;
timeout?: number;
}
interface NormalizedModuleRunnerTransport {
connect?(onMessage?: (data: HotPayload) => void): Promise<void> | void;
disconnect?(): Promise<void> | void;
send(data: HotPayload): Promise<void>;
invoke<T extends keyof InvokeMethods>(name: T, data: Parameters<InvokeMethods[T]>): Promise<ReturnType<Awaited<InvokeMethods[T]>>>;
}
declare const createWebSocketModuleRunnerTransport: (options: {
createConnection: () => WebSocket;
pingInterval?: number;
}) => Required<Pick<ModuleRunnerTransport, "connect" | "disconnect" | "send">>;
export { createWebSocketModuleRunnerTransport as c };
export type { ExternalFetchResult as E, FetchFunctionOptions as F, ModuleRunnerTransport as M, NormalizedModuleRunnerTransport as N, ViteFetchResult as V, FetchResult as a, ModuleRunnerTransportHandlers as b };

View File

@@ -1,63 +0,0 @@
import { V as ViteRuntimeOptions, b as ViteModuleRunner, M as ModuleCacheMap, c as HMRClient, R as ResolvedResult, d as ViteRuntimeModuleContext } from './types.d-aGj9QkWt.js';
export { a as FetchFunction, F as FetchResult, e as HMRConnection, H as HMRLogger, g as HMRRuntimeConnection, f as ModuleCache, S as SSRImportMetadata, h as ViteRuntimeImportMeta, s as ssrDynamicImportKey, i as ssrExportAllKey, j as ssrImportKey, k as ssrImportMetaKey, l as ssrModuleExportsKey } from './types.d-aGj9QkWt.js';
import '../../types/hot.js';
import '../../types/hmrPayload.js';
import '../../types/customEvent.js';
interface ViteRuntimeDebugger {
(formatter: unknown, ...args: unknown[]): void;
}
declare class ViteRuntime {
options: ViteRuntimeOptions;
runner: ViteModuleRunner;
private debug?;
/**
* Holds the cache of modules
* Keys of the map are ids
*/
moduleCache: ModuleCacheMap;
hmrClient?: HMRClient;
entrypoints: Set<string>;
private idToUrlMap;
private fileToIdMap;
private envProxy;
private _destroyed;
private _resetSourceMapSupport?;
constructor(options: ViteRuntimeOptions, runner: ViteModuleRunner, debug?: ViteRuntimeDebugger | undefined);
/**
* URL to execute. Accepts file path, server path or id relative to the root.
*/
executeUrl<T = any>(url: string): Promise<T>;
/**
* Entrypoint URL to execute. Accepts file path, server path or id relative to the root.
* In the case of a full reload triggered by HMR, this is the module that will be reloaded.
* If this method is called multiple times, all entrypoints will be reloaded one at a time.
*/
executeEntrypoint<T = any>(url: string): Promise<T>;
/**
* Clear all caches including HMR listeners.
*/
clearCache(): void;
/**
* Clears all caches, removes all HMR listeners, and resets source map support.
* This method doesn't stop the HMR connection.
*/
destroy(): Promise<void>;
/**
* Returns `true` if the runtime has been destroyed by calling `destroy()` method.
*/
isDestroyed(): boolean;
private invalidateFiles;
private normalizeEntryUrl;
private processImport;
private cachedRequest;
private cachedModule;
protected directRequest(id: string, fetchResult: ResolvedResult, _callstack: string[]): Promise<any>;
}
declare class ESModulesRunner implements ViteModuleRunner {
runViteModule(context: ViteRuntimeModuleContext, code: string): Promise<any>;
runExternalModule(filepath: string): Promise<any>;
}
export { ESModulesRunner, ModuleCacheMap, ResolvedResult, ViteModuleRunner, ViteRuntime, ViteRuntimeModuleContext, ViteRuntimeOptions };

View File

@@ -1,281 +0,0 @@
import { ModuleNamespace, ViteHotContext } from '../../types/hot.js';
import { Update, HMRPayload } from '../../types/hmrPayload.js';
import { InferCustomEventPayload } from '../../types/customEvent.js';
type CustomListenersMap = Map<string, ((data: any) => void)[]>;
interface HotModule {
id: string;
callbacks: HotCallback[];
}
interface HotCallback {
deps: string[];
fn: (modules: Array<ModuleNamespace | undefined>) => void;
}
interface HMRLogger {
error(msg: string | Error): void;
debug(...msg: unknown[]): void;
}
interface HMRConnection {
/**
* Checked before sending messages to the client.
*/
isReady(): boolean;
/**
* Send message to the client.
*/
send(messages: string): void;
}
declare class HMRMessenger {
private connection;
constructor(connection: HMRConnection);
private queue;
send(message: string): void;
flush(): void;
}
declare class HMRClient {
logger: HMRLogger;
private importUpdatedModule;
hotModulesMap: Map<string, HotModule>;
disposeMap: Map<string, (data: any) => void | Promise<void>>;
pruneMap: Map<string, (data: any) => void | Promise<void>>;
dataMap: Map<string, any>;
customListenersMap: CustomListenersMap;
ctxToListenersMap: Map<string, CustomListenersMap>;
messenger: HMRMessenger;
constructor(logger: HMRLogger, connection: HMRConnection, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<void>;
clear(): void;
prunePaths(paths: string[]): Promise<void>;
protected warnFailedUpdate(err: Error, path: string | string[]): void;
private updateQueue;
private pendingUpdateQueue;
/**
* buffer multiple hot updates triggered by the same src change
* so that they are invoked in the same order they were sent.
* (otherwise the order may be inconsistent because of the http request round trip)
*/
queueUpdate(payload: Update): Promise<void>;
private fetchUpdate;
}
interface DefineImportMetadata {
/**
* Imported names before being transformed to `ssrImportKey`
*
* import foo, { bar as baz, qux } from 'hello'
* => ['default', 'bar', 'qux']
*
* import * as namespace from 'world
* => undefined
*/
importedNames?: string[];
}
interface SSRImportBaseMetadata extends DefineImportMetadata {
isDynamicImport?: boolean;
}
interface SourceMapLike {
version: number;
mappings?: string;
names?: string[];
sources?: string[];
sourcesContent?: string[];
}
declare class DecodedMap {
map: SourceMapLike;
_encoded: string;
_decoded: undefined | number[][][];
_decodedMemo: Stats;
url: string;
version: number;
names: string[];
resolvedSources: string[];
constructor(map: SourceMapLike, from: string);
}
interface Stats {
lastKey: number;
lastNeedle: number;
lastIndex: number;
}
declare class ModuleCacheMap extends Map<string, ModuleCache> {
private root;
constructor(root: string, entries?: [string, ModuleCache][]);
normalize(fsPath: string): string;
/**
* Assign partial data to the map
*/
update(fsPath: string, mod: ModuleCache): this;
setByModuleId(modulePath: string, mod: ModuleCache): this;
set(fsPath: string, mod: ModuleCache): this;
getByModuleId(modulePath: string): ModuleCache;
get(fsPath: string): ModuleCache;
deleteByModuleId(modulePath: string): boolean;
delete(fsPath: string): boolean;
invalidate(id: string): void;
isImported({ importedId, importedBy, }: {
importedId: string;
importedBy: string;
}, seen?: Set<string>): boolean;
/**
* Invalidate modules that dependent on the given modules, up to the main entry
*/
invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/**
* Invalidate dependency modules of the given modules, down to the bottom-level dependencies
*/
invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
getSourceMap(moduleId: string): null | DecodedMap;
}
declare const ssrModuleExportsKey = "__vite_ssr_exports__";
declare const ssrImportKey = "__vite_ssr_import__";
declare const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
declare const ssrExportAllKey = "__vite_ssr_exportAll__";
declare const ssrImportMetaKey = "__vite_ssr_import_meta__";
interface RetrieveFileHandler {
(path: string): string | null | undefined | false;
}
interface RetrieveSourceMapHandler {
(path: string): null | {
url: string;
map: any;
};
}
interface InterceptorOptions {
retrieveFile?: RetrieveFileHandler;
retrieveSourceMap?: RetrieveSourceMapHandler;
}
interface SSRImportMetadata extends SSRImportBaseMetadata {
entrypoint?: boolean;
}
interface HMRRuntimeConnection extends HMRConnection {
/**
* Configure how HMR is handled when this connection triggers an update.
* This method expects that connection will start listening for HMR updates and call this callback when it's received.
*/
onUpdate(callback: (payload: HMRPayload) => void): void;
}
interface ViteRuntimeImportMeta extends ImportMeta {
url: string;
env: ImportMetaEnv;
hot?: ViteHotContext;
[key: string]: any;
}
interface ViteRuntimeModuleContext {
[ssrModuleExportsKey]: Record<string, any>;
[ssrImportKey]: (id: string, metadata?: DefineImportMetadata) => Promise<any>;
[ssrDynamicImportKey]: (id: string, options?: ImportCallOptions) => Promise<any>;
[ssrExportAllKey]: (obj: any) => void;
[ssrImportMetaKey]: ViteRuntimeImportMeta;
}
interface ViteModuleRunner {
/**
* Run code that was transformed by Vite.
* @param context Function context
* @param code Transformed code
* @param id ID that was used to fetch the module
*/
runViteModule(context: ViteRuntimeModuleContext, code: string, id: string): Promise<any>;
/**
* Run externalized module.
* @param file File URL to the external module
*/
runExternalModule(file: string): Promise<any>;
}
interface ModuleCache {
promise?: Promise<any>;
exports?: any;
evaluated?: boolean;
map?: DecodedMap;
meta?: FetchResult;
/**
* Module ids that imports this module
*/
importers?: Set<string>;
imports?: Set<string>;
}
type FetchResult = ExternalFetchResult | ViteFetchResult;
interface ExternalFetchResult {
/**
* The path to the externalized module starting with file://,
* by default this will be imported via a dynamic "import"
* instead of being transformed by vite and loaded with vite runtime
*/
externalize: string;
/**
* Type of the module. Will be used to determine if import statement is correct.
* For example, if Vite needs to throw an error if variable is not actually exported
*/
type?: 'module' | 'commonjs' | 'builtin' | 'network';
}
interface ViteFetchResult {
/**
* Code that will be evaluated by vite runtime
* by default this will be wrapped in an async function
*/
code: string;
/**
* File path of the module on disk.
* This will be resolved as import.meta.url/filename
*/
file: string | null;
}
type ResolvedResult = (ExternalFetchResult | ViteFetchResult) & {
id: string;
};
/**
* @experimental
*/
type FetchFunction = (id: string, importer?: string) => Promise<FetchResult>;
interface ViteRuntimeOptions {
/**
* Root of the project
*/
root: string;
/**
* A method to get the information about the module.
* For SSR, Vite exposes `server.ssrFetchModule` function that you can use here.
* For other runtime use cases, Vite also exposes `fetchModule` from its main entry point.
*/
fetchModule: FetchFunction;
/**
* Custom environment variables available on `import.meta.env`. This doesn't modify the actual `process.env`.
*/
environmentVariables?: Record<string, any>;
/**
* Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
* Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
* You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
*/
sourcemapInterceptor?: false | 'node' | 'prepareStackTrace' | InterceptorOptions;
/**
* Disable HMR or configure HMR options.
*/
hmr?: false | {
/**
* Configure how HMR communicates between the client and the server.
*/
connection: HMRRuntimeConnection;
/**
* Configure HMR logger.
*/
logger?: false | HMRLogger;
};
/**
* Custom module cache. If not provided, creates a separate module cache for each ViteRuntime instance.
*/
moduleCache?: ModuleCacheMap;
}
interface ImportMetaEnv {
[key: string]: any;
BASE_URL: string;
MODE: string;
DEV: boolean;
PROD: boolean;
SSR: boolean;
}
export { type FetchResult as F, type HMRLogger as H, ModuleCacheMap as M, type ResolvedResult as R, type SSRImportMetadata as S, type ViteRuntimeOptions as V, type FetchFunction as a, type ViteModuleRunner as b, HMRClient as c, type ViteRuntimeModuleContext as d, type HMRConnection as e, type ModuleCache as f, type HMRRuntimeConnection as g, type ViteRuntimeImportMeta as h, ssrExportAllKey as i, ssrImportKey as j, ssrImportMetaKey as k, ssrModuleExportsKey as l, ssrDynamicImportKey as s };

42
node_modules/vite/index.cjs generated vendored
View File

@@ -1,3 +1,6 @@
const description =
' See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.'
warnCjsUsage()
// type utils
@@ -17,12 +20,47 @@ const asyncFunctions = [
'formatPostcssSourceMap',
'loadConfigFromFile',
'preprocessCSS',
'createBuilder',
'runnerImport',
]
asyncFunctions.forEach((name) => {
module.exports[name] = (...args) =>
import('./dist/node/index.js').then((i) => i[name](...args))
})
// variables and sync functions that cannot be used from cjs build
const disallowedVariables = [
// was not exposed in cjs from the beginning
'parseAst',
'parseAstAsync',
'buildErrorMessage',
'sortUserPlugins',
// Environment API related variables that are too big to include in the cjs build
'DevEnvironment',
'BuildEnvironment',
'createIdResolver',
'createRunnableDevEnvironment',
// can be redirected from ESM, but doesn't make sense as it's Environment API related
'fetchModule',
'moduleRunnerTransform',
// can be exposed, but doesn't make sense as it's Environment API related
'createServerHotChannel',
'createServerModuleRunner',
'createServerModuleRunnerTransport',
'isRunnableDevEnvironment',
'createFetchableDevEnvironment',
'isFetchableDevEnvironment',
]
disallowedVariables.forEach((name) => {
Object.defineProperty(module.exports, name, {
get() {
throw new Error(
`${name} is not available in the CJS build of Vite.` + description,
)
},
})
})
function warnCjsUsage() {
if (process.env.VITE_CJS_IGNORE_WARNING) return
const logLevelIndex = process.argv.findIndex((arg) =>
@@ -39,9 +77,7 @@ function warnCjsUsage() {
}
const yellow = (str) => `\u001b[33m${str}\u001b[39m`
console.warn(
yellow(
`The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.`,
),
yellow("The CJS build of Vite's Node API is deprecated." + description),
)
if (process.env.VITE_CJS_TRACE) {
const e = {}

1
node_modules/vite/misc/false.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default false

1
node_modules/vite/misc/true.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default true

143
node_modules/vite/package.json generated vendored
View File

@@ -1,6 +1,6 @@
{
"name": "vite",
"version": "5.4.19",
"version": "6.3.5",
"type": "module",
"license": "MIT",
"author": "Evan You",
@@ -20,45 +20,45 @@
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/node/index.d.ts",
"default": "./dist/node/index.js"
},
"require": {
"types": "./index.d.cts",
"default": "./index.cjs"
}
"module-sync": "./dist/node/index.js",
"import": "./dist/node/index.js",
"require": "./index.cjs"
},
"./client": {
"types": "./client.d.ts"
},
"./runtime": {
"types": "./dist/node/runtime.d.ts",
"import": "./dist/node/runtime.js"
},
"./module-runner": "./dist/node/module-runner.js",
"./dist/client/*": "./dist/client/*",
"./types/*": {
"types": "./types/*"
},
"./types/internal/*": null,
"./package.json": "./package.json"
},
"typesVersions": {
"*": {
"runtime": [
"dist/node/runtime.d.ts"
"module-runner": [
"dist/node/module-runner.d.ts"
]
}
},
"imports": {
"#module-sync-enabled": {
"module-sync": "./misc/true.js",
"default": "./misc/false.js"
}
},
"files": [
"bin",
"dist",
"misc/**/*.js",
"client.d.ts",
"index.cjs",
"index.d.cts",
"types"
],
"engines": {
"node": "^18.0.0 || >=20.0.0"
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"repository": {
"type": "git",
@@ -72,88 +72,95 @@
"funding": "https://github.com/vitejs/vite?sponsor=1",
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
"rollup": "^4.20.0"
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
"picomatch": "^4.0.2",
"postcss": "^8.5.3",
"rollup": "^4.34.9",
"tinyglobby": "^0.2.13"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"devDependencies": {
"@ampproject/remapping": "^2.3.0",
"@babel/parser": "^7.25.6",
"@babel/parser": "^7.27.0",
"@jridgewell/trace-mapping": "^0.3.25",
"@polka/compression": "^1.0.0-next.25",
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-commonjs": "^26.0.1",
"@rollup/plugin-dynamic-import-vars": "^2.1.2",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^28.0.3",
"@rollup/plugin-dynamic-import-vars": "2.1.4",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "15.2.3",
"@rollup/pluginutils": "^5.1.0",
"@rollup/plugin-node-resolve": "16.0.1",
"@rollup/pluginutils": "^5.1.4",
"@types/escape-html": "^1.0.4",
"@types/pnpapi": "^0.0.5",
"artichokie": "^0.2.1",
"artichokie": "^0.3.1",
"cac": "^6.7.14",
"chokidar": "^3.6.0",
"connect": "^3.7.0",
"convert-source-map": "^2.0.0",
"cors": "^2.8.5",
"cross-spawn": "^7.0.3",
"debug": "^4.3.6",
"cross-spawn": "^7.0.6",
"debug": "^4.4.0",
"dep-types": "link:./src/types",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"es-module-lexer": "^1.5.4",
"dotenv": "^16.5.0",
"dotenv-expand": "^12.0.2",
"es-module-lexer": "^1.6.0",
"escape-html": "^1.0.3",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
"fast-glob": "^3.3.2",
"http-proxy": "^1.18.1",
"launch-editor-middleware": "^2.9.1",
"lightningcss": "^1.26.0",
"magic-string": "^0.30.11",
"micromatch": "^4.0.8",
"mlly": "^1.7.1",
"mrmime": "^2.0.0",
"open": "^8.4.2",
"parse5": "^7.1.2",
"pathe": "^1.1.2",
"launch-editor-middleware": "^2.10.0",
"lightningcss": "^1.29.3",
"magic-string": "^0.30.17",
"mlly": "^1.7.4",
"mrmime": "^2.0.1",
"nanoid": "^5.1.5",
"open": "^10.1.1",
"parse5": "^7.2.1",
"pathe": "^2.0.3",
"periscopic": "^4.0.2",
"picocolors": "^1.0.1",
"picomatch": "^2.3.1",
"picocolors": "^1.1.1",
"postcss-import": "^16.1.0",
"postcss-load-config": "^4.0.2",
"postcss-modules": "^6.0.0",
"resolve.exports": "^2.0.2",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-esbuild": "^6.1.1",
"rollup-plugin-license": "^3.5.2",
"sass": "^1.77.8",
"sass-embedded": "^1.77.8",
"sirv": "^2.0.4",
"postcss-load-config": "^6.0.1",
"postcss-modules": "^6.0.1",
"resolve.exports": "^2.0.3",
"rollup-plugin-dts": "^6.2.1",
"rollup-plugin-esbuild": "^6.2.1",
"rollup-plugin-license": "^3.6.0",
"sass": "^1.86.3",
"sass-embedded": "^1.86.3",
"sirv": "^3.0.1",
"source-map-support": "^0.5.21",
"strip-ansi": "^7.1.0",
"strip-literal": "^2.1.0",
"tsconfck": "^3.1.4",
"tslib": "^2.7.0",
"strip-literal": "^3.0.0",
"terser": "^5.39.0",
"tsconfck": "^3.1.5",
"tslib": "^2.8.1",
"types": "link:./types",
"ufo": "^1.5.4",
"ws": "^8.18.0"
"ufo": "^1.6.1",
"ws": "^8.18.1"
},
"peerDependencies": {
"@types/node": "^18.0.0 || >=20.0.0",
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"jiti": ">=1.21.0",
"less": "*",
"lightningcss": "^1.21.0",
"sass": "*",
"sass-embedded": "*",
"stylus": "*",
"sugarss": "*",
"terser": "^5.4.0"
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"jiti": {
"optional": true
},
"sass": {
"optional": true
},
@@ -174,17 +181,23 @@
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
},
"scripts": {
"dev": "tsx scripts/dev.ts",
"build": "rimraf dist && run-s build-bundle build-types",
"build": "premove dist && pnpm build-bundle && pnpm build-types",
"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 esbuild && rimraf temp",
"build-types": "pnpm build-types-temp && pnpm build-types-roll && pnpm build-types-check",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp -p src/node/tsconfig.build.json",
"build-types-roll": "rollup --config rollup.dts.config.ts --configPlugin esbuild && premove temp",
"build-types-check": "tsc --project tsconfig.check.json",
"typecheck": "tsc --noEmit",
"typecheck": "tsc --noEmit && tsc --noEmit -p src/node",
"lint": "eslint --cache --ext .ts src/**",
"format": "prettier --write --cache --parser typescript \"src/**/*.ts\""
}

View File

@@ -30,10 +30,16 @@ export interface WebSocketConnectionPayload {
export interface InvalidatePayload {
path: string
message: string | undefined
firstInvalidatedBy: string
}
/**
* provides types for built-in Vite events
* provides types for payloads of built-in Vite events
*/
export type InferCustomEventPayload<T extends string> =
T extends keyof CustomEventMap ? CustomEventMap[T] : any
/**
* provides types for names of built-in Vite events
*/
export type CustomEventName = keyof CustomEventMap | (string & {})

View File

@@ -1,5 +1,8 @@
export type HMRPayload =
/** @deprecated use HotPayload */
export type HMRPayload = HotPayload
export type HotPayload =
| ConnectedPayload
| PingPayload
| UpdatePayload
| FullReloadPayload
| CustomPayload
@@ -10,6 +13,10 @@ export interface ConnectedPayload {
type: 'connected'
}
export interface PingPayload {
type: 'ping'
}
export interface UpdatePayload {
type: 'update'
updates: Update[]
@@ -25,7 +32,9 @@ export interface Update {
/** @internal */
isWithinCircularImport?: boolean
/** @internal */
ssrInvalidates?: string[]
firstInvalidatedBy?: string
/** @internal */
invalidates?: string[]
}
export interface PrunePayload {

11
node_modules/vite/types/hot.d.ts generated vendored
View File

@@ -1,4 +1,4 @@
import type { InferCustomEventPayload } from './customEvent'
import type { CustomEventName, InferCustomEventPayload } from './customEvent'
export type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: 'Module'
@@ -24,13 +24,16 @@ export interface ViteHotContext {
prune(cb: (data: any) => void): void
invalidate(message?: string): void
on<T extends string>(
on<T extends CustomEventName>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
off<T extends string>(
off<T extends CustomEventName>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
send<T extends CustomEventName>(
event: T,
data?: InferCustomEventPayload<T>,
): void
}

View File

@@ -2,8 +2,17 @@
// Thus cannot contain any top-level imports
// <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
// This is tested in `packages/vite/src/node/__tests_dts__/typeOptions.ts`
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- to allow extending by users
interface ViteTypeOptions {
// strictImportMetaEnv: unknown
}
type ImportMetaEnvFallbackKey =
'strictImportMetaEnv' extends keyof ViteTypeOptions ? never : string
interface ImportMetaEnv {
[key: string]: any
[key: ImportMetaEnvFallbackKey]: any
BASE_URL: string
MODE: string
DEV: boolean

View File

@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore `sass` may not be installed
import type DartSass from 'sass'
// @ts-ignore `sass-embedded` may not be installed
import type SassEmbedded from 'sass-embedded'
// @ts-ignore `less` may not be installed
import type Less from 'less'
// @ts-ignore `stylus` may not be installed
import type Stylus from 'stylus'
/* eslint-enable @typescript-eslint/ban-ts-comment */
// https://github.com/type-challenges/type-challenges/issues/29285
type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false
type DartSassLegacyStringOptionsAsync = DartSass.LegacyStringOptions<'async'>
type SassEmbeddedLegacyStringOptionsAsync =
SassEmbedded.LegacyStringOptions<'async'>
type SassLegacyStringOptionsAsync =
IsAny<DartSassLegacyStringOptionsAsync> extends false
? DartSassLegacyStringOptionsAsync
: SassEmbeddedLegacyStringOptionsAsync
export type SassLegacyPreprocessBaseOptions = Omit<
SassLegacyStringOptionsAsync,
| 'data'
| 'file'
| 'outFile'
| 'sourceMap'
| 'omitSourceMapUrl'
| 'sourceMapEmbed'
| 'sourceMapRoot'
>
type DartSassStringOptionsAsync = DartSass.StringOptions<'async'>
type SassEmbeddedStringOptionsAsync = SassEmbedded.StringOptions<'async'>
type SassStringOptionsAsync =
IsAny<DartSassStringOptionsAsync> extends false
? DartSassStringOptionsAsync
: SassEmbeddedStringOptionsAsync
export type SassModernPreprocessBaseOptions = Omit<
SassStringOptionsAsync,
'url' | 'sourceMap'
>
export type LessPreprocessorBaseOptions = Omit<
Less.Options,
'sourceMap' | 'filename'
>
export type StylusPreprocessorBaseOptions = Omit<
Stylus.RenderOptions,
'filename'
> & { define?: Record<string, any> }
declare global {
// LESS' types somewhat references this which doesn't make sense in Node,
// so we have to shim it
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface HTMLLinkElement {}
}

View File

@@ -0,0 +1,18 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore `lightningcss` may not be installed
import type Lightningcss from 'lightningcss'
/* eslint-enable @typescript-eslint/ban-ts-comment */
export type LightningCSSOptions = Omit<
Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>,
| 'filename'
| 'resolver'
| 'minify'
| 'sourceMap'
| 'analyzeDependencies'
// properties not overridden by Vite, but does not make sense to set by end users
| 'inputSourceMap'
| 'projectRoot'
>

View File

@@ -3,8 +3,33 @@ export interface ChunkMetadata {
importedCss: Set<string>
}
export interface CustomPluginOptionsVite {
/**
* If this is a CSS Rollup module, you can scope to its importer's exports
* so that if those exports are treeshaken away, the CSS module will also
* be treeshaken.
*
* The "importerId" must import the CSS Rollup module statically.
*
* Example config if the CSS id is `/src/App.vue?vue&type=style&lang.css`:
* ```js
* cssScopeTo: ['/src/App.vue', 'default']
* ```
*
* @experimental
*/
cssScopeTo?: readonly [importerId: string, exportName: string | undefined]
/** @deprecated no-op since Vite 6.1 */
lang?: string
}
declare module 'rollup' {
export interface RenderedChunk {
viteMetadata?: ChunkMetadata
}
export interface CustomPluginOptions {
vite?: CustomPluginOptionsVite
}
}