@vitest/utils 4.0.0-beta.1 → 4.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/error.d.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import { D as DiffOptions } from './types.d-BCElaP-c.js';
2
+ export { serializeValue as serializeError } from './serialize.js';
2
3
  import '@vitest/pretty-format';
3
4
 
4
- // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
5
- declare function serializeValue(val: any, seen?: WeakMap<WeakKey, any>): any;
6
-
7
5
  declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
8
6
 
9
- export { processError, serializeValue as serializeError, serializeValue };
7
+ export { processError };
package/dist/error.js CHANGED
@@ -1,126 +1,12 @@
1
1
  import { printDiffOrStringify } from './diff.js';
2
- import { f as format, s as stringify } from './chunk-_commonjsHelpers.js';
2
+ import { stringify } from './display.js';
3
+ import { serializeValue } from './serialize.js';
3
4
  import '@vitest/pretty-format';
4
5
  import 'tinyrainbow';
5
6
  import './helpers.js';
6
- import 'loupe';
7
+ import './constants.js';
8
+ import './chunk-_commonjsHelpers.js';
7
9
 
8
- const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@";
9
- const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@";
10
- function isImmutable(v) {
11
- return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]);
12
- }
13
- const OBJECT_PROTO = Object.getPrototypeOf({});
14
- function getUnserializableMessage(err) {
15
- if (err instanceof Error) {
16
- return `<unserializable>: ${err.message}`;
17
- }
18
- if (typeof err === "string") {
19
- return `<unserializable>: ${err}`;
20
- }
21
- return "<unserializable>";
22
- }
23
- // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
24
- function serializeValue(val, seen = new WeakMap()) {
25
- if (!val || typeof val === "string") {
26
- return val;
27
- }
28
- if (val instanceof Error && "toJSON" in val && typeof val.toJSON === "function") {
29
- const jsonValue = val.toJSON();
30
- if (jsonValue && jsonValue !== val && typeof jsonValue === "object") {
31
- if (typeof val.message === "string") {
32
- safe(() => jsonValue.message ?? (jsonValue.message = val.message));
33
- }
34
- if (typeof val.stack === "string") {
35
- safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack));
36
- }
37
- if (typeof val.name === "string") {
38
- safe(() => jsonValue.name ?? (jsonValue.name = val.name));
39
- }
40
- if (val.cause != null) {
41
- safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen)));
42
- }
43
- }
44
- return serializeValue(jsonValue, seen);
45
- }
46
- if (typeof val === "function") {
47
- return `Function<${val.name || "anonymous"}>`;
48
- }
49
- if (typeof val === "symbol") {
50
- return val.toString();
51
- }
52
- if (typeof val !== "object") {
53
- return val;
54
- }
55
- if (typeof Buffer !== "undefined" && val instanceof Buffer) {
56
- return `<Buffer(${val.length}) ...>`;
57
- }
58
- if (typeof Uint8Array !== "undefined" && val instanceof Uint8Array) {
59
- return `<Uint8Array(${val.length}) ...>`;
60
- }
61
- // cannot serialize immutables as immutables
62
- if (isImmutable(val)) {
63
- return serializeValue(val.toJSON(), seen);
64
- }
65
- if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") {
66
- return "Promise";
67
- }
68
- if (typeof Element !== "undefined" && val instanceof Element) {
69
- return val.tagName;
70
- }
71
- if (typeof val.asymmetricMatch === "function") {
72
- return `${val.toString()} ${format(val.sample)}`;
73
- }
74
- if (typeof val.toJSON === "function") {
75
- return serializeValue(val.toJSON(), seen);
76
- }
77
- if (seen.has(val)) {
78
- return seen.get(val);
79
- }
80
- if (Array.isArray(val)) {
81
- // eslint-disable-next-line unicorn/no-new-array -- we need to keep sparse arrays ([1,,3])
82
- const clone = new Array(val.length);
83
- seen.set(val, clone);
84
- val.forEach((e, i) => {
85
- try {
86
- clone[i] = serializeValue(e, seen);
87
- } catch (err) {
88
- clone[i] = getUnserializableMessage(err);
89
- }
90
- });
91
- return clone;
92
- } else {
93
- // Objects with `Error` constructors appear to cause problems during worker communication
94
- // using `MessagePort`, so the serialized error object is being recreated as plain object.
95
- const clone = Object.create(null);
96
- seen.set(val, clone);
97
- let obj = val;
98
- while (obj && obj !== OBJECT_PROTO) {
99
- Object.getOwnPropertyNames(obj).forEach((key) => {
100
- if (key in clone) {
101
- return;
102
- }
103
- try {
104
- clone[key] = serializeValue(val[key], seen);
105
- } catch (err) {
106
- // delete in case it has a setter from prototype that might throw
107
- delete clone[key];
108
- clone[key] = getUnserializableMessage(err);
109
- }
110
- });
111
- obj = Object.getPrototypeOf(obj);
112
- }
113
- return clone;
114
- }
115
- }
116
- function safe(fn) {
117
- try {
118
- return fn();
119
- } catch {}
120
- }
121
- function normalizeErrorMessage(message) {
122
- return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
123
- }
124
10
  function processError(_err, diffOptions, seen = new WeakSet()) {
125
11
  if (!_err || typeof _err !== "object") {
126
12
  return { message: String(_err) };
@@ -138,12 +24,6 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
138
24
  if ("actual" in err && typeof err.actual !== "string") {
139
25
  err.actual = stringify(err.actual, 10);
140
26
  }
141
- // some Error implementations don't allow rewriting message
142
- try {
143
- if (typeof err.message === "string") {
144
- err.message = normalizeErrorMessage(err.message);
145
- }
146
- } catch {}
147
27
  // some Error implementations may not allow rewriting cause
148
28
  // in most cases, the assignment will lead to "err.cause = err.cause"
149
29
  try {
@@ -159,4 +39,4 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
159
39
  }
160
40
  }
161
41
 
162
- export { processError, serializeValue as serializeError, serializeValue };
42
+ export { processError, serializeValue as serializeError };
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import { Nullable, Arrayable } from './types.js';
2
2
 
3
+ declare function nanoid(size?: number): string;
4
+
5
+ declare function shuffle<T>(array: T[], seed?: number): T[];
6
+
3
7
  interface CloneOptions {
4
8
  forceWritable?: boolean;
5
9
  }
@@ -7,6 +11,7 @@ interface ErrorOptions {
7
11
  message?: string;
8
12
  stackTraceLimit?: number;
9
13
  }
14
+
10
15
  /**
11
16
  * Get original stacktrace without source map support the most performant way.
12
17
  * - Create only 1 stack frame.
@@ -17,8 +22,20 @@ declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
17
22
  declare function assertTypes(value: unknown, name: string, types: string[]): void;
18
23
  declare function isPrimitive(value: unknown): boolean;
19
24
  declare function slash(path: string): string;
20
- // convert RegExp.toString to RegExp
21
- declare function parseRegexp(input: string): RegExp;
25
+ declare function cleanUrl(url: string): string;
26
+ declare const isExternalUrl: (url: string) => boolean;
27
+ /**
28
+ * Prepend `/@id/` and replace null byte so the id is URL-safe.
29
+ * This is prepended to resolved ids that are not valid browser
30
+ * import specifiers by the importAnalysis plugin.
31
+ */
32
+ declare function wrapId(id: string): string;
33
+ /**
34
+ * Undo {@link wrapId}'s `/@id/` and null byte replacements.
35
+ */
36
+ declare function unwrapId(id: string): string;
37
+ declare function withTrailingSlash(path: string): string;
38
+ declare function isBareImport(id: string): boolean;
22
39
  declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
23
40
  declare function isObject(item: unknown): boolean;
24
41
  declare function getType(value: unknown): string;
@@ -28,8 +45,8 @@ declare function clone<T>(val: T, seen: WeakMap<any, any>, options?: CloneOption
28
45
  declare function noop(): void;
29
46
  declare function objectAttr(source: any, path: string, defaultValue?: undefined): any;
30
47
  type DeferPromise<T> = Promise<T> & {
31
- resolve: (value: T | PromiseLike<T>) => void
32
- reject: (reason?: any) => void
48
+ resolve: (value: T | PromiseLike<T>) => void;
49
+ reject: (reason?: any) => void;
33
50
  };
34
51
  declare function createDefer<T>(): DeferPromise<T>;
35
52
  /**
@@ -52,5 +69,5 @@ declare function isNegativeNaN(val: number): boolean;
52
69
  */
53
70
  declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T;
54
71
 
55
- export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray };
72
+ 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 };
56
73
  export type { DeferPromise };
package/dist/helpers.js CHANGED
@@ -1,3 +1,34 @@
1
+ import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js';
2
+
3
+ // port from nanoid
4
+ // https://github.com/ai/nanoid
5
+ const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
6
+ function nanoid(size = 21) {
7
+ let id = "";
8
+ let i = size;
9
+ while (i--) {
10
+ id += urlAlphabet[Math.random() * 64 | 0];
11
+ }
12
+ return id;
13
+ }
14
+
15
+ const RealDate = Date;
16
+ function random(seed) {
17
+ const x = Math.sin(seed++) * 1e4;
18
+ return x - Math.floor(x);
19
+ }
20
+ function shuffle(array, seed = RealDate.now()) {
21
+ let length = array.length;
22
+ while (length) {
23
+ const index = Math.floor(random(seed) * length--);
24
+ const previous = array[length];
25
+ array[length] = array[index];
26
+ array[index] = previous;
27
+ ++seed;
28
+ }
29
+ return array;
30
+ }
31
+
1
32
  /**
2
33
  * Get original stacktrace without source map support the most performant way.
3
34
  * - Create only 1 stack frame.
@@ -31,22 +62,35 @@ function isPrimitive(value) {
31
62
  function slash(path) {
32
63
  return path.replace(/\\/g, "/");
33
64
  }
34
- // convert RegExp.toString to RegExp
35
- function parseRegexp(input) {
36
- // Parse input
37
- // eslint-disable-next-line regexp/no-misleading-capturing-group
38
- const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
39
- // match nothing
40
- if (!m) {
41
- return /$^/;
42
- }
43
- // Invalid flags
44
- // eslint-disable-next-line regexp/optimal-quantifier-concatenation
45
- if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
46
- return new RegExp(input);
65
+ const postfixRE = /[?#].*$/;
66
+ function cleanUrl(url) {
67
+ return url.replace(postfixRE, "");
68
+ }
69
+ const externalRE = /^(?:[a-z]+:)?\/\//;
70
+ const isExternalUrl = (url) => externalRE.test(url);
71
+ /**
72
+ * Prepend `/@id/` and replace null byte so the id is URL-safe.
73
+ * This is prepended to resolved ids that are not valid browser
74
+ * import specifiers by the importAnalysis plugin.
75
+ */
76
+ function wrapId(id) {
77
+ return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
78
+ }
79
+ /**
80
+ * Undo {@link wrapId}'s `/@id/` and null byte replacements.
81
+ */
82
+ function unwrapId(id) {
83
+ return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
84
+ }
85
+ function withTrailingSlash(path) {
86
+ if (path.at(-1) !== "/") {
87
+ return `${path}/`;
47
88
  }
48
- // Create the regular expression
49
- return new RegExp(m[2], m[3]);
89
+ return path;
90
+ }
91
+ const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
92
+ function isBareImport(id) {
93
+ return bareImportRE.test(id);
50
94
  }
51
95
  function toArray(array) {
52
96
  if (array === null || array === undefined) {
@@ -248,4 +292,4 @@ function deepMerge(target, ...sources) {
248
292
  return deepMerge(target, ...sources);
249
293
  }
250
294
 
251
- export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray };
295
+ 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 };
@@ -0,0 +1,9 @@
1
+ import { Colors } from 'tinyrainbow';
2
+
3
+ interface HighlightOptions {
4
+ jsx?: boolean;
5
+ colors?: Colors;
6
+ }
7
+ declare function highlight(code: string, options?: HighlightOptions): string;
8
+
9
+ export { highlight };