msw-fetch-mock 0.3.4 → 0.4.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/README.md CHANGED
@@ -10,12 +10,12 @@ Undici-style fetch mock API built on [MSW](https://mswjs.io/) (Mock Service Work
10
10
 
11
11
  If you're familiar with Cloudflare Workers' `fetchMock` (from `cloudflare:test`) or Node.js undici's `MockAgent`, you already know this API.
12
12
 
13
- Supports both **Node.js** (`msw/node`) and **Browser** (`msw/browser`) environments via subpath exports.
13
+ Supports **Node.js** (`msw/node`), **Browser** (`msw/browser`), and **Native** (no MSW dependency) environments via subpath exports.
14
14
 
15
15
  ## Requirements
16
16
 
17
17
  - **Node.js** >= 18
18
- - **MSW** ^1.0.0 (via `/legacy`) or ^2.12.7
18
+ - **MSW** ^1.0.0 (via `/legacy`) or ^2.12.7 — **optional** when using `/native`
19
19
 
20
20
  ## Install
21
21
 
@@ -25,6 +25,12 @@ npm install -D msw-fetch-mock msw
25
25
 
26
26
  `msw` is a peer dependency — you provide your own version.
27
27
 
28
+ For MSW-free usage (patches `globalThis.fetch` directly):
29
+
30
+ ```bash
31
+ npm install -D msw-fetch-mock
32
+ ```
33
+
28
34
  ## Quick Start
29
35
 
30
36
  ### Node.js (Vitest, Jest)
@@ -95,6 +101,25 @@ afterEach(() => {
95
101
 
96
102
  > **Note:** Only one MSW server can be active at a time. If a server is already listening, standalone `activate()` will throw an error. Use `createFetchMock(server)` to share an existing server.
97
103
 
104
+ ### Native (no MSW dependency)
105
+
106
+ For environments where you don't want to install MSW, the `/native` subpath patches `globalThis.fetch` directly:
107
+
108
+ ```typescript
109
+ import { fetchMock } from 'msw-fetch-mock/native';
110
+
111
+ beforeAll(async () => {
112
+ await fetchMock.activate({ onUnhandledRequest: 'error' });
113
+ });
114
+ afterAll(() => fetchMock.deactivate());
115
+ afterEach(() => {
116
+ fetchMock.assertNoPendingInterceptors();
117
+ fetchMock.reset();
118
+ });
119
+ ```
120
+
121
+ The API is identical — only the underlying transport changes (no Service Worker, no MSW server).
122
+
98
123
  ### Legacy (MSW v1)
99
124
 
100
125
  ```typescript
@@ -145,12 +170,13 @@ fetchMock.activate({
145
170
 
146
171
  ### Import Paths
147
172
 
148
- | Path | Environment | MSW version |
149
- | ------------------------ | ---------------------------- | ----------- |
150
- | `msw-fetch-mock` | Node.js (re-exports `/node`) | v2 |
151
- | `msw-fetch-mock/node` | Node.js | v2 |
152
- | `msw-fetch-mock/browser` | Browser | v2 |
153
- | `msw-fetch-mock/legacy` | Node.js (MSW v1) | v1 |
173
+ | Path | Environment | MSW version |
174
+ | ------------------------ | ---------------------------- | ------------ |
175
+ | `msw-fetch-mock` | Node.js (re-exports `/node`) | v2 |
176
+ | `msw-fetch-mock/node` | Node.js | v2 |
177
+ | `msw-fetch-mock/browser` | Browser | v2 |
178
+ | `msw-fetch-mock/native` | Any (no MSW) | not required |
179
+ | `msw-fetch-mock/legacy` | Node.js (MSW v1) | v1 |
154
180
 
155
181
  ### `fetchMock` (singleton)
156
182
 
@@ -163,11 +189,12 @@ Factory function that creates a `FetchMock` with the appropriate adapter.
163
189
 
164
190
  - Node: `createFetchMock(server?)` — optionally pass an existing MSW `SetupServer`
165
191
  - Browser: `createFetchMock(worker)` — pass an MSW `SetupWorker` (required)
192
+ - Native: `createFetchMock()` — no arguments, no MSW dependency
166
193
  - Legacy: `createFetchMock(rest, server?)` — pass MSW v1 `rest` object
167
194
 
168
195
  ### `new FetchMock(adapter?)`
169
196
 
170
- Creates a `FetchMock` instance with an explicit `MswAdapter`. Use `NodeMswAdapter` or `BrowserMswAdapter`.
197
+ Creates a `FetchMock` instance with an explicit `MswAdapter`. Use `NodeMswAdapter`, `BrowserMswAdapter`, or `NativeFetchAdapter`.
171
198
 
172
199
  ### Intercepting & Replying
173
200
 
@@ -205,6 +232,8 @@ E2E tests run on every CI push across these environments:
205
232
  | Jest CJS | CJS (require) | Jest |
206
233
  | Node.js Test | ESM (import) | Node test runner |
207
234
  | Node.js CJS | CJS (require) | Node test runner |
235
+ | Native ESM | ESM (import) | Node test runner |
236
+ | Native CJS | CJS (require) | Node test runner |
208
237
  | Legacy CJS | CJS (require) | Jest (MSW v1) |
209
238
  | Vitest Browser | ESM (import) | Vitest + Playwright |
210
239
 
@@ -238,7 +267,7 @@ pnpm test:e2e -- node-cjs
238
267
  pnpm test:e2e -- --all
239
268
  ```
240
269
 
241
- Available suites: `jest-esm`, `jest-cjs`, `node-test`, `node-cjs`, `legacy-cjs`, `vitest-browser`
270
+ Available suites: `jest-esm`, `jest-cjs`, `node-test`, `node-cjs`, `native-esm`, `native-cjs`, `legacy-cjs`, `vitest-browser`
242
271
 
243
272
  ## License
244
273
 
package/README.zh-TW.md CHANGED
@@ -10,12 +10,12 @@
10
10
 
11
11
  如果你熟悉 Cloudflare Workers 的 `fetchMock`(來自 `cloudflare:test`)或 Node.js undici 的 `MockAgent`,你已經會使用這個 API 了。
12
12
 
13
- 透過 subpath exports 同時支援 **Node.js**(`msw/node`)和**瀏覽器**(`msw/browser`)環境。
13
+ 透過 subpath exports 支援 **Node.js**(`msw/node`)、**瀏覽器**(`msw/browser`)和**原生**(無 MSW 依賴)環境。
14
14
 
15
15
  ## 系統需求
16
16
 
17
17
  - **Node.js** >= 18
18
- - **MSW** ^1.0.0(透過 `/legacy`)或 ^2.12.7
18
+ - **MSW** ^1.0.0(透過 `/legacy`)或 ^2.12.7 — 使用 `/native` 時**可選**
19
19
 
20
20
  ## 安裝
21
21
 
@@ -25,6 +25,12 @@ npm install -D msw-fetch-mock msw
25
25
 
26
26
  `msw` 是 peer dependency — 需要自行安裝你的版本。
27
27
 
28
+ 若不需要 MSW(直接 patch `globalThis.fetch`):
29
+
30
+ ```bash
31
+ npm install -D msw-fetch-mock
32
+ ```
33
+
28
34
  ## 快速開始
29
35
 
30
36
  ### Node.js(Vitest、Jest)
@@ -95,6 +101,25 @@ afterEach(() => {
95
101
 
96
102
  > **注意:** 同一時間只能有一個 MSW server 處於啟動狀態。如果已有 server 在監聽中,獨立模式的 `activate()` 會拋出錯誤。請使用 `createFetchMock(server)` 來共用現有的 server。
97
103
 
104
+ ### 原生模式(無 MSW 依賴)
105
+
106
+ 若不想安裝 MSW,`/native` 子路徑會直接 patch `globalThis.fetch`:
107
+
108
+ ```typescript
109
+ import { fetchMock } from 'msw-fetch-mock/native';
110
+
111
+ beforeAll(async () => {
112
+ await fetchMock.activate({ onUnhandledRequest: 'error' });
113
+ });
114
+ afterAll(() => fetchMock.deactivate());
115
+ afterEach(() => {
116
+ fetchMock.assertNoPendingInterceptors();
117
+ fetchMock.reset();
118
+ });
119
+ ```
120
+
121
+ API 完全相同 — 只有底層傳輸方式不同(無 Service Worker、無 MSW server)。
122
+
98
123
  ### Legacy(MSW v1)
99
124
 
100
125
  ```typescript
@@ -150,6 +175,7 @@ fetchMock.activate({
150
175
  | `msw-fetch-mock` | Node.js(re-exports `/node`) | v2 |
151
176
  | `msw-fetch-mock/node` | Node.js | v2 |
152
177
  | `msw-fetch-mock/browser` | 瀏覽器 | v2 |
178
+ | `msw-fetch-mock/native` | 任何環境(無 MSW) | 不需要 |
153
179
  | `msw-fetch-mock/legacy` | Node.js(MSW v1) | v1 |
154
180
 
155
181
  ### `fetchMock`(單例)
@@ -163,11 +189,12 @@ fetchMock.activate({
163
189
 
164
190
  - Node:`createFetchMock(server?)` — 可選擇性傳入現有的 MSW `SetupServer`
165
191
  - 瀏覽器:`createFetchMock(worker)` — 傳入 MSW `SetupWorker`(必要)
192
+ - 原生:`createFetchMock()` — 無需參數,無 MSW 依賴
166
193
  - Legacy:`createFetchMock(rest, server?)` — 傳入 MSW v1 的 `rest` 物件
167
194
 
168
195
  ### `new FetchMock(adapter?)`
169
196
 
170
- 使用明確的 `MswAdapter` 建立 `FetchMock` 實例。可使用 `NodeMswAdapter` 或 `BrowserMswAdapter`。
197
+ 使用明確的 `MswAdapter` 建立 `FetchMock` 實例。可使用 `NodeMswAdapter`、`BrowserMswAdapter` 或 `NativeFetchAdapter`。
171
198
 
172
199
  ### 攔截與回應
173
200
 
@@ -205,6 +232,8 @@ fetchMock.reset(); // 清除攔截器 + 呼叫歷史 + handlers
205
232
  | Jest CJS | CJS (require) | Jest |
206
233
  | Node.js Test | ESM (import) | Node test runner |
207
234
  | Node.js CJS | CJS (require) | Node test runner |
235
+ | Native ESM | ESM (import) | Node test runner |
236
+ | Native CJS | CJS (require) | Node test runner |
208
237
  | Legacy CJS | CJS (require) | Jest (MSW v1) |
209
238
  | Vitest Browser | ESM (import) | Vitest + Playwright |
210
239
 
@@ -238,7 +267,7 @@ pnpm test:e2e -- node-cjs
238
267
  pnpm test:e2e -- --all
239
268
  ```
240
269
 
241
- 可用套組:`jest-esm`、`jest-cjs`、`node-test`、`node-cjs`、`legacy-cjs`、`vitest-browser`
270
+ 可用套組:`jest-esm`、`jest-cjs`、`node-test`、`node-cjs`、`native-esm`、`native-cjs`、`legacy-cjs`、`vitest-browser`
242
271
 
243
272
  ## 授權
244
273
 
package/dist/browser.cjs CHANGED
@@ -1,11 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
  var _chunkLVGXTY6Jcjs = require('./chunk-LVGXTY6J.cjs');
4
+ require('./chunk-3RE2WWHX.cjs');
4
5
 
5
6
 
6
7
 
7
8
 
8
- var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
9
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
9
10
 
10
11
  // src/browser-adapter.ts
11
12
  var BrowserMswAdapter = class {
@@ -30,9 +31,9 @@ var BrowserMswAdapter = class {
30
31
  };
31
32
 
32
33
  // src/browser.ts
33
- _chunkN6B7UP6Bcjs.FetchMock._handlerFactory = _chunkLVGXTY6Jcjs.HandlerFactory;
34
+ _chunkVUNESK75cjs.FetchMock._handlerFactory = _chunkLVGXTY6Jcjs.HandlerFactory;
34
35
  function createFetchMock(worker) {
35
- return new (0, _chunkN6B7UP6Bcjs.FetchMock)(new BrowserMswAdapter(worker));
36
+ return new (0, _chunkVUNESK75cjs.FetchMock)(new BrowserMswAdapter(worker));
36
37
  }
37
38
 
38
39
 
@@ -40,4 +41,4 @@ function createFetchMock(worker) {
40
41
 
41
42
 
42
43
 
43
- exports.BrowserMswAdapter = BrowserMswAdapter; exports.FetchMock = _chunkN6B7UP6Bcjs.FetchMock; exports.MockCallHistory = _chunkN6B7UP6Bcjs.MockCallHistory; exports.MockCallHistoryLog = _chunkN6B7UP6Bcjs.MockCallHistoryLog; exports.createFetchMock = createFetchMock;
44
+ exports.BrowserMswAdapter = BrowserMswAdapter; exports.FetchMock = _chunkVUNESK75cjs.FetchMock; exports.MockCallHistory = _chunkVUNESK75cjs.MockCallHistory; exports.MockCallHistoryLog = _chunkVUNESK75cjs.MockCallHistoryLog; exports.createFetchMock = createFetchMock;
@@ -1,5 +1,5 @@
1
- import { M as MswAdapter, S as SetupWorkerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-DhiqmHdF.cjs';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyOptions } from './fetch-mock-DhiqmHdF.cjs';
1
+ import { M as MswAdapter, S as SetupWorkerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-1oOS8WUJ.cjs';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.cjs';
3
3
 
4
4
  declare class BrowserMswAdapter implements MswAdapter {
5
5
  private readonly worker;
package/dist/browser.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MswAdapter, S as SetupWorkerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-DhiqmHdF.js';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyOptions } from './fetch-mock-DhiqmHdF.js';
1
+ import { M as MswAdapter, S as SetupWorkerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-1oOS8WUJ.js';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.js';
3
3
 
4
4
  declare class BrowserMswAdapter implements MswAdapter {
5
5
  private readonly worker;
package/dist/browser.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  HandlerFactory
3
3
  } from "./chunk-KGCQG4D2.js";
4
+ import "./chunk-GZFGTCZB.js";
4
5
  import {
5
6
  FetchMock,
6
7
  MockCallHistory,
7
8
  MockCallHistoryLog
8
- } from "./chunk-3RAWYKAG.js";
9
+ } from "./chunk-3XFP4NAO.js";
9
10
 
10
11
  // src/browser-adapter.ts
11
12
  var BrowserMswAdapter = class {
@@ -3,7 +3,7 @@
3
3
  var _chunkLVGXTY6Jcjs = require('./chunk-LVGXTY6J.cjs');
4
4
 
5
5
 
6
- var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
6
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
7
7
 
8
8
  // src/node-adapter.ts
9
9
  var _node = require('msw/node');
@@ -44,10 +44,10 @@ var NodeMswAdapter = class {
44
44
  };
45
45
 
46
46
  // src/node.ts
47
- _chunkN6B7UP6Bcjs.FetchMock._defaultAdapterFactory = () => new NodeMswAdapter();
48
- _chunkN6B7UP6Bcjs.FetchMock._handlerFactory = _chunkLVGXTY6Jcjs.HandlerFactory;
47
+ _chunkVUNESK75cjs.FetchMock._defaultAdapterFactory = () => new NodeMswAdapter();
48
+ _chunkVUNESK75cjs.FetchMock._handlerFactory = _chunkLVGXTY6Jcjs.HandlerFactory;
49
49
  function createFetchMock(server) {
50
- return new (0, _chunkN6B7UP6Bcjs.FetchMock)(new NodeMswAdapter(server));
50
+ return new (0, _chunkVUNESK75cjs.FetchMock)(new NodeMswAdapter(server));
51
51
  }
52
52
  var fetchMock = createFetchMock();
53
53
 
@@ -0,0 +1 @@
1
+ "use strict";
@@ -28,6 +28,10 @@ var MockCallHistoryLog = class {
28
28
  if (this.body === null) return null;
29
29
  return JSON.parse(this.body);
30
30
  }
31
+ /**
32
+ * Returns a Map representation of this call log.
33
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
34
+ */
31
35
  toMap() {
32
36
  return /* @__PURE__ */ new Map([
33
37
  ["body", this.body],
@@ -43,6 +47,10 @@ var MockCallHistoryLog = class {
43
47
  ["hash", this.hash]
44
48
  ]);
45
49
  }
50
+ /**
51
+ * Returns a pipe-separated string representation of this call log.
52
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
53
+ */
46
54
  toString() {
47
55
  return [
48
56
  `method->${this.method}`,
@@ -105,32 +113,47 @@ var MockCallHistory = class {
105
113
  (log) => operator === "AND" ? predicates.every((p) => p(log)) : predicates.some((p) => p(log))
106
114
  );
107
115
  }
116
+ /**
117
+ * Filter helper — matches a single field by exact string or RegExp.
118
+ *
119
+ * The `filterCallsByXxx` methods below mirror the `cloudflare:test` fetchMock
120
+ * API so that tests written for Cloudflare Workers can be reused with this library
121
+ * without modification.
122
+ */
108
123
  filterBy(field, filter) {
109
124
  return this.logs.filter(
110
125
  (log) => typeof filter === "string" ? log[field] === filter : filter.test(String(log[field]))
111
126
  );
112
127
  }
128
+ /** Filter calls by HTTP method. Mirrors `cloudflare:test` fetchMock API. */
113
129
  filterCallsByMethod(filter) {
114
130
  return this.filterBy("method", filter);
115
131
  }
132
+ /** Filter calls by path. Mirrors `cloudflare:test` fetchMock API. */
116
133
  filterCallsByPath(filter) {
117
134
  return this.filterBy("path", filter);
118
135
  }
136
+ /** Filter calls by origin. Mirrors `cloudflare:test` fetchMock API. */
119
137
  filterCallsByOrigin(filter) {
120
138
  return this.filterBy("origin", filter);
121
139
  }
140
+ /** Filter calls by protocol. Mirrors `cloudflare:test` fetchMock API. */
122
141
  filterCallsByProtocol(filter) {
123
142
  return this.filterBy("protocol", filter);
124
143
  }
144
+ /** Filter calls by host. Mirrors `cloudflare:test` fetchMock API. */
125
145
  filterCallsByHost(filter) {
126
146
  return this.filterBy("host", filter);
127
147
  }
148
+ /** Filter calls by port. Mirrors `cloudflare:test` fetchMock API. */
128
149
  filterCallsByPort(filter) {
129
150
  return this.filterBy("port", filter);
130
151
  }
152
+ /** Filter calls by URL hash. Mirrors `cloudflare:test` fetchMock API. */
131
153
  filterCallsByHash(filter) {
132
154
  return this.filterBy("hash", filter);
133
155
  }
156
+ /** Filter calls by full URL. Mirrors `cloudflare:test` fetchMock API. */
134
157
  filterCallsByFullUrl(filter) {
135
158
  return this.filterBy("fullUrl", filter);
136
159
  }
@@ -327,12 +350,19 @@ var FetchMock = class _FetchMock {
327
350
  const activeHandlers = [...this.mswHandlers.entries()].filter(([p]) => !p.consumed || p.persist).map(([, handler]) => handler);
328
351
  this.adapter.resetHandlers(...activeHandlers);
329
352
  }
353
+ /**
354
+ * Returns the call history instance.
355
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
356
+ * Equivalent to the `calls` getter.
357
+ */
330
358
  getCallHistory() {
331
359
  return this._calls;
332
360
  }
361
+ /** Clears recorded call history. Mirrors `cloudflare:test` fetchMock API. */
333
362
  clearCallHistory() {
334
363
  this._calls.clear();
335
364
  }
365
+ /** Alias for `clearCallHistory()`. Mirrors `cloudflare:test` fetchMock API. */
336
366
  clearAllCallHistory() {
337
367
  this.clearCallHistory();
338
368
  }
File without changes
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-KGCQG4D2.js";
4
4
  import {
5
5
  FetchMock
6
- } from "./chunk-3RAWYKAG.js";
6
+ } from "./chunk-3XFP4NAO.js";
7
7
 
8
8
  // src/node-adapter.ts
9
9
  import { setupServer } from "msw/node";
@@ -28,6 +28,10 @@ var MockCallHistoryLog = class {
28
28
  if (this.body === null) return null;
29
29
  return JSON.parse(this.body);
30
30
  }
31
+ /**
32
+ * Returns a Map representation of this call log.
33
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
34
+ */
31
35
  toMap() {
32
36
  return /* @__PURE__ */ new Map([
33
37
  ["body", this.body],
@@ -43,6 +47,10 @@ var MockCallHistoryLog = class {
43
47
  ["hash", this.hash]
44
48
  ]);
45
49
  }
50
+ /**
51
+ * Returns a pipe-separated string representation of this call log.
52
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
53
+ */
46
54
  toString() {
47
55
  return [
48
56
  `method->${this.method}`,
@@ -105,32 +113,47 @@ var MockCallHistory = (_class = class {constructor() { _class.prototype.__init.c
105
113
  (log) => operator === "AND" ? predicates.every((p) => p(log)) : predicates.some((p) => p(log))
106
114
  );
107
115
  }
116
+ /**
117
+ * Filter helper — matches a single field by exact string or RegExp.
118
+ *
119
+ * The `filterCallsByXxx` methods below mirror the `cloudflare:test` fetchMock
120
+ * API so that tests written for Cloudflare Workers can be reused with this library
121
+ * without modification.
122
+ */
108
123
  filterBy(field, filter) {
109
124
  return this.logs.filter(
110
125
  (log) => typeof filter === "string" ? log[field] === filter : filter.test(String(log[field]))
111
126
  );
112
127
  }
128
+ /** Filter calls by HTTP method. Mirrors `cloudflare:test` fetchMock API. */
113
129
  filterCallsByMethod(filter) {
114
130
  return this.filterBy("method", filter);
115
131
  }
132
+ /** Filter calls by path. Mirrors `cloudflare:test` fetchMock API. */
116
133
  filterCallsByPath(filter) {
117
134
  return this.filterBy("path", filter);
118
135
  }
136
+ /** Filter calls by origin. Mirrors `cloudflare:test` fetchMock API. */
119
137
  filterCallsByOrigin(filter) {
120
138
  return this.filterBy("origin", filter);
121
139
  }
140
+ /** Filter calls by protocol. Mirrors `cloudflare:test` fetchMock API. */
122
141
  filterCallsByProtocol(filter) {
123
142
  return this.filterBy("protocol", filter);
124
143
  }
144
+ /** Filter calls by host. Mirrors `cloudflare:test` fetchMock API. */
125
145
  filterCallsByHost(filter) {
126
146
  return this.filterBy("host", filter);
127
147
  }
148
+ /** Filter calls by port. Mirrors `cloudflare:test` fetchMock API. */
128
149
  filterCallsByPort(filter) {
129
150
  return this.filterBy("port", filter);
130
151
  }
152
+ /** Filter calls by URL hash. Mirrors `cloudflare:test` fetchMock API. */
131
153
  filterCallsByHash(filter) {
132
154
  return this.filterBy("hash", filter);
133
155
  }
156
+ /** Filter calls by full URL. Mirrors `cloudflare:test` fetchMock API. */
134
157
  filterCallsByFullUrl(filter) {
135
158
  return this.filterBy("fullUrl", filter);
136
159
  }
@@ -327,12 +350,19 @@ var FetchMock = (_class2 = class _FetchMock {
327
350
  const activeHandlers = [...this.mswHandlers.entries()].filter(([p]) => !p.consumed || p.persist).map(([, handler]) => handler);
328
351
  this.adapter.resetHandlers(...activeHandlers);
329
352
  }
353
+ /**
354
+ * Returns the call history instance.
355
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
356
+ * Equivalent to the `calls` getter.
357
+ */
330
358
  getCallHistory() {
331
359
  return this._calls;
332
360
  }
361
+ /** Clears recorded call history. Mirrors `cloudflare:test` fetchMock API. */
333
362
  clearCallHistory() {
334
363
  this._calls.clear();
335
364
  }
365
+ /** Alias for `clearCallHistory()`. Mirrors `cloudflare:test` fetchMock API. */
336
366
  clearAllCallHistory() {
337
367
  this.clearCallHistory();
338
368
  }
@@ -25,7 +25,15 @@ declare class MockCallHistoryLog {
25
25
  readonly hash: string;
26
26
  constructor(data: MockCallHistoryLogData);
27
27
  json(): unknown;
28
+ /**
29
+ * Returns a Map representation of this call log.
30
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
31
+ */
28
32
  toMap(): Map<string, string | null | Record<string, string>>;
33
+ /**
34
+ * Returns a pipe-separated string representation of this call log.
35
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
36
+ */
29
37
  toString(): string;
30
38
  }
31
39
  interface CallHistoryFilterCriteria {
@@ -52,14 +60,29 @@ declare class MockCallHistory {
52
60
  filterCalls(criteria: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp, options?: {
53
61
  operator?: 'AND' | 'OR';
54
62
  }): MockCallHistoryLog[];
63
+ /**
64
+ * Filter helper — matches a single field by exact string or RegExp.
65
+ *
66
+ * The `filterCallsByXxx` methods below mirror the `cloudflare:test` fetchMock
67
+ * API so that tests written for Cloudflare Workers can be reused with this library
68
+ * without modification.
69
+ */
55
70
  private filterBy;
71
+ /** Filter calls by HTTP method. Mirrors `cloudflare:test` fetchMock API. */
56
72
  filterCallsByMethod(filter: string | RegExp): MockCallHistoryLog[];
73
+ /** Filter calls by path. Mirrors `cloudflare:test` fetchMock API. */
57
74
  filterCallsByPath(filter: string | RegExp): MockCallHistoryLog[];
75
+ /** Filter calls by origin. Mirrors `cloudflare:test` fetchMock API. */
58
76
  filterCallsByOrigin(filter: string | RegExp): MockCallHistoryLog[];
77
+ /** Filter calls by protocol. Mirrors `cloudflare:test` fetchMock API. */
59
78
  filterCallsByProtocol(filter: string | RegExp): MockCallHistoryLog[];
79
+ /** Filter calls by host. Mirrors `cloudflare:test` fetchMock API. */
60
80
  filterCallsByHost(filter: string | RegExp): MockCallHistoryLog[];
81
+ /** Filter calls by port. Mirrors `cloudflare:test` fetchMock API. */
61
82
  filterCallsByPort(filter: string | RegExp): MockCallHistoryLog[];
83
+ /** Filter calls by URL hash. Mirrors `cloudflare:test` fetchMock API. */
62
84
  filterCallsByHash(filter: string | RegExp): MockCallHistoryLog[];
85
+ /** Filter calls by full URL. Mirrors `cloudflare:test` fetchMock API. */
63
86
  filterCallsByFullUrl(filter: string | RegExp): MockCallHistoryLog[];
64
87
  }
65
88
 
@@ -177,8 +200,15 @@ declare class FetchMock {
177
200
  * go through MSW's onUnhandledRequest instead of silently passing through.
178
201
  */
179
202
  private syncMswHandlers;
203
+ /**
204
+ * Returns the call history instance.
205
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
206
+ * Equivalent to the `calls` getter.
207
+ */
180
208
  getCallHistory(): MockCallHistory;
209
+ /** Clears recorded call history. Mirrors `cloudflare:test` fetchMock API. */
181
210
  clearCallHistory(): void;
211
+ /** Alias for `clearCallHistory()`. Mirrors `cloudflare:test` fetchMock API. */
182
212
  clearAllCallHistory(): void;
183
213
  defaultReplyHeaders(headers: Record<string, string>): void;
184
214
  enableCallHistory(): void;
@@ -196,4 +226,4 @@ declare class FetchMock {
196
226
  get(origin: string | RegExp | ((origin: string) => boolean)): MockPool;
197
227
  }
198
228
 
199
- export { type ActivateOptions as A, type CallHistoryFilterCriteria as C, FetchMock as F, type HandlerFactory as H, type InterceptOptions as I, type MswAdapter as M, type OnUnhandledRequest as O, type PendingInterceptor as P, type ResolvedActivateOptions as R, type SetupWorkerLike as S, MockCallHistory as a, MockCallHistoryLog as b, type MockCallHistoryLogData as c, type MockInterceptor as d, type MockPool as e, type MockReplyChain as f, type ReplyOptions as g, type HttpMethod as h, type SetupServerLike as i, type ReplyCallback as j, type SingleReplyCallback as k, type SingleReplyResult as l };
229
+ export { type ActivateOptions as A, type CallHistoryFilterCriteria as C, FetchMock as F, type HandlerFactory as H, type InterceptOptions as I, type MswAdapter as M, type OnUnhandledRequest as O, type PendingInterceptor as P, type ResolvedActivateOptions as R, type SetupWorkerLike as S, MockCallHistory as a, MockCallHistoryLog as b, type MockCallHistoryLogData as c, type MockInterceptor as d, type MockPool as e, type MockReplyChain as f, type ReplyCallback as g, type ReplyOptions as h, type SingleReplyCallback as i, type SingleReplyResult as j, type HttpMethod as k, type SetupServerLike as l };
@@ -25,7 +25,15 @@ declare class MockCallHistoryLog {
25
25
  readonly hash: string;
26
26
  constructor(data: MockCallHistoryLogData);
27
27
  json(): unknown;
28
+ /**
29
+ * Returns a Map representation of this call log.
30
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
31
+ */
28
32
  toMap(): Map<string, string | null | Record<string, string>>;
33
+ /**
34
+ * Returns a pipe-separated string representation of this call log.
35
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
36
+ */
29
37
  toString(): string;
30
38
  }
31
39
  interface CallHistoryFilterCriteria {
@@ -52,14 +60,29 @@ declare class MockCallHistory {
52
60
  filterCalls(criteria: ((log: MockCallHistoryLog) => boolean) | CallHistoryFilterCriteria | RegExp, options?: {
53
61
  operator?: 'AND' | 'OR';
54
62
  }): MockCallHistoryLog[];
63
+ /**
64
+ * Filter helper — matches a single field by exact string or RegExp.
65
+ *
66
+ * The `filterCallsByXxx` methods below mirror the `cloudflare:test` fetchMock
67
+ * API so that tests written for Cloudflare Workers can be reused with this library
68
+ * without modification.
69
+ */
55
70
  private filterBy;
71
+ /** Filter calls by HTTP method. Mirrors `cloudflare:test` fetchMock API. */
56
72
  filterCallsByMethod(filter: string | RegExp): MockCallHistoryLog[];
73
+ /** Filter calls by path. Mirrors `cloudflare:test` fetchMock API. */
57
74
  filterCallsByPath(filter: string | RegExp): MockCallHistoryLog[];
75
+ /** Filter calls by origin. Mirrors `cloudflare:test` fetchMock API. */
58
76
  filterCallsByOrigin(filter: string | RegExp): MockCallHistoryLog[];
77
+ /** Filter calls by protocol. Mirrors `cloudflare:test` fetchMock API. */
59
78
  filterCallsByProtocol(filter: string | RegExp): MockCallHistoryLog[];
79
+ /** Filter calls by host. Mirrors `cloudflare:test` fetchMock API. */
60
80
  filterCallsByHost(filter: string | RegExp): MockCallHistoryLog[];
81
+ /** Filter calls by port. Mirrors `cloudflare:test` fetchMock API. */
61
82
  filterCallsByPort(filter: string | RegExp): MockCallHistoryLog[];
83
+ /** Filter calls by URL hash. Mirrors `cloudflare:test` fetchMock API. */
62
84
  filterCallsByHash(filter: string | RegExp): MockCallHistoryLog[];
85
+ /** Filter calls by full URL. Mirrors `cloudflare:test` fetchMock API. */
63
86
  filterCallsByFullUrl(filter: string | RegExp): MockCallHistoryLog[];
64
87
  }
65
88
 
@@ -177,8 +200,15 @@ declare class FetchMock {
177
200
  * go through MSW's onUnhandledRequest instead of silently passing through.
178
201
  */
179
202
  private syncMswHandlers;
203
+ /**
204
+ * Returns the call history instance.
205
+ * Provided for compatibility with the `cloudflare:test` fetchMock API.
206
+ * Equivalent to the `calls` getter.
207
+ */
180
208
  getCallHistory(): MockCallHistory;
209
+ /** Clears recorded call history. Mirrors `cloudflare:test` fetchMock API. */
181
210
  clearCallHistory(): void;
211
+ /** Alias for `clearCallHistory()`. Mirrors `cloudflare:test` fetchMock API. */
182
212
  clearAllCallHistory(): void;
183
213
  defaultReplyHeaders(headers: Record<string, string>): void;
184
214
  enableCallHistory(): void;
@@ -196,4 +226,4 @@ declare class FetchMock {
196
226
  get(origin: string | RegExp | ((origin: string) => boolean)): MockPool;
197
227
  }
198
228
 
199
- export { type ActivateOptions as A, type CallHistoryFilterCriteria as C, FetchMock as F, type HandlerFactory as H, type InterceptOptions as I, type MswAdapter as M, type OnUnhandledRequest as O, type PendingInterceptor as P, type ResolvedActivateOptions as R, type SetupWorkerLike as S, MockCallHistory as a, MockCallHistoryLog as b, type MockCallHistoryLogData as c, type MockInterceptor as d, type MockPool as e, type MockReplyChain as f, type ReplyOptions as g, type HttpMethod as h, type SetupServerLike as i, type ReplyCallback as j, type SingleReplyCallback as k, type SingleReplyResult as l };
229
+ export { type ActivateOptions as A, type CallHistoryFilterCriteria as C, FetchMock as F, type HandlerFactory as H, type InterceptOptions as I, type MswAdapter as M, type OnUnhandledRequest as O, type PendingInterceptor as P, type ResolvedActivateOptions as R, type SetupWorkerLike as S, MockCallHistory as a, MockCallHistoryLog as b, type MockCallHistoryLogData as c, type MockInterceptor as d, type MockPool as e, type MockReplyChain as f, type ReplyCallback as g, type ReplyOptions as h, type SingleReplyCallback as i, type SingleReplyResult as j, type HttpMethod as k, type SetupServerLike as l };
package/dist/index.cjs CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkOSKJXLRHcjs = require('./chunk-OSKJXLRH.cjs');
5
+ var _chunk27BEAYUIcjs = require('./chunk-27BEAYUI.cjs');
6
6
  require('./chunk-LVGXTY6J.cjs');
7
+ require('./chunk-3RE2WWHX.cjs');
7
8
 
8
9
 
9
10
 
10
11
 
11
- var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
12
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
12
13
 
13
14
 
14
15
 
@@ -16,4 +17,4 @@ var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
16
17
 
17
18
 
18
19
 
19
- exports.FetchMock = _chunkN6B7UP6Bcjs.FetchMock; exports.MockCallHistory = _chunkN6B7UP6Bcjs.MockCallHistory; exports.MockCallHistoryLog = _chunkN6B7UP6Bcjs.MockCallHistoryLog; exports.NodeMswAdapter = _chunkOSKJXLRHcjs.NodeMswAdapter; exports.createFetchMock = _chunkOSKJXLRHcjs.createFetchMock; exports.fetchMock = _chunkOSKJXLRHcjs.fetchMock;
20
+ exports.FetchMock = _chunkVUNESK75cjs.FetchMock; exports.MockCallHistory = _chunkVUNESK75cjs.MockCallHistory; exports.MockCallHistoryLog = _chunkVUNESK75cjs.MockCallHistoryLog; exports.NodeMswAdapter = _chunk27BEAYUIcjs.NodeMswAdapter; exports.createFetchMock = _chunk27BEAYUIcjs.createFetchMock; exports.fetchMock = _chunk27BEAYUIcjs.fetchMock;
package/dist/index.d.cts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { NodeMswAdapter, createFetchMock, fetchMock } from './node.cjs';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, F as FetchMock, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, j as ReplyCallback, g as ReplyOptions, i as SetupServerLike, k as SingleReplyCallback, l as SingleReplyResult } from './fetch-mock-DhiqmHdF.cjs';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, F as FetchMock, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, l as SetupServerLike, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.cjs';
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { NodeMswAdapter, createFetchMock, fetchMock } from './node.js';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, F as FetchMock, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, j as ReplyCallback, g as ReplyOptions, i as SetupServerLike, k as SingleReplyCallback, l as SingleReplyResult } from './fetch-mock-DhiqmHdF.js';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, F as FetchMock, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, l as SetupServerLike, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.js';
package/dist/index.js CHANGED
@@ -2,13 +2,14 @@ import {
2
2
  NodeMswAdapter,
3
3
  createFetchMock,
4
4
  fetchMock
5
- } from "./chunk-NFPFLI3N.js";
5
+ } from "./chunk-IWHL7QPE.js";
6
6
  import "./chunk-KGCQG4D2.js";
7
+ import "./chunk-GZFGTCZB.js";
7
8
  import {
8
9
  FetchMock,
9
10
  MockCallHistory,
10
11
  MockCallHistoryLog
11
- } from "./chunk-3RAWYKAG.js";
12
+ } from "./chunk-3XFP4NAO.js";
12
13
  export {
13
14
  FetchMock,
14
15
  MockCallHistory,
package/dist/legacy.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
5
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
6
6
 
7
7
  // src/legacy-handler-factory.ts
8
8
  function createLegacyHandlerFactory(rest) {
@@ -56,11 +56,11 @@ function createLegacyHandlerFactory(rest) {
56
56
 
57
57
  // src/legacy.ts
58
58
  function createFetchMock(rest, server) {
59
- _chunkN6B7UP6Bcjs.FetchMock._handlerFactory = createLegacyHandlerFactory(rest);
59
+ _chunkVUNESK75cjs.FetchMock._handlerFactory = createLegacyHandlerFactory(rest);
60
60
  if (server) {
61
- return new (0, _chunkN6B7UP6Bcjs.FetchMock)(server);
61
+ return new (0, _chunkVUNESK75cjs.FetchMock)(server);
62
62
  }
63
- return new (0, _chunkN6B7UP6Bcjs.FetchMock)();
63
+ return new (0, _chunkVUNESK75cjs.FetchMock)();
64
64
  }
65
65
 
66
66
 
@@ -68,4 +68,4 @@ function createFetchMock(rest, server) {
68
68
 
69
69
 
70
70
 
71
- exports.FetchMock = _chunkN6B7UP6Bcjs.FetchMock; exports.MockCallHistory = _chunkN6B7UP6Bcjs.MockCallHistory; exports.MockCallHistoryLog = _chunkN6B7UP6Bcjs.MockCallHistoryLog; exports.createFetchMock = createFetchMock; exports.createLegacyHandlerFactory = createLegacyHandlerFactory;
71
+ exports.FetchMock = _chunkVUNESK75cjs.FetchMock; exports.MockCallHistory = _chunkVUNESK75cjs.MockCallHistory; exports.MockCallHistoryLog = _chunkVUNESK75cjs.MockCallHistoryLog; exports.createFetchMock = createFetchMock; exports.createLegacyHandlerFactory = createLegacyHandlerFactory;
package/dist/legacy.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { h as HttpMethod, H as HandlerFactory, i as SetupServerLike, F as FetchMock } from './fetch-mock-DhiqmHdF.cjs';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyOptions } from './fetch-mock-DhiqmHdF.cjs';
1
+ import { k as HttpMethod, H as HandlerFactory, l as SetupServerLike, F as FetchMock } from './fetch-mock-1oOS8WUJ.cjs';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, h as ReplyOptions } from './fetch-mock-1oOS8WUJ.cjs';
3
3
 
4
4
  /** Duck-typed interface for MSW v1's `rest` API methods */
5
5
  type LegacyRestMethod = (url: string | RegExp, resolver: (req: any, res: any, ctx: any) => any) => unknown;
package/dist/legacy.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { h as HttpMethod, H as HandlerFactory, i as SetupServerLike, F as FetchMock } from './fetch-mock-DhiqmHdF.js';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyOptions } from './fetch-mock-DhiqmHdF.js';
1
+ import { k as HttpMethod, H as HandlerFactory, l as SetupServerLike, F as FetchMock } from './fetch-mock-1oOS8WUJ.js';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, M as MswAdapter, O as OnUnhandledRequest, P as PendingInterceptor, h as ReplyOptions } from './fetch-mock-1oOS8WUJ.js';
3
3
 
4
4
  /** Duck-typed interface for MSW v1's `rest` API methods */
5
5
  type LegacyRestMethod = (url: string | RegExp, resolver: (req: any, res: any, ctx: any) => any) => unknown;
package/dist/legacy.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  FetchMock,
3
3
  MockCallHistory,
4
4
  MockCallHistoryLog
5
- } from "./chunk-3RAWYKAG.js";
5
+ } from "./chunk-3XFP4NAO.js";
6
6
 
7
7
  // src/legacy-handler-factory.ts
8
8
  function createLegacyHandlerFactory(rest) {
@@ -0,0 +1,92 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _class;require('./chunk-3RE2WWHX.cjs');
2
+
3
+
4
+
5
+
6
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
7
+
8
+ // src/native-adapter.ts
9
+ var NativeFetchAdapter = (_class = class {constructor() { _class.prototype.__init.call(this); }
10
+
11
+ __init() {this.handlers = []}
12
+
13
+ activate(options) {
14
+ this.options = options;
15
+ this.originalFetch = globalThis.fetch;
16
+ globalThis.fetch = async (input, init) => {
17
+ const request = new Request(input, init);
18
+ for (const handler of this.handlers) {
19
+ const response = await handler.handlerFn(request);
20
+ if (response !== void 0) {
21
+ if (response.type === "error") {
22
+ throw new TypeError("Failed to fetch");
23
+ }
24
+ return response;
25
+ }
26
+ }
27
+ this.options.onUnhandledRequest(request, {
28
+ warning() {
29
+ console.warn(
30
+ `[msw-fetch-mock] Warning: intercepted a request without a matching request handler:
31
+
32
+ \u2022 ${request.method} ${request.url}
33
+
34
+ If you still wish to intercept this unhandled request, please create a request handler for it.`
35
+ );
36
+ },
37
+ error() {
38
+ throw new TypeError(
39
+ `[msw-fetch-mock] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.
40
+
41
+ \u2022 ${request.method} ${request.url}
42
+ `
43
+ );
44
+ }
45
+ });
46
+ return this.originalFetch(input, init);
47
+ };
48
+ }
49
+ deactivate() {
50
+ globalThis.fetch = this.originalFetch;
51
+ this.handlers = [];
52
+ }
53
+ use(...handlers) {
54
+ this.handlers.push(...handlers);
55
+ }
56
+ resetHandlers(...handlers) {
57
+ this.handlers = handlers;
58
+ }
59
+ }, _class);
60
+
61
+ // src/native-handler-factory.ts
62
+ var NativeHandlerFactory = {
63
+ createHandler(method, urlPattern, handlerFn) {
64
+ return { method, urlPattern, handlerFn };
65
+ },
66
+ buildResponse(status, body, headers) {
67
+ if (body === null || body === void 0) {
68
+ return new Response(null, { status, headers });
69
+ }
70
+ return Response.json(body, { status, headers });
71
+ },
72
+ buildErrorResponse() {
73
+ return Response.error();
74
+ }
75
+ };
76
+
77
+ // src/native.ts
78
+ _chunkVUNESK75cjs.FetchMock._defaultAdapterFactory = () => new NativeFetchAdapter();
79
+ _chunkVUNESK75cjs.FetchMock._handlerFactory = NativeHandlerFactory;
80
+ function createFetchMock() {
81
+ return new (0, _chunkVUNESK75cjs.FetchMock)(new NativeFetchAdapter());
82
+ }
83
+ var fetchMock = createFetchMock();
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ exports.FetchMock = _chunkVUNESK75cjs.FetchMock; exports.MockCallHistory = _chunkVUNESK75cjs.MockCallHistory; exports.MockCallHistoryLog = _chunkVUNESK75cjs.MockCallHistoryLog; exports.NativeFetchAdapter = NativeFetchAdapter; exports.NativeHandlerFactory = NativeHandlerFactory; exports.createFetchMock = createFetchMock; exports.fetchMock = fetchMock;
@@ -0,0 +1,20 @@
1
+ import { M as MswAdapter, R as ResolvedActivateOptions, H as HandlerFactory, F as FetchMock } from './fetch-mock-1oOS8WUJ.cjs';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.cjs';
3
+
4
+ declare class NativeFetchAdapter implements MswAdapter {
5
+ private originalFetch;
6
+ private handlers;
7
+ private options;
8
+ activate(options: ResolvedActivateOptions): void;
9
+ deactivate(): void;
10
+ use(...handlers: unknown[]): void;
11
+ resetHandlers(...handlers: unknown[]): void;
12
+ }
13
+
14
+ declare const NativeHandlerFactory: HandlerFactory;
15
+
16
+ declare function createFetchMock(): FetchMock;
17
+ /** Pre-built singleton for quick standalone use. */
18
+ declare const fetchMock: FetchMock;
19
+
20
+ export { FetchMock, HandlerFactory, MswAdapter, NativeFetchAdapter, NativeHandlerFactory, createFetchMock, fetchMock };
@@ -0,0 +1,20 @@
1
+ import { M as MswAdapter, R as ResolvedActivateOptions, H as HandlerFactory, F as FetchMock } from './fetch-mock-1oOS8WUJ.js';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.js';
3
+
4
+ declare class NativeFetchAdapter implements MswAdapter {
5
+ private originalFetch;
6
+ private handlers;
7
+ private options;
8
+ activate(options: ResolvedActivateOptions): void;
9
+ deactivate(): void;
10
+ use(...handlers: unknown[]): void;
11
+ resetHandlers(...handlers: unknown[]): void;
12
+ }
13
+
14
+ declare const NativeHandlerFactory: HandlerFactory;
15
+
16
+ declare function createFetchMock(): FetchMock;
17
+ /** Pre-built singleton for quick standalone use. */
18
+ declare const fetchMock: FetchMock;
19
+
20
+ export { FetchMock, HandlerFactory, MswAdapter, NativeFetchAdapter, NativeHandlerFactory, createFetchMock, fetchMock };
package/dist/native.js ADDED
@@ -0,0 +1,92 @@
1
+ import "./chunk-GZFGTCZB.js";
2
+ import {
3
+ FetchMock,
4
+ MockCallHistory,
5
+ MockCallHistoryLog
6
+ } from "./chunk-3XFP4NAO.js";
7
+
8
+ // src/native-adapter.ts
9
+ var NativeFetchAdapter = class {
10
+ originalFetch;
11
+ handlers = [];
12
+ options;
13
+ activate(options) {
14
+ this.options = options;
15
+ this.originalFetch = globalThis.fetch;
16
+ globalThis.fetch = async (input, init) => {
17
+ const request = new Request(input, init);
18
+ for (const handler of this.handlers) {
19
+ const response = await handler.handlerFn(request);
20
+ if (response !== void 0) {
21
+ if (response.type === "error") {
22
+ throw new TypeError("Failed to fetch");
23
+ }
24
+ return response;
25
+ }
26
+ }
27
+ this.options.onUnhandledRequest(request, {
28
+ warning() {
29
+ console.warn(
30
+ `[msw-fetch-mock] Warning: intercepted a request without a matching request handler:
31
+
32
+ \u2022 ${request.method} ${request.url}
33
+
34
+ If you still wish to intercept this unhandled request, please create a request handler for it.`
35
+ );
36
+ },
37
+ error() {
38
+ throw new TypeError(
39
+ `[msw-fetch-mock] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.
40
+
41
+ \u2022 ${request.method} ${request.url}
42
+ `
43
+ );
44
+ }
45
+ });
46
+ return this.originalFetch(input, init);
47
+ };
48
+ }
49
+ deactivate() {
50
+ globalThis.fetch = this.originalFetch;
51
+ this.handlers = [];
52
+ }
53
+ use(...handlers) {
54
+ this.handlers.push(...handlers);
55
+ }
56
+ resetHandlers(...handlers) {
57
+ this.handlers = handlers;
58
+ }
59
+ };
60
+
61
+ // src/native-handler-factory.ts
62
+ var NativeHandlerFactory = {
63
+ createHandler(method, urlPattern, handlerFn) {
64
+ return { method, urlPattern, handlerFn };
65
+ },
66
+ buildResponse(status, body, headers) {
67
+ if (body === null || body === void 0) {
68
+ return new Response(null, { status, headers });
69
+ }
70
+ return Response.json(body, { status, headers });
71
+ },
72
+ buildErrorResponse() {
73
+ return Response.error();
74
+ }
75
+ };
76
+
77
+ // src/native.ts
78
+ FetchMock._defaultAdapterFactory = () => new NativeFetchAdapter();
79
+ FetchMock._handlerFactory = NativeHandlerFactory;
80
+ function createFetchMock() {
81
+ return new FetchMock(new NativeFetchAdapter());
82
+ }
83
+ var fetchMock = createFetchMock();
84
+ export {
85
+ FetchMock,
86
+ MockCallHistory,
87
+ MockCallHistoryLog,
88
+ NativeFetchAdapter,
89
+ NativeHandlerFactory,
90
+ createFetchMock,
91
+ fetchMock
92
+ };
package/dist/node.cjs CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkOSKJXLRHcjs = require('./chunk-OSKJXLRH.cjs');
5
+ var _chunk27BEAYUIcjs = require('./chunk-27BEAYUI.cjs');
6
6
  require('./chunk-LVGXTY6J.cjs');
7
+ require('./chunk-3RE2WWHX.cjs');
7
8
 
8
9
 
9
10
 
10
11
 
11
- var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
12
+ var _chunkVUNESK75cjs = require('./chunk-VUNESK75.cjs');
12
13
 
13
14
 
14
15
 
@@ -16,4 +17,4 @@ var _chunkN6B7UP6Bcjs = require('./chunk-N6B7UP6B.cjs');
16
17
 
17
18
 
18
19
 
19
- exports.FetchMock = _chunkN6B7UP6Bcjs.FetchMock; exports.MockCallHistory = _chunkN6B7UP6Bcjs.MockCallHistory; exports.MockCallHistoryLog = _chunkN6B7UP6Bcjs.MockCallHistoryLog; exports.NodeMswAdapter = _chunkOSKJXLRHcjs.NodeMswAdapter; exports.createFetchMock = _chunkOSKJXLRHcjs.createFetchMock; exports.fetchMock = _chunkOSKJXLRHcjs.fetchMock;
20
+ exports.FetchMock = _chunkVUNESK75cjs.FetchMock; exports.MockCallHistory = _chunkVUNESK75cjs.MockCallHistory; exports.MockCallHistoryLog = _chunkVUNESK75cjs.MockCallHistoryLog; exports.NodeMswAdapter = _chunk27BEAYUIcjs.NodeMswAdapter; exports.createFetchMock = _chunk27BEAYUIcjs.createFetchMock; exports.fetchMock = _chunk27BEAYUIcjs.fetchMock;
package/dist/node.d.cts CHANGED
@@ -1,6 +1,18 @@
1
- import { M as MswAdapter, i as SetupServerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-DhiqmHdF.cjs';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, j as ReplyCallback, g as ReplyOptions, k as SingleReplyCallback, l as SingleReplyResult } from './fetch-mock-DhiqmHdF.cjs';
1
+ import { M as MswAdapter, l as SetupServerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-1oOS8WUJ.cjs';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.cjs';
3
3
 
4
+ /**
5
+ * MSW adapter that owns and manages its own `setupServer` lifecycle.
6
+ *
7
+ * **Difference from `createServerAdapter` (in fetch-mock.ts):**
8
+ * - `NodeMswAdapter` creates a `setupServer()` on `activate()` and calls
9
+ * `close()` on `deactivate()` — it owns the server lifecycle.
10
+ * - `createServerAdapter` wraps a user-provided server and does not manage
11
+ * its lifecycle — the caller owns `listen()` / `close()`.
12
+ *
13
+ * When an external server is passed via the constructor, `NodeMswAdapter`
14
+ * delegates to it without managing lifecycle (similar to `createServerAdapter`).
15
+ */
4
16
  declare class NodeMswAdapter implements MswAdapter {
5
17
  private server;
6
18
  private readonly ownsServer;
package/dist/node.d.ts CHANGED
@@ -1,6 +1,18 @@
1
- import { M as MswAdapter, i as SetupServerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-DhiqmHdF.js';
2
- export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, j as ReplyCallback, g as ReplyOptions, k as SingleReplyCallback, l as SingleReplyResult } from './fetch-mock-DhiqmHdF.js';
1
+ import { M as MswAdapter, l as SetupServerLike, R as ResolvedActivateOptions, F as FetchMock } from './fetch-mock-1oOS8WUJ.js';
2
+ export { A as ActivateOptions, C as CallHistoryFilterCriteria, H as HandlerFactory, I as InterceptOptions, a as MockCallHistory, b as MockCallHistoryLog, c as MockCallHistoryLogData, d as MockInterceptor, e as MockPool, f as MockReplyChain, O as OnUnhandledRequest, P as PendingInterceptor, g as ReplyCallback, h as ReplyOptions, i as SingleReplyCallback, j as SingleReplyResult } from './fetch-mock-1oOS8WUJ.js';
3
3
 
4
+ /**
5
+ * MSW adapter that owns and manages its own `setupServer` lifecycle.
6
+ *
7
+ * **Difference from `createServerAdapter` (in fetch-mock.ts):**
8
+ * - `NodeMswAdapter` creates a `setupServer()` on `activate()` and calls
9
+ * `close()` on `deactivate()` — it owns the server lifecycle.
10
+ * - `createServerAdapter` wraps a user-provided server and does not manage
11
+ * its lifecycle — the caller owns `listen()` / `close()`.
12
+ *
13
+ * When an external server is passed via the constructor, `NodeMswAdapter`
14
+ * delegates to it without managing lifecycle (similar to `createServerAdapter`).
15
+ */
4
16
  declare class NodeMswAdapter implements MswAdapter {
5
17
  private server;
6
18
  private readonly ownsServer;
package/dist/node.js CHANGED
@@ -2,13 +2,14 @@ import {
2
2
  NodeMswAdapter,
3
3
  createFetchMock,
4
4
  fetchMock
5
- } from "./chunk-NFPFLI3N.js";
5
+ } from "./chunk-IWHL7QPE.js";
6
6
  import "./chunk-KGCQG4D2.js";
7
+ import "./chunk-GZFGTCZB.js";
7
8
  import {
8
9
  FetchMock,
9
10
  MockCallHistory,
10
11
  MockCallHistoryLog
11
- } from "./chunk-3RAWYKAG.js";
12
+ } from "./chunk-3XFP4NAO.js";
12
13
  export {
13
14
  FetchMock,
14
15
  MockCallHistory,
package/docs/api.md CHANGED
@@ -2,12 +2,13 @@
2
2
 
3
3
  ## Import Paths
4
4
 
5
- | Path | Environment | MSW version |
6
- | ------------------------ | ---------------------------- | ----------- |
7
- | `msw-fetch-mock` | Node.js (re-exports `/node`) | v2 |
8
- | `msw-fetch-mock/node` | Node.js | v2 |
9
- | `msw-fetch-mock/browser` | Browser | v2 |
10
- | `msw-fetch-mock/legacy` | Node.js (MSW v1) | v1 |
5
+ | Path | Environment | MSW version |
6
+ | ------------------------ | ---------------------------- | ------------ |
7
+ | `msw-fetch-mock` | Node.js (re-exports `/node`) | v2 |
8
+ | `msw-fetch-mock/node` | Node.js | v2 |
9
+ | `msw-fetch-mock/browser` | Browser | v2 |
10
+ | `msw-fetch-mock/native` | Any (no MSW) | not required |
11
+ | `msw-fetch-mock/legacy` | Node.js (MSW v1) | v1 |
11
12
 
12
13
  ## `fetchMock` (singleton)
13
14
 
@@ -58,6 +59,26 @@ beforeAll(async () => {
58
59
  });
59
60
  ```
60
61
 
62
+ ## `createFetchMock()` (Native)
63
+
64
+ Creates a `FetchMock` with `NativeFetchAdapter`. No MSW dependency required — patches `globalThis.fetch` directly.
65
+
66
+ ```typescript
67
+ import { createFetchMock } from 'msw-fetch-mock/native';
68
+
69
+ const fetchMock = createFetchMock();
70
+
71
+ beforeAll(async () => {
72
+ await fetchMock.activate({ onUnhandledRequest: 'error' });
73
+ });
74
+ ```
75
+
76
+ A pre-built singleton is also available:
77
+
78
+ ```typescript
79
+ import { fetchMock } from 'msw-fetch-mock/native';
80
+ ```
81
+
61
82
  ## `createFetchMock(rest, server?)` (Legacy)
62
83
 
63
84
  Creates a `FetchMock` for MSW v1 environments. See [MSW v1 Legacy Guide](msw-v1-legacy.md).
@@ -79,12 +100,16 @@ Creates a `FetchMock` instance with an explicit `MswAdapter`.
79
100
  import { FetchMock } from 'msw-fetch-mock';
80
101
  import { NodeMswAdapter } from 'msw-fetch-mock/node';
81
102
  import { BrowserMswAdapter } from 'msw-fetch-mock/browser';
103
+ import { NativeFetchAdapter } from 'msw-fetch-mock/native';
82
104
 
83
105
  // Node with external server
84
106
  const fetchMock = new FetchMock(new NodeMswAdapter(server));
85
107
 
86
108
  // Browser with worker
87
109
  const fetchMock = new FetchMock(new BrowserMswAdapter(worker));
110
+
111
+ // Native (no MSW)
112
+ const fetchMock = new FetchMock(new NativeFetchAdapter());
88
113
  ```
89
114
 
90
115
  | Parameter | Type | Required | Description |
package/docs/api.zh-TW.md CHANGED
@@ -7,6 +7,7 @@
7
7
  | `msw-fetch-mock` | Node.js(re-exports `/node`) | v2 |
8
8
  | `msw-fetch-mock/node` | Node.js | v2 |
9
9
  | `msw-fetch-mock/browser` | 瀏覽器 | v2 |
10
+ | `msw-fetch-mock/native` | 任何環境(無 MSW) | 不需要 |
10
11
  | `msw-fetch-mock/legacy` | Node.js(MSW v1) | v1 |
11
12
 
12
13
  ## `fetchMock`(單例)
@@ -58,6 +59,26 @@ beforeAll(async () => {
58
59
  });
59
60
  ```
60
61
 
62
+ ## `createFetchMock()`(原生模式)
63
+
64
+ 建立搭配 `NativeFetchAdapter` 的 `FetchMock`。不需要 MSW 依賴 — 直接 patch `globalThis.fetch`。
65
+
66
+ ```typescript
67
+ import { createFetchMock } from 'msw-fetch-mock/native';
68
+
69
+ const fetchMock = createFetchMock();
70
+
71
+ beforeAll(async () => {
72
+ await fetchMock.activate({ onUnhandledRequest: 'error' });
73
+ });
74
+ ```
75
+
76
+ 也提供預建的單例:
77
+
78
+ ```typescript
79
+ import { fetchMock } from 'msw-fetch-mock/native';
80
+ ```
81
+
61
82
  ## `createFetchMock(rest, server?)`(Legacy)
62
83
 
63
84
  建立適用於 MSW v1 環境的 `FetchMock`。詳見 [MSW v1 Legacy 指南](msw-v1-legacy.zh-TW.md)。
@@ -79,12 +100,16 @@ const fetchMock = createFetchMock(rest, server);
79
100
  import { FetchMock } from 'msw-fetch-mock';
80
101
  import { NodeMswAdapter } from 'msw-fetch-mock/node';
81
102
  import { BrowserMswAdapter } from 'msw-fetch-mock/browser';
103
+ import { NativeFetchAdapter } from 'msw-fetch-mock/native';
82
104
 
83
105
  // Node 搭配外部 server
84
106
  const fetchMock = new FetchMock(new NodeMswAdapter(server));
85
107
 
86
108
  // 瀏覽器搭配 worker
87
109
  const fetchMock = new FetchMock(new BrowserMswAdapter(worker));
110
+
111
+ // 原生模式(無 MSW)
112
+ const fetchMock = new FetchMock(new NativeFetchAdapter());
88
113
  ```
89
114
 
90
115
  | 參數 | 型別 | 必要 | 說明 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "msw-fetch-mock",
3
- "version": "0.3.4",
3
+ "version": "0.4.0",
4
4
  "description": "Undici-style fetch mock API built on MSW (Mock Service Worker)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,6 +57,15 @@
57
57
  },
58
58
  "import": "./dist/legacy.js",
59
59
  "require": "./dist/legacy.cjs"
60
+ },
61
+ "./native": {
62
+ "source": "./src/native.ts",
63
+ "types": {
64
+ "import": "./dist/native.d.ts",
65
+ "require": "./dist/native.d.cts"
66
+ },
67
+ "import": "./dist/native.js",
68
+ "require": "./dist/native.cjs"
60
69
  }
61
70
  },
62
71
  "files": [
@@ -81,6 +90,11 @@
81
90
  "peerDependencies": {
82
91
  "msw": "^1.0.0 || ^2.12.7"
83
92
  },
93
+ "peerDependenciesMeta": {
94
+ "msw": {
95
+ "optional": true
96
+ }
97
+ },
84
98
  "devDependencies": {
85
99
  "@eslint/js": "^9.39.2",
86
100
  "eslint": "^9.39.2",