Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@vitest/utils

Package Overview
Dependencies
Maintainers
5
Versions
190
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vitest/utils - npm Package Compare versions

Comparing version
4.0.0-beta.4
to
4.0.0-beta.5
+329
dist/chunk-helpers.js
// TODO: this is all copy pasted from Vite - can they expose a module that exports only constants?
const KNOWN_ASSET_TYPES = [
"apng",
"bmp",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"woff2?",
"eot",
"ttf",
"otf",
"webmanifest",
"pdf",
"txt"
];
const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
const VALID_ID_PREFIX = `/@id/`;
/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
const NULL_BYTE_PLACEHOLDER = `__x00__`;
/**
* Get original stacktrace without source map support the most performant way.
* - Create only 1 stack frame.
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
*/
function createSimpleStackTrace(options) {
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
const limit = Error.stackTraceLimit;
const prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
Error.prepareStackTrace = (e) => e.stack;
const err = new Error(message);
const stackTrace = err.stack || "";
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = limit;
return stackTrace;
}
function notNullish(v) {
return v != null;
}
function assertTypes(value, name, types) {
const receivedType = typeof value;
const pass = types.includes(receivedType);
if (!pass) {
throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
}
}
function isPrimitive(value) {
return value === null || typeof value !== "function" && typeof value !== "object";
}
function slash(path) {
return path.replace(/\\/g, "/");
}
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
const externalRE = /^(?:[a-z]+:)?\/\//;
const isExternalUrl = (url) => externalRE.test(url);
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
* This is prepended to resolved ids that are not valid browser
* import specifiers by the importAnalysis plugin.
*/
function wrapId(id) {
return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
}
/**
* Undo {@link wrapId}'s `/@id/` and null byte replacements.
*/
function unwrapId(id) {
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
}
function withTrailingSlash(path) {
if (path[path.length - 1] !== "/") {
return `${path}/`;
}
return path;
}
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
function isBareImport(id) {
return bareImportRE.test(id);
}
// convert RegExp.toString to RegExp
function parseRegexp(input) {
// Parse input
// eslint-disable-next-line regexp/no-misleading-capturing-group
const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
// match nothing
if (!m) {
return /$^/;
}
// Invalid flags
// eslint-disable-next-line regexp/optimal-quantifier-concatenation
if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
return new RegExp(input);
}
// Create the regular expression
return new RegExp(m[2], m[3]);
}
function toArray(array) {
if (array === null || array === undefined) {
array = [];
}
if (Array.isArray(array)) {
return array;
}
return [array];
}
function isObject(item) {
return item != null && typeof item === "object" && !Array.isArray(item);
}
function isFinalObj(obj) {
return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
}
function getType(value) {
return Object.prototype.toString.apply(value).slice(8, -1);
}
function collectOwnProperties(obj, collector) {
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
Object.getOwnPropertyNames(obj).forEach(collect);
Object.getOwnPropertySymbols(obj).forEach(collect);
}
function getOwnProperties(obj) {
const ownProps = new Set();
if (isFinalObj(obj)) {
return [];
}
collectOwnProperties(obj, ownProps);
return Array.from(ownProps);
}
const defaultCloneOptions = { forceWritable: false };
function deepClone(val, options = defaultCloneOptions) {
const seen = new WeakMap();
return clone(val, seen, options);
}
function clone(val, seen, options = defaultCloneOptions) {
let k, out;
if (seen.has(val)) {
return seen.get(val);
}
if (Array.isArray(val)) {
out = Array.from({ length: k = val.length });
seen.set(val, out);
while (k--) {
out[k] = clone(val[k], seen, options);
}
return out;
}
if (Object.prototype.toString.call(val) === "[object Object]") {
out = Object.create(Object.getPrototypeOf(val));
seen.set(val, out);
// we don't need properties from prototype
const props = getOwnProperties(val);
for (const k of props) {
const descriptor = Object.getOwnPropertyDescriptor(val, k);
if (!descriptor) {
continue;
}
const cloned = clone(val[k], seen, options);
if (options.forceWritable) {
Object.defineProperty(out, k, {
enumerable: descriptor.enumerable,
configurable: true,
writable: true,
value: cloned
});
} else if ("get" in descriptor) {
Object.defineProperty(out, k, {
...descriptor,
get() {
return cloned;
}
});
} else {
Object.defineProperty(out, k, {
...descriptor,
value: cloned
});
}
}
return out;
}
return val;
}
function noop() {}
function objectAttr(source, path, defaultValue = undefined) {
// a[3].b -> a.3.b
const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
let result = source;
for (const p of paths) {
result = new Object(result)[p];
if (result === undefined) {
return defaultValue;
}
}
return result;
}
function createDefer() {
let resolve = null;
let reject = null;
const p = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
p.resolve = resolve;
p.reject = reject;
return p;
}
/**
* If code starts with a function call, will return its last index, respecting arguments.
* This will return 25 - last ending character of toMatch ")"
* Also works with callbacks
* ```
* toMatch({ test: '123' });
* toBeAliased('123')
* ```
*/
function getCallLastIndex(code) {
let charIndex = -1;
let inString = null;
let startedBracers = 0;
let endedBracers = 0;
let beforeChar = null;
while (charIndex <= code.length) {
beforeChar = code[charIndex];
charIndex++;
const char = code[charIndex];
const isCharString = char === "\"" || char === "'" || char === "`";
if (isCharString && beforeChar !== "\\") {
if (inString === char) {
inString = null;
} else if (!inString) {
inString = char;
}
}
if (!inString) {
if (char === "(") {
startedBracers++;
}
if (char === ")") {
endedBracers++;
}
}
if (startedBracers && endedBracers && startedBracers === endedBracers) {
return charIndex;
}
}
return null;
}
function isNegativeNaN(val) {
if (!Number.isNaN(val)) {
return false;
}
const f64 = new Float64Array(1);
f64[0] = val;
const u32 = new Uint32Array(f64.buffer);
const isNegative = u32[1] >>> 31 === 1;
return isNegative;
}
function toString(v) {
return Object.prototype.toString.call(v);
}
function isPlainObject(val) {
return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
}
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
/**
* Deep merge :P
*
* Will merge objects only if they are plain
*
* Do not merge types - it is very expensive and usually it's better to case a type here
*/
function deepMerge(target, ...sources) {
if (!sources.length) {
return target;
}
const source = sources.shift();
if (source === undefined) {
return target;
}
if (isMergeableObject(target) && isMergeableObject(source)) {
Object.keys(source).forEach((key) => {
const _source = source;
if (isMergeableObject(_source[key])) {
if (!target[key]) {
target[key] = {};
}
deepMerge(target[key], _source[key]);
} else {
target[key] = _source[key];
}
});
}
return deepMerge(target, ...sources);
}
export { CSS_LANGS_RE as C, KNOWN_ASSET_RE as K, NULL_BYTE_PLACEHOLDER as N, VALID_ID_PREFIX as V, KNOWN_ASSET_TYPES as a, assertTypes as b, cleanUrl as c, clone as d, createDefer as e, createSimpleStackTrace as f, deepClone as g, deepMerge as h, isPrimitive as i, getCallLastIndex as j, getOwnProperties as k, getType as l, isBareImport as m, notNullish as n, isExternalUrl as o, isNegativeNaN as p, isObject as q, noop as r, objectAttr as s, parseRegexp as t, slash as u, toArray as v, unwrapId as w, withTrailingSlash as x, wrapId as y };
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _UNC_REGEX = /^[/\\]{2}/;
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
const normalize = function(path) {
if (path.length === 0) {
return ".";
}
path = normalizeWindowsPath(path);
const isUNCPath = path.match(_UNC_REGEX);
const isPathAbsolute = isAbsolute(path);
const trailingSeparator = path[path.length - 1] === "/";
path = normalizeString(path, !isPathAbsolute);
if (path.length === 0) {
if (isPathAbsolute) {
return "/";
}
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) {
path += "/";
}
if (_DRIVE_LETTER_RE.test(path)) {
path += "/";
}
if (isUNCPath) {
if (!isPathAbsolute) {
return `//./${path}`;
}
return `//${path}`;
}
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
};
const join = function(...segments) {
let path = "";
for (const seg of segments) {
if (!seg) {
continue;
}
if (path.length > 0) {
const pathTrailing = path[path.length - 1] === "/";
const segLeading = seg[0] === "/";
const both = pathTrailing && segLeading;
if (both) {
path += seg.slice(1);
} else {
path += pathTrailing || segLeading ? seg : `/${seg}`;
}
} else {
path += seg;
}
}
return normalize(path);
};
function cwd() {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd().replace(/\\/g, "/");
}
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd();
if (!path || path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) {
char = path[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path.slice(lastSlash + 1, index)}`;
} else {
res = path.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const dirname = function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
segments[0] += "/";
}
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
export { dirname as d, join as j, resolve as r };
declare function findNearestPackageData(basedir: string): {
type?: "module" | "commonjs";
};
declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined;
declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void;
export { findNearestPackageData, getCachedData, setCacheData };
import fs from 'node:fs';
import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js';
const packageCache = new Map();
function findNearestPackageData(basedir) {
const originalBasedir = basedir;
while (basedir) {
var _tryStatSync;
const cached = getCachedData(packageCache, basedir, originalBasedir);
if (cached) {
return cached;
}
const pkgPath = join(basedir, "package.json");
if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) {
const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
if (packageCache) {
setCacheData(packageCache, pkgData, basedir, originalBasedir);
}
return pkgData;
}
const nextBasedir = dirname(basedir);
if (nextBasedir === basedir) {
break;
}
basedir = nextBasedir;
}
return {};
}
function stripBomTag(content) {
if (content.charCodeAt(0) === 65279) {
return content.slice(1);
}
return content;
}
function tryStatSync(file) {
try {
// The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
return fs.statSync(file, { throwIfNoEntry: false });
} catch {}
}
function getCachedData(cache, basedir, originalBasedir) {
const pkgData = cache.get(getFnpdCacheKey(basedir));
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), pkgData);
});
return pkgData;
}
}
function setCacheData(cache, data, basedir, originalBasedir) {
cache.set(getFnpdCacheKey(basedir), data);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), data);
});
}
function getFnpdCacheKey(basedir) {
return `fnpd_${basedir}`;
}
/**
* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
* @param shorterDir Shorter dir path, e.g. `/User/foo`
*/
function traverseBetweenDirs(longerDir, shorterDir, cb) {
while (longerDir !== shorterDir) {
cb(longerDir);
longerDir = dirname(longerDir);
}
}
export { findNearestPackageData, getCachedData, setCacheData };
+1
-1

@@ -5,3 +5,3 @@ import { printDiffOrStringify } from './diff.js';

import 'tinyrainbow';
import './helpers.js';
import './chunk-helpers.js';
import 'loupe';

@@ -8,0 +8,0 @@

@@ -20,2 +20,16 @@ import { Nullable, Arrayable } from './types.js';

declare function slash(path: string): string;
declare function cleanUrl(url: string): string;
declare const isExternalUrl: (url: string) => boolean;
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
* This is prepended to resolved ids that are not valid browser
* import specifiers by the importAnalysis plugin.
*/
declare function wrapId(id: string): string;
/**
* Undo {@link wrapId}'s `/@id/` and null byte replacements.
*/
declare function unwrapId(id: string): string;
declare function withTrailingSlash(path: string): string;
declare function isBareImport(id: string): boolean;
// convert RegExp.toString to RegExp

@@ -56,3 +70,3 @@ declare function parseRegexp(input: string): RegExp;

export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray };
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray, unwrapId, withTrailingSlash, wrapId };
export type { DeferPromise };

@@ -1,251 +0,1 @@

/**
* Get original stacktrace without source map support the most performant way.
* - Create only 1 stack frame.
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
*/
function createSimpleStackTrace(options) {
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
const limit = Error.stackTraceLimit;
const prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
Error.prepareStackTrace = (e) => e.stack;
const err = new Error(message);
const stackTrace = err.stack || "";
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = limit;
return stackTrace;
}
function notNullish(v) {
return v != null;
}
function assertTypes(value, name, types) {
const receivedType = typeof value;
const pass = types.includes(receivedType);
if (!pass) {
throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
}
}
function isPrimitive(value) {
return value === null || typeof value !== "function" && typeof value !== "object";
}
function slash(path) {
return path.replace(/\\/g, "/");
}
// convert RegExp.toString to RegExp
function parseRegexp(input) {
// Parse input
// eslint-disable-next-line regexp/no-misleading-capturing-group
const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
// match nothing
if (!m) {
return /$^/;
}
// Invalid flags
// eslint-disable-next-line regexp/optimal-quantifier-concatenation
if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
return new RegExp(input);
}
// Create the regular expression
return new RegExp(m[2], m[3]);
}
function toArray(array) {
if (array === null || array === undefined) {
array = [];
}
if (Array.isArray(array)) {
return array;
}
return [array];
}
function isObject(item) {
return item != null && typeof item === "object" && !Array.isArray(item);
}
function isFinalObj(obj) {
return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
}
function getType(value) {
return Object.prototype.toString.apply(value).slice(8, -1);
}
function collectOwnProperties(obj, collector) {
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
Object.getOwnPropertyNames(obj).forEach(collect);
Object.getOwnPropertySymbols(obj).forEach(collect);
}
function getOwnProperties(obj) {
const ownProps = new Set();
if (isFinalObj(obj)) {
return [];
}
collectOwnProperties(obj, ownProps);
return Array.from(ownProps);
}
const defaultCloneOptions = { forceWritable: false };
function deepClone(val, options = defaultCloneOptions) {
const seen = new WeakMap();
return clone(val, seen, options);
}
function clone(val, seen, options = defaultCloneOptions) {
let k, out;
if (seen.has(val)) {
return seen.get(val);
}
if (Array.isArray(val)) {
out = Array.from({ length: k = val.length });
seen.set(val, out);
while (k--) {
out[k] = clone(val[k], seen, options);
}
return out;
}
if (Object.prototype.toString.call(val) === "[object Object]") {
out = Object.create(Object.getPrototypeOf(val));
seen.set(val, out);
// we don't need properties from prototype
const props = getOwnProperties(val);
for (const k of props) {
const descriptor = Object.getOwnPropertyDescriptor(val, k);
if (!descriptor) {
continue;
}
const cloned = clone(val[k], seen, options);
if (options.forceWritable) {
Object.defineProperty(out, k, {
enumerable: descriptor.enumerable,
configurable: true,
writable: true,
value: cloned
});
} else if ("get" in descriptor) {
Object.defineProperty(out, k, {
...descriptor,
get() {
return cloned;
}
});
} else {
Object.defineProperty(out, k, {
...descriptor,
value: cloned
});
}
}
return out;
}
return val;
}
function noop() {}
function objectAttr(source, path, defaultValue = undefined) {
// a[3].b -> a.3.b
const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
let result = source;
for (const p of paths) {
result = new Object(result)[p];
if (result === undefined) {
return defaultValue;
}
}
return result;
}
function createDefer() {
let resolve = null;
let reject = null;
const p = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
p.resolve = resolve;
p.reject = reject;
return p;
}
/**
* If code starts with a function call, will return its last index, respecting arguments.
* This will return 25 - last ending character of toMatch ")"
* Also works with callbacks
* ```
* toMatch({ test: '123' });
* toBeAliased('123')
* ```
*/
function getCallLastIndex(code) {
let charIndex = -1;
let inString = null;
let startedBracers = 0;
let endedBracers = 0;
let beforeChar = null;
while (charIndex <= code.length) {
beforeChar = code[charIndex];
charIndex++;
const char = code[charIndex];
const isCharString = char === "\"" || char === "'" || char === "`";
if (isCharString && beforeChar !== "\\") {
if (inString === char) {
inString = null;
} else if (!inString) {
inString = char;
}
}
if (!inString) {
if (char === "(") {
startedBracers++;
}
if (char === ")") {
endedBracers++;
}
}
if (startedBracers && endedBracers && startedBracers === endedBracers) {
return charIndex;
}
}
return null;
}
function isNegativeNaN(val) {
if (!Number.isNaN(val)) {
return false;
}
const f64 = new Float64Array(1);
f64[0] = val;
const u32 = new Uint32Array(f64.buffer);
const isNegative = u32[1] >>> 31 === 1;
return isNegative;
}
function toString(v) {
return Object.prototype.toString.call(v);
}
function isPlainObject(val) {
return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
}
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
/**
* Deep merge :P
*
* Will merge objects only if they are plain
*
* Do not merge types - it is very expensive and usually it's better to case a type here
*/
function deepMerge(target, ...sources) {
if (!sources.length) {
return target;
}
const source = sources.shift();
if (source === undefined) {
return target;
}
if (isMergeableObject(target) && isMergeableObject(source)) {
Object.keys(source).forEach((key) => {
const _source = source;
if (isMergeableObject(_source[key])) {
if (!target[key]) {
target[key] = {};
}
deepMerge(target[key], _source[key]);
} else {
target[key] = _source[key];
}
});
}
return deepMerge(target, ...sources);
}
export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray };
export { b as assertTypes, c as cleanUrl, d as clone, e as createDefer, f as createSimpleStackTrace, g as deepClone, h as deepMerge, j as getCallLastIndex, k as getOwnProperties, l as getType, m as isBareImport, o as isExternalUrl, p as isNegativeNaN, q as isObject, i as isPrimitive, r as noop, n as notNullish, s as objectAttr, t as parseRegexp, u as slash, v as toArray, w as unwrapId, x as withTrailingSlash, y as wrapId } from './chunk-helpers.js';
import { PrettyFormatOptions } from '@vitest/pretty-format';
export { DeferPromise, assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js';
export { DeferPromise, assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray, unwrapId, withTrailingSlash, wrapId } from './helpers.js';
import { Colors } from 'tinyrainbow';
export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js';
// TODO: this is all copy pasted from Vite - can they expose a module that exports only constants?
declare const KNOWN_ASSET_TYPES: string[];
declare const KNOWN_ASSET_RE: RegExp;
declare const CSS_LANGS_RE: RegExp;
/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
declare const VALID_ID_PREFIX = "/@id/";
/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
declare const NULL_BYTE_PLACEHOLDER = "__x00__";
type Inspect = (value: unknown, options: Options) => string;

@@ -61,3 +82,3 @@ interface Options {

export { format, getSafeTimers, highlight, inspect, lineSplitRE, nanoid, objDisplay, offsetToLineNumber, positionToOffset, setSafeTimers, shuffle, stringify };
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX, format, getSafeTimers, highlight, inspect, lineSplitRE, nanoid, objDisplay, offsetToLineNumber, positionToOffset, setSafeTimers, shuffle, stringify };
export type { LoupeOptions, SafeTimers, StringifyOptions };

@@ -0,4 +1,4 @@

export { C as CSS_LANGS_RE, K as KNOWN_ASSET_RE, a as KNOWN_ASSET_TYPES, N as NULL_BYTE_PLACEHOLDER, V as VALID_ID_PREFIX, b as assertTypes, c as cleanUrl, d as clone, e as createDefer, f as createSimpleStackTrace, g as deepClone, h as deepMerge, j as getCallLastIndex, k as getOwnProperties, l as getType, m as isBareImport, o as isExternalUrl, p as isNegativeNaN, q as isObject, i as isPrimitive, r as noop, n as notNullish, s as objectAttr, t as parseRegexp, u as slash, v as toArray, w as unwrapId, x as withTrailingSlash, y as wrapId } from './chunk-helpers.js';
import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
export { f as format, i as inspect, o as objDisplay, s as stringify } from './chunk-_commonjsHelpers.js';
export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js';
import c from 'tinyrainbow';

@@ -5,0 +5,0 @@ import '@vitest/pretty-format';

@@ -1,2 +0,3 @@

import { isPrimitive, notNullish } from './helpers.js';
import { i as isPrimitive, n as notNullish } from './chunk-helpers.js';
import { r as resolve$1 } from './chunk-pathe.M-eThtNZ.js';

@@ -285,3 +286,3 @@ const comma = ','.charCodeAt(0);

*/
function resolve$1(input, base) {
function resolve(input, base) {
if (!input && !base)

@@ -359,3 +360,3 @@ return '';

const prefix = sourceRoot ? sourceRoot + "/" : "";
return (source) => resolve$1(prefix + (source || ""), from);
return (source) => resolve(prefix + (source || ""), from);
}

@@ -642,97 +643,2 @@

const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
function cwd() {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd().replace(/\\/g, "/");
}
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd();
if (!path || path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) {
char = path[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path.slice(lastSlash + 1, index)}`;
} else {
res = path.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;

@@ -751,2 +657,4 @@ const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;

"/node_modules/tinyspy/",
"/vite/dist/node/module-runner",
"/rolldown-vite/dist/node/module-runner",
"/deps/chunk-",

@@ -855,3 +763,3 @@ "/deps/@vitest",

// normalize Windows path (\ -> /)
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$1(file);
if (method) {

@@ -858,0 +766,0 @@ method = method.replace(/__vite_ssr_import_\d+__\./g, "");

{
"name": "@vitest/utils",
"type": "module",
"version": "4.0.0-beta.4",
"version": "4.0.0-beta.5",
"description": "Shared Vitest utility functions",

@@ -31,2 +31,6 @@ "license": "MIT",

},
"./resolver": {
"types": "./dist/resolver.d.ts",
"default": "./dist/resolver.js"
},
"./error": {

@@ -66,3 +70,3 @@ "types": "./dist/error.d.ts",

"tinyrainbow": "^2.0.0",
"@vitest/pretty-format": "4.0.0-beta.4"
"@vitest/pretty-format": "4.0.0-beta.5"
},

@@ -69,0 +73,0 @@ "devDependencies": {

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