@depup/vitest__mocker 4.1.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ import './types.d-BjI5eAwu.js';
2
+
3
+ type Key = string | symbol;
4
+ type CreateMockInstanceProcedure = (options?: {
5
+ prototypeMembers?: (string | symbol)[];
6
+ name?: string | symbol;
7
+ originalImplementation?: (...args: any[]) => any;
8
+ keepMembersImplementation?: boolean;
9
+ }) => any;
10
+ interface MockObjectOptions {
11
+ type: "automock" | "autospy";
12
+ globalConstructors: GlobalConstructors;
13
+ createMockInstance: CreateMockInstanceProcedure;
14
+ }
15
+ declare function mockObject(options: MockObjectOptions, object: Record<Key, any>, mockExports?: Record<Key, any>): Record<Key, any>;
16
+ interface GlobalConstructors {
17
+ Object: ObjectConstructor;
18
+ Function: FunctionConstructor;
19
+ RegExp: RegExpConstructor;
20
+ Array: ArrayConstructor;
21
+ Map: MapConstructor;
22
+ }
23
+
24
+ export { mockObject as m };
25
+ export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M };
@@ -0,0 +1,2 @@
1
+ export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-B41z0AuW.js';
2
+ export { A as AutomockedModule, g as AutomockedModuleSerialized, h as AutospiedModule, i as AutospiedModuleSerialized, j as ManualMockedModule, k as ManualMockedModuleSerialized, a as MockedModule, l as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, e as ModuleMockContext, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, n as RedirectedModuleSerialized, f as ServerIdResolution, S as ServerMockResolution, T as TestModuleMocker } from './types.d-BjI5eAwu.js';
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js';
2
+
3
+ function mockObject(options, object, mockExports = {}) {
4
+ const finalizers = new Array();
5
+ const refs = new RefTracker();
6
+ const define = (container, key, value) => {
7
+ try {
8
+ container[key] = value;
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ };
14
+ const createMock = (currentValue) => {
15
+ if (!options.createMockInstance) {
16
+ throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
17
+ }
18
+ const createMockInstance = options.createMockInstance;
19
+ const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
20
+ return createMockInstance({
21
+ name: currentValue.name,
22
+ prototypeMembers,
23
+ originalImplementation: options.type === "autospy" ? currentValue : undefined,
24
+ keepMembersImplementation: options.type === "autospy"
25
+ });
26
+ };
27
+ const mockPropertiesOf = (container, newContainer) => {
28
+ const containerType = getType(container);
29
+ const isModule = containerType === "Module" || !!container.__esModule;
30
+ for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
31
+ // Modules define their exports as getters. We want to process those.
32
+ if (!isModule && descriptor.get) {
33
+ try {
34
+ if (options.type === "autospy") {
35
+ Object.defineProperty(newContainer, property, descriptor);
36
+ } else {
37
+ Object.defineProperty(newContainer, property, {
38
+ configurable: descriptor.configurable,
39
+ enumerable: descriptor.enumerable,
40
+ get: () => {},
41
+ set: descriptor.set ? () => {} : undefined
42
+ });
43
+ }
44
+ } catch {}
45
+ continue;
46
+ }
47
+ // Skip special read-only props, we don't want to mess with those.
48
+ if (isReadonlyProp(container[property], property)) {
49
+ continue;
50
+ }
51
+ const value = container[property];
52
+ // Special handling of references we've seen before to prevent infinite
53
+ // recursion in circular objects.
54
+ const refId = refs.getId(value);
55
+ if (refId !== undefined) {
56
+ finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
57
+ continue;
58
+ }
59
+ const type = getType(value);
60
+ if (Array.isArray(value)) {
61
+ if (options.type === "automock") {
62
+ define(newContainer, property, []);
63
+ } else {
64
+ const array = value.map((value) => {
65
+ if (value && typeof value === "object") {
66
+ const newObject = {};
67
+ mockPropertiesOf(value, newObject);
68
+ return newObject;
69
+ }
70
+ if (typeof value === "function") {
71
+ return createMock(value);
72
+ }
73
+ return value;
74
+ });
75
+ define(newContainer, property, array);
76
+ }
77
+ continue;
78
+ }
79
+ const isFunction = type.includes("Function") && typeof value === "function";
80
+ if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
81
+ define(newContainer, property, value);
82
+ continue;
83
+ }
84
+ if (options.type === "autospy" && type === "Module") {
85
+ // Replace with clean object to recursively autospy exported module objects:
86
+ // export * as ns from "./ns"
87
+ // or
88
+ // import * as ns from "./ns"
89
+ // export { ns }
90
+ const exports$1 = Object.create(null);
91
+ Object.defineProperty(exports$1, Symbol.toStringTag, {
92
+ value: "Module",
93
+ configurable: true,
94
+ writable: true
95
+ });
96
+ try {
97
+ newContainer[property] = exports$1;
98
+ } catch {
99
+ continue;
100
+ }
101
+ } else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
102
+ continue;
103
+ }
104
+ if (isFunction) {
105
+ const mock = createMock(newContainer[property]);
106
+ newContainer[property] = mock;
107
+ }
108
+ refs.track(value, newContainer[property]);
109
+ mockPropertiesOf(value, newContainer[property]);
110
+ }
111
+ };
112
+ const mockedObject = mockExports;
113
+ mockPropertiesOf(object, mockedObject);
114
+ // Plug together refs
115
+ for (const finalizer of finalizers) {
116
+ finalizer();
117
+ }
118
+ return mockedObject;
119
+ }
120
+ class RefTracker {
121
+ idMap = new Map();
122
+ mockedValueMap = new Map();
123
+ getId(value) {
124
+ return this.idMap.get(value);
125
+ }
126
+ getMockedValue(id) {
127
+ return this.mockedValueMap.get(id);
128
+ }
129
+ track(originalValue, mockedValue) {
130
+ const newId = this.idMap.size;
131
+ this.idMap.set(originalValue, newId);
132
+ this.mockedValueMap.set(newId, mockedValue);
133
+ return newId;
134
+ }
135
+ }
136
+ function getType(value) {
137
+ return Object.prototype.toString.apply(value).slice(8, -1);
138
+ }
139
+ function isReadonlyProp(object, prop) {
140
+ if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
141
+ const typeName = getType(object);
142
+ return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
143
+ }
144
+ if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
145
+ return getType(object) === "RegExp";
146
+ }
147
+ return false;
148
+ }
149
+ function getAllMockableProperties(obj, isModule, constructors) {
150
+ const { Map, Object, Function, RegExp, Array } = constructors;
151
+ const allProps = new Map();
152
+ let curr = obj;
153
+ do {
154
+ // we don't need properties from these
155
+ if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) {
156
+ break;
157
+ }
158
+ collectOwnProperties(curr, (key) => {
159
+ const descriptor = Object.getOwnPropertyDescriptor(curr, key);
160
+ if (descriptor) {
161
+ allProps.set(key, {
162
+ key,
163
+ descriptor
164
+ });
165
+ }
166
+ });
167
+ } while (curr = Object.getPrototypeOf(curr));
168
+ // default is not specified in ownKeys, if module is interoped
169
+ if (isModule && !allProps.has("default") && "default" in obj) {
170
+ const descriptor = Object.getOwnPropertyDescriptor(obj, "default");
171
+ if (descriptor) {
172
+ allProps.set("default", {
173
+ key: "default",
174
+ descriptor
175
+ });
176
+ }
177
+ }
178
+ return Array.from(allProps.values());
179
+ }
180
+ function collectOwnProperties(obj, collector) {
181
+ const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
182
+ Object.getOwnPropertyNames(obj).forEach(collect);
183
+ Object.getOwnPropertySymbols(obj).forEach(collect);
184
+ }
185
+ function collectFunctionProperties(prototype) {
186
+ const properties = new Set();
187
+ collectOwnProperties(prototype, (prop) => {
188
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
189
+ if (!descriptor || descriptor.get) {
190
+ return;
191
+ }
192
+ const type = getType(descriptor.value);
193
+ if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
194
+ properties.add(prop);
195
+ }
196
+ });
197
+ return Array.from(properties);
198
+ }
199
+
200
+ export { mockObject };
@@ -0,0 +1,86 @@
1
+ import { MaybeMockedDeep } from '@vitest/spy';
2
+ import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, T as TestModuleMocker, M as MockerRegistry, d as MockedModuleType, e as ModuleMockContext } from './types.d-BjI5eAwu.js';
3
+ import { C as CreateMockInstanceProcedure } from './index.d-B41z0AuW.js';
4
+
5
+ interface CompilerHintsOptions {
6
+ /**
7
+ * This is the key used to access the globalThis object in the worker.
8
+ * Unlike `globalThisAccessor` in other APIs, this is not injected into the script.
9
+ * ```ts
10
+ * // globalThisKey: '__my_variable__' produces:
11
+ * globalThis['__my_variable__']
12
+ * // globalThisKey: '"__my_variable__"' produces:
13
+ * globalThis['"__my_variable__"'] // notice double quotes
14
+ * ```
15
+ * @default '__vitest_mocker__'
16
+ */
17
+ globalThisKey?: string;
18
+ }
19
+ interface ModuleMockerCompilerHints {
20
+ hoisted: <T>(factory: () => T) => T;
21
+ mock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
22
+ unmock: (path: string | Promise<unknown>) => void;
23
+ doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
24
+ doUnmock: (path: string | Promise<unknown>) => void;
25
+ importActual: <T>(path: string) => Promise<T>;
26
+ importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>;
27
+ }
28
+ declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints;
29
+
30
+ interface ModuleMockerInterceptor {
31
+ register: (module: MockedModule) => Promise<void>;
32
+ delete: (url: string) => Promise<void>;
33
+ invalidate: () => Promise<void>;
34
+ }
35
+
36
+ declare class ModuleMocker implements TestModuleMocker {
37
+ private interceptor;
38
+ private rpc;
39
+ private createMockInstance;
40
+ private config;
41
+ protected registry: MockerRegistry;
42
+ private queue;
43
+ private mockedIds;
44
+ constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig);
45
+ prepare(): Promise<void>;
46
+ resolveFactoryModule(id: string): Promise<Record<string | symbol, any>>;
47
+ getFactoryModule(id: string): any;
48
+ invalidate(): Promise<void>;
49
+ importActual<T>(id: string, importer: string): Promise<T>;
50
+ protected getBaseUrl(): string;
51
+ importMock<T>(rawId: string, importer: string): Promise<T>;
52
+ mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
53
+ mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
54
+ getMockContext(): ModuleMockContext;
55
+ queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
56
+ queueUnmock(id: string, importer: string): void;
57
+ wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
58
+ getMockedModuleById(id: string): MockedModule | undefined;
59
+ reset(): void;
60
+ private resolveMockPath;
61
+ }
62
+ interface ResolveIdResult {
63
+ id: string;
64
+ url: string;
65
+ optimized: boolean;
66
+ }
67
+ interface ResolveMockResult {
68
+ mockType: MockedModuleType;
69
+ resolvedId: string;
70
+ resolvedUrl: string;
71
+ redirectUrl?: string | null;
72
+ needsInterop?: boolean;
73
+ }
74
+ interface ModuleMockerRPC {
75
+ invalidate: (ids: string[]) => Promise<void>;
76
+ resolveId: (id: string, importer: string) => Promise<ResolveIdResult | null>;
77
+ resolveMock: (id: string, importer: string, options: {
78
+ mock: "spy" | "factory" | "auto";
79
+ }) => Promise<ResolveMockResult>;
80
+ }
81
+ interface ModuleMockerConfig {
82
+ root: string;
83
+ }
84
+
85
+ export { ModuleMocker as b, createCompilerHints as f };
86
+ export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as c, ModuleMockerRPC as d, ResolveMockResult as e };
package/dist/node.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ import { H as HoistMocksOptions } from './hoistMocks.d-w2ILr1dG.js';
2
+ export { c as createManualModuleSource } from './hoistMocks.d-w2ILr1dG.js';
3
+ import { AutomockOptions } from './automock.js';
4
+ export { automockModule } from './automock.js';
5
+ import { Plugin, Rollup, ViteDevServer } from 'vite';
6
+ import { SourceMap } from 'magic-string';
7
+ import { M as MockerRegistry, S as ServerMockResolution, f as ServerIdResolution } from './types.d-BjI5eAwu.js';
8
+ export { findMockRedirect } from './redirect.js';
9
+
10
+ declare function automockPlugin(options?: AutomockOptions): Plugin;
11
+
12
+ interface DynamicImportPluginOptions {
13
+ /**
14
+ * @default `"__vitest_mocker__"`
15
+ */
16
+ globalThisAccessor?: string;
17
+ filter?: (id: string) => boolean;
18
+ }
19
+ declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin;
20
+
21
+ interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistable"> {
22
+ include?: string | RegExp | (string | RegExp)[];
23
+ exclude?: string | RegExp | (string | RegExp)[];
24
+ /**
25
+ * overrides include/exclude options
26
+ */
27
+ filter?: (id: string) => boolean;
28
+ }
29
+ declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin;
30
+ declare function hoistMockAndResolve(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
31
+ interface HoistMocksResult {
32
+ code: string;
33
+ map: SourceMap;
34
+ }
35
+
36
+ interface InterceptorPluginOptions {
37
+ /**
38
+ * @default "__vitest_mocker__"
39
+ */
40
+ globalThisAccessor?: string;
41
+ registry?: MockerRegistry;
42
+ }
43
+ declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin;
44
+
45
+ interface MockerPluginOptions extends AutomockOptions {
46
+ hoistMocks?: HoistMocksPluginOptions;
47
+ }
48
+ declare function mockerPlugin(options?: MockerPluginOptions): Plugin[];
49
+
50
+ interface ServerResolverOptions {
51
+ /**
52
+ * @default ['/node_modules/']
53
+ */
54
+ moduleDirectories?: string[];
55
+ }
56
+ declare class ServerMockResolver {
57
+ private server;
58
+ private options;
59
+ constructor(server: ViteDevServer, options?: ServerResolverOptions);
60
+ resolveMock(rawId: string, importer: string, options: {
61
+ mock: "spy" | "factory" | "auto";
62
+ }): Promise<ServerMockResolution>;
63
+ invalidate(ids: string[]): void;
64
+ resolveId(id: string, importer?: string): Promise<ServerIdResolution | null>;
65
+ private normalizeResolveIdToUrl;
66
+ private resolveMockId;
67
+ private resolveModule;
68
+ }
69
+
70
+ export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, dynamicImportPlugin, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
71
+ export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions };