mirror of
https://github.com/soconnor0919/beenpad.git
synced 2026-02-05 00:06:40 -05:00
first commit
This commit is contained in:
21
node_modules/@vitest/expect/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/expect/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
21
node_modules/@vitest/expect/README.md
generated
vendored
Normal file
21
node_modules/@vitest/expect/README.md
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# @vitest/expect
|
||||
|
||||
Jest's expect matchers as a Chai plugin.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import {
|
||||
JestAsymmetricMatchers,
|
||||
JestChaiExpect,
|
||||
JestExtend,
|
||||
} from '@vitest/expect'
|
||||
import * as chai from 'chai'
|
||||
|
||||
// allows using expect.extend instead of chai.use to extend plugins
|
||||
chai.use(JestExtend)
|
||||
// adds all jest matchers to expect
|
||||
chai.use(JestChaiExpect)
|
||||
// adds asymmetric matchers like stringContaining, objectContaining
|
||||
chai.use(JestAsymmetricMatchers)
|
||||
```
|
||||
806
node_modules/@vitest/expect/dist/index.d.ts
generated
vendored
Normal file
806
node_modules/@vitest/expect/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,806 @@
|
||||
import { Test } from '@vitest/runner';
|
||||
import { MockInstance } from '@vitest/spy';
|
||||
import { Constructable } from '@vitest/utils';
|
||||
import { Formatter } from 'tinyrainbow';
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { diff, printDiffOrStringify } from '@vitest/utils/diff';
|
||||
export { DiffOptions } from '@vitest/utils/diff';
|
||||
import { stringify } from '@vitest/utils/display';
|
||||
import * as chai from 'chai';
|
||||
export { chai };
|
||||
|
||||
declare const MATCHERS_OBJECT: unique symbol;
|
||||
declare const JEST_MATCHERS_OBJECT: unique symbol;
|
||||
declare const GLOBAL_EXPECT: unique symbol;
|
||||
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
|
||||
|
||||
interface AsymmetricMatcherInterface {
|
||||
asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean;
|
||||
toString: () => string;
|
||||
getExpectedType?: () => string;
|
||||
toAsymmetricMatcher?: () => string;
|
||||
}
|
||||
declare abstract class AsymmetricMatcher<
|
||||
T,
|
||||
State extends MatcherState = MatcherState
|
||||
> implements AsymmetricMatcherInterface {
|
||||
protected sample: T;
|
||||
protected inverse: boolean;
|
||||
$$typeof: symbol;
|
||||
constructor(sample: T, inverse?: boolean);
|
||||
protected getMatcherContext(expect?: Chai.ExpectStatic): State;
|
||||
abstract asymmetricMatch(other: unknown, customTesters?: Array<Tester>): boolean;
|
||||
abstract toString(): string;
|
||||
getExpectedType?(): string;
|
||||
toAsymmetricMatcher?(): string;
|
||||
}
|
||||
declare class StringContaining extends AsymmetricMatcher<string> {
|
||||
constructor(sample: string, inverse?: boolean);
|
||||
asymmetricMatch(other: string): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
}
|
||||
declare class Anything extends AsymmetricMatcher<void> {
|
||||
asymmetricMatch(other: unknown): boolean;
|
||||
toString(): string;
|
||||
toAsymmetricMatcher(): string;
|
||||
}
|
||||
declare class ObjectContaining extends AsymmetricMatcher<Record<string | symbol | number, unknown>> {
|
||||
constructor(sample: Record<string, unknown>, inverse?: boolean);
|
||||
getPrototype(obj: object): any;
|
||||
hasProperty(obj: object | null, property: string | symbol): boolean;
|
||||
getProperties(obj: object): (string | symbol)[];
|
||||
asymmetricMatch(other: any, customTesters?: Array<Tester>): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
}
|
||||
declare class ArrayContaining<T = unknown> extends AsymmetricMatcher<Array<T>> {
|
||||
constructor(sample: Array<T>, inverse?: boolean);
|
||||
asymmetricMatch(other: Array<T>, customTesters?: Array<Tester>): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
}
|
||||
declare class Any extends AsymmetricMatcher<any> {
|
||||
constructor(sample: unknown);
|
||||
fnNameFor(func: Function): string;
|
||||
asymmetricMatch(other: unknown): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
toAsymmetricMatcher(): string;
|
||||
}
|
||||
declare class StringMatching extends AsymmetricMatcher<RegExp> {
|
||||
constructor(sample: string | RegExp, inverse?: boolean);
|
||||
asymmetricMatch(other: string): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
}
|
||||
declare class SchemaMatching extends AsymmetricMatcher<StandardSchemaV1<unknown, unknown>> {
|
||||
private result;
|
||||
constructor(sample: StandardSchemaV1<unknown, unknown>, inverse?: boolean);
|
||||
asymmetricMatch(other: unknown): boolean;
|
||||
toString(): string;
|
||||
getExpectedType(): string;
|
||||
toAsymmetricMatcher(): string;
|
||||
}
|
||||
declare const JestAsymmetricMatchers: ChaiPlugin;
|
||||
|
||||
declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string;
|
||||
declare function printReceived(object: unknown): string;
|
||||
declare function printExpected(value: unknown): string;
|
||||
declare function getMatcherUtils(): {
|
||||
EXPECTED_COLOR: Formatter;
|
||||
RECEIVED_COLOR: Formatter;
|
||||
INVERTED_COLOR: Formatter;
|
||||
BOLD_WEIGHT: Formatter;
|
||||
DIM_COLOR: Formatter;
|
||||
diff: typeof diff;
|
||||
matcherHint: typeof matcherHint;
|
||||
printReceived: typeof printReceived;
|
||||
printExpected: typeof printExpected;
|
||||
printDiffOrStringify: typeof printDiffOrStringify;
|
||||
printWithType: typeof printWithType;
|
||||
};
|
||||
declare function printWithType<T>(name: string, value: T, print: (value: T) => string): string;
|
||||
declare function addCustomEqualityTesters(newTesters: Array<Tester>): void;
|
||||
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
*/
|
||||
|
||||
type ChaiPlugin = Chai.ChaiPlugin;
|
||||
type Tester = (this: TesterContext, a: any, b: any, customTesters: Array<Tester>) => boolean | undefined;
|
||||
interface TesterContext {
|
||||
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
|
||||
}
|
||||
|
||||
interface MatcherHintOptions {
|
||||
comment?: string;
|
||||
expectedColor?: Formatter;
|
||||
isDirectExpectCall?: boolean;
|
||||
isNot?: boolean;
|
||||
promise?: string;
|
||||
receivedColor?: Formatter;
|
||||
secondArgument?: string;
|
||||
secondArgumentColor?: Formatter;
|
||||
}
|
||||
interface MatcherState {
|
||||
customTesters: Array<Tester>;
|
||||
assertionCalls: number;
|
||||
currentTestName?: string;
|
||||
dontThrow?: () => void;
|
||||
error?: Error;
|
||||
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
|
||||
expand?: boolean;
|
||||
expectedAssertionsNumber?: number | null;
|
||||
expectedAssertionsNumberErrorGen?: (() => Error) | null;
|
||||
isExpectingAssertions?: boolean;
|
||||
isExpectingAssertionsError?: Error | null;
|
||||
isNot: boolean;
|
||||
promise: string;
|
||||
suppressedErrors: Array<Error>;
|
||||
testPath?: string;
|
||||
utils: ReturnType<typeof getMatcherUtils> & {
|
||||
diff: typeof diff;
|
||||
stringify: typeof stringify;
|
||||
iterableEquality: Tester;
|
||||
subsetEquality: Tester;
|
||||
};
|
||||
soft?: boolean;
|
||||
poll?: boolean;
|
||||
task?: Readonly<Test>;
|
||||
}
|
||||
interface SyncExpectationResult {
|
||||
pass: boolean;
|
||||
message: () => string;
|
||||
actual?: any;
|
||||
expected?: any;
|
||||
}
|
||||
type AsyncExpectationResult = Promise<SyncExpectationResult>;
|
||||
type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
|
||||
interface RawMatcherFn<
|
||||
T extends MatcherState = MatcherState,
|
||||
E extends Array<any> = Array<any>
|
||||
> {
|
||||
(this: T, received: any, ...expected: E): ExpectationResult;
|
||||
}
|
||||
interface Matchers<T = any> {}
|
||||
type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>> & ThisType<T> & { [K in keyof Matchers<T>]? : RawMatcherFn<T, Parameters<Matchers<T>[K]>> };
|
||||
interface ExpectStatic extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining {
|
||||
<T>(actual: T, message?: string): Assertion<T>;
|
||||
extend: (expects: MatchersObject) => void;
|
||||
anything: () => any;
|
||||
any: (constructor: unknown) => any;
|
||||
getState: () => MatcherState;
|
||||
setState: (state: Partial<MatcherState>) => void;
|
||||
not: AsymmetricMatchersContaining;
|
||||
}
|
||||
interface CustomMatcher {
|
||||
/**
|
||||
* Checks that a value satisfies a custom matcher function.
|
||||
*
|
||||
* @param matcher - A function returning a boolean based on the custom condition
|
||||
* @param message - Optional custom error message on failure
|
||||
*
|
||||
* @example
|
||||
* expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18');
|
||||
* expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18'));
|
||||
*/
|
||||
toSatisfy: (matcher: (value: any) => boolean, message?: string) => any;
|
||||
/**
|
||||
* Matches if the received value is one of the values in the expected array or set.
|
||||
*
|
||||
* @example
|
||||
* expect(1).toBeOneOf([1, 2, 3])
|
||||
* expect('foo').toBeOneOf([expect.any(String)])
|
||||
* expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) })
|
||||
*/
|
||||
toBeOneOf: <T>(sample: Array<T> | Set<T>) => any;
|
||||
}
|
||||
interface AsymmetricMatchersContaining extends CustomMatcher {
|
||||
/**
|
||||
* Matches if the received string contains the expected substring.
|
||||
*
|
||||
* @example
|
||||
* expect('I have an apple').toEqual(expect.stringContaining('apple'));
|
||||
* expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') });
|
||||
*/
|
||||
stringContaining: (expected: string) => any;
|
||||
/**
|
||||
* Matches if the received object contains all properties of the expected object.
|
||||
*
|
||||
* @example
|
||||
* expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' }))
|
||||
*/
|
||||
objectContaining: <T = any>(expected: DeeplyAllowMatchers<T>) => any;
|
||||
/**
|
||||
* Matches if the received array contains all elements in the expected array.
|
||||
*
|
||||
* @example
|
||||
* expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a']));
|
||||
*/
|
||||
arrayContaining: <T = unknown>(expected: Array<DeeplyAllowMatchers<T>>) => any;
|
||||
/**
|
||||
* Matches if the received string or regex matches the expected pattern.
|
||||
*
|
||||
* @example
|
||||
* expect('hello world').toEqual(expect.stringMatching(/^hello/));
|
||||
* expect('hello world').toEqual(expect.stringMatching('hello'));
|
||||
*/
|
||||
stringMatching: (expected: string | RegExp) => any;
|
||||
/**
|
||||
* Matches if the received number is within a certain precision of the expected number.
|
||||
*
|
||||
* @param precision - Optional decimal precision for comparison. Default is 2.
|
||||
*
|
||||
* @example
|
||||
* expect(10.45).toEqual(expect.closeTo(10.5, 1));
|
||||
* expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
|
||||
*/
|
||||
closeTo: (expected: number, precision?: number) => any;
|
||||
/**
|
||||
* Matches if the received value validates against a Standard Schema.
|
||||
*
|
||||
* @param schema - A Standard Schema V1 compatible schema object
|
||||
*
|
||||
* @example
|
||||
* expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() })))
|
||||
* expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())])
|
||||
*/
|
||||
schemaMatching: (schema: unknown) => any;
|
||||
}
|
||||
type WithAsymmetricMatcher<T> = T | AsymmetricMatcher<unknown>;
|
||||
type DeeplyAllowMatchers<T> = T extends Array<infer Element> ? WithAsymmetricMatcher<T> | DeeplyAllowMatchers<Element>[] : T extends object ? WithAsymmetricMatcher<T> | { [K in keyof T] : DeeplyAllowMatchers<T[K]> } : WithAsymmetricMatcher<T>;
|
||||
interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
|
||||
/**
|
||||
* Used when you want to check that two objects have the same value.
|
||||
* This matcher recursively checks the equality of all fields, rather than checking for object identity.
|
||||
*
|
||||
* @example
|
||||
* expect(user).toEqual({ name: 'Alice', age: 30 });
|
||||
*/
|
||||
toEqual: <E>(expected: E) => void;
|
||||
/**
|
||||
* Use to test that objects have the same types as well as structure.
|
||||
*
|
||||
* @example
|
||||
* expect(user).toStrictEqual({ name: 'Alice', age: 30 });
|
||||
*/
|
||||
toStrictEqual: <E>(expected: E) => void;
|
||||
/**
|
||||
* Checks that a value is what you expect. It calls `Object.is` to compare values.
|
||||
* Don't use `toBe` with floating-point numbers.
|
||||
*
|
||||
* @example
|
||||
* expect(result).toBe(42);
|
||||
* expect(status).toBe(true);
|
||||
*/
|
||||
toBe: <E>(expected: E) => void;
|
||||
/**
|
||||
* Check that a string matches a regular expression.
|
||||
*
|
||||
* @example
|
||||
* expect(message).toMatch(/hello/);
|
||||
* expect(greeting).toMatch('world');
|
||||
*/
|
||||
toMatch: (expected: string | RegExp) => void;
|
||||
/**
|
||||
* Used to check that a JavaScript object matches a subset of the properties of an object
|
||||
*
|
||||
* @example
|
||||
* expect(user).toMatchObject({
|
||||
* name: 'Alice',
|
||||
* address: { city: 'Wonderland' }
|
||||
* });
|
||||
*/
|
||||
toMatchObject: <E extends object | any[]>(expected: E) => void;
|
||||
/**
|
||||
* Used when you want to check that an item is in a list.
|
||||
* For testing the items in the list, this uses `===`, a strict equality check.
|
||||
*
|
||||
* @example
|
||||
* expect(items).toContain('apple');
|
||||
* expect(numbers).toContain(5);
|
||||
*/
|
||||
toContain: <E>(item: E) => void;
|
||||
/**
|
||||
* Used when you want to check that an item is in a list.
|
||||
* For testing the items in the list, this matcher recursively checks the
|
||||
* equality of all fields, rather than checking for object identity.
|
||||
*
|
||||
* @example
|
||||
* expect(items).toContainEqual({ name: 'apple', quantity: 1 });
|
||||
*/
|
||||
toContainEqual: <E>(item: E) => void;
|
||||
/**
|
||||
* Use when you don't care what a value is, you just want to ensure a value
|
||||
* is true in a boolean context. In JavaScript, there are six falsy values:
|
||||
* `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
|
||||
*
|
||||
* @example
|
||||
* expect(user.isActive).toBeTruthy();
|
||||
*/
|
||||
toBeTruthy: () => void;
|
||||
/**
|
||||
* When you don't care what a value is, you just want to
|
||||
* ensure a value is false in a boolean context.
|
||||
*
|
||||
* @example
|
||||
* expect(user.isActive).toBeFalsy();
|
||||
*/
|
||||
toBeFalsy: () => void;
|
||||
/**
|
||||
* For comparing floating point numbers.
|
||||
*
|
||||
* @example
|
||||
* expect(score).toBeGreaterThan(10);
|
||||
*/
|
||||
toBeGreaterThan: (num: number | bigint) => void;
|
||||
/**
|
||||
* For comparing floating point numbers.
|
||||
*
|
||||
* @example
|
||||
* expect(score).toBeGreaterThanOrEqual(10);
|
||||
*/
|
||||
toBeGreaterThanOrEqual: (num: number | bigint) => void;
|
||||
/**
|
||||
* For comparing floating point numbers.
|
||||
*
|
||||
* @example
|
||||
* expect(score).toBeLessThan(10);
|
||||
*/
|
||||
toBeLessThan: (num: number | bigint) => void;
|
||||
/**
|
||||
* For comparing floating point numbers.
|
||||
*
|
||||
* @example
|
||||
* expect(score).toBeLessThanOrEqual(10);
|
||||
*/
|
||||
toBeLessThanOrEqual: (num: number | bigint) => void;
|
||||
/**
|
||||
* Used to check that a variable is NaN.
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeNaN();
|
||||
*/
|
||||
toBeNaN: () => void;
|
||||
/**
|
||||
* Used to check that a variable is undefined.
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeUndefined();
|
||||
*/
|
||||
toBeUndefined: () => void;
|
||||
/**
|
||||
* This is the same as `.toBe(null)` but the error messages are a bit nicer.
|
||||
* So use `.toBeNull()` when you want to check that something is null.
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeNull();
|
||||
*/
|
||||
toBeNull: () => void;
|
||||
/**
|
||||
* Used to check that a variable is nullable (null or undefined).
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeNullable();
|
||||
*/
|
||||
toBeNullable: () => void;
|
||||
/**
|
||||
* Ensure that a variable is not undefined.
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeDefined();
|
||||
*/
|
||||
toBeDefined: () => void;
|
||||
/**
|
||||
* Ensure that an object is an instance of a class.
|
||||
* This matcher uses `instanceof` underneath.
|
||||
*
|
||||
* @example
|
||||
* expect(new Date()).toBeInstanceOf(Date);
|
||||
*/
|
||||
toBeInstanceOf: <E>(expected: E) => void;
|
||||
/**
|
||||
* Used to check that an object has a `.length` property
|
||||
* and it is set to a certain numeric value.
|
||||
*
|
||||
* @example
|
||||
* expect([1, 2, 3]).toHaveLength(3);
|
||||
* expect('hello').toHaveLength(5);
|
||||
*/
|
||||
toHaveLength: (length: number) => void;
|
||||
/**
|
||||
* Use to check if a property at the specified path exists on an object.
|
||||
* For checking deeply nested properties, you may use dot notation or an array containing
|
||||
* the path segments for deep references.
|
||||
*
|
||||
* Optionally, you can provide a value to check if it matches the value present at the path
|
||||
* on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
|
||||
* the equality of all fields.
|
||||
*
|
||||
* @example
|
||||
* expect(user).toHaveProperty('address.city', 'New York');
|
||||
* expect(config).toHaveProperty(['settings', 'theme'], 'dark');
|
||||
*/
|
||||
toHaveProperty: <E>(property: string | (string | number)[], value?: E) => void;
|
||||
/**
|
||||
* Using exact equality with floating point numbers is a bad idea.
|
||||
* Rounding means that intuitive things fail.
|
||||
* The default for `numDigits` is 2.
|
||||
*
|
||||
* @example
|
||||
* expect(price).toBeCloseTo(9.99, 2);
|
||||
*/
|
||||
toBeCloseTo: (number: number, numDigits?: number) => void;
|
||||
/**
|
||||
* Ensures that a mock function is called an exact number of times.
|
||||
*
|
||||
* Also under the alias `expect.toBeCalledTimes`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenCalledTimes(2);
|
||||
*/
|
||||
toHaveBeenCalledTimes: (times: number) => void;
|
||||
/**
|
||||
* Ensures that a mock function is called an exact number of times.
|
||||
*
|
||||
* Alias for `expect.toHaveBeenCalledTimes`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toBeCalledTimes(2);
|
||||
*/
|
||||
toBeCalledTimes: (times: number) => void;
|
||||
/**
|
||||
* Ensures that a mock function is called.
|
||||
*
|
||||
* Also under the alias `expect.toBeCalled`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenCalled();
|
||||
*/
|
||||
toHaveBeenCalled: () => void;
|
||||
/**
|
||||
* Ensures that a mock function is called.
|
||||
*
|
||||
* Alias for `expect.toHaveBeenCalled`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toBeCalled();
|
||||
*/
|
||||
toBeCalled: () => void;
|
||||
/**
|
||||
* Ensure that a mock function is called with specific arguments.
|
||||
*
|
||||
* Also under the alias `expect.toBeCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenCalledWith('arg1', 42);
|
||||
*/
|
||||
toHaveBeenCalledWith: <E extends any[]>(...args: E) => void;
|
||||
/**
|
||||
* Ensure that a mock function is called with specific arguments.
|
||||
*
|
||||
* Alias for `expect.toHaveBeenCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toBeCalledWith('arg1', 42);
|
||||
*/
|
||||
toBeCalledWith: <E extends any[]>(...args: E) => void;
|
||||
/**
|
||||
* Ensure that a mock function is called with specific arguments on an Nth call.
|
||||
*
|
||||
* Also under the alias `expect.nthCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg');
|
||||
*/
|
||||
toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
|
||||
/**
|
||||
* Ensure that a mock function is called with specific arguments on an Nth call.
|
||||
*
|
||||
* Alias for `expect.toHaveBeenNthCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).nthCalledWith(2, 'secondArg');
|
||||
*/
|
||||
nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void;
|
||||
/**
|
||||
* If you have a mock function, you can use `.toHaveBeenLastCalledWith`
|
||||
* to test what arguments it was last called with.
|
||||
*
|
||||
* Also under the alias `expect.lastCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenLastCalledWith('lastArg');
|
||||
*/
|
||||
toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void;
|
||||
/**
|
||||
* If you have a mock function, you can use `.lastCalledWith`
|
||||
* to test what arguments it was last called with.
|
||||
*
|
||||
* Alias for `expect.toHaveBeenLastCalledWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).lastCalledWith('lastArg');
|
||||
*/
|
||||
lastCalledWith: <E extends any[]>(...args: E) => void;
|
||||
/**
|
||||
* Used to test that a function throws when it is called.
|
||||
*
|
||||
* Also under the alias `expect.toThrowError`.
|
||||
*
|
||||
* @example
|
||||
* expect(() => functionWithError()).toThrow('Error message');
|
||||
* expect(() => parseJSON('invalid')).toThrow(SyntaxError);
|
||||
*/
|
||||
toThrow: (expected?: string | Constructable | RegExp | Error) => void;
|
||||
/**
|
||||
* Used to test that a function throws when it is called.
|
||||
*
|
||||
* Alias for `expect.toThrow`.
|
||||
*
|
||||
* @example
|
||||
* expect(() => functionWithError()).toThrowError('Error message');
|
||||
* expect(() => parseJSON('invalid')).toThrowError(SyntaxError);
|
||||
*/
|
||||
toThrowError: (expected?: string | Constructable | RegExp | Error) => void;
|
||||
/**
|
||||
* Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
|
||||
*
|
||||
* Alias for `expect.toHaveReturned`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toReturn();
|
||||
*/
|
||||
toReturn: () => void;
|
||||
/**
|
||||
* Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
|
||||
*
|
||||
* Also under the alias `expect.toReturn`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveReturned();
|
||||
*/
|
||||
toHaveReturned: () => void;
|
||||
/**
|
||||
* Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
|
||||
* Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
|
||||
*
|
||||
* Alias for `expect.toHaveReturnedTimes`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toReturnTimes(3);
|
||||
*/
|
||||
toReturnTimes: (times: number) => void;
|
||||
/**
|
||||
* Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
|
||||
* Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
|
||||
*
|
||||
* Also under the alias `expect.toReturnTimes`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveReturnedTimes(3);
|
||||
*/
|
||||
toHaveReturnedTimes: (times: number) => void;
|
||||
/**
|
||||
* Use to ensure that a mock function returned a specific value.
|
||||
*
|
||||
* Alias for `expect.toHaveReturnedWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toReturnWith('returnValue');
|
||||
*/
|
||||
toReturnWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Use to ensure that a mock function returned a specific value.
|
||||
*
|
||||
* Also under the alias `expect.toReturnWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveReturnedWith('returnValue');
|
||||
*/
|
||||
toHaveReturnedWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Use to test the specific value that a mock function last returned.
|
||||
* If the last call to the mock function threw an error, then this matcher will fail
|
||||
* no matter what value you provided as the expected return value.
|
||||
*
|
||||
* Also under the alias `expect.lastReturnedWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveLastReturnedWith('lastValue');
|
||||
*/
|
||||
toHaveLastReturnedWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Use to test the specific value that a mock function last returned.
|
||||
* If the last call to the mock function threw an error, then this matcher will fail
|
||||
* no matter what value you provided as the expected return value.
|
||||
*
|
||||
* Alias for `expect.toHaveLastReturnedWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).lastReturnedWith('lastValue');
|
||||
*/
|
||||
lastReturnedWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Use to test the specific value that a mock function returned for the nth call.
|
||||
* If the nth call to the mock function threw an error, then this matcher will fail
|
||||
* no matter what value you provided as the expected return value.
|
||||
*
|
||||
* Also under the alias `expect.nthReturnedWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue');
|
||||
*/
|
||||
toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void;
|
||||
/**
|
||||
* Use to test the specific value that a mock function returned for the nth call.
|
||||
* If the nth call to the mock function threw an error, then this matcher will fail
|
||||
* no matter what value you provided as the expected return value.
|
||||
*
|
||||
* Alias for `expect.toHaveNthReturnedWith`.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).nthReturnedWith(2, 'nthValue');
|
||||
*/
|
||||
nthReturnedWith: <E>(nthCall: number, value: E) => void;
|
||||
}
|
||||
type VitestAssertion<
|
||||
A,
|
||||
T
|
||||
> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T> } & ((type: string, message?: string) => Assertion);
|
||||
type Promisify<O> = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify<O[K]> & ((...args: A) => Promise<R>) : O[K] };
|
||||
type PromisifyAssertion<T> = Promisify<Assertion<T>>;
|
||||
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, Matchers<T> {
|
||||
/**
|
||||
* Ensures a value is of a specific type.
|
||||
*
|
||||
* @example
|
||||
* expect(value).toBeTypeOf('string');
|
||||
* expect(number).toBeTypeOf('number');
|
||||
*/
|
||||
toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => void;
|
||||
/**
|
||||
* Asserts that a mock function was called exactly once.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenCalledOnce();
|
||||
*/
|
||||
toHaveBeenCalledOnce: () => void;
|
||||
/**
|
||||
* Ensure that a mock function is called with specific arguments and called
|
||||
* exactly once.
|
||||
*
|
||||
* @example
|
||||
* expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42);
|
||||
*/
|
||||
toHaveBeenCalledExactlyOnceWith: <E extends any[]>(...args: E) => void;
|
||||
/**
|
||||
* This assertion checks if a `Mock` was called before another `Mock`.
|
||||
* @param mock - A mock function created by `vi.spyOn` or `vi.fn`
|
||||
* @param failIfNoFirstInvocation - Fail if the first mock was never called
|
||||
* @example
|
||||
* const mock1 = vi.fn()
|
||||
* const mock2 = vi.fn()
|
||||
*
|
||||
* mock1()
|
||||
* mock2()
|
||||
* mock1()
|
||||
*
|
||||
* expect(mock1).toHaveBeenCalledBefore(mock2)
|
||||
*/
|
||||
toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
|
||||
/**
|
||||
* This assertion checks if a `Mock` was called after another `Mock`.
|
||||
* @param mock - A mock function created by `vi.spyOn` or `vi.fn`
|
||||
* @param failIfNoFirstInvocation - Fail if the first mock was never called
|
||||
* @example
|
||||
* const mock1 = vi.fn()
|
||||
* const mock2 = vi.fn()
|
||||
*
|
||||
* mock2()
|
||||
* mock1()
|
||||
* mock2()
|
||||
*
|
||||
* expect(mock1).toHaveBeenCalledAfter(mock2)
|
||||
*/
|
||||
toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
|
||||
/**
|
||||
* Checks that a promise resolves successfully at least once.
|
||||
*
|
||||
* @example
|
||||
* await expect(promise).toHaveResolved();
|
||||
*/
|
||||
toHaveResolved: () => void;
|
||||
/**
|
||||
* Checks that a promise resolves to a specific value.
|
||||
*
|
||||
* @example
|
||||
* await expect(promise).toHaveResolvedWith('success');
|
||||
*/
|
||||
toHaveResolvedWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Ensures a promise resolves a specific number of times.
|
||||
*
|
||||
* @example
|
||||
* expect(mockAsyncFunc).toHaveResolvedTimes(3);
|
||||
*/
|
||||
toHaveResolvedTimes: (times: number) => void;
|
||||
/**
|
||||
* Asserts that the last resolved value of a promise matches an expected value.
|
||||
*
|
||||
* @example
|
||||
* await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult');
|
||||
*/
|
||||
toHaveLastResolvedWith: <E>(value: E) => void;
|
||||
/**
|
||||
* Ensures a specific value was returned by a promise on the nth resolution.
|
||||
*
|
||||
* @example
|
||||
* await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult');
|
||||
*/
|
||||
toHaveNthResolvedWith: <E>(nthCall: number, value: E) => void;
|
||||
/**
|
||||
* Verifies that a promise resolves.
|
||||
*
|
||||
* @example
|
||||
* await expect(someAsyncFunc).resolves.toBe(42);
|
||||
*/
|
||||
resolves: PromisifyAssertion<T>;
|
||||
/**
|
||||
* Verifies that a promise rejects.
|
||||
*
|
||||
* @example
|
||||
* await expect(someAsyncFunc).rejects.toThrow('error');
|
||||
*/
|
||||
rejects: PromisifyAssertion<T>;
|
||||
}
|
||||
declare global {
|
||||
namespace jest {
|
||||
interface Matchers<
|
||||
R,
|
||||
T = {}
|
||||
> {}
|
||||
}
|
||||
}
|
||||
|
||||
declare const customMatchers: MatchersObject;
|
||||
|
||||
declare const JestChaiExpect: ChaiPlugin;
|
||||
|
||||
declare const JestExtend: ChaiPlugin;
|
||||
|
||||
declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean;
|
||||
declare function isAsymmetric(obj: any): obj is AsymmetricMatcher<any>;
|
||||
declare function hasAsymmetric(obj: any, seen?: Set<any>): boolean;
|
||||
declare function isA(typeName: string, value: unknown): boolean;
|
||||
declare function fnNameFor(func: Function): string;
|
||||
declare function hasProperty(obj: object | null, property: string): boolean;
|
||||
declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean;
|
||||
declare function isImmutableUnorderedSet(maybeSet: any): boolean;
|
||||
declare function iterableEquality(a: any, b: any, customTesters?: Array<Tester>, aStack?: Array<any>, bStack?: Array<any>): boolean | undefined;
|
||||
declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array<Tester>): boolean | undefined;
|
||||
declare function typeEquality(a: any, b: any): boolean | undefined;
|
||||
declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined;
|
||||
declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array<Tester>): boolean | undefined;
|
||||
declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string;
|
||||
declare function pluralize(word: string, count: number): string;
|
||||
declare function getObjectKeys(object: object): Array<string | symbol>;
|
||||
declare function getObjectSubset(object: any, subset: any, customTesters: Array<Tester>): {
|
||||
subset: any;
|
||||
stripped: number;
|
||||
};
|
||||
/**
|
||||
* Detects if an object is a Standard Schema V1 compatible schema
|
||||
*/
|
||||
declare function isStandardSchema(obj: any): obj is StandardSchemaV1;
|
||||
|
||||
declare function getState<State extends MatcherState = MatcherState>(expect: ExpectStatic): State;
|
||||
declare function setState<State extends MatcherState = MatcherState>(state: Partial<State>, expect: ExpectStatic): void;
|
||||
|
||||
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };
|
||||
export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext };
|
||||
1875
node_modules/@vitest/expect/dist/index.js
generated
vendored
Normal file
1875
node_modules/@vitest/expect/dist/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
46
node_modules/@vitest/expect/package.json
generated
vendored
Normal file
46
node_modules/@vitest/expect/package.json
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "@vitest/expect",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Jest's expect matchers as a Chai plugin",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/expect"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@types/chai": "^5.2.2",
|
||||
"chai": "^6.2.1",
|
||||
"tinyrainbow": "^3.0.3",
|
||||
"@vitest/spy": "4.0.15",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitest/runner": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
21
node_modules/@vitest/mocker/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/mocker/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
5
node_modules/@vitest/mocker/README.md
generated
vendored
Normal file
5
node_modules/@vitest/mocker/README.md
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# @vitest/mocker
|
||||
|
||||
Vitest's module mocker implementation.
|
||||
|
||||
[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md)
|
||||
2
node_modules/@vitest/mocker/dist/auto-register.d.ts
generated
vendored
Normal file
2
node_modules/@vitest/mocker/dist/auto-register.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
export { };
|
||||
9
node_modules/@vitest/mocker/dist/auto-register.js
generated
vendored
Normal file
9
node_modules/@vitest/mocker/dist/auto-register.js
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
|
||||
import { registerModuleMocker } from './register.js';
|
||||
import './chunk-mocker.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
import '@vitest/spy';
|
||||
|
||||
registerModuleMocker(() => new ModuleMockerServerInterceptor());
|
||||
12
node_modules/@vitest/mocker/dist/automock.d.ts
generated
vendored
Normal file
12
node_modules/@vitest/mocker/dist/automock.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
interface AutomockOptions {
|
||||
/**
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
}
|
||||
declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString;
|
||||
|
||||
export { automockModule };
|
||||
export type { AutomockOptions };
|
||||
3
node_modules/@vitest/mocker/dist/automock.js
generated
vendored
Normal file
3
node_modules/@vitest/mocker/dist/automock.js
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import 'magic-string';
|
||||
export { a as automockModule } from './chunk-automock.js';
|
||||
import 'estree-walker';
|
||||
53
node_modules/@vitest/mocker/dist/browser.d.ts
generated
vendored
Normal file
53
node_modules/@vitest/mocker/dist/browser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
import { M as ModuleMockerInterceptor } from './mocker.d-TnKRhz7N.js';
|
||||
export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, d as ModuleMockerConfig, e as ModuleMockerRPC, R as ResolveIdResult, f as ResolveMockResult, c as createCompilerHints } from './mocker.d-TnKRhz7N.js';
|
||||
import { StartOptions, SetupWorker } from 'msw/browser';
|
||||
import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js';
|
||||
import '@vitest/spy';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
|
||||
interface ModuleMockerMSWInterceptorOptions {
|
||||
/**
|
||||
* The identifier to access the globalThis object in the worker.
|
||||
* This will be injected into the script as is, so make sure it's a valid JS expression.
|
||||
* @example
|
||||
* ```js
|
||||
* // globalThisAccessor: '__my_variable__' produces:
|
||||
* globalThis[__my_variable__]
|
||||
* // globalThisAccessor: 'Symbol.for('secret:mocks')' produces:
|
||||
* globalThis[Symbol.for('secret:mocks')]
|
||||
* // globalThisAccessor: '"__vitest_mocker__"' (notice quotes) produces:
|
||||
* globalThis["__vitest_mocker__"]
|
||||
* ```
|
||||
* @default `"__vitest_mocker__"`
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
/**
|
||||
* Options passed down to `msw.setupWorker().start(options)`
|
||||
*/
|
||||
mswOptions?: StartOptions;
|
||||
/**
|
||||
* A pre-configured `msw.setupWorker` instance.
|
||||
*/
|
||||
mswWorker?: SetupWorker;
|
||||
}
|
||||
declare class ModuleMockerMSWInterceptor implements ModuleMockerInterceptor {
|
||||
private readonly options;
|
||||
protected readonly mocks: MockerRegistry;
|
||||
private startPromise;
|
||||
private worker;
|
||||
constructor(options?: ModuleMockerMSWInterceptorOptions);
|
||||
register(module: MockedModule): Promise<void>;
|
||||
delete(url: string): Promise<void>;
|
||||
invalidate(): Promise<void>;
|
||||
private resolveManualMock;
|
||||
protected init(): Promise<SetupWorker>;
|
||||
}
|
||||
|
||||
declare class ModuleMockerServerInterceptor implements ModuleMockerInterceptor {
|
||||
register(module: MockedModule): Promise<void>;
|
||||
delete(id: string): Promise<void>;
|
||||
invalidate(): Promise<void>;
|
||||
}
|
||||
|
||||
export { ModuleMockerInterceptor, ModuleMockerMSWInterceptor, ModuleMockerServerInterceptor };
|
||||
export type { ModuleMockerMSWInterceptorOptions };
|
||||
91
node_modules/@vitest/mocker/dist/browser.js
generated
vendored
Normal file
91
node_modules/@vitest/mocker/dist/browser.js
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js';
|
||||
import { M as MockerRegistry } from './chunk-registry.js';
|
||||
import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js';
|
||||
export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
|
||||
import './index.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
class ModuleMockerMSWInterceptor {
|
||||
mocks = new MockerRegistry();
|
||||
startPromise;
|
||||
worker;
|
||||
constructor(options = {}) {
|
||||
this.options = options;
|
||||
if (!options.globalThisAccessor) {
|
||||
options.globalThisAccessor = "\"__vitest_mocker__\"";
|
||||
}
|
||||
}
|
||||
async register(module) {
|
||||
await this.init();
|
||||
this.mocks.add(module);
|
||||
}
|
||||
async delete(url) {
|
||||
await this.init();
|
||||
this.mocks.delete(url);
|
||||
}
|
||||
async invalidate() {
|
||||
this.mocks.clear();
|
||||
}
|
||||
async resolveManualMock(mock) {
|
||||
const exports$1 = Object.keys(await mock.resolve());
|
||||
const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor);
|
||||
return new Response(text, { headers: { "Content-Type": "application/javascript" } });
|
||||
}
|
||||
async init() {
|
||||
if (this.worker) {
|
||||
return this.worker;
|
||||
}
|
||||
if (this.startPromise) {
|
||||
return this.startPromise;
|
||||
}
|
||||
const worker = this.options.mswWorker;
|
||||
this.startPromise = Promise.all([worker ? { setupWorker(handler) {
|
||||
worker.use(handler);
|
||||
return worker;
|
||||
} } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => {
|
||||
const worker = setupWorker(http.get(/.+/, async ({ request }) => {
|
||||
const path = cleanQuery(request.url.slice(location.origin.length));
|
||||
if (!this.mocks.has(path)) {
|
||||
return passthrough();
|
||||
}
|
||||
const mock = this.mocks.get(path);
|
||||
switch (mock.type) {
|
||||
case "manual": return this.resolveManualMock(mock);
|
||||
case "automock":
|
||||
case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`));
|
||||
case "redirect": return Response.redirect(mock.redirect);
|
||||
default: throw new Error(`Unknown mock type: ${mock.type}`);
|
||||
}
|
||||
}));
|
||||
return worker.start(this.options.mswOptions).then(() => worker);
|
||||
}).finally(() => {
|
||||
this.worker = worker;
|
||||
this.startPromise = undefined;
|
||||
});
|
||||
return await this.startPromise;
|
||||
}
|
||||
}
|
||||
const trailingSeparatorRE = /[?&]$/;
|
||||
const timestampRE = /\bt=\d{13}&?\b/;
|
||||
const versionRE = /\bv=\w{8}&?\b/;
|
||||
function cleanQuery(url) {
|
||||
return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, "");
|
||||
}
|
||||
function passthrough() {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
statusText: "Passthrough",
|
||||
headers: { "x-msw-intention": "passthrough" }
|
||||
});
|
||||
}
|
||||
const replacePercentageRE = /%/g;
|
||||
function injectQuery(url, queryToInject) {
|
||||
// encode percents for consistent behavior with pathToFileURL
|
||||
// see #2614 for details
|
||||
const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href);
|
||||
const { search, hash } = resolvedUrl;
|
||||
const pathname = cleanUrl(url);
|
||||
return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
|
||||
}
|
||||
|
||||
export { ModuleMockerMSWInterceptor };
|
||||
345
node_modules/@vitest/mocker/dist/chunk-automock.js
generated
vendored
Normal file
345
node_modules/@vitest/mocker/dist/chunk-automock.js
generated
vendored
Normal file
@@ -0,0 +1,345 @@
|
||||
import MagicString from 'magic-string';
|
||||
import { walk } from 'estree-walker';
|
||||
|
||||
const isNodeInPatternWeakSet = new WeakSet();
|
||||
function setIsNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.add(node);
|
||||
}
|
||||
function isNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.has(node);
|
||||
}
|
||||
/**
|
||||
* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
|
||||
* Except this is using acorn AST
|
||||
*/
|
||||
function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) {
|
||||
const parentStack = [];
|
||||
const varKindStack = [];
|
||||
const scopeMap = new WeakMap();
|
||||
const identifiers = [];
|
||||
const setScope = (node, name) => {
|
||||
let scopeIds = scopeMap.get(node);
|
||||
if (scopeIds && scopeIds.has(name)) {
|
||||
return;
|
||||
}
|
||||
if (!scopeIds) {
|
||||
scopeIds = new Set();
|
||||
scopeMap.set(node, scopeIds);
|
||||
}
|
||||
scopeIds.add(name);
|
||||
};
|
||||
function isInScope(name, parents) {
|
||||
return parents.some((node) => {
|
||||
var _scopeMap$get;
|
||||
return node && ((_scopeMap$get = scopeMap.get(node)) === null || _scopeMap$get === void 0 ? void 0 : _scopeMap$get.has(name));
|
||||
});
|
||||
}
|
||||
function handlePattern(p, parentScope) {
|
||||
if (p.type === "Identifier") {
|
||||
setScope(parentScope, p.name);
|
||||
} else if (p.type === "RestElement") {
|
||||
handlePattern(p.argument, parentScope);
|
||||
} else if (p.type === "ObjectPattern") {
|
||||
p.properties.forEach((property) => {
|
||||
if (property.type === "RestElement") {
|
||||
setScope(parentScope, property.argument.name);
|
||||
} else {
|
||||
handlePattern(property.value, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "ArrayPattern") {
|
||||
p.elements.forEach((element) => {
|
||||
if (element) {
|
||||
handlePattern(element, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "AssignmentPattern") {
|
||||
handlePattern(p.left, parentScope);
|
||||
} else {
|
||||
setScope(parentScope, p.name);
|
||||
}
|
||||
}
|
||||
walk(root, {
|
||||
enter(node, parent) {
|
||||
if (node.type === "ImportDeclaration") {
|
||||
return this.skip();
|
||||
}
|
||||
// track parent stack, skip for "else-if"/"else" branches as acorn nests
|
||||
// the ast within "if" nodes instead of flattening them
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.unshift(parent);
|
||||
}
|
||||
// track variable declaration kind stack used by VariableDeclarator
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.unshift(node.kind);
|
||||
}
|
||||
if (node.type === "CallExpression") {
|
||||
onCallExpression === null || onCallExpression === void 0 ? void 0 : onCallExpression(node);
|
||||
}
|
||||
if (node.type === "MetaProperty" && node.meta.name === "import") {
|
||||
onImportMeta === null || onImportMeta === void 0 ? void 0 : onImportMeta(node);
|
||||
} else if (node.type === "ImportExpression") {
|
||||
onDynamicImport === null || onDynamicImport === void 0 ? void 0 : onDynamicImport(node);
|
||||
}
|
||||
if (node.type === "Identifier") {
|
||||
if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) {
|
||||
// record the identifier, for DFS -> BFS
|
||||
identifiers.push([node, parentStack.slice(0)]);
|
||||
}
|
||||
} else if (isFunctionNode(node)) {
|
||||
// If it is a function declaration, it could be shadowing an import
|
||||
// Add its name to the scope so it won't get replaced
|
||||
if (node.type === "FunctionDeclaration") {
|
||||
const parentScope = findParentScope(parentStack);
|
||||
if (parentScope) {
|
||||
setScope(parentScope, node.id.name);
|
||||
}
|
||||
}
|
||||
// walk function expressions and add its arguments to known identifiers
|
||||
// so that we don't prefix them
|
||||
node.params.forEach((p) => {
|
||||
if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
|
||||
handlePattern(p, node);
|
||||
return;
|
||||
}
|
||||
walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
|
||||
// skip params default value of destructure
|
||||
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "AssignmentPattern" && (parent === null || parent === void 0 ? void 0 : parent.right) === child) {
|
||||
return this.skip();
|
||||
}
|
||||
if (child.type !== "Identifier") {
|
||||
return;
|
||||
}
|
||||
// do not record as scope variable if is a destructuring keyword
|
||||
if (isStaticPropertyKey(child, parent)) {
|
||||
return;
|
||||
}
|
||||
// do not record if this is a default value
|
||||
// assignment of a destructuring variable
|
||||
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "TemplateLiteral" && (parent === null || parent === void 0 ? void 0 : parent.expressions.includes(child)) || (parent === null || parent === void 0 ? void 0 : parent.type) === "CallExpression" && (parent === null || parent === void 0 ? void 0 : parent.callee) === child) {
|
||||
return;
|
||||
}
|
||||
setScope(node, child.name);
|
||||
} });
|
||||
});
|
||||
} else if (node.type === "Property" && parent.type === "ObjectPattern") {
|
||||
// mark property in destructuring pattern
|
||||
setIsNodeInPattern(node);
|
||||
} else if (node.type === "VariableDeclarator") {
|
||||
const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
|
||||
if (parentFunction) {
|
||||
handlePattern(node.id, parentFunction);
|
||||
}
|
||||
} else if (node.type === "CatchClause" && node.param) {
|
||||
handlePattern(node.param, node);
|
||||
}
|
||||
},
|
||||
leave(node, parent) {
|
||||
// untrack parent stack from above
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.shift();
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.shift();
|
||||
}
|
||||
}
|
||||
});
|
||||
// emit the identifier events in BFS so the hoisted declarations
|
||||
// can be captured correctly
|
||||
identifiers.forEach(([node, stack]) => {
|
||||
if (!isInScope(node.name, stack)) {
|
||||
const parent = stack[0];
|
||||
const grandparent = stack[1];
|
||||
const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack));
|
||||
const classDeclaration = parent.type === "PropertyDefinition" && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && node === parent.superClass;
|
||||
const classExpression = parent.type === "ClassExpression" && node === parent.id;
|
||||
onIdentifier === null || onIdentifier === void 0 ? void 0 : onIdentifier(node, {
|
||||
hasBindingShortcut,
|
||||
classDeclaration,
|
||||
classExpression
|
||||
}, stack);
|
||||
}
|
||||
});
|
||||
}
|
||||
function isRefIdentifier(id, parent, parentStack) {
|
||||
// declaration id
|
||||
if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
if (isFunctionNode(parent)) {
|
||||
// function declaration/expression id
|
||||
if (parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
// params list
|
||||
if (parent.params.includes(id)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// class method name
|
||||
if (parent.type === "MethodDefinition" && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
// property key
|
||||
if (isStaticPropertyKey(id, parent)) {
|
||||
return false;
|
||||
}
|
||||
// object destructuring pattern
|
||||
if (isNodeInPattern(parent) && parent.value === id) {
|
||||
return false;
|
||||
}
|
||||
// non-assignment array destructuring pattern
|
||||
if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) {
|
||||
return false;
|
||||
}
|
||||
// member expression property
|
||||
if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
if (parent.type === "ExportSpecifier") {
|
||||
return false;
|
||||
}
|
||||
// is a special keyword but parsed as identifier
|
||||
if (id.name === "arguments") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isStaticProperty(node) {
|
||||
return node && node.type === "Property" && !node.computed;
|
||||
}
|
||||
function isStaticPropertyKey(node, parent) {
|
||||
return isStaticProperty(parent) && parent.key === node;
|
||||
}
|
||||
const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
|
||||
function isFunctionNode(node) {
|
||||
return functionNodeTypeRE.test(node.type);
|
||||
}
|
||||
const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
|
||||
function isBlock(node) {
|
||||
return blockNodeTypeRE.test(node.type);
|
||||
}
|
||||
function findParentScope(parentStack, isVar = false) {
|
||||
return parentStack.find(isVar ? isFunctionNode : isBlock);
|
||||
}
|
||||
function isInDestructuringAssignment(parent, parentStack) {
|
||||
if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) {
|
||||
return parentStack.some((i) => i.type === "AssignmentExpression");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getArbitraryModuleIdentifier(node) {
|
||||
return node.type === "Identifier" ? node.name : node.raw;
|
||||
}
|
||||
|
||||
// TODO: better source map replacement
|
||||
function automockModule(code, mockType, parse, options = {}) {
|
||||
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
const ast = parse(code);
|
||||
const m = new MagicString(code);
|
||||
const allSpecifiers = [];
|
||||
let importIndex = 0;
|
||||
for (const _node of ast.body) {
|
||||
if (_node.type === "ExportAllDeclaration") {
|
||||
throw new Error(`automocking files with \`export *\` is not supported in browser mode because it cannot be statically analysed`);
|
||||
}
|
||||
if (_node.type === "ExportNamedDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
function traversePattern(expression) {
|
||||
// export const test = '1'
|
||||
if (expression.type === "Identifier") {
|
||||
allSpecifiers.push({ name: expression.name });
|
||||
} else if (expression.type === "ArrayPattern") {
|
||||
expression.elements.forEach((element) => {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
traversePattern(element);
|
||||
});
|
||||
} else if (expression.type === "ObjectPattern") {
|
||||
expression.properties.forEach((property) => {
|
||||
// export const { ...rest } = {}
|
||||
if (property.type === "RestElement") {
|
||||
traversePattern(property);
|
||||
} else if (property.type === "Property") {
|
||||
traversePattern(property.value);
|
||||
} else ;
|
||||
});
|
||||
} else if (expression.type === "RestElement") {
|
||||
traversePattern(expression.argument);
|
||||
} else if (expression.type === "AssignmentPattern") {
|
||||
throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`);
|
||||
} else if (expression.type === "MemberExpression") {
|
||||
throw new Error(`MemberExpression is not supported. Please open a new bug report.`);
|
||||
} else ;
|
||||
}
|
||||
if (declaration) {
|
||||
if (declaration.type === "FunctionDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else if (declaration.type === "VariableDeclaration") {
|
||||
declaration.declarations.forEach((declaration) => {
|
||||
traversePattern(declaration.id);
|
||||
});
|
||||
} else if (declaration.type === "ClassDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else ;
|
||||
m.remove(node.start, declaration.start);
|
||||
}
|
||||
const specifiers = node.specifiers || [];
|
||||
const source = node.source;
|
||||
if (!source && specifiers.length) {
|
||||
specifiers.forEach((specifier) => {
|
||||
allSpecifiers.push({
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported),
|
||||
name: getArbitraryModuleIdentifier(specifier.local)
|
||||
});
|
||||
});
|
||||
m.remove(node.start, node.end);
|
||||
} else if (source && specifiers.length) {
|
||||
const importNames = [];
|
||||
specifiers.forEach((specifier) => {
|
||||
const importedName = `__vitest_imported_${importIndex++}__`;
|
||||
importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]);
|
||||
allSpecifiers.push({
|
||||
name: importedName,
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported)
|
||||
});
|
||||
});
|
||||
const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`;
|
||||
m.overwrite(node.start, node.end, importString);
|
||||
}
|
||||
}
|
||||
if (_node.type === "ExportDefaultDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
allSpecifiers.push({
|
||||
name: "__vitest_default",
|
||||
alias: "default"
|
||||
});
|
||||
m.overwrite(node.start, declaration.start, `const __vitest_default = `);
|
||||
}
|
||||
}
|
||||
const moduleObject = `
|
||||
const __vitest_current_es_module__ = {
|
||||
__esModule: true,
|
||||
${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")}
|
||||
}
|
||||
const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}")
|
||||
`;
|
||||
const assigning = allSpecifiers.map(({ name }, index) => {
|
||||
return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`;
|
||||
}).join("\n");
|
||||
const redeclarations = allSpecifiers.map(({ name, alias }, index) => {
|
||||
return ` __vitest_mocked_${index}__ as ${alias || name},`;
|
||||
}).join("\n");
|
||||
const specifiersExports = `
|
||||
export {
|
||||
${redeclarations}
|
||||
}
|
||||
`;
|
||||
m.append(moduleObject + assigning + specifiersExports);
|
||||
return m;
|
||||
}
|
||||
|
||||
export { automockModule as a, esmWalker as e };
|
||||
15
node_modules/@vitest/mocker/dist/chunk-interceptor-native.js
generated
vendored
Normal file
15
node_modules/@vitest/mocker/dist/chunk-interceptor-native.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { r as rpc } from './chunk-mocker.js';
|
||||
|
||||
class ModuleMockerServerInterceptor {
|
||||
async register(module) {
|
||||
await rpc("vitest:interceptor:register", module.toJSON());
|
||||
}
|
||||
async delete(id) {
|
||||
await rpc("vitest:interceptor:delete", id);
|
||||
}
|
||||
async invalidate() {
|
||||
await rpc("vitest:interceptor:invalidate");
|
||||
}
|
||||
}
|
||||
|
||||
export { ModuleMockerServerInterceptor as M };
|
||||
521
node_modules/@vitest/mocker/dist/chunk-mocker.js
generated
vendored
Normal file
521
node_modules/@vitest/mocker/dist/chunk-mocker.js
generated
vendored
Normal file
@@ -0,0 +1,521 @@
|
||||
import { mockObject } from './index.js';
|
||||
import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js';
|
||||
import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
|
||||
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
|
||||
function extractLocation(urlLike) {
|
||||
// Fail-fast but return locations like "(native)"
|
||||
if (!urlLike.includes(":")) {
|
||||
return [urlLike];
|
||||
}
|
||||
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
|
||||
const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
|
||||
if (!parts) {
|
||||
return [urlLike];
|
||||
}
|
||||
let url = parts[1];
|
||||
if (url.startsWith("async ")) {
|
||||
url = url.slice(6);
|
||||
}
|
||||
if (url.startsWith("http:") || url.startsWith("https:")) {
|
||||
const urlObj = new URL(url);
|
||||
urlObj.searchParams.delete("import");
|
||||
urlObj.searchParams.delete("browserv");
|
||||
url = urlObj.pathname + urlObj.hash + urlObj.search;
|
||||
}
|
||||
if (url.startsWith("/@fs/")) {
|
||||
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
|
||||
url = url.slice(isWindows ? 5 : 4);
|
||||
}
|
||||
return [
|
||||
url,
|
||||
parts[2] || undefined,
|
||||
parts[3] || undefined
|
||||
];
|
||||
}
|
||||
function parseSingleFFOrSafariStack(raw) {
|
||||
let line = raw.trim();
|
||||
if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
|
||||
return null;
|
||||
}
|
||||
if (line.includes(" > eval")) {
|
||||
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
|
||||
}
|
||||
// Early return for lines that don't look like Firefox/Safari stack traces
|
||||
// Firefox/Safari stack traces must contain '@' and should have location info after it
|
||||
if (!line.includes("@")) {
|
||||
return null;
|
||||
}
|
||||
// Find the correct @ that separates function name from location
|
||||
// For cases like '@https://@fs/path' or 'functionName@https://@fs/path'
|
||||
// we need to find the first @ that precedes a valid location (containing :)
|
||||
let atIndex = -1;
|
||||
let locationPart = "";
|
||||
let functionName;
|
||||
// Try each @ from left to right to find the one that gives us a valid location
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
if (line[i] === "@") {
|
||||
const candidateLocation = line.slice(i + 1);
|
||||
// Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1")
|
||||
if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
|
||||
atIndex = i;
|
||||
locationPart = candidateLocation;
|
||||
functionName = i > 0 ? line.slice(0, i) : undefined;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Validate we found a valid location with minimum length (filename:line format)
|
||||
if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
|
||||
return null;
|
||||
}
|
||||
const [url, lineNumber, columnNumber] = extractLocation(locationPart);
|
||||
if (!url || !lineNumber || !columnNumber) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
file: url,
|
||||
method: functionName || "",
|
||||
line: Number.parseInt(lineNumber),
|
||||
column: Number.parseInt(columnNumber)
|
||||
};
|
||||
}
|
||||
function parseSingleStack(raw) {
|
||||
const line = raw.trim();
|
||||
if (!CHROME_IE_STACK_REGEXP.test(line)) {
|
||||
return parseSingleFFOrSafariStack(line);
|
||||
}
|
||||
return parseSingleV8Stack(line);
|
||||
}
|
||||
// Based on https://github.com/stacktracejs/error-stack-parser
|
||||
// Credit to stacktracejs
|
||||
function parseSingleV8Stack(raw) {
|
||||
let line = raw.trim();
|
||||
if (!CHROME_IE_STACK_REGEXP.test(line)) {
|
||||
return null;
|
||||
}
|
||||
if (line.includes("(eval ")) {
|
||||
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
|
||||
}
|
||||
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
|
||||
// capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in
|
||||
// case it has spaces in it, as the string is split on \s+ later on
|
||||
const location = sanitizedLine.match(/ (\(.+\)$)/);
|
||||
// remove the parenthesized location from the line, if it was matched
|
||||
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
|
||||
// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
|
||||
// because this line doesn't have function name
|
||||
const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
|
||||
let method = location && sanitizedLine || "";
|
||||
let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url;
|
||||
if (!file || !lineNumber || !columnNumber) {
|
||||
return null;
|
||||
}
|
||||
if (method.startsWith("async ")) {
|
||||
method = method.slice(6);
|
||||
}
|
||||
if (file.startsWith("file://")) {
|
||||
file = file.slice(7);
|
||||
}
|
||||
// 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, "");
|
||||
}
|
||||
return {
|
||||
method,
|
||||
file,
|
||||
line: Number.parseInt(lineNumber),
|
||||
column: Number.parseInt(columnNumber)
|
||||
};
|
||||
}
|
||||
|
||||
function createCompilerHints(options) {
|
||||
const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__";
|
||||
function _mocker() {
|
||||
// @ts-expect-error injected by the plugin
|
||||
return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) {
|
||||
throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`);
|
||||
} });
|
||||
}
|
||||
return {
|
||||
hoisted(factory) {
|
||||
if (typeof factory !== "function") {
|
||||
throw new TypeError(`vi.hoisted() expects a function, but received a ${typeof factory}`);
|
||||
}
|
||||
return factory();
|
||||
},
|
||||
mock(path, factory) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
const importer = getImporter("mock");
|
||||
_mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory);
|
||||
},
|
||||
unmock(path) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
_mocker().queueUnmock(path, getImporter("unmock"));
|
||||
},
|
||||
doMock(path, factory) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
const importer = getImporter("doMock");
|
||||
_mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory);
|
||||
},
|
||||
doUnmock(path) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
|
||||
}
|
||||
_mocker().queueUnmock(path, getImporter("doUnmock"));
|
||||
},
|
||||
async importActual(path) {
|
||||
return _mocker().importActual(path, getImporter("importActual"));
|
||||
},
|
||||
async importMock(path) {
|
||||
return _mocker().importMock(path, getImporter("importMock"));
|
||||
}
|
||||
};
|
||||
}
|
||||
function getImporter(name) {
|
||||
const stackTrace = /* @__PURE__ */ createSimpleStackTrace({ stackTraceLimit: 5 });
|
||||
const stackArray = stackTrace.split("\n");
|
||||
// if there is no message in a stack trace, use the item - 1
|
||||
const importerStackIndex = stackArray.findIndex((stack) => {
|
||||
return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
|
||||
});
|
||||
const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]);
|
||||
return (stack === null || stack === void 0 ? void 0 : stack.file) || "";
|
||||
}
|
||||
|
||||
const hot = import.meta.hot || {
|
||||
on: warn,
|
||||
off: warn,
|
||||
send: warn
|
||||
};
|
||||
function warn() {
|
||||
console.warn("Vitest mocker cannot work if Vite didn't establish WS connection.");
|
||||
}
|
||||
function rpc(event, data) {
|
||||
hot.send(event, data);
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error(`Failed to resolve ${event} in time`));
|
||||
}, 5e3);
|
||||
hot.on(`${event}:result`, function r(data) {
|
||||
resolve(data);
|
||||
clearTimeout(timeout);
|
||||
hot.off(`${event}:result`, r);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const { now } = Date;
|
||||
class ModuleMocker {
|
||||
registry = new MockerRegistry();
|
||||
queue = new Set();
|
||||
mockedIds = new Set();
|
||||
constructor(interceptor, rpc, createMockInstance, config) {
|
||||
this.interceptor = interceptor;
|
||||
this.rpc = rpc;
|
||||
this.createMockInstance = createMockInstance;
|
||||
this.config = config;
|
||||
}
|
||||
async prepare() {
|
||||
if (!this.queue.size) {
|
||||
return;
|
||||
}
|
||||
await Promise.all([...this.queue.values()]);
|
||||
}
|
||||
async resolveFactoryModule(id) {
|
||||
const mock = this.registry.get(id);
|
||||
if (!mock || mock.type !== "manual") {
|
||||
throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
const result = await mock.resolve();
|
||||
return result;
|
||||
}
|
||||
getFactoryModule(id) {
|
||||
const mock = this.registry.get(id);
|
||||
if (!mock || mock.type !== "manual") {
|
||||
throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
if (!mock.cache) {
|
||||
throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
}
|
||||
return mock.cache;
|
||||
}
|
||||
async invalidate() {
|
||||
const ids = Array.from(this.mockedIds);
|
||||
if (!ids.length) {
|
||||
return;
|
||||
}
|
||||
await this.rpc.invalidate(ids);
|
||||
await this.interceptor.invalidate();
|
||||
this.registry.clear();
|
||||
}
|
||||
async importActual(id, importer) {
|
||||
const resolved = await this.rpc.resolveId(id, importer);
|
||||
if (resolved == null) {
|
||||
throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
|
||||
}
|
||||
const ext = extname(resolved.id);
|
||||
const url = new URL(resolved.url, location.href);
|
||||
const query = `_vitest_original&ext${ext}`;
|
||||
const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`;
|
||||
return this.wrapDynamicImport(() => import(
|
||||
/* @vite-ignore */
|
||||
actualUrl
|
||||
)).then((mod) => {
|
||||
if (!resolved.optimized || typeof mod.default === "undefined") {
|
||||
return mod;
|
||||
}
|
||||
// vite injects this helper for optimized modules, so we try to follow the same behavior
|
||||
const m = mod.default;
|
||||
return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : {
|
||||
...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
|
||||
default: m
|
||||
};
|
||||
});
|
||||
}
|
||||
async importMock(rawId, importer) {
|
||||
await this.prepare();
|
||||
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
|
||||
let mock = this.registry.get(mockUrl);
|
||||
if (!mock) {
|
||||
if (redirectUrl) {
|
||||
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
|
||||
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
|
||||
} else {
|
||||
mock = new AutomockedModule(rawId, resolvedId, mockUrl);
|
||||
}
|
||||
}
|
||||
if (mock.type === "manual") {
|
||||
return await mock.resolve();
|
||||
}
|
||||
if (mock.type === "automock" || mock.type === "autospy") {
|
||||
const url = new URL(`/@id/${resolvedId}`, location.href);
|
||||
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`;
|
||||
const moduleObject = await import(
|
||||
/* @vite-ignore */
|
||||
`${url.pathname}${query}&mock=${mock.type}${url.hash}`
|
||||
);
|
||||
return this.mockObject(moduleObject, mock.type);
|
||||
}
|
||||
return import(
|
||||
/* @vite-ignore */
|
||||
mock.redirect
|
||||
);
|
||||
}
|
||||
mockObject(object, moduleType = "automock") {
|
||||
return mockObject({
|
||||
globalConstructors: {
|
||||
Object,
|
||||
Function,
|
||||
Array,
|
||||
Map,
|
||||
RegExp
|
||||
},
|
||||
createMockInstance: this.createMockInstance,
|
||||
type: moduleType
|
||||
}, object);
|
||||
}
|
||||
queueMock(rawId, importer, factoryOrOptions) {
|
||||
const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
|
||||
this.mockedIds.add(resolvedId);
|
||||
const factory = typeof factoryOrOptions === "function" ? async () => {
|
||||
const data = await factoryOrOptions();
|
||||
// vite wraps all external modules that have "needsInterop" in a function that
|
||||
// merges all exports from default into the module object
|
||||
return needsInterop ? { default: data } : data;
|
||||
} : undefined;
|
||||
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null;
|
||||
let module;
|
||||
if (mockType === "manual") {
|
||||
module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
|
||||
} else if (mockType === "autospy") {
|
||||
module = this.registry.register("autospy", rawId, resolvedId, mockUrl);
|
||||
} else if (mockType === "redirect") {
|
||||
module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect);
|
||||
} else {
|
||||
module = this.registry.register("automock", rawId, resolvedId, mockUrl);
|
||||
}
|
||||
await this.interceptor.register(module);
|
||||
}).finally(() => {
|
||||
this.queue.delete(promise);
|
||||
});
|
||||
this.queue.add(promise);
|
||||
}
|
||||
queueUnmock(id, importer) {
|
||||
const promise = this.rpc.resolveId(id, importer).then(async (resolved) => {
|
||||
if (!resolved) {
|
||||
return;
|
||||
}
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolved.url));
|
||||
this.mockedIds.add(resolved.id);
|
||||
this.registry.delete(mockUrl);
|
||||
await this.interceptor.delete(mockUrl);
|
||||
}).finally(() => {
|
||||
this.queue.delete(promise);
|
||||
});
|
||||
this.queue.add(promise);
|
||||
}
|
||||
// We need to await mock registration before importing the actual module
|
||||
// In case there is a mocked module in the import chain
|
||||
wrapDynamicImport(moduleFactory) {
|
||||
if (typeof moduleFactory === "function") {
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
this.prepare().finally(() => {
|
||||
moduleFactory().then(resolve, reject);
|
||||
});
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
return moduleFactory;
|
||||
}
|
||||
resolveMockPath(path) {
|
||||
const config = this.config;
|
||||
const fsRoot = join("/@fs/", config.root);
|
||||
// URL can be /file/path.js, but path is resolved to /file/path
|
||||
if (path.startsWith(config.root)) {
|
||||
return path.slice(config.root.length);
|
||||
}
|
||||
if (path.startsWith(fsRoot)) {
|
||||
return path.slice(fsRoot.length);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
const versionRegexp = /(\?|&)v=\w{8}/;
|
||||
function cleanVersion(url) {
|
||||
return url.replace(versionRegexp, "");
|
||||
}
|
||||
|
||||
export { ModuleMocker as M, createCompilerHints as c, hot as h, rpc as r };
|
||||
174
node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
174
node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
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 _EXTNAME_RE = /.(\.[^./]+|\.)$/;
|
||||
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 extname = function(p) {
|
||||
if (p === "..") return "";
|
||||
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
|
||||
return match && match[1] || "";
|
||||
};
|
||||
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) ? "/" : ".");
|
||||
};
|
||||
const basename = function(p, extension) {
|
||||
const segments = normalizeWindowsPath(p).split("/");
|
||||
let lastSegment = "";
|
||||
for (let i = segments.length - 1; i >= 0; i--) {
|
||||
const val = segments[i];
|
||||
if (val) {
|
||||
lastSegment = val;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
|
||||
};
|
||||
|
||||
export { basename as b, dirname as d, extname as e, isAbsolute as i, join as j, resolve as r };
|
||||
185
node_modules/@vitest/mocker/dist/chunk-registry.js
generated
vendored
Normal file
185
node_modules/@vitest/mocker/dist/chunk-registry.js
generated
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
class MockerRegistry {
|
||||
registryByUrl = new Map();
|
||||
registryById = new Map();
|
||||
clear() {
|
||||
this.registryByUrl.clear();
|
||||
this.registryById.clear();
|
||||
}
|
||||
keys() {
|
||||
return this.registryByUrl.keys();
|
||||
}
|
||||
add(mock) {
|
||||
this.registryByUrl.set(mock.url, mock);
|
||||
this.registryById.set(mock.id, mock);
|
||||
}
|
||||
register(typeOrEvent, raw, id, url, factoryOrRedirect) {
|
||||
const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent;
|
||||
if (typeof typeOrEvent === "object") {
|
||||
const event = typeOrEvent;
|
||||
if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) {
|
||||
throw new TypeError(`[vitest] Cannot register a mock that is already defined. ` + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". ` + `Use "registry.add()" to update a mock instead.`);
|
||||
}
|
||||
if (event.type === "automock") {
|
||||
const module = AutomockedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "autospy") {
|
||||
const module = AutospiedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "redirect") {
|
||||
const module = RedirectedModule.fromJSON(event);
|
||||
this.add(module);
|
||||
return module;
|
||||
} else if (event.type === "manual") {
|
||||
throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`);
|
||||
} else {
|
||||
throw new Error(`Unknown mock type: ${event.type}`);
|
||||
}
|
||||
}
|
||||
if (typeof raw !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require a raw string.");
|
||||
}
|
||||
if (typeof url !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require a url string.");
|
||||
}
|
||||
if (typeof id !== "string") {
|
||||
throw new TypeError("[vitest] Mocks require an id string.");
|
||||
}
|
||||
if (type === "manual") {
|
||||
if (typeof factoryOrRedirect !== "function") {
|
||||
throw new TypeError("[vitest] Manual mocks require a factory function.");
|
||||
}
|
||||
const mock = new ManualMockedModule(raw, id, url, factoryOrRedirect);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else if (type === "automock" || type === "autospy") {
|
||||
const mock = type === "automock" ? new AutomockedModule(raw, id, url) : new AutospiedModule(raw, id, url);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else if (type === "redirect") {
|
||||
if (typeof factoryOrRedirect !== "string") {
|
||||
throw new TypeError("[vitest] Redirect mocks require a redirect string.");
|
||||
}
|
||||
const mock = new RedirectedModule(raw, id, url, factoryOrRedirect);
|
||||
this.add(mock);
|
||||
return mock;
|
||||
} else {
|
||||
throw new Error(`[vitest] Unknown mock type: ${type}`);
|
||||
}
|
||||
}
|
||||
delete(id) {
|
||||
this.registryByUrl.delete(id);
|
||||
}
|
||||
deleteById(id) {
|
||||
this.registryById.delete(id);
|
||||
}
|
||||
get(id) {
|
||||
return this.registryByUrl.get(id);
|
||||
}
|
||||
getById(id) {
|
||||
return this.registryById.get(id);
|
||||
}
|
||||
has(id) {
|
||||
return this.registryByUrl.has(id);
|
||||
}
|
||||
}
|
||||
class AutomockedModule {
|
||||
type = "automock";
|
||||
constructor(raw, id, url) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new AutospiedModule(data.raw, data.id, data.url);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
raw: this.raw,
|
||||
id: this.id
|
||||
};
|
||||
}
|
||||
}
|
||||
class AutospiedModule {
|
||||
type = "autospy";
|
||||
constructor(raw, id, url) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new AutospiedModule(data.raw, data.id, data.url);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
id: this.id,
|
||||
raw: this.raw
|
||||
};
|
||||
}
|
||||
}
|
||||
class RedirectedModule {
|
||||
type = "redirect";
|
||||
constructor(raw, id, url, redirect) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
this.redirect = redirect;
|
||||
}
|
||||
static fromJSON(data) {
|
||||
return new RedirectedModule(data.raw, data.id, data.url, data.redirect);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
raw: this.raw,
|
||||
id: this.id,
|
||||
redirect: this.redirect
|
||||
};
|
||||
}
|
||||
}
|
||||
class ManualMockedModule {
|
||||
cache;
|
||||
type = "manual";
|
||||
constructor(raw, id, url, factory) {
|
||||
this.raw = raw;
|
||||
this.id = id;
|
||||
this.url = url;
|
||||
this.factory = factory;
|
||||
}
|
||||
async resolve() {
|
||||
if (this.cache) {
|
||||
return this.cache;
|
||||
}
|
||||
let exports$1;
|
||||
try {
|
||||
exports$1 = await this.factory();
|
||||
} catch (err) {
|
||||
const vitestError = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock");
|
||||
vitestError.cause = err;
|
||||
throw vitestError;
|
||||
}
|
||||
if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
|
||||
throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
|
||||
}
|
||||
return this.cache = exports$1;
|
||||
}
|
||||
static fromJSON(data, factory) {
|
||||
return new ManualMockedModule(data.raw, data.id, data.url, factory);
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
type: this.type,
|
||||
url: this.url,
|
||||
id: this.id,
|
||||
raw: this.raw
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b };
|
||||
16
node_modules/@vitest/mocker/dist/chunk-utils.js
generated
vendored
Normal file
16
node_modules/@vitest/mocker/dist/chunk-utils.js
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
const postfixRE = /[?#].*$/;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(postfixRE, "");
|
||||
}
|
||||
function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") {
|
||||
const source = `const module = globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");`;
|
||||
const keys = exports$1.map((name) => {
|
||||
if (name === "default") {
|
||||
return `export default module["default"];`;
|
||||
}
|
||||
return `export const ${name} = module["${name}"];`;
|
||||
}).join("\n");
|
||||
return `${source}\n${keys}`;
|
||||
}
|
||||
|
||||
export { cleanUrl as a, createManualModuleSource as c };
|
||||
25
node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts
generated
vendored
Normal file
25
node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
import './types.d-B8CCKmHt.js';
|
||||
|
||||
type Key = string | symbol;
|
||||
type CreateMockInstanceProcedure = (options?: {
|
||||
prototypeMembers?: (string | symbol)[];
|
||||
name?: string | symbol;
|
||||
originalImplementation?: (...args: any[]) => any;
|
||||
keepMembersImplementation?: boolean;
|
||||
}) => any;
|
||||
interface MockObjectOptions {
|
||||
type: "automock" | "autospy";
|
||||
globalConstructors: GlobalConstructors;
|
||||
createMockInstance: CreateMockInstanceProcedure;
|
||||
}
|
||||
declare function mockObject(options: MockObjectOptions, object: Record<Key, any>, mockExports?: Record<Key, any>): Record<Key, any>;
|
||||
interface GlobalConstructors {
|
||||
Object: ObjectConstructor;
|
||||
Function: FunctionConstructor;
|
||||
RegExp: RegExpConstructor;
|
||||
Array: ArrayConstructor;
|
||||
Map: MapConstructor;
|
||||
}
|
||||
|
||||
export { mockObject as m };
|
||||
export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M };
|
||||
2
node_modules/@vitest/mocker/dist/index.d.ts
generated
vendored
Normal file
2
node_modules/@vitest/mocker/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-C-sLYZi-.js';
|
||||
export { A as AutomockedModule, h as AutomockedModuleSerialized, f as AutospiedModule, i as AutospiedModuleSerialized, g as ManualMockedModule, j as ManualMockedModuleSerialized, a as MockedModule, k as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, l as RedirectedModuleSerialized, e as ServerIdResolution, S as ServerMockResolution } from './types.d-B8CCKmHt.js';
|
||||
185
node_modules/@vitest/mocker/dist/index.js
generated
vendored
Normal file
185
node_modules/@vitest/mocker/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js';
|
||||
|
||||
function mockObject(options, object, mockExports = {}) {
|
||||
const finalizers = new Array();
|
||||
const refs = new RefTracker();
|
||||
const define = (container, key, value) => {
|
||||
try {
|
||||
container[key] = value;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const createMock = (currentValue) => {
|
||||
if (!options.createMockInstance) {
|
||||
throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
|
||||
}
|
||||
const createMockInstance = options.createMockInstance;
|
||||
const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
|
||||
return createMockInstance({
|
||||
name: currentValue.name,
|
||||
prototypeMembers,
|
||||
originalImplementation: options.type === "autospy" ? currentValue : undefined,
|
||||
keepMembersImplementation: options.type === "autospy"
|
||||
});
|
||||
};
|
||||
const mockPropertiesOf = (container, newContainer) => {
|
||||
const containerType = getType(container);
|
||||
const isModule = containerType === "Module" || !!container.__esModule;
|
||||
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
|
||||
// Modules define their exports as getters. We want to process those.
|
||||
if (!isModule && descriptor.get) {
|
||||
try {
|
||||
if (options.type === "autospy") {
|
||||
Object.defineProperty(newContainer, property, descriptor);
|
||||
} else {
|
||||
Object.defineProperty(newContainer, property, {
|
||||
configurable: descriptor.configurable,
|
||||
enumerable: descriptor.enumerable,
|
||||
get: () => {},
|
||||
set: descriptor.set ? () => {} : undefined
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
continue;
|
||||
}
|
||||
// Skip special read-only props, we don't want to mess with those.
|
||||
if (isReadonlyProp(container[property], property)) {
|
||||
continue;
|
||||
}
|
||||
const value = container[property];
|
||||
// Special handling of references we've seen before to prevent infinite
|
||||
// recursion in circular objects.
|
||||
const refId = refs.getId(value);
|
||||
if (refId !== undefined) {
|
||||
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
|
||||
continue;
|
||||
}
|
||||
const type = getType(value);
|
||||
if (Array.isArray(value)) {
|
||||
if (options.type === "automock") {
|
||||
define(newContainer, property, []);
|
||||
} else {
|
||||
const array = value.map((value) => {
|
||||
if (value && typeof value === "object") {
|
||||
const newObject = {};
|
||||
mockPropertiesOf(value, newObject);
|
||||
return newObject;
|
||||
}
|
||||
if (typeof value === "function") {
|
||||
return createMock(value);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
define(newContainer, property, array);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const isFunction = type.includes("Function") && typeof value === "function";
|
||||
if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
|
||||
define(newContainer, property, value);
|
||||
continue;
|
||||
}
|
||||
// Sometimes this assignment fails for some unknown reason. If it does,
|
||||
// just move along.
|
||||
if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
|
||||
continue;
|
||||
}
|
||||
if (isFunction) {
|
||||
const mock = createMock(newContainer[property]);
|
||||
newContainer[property] = mock;
|
||||
}
|
||||
refs.track(value, newContainer[property]);
|
||||
mockPropertiesOf(value, newContainer[property]);
|
||||
}
|
||||
};
|
||||
const mockedObject = mockExports;
|
||||
mockPropertiesOf(object, mockedObject);
|
||||
// Plug together refs
|
||||
for (const finalizer of finalizers) {
|
||||
finalizer();
|
||||
}
|
||||
return mockedObject;
|
||||
}
|
||||
class RefTracker {
|
||||
idMap = new Map();
|
||||
mockedValueMap = new Map();
|
||||
getId(value) {
|
||||
return this.idMap.get(value);
|
||||
}
|
||||
getMockedValue(id) {
|
||||
return this.mockedValueMap.get(id);
|
||||
}
|
||||
track(originalValue, mockedValue) {
|
||||
const newId = this.idMap.size;
|
||||
this.idMap.set(originalValue, newId);
|
||||
this.mockedValueMap.set(newId, mockedValue);
|
||||
return newId;
|
||||
}
|
||||
}
|
||||
function getType(value) {
|
||||
return Object.prototype.toString.apply(value).slice(8, -1);
|
||||
}
|
||||
function isReadonlyProp(object, prop) {
|
||||
if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
|
||||
const typeName = getType(object);
|
||||
return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
|
||||
}
|
||||
if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
|
||||
return getType(object) === "RegExp";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getAllMockableProperties(obj, isModule, constructors) {
|
||||
const { Map, Object, Function, RegExp, Array } = constructors;
|
||||
const allProps = new Map();
|
||||
let curr = obj;
|
||||
do {
|
||||
// we don't need properties from these
|
||||
if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) {
|
||||
break;
|
||||
}
|
||||
collectOwnProperties(curr, (key) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(curr, key);
|
||||
if (descriptor) {
|
||||
allProps.set(key, {
|
||||
key,
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
});
|
||||
} while (curr = Object.getPrototypeOf(curr));
|
||||
// default is not specified in ownKeys, if module is interoped
|
||||
if (isModule && !allProps.has("default") && "default" in obj) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(obj, "default");
|
||||
if (descriptor) {
|
||||
allProps.set("default", {
|
||||
key: "default",
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
}
|
||||
return Array.from(allProps.values());
|
||||
}
|
||||
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 collectFunctionProperties(prototype) {
|
||||
const properties = new Set();
|
||||
collectOwnProperties(prototype, (prop) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
|
||||
if (!descriptor || descriptor.get) {
|
||||
return;
|
||||
}
|
||||
const type = getType(descriptor.value);
|
||||
if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
|
||||
properties.add(prop);
|
||||
}
|
||||
});
|
||||
return Array.from(properties);
|
||||
}
|
||||
|
||||
export { mockObject };
|
||||
81
node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts
generated
vendored
Normal file
81
node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
import { MaybeMockedDeep } from '@vitest/spy';
|
||||
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, M as MockerRegistry, d as MockedModuleType } from './types.d-B8CCKmHt.js';
|
||||
import { C as CreateMockInstanceProcedure } from './index.d-C-sLYZi-.js';
|
||||
|
||||
interface CompilerHintsOptions {
|
||||
/**
|
||||
* This is the key used to access the globalThis object in the worker.
|
||||
* Unlike `globalThisAccessor` in other APIs, this is not injected into the script.
|
||||
* ```ts
|
||||
* // globalThisKey: '__my_variable__' produces:
|
||||
* globalThis['__my_variable__']
|
||||
* // globalThisKey: '"__my_variable__"' produces:
|
||||
* globalThis['"__my_variable__"'] // notice double quotes
|
||||
* ```
|
||||
* @default '__vitest_mocker__'
|
||||
*/
|
||||
globalThisKey?: string;
|
||||
}
|
||||
interface ModuleMockerCompilerHints {
|
||||
hoisted: <T>(factory: () => T) => T;
|
||||
mock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
|
||||
unmock: (path: string | Promise<unknown>) => void;
|
||||
doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
|
||||
doUnmock: (path: string | Promise<unknown>) => void;
|
||||
importActual: <T>(path: string) => Promise<T>;
|
||||
importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>;
|
||||
}
|
||||
declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints;
|
||||
|
||||
interface ModuleMockerInterceptor {
|
||||
register: (module: MockedModule) => Promise<void>;
|
||||
delete: (url: string) => Promise<void>;
|
||||
invalidate: () => Promise<void>;
|
||||
}
|
||||
|
||||
declare class ModuleMocker {
|
||||
private interceptor;
|
||||
private rpc;
|
||||
private createMockInstance;
|
||||
private config;
|
||||
protected registry: MockerRegistry;
|
||||
private queue;
|
||||
private mockedIds;
|
||||
constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig);
|
||||
prepare(): Promise<void>;
|
||||
resolveFactoryModule(id: string): Promise<Record<string | symbol, any>>;
|
||||
getFactoryModule(id: string): any;
|
||||
invalidate(): Promise<void>;
|
||||
importActual<T>(id: string, importer: string): Promise<T>;
|
||||
importMock<T>(rawId: string, importer: string): Promise<T>;
|
||||
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
|
||||
private resolveMockPath;
|
||||
}
|
||||
interface ResolveIdResult {
|
||||
id: string;
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
interface ResolveMockResult {
|
||||
mockType: MockedModuleType;
|
||||
resolvedId: string;
|
||||
resolvedUrl: string;
|
||||
redirectUrl?: string | null;
|
||||
needsInterop?: boolean;
|
||||
}
|
||||
interface ModuleMockerRPC {
|
||||
invalidate: (ids: string[]) => Promise<void>;
|
||||
resolveId: (id: string, importer: string) => Promise<ResolveIdResult | null>;
|
||||
resolveMock: (id: string, importer: string, options: {
|
||||
mock: "spy" | "factory" | "auto";
|
||||
}) => Promise<ResolveMockResult>;
|
||||
}
|
||||
interface ModuleMockerConfig {
|
||||
root: string;
|
||||
}
|
||||
|
||||
export { ModuleMocker as b, createCompilerHints as c };
|
||||
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as d, ModuleMockerRPC as e, ResolveMockResult as f };
|
||||
800
node_modules/@vitest/mocker/dist/node.d.ts
generated
vendored
Normal file
800
node_modules/@vitest/mocker/dist/node.d.ts
generated
vendored
Normal file
@@ -0,0 +1,800 @@
|
||||
import { AutomockOptions } from './automock.js';
|
||||
export { automockModule } from './automock.js';
|
||||
import { Plugin, Rollup, ViteDevServer } from 'vite';
|
||||
import { SourceMap } from 'magic-string';
|
||||
import { M as MockerRegistry, S as ServerMockResolution, e as ServerIdResolution } from './types.d-B8CCKmHt.js';
|
||||
export { findMockRedirect } from './redirect.js';
|
||||
|
||||
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
|
||||
|
||||
declare function automockPlugin(options?: AutomockOptions): Plugin;
|
||||
|
||||
interface DynamicImportPluginOptions {
|
||||
/**
|
||||
* @default `"__vitest_mocker__"`
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
filter?: (id: string) => boolean;
|
||||
}
|
||||
declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin;
|
||||
|
||||
// This definition file follows a somewhat unusual format. ESTree allows
|
||||
// runtime type checks based on the `type` parameter. In order to explain this
|
||||
// to typescript we want to use discriminated union types:
|
||||
// https://github.com/Microsoft/TypeScript/pull/9163
|
||||
//
|
||||
// For ESTree this is a bit tricky because the high level interfaces like
|
||||
// Node or Function are pulling double duty. We want to pass common fields down
|
||||
// to the interfaces that extend them (like Identifier or
|
||||
// ArrowFunctionExpression), but you can't extend a type union or enforce
|
||||
// common fields on them. So we've split the high level interfaces into two
|
||||
// types, a base type which passes down inherited fields, and a type union of
|
||||
// all types which extend the base type. Only the type union is exported, and
|
||||
// the union is how other types refer to the collection of inheriting types.
|
||||
//
|
||||
// This makes the definitions file here somewhat more difficult to maintain,
|
||||
// but it has the notable advantage of making ESTree much easier to use as
|
||||
// an end user.
|
||||
|
||||
interface BaseNodeWithoutComments {
|
||||
// Every leaf interface that extends BaseNode must specify a type property.
|
||||
// The type property should be a string literal. For example, Identifier
|
||||
// has: `type: "Identifier"`
|
||||
type: string;
|
||||
loc?: SourceLocation | null | undefined;
|
||||
range?: [number, number] | undefined;
|
||||
}
|
||||
|
||||
interface BaseNode extends BaseNodeWithoutComments {
|
||||
leadingComments?: Comment[] | undefined;
|
||||
trailingComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface NodeMap {
|
||||
AssignmentProperty: AssignmentProperty;
|
||||
CatchClause: CatchClause;
|
||||
Class: Class;
|
||||
ClassBody: ClassBody;
|
||||
Expression: Expression;
|
||||
Function: Function;
|
||||
Identifier: Identifier;
|
||||
Literal: Literal;
|
||||
MethodDefinition: MethodDefinition;
|
||||
ModuleDeclaration: ModuleDeclaration;
|
||||
ModuleSpecifier: ModuleSpecifier;
|
||||
Pattern: Pattern;
|
||||
PrivateIdentifier: PrivateIdentifier;
|
||||
Program: Program;
|
||||
Property: Property;
|
||||
PropertyDefinition: PropertyDefinition;
|
||||
SpreadElement: SpreadElement;
|
||||
Statement: Statement;
|
||||
Super: Super;
|
||||
SwitchCase: SwitchCase;
|
||||
TemplateElement: TemplateElement;
|
||||
VariableDeclarator: VariableDeclarator;
|
||||
}
|
||||
|
||||
type Node$1 = NodeMap[keyof NodeMap];
|
||||
|
||||
interface Comment extends BaseNodeWithoutComments {
|
||||
type: "Line" | "Block";
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface SourceLocation {
|
||||
source?: string | null | undefined;
|
||||
start: Position;
|
||||
end: Position;
|
||||
}
|
||||
|
||||
interface Position {
|
||||
/** >= 1 */
|
||||
line: number;
|
||||
/** >= 0 */
|
||||
column: number;
|
||||
}
|
||||
|
||||
interface Program extends BaseNode {
|
||||
type: "Program";
|
||||
sourceType: "script" | "module";
|
||||
body: Array<Directive | Statement | ModuleDeclaration>;
|
||||
comments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface Directive extends BaseNode {
|
||||
type: "ExpressionStatement";
|
||||
expression: Literal;
|
||||
directive: string;
|
||||
}
|
||||
|
||||
interface BaseFunction extends BaseNode {
|
||||
params: Pattern[];
|
||||
generator?: boolean | undefined;
|
||||
async?: boolean | undefined;
|
||||
// The body is either BlockStatement or Expression because arrow functions
|
||||
// can have a body that's either. FunctionDeclarations and
|
||||
// FunctionExpressions have only BlockStatement bodies.
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
|
||||
|
||||
type Statement =
|
||||
| ExpressionStatement
|
||||
| BlockStatement
|
||||
| StaticBlock
|
||||
| EmptyStatement
|
||||
| DebuggerStatement
|
||||
| WithStatement
|
||||
| ReturnStatement
|
||||
| LabeledStatement
|
||||
| BreakStatement
|
||||
| ContinueStatement
|
||||
| IfStatement
|
||||
| SwitchStatement
|
||||
| ThrowStatement
|
||||
| TryStatement
|
||||
| WhileStatement
|
||||
| DoWhileStatement
|
||||
| ForStatement
|
||||
| ForInStatement
|
||||
| ForOfStatement
|
||||
| Declaration;
|
||||
|
||||
interface BaseStatement extends BaseNode {}
|
||||
|
||||
interface EmptyStatement extends BaseStatement {
|
||||
type: "EmptyStatement";
|
||||
}
|
||||
|
||||
interface BlockStatement extends BaseStatement {
|
||||
type: "BlockStatement";
|
||||
body: Statement[];
|
||||
innerComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface StaticBlock extends Omit<BlockStatement, "type"> {
|
||||
type: "StaticBlock";
|
||||
}
|
||||
|
||||
interface ExpressionStatement extends BaseStatement {
|
||||
type: "ExpressionStatement";
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
interface IfStatement extends BaseStatement {
|
||||
type: "IfStatement";
|
||||
test: Expression;
|
||||
consequent: Statement;
|
||||
alternate?: Statement | null | undefined;
|
||||
}
|
||||
|
||||
interface LabeledStatement extends BaseStatement {
|
||||
type: "LabeledStatement";
|
||||
label: Identifier;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BreakStatement extends BaseStatement {
|
||||
type: "BreakStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface ContinueStatement extends BaseStatement {
|
||||
type: "ContinueStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface WithStatement extends BaseStatement {
|
||||
type: "WithStatement";
|
||||
object: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface SwitchStatement extends BaseStatement {
|
||||
type: "SwitchStatement";
|
||||
discriminant: Expression;
|
||||
cases: SwitchCase[];
|
||||
}
|
||||
|
||||
interface ReturnStatement extends BaseStatement {
|
||||
type: "ReturnStatement";
|
||||
argument?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ThrowStatement extends BaseStatement {
|
||||
type: "ThrowStatement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface TryStatement extends BaseStatement {
|
||||
type: "TryStatement";
|
||||
block: BlockStatement;
|
||||
handler?: CatchClause | null | undefined;
|
||||
finalizer?: BlockStatement | null | undefined;
|
||||
}
|
||||
|
||||
interface WhileStatement extends BaseStatement {
|
||||
type: "WhileStatement";
|
||||
test: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface DoWhileStatement extends BaseStatement {
|
||||
type: "DoWhileStatement";
|
||||
body: Statement;
|
||||
test: Expression;
|
||||
}
|
||||
|
||||
interface ForStatement extends BaseStatement {
|
||||
type: "ForStatement";
|
||||
init?: VariableDeclaration | Expression | null | undefined;
|
||||
test?: Expression | null | undefined;
|
||||
update?: Expression | null | undefined;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BaseForXStatement extends BaseStatement {
|
||||
left: VariableDeclaration | Pattern;
|
||||
right: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface ForInStatement extends BaseForXStatement {
|
||||
type: "ForInStatement";
|
||||
}
|
||||
|
||||
interface DebuggerStatement extends BaseStatement {
|
||||
type: "DebuggerStatement";
|
||||
}
|
||||
|
||||
type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
|
||||
|
||||
interface BaseDeclaration extends BaseStatement {}
|
||||
|
||||
interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
|
||||
type: "FunctionDeclaration";
|
||||
/** It is null when a function declaration is a part of the `export default function` statement */
|
||||
id: Identifier | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface VariableDeclaration extends BaseDeclaration {
|
||||
type: "VariableDeclaration";
|
||||
declarations: VariableDeclarator[];
|
||||
kind: "var" | "let" | "const" | "using" | "await using";
|
||||
}
|
||||
|
||||
interface VariableDeclarator extends BaseNode {
|
||||
type: "VariableDeclarator";
|
||||
id: Pattern;
|
||||
init?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ExpressionMap {
|
||||
ArrayExpression: ArrayExpression;
|
||||
ArrowFunctionExpression: ArrowFunctionExpression;
|
||||
AssignmentExpression: AssignmentExpression;
|
||||
AwaitExpression: AwaitExpression;
|
||||
BinaryExpression: BinaryExpression;
|
||||
CallExpression: CallExpression;
|
||||
ChainExpression: ChainExpression;
|
||||
ClassExpression: ClassExpression;
|
||||
ConditionalExpression: ConditionalExpression;
|
||||
FunctionExpression: FunctionExpression;
|
||||
Identifier: Identifier;
|
||||
ImportExpression: ImportExpression;
|
||||
Literal: Literal;
|
||||
LogicalExpression: LogicalExpression;
|
||||
MemberExpression: MemberExpression;
|
||||
MetaProperty: MetaProperty;
|
||||
NewExpression: NewExpression;
|
||||
ObjectExpression: ObjectExpression;
|
||||
SequenceExpression: SequenceExpression;
|
||||
TaggedTemplateExpression: TaggedTemplateExpression;
|
||||
TemplateLiteral: TemplateLiteral;
|
||||
ThisExpression: ThisExpression;
|
||||
UnaryExpression: UnaryExpression;
|
||||
UpdateExpression: UpdateExpression;
|
||||
YieldExpression: YieldExpression;
|
||||
}
|
||||
|
||||
type Expression = ExpressionMap[keyof ExpressionMap];
|
||||
|
||||
interface BaseExpression extends BaseNode {}
|
||||
|
||||
type ChainElement = SimpleCallExpression | MemberExpression;
|
||||
|
||||
interface ChainExpression extends BaseExpression {
|
||||
type: "ChainExpression";
|
||||
expression: ChainElement;
|
||||
}
|
||||
|
||||
interface ThisExpression extends BaseExpression {
|
||||
type: "ThisExpression";
|
||||
}
|
||||
|
||||
interface ArrayExpression extends BaseExpression {
|
||||
type: "ArrayExpression";
|
||||
elements: Array<Expression | SpreadElement | null>;
|
||||
}
|
||||
|
||||
interface ObjectExpression extends BaseExpression {
|
||||
type: "ObjectExpression";
|
||||
properties: Array<Property | SpreadElement>;
|
||||
}
|
||||
|
||||
interface PrivateIdentifier extends BaseNode {
|
||||
type: "PrivateIdentifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Property extends BaseNode {
|
||||
type: "Property";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: Expression | Pattern; // Could be an AssignmentProperty
|
||||
kind: "init" | "get" | "set";
|
||||
method: boolean;
|
||||
shorthand: boolean;
|
||||
computed: boolean;
|
||||
}
|
||||
|
||||
interface PropertyDefinition extends BaseNode {
|
||||
type: "PropertyDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value?: Expression | null | undefined;
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface FunctionExpression extends BaseFunction, BaseExpression {
|
||||
id?: Identifier | null | undefined;
|
||||
type: "FunctionExpression";
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface SequenceExpression extends BaseExpression {
|
||||
type: "SequenceExpression";
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface UnaryExpression extends BaseExpression {
|
||||
type: "UnaryExpression";
|
||||
operator: UnaryOperator;
|
||||
prefix: true;
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface BinaryExpression extends BaseExpression {
|
||||
type: "BinaryExpression";
|
||||
operator: BinaryOperator;
|
||||
left: Expression | PrivateIdentifier;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface AssignmentExpression extends BaseExpression {
|
||||
type: "AssignmentExpression";
|
||||
operator: AssignmentOperator;
|
||||
left: Pattern | MemberExpression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface UpdateExpression extends BaseExpression {
|
||||
type: "UpdateExpression";
|
||||
operator: UpdateOperator;
|
||||
argument: Expression;
|
||||
prefix: boolean;
|
||||
}
|
||||
|
||||
interface LogicalExpression extends BaseExpression {
|
||||
type: "LogicalExpression";
|
||||
operator: LogicalOperator;
|
||||
left: Expression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface ConditionalExpression extends BaseExpression {
|
||||
type: "ConditionalExpression";
|
||||
test: Expression;
|
||||
alternate: Expression;
|
||||
consequent: Expression;
|
||||
}
|
||||
|
||||
interface BaseCallExpression extends BaseExpression {
|
||||
callee: Expression | Super;
|
||||
arguments: Array<Expression | SpreadElement>;
|
||||
}
|
||||
type CallExpression = SimpleCallExpression | NewExpression;
|
||||
|
||||
interface SimpleCallExpression extends BaseCallExpression {
|
||||
type: "CallExpression";
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
interface NewExpression extends BaseCallExpression {
|
||||
type: "NewExpression";
|
||||
}
|
||||
|
||||
interface MemberExpression extends BaseExpression, BasePattern {
|
||||
type: "MemberExpression";
|
||||
object: Expression | Super;
|
||||
property: Expression | PrivateIdentifier;
|
||||
computed: boolean;
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
|
||||
|
||||
interface BasePattern extends BaseNode {}
|
||||
|
||||
interface SwitchCase extends BaseNode {
|
||||
type: "SwitchCase";
|
||||
test?: Expression | null | undefined;
|
||||
consequent: Statement[];
|
||||
}
|
||||
|
||||
interface CatchClause extends BaseNode {
|
||||
type: "CatchClause";
|
||||
param: Pattern | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface Identifier extends BaseNode, BaseExpression, BasePattern {
|
||||
type: "Identifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
|
||||
|
||||
interface SimpleLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value: string | boolean | number | null;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface RegExpLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: RegExp | null | undefined;
|
||||
regex: {
|
||||
pattern: string;
|
||||
flags: string;
|
||||
};
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface BigIntLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: bigint | null | undefined;
|
||||
bigint: string;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
|
||||
|
||||
type BinaryOperator =
|
||||
| "=="
|
||||
| "!="
|
||||
| "==="
|
||||
| "!=="
|
||||
| "<"
|
||||
| "<="
|
||||
| ">"
|
||||
| ">="
|
||||
| "<<"
|
||||
| ">>"
|
||||
| ">>>"
|
||||
| "+"
|
||||
| "-"
|
||||
| "*"
|
||||
| "/"
|
||||
| "%"
|
||||
| "**"
|
||||
| "|"
|
||||
| "^"
|
||||
| "&"
|
||||
| "in"
|
||||
| "instanceof";
|
||||
|
||||
type LogicalOperator = "||" | "&&" | "??";
|
||||
|
||||
type AssignmentOperator =
|
||||
| "="
|
||||
| "+="
|
||||
| "-="
|
||||
| "*="
|
||||
| "/="
|
||||
| "%="
|
||||
| "**="
|
||||
| "<<="
|
||||
| ">>="
|
||||
| ">>>="
|
||||
| "|="
|
||||
| "^="
|
||||
| "&="
|
||||
| "||="
|
||||
| "&&="
|
||||
| "??=";
|
||||
|
||||
type UpdateOperator = "++" | "--";
|
||||
|
||||
interface ForOfStatement extends BaseForXStatement {
|
||||
type: "ForOfStatement";
|
||||
await: boolean;
|
||||
}
|
||||
|
||||
interface Super extends BaseNode {
|
||||
type: "Super";
|
||||
}
|
||||
|
||||
interface SpreadElement extends BaseNode {
|
||||
type: "SpreadElement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
|
||||
type: "ArrowFunctionExpression";
|
||||
expression: boolean;
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
interface YieldExpression extends BaseExpression {
|
||||
type: "YieldExpression";
|
||||
argument?: Expression | null | undefined;
|
||||
delegate: boolean;
|
||||
}
|
||||
|
||||
interface TemplateLiteral extends BaseExpression {
|
||||
type: "TemplateLiteral";
|
||||
quasis: TemplateElement[];
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface TaggedTemplateExpression extends BaseExpression {
|
||||
type: "TaggedTemplateExpression";
|
||||
tag: Expression;
|
||||
quasi: TemplateLiteral;
|
||||
}
|
||||
|
||||
interface TemplateElement extends BaseNode {
|
||||
type: "TemplateElement";
|
||||
tail: boolean;
|
||||
value: {
|
||||
/** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
|
||||
cooked?: string | null | undefined;
|
||||
raw: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AssignmentProperty extends Property {
|
||||
value: Pattern;
|
||||
kind: "init";
|
||||
method: boolean; // false
|
||||
}
|
||||
|
||||
interface ObjectPattern extends BasePattern {
|
||||
type: "ObjectPattern";
|
||||
properties: Array<AssignmentProperty | RestElement>;
|
||||
}
|
||||
|
||||
interface ArrayPattern extends BasePattern {
|
||||
type: "ArrayPattern";
|
||||
elements: Array<Pattern | null>;
|
||||
}
|
||||
|
||||
interface RestElement extends BasePattern {
|
||||
type: "RestElement";
|
||||
argument: Pattern;
|
||||
}
|
||||
|
||||
interface AssignmentPattern extends BasePattern {
|
||||
type: "AssignmentPattern";
|
||||
left: Pattern;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
type Class = ClassDeclaration | ClassExpression;
|
||||
interface BaseClass extends BaseNode {
|
||||
superClass?: Expression | null | undefined;
|
||||
body: ClassBody;
|
||||
}
|
||||
|
||||
interface ClassBody extends BaseNode {
|
||||
type: "ClassBody";
|
||||
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
|
||||
}
|
||||
|
||||
interface MethodDefinition extends BaseNode {
|
||||
type: "MethodDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: FunctionExpression;
|
||||
kind: "constructor" | "method" | "get" | "set";
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
|
||||
type: "ClassDeclaration";
|
||||
/** It is null when a class declaration is a part of the `export default class` statement */
|
||||
id: Identifier | null;
|
||||
}
|
||||
|
||||
interface ClassDeclaration extends MaybeNamedClassDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface ClassExpression extends BaseClass, BaseExpression {
|
||||
type: "ClassExpression";
|
||||
id?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface MetaProperty extends BaseExpression {
|
||||
type: "MetaProperty";
|
||||
meta: Identifier;
|
||||
property: Identifier;
|
||||
}
|
||||
|
||||
type ModuleDeclaration =
|
||||
| ImportDeclaration
|
||||
| ExportNamedDeclaration
|
||||
| ExportDefaultDeclaration
|
||||
| ExportAllDeclaration;
|
||||
interface BaseModuleDeclaration extends BaseNode {}
|
||||
|
||||
type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
|
||||
interface BaseModuleSpecifier extends BaseNode {
|
||||
local: Identifier;
|
||||
}
|
||||
|
||||
interface ImportDeclaration extends BaseModuleDeclaration {
|
||||
type: "ImportDeclaration";
|
||||
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface ImportSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportSpecifier";
|
||||
imported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ImportAttribute extends BaseNode {
|
||||
type: "ImportAttribute";
|
||||
key: Identifier | Literal;
|
||||
value: Literal;
|
||||
}
|
||||
|
||||
interface ImportExpression extends BaseExpression {
|
||||
type: "ImportExpression";
|
||||
source: Expression;
|
||||
options?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ImportDefaultSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportDefaultSpecifier";
|
||||
}
|
||||
|
||||
interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportNamespaceSpecifier";
|
||||
}
|
||||
|
||||
interface ExportNamedDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportNamedDeclaration";
|
||||
declaration?: Declaration | null | undefined;
|
||||
specifiers: ExportSpecifier[];
|
||||
attributes: ImportAttribute[];
|
||||
source?: Literal | null | undefined;
|
||||
}
|
||||
|
||||
interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
|
||||
type: "ExportSpecifier";
|
||||
local: Identifier | Literal;
|
||||
exported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ExportDefaultDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportDefaultDeclaration";
|
||||
declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
|
||||
}
|
||||
|
||||
interface ExportAllDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportAllDeclaration";
|
||||
exported: Identifier | Literal | null;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface AwaitExpression extends BaseExpression {
|
||||
type: "AwaitExpression";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
type Positioned<T> = T & {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
type Node = Positioned<Node$1>;
|
||||
|
||||
interface HoistMocksOptions {
|
||||
/**
|
||||
* List of modules that should always be imported before compiler hints.
|
||||
* @default 'vitest'
|
||||
*/
|
||||
hoistedModule?: string;
|
||||
/**
|
||||
* @default ["vi", "vitest"]
|
||||
*/
|
||||
utilsObjectNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock"]
|
||||
*/
|
||||
hoistableMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock", "doMock", "doUnmock"]
|
||||
*/
|
||||
dynamicImportMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["hoisted"]
|
||||
*/
|
||||
hoistedMethodNames?: string[];
|
||||
regexpHoistable?: RegExp;
|
||||
codeFrameGenerator?: CodeFrameGenerator;
|
||||
}
|
||||
interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistable"> {
|
||||
include?: string | RegExp | (string | RegExp)[];
|
||||
exclude?: string | RegExp | (string | RegExp)[];
|
||||
/**
|
||||
* overrides include/exclude options
|
||||
*/
|
||||
filter?: (id: string) => boolean;
|
||||
}
|
||||
declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin;
|
||||
interface HoistMocksResult {
|
||||
code: string;
|
||||
map: SourceMap;
|
||||
}
|
||||
interface CodeFrameGenerator {
|
||||
(node: Positioned<Node>, id: string, code: string): string;
|
||||
}
|
||||
declare function hoistMocks(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
|
||||
|
||||
interface InterceptorPluginOptions {
|
||||
/**
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
registry?: MockerRegistry;
|
||||
}
|
||||
declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin;
|
||||
|
||||
interface MockerPluginOptions extends AutomockOptions {
|
||||
hoistMocks?: HoistMocksPluginOptions;
|
||||
}
|
||||
declare function mockerPlugin(options?: MockerPluginOptions): Plugin[];
|
||||
|
||||
interface ServerResolverOptions {
|
||||
/**
|
||||
* @default ['/node_modules/']
|
||||
*/
|
||||
moduleDirectories?: string[];
|
||||
}
|
||||
declare class ServerMockResolver {
|
||||
private server;
|
||||
private options;
|
||||
constructor(server: ViteDevServer, options?: ServerResolverOptions);
|
||||
resolveMock(rawId: string, importer: string, options: {
|
||||
mock: "spy" | "factory" | "auto";
|
||||
}): Promise<ServerMockResolution>;
|
||||
invalidate(ids: string[]): void;
|
||||
resolveId(id: string, importer?: string): Promise<ServerIdResolution | null>;
|
||||
private normalizeResolveIdToUrl;
|
||||
private resolveMockId;
|
||||
private resolveModule;
|
||||
}
|
||||
|
||||
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions };
|
||||
967
node_modules/@vitest/mocker/dist/node.js
generated
vendored
Normal file
967
node_modules/@vitest/mocker/dist/node.js
generated
vendored
Normal file
@@ -0,0 +1,967 @@
|
||||
import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
|
||||
import { a as automockModule, e as esmWalker } from './chunk-automock.js';
|
||||
import MagicString from 'magic-string';
|
||||
import { createFilter } from 'vite';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path/posix';
|
||||
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { findMockRedirect } from './redirect.js';
|
||||
import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
|
||||
import 'estree-walker';
|
||||
import 'node:module';
|
||||
|
||||
function automockPlugin(options = {}) {
|
||||
return {
|
||||
name: "vitest:automock",
|
||||
enforce: "post",
|
||||
transform(code, id) {
|
||||
if (id.includes("mock=automock") || id.includes("mock=autospy")) {
|
||||
const mockType = id.includes("mock=automock") ? "automock" : "autospy";
|
||||
const ms = automockModule(code, mockType, this.parse, options);
|
||||
return {
|
||||
code: ms.toString(),
|
||||
map: ms.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const regexDynamicImport = /import\s*\(/;
|
||||
function dynamicImportPlugin(options = {}) {
|
||||
return {
|
||||
name: "vitest:browser:esm-injector",
|
||||
enforce: "post",
|
||||
transform(source, id) {
|
||||
// TODO: test is not called for static imports
|
||||
if (!regexDynamicImport.test(source)) {
|
||||
return;
|
||||
}
|
||||
if (options.filter && !options.filter(id)) {
|
||||
return;
|
||||
}
|
||||
return injectDynamicImport(source, id, this.parse, options);
|
||||
}
|
||||
};
|
||||
}
|
||||
function injectDynamicImport(code, id, parse, options = {}) {
|
||||
const s = new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (err) {
|
||||
console.error(`Cannot parse ${id}:\n${err.message}`);
|
||||
return;
|
||||
}
|
||||
// 3. convert references to import bindings & import.meta references
|
||||
esmWalker(ast, {
|
||||
onImportMeta() {
|
||||
// s.update(node.start, node.end, viImportMetaKey)
|
||||
},
|
||||
onDynamicImport(node) {
|
||||
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`;
|
||||
const importSubstring = code.substring(node.start, node.end);
|
||||
const hasIgnore = importSubstring.includes("/* @vite-ignore */");
|
||||
s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : ""));
|
||||
s.overwrite(node.end - 1, node.end, "))");
|
||||
}
|
||||
});
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: id
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
// AST walker module for ESTree compatible trees
|
||||
|
||||
|
||||
function makeTest(test) {
|
||||
if (typeof test === "string")
|
||||
{ return function (type) { return type === test; } }
|
||||
else if (!test)
|
||||
{ return function () { return true; } }
|
||||
else
|
||||
{ return test }
|
||||
}
|
||||
|
||||
var Found = function Found(node, state) { this.node = node; this.state = state; };
|
||||
|
||||
// Find the innermost node of a given type that contains the given
|
||||
// position. Interface similar to findNodeAt.
|
||||
function findNodeAround(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if (node.start > pos || node.end < pos) { return }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (test(type, node)) { throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
function skipThrough(node, st, c) { c(node, st); }
|
||||
function ignore(_node, _st, _c) {}
|
||||
|
||||
// Node walkers.
|
||||
|
||||
var base = {};
|
||||
|
||||
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var stmt = list[i];
|
||||
|
||||
c(stmt, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.Statement = skipThrough;
|
||||
base.EmptyStatement = ignore;
|
||||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
|
||||
function (node, st, c) { return c(node.expression, st, "Expression"); };
|
||||
base.IfStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Statement");
|
||||
if (node.alternate) { c(node.alternate, st, "Statement"); }
|
||||
};
|
||||
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
||||
base.BreakStatement = base.ContinueStatement = ignore;
|
||||
base.WithStatement = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.SwitchStatement = function (node, st, c) {
|
||||
c(node.discriminant, st, "Expression");
|
||||
for (var i = 0, list = node.cases; i < list.length; i += 1) {
|
||||
var cs = list[i];
|
||||
|
||||
c(cs, st);
|
||||
}
|
||||
};
|
||||
base.SwitchCase = function (node, st, c) {
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
|
||||
if (node.argument) { c(node.argument, st, "Expression"); }
|
||||
};
|
||||
base.ThrowStatement = base.SpreadElement =
|
||||
function (node, st, c) { return c(node.argument, st, "Expression"); };
|
||||
base.TryStatement = function (node, st, c) {
|
||||
c(node.block, st, "Statement");
|
||||
if (node.handler) { c(node.handler, st); }
|
||||
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
||||
};
|
||||
base.CatchClause = function (node, st, c) {
|
||||
if (node.param) { c(node.param, st, "Pattern"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForStatement = function (node, st, c) {
|
||||
if (node.init) { c(node.init, st, "ForInit"); }
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
if (node.update) { c(node.update, st, "Expression"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
|
||||
c(node.left, st, "ForInit");
|
||||
c(node.right, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInit = function (node, st, c) {
|
||||
if (node.type === "VariableDeclaration") { c(node, st); }
|
||||
else { c(node, st, "Expression"); }
|
||||
};
|
||||
base.DebuggerStatement = ignore;
|
||||
|
||||
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
||||
base.VariableDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
||||
{
|
||||
var decl = list[i];
|
||||
|
||||
c(decl, st);
|
||||
}
|
||||
};
|
||||
base.VariableDeclarator = function (node, st, c) {
|
||||
c(node.id, st, "Pattern");
|
||||
if (node.init) { c(node.init, st, "Expression"); }
|
||||
};
|
||||
|
||||
base.Function = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
for (var i = 0, list = node.params; i < list.length; i += 1)
|
||||
{
|
||||
var param = list[i];
|
||||
|
||||
c(param, st, "Pattern");
|
||||
}
|
||||
c(node.body, st, node.expression ? "Expression" : "Statement");
|
||||
};
|
||||
|
||||
base.Pattern = function (node, st, c) {
|
||||
if (node.type === "Identifier")
|
||||
{ c(node, st, "VariablePattern"); }
|
||||
else if (node.type === "MemberExpression")
|
||||
{ c(node, st, "MemberPattern"); }
|
||||
else
|
||||
{ c(node, st); }
|
||||
};
|
||||
base.VariablePattern = ignore;
|
||||
base.MemberPattern = skipThrough;
|
||||
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
||||
base.ArrayPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Pattern"); }
|
||||
}
|
||||
};
|
||||
base.ObjectPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
||||
var prop = list[i];
|
||||
|
||||
if (prop.type === "Property") {
|
||||
if (prop.computed) { c(prop.key, st, "Expression"); }
|
||||
c(prop.value, st, "Pattern");
|
||||
} else if (prop.type === "RestElement") {
|
||||
c(prop.argument, st, "Pattern");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
base.Expression = skipThrough;
|
||||
base.ThisExpression = base.Super = base.MetaProperty = ignore;
|
||||
base.ArrayExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Expression"); }
|
||||
}
|
||||
};
|
||||
base.ObjectExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1)
|
||||
{
|
||||
var prop = list[i];
|
||||
|
||||
c(prop, st);
|
||||
}
|
||||
};
|
||||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
|
||||
base.SequenceExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
||||
{
|
||||
var expr = list[i];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateLiteral = function (node, st, c) {
|
||||
for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
||||
{
|
||||
var quasi = list[i];
|
||||
|
||||
c(quasi, st);
|
||||
}
|
||||
|
||||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var expr = list$1[i$1];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateElement = ignore;
|
||||
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
|
||||
c(node.argument, st, "Expression");
|
||||
};
|
||||
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
|
||||
c(node.left, st, "Expression");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
|
||||
c(node.left, st, "Pattern");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.ConditionalExpression = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Expression");
|
||||
c(node.alternate, st, "Expression");
|
||||
};
|
||||
base.NewExpression = base.CallExpression = function (node, st, c) {
|
||||
c(node.callee, st, "Expression");
|
||||
if (node.arguments)
|
||||
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
||||
{
|
||||
var arg = list[i];
|
||||
|
||||
c(arg, st, "Expression");
|
||||
} }
|
||||
};
|
||||
base.MemberExpression = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
if (node.computed) { c(node.property, st, "Expression"); }
|
||||
};
|
||||
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
|
||||
if (node.declaration)
|
||||
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
||||
if (node.source) { c(node.source, st, "Expression"); }
|
||||
};
|
||||
base.ExportAllDeclaration = function (node, st, c) {
|
||||
if (node.exported)
|
||||
{ c(node.exported, st); }
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
||||
{
|
||||
var spec = list[i];
|
||||
|
||||
c(spec, st);
|
||||
}
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportExpression = function (node, st, c) {
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
|
||||
|
||||
base.TaggedTemplateExpression = function (node, st, c) {
|
||||
c(node.tag, st, "Expression");
|
||||
c(node.quasi, st, "Expression");
|
||||
};
|
||||
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
||||
base.Class = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
if (node.superClass) { c(node.superClass, st, "Expression"); }
|
||||
c(node.body, st);
|
||||
};
|
||||
base.ClassBody = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var elt = list[i];
|
||||
|
||||
c(elt, st);
|
||||
}
|
||||
};
|
||||
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
|
||||
if (node.computed) { c(node.key, st, "Expression"); }
|
||||
if (node.value) { c(node.value, st, "Expression"); }
|
||||
};
|
||||
|
||||
function hoistMocksPlugin(options = {}) {
|
||||
const filter = options.filter || createFilter(options.include, options.exclude);
|
||||
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
|
||||
"mock",
|
||||
"unmock",
|
||||
"doMock",
|
||||
"doUnmock"
|
||||
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options;
|
||||
const methods = new Set([
|
||||
...hoistableMockMethodNames,
|
||||
...hoistedMethodNames,
|
||||
...dynamicImportMockMethodNames
|
||||
]);
|
||||
const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`);
|
||||
return {
|
||||
name: "vitest:mocks",
|
||||
enforce: "post",
|
||||
transform(code, id) {
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
return hoistMocks(code, id, this.parse, {
|
||||
regexpHoistable,
|
||||
hoistableMockMethodNames,
|
||||
hoistedMethodNames,
|
||||
utilsObjectNames,
|
||||
dynamicImportMockMethodNames,
|
||||
...options
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
|
||||
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
|
||||
To fix this issue you can either:
|
||||
- import the mocks API directly from 'vitest'
|
||||
- enable the 'globals' options`;
|
||||
function API_NOT_FOUND_CHECK(names) {
|
||||
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
|
||||
}
|
||||
function isIdentifier(node) {
|
||||
return node.type === "Identifier";
|
||||
}
|
||||
function getNodeTail(code, node) {
|
||||
let end = node.end;
|
||||
if (code[node.end] === ";") {
|
||||
end += 1;
|
||||
}
|
||||
if (code[node.end] === "\n") {
|
||||
return end + 1;
|
||||
}
|
||||
if (code[node.end + 1] === "\n") {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
|
||||
const hashbangRE = /^#!.*\n/;
|
||||
// this is a fork of Vite SSR transform
|
||||
function hoistMocks(code, id, parse, options = {}) {
|
||||
var _hashbangRE$exec;
|
||||
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
|
||||
if (!needHoisting) {
|
||||
return;
|
||||
}
|
||||
const s = new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (err) {
|
||||
console.error(`Cannot parse ${id}:\n${err.message}.`);
|
||||
return;
|
||||
}
|
||||
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
|
||||
"mock",
|
||||
"unmock",
|
||||
"doMock",
|
||||
"doUnmock"
|
||||
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
|
||||
// hoist at the start of the file, after the hashbang
|
||||
let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0;
|
||||
let hoistedModuleImported = false;
|
||||
let uid = 0;
|
||||
const idToImportMap = new Map();
|
||||
const imports = [];
|
||||
// this will transform import statements into dynamic ones, if there are imports
|
||||
// it will keep the import as is, if we don't need to mock anything
|
||||
// in browser environment it will wrap the module value with "vitest_wrap_module" function
|
||||
// that returns a proxy to the module so that named exports can be mocked
|
||||
function defineImport(importNode) {
|
||||
const source = importNode.source.value;
|
||||
// always hoist vitest import to top of the file, so
|
||||
// "vi" helpers can access it
|
||||
if (hoistedModule === source) {
|
||||
hoistedModuleImported = true;
|
||||
return;
|
||||
}
|
||||
const importId = `__vi_import_${uid++}__`;
|
||||
imports.push({
|
||||
id: importId,
|
||||
node: importNode
|
||||
});
|
||||
return importId;
|
||||
}
|
||||
// 1. check all import statements and record id -> importName map
|
||||
for (const node of ast.body) {
|
||||
// import foo from 'foo' --> foo -> __import_foo__.default
|
||||
// import { baz } from 'foo' --> baz -> __import_foo__.baz
|
||||
// import * as ok from 'foo' --> ok -> __import_foo__
|
||||
if (node.type === "ImportDeclaration") {
|
||||
const importId = defineImport(node);
|
||||
if (!importId) {
|
||||
continue;
|
||||
}
|
||||
for (const spec of node.specifiers) {
|
||||
if (spec.type === "ImportSpecifier") {
|
||||
if (spec.imported.type === "Identifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
|
||||
} else {
|
||||
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
|
||||
}
|
||||
} else if (spec.type === "ImportDefaultSpecifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.default`);
|
||||
} else {
|
||||
// namespace specifier
|
||||
idToImportMap.set(spec.local.name, importId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const declaredConst = new Set();
|
||||
const hoistedNodes = [];
|
||||
function createSyntaxError(node, message) {
|
||||
const _error = new SyntaxError(message);
|
||||
Error.captureStackTrace(_error, createSyntaxError);
|
||||
const serializedError = {
|
||||
name: "SyntaxError",
|
||||
message: _error.message,
|
||||
stack: _error.stack
|
||||
};
|
||||
if (options.codeFrameGenerator) {
|
||||
serializedError.frame = options.codeFrameGenerator(node, id, code);
|
||||
}
|
||||
return serializedError;
|
||||
}
|
||||
function assertNotDefaultExport(node, error) {
|
||||
var _findNodeAround;
|
||||
const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node;
|
||||
if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) {
|
||||
throw createSyntaxError(defaultExport, error);
|
||||
}
|
||||
}
|
||||
function assertNotNamedExport(node, error) {
|
||||
var _findNodeAround2;
|
||||
const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node;
|
||||
if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) {
|
||||
throw createSyntaxError(nodeExported, error);
|
||||
}
|
||||
}
|
||||
function getVariableDeclaration(node) {
|
||||
var _findNodeAround3, _declarationNode$decl;
|
||||
const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node;
|
||||
const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init;
|
||||
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
|
||||
return declarationNode;
|
||||
}
|
||||
}
|
||||
const usedUtilityExports = new Set();
|
||||
esmWalker(ast, {
|
||||
onIdentifier(id, info, parentStack) {
|
||||
const binding = idToImportMap.get(id.name);
|
||||
if (!binding) {
|
||||
return;
|
||||
}
|
||||
if (info.hasBindingShortcut) {
|
||||
s.appendLeft(id.end, `: ${binding}`);
|
||||
} else if (info.classDeclaration) {
|
||||
if (!declaredConst.has(id.name)) {
|
||||
declaredConst.add(id.name);
|
||||
// locate the top-most node containing the class declaration
|
||||
const topNode = parentStack[parentStack.length - 2];
|
||||
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
|
||||
}
|
||||
} else if (!info.classExpression) {
|
||||
s.update(id.start, id.end, binding);
|
||||
}
|
||||
},
|
||||
onCallExpression(node) {
|
||||
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
|
||||
const methodName = node.callee.property.name;
|
||||
usedUtilityExports.add(node.callee.object.name);
|
||||
if (hoistableMockMethodNames.includes(methodName)) {
|
||||
const method = `${node.callee.object.name}.${methodName}`;
|
||||
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
}
|
||||
// rewrite vi.mock(import('..')) into vi.mock('..')
|
||||
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
// vi.mock(import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
const source = moduleInfo.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
// vi.mock(await import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
const source = moduleInfo.argument.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
hoistedNodes.push(node);
|
||||
} else if (dynamicImportMockMethodNames.includes(methodName)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
let source = null;
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
source = moduleInfo.source;
|
||||
}
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
source = moduleInfo.argument.source;
|
||||
}
|
||||
if (source) {
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
if (hoistedMethodNames.includes(methodName)) {
|
||||
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
// hoist "const variable = vi.hoisted(() => {})"
|
||||
hoistedNodes.push(declarationNode);
|
||||
} else {
|
||||
var _findNodeAround4;
|
||||
const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node;
|
||||
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
|
||||
const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node;
|
||||
hoistedNodes.push(moveNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
function getNodeName(node) {
|
||||
const callee = node.callee || {};
|
||||
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
|
||||
return `${callee.object.name}.${callee.property.name}()`;
|
||||
}
|
||||
return "\"hoisted method\"";
|
||||
}
|
||||
function getNodeCall(node) {
|
||||
if (node.type === "CallExpression") {
|
||||
return node;
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
const { declarations } = node;
|
||||
const init = declarations[0].init;
|
||||
if (init) {
|
||||
return getNodeCall(init);
|
||||
}
|
||||
}
|
||||
if (node.type === "AwaitExpression") {
|
||||
const { argument } = node;
|
||||
if (argument.type === "CallExpression") {
|
||||
return getNodeCall(argument);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function createError(outsideNode, insideNode) {
|
||||
const outsideCall = getNodeCall(outsideNode);
|
||||
const insideCall = getNodeCall(insideNode);
|
||||
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
|
||||
}
|
||||
// validate hoistedNodes doesn't have nodes inside other nodes
|
||||
for (let i = 0; i < hoistedNodes.length; i++) {
|
||||
const node = hoistedNodes[i];
|
||||
for (let j = i + 1; j < hoistedNodes.length; j++) {
|
||||
const otherNode = hoistedNodes[j];
|
||||
if (node.start >= otherNode.start && node.end <= otherNode.end) {
|
||||
throw createError(otherNode, node);
|
||||
}
|
||||
if (otherNode.start >= node.start && otherNode.end <= node.end) {
|
||||
throw createError(node, otherNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
// hoist vi.mock/vi.hoisted
|
||||
for (const node of hoistedNodes) {
|
||||
const end = getNodeTail(code, node);
|
||||
// don't hoist into itself if it's already at the top
|
||||
if (hoistIndex === end || hoistIndex === node.start) {
|
||||
hoistIndex = end;
|
||||
} else {
|
||||
s.move(node.start, end, hoistIndex);
|
||||
}
|
||||
}
|
||||
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
|
||||
for (const { node: importNode, id: importId } of imports) {
|
||||
const source = importNode.source.value;
|
||||
s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`);
|
||||
if (importNode.start === hoistIndex) {
|
||||
// no need to hoist, but update hoistIndex to keep the order
|
||||
hoistIndex = importNode.end;
|
||||
} else {
|
||||
// There will be an error if the module is called before it is imported,
|
||||
// so the module import statement is hoisted to the top
|
||||
s.move(importNode.start, importNode.end, hoistIndex);
|
||||
}
|
||||
}
|
||||
if (!hoistedModuleImported && hoistedNodes.length) {
|
||||
const utilityImports = [...usedUtilityExports];
|
||||
// "vi" or "vitest" is imported from a module other than "vitest"
|
||||
if (utilityImports.some((name) => idToImportMap.has(name))) {
|
||||
s.prepend(API_NOT_FOUND_CHECK(utilityImports));
|
||||
} else if (utilityImports.length) {
|
||||
s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: id
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function interceptorPlugin(options = {}) {
|
||||
const registry = options.registry || new MockerRegistry();
|
||||
return {
|
||||
name: "vitest:mocks:interceptor",
|
||||
enforce: "pre",
|
||||
load: {
|
||||
order: "pre",
|
||||
async handler(id) {
|
||||
const mock = registry.getById(id);
|
||||
if (!mock) {
|
||||
return;
|
||||
}
|
||||
if (mock.type === "manual") {
|
||||
const exports$1 = Object.keys(await mock.resolve());
|
||||
const accessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
return createManualModuleSource(mock.url, exports$1, accessor);
|
||||
}
|
||||
if (mock.type === "redirect") {
|
||||
return readFile(mock.redirect, "utf-8");
|
||||
}
|
||||
}
|
||||
},
|
||||
transform: {
|
||||
order: "post",
|
||||
handler(code, id) {
|
||||
const mock = registry.getById(id);
|
||||
if (!mock) {
|
||||
return;
|
||||
}
|
||||
if (mock.type === "automock" || mock.type === "autospy") {
|
||||
const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor });
|
||||
return {
|
||||
code: m.toString(),
|
||||
map: m.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
configureServer(server) {
|
||||
server.ws.on("vitest:interceptor:register", (event) => {
|
||||
if (event.type === "manual") {
|
||||
const module = ManualMockedModule.fromJSON(event, async () => {
|
||||
const keys = await getFactoryExports(event.url);
|
||||
return Object.fromEntries(keys.map((key) => [key, null]));
|
||||
});
|
||||
registry.add(module);
|
||||
} else {
|
||||
if (event.type === "redirect") {
|
||||
const redirectUrl = new URL(event.redirect);
|
||||
event.redirect = join(server.config.root, redirectUrl.pathname);
|
||||
}
|
||||
registry.register(event);
|
||||
}
|
||||
server.ws.send("vitest:interceptor:register:result");
|
||||
});
|
||||
server.ws.on("vitest:interceptor:delete", (id) => {
|
||||
registry.delete(id);
|
||||
server.ws.send("vitest:interceptor:delete:result");
|
||||
});
|
||||
server.ws.on("vitest:interceptor:invalidate", () => {
|
||||
registry.clear();
|
||||
server.ws.send("vitest:interceptor:invalidate:result");
|
||||
});
|
||||
function getFactoryExports(url) {
|
||||
server.ws.send("vitest:interceptor:resolve", url);
|
||||
let timeout;
|
||||
return new Promise((resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(`Timeout while waiting for factory exports of ${url}`));
|
||||
}, 1e4);
|
||||
server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => {
|
||||
if (resolvedUrl === url) {
|
||||
clearTimeout(timeout);
|
||||
resolve(keys);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const VALID_ID_PREFIX = "/@id/";
|
||||
class ServerMockResolver {
|
||||
constructor(server, options = {}) {
|
||||
this.server = server;
|
||||
this.options = options;
|
||||
}
|
||||
async resolveMock(rawId, importer, options) {
|
||||
const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
|
||||
const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
|
||||
if (options.mock === "factory") {
|
||||
var _manifest$fsPath;
|
||||
const manifest = getViteDepsManifest(this.server.config);
|
||||
const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false;
|
||||
return {
|
||||
mockType: "manual",
|
||||
resolvedId: id,
|
||||
resolvedUrl,
|
||||
needsInterop
|
||||
};
|
||||
}
|
||||
if (options.mock === "spy") {
|
||||
return {
|
||||
mockType: "autospy",
|
||||
resolvedId: id,
|
||||
resolvedUrl
|
||||
};
|
||||
}
|
||||
const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external);
|
||||
return {
|
||||
mockType: redirectUrl === null ? "automock" : "redirect",
|
||||
redirectUrl,
|
||||
resolvedId: id,
|
||||
resolvedUrl
|
||||
};
|
||||
}
|
||||
invalidate(ids) {
|
||||
ids.forEach((id) => {
|
||||
const moduleGraph = this.server.moduleGraph;
|
||||
const module = moduleGraph.getModuleById(id);
|
||||
if (module) {
|
||||
module.transformResult = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
async resolveId(id, importer) {
|
||||
const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false });
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
return this.normalizeResolveIdToUrl(resolved);
|
||||
}
|
||||
normalizeResolveIdToUrl(resolved) {
|
||||
const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir));
|
||||
let url;
|
||||
// normalise the URL to be acceptable by the browser
|
||||
// https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103
|
||||
const root = this.server.config.root;
|
||||
if (resolved.id.startsWith(withTrailingSlash(root))) {
|
||||
url = resolved.id.slice(root.length);
|
||||
} else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) {
|
||||
url = join$1("/@fs/", resolved.id);
|
||||
} else {
|
||||
url = resolved.id;
|
||||
}
|
||||
if (url[0] !== "." && url[0] !== "/") {
|
||||
url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__");
|
||||
}
|
||||
return {
|
||||
id: resolved.id,
|
||||
url,
|
||||
optimized: isOptimized
|
||||
};
|
||||
}
|
||||
async resolveMockId(rawId, importer) {
|
||||
if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) {
|
||||
importer = join$1(this.server.config.root, importer);
|
||||
}
|
||||
const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false });
|
||||
return this.resolveModule(rawId, resolved);
|
||||
}
|
||||
resolveModule(rawId, resolved) {
|
||||
const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId;
|
||||
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
|
||||
return {
|
||||
id,
|
||||
fsPath: cleanUrl(id),
|
||||
external
|
||||
};
|
||||
}
|
||||
}
|
||||
function isModuleDirectory(config, path) {
|
||||
const moduleDirectories = config.moduleDirectories || ["/node_modules/"];
|
||||
return moduleDirectories.some((dir) => path.includes(dir));
|
||||
}
|
||||
const metadata = new WeakMap();
|
||||
function getViteDepsManifest(config) {
|
||||
if (metadata.has(config)) {
|
||||
return metadata.get(config);
|
||||
}
|
||||
const cacheDirPath = getDepsCacheDir(config);
|
||||
const metadataPath = resolve(cacheDirPath, "_metadata.json");
|
||||
if (!existsSync(metadataPath)) {
|
||||
return null;
|
||||
}
|
||||
const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8"));
|
||||
const newManifest = {};
|
||||
for (const name in optimized) {
|
||||
const dep = optimized[name];
|
||||
const file = resolve(cacheDirPath, dep.file);
|
||||
newManifest[file] = {
|
||||
hash: dep.fileHash,
|
||||
needsInterop: dep.needsInterop
|
||||
};
|
||||
}
|
||||
metadata.set(config, newManifest);
|
||||
return newManifest;
|
||||
}
|
||||
function getDepsCacheDir(config) {
|
||||
return resolve(config.cacheDir, "deps");
|
||||
}
|
||||
function withTrailingSlash(path) {
|
||||
if (path.at(-1) !== "/") {
|
||||
return `${path}/`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// this is an implementation for public usage
|
||||
// vitest doesn't use this plugin directly
|
||||
function mockerPlugin(options = {}) {
|
||||
let server;
|
||||
const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url)));
|
||||
return [
|
||||
{
|
||||
name: "vitest:mocker:ws-rpc",
|
||||
config(_, { command }) {
|
||||
if (command !== "serve") {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
server: { preTransformRequests: false },
|
||||
optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] }
|
||||
};
|
||||
},
|
||||
configureServer(server_) {
|
||||
server = server_;
|
||||
const mockResolver = new ServerMockResolver(server);
|
||||
server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => {
|
||||
const resolved = await mockResolver.resolveId(id, importer);
|
||||
server.ws.send("vitest:mocks:resolvedId:result", resolved);
|
||||
});
|
||||
server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => {
|
||||
const resolved = await mockResolver.resolveMock(id, importer, options);
|
||||
server.ws.send("vitest:mocks:resolveMock:result", resolved);
|
||||
});
|
||||
server.ws.on("vitest:mocks:invalidate", async ({ ids }) => {
|
||||
mockResolver.invalidate(ids);
|
||||
server.ws.send("vitest:mocks:invalidate:result");
|
||||
});
|
||||
},
|
||||
async load(id) {
|
||||
if (id !== registerPath) {
|
||||
return;
|
||||
}
|
||||
if (!server) {
|
||||
// mocker doesn't work during build
|
||||
return "export {}";
|
||||
}
|
||||
const content = await readFile(registerPath, "utf-8");
|
||||
const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root));
|
||||
return result;
|
||||
}
|
||||
},
|
||||
hoistMocksPlugin(options.hoistMocks),
|
||||
interceptorPlugin(options),
|
||||
automockPlugin(options),
|
||||
dynamicImportPlugin(options)
|
||||
];
|
||||
}
|
||||
|
||||
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
3
node_modules/@vitest/mocker/dist/redirect.d.ts
generated
vendored
Normal file
3
node_modules/@vitest/mocker/dist/redirect.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare function findMockRedirect(root: string, mockPath: string, external: string | null): string | null;
|
||||
|
||||
export { findMockRedirect };
|
||||
79
node_modules/@vitest/mocker/dist/redirect.js
generated
vendored
Normal file
79
node_modules/@vitest/mocker/dist/redirect.js
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import fs from 'node:fs';
|
||||
import nodeModule from 'node:module';
|
||||
import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
const { existsSync, readdirSync, statSync } = fs;
|
||||
function findMockRedirect(root, mockPath, external) {
|
||||
const path = external || mockPath;
|
||||
// it's a node_module alias
|
||||
// all mocks should be inside <root>/__mocks__
|
||||
if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
|
||||
const mockDirname = dirname(path);
|
||||
const mockFolder = join(root, "__mocks__", mockDirname);
|
||||
if (!existsSync(mockFolder)) {
|
||||
return null;
|
||||
}
|
||||
const baseOriginal = basename(path);
|
||||
function findFile(mockFolder, baseOriginal) {
|
||||
const files = readdirSync(mockFolder);
|
||||
for (const file of files) {
|
||||
const baseFile = basename(file, extname(file));
|
||||
if (baseFile === baseOriginal) {
|
||||
const path = resolve(mockFolder, file);
|
||||
// if the same name, return the file
|
||||
if (statSync(path).isFile()) {
|
||||
return path;
|
||||
} else {
|
||||
// find folder/index.{js,ts}
|
||||
const indexFile = findFile(path, "index");
|
||||
if (indexFile) {
|
||||
return indexFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return findFile(mockFolder, baseOriginal);
|
||||
}
|
||||
const dir = dirname(path);
|
||||
const baseId = basename(path);
|
||||
const fullPath = resolve(dir, "__mocks__", baseId);
|
||||
return existsSync(fullPath) ? fullPath : null;
|
||||
}
|
||||
const builtins = new Set([
|
||||
...nodeModule.builtinModules,
|
||||
"assert/strict",
|
||||
"diagnostics_channel",
|
||||
"dns/promises",
|
||||
"fs/promises",
|
||||
"path/posix",
|
||||
"path/win32",
|
||||
"readline/promises",
|
||||
"stream/consumers",
|
||||
"stream/promises",
|
||||
"stream/web",
|
||||
"timers/promises",
|
||||
"util/types",
|
||||
"wasi"
|
||||
]);
|
||||
// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
|
||||
const prefixedBuiltins = new Set([
|
||||
"node:sea",
|
||||
"node:sqlite",
|
||||
"node:test",
|
||||
"node:test/reporters"
|
||||
]);
|
||||
const NODE_BUILTIN_NAMESPACE = "node:";
|
||||
function isNodeBuiltin(id) {
|
||||
// Added in v18.6.0
|
||||
if (nodeModule.isBuiltin) {
|
||||
return nodeModule.isBuiltin(id);
|
||||
}
|
||||
if (prefixedBuiltins.has(id)) {
|
||||
return true;
|
||||
}
|
||||
return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id);
|
||||
}
|
||||
|
||||
export { findMockRedirect };
|
||||
9
node_modules/@vitest/mocker/dist/register.d.ts
generated
vendored
Normal file
9
node_modules/@vitest/mocker/dist/register.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js';
|
||||
import '@vitest/spy';
|
||||
import './types.d-B8CCKmHt.js';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
|
||||
declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints;
|
||||
declare function registerNativeFactoryResolver(mocker: ModuleMocker): void;
|
||||
|
||||
export { registerModuleMocker, registerNativeFactoryResolver };
|
||||
41
node_modules/@vitest/mocker/dist/register.js
generated
vendored
Normal file
41
node_modules/@vitest/mocker/dist/register.js
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
import { createMockInstance } from '@vitest/spy';
|
||||
import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
function registerModuleMocker(interceptor) {
|
||||
const mocker = new ModuleMocker(interceptor(__VITEST_GLOBAL_THIS_ACCESSOR__), {
|
||||
resolveId(id, importer) {
|
||||
return rpc("vitest:mocks:resolveId", {
|
||||
id,
|
||||
importer
|
||||
});
|
||||
},
|
||||
resolveMock(id, importer, options) {
|
||||
return rpc("vitest:mocks:resolveMock", {
|
||||
id,
|
||||
importer,
|
||||
options
|
||||
});
|
||||
},
|
||||
async invalidate(ids) {
|
||||
return rpc("vitest:mocks:invalidate", { ids });
|
||||
}
|
||||
}, createMockInstance, { root: __VITEST_MOCKER_ROOT__ });
|
||||
globalThis[__VITEST_GLOBAL_THIS_ACCESSOR__] = mocker;
|
||||
registerNativeFactoryResolver(mocker);
|
||||
return createCompilerHints({ globalThisKey: __VITEST_GLOBAL_THIS_ACCESSOR__ });
|
||||
}
|
||||
function registerNativeFactoryResolver(mocker) {
|
||||
hot.on("vitest:interceptor:resolve", async (url) => {
|
||||
const exports$1 = await mocker.resolveFactoryModule(url);
|
||||
const keys = Object.keys(exports$1);
|
||||
hot.send("vitest:interceptor:resolved", {
|
||||
url,
|
||||
keys
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export { registerModuleMocker, registerNativeFactoryResolver };
|
||||
107
node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts
generated
vendored
Normal file
107
node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
declare class MockerRegistry {
|
||||
private readonly registryByUrl;
|
||||
private readonly registryById;
|
||||
clear(): void;
|
||||
keys(): IterableIterator<string>;
|
||||
add(mock: MockedModule): void;
|
||||
register(json: MockedModuleSerialized): MockedModule;
|
||||
register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule;
|
||||
register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule;
|
||||
register(type: "automock", raw: string, id: string, url: string): AutomockedModule;
|
||||
register(type: "autospy", id: string, raw: string, url: string): AutospiedModule;
|
||||
delete(id: string): void;
|
||||
deleteById(id: string): void;
|
||||
get(id: string): MockedModule | undefined;
|
||||
getById(id: string): MockedModule | undefined;
|
||||
has(id: string): boolean;
|
||||
}
|
||||
type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule;
|
||||
type MockedModuleType = "automock" | "autospy" | "manual" | "redirect";
|
||||
type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized;
|
||||
declare class AutomockedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "automock";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutomockedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutomockedModuleSerialized;
|
||||
}
|
||||
interface AutomockedModuleSerialized {
|
||||
type: "automock";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class AutospiedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "autospy";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutospiedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutospiedModuleSerialized;
|
||||
}
|
||||
interface AutospiedModuleSerialized {
|
||||
type: "autospy";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class RedirectedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
redirect: string;
|
||||
readonly type = "redirect";
|
||||
constructor(raw: string, id: string, url: string, redirect: string);
|
||||
static fromJSON(data: RedirectedModuleSerialized): RedirectedModule;
|
||||
toJSON(): RedirectedModuleSerialized;
|
||||
}
|
||||
interface RedirectedModuleSerialized {
|
||||
type: "redirect";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
redirect: string;
|
||||
}
|
||||
declare class ManualMockedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
factory: () => any;
|
||||
cache: Record<string | symbol, any> | undefined;
|
||||
readonly type = "manual";
|
||||
constructor(raw: string, id: string, url: string, factory: () => any);
|
||||
resolve(): Promise<Record<string | symbol, any>>;
|
||||
static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule;
|
||||
toJSON(): ManualMockedModuleSerialized;
|
||||
}
|
||||
interface ManualMockedModuleSerialized {
|
||||
type: "manual";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
}
|
||||
|
||||
type Awaitable<T> = T | PromiseLike<T>;
|
||||
type ModuleMockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Awaitable<Partial<M>>;
|
||||
type ModuleMockFactory = () => any;
|
||||
interface ModuleMockOptions {
|
||||
spy?: boolean;
|
||||
}
|
||||
interface ServerMockResolution {
|
||||
mockType: "manual" | "redirect" | "automock" | "autospy";
|
||||
resolvedId: string;
|
||||
resolvedUrl: string;
|
||||
needsInterop?: boolean;
|
||||
redirectUrl?: string | null;
|
||||
}
|
||||
interface ServerIdResolution {
|
||||
id: string;
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as f, ManualMockedModule as g };
|
||||
export type { ServerMockResolution as S, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ServerIdResolution as e, AutomockedModuleSerialized as h, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as j, MockedModuleSerialized as k, RedirectedModuleSerialized as l, ModuleMockFactory as m };
|
||||
86
node_modules/@vitest/mocker/package.json
generated
vendored
Normal file
86
node_modules/@vitest/mocker/package.json
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"name": "@vitest/mocker",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Vitest module mocker implementation",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/mocker"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./node": {
|
||||
"types": "./dist/node.d.ts",
|
||||
"default": "./dist/node.js"
|
||||
},
|
||||
"./browser": {
|
||||
"types": "./dist/browser.d.ts",
|
||||
"default": "./dist/browser.js"
|
||||
},
|
||||
"./redirect": {
|
||||
"types": "./dist/redirect.d.ts",
|
||||
"default": "./dist/redirect.js"
|
||||
},
|
||||
"./automock": {
|
||||
"types": "./dist/automock.d.ts",
|
||||
"default": "./dist/automock.js"
|
||||
},
|
||||
"./register": {
|
||||
"types": "./dist/register.d.ts",
|
||||
"default": "./dist/register.js"
|
||||
},
|
||||
"./auto-register": {
|
||||
"types": "./dist/register.d.ts",
|
||||
"default": "./dist/register.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9",
|
||||
"vite": "^6.0.0 || ^7.0.0-0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^0.30.21",
|
||||
"@vitest/spy": "4.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/estree": "^1.0.8",
|
||||
"acorn-walk": "^8.3.4",
|
||||
"msw": "^2.12.3",
|
||||
"pathe": "^2.0.3",
|
||||
"vite": "^6.3.5",
|
||||
"@vitest/spy": "4.0.15",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
21
node_modules/@vitest/pretty-format/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/pretty-format/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
124
node_modules/@vitest/pretty-format/dist/index.d.ts
generated
vendored
Normal file
124
node_modules/@vitest/pretty-format/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* 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 Colors {
|
||||
comment: {
|
||||
close: string;
|
||||
open: string;
|
||||
};
|
||||
content: {
|
||||
close: string;
|
||||
open: string;
|
||||
};
|
||||
prop: {
|
||||
close: string;
|
||||
open: string;
|
||||
};
|
||||
tag: {
|
||||
close: string;
|
||||
open: string;
|
||||
};
|
||||
value: {
|
||||
close: string;
|
||||
open: string;
|
||||
};
|
||||
}
|
||||
type Indent = (arg0: string) => string;
|
||||
type Refs = Array<unknown>;
|
||||
type Print = (arg0: unknown) => string;
|
||||
type Theme = Required<{
|
||||
comment?: string;
|
||||
content?: string;
|
||||
prop?: string;
|
||||
tag?: string;
|
||||
value?: string;
|
||||
}>;
|
||||
/**
|
||||
* compare function used when sorting object keys, `null` can be used to skip over sorting.
|
||||
*/
|
||||
type CompareKeys = ((a: string, b: string) => number) | null | undefined;
|
||||
type RequiredOptions = Required<PrettyFormatOptions>;
|
||||
interface Options extends Omit<RequiredOptions, "compareKeys" | "theme"> {
|
||||
compareKeys: CompareKeys;
|
||||
theme: Theme;
|
||||
}
|
||||
interface PrettyFormatOptions {
|
||||
callToJSON?: boolean;
|
||||
escapeRegex?: boolean;
|
||||
escapeString?: boolean;
|
||||
highlight?: boolean;
|
||||
indent?: number;
|
||||
maxDepth?: number;
|
||||
maxWidth?: number;
|
||||
min?: boolean;
|
||||
printBasicPrototype?: boolean;
|
||||
printFunctionName?: boolean;
|
||||
printShadowRoot?: boolean;
|
||||
compareKeys?: CompareKeys;
|
||||
plugins?: Plugins;
|
||||
}
|
||||
type OptionsReceived = PrettyFormatOptions;
|
||||
interface Config {
|
||||
callToJSON: boolean;
|
||||
compareKeys: CompareKeys;
|
||||
colors: Colors;
|
||||
escapeRegex: boolean;
|
||||
escapeString: boolean;
|
||||
indent: string;
|
||||
maxDepth: number;
|
||||
maxWidth: number;
|
||||
min: boolean;
|
||||
plugins: Plugins;
|
||||
printBasicPrototype: boolean;
|
||||
printFunctionName: boolean;
|
||||
printShadowRoot: boolean;
|
||||
spacingInner: string;
|
||||
spacingOuter: string;
|
||||
}
|
||||
type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
|
||||
type Test = (arg0: any) => boolean;
|
||||
interface NewPlugin {
|
||||
serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
|
||||
test: Test;
|
||||
}
|
||||
interface PluginOptions {
|
||||
edgeSpacing: string;
|
||||
min: boolean;
|
||||
spacing: string;
|
||||
}
|
||||
interface OldPlugin {
|
||||
print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string;
|
||||
test: Test;
|
||||
}
|
||||
type Plugin = NewPlugin | OldPlugin;
|
||||
type Plugins = Array<Plugin>;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
declare const DEFAULT_OPTIONS: Options;
|
||||
/**
|
||||
* Returns a presentation string of your `val` object
|
||||
* @param val any potential JavaScript object
|
||||
* @param options Custom settings
|
||||
*/
|
||||
declare function format(val: unknown, options?: OptionsReceived): string;
|
||||
declare const plugins: {
|
||||
AsymmetricMatcher: NewPlugin;
|
||||
DOMCollection: NewPlugin;
|
||||
DOMElement: NewPlugin;
|
||||
Immutable: NewPlugin;
|
||||
ReactElement: NewPlugin;
|
||||
ReactTestComponent: NewPlugin;
|
||||
Error: NewPlugin;
|
||||
};
|
||||
|
||||
export { DEFAULT_OPTIONS, format, plugins };
|
||||
export type { Colors, CompareKeys, Config, NewPlugin, OldPlugin, Options, OptionsReceived, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme };
|
||||
1018
node_modules/@vitest/pretty-format/dist/index.js
generated
vendored
Normal file
1018
node_modules/@vitest/pretty-format/dist/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
44
node_modules/@vitest/pretty-format/package.json
generated
vendored
Normal file
44
node_modules/@vitest/pretty-format/package.json
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@vitest/pretty-format",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Fork of pretty-format with support for ESM",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/pretty-format"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"dependencies": {
|
||||
"tinyrainbow": "^3.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react-is": "^19.2.0",
|
||||
"react-is": "^19.2.0",
|
||||
"react-is-18": "npm:react-is@18.3.1"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
21
node_modules/@vitest/runner/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/runner/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
5
node_modules/@vitest/runner/README.md
generated
vendored
Normal file
5
node_modules/@vitest/runner/README.md
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# @vitest/runner
|
||||
|
||||
Vitest mechanism to collect and run tasks.
|
||||
|
||||
[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/advanced/runner)
|
||||
337
node_modules/@vitest/runner/dist/chunk-tasks.js
generated
vendored
Normal file
337
node_modules/@vitest/runner/dist/chunk-tasks.js
generated
vendored
Normal file
@@ -0,0 +1,337 @@
|
||||
import { processError } from '@vitest/utils/error';
|
||||
import { parseSingleStack } from '@vitest/utils/source-map';
|
||||
import { relative } from 'pathe';
|
||||
import { toArray } from '@vitest/utils/helpers';
|
||||
|
||||
function createChainable(keys, fn) {
|
||||
function create(context) {
|
||||
const chain = function(...args) {
|
||||
return fn.apply(context, args);
|
||||
};
|
||||
Object.assign(chain, fn);
|
||||
chain.withContext = () => chain.bind(context);
|
||||
chain.setContext = (key, value) => {
|
||||
context[key] = value;
|
||||
};
|
||||
chain.mergeContext = (ctx) => {
|
||||
Object.assign(context, ctx);
|
||||
};
|
||||
for (const key of keys) {
|
||||
Object.defineProperty(chain, key, { get() {
|
||||
return create({
|
||||
...context,
|
||||
[key]: true
|
||||
});
|
||||
} });
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
const chain = create({});
|
||||
chain.fn = fn;
|
||||
return chain;
|
||||
}
|
||||
|
||||
/**
|
||||
* If any tasks been marked as `only`, mark all other tasks as `skip`.
|
||||
*/
|
||||
function interpretTaskModes(file, namePattern, testLocations, onlyMode, parentIsOnly, allowOnly) {
|
||||
const matchedLocations = [];
|
||||
const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => {
|
||||
const suiteIsOnly = parentIsOnly || suite.mode === "only";
|
||||
suite.tasks.forEach((t) => {
|
||||
// Check if either the parent suite or the task itself are marked as included
|
||||
const includeTask = suiteIsOnly || t.mode === "only";
|
||||
if (onlyMode) {
|
||||
if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) {
|
||||
// Don't skip this suite
|
||||
if (t.mode === "only") {
|
||||
checkAllowOnly(t, allowOnly);
|
||||
t.mode = "run";
|
||||
}
|
||||
} else if (t.mode === "run" && !includeTask) {
|
||||
t.mode = "skip";
|
||||
} else if (t.mode === "only") {
|
||||
checkAllowOnly(t, allowOnly);
|
||||
t.mode = "run";
|
||||
}
|
||||
}
|
||||
let hasLocationMatch = parentMatchedWithLocation;
|
||||
// Match test location against provided locations, only run if present
|
||||
// in `testLocations`. Note: if `includeTaskLocations` is not enabled,
|
||||
// all test will be skipped.
|
||||
if (testLocations !== undefined && testLocations.length !== 0) {
|
||||
if (t.location && (testLocations === null || testLocations === void 0 ? void 0 : testLocations.includes(t.location.line))) {
|
||||
t.mode = "run";
|
||||
matchedLocations.push(t.location.line);
|
||||
hasLocationMatch = true;
|
||||
} else if (parentMatchedWithLocation) {
|
||||
t.mode = "run";
|
||||
} else if (t.type === "test") {
|
||||
t.mode = "skip";
|
||||
}
|
||||
}
|
||||
if (t.type === "test") {
|
||||
if (namePattern && !getTaskFullName(t).match(namePattern)) {
|
||||
t.mode = "skip";
|
||||
}
|
||||
} else if (t.type === "suite") {
|
||||
if (t.mode === "skip") {
|
||||
skipAllTasks(t);
|
||||
} else if (t.mode === "todo") {
|
||||
todoAllTasks(t);
|
||||
} else {
|
||||
traverseSuite(t, includeTask, hasLocationMatch);
|
||||
}
|
||||
}
|
||||
});
|
||||
// if all subtasks are skipped, mark as skip
|
||||
if (suite.mode === "run" || suite.mode === "queued") {
|
||||
if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) {
|
||||
suite.mode = "skip";
|
||||
}
|
||||
}
|
||||
};
|
||||
traverseSuite(file, parentIsOnly, false);
|
||||
const nonMatching = testLocations === null || testLocations === void 0 ? void 0 : testLocations.filter((loc) => !matchedLocations.includes(loc));
|
||||
if (nonMatching && nonMatching.length !== 0) {
|
||||
const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`;
|
||||
if (file.result === undefined) {
|
||||
file.result = {
|
||||
state: "fail",
|
||||
errors: []
|
||||
};
|
||||
}
|
||||
if (file.result.errors === undefined) {
|
||||
file.result.errors = [];
|
||||
}
|
||||
file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`)));
|
||||
}
|
||||
}
|
||||
function getTaskFullName(task) {
|
||||
return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`;
|
||||
}
|
||||
function someTasksAreOnly(suite) {
|
||||
return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t));
|
||||
}
|
||||
function skipAllTasks(suite) {
|
||||
suite.tasks.forEach((t) => {
|
||||
if (t.mode === "run" || t.mode === "queued") {
|
||||
t.mode = "skip";
|
||||
if (t.type === "suite") {
|
||||
skipAllTasks(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function todoAllTasks(suite) {
|
||||
suite.tasks.forEach((t) => {
|
||||
if (t.mode === "run" || t.mode === "queued") {
|
||||
t.mode = "todo";
|
||||
if (t.type === "suite") {
|
||||
todoAllTasks(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function checkAllowOnly(task, allowOnly) {
|
||||
if (allowOnly) {
|
||||
return;
|
||||
}
|
||||
const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error"));
|
||||
task.result = {
|
||||
state: "fail",
|
||||
errors: [error]
|
||||
};
|
||||
}
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function generateHash(str) {
|
||||
let hash = 0;
|
||||
if (str.length === 0) {
|
||||
return `${hash}`;
|
||||
}
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = (hash << 5) - hash + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
return `${hash}`;
|
||||
}
|
||||
function calculateSuiteHash(parent) {
|
||||
parent.tasks.forEach((t, idx) => {
|
||||
t.id = `${parent.id}_${idx}`;
|
||||
if (t.type === "suite") {
|
||||
calculateSuiteHash(t);
|
||||
}
|
||||
});
|
||||
}
|
||||
function createFileTask(filepath, root, projectName, pool, viteEnvironment) {
|
||||
const path = relative(root, filepath);
|
||||
const file = {
|
||||
id: generateFileHash(path, projectName),
|
||||
name: path,
|
||||
fullName: path,
|
||||
type: "suite",
|
||||
mode: "queued",
|
||||
filepath,
|
||||
tasks: [],
|
||||
meta: Object.create(null),
|
||||
projectName,
|
||||
file: undefined,
|
||||
pool,
|
||||
viteEnvironment
|
||||
};
|
||||
file.file = file;
|
||||
return file;
|
||||
}
|
||||
/**
|
||||
* Generate a unique ID for a file based on its path and project name
|
||||
* @param file File relative to the root of the project to keep ID the same between different machines
|
||||
* @param projectName The name of the test project
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function generateFileHash(file, projectName) {
|
||||
return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`);
|
||||
}
|
||||
function findTestFileStackTrace(testFilePath, error) {
|
||||
// first line is the error message
|
||||
const lines = error.split("\n").slice(1);
|
||||
for (const line of lines) {
|
||||
const stack = parseSingleStack(line);
|
||||
if (stack && stack.file === testFilePath) {
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a function for running multiple async operations with limited concurrency.
|
||||
*/
|
||||
function limitConcurrency(concurrency = Infinity) {
|
||||
// The number of currently active + pending tasks.
|
||||
let count = 0;
|
||||
// The head and tail of the pending task queue, built using a singly linked list.
|
||||
// Both head and tail are initially undefined, signifying an empty queue.
|
||||
// They both become undefined again whenever there are no pending tasks.
|
||||
let head;
|
||||
let tail;
|
||||
// A bookkeeping function executed whenever a task has been run to completion.
|
||||
const finish = () => {
|
||||
count--;
|
||||
// Check if there are further pending tasks in the queue.
|
||||
if (head) {
|
||||
// Allow the next pending task to run and pop it from the queue.
|
||||
head[0]();
|
||||
head = head[1];
|
||||
// The head may now be undefined if there are no further pending tasks.
|
||||
// In that case, set tail to undefined as well.
|
||||
tail = head && tail;
|
||||
}
|
||||
};
|
||||
return (func, ...args) => {
|
||||
// Create a promise chain that:
|
||||
// 1. Waits for its turn in the task queue (if necessary).
|
||||
// 2. Runs the task.
|
||||
// 3. Allows the next pending task (if any) to run.
|
||||
return new Promise((resolve) => {
|
||||
if (count++ < concurrency) {
|
||||
// No need to queue if fewer than maxConcurrency tasks are running.
|
||||
resolve();
|
||||
} else if (tail) {
|
||||
// There are pending tasks, so append to the queue.
|
||||
tail = tail[1] = [resolve];
|
||||
} else {
|
||||
// No other pending tasks, initialize the queue with a new tail and head.
|
||||
head = tail = [resolve];
|
||||
}
|
||||
}).then(() => {
|
||||
// Running func here ensures that even a non-thenable result or an
|
||||
// immediately thrown error gets wrapped into a Promise.
|
||||
return func(...args);
|
||||
}).finally(finish);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Partition in tasks groups by consecutive concurrent
|
||||
*/
|
||||
function partitionSuiteChildren(suite) {
|
||||
let tasksGroup = [];
|
||||
const tasksGroups = [];
|
||||
for (const c of suite.tasks) {
|
||||
if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) {
|
||||
tasksGroup.push(c);
|
||||
} else {
|
||||
tasksGroups.push(tasksGroup);
|
||||
tasksGroup = [c];
|
||||
}
|
||||
}
|
||||
if (tasksGroup.length > 0) {
|
||||
tasksGroups.push(tasksGroup);
|
||||
}
|
||||
return tasksGroups;
|
||||
}
|
||||
|
||||
function isTestCase(s) {
|
||||
return s.type === "test";
|
||||
}
|
||||
function getTests(suite) {
|
||||
const tests = [];
|
||||
const arraySuites = toArray(suite);
|
||||
for (const s of arraySuites) {
|
||||
if (isTestCase(s)) {
|
||||
tests.push(s);
|
||||
} else {
|
||||
for (const task of s.tasks) {
|
||||
if (isTestCase(task)) {
|
||||
tests.push(task);
|
||||
} else {
|
||||
const taskTests = getTests(task);
|
||||
for (const test of taskTests) {
|
||||
tests.push(test);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return tests;
|
||||
}
|
||||
function getTasks(tasks = []) {
|
||||
return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]);
|
||||
}
|
||||
function getSuites(suite) {
|
||||
return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []);
|
||||
}
|
||||
function hasTests(suite) {
|
||||
return toArray(suite).some((s) => s.tasks.some((c) => isTestCase(c) || hasTests(c)));
|
||||
}
|
||||
function hasFailed(suite) {
|
||||
return toArray(suite).some((s) => {
|
||||
var _s$result;
|
||||
return ((_s$result = s.result) === null || _s$result === void 0 ? void 0 : _s$result.state) === "fail" || s.type === "suite" && hasFailed(s.tasks);
|
||||
});
|
||||
}
|
||||
function getNames(task) {
|
||||
const names = [task.name];
|
||||
let current = task;
|
||||
while (current === null || current === void 0 ? void 0 : current.suite) {
|
||||
current = current.suite;
|
||||
if (current === null || current === void 0 ? void 0 : current.name) {
|
||||
names.unshift(current.name);
|
||||
}
|
||||
}
|
||||
if (current !== task.file) {
|
||||
names.unshift(task.file.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
function getFullName(task, separator = " > ") {
|
||||
return getNames(task).join(separator);
|
||||
}
|
||||
function getTestName(task, separator = " > ") {
|
||||
return getNames(task).slice(1).join(separator);
|
||||
}
|
||||
function createTaskName(names, separator = " > ") {
|
||||
return names.filter((name) => name !== undefined).join(separator);
|
||||
}
|
||||
|
||||
export { calculateSuiteHash as a, createFileTask as b, createChainable as c, generateHash as d, createTaskName as e, findTestFileStackTrace as f, generateFileHash as g, getFullName as h, interpretTaskModes as i, getNames as j, getSuites as k, limitConcurrency as l, getTasks as m, getTestName as n, getTests as o, partitionSuiteChildren as p, hasFailed as q, hasTests as r, someTasksAreOnly as s, isTestCase as t };
|
||||
180
node_modules/@vitest/runner/dist/index.d.ts
generated
vendored
Normal file
180
node_modules/@vitest/runner/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,180 @@
|
||||
import { b as TestArtifact, a as Test, S as Suite, d as SuiteHooks, F as File, e as TaskUpdateEvent, T as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-Xu8VaPgy.js';
|
||||
export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, I as ImportDuration, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, x as SequenceHooks, y as SequenceSetupFiles, z as SuiteFactory, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, Z as TestContext, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact, i as afterAll, j as afterEach, k as beforeAll, l as beforeEach, o as onTestFailed, m as onTestFinished } from './tasks.d-Xu8VaPgy.js';
|
||||
import { Awaitable } from '@vitest/utils';
|
||||
import { FileSpecification, VitestRunner } from './types.js';
|
||||
export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js';
|
||||
import '@vitest/utils/diff';
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
* @advanced
|
||||
*
|
||||
* Records a custom test artifact during test execution.
|
||||
*
|
||||
* This function allows you to attach structured data, files, or metadata to a test.
|
||||
*
|
||||
* Vitest automatically injects the source location where the artifact was created and manages any attachments you include.
|
||||
*
|
||||
* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests
|
||||
* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase}
|
||||
*
|
||||
* @returns A promise that resolves to the recorded artifact with location injected
|
||||
*
|
||||
* @throws {Error} If called after the test has finished running
|
||||
* @throws {Error} If the test runner doesn't support artifacts
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // In a custom assertion
|
||||
* async function toHaveValidSchema(this: MatcherState, actual: unknown) {
|
||||
* const validation = validateSchema(actual)
|
||||
*
|
||||
* await recordArtifact(this.task, {
|
||||
* type: 'my-plugin:schema-validation',
|
||||
* passed: validation.valid,
|
||||
* errors: validation.errors,
|
||||
* })
|
||||
*
|
||||
* return { pass: validation.valid, message: () => '...' }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function recordArtifact<Artifact extends TestArtifact>(task: Test, artifact: Artifact): Promise<Artifact>;
|
||||
|
||||
declare function setFn(key: Test, fn: () => Awaitable<void>): void;
|
||||
declare function getFn<Task = Test>(key: Task): () => Awaitable<void>;
|
||||
declare function setHooks(key: Suite, hooks: SuiteHooks): void;
|
||||
declare function getHooks(key: Suite): SuiteHooks;
|
||||
|
||||
declare function updateTask(event: TaskUpdateEvent, task: Task, runner: VitestRunner): void;
|
||||
declare function startTests(specs: string[] | FileSpecification[], runner: VitestRunner): Promise<File[]>;
|
||||
declare function publicCollect(specs: string[] | FileSpecification[], runner: VitestRunner): Promise<File[]>;
|
||||
|
||||
/**
|
||||
* Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
|
||||
* Suites can contain both tests and other suites, enabling complex test structures.
|
||||
*
|
||||
* @param {string} name - The name of the suite, used for identification and reporting.
|
||||
* @param {Function} fn - A function that defines the tests and suites within this suite.
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a suite with two tests
|
||||
* suite('Math operations', () => {
|
||||
* test('should add two numbers', () => {
|
||||
* expect(add(1, 2)).toBe(3);
|
||||
* });
|
||||
*
|
||||
* test('should subtract two numbers', () => {
|
||||
* expect(subtract(5, 2)).toBe(3);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define nested suites
|
||||
* suite('String operations', () => {
|
||||
* suite('Trimming', () => {
|
||||
* test('should trim whitespace from start and end', () => {
|
||||
* expect(' hello '.trim()).toBe('hello');
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* suite('Concatenation', () => {
|
||||
* test('should concatenate two strings', () => {
|
||||
* expect('hello' + ' ' + 'world').toBe('hello world');
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const suite: SuiteAPI;
|
||||
/**
|
||||
* Defines a test case with a given name and test function. The test function can optionally be configured with test options.
|
||||
*
|
||||
* @param {string | Function} name - The name of the test or a function that will be used as a test name.
|
||||
* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
|
||||
* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
|
||||
* @throws {Error} If called inside another test function.
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a simple test
|
||||
* test('should add two numbers', () => {
|
||||
* expect(add(1, 2)).toBe(3);
|
||||
* });
|
||||
* ```
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a test with options
|
||||
* test('should subtract two numbers', { retry: 3 }, () => {
|
||||
* expect(subtract(5, 2)).toBe(3);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const test: TestAPI;
|
||||
/**
|
||||
* Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
|
||||
* Suites can contain both tests and other suites, enabling complex test structures.
|
||||
*
|
||||
* @param {string} name - The name of the suite, used for identification and reporting.
|
||||
* @param {Function} fn - A function that defines the tests and suites within this suite.
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a suite with two tests
|
||||
* describe('Math operations', () => {
|
||||
* test('should add two numbers', () => {
|
||||
* expect(add(1, 2)).toBe(3);
|
||||
* });
|
||||
*
|
||||
* test('should subtract two numbers', () => {
|
||||
* expect(subtract(5, 2)).toBe(3);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define nested suites
|
||||
* describe('String operations', () => {
|
||||
* describe('Trimming', () => {
|
||||
* test('should trim whitespace from start and end', () => {
|
||||
* expect(' hello '.trim()).toBe('hello');
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* describe('Concatenation', () => {
|
||||
* test('should concatenate two strings', () => {
|
||||
* expect('hello' + ' ' + 'world').toBe('hello world');
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const describe: SuiteAPI;
|
||||
/**
|
||||
* Defines a test case with a given name and test function. The test function can optionally be configured with test options.
|
||||
*
|
||||
* @param {string | Function} name - The name of the test or a function that will be used as a test name.
|
||||
* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
|
||||
* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
|
||||
* @throws {Error} If called inside another test function.
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a simple test
|
||||
* it('adds two numbers', () => {
|
||||
* expect(add(1, 2)).toBe(3);
|
||||
* });
|
||||
* ```
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define a test with options
|
||||
* it('subtracts two numbers', { retry: 3 }, () => {
|
||||
* expect(subtract(5, 2)).toBe(3);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const it: TestAPI;
|
||||
declare function getCurrentSuite<ExtraContext = object>(): SuiteCollector<ExtraContext>;
|
||||
declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record<string, unknown>): TestAPI;
|
||||
|
||||
declare function getCurrentTest<T extends Test | undefined>(): T;
|
||||
|
||||
export { File, FileSpecification, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, TaskUpdateEvent, Test, TestAPI, TestArtifact, VitestRunner, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask };
|
||||
2111
node_modules/@vitest/runner/dist/index.js
generated
vendored
Normal file
2111
node_modules/@vitest/runner/dist/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
834
node_modules/@vitest/runner/dist/tasks.d-Xu8VaPgy.d.ts
generated
vendored
Normal file
834
node_modules/@vitest/runner/dist/tasks.d-Xu8VaPgy.d.ts
generated
vendored
Normal file
@@ -0,0 +1,834 @@
|
||||
import { TestError, Awaitable } from '@vitest/utils';
|
||||
|
||||
interface FixtureItem extends FixtureOptions {
|
||||
prop: string;
|
||||
value: any;
|
||||
scope: "test" | "file" | "worker";
|
||||
/**
|
||||
* Indicates whether the fixture is a function
|
||||
*/
|
||||
isFn: boolean;
|
||||
/**
|
||||
* The dependencies(fixtures) of current fixture function.
|
||||
*/
|
||||
deps?: FixtureItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback function to be executed once before all tests within the current suite.
|
||||
* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
|
||||
*
|
||||
* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed before all tests.
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using beforeAll to set up a database connection
|
||||
* beforeAll(async () => {
|
||||
* await database.connect();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function beforeAll(fn: BeforeAllListener, timeout?: number): void;
|
||||
/**
|
||||
* Registers a callback function to be executed once after all tests within the current suite have completed.
|
||||
* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
|
||||
*
|
||||
* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed after all tests.
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using afterAll to close a database connection
|
||||
* afterAll(async () => {
|
||||
* await database.disconnect();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function afterAll(fn: AfterAllListener, timeout?: number): void;
|
||||
/**
|
||||
* Registers a callback function to be executed before each test within the current suite.
|
||||
* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
|
||||
*
|
||||
* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using beforeEach to reset a database state
|
||||
* beforeEach(async () => {
|
||||
* await database.reset();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void;
|
||||
/**
|
||||
* Registers a callback function to be executed after each test within the current suite has completed.
|
||||
* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
|
||||
*
|
||||
* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using afterEach to delete temporary files created during a test
|
||||
* afterEach(async () => {
|
||||
* await fileSystem.deleteTempFiles();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void;
|
||||
/**
|
||||
* Registers a callback function to be executed when a test fails within the current suite.
|
||||
* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
|
||||
*
|
||||
* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @throws {Error} Throws an error if the function is not called within a test.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using onTestFailed to log failure details
|
||||
* onTestFailed(({ errors }) => {
|
||||
* console.log(`Test failed: ${test.name}`, errors);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const onTestFailed: TaskHook<OnTestFailedHandler>;
|
||||
/**
|
||||
* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
|
||||
* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
|
||||
*
|
||||
* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
|
||||
*
|
||||
* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
|
||||
*
|
||||
* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
|
||||
*
|
||||
* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
|
||||
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
|
||||
* @throws {Error} Throws an error if the function is not called within a test.
|
||||
* @returns {void}
|
||||
* @example
|
||||
* ```ts
|
||||
* // Example of using onTestFinished for cleanup
|
||||
* const db = await connectToDatabase();
|
||||
* onTestFinished(async () => {
|
||||
* await db.disconnect();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare const onTestFinished: TaskHook<OnTestFinishedHandler>;
|
||||
|
||||
type ChainableFunction<
|
||||
T extends string,
|
||||
F extends (...args: any) => any,
|
||||
C = object
|
||||
> = F & { [x in T] : ChainableFunction<T, F, C> } & {
|
||||
fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
|
||||
} & C;
|
||||
declare function createChainable<
|
||||
T extends string,
|
||||
Args extends any[],
|
||||
R = any
|
||||
>(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R): ChainableFunction<T, (...args: Args) => R>;
|
||||
|
||||
type RunMode = "run" | "skip" | "only" | "todo" | "queued";
|
||||
type TaskState = RunMode | "pass" | "fail";
|
||||
interface TaskBase {
|
||||
/**
|
||||
* Unique task identifier. Based on the file id and the position of the task.
|
||||
* The id of the file task is based on the file path relative to root and project name.
|
||||
* It will not change between runs.
|
||||
* @example `1201091390`, `1201091390_0`, `1201091390_0_1`
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Task name provided by the user. If no name was provided, it will be an empty string.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Full name including the file path, any parent suites, and this task's name.
|
||||
*
|
||||
* Uses ` > ` as the separator between levels.
|
||||
*
|
||||
* @example
|
||||
* // file
|
||||
* 'test/task-names.test.ts'
|
||||
* @example
|
||||
* // suite
|
||||
* 'test/task-names.test.ts > meal planning'
|
||||
* 'test/task-names.test.ts > meal planning > grocery lists'
|
||||
* @example
|
||||
* // test
|
||||
* 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients'
|
||||
*/
|
||||
fullName: string;
|
||||
/**
|
||||
* Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks.
|
||||
*
|
||||
* Uses ` > ` as the separator between levels.
|
||||
*
|
||||
* @example
|
||||
* // file
|
||||
* undefined
|
||||
* @example
|
||||
* // suite
|
||||
* 'meal planning'
|
||||
* 'meal planning > grocery lists'
|
||||
* @example
|
||||
* // test
|
||||
* 'meal planning > grocery lists > calculates ingredients'
|
||||
*/
|
||||
fullTestName?: string;
|
||||
/**
|
||||
* Task mode.
|
||||
* - **skip**: task is skipped
|
||||
* - **only**: only this task and other tasks with `only` mode will run
|
||||
* - **todo**: task is marked as a todo, alias for `skip`
|
||||
* - **run**: task will run or already ran
|
||||
* - **queued**: task will start running next. It can only exist on the File
|
||||
*/
|
||||
mode: RunMode;
|
||||
/**
|
||||
* Custom metadata for the task. JSON reporter will save this data.
|
||||
*/
|
||||
meta: TaskMeta;
|
||||
/**
|
||||
* Whether the task was produced with `.each()` method.
|
||||
*/
|
||||
each?: boolean;
|
||||
/**
|
||||
* Whether the task should run concurrently with other tasks.
|
||||
*/
|
||||
concurrent?: boolean;
|
||||
/**
|
||||
* Whether the tasks of the suite run in a random order.
|
||||
*/
|
||||
shuffle?: boolean;
|
||||
/**
|
||||
* Suite that this task is part of. File task or the global suite will have no parent.
|
||||
*/
|
||||
suite?: Suite;
|
||||
/**
|
||||
* Result of the task. Suite and file tasks will only have the result if there
|
||||
* was an error during collection or inside `afterAll`/`beforeAll`.
|
||||
*/
|
||||
result?: TaskResult;
|
||||
/**
|
||||
* The amount of times the task should be retried if it fails.
|
||||
* @default 0
|
||||
*/
|
||||
retry?: number;
|
||||
/**
|
||||
* The amount of times the task should be repeated after the successful run.
|
||||
* If the task fails, it will not be retried unless `retry` is specified.
|
||||
* @default 0
|
||||
*/
|
||||
repeats?: number;
|
||||
/**
|
||||
* Location of the task in the file. This field is populated only if
|
||||
* `includeTaskLocation` option is set. It is generated by calling `new Error`
|
||||
* and parsing the stack trace, so the location might differ depending on the runtime.
|
||||
*/
|
||||
location?: {
|
||||
line: number;
|
||||
column: number;
|
||||
};
|
||||
/**
|
||||
* If the test was collected by parsing the file AST, and the name
|
||||
* is not a static string, this property will be set to `true`.
|
||||
* @experimental
|
||||
*/
|
||||
dynamic?: boolean;
|
||||
}
|
||||
interface TaskPopulated extends TaskBase {
|
||||
/**
|
||||
* File task. It's the root task of the file.
|
||||
*/
|
||||
file: File;
|
||||
/**
|
||||
* Whether the task should succeed if it fails. If the task fails, it will be marked as passed.
|
||||
*/
|
||||
fails?: boolean;
|
||||
/**
|
||||
* Store promises (from async expects) to wait for them before finishing the test
|
||||
*/
|
||||
promises?: Promise<any>[];
|
||||
}
|
||||
/**
|
||||
* Custom metadata that can be used in reporters.
|
||||
*/
|
||||
interface TaskMeta {}
|
||||
/**
|
||||
* The result of calling a task.
|
||||
*/
|
||||
interface TaskResult {
|
||||
/**
|
||||
* State of the task. Inherits the `task.mode` during collection.
|
||||
* When the task has finished, it will be changed to `pass` or `fail`.
|
||||
* - **pass**: task ran successfully
|
||||
* - **fail**: task failed
|
||||
*/
|
||||
state: TaskState;
|
||||
/**
|
||||
* Errors that occurred during the task execution. It is possible to have several errors
|
||||
* if `expect.soft()` failed multiple times or `retry` was triggered.
|
||||
*/
|
||||
errors?: TestError[];
|
||||
/**
|
||||
* How long in milliseconds the task took to run.
|
||||
*/
|
||||
duration?: number;
|
||||
/**
|
||||
* Time in milliseconds when the task started running.
|
||||
*/
|
||||
startTime?: number;
|
||||
/**
|
||||
* Heap size in bytes after the task finished.
|
||||
* Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined.
|
||||
*/
|
||||
heap?: number;
|
||||
/**
|
||||
* State of related to this task hooks. Useful during reporting.
|
||||
*/
|
||||
hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
|
||||
/**
|
||||
* The amount of times the task was retried. The task is retried only if it
|
||||
* failed and `retry` option is set.
|
||||
*/
|
||||
retryCount?: number;
|
||||
/**
|
||||
* The amount of times the task was repeated. The task is repeated only if
|
||||
* `repeats` option is set. This number also contains `retryCount`.
|
||||
*/
|
||||
repeatCount?: number;
|
||||
}
|
||||
/** The time spent importing & executing a non-externalized file. */
|
||||
interface ImportDuration {
|
||||
/** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */
|
||||
selfTime: number;
|
||||
/** The time spent importing & executing the file and all its imports. */
|
||||
totalTime: number;
|
||||
/** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */
|
||||
external?: boolean;
|
||||
/** Which module imported this module first. All subsequent imports are cached. */
|
||||
importer?: string;
|
||||
}
|
||||
/**
|
||||
* The tuple representing a single task update.
|
||||
* Usually reported after the task finishes.
|
||||
*/
|
||||
type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta];
|
||||
interface TaskEventData {
|
||||
annotation?: TestAnnotation | undefined;
|
||||
artifact?: TestArtifact | undefined;
|
||||
}
|
||||
type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined];
|
||||
type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact";
|
||||
interface Suite extends TaskBase {
|
||||
type: "suite";
|
||||
/**
|
||||
* File task. It's the root task of the file.
|
||||
*/
|
||||
file: File;
|
||||
/**
|
||||
* An array of tasks that are part of the suite.
|
||||
*/
|
||||
tasks: Task[];
|
||||
}
|
||||
interface File extends Suite {
|
||||
/**
|
||||
* The name of the pool that the file belongs to.
|
||||
* @default 'forks'
|
||||
*/
|
||||
pool?: string;
|
||||
/**
|
||||
* The environment that processes the file on the server.
|
||||
*/
|
||||
viteEnvironment?: string;
|
||||
/**
|
||||
* The path to the file in UNIX format.
|
||||
*/
|
||||
filepath: string;
|
||||
/**
|
||||
* The name of the workspace project the file belongs to.
|
||||
*/
|
||||
projectName: string | undefined;
|
||||
/**
|
||||
* The time it took to collect all tests in the file.
|
||||
* This time also includes importing all the file dependencies.
|
||||
*/
|
||||
collectDuration?: number;
|
||||
/**
|
||||
* The time it took to import the setup file.
|
||||
*/
|
||||
setupDuration?: number;
|
||||
/** The time spent importing every non-externalized dependency that Vitest has processed. */
|
||||
importDurations?: Record<string, ImportDuration>;
|
||||
}
|
||||
interface Test<ExtraContext = object> extends TaskPopulated {
|
||||
type: "test";
|
||||
/**
|
||||
* Test context that will be passed to the test function.
|
||||
*/
|
||||
context: TestContext & ExtraContext;
|
||||
/**
|
||||
* The test timeout in milliseconds.
|
||||
*/
|
||||
timeout: number;
|
||||
/**
|
||||
* An array of custom annotations.
|
||||
*/
|
||||
annotations: TestAnnotation[];
|
||||
/**
|
||||
* An array of artifacts produced by the test.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
artifacts: TestArtifact[];
|
||||
fullTestName: string;
|
||||
}
|
||||
type Task = Test | Suite | File;
|
||||
type TestFunction<ExtraContext = object> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
|
||||
type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
|
||||
1: [T[0]];
|
||||
2: [T[0], T[1]];
|
||||
3: [T[0], T[1], T[2]];
|
||||
4: [T[0], T[1], T[2], T[3]];
|
||||
5: [T[0], T[1], T[2], T[3], T[4]];
|
||||
6: [T[0], T[1], T[2], T[3], T[4], T[5]];
|
||||
7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
|
||||
8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
|
||||
9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
|
||||
10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
|
||||
fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
|
||||
}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : "fallback"];
|
||||
interface EachFunctionReturn<T extends any[]> {
|
||||
(name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number): void;
|
||||
(name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable<void>): void;
|
||||
}
|
||||
interface TestEachFunction {
|
||||
<T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>;
|
||||
<T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>;
|
||||
<T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>;
|
||||
(...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
|
||||
}
|
||||
interface TestForFunctionReturn<
|
||||
Arg,
|
||||
Context
|
||||
> {
|
||||
(name: string | Function, fn: (arg: Arg, context: Context) => Awaitable<void>): void;
|
||||
(name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable<void>): void;
|
||||
}
|
||||
interface TestForFunction<ExtraContext> {
|
||||
<T>(cases: ReadonlyArray<T>): TestForFunctionReturn<T, TestContext & ExtraContext>;
|
||||
(strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn<any, TestContext & ExtraContext>;
|
||||
}
|
||||
interface SuiteForFunction {
|
||||
<T>(cases: ReadonlyArray<T>): EachFunctionReturn<[T]>;
|
||||
(...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>;
|
||||
}
|
||||
interface TestCollectorCallable<C = object> {
|
||||
<ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number): void;
|
||||
<ExtraContext extends C>(name: string | Function, options?: TestCollectorOptions, fn?: TestFunction<ExtraContext>): void;
|
||||
}
|
||||
type ChainableTestAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "fails", TestCollectorCallable<ExtraContext>, {
|
||||
each: TestEachFunction;
|
||||
for: TestForFunction<ExtraContext>;
|
||||
}>;
|
||||
type TestCollectorOptions = Omit<TestOptions, "shuffle">;
|
||||
interface TestOptions {
|
||||
/**
|
||||
* Test timeout.
|
||||
*/
|
||||
timeout?: number;
|
||||
/**
|
||||
* Times to retry the test if fails. Useful for making flaky tests more stable.
|
||||
* When retries is up, the last test error will be thrown.
|
||||
*
|
||||
* @default 0
|
||||
*/
|
||||
retry?: number;
|
||||
/**
|
||||
* How many times the test will run again.
|
||||
* Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default.
|
||||
*
|
||||
* @default 0
|
||||
*/
|
||||
repeats?: number;
|
||||
/**
|
||||
* Whether suites and tests run concurrently.
|
||||
* Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`.
|
||||
*/
|
||||
concurrent?: boolean;
|
||||
/**
|
||||
* Whether tests run sequentially.
|
||||
* Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`.
|
||||
*/
|
||||
sequential?: boolean;
|
||||
/**
|
||||
* Whether the tasks of the suite run in a random order.
|
||||
*/
|
||||
shuffle?: boolean;
|
||||
/**
|
||||
* Whether the test should be skipped.
|
||||
*/
|
||||
skip?: boolean;
|
||||
/**
|
||||
* Should this test be the only one running in a suite.
|
||||
*/
|
||||
only?: boolean;
|
||||
/**
|
||||
* Whether the test should be skipped and marked as a todo.
|
||||
*/
|
||||
todo?: boolean;
|
||||
/**
|
||||
* Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail.
|
||||
*/
|
||||
fails?: boolean;
|
||||
}
|
||||
interface ExtendedAPI<ExtraContext> {
|
||||
skipIf: (condition: any) => ChainableTestAPI<ExtraContext>;
|
||||
runIf: (condition: any) => ChainableTestAPI<ExtraContext>;
|
||||
}
|
||||
interface Hooks<ExtraContext> {
|
||||
beforeAll: typeof beforeAll;
|
||||
afterAll: typeof afterAll;
|
||||
beforeEach: typeof beforeEach<ExtraContext>;
|
||||
afterEach: typeof afterEach<ExtraContext>;
|
||||
}
|
||||
type TestAPI<ExtraContext = object> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & Hooks<ExtraContext> & {
|
||||
extend: <T extends Record<string, any> = object>(fixtures: Fixtures<T, ExtraContext>) => TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>;
|
||||
scoped: (fixtures: Fixtures<Partial<ExtraContext>>) => void;
|
||||
};
|
||||
interface FixtureOptions {
|
||||
/**
|
||||
* Whether to automatically set up current fixture, even though it's not being used in tests.
|
||||
* @default false
|
||||
*/
|
||||
auto?: boolean;
|
||||
/**
|
||||
* Indicated if the injected value from the config should be preferred over the fixture value
|
||||
*/
|
||||
injected?: boolean;
|
||||
/**
|
||||
* When should the fixture be set up.
|
||||
* - **test**: fixture will be set up before every test
|
||||
* - **worker**: fixture will be set up once per worker
|
||||
* - **file**: fixture will be set up once per file
|
||||
*
|
||||
* **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file.
|
||||
* @default 'test'
|
||||
*/
|
||||
scope?: "test" | "worker" | "file";
|
||||
}
|
||||
type Use<T> = (value: T) => Promise<void>;
|
||||
type FixtureFn<
|
||||
T,
|
||||
K extends keyof T,
|
||||
ExtraContext
|
||||
> = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>;
|
||||
type Fixture<
|
||||
T,
|
||||
K extends keyof T,
|
||||
ExtraContext = object
|
||||
> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never);
|
||||
type Fixtures<
|
||||
T extends Record<string, any>,
|
||||
ExtraContext = object
|
||||
> = { [K in keyof T] : Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?] };
|
||||
type InferFixturesTypes<T> = T extends TestAPI<infer C> ? C : T;
|
||||
interface SuiteCollectorCallable<ExtraContext = object> {
|
||||
<OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, fn?: SuiteFactory<OverrideExtraContext>, options?: number): SuiteCollector<OverrideExtraContext>;
|
||||
<OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, options: TestOptions, fn?: SuiteFactory<OverrideExtraContext>): SuiteCollector<OverrideExtraContext>;
|
||||
}
|
||||
type ChainableSuiteAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "shuffle", SuiteCollectorCallable<ExtraContext>, {
|
||||
each: TestEachFunction;
|
||||
for: SuiteForFunction;
|
||||
}>;
|
||||
type SuiteAPI<ExtraContext = object> = ChainableSuiteAPI<ExtraContext> & {
|
||||
skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
|
||||
runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>;
|
||||
};
|
||||
interface BeforeAllListener {
|
||||
(suite: Readonly<Suite | File>): Awaitable<unknown>;
|
||||
}
|
||||
interface AfterAllListener {
|
||||
(suite: Readonly<Suite | File>): Awaitable<unknown>;
|
||||
}
|
||||
interface BeforeEachListener<ExtraContext = object> {
|
||||
(context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
|
||||
}
|
||||
interface AfterEachListener<ExtraContext = object> {
|
||||
(context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>;
|
||||
}
|
||||
interface SuiteHooks<ExtraContext = object> {
|
||||
beforeAll: BeforeAllListener[];
|
||||
afterAll: AfterAllListener[];
|
||||
beforeEach: BeforeEachListener<ExtraContext>[];
|
||||
afterEach: AfterEachListener<ExtraContext>[];
|
||||
}
|
||||
interface TaskCustomOptions extends TestOptions {
|
||||
/**
|
||||
* Whether the task was produced with `.each()` method.
|
||||
*/
|
||||
each?: boolean;
|
||||
/**
|
||||
* Custom metadata for the task that will be assigned to `task.meta`.
|
||||
*/
|
||||
meta?: Record<string, unknown>;
|
||||
/**
|
||||
* Task fixtures.
|
||||
*/
|
||||
fixtures?: FixtureItem[];
|
||||
/**
|
||||
* Function that will be called when the task is executed.
|
||||
* If nothing is provided, the runner will try to get the function using `getFn(task)`.
|
||||
* If the runner cannot find the function, the task will be marked as failed.
|
||||
*/
|
||||
handler?: (context: TestContext) => Awaitable<void>;
|
||||
}
|
||||
interface SuiteCollector<ExtraContext = object> {
|
||||
readonly name: string;
|
||||
readonly mode: RunMode;
|
||||
options?: TestOptions;
|
||||
type: "collector";
|
||||
test: TestAPI<ExtraContext>;
|
||||
tasks: (Suite | Test<ExtraContext> | SuiteCollector<ExtraContext>)[];
|
||||
scoped: (fixtures: Fixtures<any, ExtraContext>) => void;
|
||||
fixtures: () => FixtureItem[] | undefined;
|
||||
file?: File;
|
||||
suite?: Suite;
|
||||
task: (name: string, options?: TaskCustomOptions) => Test<ExtraContext>;
|
||||
collect: (file: File) => Promise<Suite>;
|
||||
clear: () => void;
|
||||
on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
|
||||
}
|
||||
type SuiteFactory<ExtraContext = object> = (test: TestAPI<ExtraContext>) => Awaitable<void>;
|
||||
interface RuntimeContext {
|
||||
tasks: (SuiteCollector | Test)[];
|
||||
currentSuite: SuiteCollector | null;
|
||||
}
|
||||
/**
|
||||
* User's custom test context.
|
||||
*/
|
||||
interface TestContext {
|
||||
/**
|
||||
* Metadata of the current test
|
||||
*/
|
||||
readonly task: Readonly<Test>;
|
||||
/**
|
||||
* An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or
|
||||
* the test run was cancelled.
|
||||
* @see {@link https://vitest.dev/guide/test-context#signal}
|
||||
*/
|
||||
readonly signal: AbortSignal;
|
||||
/**
|
||||
* Extract hooks on test failed
|
||||
* @see {@link https://vitest.dev/guide/test-context#ontestfailed}
|
||||
*/
|
||||
readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void;
|
||||
/**
|
||||
* Extract hooks on test failed
|
||||
* @see {@link https://vitest.dev/guide/test-context#ontestfinished}
|
||||
*/
|
||||
readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void;
|
||||
/**
|
||||
* Mark tests as skipped. All execution after this call will be skipped.
|
||||
* This function throws an error, so make sure you are not catching it accidentally.
|
||||
* @see {@link https://vitest.dev/guide/test-context#skip}
|
||||
*/
|
||||
readonly skip: {
|
||||
(note?: string): never;
|
||||
(condition: boolean, note?: string): void;
|
||||
};
|
||||
/**
|
||||
* Add a test annotation that will be displayed by your reporter.
|
||||
* @see {@link https://vitest.dev/guide/test-context#annotate}
|
||||
*/
|
||||
readonly annotate: {
|
||||
(message: string, type?: string, attachment?: TestAttachment): Promise<TestAnnotation>;
|
||||
(message: string, attachment?: TestAttachment): Promise<TestAnnotation>;
|
||||
};
|
||||
}
|
||||
type OnTestFailedHandler = (context: TestContext) => Awaitable<void>;
|
||||
type OnTestFinishedHandler = (context: TestContext) => Awaitable<void>;
|
||||
interface TaskHook<HookListener> {
|
||||
(fn: HookListener, timeout?: number): void;
|
||||
}
|
||||
type SequenceHooks = "stack" | "list" | "parallel";
|
||||
type SequenceSetupFiles = "list" | "parallel";
|
||||
/**
|
||||
* Represents a file or data attachment associated with a test artifact.
|
||||
*
|
||||
* Attachments can be either file-based (via `path`) or inline content (via `body`).
|
||||
* The `contentType` helps consumers understand how to interpret the attachment data.
|
||||
*/
|
||||
interface TestAttachment {
|
||||
/** MIME type of the attachment (e.g., 'image/png', 'text/plain') */
|
||||
contentType?: string;
|
||||
/** File system path to the attachment */
|
||||
path?: string;
|
||||
/** Inline attachment content as a string or raw binary data */
|
||||
body?: string | Uint8Array;
|
||||
}
|
||||
/**
|
||||
* Source code location information for a test artifact.
|
||||
*
|
||||
* Indicates where in the source code the artifact originated from.
|
||||
*/
|
||||
interface TestArtifactLocation {
|
||||
/** Line number in the source file (1-indexed) */
|
||||
line: number;
|
||||
/** Column number in the line (1-indexed) */
|
||||
column: number;
|
||||
/** Path to the source file */
|
||||
file: string;
|
||||
}
|
||||
/**
|
||||
* @experimental
|
||||
*
|
||||
* Base interface for all test artifacts.
|
||||
*
|
||||
* Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code.
|
||||
*/
|
||||
interface TestArtifactBase {
|
||||
/** File or data attachments associated with this artifact */
|
||||
attachments?: TestAttachment[];
|
||||
/** Source location where this artifact was created */
|
||||
location?: TestArtifactLocation;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use {@linkcode TestArtifactLocation} instead.
|
||||
*
|
||||
* Kept for backwards compatibility.
|
||||
*/
|
||||
type TestAnnotationLocation = TestArtifactLocation;
|
||||
interface TestAnnotation {
|
||||
message: string;
|
||||
type: string;
|
||||
location?: TestArtifactLocation;
|
||||
attachment?: TestAttachment;
|
||||
}
|
||||
/**
|
||||
* @experimental
|
||||
*
|
||||
* Artifact type for test annotations.
|
||||
*/
|
||||
interface TestAnnotationArtifact extends TestArtifactBase {
|
||||
type: "internal:annotation";
|
||||
annotation: TestAnnotation;
|
||||
}
|
||||
type VisualRegressionArtifactAttachment = TestAttachment & ({
|
||||
name: "reference" | "actual";
|
||||
width: number;
|
||||
height: number;
|
||||
} | {
|
||||
name: "diff";
|
||||
});
|
||||
/**
|
||||
* @experimental
|
||||
*
|
||||
* Artifact type for visual regressions.
|
||||
*/
|
||||
interface VisualRegressionArtifact extends TestArtifactBase {
|
||||
type: "internal:toMatchScreenshot";
|
||||
kind: "visual-regression";
|
||||
message: string;
|
||||
attachments: VisualRegressionArtifactAttachment[];
|
||||
}
|
||||
/**
|
||||
* @experimental
|
||||
* @advanced
|
||||
*
|
||||
* Registry for custom test artifact types.
|
||||
*
|
||||
* Augment this interface to register custom artifact types that your tests can produce.
|
||||
*
|
||||
* Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property.
|
||||
*
|
||||
* @remarks
|
||||
* - Use a `Symbol` as the **registry key** to guarantee uniqueness
|
||||
* - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix
|
||||
* - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata
|
||||
* - `location` property is automatically injected to indicate where the artifact was created
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Define custom attachment type for generated PDF
|
||||
* interface PDFAttachment extends TestAttachment {
|
||||
* contentType: 'application/pdf'
|
||||
* body: Uint8Array
|
||||
* pageCount: number
|
||||
* fileSize: number
|
||||
* }
|
||||
*
|
||||
* interface PDFGenerationArtifact extends TestArtifactBase {
|
||||
* type: 'my-plugin:pdf-generation'
|
||||
* templateName: string
|
||||
* isValid: boolean
|
||||
* attachments: [PDFAttachment]
|
||||
* }
|
||||
*
|
||||
* // Use a symbol to guarantee key uniqueness
|
||||
* const pdfKey = Symbol('pdf-generation')
|
||||
*
|
||||
* declare module 'vitest' {
|
||||
* interface TestArtifactRegistry {
|
||||
* [pdfKey]: PDFGenerationArtifact
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* // Custom assertion for PDF generation
|
||||
* async function toGenerateValidPDF(
|
||||
* this: MatcherState,
|
||||
* actual: PDFTemplate,
|
||||
* data: Record<string, unknown>
|
||||
* ): AsyncExpectationResult {
|
||||
* const pdfBuffer = await actual.render(data)
|
||||
* const validation = await validatePDF(pdfBuffer)
|
||||
*
|
||||
* await recordArtifact(this.task, {
|
||||
* type: 'my-plugin:pdf-generation',
|
||||
* templateName: actual.name,
|
||||
* isValid: validation.success,
|
||||
* attachments: [{
|
||||
* contentType: 'application/pdf',
|
||||
* body: pdfBuffer,
|
||||
* pageCount: validation.pageCount,
|
||||
* fileSize: pdfBuffer.byteLength
|
||||
* }]
|
||||
* })
|
||||
*
|
||||
* return {
|
||||
* pass: validation.success,
|
||||
* message: () => validation.success
|
||||
* ? `Generated valid PDF with ${validation.pageCount} pages`
|
||||
* : `Invalid PDF: ${validation.error}`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
interface TestArtifactRegistry {}
|
||||
/**
|
||||
* @experimental
|
||||
*
|
||||
* Union type of all test artifacts, including built-in and custom registered artifacts.
|
||||
*
|
||||
* This type automatically includes all artifacts registered via {@link TestArtifactRegistry}.
|
||||
*/
|
||||
type TestArtifact = TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry];
|
||||
|
||||
export { createChainable as c, afterAll as i, afterEach as j, beforeAll as k, beforeEach as l, onTestFinished as m, onTestFailed as o };
|
||||
export type { TestOptions as $, AfterAllListener as A, BeforeAllListener as B, ChainableFunction as C, TaskBase as D, TaskCustomOptions as E, File as F, TaskEventPack as G, TaskHook as H, ImportDuration as I, TaskMeta as J, TaskPopulated as K, TaskResult as L, TaskResultPack as M, TaskState as N, OnTestFailedHandler as O, TestAnnotation as P, TestAnnotationArtifact as Q, RunMode as R, Suite as S, Task as T, TestAnnotationLocation as U, TestArtifactBase as V, TestArtifactLocation as W, TestArtifactRegistry as X, TestAttachment as Y, TestContext as Z, TestFunction as _, Test as a, Use as a0, VisualRegressionArtifact as a1, TestArtifact as b, SuiteHooks as d, TaskUpdateEvent as e, TestAPI as f, SuiteAPI as g, SuiteCollector as h, AfterEachListener as n, BeforeEachListener as p, Fixture as q, FixtureFn as r, FixtureOptions as s, Fixtures as t, InferFixturesTypes as u, OnTestFinishedHandler as v, RuntimeContext as w, SequenceHooks as x, SequenceSetupFiles as y, SuiteFactory as z };
|
||||
183
node_modules/@vitest/runner/dist/types.d.ts
generated
vendored
Normal file
183
node_modules/@vitest/runner/dist/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,183 @@
|
||||
import { DiffOptions } from '@vitest/utils/diff';
|
||||
import { F as File, a as Test, S as Suite, M as TaskResultPack, G as TaskEventPack, P as TestAnnotation, b as TestArtifact, Z as TestContext, I as ImportDuration, x as SequenceHooks, y as SequenceSetupFiles } from './tasks.d-Xu8VaPgy.js';
|
||||
export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, g as SuiteAPI, h as SuiteCollector, z as SuiteFactory, d as SuiteHooks, T as Task, D as TaskBase, E as TaskCustomOptions, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, N as TaskState, e as TaskUpdateEvent, f as TestAPI, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact } from './tasks.d-Xu8VaPgy.js';
|
||||
import '@vitest/utils';
|
||||
|
||||
/**
|
||||
* This is a subset of Vitest config that's required for the runner to work.
|
||||
*/
|
||||
interface VitestRunnerConfig {
|
||||
root: string;
|
||||
setupFiles: string[];
|
||||
name?: string;
|
||||
passWithNoTests: boolean;
|
||||
testNamePattern?: RegExp;
|
||||
allowOnly?: boolean;
|
||||
sequence: {
|
||||
shuffle?: boolean;
|
||||
concurrent?: boolean;
|
||||
seed: number;
|
||||
hooks: SequenceHooks;
|
||||
setupFiles: SequenceSetupFiles;
|
||||
};
|
||||
chaiConfig?: {
|
||||
truncateThreshold?: number;
|
||||
};
|
||||
maxConcurrency: number;
|
||||
testTimeout: number;
|
||||
hookTimeout: number;
|
||||
retry: number;
|
||||
includeTaskLocation?: boolean;
|
||||
diffOptions?: DiffOptions;
|
||||
}
|
||||
/**
|
||||
* Possible options to run a single file in a test.
|
||||
*/
|
||||
interface FileSpecification {
|
||||
filepath: string;
|
||||
testLocations: number[] | undefined;
|
||||
}
|
||||
type VitestRunnerImportSource = "collect" | "setup";
|
||||
interface VitestRunnerConstructor {
|
||||
new (config: VitestRunnerConfig): VitestRunner;
|
||||
}
|
||||
type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>);
|
||||
interface VitestRunner {
|
||||
/**
|
||||
* First thing that's getting called before actually collecting and running tests.
|
||||
*/
|
||||
onBeforeCollect?: (paths: string[]) => unknown;
|
||||
/**
|
||||
* Called after the file task was created but not collected yet.
|
||||
*/
|
||||
onCollectStart?: (file: File) => unknown;
|
||||
/**
|
||||
* Called after collecting tests and before "onBeforeRun".
|
||||
*/
|
||||
onCollected?: (files: File[]) => unknown;
|
||||
/**
|
||||
* Called when test runner should cancel next test runs.
|
||||
* Runner should listen for this method and mark tests and suites as skipped in
|
||||
* "onBeforeRunSuite" and "onBeforeRunTask" when called.
|
||||
*/
|
||||
cancel?: (reason: CancelReason) => unknown;
|
||||
/**
|
||||
* Called before running a single test. Doesn't have "result" yet.
|
||||
*/
|
||||
onBeforeRunTask?: (test: Test) => unknown;
|
||||
/**
|
||||
* Called before actually running the test function. Already has "result" with "state" and "startTime".
|
||||
*/
|
||||
onBeforeTryTask?: (test: Test, options: {
|
||||
retry: number;
|
||||
repeats: number;
|
||||
}) => unknown;
|
||||
/**
|
||||
* When the task has finished running, but before cleanup hooks are called
|
||||
*/
|
||||
onTaskFinished?: (test: Test) => unknown;
|
||||
/**
|
||||
* Called after result and state are set.
|
||||
*/
|
||||
onAfterRunTask?: (test: Test) => unknown;
|
||||
/**
|
||||
* Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
|
||||
*/
|
||||
onAfterTryTask?: (test: Test, options: {
|
||||
retry: number;
|
||||
repeats: number;
|
||||
}) => unknown;
|
||||
/**
|
||||
* Called after the retry resolution happend. Unlike `onAfterTryTask`, the test now has a new state.
|
||||
* All `after` hooks were also called by this point.
|
||||
*/
|
||||
onAfterRetryTask?: (test: Test, options: {
|
||||
retry: number;
|
||||
repeats: number;
|
||||
}) => unknown;
|
||||
/**
|
||||
* Called before running a single suite. Doesn't have "result" yet.
|
||||
*/
|
||||
onBeforeRunSuite?: (suite: Suite) => unknown;
|
||||
/**
|
||||
* Called after running a single suite. Has state and result.
|
||||
*/
|
||||
onAfterRunSuite?: (suite: Suite) => unknown;
|
||||
/**
|
||||
* If defined, will be called instead of usual Vitest suite partition and handling.
|
||||
* "before" and "after" hooks will not be ignored.
|
||||
*/
|
||||
runSuite?: (suite: Suite) => Promise<void>;
|
||||
/**
|
||||
* If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
|
||||
* "before" and "after" hooks will not be ignored.
|
||||
*/
|
||||
runTask?: (test: Test) => Promise<void>;
|
||||
/**
|
||||
* Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
|
||||
*/
|
||||
onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
|
||||
/**
|
||||
* Called when annotation is added via the `context.annotate` method.
|
||||
*/
|
||||
onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise<TestAnnotation>;
|
||||
/**
|
||||
* @experimental
|
||||
*
|
||||
* Called when artifacts are recorded on tests via the `recordArtifact` utility.
|
||||
*/
|
||||
onTestArtifactRecord?: <Artifact extends TestArtifact>(test: Test, artifact: Artifact) => Promise<Artifact>;
|
||||
/**
|
||||
* Called before running all tests in collected paths.
|
||||
*/
|
||||
onBeforeRunFiles?: (files: File[]) => unknown;
|
||||
/**
|
||||
* Called right after running all tests in collected paths.
|
||||
*/
|
||||
onAfterRunFiles?: (files: File[]) => unknown;
|
||||
/**
|
||||
* Called when new context for a test is defined. Useful if you want to add custom properties to the context.
|
||||
* If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
|
||||
*
|
||||
* @see https://vitest.dev/advanced/runner#your-task-function
|
||||
*/
|
||||
extendTaskContext?: (context: TestContext) => TestContext;
|
||||
/**
|
||||
* Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files.
|
||||
*/
|
||||
importFile: (filepath: string, source: VitestRunnerImportSource) => unknown;
|
||||
/**
|
||||
* Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }`
|
||||
*/
|
||||
injectValue?: (key: string) => unknown;
|
||||
/**
|
||||
* Gets the time spent importing each individual non-externalized file that Vitest collected.
|
||||
*/
|
||||
getImportDurations?: () => Record<string, ImportDuration>;
|
||||
/**
|
||||
* Publicly available configuration.
|
||||
*/
|
||||
config: VitestRunnerConfig;
|
||||
/**
|
||||
* The name of the current pool. Can affect how stack trace is inferred on the server side.
|
||||
*/
|
||||
pool?: string;
|
||||
/**
|
||||
* The current Vite environment that processes the files on the server.
|
||||
*/
|
||||
viteEnvironment?: string;
|
||||
/**
|
||||
* Return the worker context for fixtures specified with `scope: 'worker'`
|
||||
*/
|
||||
getWorkerContext?: () => Record<string, unknown>;
|
||||
onCleanupWorkerContext?: (cleanup: () => unknown) => void;
|
||||
trace?<T>(name: string, cb: () => T): T;
|
||||
trace?<T>(name: string, attributes: Record<string, any>, cb: () => T): T;
|
||||
/** @private */
|
||||
_currentTaskStartTime?: number;
|
||||
/** @private */
|
||||
_currentTaskTimeout?: number;
|
||||
}
|
||||
|
||||
export { File, ImportDuration, SequenceHooks, SequenceSetupFiles, Suite, TaskEventPack, TaskResultPack, Test, TestAnnotation, TestArtifact, TestContext };
|
||||
export type { CancelReason, FileSpecification, VitestRunner, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource };
|
||||
1
node_modules/@vitest/runner/dist/types.js
generated
vendored
Normal file
1
node_modules/@vitest/runner/dist/types.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
45
node_modules/@vitest/runner/dist/utils.d.ts
generated
vendored
Normal file
45
node_modules/@vitest/runner/dist/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
import { S as Suite, F as File, T as Task, a as Test } from './tasks.d-Xu8VaPgy.js';
|
||||
export { C as ChainableFunction, c as createChainable } from './tasks.d-Xu8VaPgy.js';
|
||||
import { ParsedStack, Arrayable } from '@vitest/utils';
|
||||
|
||||
/**
|
||||
* If any tasks been marked as `only`, mark all other tasks as `skip`.
|
||||
*/
|
||||
declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void;
|
||||
declare function someTasksAreOnly(suite: Suite): boolean;
|
||||
declare function generateHash(str: string): string;
|
||||
declare function calculateSuiteHash(parent: Suite): void;
|
||||
declare function createFileTask(filepath: string, root: string, projectName: string | undefined, pool?: string, viteEnvironment?: string): File;
|
||||
/**
|
||||
* Generate a unique ID for a file based on its path and project name
|
||||
* @param file File relative to the root of the project to keep ID the same between different machines
|
||||
* @param projectName The name of the test project
|
||||
*/
|
||||
declare function generateFileHash(file: string, projectName: string | undefined): string;
|
||||
declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined;
|
||||
|
||||
/**
|
||||
* Return a function for running multiple async operations with limited concurrency.
|
||||
*/
|
||||
declare function limitConcurrency(concurrency?: number): <
|
||||
Args extends unknown[],
|
||||
T
|
||||
>(func: (...args: Args) => PromiseLike<T> | T, ...args: Args) => Promise<T>;
|
||||
|
||||
/**
|
||||
* Partition in tasks groups by consecutive concurrent
|
||||
*/
|
||||
declare function partitionSuiteChildren(suite: Suite): Task[][];
|
||||
|
||||
declare function isTestCase(s: Task): s is Test;
|
||||
declare function getTests(suite: Arrayable<Task>): Test[];
|
||||
declare function getTasks(tasks?: Arrayable<Task>): Task[];
|
||||
declare function getSuites(suite: Arrayable<Task>): Suite[];
|
||||
declare function hasTests(suite: Arrayable<Suite>): boolean;
|
||||
declare function hasFailed(suite: Arrayable<Task>): boolean;
|
||||
declare function getNames(task: Task): string[];
|
||||
declare function getFullName(task: Task, separator?: string): string;
|
||||
declare function getTestName(task: Task, separator?: string): string;
|
||||
declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string;
|
||||
|
||||
export { calculateSuiteHash, createFileTask, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, partitionSuiteChildren, someTasksAreOnly };
|
||||
5
node_modules/@vitest/runner/dist/utils.js
generated
vendored
Normal file
5
node_modules/@vitest/runner/dist/utils.js
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
export { a as calculateSuiteHash, c as createChainable, b as createFileTask, e as createTaskName, f as findTestFileStackTrace, g as generateFileHash, d as generateHash, h as getFullName, j as getNames, k as getSuites, m as getTasks, n as getTestName, o as getTests, q as hasFailed, r as hasTests, i as interpretTaskModes, t as isTestCase, l as limitConcurrency, p as partitionSuiteChildren, s as someTasksAreOnly } from './chunk-tasks.js';
|
||||
import '@vitest/utils/error';
|
||||
import '@vitest/utils/source-map';
|
||||
import 'pathe';
|
||||
import '@vitest/utils/helpers';
|
||||
48
node_modules/@vitest/runner/package.json
generated
vendored
Normal file
48
node_modules/@vitest/runner/package.json
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "@vitest/runner",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Vitest test runner",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/runner#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/runner"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": true,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./dist/utils.d.ts",
|
||||
"default": "./dist/utils.js"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./dist/types.d.ts",
|
||||
"default": "./dist/types.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"dependencies": {
|
||||
"pathe": "^2.0.3",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
1
node_modules/@vitest/runner/types.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/runner/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './dist/types.js'
|
||||
1
node_modules/@vitest/runner/utils.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/runner/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './dist/utils.js'
|
||||
21
node_modules/@vitest/snapshot/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/snapshot/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
84
node_modules/@vitest/snapshot/README.md
generated
vendored
Normal file
84
node_modules/@vitest/snapshot/README.md
generated
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
# @vitest/snapshot
|
||||
|
||||
Lightweight implementation of Jest's snapshots.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { SnapshotClient } from '@vitest/snapshot'
|
||||
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment'
|
||||
import { SnapshotManager } from '@vitest/snapshot/manager'
|
||||
|
||||
const client = new SnapshotClient({
|
||||
// you need to provide your own equality check implementation if you use it
|
||||
// this function is called when `.toMatchSnapshot({ property: 1 })` is called
|
||||
isEqual: (received, expected) =>
|
||||
equals(received, expected, [iterableEquality, subsetEquality]),
|
||||
})
|
||||
|
||||
// class that implements snapshot saving and reading
|
||||
// by default uses fs module, but you can provide your own implementation depending on the environment
|
||||
const environment = new NodeSnapshotEnvironment()
|
||||
|
||||
// you need to implement this yourselves,
|
||||
// this depends on your runner
|
||||
function getCurrentFilepath() {
|
||||
return '/file.spec.js'
|
||||
}
|
||||
function getCurrentTestName() {
|
||||
return 'test1'
|
||||
}
|
||||
|
||||
// example for inline snapshots, nothing is required to support regular snapshots,
|
||||
// just call `assert` with `isInline: false`
|
||||
function wrapper(received) {
|
||||
function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
|
||||
client.assert({
|
||||
received,
|
||||
message,
|
||||
isInline: true,
|
||||
inlineSnapshot,
|
||||
filepath: getCurrentFilepath(),
|
||||
name: getCurrentTestName(),
|
||||
})
|
||||
}
|
||||
return {
|
||||
// the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2)
|
||||
// you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor
|
||||
toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args),
|
||||
}
|
||||
}
|
||||
|
||||
const options = {
|
||||
updateSnapshot: 'new',
|
||||
snapshotEnvironment: environment,
|
||||
}
|
||||
|
||||
await client.startCurrentRun(
|
||||
getCurrentFilepath(),
|
||||
getCurrentTestName(),
|
||||
options
|
||||
)
|
||||
|
||||
// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath"
|
||||
client.assert({
|
||||
received: 'some text',
|
||||
isInline: false,
|
||||
})
|
||||
|
||||
// uses "pretty-format", so it requires quotes
|
||||
// also naming is hard-coded when parsing test files
|
||||
wrapper('text 1').toMatchInlineSnapshot()
|
||||
wrapper('text 2').toMatchInlineSnapshot('"text 2"')
|
||||
|
||||
const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult
|
||||
|
||||
// you can use manager to manage several clients
|
||||
const manager = new SnapshotManager(options)
|
||||
manager.add(result)
|
||||
|
||||
// do something
|
||||
// and then read the summary
|
||||
|
||||
console.log(manager.summary)
|
||||
```
|
||||
22
node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts
generated
vendored
Normal file
22
node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
interface ParsedStack {
|
||||
method: string;
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
interface SnapshotEnvironment {
|
||||
getVersion: () => string;
|
||||
getHeader: () => string;
|
||||
resolvePath: (filepath: string) => Promise<string>;
|
||||
resolveRawPath: (testPath: string, rawPath: string) => Promise<string>;
|
||||
saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>;
|
||||
readSnapshotFile: (filepath: string) => Promise<string | null>;
|
||||
removeSnapshotFile: (filepath: string) => Promise<void>;
|
||||
processStackTrace?: (stack: ParsedStack) => ParsedStack;
|
||||
}
|
||||
interface SnapshotEnvironmentOptions {
|
||||
snapshotsDirName?: string;
|
||||
}
|
||||
|
||||
export type { ParsedStack as P, SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };
|
||||
16
node_modules/@vitest/snapshot/dist/environment.d.ts
generated
vendored
Normal file
16
node_modules/@vitest/snapshot/dist/environment.d.ts
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DHdQ1Csl.js';
|
||||
|
||||
declare class NodeSnapshotEnvironment implements SnapshotEnvironment {
|
||||
private options;
|
||||
constructor(options?: SnapshotEnvironmentOptions);
|
||||
getVersion(): string;
|
||||
getHeader(): string;
|
||||
resolveRawPath(testPath: string, rawPath: string): Promise<string>;
|
||||
resolvePath(filepath: string): Promise<string>;
|
||||
prepareDirectory(dirPath: string): Promise<void>;
|
||||
saveSnapshotFile(filepath: string, snapshot: string): Promise<void>;
|
||||
readSnapshotFile(filepath: string): Promise<string | null>;
|
||||
removeSnapshotFile(filepath: string): Promise<void>;
|
||||
}
|
||||
|
||||
export { NodeSnapshotEnvironment, SnapshotEnvironment };
|
||||
40
node_modules/@vitest/snapshot/dist/environment.js
generated
vendored
Normal file
40
node_modules/@vitest/snapshot/dist/environment.js
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
import { promises, existsSync } from 'node:fs';
|
||||
import { resolve, isAbsolute, dirname, join, basename } from 'pathe';
|
||||
|
||||
class NodeSnapshotEnvironment {
|
||||
constructor(options = {}) {
|
||||
this.options = options;
|
||||
}
|
||||
getVersion() {
|
||||
return "1";
|
||||
}
|
||||
getHeader() {
|
||||
return `// Snapshot v${this.getVersion()}`;
|
||||
}
|
||||
async resolveRawPath(testPath, rawPath) {
|
||||
return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath);
|
||||
}
|
||||
async resolvePath(filepath) {
|
||||
return join(join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), `${basename(filepath)}.snap`);
|
||||
}
|
||||
async prepareDirectory(dirPath) {
|
||||
await promises.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
async saveSnapshotFile(filepath, snapshot) {
|
||||
await promises.mkdir(dirname(filepath), { recursive: true });
|
||||
await promises.writeFile(filepath, snapshot, "utf-8");
|
||||
}
|
||||
async readSnapshotFile(filepath) {
|
||||
if (!existsSync(filepath)) {
|
||||
return null;
|
||||
}
|
||||
return promises.readFile(filepath, "utf-8");
|
||||
}
|
||||
async removeSnapshotFile(filepath) {
|
||||
if (existsSync(filepath)) {
|
||||
await promises.unlink(filepath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { NodeSnapshotEnvironment };
|
||||
130
node_modules/@vitest/snapshot/dist/index.d.ts
generated
vendored
Normal file
130
node_modules/@vitest/snapshot/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,130 @@
|
||||
import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-lFsMJFUd.js';
|
||||
export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-lFsMJFUd.js';
|
||||
import { S as SnapshotEnvironment, P as ParsedStack } from './environment.d-DHdQ1Csl.js';
|
||||
import { Plugin, Plugins } from '@vitest/pretty-format';
|
||||
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
declare class DefaultMap<
|
||||
K,
|
||||
V
|
||||
> extends Map<K, V> {
|
||||
private defaultFn;
|
||||
constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>);
|
||||
get(key: K): V;
|
||||
}
|
||||
declare class CounterMap<K> extends DefaultMap<K, number> {
|
||||
constructor();
|
||||
_total: number | undefined;
|
||||
valueOf(): number;
|
||||
increment(key: K): void;
|
||||
total(): number;
|
||||
}
|
||||
|
||||
interface SnapshotReturnOptions {
|
||||
actual: string;
|
||||
count: number;
|
||||
expected?: string;
|
||||
key: string;
|
||||
pass: boolean;
|
||||
}
|
||||
interface SaveStatus {
|
||||
deleted: boolean;
|
||||
saved: boolean;
|
||||
}
|
||||
declare class SnapshotState {
|
||||
testFilePath: string;
|
||||
snapshotPath: string;
|
||||
private _counters;
|
||||
private _dirty;
|
||||
private _updateSnapshot;
|
||||
private _snapshotData;
|
||||
private _initialData;
|
||||
private _inlineSnapshots;
|
||||
private _inlineSnapshotStacks;
|
||||
private _testIdToKeys;
|
||||
private _rawSnapshots;
|
||||
private _uncheckedKeys;
|
||||
private _snapshotFormat;
|
||||
private _environment;
|
||||
private _fileExists;
|
||||
expand: boolean;
|
||||
private _added;
|
||||
private _matched;
|
||||
private _unmatched;
|
||||
private _updated;
|
||||
get added(): CounterMap<string>;
|
||||
set added(value: number);
|
||||
get matched(): CounterMap<string>;
|
||||
set matched(value: number);
|
||||
get unmatched(): CounterMap<string>;
|
||||
set unmatched(value: number);
|
||||
get updated(): CounterMap<string>;
|
||||
set updated(value: number);
|
||||
private constructor();
|
||||
static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
|
||||
get environment(): SnapshotEnvironment;
|
||||
markSnapshotsAsCheckedForTest(testName: string): void;
|
||||
clearTest(testId: string): void;
|
||||
protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
|
||||
private _addSnapshot;
|
||||
save(): Promise<SaveStatus>;
|
||||
getUncheckedCount(): number;
|
||||
getUncheckedKeys(): Array<string>;
|
||||
removeUncheckedKeys(): void;
|
||||
match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }: SnapshotMatchOptions): SnapshotReturnOptions;
|
||||
pack(): Promise<SnapshotResult>;
|
||||
}
|
||||
|
||||
interface AssertOptions {
|
||||
received: unknown;
|
||||
filepath: string;
|
||||
name: string;
|
||||
/**
|
||||
* Not required but needed for `SnapshotClient.clearTest` to implement test-retry behavior.
|
||||
* @default name
|
||||
*/
|
||||
testId?: string;
|
||||
message?: string;
|
||||
isInline?: boolean;
|
||||
properties?: object;
|
||||
inlineSnapshot?: string;
|
||||
error?: Error;
|
||||
errorMessage?: string;
|
||||
rawSnapshot?: RawSnapshotInfo;
|
||||
}
|
||||
interface SnapshotClientOptions {
|
||||
isEqual?: (received: unknown, expected: unknown) => boolean;
|
||||
}
|
||||
declare class SnapshotClient {
|
||||
private options;
|
||||
snapshotStateMap: Map<string, SnapshotState>;
|
||||
constructor(options?: SnapshotClientOptions);
|
||||
setup(filepath: string, options: SnapshotStateOptions): Promise<void>;
|
||||
finish(filepath: string): Promise<SnapshotResult>;
|
||||
skipTest(filepath: string, testName: string): void;
|
||||
clearTest(filepath: string, testId: string): void;
|
||||
getSnapshotState(filepath: string): SnapshotState;
|
||||
assert(options: AssertOptions): void;
|
||||
assertRaw(options: AssertOptions): Promise<void>;
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
declare function stripSnapshotIndentation(inlineSnapshot: string): string;
|
||||
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
declare function addSerializer(plugin: Plugin): void;
|
||||
declare function getSerializers(): Plugins;
|
||||
|
||||
export { SnapshotClient, SnapshotEnvironment, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation };
|
||||
1437
node_modules/@vitest/snapshot/dist/index.js
generated
vendored
Normal file
1437
node_modules/@vitest/snapshot/dist/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
18
node_modules/@vitest/snapshot/dist/manager.d.ts
generated
vendored
Normal file
18
node_modules/@vitest/snapshot/dist/manager.d.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-lFsMJFUd.js';
|
||||
import '@vitest/pretty-format';
|
||||
import './environment.d-DHdQ1Csl.js';
|
||||
|
||||
declare class SnapshotManager {
|
||||
options: Omit<SnapshotStateOptions, "snapshotEnvironment">;
|
||||
summary: SnapshotSummary;
|
||||
extension: string;
|
||||
constructor(options: Omit<SnapshotStateOptions, "snapshotEnvironment">);
|
||||
clear(): void;
|
||||
add(result: SnapshotResult): void;
|
||||
resolvePath<T = any>(testPath: string, context?: T): string;
|
||||
resolveRawPath(testPath: string, rawPath: string): string;
|
||||
}
|
||||
declare function emptySummary(options: Omit<SnapshotStateOptions, "snapshotEnvironment">): SnapshotSummary;
|
||||
declare function addSnapshotResult(summary: SnapshotSummary, result: SnapshotResult): void;
|
||||
|
||||
export { SnapshotManager, addSnapshotResult, emptySummary };
|
||||
73
node_modules/@vitest/snapshot/dist/manager.js
generated
vendored
Normal file
73
node_modules/@vitest/snapshot/dist/manager.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
import { join, dirname, basename, resolve, isAbsolute } from 'pathe';
|
||||
|
||||
class SnapshotManager {
|
||||
summary;
|
||||
extension = ".snap";
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.clear();
|
||||
}
|
||||
clear() {
|
||||
this.summary = emptySummary(this.options);
|
||||
}
|
||||
add(result) {
|
||||
addSnapshotResult(this.summary, result);
|
||||
}
|
||||
resolvePath(testPath, context) {
|
||||
const resolver = this.options.resolveSnapshotPath || (() => {
|
||||
return join(join(dirname(testPath), "__snapshots__"), `${basename(testPath)}${this.extension}`);
|
||||
});
|
||||
const path = resolver(testPath, this.extension, context);
|
||||
return path;
|
||||
}
|
||||
resolveRawPath(testPath, rawPath) {
|
||||
return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath);
|
||||
}
|
||||
}
|
||||
function emptySummary(options) {
|
||||
const summary = {
|
||||
added: 0,
|
||||
failure: false,
|
||||
filesAdded: 0,
|
||||
filesRemoved: 0,
|
||||
filesRemovedList: [],
|
||||
filesUnmatched: 0,
|
||||
filesUpdated: 0,
|
||||
matched: 0,
|
||||
total: 0,
|
||||
unchecked: 0,
|
||||
uncheckedKeysByFile: [],
|
||||
unmatched: 0,
|
||||
updated: 0,
|
||||
didUpdate: options.updateSnapshot === "all"
|
||||
};
|
||||
return summary;
|
||||
}
|
||||
function addSnapshotResult(summary, result) {
|
||||
if (result.added) {
|
||||
summary.filesAdded++;
|
||||
}
|
||||
if (result.fileDeleted) {
|
||||
summary.filesRemoved++;
|
||||
}
|
||||
if (result.unmatched) {
|
||||
summary.filesUnmatched++;
|
||||
}
|
||||
if (result.updated) {
|
||||
summary.filesUpdated++;
|
||||
}
|
||||
summary.added += result.added;
|
||||
summary.matched += result.matched;
|
||||
summary.unchecked += result.unchecked;
|
||||
if (result.uncheckedKeys && result.uncheckedKeys.length > 0) {
|
||||
summary.uncheckedKeysByFile.push({
|
||||
filePath: result.filepath,
|
||||
keys: result.uncheckedKeys
|
||||
});
|
||||
}
|
||||
summary.unmatched += result.unmatched;
|
||||
summary.updated += result.updated;
|
||||
summary.total += result.added + result.matched + result.unmatched + result.updated;
|
||||
}
|
||||
|
||||
export { SnapshotManager, addSnapshotResult, emptySummary };
|
||||
61
node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts
generated
vendored
Normal file
61
node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import { OptionsReceived, Plugin } from '@vitest/pretty-format';
|
||||
import { S as SnapshotEnvironment } from './environment.d-DHdQ1Csl.js';
|
||||
|
||||
type SnapshotData = Record<string, string>;
|
||||
type SnapshotUpdateState = "all" | "new" | "none";
|
||||
type SnapshotSerializer = Plugin;
|
||||
interface SnapshotStateOptions {
|
||||
updateSnapshot: SnapshotUpdateState;
|
||||
snapshotEnvironment: SnapshotEnvironment;
|
||||
expand?: boolean;
|
||||
snapshotFormat?: OptionsReceived;
|
||||
resolveSnapshotPath?: (path: string, extension: string, context?: any) => string;
|
||||
}
|
||||
interface SnapshotMatchOptions {
|
||||
testId: string;
|
||||
testName: string;
|
||||
received: unknown;
|
||||
key?: string;
|
||||
inlineSnapshot?: string;
|
||||
isInline: boolean;
|
||||
error?: Error;
|
||||
rawSnapshot?: RawSnapshotInfo;
|
||||
}
|
||||
interface SnapshotResult {
|
||||
filepath: string;
|
||||
added: number;
|
||||
fileDeleted: boolean;
|
||||
matched: number;
|
||||
unchecked: number;
|
||||
uncheckedKeys: Array<string>;
|
||||
unmatched: number;
|
||||
updated: number;
|
||||
}
|
||||
interface UncheckedSnapshot {
|
||||
filePath: string;
|
||||
keys: Array<string>;
|
||||
}
|
||||
interface SnapshotSummary {
|
||||
added: number;
|
||||
didUpdate: boolean;
|
||||
failure: boolean;
|
||||
filesAdded: number;
|
||||
filesRemoved: number;
|
||||
filesRemovedList: Array<string>;
|
||||
filesUnmatched: number;
|
||||
filesUpdated: number;
|
||||
matched: number;
|
||||
total: number;
|
||||
unchecked: number;
|
||||
uncheckedKeysByFile: Array<UncheckedSnapshot>;
|
||||
unmatched: number;
|
||||
updated: number;
|
||||
}
|
||||
|
||||
interface RawSnapshotInfo {
|
||||
file: string;
|
||||
readonly?: boolean;
|
||||
content?: string;
|
||||
}
|
||||
|
||||
export type { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotSerializer as d, SnapshotSummary as e, SnapshotUpdateState as f };
|
||||
1
node_modules/@vitest/snapshot/environment.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/snapshot/environment.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './dist/environment.js'
|
||||
1
node_modules/@vitest/snapshot/manager.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/snapshot/manager.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './dist/manager.js'
|
||||
54
node_modules/@vitest/snapshot/package.json
generated
vendored
Normal file
54
node_modules/@vitest/snapshot/package.json
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@vitest/snapshot",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Vitest snapshot manager",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/snapshot#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/snapshot"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./environment": {
|
||||
"types": "./dist/environment.d.ts",
|
||||
"default": "./dist/environment.js"
|
||||
},
|
||||
"./manager": {
|
||||
"types": "./dist/manager.d.ts",
|
||||
"default": "./dist/manager.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"dependencies": {
|
||||
"magic-string": "^0.30.21",
|
||||
"pathe": "^2.0.3",
|
||||
"@vitest/pretty-format": "4.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/natural-compare": "^1.4.3",
|
||||
"natural-compare": "^1.4.0",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
21
node_modules/@vitest/spy/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/spy/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
3
node_modules/@vitest/spy/README.md
generated
vendored
Normal file
3
node_modules/@vitest/spy/README.md
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# @vitest/spy
|
||||
|
||||
Lightweight Jest compatible spy implementation.
|
||||
384
node_modules/@vitest/spy/dist/index.d.ts
generated
vendored
Normal file
384
node_modules/@vitest/spy/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,384 @@
|
||||
interface MockResultReturn<T> {
|
||||
type: "return";
|
||||
/**
|
||||
* The value that was returned from the function. If function returned a Promise, then this will be a resolved value.
|
||||
*/
|
||||
value: T;
|
||||
}
|
||||
interface MockResultIncomplete {
|
||||
type: "incomplete";
|
||||
value: undefined;
|
||||
}
|
||||
interface MockResultThrow {
|
||||
type: "throw";
|
||||
/**
|
||||
* An error that was thrown during function execution.
|
||||
*/
|
||||
value: any;
|
||||
}
|
||||
interface MockSettledResultIncomplete {
|
||||
type: "incomplete";
|
||||
value: undefined;
|
||||
}
|
||||
interface MockSettledResultFulfilled<T> {
|
||||
type: "fulfilled";
|
||||
value: T;
|
||||
}
|
||||
interface MockSettledResultRejected {
|
||||
type: "rejected";
|
||||
value: any;
|
||||
}
|
||||
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
|
||||
type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected | MockSettledResultIncomplete;
|
||||
type MockParameters<T extends Procedure | Constructable> = T extends Constructable ? ConstructorParameters<T> : T extends Procedure ? Parameters<T> : never;
|
||||
type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? void : T extends Procedure ? ReturnType<T> : never;
|
||||
type MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>;
|
||||
interface MockContext<T extends Procedure | Constructable = Procedure> {
|
||||
/**
|
||||
* This is an array containing all arguments for each call. One item of the array is the arguments of that call.
|
||||
*
|
||||
* @see https://vitest.dev/api/mock#mock-calls
|
||||
* @example
|
||||
* const fn = vi.fn()
|
||||
*
|
||||
* fn('arg1', 'arg2')
|
||||
* fn('arg3')
|
||||
*
|
||||
* fn.mock.calls === [
|
||||
* ['arg1', 'arg2'], // first call
|
||||
* ['arg3'], // second call
|
||||
* ]
|
||||
*/
|
||||
calls: MockParameters<T>[];
|
||||
/**
|
||||
* This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value.
|
||||
* @see https://vitest.dev/api/mock#mock-instances
|
||||
*/
|
||||
instances: MockProcedureContext<T>[];
|
||||
/**
|
||||
* An array of `this` values that were used during each call to the mock function.
|
||||
* @see https://vitest.dev/api/mock#mock-contexts
|
||||
*/
|
||||
contexts: MockProcedureContext<T>[];
|
||||
/**
|
||||
* The order of mock's execution. This returns an array of numbers which are shared between all defined mocks.
|
||||
*
|
||||
* @see https://vitest.dev/api/mock#mock-invocationcallorder
|
||||
* @example
|
||||
* const fn1 = vi.fn()
|
||||
* const fn2 = vi.fn()
|
||||
*
|
||||
* fn1()
|
||||
* fn2()
|
||||
* fn1()
|
||||
*
|
||||
* fn1.mock.invocationCallOrder === [1, 3]
|
||||
* fn2.mock.invocationCallOrder === [2]
|
||||
*/
|
||||
invocationCallOrder: number[];
|
||||
/**
|
||||
* This is an array containing all values that were `returned` from the function.
|
||||
*
|
||||
* The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected.
|
||||
*
|
||||
* @see https://vitest.dev/api/mock#mock-results
|
||||
* @example
|
||||
* const fn = vi.fn()
|
||||
* .mockReturnValueOnce('result')
|
||||
* .mockImplementationOnce(() => { throw new Error('thrown error') })
|
||||
*
|
||||
* const result = fn()
|
||||
*
|
||||
* try {
|
||||
* fn()
|
||||
* }
|
||||
* catch {}
|
||||
*
|
||||
* fn.mock.results === [
|
||||
* {
|
||||
* type: 'return',
|
||||
* value: 'result',
|
||||
* },
|
||||
* {
|
||||
* type: 'throw',
|
||||
* value: Error,
|
||||
* },
|
||||
* ]
|
||||
*/
|
||||
results: MockResult<MockReturnType<T>>[];
|
||||
/**
|
||||
* An array containing all values that were `resolved` or `rejected` from the function.
|
||||
*
|
||||
* This array will be empty if the function was never resolved or rejected.
|
||||
*
|
||||
* @see https://vitest.dev/api/mock#mock-settledresults
|
||||
* @example
|
||||
* const fn = vi.fn().mockResolvedValueOnce('result')
|
||||
*
|
||||
* const result = fn()
|
||||
*
|
||||
* fn.mock.settledResults === [
|
||||
* {
|
||||
* type: 'incomplete',
|
||||
* value: undefined,
|
||||
* }
|
||||
* ]
|
||||
* fn.mock.results === [
|
||||
* {
|
||||
* type: 'return',
|
||||
* value: Promise<'result'>,
|
||||
* },
|
||||
* ]
|
||||
*
|
||||
* await result
|
||||
*
|
||||
* fn.mock.settledResults === [
|
||||
* {
|
||||
* type: 'fulfilled',
|
||||
* value: 'result',
|
||||
* },
|
||||
* ]
|
||||
*/
|
||||
settledResults: MockSettledResult<Awaited<MockReturnType<T>>>[];
|
||||
/**
|
||||
* This contains the arguments of the last call. If spy wasn't called, will return `undefined`.
|
||||
* @see https://vitest.dev/api/mock#mock-lastcall
|
||||
*/
|
||||
lastCall: MockParameters<T> | undefined;
|
||||
}
|
||||
type Procedure = (...args: any[]) => any;
|
||||
type NormalizedProcedure<T extends Procedure | Constructable> = T extends Constructable ? ({
|
||||
new (...args: ConstructorParameters<T>): InstanceType<T>;
|
||||
}) | ({
|
||||
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
|
||||
}) : T extends Procedure ? (...args: Parameters<T>) => ReturnType<T> : never;
|
||||
type Methods<T> = keyof { [K in keyof T as T[K] extends Procedure ? K : never] : T[K] };
|
||||
type Properties<T> = { [K in keyof T] : T[K] extends Procedure ? never : K }[keyof T] & (string | symbol);
|
||||
type Classes<T> = { [K in keyof T] : T[K] extends new (...args: any[]) => any ? K : never }[keyof T] & (string | symbol);
|
||||
interface MockInstance<T extends Procedure | Constructable = Procedure> extends Disposable {
|
||||
/**
|
||||
* Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.
|
||||
* @see https://vitest.dev/api/mock#getmockname
|
||||
*/
|
||||
getMockName(): string;
|
||||
/**
|
||||
* Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
|
||||
* @see https://vitest.dev/api/mock#mockname
|
||||
*/
|
||||
mockName(name: string): this;
|
||||
/**
|
||||
* Current context of the mock. It stores information about all invocation calls, instances, and results.
|
||||
*/
|
||||
mock: MockContext<T>;
|
||||
/**
|
||||
* Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
|
||||
*
|
||||
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration.
|
||||
* @see https://vitest.dev/api/mock#mockclear
|
||||
*/
|
||||
mockClear(): this;
|
||||
/**
|
||||
* Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations.
|
||||
*
|
||||
* Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`.
|
||||
* Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state.
|
||||
*
|
||||
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration.
|
||||
* @see https://vitest.dev/api/mock#mockreset
|
||||
*/
|
||||
mockReset(): this;
|
||||
/**
|
||||
* Does what `mockReset` does and restores original descriptors of spied-on objects.
|
||||
* @see https://vitest.dev/api/mock#mockrestore
|
||||
*/
|
||||
mockRestore(): void;
|
||||
/**
|
||||
* Returns current permanent mock implementation if there is one.
|
||||
*
|
||||
* If mock was created with `vi.fn`, it will consider passed down method as a mock implementation.
|
||||
*
|
||||
* If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided.
|
||||
*/
|
||||
getMockImplementation(): NormalizedProcedure<T> | undefined;
|
||||
/**
|
||||
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
|
||||
* @see https://vitest.dev/api/mock#mockimplementation
|
||||
* @example
|
||||
* const increment = vi.fn().mockImplementation(count => count + 1);
|
||||
* expect(increment(3)).toBe(4);
|
||||
*/
|
||||
mockImplementation(fn: NormalizedProcedure<T>): this;
|
||||
/**
|
||||
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.
|
||||
*
|
||||
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
|
||||
* @see https://vitest.dev/api/mock#mockimplementationonce
|
||||
* @example
|
||||
* const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1);
|
||||
* expect(fn(3)).toBe(4);
|
||||
* expect(fn(3)).toBe(3);
|
||||
*/
|
||||
mockImplementationOnce(fn: NormalizedProcedure<T>): this;
|
||||
/**
|
||||
* Overrides the original mock implementation temporarily while the callback is being executed.
|
||||
*
|
||||
* Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce).
|
||||
* @see https://vitest.dev/api/mock#withimplementation
|
||||
* @example
|
||||
* const myMockFn = vi.fn(() => 'original')
|
||||
*
|
||||
* myMockFn.withImplementation(() => 'temp', () => {
|
||||
* myMockFn() // 'temp'
|
||||
* })
|
||||
*
|
||||
* myMockFn() // 'original'
|
||||
*/
|
||||
withImplementation(fn: NormalizedProcedure<T>, cb: () => Promise<unknown>): Promise<this>;
|
||||
withImplementation(fn: NormalizedProcedure<T>, cb: () => unknown): this;
|
||||
/**
|
||||
* Use this if you need to return the `this` context from the method without invoking the actual implementation.
|
||||
* @see https://vitest.dev/api/mock#mockreturnthis
|
||||
*/
|
||||
mockReturnThis(): this;
|
||||
/**
|
||||
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
|
||||
* @see https://vitest.dev/api/mock#mockreturnvalue
|
||||
* @example
|
||||
* const mock = vi.fn()
|
||||
* mock.mockReturnValue(42)
|
||||
* mock() // 42
|
||||
* mock.mockReturnValue(43)
|
||||
* mock() // 43
|
||||
*/
|
||||
mockReturnValue(value: MockReturnType<T>): this;
|
||||
/**
|
||||
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
|
||||
*
|
||||
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
|
||||
* @example
|
||||
* const myMockFn = vi
|
||||
* .fn()
|
||||
* .mockReturnValue('default')
|
||||
* .mockReturnValueOnce('first call')
|
||||
* .mockReturnValueOnce('second call')
|
||||
*
|
||||
* // 'first call', 'second call', 'default'
|
||||
* console.log(myMockFn(), myMockFn(), myMockFn())
|
||||
*/
|
||||
mockReturnValueOnce(value: MockReturnType<T>): this;
|
||||
/**
|
||||
* Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
|
||||
* @example
|
||||
* const asyncMock = vi.fn().mockResolvedValue(42)
|
||||
* asyncMock() // Promise<42>
|
||||
*/
|
||||
mockResolvedValue(value: Awaited<MockReturnType<T>>): this;
|
||||
/**
|
||||
* Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.
|
||||
* @example
|
||||
* const myMockFn = vi
|
||||
* .fn()
|
||||
* .mockResolvedValue('default')
|
||||
* .mockResolvedValueOnce('first call')
|
||||
* .mockResolvedValueOnce('second call')
|
||||
*
|
||||
* // Promise<'first call'>, Promise<'second call'>, Promise<'default'>
|
||||
* console.log(myMockFn(), myMockFn(), myMockFn())
|
||||
*/
|
||||
mockResolvedValueOnce(value: Awaited<MockReturnType<T>>): this;
|
||||
/**
|
||||
* Accepts an error that will be rejected when async function is called.
|
||||
* @example
|
||||
* const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
|
||||
* await asyncMock() // throws Error<'Async error'>
|
||||
*/
|
||||
mockRejectedValue(error: unknown): this;
|
||||
/**
|
||||
* Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
|
||||
* @example
|
||||
* const asyncMock = vi
|
||||
* .fn()
|
||||
* .mockResolvedValueOnce('first call')
|
||||
* .mockRejectedValueOnce(new Error('Async error'))
|
||||
*
|
||||
* await asyncMock() // first call
|
||||
* await asyncMock() // throws Error<'Async error'>
|
||||
*/
|
||||
mockRejectedValueOnce(error: unknown): this;
|
||||
}
|
||||
type Mock<T extends Procedure | Constructable = Procedure> = MockInstance<T> & (T extends Constructable ? (T extends Procedure ? {
|
||||
new (...args: ConstructorParameters<T>): InstanceType<T>;
|
||||
(...args: Parameters<T>): ReturnType<T>;
|
||||
} : {
|
||||
new (...args: ConstructorParameters<T>): InstanceType<T>;
|
||||
}) : {
|
||||
new (...args: MockParameters<T>): MockReturnType<T>;
|
||||
(...args: MockParameters<T>): MockReturnType<T>;
|
||||
}) & { [P in keyof T] : T[P] };
|
||||
type PartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<Partial<Awaited<T>>> : Partial<T>;
|
||||
type PartialResultFunction<T> = T extends Constructable ? ({
|
||||
new (...args: ConstructorParameters<T>): InstanceType<T>;
|
||||
}) | ({
|
||||
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
|
||||
}) : T extends Procedure ? (...args: Parameters<T>) => PartialMaybePromise<ReturnType<T>> : T;
|
||||
type PartialMock<T extends Procedure | Constructable = Procedure> = Mock<PartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
|
||||
type MaybeMockedConstructor<T> = T extends Constructable ? Mock<T> : T;
|
||||
type MockedFunction<T extends Procedure | Constructable> = Mock<T> & { [K in keyof T] : T[K] };
|
||||
type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & { [K in keyof T] : T[K] };
|
||||
type MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>;
|
||||
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartialMock<T> & MockedObjectDeep<T>;
|
||||
type MockedObject<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunction<T[K]> : T[K] } & { [K in Properties<T>] : T[K] };
|
||||
type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K] } & { [K in Properties<T>] : MaybeMockedDeep<T[K]> };
|
||||
type MaybeMockedDeep<T> = T extends Procedure | Constructable ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
|
||||
type MaybePartiallyMockedDeep<T> = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
|
||||
type MaybeMocked<T> = T extends Procedure | Constructable ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
|
||||
type MaybePartiallyMocked<T> = T extends Procedure | Constructable ? PartiallyMockedFunction<T> : T extends object ? MockedObject<T> : T;
|
||||
interface Constructable {
|
||||
new (...args: any[]): any;
|
||||
}
|
||||
type MockedClass<T extends Constructable> = MockInstance<T> & {
|
||||
prototype: T extends {
|
||||
prototype: any;
|
||||
} ? Mocked<T["prototype"]> : never;
|
||||
} & T;
|
||||
type Mocked<T> = { [P in keyof T] : T[P] extends Procedure ? MockInstance<T[P]> : T[P] extends Constructable ? MockedClass<T[P]> : T[P] } & T;
|
||||
interface MockConfig {
|
||||
mockImplementation: Procedure | Constructable | undefined;
|
||||
mockOriginal: Procedure | Constructable | undefined;
|
||||
mockName: string;
|
||||
onceMockImplementations: Array<Procedure | Constructable>;
|
||||
}
|
||||
interface MockInstanceOption {
|
||||
originalImplementation?: Procedure | Constructable;
|
||||
mockImplementation?: Procedure | Constructable;
|
||||
resetToMockImplementation?: boolean;
|
||||
restore?: () => void;
|
||||
prototypeMembers?: (string | symbol)[];
|
||||
keepMembersImplementation?: boolean;
|
||||
prototypeState?: MockContext;
|
||||
prototypeConfig?: MockConfig;
|
||||
resetToMockName?: boolean;
|
||||
name?: string | symbol;
|
||||
}
|
||||
|
||||
declare function isMockFunction(fn: any): fn is Mock;
|
||||
declare function createMockInstance(options?: MockInstanceOption): Mock<Procedure | Constructable>;
|
||||
declare function fn<T extends Procedure | Constructable = Procedure>(originalImplementation?: T): Mock<T>;
|
||||
declare function spyOn<
|
||||
T extends object,
|
||||
S extends Properties<Required<T>>
|
||||
>(object: T, key: S, accessor: "get"): Mock<() => T[S]>;
|
||||
declare function spyOn<
|
||||
T extends object,
|
||||
G extends Properties<Required<T>>
|
||||
>(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>;
|
||||
declare function spyOn<
|
||||
T extends object,
|
||||
M extends Classes<Required<T>> | Methods<Required<T>>
|
||||
>(object: T, key: M): Required<T>[M] extends Constructable | Procedure ? Mock<Required<T>[M]> : never;
|
||||
declare function restoreAllMocks(): void;
|
||||
declare function clearAllMocks(): void;
|
||||
declare function resetAllMocks(): void;
|
||||
|
||||
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };
|
||||
export type { Constructable, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep, Mock, MockContext, MockInstance, MockInstanceOption, MockParameters, MockProcedureContext, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockReturnType, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, PartialMock, PartiallyMockedFunction, PartiallyMockedFunctionDeep, Procedure };
|
||||
433
node_modules/@vitest/spy/dist/index.js
generated
vendored
Normal file
433
node_modules/@vitest/spy/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,433 @@
|
||||
function isMockFunction(fn) {
|
||||
return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true;
|
||||
}
|
||||
const MOCK_RESTORE = new Set();
|
||||
// Jest keeps the state in a separate WeakMap which is good for memory,
|
||||
// but it makes the state slower to access and return different values
|
||||
// if you stored it before calling `mockClear` where it will be recreated
|
||||
const REGISTERED_MOCKS = new Set();
|
||||
const MOCK_CONFIGS = new WeakMap();
|
||||
function createMockInstance(options = {}) {
|
||||
var _ref;
|
||||
const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options;
|
||||
if (restore) {
|
||||
MOCK_RESTORE.add(restore);
|
||||
}
|
||||
const config = getDefaultConfig(originalImplementation);
|
||||
const state = getDefaultState();
|
||||
const mock = createMock({
|
||||
config,
|
||||
state,
|
||||
...options
|
||||
});
|
||||
const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0;
|
||||
Object.defineProperty(mock, "length", {
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
value: mockLength,
|
||||
configurable: true
|
||||
});
|
||||
// inherit the default name so it appears in snapshots and logs
|
||||
// this is used by `vi.spyOn()` for better debugging.
|
||||
// when `vi.fn()` is called, we just use the default string
|
||||
if (resetToMockName) {
|
||||
config.mockName = mock.name || "vi.fn()";
|
||||
}
|
||||
MOCK_CONFIGS.set(mock, config);
|
||||
REGISTERED_MOCKS.add(mock);
|
||||
mock._isMockFunction = true;
|
||||
mock.getMockImplementation = () => {
|
||||
// Jest only returns `config.mockImplementation` here,
|
||||
// but we think it makes sense to return what the next function will be called
|
||||
return config.onceMockImplementations[0] || config.mockImplementation;
|
||||
};
|
||||
Object.defineProperty(mock, "mock", {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
writable: false,
|
||||
value: state
|
||||
});
|
||||
mock.mockImplementation = function mockImplementation(implementation) {
|
||||
config.mockImplementation = implementation;
|
||||
return mock;
|
||||
};
|
||||
mock.mockImplementationOnce = function mockImplementationOnce(implementation) {
|
||||
config.onceMockImplementations.push(implementation);
|
||||
return mock;
|
||||
};
|
||||
mock.withImplementation = function withImplementation(implementation, callback) {
|
||||
const previousImplementation = config.mockImplementation;
|
||||
const previousOnceImplementations = config.onceMockImplementations;
|
||||
const reset = () => {
|
||||
config.mockImplementation = previousImplementation;
|
||||
config.onceMockImplementations = previousOnceImplementations;
|
||||
};
|
||||
config.mockImplementation = implementation;
|
||||
config.onceMockImplementations = [];
|
||||
const returnValue = callback();
|
||||
if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") {
|
||||
return returnValue.then(() => {
|
||||
reset();
|
||||
return mock;
|
||||
});
|
||||
} else {
|
||||
reset();
|
||||
}
|
||||
return mock;
|
||||
};
|
||||
mock.mockReturnThis = function mockReturnThis() {
|
||||
return mock.mockImplementation(function() {
|
||||
return this;
|
||||
});
|
||||
};
|
||||
mock.mockReturnValue = function mockReturnValue(value) {
|
||||
return mock.mockImplementation(() => value);
|
||||
};
|
||||
mock.mockReturnValueOnce = function mockReturnValueOnce(value) {
|
||||
return mock.mockImplementationOnce(() => value);
|
||||
};
|
||||
mock.mockResolvedValue = function mockResolvedValue(value) {
|
||||
return mock.mockImplementation(() => Promise.resolve(value));
|
||||
};
|
||||
mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) {
|
||||
return mock.mockImplementationOnce(() => Promise.resolve(value));
|
||||
};
|
||||
mock.mockRejectedValue = function mockRejectedValue(value) {
|
||||
return mock.mockImplementation(() => Promise.reject(value));
|
||||
};
|
||||
mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) {
|
||||
return mock.mockImplementationOnce(() => Promise.reject(value));
|
||||
};
|
||||
mock.mockClear = function mockClear() {
|
||||
state.calls = [];
|
||||
state.contexts = [];
|
||||
state.instances = [];
|
||||
state.invocationCallOrder = [];
|
||||
state.results = [];
|
||||
state.settledResults = [];
|
||||
return mock;
|
||||
};
|
||||
mock.mockReset = function mockReset() {
|
||||
mock.mockClear();
|
||||
config.mockImplementation = resetToMockImplementation ? mockImplementation : undefined;
|
||||
config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()";
|
||||
config.onceMockImplementations = [];
|
||||
return mock;
|
||||
};
|
||||
mock.mockRestore = function mockRestore() {
|
||||
mock.mockReset();
|
||||
return restore === null || restore === void 0 ? void 0 : restore();
|
||||
};
|
||||
mock.mockName = function mockName(name) {
|
||||
if (typeof name === "string") {
|
||||
config.mockName = name;
|
||||
}
|
||||
return mock;
|
||||
};
|
||||
mock.getMockName = function getMockName() {
|
||||
return config.mockName || "vi.fn()";
|
||||
};
|
||||
if (Symbol.dispose) {
|
||||
mock[Symbol.dispose] = () => mock.mockRestore();
|
||||
}
|
||||
if (mockImplementation) {
|
||||
mock.mockImplementation(mockImplementation);
|
||||
}
|
||||
return mock;
|
||||
}
|
||||
function fn(originalImplementation) {
|
||||
// if the function is already a mock, just return the same function,
|
||||
// simillarly to how vi.spyOn() works
|
||||
if (originalImplementation != null && isMockFunction(originalImplementation)) {
|
||||
return originalImplementation;
|
||||
}
|
||||
return createMockInstance({
|
||||
mockImplementation: originalImplementation,
|
||||
resetToMockImplementation: true
|
||||
});
|
||||
}
|
||||
function spyOn(object, key, accessor) {
|
||||
assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined.");
|
||||
assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value.");
|
||||
const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || [];
|
||||
assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`);
|
||||
let accessType = accessor || "value";
|
||||
let ssr = false;
|
||||
// vite ssr support - actual function is stored inside a getter
|
||||
if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) {
|
||||
accessType = "get";
|
||||
ssr = true;
|
||||
}
|
||||
let original;
|
||||
if (originalDescriptor) {
|
||||
original = originalDescriptor[accessType];
|
||||
} else if (accessType !== "value") {
|
||||
original = () => object[key];
|
||||
} else {
|
||||
original = object[key];
|
||||
}
|
||||
const originalImplementation = ssr && original ? original() : original;
|
||||
const originalType = typeof originalImplementation;
|
||||
assert(
|
||||
// allow only functions
|
||||
originalType === "function" || accessType !== "value" && original == null,
|
||||
`vi.spyOn() can only spy on a function. Received ${originalType}.`
|
||||
);
|
||||
if (isMockFunction(originalImplementation)) {
|
||||
return originalImplementation;
|
||||
}
|
||||
const reassign = (cb) => {
|
||||
const { value, ...desc } = originalDescriptor || {
|
||||
configurable: true,
|
||||
writable: true
|
||||
};
|
||||
if (accessType !== "value") {
|
||||
delete desc.writable;
|
||||
}
|
||||
desc[accessType] = cb;
|
||||
Object.defineProperty(object, key, desc);
|
||||
};
|
||||
const restore = () => {
|
||||
// if method is defined on the prototype, we can just remove it from
|
||||
// the current object instead of redefining a copy of it
|
||||
if (originalDescriptorObject !== object) {
|
||||
Reflect.deleteProperty(object, key);
|
||||
} else if (originalDescriptor && !original) {
|
||||
Object.defineProperty(object, key, originalDescriptor);
|
||||
} else {
|
||||
reassign(original);
|
||||
}
|
||||
};
|
||||
const mock = createMockInstance({
|
||||
restore,
|
||||
originalImplementation,
|
||||
resetToMockName: true
|
||||
});
|
||||
try {
|
||||
reassign(ssr ? () => mock : mock);
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) {
|
||||
throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return mock;
|
||||
}
|
||||
function getDescriptor(obj, method) {
|
||||
const objDescriptor = Object.getOwnPropertyDescriptor(obj, method);
|
||||
if (objDescriptor) {
|
||||
return [obj, objDescriptor];
|
||||
}
|
||||
let currentProto = Object.getPrototypeOf(obj);
|
||||
while (currentProto !== null) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(currentProto, method);
|
||||
if (descriptor) {
|
||||
return [currentProto, descriptor];
|
||||
}
|
||||
currentProto = Object.getPrototypeOf(currentProto);
|
||||
}
|
||||
}
|
||||
function assert(condition, message) {
|
||||
if (!condition) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
let invocationCallCounter = 1;
|
||||
function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) {
|
||||
const original = config.mockOriginal;
|
||||
const pseudoOriginal = mockImplementation;
|
||||
const name = mockName || (original === null || original === void 0 ? void 0 : original.name) || "Mock";
|
||||
const namedObject = { [name]: (function(...args) {
|
||||
registerCalls(args, state, prototypeState);
|
||||
registerInvocationOrder(invocationCallCounter++, state, prototypeState);
|
||||
const result = {
|
||||
type: "incomplete",
|
||||
value: undefined
|
||||
};
|
||||
const settledResult = {
|
||||
type: "incomplete",
|
||||
value: undefined
|
||||
};
|
||||
registerResult(result, state, prototypeState);
|
||||
registerSettledResult(settledResult, state, prototypeState);
|
||||
const context = new.target ? undefined : this;
|
||||
const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState);
|
||||
const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState);
|
||||
const implementation = config.onceMockImplementations.shift() || config.mockImplementation || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.onceMockImplementations.shift()) || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockImplementation) || original || function() {};
|
||||
let returnValue;
|
||||
let thrownValue;
|
||||
let didThrow = false;
|
||||
try {
|
||||
if (new.target) {
|
||||
returnValue = Reflect.construct(implementation, args, new.target);
|
||||
// jest calls this before the implementation, but we have to resolve this _after_
|
||||
// because we cannot do it before the `Reflect.construct` called the custom implementation.
|
||||
// fortunetly, the constructor is always an empty functon because `prototypeMethods`
|
||||
// are only used by the automocker, so this doesn't matter
|
||||
for (const prop of prototypeMembers) {
|
||||
const prototypeMock = returnValue[prop];
|
||||
// the method was overidden because of inheritence, ignore it
|
||||
// eslint-disable-next-line ts/no-use-before-define
|
||||
if (prototypeMock !== mock.prototype[prop]) {
|
||||
continue;
|
||||
}
|
||||
const isMock = isMockFunction(prototypeMock);
|
||||
const prototypeState = isMock ? prototypeMock.mock : undefined;
|
||||
const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined;
|
||||
returnValue[prop] = createMockInstance({
|
||||
originalImplementation: keepMembersImplementation ? prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockOriginal : undefined,
|
||||
prototypeState,
|
||||
prototypeConfig,
|
||||
keepMembersImplementation
|
||||
});
|
||||
}
|
||||
} else {
|
||||
returnValue = implementation.apply(this, args);
|
||||
}
|
||||
} catch (error) {
|
||||
thrownValue = error;
|
||||
didThrow = true;
|
||||
if (error instanceof TypeError && error.message.includes("is not a constructor")) {
|
||||
console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (didThrow) {
|
||||
result.type = "throw";
|
||||
result.value = thrownValue;
|
||||
settledResult.type = "rejected";
|
||||
settledResult.value = thrownValue;
|
||||
} else {
|
||||
result.type = "return";
|
||||
result.value = returnValue;
|
||||
if (new.target) {
|
||||
state.contexts[contextIndex - 1] = returnValue;
|
||||
state.instances[instanceIndex - 1] = returnValue;
|
||||
if (contextPrototypeIndex != null && prototypeState) {
|
||||
prototypeState.contexts[contextPrototypeIndex - 1] = returnValue;
|
||||
}
|
||||
if (instancePrototypeIndex != null && prototypeState) {
|
||||
prototypeState.instances[instancePrototypeIndex - 1] = returnValue;
|
||||
}
|
||||
}
|
||||
if (returnValue instanceof Promise) {
|
||||
returnValue.then((settledValue) => {
|
||||
settledResult.type = "fulfilled";
|
||||
settledResult.value = settledValue;
|
||||
}, (rejectedValue) => {
|
||||
settledResult.type = "rejected";
|
||||
settledResult.value = rejectedValue;
|
||||
});
|
||||
} else {
|
||||
settledResult.type = "fulfilled";
|
||||
settledResult.value = returnValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnValue;
|
||||
}) };
|
||||
const mock = namedObject[name];
|
||||
const copyPropertiesFrom = original || pseudoOriginal;
|
||||
if (copyPropertiesFrom) {
|
||||
copyOriginalStaticProperties(mock, copyPropertiesFrom);
|
||||
}
|
||||
return mock;
|
||||
}
|
||||
function registerCalls(args, state, prototypeState) {
|
||||
state.calls.push(args);
|
||||
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args);
|
||||
}
|
||||
function registerInvocationOrder(order, state, prototypeState) {
|
||||
state.invocationCallOrder.push(order);
|
||||
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order);
|
||||
}
|
||||
function registerResult(result, state, prototypeState) {
|
||||
state.results.push(result);
|
||||
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result);
|
||||
}
|
||||
function registerSettledResult(result, state, prototypeState) {
|
||||
state.settledResults.push(result);
|
||||
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.settledResults.push(result);
|
||||
}
|
||||
function registerInstance(instance, state, prototypeState) {
|
||||
const instanceIndex = state.instances.push(instance);
|
||||
const instancePrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.instances.push(instance);
|
||||
return [instanceIndex, instancePrototypeIndex];
|
||||
}
|
||||
function registerContext(context, state, prototypeState) {
|
||||
const contextIndex = state.contexts.push(context);
|
||||
const contextPrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.contexts.push(context);
|
||||
return [contextIndex, contextPrototypeIndex];
|
||||
}
|
||||
function copyOriginalStaticProperties(mock, original) {
|
||||
const { properties, descriptors } = getAllProperties(original);
|
||||
for (const key of properties) {
|
||||
const descriptor = descriptors[key];
|
||||
const mockDescriptor = getDescriptor(mock, key);
|
||||
if (mockDescriptor) {
|
||||
continue;
|
||||
}
|
||||
Object.defineProperty(mock, key, descriptor);
|
||||
}
|
||||
}
|
||||
const ignoreProperties = new Set([
|
||||
"length",
|
||||
"name",
|
||||
"prototype",
|
||||
Symbol.for("nodejs.util.promisify.custom")
|
||||
]);
|
||||
function getAllProperties(original) {
|
||||
const properties = new Set();
|
||||
const descriptors = {};
|
||||
while (original && original !== Object.prototype && original !== Function.prototype) {
|
||||
const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)];
|
||||
for (const prop of ownProperties) {
|
||||
if (descriptors[prop] || ignoreProperties.has(prop)) {
|
||||
continue;
|
||||
}
|
||||
properties.add(prop);
|
||||
descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop);
|
||||
}
|
||||
original = Object.getPrototypeOf(original);
|
||||
}
|
||||
return {
|
||||
properties,
|
||||
descriptors
|
||||
};
|
||||
}
|
||||
function getDefaultConfig(original) {
|
||||
return {
|
||||
mockImplementation: undefined,
|
||||
mockOriginal: original,
|
||||
mockName: "vi.fn()",
|
||||
onceMockImplementations: []
|
||||
};
|
||||
}
|
||||
function getDefaultState() {
|
||||
const state = {
|
||||
calls: [],
|
||||
contexts: [],
|
||||
instances: [],
|
||||
invocationCallOrder: [],
|
||||
settledResults: [],
|
||||
results: [],
|
||||
get lastCall() {
|
||||
return state.calls.at(-1);
|
||||
}
|
||||
};
|
||||
return state;
|
||||
}
|
||||
function restoreAllMocks() {
|
||||
for (const restore of MOCK_RESTORE) {
|
||||
restore();
|
||||
}
|
||||
MOCK_RESTORE.clear();
|
||||
}
|
||||
function clearAllMocks() {
|
||||
REGISTERED_MOCKS.forEach((mock) => mock.mockClear());
|
||||
}
|
||||
function resetAllMocks() {
|
||||
REGISTERED_MOCKS.forEach((mock) => mock.mockReset());
|
||||
}
|
||||
|
||||
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };
|
||||
35
node_modules/@vitest/spy/package.json
generated
vendored
Normal file
35
node_modules/@vitest/spy/package.json
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@vitest/spy",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "Lightweight Jest compatible spy implementation",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/spy"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
"dev": "rollup -c --watch"
|
||||
}
|
||||
}
|
||||
21
node_modules/@vitest/ui/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/ui/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
29
node_modules/@vitest/ui/README.md
generated
vendored
Normal file
29
node_modules/@vitest/ui/README.md
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
# @vitest/ui
|
||||
|
||||
This package is for UI interface of Vitest.
|
||||
|
||||
## Development Setup
|
||||
|
||||
At project root, create terminals with each of the following commands:
|
||||
|
||||
```bash
|
||||
nr ui:dev
|
||||
```
|
||||
|
||||
```bash
|
||||
nr test --api
|
||||
```
|
||||
|
||||
As the last command, you can use any of the available tests suites instead. Make sure that they run at 51204 port or specify a custom port with `VITE_PORT` environmental variable when running the first command. For example,
|
||||
|
||||
```bash
|
||||
VITE_PORT=3200 nr ui:dev
|
||||
```
|
||||
|
||||
```bash
|
||||
nr test --api=3200
|
||||
```
|
||||
|
||||
Open the browser at the URL printed by the first command. For example, `http://localhost:5173/`. If you see a connection error, it means the port is specified incorrectly.
|
||||
|
||||
To preview the browser tab, uncomment the "browser-dev-preview" plugin in `vite.config.ts`. To configure the browser state, update the `__vitest_browser_runner__` object in `browser.dev.js`.
|
||||
57
node_modules/@vitest/ui/dist/client/assets/index-CfDzoXo3.js
generated
vendored
Normal file
57
node_modules/@vitest/ui/dist/client/assets/index-CfDzoXo3.js
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1
node_modules/@vitest/ui/dist/client/assets/index-DlhE0rqZ.css
generated
vendored
Normal file
1
node_modules/@vitest/ui/dist/client/assets/index-DlhE0rqZ.css
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
BIN
node_modules/@vitest/ui/dist/client/bg.png
generated
vendored
Normal file
BIN
node_modules/@vitest/ui/dist/client/bg.png
generated
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 186 KiB |
BIN
node_modules/@vitest/ui/dist/client/favicon.ico
generated
vendored
Normal file
BIN
node_modules/@vitest/ui/dist/client/favicon.ico
generated
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 814 B |
5
node_modules/@vitest/ui/dist/client/favicon.svg
generated
vendored
Normal file
5
node_modules/@vitest/ui/dist/client/favicon.svg
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg width="165" height="165" viewBox="0 0 165 165" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M120.831 57.2543L84.693 109.505C84.3099 110.059 83.7558 110.474 83.1148 110.687C82.4738 110.9 81.7809 110.898 81.1412 110.684C80.5015 110.469 79.95 110.052 79.5702 109.497C79.1905 108.941 79.0032 108.277 79.037 107.606L80.4833 78.7582L57.1343 73.8064C56.6353 73.7007 56.1704 73.474 55.7807 73.1465C55.391 72.8191 55.0885 72.4009 54.9001 71.929C54.7117 71.4571 54.6432 70.9461 54.7006 70.4412C54.758 69.9364 54.9395 69.4532 55.2291 69.0345L91.3675 16.7837C91.7507 16.2294 92.3048 15.8145 92.9458 15.6018C93.5869 15.3891 94.2798 15.3902 94.9196 15.6051C95.5593 15.8199 96.1109 16.2367 96.4906 16.7923C96.8703 17.3478 97.0575 18.0117 97.0236 18.6833L95.5773 47.5314L118.926 52.4828C119.425 52.5885 119.89 52.8152 120.28 53.1426C120.67 53.4701 120.972 53.8883 121.16 54.3602C121.349 54.8321 121.417 55.3431 121.36 55.8479C121.303 56.3528 121.121 56.836 120.831 57.2547L120.831 57.2543Z" fill="#FCC72B"/>
|
||||
<path d="M82.9866 153.343C82.0254 153.344 81.0735 153.156 80.1855 152.788C79.2975 152.42 78.4909 151.88 77.8122 151.2L43.6658 117.056C42.2998 115.683 41.5341 113.824 41.5366 111.887C41.5392 109.95 42.3098 108.092 43.6796 106.723C45.0493 105.353 46.9064 104.582 48.8435 104.579C50.7807 104.577 52.6399 105.342 54.0134 106.708L82.9866 135.678L146.105 72.5626C147.481 71.2088 149.336 70.4536 151.266 70.4615C153.197 70.4693 155.046 71.2396 156.41 72.6045C157.775 73.9695 158.546 75.8184 158.554 77.7487C158.561 79.679 157.806 81.5342 156.452 82.9101L88.1597 151.2C87.4811 151.881 86.6747 152.42 85.7869 152.788C84.8992 153.156 83.9475 153.344 82.9866 153.343Z" fill="#729B1B"/>
|
||||
<path d="M82.9572 153.343C83.9184 153.344 84.8703 153.156 85.7583 152.788C86.6463 152.42 87.4528 151.88 88.1316 151.2L122.278 117.056C123.644 115.683 124.41 113.824 124.407 111.887C124.405 109.95 123.634 108.092 122.264 106.723C120.894 105.353 119.037 104.582 117.1 104.579C115.163 104.577 113.304 105.342 111.93 106.708L82.9572 135.678L19.8389 72.5626C18.4629 71.2088 16.6077 70.4536 14.6775 70.4615C12.7472 70.4693 10.8982 71.2396 9.53331 72.6045C8.16839 73.9695 7.39811 75.8184 7.39025 77.7487C7.38239 79.679 8.13759 81.5342 9.49135 82.9101L77.784 151.2C78.4627 151.881 79.2691 152.42 80.1568 152.788C81.0446 153.156 81.9963 153.344 82.9572 153.343Z" fill="#729B1B" fill-opacity="0.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
32
node_modules/@vitest/ui/dist/client/index.html
generated
vendored
Normal file
32
node_modules/@vitest/ui/dist/client/index.html
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="./favicon.ico" sizes="48x48">
|
||||
<link rel="icon" href="./favicon.svg" sizes="any" type="image/svg+xml">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vitest</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Readex+Pro:wght@300;400&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<script>
|
||||
(function () {
|
||||
const prefersDark =
|
||||
window.matchMedia &&
|
||||
window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
const setting = localStorage.getItem("vueuse-color-scheme") || "auto";
|
||||
if (setting === "dark" || (prefersDark && setting !== "light"))
|
||||
document.documentElement.classList.toggle("dark", true);
|
||||
})();
|
||||
</script>
|
||||
<!-- !LOAD_METADATA! -->
|
||||
<script type="module" src="./assets/index-CfDzoXo3.js"></script>
|
||||
<link rel="stylesheet" href="./assets/index-DlhE0rqZ.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
6
node_modules/@vitest/ui/dist/index.d.ts
generated
vendored
Normal file
6
node_modules/@vitest/ui/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import { Plugin } from 'vite';
|
||||
import { Vitest } from 'vitest/node';
|
||||
|
||||
declare const _default: (ctx: Vitest) => Plugin;
|
||||
|
||||
export { _default as default };
|
||||
111
node_modules/@vitest/ui/dist/index.js
generated
vendored
Normal file
111
node_modules/@vitest/ui/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
import fs from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { toArray } from '@vitest/utils/helpers';
|
||||
import { resolve, basename } from 'pathe';
|
||||
import sirv from 'sirv';
|
||||
import c from 'tinyrainbow';
|
||||
import { coverageConfigDefaults } from 'vitest/config';
|
||||
import { isValidApiRequest, isFileServingAllowed } from 'vitest/node';
|
||||
|
||||
var version = "4.0.15";
|
||||
|
||||
var index = (ctx) => {
|
||||
if (ctx.version !== version) {
|
||||
ctx.logger.warn(c.yellow(`Loaded ${c.inverse(c.yellow(` vitest@${ctx.version} `))} and ${c.inverse(c.yellow(` @vitest/ui@${version} `))}.` + "\nRunning mixed versions is not supported and may lead into bugs" + "\nUpdate your dependencies and make sure the versions match."));
|
||||
}
|
||||
return {
|
||||
name: "vitest:ui",
|
||||
apply: "serve",
|
||||
configureServer: {
|
||||
order: "post",
|
||||
handler(server) {
|
||||
const uiOptions = ctx.config;
|
||||
const base = uiOptions.uiBase;
|
||||
const coverageFolder = resolveCoverageFolder(ctx);
|
||||
const coveragePath = coverageFolder ? coverageFolder[1] : undefined;
|
||||
if (coveragePath && base === coveragePath) {
|
||||
throw new Error(`The ui base path and the coverage path cannot be the same: ${base}, change coverage.reportsDirectory`);
|
||||
}
|
||||
if (coverageFolder) {
|
||||
server.middlewares.use(coveragePath, sirv(coverageFolder[0], {
|
||||
single: true,
|
||||
dev: true,
|
||||
setHeaders: (res) => {
|
||||
res.setHeader("Cache-Control", "public,max-age=0,must-revalidate");
|
||||
}
|
||||
}));
|
||||
}
|
||||
const clientDist = resolve(fileURLToPath(import.meta.url), "../client");
|
||||
const clientIndexHtml = fs.readFileSync(resolve(clientDist, "index.html"), "utf-8");
|
||||
// eslint-disable-next-line prefer-arrow-callback
|
||||
server.middlewares.use(function vitestAttachment(req, res, next) {
|
||||
if (!req.url) {
|
||||
return next();
|
||||
}
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/__vitest_attachment__") {
|
||||
const path = url.searchParams.get("path");
|
||||
const contentType = url.searchParams.get("contentType");
|
||||
// ignore invalid requests
|
||||
if (!isValidApiRequest(ctx.config, req) || !contentType || !path) {
|
||||
return next();
|
||||
}
|
||||
const fsPath = decodeURIComponent(path);
|
||||
if (!isFileServingAllowed(ctx.vite.config, fsPath)) {
|
||||
return next();
|
||||
}
|
||||
try {
|
||||
res.writeHead(200, { "content-type": contentType });
|
||||
fs.createReadStream(fsPath).pipe(res).on("close", () => res.end());
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
// serve index.html with api token
|
||||
// eslint-disable-next-line prefer-arrow-callback
|
||||
server.middlewares.use(function vitestUiHtmlMiddleware(req, res, next) {
|
||||
if (req.url) {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === base) {
|
||||
const html = clientIndexHtml.replace("<!-- !LOAD_METADATA! -->", `<script>window.VITEST_API_TOKEN = ${JSON.stringify(ctx.config.api.token)}<\/script>`);
|
||||
res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.write(html);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
server.middlewares.use(base, sirv(clientDist, {
|
||||
single: true,
|
||||
dev: true
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
function resolveCoverageFolder(ctx) {
|
||||
const options = ctx.config;
|
||||
const htmlReporter = options.api?.port && options.coverage?.enabled ? toArray(options.coverage.reporter).find((reporter) => {
|
||||
if (typeof reporter === "string") {
|
||||
return reporter === "html";
|
||||
}
|
||||
return reporter[0] === "html";
|
||||
}) : undefined;
|
||||
if (!htmlReporter) {
|
||||
return undefined;
|
||||
}
|
||||
// reportsDirectory not resolved yet
|
||||
const root = resolve(ctx.config?.root || options.root || process.cwd(), options.coverage.reportsDirectory || coverageConfigDefaults.reportsDirectory);
|
||||
const subdir = Array.isArray(htmlReporter) && htmlReporter.length > 1 && "subdir" in htmlReporter[1] ? htmlReporter[1].subdir : undefined;
|
||||
if (!subdir || typeof subdir !== "string") {
|
||||
return [root, `/${basename(root)}/`];
|
||||
}
|
||||
return [resolve(root, subdir), `/${basename(root)}/${subdir}/`];
|
||||
}
|
||||
|
||||
export { index as default };
|
||||
656
node_modules/@vitest/ui/dist/reporter.js
generated
vendored
Normal file
656
node_modules/@vitest/ui/dist/reporter.js
generated
vendored
Normal file
@@ -0,0 +1,656 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { promises } from 'node:fs';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { gzip, constants } from 'node:zlib';
|
||||
import { stringify } from 'flatted';
|
||||
import { resolve, dirname, extname, relative } from 'pathe';
|
||||
import { globSync } from 'tinyglobby';
|
||||
import c from 'tinyrainbow';
|
||||
|
||||
const types = {
|
||||
'application/andrew-inset': ['ez'],
|
||||
'application/appinstaller': ['appinstaller'],
|
||||
'application/applixware': ['aw'],
|
||||
'application/appx': ['appx'],
|
||||
'application/appxbundle': ['appxbundle'],
|
||||
'application/atom+xml': ['atom'],
|
||||
'application/atomcat+xml': ['atomcat'],
|
||||
'application/atomdeleted+xml': ['atomdeleted'],
|
||||
'application/atomsvc+xml': ['atomsvc'],
|
||||
'application/atsc-dwd+xml': ['dwd'],
|
||||
'application/atsc-held+xml': ['held'],
|
||||
'application/atsc-rsat+xml': ['rsat'],
|
||||
'application/automationml-aml+xml': ['aml'],
|
||||
'application/automationml-amlx+zip': ['amlx'],
|
||||
'application/bdoc': ['bdoc'],
|
||||
'application/calendar+xml': ['xcs'],
|
||||
'application/ccxml+xml': ['ccxml'],
|
||||
'application/cdfx+xml': ['cdfx'],
|
||||
'application/cdmi-capability': ['cdmia'],
|
||||
'application/cdmi-container': ['cdmic'],
|
||||
'application/cdmi-domain': ['cdmid'],
|
||||
'application/cdmi-object': ['cdmio'],
|
||||
'application/cdmi-queue': ['cdmiq'],
|
||||
'application/cpl+xml': ['cpl'],
|
||||
'application/cu-seeme': ['cu'],
|
||||
'application/cwl': ['cwl'],
|
||||
'application/dash+xml': ['mpd'],
|
||||
'application/dash-patch+xml': ['mpp'],
|
||||
'application/davmount+xml': ['davmount'],
|
||||
'application/dicom': ['dcm'],
|
||||
'application/docbook+xml': ['dbk'],
|
||||
'application/dssc+der': ['dssc'],
|
||||
'application/dssc+xml': ['xdssc'],
|
||||
'application/ecmascript': ['ecma'],
|
||||
'application/emma+xml': ['emma'],
|
||||
'application/emotionml+xml': ['emotionml'],
|
||||
'application/epub+zip': ['epub'],
|
||||
'application/exi': ['exi'],
|
||||
'application/express': ['exp'],
|
||||
'application/fdf': ['fdf'],
|
||||
'application/fdt+xml': ['fdt'],
|
||||
'application/font-tdpfr': ['pfr'],
|
||||
'application/geo+json': ['geojson'],
|
||||
'application/gml+xml': ['gml'],
|
||||
'application/gpx+xml': ['gpx'],
|
||||
'application/gxf': ['gxf'],
|
||||
'application/gzip': ['gz'],
|
||||
'application/hjson': ['hjson'],
|
||||
'application/hyperstudio': ['stk'],
|
||||
'application/inkml+xml': ['ink', 'inkml'],
|
||||
'application/ipfix': ['ipfix'],
|
||||
'application/its+xml': ['its'],
|
||||
'application/java-archive': ['jar', 'war', 'ear'],
|
||||
'application/java-serialized-object': ['ser'],
|
||||
'application/java-vm': ['class'],
|
||||
'application/javascript': ['*js'],
|
||||
'application/json': ['json', 'map'],
|
||||
'application/json5': ['json5'],
|
||||
'application/jsonml+json': ['jsonml'],
|
||||
'application/ld+json': ['jsonld'],
|
||||
'application/lgr+xml': ['lgr'],
|
||||
'application/lost+xml': ['lostxml'],
|
||||
'application/mac-binhex40': ['hqx'],
|
||||
'application/mac-compactpro': ['cpt'],
|
||||
'application/mads+xml': ['mads'],
|
||||
'application/manifest+json': ['webmanifest'],
|
||||
'application/marc': ['mrc'],
|
||||
'application/marcxml+xml': ['mrcx'],
|
||||
'application/mathematica': ['ma', 'nb', 'mb'],
|
||||
'application/mathml+xml': ['mathml'],
|
||||
'application/mbox': ['mbox'],
|
||||
'application/media-policy-dataset+xml': ['mpf'],
|
||||
'application/mediaservercontrol+xml': ['mscml'],
|
||||
'application/metalink+xml': ['metalink'],
|
||||
'application/metalink4+xml': ['meta4'],
|
||||
'application/mets+xml': ['mets'],
|
||||
'application/mmt-aei+xml': ['maei'],
|
||||
'application/mmt-usd+xml': ['musd'],
|
||||
'application/mods+xml': ['mods'],
|
||||
'application/mp21': ['m21', 'mp21'],
|
||||
'application/mp4': ['*mp4', '*mpg4', 'mp4s', 'm4p'],
|
||||
'application/msix': ['msix'],
|
||||
'application/msixbundle': ['msixbundle'],
|
||||
'application/msword': ['doc', 'dot'],
|
||||
'application/mxf': ['mxf'],
|
||||
'application/n-quads': ['nq'],
|
||||
'application/n-triples': ['nt'],
|
||||
'application/node': ['cjs'],
|
||||
'application/octet-stream': [
|
||||
'bin',
|
||||
'dms',
|
||||
'lrf',
|
||||
'mar',
|
||||
'so',
|
||||
'dist',
|
||||
'distz',
|
||||
'pkg',
|
||||
'bpk',
|
||||
'dump',
|
||||
'elc',
|
||||
'deploy',
|
||||
'exe',
|
||||
'dll',
|
||||
'deb',
|
||||
'dmg',
|
||||
'iso',
|
||||
'img',
|
||||
'msi',
|
||||
'msp',
|
||||
'msm',
|
||||
'buffer',
|
||||
],
|
||||
'application/oda': ['oda'],
|
||||
'application/oebps-package+xml': ['opf'],
|
||||
'application/ogg': ['ogx'],
|
||||
'application/omdoc+xml': ['omdoc'],
|
||||
'application/onenote': [
|
||||
'onetoc',
|
||||
'onetoc2',
|
||||
'onetmp',
|
||||
'onepkg',
|
||||
'one',
|
||||
'onea',
|
||||
],
|
||||
'application/oxps': ['oxps'],
|
||||
'application/p2p-overlay+xml': ['relo'],
|
||||
'application/patch-ops-error+xml': ['xer'],
|
||||
'application/pdf': ['pdf'],
|
||||
'application/pgp-encrypted': ['pgp'],
|
||||
'application/pgp-keys': ['asc'],
|
||||
'application/pgp-signature': ['sig', '*asc'],
|
||||
'application/pics-rules': ['prf'],
|
||||
'application/pkcs10': ['p10'],
|
||||
'application/pkcs7-mime': ['p7m', 'p7c'],
|
||||
'application/pkcs7-signature': ['p7s'],
|
||||
'application/pkcs8': ['p8'],
|
||||
'application/pkix-attr-cert': ['ac'],
|
||||
'application/pkix-cert': ['cer'],
|
||||
'application/pkix-crl': ['crl'],
|
||||
'application/pkix-pkipath': ['pkipath'],
|
||||
'application/pkixcmp': ['pki'],
|
||||
'application/pls+xml': ['pls'],
|
||||
'application/postscript': ['ai', 'eps', 'ps'],
|
||||
'application/provenance+xml': ['provx'],
|
||||
'application/pskc+xml': ['pskcxml'],
|
||||
'application/raml+yaml': ['raml'],
|
||||
'application/rdf+xml': ['rdf', 'owl'],
|
||||
'application/reginfo+xml': ['rif'],
|
||||
'application/relax-ng-compact-syntax': ['rnc'],
|
||||
'application/resource-lists+xml': ['rl'],
|
||||
'application/resource-lists-diff+xml': ['rld'],
|
||||
'application/rls-services+xml': ['rs'],
|
||||
'application/route-apd+xml': ['rapd'],
|
||||
'application/route-s-tsid+xml': ['sls'],
|
||||
'application/route-usd+xml': ['rusd'],
|
||||
'application/rpki-ghostbusters': ['gbr'],
|
||||
'application/rpki-manifest': ['mft'],
|
||||
'application/rpki-roa': ['roa'],
|
||||
'application/rsd+xml': ['rsd'],
|
||||
'application/rss+xml': ['rss'],
|
||||
'application/rtf': ['rtf'],
|
||||
'application/sbml+xml': ['sbml'],
|
||||
'application/scvp-cv-request': ['scq'],
|
||||
'application/scvp-cv-response': ['scs'],
|
||||
'application/scvp-vp-request': ['spq'],
|
||||
'application/scvp-vp-response': ['spp'],
|
||||
'application/sdp': ['sdp'],
|
||||
'application/senml+xml': ['senmlx'],
|
||||
'application/sensml+xml': ['sensmlx'],
|
||||
'application/set-payment-initiation': ['setpay'],
|
||||
'application/set-registration-initiation': ['setreg'],
|
||||
'application/shf+xml': ['shf'],
|
||||
'application/sieve': ['siv', 'sieve'],
|
||||
'application/smil+xml': ['smi', 'smil'],
|
||||
'application/sparql-query': ['rq'],
|
||||
'application/sparql-results+xml': ['srx'],
|
||||
'application/sql': ['sql'],
|
||||
'application/srgs': ['gram'],
|
||||
'application/srgs+xml': ['grxml'],
|
||||
'application/sru+xml': ['sru'],
|
||||
'application/ssdl+xml': ['ssdl'],
|
||||
'application/ssml+xml': ['ssml'],
|
||||
'application/swid+xml': ['swidtag'],
|
||||
'application/tei+xml': ['tei', 'teicorpus'],
|
||||
'application/thraud+xml': ['tfi'],
|
||||
'application/timestamped-data': ['tsd'],
|
||||
'application/toml': ['toml'],
|
||||
'application/trig': ['trig'],
|
||||
'application/ttml+xml': ['ttml'],
|
||||
'application/ubjson': ['ubj'],
|
||||
'application/urc-ressheet+xml': ['rsheet'],
|
||||
'application/urc-targetdesc+xml': ['td'],
|
||||
'application/voicexml+xml': ['vxml'],
|
||||
'application/wasm': ['wasm'],
|
||||
'application/watcherinfo+xml': ['wif'],
|
||||
'application/widget': ['wgt'],
|
||||
'application/winhlp': ['hlp'],
|
||||
'application/wsdl+xml': ['wsdl'],
|
||||
'application/wspolicy+xml': ['wspolicy'],
|
||||
'application/xaml+xml': ['xaml'],
|
||||
'application/xcap-att+xml': ['xav'],
|
||||
'application/xcap-caps+xml': ['xca'],
|
||||
'application/xcap-diff+xml': ['xdf'],
|
||||
'application/xcap-el+xml': ['xel'],
|
||||
'application/xcap-ns+xml': ['xns'],
|
||||
'application/xenc+xml': ['xenc'],
|
||||
'application/xfdf': ['xfdf'],
|
||||
'application/xhtml+xml': ['xhtml', 'xht'],
|
||||
'application/xliff+xml': ['xlf'],
|
||||
'application/xml': ['xml', 'xsl', 'xsd', 'rng'],
|
||||
'application/xml-dtd': ['dtd'],
|
||||
'application/xop+xml': ['xop'],
|
||||
'application/xproc+xml': ['xpl'],
|
||||
'application/xslt+xml': ['*xsl', 'xslt'],
|
||||
'application/xspf+xml': ['xspf'],
|
||||
'application/xv+xml': ['mxml', 'xhvml', 'xvml', 'xvm'],
|
||||
'application/yang': ['yang'],
|
||||
'application/yin+xml': ['yin'],
|
||||
'application/zip': ['zip'],
|
||||
'application/zip+dotlottie': ['lottie'],
|
||||
'audio/3gpp': ['*3gpp'],
|
||||
'audio/aac': ['adts', 'aac'],
|
||||
'audio/adpcm': ['adp'],
|
||||
'audio/amr': ['amr'],
|
||||
'audio/basic': ['au', 'snd'],
|
||||
'audio/midi': ['mid', 'midi', 'kar', 'rmi'],
|
||||
'audio/mobile-xmf': ['mxmf'],
|
||||
'audio/mp3': ['*mp3'],
|
||||
'audio/mp4': ['m4a', 'mp4a', 'm4b'],
|
||||
'audio/mpeg': ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'],
|
||||
'audio/ogg': ['oga', 'ogg', 'spx', 'opus'],
|
||||
'audio/s3m': ['s3m'],
|
||||
'audio/silk': ['sil'],
|
||||
'audio/wav': ['wav'],
|
||||
'audio/wave': ['*wav'],
|
||||
'audio/webm': ['weba'],
|
||||
'audio/xm': ['xm'],
|
||||
'font/collection': ['ttc'],
|
||||
'font/otf': ['otf'],
|
||||
'font/ttf': ['ttf'],
|
||||
'font/woff': ['woff'],
|
||||
'font/woff2': ['woff2'],
|
||||
'image/aces': ['exr'],
|
||||
'image/apng': ['apng'],
|
||||
'image/avci': ['avci'],
|
||||
'image/avcs': ['avcs'],
|
||||
'image/avif': ['avif'],
|
||||
'image/bmp': ['bmp', 'dib'],
|
||||
'image/cgm': ['cgm'],
|
||||
'image/dicom-rle': ['drle'],
|
||||
'image/dpx': ['dpx'],
|
||||
'image/emf': ['emf'],
|
||||
'image/fits': ['fits'],
|
||||
'image/g3fax': ['g3'],
|
||||
'image/gif': ['gif'],
|
||||
'image/heic': ['heic'],
|
||||
'image/heic-sequence': ['heics'],
|
||||
'image/heif': ['heif'],
|
||||
'image/heif-sequence': ['heifs'],
|
||||
'image/hej2k': ['hej2'],
|
||||
'image/ief': ['ief'],
|
||||
'image/jaii': ['jaii'],
|
||||
'image/jais': ['jais'],
|
||||
'image/jls': ['jls'],
|
||||
'image/jp2': ['jp2', 'jpg2'],
|
||||
'image/jpeg': ['jpg', 'jpeg', 'jpe'],
|
||||
'image/jph': ['jph'],
|
||||
'image/jphc': ['jhc'],
|
||||
'image/jpm': ['jpm', 'jpgm'],
|
||||
'image/jpx': ['jpx', 'jpf'],
|
||||
'image/jxl': ['jxl'],
|
||||
'image/jxr': ['jxr'],
|
||||
'image/jxra': ['jxra'],
|
||||
'image/jxrs': ['jxrs'],
|
||||
'image/jxs': ['jxs'],
|
||||
'image/jxsc': ['jxsc'],
|
||||
'image/jxsi': ['jxsi'],
|
||||
'image/jxss': ['jxss'],
|
||||
'image/ktx': ['ktx'],
|
||||
'image/ktx2': ['ktx2'],
|
||||
'image/pjpeg': ['jfif'],
|
||||
'image/png': ['png'],
|
||||
'image/sgi': ['sgi'],
|
||||
'image/svg+xml': ['svg', 'svgz'],
|
||||
'image/t38': ['t38'],
|
||||
'image/tiff': ['tif', 'tiff'],
|
||||
'image/tiff-fx': ['tfx'],
|
||||
'image/webp': ['webp'],
|
||||
'image/wmf': ['wmf'],
|
||||
'message/disposition-notification': ['disposition-notification'],
|
||||
'message/global': ['u8msg'],
|
||||
'message/global-delivery-status': ['u8dsn'],
|
||||
'message/global-disposition-notification': ['u8mdn'],
|
||||
'message/global-headers': ['u8hdr'],
|
||||
'message/rfc822': ['eml', 'mime', 'mht', 'mhtml'],
|
||||
'model/3mf': ['3mf'],
|
||||
'model/gltf+json': ['gltf'],
|
||||
'model/gltf-binary': ['glb'],
|
||||
'model/iges': ['igs', 'iges'],
|
||||
'model/jt': ['jt'],
|
||||
'model/mesh': ['msh', 'mesh', 'silo'],
|
||||
'model/mtl': ['mtl'],
|
||||
'model/obj': ['obj'],
|
||||
'model/prc': ['prc'],
|
||||
'model/step': ['step', 'stp', 'stpnc', 'p21', '210'],
|
||||
'model/step+xml': ['stpx'],
|
||||
'model/step+zip': ['stpz'],
|
||||
'model/step-xml+zip': ['stpxz'],
|
||||
'model/stl': ['stl'],
|
||||
'model/u3d': ['u3d'],
|
||||
'model/vrml': ['wrl', 'vrml'],
|
||||
'model/x3d+binary': ['*x3db', 'x3dbz'],
|
||||
'model/x3d+fastinfoset': ['x3db'],
|
||||
'model/x3d+vrml': ['*x3dv', 'x3dvz'],
|
||||
'model/x3d+xml': ['x3d', 'x3dz'],
|
||||
'model/x3d-vrml': ['x3dv'],
|
||||
'text/cache-manifest': ['appcache', 'manifest'],
|
||||
'text/calendar': ['ics', 'ifb'],
|
||||
'text/coffeescript': ['coffee', 'litcoffee'],
|
||||
'text/css': ['css'],
|
||||
'text/csv': ['csv'],
|
||||
'text/html': ['html', 'htm', 'shtml'],
|
||||
'text/jade': ['jade'],
|
||||
'text/javascript': ['js', 'mjs'],
|
||||
'text/jsx': ['jsx'],
|
||||
'text/less': ['less'],
|
||||
'text/markdown': ['md', 'markdown'],
|
||||
'text/mathml': ['mml'],
|
||||
'text/mdx': ['mdx'],
|
||||
'text/n3': ['n3'],
|
||||
'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in', 'ini'],
|
||||
'text/richtext': ['rtx'],
|
||||
'text/rtf': ['*rtf'],
|
||||
'text/sgml': ['sgml', 'sgm'],
|
||||
'text/shex': ['shex'],
|
||||
'text/slim': ['slim', 'slm'],
|
||||
'text/spdx': ['spdx'],
|
||||
'text/stylus': ['stylus', 'styl'],
|
||||
'text/tab-separated-values': ['tsv'],
|
||||
'text/troff': ['t', 'tr', 'roff', 'man', 'me', 'ms'],
|
||||
'text/turtle': ['ttl'],
|
||||
'text/uri-list': ['uri', 'uris', 'urls'],
|
||||
'text/vcard': ['vcard'],
|
||||
'text/vtt': ['vtt'],
|
||||
'text/wgsl': ['wgsl'],
|
||||
'text/xml': ['*xml'],
|
||||
'text/yaml': ['yaml', 'yml'],
|
||||
'video/3gpp': ['3gp', '3gpp'],
|
||||
'video/3gpp2': ['3g2'],
|
||||
'video/h261': ['h261'],
|
||||
'video/h263': ['h263'],
|
||||
'video/h264': ['h264'],
|
||||
'video/iso.segment': ['m4s'],
|
||||
'video/jpeg': ['jpgv'],
|
||||
'video/jpm': ['*jpm', '*jpgm'],
|
||||
'video/mj2': ['mj2', 'mjp2'],
|
||||
'video/mp2t': ['ts', 'm2t', 'm2ts', 'mts'],
|
||||
'video/mp4': ['mp4', 'mp4v', 'mpg4'],
|
||||
'video/mpeg': ['mpeg', 'mpg', 'mpe', 'm1v', 'm2v'],
|
||||
'video/ogg': ['ogv'],
|
||||
'video/quicktime': ['qt', 'mov'],
|
||||
'video/webm': ['webm'],
|
||||
};
|
||||
Object.freeze(types);
|
||||
|
||||
var __classPrivateFieldGet = ({} && {}.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
||||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
||||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
||||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
||||
};
|
||||
var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;
|
||||
class Mime {
|
||||
constructor(...args) {
|
||||
_Mime_extensionToType.set(this, new Map());
|
||||
_Mime_typeToExtension.set(this, new Map());
|
||||
_Mime_typeToExtensions.set(this, new Map());
|
||||
for (const arg of args) {
|
||||
this.define(arg);
|
||||
}
|
||||
}
|
||||
define(typeMap, force = false) {
|
||||
for (let [type, extensions] of Object.entries(typeMap)) {
|
||||
type = type.toLowerCase();
|
||||
extensions = extensions.map((ext) => ext.toLowerCase());
|
||||
if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
|
||||
__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, new Set());
|
||||
}
|
||||
const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
|
||||
let first = true;
|
||||
for (let extension of extensions) {
|
||||
const starred = extension.startsWith('*');
|
||||
extension = starred ? extension.slice(1) : extension;
|
||||
allExtensions?.add(extension);
|
||||
if (first) {
|
||||
__classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
|
||||
}
|
||||
first = false;
|
||||
if (starred)
|
||||
continue;
|
||||
const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
|
||||
if (currentType && currentType != type && !force) {
|
||||
throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
|
||||
}
|
||||
__classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
getType(path) {
|
||||
if (typeof path !== 'string')
|
||||
return null;
|
||||
const last = path.replace(/^.*[/\\]/s, '').toLowerCase();
|
||||
const ext = last.replace(/^.*\./s, '').toLowerCase();
|
||||
const hasPath = last.length < path.length;
|
||||
const hasDot = ext.length < last.length - 1;
|
||||
if (!hasDot && hasPath)
|
||||
return null;
|
||||
return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
|
||||
}
|
||||
getExtension(type) {
|
||||
if (typeof type !== 'string')
|
||||
return null;
|
||||
type = type?.split?.(';')[0];
|
||||
return ((type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null);
|
||||
}
|
||||
getAllExtensions(type) {
|
||||
if (typeof type !== 'string')
|
||||
return null;
|
||||
return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
|
||||
}
|
||||
_freeze() {
|
||||
this.define = () => {
|
||||
throw new Error('define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances');
|
||||
};
|
||||
Object.freeze(this);
|
||||
for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
|
||||
Object.freeze(extensions);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
_getTestState() {
|
||||
return {
|
||||
types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
|
||||
extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f"),
|
||||
};
|
||||
}
|
||||
}
|
||||
_Mime_extensionToType = new WeakMap(), _Mime_typeToExtension = new WeakMap(), _Mime_typeToExtensions = new WeakMap();
|
||||
|
||||
var mime = new Mime(types)._freeze();
|
||||
|
||||
function getTestFileEnvironment(project, testFile, browser = false) {
|
||||
let environment;
|
||||
if (browser) {
|
||||
environment = project.browser?.vite.environments.client;
|
||||
} else {
|
||||
for (const name in project.vite.environments) {
|
||||
const env = project.vite.environments[name];
|
||||
if (env.moduleGraph.getModuleById(testFile)) {
|
||||
environment = env;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return environment;
|
||||
}
|
||||
|
||||
async function getModuleGraph(ctx, projectName, testFilePath, browser = false) {
|
||||
const graph = {};
|
||||
const externalized = new Set();
|
||||
const inlined = new Set();
|
||||
const project = ctx.getProjectByName(projectName);
|
||||
const environment = getTestFileEnvironment(project, testFilePath, browser);
|
||||
if (!environment) {
|
||||
throw new Error(`Cannot find environment for ${testFilePath}`);
|
||||
}
|
||||
const seen = new Map();
|
||||
function get(mod) {
|
||||
if (!mod || !mod.id) {
|
||||
return;
|
||||
}
|
||||
if (mod.id === "\0vitest/browser" || mod.id.includes("plugin-vue:export-helper")) {
|
||||
return;
|
||||
}
|
||||
if (seen.has(mod)) {
|
||||
return seen.get(mod);
|
||||
}
|
||||
const id = clearId(mod.id);
|
||||
seen.set(mod, id);
|
||||
if (id.startsWith("__vite-browser-external:")) {
|
||||
const external = id.slice("__vite-browser-external:".length);
|
||||
externalized.add(external);
|
||||
return external;
|
||||
}
|
||||
const external = project._resolver.wasExternalized(id);
|
||||
if (typeof external === "string") {
|
||||
externalized.add(external);
|
||||
return external;
|
||||
}
|
||||
if (browser && mod.file?.includes(project.browser.vite.config.cacheDir)) {
|
||||
externalized.add(mod.id);
|
||||
return id;
|
||||
}
|
||||
inlined.add(id);
|
||||
// TODO: cached modules don't have that!
|
||||
const mods = Array.from(mod.importedModules).filter((i) => i.id && !i.id.includes("/vitest/dist/"));
|
||||
graph[id] = mods.map((m) => get(m)).filter(Boolean);
|
||||
return id;
|
||||
}
|
||||
get(environment.moduleGraph.getModuleById(testFilePath));
|
||||
project.config.setupFiles.forEach((setupFile) => {
|
||||
get(environment.moduleGraph.getModuleById(setupFile));
|
||||
});
|
||||
return {
|
||||
graph,
|
||||
externalized: Array.from(externalized),
|
||||
inlined: Array.from(inlined)
|
||||
};
|
||||
}
|
||||
function clearId(id) {
|
||||
return id?.replace(/\?v=\w+$/, "") || "";
|
||||
}
|
||||
|
||||
function getOutputFile(config) {
|
||||
if (!config?.outputFile) {
|
||||
return;
|
||||
}
|
||||
if (typeof config.outputFile === "string") {
|
||||
return config.outputFile;
|
||||
}
|
||||
return config.outputFile.html;
|
||||
}
|
||||
const distDir = resolve(fileURLToPath(import.meta.url), "../../dist");
|
||||
class HTMLReporter {
|
||||
start = 0;
|
||||
ctx;
|
||||
options;
|
||||
reporterDir;
|
||||
htmlFilePath;
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
}
|
||||
async onInit(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.start = Date.now();
|
||||
const htmlFile = this.options.outputFile || getOutputFile(this.ctx.config) || "html/index.html";
|
||||
const htmlFilePath = resolve(this.ctx.config.root, htmlFile);
|
||||
this.reporterDir = dirname(htmlFilePath);
|
||||
this.htmlFilePath = htmlFilePath;
|
||||
await promises.mkdir(resolve(this.reporterDir, "data"), { recursive: true });
|
||||
await promises.mkdir(resolve(this.reporterDir, "assets"), { recursive: true });
|
||||
}
|
||||
async onTestRunEnd() {
|
||||
const result = {
|
||||
paths: this.ctx.state.getPaths(),
|
||||
files: this.ctx.state.getFiles(),
|
||||
config: this.ctx.getRootProject().serializedConfig,
|
||||
unhandledErrors: this.ctx.state.getUnhandledErrors(),
|
||||
projects: this.ctx.projects.map((p) => p.name),
|
||||
moduleGraph: {},
|
||||
sources: {}
|
||||
};
|
||||
const promises$1 = [];
|
||||
const processAttachments = (task) => {
|
||||
if (task.type === "test") {
|
||||
task.annotations.forEach((annotation) => {
|
||||
const attachment = annotation.attachment;
|
||||
if (attachment) {
|
||||
promises$1.push(this.processAttachment(attachment));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
task.tasks.forEach(processAttachments);
|
||||
}
|
||||
};
|
||||
promises$1.push(...result.files.map(async (file) => {
|
||||
processAttachments(file);
|
||||
const projectName = file.projectName || "";
|
||||
const resolvedConfig = this.ctx.getProjectByName(projectName).config;
|
||||
const browser = resolvedConfig.browser.enabled && resolvedConfig.browser.ui;
|
||||
result.moduleGraph[projectName] ??= {};
|
||||
result.moduleGraph[projectName][file.filepath] = await getModuleGraph(this.ctx, projectName, file.filepath, browser);
|
||||
if (!result.sources[file.filepath]) {
|
||||
try {
|
||||
result.sources[file.filepath] = await promises.readFile(file.filepath, { encoding: "utf-8" });
|
||||
} catch {}
|
||||
}
|
||||
}));
|
||||
await Promise.all(promises$1);
|
||||
await this.writeReport(stringify(result));
|
||||
}
|
||||
async processAttachment(attachment) {
|
||||
if (attachment.path) {
|
||||
// keep external resource as is, but remove body if it's set somehow
|
||||
if (attachment.path.startsWith("http://") || attachment.path.startsWith("https://")) {
|
||||
attachment.body = undefined;
|
||||
return;
|
||||
}
|
||||
const buffer = await readFile(attachment.path);
|
||||
const hash = crypto.createHash("sha1").update(buffer).digest("hex");
|
||||
const filename = hash + extname(attachment.path);
|
||||
// move the file into an html directory to make access/publishing UI easier
|
||||
await writeFile(resolve(this.reporterDir, "data", filename), buffer);
|
||||
attachment.path = filename;
|
||||
attachment.body = undefined;
|
||||
return;
|
||||
}
|
||||
if (attachment.body) {
|
||||
const buffer = typeof attachment.body === "string" ? Buffer.from(attachment.body, "base64") : Buffer.from(attachment.body);
|
||||
const hash = crypto.createHash("sha1").update(buffer).digest("hex");
|
||||
const extension = mime.getExtension(attachment.contentType || "application/octet-stream") || "dat";
|
||||
const filename = `${hash}.${extension}`;
|
||||
// store the file in html directory instead of passing down as a body
|
||||
await writeFile(resolve(this.reporterDir, "data", filename), buffer);
|
||||
attachment.path = filename;
|
||||
attachment.body = undefined;
|
||||
}
|
||||
}
|
||||
async writeReport(report) {
|
||||
const metaFile = resolve(this.reporterDir, "html.meta.json.gz");
|
||||
const promiseGzip = promisify(gzip);
|
||||
const data = await promiseGzip(report, { level: constants.Z_BEST_COMPRESSION });
|
||||
await promises.writeFile(metaFile, data, "base64");
|
||||
const ui = resolve(distDir, "client");
|
||||
// copy ui
|
||||
const files = globSync(["**/*"], {
|
||||
cwd: ui,
|
||||
expandDirectories: false
|
||||
});
|
||||
await Promise.all(files.map(async (f) => {
|
||||
if (f === "index.html") {
|
||||
const html = await promises.readFile(resolve(ui, f), "utf-8");
|
||||
const filePath = relative(this.reporterDir, metaFile);
|
||||
await promises.writeFile(this.htmlFilePath, html.replace("<!-- !LOAD_METADATA! -->", `<script>window.METADATA_PATH="${filePath}"<\/script>`));
|
||||
} else {
|
||||
await promises.copyFile(resolve(ui, f), resolve(this.reporterDir, f));
|
||||
}
|
||||
}));
|
||||
this.ctx.logger.log(`${c.bold(c.inverse(c.magenta(" HTML ")))} ${c.magenta("Report is generated")}`);
|
||||
this.ctx.logger.log(`${c.dim(" You can run ")}${c.bold(`npx vite preview --outDir ${relative(this.ctx.config.root, this.reporterDir)}`)}${c.dim(" to see the test results.")}`);
|
||||
}
|
||||
}
|
||||
|
||||
export { HTMLReporter as default };
|
||||
93
node_modules/@vitest/ui/package.json
generated
vendored
Normal file
93
node_modules/@vitest/ui/package.json
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"name": "@vitest/ui",
|
||||
"type": "module",
|
||||
"version": "4.0.15",
|
||||
"description": "UI for Vitest",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/ui#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/ui"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./reporter": {
|
||||
"types": "./reporter.d.ts",
|
||||
"default": "./dist/reporter.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"dist"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"vitest": "4.0.15"
|
||||
},
|
||||
"dependencies": {
|
||||
"fflate": "^0.8.2",
|
||||
"flatted": "^3.3.3",
|
||||
"pathe": "^2.0.3",
|
||||
"sirv": "^3.0.2",
|
||||
"tinyglobby": "^0.2.15",
|
||||
"tinyrainbow": "^3.0.3",
|
||||
"@vitest/utils": "4.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^10.1.0",
|
||||
"@iconify-json/carbon": "^1.2.14",
|
||||
"@iconify-json/logos": "^1.2.10",
|
||||
"@types/codemirror": "^5.60.17",
|
||||
"@types/d3-force": "^3.0.10",
|
||||
"@types/d3-selection": "^3.0.11",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@unocss/reset": "^66.5.9",
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"@vueuse/core": "^12.8.2",
|
||||
"ansi-to-html": "^0.7.2",
|
||||
"birpc": "^2.8.0",
|
||||
"codemirror": "^5.65.18",
|
||||
"codemirror-theme-vars": "^0.1.2",
|
||||
"d3-graph-controller": "^3.1.6",
|
||||
"floating-vue": "^5.2.2",
|
||||
"mime": "^4.1.0",
|
||||
"rollup": "^4.53.3",
|
||||
"splitpanes": "^4.0.4",
|
||||
"typescript": "^5.9.3",
|
||||
"unocss": "^66.5.9",
|
||||
"vite": "^5.0.0",
|
||||
"vite-plugin-pages": "^0.33.1",
|
||||
"vitest-browser-vue": "2.0.1",
|
||||
"vue": "^3.5.25",
|
||||
"vue-router": "^4.6.3",
|
||||
"vue-tsc": "^3.1.5",
|
||||
"vue-virtual-scroller": "2.0.0-beta.8",
|
||||
"@vitest/browser-playwright": "4.0.15",
|
||||
"@vitest/runner": "4.0.15",
|
||||
"@vitest/ws-client": "4.0.15"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && pnpm build:node && pnpm build:client",
|
||||
"build:client": "vite build",
|
||||
"build:node": "rollup -c",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:client": "vue-tsc --noEmit",
|
||||
"dev:client": "vite",
|
||||
"dev": "rollup -c --watch --watch.include 'node/**'",
|
||||
"dev:ui": "pnpm run --stream '/^(dev|dev:client)$/'",
|
||||
"test:ui": "vitest --browser"
|
||||
}
|
||||
}
|
||||
4
node_modules/@vitest/ui/reporter.d.ts
generated
vendored
Normal file
4
node_modules/@vitest/ui/reporter.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { Reporter } from 'vitest/node'
|
||||
|
||||
declare const reporter: Reporter
|
||||
export default reporter
|
||||
1
node_modules/@vitest/ui/shim.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/ui/shim.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="./client/shim" />
|
||||
21
node_modules/@vitest/utils/LICENSE
generated
vendored
Normal file
21
node_modules/@vitest/utils/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
1
node_modules/@vitest/utils/diff.d.ts
generated
vendored
Normal file
1
node_modules/@vitest/utils/diff.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './dist/diff.js'
|
||||
5
node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js
generated
vendored
Normal file
5
node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
function getDefaultExportFromCjs(x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
|
||||
}
|
||||
|
||||
export { getDefaultExportFromCjs as g };
|
||||
156
node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
156
node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
generated
vendored
Normal file
@@ -0,0 +1,156 @@
|
||||
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 };
|
||||
21
node_modules/@vitest/utils/dist/constants.d.ts
generated
vendored
Normal file
21
node_modules/@vitest/utils/dist/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
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__";
|
||||
|
||||
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX };
|
||||
49
node_modules/@vitest/utils/dist/constants.js
generated
vendored
Normal file
49
node_modules/@vitest/utils/dist/constants.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
// 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__`;
|
||||
|
||||
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX };
|
||||
93
node_modules/@vitest/utils/dist/diff.d.ts
generated
vendored
Normal file
93
node_modules/@vitest/utils/dist/diff.d.ts
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
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
|
||||
* Copyright 2018 The diff-match-patch Authors.
|
||||
* https://github.com/google/diff-match-patch
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/**
|
||||
* @fileoverview Computes the difference between two texts to create a patch.
|
||||
* Applies the patch onto another text, allowing for errors.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
/**
|
||||
* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file:
|
||||
*
|
||||
* 1. Delete anything not needed to use diff_cleanupSemantic method
|
||||
* 2. Convert from prototype properties to var declarations
|
||||
* 3. Convert Diff to class from constructor and prototype
|
||||
* 4. Add type annotations for arguments and return values
|
||||
* 5. Add exports
|
||||
*/
|
||||
/**
|
||||
* The data structure representing a diff is an array of tuples:
|
||||
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
|
||||
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
|
||||
*/
|
||||
declare const DIFF_DELETE = -1;
|
||||
declare const DIFF_INSERT = 1;
|
||||
declare const DIFF_EQUAL = 0;
|
||||
/**
|
||||
* Class representing one diff tuple.
|
||||
* Attempts to look like a two-element array (which is what this used to be).
|
||||
* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
|
||||
* @param {string} text Text to be deleted, inserted, or retained.
|
||||
* @constructor
|
||||
*/
|
||||
declare class Diff {
|
||||
0: number;
|
||||
1: string;
|
||||
constructor(op: number, text: string);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
declare function diffLinesUnified(aLines: Array<string>, bLines: Array<string>, options?: DiffOptions): string;
|
||||
declare function diffLinesUnified2(aLinesDisplay: Array<string>, bLinesDisplay: Array<string>, aLinesCompare: Array<string>, bLinesCompare: Array<string>, options?: DiffOptions): string;
|
||||
declare function diffLinesRaw(aLines: Array<string>, bLines: Array<string>, 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.
|
||||
*/
|
||||
|
||||
declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string;
|
||||
declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array<Diff>, boolean];
|
||||
|
||||
/**
|
||||
* @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 replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet<WeakKey>, expectedReplaced?: WeakSet<WeakKey>): {
|
||||
replacedActual: any;
|
||||
replacedExpected: any;
|
||||
};
|
||||
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 };
|
||||
2187
node_modules/@vitest/utils/dist/diff.js
generated
vendored
Normal file
2187
node_modules/@vitest/utils/dist/diff.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
28
node_modules/@vitest/utils/dist/display.d.ts
generated
vendored
Normal file
28
node_modules/@vitest/utils/dist/display.d.ts
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
import { PrettyFormatOptions } from '@vitest/pretty-format';
|
||||
|
||||
type Inspect = (value: unknown, options: Options) => string;
|
||||
interface Options {
|
||||
showHidden: boolean;
|
||||
depth: number;
|
||||
colors: boolean;
|
||||
customInspect: boolean;
|
||||
showProxy: boolean;
|
||||
maxArrayLength: number;
|
||||
breakLength: number;
|
||||
truncate: number;
|
||||
seen: unknown[];
|
||||
inspect: Inspect;
|
||||
stylize: (value: string, styleType: string) => string;
|
||||
}
|
||||
type LoupeOptions = Partial<Options>;
|
||||
interface StringifyOptions extends PrettyFormatOptions {
|
||||
maxLength?: number;
|
||||
}
|
||||
declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: StringifyOptions): string;
|
||||
declare const formatRegExp: RegExp;
|
||||
declare function format(...args: unknown[]): string;
|
||||
declare function inspect(obj: unknown, options?: LoupeOptions): string;
|
||||
declare function objDisplay(obj: unknown, options?: LoupeOptions): string;
|
||||
|
||||
export { format, formatRegExp, inspect, objDisplay, stringify };
|
||||
export type { LoupeOptions, StringifyOptions };
|
||||
727
node_modules/@vitest/utils/dist/display.js
generated
vendored
Normal file
727
node_modules/@vitest/utils/dist/display.js
generated
vendored
Normal file
@@ -0,0 +1,727 @@
|
||||
import { plugins, format as format$1 } from '@vitest/pretty-format';
|
||||
|
||||
const ansiColors = {
|
||||
bold: ['1', '22'],
|
||||
dim: ['2', '22'],
|
||||
italic: ['3', '23'],
|
||||
underline: ['4', '24'],
|
||||
// 5 & 6 are blinking
|
||||
inverse: ['7', '27'],
|
||||
hidden: ['8', '28'],
|
||||
strike: ['9', '29'],
|
||||
// 10-20 are fonts
|
||||
// 21-29 are resets for 1-9
|
||||
black: ['30', '39'],
|
||||
red: ['31', '39'],
|
||||
green: ['32', '39'],
|
||||
yellow: ['33', '39'],
|
||||
blue: ['34', '39'],
|
||||
magenta: ['35', '39'],
|
||||
cyan: ['36', '39'],
|
||||
white: ['37', '39'],
|
||||
brightblack: ['30;1', '39'],
|
||||
brightred: ['31;1', '39'],
|
||||
brightgreen: ['32;1', '39'],
|
||||
brightyellow: ['33;1', '39'],
|
||||
brightblue: ['34;1', '39'],
|
||||
brightmagenta: ['35;1', '39'],
|
||||
brightcyan: ['36;1', '39'],
|
||||
brightwhite: ['37;1', '39'],
|
||||
grey: ['90', '39'],
|
||||
};
|
||||
const styles = {
|
||||
special: 'cyan',
|
||||
number: 'yellow',
|
||||
bigint: 'yellow',
|
||||
boolean: 'yellow',
|
||||
undefined: 'grey',
|
||||
null: 'bold',
|
||||
string: 'green',
|
||||
symbol: 'green',
|
||||
date: 'magenta',
|
||||
regexp: 'red',
|
||||
};
|
||||
const truncator = '…';
|
||||
function colorise(value, styleType) {
|
||||
const color = ansiColors[styles[styleType]] || ansiColors[styleType] || '';
|
||||
if (!color) {
|
||||
return String(value);
|
||||
}
|
||||
return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`;
|
||||
}
|
||||
function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [],
|
||||
// eslint-disable-next-line no-shadow
|
||||
truncate = Infinity, stylize = String, } = {}, inspect) {
|
||||
const options = {
|
||||
showHidden: Boolean(showHidden),
|
||||
depth: Number(depth),
|
||||
colors: Boolean(colors),
|
||||
customInspect: Boolean(customInspect),
|
||||
showProxy: Boolean(showProxy),
|
||||
maxArrayLength: Number(maxArrayLength),
|
||||
breakLength: Number(breakLength),
|
||||
truncate: Number(truncate),
|
||||
seen,
|
||||
inspect,
|
||||
stylize,
|
||||
};
|
||||
if (options.colors) {
|
||||
options.stylize = colorise;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
function isHighSurrogate(char) {
|
||||
return char >= '\ud800' && char <= '\udbff';
|
||||
}
|
||||
function truncate(string, length, tail = truncator) {
|
||||
string = String(string);
|
||||
const tailLength = tail.length;
|
||||
const stringLength = string.length;
|
||||
if (tailLength > length && stringLength > tailLength) {
|
||||
return tail;
|
||||
}
|
||||
if (stringLength > length && stringLength > tailLength) {
|
||||
let end = length - tailLength;
|
||||
if (end > 0 && isHighSurrogate(string[end - 1])) {
|
||||
end = end - 1;
|
||||
}
|
||||
return `${string.slice(0, end)}${tail}`;
|
||||
}
|
||||
return string;
|
||||
}
|
||||
// eslint-disable-next-line complexity
|
||||
function inspectList(list, options, inspectItem, separator = ', ') {
|
||||
inspectItem = inspectItem || options.inspect;
|
||||
const size = list.length;
|
||||
if (size === 0)
|
||||
return '';
|
||||
const originalLength = options.truncate;
|
||||
let output = '';
|
||||
let peek = '';
|
||||
let truncated = '';
|
||||
for (let i = 0; i < size; i += 1) {
|
||||
const last = i + 1 === list.length;
|
||||
const secondToLast = i + 2 === list.length;
|
||||
truncated = `${truncator}(${list.length - i})`;
|
||||
const value = list[i];
|
||||
// If there is more than one remaining we need to account for a separator of `, `
|
||||
options.truncate = originalLength - output.length - (last ? 0 : separator.length);
|
||||
const string = peek || inspectItem(value, options) + (last ? '' : separator);
|
||||
const nextLength = output.length + string.length;
|
||||
const truncatedLength = nextLength + truncated.length;
|
||||
// If this is the last element, and adding it would
|
||||
// take us over length, but adding the truncator wouldn't - then break now
|
||||
if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
|
||||
break;
|
||||
}
|
||||
// If this isn't the last or second to last element to scan,
|
||||
// but the string is already over length then break here
|
||||
if (!last && !secondToLast && truncatedLength > originalLength) {
|
||||
break;
|
||||
}
|
||||
// Peek at the next string to determine if we should
|
||||
// break early before adding this item to the output
|
||||
peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator);
|
||||
// If we have one element left, but this element and
|
||||
// the next takes over length, the break early
|
||||
if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
|
||||
break;
|
||||
}
|
||||
output += string;
|
||||
// If the next element takes us to length -
|
||||
// but there are more after that, then we should truncate now
|
||||
if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
|
||||
truncated = `${truncator}(${list.length - i - 1})`;
|
||||
break;
|
||||
}
|
||||
truncated = '';
|
||||
}
|
||||
return `${output}${truncated}`;
|
||||
}
|
||||
function quoteComplexKey(key) {
|
||||
if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) {
|
||||
return key;
|
||||
}
|
||||
return JSON.stringify(key)
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/\\"/g, '"')
|
||||
.replace(/(^"|"$)/g, "'");
|
||||
}
|
||||
function inspectProperty([key, value], options) {
|
||||
options.truncate -= 2;
|
||||
if (typeof key === 'string') {
|
||||
key = quoteComplexKey(key);
|
||||
}
|
||||
else if (typeof key !== 'number') {
|
||||
key = `[${options.inspect(key, options)}]`;
|
||||
}
|
||||
options.truncate -= key.length;
|
||||
value = options.inspect(value, options);
|
||||
return `${key}: ${value}`;
|
||||
}
|
||||
|
||||
function inspectArray(array, options) {
|
||||
// Object.keys will always output the Array indices first, so we can slice by
|
||||
// `array.length` to get non-index properties
|
||||
const nonIndexProperties = Object.keys(array).slice(array.length);
|
||||
if (!array.length && !nonIndexProperties.length)
|
||||
return '[]';
|
||||
options.truncate -= 4;
|
||||
const listContents = inspectList(array, options);
|
||||
options.truncate -= listContents.length;
|
||||
let propertyContents = '';
|
||||
if (nonIndexProperties.length) {
|
||||
propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty);
|
||||
}
|
||||
return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`;
|
||||
}
|
||||
|
||||
const getArrayName = (array) => {
|
||||
// We need to special case Node.js' Buffers, which report to be Uint8Array
|
||||
// @ts-ignore
|
||||
if (typeof Buffer === 'function' && array instanceof Buffer) {
|
||||
return 'Buffer';
|
||||
}
|
||||
if (array[Symbol.toStringTag]) {
|
||||
return array[Symbol.toStringTag];
|
||||
}
|
||||
return array.constructor.name;
|
||||
};
|
||||
function inspectTypedArray(array, options) {
|
||||
const name = getArrayName(array);
|
||||
options.truncate -= name.length + 4;
|
||||
// Object.keys will always output the Array indices first, so we can slice by
|
||||
// `array.length` to get non-index properties
|
||||
const nonIndexProperties = Object.keys(array).slice(array.length);
|
||||
if (!array.length && !nonIndexProperties.length)
|
||||
return `${name}[]`;
|
||||
// As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply
|
||||
// stylise the toString() value of them
|
||||
let output = '';
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`;
|
||||
options.truncate -= string.length;
|
||||
if (array[i] !== array.length && options.truncate <= 3) {
|
||||
output += `${truncator}(${array.length - array[i] + 1})`;
|
||||
break;
|
||||
}
|
||||
output += string;
|
||||
}
|
||||
let propertyContents = '';
|
||||
if (nonIndexProperties.length) {
|
||||
propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty);
|
||||
}
|
||||
return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`;
|
||||
}
|
||||
|
||||
function inspectDate(dateObject, options) {
|
||||
const stringRepresentation = dateObject.toJSON();
|
||||
if (stringRepresentation === null) {
|
||||
return 'Invalid Date';
|
||||
}
|
||||
const split = stringRepresentation.split('T');
|
||||
const date = split[0];
|
||||
// If we need to - truncate the time portion, but never the date
|
||||
return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date');
|
||||
}
|
||||
|
||||
function inspectFunction(func, options) {
|
||||
const functionType = func[Symbol.toStringTag] || 'Function';
|
||||
const name = func.name;
|
||||
if (!name) {
|
||||
return options.stylize(`[${functionType}]`, 'special');
|
||||
}
|
||||
return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special');
|
||||
}
|
||||
|
||||
function inspectMapEntry([key, value], options) {
|
||||
options.truncate -= 4;
|
||||
key = options.inspect(key, options);
|
||||
options.truncate -= key.length;
|
||||
value = options.inspect(value, options);
|
||||
return `${key} => ${value}`;
|
||||
}
|
||||
// IE11 doesn't support `map.entries()`
|
||||
function mapToEntries(map) {
|
||||
const entries = [];
|
||||
map.forEach((value, key) => {
|
||||
entries.push([key, value]);
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
function inspectMap(map, options) {
|
||||
if (map.size === 0)
|
||||
return 'Map{}';
|
||||
options.truncate -= 7;
|
||||
return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`;
|
||||
}
|
||||
|
||||
const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare
|
||||
function inspectNumber(number, options) {
|
||||
if (isNaN(number)) {
|
||||
return options.stylize('NaN', 'number');
|
||||
}
|
||||
if (number === Infinity) {
|
||||
return options.stylize('Infinity', 'number');
|
||||
}
|
||||
if (number === -Infinity) {
|
||||
return options.stylize('-Infinity', 'number');
|
||||
}
|
||||
if (number === 0) {
|
||||
return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number');
|
||||
}
|
||||
return options.stylize(truncate(String(number), options.truncate), 'number');
|
||||
}
|
||||
|
||||
function inspectBigInt(number, options) {
|
||||
let nums = truncate(number.toString(), options.truncate - 1);
|
||||
if (nums !== truncator)
|
||||
nums += 'n';
|
||||
return options.stylize(nums, 'bigint');
|
||||
}
|
||||
|
||||
function inspectRegExp(value, options) {
|
||||
const flags = value.toString().split('/')[2];
|
||||
const sourceLength = options.truncate - (2 + flags.length);
|
||||
const source = value.source;
|
||||
return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp');
|
||||
}
|
||||
|
||||
// IE11 doesn't support `Array.from(set)`
|
||||
function arrayFromSet(set) {
|
||||
const values = [];
|
||||
set.forEach(value => {
|
||||
values.push(value);
|
||||
});
|
||||
return values;
|
||||
}
|
||||
function inspectSet(set, options) {
|
||||
if (set.size === 0)
|
||||
return 'Set{}';
|
||||
options.truncate -= 7;
|
||||
return `Set{ ${inspectList(arrayFromSet(set), options)} }`;
|
||||
}
|
||||
|
||||
const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" +
|
||||
'\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g');
|
||||
const escapeCharacters = {
|
||||
'\b': '\\b',
|
||||
'\t': '\\t',
|
||||
'\n': '\\n',
|
||||
'\f': '\\f',
|
||||
'\r': '\\r',
|
||||
"'": "\\'",
|
||||
'\\': '\\\\',
|
||||
};
|
||||
const hex = 16;
|
||||
function escape(char) {
|
||||
return (escapeCharacters[char] ||
|
||||
`\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`);
|
||||
}
|
||||
function inspectString(string, options) {
|
||||
if (stringEscapeChars.test(string)) {
|
||||
string = string.replace(stringEscapeChars, escape);
|
||||
}
|
||||
return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string');
|
||||
}
|
||||
|
||||
function inspectSymbol(value) {
|
||||
if ('description' in Symbol.prototype) {
|
||||
return value.description ? `Symbol(${value.description})` : 'Symbol()';
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
const getPromiseValue = () => 'Promise{…}';
|
||||
|
||||
function inspectObject$1(object, options) {
|
||||
const properties = Object.getOwnPropertyNames(object);
|
||||
const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [];
|
||||
if (properties.length === 0 && symbols.length === 0) {
|
||||
return '{}';
|
||||
}
|
||||
options.truncate -= 4;
|
||||
options.seen = options.seen || [];
|
||||
if (options.seen.includes(object)) {
|
||||
return '[Circular]';
|
||||
}
|
||||
options.seen.push(object);
|
||||
const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty);
|
||||
const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty);
|
||||
options.seen.pop();
|
||||
let sep = '';
|
||||
if (propertyContents && symbolContents) {
|
||||
sep = ', ';
|
||||
}
|
||||
return `{ ${propertyContents}${sep}${symbolContents} }`;
|
||||
}
|
||||
|
||||
const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false;
|
||||
function inspectClass(value, options) {
|
||||
let name = '';
|
||||
if (toStringTag && toStringTag in value) {
|
||||
name = value[toStringTag];
|
||||
}
|
||||
name = name || value.constructor.name;
|
||||
// Babel transforms anonymous classes to the name `_class`
|
||||
if (!name || name === '_class') {
|
||||
name = '<Anonymous Class>';
|
||||
}
|
||||
options.truncate -= name.length;
|
||||
return `${name}${inspectObject$1(value, options)}`;
|
||||
}
|
||||
|
||||
function inspectArguments(args, options) {
|
||||
if (args.length === 0)
|
||||
return 'Arguments[]';
|
||||
options.truncate -= 13;
|
||||
return `Arguments[ ${inspectList(args, options)} ]`;
|
||||
}
|
||||
|
||||
const errorKeys = [
|
||||
'stack',
|
||||
'line',
|
||||
'column',
|
||||
'name',
|
||||
'message',
|
||||
'fileName',
|
||||
'lineNumber',
|
||||
'columnNumber',
|
||||
'number',
|
||||
'description',
|
||||
'cause',
|
||||
];
|
||||
function inspectObject(error, options) {
|
||||
const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1);
|
||||
const name = error.name;
|
||||
options.truncate -= name.length;
|
||||
let message = '';
|
||||
if (typeof error.message === 'string') {
|
||||
message = truncate(error.message, options.truncate);
|
||||
}
|
||||
else {
|
||||
properties.unshift('message');
|
||||
}
|
||||
message = message ? `: ${message}` : '';
|
||||
options.truncate -= message.length + 5;
|
||||
options.seen = options.seen || [];
|
||||
if (options.seen.includes(error)) {
|
||||
return '[Circular]';
|
||||
}
|
||||
options.seen.push(error);
|
||||
const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty);
|
||||
return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`;
|
||||
}
|
||||
|
||||
function inspectAttribute([key, value], options) {
|
||||
options.truncate -= 3;
|
||||
if (!value) {
|
||||
return `${options.stylize(String(key), 'yellow')}`;
|
||||
}
|
||||
return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`;
|
||||
}
|
||||
function inspectNodeCollection(collection, options) {
|
||||
return inspectList(collection, options, inspectNode, '\n');
|
||||
}
|
||||
function inspectNode(node, options) {
|
||||
switch (node.nodeType) {
|
||||
case 1:
|
||||
return inspectHTML(node, options);
|
||||
case 3:
|
||||
return options.inspect(node.data, options);
|
||||
default:
|
||||
return options.inspect(node, options);
|
||||
}
|
||||
}
|
||||
// @ts-ignore (Deno doesn't have Element)
|
||||
function inspectHTML(element, options) {
|
||||
const properties = element.getAttributeNames();
|
||||
const name = element.tagName.toLowerCase();
|
||||
const head = options.stylize(`<${name}`, 'special');
|
||||
const headClose = options.stylize(`>`, 'special');
|
||||
const tail = options.stylize(`</${name}>`, 'special');
|
||||
options.truncate -= name.length * 2 + 5;
|
||||
let propertyContents = '';
|
||||
if (properties.length > 0) {
|
||||
propertyContents += ' ';
|
||||
propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' ');
|
||||
}
|
||||
options.truncate -= propertyContents.length;
|
||||
const truncate = options.truncate;
|
||||
let children = inspectNodeCollection(element.children, options);
|
||||
if (children && children.length > truncate) {
|
||||
children = `${truncator}(${element.children.length})`;
|
||||
}
|
||||
return `${head}${propertyContents}${headClose}${children}${tail}`;
|
||||
}
|
||||
|
||||
/* !
|
||||
* loupe
|
||||
* Copyright(c) 2013 Jake Luer <jake@alogicalparadox.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function';
|
||||
const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect';
|
||||
const nodeInspect = Symbol.for('nodejs.util.inspect.custom');
|
||||
const constructorMap = new WeakMap();
|
||||
const stringTagMap = {};
|
||||
const baseTypesMap = {
|
||||
undefined: (value, options) => options.stylize('undefined', 'undefined'),
|
||||
null: (value, options) => options.stylize('null', 'null'),
|
||||
boolean: (value, options) => options.stylize(String(value), 'boolean'),
|
||||
Boolean: (value, options) => options.stylize(String(value), 'boolean'),
|
||||
number: inspectNumber,
|
||||
Number: inspectNumber,
|
||||
bigint: inspectBigInt,
|
||||
BigInt: inspectBigInt,
|
||||
string: inspectString,
|
||||
String: inspectString,
|
||||
function: inspectFunction,
|
||||
Function: inspectFunction,
|
||||
symbol: inspectSymbol,
|
||||
// A Symbol polyfill will return `Symbol` not `symbol` from typedetect
|
||||
Symbol: inspectSymbol,
|
||||
Array: inspectArray,
|
||||
Date: inspectDate,
|
||||
Map: inspectMap,
|
||||
Set: inspectSet,
|
||||
RegExp: inspectRegExp,
|
||||
Promise: getPromiseValue,
|
||||
// WeakSet, WeakMap are totally opaque to us
|
||||
WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'),
|
||||
WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'),
|
||||
Arguments: inspectArguments,
|
||||
Int8Array: inspectTypedArray,
|
||||
Uint8Array: inspectTypedArray,
|
||||
Uint8ClampedArray: inspectTypedArray,
|
||||
Int16Array: inspectTypedArray,
|
||||
Uint16Array: inspectTypedArray,
|
||||
Int32Array: inspectTypedArray,
|
||||
Uint32Array: inspectTypedArray,
|
||||
Float32Array: inspectTypedArray,
|
||||
Float64Array: inspectTypedArray,
|
||||
Generator: () => '',
|
||||
DataView: () => '',
|
||||
ArrayBuffer: () => '',
|
||||
Error: inspectObject,
|
||||
HTMLCollection: inspectNodeCollection,
|
||||
NodeList: inspectNodeCollection,
|
||||
};
|
||||
// eslint-disable-next-line complexity
|
||||
const inspectCustom = (value, options, type, inspectFn) => {
|
||||
if (chaiInspect in value && typeof value[chaiInspect] === 'function') {
|
||||
return value[chaiInspect](options);
|
||||
}
|
||||
if (nodeInspect in value && typeof value[nodeInspect] === 'function') {
|
||||
return value[nodeInspect](options.depth, options, inspectFn);
|
||||
}
|
||||
if ('inspect' in value && typeof value.inspect === 'function') {
|
||||
return value.inspect(options.depth, options);
|
||||
}
|
||||
if ('constructor' in value && constructorMap.has(value.constructor)) {
|
||||
return constructorMap.get(value.constructor)(value, options);
|
||||
}
|
||||
if (stringTagMap[type]) {
|
||||
return stringTagMap[type](value, options);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
const toString = Object.prototype.toString;
|
||||
// eslint-disable-next-line complexity
|
||||
function inspect$1(value, opts = {}) {
|
||||
const options = normaliseOptions(opts, inspect$1);
|
||||
const { customInspect } = options;
|
||||
let type = value === null ? 'null' : typeof value;
|
||||
if (type === 'object') {
|
||||
type = toString.call(value).slice(8, -1);
|
||||
}
|
||||
// If it is a base value that we already support, then use Loupe's inspector
|
||||
if (type in baseTypesMap) {
|
||||
return baseTypesMap[type](value, options);
|
||||
}
|
||||
// If `options.customInspect` is set to true then try to use the custom inspector
|
||||
if (customInspect && value) {
|
||||
const output = inspectCustom(value, options, type, inspect$1);
|
||||
if (output) {
|
||||
if (typeof output === 'string')
|
||||
return output;
|
||||
return inspect$1(output, options);
|
||||
}
|
||||
}
|
||||
const proto = value ? Object.getPrototypeOf(value) : false;
|
||||
// If it's a plain Object then use Loupe's inspector
|
||||
if (proto === Object.prototype || proto === null) {
|
||||
return inspectObject$1(value, options);
|
||||
}
|
||||
// Specifically account for HTMLElements
|
||||
// @ts-ignore
|
||||
if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) {
|
||||
return inspectHTML(value, options);
|
||||
}
|
||||
if ('constructor' in value) {
|
||||
// If it is a class, inspect it like an object but add the constructor name
|
||||
if (value.constructor !== Object) {
|
||||
return inspectClass(value, options);
|
||||
}
|
||||
// If it is an object with an anonymous prototype, display it as an object.
|
||||
return inspectObject$1(value, options);
|
||||
}
|
||||
// last chance to check if it's an object
|
||||
if (value === Object(value)) {
|
||||
return inspectObject$1(value, options);
|
||||
}
|
||||
// We have run out of options! Just stringify the value
|
||||
return options.stylize(String(value), type);
|
||||
}
|
||||
|
||||
const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins;
|
||||
const PLUGINS = [
|
||||
ReactTestComponent,
|
||||
ReactElement,
|
||||
DOMElement,
|
||||
DOMCollection,
|
||||
Immutable,
|
||||
AsymmetricMatcher
|
||||
];
|
||||
function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) {
|
||||
const MAX_LENGTH = maxLength ?? 1e4;
|
||||
let result;
|
||||
try {
|
||||
result = format$1(object, {
|
||||
maxDepth,
|
||||
escapeString: false,
|
||||
plugins: PLUGINS,
|
||||
...options
|
||||
});
|
||||
} catch {
|
||||
result = format$1(object, {
|
||||
callToJSON: false,
|
||||
maxDepth,
|
||||
escapeString: false,
|
||||
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,
|
||||
...options
|
||||
}) : result;
|
||||
}
|
||||
const formatRegExp = /%[sdjifoOc%]/g;
|
||||
function format(...args) {
|
||||
if (typeof args[0] !== "string") {
|
||||
const objects = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
objects.push(inspect(args[i], {
|
||||
depth: 0,
|
||||
colors: false
|
||||
}));
|
||||
}
|
||||
return objects.join(" ");
|
||||
}
|
||||
const len = args.length;
|
||||
let i = 1;
|
||||
const template = args[0];
|
||||
let str = String(template).replace(formatRegExp, (x) => {
|
||||
if (x === "%%") {
|
||||
return "%";
|
||||
}
|
||||
if (i >= len) {
|
||||
return x;
|
||||
}
|
||||
switch (x) {
|
||||
case "%s": {
|
||||
const value = args[i++];
|
||||
if (typeof value === "bigint") {
|
||||
return `${value.toString()}n`;
|
||||
}
|
||||
if (typeof value === "number" && value === 0 && 1 / value < 0) {
|
||||
return "-0";
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
|
||||
return value.toString();
|
||||
}
|
||||
return inspect(value, {
|
||||
depth: 0,
|
||||
colors: false
|
||||
});
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
case "%d": {
|
||||
const value = args[i++];
|
||||
if (typeof value === "bigint") {
|
||||
return `${value.toString()}n`;
|
||||
}
|
||||
return Number(value).toString();
|
||||
}
|
||||
case "%i": {
|
||||
const value = args[i++];
|
||||
if (typeof value === "bigint") {
|
||||
return `${value.toString()}n`;
|
||||
}
|
||||
return Number.parseInt(String(value)).toString();
|
||||
}
|
||||
case "%f": return Number.parseFloat(String(args[i++])).toString();
|
||||
case "%o": return inspect(args[i++], {
|
||||
showHidden: true,
|
||||
showProxy: true
|
||||
});
|
||||
case "%O": return inspect(args[i++]);
|
||||
case "%c": {
|
||||
i++;
|
||||
return "";
|
||||
}
|
||||
case "%j": try {
|
||||
return JSON.stringify(args[i++]);
|
||||
} catch (err) {
|
||||
const m = err.message;
|
||||
if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) {
|
||||
return "[Circular]";
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
default: return x;
|
||||
}
|
||||
});
|
||||
for (let x = args[i]; i < len; x = args[++i]) {
|
||||
if (x === null || typeof x !== "object") {
|
||||
str += ` ${x}`;
|
||||
} else {
|
||||
str += ` ${inspect(x)}`;
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function inspect(obj, options = {}) {
|
||||
if (options.truncate === 0) {
|
||||
options.truncate = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
return inspect$1(obj, options);
|
||||
}
|
||||
function objDisplay(obj, options = {}) {
|
||||
if (typeof options.truncate === "undefined") {
|
||||
options.truncate = 40;
|
||||
}
|
||||
const str = inspect(obj, options);
|
||||
const type = Object.prototype.toString.call(obj);
|
||||
if (options.truncate && str.length >= options.truncate) {
|
||||
if (type === "[object Function]") {
|
||||
const fn = obj;
|
||||
return !fn.name ? "[Function]" : `[Function: ${fn.name}]`;
|
||||
} else if (type === "[object Array]") {
|
||||
return `[ Array(${obj.length}) ]`;
|
||||
} else if (type === "[object Object]") {
|
||||
const keys = Object.keys(obj);
|
||||
const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", ");
|
||||
return `{ Object (${kstr}) }`;
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
export { format, formatRegExp, inspect, objDisplay, stringify };
|
||||
7
node_modules/@vitest/utils/dist/error.d.ts
generated
vendored
Normal file
7
node_modules/@vitest/utils/dist/error.d.ts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import { D as DiffOptions } from './types.d-BCElaP-c.js';
|
||||
export { serializeValue as serializeError } from './serialize.js';
|
||||
import '@vitest/pretty-format';
|
||||
|
||||
declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
|
||||
|
||||
export { processError };
|
||||
42
node_modules/@vitest/utils/dist/error.js
generated
vendored
Normal file
42
node_modules/@vitest/utils/dist/error.js
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
import { printDiffOrStringify } from './diff.js';
|
||||
import { stringify } from './display.js';
|
||||
import { serializeValue } from './serialize.js';
|
||||
import '@vitest/pretty-format';
|
||||
import 'tinyrainbow';
|
||||
import './helpers.js';
|
||||
import './constants.js';
|
||||
import './chunk-_commonjsHelpers.js';
|
||||
|
||||
function processError(_err, diffOptions, seen = new WeakSet()) {
|
||||
if (!_err || typeof _err !== "object") {
|
||||
return { message: String(_err) };
|
||||
}
|
||||
const err = _err;
|
||||
if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) {
|
||||
err.diff = printDiffOrStringify(err.actual, err.expected, {
|
||||
...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);
|
||||
}
|
||||
// some Error implementations may not allow rewriting cause
|
||||
// in most cases, the assignment will lead to "err.cause = err.cause"
|
||||
try {
|
||||
if (!seen.has(err) && typeof err.cause === "object") {
|
||||
seen.add(err);
|
||||
err.cause = processError(err.cause, diffOptions, seen);
|
||||
}
|
||||
} catch {}
|
||||
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}`));
|
||||
}
|
||||
}
|
||||
|
||||
export { processError, serializeValue as serializeError };
|
||||
73
node_modules/@vitest/utils/dist/helpers.d.ts
generated
vendored
Normal file
73
node_modules/@vitest/utils/dist/helpers.d.ts
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
import { Nullable, Arrayable } from './types.js';
|
||||
|
||||
declare function nanoid(size?: number): string;
|
||||
|
||||
declare function shuffle<T>(array: T[], seed?: number): T[];
|
||||
|
||||
interface CloneOptions {
|
||||
forceWritable?: boolean;
|
||||
}
|
||||
interface ErrorOptions {
|
||||
message?: string;
|
||||
stackTraceLimit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
declare function createSimpleStackTrace(options?: ErrorOptions): string;
|
||||
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
|
||||
declare function assertTypes(value: unknown, name: string, types: string[]): void;
|
||||
declare function isPrimitive(value: unknown): boolean;
|
||||
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;
|
||||
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
|
||||
declare function isObject(item: unknown): boolean;
|
||||
declare function getType(value: unknown): string;
|
||||
declare function getOwnProperties(obj: any): (string | symbol)[];
|
||||
declare function deepClone<T>(val: T, options?: CloneOptions): T;
|
||||
declare function clone<T>(val: T, seen: WeakMap<any, any>, options?: CloneOptions): T;
|
||||
declare function noop(): void;
|
||||
declare function objectAttr(source: any, path: string, defaultValue?: undefined): any;
|
||||
type DeferPromise<T> = Promise<T> & {
|
||||
resolve: (value: T | PromiseLike<T>) => void;
|
||||
reject: (reason?: any) => void;
|
||||
};
|
||||
declare function createDefer<T>(): DeferPromise<T>;
|
||||
/**
|
||||
* 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')
|
||||
* ```
|
||||
*/
|
||||
declare function getCallLastIndex(code: string): number | null;
|
||||
declare function isNegativeNaN(val: number): boolean;
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): 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 type { DeferPromise };
|
||||
295
node_modules/@vitest/utils/dist/helpers.js
generated
vendored
Normal file
295
node_modules/@vitest/utils/dist/helpers.js
generated
vendored
Normal file
@@ -0,0 +1,295 @@
|
||||
import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js';
|
||||
|
||||
// port from nanoid
|
||||
// https://github.com/ai/nanoid
|
||||
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
||||
function nanoid(size = 21) {
|
||||
let id = "";
|
||||
let i = size;
|
||||
while (i--) {
|
||||
id += urlAlphabet[Math.random() * 64 | 0];
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
const RealDate = Date;
|
||||
function random(seed) {
|
||||
const x = Math.sin(seed++) * 1e4;
|
||||
return x - Math.floor(x);
|
||||
}
|
||||
function shuffle(array, seed = RealDate.now()) {
|
||||
let length = array.length;
|
||||
while (length) {
|
||||
const index = Math.floor(random(seed) * length--);
|
||||
const previous = array[length];
|
||||
array[length] = array[index];
|
||||
array[index] = previous;
|
||||
++seed;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.at(-1) !== "/") {
|
||||
return `${path}/`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
|
||||
function isBareImport(id) {
|
||||
return bareImportRE.test(id);
|
||||
}
|
||||
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, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
|
||||
9
node_modules/@vitest/utils/dist/highlight.d.ts
generated
vendored
Normal file
9
node_modules/@vitest/utils/dist/highlight.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Colors } from 'tinyrainbow';
|
||||
|
||||
interface HighlightOptions {
|
||||
jsx?: boolean;
|
||||
colors?: Colors;
|
||||
}
|
||||
declare function highlight(code: string, options?: HighlightOptions): string;
|
||||
|
||||
export { highlight };
|
||||
538
node_modules/@vitest/utils/dist/highlight.js
generated
vendored
Normal file
538
node_modules/@vitest/utils/dist/highlight.js
generated
vendored
Normal file
@@ -0,0 +1,538 @@
|
||||
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 };
|
||||
5
node_modules/@vitest/utils/dist/index.d.ts
generated
vendored
Normal file
5
node_modules/@vitest/utils/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
export { LoupeOptions, StringifyOptions } from './display.js';
|
||||
export { DeferPromise } from './helpers.js';
|
||||
export { SafeTimers } from './timers.js';
|
||||
export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js';
|
||||
import '@vitest/pretty-format';
|
||||
1
node_modules/@vitest/utils/dist/index.js
generated
vendored
Normal file
1
node_modules/@vitest/utils/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
5
node_modules/@vitest/utils/dist/offset.d.ts
generated
vendored
Normal file
5
node_modules/@vitest/utils/dist/offset.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
declare const lineSplitRE: RegExp;
|
||||
declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number;
|
||||
declare function offsetToLineNumber(source: string, offset: number): number;
|
||||
|
||||
export { lineSplitRE, offsetToLineNumber, positionToOffset };
|
||||
32
node_modules/@vitest/utils/dist/offset.js
generated
vendored
Normal file
32
node_modules/@vitest/utils/dist/offset.js
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
const lineSplitRE = /\r?\n/;
|
||||
function positionToOffset(source, lineNumber, columnNumber) {
|
||||
const lines = source.split(lineSplitRE);
|
||||
const nl = /\r\n/.test(source) ? 2 : 1;
|
||||
let start = 0;
|
||||
if (lineNumber > lines.length) {
|
||||
return source.length;
|
||||
}
|
||||
for (let i = 0; i < lineNumber - 1; i++) {
|
||||
start += lines[i].length + nl;
|
||||
}
|
||||
return start + columnNumber;
|
||||
}
|
||||
function offsetToLineNumber(source, offset) {
|
||||
if (offset > source.length) {
|
||||
throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
|
||||
}
|
||||
const lines = source.split(lineSplitRE);
|
||||
const nl = /\r\n/.test(source) ? 2 : 1;
|
||||
let counted = 0;
|
||||
let line = 0;
|
||||
for (; line < lines.length; line++) {
|
||||
const lineLength = lines[line].length + nl;
|
||||
if (counted + lineLength >= offset) {
|
||||
break;
|
||||
}
|
||||
counted += lineLength;
|
||||
}
|
||||
return line + 1;
|
||||
}
|
||||
|
||||
export { lineSplitRE, offsetToLineNumber, positionToOffset };
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user