initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions

243
node_modules/vite-node/dist/chunk-hmr.cjs generated vendored Normal file
View File

@@ -0,0 +1,243 @@
'use strict';
var events = require('events');
var picocolors = require('./chunk-picocolors.cjs');
var createDebug = require('debug');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
function createHmrEmitter() {
const emitter = new events.EventEmitter();
return emitter;
}
function viteNodeHmrPlugin() {
const emitter = createHmrEmitter();
return {
name: "vite-node:hmr",
configureServer(server) {
const _send = server.ws.send;
server.emitter = emitter;
server.ws.send = function(payload) {
_send(payload);
emitter.emit("message", payload);
};
}
};
}
const debugHmr = createDebug__default["default"]("vite-node:hmr");
const cache = /* @__PURE__ */ new WeakMap();
function getCache(runner) {
if (!cache.has(runner)) {
cache.set(runner, {
hotModulesMap: /* @__PURE__ */ new Map(),
dataMap: /* @__PURE__ */ new Map(),
disposeMap: /* @__PURE__ */ new Map(),
pruneMap: /* @__PURE__ */ new Map(),
customListenersMap: /* @__PURE__ */ new Map(),
ctxToListenersMap: /* @__PURE__ */ new Map(),
messageBuffer: [],
isFirstUpdate: false,
pending: false,
queued: []
});
}
return cache.get(runner);
}
function sendMessageBuffer(runner, emitter) {
const maps = getCache(runner);
maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
maps.messageBuffer.length = 0;
}
async function reload(runner, files) {
Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
if (!fsPath.includes("node_modules"))
runner.moduleCache.delete(fsPath);
});
return Promise.all(files.map((file) => runner.executeId(file)));
}
function notifyListeners(runner, event, data) {
const maps = getCache(runner);
const cbs = maps.customListenersMap.get(event);
if (cbs)
cbs.forEach((cb) => cb(data));
}
async function queueUpdate(runner, p) {
const maps = getCache(runner);
maps.queued.push(p);
if (!maps.pending) {
maps.pending = true;
await Promise.resolve();
maps.pending = false;
const loading = [...maps.queued];
maps.queued = [];
(await Promise.all(loading)).forEach((fn) => fn && fn());
}
}
async function fetchUpdate(runner, { path, acceptedPath }) {
const maps = getCache(runner);
const mod = maps.hotModulesMap.get(path);
if (!mod) {
return;
}
const moduleMap = /* @__PURE__ */ new Map();
const isSelfUpdate = path === acceptedPath;
const modulesToUpdate = /* @__PURE__ */ new Set();
if (isSelfUpdate) {
modulesToUpdate.add(path);
} else {
for (const { deps } of mod.callbacks) {
deps.forEach((dep) => {
if (acceptedPath === dep)
modulesToUpdate.add(dep);
});
}
}
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
return deps.some((dep) => modulesToUpdate.has(dep));
});
await Promise.all(
Array.from(modulesToUpdate).map(async (dep) => {
const disposer = maps.disposeMap.get(dep);
if (disposer)
await disposer(maps.dataMap.get(dep));
try {
const newMod = await reload(runner, [dep]);
moduleMap.set(dep, newMod);
} catch (e) {
warnFailedFetch(e, dep);
}
})
);
return () => {
for (const { deps, fn } of qualifiedCallbacks)
fn(deps.map((dep) => moduleMap.get(dep)));
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
console.log(`${picocolors.picocolors.exports.cyan("[vite-node]")} hot updated: ${loggedPath}`);
};
}
function warnFailedFetch(err, path) {
if (!err.message.match("fetch"))
console.error(err);
console.error(
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
async function handleMessage(runner, emitter, files, payload) {
const maps = getCache(runner);
switch (payload.type) {
case "connected":
sendMessageBuffer(runner, emitter);
break;
case "update":
notifyListeners(runner, "vite:beforeUpdate", payload);
if (maps.isFirstUpdate) {
reload(runner, files);
maps.isFirstUpdate = true;
}
payload.updates.forEach((update) => {
if (update.type === "js-update") {
queueUpdate(runner, fetchUpdate(runner, update));
} else {
console.error(`${picocolors.picocolors.exports.cyan("[vite-node]")} no support css hmr.}`);
}
});
break;
case "full-reload":
notifyListeners(runner, "vite:beforeFullReload", payload);
reload(runner, files);
break;
case "prune":
notifyListeners(runner, "vite:beforePrune", payload);
payload.paths.forEach((path) => {
const fn = maps.pruneMap.get(path);
if (fn)
fn(maps.dataMap.get(path));
});
break;
case "error": {
notifyListeners(runner, "vite:error", payload);
const err = payload.err;
console.error(`${picocolors.picocolors.exports.cyan("[vite-node]")} Internal Server Error
${err.message}
${err.stack}`);
break;
}
}
}
function createHotContext(runner, emitter, files, ownerPath) {
debugHmr("createHotContext", ownerPath);
const maps = getCache(runner);
if (!maps.dataMap.has(ownerPath))
maps.dataMap.set(ownerPath, {});
const mod = maps.hotModulesMap.get(ownerPath);
if (mod)
mod.callbacks = [];
const newListeners = /* @__PURE__ */ new Map();
maps.ctxToListenersMap.set(ownerPath, newListeners);
function acceptDeps(deps, callback = () => {
}) {
const mod2 = maps.hotModulesMap.get(ownerPath) || {
id: ownerPath,
callbacks: []
};
mod2.callbacks.push({
deps,
fn: callback
});
maps.hotModulesMap.set(ownerPath, mod2);
}
const hot = {
get data() {
return maps.dataMap.get(ownerPath);
},
acceptExports(_, callback) {
acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
},
accept(deps, callback) {
if (typeof deps === "function" || !deps) {
acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
} else if (typeof deps === "string") {
acceptDeps([deps], ([mod2]) => callback && callback(mod2));
} else if (Array.isArray(deps)) {
acceptDeps(deps, callback);
} else {
throw new TypeError("invalid hot.accept() usage.");
}
},
dispose(cb) {
maps.disposeMap.set(ownerPath, cb);
},
prune(cb) {
maps.pruneMap.set(ownerPath, cb);
},
invalidate() {
notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
return reload(runner, files);
},
on(event, cb) {
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(maps.customListenersMap);
addToMap(newListeners);
},
send(event, data) {
maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
sendMessageBuffer(runner, emitter);
}
};
return hot;
}
exports.createHmrEmitter = createHmrEmitter;
exports.createHotContext = createHotContext;
exports.getCache = getCache;
exports.handleMessage = handleMessage;
exports.reload = reload;
exports.sendMessageBuffer = sendMessageBuffer;
exports.viteNodeHmrPlugin = viteNodeHmrPlugin;

231
node_modules/vite-node/dist/chunk-hmr.mjs generated vendored Normal file
View File

@@ -0,0 +1,231 @@
import { EventEmitter } from 'events';
import { p as picocolors } from './chunk-picocolors.mjs';
import createDebug from 'debug';
function createHmrEmitter() {
const emitter = new EventEmitter();
return emitter;
}
function viteNodeHmrPlugin() {
const emitter = createHmrEmitter();
return {
name: "vite-node:hmr",
configureServer(server) {
const _send = server.ws.send;
server.emitter = emitter;
server.ws.send = function(payload) {
_send(payload);
emitter.emit("message", payload);
};
}
};
}
const debugHmr = createDebug("vite-node:hmr");
const cache = /* @__PURE__ */ new WeakMap();
function getCache(runner) {
if (!cache.has(runner)) {
cache.set(runner, {
hotModulesMap: /* @__PURE__ */ new Map(),
dataMap: /* @__PURE__ */ new Map(),
disposeMap: /* @__PURE__ */ new Map(),
pruneMap: /* @__PURE__ */ new Map(),
customListenersMap: /* @__PURE__ */ new Map(),
ctxToListenersMap: /* @__PURE__ */ new Map(),
messageBuffer: [],
isFirstUpdate: false,
pending: false,
queued: []
});
}
return cache.get(runner);
}
function sendMessageBuffer(runner, emitter) {
const maps = getCache(runner);
maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
maps.messageBuffer.length = 0;
}
async function reload(runner, files) {
Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
if (!fsPath.includes("node_modules"))
runner.moduleCache.delete(fsPath);
});
return Promise.all(files.map((file) => runner.executeId(file)));
}
function notifyListeners(runner, event, data) {
const maps = getCache(runner);
const cbs = maps.customListenersMap.get(event);
if (cbs)
cbs.forEach((cb) => cb(data));
}
async function queueUpdate(runner, p) {
const maps = getCache(runner);
maps.queued.push(p);
if (!maps.pending) {
maps.pending = true;
await Promise.resolve();
maps.pending = false;
const loading = [...maps.queued];
maps.queued = [];
(await Promise.all(loading)).forEach((fn) => fn && fn());
}
}
async function fetchUpdate(runner, { path, acceptedPath }) {
const maps = getCache(runner);
const mod = maps.hotModulesMap.get(path);
if (!mod) {
return;
}
const moduleMap = /* @__PURE__ */ new Map();
const isSelfUpdate = path === acceptedPath;
const modulesToUpdate = /* @__PURE__ */ new Set();
if (isSelfUpdate) {
modulesToUpdate.add(path);
} else {
for (const { deps } of mod.callbacks) {
deps.forEach((dep) => {
if (acceptedPath === dep)
modulesToUpdate.add(dep);
});
}
}
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
return deps.some((dep) => modulesToUpdate.has(dep));
});
await Promise.all(
Array.from(modulesToUpdate).map(async (dep) => {
const disposer = maps.disposeMap.get(dep);
if (disposer)
await disposer(maps.dataMap.get(dep));
try {
const newMod = await reload(runner, [dep]);
moduleMap.set(dep, newMod);
} catch (e) {
warnFailedFetch(e, dep);
}
})
);
return () => {
for (const { deps, fn } of qualifiedCallbacks)
fn(deps.map((dep) => moduleMap.get(dep)));
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
console.log(`${picocolors.exports.cyan("[vite-node]")} hot updated: ${loggedPath}`);
};
}
function warnFailedFetch(err, path) {
if (!err.message.match("fetch"))
console.error(err);
console.error(
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
async function handleMessage(runner, emitter, files, payload) {
const maps = getCache(runner);
switch (payload.type) {
case "connected":
sendMessageBuffer(runner, emitter);
break;
case "update":
notifyListeners(runner, "vite:beforeUpdate", payload);
if (maps.isFirstUpdate) {
reload(runner, files);
maps.isFirstUpdate = true;
}
payload.updates.forEach((update) => {
if (update.type === "js-update") {
queueUpdate(runner, fetchUpdate(runner, update));
} else {
console.error(`${picocolors.exports.cyan("[vite-node]")} no support css hmr.}`);
}
});
break;
case "full-reload":
notifyListeners(runner, "vite:beforeFullReload", payload);
reload(runner, files);
break;
case "prune":
notifyListeners(runner, "vite:beforePrune", payload);
payload.paths.forEach((path) => {
const fn = maps.pruneMap.get(path);
if (fn)
fn(maps.dataMap.get(path));
});
break;
case "error": {
notifyListeners(runner, "vite:error", payload);
const err = payload.err;
console.error(`${picocolors.exports.cyan("[vite-node]")} Internal Server Error
${err.message}
${err.stack}`);
break;
}
}
}
function createHotContext(runner, emitter, files, ownerPath) {
debugHmr("createHotContext", ownerPath);
const maps = getCache(runner);
if (!maps.dataMap.has(ownerPath))
maps.dataMap.set(ownerPath, {});
const mod = maps.hotModulesMap.get(ownerPath);
if (mod)
mod.callbacks = [];
const newListeners = /* @__PURE__ */ new Map();
maps.ctxToListenersMap.set(ownerPath, newListeners);
function acceptDeps(deps, callback = () => {
}) {
const mod2 = maps.hotModulesMap.get(ownerPath) || {
id: ownerPath,
callbacks: []
};
mod2.callbacks.push({
deps,
fn: callback
});
maps.hotModulesMap.set(ownerPath, mod2);
}
const hot = {
get data() {
return maps.dataMap.get(ownerPath);
},
acceptExports(_, callback) {
acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
},
accept(deps, callback) {
if (typeof deps === "function" || !deps) {
acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
} else if (typeof deps === "string") {
acceptDeps([deps], ([mod2]) => callback && callback(mod2));
} else if (Array.isArray(deps)) {
acceptDeps(deps, callback);
} else {
throw new TypeError("invalid hot.accept() usage.");
}
},
dispose(cb) {
maps.disposeMap.set(ownerPath, cb);
},
prune(cb) {
maps.pruneMap.set(ownerPath, cb);
},
invalidate() {
notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
return reload(runner, files);
},
on(event, cb) {
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(maps.customListenersMap);
addToMap(newListeners);
},
send(event, data) {
maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
sendMessageBuffer(runner, emitter);
}
};
return hot;
}
export { createHmrEmitter as a, createHotContext as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };

70
node_modules/vite-node/dist/chunk-picocolors.cjs generated vendored Normal file
View File

@@ -0,0 +1,70 @@
'use strict';
var require$$0 = require('tty');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
var picocolors = {exports: {}};
let tty = require$$0__default["default"];
let isColorSupported =
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
("FORCE_COLOR" in process.env ||
process.argv.includes("--color") ||
process.platform === "win32" ||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
"CI" in process.env);
let formatter =
(open, close, replace = open) =>
input => {
let string = "" + input;
let index = string.indexOf(close, open.length);
return ~index
? open + replaceClose(string, close, replace, index) + close
: open + string + close
};
let replaceClose = (string, close, replace, index) => {
let start = string.substring(0, index) + replace;
let end = string.substring(index + close.length);
let nextIndex = end.indexOf(close);
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
};
let createColors = (enabled = isColorSupported) => ({
isColorSupported: enabled,
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
});
picocolors.exports = createColors();
picocolors.exports.createColors = createColors;
exports.picocolors = picocolors;

64
node_modules/vite-node/dist/chunk-picocolors.mjs generated vendored Normal file
View File

@@ -0,0 +1,64 @@
import require$$0 from 'tty';
var picocolors = {exports: {}};
let tty = require$$0;
let isColorSupported =
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
("FORCE_COLOR" in process.env ||
process.argv.includes("--color") ||
process.platform === "win32" ||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
"CI" in process.env);
let formatter =
(open, close, replace = open) =>
input => {
let string = "" + input;
let index = string.indexOf(close, open.length);
return ~index
? open + replaceClose(string, close, replace, index) + close
: open + string + close
};
let replaceClose = (string, close, replace, index) => {
let start = string.substring(0, index) + replace;
let end = string.substring(index + close.length);
let nextIndex = end.indexOf(close);
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
};
let createColors = (enabled = isColorSupported) => ({
isColorSupported: enabled,
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
});
picocolors.exports = createColors();
picocolors.exports.createColors = createColors;
export { picocolors as p };

710
node_modules/vite-node/dist/cli.cjs generated vendored Normal file
View File

@@ -0,0 +1,710 @@
'use strict';
var events = require('events');
var picocolors = require('./chunk-picocolors.cjs');
var vite = require('vite');
var server = require('./server.cjs');
var client = require('./client.cjs');
var utils = require('./utils.cjs');
var hmr = require('./chunk-hmr.cjs');
var sourceMap = require('./source-map.cjs');
require('tty');
require('perf_hooks');
require('pathe');
require('debug');
require('fs');
require('mlly');
require('url');
require('source-map-support');
require('module');
require('vm');
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
function mri2 (args, opts) {
args = args || [];
opts = opts || {};
var k, arr, arg, name, val, out={ _:[] };
var i=0, j=0, idx=0, len=args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i=0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i=opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i=opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i=0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i=0; i < len; i++) {
arg = args[i];
if (arg === '--') {
out._ = out._.concat(args.slice(++i));
break;
}
for (j=0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) break; // "-"
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === 'no-') {
name = arg.substring(j + 3);
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx=j+1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) break; // "="
}
name = arg.substring(j, idx);
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
arr = (j === 2 ? [name] : name);
for (idx=0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
toVal(out, name, (idx + 1 < arr.length) || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
const findAllBrackets = (v) => {
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
const res = [];
const parse = (match) => {
let variadic = false;
let value = match[1];
if (value.startsWith("...")) {
value = value.slice(3);
variadic = true;
}
return {
required: match[0].startsWith("<"),
value,
variadic
};
};
let angledMatch;
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(angledMatch));
}
let squareMatch;
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(squareMatch));
}
return res;
};
const getMriOptions = (options) => {
const result = {alias: {}, boolean: []};
for (const [index, option] of options.entries()) {
if (option.names.length > 1) {
result.alias[option.names[0]] = option.names.slice(1);
}
if (option.isBoolean) {
if (option.negated) {
const hasStringTypeOption = options.some((o, i) => {
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
});
if (!hasStringTypeOption) {
result.boolean.push(option.names[0]);
}
} else {
result.boolean.push(option.names[0]);
}
}
}
return result;
};
const findLongest = (arr) => {
return arr.sort((a, b) => {
return a.length > b.length ? -1 : 1;
})[0];
};
const padRight = (str, length) => {
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
};
const camelcase = (input) => {
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
return p1 + p2.toUpperCase();
});
};
const setDotProp = (obj, keys, val) => {
let i = 0;
let length = keys.length;
let t = obj;
let x;
for (; i < length; ++i) {
x = t[keys[i]];
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
}
};
const setByType = (obj, transforms) => {
for (const key of Object.keys(transforms)) {
const transform = transforms[key];
if (transform.shouldTransform) {
obj[key] = Array.prototype.concat.call([], obj[key]);
if (typeof transform.transformFunction === "function") {
obj[key] = obj[key].map(transform.transformFunction);
}
}
}
};
const getFileName = (input) => {
const m = /([^\\\/]+)$/.exec(input);
return m ? m[1] : "";
};
const camelcaseOptionName = (name) => {
return name.split(".").map((v, i) => {
return i === 0 ? camelcase(v) : v;
}).join(".");
};
class CACError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(message).stack;
}
}
}
class Option {
constructor(rawName, description, config) {
this.rawName = rawName;
this.description = description;
this.config = Object.assign({}, config);
rawName = rawName.replace(/\.\*/g, "");
this.negated = false;
this.names = removeBrackets(rawName).split(",").map((v) => {
let name = v.trim().replace(/^-{1,2}/, "");
if (name.startsWith("no-")) {
this.negated = true;
name = name.replace(/^no-/, "");
}
return camelcaseOptionName(name);
}).sort((a, b) => a.length > b.length ? 1 : -1);
this.name = this.names[this.names.length - 1];
if (this.negated && this.config.default == null) {
this.config.default = true;
}
if (rawName.includes("<")) {
this.required = true;
} else if (rawName.includes("[")) {
this.required = false;
} else {
this.isBoolean = true;
}
}
}
const processArgs = process.argv;
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
class Command {
constructor(rawName, description, config = {}, cli) {
this.rawName = rawName;
this.description = description;
this.config = config;
this.cli = cli;
this.options = [];
this.aliasNames = [];
this.name = removeBrackets(rawName);
this.args = findAllBrackets(rawName);
this.examples = [];
}
usage(text) {
this.usageText = text;
return this;
}
allowUnknownOptions() {
this.config.allowUnknownOptions = true;
return this;
}
ignoreOptionDefaultValue() {
this.config.ignoreOptionDefaultValue = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.versionNumber = version;
this.option(customFlags, "Display version number");
return this;
}
example(example) {
this.examples.push(example);
return this;
}
option(rawName, description, config) {
const option = new Option(rawName, description, config);
this.options.push(option);
return this;
}
alias(name) {
this.aliasNames.push(name);
return this;
}
action(callback) {
this.commandAction = callback;
return this;
}
isMatched(name) {
return this.name === name || this.aliasNames.includes(name);
}
get isDefaultCommand() {
return this.name === "" || this.aliasNames.includes("!");
}
get isGlobalCommand() {
return this instanceof GlobalCommand;
}
hasOption(name) {
name = name.split(".")[0];
return this.options.find((option) => {
return option.names.includes(name);
});
}
outputHelp() {
const {name, commands} = this.cli;
const {
versionNumber,
options: globalOptions,
helpCallback
} = this.cli.globalCommand;
let sections = [
{
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
}
];
sections.push({
title: "Usage",
body: ` $ ${name} ${this.usageText || this.rawName}`
});
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
if (showCommands) {
const longestCommandName = findLongest(commands.map((command) => command.rawName));
sections.push({
title: "Commands",
body: commands.map((command) => {
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
}).join("\n")
});
sections.push({
title: `For more info, run any command with the \`--help\` flag`,
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
});
}
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
if (!this.isGlobalCommand && !this.isDefaultCommand) {
options = options.filter((option) => option.name !== "version");
}
if (options.length > 0) {
const longestOptionName = findLongest(options.map((option) => option.rawName));
sections.push({
title: "Options",
body: options.map((option) => {
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
}).join("\n")
});
}
if (this.examples.length > 0) {
sections.push({
title: "Examples",
body: this.examples.map((example) => {
if (typeof example === "function") {
return example(name);
}
return example;
}).join("\n")
});
}
if (helpCallback) {
sections = helpCallback(sections) || sections;
}
console.log(sections.map((section) => {
return section.title ? `${section.title}:
${section.body}` : section.body;
}).join("\n\n"));
}
outputVersion() {
const {name} = this.cli;
const {versionNumber} = this.cli.globalCommand;
if (versionNumber) {
console.log(`${name}/${versionNumber} ${platformInfo}`);
}
}
checkRequiredArgs() {
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
if (this.cli.args.length < minimalArgsCount) {
throw new CACError(`missing required args for command \`${this.rawName}\``);
}
}
checkUnknownOptions() {
const {options, globalCommand} = this.cli;
if (!this.config.allowUnknownOptions) {
for (const name of Object.keys(options)) {
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
}
}
}
}
checkOptionValue() {
const {options: parsedOptions, globalCommand} = this.cli;
const options = [...globalCommand.options, ...this.options];
for (const option of options) {
const value = parsedOptions[option.name.split(".")[0]];
if (option.required) {
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
if (value === true || value === false && !hasNegated) {
throw new CACError(`option \`${option.rawName}\` value is missing`);
}
}
}
}
}
class GlobalCommand extends Command {
constructor(cli) {
super("@@global@@", "", {}, cli);
}
}
var __assign = Object.assign;
class CAC extends events.EventEmitter {
constructor(name = "") {
super();
this.name = name;
this.commands = [];
this.rawArgs = [];
this.args = [];
this.options = {};
this.globalCommand = new GlobalCommand(this);
this.globalCommand.usage("<command> [options]");
}
usage(text) {
this.globalCommand.usage(text);
return this;
}
command(rawName, description, config) {
const command = new Command(rawName, description || "", config, this);
command.globalCommand = this.globalCommand;
this.commands.push(command);
return command;
}
option(rawName, description, config) {
this.globalCommand.option(rawName, description, config);
return this;
}
help(callback) {
this.globalCommand.option("-h, --help", "Display this message");
this.globalCommand.helpCallback = callback;
this.showHelpOnExit = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.globalCommand.version(version, customFlags);
this.showVersionOnExit = true;
return this;
}
example(example) {
this.globalCommand.example(example);
return this;
}
outputHelp() {
if (this.matchedCommand) {
this.matchedCommand.outputHelp();
} else {
this.globalCommand.outputHelp();
}
}
outputVersion() {
this.globalCommand.outputVersion();
}
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
this.args = args;
this.options = options;
if (matchedCommand) {
this.matchedCommand = matchedCommand;
}
if (matchedCommandName) {
this.matchedCommandName = matchedCommandName;
}
return this;
}
unsetMatchedCommand() {
this.matchedCommand = void 0;
this.matchedCommandName = void 0;
}
parse(argv = processArgs, {
run = true
} = {}) {
this.rawArgs = argv;
if (!this.name) {
this.name = argv[1] ? getFileName(argv[1]) : "cli";
}
let shouldParse = true;
for (const command of this.commands) {
const parsed = this.mri(argv.slice(2), command);
const commandName = parsed.args[0];
if (command.isMatched(commandName)) {
shouldParse = false;
const parsedInfo = __assign(__assign({}, parsed), {
args: parsed.args.slice(1)
});
this.setParsedInfo(parsedInfo, command, commandName);
this.emit(`command:${commandName}`, command);
}
}
if (shouldParse) {
for (const command of this.commands) {
if (command.name === "") {
shouldParse = false;
const parsed = this.mri(argv.slice(2), command);
this.setParsedInfo(parsed, command);
this.emit(`command:!`, command);
}
}
}
if (shouldParse) {
const parsed = this.mri(argv.slice(2));
this.setParsedInfo(parsed);
}
if (this.options.help && this.showHelpOnExit) {
this.outputHelp();
run = false;
this.unsetMatchedCommand();
}
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
this.outputVersion();
run = false;
this.unsetMatchedCommand();
}
const parsedArgv = {args: this.args, options: this.options};
if (run) {
this.runMatchedCommand();
}
if (!this.matchedCommand && this.args[0]) {
this.emit("command:*");
}
return parsedArgv;
}
mri(argv, command) {
const cliOptions = [
...this.globalCommand.options,
...command ? command.options : []
];
const mriOptions = getMriOptions(cliOptions);
let argsAfterDoubleDashes = [];
const doubleDashesIndex = argv.indexOf("--");
if (doubleDashesIndex > -1) {
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
argv = argv.slice(0, doubleDashesIndex);
}
let parsed = mri2(argv, mriOptions);
parsed = Object.keys(parsed).reduce((res, name) => {
return __assign(__assign({}, res), {
[camelcaseOptionName(name)]: parsed[name]
});
}, {_: []});
const args = parsed._;
const options = {
"--": argsAfterDoubleDashes
};
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
let transforms = Object.create(null);
for (const cliOption of cliOptions) {
if (!ignoreDefault && cliOption.config.default !== void 0) {
for (const name of cliOption.names) {
options[name] = cliOption.config.default;
}
}
if (Array.isArray(cliOption.config.type)) {
if (transforms[cliOption.name] === void 0) {
transforms[cliOption.name] = Object.create(null);
transforms[cliOption.name]["shouldTransform"] = true;
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
}
}
}
for (const key of Object.keys(parsed)) {
if (key !== "_") {
const keys = key.split(".");
setDotProp(options, keys, parsed[key]);
setByType(options, transforms);
}
}
return {
args,
options
};
}
runMatchedCommand() {
const {args, options, matchedCommand: command} = this;
if (!command || !command.commandAction)
return;
command.checkUnknownOptions();
command.checkOptionValue();
command.checkRequiredArgs();
const actionArgs = [];
command.args.forEach((arg, index) => {
if (arg.variadic) {
actionArgs.push(args.slice(index));
} else {
actionArgs.push(args[index]);
}
});
actionArgs.push(options);
return command.commandAction.apply(this, actionArgs);
}
}
const cac = (name = "") => new CAC(name);
var version = "0.25.8";
const cli = cac("vite-node");
cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
cli.command("[...files]").action(run);
cli.parse();
async function run(files, options = {}) {
var _a;
if (!files.length) {
console.error(picocolors.picocolors.exports.red("No files specified."));
cli.outputHelp();
process.exit(1);
}
process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
const serverOptions = options.options ? parseServerOptions(options.options) : {};
const server$1 = await vite.createServer({
logLevel: "error",
configFile: options.config,
root: options.root,
plugins: [
options.watch && hmr.viteNodeHmrPlugin()
]
});
await server$1.pluginContainer.buildStart({});
const node = new server.ViteNodeServer(server$1, serverOptions);
sourceMap.installSourcemapsSupport({
getSourceMap: (source) => node.getSourceMap(source)
});
const runner = new client.ViteNodeRunner({
root: server$1.config.root,
base: server$1.config.base,
fetchModule(id) {
return node.fetchModule(id);
},
resolveId(id, importer) {
return node.resolveId(id, importer);
},
createHotContext(runner2, url) {
return hmr.createHotContext(runner2, server$1.emitter, files, url);
}
});
await runner.executeId("/@vite/env");
for (const file of files)
await runner.executeFile(file);
if (!options.watch)
await server$1.close();
(_a = server$1.emitter) == null ? void 0 : _a.on("message", (payload) => {
hmr.handleMessage(runner, server$1.emitter, files, payload);
});
if (options.watch) {
process.on("uncaughtException", (err) => {
console.error(picocolors.picocolors.exports.red("[vite-node] Failed to execute file: \n"), err);
});
}
}
function parseServerOptions(serverOptions) {
var _a, _b, _c, _d, _e;
const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : utils.toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline);
return {
...serverOptions,
deps: {
...serverOptions.deps,
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}) : true,
external: utils.toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
})
},
transformMode: {
...serverOptions.transformMode,
ssr: utils.toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)),
web: utils.toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep))
}
};
}

