123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688 |
- import { EventEmitter } from 'events';
- import { p as picocolors } from './chunk-constants.71e8a211.mjs';
- import { v as version, s as startVitest, d as divider } from './chunk-vite-node-externalize.8d8032d0.mjs';
- import 'tty';
- import 'url';
- import 'path';
- import './chunk-integrations-coverage.99c020eb.mjs';
- import 'local-pkg';
- import './chunk-env-node.ceb43f1c.mjs';
- import 'console';
- import './chunk-mock-date.2917be60.mjs';
- import 'vite';
- import 'process';
- import 'fs';
- import 'os';
- import 'util';
- import 'stream';
- import './vendor-_commonjsHelpers.4da45ef5.mjs';
- import './chunk-vite-node-client.da0a17ff.mjs';
- import 'module';
- import 'vm';
- import './chunk-vite-node-utils.473cd0b2.mjs';
- import 'assert';
- import 'debug';
- import 'perf_hooks';
- import 'worker_threads';
- import 'tinypool';
- import './chunk-utils-source-map.2be5aa48.mjs';
- import './chunk-utils-timers.b48455ed.mjs';
- import 'crypto';
- import './vendor-index.9d9196cc.mjs';
- import './vendor-index.29636037.mjs';
- import './chunk-magic-string.56b2b543.mjs';
- import 'strip-literal';
- import 'readline';
- import './vendor-index.ae96af6e.mjs';
- 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);
- const cli = cac("vitest");
- cli.version(version).option("-r, --root <path>", "root path").option("-c, --config <path>", "path to config file").option("-u, --update", "update snapshot").option("-w, --watch", "watch mode").option("-t, --testNamePattern <pattern>", "run tests with full names matching the specified pattern").option("--dir <path>", "base directory to scan for the test files").option("--ui", "enable UI").option("--open", "open UI automatically (default: !process.env.CI))").option("--api [api]", "serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--threads", "enabled threads (default: true)").option("--silent", "silent console output from tests").option("--isolate", "isolate environment for each test file (default: true)").option("--reporter <name>", "reporter").option("--outputTruncateLength <length>", "diff output length (default: 80)").option("--outputDiffLines <lines>", "number of diff output lines (default: 15)").option("--outputFile <filename/-s>", "write test results to a file when the --reporter=json or --reporter=junit option is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "enable coverage report").option("--run", "do not watch").option("--mode <name>", "override Vite mode (default: test)").option("--globals", "inject apis globally").option("--dom", "mock browser api with happy-dom").option("--browser", "run tests in browser").option("--environment <env>", "runner environment (default: node)").option("--passWithNoTests", "pass when no tests found").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order)").option("--no-color", "Removes colors from the console output").option("--segfault-retry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").help();
- cli.command("run [...filters]").action(run);
- cli.command("related [...filters]").action(runRelated);
- cli.command("watch [...filters]").action(watch);
- cli.command("dev [...filters]").action(watch);
- cli.command("bench [...filters]").action(benchmark);
- cli.command("[...filters]").action((filters, options) => start("test", filters, options));
- cli.parse();
- async function runRelated(relatedFiles, argv) {
- argv.related = relatedFiles;
- argv.passWithNoTests ?? (argv.passWithNoTests = true);
- await start("test", [], argv);
- }
- async function watch(cliFilters, options) {
- options.watch = true;
- await start("test", cliFilters, options);
- }
- async function run(cliFilters, options) {
- options.run = true;
- await start("test", cliFilters, options);
- }
- async function benchmark(cliFilters, options) {
- console.warn(picocolors.exports.yellow("Benchmarking is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it."));
- await start("benchmark", cliFilters, options);
- }
- async function start(mode, cliFilters, options) {
- try {
- if (await startVitest(mode, cliFilters, options) === false)
- process.exit();
- } catch (e) {
- process.exitCode = 1;
- console.error(`
- ${picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(" Unhandled Error "))))}`);
- console.error(e);
- console.error("\n\n");
- }
- }
|