@vitest/utils 4.0.0-beta.10 → 4.0.0-beta.12

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.
@@ -0,0 +1,18 @@
1
+ interface SafeTimers {
2
+ nextTick?: (cb: () => void) => void;
3
+ setImmediate?: {
4
+ <TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): any;
5
+ __promisify__: <T = void>(value?: T, options?: any) => Promise<T>;
6
+ };
7
+ clearImmediate?: (immediateId: any) => void;
8
+ setTimeout: typeof setTimeout;
9
+ setInterval: typeof setInterval;
10
+ clearInterval: typeof clearInterval;
11
+ clearTimeout: typeof clearTimeout;
12
+ queueMicrotask: typeof queueMicrotask;
13
+ }
14
+ declare function getSafeTimers(): SafeTimers;
15
+ declare function setSafeTimers(): void;
16
+
17
+ export { getSafeTimers, setSafeTimers };
18
+ export type { SafeTimers };
package/dist/timers.js ADDED
@@ -0,0 +1,32 @@
1
+ const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS");
2
+ function getSafeTimers() {
3
+ const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis;
4
+ const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {};
5
+ return {
6
+ nextTick: safeNextTick,
7
+ setTimeout: safeSetTimeout,
8
+ setInterval: safeSetInterval,
9
+ clearInterval: safeClearInterval,
10
+ clearTimeout: safeClearTimeout,
11
+ setImmediate: safeSetImmediate,
12
+ clearImmediate: safeClearImmediate,
13
+ queueMicrotask: safeQueueMicrotask
14
+ };
15
+ }
16
+ function setSafeTimers() {
17
+ const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis;
18
+ const { nextTick: safeNextTick } = globalThis.process || {};
19
+ const timers = {
20
+ nextTick: safeNextTick,
21
+ setTimeout: safeSetTimeout,
22
+ setInterval: safeSetInterval,
23
+ clearInterval: safeClearInterval,
24
+ clearTimeout: safeClearTimeout,
25
+ setImmediate: safeSetImmediate,
26
+ clearImmediate: safeClearImmediate,
27
+ queueMicrotask: safeQueueMicrotask
28
+ };
29
+ globalThis[SAFE_TIMERS_SYMBOL] = timers;
30
+ }
31
+
32
+ export { getSafeTimers, setSafeTimers };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/utils",
3
3
  "type": "module",
4
- "version": "4.0.0-beta.10",
4
+ "version": "4.0.0-beta.12",
5
5
  "description": "Shared Vitest utility functions",
6
6
  "license": "MIT",
7
7
  "funding": "https://opencollective.com/vitest",
@@ -36,10 +36,34 @@
36
36
  "types": "./dist/helpers.d.ts",
37
37
  "default": "./dist/helpers.js"
38
38
  },
39
+ "./offset": {
40
+ "types": "./dist/offset.d.ts",
41
+ "default": "./dist/offset.js"
42
+ },
43
+ "./constants": {
44
+ "types": "./dist/constants.d.ts",
45
+ "default": "./dist/constants.js"
46
+ },
47
+ "./timers": {
48
+ "types": "./dist/timers.d.ts",
49
+ "default": "./dist/timers.js"
50
+ },
51
+ "./display": {
52
+ "types": "./dist/display.d.ts",
53
+ "default": "./dist/display.js"
54
+ },
55
+ "./highlight": {
56
+ "types": "./dist/highlight.d.ts",
57
+ "default": "./dist/highlight.js"
58
+ },
39
59
  "./source-map": {
40
60
  "types": "./dist/source-map.d.ts",
41
61
  "default": "./dist/source-map.js"
42
62
  },
63
+ "./serialize": {
64
+ "types": "./dist/serialize.d.ts",
65
+ "default": "./dist/serialize.js"
66
+ },
43
67
  "./*": "./*"
44
68
  },
45
69
  "main": "./dist/index.js",
@@ -57,18 +81,18 @@
57
81
  "dist"
58
82
  ],
59
83
  "dependencies": {
60
- "loupe": "^3.2.1",
61
- "tinyrainbow": "^2.0.0",
62
- "@vitest/pretty-format": "4.0.0-beta.10"
84
+ "tinyrainbow": "^3.0.3",
85
+ "@vitest/pretty-format": "4.0.0-beta.12"
63
86
  },
64
87
  "devDependencies": {
65
- "@jridgewell/trace-mapping": "^0.3.30",
88
+ "@jridgewell/trace-mapping": "0.3.31",
66
89
  "@types/estree": "^1.0.8",
67
90
  "diff-sequences": "^29.6.3",
91
+ "loupe": "^3.2.1",
68
92
  "tinyhighlight": "^0.3.2"
69
93
  },
70
94
  "scripts": {
71
- "build": "rimraf dist && rollup -c",
95
+ "build": "premove dist && rollup -c",
72
96
  "dev": "rollup -c --watch"
73
97
  }
74
98
  }
