msw-fetch-mock 0.3.0 → 0.3.2

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.
Files changed (46) hide show
  1. package/README.md +72 -6
  2. package/dist/browser.cjs +43 -0
  3. package/dist/browser.d.cts +15 -0
  4. package/dist/browser.d.ts +15 -9
  5. package/dist/browser.js +42 -7
  6. package/dist/chunk-3RAWYKAG.js +551 -0
  7. package/dist/chunk-IOGQ34QL.js +27 -0
  8. package/dist/chunk-N6B7UP6B.cjs +551 -0
  9. package/dist/chunk-PJU5FUNI.cjs +58 -0
  10. package/dist/chunk-PUVZ7LB4.js +58 -0
  11. package/dist/chunk-QKIKWNFZ.cjs +27 -0
  12. package/dist/fetch-mock-DhiqmHdF.d.cts +199 -0
  13. package/dist/fetch-mock-DhiqmHdF.d.ts +199 -0
  14. package/dist/index.cjs +19 -0
  15. package/dist/index.d.cts +2 -0
  16. package/dist/index.d.ts +2 -3
  17. package/dist/index.js +19 -1
  18. package/dist/legacy.cjs +71 -0
  19. package/dist/legacy.d.cts +38 -0
  20. package/dist/legacy.d.ts +38 -0
  21. package/dist/legacy.js +71 -0
  22. package/dist/node.cjs +19 -0
  23. package/dist/node.d.cts +18 -0
  24. package/dist/node.d.ts +17 -10
  25. package/dist/node.js +19 -12
  26. package/docs/api.md +121 -13
  27. package/docs/msw-v1-legacy.md +94 -0
  28. package/package.json +34 -10
  29. package/dist/browser-adapter.d.ts +0 -10
  30. package/dist/browser-adapter.d.ts.map +0 -1
  31. package/dist/browser-adapter.js +0 -20
  32. package/dist/browser.d.ts.map +0 -1
  33. package/dist/fetch-mock.d.ts +0 -31
  34. package/dist/fetch-mock.d.ts.map +0 -1
  35. package/dist/fetch-mock.js +0 -347
  36. package/dist/index.d.ts.map +0 -1
  37. package/dist/mock-call-history.d.ts +0 -65
  38. package/dist/mock-call-history.d.ts.map +0 -1
  39. package/dist/mock-call-history.js +0 -140
  40. package/dist/node-adapter.d.ts +0 -11
  41. package/dist/node-adapter.d.ts.map +0 -1
  42. package/dist/node-adapter.js +0 -34
  43. package/dist/node.d.ts.map +0 -1
  44. package/dist/types.d.ts +0 -74
  45. package/dist/types.d.ts.map +0 -1
  46. package/dist/types.js +0 -1