16
node_modules/vite-node/dist/cli.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import { e as ViteNodeServerOptions } from './types-fc7e68bc.js';
interface CliOptions {
root?: string;
config?: string;
watch?: boolean;
options?: ViteNodeServerOptionsCLI;
'--'?: string[];
}
type Optional<T> = T | undefined;
type ComputeViteNodeServerOptionsCLI<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Optional<RegExp[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[] | true> ? string | string[] | true : T[K] extends Optional<Record<string, any>> ? ComputeViteNodeServerOptionsCLI<T[K]> : T[K];
};
type ViteNodeServerOptionsCLI = ComputeViteNodeServerOptionsCLI<ViteNodeServerOptions>;
export { CliOptions, ViteNodeServerOptionsCLI };

708
node_modules/vite-node/dist/cli.mjs generated vendored Normal file
View File

@@ -0,0 +1,708 @@
import { EventEmitter } from 'events';
import { p as picocolors } from './chunk-picocolors.mjs';
import { createServer } from 'vite';
import { ViteNodeServer } from './server.mjs';
import { ViteNodeRunner } from './client.mjs';
import { toArray } from './utils.mjs';
import { v as viteNodeHmrPlugin, c as createHotContext, h as handleMessage } from './chunk-hmr.mjs';
import { installSourcemapsSupport } from './source-map.mjs';
import 'tty';
import 'perf_hooks';
import 'pathe';
import 'debug';
import 'fs';
import 'mlly';
import 'url';
import 'source-map-support';
import 'module';
import 'vm';
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
function mri2 (args, opts) {
args = args || [];
opts = opts || {};
var k, arr, arg, name, val, out={ _:[] };
var i=0, j=0, idx=0, len=args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i=0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i=opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i=opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i=0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i=0; i < len; i++) {
arg = args[i];
if (arg === '--') {
out._ = out._.concat(args.slice(++i));
break;
}
for (j=0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) break; // "-"
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === 'no-') {
name = arg.substring(j + 3);
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx=j+1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) break; // "="
}
name = arg.substring(j, idx);
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
arr = (j === 2 ? [name] : name);
for (idx=0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
toVal(out, name, (idx + 1 < arr.length) || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
const findAllBrackets = (v) => {
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
const res = [];
const parse = (match) => {
let variadic = false;
let value = match[1];
if (value.startsWith("...")) {
value = value.slice(3);
variadic = true;
}
return {
required: match[0].startsWith("<"),
value,
variadic
};
};
let angledMatch;
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(angledMatch));
}
let squareMatch;
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(squareMatch));
}
return res;
};
const getMriOptions = (options) => {
const result = {alias: {}, boolean: []};
for (const [index, option] of options.entries()) {
if (option.names.length > 1) {
result.alias[option.names[0]] = option.names.slice(1);
}
if (option.isBoolean) {
if (option.negated) {
const hasStringTypeOption = options.some((o, i) => {
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
});
if (!hasStringTypeOption) {
result.boolean.push(option.names[0]);
}
} else {
result.boolean.push(option.names[0]);
}
}
}
return result;
};
const findLongest = (arr) => {
return arr.sort((a, b) => {
return a.length > b.length ? -1 : 1;
})[0];
};
const padRight = (str, length) => {
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
};
const camelcase = (input) => {
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
return p1 + p2.toUpperCase();
});
};
const setDotProp = (obj, keys, val) => {
let i = 0;
let length = keys.length;
let t = obj;
let x;
for (; i < length; ++i) {
x = t[keys[i]];
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
}
};
const setByType = (obj, transforms) => {
for (const key of Object.keys(transforms)) {
const transform = transforms[key];
if (transform.shouldTransform) {
obj[key] = Array.prototype.concat.call([], obj[key]);
if (typeof transform.transformFunction === "function") {
obj[key] = obj[key].map(transform.transformFunction);
}
}
}
};
const getFileName = (input) => {
const m = /([^\\\/]+)$/.exec(input);
return m ? m[1] : "";
};
const camelcaseOptionName = (name) => {
return name.split(".").map((v, i) => {
return i === 0 ? camelcase(v) : v;
}).join(".");
};
class CACError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(message).stack;
}
}
}
class Option {
constructor(rawName, description, config) {
this.rawName = rawName;
this.description = description;
this.config = Object.assign({}, config);
rawName = rawName.replace(/\.\*/g, "");
this.negated = false;
this.names = removeBrackets(rawName).split(",").map((v) => {
let name = v.trim().replace(/^-{1,2}/, "");
if (name.startsWith("no-")) {
this.negated = true;
name = name.replace(/^no-/, "");
}
return camelcaseOptionName(name);
}).sort((a, b) => a.length > b.length ? 1 : -1);
this.name = this.names[this.names.length - 1];
if (this.negated && this.config.default == null) {
this.config.default = true;
}
if (rawName.includes("<")) {
this.required = true;
} else if (rawName.includes("[")) {
this.required = false;
} else {
this.isBoolean = true;
}
}
}
const processArgs = process.argv;
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
class Command {
constructor(rawName, description, config = {}, cli) {
this.rawName = rawName;
this.description = description;
this.config = config;
this.cli = cli;
this.options = [];
this.aliasNames = [];
this.name = removeBrackets(rawName);
this.args = findAllBrackets(rawName);
this.examples = [];
}
usage(text) {
this.usageText = text;
return this;
}
allowUnknownOptions() {
this.config.allowUnknownOptions = true;
return this;
}
ignoreOptionDefaultValue() {
this.config.ignoreOptionDefaultValue = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.versionNumber = version;
this.option(customFlags, "Display version number");
return this;
}
example(example) {
this.examples.push(example);
return this;
}
option(rawName, description, config) {
const option = new Option(rawName, description, config);
this.options.push(option);
return this;
}
alias(name) {
this.aliasNames.push(name);
return this;
}
action(callback) {
this.commandAction = callback;
return this;
}
isMatched(name) {
return this.name === name || this.aliasNames.includes(name);
}
get isDefaultCommand() {
return this.name === "" || this.aliasNames.includes("!");
}
get isGlobalCommand() {
return this instanceof GlobalCommand;
}
hasOption(name) {
name = name.split(".")[0];
return this.options.find((option) => {
return option.names.includes(name);
});
}
outputHelp() {
const {name, commands} = this.cli;
const {
versionNumber,
options: globalOptions,
helpCallback
} = this.cli.globalCommand;
let sections = [
{
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
}
];
sections.push({
title: "Usage",
body: ` $ ${name} ${this.usageText || this.rawName}`
});
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
if (showCommands) {
const longestCommandName = findLongest(commands.map((command) => command.rawName));
sections.push({
title: "Commands",
body: commands.map((command) => {
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
}).join("\n")
});
sections.push({
title: `For more info, run any command with the \`--help\` flag`,
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
});
}
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
if (!this.isGlobalCommand && !this.isDefaultCommand) {
options = options.filter((option) => option.name !== "version");
}
if (options.length > 0) {
const longestOptionName = findLongest(options.map((option) => option.rawName));
sections.push({
title: "Options",
body: options.map((option) => {
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
}).join("\n")
});
}
if (this.examples.length > 0) {
sections.push({
title: "Examples",
body: this.examples.map((example) => {
if (typeof example === "function") {
return example(name);
}
return example;
}).join("\n")
});
}
if (helpCallback) {
sections = helpCallback(sections) || sections;
}
console.log(sections.map((section) => {
return section.title ? `${section.title}:
${section.body}` : section.body;
}).join("\n\n"));
}
outputVersion() {
const {name} = this.cli;
const {versionNumber} = this.cli.globalCommand;
if (versionNumber) {
console.log(`${name}/${versionNumber} ${platformInfo}`);
}
}
checkRequiredArgs() {
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
if (this.cli.args.length < minimalArgsCount) {
throw new CACError(`missing required args for command \`${this.rawName}\``);
}
}
checkUnknownOptions() {
const {options, globalCommand} = this.cli;
if (!this.config.allowUnknownOptions) {
for (const name of Object.keys(options)) {
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
}
}
}
}
checkOptionValue() {
const {options: parsedOptions, globalCommand} = this.cli;
const options = [...globalCommand.options, ...this.options];
for (const option of options) {
const value = parsedOptions[option.name.split(".")[0]];
if (option.required) {
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
if (value === true || value === false && !hasNegated) {
throw new CACError(`option \`${option.rawName}\` value is missing`);
}
}
}
}
}
class GlobalCommand extends Command {
constructor(cli) {
super("@@global@@", "", {}, cli);
}
}
var __assign = Object.assign;
class CAC extends EventEmitter {
constructor(name = "") {
super();
this.name = name;
this.commands = [];
this.rawArgs = [];
this.args = [];
this.options = {};
this.globalCommand = new GlobalCommand(this);
this.globalCommand.usage("<command> [options]");
}
usage(text) {
this.globalCommand.usage(text);
return this;
}
command(rawName, description, config) {
const command = new Command(rawName, description || "", config, this);
command.globalCommand = this.globalCommand;
this.commands.push(command);
return command;
}
option(rawName, description, config) {
this.globalCommand.option(rawName, description, config);
return this;
}
help(callback) {
this.globalCommand.option("-h, --help", "Display this message");
this.globalCommand.helpCallback = callback;
this.showHelpOnExit = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.globalCommand.version(version, customFlags);
this.showVersionOnExit = true;
return this;
}
example(example) {
this.globalCommand.example(example);
return this;
}
outputHelp() {
if (this.matchedCommand) {
this.matchedCommand.outputHelp();
} else {
this.globalCommand.outputHelp();
}
}
outputVersion() {
this.globalCommand.outputVersion();
}
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
this.args = args;
this.options = options;
if (matchedCommand) {
this.matchedCommand = matchedCommand;
}
if (matchedCommandName) {
this.matchedCommandName = matchedCommandName;
}
return this;
}
unsetMatchedCommand() {
this.matchedCommand = void 0;
this.matchedCommandName = void 0;
}
parse(argv = processArgs, {
run = true
} = {}) {
this.rawArgs = argv;
if (!this.name) {
this.name = argv[1] ? getFileName(argv[1]) : "cli";
}
let shouldParse = true;
for (const command of this.commands) {
const parsed = this.mri(argv.slice(2), command);
const commandName = parsed.args[0];
if (command.isMatched(commandName)) {
shouldParse = false;
const parsedInfo = __assign(__assign({}, parsed), {
args: parsed.args.slice(1)
});
this.setParsedInfo(parsedInfo, command, commandName);
this.emit(`command:${commandName}`, command);
}
}
if (shouldParse) {
for (const command of this.commands) {
if (command.name === "") {
shouldParse = false;
const parsed = this.mri(argv.slice(2), command);
this.setParsedInfo(parsed, command);
this.emit(`command:!`, command);
}
}
}
if (shouldParse) {
const parsed = this.mri(argv.slice(2));
this.setParsedInfo(parsed);
}
if (this.options.help && this.showHelpOnExit) {
this.outputHelp();
run = false;
this.unsetMatchedCommand();
}
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
this.outputVersion();
run = false;
this.unsetMatchedCommand();
}
const parsedArgv = {args: this.args, options: this.options};
if (run) {
this.runMatchedCommand();
}
if (!this.matchedCommand && this.args[0]) {
this.emit("command:*");
}
return parsedArgv;
}
mri(argv, command) {
const cliOptions = [
...this.globalCommand.options,
...command ? command.options : []
];
const mriOptions = getMriOptions(cliOptions);
let argsAfterDoubleDashes = [];
const doubleDashesIndex = argv.indexOf("--");
if (doubleDashesIndex > -1) {
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
argv = argv.slice(0, doubleDashesIndex);
}
let parsed = mri2(argv, mriOptions);
parsed = Object.keys(parsed).reduce((res, name) => {
return __assign(__assign({}, res), {
[camelcaseOptionName(name)]: parsed[name]
});
}, {_: []});
const args = parsed._;
const options = {
"--": argsAfterDoubleDashes
};
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
let transforms = Object.create(null);
for (const cliOption of cliOptions) {
if (!ignoreDefault && cliOption.config.default !== void 0) {
for (const name of cliOption.names) {
options[name] = cliOption.config.default;
}
}
if (Array.isArray(cliOption.config.type)) {
if (transforms[cliOption.name] === void 0) {
transforms[cliOption.name] = Object.create(null);
transforms[cliOption.name]["shouldTransform"] = true;
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
}
}
}
for (const key of Object.keys(parsed)) {
if (key !== "_") {
const keys = key.split(".");
setDotProp(options, keys, parsed[key]);
setByType(options, transforms);
}
}
return {
args,
options
};
}
runMatchedCommand() {
const {args, options, matchedCommand: command} = this;
if (!command || !command.commandAction)
return;
command.checkUnknownOptions();
command.checkOptionValue();
command.checkRequiredArgs();
const actionArgs = [];
command.args.forEach((arg, index) => {
if (arg.variadic) {
actionArgs.push(args.slice(index));
} else {
actionArgs.push(args[index]);
}
});
actionArgs.push(options);
return command.commandAction.apply(this, actionArgs);
}
}
const cac = (name = "") => new CAC(name);
var version = "0.25.8";
const cli = cac("vite-node");
cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
cli.command("[...files]").action(run);
cli.parse();
async function run(files, options = {}) {
var _a;
if (!files.length) {
console.error(picocolors.exports.red("No files specified."));
cli.outputHelp();
process.exit(1);
}
process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
const serverOptions = options.options ? parseServerOptions(options.options) : {};
const server = await createServer({
logLevel: "error",
configFile: options.config,
root: options.root,
plugins: [
options.watch && viteNodeHmrPlugin()
]
});
await server.pluginContainer.buildStart({});
const node = new ViteNodeServer(server, serverOptions);
installSourcemapsSupport({
getSourceMap: (source) => node.getSourceMap(source)
});
const runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
fetchModule(id) {
return node.fetchModule(id);
},
resolveId(id, importer) {
return node.resolveId(id, importer);
},
createHotContext(runner2, url) {
return createHotContext(runner2, server.emitter, files, url);
}
});
await runner.executeId("/@vite/env");
for (const file of files)
await runner.executeFile(file);
if (!options.watch)
await server.close();
(_a = server.emitter) == null ? void 0 : _a.on("message", (payload) => {
handleMessage(runner, server.emitter, files, payload);
});
if (options.watch) {
process.on("uncaughtException", (err) => {
console.error(picocolors.exports.red("[vite-node] Failed to execute file: \n"), err);
});
}
}
function parseServerOptions(serverOptions) {
var _a, _b, _c, _d, _e;
const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline);
return {
...serverOptions,
deps: {
...serverOptions.deps,
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}) : true,
external: toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
})
},
transformMode: {
...serverOptions.transformMode,
ssr: toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)),
web: toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep))
}
};
}

