@mswjs/interceptors 0.14.1 → 0.15.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 (90) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +68 -49
  3. package/lib/BatchInterceptor.d.ts +18 -0
  4. package/lib/BatchInterceptor.js +79 -0
  5. package/lib/BatchInterceptor.js.map +1 -0
  6. package/lib/Interceptor.d.ts +49 -0
  7. package/lib/Interceptor.js +197 -0
  8. package/lib/Interceptor.js.map +1 -0
  9. package/lib/RemoteInterceptor.d.ts +24 -0
  10. package/lib/RemoteInterceptor.js +216 -0
  11. package/lib/RemoteInterceptor.js.map +1 -0
  12. package/lib/glossary.d.ts +32 -0
  13. package/lib/glossary.js +3 -0
  14. package/lib/glossary.js.map +1 -0
  15. package/lib/index.d.ts +2 -2
  16. package/lib/index.js +2 -2
  17. package/lib/index.js.map +1 -1
  18. package/lib/interceptors/ClientRequest/NodeClientRequest.d.ts +5 -5
  19. package/lib/interceptors/ClientRequest/NodeClientRequest.js +65 -16
  20. package/lib/interceptors/ClientRequest/NodeClientRequest.js.map +1 -1
  21. package/lib/interceptors/ClientRequest/http.get.d.ts +2 -3
  22. package/lib/interceptors/ClientRequest/http.get.js +2 -5
  23. package/lib/interceptors/ClientRequest/http.get.js.map +1 -1
  24. package/lib/interceptors/ClientRequest/http.request.d.ts +2 -3
  25. package/lib/interceptors/ClientRequest/http.request.js +3 -6
  26. package/lib/interceptors/ClientRequest/http.request.js.map +1 -1
  27. package/lib/interceptors/ClientRequest/index.d.ts +14 -4
  28. package/lib/interceptors/ClientRequest/index.js +59 -46
  29. package/lib/interceptors/ClientRequest/index.js.map +1 -1
  30. package/lib/interceptors/ClientRequest/utils/getIncomingMessageBody.js +7 -2
  31. package/lib/interceptors/ClientRequest/utils/getIncomingMessageBody.js.map +1 -1
  32. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestOverride.d.ts +11 -4
  33. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestOverride.js +110 -58
  34. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestOverride.js.map +1 -1
  35. package/lib/interceptors/XMLHttpRequest/index.d.ts +11 -5
  36. package/lib/interceptors/XMLHttpRequest/index.js +43 -25
  37. package/lib/interceptors/XMLHttpRequest/index.js.map +1 -1
  38. package/lib/interceptors/fetch/index.d.ts +8 -2
  39. package/lib/interceptors/fetch/index.js +120 -68
  40. package/lib/interceptors/fetch/index.js.map +1 -1
  41. package/lib/presets/browser.d.ts +3 -1
  42. package/lib/presets/browser.js +2 -2
  43. package/lib/presets/browser.js.map +1 -1
  44. package/lib/presets/node.d.ts +3 -1
  45. package/lib/presets/node.js +1 -1
  46. package/lib/presets/node.js.map +1 -1
  47. package/lib/utils/AsyncEventEmitter.d.ts +29 -0
  48. package/lib/utils/AsyncEventEmitter.js +241 -0
  49. package/lib/utils/AsyncEventEmitter.js.map +1 -0
  50. package/lib/utils/createLazyCallback.d.ts +11 -0
  51. package/lib/utils/createLazyCallback.js +75 -0
  52. package/lib/utils/createLazyCallback.js.map +1 -0
  53. package/lib/utils/nextTick.d.ts +2 -0
  54. package/lib/utils/nextTick.js +16 -0
  55. package/lib/utils/nextTick.js.map +1 -0
  56. package/lib/utils/toIsoResponse.d.ts +1 -1
  57. package/package.json +7 -7
  58. package/src/BatchInterceptor.test.ts +113 -0
  59. package/src/BatchInterceptor.ts +60 -0
  60. package/src/Interceptor.test.ts +166 -0
  61. package/src/Interceptor.ts +226 -0
  62. package/src/RemoteInterceptor.ts +176 -0
  63. package/src/glossary.ts +42 -0
  64. package/src/index.ts +2 -2
  65. package/src/interceptors/ClientRequest/NodeClientRequest.test.ts +87 -70
  66. package/src/interceptors/ClientRequest/NodeClientRequest.ts +150 -99
  67. package/src/interceptors/ClientRequest/http.get.ts +7 -11
  68. package/src/interceptors/ClientRequest/http.request.ts +8 -12
  69. package/src/interceptors/ClientRequest/index.test.ts +43 -0
  70. package/src/interceptors/ClientRequest/index.ts +46 -46
  71. package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts +9 -0
  72. package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts +9 -2
  73. package/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts +215 -159
  74. package/src/interceptors/XMLHttpRequest/index.ts +41 -23
  75. package/src/interceptors/fetch/index.ts +81 -55
  76. package/src/presets/browser.ts +3 -3
  77. package/src/presets/node.ts +3 -3
  78. package/src/utils/AsyncEventEmitter.test.ts +68 -0
  79. package/src/utils/AsyncEventEmitter.ts +171 -0
  80. package/src/utils/createLazyCallback.ts +49 -0
  81. package/src/utils/nextTick.ts +11 -0
  82. package/src/utils/toIsoResponse.ts +1 -1
  83. package/lib/createInterceptor.d.ts +0 -54
  84. package/lib/createInterceptor.js +0 -27
  85. package/lib/createInterceptor.js.map +0 -1
  86. package/lib/remote.d.ts +0 -21
  87. package/lib/remote.js +0 -178
  88. package/lib/remote.js.map +0 -1
  89. package/src/createInterceptor.ts +0 -100
  90. package/src/remote.ts +0 -174
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (_) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ var __read = (this && this.__read) || function (o, n) {
54
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
55
+ if (!m) return o;
56
+ var i = m.call(o), r, ar = [], e;
57
+ try {
58
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
59
+ }
60
+ catch (error) { e = { error: error }; }
61
+ finally {
62
+ try {
63
+ if (r && !r.done && (m = i["return"])) m.call(i);
64
+ }
65
+ finally { if (e) throw e.error; }
66
+ }
67
+ return ar;
68
+ };
69
+ var __spreadArray = (this && this.__spreadArray) || function (to, from) {
70
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
71
+ to[j] = from[i];
72
+ return to;
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.AsyncEventEmitter = exports.AsyncEventEmitterReadyState = void 0;
76
+ var debug_1 = require("debug");
77
+ var strict_event_emitter_1 = require("strict-event-emitter");
78
+ var nextTick_1 = require("./nextTick");
79
+ var AsyncEventEmitterReadyState;
80
+ (function (AsyncEventEmitterReadyState) {
81
+ AsyncEventEmitterReadyState["ACTIVE"] = "ACTIVE";
82
+ AsyncEventEmitterReadyState["DEACTIVATED"] = "DEACTIVATED";
83
+ })(AsyncEventEmitterReadyState = exports.AsyncEventEmitterReadyState || (exports.AsyncEventEmitterReadyState = {}));
84
+ var AsyncEventEmitter = /** @class */ (function (_super) {
85
+ __extends(AsyncEventEmitter, _super);
86
+ function AsyncEventEmitter() {
87
+ var _this = _super.call(this) || this;
88
+ _this.log = debug_1.debug('async-event-emitter');
89
+ _this.queue = new Map();
90
+ _this.readyState = AsyncEventEmitterReadyState.ACTIVE;
91
+ return _this;
92
+ }
93
+ AsyncEventEmitter.prototype.on = function (event, listener) {
94
+ var _this = this;
95
+ var log = this.log.extend('on');
96
+ log('adding "%s" listener...', event);
97
+ if (this.readyState === AsyncEventEmitterReadyState.DEACTIVATED) {
98
+ log('the emitter is destroyed, skipping!');
99
+ return this;
100
+ }
101
+ return _super.prototype.on.call(this, event, (function () {
102
+ var args = [];
103
+ for (var _i = 0; _i < arguments.length; _i++) {
104
+ args[_i] = arguments[_i];
105
+ }
106
+ return __awaiter(_this, void 0, void 0, function () {
107
+ var queue;
108
+ var _this = this;
109
+ return __generator(this, function (_a) {
110
+ queue = this.openListenerQueue(event);
111
+ log('awaiting the "%s" listener...', event);
112
+ // Whenever a listener is called, create a new Promise
113
+ // that resolves when that listener function completes its execution.
114
+ queue.push(new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
115
+ var error_1;
116
+ return __generator(this, function (_a) {
117
+ switch (_a.label) {
118
+ case 0:
119
+ _a.trys.push([0, 2, , 3]);
120
+ // Treat listeners as potentially asynchronous functions
121
+ // so they could be awaited.
122
+ return [4 /*yield*/, listener.apply(void 0, __spreadArray([], __read(args)))];
123
+ case 1:
124
+ // Treat listeners as potentially asynchronous functions
125
+ // so they could be awaited.
126
+ _a.sent();
127
+ resolve();
128
+ log('"%s" listener has resolved!', event);
129
+ return [3 /*break*/, 3];
130
+ case 2:
131
+ error_1 = _a.sent();
132
+ log('"%s" listener has rejected!', error_1);
133
+ reject(error_1);
134
+ return [3 /*break*/, 3];
135
+ case 3: return [2 /*return*/];
136
+ }
137
+ });
138
+ }); }));
139
+ return [2 /*return*/];
140
+ });
141
+ });
142
+ }));
143
+ };
144
+ AsyncEventEmitter.prototype.emit = function (event) {
145
+ var _this = this;
146
+ var args = [];
147
+ for (var _i = 1; _i < arguments.length; _i++) {
148
+ args[_i - 1] = arguments[_i];
149
+ }
150
+ var log = this.log.extend('emit');
151
+ log('emitting "%s" event...', event);
152
+ if (this.readyState === AsyncEventEmitterReadyState.DEACTIVATED) {
153
+ log('the emitter is destroyed, skipping!');
154
+ return false;
155
+ }
156
+ // Establish the Promise queue for this particular event.
157
+ this.openListenerQueue(event);
158
+ log('appending a one-time cleanup "%s" listener...', event);
159
+ // Append a one-time clean up listener.
160
+ this.once(event, (function () {
161
+ // Clear the Promise queue for this particular event
162
+ // in the next tick so the Promise in "untilIdle" has
163
+ // time to properly resolve.
164
+ nextTick_1.nextTick(function () {
165
+ _this.queue.delete(event);
166
+ log('cleaned up "%s" listeners queue!', event);
167
+ });
168
+ }));
169
+ return _super.prototype.emit.apply(this, __spreadArray([event], __read(args)));
170
+ };
171
+ /**
172
+ * Returns a promise that resolves when all the listeners for the given event
173
+ * has been called. Awaits asynchronous listeners.
174
+ * If the event has no listeners, resolves immediately.
175
+ */
176
+ AsyncEventEmitter.prototype.untilIdle = function (event) {
177
+ return __awaiter(this, void 0, void 0, function () {
178
+ var listenersQueue;
179
+ var _this = this;
180
+ return __generator(this, function (_a) {
181
+ switch (_a.label) {
182
+ case 0:
183
+ listenersQueue = this.queue.get(event) || [];
184
+ return [4 /*yield*/, Promise.all(listenersQueue).finally(function () {
185
+ // Clear the queue one the promise settles
186
+ // so that different events don't share the same queue.
187
+ _this.queue.delete(event);
188
+ })];
189
+ case 1:
190
+ _a.sent();
191
+ return [2 /*return*/];
192
+ }
193
+ });
194
+ });
195
+ };
196
+ AsyncEventEmitter.prototype.openListenerQueue = function (event) {
197
+ var log = this.log.extend('openListenerQueue');
198
+ log('opening "%s" listeners queue...', event);
199
+ var queue = this.queue.get(event);
200
+ if (!queue) {
201
+ log('no queue found, creating one...');
202
+ this.queue.set(event, []);
203
+ return [];
204
+ }
205
+ log('returning an exising queue:', queue);
206
+ return queue;
207
+ };
208
+ AsyncEventEmitter.prototype.removeAllListeners = function (event) {
209
+ var log = this.log.extend('removeAllListeners');
210
+ log('event:', event);
211
+ if (event) {
212
+ this.queue.delete(event);
213
+ log('cleared the "%s" listeners queue!', event, this.queue.get(event));
214
+ }
215
+ else {
216
+ this.queue.clear();
217
+ log('cleared the listeners queue!', this.queue);
218
+ }
219
+ return _super.prototype.removeAllListeners.call(this, event);
220
+ };
221
+ AsyncEventEmitter.prototype.activate = function () {
222
+ var log = this.log.extend('activate');
223
+ this.readyState = AsyncEventEmitterReadyState.ACTIVE;
224
+ log('set state to:', this.readyState);
225
+ };
226
+ /**
227
+ * Deactivate this event emitter.
228
+ * Deactivated emitter can no longer emit and listen to events
229
+ * and needs to be activated again in order to do so.
230
+ */
231
+ AsyncEventEmitter.prototype.deactivate = function () {
232
+ var log = this.log.extend('deactivate');
233
+ log('removing all listeners...');
234
+ this.removeAllListeners();
235
+ this.readyState = AsyncEventEmitterReadyState.DEACTIVATED;
236
+ log('set state to:', this.readyState);
237
+ };
238
+ return AsyncEventEmitter;
239
+ }(strict_event_emitter_1.StrictEventEmitter));
240
+ exports.AsyncEventEmitter = AsyncEventEmitter;
241
+ //# sourceMappingURL=AsyncEventEmitter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AsyncEventEmitter.js","sourceRoot":"","sources":["../../src/utils/AsyncEventEmitter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+BAAuC;AACvC,6DAAuE;AACvE,uCAAqC;AAIrC,IAAY,2BAGX;AAHD,WAAY,2BAA2B;IACrC,gDAAiB,CAAA;IACjB,0DAA2B,CAAA;AAC7B,CAAC,EAHW,2BAA2B,GAA3B,mCAA2B,KAA3B,mCAA2B,QAGtC;AAED;IAEU,qCAA4B;IAMpC;QAAA,YACE,iBAAO,SAMR;QAJC,KAAI,CAAC,GAAG,GAAG,aAAK,CAAC,qBAAqB,CAAC,CAAA;QACvC,KAAI,CAAC,KAAK,GAAG,IAAI,GAAG,EAAE,CAAA;QAEtB,KAAI,CAAC,UAAU,GAAG,2BAA2B,CAAC,MAAM,CAAA;;IACtD,CAAC;IAEM,8BAAE,GAAT,UACE,KAAY,EACZ,QAAyB;QAF3B,iBAqCC;QAjCC,IAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAEjC,GAAG,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAA;QAErC,IAAI,IAAI,CAAC,UAAU,K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,8CAAiB"}
@@ -0,0 +1,11 @@
1
+ export declare type AnyFunction = (...args: any[]) => any;
2
+ export declare type LazyCallbackReturnType<FnType extends AnyFunction> = Parameters<FnType> | [];
3
+ export interface LazyCallback<FnType extends AnyFunction> {
4
+ (...args: Parameters<FnType>): void;
5
+ invoked(): Promise<LazyCallbackReturnType<FnType>>;
6
+ }
7
+ export interface LazyCallbackOptions {
8
+ maxCalls?: number;
9
+ maxCallsCallback?(): void;
10
+ }
11
+ export declare function createLazyCallback<FnType extends AnyFunction>(options?: LazyCallbackOptions): LazyCallback<FnType>;
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.createLazyCallback = void 0;
40
+ function createLazyCallback(options) {
41
+ var _this = this;
42
+ if (options === void 0) { options = {}; }
43
+ var calledTimes = 0;
44
+ var autoResolveTimeout;
45
+ var remoteResolve;
46
+ var callPromise = new Promise(function (resolve) {
47
+ remoteResolve = resolve;
48
+ }).finally(function () {
49
+ clearTimeout(autoResolveTimeout);
50
+ });
51
+ var fn = function () {
52
+ var _a;
53
+ var args = [];
54
+ for (var _i = 0; _i < arguments.length; _i++) {
55
+ args[_i] = arguments[_i];
56
+ }
57
+ if (options.maxCalls && calledTimes >= options.maxCalls) {
58
+ (_a = options.maxCallsCallback) === null || _a === void 0 ? void 0 : _a.call(options);
59
+ }
60
+ remoteResolve(args);
61
+ calledTimes++;
62
+ };
63
+ fn.invoked = function () { return __awaiter(_this, void 0, void 0, function () {
64
+ return __generator(this, function (_a) {
65
+ // Immediately resolve the callback if it hasn't been called already.
66
+ autoResolveTimeout = setTimeout(function () {
67
+ remoteResolve([]);
68
+ }, 0);
69
+ return [2 /*return*/, callPromise];
70
+ });
71
+ }); };
72
+ return fn;
73
+ }
74
+ exports.createLazyCallback = createLazyCallback;
75
+ //# sourceMappingURL=createLazyCallback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createLazyCallback.js","sourceRoot":"","sources":["../../src/utils/createLazyCallback.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAAkB,CAChC,OAAiC;IADnC,iBAgCC;IA/BC,wBAAA,EAAA,YAAiC;IAEjC,IAAI,WAAW,GAAG,CAAC,CAAA;IACnB,IAAI,kBAAkC,CAAA;IACtC,IAAI,aAAgE,CAAA;IAEpE,IAAM,WAAW,GAAG,IAAI,OAAO,CAAiC,UAAC,OAAO;QACtE,aAAa,GAAG,OAAO,CAAA;IACzB,CAAC,CAAC,CAAC,OAAO,CAAC;QACT,YAAY,CAAC,kBAAkB,CAAC,CAAA;IAClC,CAAC,CAAC,CAAA;IAEF,IAAM,EAAE,GAAyB;;QAAU,cAAO;aAAP,UAAO,EAAP,qBAAO,EAAP,IAAO;YAAP,yBAAO;;QAChD,IAAI,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,OAAO,CAAC,QAAQ,EAAE;YACvD,MAAA,OAAO,CAAC,gBAAgB,+CAAxB,OAAO,CAAqB,CAAA;SAC7B;QAED,aAAa,CAAC,IAAI,CAAC,CAAA;QACnB,WAAW,EAAE,CAAA;IACf,CAAC,CAAA;IAED,EAAE,CAAC,OAAO,GAAG;;YACX,qEAAqE;YACrE,kBAAkB,GAAG,UAAU,CAAC;gBAC9B,aAAa,CAAC,EAAE,CAAC,CAAA;YACnB,CAAC,EAAE,CAAC,CAAC,CAAA;YAEL,sBAAO,WAAW,EAAA;;SACnB,CAAA;IAED,OAAO,EAAE,CAAA;AACX,CAAC;AAhCD,gDAgCC"}
@@ -0,0 +1,2 @@
1
+ export declare function nextTick(callback: () => void): void;
2
+ export declare function nextTickAsync(callback: () => void): Promise<unknown>;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.nextTickAsync = exports.nextTick = void 0;
4
+ function nextTick(callback) {
5
+ setTimeout(callback, 0);
6
+ }
7
+ exports.nextTick = nextTick;
8
+ function nextTickAsync(callback) {
9
+ return new Promise(function (resolve) {
10
+ setTimeout(function () {
11
+ resolve(callback());
12
+ }, 0);
13
+ });
14
+ }
15
+ exports.nextTickAsync = nextTickAsync;
16
+ //# sourceMappingURL=nextTick.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nextTick.js","sourceRoot":"","sources":["../../src/utils/nextTick.ts"],"names":[],"mappings":";;;AAAA,SAAgB,QAAQ,CAAC,QAAoB;IAC3C,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;AACzB,CAAC;AAFD,4BAEC;AAED,SAAgB,aAAa,CAAC,QAAoB;IAChD,OAAO,IAAI,OAAO,CAAC,UAAC,OAAO;QACzB,UAAU,CAAC;YACT,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAA;QACrB,CAAC,EAAE,CAAC,CAAC,CAAA;IACP,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,sCAMC"}
@@ -1,4 +1,4 @@
1
- import { IsomorphicResponse, MockedResponse } from '../createInterceptor';
1
+ import { IsomorphicResponse, MockedResponse } from '../glossary';
2
2
  /**
3
3
  * Converts a given mocked response object into an isomorphic response.
4
4
  */
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@mswjs/interceptors",
3
3
  "description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.",
