This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
-5
View File
@@ -1,5 +0,0 @@
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
export { getDefaultExportFromCjs as g };
+20 -4
View File
@@ -1,6 +1,6 @@
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { D as DiffOptions } from './types.d-BCElaP-c.js';
export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js';
import '@vitest/pretty-format';
/**
* Diff Match and Patch
@@ -75,14 +75,29 @@ declare function diffLinesRaw(aLines: Array<string>, bLines: Array<string>, opti
declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string;
declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array<Diff>, boolean];
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
interface StringifiedMemory {
expected?: string;
actual?: string;
}
interface Memorize {
(pointer: "expected" | "actual", stringifiedValue: string): string;
}
/**
* @param a Expected value
* @param b Received value
* @param options Diff options
* @returns {string | null} a string diff
*/
declare function diff(a: any, b: any, options?: DiffOptions): string | undefined;
declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions): string | undefined;
declare function diff(a: any, b: any, options?: DiffOptions, memorize?: Memorize): string | undefined;
declare function getDefaultFormatOptions(options?: DiffOptions): PrettyFormatOptions;
declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions, memory?: StringifiedMemory): string | undefined;
declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet<WeakKey>, expectedReplaced?: WeakSet<WeakKey>): {
replacedActual: any;
replacedExpected: any;
@@ -90,4 +105,5 @@ declare function replaceAsymmetricMatcher(actual: any, expected: any, actualRepl
type PrintLabel = (string: string) => string;
declare function getLabelPrinter(...strings: Array<string>): PrintLabel;
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getDefaultFormatOptions, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export type { StringifiedMemory };
+41 -28
View File
@@ -2,7 +2,6 @@ import { plugins, format } from '@vitest/pretty-format';
import c from 'tinyrainbow';
import { stringify } from './display.js';
import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js';
import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
import './constants.js';
/**
@@ -333,7 +332,6 @@ function diff_cleanupSemanticLossless(diffs) {
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
function diff_cleanupMerge(diffs) {
var _diffs$at;
// Add a dummy entry at the end.
diffs.push(new Diff(DIFF_EQUAL, ""));
let pointer = 0;
@@ -404,7 +402,7 @@ function diff_cleanupMerge(diffs) {
break;
}
}
if (((_diffs$at = diffs.at(-1)) === null || _diffs$at === void 0 ? void 0 : _diffs$at[1]) === "") {
if (diffs.at(-1)?.[1] === "") {
diffs.pop();
}
// Second pass: look for single edits surrounded on both sides by equalities
@@ -495,6 +493,10 @@ function diff_cleanupSemanticScore_(one, two) {
const NO_DIFF_MESSAGE = "Compared values have no visual difference.";
const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead.";
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var build = {};
var hasRequiredBuild;
@@ -1623,8 +1625,8 @@ function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCo
}
// Compare two arrays of strings line-by-line.
function diffLinesRaw(aLines, bLines, options) {
const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
const truncate = options?.truncateThreshold ?? false;
const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length;
const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length;
const truncated = aLength !== aLines.length || bLength !== bLines.length;
@@ -1697,8 +1699,8 @@ function getNewLineSymbol(string) {
return string.includes("\r\n") ? "\r\n" : "\n";
}
function diffStrings(a, b, options) {
const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
const truncate = options?.truncateThreshold ?? false;
const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
let aLength = a.length;
let bLength = b.length;
if (truncate) {
@@ -1966,6 +1968,7 @@ const FALLBACK_FORMAT_OPTIONS = {
maxDepth: 8,
plugins: PLUGINS
};
const DEFAULT_MEMORIZE = (_, v) => v;
// Generate a string that will highlight the difference between two values
// with green and red. (similar to how github does code diffing)
/**
@@ -1974,7 +1977,7 @@ const FALLBACK_FORMAT_OPTIONS = {
* @param options Diff options
* @returns {string | null} a string diff
*/
function diff(a, b, options) {
function diff(a, b, options, memorize = DEFAULT_MEMORIZE) {
if (Object.is(a, b)) {
return "";
}
@@ -2008,10 +2011,10 @@ function diff(a, b, options) {
function truncate(s) {
return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`;
}
aDisplay = truncate(aDisplay);
bDisplay = truncate(bDisplay);
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`;
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`;
aDisplay = memorize("expected", truncate(aDisplay));
bDisplay = memorize("actual", truncate(bDisplay));
const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)}\n${aDisplay}`;
const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)}\n${bDisplay}`;
return `${aDiff}\n\n${bDiff}`;
}
if (omitDifference) {
@@ -2020,15 +2023,21 @@ function diff(a, b, options) {
switch (aType) {
case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options);
case "boolean":
case "number": return comparePrimitive(a, b, options);
case "map": return compareObjects(sortMap(a), sortMap(b), options);
case "set": return compareObjects(sortSet(a), sortSet(b), options);
default: return compareObjects(a, b, options);
case "number": return comparePrimitive(a, b, options, memorize);
case "map": return compareObjects(sortMap(a), sortMap(b), options, memorize);
case "set": return compareObjects(sortSet(a), sortSet(b), options, memorize);
default: return compareObjects(a, b, options, memorize);
}
}
function comparePrimitive(a, b, options) {
const aFormat = format(a, FORMAT_OPTIONS);
const bFormat = format(b, FORMAT_OPTIONS);
function createMemorize(memory) {
return (pointer, stringifiedValue) => {
memory[pointer] = stringifiedValue;
return stringifiedValue;
};
}
function comparePrimitive(a, b, options, memorize = DEFAULT_MEMORIZE) {
const aFormat = memorize("expected", format(a, FORMAT_OPTIONS));
const bFormat = memorize("actual", format(b, FORMAT_OPTIONS));
return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options);
}
function sortMap(map) {
@@ -2037,12 +2046,12 @@ function sortMap(map) {
function sortSet(set) {
return new Set(Array.from(set.values()).sort());
}
function compareObjects(a, b, options) {
function compareObjects(a, b, options, memorize = DEFAULT_MEMORIZE) {
let difference;
let hasThrown = false;
try {
const formatOptions = getFormatOptions(FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b, formatOptions, options);
difference = getObjectsDifference(a, b, formatOptions, options, memorize);
} catch {
hasThrown = true;
}
@@ -2051,13 +2060,16 @@ function compareObjects(a, b, options) {
// without calling `toJSON`. It's also possible that toJSON might throw.
if (difference === undefined || difference === noDiffMessage) {
const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b, formatOptions, options);
difference = getObjectsDifference(a, b, formatOptions, options, memorize);
if (difference !== noDiffMessage && !hasThrown) {
difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`;
}
}
return difference;
}
function getDefaultFormatOptions(options) {
return getFormatOptions(FORMAT_OPTIONS, options);
}
function getFormatOptions(formatOptions, options) {
const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options);
return {
@@ -2067,7 +2079,7 @@ function getFormatOptions(formatOptions, options) {
maxDepth: maxDepth ?? formatOptions.maxDepth
};
}
function getObjectsDifference(a, b, formatOptions, options) {
function getObjectsDifference(a, b, formatOptions, options, memorize = DEFAULT_MEMORIZE) {
const formatOptionsZeroIndent = {
...formatOptions,
indent: 0
@@ -2077,8 +2089,8 @@ function getObjectsDifference(a, b, formatOptions, options) {
if (aCompare === bCompare) {
return getCommonMessage(NO_DIFF_MESSAGE, options);
} else {
const aDisplay = format(a, formatOptions);
const bDisplay = format(b, formatOptions);
const aDisplay = memorize("expected", format(a, formatOptions));
const bDisplay = memorize("actual", format(b, formatOptions));
return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options);
}
}
@@ -2092,7 +2104,7 @@ function isReplaceable(obj1, obj2) {
const obj2Type = getType$1(obj2);
return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array");
}
function printDiffOrStringify(received, expected, options) {
function printDiffOrStringify(received, expected, options, memory) {
const { aAnnotation, bAnnotation } = normalizeDiffOptions(options);
if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) {
if (expected.includes("\n") || received.includes("\n")) {
@@ -2109,7 +2121,8 @@ function printDiffOrStringify(received, expected, options) {
const clonedExpected = deepClone(expected, { forceWritable: true });
const clonedReceived = deepClone(received, { forceWritable: true });
const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected);
const difference = diff(replacedExpected, replacedActual, options);
const memorize = memory ? createMemorize(memory) : DEFAULT_MEMORIZE;
const difference = diff(replacedExpected, replacedActual, options, memorize);
return difference;
// }
// const printLabel = getLabelPrinter(aAnnotation, bAnnotation)
@@ -2196,4 +2209,4 @@ function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) {
return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), "");
}
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getDefaultFormatOptions, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
+2 -1
View File
@@ -17,8 +17,9 @@ interface Options {
type LoupeOptions = Partial<Options>;
interface StringifyOptions extends PrettyFormatOptions {
maxLength?: number;
filterNode?: string | ((node: any) => boolean);
}
declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: StringifyOptions): string;
declare function stringify(object: unknown, maxDepth?: number, { maxLength, filterNode, ...options }?: StringifyOptions): string;
declare const formatRegExp: RegExp;
declare function format(...args: unknown[]): string;
declare function browserFormat(...args: unknown[]): string;
+38 -5
View File
@@ -1,4 +1,4 @@
import { plugins, format as format$1 } from '@vitest/pretty-format';
import { plugins, createDOMElementFilter, format as format$1 } from '@vitest/pretty-format';
const ansiColors = {
bold: ['1', '22'],
@@ -583,14 +583,24 @@ const PLUGINS = [
Immutable,
AsymmetricMatcher
];
function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) {
function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
const MAX_LENGTH = maxLength ?? 1e4;
let result;
// Convert string selector to filter function
const filterFn = typeof filterNode === "string" ? createNodeFilterFromSelector(filterNode) : filterNode;
const plugins = filterFn ? [
ReactTestComponent,
ReactElement,
createDOMElementFilter(filterFn),
DOMCollection,
Immutable,
AsymmetricMatcher
] : PLUGINS;
try {
result = format$1(object, {
maxDepth,
escapeString: false,
plugins: PLUGINS,
plugins,
...options
});
} catch {
@@ -598,16 +608,36 @@ function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) {
callToJSON: false,
maxDepth,
escapeString: false,
plugins: PLUGINS,
plugins,
...options
});
}
// Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249
return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
maxLength,
filterNode,
...options
}) : result;
}
function createNodeFilterFromSelector(selector) {
const ELEMENT_NODE = 1;
const COMMENT_NODE = 8;
return (node) => {
// Filter out comments
if (node.nodeType === COMMENT_NODE) {
return false;
}
// Filter out elements matching the selector
if (node.nodeType === ELEMENT_NODE && node.matches) {
try {
return !node.matches(selector);
} catch {
return true;
}
}
return true;
};
}
const formatRegExp = /%[sdjifoOc%]/g;
function baseFormat(args, options = {}) {
const formatArg = (item, inspecOptions) => {
@@ -664,6 +694,9 @@ function baseFormat(args, options = {}) {
if (typeof value === "bigint") {
return `${value.toString()}n`;
}
if (typeof value === "symbol") {
return "NaN";
}
return Number(value).toString();
}
case "%i": {
@@ -697,7 +730,7 @@ function baseFormat(args, options = {}) {
});
for (let x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== "object") {
str += ` ${x}`;
str += ` ${typeof x === "symbol" ? x.toString() : x}`;
} else {
str += ` ${formatArg(x)}`;
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { D as DiffOptions } from './types.d-BCElaP-c.js';
import { TestError } from './types.js';
export { serializeValue as serializeError } from './serialize.js';
import '@vitest/pretty-format';
declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): TestError;
export { processError };
+15 -13
View File
@@ -1,11 +1,10 @@
import { printDiffOrStringify } from './diff.js';
import { stringify } from './display.js';
import { format } from '@vitest/pretty-format';
import { printDiffOrStringify, getDefaultFormatOptions } from './diff.js';
import { serializeValue } from './serialize.js';
import '@vitest/pretty-format';
import 'tinyrainbow';
import './display.js';
import './helpers.js';
import './constants.js';
import './chunk-_commonjsHelpers.js';
function processError(_err, diffOptions, seen = new WeakSet()) {
if (!_err || typeof _err !== "object") {
@@ -13,16 +12,13 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
}
const err = _err;
if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) {
err.diff = printDiffOrStringify(err.actual, err.expected, {
const options = {
...diffOptions,
...err.diffOptions
});
}
if ("expected" in err && typeof err.expected !== "string") {
err.expected = stringify(err.expected, 10);
}
if ("actual" in err && typeof err.actual !== "string") {
err.actual = stringify(err.actual, 10);
};
err.diff = printDiffOrStringify(err.actual, err.expected, options, err);
err.expected = prettifyValue(err.expected, options);
err.actual = prettifyValue(err.actual, options);
}
// some Error implementations may not allow rewriting cause
// in most cases, the assignment will lead to "err.cause = err.cause"
@@ -35,8 +31,14 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
try {
return serializeValue(err);
} catch (e) {
return serializeValue(new Error(`Failed to fully serialize error: ${e === null || e === void 0 ? void 0 : e.message}\nInner error message: ${err === null || err === void 0 ? void 0 : err.message}`));
return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`));
}
}
function prettifyValue(value, options) {
if (typeof value !== "string") {
return format(value, getDefaultFormatOptions(options));
}
return value;
}
export { processError, serializeValue as serializeError };
+8 -1
View File
@@ -23,6 +23,10 @@ declare function assertTypes(value: unknown, name: string, types: string[]): voi
declare function isPrimitive(value: unknown): boolean;
declare function slash(path: string): string;
declare function cleanUrl(url: string): string;
declare function splitFileAndPostfix(path: string): {
file: string;
postfix: string;
};
declare const isExternalUrl: (url: string) => boolean;
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
@@ -35,6 +39,7 @@ declare function wrapId(id: string): string;
*/
declare function unwrapId(id: string): string;
declare function withTrailingSlash(path: string): string;
declare function filterOutComments(s: string): string;
declare function isBareImport(id: string): boolean;
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
declare function isObject(item: unknown): boolean;
@@ -60,6 +65,7 @@ declare function createDefer<T>(): DeferPromise<T>;
*/
declare function getCallLastIndex(code: string): number | null;
declare function isNegativeNaN(val: number): boolean;
declare function ordinal(i: number): string;
/**
* Deep merge :P
*
@@ -68,6 +74,7 @@ declare function isNegativeNaN(val: number): boolean;
* Do not merge types - it is very expensive and usually it's better to case a type here
*/
declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T;
declare function unique<T>(array: T[]): T[];
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId };
export type { DeferPromise };
+50 -1
View File
@@ -66,6 +66,13 @@ const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path) {
const file = cleanUrl(path);
return {
file,
postfix: path.slice(file.length)
};
}
const externalRE = /^(?:[a-z]+:)?\/\//;
const isExternalUrl = (url) => externalRE.test(url);
/**
@@ -88,6 +95,31 @@ function withTrailingSlash(path) {
}
return path;
}
function filterOutComments(s) {
const result = [];
let commentState = "none";
for (let i = 0; i < s.length; ++i) {
if (commentState === "singleline") {
if (s[i] === "\n") {
commentState = "none";
}
} else if (commentState === "multiline") {
if (s[i - 1] === "*" && s[i] === "/") {
commentState = "none";
}
} else if (commentState === "none") {
if (s[i] === "/" && s[i + 1] === "/") {
commentState = "singleline";
} else if (s[i] === "/" && s[i + 1] === "*") {
commentState = "multiline";
i += 2;
} else {
result.push(s[i]);
}
}
}
return result.join("");
}
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
function isBareImport(id) {
return bareImportRE.test(id);
@@ -261,6 +293,20 @@ function isPlainObject(val) {
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
function ordinal(i) {
const j = i % 10;
const k = i % 100;
if (j === 1 && k !== 11) {
return `${i}st`;
}
if (j === 2 && k !== 12) {
return `${i}nd`;
}
if (j === 3 && k !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
/**
* Deep merge :P
*
@@ -291,5 +337,8 @@ function deepMerge(target, ...sources) {
}
return deepMerge(target, ...sources);
}
function unique(array) {
return Array.from(new Set(array));
}
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId };
-9
View File
@@ -1,9 +0,0 @@
import { Colors } from 'tinyrainbow';
interface HighlightOptions {
jsx?: boolean;
colors?: Colors;
}
declare function highlight(code: string, options?: HighlightOptions): string;
export { highlight };
-538
View File
@@ -1,538 +0,0 @@
import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
import c from 'tinyrainbow';
var jsTokens_1;
var hasRequiredJsTokens;
function requireJsTokens () {
if (hasRequiredJsTokens) return jsTokens_1;
hasRequiredJsTokens = 1;
// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
// License: MIT.
var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
jsTokens_1 = function*(input, {jsx = false} = {}) {
var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
({length} = input);
lastIndex = 0;
lastSignificantToken = "";
stack = [
{tag: "JS"}
];
braces = [];
parenNesting = 0;
postfixIncDec = false;
while (lastIndex < length) {
mode = stack[stack.length - 1];
switch (mode.tag) {
case "JS":
case "JSNonExpressionParen":
case "InterpolationInTemplate":
case "InterpolationInJSX":
if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
RegularExpressionLiteral.lastIndex = lastIndex;
if (match = RegularExpressionLiteral.exec(input)) {
lastIndex = RegularExpressionLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "RegularExpressionLiteral",
value: match[0],
closed: match[1] !== void 0 && match[1] !== "\\"
});
continue;
}
}
Punctuator.lastIndex = lastIndex;
if (match = Punctuator.exec(input)) {
punctuator = match[0];
nextLastIndex = Punctuator.lastIndex;
nextLastSignificantToken = punctuator;
switch (punctuator) {
case "(":
if (lastSignificantToken === "?NonExpressionParenKeyword") {
stack.push({
tag: "JSNonExpressionParen",
nesting: parenNesting
});
}
parenNesting++;
postfixIncDec = false;
break;
case ")":
parenNesting--;
postfixIncDec = true;
if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
stack.pop();
nextLastSignificantToken = "?NonExpressionParenEnd";
postfixIncDec = false;
}
break;
case "{":
Punctuator.lastIndex = 0;
isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
braces.push(isExpression);
postfixIncDec = false;
break;
case "}":
switch (mode.tag) {
case "InterpolationInTemplate":
if (braces.length === mode.nesting) {
Template.lastIndex = lastIndex;
match = Template.exec(input);
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
postfixIncDec = false;
yield ({
type: "TemplateMiddle",
value: match[0]
});
} else {
stack.pop();
postfixIncDec = true;
yield ({
type: "TemplateTail",
value: match[0],
closed: match[1] === "`"
});
}
continue;
}
break;
case "InterpolationInJSX":
if (braces.length === mode.nesting) {
stack.pop();
lastIndex += 1;
lastSignificantToken = "}";
yield ({
type: "JSXPunctuator",
value: "}"
});
continue;
}
}
postfixIncDec = braces.pop();
nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
break;
case "]":
postfixIncDec = true;
break;
case "++":
case "--":
nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
break;
case "<":
if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
stack.push({tag: "JSXTag"});
lastIndex += 1;
lastSignificantToken = "<";
yield ({
type: "JSXPunctuator",
value: punctuator
});
continue;
}
postfixIncDec = false;
break;
default:
postfixIncDec = false;
}
lastIndex = nextLastIndex;
lastSignificantToken = nextLastSignificantToken;
yield ({
type: "Punctuator",
value: punctuator
});
continue;
}
Identifier.lastIndex = lastIndex;
if (match = Identifier.exec(input)) {
lastIndex = Identifier.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "for":
case "if":
case "while":
case "with":
if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
nextLastSignificantToken = "?NonExpressionParenKeyword";
}
}
lastSignificantToken = nextLastSignificantToken;
postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
yield ({
type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
value: match[0]
});
continue;
}
StringLiteral.lastIndex = lastIndex;
if (match = StringLiteral.exec(input)) {
lastIndex = StringLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "StringLiteral",
value: match[0],
closed: match[2] !== void 0
});
continue;
}
NumericLiteral.lastIndex = lastIndex;
if (match = NumericLiteral.exec(input)) {
lastIndex = NumericLiteral.lastIndex;
lastSignificantToken = match[0];
postfixIncDec = true;
yield ({
type: "NumericLiteral",
value: match[0]
});
continue;
}
Template.lastIndex = lastIndex;
if (match = Template.exec(input)) {
lastIndex = Template.lastIndex;
lastSignificantToken = match[0];
if (match[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
stack.push({
tag: "InterpolationInTemplate",
nesting: braces.length
});
postfixIncDec = false;
yield ({
type: "TemplateHead",
value: match[0]
});
} else {
postfixIncDec = true;
yield ({
type: "NoSubstitutionTemplate",
value: match[0],
closed: match[1] === "`"
});
}
continue;
}
break;
case "JSXTag":
case "JSXTagEnd":
JSXPunctuator.lastIndex = lastIndex;
if (match = JSXPunctuator.exec(input)) {
lastIndex = JSXPunctuator.lastIndex;
nextLastSignificantToken = match[0];
switch (match[0]) {
case "<":
stack.push({tag: "JSXTag"});
break;
case ">":
stack.pop();
if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
nextLastSignificantToken = "?JSX";
postfixIncDec = true;
} else {
stack.push({tag: "JSXChildren"});
}
break;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
nextLastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
break;
case "/":
if (lastSignificantToken === "<") {
stack.pop();
if (stack[stack.length - 1].tag === "JSXChildren") {
stack.pop();
}
stack.push({tag: "JSXTagEnd"});
}
}
lastSignificantToken = nextLastSignificantToken;
yield ({
type: "JSXPunctuator",
value: match[0]
});
continue;
}
JSXIdentifier.lastIndex = lastIndex;
if (match = JSXIdentifier.exec(input)) {
lastIndex = JSXIdentifier.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXIdentifier",
value: match[0]
});
continue;
}
JSXString.lastIndex = lastIndex;
if (match = JSXString.exec(input)) {
lastIndex = JSXString.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXString",
value: match[0],
closed: match[2] !== void 0
});
continue;
}
break;
case "JSXChildren":
JSXText.lastIndex = lastIndex;
if (match = JSXText.exec(input)) {
lastIndex = JSXText.lastIndex;
lastSignificantToken = match[0];
yield ({
type: "JSXText",
value: match[0]
});
continue;
}
switch (input[lastIndex]) {
case "<":
stack.push({tag: "JSXTag"});
lastIndex++;
lastSignificantToken = "<";
yield ({
type: "JSXPunctuator",
value: "<"
});
continue;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces.length
});
lastIndex++;
lastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
yield ({
type: "JSXPunctuator",
value: "{"
});
continue;
}
}
WhiteSpace.lastIndex = lastIndex;
if (match = WhiteSpace.exec(input)) {
lastIndex = WhiteSpace.lastIndex;
yield ({
type: "WhiteSpace",
value: match[0]
});
continue;
}
LineTerminatorSequence.lastIndex = lastIndex;
if (match = LineTerminatorSequence.exec(input)) {
lastIndex = LineTerminatorSequence.lastIndex;
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
yield ({
type: "LineTerminatorSequence",
value: match[0]
});
continue;
}
MultiLineComment.lastIndex = lastIndex;
if (match = MultiLineComment.exec(input)) {
lastIndex = MultiLineComment.lastIndex;
if (Newline.test(match[0])) {
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
}
yield ({
type: "MultiLineComment",
value: match[0],
closed: match[1] !== void 0
});
continue;
}
SingleLineComment.lastIndex = lastIndex;
if (match = SingleLineComment.exec(input)) {
lastIndex = SingleLineComment.lastIndex;
postfixIncDec = false;
yield ({
type: "SingleLineComment",
value: match[0]
});
continue;
}
firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
lastIndex += firstCodePoint.length;
lastSignificantToken = firstCodePoint;
postfixIncDec = false;
yield ({
type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
value: firstCodePoint
});
}
return void 0;
};
return jsTokens_1;
}
var jsTokensExports = /*@__PURE__*/ requireJsTokens();
var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokensExports);
// src/index.ts
var reservedWords = {
keyword: [
"break",
"case",
"catch",
"continue",
"debugger",
"default",
"do",
"else",
"finally",
"for",
"function",
"if",
"return",
"switch",
"throw",
"try",
"var",
"const",
"while",
"with",
"new",
"this",
"super",
"class",
"extends",
"export",
"import",
"null",
"true",
"false",
"in",
"instanceof",
"typeof",
"void",
"delete"
],
strict: [
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
"yield"
]
}, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
function isReservedWord(word) {
return word === "await" || word === "enum";
}
function isStrictReservedWord(word) {
return isReservedWord(word) || reservedWordsStrictSet.has(word);
}
function isKeyword(word) {
return keywords.has(word);
}
var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) {
if (token.type === "IdentifierName") {
if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value))
return "Keyword";
if (token.value[0] && token.value[0] !== token.value[0].toLowerCase())
return "IdentifierCapitalized";
}
return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type;
};
function getCallableType(token) {
if (token.type === "IdentifierName")
return "IdentifierCallable";
if (token.type === "PrivateIdentifier")
return "PrivateIdentifierCallable";
throw new Error("Not a callable token");
}
var colorize = (defs, type, value) => {
let colorize2 = defs[type];
return colorize2 ? colorize2(value) : value;
}, highlightTokens = (defs, text, jsx) => {
let highlighted = "", lastPotentialCallable = null, stackedHighlight = "";
for (let token of jsTokens(text, { jsx })) {
let type = getTokenType(token);
if (type === "IdentifierName" || type === "PrivateIdentifier") {
lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token;
continue;
}
if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) {
stackedHighlight += colorize(defs, type, token.value);
continue;
}
if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) {
let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable);
highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null;
}
highlighted += colorize(defs, type, token.value);
}
return highlighted;
};
function highlight$1(code, options = { jsx: false, colors: {} }) {
return code && highlightTokens(options.colors || {}, code, options.jsx);
}
function getDefs(c) {
const Invalid = (text) => c.white(c.bgRed(c.bold(text)));
return {
Keyword: c.magenta,
IdentifierCapitalized: c.yellow,
Punctuator: c.yellow,
StringLiteral: c.green,
NoSubstitutionTemplate: c.green,
MultiLineComment: c.gray,
SingleLineComment: c.gray,
RegularExpressionLiteral: c.cyan,
NumericLiteral: c.blue,
TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)),
TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)),
TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)),
IdentifierCallable: c.blue,
PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`,
Invalid,
JSXString: c.green,
JSXIdentifier: c.yellow,
JSXInvalid: Invalid,
JSXPunctuator: c.yellow
};
}
function highlight(code, options = { jsx: false }) {
return highlight$1(code, {
jsx: options.jsx,
colors: getDefs(options.colors || c)
});
}
export { highlight };
+1 -2
View File
@@ -5,13 +5,12 @@ 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()) {
if (tryStatSync(pkgPath)?.isFile()) {
const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
if (packageCache) {
setCacheData(packageCache, pkgData, basedir, originalBasedir);
+6 -6
View File
@@ -22,16 +22,16 @@ function serializeValue(val, seen = new WeakMap()) {
const jsonValue = val.toJSON();
if (jsonValue && jsonValue !== val && typeof jsonValue === "object") {
if (typeof val.message === "string") {
safe(() => jsonValue.message ?? (jsonValue.message = normalizeErrorMessage(val.message)));
safe(() => jsonValue.message ??= normalizeErrorMessage(val.message));
}
if (typeof val.stack === "string") {
safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack));
safe(() => jsonValue.stack ??= val.stack);
}
if (typeof val.name === "string") {
safe(() => jsonValue.name ?? (jsonValue.name = val.name));
safe(() => jsonValue.name ??= val.name);
}
if (val.cause != null) {
safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen)));
safe(() => jsonValue.cause ??= serializeValue(val.cause, seen));
}
}
return serializeValue(jsonValue, seen);
@@ -101,7 +101,7 @@ function serializeValue(val, seen = new WeakMap()) {
obj = Object.getPrototypeOf(obj);
}
if (val instanceof Error) {
safe(() => val.message = normalizeErrorMessage(val.message));
safe(() => clone.message = normalizeErrorMessage(val.message));
}
return clone;
}
@@ -112,7 +112,7 @@ function safe(fn) {
} catch {}
}
function normalizeErrorMessage(message) {
return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
return message.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/getByTestId('__vitest_\d+__')/g, "page");
}
export { serializeValue };
+15 -5
View File
@@ -233,8 +233,11 @@ const stackIgnorePatterns = [
/node:\w+/,
/__vitest_test__/,
/__vitest_browser__/,
"/@id/__x00__vitest/browser",
/\/deps\/vitest_/
];
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (!urlLike.includes(":")) {
@@ -259,6 +262,9 @@ function extractLocation(urlLike) {
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows ? 5 : 4);
}
if (url.includes("vitest=")) {
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
}
return [
url,
parts[2] || undefined,
@@ -352,7 +358,7 @@ function parseSingleV8Stack(raw) {
// normalize Windows path (\ -> /)
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
if (method) {
method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
}
return {
method,
@@ -372,13 +378,17 @@ function createStackString(stacks) {
}
function parseStacktrace(stack, options = {}) {
const { ignoreStackEntries = stackIgnorePatterns } = options;
const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
// remove vi.defineHelper's internal stacks
const helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__"));
if (helperIndex >= 0) {
stacks = stacks.slice(helperIndex + 1);
}
return stacks.map((stack) => {
var _options$getSourceMap;
if (options.getUrlId) {
stack.file = options.getUrlId(stack.file);
}
const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file);
const map = options.getSourceMap?.(stack.file);
if (!map || typeof map !== "object" || !map.version) {
return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
}
@@ -457,7 +467,7 @@ class DecodedMap {
this._encoded = mappings || "";
this._decodedMemo = memoizedState();
this.url = from;
this.resolvedSources = (sources || []).map((s) => resolve(s || "", from));
this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || ""));
}
}
function memoizedState() {
+6
View File
@@ -0,0 +1,6 @@
interface ExtractedSourceMap {
map: any;
}
declare function extractSourcemapFromFile(code: string, filePath: string): ExtractedSourceMap | undefined;
export { extractSourcemapFromFile };
+23
View File
@@ -0,0 +1,23 @@
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import convertSourceMap from 'convert-source-map';
// based on vite
// https://github.com/vitejs/vite/blob/84079a84ad94de4c1ef4f1bdb2ab448ff2c01196/packages/vite/src/node/server/sourcemap.ts#L149
function extractSourcemapFromFile(code, filePath) {
const map = (convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
return map ? { map } : undefined;
}
function createConvertSourceMapReadMap(originalFileName) {
return (filename) => {
// convertSourceMap can detect invalid filename from comments.
// fallback to empty source map to avoid errors.
const targetPath = path.resolve(path.dirname(originalFileName), filename);
if (existsSync(targetPath)) {
return readFileSync(targetPath, "utf-8");
}
return "{}";
};
}
export { extractSourcemapFromFile };