379
node_modules/vite-node/dist/client.cjs generated vendored Normal file
View File

@@ -0,0 +1,379 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var module$1 = require('module');
var url = require('url');
var vm = require('vm');
var pathe = require('pathe');
var mlly = require('mlly');
var createDebug = require('debug');
var utils = require('./utils.cjs');
var sourceMap = require('./source-map.cjs');
require('fs');
require('source-map-support');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var vm__default = /*#__PURE__*/_interopDefaultLegacy(vm);
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
const debugExecute = createDebug__default["default"]("vite-node:client:execute");
const debugNative = createDebug__default["default"]("vite-node:client:native");
const DEFAULT_REQUEST_STUBS = {
"/@vite/client": {
injectQuery: (id) => id,
createHotContext() {
return {
accept: () => {
},
prune: () => {
},
dispose: () => {
},
decline: () => {
},
invalidate: () => {
},
on: () => {
}
};
},
updateStyle(id, css) {
if (typeof document === "undefined")
return;
const element = document.getElementById(id);
if (element)
element.remove();
const head = document.querySelector("head");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.id = id;
style.innerHTML = css;
head == null ? void 0 : head.appendChild(style);
}
}
};
class ModuleCacheMap extends Map {
normalizePath(fsPath) {
return utils.normalizeModuleId(fsPath);
}
update(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath))
super.set(fsPath, mod);
else
Object.assign(super.get(fsPath), mod);
return this;
}
set(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
return super.set(fsPath, mod);
}
get(fsPath) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath))
super.set(fsPath, {});
return super.get(fsPath);
}
delete(fsPath) {
fsPath = this.normalizePath(fsPath);
return super.delete(fsPath);
}
invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const mod = super.get(id);
if (mod == null ? void 0 : mod.importers)
this.invalidateDepTree(mod.importers, invalidated);
super.delete(id);
}
return invalidated;
}
invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const subIds = Array.from(super.entries()).filter(([, mod]) => {
var _a;
return (_a = mod.importers) == null ? void 0 : _a.has(id);
}).map(([key]) => key);
subIds.length && this.invalidateSubDepTree(subIds, invalidated);
super.delete(id);
}
return invalidated;
}
getSourceMap(id) {
const cache = this.get(id);
if (cache.map)
return cache.map;
const map = cache.code && sourceMap.extractSourceMap(cache.code);
if (map) {
cache.map = map;
return map;
}
return null;
}
}
class ViteNodeRunner {
constructor(options) {
this.options = options;
this.root = options.root ?? process.cwd();
this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
}
async executeFile(file) {
return await this.cachedRequest(`/@fs/${utils.slash(pathe.resolve(file))}`, []);
}
async executeId(id) {
return await this.cachedRequest(id, []);
}
getSourceMap(id) {
return this.moduleCache.getSourceMap(id);
}
async cachedRequest(rawId, callstack) {
const id = utils.normalizeRequestId(rawId, this.options.base);
const fsPath = utils.toFilePath(id, this.root);
const mod = this.moduleCache.get(fsPath);
const importee = callstack[callstack.length - 1];
if (!mod.importers)
mod.importers = /* @__PURE__ */ new Set();
if (importee)
mod.importers.add(importee);
if (callstack.includes(fsPath) && mod.exports)
return mod.exports;
if (mod.promise)
return mod.promise;
const promise = this.directRequest(id, fsPath, callstack);
Object.assign(mod, { promise, evaluated: false });
try {
return await promise;
} finally {
mod.evaluated = true;
}
}
async directRequest(id, fsPath, _callstack) {
const callstack = [..._callstack, fsPath];
let mod = this.moduleCache.get(fsPath);
const request = async (dep2) => {
var _a;
const depFsPath = utils.toFilePath(utils.normalizeRequestId(dep2, this.options.base), this.root);
const getStack = () => {
return `stack:
${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
};
let debugTimer;
if (this.debug)
debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
${getStack()}`), 2e3);
try {
if (callstack.includes(depFsPath)) {
const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
if (depExports)
return depExports;
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
}
return await this.cachedRequest(dep2, callstack);
} finally {
if (debugTimer)
clearTimeout(debugTimer);
}
};
Object.defineProperty(request, "callstack", { get: () => callstack });
const resolveId = async (dep2, callstackPosition = 1) => {
if (this.options.resolveId && this.shouldResolveId(dep2)) {
let importer = callstack[callstack.length - callstackPosition];
if (importer && !dep2.startsWith("."))
importer = void 0;
if (importer && importer.startsWith("mock:"))
importer = importer.slice(5);
const resolved = await this.options.resolveId(utils.normalizeRequestId(dep2), importer);
return [dep2, resolved == null ? void 0 : resolved.id];
}
return [dep2, void 0];
};
const [dep, resolvedId] = await resolveId(id, 2);
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
if (id in requestStubs)
return requestStubs[id];
let { code: transformed, externalize } = await this.options.fetchModule(resolvedId || dep);
if (resolvedId && !fsPath.includes("?") && fsPath !== resolvedId) {
if (this.moduleCache.has(resolvedId)) {
mod = this.moduleCache.get(resolvedId);
this.moduleCache.set(fsPath, mod);
if (mod.promise)
return mod.promise;
if (mod.exports)
return mod.exports;
} else {
this.moduleCache.set(resolvedId, mod);
}
}
if (externalize) {
debugNative(externalize);
const exports2 = await this.interopedImport(externalize);
mod.exports = exports2;
return exports2;
}
if (transformed == null)
throw new Error(`[vite-node] Failed to load ${id}`);
const file = utils.cleanUrl(resolvedId || fsPath);
const url$1 = url.pathToFileURL(file).href;
const meta = { url: url$1 };
const exports = /* @__PURE__ */ Object.create(null);
Object.defineProperty(exports, Symbol.toStringTag, {
value: "Module",
enumerable: false,
configurable: false
});
const cjsExports = new Proxy(exports, {
set(_, p, value) {
if (!Reflect.has(exports, "default"))
exports.default = {};
if (utils.isPrimitive(exports.default)) {
defineExport(exports, p, () => void 0);
return true;
}
exports.default[p] = value;
if (p !== "default")
defineExport(exports, p, () => value);
return true;
}
});
Object.assign(mod, { code: transformed, exports });
const __filename = url.fileURLToPath(url$1);
const moduleProxy = {
set exports(value) {
exportAll(cjsExports, value);
exports.default = value;
},
get exports() {
return cjsExports;
}
};
let hotContext;
if (this.options.createHotContext) {
Object.defineProperty(meta, "hot", {
enumerable: true,
get: () => {
var _a, _b;
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
return hotContext;
}
});
}
const context = this.prepareContext({
__vite_ssr_import__: request,
__vite_ssr_dynamic_import__: request,
__vite_ssr_exports__: exports,
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
__vite_ssr_import_meta__: meta,
__vitest_resolve_id__: resolveId,
require: module$1.createRequire(url$1),
exports: cjsExports,
module: moduleProxy,
__filename,
__dirname: pathe.dirname(__filename)
});
debugExecute(__filename);
if (transformed[0] === "#")
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
const code = `${codeDefinition}${transformed}
}}`;
const fn = vm__default["default"].runInThisContext(code, {
filename: __filename,
lineOffset: 0,
columnOffset: -codeDefinition.length
});
await fn(...Object.values(context));
return exports;
}
prepareContext(context) {
return context;
}
shouldResolveId(dep) {
if (mlly.isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
return false;
return !pathe.isAbsolute(dep) || !pathe.extname(dep);
}
shouldInterop(path, mod) {
if (this.options.interopDefault === false)
return false;
return !path.endsWith(".mjs") && "default" in mod;
}
async interopedImport(path) {
const mod = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path);
if (this.shouldInterop(path, mod)) {
const tryDefault = this.hasNestedDefault(mod);
return new Proxy(mod, {
get: proxyMethod("get", tryDefault),
set: proxyMethod("set", tryDefault),
has: proxyMethod("has", tryDefault),
deleteProperty: proxyMethod("deleteProperty", tryDefault)
});
}
return mod;
}
hasNestedDefault(target) {
return "__esModule" in target && target.__esModule && "default" in target.default;
}
}
function proxyMethod(name, tryDefault) {
return function(target, key, ...args) {
const result = Reflect[name](target, key, ...args);
if (utils.isPrimitive(target.default))
return result;
if (tryDefault && key === "default" || typeof result === "undefined")
return Reflect[name](target.default, key, ...args);
return result;
};
}
function defineExport(exports, key, value) {
Object.defineProperty(exports, key, {
enumerable: true,
configurable: true,
get: value
});
}
function exportAll(exports, sourceModule) {
if (exports === sourceModule)
return;
if (utils.isPrimitive(sourceModule) || Array.isArray(sourceModule))
return;
for (const key in sourceModule) {
if (key !== "default") {
try {
defineExport(exports, key, () => sourceModule[key]);
} catch (_err) {
}
}
}
}
exports.DEFAULT_REQUEST_STUBS = DEFAULT_REQUEST_STUBS;
exports.ModuleCacheMap = ModuleCacheMap;
exports.ViteNodeRunner = ViteNodeRunner;

