hypotes 0.0.0-stage → 0.0.1-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.
package/dist/index.js ADDED
@@ -0,0 +1,274 @@
1
+ import { a as hoisted, c as unmock, i as doUnmock, o as importActual, r as doMock, s as mock } from "./mocks-ciQvBYVw.js";
2
+ import { a as suite, n as describe, o as test, r as it } from "./tests-D4v1ZaoR.js";
3
+ import { clearAllMocks, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn } from "@vitest/spy";
4
+ import { diff, inspect, styleText } from "node:util";
5
+ import { JestAsymmetricMatchers, JestChaiExpect, JestExtend, addCustomEqualityTesters, arrayBufferEquality, chai, customMatchers, getCustomEqualityTesters, isAsymmetric, iterableEquality, sparseArrayEquality, typeEquality } from "@vitest/expect";
6
+ import { disableDefaultColors } from "tinyrainbow";
7
+ import { Buffer } from "node:buffer";
8
+ import * as nodeTest from "node:test";
9
+ // source/equals.ts
10
+ /**
11
+ * Nesting past which the tester leaves values to `equals`, which tells
12
+ * cycles from deep values
13
+ */
14
+ const MAX_DEPTH = 256;
15
+ /**
16
+ * Whether `a` and `b` are equal as `equals` compares them with the testers
17
+ * of `toEqual` or of `toStrictEqual`, strictly or not, or undefined to leave
18
+ * them to `equals`. It leaves them all to it with testers of other matchers,
19
+ * such as `toMatchObject`, or other custom testers, whose results it couldn't
20
+ * know.
21
+ */
22
+ const fastEquality = function(a, b, customTesters) {
23
+ const strict = strictnessOf(customTesters);
24
+ return strict === void 0 ? void 0 : compare(a, b, strict, 0);
25
+ };
26
+ /**
27
+ * Whether the testers are those of `toStrictEqual`, which compare
28
+ * constructors and tell holes from undefined, rather than `toEqual`, or
29
+ * undefined if they're another matcher's
30
+ */
31
+ function strictnessOf(customTesters) {
32
+ if (getCustomEqualityTesters().length !== 1 || customTesters[0] !== fastEquality) return;
33
+ if (customTesters.length === 2 && customTesters[1] === iterableEquality) return false;
34
+ return customTesters.length === 5 && customTesters[1] === iterableEquality && customTesters[2] === typeEquality && customTesters[3] === sparseArrayEquality && customTesters[4] === arrayBufferEquality ? true : void 0;
35
+ }
36
+ function compare(a, b, strict, depth) {
37
+ if (!isObject(a) || !isObject(b)) {
38
+ if (Object.is(a, b)) return true;
39
+ return isAsymmetric(a) || isAsymmetric(b) ? void 0 : false;
40
+ }
41
+ if (depth > MAX_DEPTH || isAsymmetric(a) || isAsymmetric(b)) return;
42
+ if (Array.isArray(a)) return Array.isArray(b) ? compareArrays(a, b, strict, depth) : false;
43
+ if (isTypedArray(a)) return isTypedArray(b) && a.constructor === b.constructor ? compareTypedArrays(a, b) : void 0;
44
+ if (isPlainObject(a) && isPlainObject(b)) return compareObjects(a, b, strict, depth);
45
+ }
46
+ function isObject(value) {
47
+ return typeof value === "object" && value !== null;
48
+ }
49
+ function isTypedArray(value) {
50
+ return ArrayBuffer.isView(value) && !(value instanceof DataView);
51
+ }
52
+ /**
53
+ * Whether `equals` compares the value by its own keys alone: an object of
54
+ * Object's tag, whatever its prototype, that isn't iterable or an error
55
+ */
56
+ function isPlainObject(value) {
57
+ return Object.prototype.toString.call(value) === "[object Object]" && !(Symbol.iterator in value) && !Error.isError(value);
58
+ }
59
+ /**
60
+ * Objects of the same constructor, if strict, with the same own enumerable
61
+ * string keys, and equal values at them. Where the keys that only one of
62
+ * them has all have undefined values, they're equal unless `equals` compares
63
+ * strictly, which is left to it.
64
+ */
65
+ function compareObjects(a, b, strict, depth) {
66
+ if (a === b) return true;
67
+ if (strict && a.constructor !== b.constructor) return false;
68
+ const aKeys = Object.keys(a);
69
+ const bKeys = Object.keys(b);
70
+ let sameKeys = aKeys.length === bKeys.length;
71
+ for (const key of aKeys) {
72
+ const value = a[key];
73
+ if (Object.hasOwn(b, key)) {
74
+ const equal = compare(value, b[key], strict, depth + 1);
75
+ if (equal !== true) return equal;
76
+ } else if (value === void 0) sameKeys = false;
77
+ else return false;
78
+ }
79
+ if (sameKeys) return true;
80
+ return hasDefinedKeyMissingFrom(b, bKeys, a) ? false : void 0;
81
+ }
82
+ /** Whether a key of the object has a value other than undefined, and the other lacks it */
83
+ function hasDefinedKeyMissingFrom(object, keys, other) {
84
+ for (const key of keys) if (!Object.hasOwn(other, key) && object[key] !== void 0) return true;
85
+ return false;
86
+ }
87
+ /**
88
+ * Arrays of the same constructor, if strict, and length, with equal elements.
89
+ * A hole is missing, which the testers of `toStrictEqual` tell from
90
+ * undefined. With those of `toEqual`, the two are equal unless `equals`
91
+ * compares strictly, which is left to it.
92
+ */
93
+ function compareArrays(a, b, strict, depth) {
94
+ if (a === b) return true;
95
+ if (strict && a.constructor !== b.constructor || a.length !== b.length) return false;
96
+ for (let index = 0; index < a.length; index++) {
97
+ const value = a[index];
98
+ const other = b[index];
99
+ if (value === other && typeof value !== "object" && value !== 0) {
100
+ if (value === void 0 && index in a !== index in b) return strict ? false : void 0;
101
+ continue;
102
+ }
103
+ const equal = compare(value, other, strict, depth + 1);
104
+ if (equal !== true) return equal;
105
+ }
106
+ return true;
107
+ }
108
+ /**
109
+ * Typed arrays of the same constructor and length, with equal elements, as
110
+ * `Object.is` compares them. Equal bytes make equal elements; a float array's
111
+ * elements can be equal with other bytes, as NaNs.
112
+ */
113
+ function compareTypedArrays(a, b) {
114
+ if (a.length !== b.length) return false;
115
+ if (a === b || Buffer.compare(bytesOf(a), bytesOf(b)) === 0) return true;
116
+ return (a instanceof Float64Array || a instanceof Float32Array || a instanceof Float16Array) && haveSameElements(a, b);
117
+ }
118
+ function bytesOf(array) {
119
+ return new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
120
+ }
121
+ function haveSameElements(a, b) {
122
+ for (let index = 0; index < a.length; index++) if (!Object.is(a[index], b[index])) return false;
123
+ return true;
124
+ }
125
+ // source/expect.ts
126
+ // @vitest/expect colours the messages of its spies' matchers with
127
+ if (styleText("red", "text") === "text") disableDefaultColors();
128
+ chai.use(JestExtend);
129
+ chai.use(JestChaiExpect);
130
+ chai.use(JestAsymmetricMatchers);
131
+ const chaiExpect = chai.expect;
132
+ const expect = Object.assign((actual, message) => chaiExpect(actual, message), chaiExpect, {
133
+ extend: (matchers) => {
134
+ chaiExpect.extend(expect, matchers);
135
+ },
136
+ addEqualityTesters: (testers) => {
137
+ addCustomEqualityTesters(testers);
138
+ }
139
+ });
140
+ expect.extend(customMatchers);
141
+ addCustomEqualityTesters([fastEquality]);
142
+ const INSPECT_OPTIONS = {
143
+ depth: 1e400,
144
+ maxArrayLength: 1e400,
145
+ maxStringLength: 1e400,
146
+ sorted: true
147
+ };
148
+ /** Unchanged lines kept around each change */
149
+ const CONTEXT = 3;
150
+ /**
151
+ * The lines of each value that are compared, from the first that differs:
152
+ * comparing takes time that grows with their number times the number that
153
+ * differ, which is seconds for tens of thousands of lines
154
+ */
155
+ const MAX_LINES = 1e3;
156
+ const OMITTED = " ...";
157
+ /**
158
+ * The lines of two values' inspections that differ, with some around them,
159
+ * or undefined if none does
160
+ */
161
+ function describeDiff(actual, expected) {
162
+ const actualLines = inspect(actual, INSPECT_OPTIONS).split("\n");
163
+ const expectedLines = inspect(expected, INSPECT_OPTIONS).split("\n");
164
+ const start = commonStart(actualLines, expectedLines);
165
+ const end = commonEnd(actualLines, expectedLines, start);
166
+ if (start + end === Math.max(actualLines.length, expectedLines.length)) return;
167
+ const from = Math.max(0, start - CONTEXT);
168
+ const actualTo = Math.min(actualLines.length - end + CONTEXT, from + MAX_LINES);
169
+ const expectedTo = Math.min(expectedLines.length - end + CONTEXT, from + MAX_LINES);
170
+ const changes = diff(actualLines.slice(from, actualTo), expectedLines.slice(from, expectedTo));
171
+ const hasAfter = actualTo < actualLines.length || expectedTo < expectedLines.length;
172
+ return describeChanges(changes, from > 0, hasAfter);
173
+ }
174
+ /** How many lines both start with */
175
+ function commonStart(a, b) {
176
+ const length = Math.min(a.length, b.length);
177
+ let count = 0;
178
+ while (count < length && a[count] === b[count]) count++;
179
+ return count;
180
+ }
181
+ /** How many lines both end with, after the `start` that both start with */
182
+ function commonEnd(a, b, start) {
183
+ const length = Math.min(a.length, b.length) - start;
184
+ let count = 0;
185
+ while (count < length && a.at(-1 - count) === b.at(-1 - count)) count++;
186
+ return count;
187
+ }
188
+ /**
189
+ * The changed lines, each marked as the actual value's or the expected
190
+ * one's, with the unchanged lines around them, and a mark where others are
191
+ * left out: between them, and before and after, if there are any
192
+ */
193
+ function describeChanges(changes, hasBefore, hasAfter) {
194
+ const changed = changes.map(([operation]) => operation !== 0);
195
+ const nearChange = (index) => changed.slice(Math.max(0, index - CONTEXT), index + CONTEXT + 1).includes(true);
196
+ const lines = hasBefore ? [OMITTED] : [];
197
+ for (const [index, [operation, line]] of changes.entries()) if (nearChange(index)) lines.push(`${operation === 1 ? "+" : operation === -1 ? "-" : " "} ${line}`);
198
+ else if (lines.at(-1) !== OMITTED) lines.push(OMITTED);
199
+ if (hasAfter && lines.at(-1) !== OMITTED) lines.push(OMITTED);
200
+ return lines.join("\n");
201
+ }
202
+ /** Marks chai's `assert` once it adds diffs, if another copy of this module loads */
203
+ const WITH_DIFF = Symbol.for("hypotes.withDiff");
204
+ const assert = chai.Assertion.prototype.assert;
205
+ if (assert[WITH_DIFF] !== true) {
206
+ const assertWithDiff = function(...args) {
207
+ try {
208
+ assert.apply(this, args);
209
+ } catch (error) {
210
+ if (error instanceof chai.AssertionError && error.showDiff === true) {
211
+ const changes = describeDiff(error.actual, error.expected);
212
+ if (changes !== void 0) error.message += `\n\n+ actual - expected\n\n${changes}`;
213
+ }
214
+ throw error;
215
+ }
216
+ };
217
+ assertWithDiff[WITH_DIFF] = true;
218
+ chai.Assertion.prototype.assert = assertWithDiff;
219
+ }
220
+ // source/hooks.ts
221
+ /** Runs `cleanup` if a hook returned a function */
222
+ async function cleanUp(cleanup) {
223
+ if (typeof cleanup === "function") await cleanup();
224
+ }
225
+ /** Runs the hook before the suite's tests, and its cleanup after them */
226
+ function beforeAll(fn, timeout) {
227
+ let cleanup;
228
+ nodeTest.before(async (context) => {
229
+ cleanup = await fn(context);
230
+ }, { timeout });
231
+ nodeTest.after(() => cleanUp(cleanup), { timeout });
232
+ }
233
+ /** Runs the hook after the suite's tests */
234
+ function afterAll(fn, timeout) {
235
+ nodeTest.after(async (context) => void await fn(context), { timeout });
236
+ }
237
+ /** Runs the hook before each of the suite's tests, and its cleanup after it */
238
+ function beforeEach(fn, timeout) {
239
+ const cleanups = /* @__PURE__ */ new WeakMap();
240
+ nodeTest.beforeEach(async (context) => {
241
+ const test = context;
242
+ cleanups.set(test, await fn(test));
243
+ }, { timeout });
244
+ nodeTest.afterEach((context) => cleanUp(cleanups.get(context)), { timeout });
245
+ }
246
+ /** Runs the hook after each of the suite's tests */
247
+ function afterEach(fn, timeout) {
248
+ nodeTest.afterEach(async (context) => void await fn(context), { timeout });
249
+ }
250
+ // source/index.ts
251
+ function mocked(item) {
252
+ return item;
253
+ }
254
+ /**
255
+ * Vitest's spies, which its matchers, such as `toHaveBeenCalledWith`, check,
256
+ * and its module mocks, which node preloads with `--import hypotes/register`.
257
+ * node:test's `mock` mocks timers.
258
+ */
259
+ const vi = {
260
+ clearAllMocks,
261
+ doMock,
262
+ doUnmock,
263
+ fn,
264
+ hoisted,
265
+ importActual,
266
+ isMockFunction,
267
+ mock,
268
+ mocked,
269
+ resetAllMocks,
270
+ restoreAllMocks,
271
+ spyOn,
272
+ unmock
273
+ };
274
+ export { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, suite, test, vi };
@@ -0,0 +1,281 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ // source/mocks.ts
3
+ /** The registry's key on globalThis, for the code of transformed modules */
4
+ const MOCKS_KEY = "hypotes.mocks";
5
+ const MOCKS = Symbol.for(MOCKS_KEY);
6
+ /** The scheme of each mocked module's URL: `hypotes-mock:<id>:<url>` */
7
+ const MOCK = "hypotes-mock:";
8
+ /** The scheme of the URL that resolves to a mocked module's original */
9
+ const ACTUAL = "hypotes-actual:";
10
+ /**
11
+ * The scheme of the URL of a package that isn't installed, or an import that
12
+ * isn't defined, which a mock stands in for: `hypotes-package:<specifier>`
13
+ */
14
+ const PACKAGE = "hypotes-package:";
15
+ /**
16
+ * The drive of a Windows path, such as `C:\a.ts`, which parses as a URL whose
17
+ * scheme is the drive's letter
18
+ */
19
+ const DRIVE = /^[a-z]:/iu;
20
+ /**
21
+ * The mocks whose factories run the code that reads this, or started it: an
22
+ * import from a factory doesn't wait for that factory, which waits for it
23
+ */
24
+ const running = new AsyncLocalStorage();
25
+ /** Imports the original of a mocked module */
26
+ function importOriginal(url) {
27
+ return import(ACTUAL + url);
28
+ }
29
+ /** A mock of a module, whose factory runs once */
30
+ var ModuleMock = class {
31
+ /** The URL that the module resolves to while it's mocked */
32
+ url;
33
+ #original;
34
+ #factory;
35
+ #ran = false;
36
+ /** Resolves once the exports of a factory that returned a promise settle */
37
+ #settling;
38
+ #outcome;
39
+ constructor(id, original, factory) {
40
+ this.url = `${MOCK}${id}:${original}`;
41
+ this.#original = original;
42
+ this.#factory = factory;
43
+ }
44
+ /**
45
+ * Runs the factory, unless it ran, and resolves once its exports have
46
+ * settled, but for the factory's own code, which they wait for
47
+ */
48
+ run() {
49
+ const around = running.getStore();
50
+ if (this.#ran) return around?.has(this) === true ? void 0 : this.#settling;
51
+ this.#ran = true;
52
+ let exports;
53
+ try {
54
+ exports = running.run(new Set(around).add(this), () => this.#factory(() => importOriginal(this.#original)));
55
+ } catch (error) {
56
+ this.#fail(error);
57
+ return;
58
+ }
59
+ if (typeof exports?.then === "function") {
60
+ this.#settling = this.#await(exports);
61
+ return this.#settling;
62
+ }
63
+ this.#settle(exports);
64
+ }
65
+ /** The factory's exports, for the mocked module, which loads now */
66
+ exports() {
67
+ this.run();
68
+ const outcome = this.#outcome;
69
+ if (outcome === void 0) throw new Error(`The factory of the mock of ${nameOf(this.#original)} returned a promise, which hadn't settled when the module was imported. A module that mocks modules waits for their factories before its imports, so import it from there, after the mock, or from a module that it imports. Mocks settle in the order of their calls, so mock a module that a factory imports before the mock of that factory.`);
70
+ if ("error" in outcome) throw outcome.error;
71
+ return outcome.exports;
72
+ }
73
+ async #await(exports) {
74
+ try {
75
+ this.#settle(await exports);
76
+ } catch (error) {
77
+ this.#fail(error);
78
+ }
79
+ }
80
+ #settle(exports) {
81
+ if (typeof exports !== "object" || exports === null) {
82
+ this.#outcome = { error: /* @__PURE__ */ new TypeError(`The factory of the mock of ${nameOf(this.#original)} returned ${String(exports)}, rather than an object of the module's exports. A default export is its "default" key.`) };
83
+ return;
84
+ }
85
+ this.#outcome = { exports };
86
+ }
87
+ #fail(error) {
88
+ this.#outcome = { error: new Error(`The factory of the mock of ${nameOf(this.#original)} failed. The factory of vi.mock() runs above the module's code, where the call is hoisted, so it can read only the variables that vi.hoisted() declares.`, { cause: error }) };
89
+ }
90
+ };
91
+ /**
92
+ * The module mocks of the process, which `hypotes/register` installs, with
93
+ * hooks that resolve and load mocked modules
94
+ */
95
+ var ModuleMocks = class ModuleMocks {
96
+ /** The current mock of each mocked module, by the original's URL */
97
+ #mocks = /* @__PURE__ */ new Map();
98
+ /** Every mock, by its ID, which its module's URL holds */
99
+ #byId = [];
100
+ /** Installs the registry of the process, unless one is installed */
101
+ static install() {
102
+ const global = globalThis;
103
+ if (global[MOCKS] !== void 0) return;
104
+ const mocks = new ModuleMocks();
105
+ global[MOCKS] = mocks;
106
+ return mocks;
107
+ }
108
+ /** The registry of the process, which `method` needs */
109
+ static installed(method) {
110
+ const mocks = globalThis[MOCKS];
111
+ if (mocks === void 0) throw new Error(`${method} needs the module mocks that node preloads with --import hypotes/register`);
112
+ return mocks;
113
+ }
114
+ /** Mocks the module at the URL, from the imports after this */
115
+ mock(url, factory) {
116
+ const mock = new ModuleMock(this.#byId.length, url, factory);
117
+ this.#byId.push(mock);
118
+ this.#mocks.set(url, mock);
119
+ }
120
+ /** Ends the mock of the module at the URL, for the imports after this */
121
+ unmock(url) {
122
+ this.#mocks.delete(url);
123
+ }
124
+ /**
125
+ * Runs the factories of the mocks that haven't run, and resolves once
126
+ * the exports of every factory have settled. A factory that this waits
127
+ * for can import through `wrapDynamicImport`, which doesn't wait for it,
128
+ * and runs the factories after it.
129
+ */
130
+ async settle() {
131
+ for (const mock of this.#mocks.values()) await mock.run();
132
+ }
133
+ /** Imports through `load`, after the factories of the mocks settle */
134
+ async wrapDynamicImport(load) {
135
+ await this.settle();
136
+ return load();
137
+ }
138
+ /** The exports of a mock, for its module, which reads them as it runs */
139
+ exportsOf(id) {
140
+ return this.#byId[id].exports();
141
+ }
142
+ /**
143
+ * Resolves the path of a mock from the module whose `import.meta` this
144
+ * gets, for the transform, which passes the URL to `vi`
145
+ */
146
+ resolvePath(meta, path) {
147
+ try {
148
+ return meta.resolve(path);
149
+ } catch (error) {
150
+ if (!namesNoPackage(error)) throw error;
151
+ return PACKAGE + path;
152
+ }
153
+ }
154
+ /** Resolves a mocked module to its mock, and an actual one to its URL */
155
+ resolve(specifier, context, nextResolve) {
156
+ if (specifier.startsWith(ACTUAL)) return {
157
+ url: actualURL(specifier),
158
+ shortCircuit: true
159
+ };
160
+ let resolved;
161
+ try {
162
+ resolved = nextResolve(specifier, context);
163
+ } catch (error) {
164
+ const mock = namesNoPackage(error) ? this.#mocks.get(PACKAGE + specifier) : void 0;
165
+ if (mock === void 0) throw error;
166
+ return {
167
+ url: mock.url,
168
+ format: "module",
169
+ shortCircuit: true
170
+ };
171
+ }
172
+ const mock = this.#mocks.get(resolved.url);
173
+ return mock === void 0 ? resolved : {
174
+ url: mock.url,
175
+ format: "module",
176
+ shortCircuit: true
177
+ };
178
+ }
179
+ /** Loads a mock's module, which exports its factory's exports */
180
+ load(url, context, nextLoad) {
181
+ if (!url.startsWith(MOCK)) return nextLoad(url, context);
182
+ const id = Number(url.slice(13, url.indexOf(":", 13)));
183
+ return {
184
+ format: "module",
185
+ source: mockSource(id, this.#byId[id].exports()),
186
+ shortCircuit: true
187
+ };
188
+ }
189
+ };
190
+ /**
191
+ * Whether the error of a resolution says that its specifier names no
192
+ * package that's installed, or import that its package defines. That of a
193
+ * file that isn't there has the file's URL.
194
+ */
195
+ function namesNoPackage(error) {
196
+ const { code, url } = error;
197
+ return code === "ERR_MODULE_NOT_FOUND" && url === void 0 || code === "ERR_PACKAGE_IMPORT_NOT_DEFINED";
198
+ }
199
+ /**
200
+ * The URL of the original that the specifier names, after `hypotes-actual:`,
201
+ * which a package that isn't installed doesn't have
202
+ */
203
+ function actualURL(specifier) {
204
+ const url = specifier.slice(15);
205
+ if (url.startsWith(PACKAGE)) throw new Error(`Cannot import the original of '${nameOf(url)}', which isn't an installed package, or an import that its package defines`);
206
+ return url;
207
+ }
208
+ /**
209
+ * The name of a mocked module in messages: its URL, or the specifier of a
210
+ * package that isn't installed
211
+ */
212
+ function nameOf(url) {
213
+ return url.startsWith(PACKAGE) ? url.slice(16) : url;
214
+ }
215
+ /**
216
+ * The source of a mock's module, which reads its exports from the registry.
217
+ * Its names are strings, which any key can be.
218
+ */
219
+ function mockSource(id, exports) {
220
+ const names = Object.keys(exports);
221
+ const bindings = names.map((name, index) => `e${index} = exports[${JSON.stringify(name)}]`);
222
+ const specifiers = names.map((name, index) => `e${index} as ${JSON.stringify(name)}`);
223
+ return [
224
+ `const exports = globalThis[Symbol.for(${JSON.stringify(MOCKS_KEY)})].exportsOf(${id});`,
225
+ ...bindings.length > 0 ? [`const ${bindings.join(", ")};`] : [],
226
+ `export { ${specifiers.join(", ")} };`
227
+ ].join("\n");
228
+ }
229
+ /**
230
+ * The URL that the transform resolved a path to, or of the original, if it's
231
+ * mocked: where it resolves to the mock's
232
+ */
233
+ function urlOf(method, path) {
234
+ if (typeof path !== "string" || !URL.canParse(path) || DRIVE.test(path)) throw new TypeError(`${method} got ${typeof path === "string" ? JSON.stringify(path) : typeof path}, rather than a URL that hypotes/register resolved its path to. It transforms the ES modules outside node_modules that call it, which it resolves the path from.`);
235
+ return path.startsWith(MOCK) ? path.slice(path.indexOf(":", 13) + 1) : path;
236
+ }
237
+ /** Mocks the module at the path, with the factory's exports */
238
+ function register(method, path, factory) {
239
+ const mocks = ModuleMocks.installed(method);
240
+ const url = urlOf(method, path);
241
+ if (typeof factory !== "function") throw new TypeError(`${method} takes a factory of the module's exports: hypotes doesn't mock a module's exports by itself, or from a __mocks__ directory`);
242
+ mocks.mock(url, factory);
243
+ return url;
244
+ }
245
+ /**
246
+ * Runs the factory, and returns what it returns. With `vi.mock()`, it's
247
+ * hoisted above the module's imports, in the order of the calls, so that
248
+ * the factory of a mock can read what it declares.
249
+ */
250
+ function hoisted(factory) {
251
+ return factory();
252
+ }
253
+ function mock(path, factory) {
254
+ register("vi.mock()", path, factory);
255
+ }
256
+ function doMock(path, factory) {
257
+ const url = register("vi.doMock()", path, factory);
258
+ return { [Symbol.dispose]: () => {
259
+ ModuleMocks.installed("vi.doMock()").unmock(url);
260
+ } };
261
+ }
262
+ /**
263
+ * Ends the mock of the module at the path, for the imports after it. It's
264
+ * hoisted above the module's imports, which import the original.
265
+ */
266
+ function unmock(path) {
267
+ ModuleMocks.installed("vi.unmock()").unmock(urlOf("vi.unmock()", path));
268
+ }
269
+ /**
270
+ * Ends the mock of the module at the path, as `vi.unmock()` does, but from
271
+ * where it's called: for the dynamic imports after it
272
+ */
273
+ function doUnmock(path) {
274
+ ModuleMocks.installed("vi.doUnmock()").unmock(urlOf("vi.doUnmock()", path));
275
+ }
276
+ /** Imports the module at the path, rather than its mock, if it's mocked */
277
+ function importActual(path) {
278
+ ModuleMocks.installed("vi.importActual()");
279
+ return importOriginal(urlOf("vi.importActual()", path));
280
+ }
281
+ export { hoisted as a, unmock as c, doUnmock as i, ModuleMocks as n, importActual as o, doMock as r, mock as s, MOCKS_KEY as t };
@@ -0,0 +1,83 @@
1
+ import type { LoadFnOutput, LoadHookContext, ResolveFnOutput, ResolveHookContext } from 'node:module';
2
+ type Awaitable<T> = PromiseLike<T> | T;
3
+ /**
4
+ * Makes the exports of a mocked module, from those of the original, if it
5
+ * imports them
6
+ */
7
+ export type MockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Awaitable<Partial<M>>;
8
+ /** A mocked module's exports, by name */
9
+ type Exports = Readonly<Record<string, unknown>>;
10
+ type NextResolve = (specifier: string, context?: Partial<ResolveHookContext>) => ResolveFnOutput;
11
+ type NextLoad = (url: string, context?: Partial<LoadHookContext>) => LoadFnOutput;
12
+ /** The registry's key on globalThis, for the code of transformed modules */
13
+ export declare const MOCKS_KEY = "hypotes.mocks";
14
+ /**
15
+ * The module mocks of the process, which `hypotes/register` installs, with
16
+ * hooks that resolve and load mocked modules
17
+ */
18
+ export declare class ModuleMocks {
19
+ #private;
20
+ /** Installs the registry of the process, unless one is installed */
21
+ static install(): ModuleMocks | undefined;
22
+ /** The registry of the process, which `method` needs */
23
+ static installed(method: string): ModuleMocks;
24
+ /** Mocks the module at the URL, from the imports after this */
25
+ mock(url: string, factory: MockFactoryWithHelper): void;
26
+ /** Ends the mock of the module at the URL, for the imports after this */
27
+ unmock(url: string): void;
28
+ /**
29
+ * Runs the factories of the mocks that haven't run, and resolves once
30
+ * the exports of every factory have settled. A factory that this waits
31
+ * for can import through `wrapDynamicImport`, which doesn't wait for it,
32
+ * and runs the factories after it.
33
+ */
34
+ settle(): Promise<void>;
35
+ /** Imports through `load`, after the factories of the mocks settle */
36
+ wrapDynamicImport<T>(load: () => Promise<T>): Promise<T>;
37
+ /** The exports of a mock, for its module, which reads them as it runs */
38
+ exportsOf(id: number): Exports;
39
+ /**
40
+ * Resolves the path of a mock from the module whose `import.meta` this
41
+ * gets, for the transform, which passes the URL to `vi`
42
+ */
43
+ resolvePath(meta: ImportMeta, path: string): string;
44
+ /** Resolves a mocked module to its mock, and an actual one to its URL */
45
+ resolve(specifier: string, context: ResolveHookContext, nextResolve: NextResolve): ResolveFnOutput;
46
+ /** Loads a mock's module, which exports its factory's exports */
47
+ load(url: string, context: LoadHookContext, nextLoad: NextLoad): LoadFnOutput;
48
+ }
49
+ /**
50
+ * Runs the factory, and returns what it returns. With `vi.mock()`, it's
51
+ * hoisted above the module's imports, in the order of the calls, so that
52
+ * the factory of a mock can read what it declares.
53
+ */
54
+ export declare function hoisted<T>(factory: () => T): T;
55
+ /**
56
+ * Mocks the module at the path, which resolves from the module that calls
57
+ * this, for every import of it after this, with the exports that the factory
58
+ * returns. It's hoisted above the module's imports, so they import the mock,
59
+ * and its factory can read only what `vi.hoisted()` declares. The factory
60
+ * runs once, before those imports or when the mock is first imported.
61
+ */
62
+ export declare function mock(path: string, factory: MockFactoryWithHelper): void;
63
+ export declare function mock<T>(module: Promise<T>, factory: MockFactoryWithHelper<T>): void;
64
+ /**
65
+ * Mocks the module at the path, as `vi.mock()` does, but from where it's
66
+ * called: for the dynamic imports after it. Disposing what it returns ends
67
+ * the mock.
68
+ */
69
+ export declare function doMock(path: string, factory: MockFactoryWithHelper): Disposable;
70
+ export declare function doMock<T>(module: Promise<T>, factory: MockFactoryWithHelper<T>): Disposable;
71
+ /**
72
+ * Ends the mock of the module at the path, for the imports after it. It's
73
+ * hoisted above the module's imports, which import the original.
74
+ */
75
+ export declare function unmock(path: Promise<unknown> | string): void;
76
+ /**
77
+ * Ends the mock of the module at the path, as `vi.unmock()` does, but from
78
+ * where it's called: for the dynamic imports after it
79
+ */
80
+ export declare function doUnmock(path: Promise<unknown> | string): void;
81
+ /** Imports the module at the path, rather than its mock, if it's mocked */
82
+ export declare function importActual<T = Record<string, unknown>>(path: string): Promise<T>;
83
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { Rule } from './types.ts';
2
+ export interface Plugin {
3
+ readonly meta: {
4
+ readonly name: string;
5
+ };
6
+ readonly rules: Readonly<Record<string, Rule>>;
7
+ }
8
+ declare const plugin: Plugin;
9
+ export default plugin;