Update package dependencies and remove unused files from node_modules

This commit is contained in:
becarta
2025-05-16 00:25:30 +02:00
parent 04584e9c98
commit 969d9c0af3
250 changed files with 47796 additions and 47121 deletions

View File

@@ -56,19 +56,13 @@ class HMRContext {
decline() {
}
invalidate(message) {
const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
this.hmrClient.notifyListeners("vite:invalidate", {
path: this.ownerPath,
message,
firstInvalidatedBy
});
this.send("vite:invalidate", {
path: this.ownerPath,
message,
firstInvalidatedBy
message
});
this.send("vite:invalidate", { path: this.ownerPath, message });
this.hmrClient.logger.debug(
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
);
}
on(event, cb) {
@@ -97,7 +91,9 @@ class HMRContext {
removeFromMap(this.newListeners);
}
send(event, data) {
this.hmrClient.send({ type: "custom", event, data });
this.hmrClient.messenger.send(
JSON.stringify({ type: "custom", event, data })
);
}
acceptDeps(deps, callback = () => {
}) {
@@ -112,10 +108,25 @@ 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, transport, importUpdatedModule) {
constructor(logger, connection, importUpdatedModule) {
this.logger = logger;
this.transport = transport;
this.importUpdatedModule = importUpdatedModule;
this.hotModulesMap = /* @__PURE__ */ new Map();
this.disposeMap = /* @__PURE__ */ new Map();
@@ -125,6 +136,7 @@ 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);
@@ -132,11 +144,6 @@ 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();
@@ -147,7 +154,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) => {
@@ -163,11 +170,11 @@ class HMRClient {
});
}
warnFailedUpdate(err, path) {
if (!(err instanceof Error) || !err.message.includes("fetch")) {
if (!err.message.includes("fetch")) {
this.logger.error(err);
}
this.logger.error(
`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
/**
@@ -187,7 +194,7 @@ class HMRClient {
}
}
async fetchUpdate(update) {
const { path, acceptedPath, firstInvalidatedBy } = update;
const { path, acceptedPath } = update;
const mod = this.hotModulesMap.get(path);
if (!mod) {
return;
@@ -207,317 +214,14 @@ class HMRClient {
}
}
return () => {
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;
}
};
}
}
/* @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)}`
)
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
});
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 loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`[vite] hot updated: ${loggedPath}`);
};
}
}
@@ -757,21 +461,23 @@ class ErrorOverlay extends HTMLElement {
fileRE.lastIndex = 0;
while (match = fileRE.exec(text)) {
const { 0: file, index } = match;
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;
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;
}
}
}
}
@@ -794,68 +500,69 @@ 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__;
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.
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.
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 .`
);
}
}
return;
}
console.error(`[vite] failed to connect to websocket (${e}). `);
throw e;
}
},
async disconnect() {
await wsTransport.disconnect();
},
send(data) {
wsTransport.send(data);
}
);
});
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 }
);
};
})()
);
let willUnload = false;
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
willUnload = true;
}
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));
});
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");
@@ -878,11 +585,11 @@ const debounceReload = (time) => {
};
const pageReload = debounceReload(50);
const hmrClient = new HMRClient(
console,
{
error: (err) => console.error("[vite]", err),
debug: (...msg) => console.debug("[vite]", ...msg)
isReady: () => socket && socket.readyState === 1,
send: (message) => socket.send(message)
},
transport,
async function importUpdatedModule({
acceptedPath,
timestamp,
@@ -905,14 +612,19 @@ 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":
await hmrClient.notifyListeners("vite:beforeUpdate", payload);
notifyListeners("vite:beforeUpdate", payload);
if (hasDocument) {
if (isFirstUpdate && hasErrorOverlay()) {
location.reload();
@@ -955,24 +667,14 @@ async function handleMessage(payload) {
});
})
);
await hmrClient.notifyListeners("vite:afterUpdate", payload);
notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
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();
}
}
notifyListeners(payload.event, payload.data);
break;
}
case "full-reload":
await hmrClient.notifyListeners("vite:beforeFullReload", payload);
notifyListeners("vite:beforeFullReload", payload);
if (hasDocument) {
if (payload.path && payload.path.endsWith(".html")) {
const pagePath = decodeURI(location.pathname);
@@ -987,11 +689,11 @@ async function handleMessage(payload) {
}
break;
case "prune":
await hmrClient.notifyListeners("vite:beforePrune", payload);
notifyListeners("vite:beforePrune", payload);
await hmrClient.prunePaths(payload.paths);
break;
case "error": {
await hmrClient.notifyListeners("vite:error", payload);
notifyListeners("vite:error", payload);
if (hasDocument) {
const err = payload.err;
if (enableOverlay) {
@@ -1006,23 +708,20 @@ ${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();
const { customElements } = globalThis;
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId);
document.body.appendChild(new ErrorOverlayConstructor(err));
}
document.body.appendChild(new ErrorOverlay(err));
}
function clearErrorOverlay() {
document.querySelectorAll(overlayId).forEach((n) => n.close());
@@ -1030,27 +729,23 @@ function clearErrorOverlay() {
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length;
}
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);
});
}
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;
};
if (await ping()) {
return;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,11 +1,19 @@
import { Q as commonjsGlobal, P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import require$$0$2 from 'fs';
import { D as commonjsGlobal, C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import require$$0__default from 'fs';
import require$$0 from 'postcss';
import require$$0$1 from 'path';
import require$$3 from 'crypto';
import require$$1 from 'util';
import { l as lib } from './dep-3RmXg9uo.js';
import require$$0$2 from 'util';
import { l as lib } from './dep-IQS-Za7F.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];
@@ -388,6 +396,9 @@ 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]';
@@ -722,7 +733,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;
}
/**
@@ -737,7 +748,7 @@ function baseToString(value) {
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (false && end >= length) ? array : baseSlice(array, start, end);
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
@@ -1459,7 +1470,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) & -4;
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
class WasmHash {
/**
@@ -2024,17 +2035,12 @@ function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
digestType === "base49" ||
digestType === "base52" ||
digestType === "base58" ||
digestType === "base62" ||
digestType === "base64safe"
digestType === "base62"
) {
return encodeBufferToBase(
hash.digest(),
digestType === "base64safe" ? 64 : digestType.substr(4),
maxLength
);
return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
} else {
return hash.digest(digestType || "hex").substr(0, maxLength);
}
return hash.digest(digestType || "hex").substr(0, maxLength);
}
var getHashDigest_1 = getHashDigest$1;
@@ -2090,10 +2096,9 @@ function interpolateName$1(loaderContext, name, options = {}) {
directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
}
if (directory.length <= 1) {
if (directory.length === 1) {
directory = "";
} else {
// directory.length > 1
} else if (directory.length > 1) {
folder = path$1.basename(directory);
}
}
@@ -2116,7 +2121,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*(?:safe)?))?(?::(\d+))?\]/gi,
/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
(all, hashType, digestType, maxLength) =>
getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
);
@@ -2645,9 +2650,6 @@ 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) {
@@ -2684,39 +2686,29 @@ types.UNIVERSAL = UNIVERSAL;
return this.removeAll();
};
_proto.insertAfter = function insertAfter(oldNode, newNode) {
var _this$nodes;
newNode.parent = this;
var oldIndex = this.index(oldNode);
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));
this.nodes.splice(oldIndex + 1, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex < index) {
this.indexes[id] = index + arguments.length - 1;
if (oldIndex <= index) {
this.indexes[id] = index + 1;
}
}
return this;
};
_proto.insertBefore = function insertBefore(oldNode, newNode) {
var _this$nodes2;
newNode.parent = this;
var oldIndex = this.index(oldNode);
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));
this.nodes.splice(oldIndex, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= oldIndex) {
this.indexes[id] = index + arguments.length - 1;
if (index <= oldIndex) {
this.indexes[id] = index + 1;
}
}
return this;
@@ -2742,7 +2734,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.
@@ -3410,7 +3402,7 @@ var attribute$1 = {};
* For Node.js, simply re-export the core `util.deprecate` function.
*/
var node = require$$1.deprecate;
var node = require$$0$2.deprecate;
(function (exports) {
@@ -4760,7 +4752,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 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
if (nodes.length > 0) {
var last = this.current.last;
@@ -5639,40 +5631,8 @@ 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 = [];
@@ -5692,8 +5652,6 @@ 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)) {
@@ -5901,7 +5859,7 @@ function localizeNode(rule, mode, localAliasMap) {
}
case "nesting": {
if (node.value === "&") {
context.hasLocals = rule.parent[isPureSelectorSymbol];
context.hasLocals = true;
}
}
}
@@ -6007,7 +5965,7 @@ function localizeDeclarationValues(localize, declaration, context) {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: localize,
localizeNextItem: localize && !context.global,
localAliasMap: context.localAliasMap,
};
nodes[index] = localizeDeclNode(node, subContext);
@@ -6016,20 +5974,24 @@ function localizeDeclarationValues(localize, declaration, context) {
declaration.value = valueNodes.toString();
}
// 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 (-).
function localizeDeclaration(declaration, context) {
const isAnimation = /animation$/i.test(declaration.prop);
// 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;
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;
/*
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
@@ -6040,43 +6002,38 @@ const validIdent =
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,
};
function localizeDeclaration(declaration, context) {
const isAnimation = /animation(-name)?$/i.test(declaration.prop);
if (isAnimation) {
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,
};
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.
@@ -6084,28 +6041,9 @@ function localizeDeclaration(declaration, context) {
parsedAnimationKeywords = {};
return;
} 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
}
// Do not handle nested functions
else if (node.type === "function") {
return false;
}
// Ignore all except word
@@ -6132,12 +6070,14 @@ function localizeDeclaration(declaration, context) {
}
}
return localizeDeclNode(node, {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: shouldParseAnimationName && !context.global,
localAliasMap: context.localAliasMap,
});
};
return localizeDeclNode(node, subContext);
});
declaration.value = valueNodes.toString();
@@ -6145,35 +6085,19 @@ function localizeDeclaration(declaration, context) {
return;
}
if (/url\(/i.test(declaration.value)) {
const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
if (isAnimationName) {
return localizeDeclarationValues(true, declaration, context);
}
const hasUrl = /url\(/i.test(declaration.value);
if (hasUrl) {
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 &&
@@ -6198,7 +6122,6 @@ 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) => {
@@ -6218,15 +6141,10 @@ src$2.exports = (options = {}) => {
let globalKeyframes = globalMode;
if (globalMatch) {
if (enforcePureMode) {
const ignoreComment = getIgnoreComment(atRule);
if (!ignoreComment) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
} else {
ignoreComment.remove();
}
if (pureMode) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
}
atRule.params = globalMatch[1];
globalKeyframes = true;
@@ -6250,14 +6168,6 @@ 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) => {
@@ -6271,11 +6181,7 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
if (
enforcePureMode &&
context.hasPureGlobals &&
!ignoreComment
) {
if (pureMode && context.hasPureGlobals) {
throw atRule.error(
'Selector in at-rule"' +
selector +
@@ -6326,28 +6232,13 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
const ignoreComment = enforcePureMode
? getIgnoreComment(rule)
: undefined;
const isNotPure = enforcePureMode && !isPureSelector(context, rule);
if (
isNotPure &&
isNodeWithoutDeclarations(rule) &&
!ignoreComment
) {
if (pureMode && context.hasPureGlobals) {
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;
@@ -7086,7 +6977,7 @@ function makePlugin(opts) {
};
}
var _fs = require$$0$2;
var _fs = require$$0__default;
var _fs2 = fs;

View File

@@ -1,10 +1,16 @@
import { P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import { C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import require$$0 from 'path';
import { l as lib } from './dep-3RmXg9uo.js';
import require$$0__default from 'fs';
import { l as lib } from './dep-IQS-Za7F.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 __require = __cjs_createRequire(import.meta.url);
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];
@@ -184,6 +190,160 @@ 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;
@@ -212,6 +372,17 @@ 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;
@@ -749,7 +920,7 @@ const path = require$$0;
const applyConditions = applyConditions$1;
const applyRaws = applyRaws$1;
const applyStyles = applyStyles$1;
const loadContent = () => "";
const loadContent = loadContent$1;
const parseStyles = parseStyles_1;
const resolveId = (id) => id;

View File

@@ -1,3 +1,11 @@
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);

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

@@ -2,22 +2,23 @@ import path from 'node:path';
import fs__default from 'node:fs';
import { performance } from 'node:perf_hooks';
import { EventEmitter } from 'events';
import { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-DBxKXgDP.js';
import { B as colors, v as createLogger, r as resolveConfig } from './chunks/dep-C6uTJdX2.js';
import { VERSION } from './constants.js';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'esbuild';
import 'tty';
import 'path';
import 'esbuild';
import 'fs';
import 'fdir';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'url';
@@ -26,26 +27,22 @@ import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
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 'module';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'node:buffer';
import 'rollup/parseAst';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'assert';
import 'node:querystring';
import 'node:zlib';
function toArr(any) {
@@ -693,7 +690,7 @@ const filterDuplicateOptions = (options) => {
}
}
};
function cleanGlobalCLIOptions(options) {
function cleanOptions(options) {
const ret = { ...options };
delete ret["--"];
delete ret.c;
@@ -702,27 +699,16 @@ function cleanGlobalCLIOptions(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) => {
@@ -739,34 +725,29 @@ 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(
"--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`);
}).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--open [path]", `[boolean | string] open browser on startup`).option("--cors", `[boolean] enable CORS`).option("--strictPort", `[boolean] exit if specified port is already in use`).option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(async (root, options) => {
filterDuplicateOptions(options);
const { createServer } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.S; });
const { createServer } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.F; });
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
server: cleanGlobalCLIOptions(options),
forceOptimizeDeps: options.force
optimizeDeps: { force: options.force },
server: cleanOptions(options)
});
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(
@@ -778,7 +759,7 @@ cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--
`
${colors.green(
`${colors.bold("VITE")} v${VERSION}`
)}${modeString} ${startupDurationString}
)} ${startupDurationString}
`,
{
clear: !hasExistingLogs
@@ -840,56 +821,44 @@ 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`).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)
);
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:
).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 }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
{ error: e }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
);
cli.command(
"optimize [root]",
"pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)"
).option(
});
cli.command("optimize [root]", "pre-bundle dependencies").option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(
async (root, options) => {
filterDuplicateOptions(options);
const { optimizeDeps } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.R; });
const { optimizeDeps } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.E; });
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode
},
@@ -909,13 +878,12 @@ ${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-DBxKXgDP.js').then(function (n) { return n.U; });
const { preview } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.H; });
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,35 +5,6 @@ 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",
@@ -42,25 +13,23 @@ 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",
@@ -98,8 +67,6 @@ const KNOWN_ASSET_TYPES = [
"ico",
"webp",
"avif",
"cur",
"jxl",
// media
"mp4",
"webm",
@@ -123,8 +90,7 @@ const KNOWN_ASSET_TYPES = [
"txt"
];
const DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`,
"i"
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`
);
const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
const loopbackHosts = /* @__PURE__ */ new Set([
@@ -143,7 +109,5 @@ 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_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 };
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 };

2447
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,24 +1,26 @@
export { parseAst, parseAstAsync } from 'rollup/parseAst';
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';
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';
export { version as esbuildVersion } from 'esbuild';
import 'node:fs';
import 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import { ViteRuntime, ESModulesRunner } from 'vite/runtime';
import 'node:fs/promises';
import 'node:path';
import 'node:url';
import 'node:util';
import 'node:perf_hooks';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'tty';
import 'path';
import 'fs';
import 'fdir';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'events';
@@ -28,25 +30,21 @@ import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
import 'vite/module-runner';
import 'node:buffer';
import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'module';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'node:buffer';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'assert';
import 'node:querystring';
import 'node:zlib';
const CSS_LANGS_RE = (
@@ -105,7 +103,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 });
}
@@ -113,7 +111,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) {
@@ -153,42 +151,111 @@ function splitVendorChunkPlugin() {
};
}
function createFetchableDevEnvironment(name, config, context) {
if (typeof Request === "undefined" || typeof Response === "undefined") {
throw new TypeError(
"FetchableDevEnvironment requires a global `Request` and `Response` object."
);
class ServerHMRBroadcasterClient {
constructor(hmrChannel) {
this.hmrChannel = hmrChannel;
}
if (!context.handleRequest) {
throw new TypeError(
"FetchableDevEnvironment requires a `handleRequest` method during initialisation."
);
}
return new FetchableDevEnvironment(name, config, context);
}
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."
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."
);
}
const response = await this._handleRequest(request);
if (!(response instanceof Response)) {
throw new TypeError(
"FetchableDevEnvironment `context.handleRequest` must return a `Response` object."
this.hmrChannel.send(payload);
}
}
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."
);
}
return response;
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;
}
}
export { DevEnvironment, createFetchableDevEnvironment, isCSSRequest, isFetchableDevEnvironment, splitVendorChunk, splitVendorChunkPlugin };
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 };

View File

@@ -1,290 +0,0 @@
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 };

View File

@@ -1,87 +0,0 @@
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 };

63
node_modules/vite/dist/node/runtime.d.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
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 };

File diff suppressed because it is too large Load Diff

281
node_modules/vite/dist/node/types.d-aGj9QkWt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,281 @@
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 };