1
node_modules/vite-node/dist/client.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { j as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-fc7e68bc.js';

350
node_modules/vite-node/dist/client.mjs generated vendored Normal file
View File

@@ -0,0 +1,350 @@
import { createRequire } from 'module';
import { pathToFileURL, fileURLToPath } from 'url';
import vm from 'vm';
import { resolve, dirname, isAbsolute, extname } from 'pathe';
import { isNodeBuiltin } from 'mlly';
import createDebug from 'debug';
import { normalizeModuleId, slash, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs';
import { extractSourceMap } from './source-map.mjs';
import 'fs';
import 'source-map-support';
const debugExecute = createDebug("vite-node:client:execute");
const debugNative = createDebug("vite-node:client:native");
const DEFAULT_REQUEST_STUBS = {
"/@vite/client": {
injectQuery: (id) => id,
createHotContext() {
return {
accept: () => {
},
prune: () => {
},
dispose: () => {
},
decline: () => {
},
invalidate: () => {
},
on: () => {
}
};
},
updateStyle(id, css) {
if (typeof document === "undefined")
return;
const element = document.getElementById(id);
if (element)
element.remove();
const head = document.querySelector("head");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.id = id;
style.innerHTML = css;
head == null ? void 0 : head.appendChild(style);
}
}
};
class ModuleCacheMap extends Map {
normalizePath(fsPath) {
return normalizeModuleId(fsPath);
}
update(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath))
super.set(fsPath, mod);
else
Object.assign(super.get(fsPath), mod);
return this;
}
set(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
return super.set(fsPath, mod);
}
get(fsPath) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath))
super.set(fsPath, {});
return super.get(fsPath);
}
delete(fsPath) {
fsPath = this.normalizePath(fsPath);
return super.delete(fsPath);
}
invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const mod = super.get(id);
if (mod == null ? void 0 : mod.importers)
this.invalidateDepTree(mod.importers, invalidated);
super.delete(id);
}
return invalidated;
}
invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id))
continue;
invalidated.add(id);
const subIds = Array.from(super.entries()).filter(([, mod]) => {
var _a;
return (_a = mod.importers) == null ? void 0 : _a.has(id);
}).map(([key]) => key);
subIds.length && this.invalidateSubDepTree(subIds, invalidated);
super.delete(id);
}
return invalidated;
}
getSourceMap(id) {
const cache = this.get(id);
if (cache.map)
return cache.map;
const map = cache.code && extractSourceMap(cache.code);
if (map) {
cache.map = map;
return map;
}
return null;
}
}
class ViteNodeRunner {
constructor(options) {
this.options = options;
this.root = options.root ?? process.cwd();
this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
}
async executeFile(file) {
return await this.cachedRequest(`/@fs/${slash(resolve(file))}`, []);
}
async executeId(id) {
return await this.cachedRequest(id, []);
}
getSourceMap(id) {
return this.moduleCache.getSourceMap(id);
}
async cachedRequest(rawId, callstack) {
const id = normalizeRequestId(rawId, this.options.base);
const fsPath = toFilePath(id, this.root);
const mod = this.moduleCache.get(fsPath);
const importee = callstack[callstack.length - 1];
if (!mod.importers)
mod.importers = /* @__PURE__ */ new Set();
if (importee)
mod.importers.add(importee);
if (callstack.includes(fsPath) && mod.exports)
return mod.exports;
if (mod.promise)
return mod.promise;
const promise = this.directRequest(id, fsPath, callstack);
Object.assign(mod, { promise, evaluated: false });
try {
return await promise;
} finally {
mod.evaluated = true;
}
}
async directRequest(id, fsPath, _callstack) {
const callstack = [..._callstack, fsPath];
let mod = this.moduleCache.get(fsPath);
const request = async (dep2) => {
var _a;
const depFsPath = toFilePath(normalizeRequestId(dep2, this.options.base), this.root);
const getStack = () => {
return `stack:
${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
};
let debugTimer;
if (this.debug)
debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
${getStack()}`), 2e3);
try {
if (callstack.includes(depFsPath)) {
const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
if (depExports)
return depExports;
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
}
return await this.cachedRequest(dep2, callstack);
} finally {
if (debugTimer)
clearTimeout(debugTimer);
}
};
Object.defineProperty(request, "callstack", { get: () => callstack });
const resolveId = async (dep2, callstackPosition = 1) => {
if (this.options.resolveId && this.shouldResolveId(dep2)) {
let importer = callstack[callstack.length - callstackPosition];
if (importer && !dep2.startsWith("."))
importer = void 0;
if (importer && importer.startsWith("mock:"))
importer = importer.slice(5);
const resolved = await this.options.resolveId(normalizeRequestId(dep2), importer);
return [dep2, resolved == null ? void 0 : resolved.id];
}
return [dep2, void 0];
};
const [dep, resolvedId] = await resolveId(id, 2);
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
if (id in requestStubs)
return requestStubs[id];
let { code: transformed, externalize } = await this.options.fetchModule(resolvedId || dep);
if (resolvedId && !fsPath.includes("?") && fsPath !== resolvedId) {
if (this.moduleCache.has(resolvedId)) {
mod = this.moduleCache.get(resolvedId);
this.moduleCache.set(fsPath, mod);
if (mod.promise)
return mod.promise;
if (mod.exports)
return mod.exports;
} else {
this.moduleCache.set(resolvedId, mod);
}
}
if (externalize) {
debugNative(externalize);
const exports2 = await this.interopedImport(externalize);
mod.exports = exports2;
return exports2;
}
if (transformed == null)
throw new Error(`[vite-node] Failed to load ${id}`);
const file = cleanUrl(resolvedId || fsPath);
const url = pathToFileURL(file).href;
const meta = { url };
const exports = /* @__PURE__ */ Object.create(null);
Object.defineProperty(exports, Symbol.toStringTag, {
value: "Module",
enumerable: false,
configurable: false
});
const cjsExports = new Proxy(exports, {
set(_, p, value) {
if (!Reflect.has(exports, "default"))
exports.default = {};
if (isPrimitive(exports.default)) {
defineExport(exports, p, () => void 0);
return true;
}
exports.default[p] = value;
if (p !== "default")
defineExport(exports, p, () => value);
return true;
}
});
Object.assign(mod, { code: transformed, exports });
const __filename = fileURLToPath(url);
const moduleProxy = {
set exports(value) {
exportAll(cjsExports, value);
exports.default = value;
},
get exports() {
return cjsExports;
}
};
let hotContext;
if (this.options.createHotContext) {
Object.defineProperty(meta, "hot", {
enumerable: true,
get: () => {
var _a, _b;
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
return hotContext;
}
});
}
const context = this.prepareContext({
__vite_ssr_import__: request,
__vite_ssr_dynamic_import__: request,
__vite_ssr_exports__: exports,
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
__vite_ssr_import_meta__: meta,
__vitest_resolve_id__: resolveId,
require: createRequire(url),
exports: cjsExports,
module: moduleProxy,
__filename,
__dirname: dirname(__filename)
});
debugExecute(__filename);
if (transformed[0] === "#")
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
const code = `${codeDefinition}${transformed}
}}`;
const fn = vm.runInThisContext(code, {
filename: __filename,
lineOffset: 0,
columnOffset: -codeDefinition.length
});
await fn(...Object.values(context));
return exports;
}
prepareContext(context) {
return context;
}
shouldResolveId(dep) {
if (isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
return false;
return !isAbsolute(dep) || !extname(dep);
}
shouldInterop(path, mod) {
if (this.options.interopDefault === false)
return false;
return !path.endsWith(".mjs") && "default" in mod;
}
async interopedImport(path) {
const mod = await import(path);
if (this.shouldInterop(path, mod)) {
const tryDefault = this.hasNestedDefault(mod);
return new Proxy(mod, {
get: proxyMethod("get", tryDefault),
set: proxyMethod("set", tryDefault),
has: proxyMethod("has", tryDefault),
deleteProperty: proxyMethod("deleteProperty", tryDefault)
});
}
return mod;
}
hasNestedDefault(target) {
return "__esModule" in target && target.__esModule && "default" in target.default;
}
}
function proxyMethod(name, tryDefault) {
return function(target, key, ...args) {
const result = Reflect[name](target, key, ...args);
if (isPrimitive(target.default))
return result;
if (tryDefault && key === "default" || typeof result === "undefined")
return Reflect[name](target.default, key, ...args);
return result;
};
}
function defineExport(exports, key, value) {
Object.defineProperty(exports, key, {
enumerable: true,
configurable: true,
get: value
});
}
function exportAll(exports, sourceModule) {
if (exports === sourceModule)
return;
if (isPrimitive(sourceModule) || Array.isArray(sourceModule))
return;
for (const key in sourceModule) {
if (key !== "default") {
try {
defineExport(exports, key, () => sourceModule[key]);
} catch (_err) {
}
}
}
}
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };

19
node_modules/vite-node/dist/hmr.cjs generated vendored Normal file
View File

@@ -0,0 +1,19 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var hmr = require('./chunk-hmr.cjs');
require('events');
require('./chunk-picocolors.cjs');
require('tty');
require('debug');
exports.createHmrEmitter = hmr.createHmrEmitter;
exports.createHotContext = hmr.createHotContext;
exports.getCache = hmr.getCache;
exports.handleMessage = hmr.handleMessage;
exports.reload = hmr.reload;
exports.sendMessageBuffer = hmr.sendMessageBuffer;
exports.viteNodeHmrPlugin = hmr.viteNodeHmrPlugin;

51
node_modules/vite-node/dist/hmr.d.ts generated vendored Normal file
View File

@@ -0,0 +1,51 @@
import { EventEmitter } from 'events';
import { HMRPayload, Plugin } from 'vite';
import { g as CustomEventMap, h as ViteNodeRunner, i as HMRPayload$1, H as HotContext } from './types-fc7e68bc.js';
type EventType = string | symbol;
type Handler<T = unknown> = (event: T) => void;
interface Emitter<Events extends Record<EventType, unknown>> {
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
}
type HMREmitter = Emitter<{
'message': HMRPayload;
}> & EventEmitter;
declare module 'vite' {
interface ViteDevServer {
emitter: HMREmitter;
}
}
declare function createHmrEmitter(): HMREmitter;
declare function viteNodeHmrPlugin(): Plugin;
type InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
interface HotModule {
id: string;
callbacks: HotCallback[];
}
interface HotCallback {
deps: string[];
fn: (modules: object[]) => void;
}
interface CacheData {
hotModulesMap: Map<string, HotModule>;
dataMap: Map<string, any>;
disposeMap: Map<string, (data: any) => void | Promise<void>>;
pruneMap: Map<string, (data: any) => void | Promise<void>>;
customListenersMap: Map<string, ((data: any) => void)[]>;
ctxToListenersMap: Map<string, Map<string, ((data: any) => void)[]>>;
messageBuffer: string[];
isFirstUpdate: boolean;
pending: boolean;
queued: Promise<(() => void) | undefined>[];
}
declare function getCache(runner: ViteNodeRunner): CacheData;
declare function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter): void;
declare function reload(runner: ViteNodeRunner, files: string[]): Promise<any[]>;
declare function handleMessage(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], payload: HMRPayload$1): Promise<void>;
declare function createHotContext(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], ownerPath: string): HotContext;
export { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };

5
node_modules/vite-node/dist/hmr.mjs generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export { a as createHmrEmitter, c as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs';
import 'events';
import './chunk-picocolors.mjs';
import 'tty';
import 'debug';

2
node_modules/vite-node/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
'use strict';

1
node_modules/vite-node/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-fc7e68bc.js';

1
node_modules/vite-node/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@

314
node_modules/vite-node/dist/server.cjs generated vendored Normal file
View File

@@ -0,0 +1,314 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var perf_hooks = require('perf_hooks');
var pathe = require('pathe');
var createDebug = require('debug');
var fs = require('fs');
var mlly = require('mlly');
var utils = require('./utils.cjs');
var picocolors = require('./chunk-picocolors.cjs');
var sourceMap = require('./source-map.cjs');
require('url');
require('tty');
require('source-map-support');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
const defaultInline = [
/virtual:/,
/\.[mc]?ts$/
];
const depsExternal = [
/\.cjs\.js$/,
/\.mjs$/
];
function guessCJSversion(id) {
if (id.match(ESM_EXT_RE)) {
for (const i of [
id.replace(ESM_EXT_RE, ".mjs"),
id.replace(ESM_EXT_RE, ".umd.js"),
id.replace(ESM_EXT_RE, ".cjs.js"),
id.replace(ESM_EXT_RE, ".js")
]) {
if (fs.existsSync(i))
return i;
}
}
if (id.match(ESM_FOLDER_RE)) {
for (const i of [
id.replace(ESM_FOLDER_RE, "/umd/$1"),
id.replace(ESM_FOLDER_RE, "/cjs/$1"),
id.replace(ESM_FOLDER_RE, "/lib/$1"),
id.replace(ESM_FOLDER_RE, "/$1")
]) {
if (fs.existsSync(i))
return i;
}
}
}
const _defaultExternalizeCache = /* @__PURE__ */ new Map();
async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
if (!cache.has(id))
cache.set(id, _shouldExternalize(id, options));
return cache.get(id);
}
async function _shouldExternalize(id, options) {
if (mlly.isNodeBuiltin(id))
return id;
if (id.startsWith("data:"))
return id;
id = patchWindowsImportPath(id);
if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
return false;
if (matchExternalizePattern(id, options == null ? void 0 : options.external))
return id;
const isNodeModule = id.includes("/node_modules/");
const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
id = guessCJS ? guessCJSversion(id) || id : id;
if (matchExternalizePattern(id, defaultInline))
return false;
if (matchExternalizePattern(id, depsExternal))
return id;
const isDist = id.includes("/dist/");
if ((isNodeModule || isDist) && await mlly.isValidNodeImport(id))
return id;
return false;
}
function matchExternalizePattern(id, patterns) {
if (patterns == null)
return false;
if (patterns === true)
return true;
for (const ex of patterns) {
if (typeof ex === "string") {
if (id.includes(`/node_modules/${ex}/`))
return true;
} else {
if (ex.test(id))
return true;
}
}
return false;
}
function patchWindowsImportPath(path) {
if (path.match(/^\w:\\/))
return `file:///${utils.slash(path)}`;
else if (path.match(/^\w:\//))
return `file:///${path}`;
else
return path;
}
function hashCode(s) {
return s.split("").reduce((a, b) => {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
class Debugger {
constructor(root, options) {
this.options = options;
this.externalizeMap = /* @__PURE__ */ new Map();
if (options.dumpModules)
this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
if (this.dumpDir) {
if (options.loadDumppedModules)
console.info(picocolors.picocolors.exports.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
else
console.info(picocolors.picocolors.exports.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
}
this.initPromise = this.clearDump();
}
async clearDump() {
if (!this.dumpDir)
return;
if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir))
await fs.promises.rm(this.dumpDir, { recursive: true, force: true });
await fs.promises.mkdir(this.dumpDir, { recursive: true });
}
encodeId(id) {
return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
}
async recordExternalize(id, path) {
if (!this.dumpDir)
return;
this.externalizeMap.set(id, path);
await this.writeInfo();
}
async dumpFile(id, result) {
if (!result || !this.dumpDir)
return;
await this.initPromise;
const name = this.encodeId(id);
return await fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}
${result.code}`, "utf-8");
}
async loadDump(id) {
if (!this.dumpDir)
return null;
await this.initPromise;
const name = this.encodeId(id);
const path = pathe.join(this.dumpDir, name);
if (!fs.existsSync(path))
return null;
const code = await fs.promises.readFile(path, "utf-8");
return {
code: code.replace(/^\/\/.*?\n/, ""),
map: void 0
};
}
async writeInfo() {
if (!this.dumpDir)
return;
const info = JSON.stringify({
time: new Date().toLocaleString(),
externalize: Object.fromEntries(this.externalizeMap.entries())
}, null, 2);
return fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8");
}
}
const debugRequest = createDebug__default["default"]("vite-node:server:request");
class ViteNodeServer {
constructor(server, options = {}) {
this.server = server;
this.options = options;
this.fetchPromiseMap = /* @__PURE__ */ new Map();
this.transformPromiseMap = /* @__PURE__ */ new Map();
this.fetchCache = /* @__PURE__ */ new Map();
this.externalizeCache = /* @__PURE__ */ new Map();
var _a, _b;
const ssrOptions = server.config.ssr;
if (ssrOptions) {
options.deps ?? (options.deps = {});
if (ssrOptions.noExternal === true) {
(_a = options.deps).inline ?? (_a.inline = true);
} else if (options.deps.inline !== true) {
(_b = options.deps).inline ?? (_b.inline = []);
options.deps.inline.push(...utils.toArray(ssrOptions.noExternal));
}
}
if (process.env.VITE_NODE_DEBUG_DUMP) {
options.debug = Object.assign({
dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
}, options.debug ?? {});
}
if (options.debug)
this.debugger = new Debugger(server.config.root, options.debug);
}
shouldExternalize(id) {
return shouldExternalize(id, this.options.deps, this.externalizeCache);
}
async resolveId(id, importer) {
if (importer && !importer.startsWith(this.server.config.root))
importer = pathe.resolve(this.server.config.root, importer);
const mode = importer && this.getTransformMode(importer) || "ssr";
return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
}
getSourceMap(source) {
var _a, _b;
const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
if (fetchResult == null ? void 0 : fetchResult.map)
return fetchResult.map;
const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null;
}
async fetchModule(id) {
id = utils.normalizeModuleId(id);
if (!this.fetchPromiseMap.has(id)) {
this.fetchPromiseMap.set(
id,
this._fetchModule(id).then((r) => {
return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
}).finally(() => {
this.fetchPromiseMap.delete(id);
})
);
}
return this.fetchPromiseMap.get(id);
}
async transformRequest(id) {
if (!this.transformPromiseMap.has(id)) {
this.transformPromiseMap.set(
id,
this._transformRequest(id).finally(() => {
this.transformPromiseMap.delete(id);
})
);
}
return this.transformPromiseMap.get(id);
}
getTransformMode(id) {
var _a, _b, _c, _d;
const withoutQuery = id.split("?")[0];
if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
return "web";
if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r)))
return "ssr";
if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
return "ssr";
return "web";
}
async _fetchModule(id) {
var _a;
let result;
const filePath = utils.toFilePath(id, this.server.config.root);
const module = this.server.moduleGraph.getModuleById(id);
const timestamp = module ? module.lastHMRTimestamp : null;
const cache = this.fetchCache.get(filePath);
if (timestamp !== null && cache && cache.timestamp >= timestamp)
return cache.result;
const time = Date.now();
const externalize = await this.shouldExternalize(filePath);
let duration;
if (externalize) {
result = { externalize };
(_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
} else {
const start = perf_hooks.performance.now();
const r = await this._transformRequest(id);
duration = perf_hooks.performance.now() - start;
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
}
this.fetchCache.set(filePath, {
duration,
timestamp: time,
result
});
return result;
}
async _transformRequest(id) {
var _a, _b, _c, _d;
debugRequest(id);
let result = null;
if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null;
if (result)
return result;
}
if (this.getTransformMode(id) === "web") {
result = await this.server.transformRequest(id);
if (result)
result = await this.server.ssrTransform(result.code, result.map, id);
} else {
result = await this.server.transformRequest(id, { ssr: true });
}
const sourcemap = this.options.sourcemap ?? "inline";
if (sourcemap === "inline" && result && !id.includes("node_modules"))
sourceMap.withInlineSourcemap(result);
if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
return result;
}
}
exports.ViteNodeServer = ViteNodeServer;
exports.guessCJSversion = guessCJSversion;
exports.shouldExternalize = shouldExternalize;

44
node_modules/vite-node/dist/server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { TransformResult, ViteDevServer } from 'vite';
import { f as DebuggerOptions, D as DepsHandlingOptions, e as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId, R as RawSourceMap } from './types-fc7e68bc.js';
declare class Debugger {
options: DebuggerOptions;
dumpDir: string | undefined;
initPromise: Promise<void> | undefined;
externalizeMap: Map<string, string>;
constructor(root: string, options: DebuggerOptions);
clearDump(): Promise<void>;
encodeId(id: string): string;
recordExternalize(id: string, path: string): Promise<void>;
dumpFile(id: string, result: TransformResult | null): Promise<void>;
loadDump(id: string): Promise<TransformResult | null>;
writeInfo(): Promise<void>;
}
declare function guessCJSversion(id: string): string | undefined;
declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map<string, Promise<string | false>>): Promise<string | false>;
declare class ViteNodeServer {
server: ViteDevServer;
options: ViteNodeServerOptions;
private fetchPromiseMap;
private transformPromiseMap;
fetchCache: Map<string, {
duration?: number | undefined;
timestamp: number;
result: FetchResult;
}>;
externalizeCache: Map<string, Promise<string | false>>;
debugger?: Debugger;
constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
shouldExternalize(id: string): Promise<string | false>;
resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null>;
getSourceMap(source: string): RawSourceMap | null;
fetchModule(id: string): Promise<FetchResult>;
transformRequest(id: string): Promise<TransformResult | null | undefined>;
getTransformMode(id: string): "web" | "ssr";
private _fetchModule;
private _transformRequest;
}
export { ViteNodeServer, guessCJSversion, shouldExternalize };

304
node_modules/vite-node/dist/server.mjs generated vendored Normal file
View File

@@ -0,0 +1,304 @@
import { performance } from 'perf_hooks';
import { resolve, join } from 'pathe';
import createDebug from 'debug';
import { existsSync, promises } from 'fs';
import { isNodeBuiltin, isValidNodeImport } from 'mlly';
import { slash, toArray, normalizeModuleId, toFilePath } from './utils.mjs';
import { p as picocolors } from './chunk-picocolors.mjs';
import { withInlineSourcemap } from './source-map.mjs';
import 'url';
import 'tty';
import 'source-map-support';
const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
const defaultInline = [
/virtual:/,
/\.[mc]?ts$/
];
const depsExternal = [
/\.cjs\.js$/,
/\.mjs$/
];
function guessCJSversion(id) {
if (id.match(ESM_EXT_RE)) {
for (const i of [
id.replace(ESM_EXT_RE, ".mjs"),
id.replace(ESM_EXT_RE, ".umd.js"),
id.replace(ESM_EXT_RE, ".cjs.js"),
id.replace(ESM_EXT_RE, ".js")
]) {
if (existsSync(i))
return i;
}
}
if (id.match(ESM_FOLDER_RE)) {
for (const i of [
id.replace(ESM_FOLDER_RE, "/umd/$1"),
id.replace(ESM_FOLDER_RE, "/cjs/$1"),
id.replace(ESM_FOLDER_RE, "/lib/$1"),
id.replace(ESM_FOLDER_RE, "/$1")
]) {
if (existsSync(i))
return i;
}
}
}
const _defaultExternalizeCache = /* @__PURE__ */ new Map();
async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
if (!cache.has(id))
cache.set(id, _shouldExternalize(id, options));
return cache.get(id);
}
async function _shouldExternalize(id, options) {
if (isNodeBuiltin(id))
return id;
if (id.startsWith("data:"))
return id;
id = patchWindowsImportPath(id);
if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
return false;
if (matchExternalizePattern(id, options == null ? void 0 : options.external))
return id;
const isNodeModule = id.includes("/node_modules/");
const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
id = guessCJS ? guessCJSversion(id) || id : id;
if (matchExternalizePattern(id, defaultInline))
return false;
if (matchExternalizePattern(id, depsExternal))
return id;
const isDist = id.includes("/dist/");
if ((isNodeModule || isDist) && await isValidNodeImport(id))
return id;
return false;
}
function matchExternalizePattern(id, patterns) {
if (patterns == null)
return false;
if (patterns === true)
return true;
for (const ex of patterns) {
if (typeof ex === "string") {
if (id.includes(`/node_modules/${ex}/`))
return true;
} else {
if (ex.test(id))
return true;
}
}
return false;
}
function patchWindowsImportPath(path) {
if (path.match(/^\w:\\/))
return `file:///${slash(path)}`;
else if (path.match(/^\w:\//))
return `file:///${path}`;
else
return path;
}
function hashCode(s) {
return s.split("").reduce((a, b) => {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
class Debugger {
constructor(root, options) {
this.options = options;
this.externalizeMap = /* @__PURE__ */ new Map();
if (options.dumpModules)
this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
if (this.dumpDir) {
if (options.loadDumppedModules)
console.info(picocolors.exports.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
else
console.info(picocolors.exports.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
}
this.initPromise = this.clearDump();
}
async clearDump() {
if (!this.dumpDir)
return;
if (!this.options.loadDumppedModules && existsSync(this.dumpDir))
await promises.rm(this.dumpDir, { recursive: true, force: true });
await promises.mkdir(this.dumpDir, { recursive: true });
}
encodeId(id) {
return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
}
async recordExternalize(id, path) {
if (!this.dumpDir)
return;
this.externalizeMap.set(id, path);
await this.writeInfo();
}
async dumpFile(id, result) {
if (!result || !this.dumpDir)
return;
await this.initPromise;
const name = this.encodeId(id);
return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}
${result.code}`, "utf-8");
}
async loadDump(id) {
if (!this.dumpDir)
return null;
await this.initPromise;
const name = this.encodeId(id);
const path = join(this.dumpDir, name);
if (!existsSync(path))
return null;
const code = await promises.readFile(path, "utf-8");
return {
code: code.replace(/^\/\/.*?\n/, ""),
map: void 0
};
}
async writeInfo() {
if (!this.dumpDir)
return;
const info = JSON.stringify({
time: new Date().toLocaleString(),
externalize: Object.fromEntries(this.externalizeMap.entries())
}, null, 2);
return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8");
}
}
const debugRequest = createDebug("vite-node:server:request");
class ViteNodeServer {
constructor(server, options = {}) {
this.server = server;
this.options = options;
this.fetchPromiseMap = /* @__PURE__ */ new Map();
this.transformPromiseMap = /* @__PURE__ */ new Map();
this.fetchCache = /* @__PURE__ */ new Map();
this.externalizeCache = /* @__PURE__ */ new Map();
var _a, _b;
const ssrOptions = server.config.ssr;
if (ssrOptions) {
options.deps ?? (options.deps = {});
if (ssrOptions.noExternal === true) {
(_a = options.deps).inline ?? (_a.inline = true);
} else if (options.deps.inline !== true) {
(_b = options.deps).inline ?? (_b.inline = []);
options.deps.inline.push(...toArray(ssrOptions.noExternal));
}
}
if (process.env.VITE_NODE_DEBUG_DUMP) {
options.debug = Object.assign({
dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
}, options.debug ?? {});
}
if (options.debug)
this.debugger = new Debugger(server.config.root, options.debug);
}
shouldExternalize(id) {
return shouldExternalize(id, this.options.deps, this.externalizeCache);
}
async resolveId(id, importer) {
if (importer && !importer.startsWith(this.server.config.root))
importer = resolve(this.server.config.root, importer);
const mode = importer && this.getTransformMode(importer) || "ssr";
return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
}
getSourceMap(source) {
var _a, _b;
const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
if (fetchResult == null ? void 0 : fetchResult.map)
return fetchResult.map;
const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null;
}
async fetchModule(id) {
id = normalizeModuleId(id);
if (!this.fetchPromiseMap.has(id)) {
this.fetchPromiseMap.set(
id,
this._fetchModule(id).then((r) => {
return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
}).finally(() => {
this.fetchPromiseMap.delete(id);
})
);
}
return this.fetchPromiseMap.get(id);
}
async transformRequest(id) {
if (!this.transformPromiseMap.has(id)) {
this.transformPromiseMap.set(
id,
this._transformRequest(id).finally(() => {
this.transformPromiseMap.delete(id);
})
);
}
return this.transformPromiseMap.get(id);
}
getTransformMode(id) {
var _a, _b, _c, _d;
const withoutQuery = id.split("?")[0];
if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
return "web";
if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r)))
return "ssr";
if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
return "ssr";
return "web";
}
async _fetchModule(id) {
var _a;
let result;
const filePath = toFilePath(id, this.server.config.root);
const module = this.server.moduleGraph.getModuleById(id);
const timestamp = module ? module.lastHMRTimestamp : null;
const cache = this.fetchCache.get(filePath);
if (timestamp !== null && cache && cache.timestamp >= timestamp)
return cache.result;
const time = Date.now();
const externalize = await this.shouldExternalize(filePath);
let duration;
if (externalize) {
result = { externalize };
(_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
} else {
const start = performance.now();
const r = await this._transformRequest(id);
duration = performance.now() - start;
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
}
this.fetchCache.set(filePath, {
duration,
timestamp: time,
result
});
return result;
}
async _transformRequest(id) {
var _a, _b, _c, _d;
debugRequest(id);
let result = null;
if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null;
if (result)
return result;
}
if (this.getTransformMode(id) === "web") {
result = await this.server.transformRequest(id);
if (result)
result = await this.server.ssrTransform(result.code, result.map, id);
} else {
result = await this.server.transformRequest(id, { ssr: true });
}
const sourcemap = this.options.sourcemap ?? "inline";
if (sourcemap === "inline" && result && !id.includes("node_modules"))
withInlineSourcemap(result);
if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
return result;
}
}
export { ViteNodeServer, guessCJSversion, shouldExternalize };

54
node_modules/vite-node/dist/source-map.cjs generated vendored Normal file
View File

@@ -0,0 +1,54 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var sourceMapSupport = require('source-map-support');
let SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
async function withInlineSourcemap(result) {
const map = result.map;
let code = result.code;
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
return result;
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
while (OTHER_SOURCE_MAP_REGEXP.test(code))
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
result.code = `${code.trimEnd()}
${VITE_NODE_SOURCEMAPPING_SOURCE}
//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
`;
return result;
}
function extractSourceMap(code) {
var _a;
const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
if (mapString)
return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
return null;
}
function installSourcemapsSupport(options) {
sourceMapSupport.install({
environment: "node",
handleUncaughtExceptions: false,
retrieveSourceMap(source) {
const map = options.getSourceMap(source);
if (map) {
return {
url: source,
map
};
}
return null;
}
});
}
exports.extractSourceMap = extractSourceMap;
exports.installSourcemapsSupport = installSourcemapsSupport;
exports.withInlineSourcemap = withInlineSourcemap;

11
node_modules/vite-node/dist/source-map.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import { TransformResult } from 'vite';
import { R as RawSourceMap } from './types-fc7e68bc.js';
interface InstallSourceMapSupportOptions {
getSourceMap: (source: string) => RawSourceMap | null | undefined;
}
declare function withInlineSourcemap(result: TransformResult): Promise<TransformResult>;
declare function extractSourceMap(code: string): RawSourceMap | null;
declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };

48
node_modules/vite-node/dist/source-map.mjs generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import { install } from 'source-map-support';
let SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
async function withInlineSourcemap(result) {
const map = result.map;
let code = result.code;
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
return result;
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
while (OTHER_SOURCE_MAP_REGEXP.test(code))
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
result.code = `${code.trimEnd()}
${VITE_NODE_SOURCEMAPPING_SOURCE}
//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
`;
return result;
}
function extractSourceMap(code) {
var _a;
const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
if (mapString)
return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
return null;
}
function installSourcemapsSupport(options) {
install({
environment: "node",
handleUncaughtExceptions: false,
retrieveSourceMap(source) {
const map = options.getSourceMap(source);
if (map) {
return {
url: source,
map
};
}
return null;
}
});
}
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };

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

@@ -0,0 +1,270 @@
type HMRPayload =
| ConnectedPayload
| UpdatePayload
| FullReloadPayload
| CustomPayload
| ErrorPayload
| PrunePayload
interface ConnectedPayload {
type: 'connected'
}
interface UpdatePayload {
type: 'update'
updates: Update[]
}
interface Update {
type: 'js-update' | 'css-update'
path: string
acceptedPath: string
timestamp: number
/**
* @experimental internal
*/
explicitImportRequired?: boolean | undefined
}
interface PrunePayload {
type: 'prune'
paths: string[]
}
interface FullReloadPayload {
type: 'full-reload'
path?: string
}
interface CustomPayload {
type: 'custom'
event: string
data?: any
}
interface ErrorPayload {
type: 'error'
err: {
[name: string]: any
message: string
stack: string
id?: string
frame?: string
plugin?: string
pluginCode?: string
loc?: {
file?: string
line: number
column: number
}
}
}
interface CustomEventMap {
'vite:beforeUpdate': UpdatePayload
'vite:afterUpdate': UpdatePayload
'vite:beforePrune': PrunePayload
'vite:beforeFullReload': FullReloadPayload
'vite:error': ErrorPayload
'vite:invalidate': InvalidatePayload
}
interface InvalidatePayload {
path: string
message: string | undefined
}
type InferCustomEventPayload<T extends string> =
T extends keyof CustomEventMap ? CustomEventMap[T] : any
type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: 'Module'
}
interface ViteHotContext {
readonly data: any
accept(): void
accept(cb: (mod: ModuleNamespace | undefined) => void): void
accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
accept(
deps: readonly string[],
cb: (mods: Array<ModuleNamespace | undefined>) => void,
): void
acceptExports(
exportNames: string | readonly string[],
cb?: (mod: ModuleNamespace | undefined) => void,
): void
dispose(cb: (data: any) => void): void
prune(cb: (data: any) => void): void
invalidate(message?: string): void
on<T extends string>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
}
declare const DEFAULT_REQUEST_STUBS: {
'/@vite/client': {
injectQuery: (id: string) => string;
createHotContext(): {
accept: () => void;
prune: () => void;
dispose: () => void;
decline: () => void;
invalidate: () => void;
on: () => void;
};
updateStyle(id: string, css: string): void;
};
};
declare class ModuleCacheMap extends Map<string, ModuleCache> {
normalizePath(fsPath: string): string;
/**
* Assign partial data to the map
*/
update(fsPath: string, mod: Partial<ModuleCache>): this;
set(fsPath: string, mod: ModuleCache): this;
get(fsPath: string): ModuleCache;
delete(fsPath: 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>;
/**
* Return parsed source map based on inlined source map of the module
*/
getSourceMap(id: string): RawSourceMap | null;
}
declare class ViteNodeRunner {
options: ViteNodeRunnerOptions;
root: string;
debug: boolean;
/**
* Holds the cache of modules
* Keys of the map are filepaths, or plain package names
*/
moduleCache: ModuleCacheMap;
constructor(options: ViteNodeRunnerOptions);
executeFile(file: string): Promise<any>;
executeId(id: string): Promise<any>;
getSourceMap(id: string): RawSourceMap | null;
/** @internal */
cachedRequest(rawId: string, callstack: string[]): Promise<any>;
/** @internal */
directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
prepareContext(context: Record<string, any>): Record<string, any>;
shouldResolveId(dep: string): boolean;
/**
* Define if a module should be interop-ed
* This function mostly for the ability to override by subclass
*/
shouldInterop(path: string, mod: any): boolean;
/**
* Import a module and interop it
*/
interopedImport(path: string): Promise<any>;
hasNestedDefault(target: any): any;
}
type Nullable<T> = T | null | undefined;
type Arrayable<T> = T | Array<T>;
interface DepsHandlingOptions {
external?: (string | RegExp)[];
inline?: (string | RegExp)[] | true;
/**
* Try to guess the CJS version of a package when it's invalid ESM
* @default false
*/
fallbackCJS?: boolean;
}
interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
}
interface FetchResult {
code?: string;
externalize?: string;
map?: RawSourceMap;
}
type HotContext = Omit<ViteHotContext, 'acceptDeps' | 'decline'>;
type FetchFunction = (id: string) => Promise<FetchResult>;
type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext;
interface ModuleCache {
promise?: Promise<any>;
exports?: any;
evaluated?: boolean;
code?: string;
map?: RawSourceMap;
/**
* Module ids that imports this module
*/
importers?: Set<string>;
}
interface ViteNodeRunnerOptions {
root: string;
fetchModule: FetchFunction;
resolveId?: ResolveIdFunction;
createHotContext?: CreateHotContextFunction;
base?: string;
moduleCache?: ModuleCacheMap;
interopDefault?: boolean;
requestStubs?: Record<string, any>;
debug?: boolean;
}
interface ViteNodeResolveId {
external?: boolean | 'absolute' | 'relative';
id: string;
meta?: Record<string, any> | null;
moduleSideEffects?: boolean | 'no-treeshake' | null;
syntheticNamedExports?: boolean | string | null;
}
interface ViteNodeServerOptions {
/**
* Inject inline sourcemap to modules
* @default 'inline'
*/
sourcemap?: 'inline' | boolean;
/**
* Deps handling
*/
deps?: DepsHandlingOptions;
/**
* Transform method for modules
*/
transformMode?: {
ssr?: RegExp[];
web?: RegExp[];
};
debug?: DebuggerOptions;
}
interface DebuggerOptions {
/**
* Dump the transformed module to filesystem
* Passing a string will dump to the specified path
*/
dumpModules?: boolean | string;
/**
* Read dumpped module from filesystem whenever exists.
* Useful for debugging by modifying the dump result from the filesystem.
*/
loadDumppedModules?: boolean;
}
export { Arrayable as A, CreateHotContextFunction as C, DepsHandlingOptions as D, FetchResult as F, HotContext as H, ModuleCacheMap as M, Nullable as N, RawSourceMap as R, StartOfSourceMap as S, ViteNodeRunnerOptions as V, FetchFunction as a, ResolveIdFunction as b, ModuleCache as c, ViteNodeResolveId as d, ViteNodeServerOptions as e, DebuggerOptions as f, CustomEventMap as g, ViteNodeRunner as h, HMRPayload as i, DEFAULT_REQUEST_STUBS as j };

2
node_modules/vite-node/dist/types.cjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
'use strict';

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

@@ -0,0 +1 @@
export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-fc7e68bc.js';

1
node_modules/vite-node/dist/types.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@

76
node_modules/vite-node/dist/utils.cjs generated vendored Normal file
View File

@@ -0,0 +1,76 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var url = require('url');
var fs = require('fs');
var pathe = require('pathe');
var mlly = require('mlly');
const isWindows = process.platform === "win32";
function slash(str) {
return str.replace(/\\/g, "/");
}
function mergeSlashes(str) {
return str.replace(/\/\//g, "/");
}
function normalizeRequestId(id, base) {
if (base && id.startsWith(base))
id = `/${id.slice(base.length)}`;
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^(node|file):/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
}
const queryRE = /\?.*$/s;
const hashRE = /#.*$/s;
const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, "");
function normalizeModuleId(id) {
return id.replace(/\\/g, "/").replace(/^\/@fs\//, "/").replace(/^file:\//, "/").replace(/^\/+/, "/");
}
function isPrimitive(v) {
return v !== Object(v);
}
function pathFromRoot(root, filename) {
if (mlly.isNodeBuiltin(filename))
return filename;
filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
if (!filename.startsWith(root))
return filename;
const relativePath = pathe.relative(root, filename);
const segments = relativePath.split("/");
const startIndex = segments.findIndex((segment) => segment !== ".." && segment !== ".");
return `/${segments.slice(startIndex).join("/")}`;
}
function toFilePath(id, root) {
let absolute = (() => {
if (id.startsWith("/@fs/"))
return id.slice(4);
if (!id.startsWith(root) && id.startsWith("/")) {
const resolved = pathe.resolve(root, id.slice(1));
if (fs.existsSync(resolved.replace(/\?.*$/, "")))
return resolved;
}
return id;
})();
if (absolute.startsWith("//"))
absolute = absolute.slice(1);
return isWindows && absolute.startsWith("/") ? slash(url.fileURLToPath(url.pathToFileURL(absolute.slice(1)).href)) : absolute;
}
function toArray(array) {
if (array === null || array === void 0)
array = [];
if (Array.isArray(array))
return array;
return [array];
}
exports.cleanUrl = cleanUrl;
exports.hashRE = hashRE;
exports.isPrimitive = isPrimitive;
exports.isWindows = isWindows;
exports.mergeSlashes = mergeSlashes;
exports.normalizeModuleId = normalizeModuleId;
exports.normalizeRequestId = normalizeRequestId;
exports.pathFromRoot = pathFromRoot;
exports.queryRE = queryRE;
exports.slash = slash;
exports.toArray = toArray;
exports.toFilePath = toFilePath;

21
node_modules/vite-node/dist/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { N as Nullable, A as Arrayable } from './types-fc7e68bc.js';
declare const isWindows: boolean;
declare function slash(str: string): string;
declare function mergeSlashes(str: string): string;
declare function normalizeRequestId(id: string, base?: string): string;
declare const queryRE: RegExp;
declare const hashRE: RegExp;
declare const cleanUrl: (url: string) => string;
declare function normalizeModuleId(id: string): string;
declare function isPrimitive(v: any): boolean;
declare function pathFromRoot(root: string, filename: string): string;
declare function toFilePath(id: string, root: string): string;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
export { cleanUrl, hashRE, isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, queryRE, slash, toArray, toFilePath };

61
node_modules/vite-node/dist/utils.mjs generated vendored Normal file
View File

@@ -0,0 +1,61 @@
import { fileURLToPath, pathToFileURL } from 'url';
import { existsSync } from 'fs';
import { relative, resolve } from 'pathe';
import { isNodeBuiltin } from 'mlly';
const isWindows = process.platform === "win32";
function slash(str) {
return str.replace(/\\/g, "/");
}
function mergeSlashes(str) {
return str.replace(/\/\//g, "/");
}
function normalizeRequestId(id, base) {
if (base && id.startsWith(base))
id = `/${id.slice(base.length)}`;
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^(node|file):/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
}
const queryRE = /\?.*$/s;
const hashRE = /#.*$/s;
const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, "");
function normalizeModuleId(id) {
return id.replace(/\\/g, "/").replace(/^\/@fs\//, "/").replace(/^file:\//, "/").replace(/^\/+/, "/");
}
function isPrimitive(v) {
return v !== Object(v);
}
function pathFromRoot(root, filename) {
if (isNodeBuiltin(filename))
return filename;
filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
if (!filename.startsWith(root))
return filename;
const relativePath = relative(root, filename);
const segments = relativePath.split("/");
const startIndex = segments.findIndex((segment) => segment !== ".." && segment !== ".");
return `/${segments.slice(startIndex).join("/")}`;
}
function toFilePath(id, root) {
let absolute = (() => {
if (id.startsWith("/@fs/"))
return id.slice(4);
if (!id.startsWith(root) && id.startsWith("/")) {
const resolved = resolve(root, id.slice(1));
if (existsSync(resolved.replace(/\?.*$/, "")))
return resolved;
}
return id;
})();
if (absolute.startsWith("//"))
absolute = absolute.slice(1);
return isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute;
}
function toArray(array) {
if (array === null || array === void 0)
array = [];
if (Array.isArray(array))
return array;
return [array];
}
export { cleanUrl, hashRE, isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, queryRE, slash, toArray, toFilePath };