4
- "version": "0.14.1",
4
+ "version": "0.15.2",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "author": "Artem Zakharchenko",
8
8
  "license": "MIT",
9
9
  "engines": {
10
- "node": ">=16.x"
10
+ "node": ">=14"
11
11
  },
12
12
  "scripts": {
13
13
  "start": "tsc --build -w",
@@ -19,7 +19,7 @@
19
19
  "clean": "rimraf lib",
20
20
  "build": "yarn clean && tsc --build",
21
21
  "prepare": "yarn simple-git-hooks init",
22
- "release": "semantic-release",
22
+ "release": "release publish",
23
23
  "prepublishOnly": "yarn build && yarn test"
24
24
  },
25
25
  "files": [
@@ -34,7 +34,8 @@
34
34
  "devDependencies": {
35
35
  "@commitlint/cli": "^16.0.2",
36
36
  "@commitlint/config-conventional": "^16.0.0",
37
- "@open-draft/test-server": "^0.2.3",
37
+ "@open-draft/test-server": "^0.4.2",
38
+ "@ossjs/release": "^0.3.0",
38
39
  "@types/cors": "^2.8.12",
39
40
  "@types/express": "^4.17.13",
40
41
  "@types/express-rate-limit": "^6.0.0",
@@ -55,7 +56,6 @@
55
56
  "node-fetch": "2.6.7",
56
57
  "page-with": "^0.5.1",
57
58
  "rimraf": "^3.0.2",
58
- "semantic-release": "^19.0.2",
59
59
  "simple-git-hooks": "^2.7.0",
60
60
  "superagent": "^6.1.0",
61
61
  "supertest": "^6.1.6",
@@ -69,7 +69,7 @@
69
69
  "debug": "^4.3.3",
70
70
  "headers-polyfill": "^3.0.4",
71
71
  "outvariant": "^1.2.1",
72
- "strict-event-emitter": "^0.2.0"
72
+ "strict-event-emitter": "^0.2.4"
73
73
  },
74
74
  "keywords": [
75
75
  "request",
@@ -87,4 +87,4 @@
87
87
  "path": "./node_modules/cz-conventional-changelog"
88
88
  }
89
89
  }