@@ -1,347 +0,0 @@
1
- import { http, HttpResponse } from 'msw';
2
- import { MockCallHistory } from './mock-call-history';
3
- function isPending(p) {
4
- if (p.persist)
5
- return p.timesInvoked === 0;
6
- return p.timesInvoked < p.times;
7
- }
8
- function escapeRegExp(str) {
9
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
10
- }
11
- function matchesValue(value, matcher) {
12
- if (typeof matcher === 'string')
13
- return value === matcher;
14
- if (matcher instanceof RegExp)
15
- return matcher.test(value);
16
- return matcher(value);
17
- }
18
- function getHttpMethod(method) {
19
- const methods = {
20
- GET: http.get,
21
- POST: http.post,
22
- PUT: http.put,
23
- DELETE: http.delete,
24
- PATCH: http.patch,
25
- };
26
- return methods[method];
27
- }
28
- function matchPath(request, origin, pathMatcher) {
29
- if (typeof pathMatcher === 'string')
30
- return true; // string paths are matched by MSW URL pattern
31
- const url = new URL(request.url);
32
- const originPrefix = new URL(origin).pathname.replace(/\/$/, '');
33
- const fullPath = url.pathname + url.search;
34
- const relativePath = fullPath.startsWith(originPrefix)
35
- ? fullPath.slice(originPrefix.length)
36
- : fullPath;
37
- return matchesValue(relativePath, pathMatcher);
38
- }
39
- function matchQuery(request, query) {
40
- if (!query)
41
- return true;
42
- const url = new URL(request.url);
43
- for (const [key, value] of Object.entries(query)) {
44
- if (url.searchParams.get(key) !== value)
45
- return false;
46
- }
47
- return true;
48
- }
49
- function matchHeaders(request, headers) {
50
- if (!headers)
51
- return true;
52
- for (const [key, matcher] of Object.entries(headers)) {
53
- const value = request.headers.get(key);
54
- if (value === null || !matchesValue(value, matcher))
55
- return false;
56
- }
57
- return true;
58
- }
59
- function matchBody(bodyText, bodyMatcher) {
60
- if (!bodyMatcher)
61
- return true;
62
- return matchesValue(bodyText ?? '', bodyMatcher);
63
- }
64
- function recordCall(callHistory, request, bodyText) {
65
- const url = new URL(request.url);
66
- const requestHeaders = {};
67
- request.headers.forEach((value, key) => {
68
- requestHeaders[key] = value;
69
- });
70
- const searchParams = {};
71
- url.searchParams.forEach((value, key) => {
72
- searchParams[key] = value;
73
- });
74
- callHistory.record({
75
- body: bodyText,
76
- method: request.method,
77
- headers: requestHeaders,
78
- fullUrl: url.origin + url.pathname + url.search,
79
- origin: url.origin,
80
- path: url.pathname,
81
- searchParams,
82
- protocol: url.protocol,
83
- host: url.host,
84
- port: url.port,
85
- hash: url.hash,
86
- });
87
- }
88
- function buildResponse(status, responseBody, replyOptions) {
89
- const headers = replyOptions?.headers ? new Headers(replyOptions.headers) : undefined;
90
- if (responseBody === null || responseBody === undefined) {
91
- return new HttpResponse(null, { status, headers });
92
- }
93
- return HttpResponse.json(responseBody, { status, headers });
94
- }
95
- function isSetupServerLike(input) {
96
- return (typeof input === 'object' &&
97
- input !== null &&
98
- 'listen' in input &&
99
- typeof input.listen === 'function' &&
100
- 'close' in input &&
101
- typeof input.close === 'function');
102
- }
103
- function isSetupWorkerLike(input) {
104
- return (typeof input === 'object' &&
105
- input !== null &&
106
- 'start' in input &&
107
- typeof input.start === 'function' &&
108
- 'stop' in input &&
109
- typeof input.stop === 'function');
110
- }
111
- function isMswAdapter(input) {
112
- return (typeof input === 'object' &&
113
- input !== null &&
114
- 'activate' in input &&
115
- typeof input.activate === 'function' &&
116
- 'deactivate' in input &&
117
- typeof input.deactivate === 'function');
118
- }
119
- function createServerAdapter(server) {
120
- return {
121
- use: (...handlers) => server.use(...handlers),
122
- resetHandlers: (...handlers) => server.resetHandlers(...handlers),
123
- activate(options) {
124
- server.listen({ onUnhandledRequest: options.onUnhandledRequest });
125
- },
126
- deactivate() {
127
- server.close();
128
- },
129
- };
130
- }
131
- function createWorkerAdapter(worker) {
132
- return {
133
- use: (...handlers) => worker.use(...handlers),
134
- resetHandlers: (...handlers) => worker.resetHandlers(...handlers),
135
- async activate(options) {
136
- await worker.start({ onUnhandledRequest: options.onUnhandledRequest });
137
- },
138
- deactivate() {
139
- worker.stop();
140
- },
141
- };
142
- }
143
- function resolveAdapter(input) {
144
- if (!input) {
145
- if (!FetchMock._defaultAdapterFactory) {
146
- throw new Error('FetchMock requires a server, worker, or adapter argument. ' +
147
- 'Use createFetchMock() from msw-fetch-mock/node or msw-fetch-mock/browser, ' +
148
- 'or pass a setupServer/setupWorker instance directly.');
149
- }
150
- return FetchMock._defaultAdapterFactory();
151
- }
152
- if (isMswAdapter(input))
153
- return input;
154
- if (isSetupServerLike(input))
155
- return createServerAdapter(input);
156
- if (isSetupWorkerLike(input))
157
- return createWorkerAdapter(input);
158
- throw new Error('Invalid argument: expected a setupServer, setupWorker, or MswAdapter instance.');
159
- }
160
- export class FetchMock {
161
- /** @internal */
162
- static _defaultAdapterFactory;
163
- _calls = new MockCallHistory();
164
- adapter;
165
- interceptors = [];
166
- netConnectAllowed = false;
167
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
168
- mswHandlers = new Map();
169
- get calls() {
170
- return this._calls;
171
- }
172
- constructor(input) {
173
- this.adapter = resolveAdapter(input);
174
- }
175
- async activate(options) {
176
- const mode = options?.onUnhandledRequest ?? 'error';
177
- await this.adapter.activate({
178
- onUnhandledRequest: (request, print) => {
179
- if (this.isNetConnectAllowed(request))
180
- return;
181
- if (typeof mode === 'function') {
182
- mode(request, print);
183
- }
184
- else if (mode === 'error') {
185
- print.error();
186
- }
187
- else if (mode === 'warn') {
188
- print.warning();
189
- }
190
- // 'bypass' → do nothing
191
- },
192
- });
193
- }
194
- disableNetConnect() {
195
- this.netConnectAllowed = false;
196
- }
197
- enableNetConnect(matcher) {
198
- this.netConnectAllowed = matcher ?? true;
199
- }
200
- isNetConnectAllowed(request) {
201
- if (this.netConnectAllowed === true)
202
- return true;
203
- if (this.netConnectAllowed === false)
204
- return false;
205
- const host = new URL(request.url).host;
206
- if (typeof this.netConnectAllowed === 'string')
207
- return host === this.netConnectAllowed;
208
- if (this.netConnectAllowed instanceof RegExp)
209
- return this.netConnectAllowed.test(host);
210
- return this.netConnectAllowed(host);
211
- }
212
- /**
213
- * Remove consumed MSW handlers so future requests to those URLs
214
- * go through MSW's onUnhandledRequest instead of silently passing through.
215
- */
216
- syncMswHandlers() {
217
- const activeHandlers = [...this.mswHandlers.entries()]
218
- .filter(([p]) => !p.consumed || p.persist)
219
- .map(([, handler]) => handler);
220
- this.adapter.resetHandlers(...activeHandlers);
221
- }
222
- getCallHistory() {
223
- return this._calls;
224
- }
225
- clearCallHistory() {
226
- this._calls.clear();
227
- }
228
- deactivate() {
229
- this.interceptors = [];
230
- this.mswHandlers.clear();
231
- this._calls.clear();
232
- this.adapter.deactivate();
233
- }
234
- reset() {
235
- this.interceptors = [];
236
- this.mswHandlers.clear();
237
- this._calls.clear();
238
- this.adapter.resetHandlers();
239
- }
240
- assertNoPendingInterceptors() {
241
- const unconsumed = this.interceptors.filter(isPending);
242
- if (unconsumed.length > 0) {
243
- const descriptions = unconsumed.map((p) => ` ${p.method} ${p.origin}${p.path}`);
244
- throw new Error(`Pending interceptor(s) not consumed:\n${descriptions.join('\n')}`);
245
- }
246
- }
247
- pendingInterceptors() {
248
- return this.interceptors.filter(isPending).map((p) => ({ ...p }));
249
- }
250
- get(origin) {
251
- return {
252
- intercept: (options) => {
253
- const method = options.method ?? 'GET';
254
- const pathStr = typeof options.path === 'string'
255
- ? options.path
256
- : typeof options.path === 'function'
257
- ? '<function>'
258
- : options.path.toString();
259
- const pending = {
260
- origin,
261
- path: pathStr,
262
- method,
263
- consumed: false,
264
- times: 1,
265
- timesInvoked: 0,
266
- persist: false,
267
- };
268
- this.interceptors.push(pending);
269
- const urlPattern = typeof options.path === 'string'
270
- ? `${origin}${options.path}`
271
- : new RegExp(`^${escapeRegExp(origin)}`);
272
- const matchAndConsume = async (request) => {
273
- if (!pending.persist && pending.timesInvoked >= pending.times)
274
- return;
275
- if (!matchPath(request, origin, options.path))
276
- return;
277
- if (!matchQuery(request, options.query))
278
- return;
279
- if (!matchHeaders(request, options.headers))
280
- return;
281
- const bodyText = (await request.text()) || null;
282
- if (!matchBody(bodyText, options.body))
283
- return;
284
- pending.timesInvoked++;
285
- if (!pending.persist && pending.timesInvoked >= pending.times) {
286
- pending.consumed = true;
287
- this.syncMswHandlers();
288
- }
289
- recordCall(this._calls, request, bodyText);
290
- return bodyText;
291
- };
292
- const registerHandler = (handlerFn) => {
293
- const handler = getHttpMethod(method)(urlPattern, async ({ request }) => handlerFn(request));
294
- this.mswHandlers.set(pending, handler);
295
- this.adapter.use(handler);
296
- };
297
- const buildChain = (delayRef) => ({
298
- times(n) {
299
- pending.times = n;
300
- pending.consumed = false;
301
- },
302
- persist() {
303
- pending.persist = true;
304
- pending.consumed = false;
305
- },
306
- delay(ms) {
307
- delayRef.ms = ms;
308
- },
309
- });
310
- return {
311
- reply: (status, bodyOrCallback, replyOptions) => {
312
- const delayRef = { ms: 0 };
313
- registerHandler(async (request) => {
314
- const bodyText = await matchAndConsume(request);
315
- if (bodyText === undefined)
316
- return;
317
- if (delayRef.ms > 0) {
318
- await new Promise((resolve) => setTimeout(resolve, delayRef.ms));
319
- }
320
- let responseBody;
321
- if (typeof bodyOrCallback === 'function') {
322
- responseBody = await bodyOrCallback({
323
- body: bodyText || null,
324
- });
325
- }
326
- else {
327
- responseBody = bodyOrCallback;
328
- }
329
- return buildResponse(status, responseBody, replyOptions);
330
- });
331
- return buildChain(delayRef);
332
- },
333
- replyWithError: () => {
334
- const delayRef = { ms: 0 };
335
- registerHandler(async (request) => {
336
- const bodyText = await matchAndConsume(request);
337
- if (bodyText === undefined)
338
- return;
339
- return HttpResponse.error();
340
- });
341
- return buildChain(delayRef);
342
- },
343
- };
344
- },
345
- };
346
- }
347
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,cAAc,EACd,eAAe,EACf,SAAS,EACT,eAAe,EACf,kBAAkB,GACnB,MAAM,QAAQ,CAAC;AAChB,YAAY,EACV,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,QAAQ,EACR,eAAe,EACf,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,QAAQ,CAAC"}
@@ -1,65 +0,0 @@
1
- export interface MockCallHistoryLogData {
2
- body: string | null;
3
- method: string;
4
- headers: Record<string, string>;
5
- fullUrl: string;
6
- origin: string;
7
- path: string;
8
- searchParams: Record<string, string>;
9
- protocol: string;
10
- host: string;
11
- port: string;
12
- hash: string;
13
- }
14
- export declare class MockCallHistoryLog {
15
- readonly body: string | null;
16
- readonly method: string;
17
- readonly headers: Record<string, string>;
18
- readonly fullUrl: string;
19
- readonly origin: string;
20
- readonly path: string;
21
- readonly searchParams: Record<string, string>;
22
- readonly protocol: string;
23
- readonly host: string;
24
- readonly port: string;
25
- readonly hash: string;
26
- constructor(data: MockCallHistoryLogData);
27
- json(): unknown;
28
- toMap(): Map<string, string | null | Record<string, string>>;
29
- toString(): string;
30
- }
31
- export interface CallHistoryFilterCriteria {
32
- method?: string;
33
- path?: string;
34
- origin?: string;
35
- protocol?: string;
36
- host?: string;
37
- port?: string;
38
- hash?: string;
39
- fullUrl?: string;
40
- }
41
- export declare class MockCallHistory {
42
- private logs;
43
- get length(): number;
44
- record(data: MockCallHistoryLogData): void;
45
- called(criteria?: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp): boolean;
46
- calls(): MockCallHistoryLog[];
47
- firstCall(criteria?: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp): MockCallHistoryLog | undefined;
48
- lastCall(criteria?: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp): MockCallHistoryLog | undefined;
49
- nthCall(n: number, criteria?: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp): MockCallHistoryLog | undefined;
50
- clear(): void;
51
- [Symbol.iterator](): Iterator<MockCallHistoryLog>;
52
- filterCalls(criteria: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp, options?: {
53
- operator?: 'AND' | 'OR';
54
- }): MockCallHistoryLog[];
55
- private filterBy;
56
- filterCallsByMethod(filter: string | RegExp): MockCallHistoryLog[];
57
- filterCallsByPath(filter: string | RegExp): MockCallHistoryLog[];
58
- filterCallsByOrigin(filter: string | RegExp): MockCallHistoryLog[];
59
- filterCallsByProtocol(filter: string | RegExp): MockCallHistoryLog[];
60
- filterCallsByHost(filter: string | RegExp): MockCallHistoryLog[];
61
- filterCallsByPort(filter: string | RegExp): MockCallHistoryLog[];
62
- filterCallsByHash(filter: string | RegExp): MockCallHistoryLog[];
63
- filterCallsByFullUrl(filter: string | RegExp): MockCallHistoryLog[];
64
- }
65
- //# sourceMappingURL=mock-call-history.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mock-call-history.d.ts","sourceRoot":"","sources":["../src/mock-call-history.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qBAAa,kBAAkB;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,QAAQ,CAAC,MAAM,EA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AAM,GAAG,kBAAkB,EAAE;IAIhE,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,kBAAkB,EAAE;IAIhE,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,kBAAkB,EAAE;CAGpE"}
@@ -1,140 +0,0 @@
1
- export class MockCallHistoryLog {
2
- body;
3
- method;
4
- headers;
5
- fullUrl;
6
- origin;
7
- path;
8
- searchParams;
9
- protocol;
10
- host;
11
- port;
12
- hash;
13
- constructor(data) {
14
- this.body = data.body;
15
- this.method = data.method;
16
- this.headers = data.headers;
17
- this.fullUrl = data.fullUrl;
18
- this.origin = data.origin;
19
- this.path = data.path;
20
- this.searchParams = data.searchParams;
21
- this.protocol = data.protocol;
22
- this.host = data.host;
23
- this.port = data.port;
24
- this.hash = data.hash;
25
- }
26
- json() {
27
- if (this.body === null)
28
- return null;
29
- return JSON.parse(this.body);
30
- }
31
- toMap() {
32
- return new Map([
33
- ['body', this.body],
34
- ['method', this.method],
35
- ['headers', this.headers],
36
- ['fullUrl', this.fullUrl],
37
- ['origin', this.origin],
38
- ['path', this.path],
39
- ['searchParams', this.searchParams],
40
- ['protocol', this.protocol],
41
- ['host', this.host],
42
- ['port', this.port],
43
- ['hash', this.hash],
44
- ]);
45
- }
46
- toString() {
47
- return [
48
- `method->${this.method}`,
49
- `protocol->${this.protocol}`,
50
- `host->${this.host}`,
51
- `port->${this.port}`,
52
- `origin->${this.origin}`,
53
- `path->${this.path}`,
54
- `hash->${this.hash}`,
55
- `fullUrl->${this.fullUrl}`,
56
- ].join('|');
57
- }
58
- }
59
- export class MockCallHistory {
60
- logs = [];
61
- get length() {
62
- return this.logs.length;
63
- }
64
- record(data) {
65
- this.logs.push(data instanceof MockCallHistoryLog ? data : new MockCallHistoryLog(data));
66
- }
67
- called(criteria) {
68
- if (criteria === undefined)
69
- return this.logs.length > 0;
70
- return this.filterCalls(criteria).length > 0;
71
- }
72
- calls() {
73
- return [...this.logs];
74
- }
75
- firstCall(criteria) {
76
- if (criteria === undefined)
77
- return this.logs[0];
78
- return this.filterCalls(criteria)[0];
79
- }
80
- lastCall(criteria) {
81
- if (criteria === undefined)
82
- return this.logs[this.logs.length - 1];
83
- const filtered = this.filterCalls(criteria);
84
- return filtered[filtered.length - 1];
85
- }
86
- nthCall(n, criteria) {
87
- if (criteria === undefined)
88
- return this.logs[n - 1];
89
- return this.filterCalls(criteria)[n - 1];
90
- }
91
- clear() {
92
- this.logs = [];
93
- }
94
- [Symbol.iterator]() {
95
- return this.logs[Symbol.iterator]();
96
- }
97
- filterCalls(criteria, options) {
98
- if (typeof criteria === 'function') {
99
- return this.logs.filter(criteria);
100
- }
101
- if (criteria instanceof RegExp) {
102
- return this.logs.filter((log) => criteria.test(log.toString()));
103
- }
104
- const operator = options?.operator ?? 'OR';
105
- const keys = Object.keys(criteria);
106
- const predicates = keys
107
- .filter((key) => criteria[key] !== undefined)
108
- .map((key) => (log) => log[key] === criteria[key]);
109
- if (predicates.length === 0)
110
- return [...this.logs];
111
- return this.logs.filter((log) => operator === 'AND' ? predicates.every((p) => p(log)) : predicates.some((p) => p(log)));
112
- }
113
- filterBy(field, filter) {
114
- return this.logs.filter((log) => typeof filter === 'string' ? log[field] === filter : filter.test(String(log[field])));
115
- }
116
- filterCallsByMethod(filter) {
117
- return this.filterBy('method', filter);
118
- }
119
- filterCallsByPath(filter) {
120
- return this.filterBy('path', filter);
121
- }
122
- filterCallsByOrigin(filter) {
123
- return this.filterBy('origin', filter);
124
- }
125
- filterCallsByProtocol(filter) {
126
- return this.filterBy('protocol', filter);
127
- }
128
- filterCallsByHost(filter) {
129
- return this.filterBy('host', filter);
130
- }
131
- filterCallsByPort(filter) {
132
- return this.filterBy('port', filter);
133
- }
134
- filterCallsByHash(filter) {
135
- return this.filterBy('hash', filter);
136
- }
137
- filterCallsByFullUrl(filter) {
138
- return this.filterBy('fullUrl', filter);
139
- }
140
- }
@@ -1,11 +0,0 @@
1
- import type { MswAdapter, ResolvedActivateOptions, SetupServerLike } from './types';
2
- export declare class NodeMswAdapter implements MswAdapter {
3
- private server;
4
- private readonly ownsServer;
5
- constructor(externalServer?: SetupServerLike);
6
- use(...handlers: Array<unknown>): void;
7
- resetHandlers(...handlers: Array<unknown>): void;
8
- activate(options: ResolvedActivateOptions): void;
9
- deactivate(): void;
10
- }
11
- //# sourceMappingURL=node-adapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"node-adapter.d.ts","sourceRoot":"","sources":["../src/node-adapter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEpF,qBAAa,cAAe,YAAW,UAAU;IAC/C,OAAO,CAAC,MAAM,CAAyB;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAU;gBAEzB,cAAc,CAAC,EAAE,eAAe;IAK5C,GAAG,CAAC,GAAG,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI;IAItC,aAAa,CAAC,GAAG,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI;IAIhD,QAAQ,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAmBhD,UAAU,IAAI,IAAI;CAMnB"}
@@ -1,34 +0,0 @@
1
- import { setupServer } from 'msw/node';
2
- export class NodeMswAdapter {
3
- server;
4
- ownsServer;
5
- constructor(externalServer) {
6
- this.server = externalServer ?? null;
7
- this.ownsServer = !externalServer;
8
- }
9
- use(...handlers) {
10
- this.server.use(...handlers);
11
- }
12
- resetHandlers(...handlers) {
13
- this.server.resetHandlers(...handlers);
14
- }
15
- activate(options) {
16
- if (!this.ownsServer)
17
- return;
18
- const isPatched = Object.getOwnPropertySymbols(globalThis.fetch).some((s) => s.description === 'isPatchedModule');
19
- if (isPatched) {
20
- throw new Error('Another MSW server is already active. ' +
21
- 'Pass your existing server to new FetchMock(server) instead.');
22
- }
23
- this.server = setupServer();
24
- this.server.listen({
25
- onUnhandledRequest: options.onUnhandledRequest,
26
- });
27
- }
28
- deactivate() {
29
- if (this.ownsServer) {
30
- this.server?.close();
31
- this.server = null;
32
- }
33
- }
34
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAKhD,wBAAgB,eAAe,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,SAAS,CAEnE;AAED,sFAAsF;AACtF,eAAO,MAAM,SAAS,WAAoB,CAAC;AAE3C,YAAY,EACV,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,QAAQ,EACR,eAAe,EACf,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,eAAe,GAChB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC1E,YAAY,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/types.d.ts DELETED
@@ -1,74 +0,0 @@
1
- export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
2
- export type PathMatcher = string | RegExp | ((path: string) => boolean);
3
- export type HeaderValueMatcher = string | RegExp | ((value: string) => boolean);
4
- export type BodyMatcher = string | RegExp | ((body: string) => boolean);
5
- export interface InterceptOptions {
6
- path: PathMatcher;
7
- method?: HttpMethod;
8
- headers?: Record<string, HeaderValueMatcher>;
9
- body?: BodyMatcher;
10
- query?: Record<string, string>;
11
- }
12
- export interface ReplyOptions {
13
- headers?: Record<string, string>;
14
- }
15
- export type ReplyCallback = (req: {
16
- body: string | null;
17
- }) => unknown | Promise<unknown>;
18
- export interface MockReplyChain {
19
- times(n: number): void;
20
- persist(): void;
21
- delay(ms: number): void;
22
- }
23
- export interface MockInterceptor {
24
- reply(status: number, body?: unknown, options?: ReplyOptions): MockReplyChain;
25
- reply(status: number, callback: ReplyCallback): MockReplyChain;
26
- replyWithError(error: Error): MockReplyChain;
27
- }
28
- export interface MockPool {
29
- intercept(options: InterceptOptions): MockInterceptor;
30
- }
31
- export interface PendingInterceptor {
32
- origin: string;
33
- path: string;
34
- method: string;
35
- consumed: boolean;
36
- times: number;
37
- timesInvoked: number;
38
- persist: boolean;
39
- }
40
- export type NetConnectMatcher = true | false | string | RegExp | ((host: string) => boolean);
41
- export type PrintAPI = {
42
- warning(): void;
43
- error(): void;
44
- };
45
- export type OnUnhandledRequestCallback = (request: Request, print: PrintAPI) => void;
46
- export type OnUnhandledRequest = 'bypass' | 'warn' | 'error' | OnUnhandledRequestCallback;
47
- export interface ActivateOptions {
48
- onUnhandledRequest?: OnUnhandledRequest;
49
- }
50
- export interface ResolvedActivateOptions {
51
- onUnhandledRequest: OnUnhandledRequestCallback;
52
- }
53
- /** Structural type to avoid cross-package nominal type mismatch on MSW's private fields */
54
- export interface SetupServerLike {
55
- use(...handlers: Array<unknown>): void;
56
- resetHandlers(...handlers: Array<unknown>): void;
57
- listen(options?: Record<string, unknown>): void;
58
- close(): void;
59
- }
60
- /** Structural type for MSW's setupWorker return type */
61
- export interface SetupWorkerLike {
62
- use(...handlers: Array<unknown>): void;
63
- resetHandlers(...handlers: Array<unknown>): void;
64
- start(options?: Record<string, unknown>): Promise<void>;
65
- stop(): void;
66
- }
67
- /** Environment-agnostic adapter interface for MSW server/worker */
68
- export interface MswAdapter {
69
- use(...handlers: Array<unknown>): void;
70
- resetHandlers(...handlers: Array<unknown>): void;
71
- activate(options: ResolvedActivateOptions): void | Promise<void>;
72
- deactivate(): void;
73
- }
74
- //# sourceMappingURL=types.d.ts.map