@@ -1,329 +0,0 @@
1
- // TODO: this is all copy pasted from Vite - can they expose a module that exports only constants?
2
- const KNOWN_ASSET_TYPES = [
3
- "apng",
4
- "bmp",
5
- "png",
6
- "jpe?g",
7
- "jfif",
8
- "pjpeg",
9
- "pjp",
10
- "gif",
11
- "svg",
12
- "ico",
13
- "webp",
14
- "avif",
15
- "mp4",
16
- "webm",
17
- "ogg",
18
- "mp3",
19
- "wav",
20
- "flac",
21
- "aac",
22
- "woff2?",
23
- "eot",
24
- "ttf",
25
- "otf",
26
- "webmanifest",
27
- "pdf",
28
- "txt"
29
- ];
30
- const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
31
- const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
32
- /**
33
- * Prefix for resolved Ids that are not valid browser import specifiers
34
- */
35
- const VALID_ID_PREFIX = `/@id/`;
36
- /**
37
- * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
38
- * module ID with `\0`, a convention from the rollup ecosystem.
39
- * This prevents other plugins from trying to process the id (like node resolution),
40
- * and core features like sourcemaps can use this info to differentiate between
41
- * virtual modules and regular files.
42
- * `\0` is not a permitted char in import URLs so we have to replace them during
43
- * import analysis. The id will be decoded back before entering the plugins pipeline.
44
- * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
45
- * modules in the browser end up encoded as `/@id/__x00__{id}`
46
- */
47
- const NULL_BYTE_PLACEHOLDER = `__x00__`;
48
-
49
- /**
50
- * Get original stacktrace without source map support the most performant way.
51
- * - Create only 1 stack frame.
52
- * - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
53
- */
54
- function createSimpleStackTrace(options) {
55
- const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
56
- const limit = Error.stackTraceLimit;
57
- const prepareStackTrace = Error.prepareStackTrace;
58
- Error.stackTraceLimit = stackTraceLimit;
59
- Error.prepareStackTrace = (e) => e.stack;
60
- const err = new Error(message);
61
- const stackTrace = err.stack || "";
62
- Error.prepareStackTrace = prepareStackTrace;
63
- Error.stackTraceLimit = limit;
64
- return stackTrace;
65
- }
66
- function notNullish(v) {
67
- return v != null;
68
- }
69
- function assertTypes(value, name, types) {
70
- const receivedType = typeof value;
71
- const pass = types.includes(receivedType);
72
- if (!pass) {
73
- throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
74
- }
75
- }
76
- function isPrimitive(value) {
77
- return value === null || typeof value !== "function" && typeof value !== "object";
78
- }
79
- function slash(path) {
80
- return path.replace(/\\/g, "/");
81
- }
82
- const postfixRE = /[?#].*$/;
83
- function cleanUrl(url) {
84
- return url.replace(postfixRE, "");
85
- }
86
- const externalRE = /^(?:[a-z]+:)?\/\//;
87
- const isExternalUrl = (url) => externalRE.test(url);
88
- /**
89
- * Prepend `/@id/` and replace null byte so the id is URL-safe.
90
- * This is prepended to resolved ids that are not valid browser
91
- * import specifiers by the importAnalysis plugin.
92
- */
93
- function wrapId(id) {
94
- return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
95
- }
96
- /**
97
- * Undo {@link wrapId}'s `/@id/` and null byte replacements.
98
- */
99
- function unwrapId(id) {
100
- return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
101
- }
102
- function withTrailingSlash(path) {
103
- if (path.at(-1) !== "/") {
104
- return `${path}/`;
105
- }
106
- return path;
107
- }
108
- const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
109
- function isBareImport(id) {
110
- return bareImportRE.test(id);
111
- }
112
- // convert RegExp.toString to RegExp
113
- function parseRegexp(input) {
114
- // Parse input
115
- // eslint-disable-next-line regexp/no-misleading-capturing-group
116
- const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
117
- // match nothing
118
- if (!m) {
119
- return /$^/;
120
- }
121
- // Invalid flags
122
- // eslint-disable-next-line regexp/optimal-quantifier-concatenation
123
- if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
124
- return new RegExp(input);
125
- }
126
- // Create the regular expression
127
- return new RegExp(m[2], m[3]);
128
- }
129
- function toArray(array) {
130
- if (array === null || array === undefined) {
131
- array = [];
132
- }
133
- if (Array.isArray(array)) {
134
- return array;
135
- }
136
- return [array];
137
- }
138
- function isObject(item) {
139
- return item != null && typeof item === "object" && !Array.isArray(item);
140
- }
141
- function isFinalObj(obj) {
142
- return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
143
- }
144
- function getType(value) {
145
- return Object.prototype.toString.apply(value).slice(8, -1);
146
- }
147
- function collectOwnProperties(obj, collector) {
148
- const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
149
- Object.getOwnPropertyNames(obj).forEach(collect);
150
- Object.getOwnPropertySymbols(obj).forEach(collect);
151
- }
152
- function getOwnProperties(obj) {
153
- const ownProps = new Set();
154
- if (isFinalObj(obj)) {
155
- return [];
156
- }
157
- collectOwnProperties(obj, ownProps);
158
- return Array.from(ownProps);
159
- }
160
- const defaultCloneOptions = { forceWritable: false };
161
- function deepClone(val, options = defaultCloneOptions) {
162
- const seen = new WeakMap();
163
- return clone(val, seen, options);
164
- }
165
- function clone(val, seen, options = defaultCloneOptions) {
166
- let k, out;
167
- if (seen.has(val)) {
168
- return seen.get(val);
169
- }
170
- if (Array.isArray(val)) {
171
- out = Array.from({ length: k = val.length });
172
- seen.set(val, out);
173
- while (k--) {
174
- out[k] = clone(val[k], seen, options);
175
- }
176
- return out;
177
- }
178
- if (Object.prototype.toString.call(val) === "[object Object]") {
179
- out = Object.create(Object.getPrototypeOf(val));
180
- seen.set(val, out);
181
- // we don't need properties from prototype
182
- const props = getOwnProperties(val);
183
- for (const k of props) {
184
- const descriptor = Object.getOwnPropertyDescriptor(val, k);
185
- if (!descriptor) {
186
- continue;
187
- }
188
- const cloned = clone(val[k], seen, options);
189
- if (options.forceWritable) {
190
- Object.defineProperty(out, k, {
191
- enumerable: descriptor.enumerable,
192
- configurable: true,
193
- writable: true,
194
- value: cloned
195
- });
196
- } else if ("get" in descriptor) {
197
- Object.defineProperty(out, k, {
198
- ...descriptor,
199
- get() {
200
- return cloned;
201
- }
202
- });
203
- } else {
204
- Object.defineProperty(out, k, {
205
- ...descriptor,
206
- value: cloned
207
- });
208
- }
209
- }
210
- return out;
211
- }
212
- return val;
213
- }
214
- function noop() {}
215
- function objectAttr(source, path, defaultValue = undefined) {
216
- // a[3].b -> a.3.b
217
- const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
218
- let result = source;
219
- for (const p of paths) {
220
- result = new Object(result)[p];
221
- if (result === undefined) {
222
- return defaultValue;
223
- }
224
- }
225
- return result;
226
- }
227
- function createDefer() {
228
- let resolve = null;
229
- let reject = null;
230
- const p = new Promise((_resolve, _reject) => {
231
- resolve = _resolve;
232
- reject = _reject;
233
- });
234
- p.resolve = resolve;
235
- p.reject = reject;
236
- return p;
237
- }
238
- /**
239
- * If code starts with a function call, will return its last index, respecting arguments.
240
- * This will return 25 - last ending character of toMatch ")"
241
- * Also works with callbacks
242
- * ```
243
- * toMatch({ test: '123' });
244
- * toBeAliased('123')
245
- * ```
246
- */
247
- function getCallLastIndex(code) {
248
- let charIndex = -1;
249
- let inString = null;
250
- let startedBracers = 0;
251
- let endedBracers = 0;
252
- let beforeChar = null;
253
- while (charIndex <= code.length) {
254
- beforeChar = code[charIndex];
255
- charIndex++;
256
- const char = code[charIndex];
257
- const isCharString = char === "\"" || char === "'" || char === "`";
258
- if (isCharString && beforeChar !== "\\") {
259
- if (inString === char) {
260
- inString = null;
261
- } else if (!inString) {
262
- inString = char;
263
- }
264
- }
265
- if (!inString) {
266
- if (char === "(") {
267
- startedBracers++;
268
- }
269
- if (char === ")") {
270
- endedBracers++;
271
- }
272
- }
273
- if (startedBracers && endedBracers && startedBracers === endedBracers) {
274
- return charIndex;
275
- }
276
- }
277
- return null;
278
- }
279
- function isNegativeNaN(val) {
280
- if (!Number.isNaN(val)) {
281
- return false;
282
- }
283
- const f64 = new Float64Array(1);
284
- f64[0] = val;
285
- const u32 = new Uint32Array(f64.buffer);
286
- const isNegative = u32[1] >>> 31 === 1;
287
- return isNegative;
288
- }
289
- function toString(v) {
290
- return Object.prototype.toString.call(v);
291
- }
292
- function isPlainObject(val) {
293
- return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
294
- }
295
- function isMergeableObject(item) {
296
- return isPlainObject(item) && !Array.isArray(item);
297
- }
298
- /**
299
- * Deep merge :P
300
- *
301
- * Will merge objects only if they are plain
302
- *
303
- * Do not merge types - it is very expensive and usually it's better to case a type here
304
- */
305
- function deepMerge(target, ...sources) {
306
- if (!sources.length) {
307
- return target;
308
- }
309
- const source = sources.shift();
310
- if (source === undefined) {
311
- return target;
312
- }
313
- if (isMergeableObject(target) && isMergeableObject(source)) {
314
- Object.keys(source).forEach((key) => {
315
- const _source = source;
316
- if (isMergeableObject(_source[key])) {
317
- if (!target[key]) {
318
- target[key] = {};
319
- }
320
- deepMerge(target[key], _source[key]);
321
- } else {
322
- target[key] = _source[key];
323
- }
324
- });
325
- }
326
- return deepMerge(target, ...sources);
327
- }
328
-
329
- 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 };