msw 0.40.2 → 0.42.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/config/constants.js +1 -3
- package/config/scripts/postinstall.js +32 -25
- package/lib/glossary-58eca5a8.d.ts +332 -0
- package/lib/iife/index.js +10911 -21
- package/lib/iife/index.js.map +1 -0
- package/lib/index.d.ts +353 -0
- package/lib/index.js +1875 -0
- package/lib/index.js.map +1 -0
- package/lib/{esm/mockServiceWorker.js → mockServiceWorker.js} +1 -1
- package/lib/native/index.d.ts +9 -0
- package/lib/native/index.js +1304 -0
- package/lib/native/index.mjs +1291 -0
- package/lib/node/index.d.ts +15 -0
- package/lib/node/index.js +1312 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/index.mjs +1297 -0
- package/lib/node/index.mjs.map +1 -0
- package/native/package.json +3 -2
- package/node/package.json +3 -2
- package/package.json +14 -24
- package/lib/esm/errors-deps.js +0 -74
- package/lib/esm/fetch-deps.js +0 -1005
- package/lib/esm/graphql-deps.js +0 -3545
- package/lib/esm/graphql.js +0 -5
- package/lib/esm/index-deps.js +0 -21
- package/lib/esm/index.js +0 -1731
- package/lib/esm/index2.js +0 -3
- package/lib/esm/matchRequestUrl-deps.js +0 -992
- package/lib/esm/rest-deps.js +0 -103
- package/lib/esm/rest.js +0 -5
- package/lib/esm/xml-deps.js +0 -44
- package/lib/iife/mockServiceWorker.js +0 -338
- package/lib/types/context/body.d.ts +0 -9
- package/lib/types/context/cookie.d.ts +0 -7
- package/lib/types/context/data.d.ts +0 -8
- package/lib/types/context/delay.d.ts +0 -15
- package/lib/types/context/errors.d.ts +0 -8
- package/lib/types/context/extensions.d.ts +0 -8
- package/lib/types/context/fetch.d.ts +0 -9
- package/lib/types/context/index.d.ts +0 -12
- package/lib/types/context/json.d.ts +0 -12
- package/lib/types/context/set.d.ts +0 -18
- package/lib/types/context/status.d.ts +0 -9
- package/lib/types/context/text.d.ts +0 -8
- package/lib/types/context/xml.d.ts +0 -9
- package/lib/types/graphql.d.ts +0 -74
- package/lib/types/handlers/GraphQLHandler.d.ts +0 -39
- package/lib/types/handlers/RequestHandler.d.ts +0 -103
- package/lib/types/handlers/RestHandler.d.ts +0 -47
- package/lib/types/index.d.ts +0 -26
- package/lib/types/native/index.d.ts +0 -1
- package/lib/types/node/createSetupServer.d.ts +0 -8
- package/lib/types/node/glossary.d.ts +0 -38
- package/lib/types/node/index.d.ts +0 -2
- package/lib/types/node/setupServer.d.ts +0 -6
- package/lib/types/response.d.ts +0 -35
- package/lib/types/rest.d.ts +0 -13
- package/lib/types/setupWorker/glossary.d.ts +0 -161
- package/lib/types/setupWorker/setupWorker.d.ts +0 -9
- package/lib/types/setupWorker/start/createFallbackStart.d.ts +0 -2
- package/lib/types/setupWorker/start/createStartHandler.d.ts +0 -2
- package/lib/types/setupWorker/start/utils/enableMocking.d.ts +0 -5
- package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +0 -6
- package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +0 -6
- package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +0 -9
- package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +0 -10
- package/lib/types/setupWorker/start/utils/validateWorkerScope.d.ts +0 -2
- package/lib/types/setupWorker/stop/createFallbackStop.d.ts +0 -2
- package/lib/types/setupWorker/stop/createStop.d.ts +0 -2
- package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +0 -3
- package/lib/types/sharedOptions.d.ts +0 -24
- package/lib/types/typeUtils.d.ts +0 -7
- package/lib/types/utils/NetworkError.d.ts +0 -3
- package/lib/types/utils/createBroadcastChannel.d.ts +0 -18
- package/lib/types/utils/deferNetworkRequestsUntil.d.ts +0 -6
- package/lib/types/utils/getResponse.d.ts +0 -15
- package/lib/types/utils/handleRequest.d.ts +0 -34
- package/lib/types/utils/internal/compose.d.ts +0 -14
- package/lib/types/utils/internal/devUtils.d.ts +0 -18
- package/lib/types/utils/internal/getCallFrame.d.ts +0 -4
- package/lib/types/utils/internal/isIterable.d.ts +0 -4
- package/lib/types/utils/internal/isObject.d.ts +0 -4
- package/lib/types/utils/internal/isStringEqual.d.ts +0 -4
- package/lib/types/utils/internal/jsonParse.d.ts +0 -5
- package/lib/types/utils/internal/mergeRight.d.ts +0 -5
- package/lib/types/utils/internal/parseGraphQLRequest.d.ts +0 -23
- package/lib/types/utils/internal/parseMultipartData.d.ts +0 -6
- package/lib/types/utils/internal/pipeEvents.d.ts +0 -6
- package/lib/types/utils/internal/requestHandlerUtils.d.ts +0 -4
- package/lib/types/utils/internal/requestIntegrityCheck.d.ts +0 -2
- package/lib/types/utils/internal/tryCatch.d.ts +0 -1
- package/lib/types/utils/internal/uuidv4.d.ts +0 -1
- package/lib/types/utils/logging/getStatusCodeColor.d.ts +0 -9
- package/lib/types/utils/logging/getTimestamp.d.ts +0 -4
- package/lib/types/utils/logging/prepareRequest.d.ts +0 -23
- package/lib/types/utils/logging/prepareResponse.d.ts +0 -10
- package/lib/types/utils/matching/matchRequestUrl.d.ts +0 -17
- package/lib/types/utils/matching/normalizePath.d.ts +0 -9
- package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +0 -6
- package/lib/types/utils/request/getRequestCookies.d.ts +0 -7
- package/lib/types/utils/request/onUnhandledRequest.d.ts +0 -8
- package/lib/types/utils/request/parseBody.d.ts +0 -5
- package/lib/types/utils/request/parseIsomorphicRequest.d.ts +0 -6
- package/lib/types/utils/request/parseWorkerRequest.d.ts +0 -7
- package/lib/types/utils/request/pruneGetRequestBody.d.ts +0 -7
- package/lib/types/utils/request/readResponseCookies.d.ts +0 -3
- package/lib/types/utils/request/setRequestCookies.d.ts +0 -9
- package/lib/types/utils/url/cleanUrl.d.ts +0 -5
- package/lib/types/utils/url/getAbsoluteUrl.d.ts +0 -4
- package/lib/types/utils/url/getAbsoluteWorkerUrl.d.ts +0 -5
- package/lib/types/utils/url/isAbsoluteUrl.d.ts +0 -4
- package/lib/types/utils/worker/createFallbackRequestListener.d.ts +0 -4
- package/lib/types/utils/worker/createRequestListener.d.ts +0 -4
- package/lib/types/utils/worker/createResponseListener.d.ts +0 -3
- package/lib/umd/index.js +0 -31617
- package/lib/umd/mockServiceWorker.js +0 -338
- package/native/lib/index.js +0 -6384
- package/node/lib/index.js +0 -8276
package/lib/esm/index.js
DELETED
|
@@ -1,1731 +0,0 @@
|
|
|
1
|
-
export { i as context } from './index-deps.js';
|
|
2
|
-
import { c as commonjsGlobal, p as parse_1, l as lib$2, a as lib$3, j as jsonParse } from './fetch-deps.js';
|
|
3
|
-
import { _ as __awaiter, d as devUtils, p as passthrough, a as parseBody, g as getPublicUrlFromRequest, N as NetworkError } from './matchRequestUrl-deps.js';
|
|
4
|
-
export { R as RequestHandler, h as cleanUrl, f as compose, c as createResponseComposition, e as defaultContext, b as defaultResponse, m as matchRequestUrl, r as response } from './matchRequestUrl-deps.js';
|
|
5
|
-
import { store } from '@mswjs/cookies';
|
|
6
|
-
import { i as isStringEqual, R as RestHandler } from './rest-deps.js';
|
|
7
|
-
export { a as RESTMethods, R as RestHandler, r as rest, b as restContext } from './rest-deps.js';
|
|
8
|
-
import { t as tryCatch, p as parseGraphQLRequest, G as GraphQLHandler } from './graphql-deps.js';
|
|
9
|
-
export { G as GraphQLHandler, g as graphql, a as graphqlContext } from './graphql-deps.js';
|
|
10
|
-
import { m as mergeRight } from './errors-deps.js';
|
|
11
|
-
import { createInterceptor } from '@mswjs/interceptors';
|
|
12
|
-
import { interceptFetch } from '@mswjs/interceptors/lib/interceptors/fetch';
|
|
13
|
-
import { interceptXMLHttpRequest } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest';
|
|
14
|
-
import './xml-deps.js';
|
|
15
|
-
import '@mswjs/interceptors/lib/utils/getCleanUrl';
|
|
16
|
-
|
|
17
|
-
var lib$1 = {};
|
|
18
|
-
|
|
19
|
-
var StrictEventEmitter$1 = {};
|
|
20
|
-
|
|
21
|
-
var events = {exports: {}};
|
|
22
|
-
|
|
23
|
-
var R = typeof Reflect === 'object' ? Reflect : null;
|
|
24
|
-
var ReflectApply = R && typeof R.apply === 'function'
|
|
25
|
-
? R.apply
|
|
26
|
-
: function ReflectApply(target, receiver, args) {
|
|
27
|
-
return Function.prototype.apply.call(target, receiver, args);
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
var ReflectOwnKeys;
|
|
31
|
-
if (R && typeof R.ownKeys === 'function') {
|
|
32
|
-
ReflectOwnKeys = R.ownKeys;
|
|
33
|
-
} else if (Object.getOwnPropertySymbols) {
|
|
34
|
-
ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
35
|
-
return Object.getOwnPropertyNames(target)
|
|
36
|
-
.concat(Object.getOwnPropertySymbols(target));
|
|
37
|
-
};
|
|
38
|
-
} else {
|
|
39
|
-
ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
40
|
-
return Object.getOwnPropertyNames(target);
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function ProcessEmitWarning(warning) {
|
|
45
|
-
if (console && console.warn) console.warn(warning);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
|
|
49
|
-
return value !== value;
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
function EventEmitter() {
|
|
53
|
-
EventEmitter.init.call(this);
|
|
54
|
-
}
|
|
55
|
-
events.exports = EventEmitter;
|
|
56
|
-
events.exports.once = once;
|
|
57
|
-
|
|
58
|
-
// Backwards-compat with node 0.10.x
|
|
59
|
-
EventEmitter.EventEmitter = EventEmitter;
|
|
60
|
-
|
|
61
|
-
EventEmitter.prototype._events = undefined;
|
|
62
|
-
EventEmitter.prototype._eventsCount = 0;
|
|
63
|
-
EventEmitter.prototype._maxListeners = undefined;
|
|
64
|
-
|
|
65
|
-
// By default EventEmitters will print a warning if more than 10 listeners are
|
|
66
|
-
// added to it. This is a useful default which helps finding memory leaks.
|
|
67
|
-
var defaultMaxListeners = 10;
|
|
68
|
-
|
|
69
|
-
function checkListener(listener) {
|
|
70
|
-
if (typeof listener !== 'function') {
|
|
71
|
-
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
|
|
76
|
-
enumerable: true,
|
|
77
|
-
get: function() {
|
|
78
|
-
return defaultMaxListeners;
|
|
79
|
-
},
|
|
80
|
-
set: function(arg) {
|
|
81
|
-
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
|
|
82
|
-
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
|
|
83
|
-
}
|
|
84
|
-
defaultMaxListeners = arg;
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
EventEmitter.init = function() {
|
|
89
|
-
|
|
90
|
-
if (this._events === undefined ||
|
|
91
|
-
this._events === Object.getPrototypeOf(this)._events) {
|
|
92
|
-
this._events = Object.create(null);
|
|
93
|
-
this._eventsCount = 0;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
this._maxListeners = this._maxListeners || undefined;
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
// Obviously not all Emitters should be limited to 10. This function allows
|
|
100
|
-
// that to be increased. Set to zero for unlimited.
|
|
101
|
-
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
|
|
102
|
-
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
|
|
103
|
-
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
|
|
104
|
-
}
|
|
105
|
-
this._maxListeners = n;
|
|
106
|
-
return this;
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
function _getMaxListeners(that) {
|
|
110
|
-
if (that._maxListeners === undefined)
|
|
111
|
-
return EventEmitter.defaultMaxListeners;
|
|
112
|
-
return that._maxListeners;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
|
116
|
-
return _getMaxListeners(this);
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
EventEmitter.prototype.emit = function emit(type) {
|
|
120
|
-
var args = [];
|
|
121
|
-
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
|
|
122
|
-
var doError = (type === 'error');
|
|
123
|
-
|
|
124
|
-
var events = this._events;
|
|
125
|
-
if (events !== undefined)
|
|
126
|
-
doError = (doError && events.error === undefined);
|
|
127
|
-
else if (!doError)
|
|
128
|
-
return false;
|
|
129
|
-
|
|
130
|
-
// If there is no 'error' event listener then throw.
|
|
131
|
-
if (doError) {
|
|
132
|
-
var er;
|
|
133
|
-
if (args.length > 0)
|
|
134
|
-
er = args[0];
|
|
135
|
-
if (er instanceof Error) {
|
|
136
|
-
// Note: The comments on the `throw` lines are intentional, they show
|
|
137
|
-
// up in Node's output if this results in an unhandled exception.
|
|
138
|
-
throw er; // Unhandled 'error' event
|
|
139
|
-
}
|
|
140
|
-
// At least give some kind of context to the user
|
|
141
|
-
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
|
|
142
|
-
err.context = er;
|
|
143
|
-
throw err; // Unhandled 'error' event
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
var handler = events[type];
|
|
147
|
-
|
|
148
|
-
if (handler === undefined)
|
|
149
|
-
return false;
|
|
150
|
-
|
|
151
|
-
if (typeof handler === 'function') {
|
|
152
|
-
ReflectApply(handler, this, args);
|
|
153
|
-
} else {
|
|
154
|
-
var len = handler.length;
|
|
155
|
-
var listeners = arrayClone(handler, len);
|
|
156
|
-
for (var i = 0; i < len; ++i)
|
|
157
|
-
ReflectApply(listeners[i], this, args);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
return true;
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
function _addListener(target, type, listener, prepend) {
|
|
164
|
-
var m;
|
|
165
|
-
var events;
|
|
166
|
-
var existing;
|
|
167
|
-
|
|
168
|
-
checkListener(listener);
|
|
169
|
-
|
|
170
|
-
events = target._events;
|
|
171
|
-
if (events === undefined) {
|
|
172
|
-
events = target._events = Object.create(null);
|
|
173
|
-
target._eventsCount = 0;
|
|
174
|
-
} else {
|
|
175
|
-
// To avoid recursion in the case that type === "newListener"! Before
|
|
176
|
-
// adding it to the listeners, first emit "newListener".
|
|
177
|
-
if (events.newListener !== undefined) {
|
|
178
|
-
target.emit('newListener', type,
|
|
179
|
-
listener.listener ? listener.listener : listener);
|
|
180
|
-
|
|
181
|
-
// Re-assign `events` because a newListener handler could have caused the
|
|
182
|
-
// this._events to be assigned to a new object
|
|
183
|
-
events = target._events;
|
|
184
|
-
}
|
|
185
|
-
existing = events[type];
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
if (existing === undefined) {
|
|
189
|
-
// Optimize the case of one listener. Don't need the extra array object.
|
|
190
|
-
existing = events[type] = listener;
|
|
191
|
-
++target._eventsCount;
|
|
192
|
-
} else {
|
|
193
|
-
if (typeof existing === 'function') {
|
|
194
|
-
// Adding the second element, need to change to array.
|
|
195
|
-
existing = events[type] =
|
|
196
|
-
prepend ? [listener, existing] : [existing, listener];
|
|
197
|
-
// If we've already got an array, just append.
|
|
198
|
-
} else if (prepend) {
|
|
199
|
-
existing.unshift(listener);
|
|
200
|
-
} else {
|
|
201
|
-
existing.push(listener);
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
// Check for listener leak
|
|
205
|
-
m = _getMaxListeners(target);
|
|
206
|
-
if (m > 0 && existing.length > m && !existing.warned) {
|
|
207
|
-
existing.warned = true;
|
|
208
|
-
// No error code for this since it is a Warning
|
|
209
|
-
// eslint-disable-next-line no-restricted-syntax
|
|
210
|
-
var w = new Error('Possible EventEmitter memory leak detected. ' +
|
|
211
|
-
existing.length + ' ' + String(type) + ' listeners ' +
|
|
212
|
-
'added. Use emitter.setMaxListeners() to ' +
|
|
213
|
-
'increase limit');
|
|
214
|
-
w.name = 'MaxListenersExceededWarning';
|
|
215
|
-
w.emitter = target;
|
|
216
|
-
w.type = type;
|
|
217
|
-
w.count = existing.length;
|
|
218
|
-
ProcessEmitWarning(w);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
return target;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
|
226
|
-
return _addListener(this, type, listener, false);
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
|
230
|
-
|
|
231
|
-
EventEmitter.prototype.prependListener =
|
|
232
|
-
function prependListener(type, listener) {
|
|
233
|
-
return _addListener(this, type, listener, true);
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
function onceWrapper() {
|
|
237
|
-
if (!this.fired) {
|
|
238
|
-
this.target.removeListener(this.type, this.wrapFn);
|
|
239
|
-
this.fired = true;
|
|
240
|
-
if (arguments.length === 0)
|
|
241
|
-
return this.listener.call(this.target);
|
|
242
|
-
return this.listener.apply(this.target, arguments);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
function _onceWrap(target, type, listener) {
|
|
247
|
-
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
|
|
248
|
-
var wrapped = onceWrapper.bind(state);
|
|
249
|
-
wrapped.listener = listener;
|
|
250
|
-
state.wrapFn = wrapped;
|
|
251
|
-
return wrapped;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
EventEmitter.prototype.once = function once(type, listener) {
|
|
255
|
-
checkListener(listener);
|
|
256
|
-
this.on(type, _onceWrap(this, type, listener));
|
|
257
|
-
return this;
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
EventEmitter.prototype.prependOnceListener =
|
|
261
|
-
function prependOnceListener(type, listener) {
|
|
262
|
-
checkListener(listener);
|
|
263
|
-
this.prependListener(type, _onceWrap(this, type, listener));
|
|
264
|
-
return this;
|
|
265
|
-
};
|
|
266
|
-
|
|
267
|
-
// Emits a 'removeListener' event if and only if the listener was removed.
|
|
268
|
-
EventEmitter.prototype.removeListener =
|
|
269
|
-
function removeListener(type, listener) {
|
|
270
|
-
var list, events, position, i, originalListener;
|
|
271
|
-
|
|
272
|
-
checkListener(listener);
|
|
273
|
-
|
|
274
|
-
events = this._events;
|
|
275
|
-
if (events === undefined)
|
|
276
|
-
return this;
|
|
277
|
-
|
|
278
|
-
list = events[type];
|
|
279
|
-
if (list === undefined)
|
|
280
|
-
return this;
|
|
281
|
-
|
|
282
|
-
if (list === listener || list.listener === listener) {
|
|
283
|
-
if (--this._eventsCount === 0)
|
|
284
|
-
this._events = Object.create(null);
|
|
285
|
-
else {
|
|
286
|
-
delete events[type];
|
|
287
|
-
if (events.removeListener)
|
|
288
|
-
this.emit('removeListener', type, list.listener || listener);
|
|
289
|
-
}
|
|
290
|
-
} else if (typeof list !== 'function') {
|
|
291
|
-
position = -1;
|
|
292
|
-
|
|
293
|
-
for (i = list.length - 1; i >= 0; i--) {
|
|
294
|
-
if (list[i] === listener || list[i].listener === listener) {
|
|
295
|
-
originalListener = list[i].listener;
|
|
296
|
-
position = i;
|
|
297
|
-
break;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
if (position < 0)
|
|
302
|
-
return this;
|
|
303
|
-
|
|
304
|
-
if (position === 0)
|
|
305
|
-
list.shift();
|
|
306
|
-
else {
|
|
307
|
-
spliceOne(list, position);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
if (list.length === 1)
|
|
311
|
-
events[type] = list[0];
|
|
312
|
-
|
|
313
|
-
if (events.removeListener !== undefined)
|
|
314
|
-
this.emit('removeListener', type, originalListener || listener);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
return this;
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
|
321
|
-
|
|
322
|
-
EventEmitter.prototype.removeAllListeners =
|
|
323
|
-
function removeAllListeners(type) {
|
|
324
|
-
var listeners, events, i;
|
|
325
|
-
|
|
326
|
-
events = this._events;
|
|
327
|
-
if (events === undefined)
|
|
328
|
-
return this;
|
|
329
|
-
|
|
330
|
-
// not listening for removeListener, no need to emit
|
|
331
|
-
if (events.removeListener === undefined) {
|
|
332
|
-
if (arguments.length === 0) {
|
|
333
|
-
this._events = Object.create(null);
|
|
334
|
-
this._eventsCount = 0;
|
|
335
|
-
} else if (events[type] !== undefined) {
|
|
336
|
-
if (--this._eventsCount === 0)
|
|
337
|
-
this._events = Object.create(null);
|
|
338
|
-
else
|
|
339
|
-
delete events[type];
|
|
340
|
-
}
|
|
341
|
-
return this;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// emit removeListener for all listeners on all events
|
|
345
|
-
if (arguments.length === 0) {
|
|
346
|
-
var keys = Object.keys(events);
|
|
347
|
-
var key;
|
|
348
|
-
for (i = 0; i < keys.length; ++i) {
|
|
349
|
-
key = keys[i];
|
|
350
|
-
if (key === 'removeListener') continue;
|
|
351
|
-
this.removeAllListeners(key);
|
|
352
|
-
}
|
|
353
|
-
this.removeAllListeners('removeListener');
|
|
354
|
-
this._events = Object.create(null);
|
|
355
|
-
this._eventsCount = 0;
|
|
356
|
-
return this;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
listeners = events[type];
|
|
360
|
-
|
|
361
|
-
if (typeof listeners === 'function') {
|
|
362
|
-
this.removeListener(type, listeners);
|
|
363
|
-
} else if (listeners !== undefined) {
|
|
364
|
-
// LIFO order
|
|
365
|
-
for (i = listeners.length - 1; i >= 0; i--) {
|
|
366
|
-
this.removeListener(type, listeners[i]);
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
return this;
|
|
371
|
-
};
|
|
372
|
-
|
|
373
|
-
function _listeners(target, type, unwrap) {
|
|
374
|
-
var events = target._events;
|
|
375
|
-
|
|
376
|
-
if (events === undefined)
|
|
377
|
-
return [];
|
|
378
|
-
|
|
379
|
-
var evlistener = events[type];
|
|
380
|
-
if (evlistener === undefined)
|
|
381
|
-
return [];
|
|
382
|
-
|
|
383
|
-
if (typeof evlistener === 'function')
|
|
384
|
-
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
|
|
385
|
-
|
|
386
|
-
return unwrap ?
|
|
387
|
-
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
EventEmitter.prototype.listeners = function listeners(type) {
|
|
391
|
-
return _listeners(this, type, true);
|
|
392
|
-
};
|
|
393
|
-
|
|
394
|
-
EventEmitter.prototype.rawListeners = function rawListeners(type) {
|
|
395
|
-
return _listeners(this, type, false);
|
|
396
|
-
};
|
|
397
|
-
|
|
398
|
-
EventEmitter.listenerCount = function(emitter, type) {
|
|
399
|
-
if (typeof emitter.listenerCount === 'function') {
|
|
400
|
-
return emitter.listenerCount(type);
|
|
401
|
-
} else {
|
|
402
|
-
return listenerCount.call(emitter, type);
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
|
|
406
|
-
EventEmitter.prototype.listenerCount = listenerCount;
|
|
407
|
-
function listenerCount(type) {
|
|
408
|
-
var events = this._events;
|
|
409
|
-
|
|
410
|
-
if (events !== undefined) {
|
|
411
|
-
var evlistener = events[type];
|
|
412
|
-
|
|
413
|
-
if (typeof evlistener === 'function') {
|
|
414
|
-
return 1;
|
|
415
|
-
} else if (evlistener !== undefined) {
|
|
416
|
-
return evlistener.length;
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
return 0;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
EventEmitter.prototype.eventNames = function eventNames() {
|
|
424
|
-
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
|
425
|
-
};
|
|
426
|
-
|
|
427
|
-
function arrayClone(arr, n) {
|
|
428
|
-
var copy = new Array(n);
|
|
429
|
-
for (var i = 0; i < n; ++i)
|
|
430
|
-
copy[i] = arr[i];
|
|
431
|
-
return copy;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
function spliceOne(list, index) {
|
|
435
|
-
for (; index + 1 < list.length; index++)
|
|
436
|
-
list[index] = list[index + 1];
|
|
437
|
-
list.pop();
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
function unwrapListeners(arr) {
|
|
441
|
-
var ret = new Array(arr.length);
|
|
442
|
-
for (var i = 0; i < ret.length; ++i) {
|
|
443
|
-
ret[i] = arr[i].listener || arr[i];
|
|
444
|
-
}
|
|
445
|
-
return ret;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function once(emitter, name) {
|
|
449
|
-
return new Promise(function (resolve, reject) {
|
|
450
|
-
function errorListener(err) {
|
|
451
|
-
emitter.removeListener(name, resolver);
|
|
452
|
-
reject(err);
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
function resolver() {
|
|
456
|
-
if (typeof emitter.removeListener === 'function') {
|
|
457
|
-
emitter.removeListener('error', errorListener);
|
|
458
|
-
}
|
|
459
|
-
resolve([].slice.call(arguments));
|
|
460
|
-
}
|
|
461
|
-
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
|
|
462
|
-
if (name !== 'error') {
|
|
463
|
-
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
|
|
464
|
-
}
|
|
465
|
-
});
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
|
|
469
|
-
if (typeof emitter.on === 'function') {
|
|
470
|
-
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
|
|
475
|
-
if (typeof emitter.on === 'function') {
|
|
476
|
-
if (flags.once) {
|
|
477
|
-
emitter.once(name, listener);
|
|
478
|
-
} else {
|
|
479
|
-
emitter.on(name, listener);
|
|
480
|
-
}
|
|
481
|
-
} else if (typeof emitter.addEventListener === 'function') {
|
|
482
|
-
// EventTarget does not have `error` event semantics like Node
|
|
483
|
-
// EventEmitters, we do not listen for `error` events here.
|
|
484
|
-
emitter.addEventListener(name, function wrapListener(arg) {
|
|
485
|
-
// IE does not have builtin `{ once: true }` support so we
|
|
486
|
-
// have to do it manually.
|
|
487
|
-
if (flags.once) {
|
|
488
|
-
emitter.removeEventListener(name, wrapListener);
|
|
489
|
-
}
|
|
490
|
-
listener(arg);
|
|
491
|
-
});
|
|
492
|
-
} else {
|
|
493
|
-
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
|
|
498
|
-
var extendStatics = function (d, b) {
|
|
499
|
-
extendStatics = Object.setPrototypeOf ||
|
|
500
|
-
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
501
|
-
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
|
502
|
-
return extendStatics(d, b);
|
|
503
|
-
};
|
|
504
|
-
return function (d, b) {
|
|
505
|
-
extendStatics(d, b);
|
|
506
|
-
function __() { this.constructor = d; }
|
|
507
|
-
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
508
|
-
};
|
|
509
|
-
})();
|
|
510
|
-
var __spreadArrays = (commonjsGlobal && commonjsGlobal.__spreadArrays) || function () {
|
|
511
|
-
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
|
|
512
|
-
for (var r = Array(s), k = 0, i = 0; i < il; i++)
|
|
513
|
-
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
|
|
514
|
-
r[k] = a[j];
|
|
515
|
-
return r;
|
|
516
|
-
};
|
|
517
|
-
StrictEventEmitter$1.__esModule = true;
|
|
518
|
-
StrictEventEmitter$1.StrictEventEmitter = void 0;
|
|
519
|
-
var events_1 = events.exports;
|
|
520
|
-
var StrictEventEmitter = /** @class */ (function (_super) {
|
|
521
|
-
__extends(StrictEventEmitter, _super);
|
|
522
|
-
function StrictEventEmitter() {
|
|
523
|
-
return _super.call(this) || this;
|
|
524
|
-
}
|
|
525
|
-
StrictEventEmitter.prototype.on = function (event, listener) {
|
|
526
|
-
return _super.prototype.on.call(this, event.toString(), listener);
|
|
527
|
-
};
|
|
528
|
-
StrictEventEmitter.prototype.once = function (event, listener) {
|
|
529
|
-
return _super.prototype.on.call(this, event.toString(), listener);
|
|
530
|
-
};
|
|
531
|
-
StrictEventEmitter.prototype.off = function (event, listener) {
|
|
532
|
-
return _super.prototype.off.call(this, event.toString(), listener);
|
|
533
|
-
};
|
|
534
|
-
StrictEventEmitter.prototype.emit = function (event) {
|
|
535
|
-
var data = [];
|
|
536
|
-
for (var _i = 1; _i < arguments.length; _i++) {
|
|
537
|
-
data[_i - 1] = arguments[_i];
|
|
538
|
-
}
|
|
539
|
-
return _super.prototype.emit.apply(this, __spreadArrays([event.toString()], data));
|
|
540
|
-
};
|
|
541
|
-
StrictEventEmitter.prototype.addListener = function (event, listener) {
|
|
542
|
-
return _super.prototype.addListener.call(this, event.toString(), listener);
|
|
543
|
-
};
|
|
544
|
-
StrictEventEmitter.prototype.removeListener = function (event, listener) {
|
|
545
|
-
return _super.prototype.removeListener.call(this, event.toString(), listener);
|
|
546
|
-
};
|
|
547
|
-
return StrictEventEmitter;
|
|
548
|
-
}(events_1.EventEmitter));
|
|
549
|
-
StrictEventEmitter$1.StrictEventEmitter = StrictEventEmitter;
|
|
550
|
-
|
|
551
|
-
(function (exports) {
|
|
552
|
-
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
553
|
-
if (k2 === undefined) k2 = k;
|
|
554
|
-
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
555
|
-
}) : (function(o, m, k, k2) {
|
|
556
|
-
if (k2 === undefined) k2 = k;
|
|
557
|
-
o[k2] = m[k];
|
|
558
|
-
}));
|
|
559
|
-
exports.__esModule = true;
|
|
560
|
-
exports.StrictEventEmitter = void 0;
|
|
561
|
-
var StrictEventEmitter_1 = StrictEventEmitter$1;
|
|
562
|
-
__createBinding(exports, StrictEventEmitter_1, "StrictEventEmitter");
|
|
563
|
-
}(lib$1));
|
|
564
|
-
|
|
565
|
-
var lib = {};
|
|
566
|
-
|
|
567
|
-
var until$1 = {};
|
|
568
|
-
|
|
569
|
-
Object.defineProperty(until$1, "__esModule", { value: true });
|
|
570
|
-
/**
|
|
571
|
-
* Gracefully handles a given Promise factory.
|
|
572
|
-
* @example
|
|
573
|
-
* cosnt [error, data] = await until(() => asyncAction())
|
|
574
|
-
*/
|
|
575
|
-
until$1.until = async (promise) => {
|
|
576
|
-
try {
|
|
577
|
-
const data = await promise().catch((error) => {
|
|
578
|
-
throw error;
|
|
579
|
-
});
|
|
580
|
-
return [null, data];
|
|
581
|
-
}
|
|
582
|
-
catch (error) {
|
|
583
|
-
return [error, null];
|
|
584
|
-
}
|
|
585
|
-
};
|
|
586
|
-
|
|
587
|
-
Object.defineProperty(lib, "__esModule", { value: true });
|
|
588
|
-
var until_1 = until$1;
|
|
589
|
-
var until = lib.until = until_1.until;
|
|
590
|
-
|
|
591
|
-
/**
|
|
592
|
-
* Attempts to resolve a Service Worker instance from a given registration,
|
|
593
|
-
* regardless of its state (active, installing, waiting).
|
|
594
|
-
*/
|
|
595
|
-
const getWorkerByRegistration = (registration, absoluteWorkerUrl, findWorker) => {
|
|
596
|
-
const allStates = [
|
|
597
|
-
registration.active,
|
|
598
|
-
registration.installing,
|
|
599
|
-
registration.waiting,
|
|
600
|
-
];
|
|
601
|
-
const existingStates = allStates.filter(Boolean);
|
|
602
|
-
const mockWorker = existingStates.find((worker) => {
|
|
603
|
-
return findWorker(worker.scriptURL, absoluteWorkerUrl);
|
|
604
|
-
});
|
|
605
|
-
return mockWorker || null;
|
|
606
|
-
};
|
|
607
|
-
|
|
608
|
-
/**
|
|
609
|
-
* Returns an absolute Service Worker URL based on the given
|
|
610
|
-
* relative URL (known during the registration).
|
|
611
|
-
*/
|
|
612
|
-
function getAbsoluteWorkerUrl(relativeUrl) {
|
|
613
|
-
return new URL(relativeUrl, location.origin).href;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* Returns an active Service Worker instance.
|
|
618
|
-
* When not found, registers a new Service Worker.
|
|
619
|
-
*/
|
|
620
|
-
const getWorkerInstance = (url, options = {}, findWorker) => __awaiter(void 0, void 0, void 0, function* () {
|
|
621
|
-
// Resolve the absolute Service Worker URL.
|
|
622
|
-
const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
|
|
623
|
-
const mockRegistrations = yield navigator.serviceWorker
|
|
624
|
-
.getRegistrations()
|
|
625
|
-
.then((registrations) => registrations.filter((registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)));
|
|
626
|
-
if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
|
|
627
|
-
// Reload the page when it has associated workers, but no active controller.
|
|
628
|
-
// The absence of a controller can mean either:
|
|
629
|
-
// - page has no Service Worker associated with it
|
|
630
|
-
// - page has been hard-reloaded and its workers won't be used until the next reload.
|
|
631
|
-
// Since we've checked that there are registrations associated with this page,
|
|
632
|
-
// at this point we are sure it's hard reload that falls into this clause.
|
|
633
|
-
location.reload();
|
|
634
|
-
}
|
|
635
|
-
const [existingRegistration] = mockRegistrations;
|
|
636
|
-
if (existingRegistration) {
|
|
637
|
-
// When the Service Worker is registered, update it and return the reference.
|
|
638
|
-
return existingRegistration.update().then(() => {
|
|
639
|
-
return [
|
|
640
|
-
getWorkerByRegistration(existingRegistration, absoluteWorkerUrl, findWorker),
|
|
641
|
-
existingRegistration,
|
|
642
|
-
];
|
|
643
|
-
});
|
|
644
|
-
}
|
|
645
|
-
// When the Service Worker wasn't found, register it anew and return the reference.
|
|
646
|
-
const [error, instance] = yield until(() => __awaiter(void 0, void 0, void 0, function* () {
|
|
647
|
-
const registration = yield navigator.serviceWorker.register(url, options);
|
|
648
|
-
return [
|
|
649
|
-
// Compare existing worker registration by its worker URL,
|
|
650
|
-
// to prevent irrelevant workers to resolve here (such as Codesandbox worker).
|
|
651
|
-
getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
|
|
652
|
-
registration,
|
|
653
|
-
];
|
|
654
|
-
}));
|
|
655
|
-
// Handle Service Worker registration errors.
|
|
656
|
-
if (error) {
|
|
657
|
-
const isWorkerMissing = error.message.includes('(404)');
|
|
658
|
-
// Produce a custom error message when given a non-existing Service Worker url.
|
|
659
|
-
// Suggest developers to check their setup.
|
|
660
|
-
if (isWorkerMissing) {
|
|
661
|
-
const scopeUrl = new URL((options === null || options === void 0 ? void 0 : options.scope) || '/', location.href);
|
|
662
|
-
throw new Error(devUtils.formatMessage(`\
|
|
663
|
-
Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
|
|
664
|
-
|
|
665
|
-
Did you forget to run "npx msw init <PUBLIC_DIR>"?
|
|
666
|
-
|
|
667
|
-
Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`));
|
|
668
|
-
}
|
|
669
|
-
// Fallback error message for any other registration errors.
|
|
670
|
-
throw new Error(devUtils.formatMessage('Failed to register the Service Worker:\n\n%s', error.message));
|
|
671
|
-
}
|
|
672
|
-
return instance;
|
|
673
|
-
});
|
|
674
|
-
|
|
675
|
-
/**
|
|
676
|
-
* Prints a worker activation message in the browser's console.
|
|
677
|
-
*/
|
|
678
|
-
function printStartMessage(args = {}) {
|
|
679
|
-
if (args.quiet) {
|
|
680
|
-
return;
|
|
681
|
-
}
|
|
682
|
-
const message = args.message || 'Mocking enabled.';
|
|
683
|
-
console.groupCollapsed(`%c${devUtils.formatMessage(message)}`, 'color:orangered;font-weight:bold;');
|
|
684
|
-
console.log('%cDocumentation: %chttps://mswjs.io/docs', 'font-weight:bold', 'font-weight:normal');
|
|
685
|
-
console.log('Found an issue? https://github.com/mswjs/msw/issues');
|
|
686
|
-
if (args.workerUrl) {
|
|
687
|
-
console.log('Worker script URL:', args.workerUrl);
|
|
688
|
-
}
|
|
689
|
-
if (args.workerScope) {
|
|
690
|
-
console.log('Worker scope:', args.workerScope);
|
|
691
|
-
}
|
|
692
|
-
console.groupEnd();
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
/**
|
|
696
|
-
* Signals the worker to enable the interception of requests.
|
|
697
|
-
*/
|
|
698
|
-
function enableMocking(context, options) {
|
|
699
|
-
var _a, _b;
|
|
700
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
701
|
-
context.workerChannel.send('MOCK_ACTIVATE');
|
|
702
|
-
yield context.events.once('MOCKING_ENABLED');
|
|
703
|
-
// Warn the developer on multiple "worker.start()" calls.
|
|
704
|
-
// While this will not affect the worker in any way,
|
|
705
|
-
// it likely indicates an issue with the developer's code.
|
|
706
|
-
if (context.isMockingEnabled) {
|
|
707
|
-
devUtils.warn(`Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`);
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
context.isMockingEnabled = true;
|
|
711
|
-
printStartMessage({
|
|
712
|
-
quiet: options.quiet,
|
|
713
|
-
workerScope: (_a = context.registration) === null || _a === void 0 ? void 0 : _a.scope,
|
|
714
|
-
workerUrl: (_b = context.worker) === null || _b === void 0 ? void 0 : _b.scriptURL,
|
|
715
|
-
});
|
|
716
|
-
});
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
/**
|
|
720
|
-
* Creates a communication channel between the client
|
|
721
|
-
* and the Service Worker associated with the given event.
|
|
722
|
-
*/
|
|
723
|
-
const createBroadcastChannel = (event) => {
|
|
724
|
-
const port = event.ports[0];
|
|
725
|
-
return {
|
|
726
|
-
/**
|
|
727
|
-
* Sends a text message to the connected Service Worker.
|
|
728
|
-
*/
|
|
729
|
-
send(message) {
|
|
730
|
-
if (port) {
|
|
731
|
-
port.postMessage(message);
|
|
732
|
-
}
|
|
733
|
-
},
|
|
734
|
-
};
|
|
735
|
-
};
|
|
736
|
-
|
|
737
|
-
function getAllCookies() {
|
|
738
|
-
return parse_1(document.cookie);
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Returns relevant document cookies based on the request `credentials` option.
|
|
742
|
-
*/
|
|
743
|
-
function getRequestCookies(request) {
|
|
744
|
-
/**
|
|
745
|
-
* @note No cookies persist on the document in Node.js: no document.
|
|
746
|
-
*/
|
|
747
|
-
if (typeof document === 'undefined' || typeof location === 'undefined') {
|
|
748
|
-
return {};
|
|
749
|
-
}
|
|
750
|
-
switch (request.credentials) {
|
|
751
|
-
case 'same-origin': {
|
|
752
|
-
// Return document cookies only when requested a resource
|
|
753
|
-
// from the same origin as the current document.
|
|
754
|
-
return location.origin === request.url.origin ? getAllCookies() : {};
|
|
755
|
-
}
|
|
756
|
-
case 'include': {
|
|
757
|
-
// Return all document cookies.
|
|
758
|
-
return getAllCookies();
|
|
759
|
-
}
|
|
760
|
-
default: {
|
|
761
|
-
return {};
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
/**
|
|
767
|
-
* Sets relevant cookies on the request.
|
|
768
|
-
* Request cookies are taken from the following sources:
|
|
769
|
-
* - Immediate (own) request cookies (those in the "Cookie" request header);
|
|
770
|
-
* - From the `document.cookie` based on the request's `credentials` value;
|
|
771
|
-
* - From the internal cookie store that persists/hydrates cookies in Node.js
|
|
772
|
-
*/
|
|
773
|
-
function setRequestCookies(request) {
|
|
774
|
-
var _a;
|
|
775
|
-
// Set mocked request cookies from the `cookie` header of the original request.
|
|
776
|
-
// No need to take `credentials` into account, because in Node.js requests are intercepted
|
|
777
|
-
// _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
|
|
778
|
-
// Unlike browser, where interception is on the worker level, _before_ the request happens.
|
|
779
|
-
const requestCookiesString = request.headers.get('cookie');
|
|
780
|
-
store.hydrate();
|
|
781
|
-
const cookiesFromStore = Array.from((_a = store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
|
|
782
|
-
return Object.assign(cookies, { [name.trim()]: value });
|
|
783
|
-
}, {});
|
|
784
|
-
const cookiesFromDocument = getRequestCookies(request);
|
|
785
|
-
const forwardedCookies = Object.assign(Object.assign({}, cookiesFromDocument), cookiesFromStore);
|
|
786
|
-
// Ensure the persisted (document) cookies are propagated to the request.
|
|
787
|
-
// Propagated the cookies persisted in the Cookuie Store to the request headers.
|
|
788
|
-
// This forwards relevant request cookies based on the request's credentials.
|
|
789
|
-
for (const [name, value] of Object.entries(forwardedCookies)) {
|
|
790
|
-
request.headers.append('cookie', `${name}=${value}`);
|
|
791
|
-
}
|
|
792
|
-
const ownCookies = requestCookiesString
|
|
793
|
-
? parse_1(requestCookiesString)
|
|
794
|
-
: {};
|
|
795
|
-
request.cookies = Object.assign(Object.assign(Object.assign({}, request.cookies), forwardedCookies), ownCookies);
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
/**
|
|
799
|
-
* Ensures that an empty GET request body is always represented as `undefined`.
|
|
800
|
-
*/
|
|
801
|
-
function pruneGetRequestBody(request) {
|
|
802
|
-
if (request.method &&
|
|
803
|
-
isStringEqual(request.method, 'GET') &&
|
|
804
|
-
request.body === '') {
|
|
805
|
-
return undefined;
|
|
806
|
-
}
|
|
807
|
-
return request.body;
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/**
|
|
811
|
-
* Converts a given request received from the Service Worker
|
|
812
|
-
* into a `MockedRequest` instance.
|
|
813
|
-
*/
|
|
814
|
-
function parseWorkerRequest(rawRequest) {
|
|
815
|
-
const request = {
|
|
816
|
-
id: rawRequest.id,
|
|
817
|
-
cache: rawRequest.cache,
|
|
818
|
-
credentials: rawRequest.credentials,
|
|
819
|
-
method: rawRequest.method,
|
|
820
|
-
url: new URL(rawRequest.url),
|
|
821
|
-
referrer: rawRequest.referrer,
|
|
822
|
-
referrerPolicy: rawRequest.referrerPolicy,
|
|
823
|
-
redirect: rawRequest.redirect,
|
|
824
|
-
mode: rawRequest.mode,
|
|
825
|
-
params: {},
|
|
826
|
-
cookies: {},
|
|
827
|
-
integrity: rawRequest.integrity,
|
|
828
|
-
keepalive: rawRequest.keepalive,
|
|
829
|
-
destination: rawRequest.destination,
|
|
830
|
-
body: pruneGetRequestBody(rawRequest),
|
|
831
|
-
bodyUsed: rawRequest.bodyUsed,
|
|
832
|
-
headers: new lib$2.Headers(rawRequest.headers),
|
|
833
|
-
passthrough,
|
|
834
|
-
};
|
|
835
|
-
// Set document cookies on the request.
|
|
836
|
-
setRequestCookies(request);
|
|
837
|
-
// Parse the request's body based on the "Content-Type" header.
|
|
838
|
-
request.body = parseBody(request.body, request.headers);
|
|
839
|
-
return request;
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
/**
|
|
843
|
-
* Returns a mocked response for a given request using following request handlers.
|
|
844
|
-
*/
|
|
845
|
-
const getResponse = (request, handlers, resolutionContext) => __awaiter(void 0, void 0, void 0, function* () {
|
|
846
|
-
const relevantHandlers = handlers.filter((handler) => {
|
|
847
|
-
return handler.test(request, resolutionContext);
|
|
848
|
-
});
|
|
849
|
-
if (relevantHandlers.length === 0) {
|
|
850
|
-
return {
|
|
851
|
-
handler: undefined,
|
|
852
|
-
response: undefined,
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter(void 0, void 0, void 0, function* () {
|
|
856
|
-
const previousResults = yield executionResult;
|
|
857
|
-
if (!!(previousResults === null || previousResults === void 0 ? void 0 : previousResults.response)) {
|
|
858
|
-
return executionResult;
|
|
859
|
-
}
|
|
860
|
-
const result = yield handler.run(request, resolutionContext);
|
|
861
|
-
if (result === null || result.handler.shouldSkip) {
|
|
862
|
-
return null;
|
|
863
|
-
}
|
|
864
|
-
if (!result.response) {
|
|
865
|
-
return {
|
|
866
|
-
request: result.request,
|
|
867
|
-
handler: result.handler,
|
|
868
|
-
response: undefined,
|
|
869
|
-
parsedResult: result.parsedResult,
|
|
870
|
-
};
|
|
871
|
-
}
|
|
872
|
-
if (result.response.once) {
|
|
873
|
-
handler.markAsSkipped(true);
|
|
874
|
-
}
|
|
875
|
-
return result;
|
|
876
|
-
}), Promise.resolve(null));
|
|
877
|
-
// Although reducing a list of relevant request handlers, it's possible
|
|
878
|
-
// that in the end there will be no handler associted with the request
|
|
879
|
-
// (i.e. if relevant handlers are fall-through).
|
|
880
|
-
if (!result) {
|
|
881
|
-
return {
|
|
882
|
-
handler: undefined,
|
|
883
|
-
response: undefined,
|
|
884
|
-
};
|
|
885
|
-
}
|
|
886
|
-
return {
|
|
887
|
-
handler: result.handler,
|
|
888
|
-
publicRequest: result.request,
|
|
889
|
-
parsedRequest: result.parsedResult,
|
|
890
|
-
response: result.response,
|
|
891
|
-
};
|
|
892
|
-
});
|
|
893
|
-
|
|
894
|
-
var jsLevenshtein = (function()
|
|
895
|
-
{
|
|
896
|
-
function _min(d0, d1, d2, bx, ay)
|
|
897
|
-
{
|
|
898
|
-
return d0 < d1 || d2 < d1
|
|
899
|
-
? d0 > d2
|
|
900
|
-
? d2 + 1
|
|
901
|
-
: d0 + 1
|
|
902
|
-
: bx === ay
|
|
903
|
-
? d1
|
|
904
|
-
: d1 + 1;
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
return function(a, b)
|
|
908
|
-
{
|
|
909
|
-
if (a === b) {
|
|
910
|
-
return 0;
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
if (a.length > b.length) {
|
|
914
|
-
var tmp = a;
|
|
915
|
-
a = b;
|
|
916
|
-
b = tmp;
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
var la = a.length;
|
|
920
|
-
var lb = b.length;
|
|
921
|
-
|
|
922
|
-
while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {
|
|
923
|
-
la--;
|
|
924
|
-
lb--;
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
var offset = 0;
|
|
928
|
-
|
|
929
|
-
while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {
|
|
930
|
-
offset++;
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
la -= offset;
|
|
934
|
-
lb -= offset;
|
|
935
|
-
|
|
936
|
-
if (la === 0 || lb < 3) {
|
|
937
|
-
return lb;
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
var x = 0;
|
|
941
|
-
var y;
|
|
942
|
-
var d0;
|
|
943
|
-
var d1;
|
|
944
|
-
var d2;
|
|
945
|
-
var d3;
|
|
946
|
-
var dd;
|
|
947
|
-
var dy;
|
|
948
|
-
var ay;
|
|
949
|
-
var bx0;
|
|
950
|
-
var bx1;
|
|
951
|
-
var bx2;
|
|
952
|
-
var bx3;
|
|
953
|
-
|
|
954
|
-
var vector = [];
|
|
955
|
-
|
|
956
|
-
for (y = 0; y < la; y++) {
|
|
957
|
-
vector.push(y + 1);
|
|
958
|
-
vector.push(a.charCodeAt(offset + y));
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
var len = vector.length - 1;
|
|
962
|
-
|
|
963
|
-
for (; x < lb - 3;) {
|
|
964
|
-
bx0 = b.charCodeAt(offset + (d0 = x));
|
|
965
|
-
bx1 = b.charCodeAt(offset + (d1 = x + 1));
|
|
966
|
-
bx2 = b.charCodeAt(offset + (d2 = x + 2));
|
|
967
|
-
bx3 = b.charCodeAt(offset + (d3 = x + 3));
|
|
968
|
-
dd = (x += 4);
|
|
969
|
-
for (y = 0; y < len; y += 2) {
|
|
970
|
-
dy = vector[y];
|
|
971
|
-
ay = vector[y + 1];
|
|
972
|
-
d0 = _min(dy, d0, d1, bx0, ay);
|
|
973
|
-
d1 = _min(d0, d1, d2, bx1, ay);
|
|
974
|
-
d2 = _min(d1, d2, d3, bx2, ay);
|
|
975
|
-
dd = _min(d2, d3, dd, bx3, ay);
|
|
976
|
-
vector[y] = dd;
|
|
977
|
-
d3 = d2;
|
|
978
|
-
d2 = d1;
|
|
979
|
-
d1 = d0;
|
|
980
|
-
d0 = dy;
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
for (; x < lb;) {
|
|
985
|
-
bx0 = b.charCodeAt(offset + (d0 = x));
|
|
986
|
-
dd = ++x;
|
|
987
|
-
for (y = 0; y < len; y += 2) {
|
|
988
|
-
dy = vector[y];
|
|
989
|
-
vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);
|
|
990
|
-
d0 = dy;
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
return dd;
|
|
995
|
-
};
|
|
996
|
-
})();
|
|
997
|
-
|
|
998
|
-
const MAX_MATCH_SCORE = 3;
|
|
999
|
-
const MAX_SUGGESTION_COUNT = 4;
|
|
1000
|
-
const TYPE_MATCH_DELTA = 0.5;
|
|
1001
|
-
function groupHandlersByType(handlers) {
|
|
1002
|
-
return handlers.reduce((groups, handler) => {
|
|
1003
|
-
if (handler instanceof RestHandler) {
|
|
1004
|
-
groups.rest.push(handler);
|
|
1005
|
-
}
|
|
1006
|
-
if (handler instanceof GraphQLHandler) {
|
|
1007
|
-
groups.graphql.push(handler);
|
|
1008
|
-
}
|
|
1009
|
-
return groups;
|
|
1010
|
-
}, {
|
|
1011
|
-
rest: [],
|
|
1012
|
-
graphql: [],
|
|
1013
|
-
});
|
|
1014
|
-
}
|
|
1015
|
-
function getRestHandlerScore() {
|
|
1016
|
-
return (request, handler) => {
|
|
1017
|
-
const { path, method } = handler.info;
|
|
1018
|
-
if (path instanceof RegExp || method instanceof RegExp) {
|
|
1019
|
-
return Infinity;
|
|
1020
|
-
}
|
|
1021
|
-
const hasSameMethod = isStringEqual(request.method, method);
|
|
1022
|
-
// Always treat a handler with the same method as a more similar one.
|
|
1023
|
-
const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
|
|
1024
|
-
const requestPublicUrl = getPublicUrlFromRequest(request);
|
|
1025
|
-
const score = jsLevenshtein(requestPublicUrl, path);
|
|
1026
|
-
return score - methodScoreDelta;
|
|
1027
|
-
};
|
|
1028
|
-
}
|
|
1029
|
-
function getGraphQLHandlerScore(parsedQuery) {
|
|
1030
|
-
return (_, handler) => {
|
|
1031
|
-
if (typeof parsedQuery.operationName === 'undefined') {
|
|
1032
|
-
return Infinity;
|
|
1033
|
-
}
|
|
1034
|
-
const { operationType, operationName } = handler.info;
|
|
1035
|
-
if (typeof operationName !== 'string') {
|
|
1036
|
-
return Infinity;
|
|
1037
|
-
}
|
|
1038
|
-
const hasSameOperationType = parsedQuery.operationType === operationType;
|
|
1039
|
-
// Always treat a handler with the same operation type as a more similar one.
|
|
1040
|
-
const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
|
|
1041
|
-
const score = jsLevenshtein(parsedQuery.operationName, operationName);
|
|
1042
|
-
return score - operationTypeScoreDelta;
|
|
1043
|
-
};
|
|
1044
|
-
}
|
|
1045
|
-
function getSuggestedHandler(request, handlers, getScore) {
|
|
1046
|
-
const suggestedHandlers = handlers
|
|
1047
|
-
.reduce((suggestions, handler) => {
|
|
1048
|
-
const score = getScore(request, handler);
|
|
1049
|
-
return suggestions.concat([[score, handler]]);
|
|
1050
|
-
}, [])
|
|
1051
|
-
.sort(([leftScore], [rightScore]) => leftScore - rightScore)
|
|
1052
|
-
.filter(([score]) => score <= MAX_MATCH_SCORE)
|
|
1053
|
-
.slice(0, MAX_SUGGESTION_COUNT)
|
|
1054
|
-
.map(([, handler]) => handler);
|
|
1055
|
-
return suggestedHandlers;
|
|
1056
|
-
}
|
|
1057
|
-
function getSuggestedHandlersMessage(handlers) {
|
|
1058
|
-
if (handlers.length > 1) {
|
|
1059
|
-
return `\
|
|
1060
|
-
Did you mean to request one of the following resources instead?
|
|
1061
|
-
|
|
1062
|
-
${handlers.map((handler) => ` • ${handler.info.header}`).join('\n')}`;
|
|
1063
|
-
}
|
|
1064
|
-
return `Did you mean to request "${handlers[0].info.header}" instead?`;
|
|
1065
|
-
}
|
|
1066
|
-
function onUnhandledRequest(request, handlers, strategy = 'warn') {
|
|
1067
|
-
const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
|
|
1068
|
-
function generateHandlerSuggestion() {
|
|
1069
|
-
/**
|
|
1070
|
-
* @note Ignore exceptions during GraphQL request parsing because at this point
|
|
1071
|
-
* we cannot assume the unhandled request is a valid GraphQL request.
|
|
1072
|
-
* If the GraphQL parsing fails, just don't treat it as a GraphQL request.
|
|
1073
|
-
*/
|
|
1074
|
-
const handlerGroups = groupHandlersByType(handlers);
|
|
1075
|
-
const relevantHandlers = parsedGraphQLQuery
|
|
1076
|
-
? handlerGroups.graphql
|
|
1077
|
-
: handlerGroups.rest;
|
|
1078
|
-
const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery
|
|
1079
|
-
? getGraphQLHandlerScore(parsedGraphQLQuery)
|
|
1080
|
-
: getRestHandlerScore());
|
|
1081
|
-
return suggestedHandlers.length > 0
|
|
1082
|
-
? getSuggestedHandlersMessage(suggestedHandlers)
|
|
1083
|
-
: '';
|
|
1084
|
-
}
|
|
1085
|
-
function generateUnhandledRequestMessage() {
|
|
1086
|
-
const publicUrl = getPublicUrlFromRequest(request);
|
|
1087
|
-
const requestHeader = parsedGraphQLQuery
|
|
1088
|
-
? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})`
|
|
1089
|
-
: `${request.method} ${publicUrl}`;
|
|
1090
|
-
const handlerSuggestion = generateHandlerSuggestion();
|
|
1091
|
-
const messageTemplate = [
|
|
1092
|
-
`captured a request without a matching request handler:`,
|
|
1093
|
-
` \u2022 ${requestHeader}`,
|
|
1094
|
-
handlerSuggestion,
|
|
1095
|
-
`\
|
|
1096
|
-
If you still wish to intercept this unhandled request, please create a request handler for it.
|
|
1097
|
-
Read more: https://mswjs.io/docs/getting-started/mocks\
|
|
1098
|
-
`,
|
|
1099
|
-
].filter(Boolean);
|
|
1100
|
-
return messageTemplate.join('\n\n');
|
|
1101
|
-
}
|
|
1102
|
-
function applyStrategy(strategy) {
|
|
1103
|
-
// Generate handler suggestions only when applying the strategy.
|
|
1104
|
-
// This saves bandwidth for scenarios when developers opt-out
|
|
1105
|
-
// from the default unhandled request handling strategy.
|
|
1106
|
-
const message = generateUnhandledRequestMessage();
|
|
1107
|
-
switch (strategy) {
|
|
1108
|
-
case 'error': {
|
|
1109
|
-
// Print a developer-friendly error.
|
|
1110
|
-
devUtils.error('Error: %s', message);
|
|
1111
|
-
// Throw an exception to halt request processing and not perform the original request.
|
|
1112
|
-
throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
|
|
1113
|
-
}
|
|
1114
|
-
case 'warn': {
|
|
1115
|
-
devUtils.warn('Warning: %s', message);
|
|
1116
|
-
break;
|
|
1117
|
-
}
|
|
1118
|
-
case 'bypass':
|
|
1119
|
-
break;
|
|
1120
|
-
default:
|
|
1121
|
-
throw new Error(devUtils.formatMessage('Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', strategy));
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
if (typeof strategy === 'function') {
|
|
1125
|
-
strategy(request, {
|
|
1126
|
-
warning: applyStrategy.bind(null, 'warn'),
|
|
1127
|
-
error: applyStrategy.bind(null, 'error'),
|
|
1128
|
-
});
|
|
1129
|
-
return;
|
|
1130
|
-
}
|
|
1131
|
-
applyStrategy(strategy);
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
function readResponseCookies(request, response) {
|
|
1135
|
-
store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
|
|
1136
|
-
store.persist();
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
|
|
1140
|
-
var _a, _b, _c, _d;
|
|
1141
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1142
|
-
emitter.emit('request:start', request);
|
|
1143
|
-
// Perform bypassed requests (i.e. issued via "ctx.fetch") as-is.
|
|
1144
|
-
if (request.headers.get('x-msw-bypass') === 'true') {
|
|
1145
|
-
emitter.emit('request:end', request);
|
|
1146
|
-
(_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, request);
|
|
1147
|
-
return;
|
|
1148
|
-
}
|
|
1149
|
-
// Resolve a mocked response from the list of request handlers.
|
|
1150
|
-
const [lookupError, lookupResult] = yield until(() => {
|
|
1151
|
-
return getResponse(request, handlers, handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.resolutionContext);
|
|
1152
|
-
});
|
|
1153
|
-
if (lookupError) {
|
|
1154
|
-
// Allow developers to react to unhandled exceptions in request handlers.
|
|
1155
|
-
emitter.emit('unhandledException', lookupError, request);
|
|
1156
|
-
throw lookupError;
|
|
1157
|
-
}
|
|
1158
|
-
const { handler, response } = lookupResult;
|
|
1159
|
-
// When there's no handler for the request, consider it unhandled.
|
|
1160
|
-
// Allow the developer to react to such cases.
|
|
1161
|
-
if (!handler) {
|
|
1162
|
-
onUnhandledRequest(request, handlers, options.onUnhandledRequest);
|
|
1163
|
-
emitter.emit('request:unhandled', request);
|
|
1164
|
-
emitter.emit('request:end', request);
|
|
1165
|
-
(_b = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _b === void 0 ? void 0 : _b.call(handleRequestOptions, request);
|
|
1166
|
-
return;
|
|
1167
|
-
}
|
|
1168
|
-
// When the handled request returned no mocked response, warn the developer,
|
|
1169
|
-
// as it may be an oversight on their part. Perform the request as-is.
|
|
1170
|
-
if (!response) {
|
|
1171
|
-
devUtils.warn(`\
|
|
1172
|
-
Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.\
|
|
1173
|
-
\n
|
|
1174
|
-
\u2022 %s
|
|
1175
|
-
%s\
|
|
1176
|
-
`, response, handler.info.header, handler.info.callFrame);
|
|
1177
|
-
emitter.emit('request:end', request);
|
|
1178
|
-
(_c = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _c === void 0 ? void 0 : _c.call(handleRequestOptions, request);
|
|
1179
|
-
return;
|
|
1180
|
-
}
|
|
1181
|
-
// When the developer explicitly returned "req.passthrough()" do not warn them.
|
|
1182
|
-
// Perform the request as-is.
|
|
1183
|
-
if (response.passthrough) {
|
|
1184
|
-
emitter.emit('request:end', request);
|
|
1185
|
-
(_d = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _d === void 0 ? void 0 : _d.call(handleRequestOptions, request);
|
|
1186
|
-
return;
|
|
1187
|
-
}
|
|
1188
|
-
// Store all the received response cookies in the virtual cookie store.
|
|
1189
|
-
readResponseCookies(request, response);
|
|
1190
|
-
emitter.emit('request:match', request);
|
|
1191
|
-
return new Promise((resolve) => {
|
|
1192
|
-
var _a, _b, _c;
|
|
1193
|
-
const requiredLookupResult = lookupResult;
|
|
1194
|
-
const transformedResponse = ((_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.transformResponse) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, response)) ||
|
|
1195
|
-
response;
|
|
1196
|
-
(_b = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onMockedResponse) === null || _b === void 0 ? void 0 : _b.call(handleRequestOptions, transformedResponse, requiredLookupResult);
|
|
1197
|
-
setTimeout(() => {
|
|
1198
|
-
var _a;
|
|
1199
|
-
(_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onMockedResponseSent) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, transformedResponse, requiredLookupResult);
|
|
1200
|
-
emitter.emit('request:end', request);
|
|
1201
|
-
resolve(transformedResponse);
|
|
1202
|
-
}, (_c = response.delay) !== null && _c !== void 0 ? _c : 0);
|
|
1203
|
-
});
|
|
1204
|
-
});
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
const createRequestListener = (context, options) => {
|
|
1208
|
-
return (event, message) => __awaiter(void 0, void 0, void 0, function* () {
|
|
1209
|
-
const channel = createBroadcastChannel(event);
|
|
1210
|
-
try {
|
|
1211
|
-
const request = parseWorkerRequest(message.payload);
|
|
1212
|
-
yield handleRequest(request, context.requestHandlers, options, context.emitter, {
|
|
1213
|
-
transformResponse(response) {
|
|
1214
|
-
return Object.assign(Object.assign({}, response), { headers: response.headers.all() });
|
|
1215
|
-
},
|
|
1216
|
-
onPassthroughResponse() {
|
|
1217
|
-
return channel.send({
|
|
1218
|
-
type: 'MOCK_NOT_FOUND',
|
|
1219
|
-
});
|
|
1220
|
-
},
|
|
1221
|
-
onMockedResponse(response) {
|
|
1222
|
-
channel.send({
|
|
1223
|
-
type: 'MOCK_SUCCESS',
|
|
1224
|
-
payload: response,
|
|
1225
|
-
});
|
|
1226
|
-
},
|
|
1227
|
-
onMockedResponseSent(response, { handler, publicRequest, parsedRequest }) {
|
|
1228
|
-
if (!options.quiet) {
|
|
1229
|
-
handler.log(publicRequest, response, handler, parsedRequest);
|
|
1230
|
-
}
|
|
1231
|
-
},
|
|
1232
|
-
});
|
|
1233
|
-
}
|
|
1234
|
-
catch (error) {
|
|
1235
|
-
if (error instanceof NetworkError) {
|
|
1236
|
-
// Treat emulated network error differently,
|
|
1237
|
-
// as it is an intended exception in a request handler.
|
|
1238
|
-
return channel.send({
|
|
1239
|
-
type: 'NETWORK_ERROR',
|
|
1240
|
-
payload: {
|
|
1241
|
-
name: error.name,
|
|
1242
|
-
message: error.message,
|
|
1243
|
-
},
|
|
1244
|
-
});
|
|
1245
|
-
}
|
|
1246
|
-
if (error instanceof Error) {
|
|
1247
|
-
// Treat all the other exceptions in a request handler
|
|
1248
|
-
// as unintended, alerting that there is a problem needs fixing.
|
|
1249
|
-
channel.send({
|
|
1250
|
-
type: 'INTERNAL_ERROR',
|
|
1251
|
-
payload: {
|
|
1252
|
-
status: 500,
|
|
1253
|
-
body: JSON.stringify({
|
|
1254
|
-
errorType: error.constructor.name,
|
|
1255
|
-
message: error.message,
|
|
1256
|
-
location: error.stack,
|
|
1257
|
-
}),
|
|
1258
|
-
},
|
|
1259
|
-
});
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
});
|
|
1263
|
-
};
|
|
1264
|
-
|
|
1265
|
-
function requestIntegrityCheck(context, serviceWorker) {
|
|
1266
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1267
|
-
// Signal Service Worker to report back its integrity
|
|
1268
|
-
context.workerChannel.send('INTEGRITY_CHECK_REQUEST');
|
|
1269
|
-
const { payload: actualChecksum } = yield context.events.once('INTEGRITY_CHECK_RESPONSE');
|
|
1270
|
-
// Compare the response from the Service Worker and the
|
|
1271
|
-
// global variable set by Rollup during the build.
|
|
1272
|
-
if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
|
|
1273
|
-
throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
|
|
1274
|
-
}
|
|
1275
|
-
return serviceWorker;
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
|
|
1279
|
-
/**
|
|
1280
|
-
* Intercepts and defers any requests on the page
|
|
1281
|
-
* until the Service Worker instance is ready.
|
|
1282
|
-
* Must only be used in a browser.
|
|
1283
|
-
*/
|
|
1284
|
-
function deferNetworkRequestsUntil(predicatePromise) {
|
|
1285
|
-
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
|
|
1286
|
-
const originalXhrSend = window.XMLHttpRequest.prototype.send;
|
|
1287
|
-
window.XMLHttpRequest.prototype.send = function (...args) {
|
|
1288
|
-
// Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
|
|
1289
|
-
// because that method is always synchronous.
|
|
1290
|
-
until(() => predicatePromise).then(() => {
|
|
1291
|
-
window.XMLHttpRequest.prototype.send = originalXhrSend;
|
|
1292
|
-
this.send(...args);
|
|
1293
|
-
});
|
|
1294
|
-
};
|
|
1295
|
-
// Defer any `fetch` requests until the Service Worker is ready.
|
|
1296
|
-
const originalFetch = window.fetch;
|
|
1297
|
-
window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
|
|
1298
|
-
yield until(() => predicatePromise);
|
|
1299
|
-
window.fetch = originalFetch;
|
|
1300
|
-
return window.fetch(...args);
|
|
1301
|
-
});
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
function createResponseListener(context) {
|
|
1305
|
-
return (_, message) => {
|
|
1306
|
-
var _a;
|
|
1307
|
-
const { payload: responseJson } = message;
|
|
1308
|
-
/**
|
|
1309
|
-
* CORS requests with `mode: "no-cors"` result in "opaque" responses.
|
|
1310
|
-
* That kind of responses cannot be manipulated in JavaScript due
|
|
1311
|
-
* to the security considerations.
|
|
1312
|
-
* @see https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
|
|
1313
|
-
* @see https://github.com/mswjs/msw/issues/529
|
|
1314
|
-
*/
|
|
1315
|
-
if ((_a = responseJson.type) === null || _a === void 0 ? void 0 : _a.includes('opaque')) {
|
|
1316
|
-
return;
|
|
1317
|
-
}
|
|
1318
|
-
const response = new Response(responseJson.body || null, responseJson);
|
|
1319
|
-
const isMockedResponse = response.headers.get('x-powered-by') === 'msw';
|
|
1320
|
-
if (isMockedResponse) {
|
|
1321
|
-
context.emitter.emit('response:mocked', response, responseJson.requestId);
|
|
1322
|
-
}
|
|
1323
|
-
else {
|
|
1324
|
-
context.emitter.emit('response:bypass', response, responseJson.requestId);
|
|
1325
|
-
}
|
|
1326
|
-
};
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
function validateWorkerScope(registration, options) {
|
|
1330
|
-
if (!(options === null || options === void 0 ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
|
|
1331
|
-
devUtils.warn(`\
|
|
1332
|
-
Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
|
|
1333
|
-
|
|
1334
|
-
- (Recommended) Register the worker at the root level ("/") of your application.
|
|
1335
|
-
- Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.\
|
|
1336
|
-
`);
|
|
1337
|
-
}
|
|
1338
|
-
}
|
|
1339
|
-
|
|
1340
|
-
const createStartHandler = (context) => {
|
|
1341
|
-
return function start(options, customOptions) {
|
|
1342
|
-
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
|
|
1343
|
-
// Remove all previously existing event listeners.
|
|
1344
|
-
// This way none of the listeners persists between Fast refresh
|
|
1345
|
-
// of the application's code.
|
|
1346
|
-
context.events.removeAllListeners();
|
|
1347
|
-
// Handle requests signaled by the worker.
|
|
1348
|
-
context.workerChannel.on('REQUEST', createRequestListener(context, options));
|
|
1349
|
-
context.workerChannel.on('RESPONSE', createResponseListener(context));
|
|
1350
|
-
const instance = yield getWorkerInstance(options.serviceWorker.url, options.serviceWorker.options, options.findWorker);
|
|
1351
|
-
const [worker, registration] = instance;
|
|
1352
|
-
if (!worker) {
|
|
1353
|
-
const missingWorkerMessage = (customOptions === null || customOptions === void 0 ? void 0 : customOptions.findWorker)
|
|
1354
|
-
? devUtils.formatMessage(`Failed to locate the Service Worker registration using a custom "findWorker" predicate.
|
|
1355
|
-
|
|
1356
|
-
Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
|
|
1357
|
-
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
|
|
1358
|
-
`, options.serviceWorker.url)
|
|
1359
|
-
: devUtils.formatMessage(`Failed to locate the Service Worker registration.
|
|
1360
|
-
|
|
1361
|
-
This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.
|
|
1362
|
-
|
|
1363
|
-
Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`, options.serviceWorker.url, location.host);
|
|
1364
|
-
throw new Error(missingWorkerMessage);
|
|
1365
|
-
}
|
|
1366
|
-
context.worker = worker;
|
|
1367
|
-
context.registration = registration;
|
|
1368
|
-
context.events.addListener(window, 'beforeunload', () => {
|
|
1369
|
-
if (worker.state !== 'redundant') {
|
|
1370
|
-
// Notify the Service Worker that this client has closed.
|
|
1371
|
-
// Internally, it's similar to disabling the mocking, only
|
|
1372
|
-
// client close event has a handler that self-terminates
|
|
1373
|
-
// the Service Worker when there are no open clients.
|
|
1374
|
-
context.workerChannel.send('CLIENT_CLOSED');
|
|
1375
|
-
}
|
|
1376
|
-
// Make sure we're always clearing the interval - there are reports that not doing this can
|
|
1377
|
-
// cause memory leaks in headless browser environments.
|
|
1378
|
-
window.clearInterval(context.keepAliveInterval);
|
|
1379
|
-
});
|
|
1380
|
-
// Check if the active Service Worker is the latest published one
|
|
1381
|
-
const [integrityError] = yield until(() => requestIntegrityCheck(context, worker));
|
|
1382
|
-
if (integrityError) {
|
|
1383
|
-
devUtils.error(`\
|
|
1384
|
-
Detected outdated Service Worker: ${integrityError.message}
|
|
1385
|
-
|
|
1386
|
-
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
|
|
1387
|
-
|
|
1388
|
-
$ npx msw init <PUBLIC_DIR>
|
|
1389
|
-
|
|
1390
|
-
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
|
|
1391
|
-
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
|
|
1392
|
-
`);
|
|
1393
|
-
}
|
|
1394
|
-
context.keepAliveInterval = window.setInterval(() => context.workerChannel.send('KEEPALIVE_REQUEST'), 5000);
|
|
1395
|
-
// Warn the user when loading the page that lies outside
|
|
1396
|
-
// of the worker's scope.
|
|
1397
|
-
validateWorkerScope(registration, context.startOptions);
|
|
1398
|
-
return registration;
|
|
1399
|
-
});
|
|
1400
|
-
const workerRegistration = startWorkerInstance().then((registration) => __awaiter(this, void 0, void 0, function* () {
|
|
1401
|
-
const pendingInstance = registration.installing || registration.waiting;
|
|
1402
|
-
// Wait until the worker is activated.
|
|
1403
|
-
// Assume the worker is already activated if there's no pending registration
|
|
1404
|
-
// (i.e. when reloading the page after a successful activation).
|
|
1405
|
-
if (pendingInstance) {
|
|
1406
|
-
yield new Promise((resolve) => {
|
|
1407
|
-
pendingInstance.addEventListener('statechange', () => {
|
|
1408
|
-
if (pendingInstance.state === 'activated') {
|
|
1409
|
-
return resolve();
|
|
1410
|
-
}
|
|
1411
|
-
});
|
|
1412
|
-
});
|
|
1413
|
-
}
|
|
1414
|
-
// Print the activation message only after the worker has been activated.
|
|
1415
|
-
yield enableMocking(context, options).catch((error) => {
|
|
1416
|
-
throw new Error(`Failed to enable mocking: ${error === null || error === void 0 ? void 0 : error.message}`);
|
|
1417
|
-
});
|
|
1418
|
-
return registration;
|
|
1419
|
-
}));
|
|
1420
|
-
// Defer any network requests until the Service Worker instance is ready.
|
|
1421
|
-
// This prevents a race condition between the Service Worker registration
|
|
1422
|
-
// and application's runtime requests (i.e. requests on mount).
|
|
1423
|
-
if (options.waitUntilReady) {
|
|
1424
|
-
deferNetworkRequestsUntil(workerRegistration);
|
|
1425
|
-
}
|
|
1426
|
-
return workerRegistration;
|
|
1427
|
-
};
|
|
1428
|
-
};
|
|
1429
|
-
|
|
1430
|
-
function printStopMessage(args = {}) {
|
|
1431
|
-
if (args.quiet) {
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
console.log(`%c${devUtils.formatMessage('Mocking disabled.')}`, 'color:orangered;font-weight:bold;');
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
const createStop = (context) => {
|
|
1438
|
-
return function stop() {
|
|
1439
|
-
var _a;
|
|
1440
|
-
// Warn developers calling "worker.stop()" more times than necessary.
|
|
1441
|
-
// This likely indicates a mistake in their code.
|
|
1442
|
-
if (!context.isMockingEnabled) {
|
|
1443
|
-
devUtils.warn('Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.');
|
|
1444
|
-
return;
|
|
1445
|
-
}
|
|
1446
|
-
/**
|
|
1447
|
-
* Signal the Service Worker to disable mocking for this client.
|
|
1448
|
-
* Use this an an explicit way to stop the mocking, while preserving
|
|
1449
|
-
* the worker-client relation. Does not affect the worker's lifecycle.
|
|
1450
|
-
*/
|
|
1451
|
-
context.workerChannel.send('MOCK_DEACTIVATE');
|
|
1452
|
-
context.isMockingEnabled = false;
|
|
1453
|
-
window.clearInterval(context.keepAliveInterval);
|
|
1454
|
-
printStopMessage({ quiet: (_a = context.startOptions) === null || _a === void 0 ? void 0 : _a.quiet });
|
|
1455
|
-
};
|
|
1456
|
-
};
|
|
1457
|
-
|
|
1458
|
-
function use(currentHandlers, ...handlers) {
|
|
1459
|
-
currentHandlers.unshift(...handlers);
|
|
1460
|
-
}
|
|
1461
|
-
function restoreHandlers(handlers) {
|
|
1462
|
-
handlers.forEach((handler) => {
|
|
1463
|
-
handler.markAsSkipped(false);
|
|
1464
|
-
});
|
|
1465
|
-
}
|
|
1466
|
-
function resetHandlers(initialHandlers, ...nextHandlers) {
|
|
1467
|
-
return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
const DEFAULT_START_OPTIONS = {
|
|
1471
|
-
serviceWorker: {
|
|
1472
|
-
url: '/mockServiceWorker.js',
|
|
1473
|
-
options: null,
|
|
1474
|
-
},
|
|
1475
|
-
quiet: false,
|
|
1476
|
-
waitUntilReady: true,
|
|
1477
|
-
onUnhandledRequest: 'warn',
|
|
1478
|
-
findWorker(scriptURL, mockServiceWorkerUrl) {
|
|
1479
|
-
return scriptURL === mockServiceWorkerUrl;
|
|
1480
|
-
},
|
|
1481
|
-
};
|
|
1482
|
-
/**
|
|
1483
|
-
* Returns resolved worker start options, merging the default options
|
|
1484
|
-
* with the given custom options.
|
|
1485
|
-
*/
|
|
1486
|
-
function resolveStartOptions(initialOptions) {
|
|
1487
|
-
return mergeRight(DEFAULT_START_OPTIONS, initialOptions || {});
|
|
1488
|
-
}
|
|
1489
|
-
function prepareStartHandler(handler, context) {
|
|
1490
|
-
return (initialOptions) => {
|
|
1491
|
-
context.startOptions = resolveStartOptions(initialOptions);
|
|
1492
|
-
return handler(context.startOptions, initialOptions || {});
|
|
1493
|
-
};
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
/**
|
|
1497
|
-
* Converts a given isomorphic request to a `MockedRequest` instance.
|
|
1498
|
-
*/
|
|
1499
|
-
function parseIsomorphicRequest(request) {
|
|
1500
|
-
const mockedRequest = {
|
|
1501
|
-
id: request.id,
|
|
1502
|
-
url: request.url,
|
|
1503
|
-
method: request.method,
|
|
1504
|
-
body: parseBody(request.body, request.headers),
|
|
1505
|
-
credentials: request.credentials || 'same-origin',
|
|
1506
|
-
headers: request.headers,
|
|
1507
|
-
cookies: {},
|
|
1508
|
-
redirect: 'manual',
|
|
1509
|
-
referrer: '',
|
|
1510
|
-
keepalive: false,
|
|
1511
|
-
cache: 'default',
|
|
1512
|
-
mode: 'cors',
|
|
1513
|
-
referrerPolicy: 'no-referrer',
|
|
1514
|
-
integrity: '',
|
|
1515
|
-
destination: 'document',
|
|
1516
|
-
bodyUsed: false,
|
|
1517
|
-
passthrough,
|
|
1518
|
-
};
|
|
1519
|
-
// Attach all the cookies from the virtual cookie store.
|
|
1520
|
-
setRequestCookies(mockedRequest);
|
|
1521
|
-
return mockedRequest;
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
function createFallbackRequestListener(context, options) {
|
|
1525
|
-
const interceptor = createInterceptor({
|
|
1526
|
-
modules: [interceptFetch, interceptXMLHttpRequest],
|
|
1527
|
-
resolver(request) {
|
|
1528
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1529
|
-
const mockedRequest = parseIsomorphicRequest(request);
|
|
1530
|
-
return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
|
|
1531
|
-
transformResponse(response) {
|
|
1532
|
-
return {
|
|
1533
|
-
status: response.status,
|
|
1534
|
-
statusText: response.statusText,
|
|
1535
|
-
headers: response.headers.all(),
|
|
1536
|
-
body: response.body,
|
|
1537
|
-
};
|
|
1538
|
-
},
|
|
1539
|
-
onMockedResponseSent(response, { handler, publicRequest, parsedRequest }) {
|
|
1540
|
-
if (!options.quiet) {
|
|
1541
|
-
handler.log(publicRequest, response, handler, parsedRequest);
|
|
1542
|
-
}
|
|
1543
|
-
},
|
|
1544
|
-
});
|
|
1545
|
-
});
|
|
1546
|
-
},
|
|
1547
|
-
});
|
|
1548
|
-
interceptor.apply();
|
|
1549
|
-
return interceptor;
|
|
1550
|
-
}
|
|
1551
|
-
|
|
1552
|
-
function createFallbackStart(context) {
|
|
1553
|
-
return function start(options) {
|
|
1554
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1555
|
-
context.fallbackInterceptor = createFallbackRequestListener(context, options);
|
|
1556
|
-
printStartMessage({
|
|
1557
|
-
message: 'Mocking enabled (fallback mode).',
|
|
1558
|
-
quiet: options.quiet,
|
|
1559
|
-
});
|
|
1560
|
-
return undefined;
|
|
1561
|
-
});
|
|
1562
|
-
};
|
|
1563
|
-
}
|
|
1564
|
-
|
|
1565
|
-
function createFallbackStop(context) {
|
|
1566
|
-
return function stop() {
|
|
1567
|
-
var _a, _b;
|
|
1568
|
-
(_a = context.fallbackInterceptor) === null || _a === void 0 ? void 0 : _a.restore();
|
|
1569
|
-
printStopMessage({ quiet: (_b = context.startOptions) === null || _b === void 0 ? void 0 : _b.quiet });
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
1572
|
-
|
|
1573
|
-
/**
|
|
1574
|
-
* Pipes all emitted events from one emitter to another.
|
|
1575
|
-
*/
|
|
1576
|
-
function pipeEvents(source, destination) {
|
|
1577
|
-
const rawEmit = source.emit;
|
|
1578
|
-
// @ts-ignore
|
|
1579
|
-
if (rawEmit._isPiped) {
|
|
1580
|
-
return;
|
|
1581
|
-
}
|
|
1582
|
-
source.emit = function (event, ...data) {
|
|
1583
|
-
destination.emit(event, ...data);
|
|
1584
|
-
return rawEmit.call(this, event, ...data);
|
|
1585
|
-
};
|
|
1586
|
-
// @ts-ignore
|
|
1587
|
-
source.emit._isPiped = true;
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
// Declare the list of event handlers on the module's scope
|
|
1591
|
-
// so it persists between Fash refreshes of the application's code.
|
|
1592
|
-
let listeners = [];
|
|
1593
|
-
/**
|
|
1594
|
-
* Creates a new mock Service Worker registration
|
|
1595
|
-
* with the given request handlers.
|
|
1596
|
-
* @param {RequestHandler[]} requestHandlers List of request handlers
|
|
1597
|
-
* @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker`}
|
|
1598
|
-
*/
|
|
1599
|
-
function setupWorker(...requestHandlers) {
|
|
1600
|
-
requestHandlers.forEach((handler) => {
|
|
1601
|
-
if (Array.isArray(handler))
|
|
1602
|
-
throw new Error(devUtils.formatMessage('Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).'));
|
|
1603
|
-
});
|
|
1604
|
-
// Error when attempting to run this function in a Node.js environment.
|
|
1605
|
-
if (lib$3.exports.isNodeProcess()) {
|
|
1606
|
-
throw new Error(devUtils.formatMessage('Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead.'));
|
|
1607
|
-
}
|
|
1608
|
-
const emitter = new lib$1.StrictEventEmitter();
|
|
1609
|
-
const publicEmitter = new lib$1.StrictEventEmitter();
|
|
1610
|
-
pipeEvents(emitter, publicEmitter);
|
|
1611
|
-
const context = {
|
|
1612
|
-
// Mocking is not considered enabled until the worker
|
|
1613
|
-
// signals back the successful activation event.
|
|
1614
|
-
isMockingEnabled: false,
|
|
1615
|
-
startOptions: undefined,
|
|
1616
|
-
worker: null,
|
|
1617
|
-
registration: null,
|
|
1618
|
-
requestHandlers: [...requestHandlers],
|
|
1619
|
-
emitter,
|
|
1620
|
-
workerChannel: {
|
|
1621
|
-
on(eventType, callback) {
|
|
1622
|
-
context.events.addListener(navigator.serviceWorker, 'message', (event) => {
|
|
1623
|
-
// Avoid messages broadcasted from unrelated workers.
|
|
1624
|
-
if (event.source !== context.worker) {
|
|
1625
|
-
return;
|
|
1626
|
-
}
|
|
1627
|
-
const message = jsonParse(event.data);
|
|
1628
|
-
if (!message) {
|
|
1629
|
-
return;
|
|
1630
|
-
}
|
|
1631
|
-
if (message.type === eventType) {
|
|
1632
|
-
callback(event, message);
|
|
1633
|
-
}
|
|
1634
|
-
});
|
|
1635
|
-
},
|
|
1636
|
-
send(type) {
|
|
1637
|
-
var _a;
|
|
1638
|
-
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage(type);
|
|
1639
|
-
},
|
|
1640
|
-
},
|
|
1641
|
-
events: {
|
|
1642
|
-
addListener(target, eventType, callback) {
|
|
1643
|
-
target.addEventListener(eventType, callback);
|
|
1644
|
-
listeners.push({ eventType, target, callback });
|
|
1645
|
-
return () => {
|
|
1646
|
-
target.removeEventListener(eventType, callback);
|
|
1647
|
-
};
|
|
1648
|
-
},
|
|
1649
|
-
removeAllListeners() {
|
|
1650
|
-
for (const { target, eventType, callback } of listeners) {
|
|
1651
|
-
target.removeEventListener(eventType, callback);
|
|
1652
|
-
}
|
|
1653
|
-
listeners = [];
|
|
1654
|
-
},
|
|
1655
|
-
once(eventType) {
|
|
1656
|
-
const bindings = [];
|
|
1657
|
-
return new Promise((resolve, reject) => {
|
|
1658
|
-
const handleIncomingMessage = (event) => {
|
|
1659
|
-
try {
|
|
1660
|
-
const message = JSON.parse(event.data);
|
|
1661
|
-
if (message.type === eventType) {
|
|
1662
|
-
resolve(message);
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
catch (error) {
|
|
1666
|
-
reject(error);
|
|
1667
|
-
}
|
|
1668
|
-
};
|
|
1669
|
-
bindings.push(context.events.addListener(navigator.serviceWorker, 'message', handleIncomingMessage), context.events.addListener(navigator.serviceWorker, 'messageerror', reject));
|
|
1670
|
-
}).finally(() => {
|
|
1671
|
-
bindings.forEach((unbind) => unbind());
|
|
1672
|
-
});
|
|
1673
|
-
},
|
|
1674
|
-
},
|
|
1675
|
-
useFallbackMode: !('serviceWorker' in navigator) || location.protocol === 'file:',
|
|
1676
|
-
};
|
|
1677
|
-
const startHandler = context.useFallbackMode
|
|
1678
|
-
? createFallbackStart(context)
|
|
1679
|
-
: createStartHandler(context);
|
|
1680
|
-
const stopHandler = context.useFallbackMode
|
|
1681
|
-
? createFallbackStop(context)
|
|
1682
|
-
: createStop(context);
|
|
1683
|
-
return {
|
|
1684
|
-
start: prepareStartHandler(startHandler, context),
|
|
1685
|
-
stop() {
|
|
1686
|
-
context.events.removeAllListeners();
|
|
1687
|
-
context.emitter.removeAllListeners();
|
|
1688
|
-
publicEmitter.removeAllListeners();
|
|
1689
|
-
stopHandler();
|
|
1690
|
-
},
|
|
1691
|
-
use(...handlers) {
|
|
1692
|
-
use(context.requestHandlers, ...handlers);
|
|
1693
|
-
},
|
|
1694
|
-
restoreHandlers() {
|
|
1695
|
-
restoreHandlers(context.requestHandlers);
|
|
1696
|
-
},
|
|
1697
|
-
resetHandlers(...nextHandlers) {
|
|
1698
|
-
context.requestHandlers = resetHandlers(requestHandlers, ...nextHandlers);
|
|
1699
|
-
},
|
|
1700
|
-
printHandlers() {
|
|
1701
|
-
context.requestHandlers.forEach((handler) => {
|
|
1702
|
-
const { header, callFrame } = handler.info;
|
|
1703
|
-
const pragma = handler.info.hasOwnProperty('operationType')
|
|
1704
|
-
? '[graphql]'
|
|
1705
|
-
: '[rest]';
|
|
1706
|
-
console.groupCollapsed(`${pragma} ${header}`);
|
|
1707
|
-
if (callFrame) {
|
|
1708
|
-
console.log(`Declaration: ${callFrame}`);
|
|
1709
|
-
}
|
|
1710
|
-
console.log('Handler:', handler);
|
|
1711
|
-
if (handler instanceof RestHandler) {
|
|
1712
|
-
console.log('Match:', `https://mswjs.io/repl?path=${handler.info.path}`);
|
|
1713
|
-
}
|
|
1714
|
-
console.groupEnd();
|
|
1715
|
-
});
|
|
1716
|
-
},
|
|
1717
|
-
events: {
|
|
1718
|
-
on(...args) {
|
|
1719
|
-
return publicEmitter.on(...args);
|
|
1720
|
-
},
|
|
1721
|
-
removeListener(...args) {
|
|
1722
|
-
return publicEmitter.removeListener(...args);
|
|
1723
|
-
},
|
|
1724
|
-
removeAllListeners(...args) {
|
|
1725
|
-
return publicEmitter.removeAllListeners(...args);
|
|
1726
|
-
},
|
|
1727
|
-
},
|
|
1728
|
-
};
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
export { handleRequest, parseIsomorphicRequest, setupWorker };
|