90
- }
90
+ }
@@ -0,0 +1,113 @@
1
+ import { Interceptor } from './Interceptor'
2
+ import { BatchInterceptor } from './BatchInterceptor'
3
+
4
+ afterEach(() => {
5
+ jest.resetAllMocks()
6
+ })
7
+
8
+ it('applies child interceptors', () => {
9
+ class PrimaryInterceptor extends Interceptor<any> {
10
+ constructor() {
11
+ super(Symbol('primary'))
12
+ }
13
+ }
14
+
15
+ class SecondaryInterceptor extends Interceptor<any> {
16
+ constructor() {
17
+ super(Symbol('secondary'))
18
+ }
19
+ }
20
+
21
+ const instances = {
22
+ primary: new PrimaryInterceptor(),
23
+ secondary: new SecondaryInterceptor(),
24
+ }
25
+
26
+ const interceptor = new BatchInterceptor({
27
+ name: 'batch-apply',
28
+ interceptors: [instances.primary, instances.secondary],
29
+ })
30
+
31
+ const primaryApplySpy = jest.spyOn(instances.primary, 'apply')
32
+ const secondaryApplySpy = jest.spyOn(instances.secondary, 'apply')
33
+
34
+ interceptor.apply()
35
+
36
+ expect(primaryApplySpy).toHaveBeenCalledTimes(1)
37
+ expect(secondaryApplySpy).toHaveBeenCalledTimes(1)
38
+ })
39
+
40
+ it('proxies event listeners to the interceptors', () => {
41
+ class PrimaryInterceptor extends Interceptor<{ hello(name: string): void }> {
42
+ constructor() {
43
+ super(Symbol('primary'))
44
+ }
45
+ }
46
+
47
+ class SecondaryInterceptor extends Interceptor<{
48
+ goodbye(name: string): void
49
+ }> {
50
+ constructor() {
51
+ super(Symbol('secondary'))
52
+ }
53
+ }
54
+
55
+ const instances = {
56
+ primary: new PrimaryInterceptor(),
57
+ secondary: new SecondaryInterceptor(),
58
+ }
59
+
60
+ const interceptor = new BatchInterceptor({
61
+ name: 'batch-proxy',
62
+ interceptors: [instances.primary, instances.secondary],
63
+ })
64
+
65
+ const helloListener = jest.fn()
66
+ interceptor.on('hello', helloListener)
67
+
68
+ const goodbyeListener = jest.fn()
69
+ interceptor.on('goodbye', goodbyeListener)
70
+
71
+ // Emulate the child interceptor emitting events.
72
+ instances.primary['emitter'].emit('hello', 'John')
73
+ instances.secondary['emitter'].emit('goodbye', 'Kate')
74
+
75
+ // Must call the batch interceptor listener.
76
+ expect(helloListener).toHaveBeenCalledTimes(1)
77
+ expect(helloListener).toHaveBeenCalledWith('John')
78
+ expect(goodbyeListener).toHaveBeenCalledTimes(1)
79
+ expect(goodbyeListener).toHaveBeenCalledWith('Kate')
80
+ })
81
+
82
+ it('disposes of child interceptors', async () => {
83
+ class PrimaryInterceptor extends Interceptor<never> {
84
+ constructor() {
85
+ super(Symbol('primary'))
86
+ }
87
+ }
88
+
89
+ class SecondaryInterceptor extends Interceptor<never> {
90
+ constructor() {
91
+ super(Symbol('secondary'))
92
+ }
93
+ }
94
+
95
+ const instances = {
96
+ primary: new PrimaryInterceptor(),
97
+ secondary: new SecondaryInterceptor(),
98
+ }
99
+
100
+ const interceptor = new BatchInterceptor({
101
+ name: 'batch-dispose',
102
+ interceptors: [instances.primary, instances.secondary],
103
+ })
104
+
105
+ const primaryDisposeSpy = jest.spyOn(instances.primary, 'dispose')
106
+ const secondaryDisposeSpy = jest.spyOn(instances.secondary, 'dispose')
107
+
108
+ interceptor.apply()
109
+ interceptor.dispose()
110
+
111
+ expect(primaryDisposeSpy).toHaveBeenCalledTimes(1)
112
+ expect(secondaryDisposeSpy).toHaveBeenCalledTimes(1)
113
+ })
@@ -0,0 +1,60 @@
1
+ import { EventMapType } from 'strict-event-emitter'
2
+ import { ExtractEventNames, Interceptor } from './Interceptor'
3
+
4
+ export interface BatchInterceptorOptions<
5
+ InterceptorList extends Interceptor<any>[]
6
+ > {
7
+ name: string
8
+ interceptors: InterceptorList
9
+ }
10
+
11
+ export type ExtractEventMapType<InterceptorList extends Interceptor<any>[]> =
12
+ InterceptorList extends Array<infer InterceptorType>
13
+ ? InterceptorType extends Interceptor<infer EventMap>
14
+ ? EventMap
15
+ : never
16
+ : never
17
+
18
+ /**
19
+ * A batch interceptor that exposes a single interface
20
+ * to apply and operate with multiple interceptors at once.
21
+ */
22
+ export class BatchInterceptor<
23
+ InterceptorList extends Interceptor<any>[],
24
+ EventMap extends EventMapType = ExtractEventMapType<InterceptorList>
25
+ > extends Interceptor<EventMap> {
26
+ static symbol: Symbol
27
+
28
+ private interceptors: InterceptorList
29
+
30
+ constructor(options: BatchInterceptorOptions<InterceptorList>) {
31
+ BatchInterceptor.symbol = Symbol(options.name)
32
+ super(BatchInterceptor.symbol)
33
+ this.interceptors = options.interceptors
34
+ }
35
+
36
+ protected setup() {
37
+ const log = this.log.extend('setup')
38
+
39
+ log('applying all %d interceptors...', this.interceptors.length)
40
+
41
+ for (const interceptor of this.interceptors) {
42
+ log('applying "%s" interceptor...', interceptor.constructor.name)
43
+ interceptor.apply()
44
+
45
+ log('adding interceptor dispose subscription')
46
+ this.subscriptions.push(() => interceptor.dispose())
47
+ }
48
+ }
49
+
50
+ public on<Event extends ExtractEventNames<EventMap>>(
51
+ event: Event,
52
+ listener: EventMap[Event]
53
+ ) {
54
+ // Instead of adding a listener to the batch interceptor,
55
+ // propagate the listener to each of the individual interceptors.
56
+ this.interceptors.forEach((interceptor) => {
57
+ interceptor.on(event, listener)
58
+ })
59
+ }
60
+ }