msw 0.40.1 → 0.41.1
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/esm/index.js +1967 -1587
- package/lib/esm/index.js.map +1 -0
- package/lib/glossary-eda04a15.d.ts +331 -0
- package/lib/iife/index.js +9773 -21
- package/lib/iife/index.js.map +1 -0
- package/lib/index.d.ts +353 -0
- package/lib/index.js +2125 -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 +1532 -0
- package/lib/native/index.mjs +1532 -0
- package/lib/node/index.d.ts +15 -0
- package/lib/node/index.js +1601 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/index.mjs +1601 -0
- package/lib/node/index.mjs.map +1 -0
- package/native/package.json +3 -2
- package/node/package.json +3 -2
- package/package.json +13 -22
- 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/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 -31615
- package/lib/umd/mockServiceWorker.js +0 -338
- package/native/lib/index.js +0 -6384
- package/node/lib/index.js +0 -8276
package/lib/index.js
ADDED
|
@@ -0,0 +1,2125 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __defProps = Object.defineProperties;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
8
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
9
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
10
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
11
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
12
|
+
var __spreadValues = (a, b) => {
|
|
13
|
+
for (var prop in b || (b = {}))
|
|
14
|
+
if (__hasOwnProp.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
if (__getOwnPropSymbols)
|
|
17
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
18
|
+
if (__propIsEnum.call(b, prop))
|
|
19
|
+
__defNormalProp(a, prop, b[prop]);
|
|
20
|
+
}
|
|
21
|
+
return a;
|
|
22
|
+
};
|
|
23
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
24
|
+
var __objRest = (source, exclude) => {
|
|
25
|
+
var target = {};
|
|
26
|
+
for (var prop in source)
|
|
27
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
28
|
+
target[prop] = source[prop];
|
|
29
|
+
if (source != null && __getOwnPropSymbols)
|
|
30
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
31
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
32
|
+
target[prop] = source[prop];
|
|
33
|
+
}
|
|
34
|
+
return target;
|
|
35
|
+
};
|
|
36
|
+
var __esm = (fn, res) => function __init() {
|
|
37
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
38
|
+
};
|
|
39
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
40
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
41
|
+
};
|
|
42
|
+
var __export = (target, all) => {
|
|
43
|
+
for (var name in all)
|
|
44
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
45
|
+
};
|
|
46
|
+
var __copyProps = (to, from, except, desc) => {
|
|
47
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
48
|
+
for (let key of __getOwnPropNames(from))
|
|
49
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
50
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
51
|
+
}
|
|
52
|
+
return to;
|
|
53
|
+
};
|
|
54
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
|
|
55
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
56
|
+
|
|
57
|
+
// node_modules/tsup/assets/cjs_shims.js
|
|
58
|
+
var init_cjs_shims = __esm({
|
|
59
|
+
"node_modules/tsup/assets/cjs_shims.js"() {
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// node_modules/outvariant/lib/format.js
|
|
64
|
+
var require_format = __commonJS({
|
|
65
|
+
"node_modules/outvariant/lib/format.js"(exports) {
|
|
66
|
+
"use strict";
|
|
67
|
+
init_cjs_shims();
|
|
68
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
69
|
+
exports.format = void 0;
|
|
70
|
+
var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
|
|
71
|
+
function serializePositional(positional, flag) {
|
|
72
|
+
switch (flag) {
|
|
73
|
+
case "s":
|
|
74
|
+
return positional;
|
|
75
|
+
case "d":
|
|
76
|
+
case "i":
|
|
77
|
+
return Number(positional);
|
|
78
|
+
case "j":
|
|
79
|
+
return JSON.stringify(positional);
|
|
80
|
+
case "o": {
|
|
81
|
+
if (typeof positional === "string") {
|
|
82
|
+
return positional;
|
|
83
|
+
}
|
|
84
|
+
var json2 = JSON.stringify(positional);
|
|
85
|
+
if (json2 === "{}" || json2 === "[]" || /^\[object .+?\]$/.test(json2)) {
|
|
86
|
+
return positional;
|
|
87
|
+
}
|
|
88
|
+
return json2;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function format2(message) {
|
|
93
|
+
var positionals = [];
|
|
94
|
+
for (var _i = 1; _i < arguments.length; _i++) {
|
|
95
|
+
positionals[_i - 1] = arguments[_i];
|
|
96
|
+
}
|
|
97
|
+
if (positionals.length === 0) {
|
|
98
|
+
return message;
|
|
99
|
+
}
|
|
100
|
+
var positionalIndex = 0;
|
|
101
|
+
var formattedMessage = message.replace(POSITIONALS_EXP, function(match2, isEscaped, _, flag) {
|
|
102
|
+
var positional = positionals[positionalIndex];
|
|
103
|
+
var value = serializePositional(positional, flag);
|
|
104
|
+
if (!isEscaped) {
|
|
105
|
+
positionalIndex++;
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
return match2;
|
|
109
|
+
});
|
|
110
|
+
if (positionalIndex < positionals.length) {
|
|
111
|
+
formattedMessage += " " + positionals.slice(positionalIndex).join(" ");
|
|
112
|
+
}
|
|
113
|
+
formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
|
|
114
|
+
return formattedMessage;
|
|
115
|
+
}
|
|
116
|
+
exports.format = format2;
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// node_modules/outvariant/lib/invariant.js
|
|
121
|
+
var require_invariant = __commonJS({
|
|
122
|
+
"node_modules/outvariant/lib/invariant.js"(exports) {
|
|
123
|
+
"use strict";
|
|
124
|
+
init_cjs_shims();
|
|
125
|
+
var __extends = exports && exports.__extends || function() {
|
|
126
|
+
var extendStatics = function(d, b) {
|
|
127
|
+
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
|
|
128
|
+
d2.__proto__ = b2;
|
|
129
|
+
} || function(d2, b2) {
|
|
130
|
+
for (var p in b2)
|
|
131
|
+
if (Object.prototype.hasOwnProperty.call(b2, p))
|
|
132
|
+
d2[p] = b2[p];
|
|
133
|
+
};
|
|
134
|
+
return extendStatics(d, b);
|
|
135
|
+
};
|
|
136
|
+
return function(d, b) {
|
|
137
|
+
if (typeof b !== "function" && b !== null)
|
|
138
|
+
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
|
139
|
+
extendStatics(d, b);
|
|
140
|
+
function __() {
|
|
141
|
+
this.constructor = d;
|
|
142
|
+
}
|
|
143
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
144
|
+
};
|
|
145
|
+
}();
|
|
146
|
+
var __spreadArray = exports && exports.__spreadArray || function(to, from) {
|
|
147
|
+
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
|
|
148
|
+
to[j] = from[i];
|
|
149
|
+
return to;
|
|
150
|
+
};
|
|
151
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
152
|
+
exports.invariant = exports.InvariantError = void 0;
|
|
153
|
+
var format_1 = require_format();
|
|
154
|
+
var STACK_FRAMES_TO_IGNORE = 2;
|
|
155
|
+
var InvariantError = function(_super) {
|
|
156
|
+
__extends(InvariantError2, _super);
|
|
157
|
+
function InvariantError2(message) {
|
|
158
|
+
var positionals = [];
|
|
159
|
+
for (var _i = 1; _i < arguments.length; _i++) {
|
|
160
|
+
positionals[_i - 1] = arguments[_i];
|
|
161
|
+
}
|
|
162
|
+
var _this = _super.call(this, message) || this;
|
|
163
|
+
_this.name = "Invariant Violation";
|
|
164
|
+
_this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
|
|
165
|
+
if (_this.stack) {
|
|
166
|
+
var nextStack = _this.stack.split("\n");
|
|
167
|
+
nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
|
|
168
|
+
_this.stack = nextStack.join("\n");
|
|
169
|
+
}
|
|
170
|
+
return _this;
|
|
171
|
+
}
|
|
172
|
+
return InvariantError2;
|
|
173
|
+
}(Error);
|
|
174
|
+
exports.InvariantError = InvariantError;
|
|
175
|
+
function invariant(predicate, message) {
|
|
176
|
+
var positionals = [];
|
|
177
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
178
|
+
positionals[_i - 2] = arguments[_i];
|
|
179
|
+
}
|
|
180
|
+
if (!predicate) {
|
|
181
|
+
throw new (InvariantError.bind.apply(InvariantError, __spreadArray([void 0, message], positionals)))();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
exports.invariant = invariant;
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// node_modules/outvariant/lib/index.js
|
|
189
|
+
var require_lib = __commonJS({
|
|
190
|
+
"node_modules/outvariant/lib/index.js"(exports) {
|
|
191
|
+
"use strict";
|
|
192
|
+
init_cjs_shims();
|
|
193
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
194
|
+
if (k2 === void 0)
|
|
195
|
+
k2 = k;
|
|
196
|
+
Object.defineProperty(o, k2, { enumerable: true, get: function() {
|
|
197
|
+
return m[k];
|
|
198
|
+
} });
|
|
199
|
+
} : function(o, m, k, k2) {
|
|
200
|
+
if (k2 === void 0)
|
|
201
|
+
k2 = k;
|
|
202
|
+
o[k2] = m[k];
|
|
203
|
+
});
|
|
204
|
+
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
|
|
205
|
+
for (var p in m)
|
|
206
|
+
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
|
|
207
|
+
__createBinding(exports2, m, p);
|
|
208
|
+
};
|
|
209
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
210
|
+
__exportStar(require_invariant(), exports);
|
|
211
|
+
__exportStar(require_format(), exports);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// src/index.ts
|
|
216
|
+
var src_exports = {};
|
|
217
|
+
__export(src_exports, {
|
|
218
|
+
GraphQLHandler: () => GraphQLHandler,
|
|
219
|
+
RESTMethods: () => RESTMethods,
|
|
220
|
+
RequestHandler: () => RequestHandler,
|
|
221
|
+
RestHandler: () => RestHandler,
|
|
222
|
+
cleanUrl: () => cleanUrl,
|
|
223
|
+
compose: () => compose,
|
|
224
|
+
context: () => context_exports,
|
|
225
|
+
createResponseComposition: () => createResponseComposition,
|
|
226
|
+
defaultContext: () => defaultContext,
|
|
227
|
+
defaultResponse: () => defaultResponse,
|
|
228
|
+
graphql: () => graphql,
|
|
229
|
+
graphqlContext: () => graphqlContext,
|
|
230
|
+
handleRequest: () => handleRequest,
|
|
231
|
+
matchRequestUrl: () => matchRequestUrl,
|
|
232
|
+
parseIsomorphicRequest: () => parseIsomorphicRequest,
|
|
233
|
+
response: () => response,
|
|
234
|
+
rest: () => rest,
|
|
235
|
+
restContext: () => restContext,
|
|
236
|
+
setupWorker: () => setupWorker
|
|
237
|
+
});
|
|
238
|
+
module.exports = __toCommonJS(src_exports);
|
|
239
|
+
init_cjs_shims();
|
|
240
|
+
|
|
241
|
+
// src/context/index.ts
|
|
242
|
+
var context_exports = {};
|
|
243
|
+
__export(context_exports, {
|
|
244
|
+
body: () => body,
|
|
245
|
+
cookie: () => cookie,
|
|
246
|
+
data: () => data,
|
|
247
|
+
delay: () => delay,
|
|
248
|
+
errors: () => errors,
|
|
249
|
+
extensions: () => extensions,
|
|
250
|
+
fetch: () => fetch,
|
|
251
|
+
json: () => json,
|
|
252
|
+
set: () => set,
|
|
253
|
+
status: () => status,
|
|
254
|
+
text: () => text,
|
|
255
|
+
xml: () => xml
|
|
256
|
+
});
|
|
257
|
+
init_cjs_shims();
|
|
258
|
+
|
|
259
|
+
// src/context/status.ts
|
|
260
|
+
init_cjs_shims();
|
|
261
|
+
var import_codes = __toESM(require("statuses/codes.json"));
|
|
262
|
+
var status = (statusCode, statusText) => {
|
|
263
|
+
return (res) => {
|
|
264
|
+
res.status = statusCode;
|
|
265
|
+
res.statusText = statusText || import_codes.default[String(statusCode)];
|
|
266
|
+
return res;
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// src/context/set.ts
|
|
271
|
+
init_cjs_shims();
|
|
272
|
+
var import_headers_polyfill = require("headers-polyfill");
|
|
273
|
+
function set(...args) {
|
|
274
|
+
return (res) => {
|
|
275
|
+
const [name, value] = args;
|
|
276
|
+
if (typeof name === "string") {
|
|
277
|
+
res.headers.append(name, value);
|
|
278
|
+
} else {
|
|
279
|
+
const headers = (0, import_headers_polyfill.objectToHeaders)(name);
|
|
280
|
+
headers.forEach((value2, name2) => {
|
|
281
|
+
res.headers.append(name2, value2);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
return res;
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// src/context/cookie.ts
|
|
289
|
+
init_cjs_shims();
|
|
290
|
+
var cookieUtils = __toESM(require("cookie"));
|
|
291
|
+
var cookie = (name, value, options) => {
|
|
292
|
+
return (res) => {
|
|
293
|
+
const serializedCookie = cookieUtils.serialize(name, value, options);
|
|
294
|
+
res.headers.set("Set-Cookie", serializedCookie);
|
|
295
|
+
if (typeof document !== "undefined") {
|
|
296
|
+
document.cookie = serializedCookie;
|
|
297
|
+
}
|
|
298
|
+
return res;
|
|
299
|
+
};
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// src/context/body.ts
|
|
303
|
+
init_cjs_shims();
|
|
304
|
+
var body = (value) => {
|
|
305
|
+
return (res) => {
|
|
306
|
+
res.body = value;
|
|
307
|
+
return res;
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// src/context/data.ts
|
|
312
|
+
init_cjs_shims();
|
|
313
|
+
|
|
314
|
+
// src/utils/internal/jsonParse.ts
|
|
315
|
+
init_cjs_shims();
|
|
316
|
+
function jsonParse(value) {
|
|
317
|
+
try {
|
|
318
|
+
return JSON.parse(value);
|
|
319
|
+
} catch (error2) {
|
|
320
|
+
return void 0;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/utils/internal/mergeRight.ts
|
|
325
|
+
init_cjs_shims();
|
|
326
|
+
|
|
327
|
+
// src/utils/internal/isObject.ts
|
|
328
|
+
init_cjs_shims();
|
|
329
|
+
function isObject(value) {
|
|
330
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/utils/internal/mergeRight.ts
|
|
334
|
+
function mergeRight(left, right) {
|
|
335
|
+
return Object.entries(right).reduce((result, [key, rightValue]) => {
|
|
336
|
+
const leftValue = result[key];
|
|
337
|
+
if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
|
|
338
|
+
result[key] = leftValue.concat(rightValue);
|
|
339
|
+
return result;
|
|
340
|
+
}
|
|
341
|
+
if (isObject(leftValue) && isObject(rightValue)) {
|
|
342
|
+
result[key] = mergeRight(leftValue, rightValue);
|
|
343
|
+
return result;
|
|
344
|
+
}
|
|
345
|
+
result[key] = rightValue;
|
|
346
|
+
return result;
|
|
347
|
+
}, Object.assign({}, left));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/context/json.ts
|
|
351
|
+
init_cjs_shims();
|
|
352
|
+
var json = (body2) => {
|
|
353
|
+
return (res) => {
|
|
354
|
+
res.headers.set("Content-Type", "application/json");
|
|
355
|
+
res.body = JSON.stringify(body2);
|
|
356
|
+
return res;
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
// src/context/data.ts
|
|
361
|
+
var data = (payload) => {
|
|
362
|
+
return (res) => {
|
|
363
|
+
const prevBody = jsonParse(res.body) || {};
|
|
364
|
+
const nextBody = mergeRight(prevBody, { data: payload });
|
|
365
|
+
return json(nextBody)(res);
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
// src/context/extensions.ts
|
|
370
|
+
init_cjs_shims();
|
|
371
|
+
var extensions = (payload) => {
|
|
372
|
+
return (res) => {
|
|
373
|
+
const prevBody = jsonParse(res.body) || {};
|
|
374
|
+
const nextBody = mergeRight(prevBody, { extensions: payload });
|
|
375
|
+
return json(nextBody)(res);
|
|
376
|
+
};
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
// src/context/delay.ts
|
|
380
|
+
init_cjs_shims();
|
|
381
|
+
var import_is_node_process = require("is-node-process");
|
|
382
|
+
var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
|
|
383
|
+
var MIN_SERVER_RESPONSE_TIME = 100;
|
|
384
|
+
var MAX_SERVER_RESPONSE_TIME = 400;
|
|
385
|
+
var NODE_SERVER_RESPONSE_TIME = 5;
|
|
386
|
+
var getRandomServerResponseTime = () => {
|
|
387
|
+
if ((0, import_is_node_process.isNodeProcess)()) {
|
|
388
|
+
return NODE_SERVER_RESPONSE_TIME;
|
|
389
|
+
}
|
|
390
|
+
return Math.floor(Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME);
|
|
391
|
+
};
|
|
392
|
+
var delay = (durationOrMode) => {
|
|
393
|
+
return (res) => {
|
|
394
|
+
let delayTime;
|
|
395
|
+
if (typeof durationOrMode === "string") {
|
|
396
|
+
switch (durationOrMode) {
|
|
397
|
+
case "infinite": {
|
|
398
|
+
delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
case "real": {
|
|
402
|
+
delayTime = getRandomServerResponseTime();
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
default: {
|
|
406
|
+
throw new Error(`Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number to "ctx.delay".`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
} else if (typeof durationOrMode === "undefined") {
|
|
410
|
+
delayTime = getRandomServerResponseTime();
|
|
411
|
+
} else {
|
|
412
|
+
if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
|
|
413
|
+
throw new Error(`Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`);
|
|
414
|
+
}
|
|
415
|
+
delayTime = durationOrMode;
|
|
416
|
+
}
|
|
417
|
+
res.delay = delayTime;
|
|
418
|
+
return res;
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
// src/context/errors.ts
|
|
423
|
+
init_cjs_shims();
|
|
424
|
+
var errors = (errorsList) => {
|
|
425
|
+
return (res) => {
|
|
426
|
+
if (errorsList == null) {
|
|
427
|
+
return res;
|
|
428
|
+
}
|
|
429
|
+
const prevBody = jsonParse(res.body) || {};
|
|
430
|
+
const nextBody = mergeRight(prevBody, { errors: errorsList });
|
|
431
|
+
return json(nextBody)(res);
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
// src/context/fetch.ts
|
|
436
|
+
init_cjs_shims();
|
|
437
|
+
var import_is_node_process2 = require("is-node-process");
|
|
438
|
+
var import_headers_polyfill2 = require("headers-polyfill");
|
|
439
|
+
var useFetch = (0, import_is_node_process2.isNodeProcess)() ? require("node-fetch") : window.fetch;
|
|
440
|
+
var augmentRequestInit = (requestInit) => {
|
|
441
|
+
const headers = new import_headers_polyfill2.Headers(requestInit.headers);
|
|
442
|
+
headers.set("x-msw-bypass", "true");
|
|
443
|
+
return __spreadProps(__spreadValues({}, requestInit), {
|
|
444
|
+
headers: headers.all()
|
|
445
|
+
});
|
|
446
|
+
};
|
|
447
|
+
var createFetchRequestParameters = (input) => {
|
|
448
|
+
const { body: body2, method } = input;
|
|
449
|
+
const requestParameters = __spreadProps(__spreadValues({}, input), {
|
|
450
|
+
body: void 0
|
|
451
|
+
});
|
|
452
|
+
if (["GET", "HEAD"].includes(method)) {
|
|
453
|
+
return requestParameters;
|
|
454
|
+
}
|
|
455
|
+
if (typeof body2 === "object" || typeof body2 === "number" || typeof body2 === "boolean") {
|
|
456
|
+
requestParameters.body = JSON.stringify(body2);
|
|
457
|
+
} else {
|
|
458
|
+
requestParameters.body = body2;
|
|
459
|
+
}
|
|
460
|
+
return requestParameters;
|
|
461
|
+
};
|
|
462
|
+
var fetch = (input, requestInit = {}) => {
|
|
463
|
+
if (typeof input === "string") {
|
|
464
|
+
return useFetch(input, augmentRequestInit(requestInit));
|
|
465
|
+
}
|
|
466
|
+
const requestParameters = createFetchRequestParameters(input);
|
|
467
|
+
const derivedRequestInit = augmentRequestInit(requestParameters);
|
|
468
|
+
return useFetch(input.url.href, derivedRequestInit);
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
// src/context/text.ts
|
|
472
|
+
init_cjs_shims();
|
|
473
|
+
var text = (body2) => {
|
|
474
|
+
return (res) => {
|
|
475
|
+
res.headers.set("Content-Type", "text/plain");
|
|
476
|
+
res.body = body2;
|
|
477
|
+
return res;
|
|
478
|
+
};
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
// src/context/xml.ts
|
|
482
|
+
init_cjs_shims();
|
|
483
|
+
var xml = (body2) => {
|
|
484
|
+
return (res) => {
|
|
485
|
+
res.headers.set("Content-Type", "text/xml");
|
|
486
|
+
res.body = body2;
|
|
487
|
+
return res;
|
|
488
|
+
};
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
// src/setupWorker/setupWorker.ts
|
|
492
|
+
init_cjs_shims();
|
|
493
|
+
var import_is_node_process3 = require("is-node-process");
|
|
494
|
+
var import_strict_event_emitter = require("strict-event-emitter");
|
|
495
|
+
|
|
496
|
+
// src/setupWorker/start/createStartHandler.ts
|
|
497
|
+
init_cjs_shims();
|
|
498
|
+
var import_until4 = require("@open-draft/until");
|
|
499
|
+
|
|
500
|
+
// src/setupWorker/start/utils/getWorkerInstance.ts
|
|
501
|
+
init_cjs_shims();
|
|
502
|
+
var import_until = require("@open-draft/until");
|
|
503
|
+
|
|
504
|
+
// src/setupWorker/start/utils/getWorkerByRegistration.ts
|
|
505
|
+
init_cjs_shims();
|
|
506
|
+
var getWorkerByRegistration = (registration, absoluteWorkerUrl, findWorker) => {
|
|
507
|
+
const allStates = [
|
|
508
|
+
registration.active,
|
|
509
|
+
registration.installing,
|
|
510
|
+
registration.waiting
|
|
511
|
+
];
|
|
512
|
+
const existingStates = allStates.filter(Boolean);
|
|
513
|
+
const mockWorker = existingStates.find((worker) => {
|
|
514
|
+
return findWorker(worker.scriptURL, absoluteWorkerUrl);
|
|
515
|
+
});
|
|
516
|
+
return mockWorker || null;
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
// src/utils/url/getAbsoluteWorkerUrl.ts
|
|
520
|
+
init_cjs_shims();
|
|
521
|
+
function getAbsoluteWorkerUrl(relativeUrl) {
|
|
522
|
+
return new URL(relativeUrl, location.origin).href;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/utils/internal/devUtils.ts
|
|
526
|
+
init_cjs_shims();
|
|
527
|
+
var import_outvariant = __toESM(require_lib());
|
|
528
|
+
var LIBRARY_PREFIX = "[MSW]";
|
|
529
|
+
function formatMessage(message, ...positionals) {
|
|
530
|
+
const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
|
|
531
|
+
return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
|
|
532
|
+
}
|
|
533
|
+
function warn(message, ...positionals) {
|
|
534
|
+
console.warn(formatMessage(message, ...positionals));
|
|
535
|
+
}
|
|
536
|
+
function error(message, ...positionals) {
|
|
537
|
+
console.error(formatMessage(message, ...positionals));
|
|
538
|
+
}
|
|
539
|
+
var devUtils = {
|
|
540
|
+
formatMessage,
|
|
541
|
+
warn,
|
|
542
|
+
error
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
// src/setupWorker/start/utils/getWorkerInstance.ts
|
|
546
|
+
var getWorkerInstance = async (url, options = {}, findWorker) => {
|
|
547
|
+
const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
|
|
548
|
+
const mockRegistrations = await navigator.serviceWorker.getRegistrations().then((registrations) => registrations.filter((registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)));
|
|
549
|
+
if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
|
|
550
|
+
location.reload();
|
|
551
|
+
}
|
|
552
|
+
const [existingRegistration] = mockRegistrations;
|
|
553
|
+
if (existingRegistration) {
|
|
554
|
+
return existingRegistration.update().then(() => {
|
|
555
|
+
return [
|
|
556
|
+
getWorkerByRegistration(existingRegistration, absoluteWorkerUrl, findWorker),
|
|
557
|
+
existingRegistration
|
|
558
|
+
];
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
const [error2, instance] = await (0, import_until.until)(async () => {
|
|
562
|
+
const registration = await navigator.serviceWorker.register(url, options);
|
|
563
|
+
return [
|
|
564
|
+
getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
|
|
565
|
+
registration
|
|
566
|
+
];
|
|
567
|
+
});
|
|
568
|
+
if (error2) {
|
|
569
|
+
const isWorkerMissing = error2.message.includes("(404)");
|
|
570
|
+
if (isWorkerMissing) {
|
|
571
|
+
const scopeUrl = new URL((options == null ? void 0 : options.scope) || "/", location.href);
|
|
572
|
+
throw new Error(devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
|
|
573
|
+
|
|
574
|
+
Did you forget to run "npx msw init <PUBLIC_DIR>"?
|
|
575
|
+
|
|
576
|
+
Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`));
|
|
577
|
+
}
|
|
578
|
+
throw new Error(devUtils.formatMessage("Failed to register the Service Worker:\n\n%s", error2.message));
|
|
579
|
+
}
|
|
580
|
+
return instance;
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
// src/setupWorker/start/utils/enableMocking.ts
|
|
584
|
+
init_cjs_shims();
|
|
585
|
+
|
|
586
|
+
// src/setupWorker/start/utils/printStartMessage.ts
|
|
587
|
+
init_cjs_shims();
|
|
588
|
+
function printStartMessage(args = {}) {
|
|
589
|
+
if (args.quiet) {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const message = args.message || "Mocking enabled.";
|
|
593
|
+
console.groupCollapsed(`%c${devUtils.formatMessage(message)}`, "color:orangered;font-weight:bold;");
|
|
594
|
+
console.log("%cDocumentation: %chttps://mswjs.io/docs", "font-weight:bold", "font-weight:normal");
|
|
595
|
+
console.log("Found an issue? https://github.com/mswjs/msw/issues");
|
|
596
|
+
if (args.workerUrl) {
|
|
597
|
+
console.log("Worker script URL:", args.workerUrl);
|
|
598
|
+
}
|
|
599
|
+
if (args.workerScope) {
|
|
600
|
+
console.log("Worker scope:", args.workerScope);
|
|
601
|
+
}
|
|
602
|
+
console.groupEnd();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// src/setupWorker/start/utils/enableMocking.ts
|
|
606
|
+
async function enableMocking(context, options) {
|
|
607
|
+
var _a, _b;
|
|
608
|
+
context.workerChannel.send("MOCK_ACTIVATE");
|
|
609
|
+
await context.events.once("MOCKING_ENABLED");
|
|
610
|
+
if (context.isMockingEnabled) {
|
|
611
|
+
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.`);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
context.isMockingEnabled = true;
|
|
615
|
+
printStartMessage({
|
|
616
|
+
quiet: options.quiet,
|
|
617
|
+
workerScope: (_a = context.registration) == null ? void 0 : _a.scope,
|
|
618
|
+
workerUrl: (_b = context.worker) == null ? void 0 : _b.scriptURL
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// src/utils/worker/createRequestListener.ts
|
|
623
|
+
init_cjs_shims();
|
|
624
|
+
|
|
625
|
+
// src/utils/createBroadcastChannel.ts
|
|
626
|
+
init_cjs_shims();
|
|
627
|
+
var createBroadcastChannel = (event) => {
|
|
628
|
+
const port = event.ports[0];
|
|
629
|
+
return {
|
|
630
|
+
send(message) {
|
|
631
|
+
if (port) {
|
|
632
|
+
port.postMessage(message);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
// src/utils/NetworkError.ts
|
|
639
|
+
init_cjs_shims();
|
|
640
|
+
var NetworkError = class extends Error {
|
|
641
|
+
constructor(message) {
|
|
642
|
+
super(message);
|
|
643
|
+
this.name = "NetworkError";
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
// src/utils/request/parseWorkerRequest.ts
|
|
648
|
+
init_cjs_shims();
|
|
649
|
+
var import_headers_polyfill6 = require("headers-polyfill");
|
|
650
|
+
|
|
651
|
+
// src/handlers/RequestHandler.ts
|
|
652
|
+
init_cjs_shims();
|
|
653
|
+
var import_headers_polyfill4 = require("headers-polyfill");
|
|
654
|
+
|
|
655
|
+
// src/response.ts
|
|
656
|
+
init_cjs_shims();
|
|
657
|
+
var import_headers_polyfill3 = require("headers-polyfill");
|
|
658
|
+
|
|
659
|
+
// src/utils/internal/compose.ts
|
|
660
|
+
init_cjs_shims();
|
|
661
|
+
function compose(...fns) {
|
|
662
|
+
return (...args) => {
|
|
663
|
+
return fns.reduceRight((leftFn, rightFn) => {
|
|
664
|
+
return leftFn instanceof Promise ? Promise.resolve(leftFn).then(rightFn) : rightFn(leftFn);
|
|
665
|
+
}, args[0]);
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// src/response.ts
|
|
670
|
+
var defaultResponse = {
|
|
671
|
+
status: 200,
|
|
672
|
+
statusText: "OK",
|
|
673
|
+
body: null,
|
|
674
|
+
delay: 0,
|
|
675
|
+
once: false,
|
|
676
|
+
passthrough: false
|
|
677
|
+
};
|
|
678
|
+
var defaultResponseTransformers = [];
|
|
679
|
+
function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
|
|
680
|
+
return async (...transformers) => {
|
|
681
|
+
const initialResponse = Object.assign({}, defaultResponse, {
|
|
682
|
+
headers: new import_headers_polyfill3.Headers({
|
|
683
|
+
"x-powered-by": "msw"
|
|
684
|
+
})
|
|
685
|
+
}, responseOverrides);
|
|
686
|
+
const resolvedTransformers = [
|
|
687
|
+
...defaultTransformers,
|
|
688
|
+
...transformers
|
|
689
|
+
].filter(Boolean);
|
|
690
|
+
const resolvedResponse = resolvedTransformers.length > 0 ? compose(...resolvedTransformers)(initialResponse) : initialResponse;
|
|
691
|
+
return resolvedResponse;
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
var response = Object.assign(createResponseComposition(), {
|
|
695
|
+
once: createResponseComposition({ once: true }),
|
|
696
|
+
networkError(message) {
|
|
697
|
+
throw new NetworkError(message);
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
// src/utils/internal/getCallFrame.ts
|
|
702
|
+
init_cjs_shims();
|
|
703
|
+
var SOURCE_FRAME = /\/msw\/src\/(.+)/;
|
|
704
|
+
var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
|
|
705
|
+
function getCallFrame(error2) {
|
|
706
|
+
const stack = error2.stack;
|
|
707
|
+
if (!stack) {
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const frames = stack.split("\n").slice(1);
|
|
711
|
+
const declarationFrame = frames.find((frame) => {
|
|
712
|
+
return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
|
|
713
|
+
});
|
|
714
|
+
if (!declarationFrame) {
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
|
|
718
|
+
return declarationPath;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// src/utils/internal/isIterable.ts
|
|
722
|
+
init_cjs_shims();
|
|
723
|
+
function isIterable(fn) {
|
|
724
|
+
if (!fn) {
|
|
725
|
+
return false;
|
|
726
|
+
}
|
|
727
|
+
return typeof fn[Symbol.iterator] == "function";
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// src/handlers/RequestHandler.ts
|
|
731
|
+
var defaultContext = {
|
|
732
|
+
status,
|
|
733
|
+
set,
|
|
734
|
+
delay,
|
|
735
|
+
fetch
|
|
736
|
+
};
|
|
737
|
+
var RequestHandler = class {
|
|
738
|
+
constructor(options) {
|
|
739
|
+
this.shouldSkip = false;
|
|
740
|
+
this.ctx = options.ctx || defaultContext;
|
|
741
|
+
this.resolver = options.resolver;
|
|
742
|
+
const callFrame = getCallFrame(new Error());
|
|
743
|
+
this.info = __spreadProps(__spreadValues({}, options.info), {
|
|
744
|
+
callFrame
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
parse(_request, _resolutionContext) {
|
|
748
|
+
return null;
|
|
749
|
+
}
|
|
750
|
+
test(request, resolutionContext) {
|
|
751
|
+
return this.predicate(request, this.parse(request, resolutionContext), resolutionContext);
|
|
752
|
+
}
|
|
753
|
+
getPublicRequest(request, _parsedResult) {
|
|
754
|
+
return request;
|
|
755
|
+
}
|
|
756
|
+
markAsSkipped(shouldSkip = true) {
|
|
757
|
+
this.shouldSkip = shouldSkip;
|
|
758
|
+
}
|
|
759
|
+
async run(request, resolutionContext) {
|
|
760
|
+
if (this.shouldSkip) {
|
|
761
|
+
return null;
|
|
762
|
+
}
|
|
763
|
+
const parsedResult = this.parse(request, resolutionContext);
|
|
764
|
+
const shouldIntercept = this.predicate(request, parsedResult, resolutionContext);
|
|
765
|
+
if (!shouldIntercept) {
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
const publicRequest = this.getPublicRequest(request, parsedResult);
|
|
769
|
+
const executeResolver = this.wrapResolver(this.resolver);
|
|
770
|
+
const mockedResponse = await executeResolver(publicRequest, response, this.ctx);
|
|
771
|
+
return this.createExecutionResult(parsedResult, publicRequest, mockedResponse);
|
|
772
|
+
}
|
|
773
|
+
wrapResolver(resolver) {
|
|
774
|
+
return async (req, res, ctx) => {
|
|
775
|
+
const result = this.resolverGenerator || await resolver(req, res, ctx);
|
|
776
|
+
if (isIterable(result)) {
|
|
777
|
+
const { value, done } = result[Symbol.iterator]().next();
|
|
778
|
+
const nextResponse = await value;
|
|
779
|
+
if (!nextResponse && done) {
|
|
780
|
+
return this.resolverGeneratorResult;
|
|
781
|
+
}
|
|
782
|
+
if (!this.resolverGenerator) {
|
|
783
|
+
this.resolverGenerator = result;
|
|
784
|
+
}
|
|
785
|
+
this.resolverGeneratorResult = nextResponse;
|
|
786
|
+
return nextResponse;
|
|
787
|
+
}
|
|
788
|
+
return result;
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
createExecutionResult(parsedResult, request, response2) {
|
|
792
|
+
return {
|
|
793
|
+
handler: this,
|
|
794
|
+
parsedResult: parsedResult || null,
|
|
795
|
+
request,
|
|
796
|
+
response: response2 || null
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
function passthrough() {
|
|
801
|
+
return {
|
|
802
|
+
status: 101,
|
|
803
|
+
statusText: "Continue",
|
|
804
|
+
headers: new import_headers_polyfill4.Headers(),
|
|
805
|
+
body: null,
|
|
806
|
+
passthrough: true,
|
|
807
|
+
once: false
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/utils/request/setRequestCookies.ts
|
|
812
|
+
init_cjs_shims();
|
|
813
|
+
var cookieUtils3 = __toESM(require("cookie"));
|
|
814
|
+
var import_cookies = require("@mswjs/cookies");
|
|
815
|
+
|
|
816
|
+
// src/utils/request/getRequestCookies.ts
|
|
817
|
+
init_cjs_shims();
|
|
818
|
+
var cookieUtils2 = __toESM(require("cookie"));
|
|
819
|
+
function getAllCookies() {
|
|
820
|
+
return cookieUtils2.parse(document.cookie);
|
|
821
|
+
}
|
|
822
|
+
function getRequestCookies(request) {
|
|
823
|
+
if (typeof document === "undefined" || typeof location === "undefined") {
|
|
824
|
+
return {};
|
|
825
|
+
}
|
|
826
|
+
switch (request.credentials) {
|
|
827
|
+
case "same-origin": {
|
|
828
|
+
return location.origin === request.url.origin ? getAllCookies() : {};
|
|
829
|
+
}
|
|
830
|
+
case "include": {
|
|
831
|
+
return getAllCookies();
|
|
832
|
+
}
|
|
833
|
+
default: {
|
|
834
|
+
return {};
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// src/utils/request/setRequestCookies.ts
|
|
840
|
+
function setRequestCookies(request) {
|
|
841
|
+
var _a;
|
|
842
|
+
const requestCookiesString = request.headers.get("cookie");
|
|
843
|
+
import_cookies.store.hydrate();
|
|
844
|
+
const cookiesFromStore = Array.from((_a = import_cookies.store.get(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
|
|
845
|
+
return Object.assign(cookies, { [name.trim()]: value });
|
|
846
|
+
}, {});
|
|
847
|
+
const cookiesFromDocument = getRequestCookies(request);
|
|
848
|
+
const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
|
|
849
|
+
for (const [name, value] of Object.entries(forwardedCookies)) {
|
|
850
|
+
request.headers.append("cookie", `${name}=${value}`);
|
|
851
|
+
}
|
|
852
|
+
const ownCookies = requestCookiesString ? cookieUtils3.parse(requestCookiesString) : {};
|
|
853
|
+
request.cookies = __spreadValues(__spreadValues(__spreadValues({}, request.cookies), forwardedCookies), ownCookies);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// src/utils/request/parseBody.ts
|
|
857
|
+
init_cjs_shims();
|
|
858
|
+
|
|
859
|
+
// src/utils/internal/parseMultipartData.ts
|
|
860
|
+
init_cjs_shims();
|
|
861
|
+
var import_headers_polyfill5 = require("headers-polyfill");
|
|
862
|
+
function parseContentHeaders(headersString) {
|
|
863
|
+
var _a, _b;
|
|
864
|
+
const headers = (0, import_headers_polyfill5.stringToHeaders)(headersString);
|
|
865
|
+
const contentType = headers.get("content-type") || "text/plain";
|
|
866
|
+
const disposition = headers.get("content-disposition");
|
|
867
|
+
if (!disposition) {
|
|
868
|
+
throw new Error('"Content-Disposition" header is required.');
|
|
869
|
+
}
|
|
870
|
+
const directives = disposition.split(";").reduce((acc, chunk) => {
|
|
871
|
+
const [name2, ...rest2] = chunk.trim().split("=");
|
|
872
|
+
acc[name2] = rest2.join("=");
|
|
873
|
+
return acc;
|
|
874
|
+
}, {});
|
|
875
|
+
const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
|
|
876
|
+
const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
|
|
877
|
+
return {
|
|
878
|
+
name,
|
|
879
|
+
filename,
|
|
880
|
+
contentType
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
function parseMultipartData(data2, headers) {
|
|
884
|
+
const contentType = headers == null ? void 0 : headers.get("content-type");
|
|
885
|
+
if (!contentType) {
|
|
886
|
+
return void 0;
|
|
887
|
+
}
|
|
888
|
+
const [, ...directives] = contentType.split(/; */);
|
|
889
|
+
const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
|
|
890
|
+
if (!boundary) {
|
|
891
|
+
return void 0;
|
|
892
|
+
}
|
|
893
|
+
const boundaryRegExp = new RegExp(`--+${boundary}`);
|
|
894
|
+
const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
|
|
895
|
+
if (!fields.length) {
|
|
896
|
+
return void 0;
|
|
897
|
+
}
|
|
898
|
+
const parsedBody = {};
|
|
899
|
+
try {
|
|
900
|
+
for (const field of fields) {
|
|
901
|
+
const [contentHeaders, ...rest2] = field.split("\r\n\r\n");
|
|
902
|
+
const contentBody = rest2.join("\r\n\r\n");
|
|
903
|
+
const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
|
|
904
|
+
const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
|
|
905
|
+
const parsedValue = parsedBody[name];
|
|
906
|
+
if (parsedValue === void 0) {
|
|
907
|
+
parsedBody[name] = value;
|
|
908
|
+
} else if (Array.isArray(parsedValue)) {
|
|
909
|
+
parsedBody[name] = [...parsedValue, value];
|
|
910
|
+
} else {
|
|
911
|
+
parsedBody[name] = [parsedValue, value];
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return parsedBody;
|
|
915
|
+
} catch (error2) {
|
|
916
|
+
return void 0;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/utils/request/parseBody.ts
|
|
921
|
+
function parseBody(body2, headers) {
|
|
922
|
+
var _a;
|
|
923
|
+
if (!body2) {
|
|
924
|
+
return body2;
|
|
925
|
+
}
|
|
926
|
+
const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
|
|
927
|
+
const hasMultipartContent = contentType.startsWith("multipart/form-data");
|
|
928
|
+
if (hasMultipartContent && typeof body2 !== "object") {
|
|
929
|
+
return parseMultipartData(body2.toString(), headers) || body2;
|
|
930
|
+
}
|
|
931
|
+
const hasJsonContent = contentType.includes("json");
|
|
932
|
+
if (hasJsonContent && typeof body2 !== "object") {
|
|
933
|
+
return jsonParse(body2.toString()) || body2;
|
|
934
|
+
}
|
|
935
|
+
return body2;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// src/utils/request/pruneGetRequestBody.ts
|
|
939
|
+
init_cjs_shims();
|
|
940
|
+
|
|
941
|
+
// src/utils/internal/isStringEqual.ts
|
|
942
|
+
init_cjs_shims();
|
|
943
|
+
function isStringEqual(actual, expected) {
|
|
944
|
+
return actual.toLowerCase() === expected.toLowerCase();
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// src/utils/request/pruneGetRequestBody.ts
|
|
948
|
+
function pruneGetRequestBody(request) {
|
|
949
|
+
if (request.method && isStringEqual(request.method, "GET") && request.body === "") {
|
|
950
|
+
return void 0;
|
|
951
|
+
}
|
|
952
|
+
return request.body;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// src/utils/request/parseWorkerRequest.ts
|
|
956
|
+
function parseWorkerRequest(rawRequest) {
|
|
957
|
+
const request = {
|
|
958
|
+
id: rawRequest.id,
|
|
959
|
+
cache: rawRequest.cache,
|
|
960
|
+
credentials: rawRequest.credentials,
|
|
961
|
+
method: rawRequest.method,
|
|
962
|
+
url: new URL(rawRequest.url),
|
|
963
|
+
referrer: rawRequest.referrer,
|
|
964
|
+
referrerPolicy: rawRequest.referrerPolicy,
|
|
965
|
+
redirect: rawRequest.redirect,
|
|
966
|
+
mode: rawRequest.mode,
|
|
967
|
+
params: {},
|
|
968
|
+
cookies: {},
|
|
969
|
+
integrity: rawRequest.integrity,
|
|
970
|
+
keepalive: rawRequest.keepalive,
|
|
971
|
+
destination: rawRequest.destination,
|
|
972
|
+
body: pruneGetRequestBody(rawRequest),
|
|
973
|
+
bodyUsed: rawRequest.bodyUsed,
|
|
974
|
+
headers: new import_headers_polyfill6.Headers(rawRequest.headers),
|
|
975
|
+
passthrough
|
|
976
|
+
};
|
|
977
|
+
setRequestCookies(request);
|
|
978
|
+
request.body = parseBody(request.body, request.headers);
|
|
979
|
+
return request;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// src/utils/handleRequest.ts
|
|
983
|
+
init_cjs_shims();
|
|
984
|
+
var import_until2 = require("@open-draft/until");
|
|
985
|
+
|
|
986
|
+
// src/utils/getResponse.ts
|
|
987
|
+
init_cjs_shims();
|
|
988
|
+
var getResponse = async (request, handlers, resolutionContext) => {
|
|
989
|
+
const relevantHandlers = handlers.filter((handler) => {
|
|
990
|
+
return handler.test(request, resolutionContext);
|
|
991
|
+
});
|
|
992
|
+
if (relevantHandlers.length === 0) {
|
|
993
|
+
return {
|
|
994
|
+
handler: void 0,
|
|
995
|
+
response: void 0
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
const result = await relevantHandlers.reduce(async (executionResult, handler) => {
|
|
999
|
+
const previousResults = await executionResult;
|
|
1000
|
+
if (!!(previousResults == null ? void 0 : previousResults.response)) {
|
|
1001
|
+
return executionResult;
|
|
1002
|
+
}
|
|
1003
|
+
const result2 = await handler.run(request, resolutionContext);
|
|
1004
|
+
if (result2 === null || result2.handler.shouldSkip) {
|
|
1005
|
+
return null;
|
|
1006
|
+
}
|
|
1007
|
+
if (!result2.response) {
|
|
1008
|
+
return {
|
|
1009
|
+
request: result2.request,
|
|
1010
|
+
handler: result2.handler,
|
|
1011
|
+
response: void 0,
|
|
1012
|
+
parsedResult: result2.parsedResult
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
if (result2.response.once) {
|
|
1016
|
+
handler.markAsSkipped(true);
|
|
1017
|
+
}
|
|
1018
|
+
return result2;
|
|
1019
|
+
}, Promise.resolve(null));
|
|
1020
|
+
if (!result) {
|
|
1021
|
+
return {
|
|
1022
|
+
handler: void 0,
|
|
1023
|
+
response: void 0
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
return {
|
|
1027
|
+
handler: result.handler,
|
|
1028
|
+
publicRequest: result.request,
|
|
1029
|
+
parsedRequest: result.parsedResult,
|
|
1030
|
+
response: result.response
|
|
1031
|
+
};
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
// src/utils/request/onUnhandledRequest.ts
|
|
1035
|
+
init_cjs_shims();
|
|
1036
|
+
var import_js_levenshtein = __toESM(require("js-levenshtein"));
|
|
1037
|
+
|
|
1038
|
+
// src/utils/internal/parseGraphQLRequest.ts
|
|
1039
|
+
init_cjs_shims();
|
|
1040
|
+
var import_graphql = require("graphql");
|
|
1041
|
+
|
|
1042
|
+
// src/utils/request/getPublicUrlFromRequest.ts
|
|
1043
|
+
init_cjs_shims();
|
|
1044
|
+
var getPublicUrlFromRequest = (request) => {
|
|
1045
|
+
return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
|
|
1046
|
+
};
|
|
1047
|
+
|
|
1048
|
+
// src/utils/internal/parseGraphQLRequest.ts
|
|
1049
|
+
function parseDocumentNode(node) {
|
|
1050
|
+
var _a;
|
|
1051
|
+
const operationDef = node.definitions.find((def) => {
|
|
1052
|
+
return def.kind === "OperationDefinition";
|
|
1053
|
+
});
|
|
1054
|
+
return {
|
|
1055
|
+
operationType: operationDef == null ? void 0 : operationDef.operation,
|
|
1056
|
+
operationName: (_a = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a.value
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
function parseQuery(query) {
|
|
1060
|
+
try {
|
|
1061
|
+
const ast = (0, import_graphql.parse)(query);
|
|
1062
|
+
return parseDocumentNode(ast);
|
|
1063
|
+
} catch (error2) {
|
|
1064
|
+
return error2;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
function extractMultipartVariables(variables, map, files) {
|
|
1068
|
+
const operations = { variables };
|
|
1069
|
+
for (const [key, pathArray] of Object.entries(map)) {
|
|
1070
|
+
if (!(key in files)) {
|
|
1071
|
+
throw new Error(`Given files do not have a key '${key}' .`);
|
|
1072
|
+
}
|
|
1073
|
+
for (const dotPath of pathArray) {
|
|
1074
|
+
const [lastPath, ...reversedPaths] = dotPath.split(".").reverse();
|
|
1075
|
+
const paths = reversedPaths.reverse();
|
|
1076
|
+
let target = operations;
|
|
1077
|
+
for (const path of paths) {
|
|
1078
|
+
if (!(path in target)) {
|
|
1079
|
+
throw new Error(`Property '${paths}' is not in operations.`);
|
|
1080
|
+
}
|
|
1081
|
+
target = target[path];
|
|
1082
|
+
}
|
|
1083
|
+
target[lastPath] = files[key];
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return operations.variables;
|
|
1087
|
+
}
|
|
1088
|
+
function getGraphQLInput(request) {
|
|
1089
|
+
var _a, _b;
|
|
1090
|
+
switch (request.method) {
|
|
1091
|
+
case "GET": {
|
|
1092
|
+
const query = request.url.searchParams.get("query");
|
|
1093
|
+
const variables = request.url.searchParams.get("variables") || "";
|
|
1094
|
+
return {
|
|
1095
|
+
query,
|
|
1096
|
+
variables: jsonParse(variables)
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
case "POST": {
|
|
1100
|
+
if ((_a = request.body) == null ? void 0 : _a.query) {
|
|
1101
|
+
const { query, variables } = request.body;
|
|
1102
|
+
return {
|
|
1103
|
+
query,
|
|
1104
|
+
variables
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
if ((_b = request.body) == null ? void 0 : _b.operations) {
|
|
1108
|
+
const _c = request.body, { operations, map } = _c, files = __objRest(_c, ["operations", "map"]);
|
|
1109
|
+
const parsedOperations = jsonParse(operations) || {};
|
|
1110
|
+
if (!parsedOperations.query) {
|
|
1111
|
+
return null;
|
|
1112
|
+
}
|
|
1113
|
+
const parsedMap = jsonParse(map || "") || {};
|
|
1114
|
+
const variables = parsedOperations.variables ? extractMultipartVariables(parsedOperations.variables, parsedMap, files) : {};
|
|
1115
|
+
return {
|
|
1116
|
+
query: parsedOperations.query,
|
|
1117
|
+
variables
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
default:
|
|
1122
|
+
return null;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
function parseGraphQLRequest(request) {
|
|
1126
|
+
const input = getGraphQLInput(request);
|
|
1127
|
+
if (!input || !input.query) {
|
|
1128
|
+
return void 0;
|
|
1129
|
+
}
|
|
1130
|
+
const { query, variables } = input;
|
|
1131
|
+
const parsedResult = parseQuery(query);
|
|
1132
|
+
if (parsedResult instanceof Error) {
|
|
1133
|
+
const requestPublicUrl = getPublicUrlFromRequest(request);
|
|
1134
|
+
throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', request.method, requestPublicUrl, parsedResult.message));
|
|
1135
|
+
}
|
|
1136
|
+
return {
|
|
1137
|
+
operationType: parsedResult.operationType,
|
|
1138
|
+
operationName: parsedResult.operationName,
|
|
1139
|
+
variables
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// src/handlers/RestHandler.ts
|
|
1144
|
+
init_cjs_shims();
|
|
1145
|
+
|
|
1146
|
+
// src/utils/logging/getStatusCodeColor.ts
|
|
1147
|
+
init_cjs_shims();
|
|
1148
|
+
function getStatusCodeColor(status2) {
|
|
1149
|
+
if (status2 < 300) {
|
|
1150
|
+
return "#69AB32" /* Success */;
|
|
1151
|
+
}
|
|
1152
|
+
if (status2 < 400) {
|
|
1153
|
+
return "#F0BB4B" /* Warning */;
|
|
1154
|
+
}
|
|
1155
|
+
return "#E95F5D" /* Danger */;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
// src/utils/logging/getTimestamp.ts
|
|
1159
|
+
init_cjs_shims();
|
|
1160
|
+
function getTimestamp() {
|
|
1161
|
+
const now = new Date();
|
|
1162
|
+
return [now.getHours(), now.getMinutes(), now.getSeconds()].map(String).map((chunk) => chunk.slice(0, 2)).map((chunk) => chunk.padStart(2, "0")).join(":");
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// src/utils/logging/prepareRequest.ts
|
|
1166
|
+
init_cjs_shims();
|
|
1167
|
+
function prepareRequest(request) {
|
|
1168
|
+
return __spreadProps(__spreadValues({}, request), {
|
|
1169
|
+
headers: request.headers.all()
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// src/utils/logging/prepareResponse.ts
|
|
1174
|
+
init_cjs_shims();
|
|
1175
|
+
var import_headers_polyfill7 = require("headers-polyfill");
|
|
1176
|
+
function prepareResponse(res) {
|
|
1177
|
+
const responseHeaders = (0, import_headers_polyfill7.objectToHeaders)(res.headers);
|
|
1178
|
+
return __spreadProps(__spreadValues({}, res), {
|
|
1179
|
+
body: parseBody(res.body, responseHeaders)
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// src/utils/matching/matchRequestUrl.ts
|
|
1184
|
+
init_cjs_shims();
|
|
1185
|
+
var import_path_to_regexp = require("path-to-regexp");
|
|
1186
|
+
var import_getCleanUrl = require("@mswjs/interceptors/lib/utils/getCleanUrl");
|
|
1187
|
+
|
|
1188
|
+
// src/utils/matching/normalizePath.ts
|
|
1189
|
+
init_cjs_shims();
|
|
1190
|
+
|
|
1191
|
+
// src/utils/url/cleanUrl.ts
|
|
1192
|
+
init_cjs_shims();
|
|
1193
|
+
var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
|
|
1194
|
+
function getSearchParams(path) {
|
|
1195
|
+
return new URL(`/${path}`, "http://localhost").searchParams;
|
|
1196
|
+
}
|
|
1197
|
+
function cleanUrl(path) {
|
|
1198
|
+
return path.replace(REDUNDANT_CHARACTERS_EXP, "");
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
// src/utils/url/getAbsoluteUrl.ts
|
|
1202
|
+
init_cjs_shims();
|
|
1203
|
+
|
|
1204
|
+
// src/utils/url/isAbsoluteUrl.ts
|
|
1205
|
+
init_cjs_shims();
|
|
1206
|
+
function isAbsoluteUrl(url) {
|
|
1207
|
+
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// src/utils/url/getAbsoluteUrl.ts
|
|
1211
|
+
function getAbsoluteUrl(path, baseUrl) {
|
|
1212
|
+
if (isAbsoluteUrl(path)) {
|
|
1213
|
+
return path;
|
|
1214
|
+
}
|
|
1215
|
+
if (path.startsWith("*")) {
|
|
1216
|
+
return path;
|
|
1217
|
+
}
|
|
1218
|
+
const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
|
|
1219
|
+
return origin ? decodeURI(new URL(encodeURI(path), origin).href) : path;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// src/utils/matching/normalizePath.ts
|
|
1223
|
+
function normalizePath(path, baseUrl) {
|
|
1224
|
+
if (path instanceof RegExp) {
|
|
1225
|
+
return path;
|
|
1226
|
+
}
|
|
1227
|
+
const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
|
|
1228
|
+
return cleanUrl(maybeAbsoluteUrl);
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// src/utils/matching/matchRequestUrl.ts
|
|
1232
|
+
function coercePath(path) {
|
|
1233
|
+
return path.replace(/([:a-zA-Z_-]*)(\*{1,2})+/g, (_, parameterName, wildcard) => {
|
|
1234
|
+
const expression = "(.*)";
|
|
1235
|
+
if (!parameterName) {
|
|
1236
|
+
return expression;
|
|
1237
|
+
}
|
|
1238
|
+
return parameterName.startsWith(":") ? `${parameterName}${wildcard}` : `${parameterName}${expression}`;
|
|
1239
|
+
}).replace(/([^\/])(:)(?=\d+)/, "$1\\$2").replace(/^([^\/]+)(:)(?=\/\/)/, "$1\\$2");
|
|
1240
|
+
}
|
|
1241
|
+
function matchRequestUrl(url, path, baseUrl) {
|
|
1242
|
+
const normalizedPath = normalizePath(path, baseUrl);
|
|
1243
|
+
const cleanPath = typeof normalizedPath === "string" ? coercePath(normalizedPath) : normalizedPath;
|
|
1244
|
+
const cleanUrl2 = (0, import_getCleanUrl.getCleanUrl)(url);
|
|
1245
|
+
const result = (0, import_path_to_regexp.match)(cleanPath, { decode: decodeURIComponent })(cleanUrl2);
|
|
1246
|
+
const params = result && result.params || {};
|
|
1247
|
+
return {
|
|
1248
|
+
matches: result !== false,
|
|
1249
|
+
params
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// src/handlers/RestHandler.ts
|
|
1254
|
+
var RESTMethods = /* @__PURE__ */ ((RESTMethods2) => {
|
|
1255
|
+
RESTMethods2["HEAD"] = "HEAD";
|
|
1256
|
+
RESTMethods2["GET"] = "GET";
|
|
1257
|
+
RESTMethods2["POST"] = "POST";
|
|
1258
|
+
RESTMethods2["PUT"] = "PUT";
|
|
1259
|
+
RESTMethods2["PATCH"] = "PATCH";
|
|
1260
|
+
RESTMethods2["OPTIONS"] = "OPTIONS";
|
|
1261
|
+
RESTMethods2["DELETE"] = "DELETE";
|
|
1262
|
+
return RESTMethods2;
|
|
1263
|
+
})(RESTMethods || {});
|
|
1264
|
+
var restContext = __spreadProps(__spreadValues({}, defaultContext), {
|
|
1265
|
+
cookie,
|
|
1266
|
+
body,
|
|
1267
|
+
text,
|
|
1268
|
+
json,
|
|
1269
|
+
xml
|
|
1270
|
+
});
|
|
1271
|
+
var RestHandler = class extends RequestHandler {
|
|
1272
|
+
constructor(method, path, resolver) {
|
|
1273
|
+
super({
|
|
1274
|
+
info: {
|
|
1275
|
+
header: `${method} ${path}`,
|
|
1276
|
+
path,
|
|
1277
|
+
method
|
|
1278
|
+
},
|
|
1279
|
+
ctx: restContext,
|
|
1280
|
+
resolver
|
|
1281
|
+
});
|
|
1282
|
+
this.checkRedundantQueryParameters();
|
|
1283
|
+
}
|
|
1284
|
+
checkRedundantQueryParameters() {
|
|
1285
|
+
const { method, path } = this.info;
|
|
1286
|
+
if (path instanceof RegExp) {
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
const url = cleanUrl(path);
|
|
1290
|
+
if (url === path) {
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
const searchParams = getSearchParams(path);
|
|
1294
|
+
const queryParams = [];
|
|
1295
|
+
searchParams.forEach((_, paramName) => {
|
|
1296
|
+
queryParams.push(paramName);
|
|
1297
|
+
});
|
|
1298
|
+
devUtils.warn(`Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`);
|
|
1299
|
+
}
|
|
1300
|
+
parse(request, resolutionContext) {
|
|
1301
|
+
return matchRequestUrl(request.url, this.info.path, resolutionContext == null ? void 0 : resolutionContext.baseUrl);
|
|
1302
|
+
}
|
|
1303
|
+
getPublicRequest(request, parsedResult) {
|
|
1304
|
+
return __spreadProps(__spreadValues({}, request), {
|
|
1305
|
+
params: parsedResult.params || {}
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
predicate(request, parsedResult) {
|
|
1309
|
+
const matchesMethod = this.info.method instanceof RegExp ? this.info.method.test(request.method) : isStringEqual(this.info.method, request.method);
|
|
1310
|
+
return matchesMethod && parsedResult.matches;
|
|
1311
|
+
}
|
|
1312
|
+
log(request, response2) {
|
|
1313
|
+
const publicUrl = getPublicUrlFromRequest(request);
|
|
1314
|
+
const loggedRequest = prepareRequest(request);
|
|
1315
|
+
const loggedResponse = prepareResponse(response2);
|
|
1316
|
+
const statusColor = getStatusCodeColor(response2.status);
|
|
1317
|
+
console.groupCollapsed(devUtils.formatMessage("%s %s %s (%c%s%c)"), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
|
|
1318
|
+
console.log("Request", loggedRequest);
|
|
1319
|
+
console.log("Handler:", {
|
|
1320
|
+
mask: this.info.path,
|
|
1321
|
+
resolver: this.resolver
|
|
1322
|
+
});
|
|
1323
|
+
console.log("Response", loggedResponse);
|
|
1324
|
+
console.groupEnd();
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
|
|
1328
|
+
// src/handlers/GraphQLHandler.ts
|
|
1329
|
+
init_cjs_shims();
|
|
1330
|
+
|
|
1331
|
+
// src/utils/internal/tryCatch.ts
|
|
1332
|
+
init_cjs_shims();
|
|
1333
|
+
function tryCatch(fn, onException) {
|
|
1334
|
+
try {
|
|
1335
|
+
const result = fn();
|
|
1336
|
+
return result;
|
|
1337
|
+
} catch (error2) {
|
|
1338
|
+
onException == null ? void 0 : onException(error2);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// src/handlers/GraphQLHandler.ts
|
|
1343
|
+
var graphqlContext = __spreadProps(__spreadValues({}, defaultContext), {
|
|
1344
|
+
data,
|
|
1345
|
+
extensions,
|
|
1346
|
+
errors,
|
|
1347
|
+
cookie
|
|
1348
|
+
});
|
|
1349
|
+
function isDocumentNode(value) {
|
|
1350
|
+
if (value == null) {
|
|
1351
|
+
return false;
|
|
1352
|
+
}
|
|
1353
|
+
return typeof value === "object" && "kind" in value && "definitions" in value;
|
|
1354
|
+
}
|
|
1355
|
+
var GraphQLHandler = class extends RequestHandler {
|
|
1356
|
+
constructor(operationType, operationName, endpoint, resolver) {
|
|
1357
|
+
let resolvedOperationName = operationName;
|
|
1358
|
+
if (isDocumentNode(operationName)) {
|
|
1359
|
+
const parsedNode = parseDocumentNode(operationName);
|
|
1360
|
+
if (parsedNode.operationType !== operationType) {
|
|
1361
|
+
throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
|
|
1362
|
+
}
|
|
1363
|
+
if (!parsedNode.operationName) {
|
|
1364
|
+
throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
|
|
1365
|
+
}
|
|
1366
|
+
resolvedOperationName = parsedNode.operationName;
|
|
1367
|
+
}
|
|
1368
|
+
const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
|
|
1369
|
+
super({
|
|
1370
|
+
info: {
|
|
1371
|
+
header,
|
|
1372
|
+
operationType,
|
|
1373
|
+
operationName: resolvedOperationName
|
|
1374
|
+
},
|
|
1375
|
+
ctx: graphqlContext,
|
|
1376
|
+
resolver
|
|
1377
|
+
});
|
|
1378
|
+
this.endpoint = endpoint;
|
|
1379
|
+
}
|
|
1380
|
+
parse(request) {
|
|
1381
|
+
return tryCatch(() => parseGraphQLRequest(request), (error2) => console.error(error2.message));
|
|
1382
|
+
}
|
|
1383
|
+
getPublicRequest(request, parsedResult) {
|
|
1384
|
+
return __spreadProps(__spreadValues({}, request), {
|
|
1385
|
+
variables: (parsedResult == null ? void 0 : parsedResult.variables) || {}
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
predicate(request, parsedResult) {
|
|
1389
|
+
if (!parsedResult) {
|
|
1390
|
+
return false;
|
|
1391
|
+
}
|
|
1392
|
+
if (!parsedResult.operationName && this.info.operationType !== "all") {
|
|
1393
|
+
const publicUrl = getPublicUrlFromRequest(request);
|
|
1394
|
+
devUtils.warn(`Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
|
|
1395
|
+
|
|
1396
|
+
Consider naming this operation or using "graphql.operation" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation `);
|
|
1397
|
+
return false;
|
|
1398
|
+
}
|
|
1399
|
+
const hasMatchingUrl = matchRequestUrl(request.url, this.endpoint);
|
|
1400
|
+
const hasMatchingOperationType = this.info.operationType === "all" || parsedResult.operationType === this.info.operationType;
|
|
1401
|
+
const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(parsedResult.operationName || "") : parsedResult.operationName === this.info.operationName;
|
|
1402
|
+
return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
|
|
1403
|
+
}
|
|
1404
|
+
log(request, response2, handler, parsedRequest) {
|
|
1405
|
+
const loggedRequest = prepareRequest(request);
|
|
1406
|
+
const loggedResponse = prepareResponse(response2);
|
|
1407
|
+
const statusColor = getStatusCodeColor(response2.status);
|
|
1408
|
+
const requestInfo = (parsedRequest == null ? void 0 : parsedRequest.operationName) ? `${parsedRequest == null ? void 0 : parsedRequest.operationType} ${parsedRequest == null ? void 0 : parsedRequest.operationName}` : `anonymous ${parsedRequest == null ? void 0 : parsedRequest.operationType}`;
|
|
1409
|
+
console.groupCollapsed(devUtils.formatMessage("%s %s (%c%s%c)"), getTimestamp(), `${requestInfo}`, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
|
|
1410
|
+
console.log("Request:", loggedRequest);
|
|
1411
|
+
console.log("Handler:", this);
|
|
1412
|
+
console.log("Response:", loggedResponse);
|
|
1413
|
+
console.groupEnd();
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
|
|
1417
|
+
// src/utils/request/onUnhandledRequest.ts
|
|
1418
|
+
var MAX_MATCH_SCORE = 3;
|
|
1419
|
+
var MAX_SUGGESTION_COUNT = 4;
|
|
1420
|
+
var TYPE_MATCH_DELTA = 0.5;
|
|
1421
|
+
function groupHandlersByType(handlers) {
|
|
1422
|
+
return handlers.reduce((groups, handler) => {
|
|
1423
|
+
if (handler instanceof RestHandler) {
|
|
1424
|
+
groups.rest.push(handler);
|
|
1425
|
+
}
|
|
1426
|
+
if (handler instanceof GraphQLHandler) {
|
|
1427
|
+
groups.graphql.push(handler);
|
|
1428
|
+
}
|
|
1429
|
+
return groups;
|
|
1430
|
+
}, {
|
|
1431
|
+
rest: [],
|
|
1432
|
+
graphql: []
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
function getRestHandlerScore() {
|
|
1436
|
+
return (request, handler) => {
|
|
1437
|
+
const { path, method } = handler.info;
|
|
1438
|
+
if (path instanceof RegExp || method instanceof RegExp) {
|
|
1439
|
+
return Infinity;
|
|
1440
|
+
}
|
|
1441
|
+
const hasSameMethod = isStringEqual(request.method, method);
|
|
1442
|
+
const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
|
|
1443
|
+
const requestPublicUrl = getPublicUrlFromRequest(request);
|
|
1444
|
+
const score = (0, import_js_levenshtein.default)(requestPublicUrl, path);
|
|
1445
|
+
return score - methodScoreDelta;
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
function getGraphQLHandlerScore(parsedQuery) {
|
|
1449
|
+
return (_, handler) => {
|
|
1450
|
+
if (typeof parsedQuery.operationName === "undefined") {
|
|
1451
|
+
return Infinity;
|
|
1452
|
+
}
|
|
1453
|
+
const { operationType, operationName } = handler.info;
|
|
1454
|
+
if (typeof operationName !== "string") {
|
|
1455
|
+
return Infinity;
|
|
1456
|
+
}
|
|
1457
|
+
const hasSameOperationType = parsedQuery.operationType === operationType;
|
|
1458
|
+
const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
|
|
1459
|
+
const score = (0, import_js_levenshtein.default)(parsedQuery.operationName, operationName);
|
|
1460
|
+
return score - operationTypeScoreDelta;
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
function getSuggestedHandler(request, handlers, getScore) {
|
|
1464
|
+
const suggestedHandlers = handlers.reduce((suggestions, handler) => {
|
|
1465
|
+
const score = getScore(request, handler);
|
|
1466
|
+
return suggestions.concat([[score, handler]]);
|
|
1467
|
+
}, []).sort(([leftScore], [rightScore]) => leftScore - rightScore).filter(([score]) => score <= MAX_MATCH_SCORE).slice(0, MAX_SUGGESTION_COUNT).map(([, handler]) => handler);
|
|
1468
|
+
return suggestedHandlers;
|
|
1469
|
+
}
|
|
1470
|
+
function getSuggestedHandlersMessage(handlers) {
|
|
1471
|
+
if (handlers.length > 1) {
|
|
1472
|
+
return `Did you mean to request one of the following resources instead?
|
|
1473
|
+
|
|
1474
|
+
${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
|
|
1475
|
+
}
|
|
1476
|
+
return `Did you mean to request "${handlers[0].info.header}" instead?`;
|
|
1477
|
+
}
|
|
1478
|
+
function onUnhandledRequest(request, handlers, strategy = "warn") {
|
|
1479
|
+
const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
|
|
1480
|
+
function generateHandlerSuggestion() {
|
|
1481
|
+
const handlerGroups = groupHandlersByType(handlers);
|
|
1482
|
+
const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.rest;
|
|
1483
|
+
const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getRestHandlerScore());
|
|
1484
|
+
return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
|
|
1485
|
+
}
|
|
1486
|
+
function generateUnhandledRequestMessage() {
|
|
1487
|
+
const publicUrl = getPublicUrlFromRequest(request);
|
|
1488
|
+
const requestHeader = parsedGraphQLQuery ? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})` : `${request.method} ${publicUrl}`;
|
|
1489
|
+
const handlerSuggestion = generateHandlerSuggestion();
|
|
1490
|
+
const messageTemplate = [
|
|
1491
|
+
`captured a request without a matching request handler:`,
|
|
1492
|
+
` \u2022 ${requestHeader}`,
|
|
1493
|
+
handlerSuggestion,
|
|
1494
|
+
`If you still wish to intercept this unhandled request, please create a request handler for it.
|
|
1495
|
+
Read more: https://mswjs.io/docs/getting-started/mocks`
|
|
1496
|
+
].filter(Boolean);
|
|
1497
|
+
return messageTemplate.join("\n\n");
|
|
1498
|
+
}
|
|
1499
|
+
function applyStrategy(strategy2) {
|
|
1500
|
+
const message = generateUnhandledRequestMessage();
|
|
1501
|
+
switch (strategy2) {
|
|
1502
|
+
case "error": {
|
|
1503
|
+
devUtils.error("Error: %s", message);
|
|
1504
|
+
throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
|
|
1505
|
+
}
|
|
1506
|
+
case "warn": {
|
|
1507
|
+
devUtils.warn("Warning: %s", message);
|
|
1508
|
+
break;
|
|
1509
|
+
}
|
|
1510
|
+
case "bypass":
|
|
1511
|
+
break;
|
|
1512
|
+
default:
|
|
1513
|
+
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.', strategy2));
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
if (typeof strategy === "function") {
|
|
1517
|
+
strategy(request, {
|
|
1518
|
+
warning: applyStrategy.bind(null, "warn"),
|
|
1519
|
+
error: applyStrategy.bind(null, "error")
|
|
1520
|
+
});
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
applyStrategy(strategy);
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
// src/utils/request/readResponseCookies.ts
|
|
1527
|
+
init_cjs_shims();
|
|
1528
|
+
var import_cookies2 = require("@mswjs/cookies");
|
|
1529
|
+
function readResponseCookies(request, response2) {
|
|
1530
|
+
import_cookies2.store.add(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }), response2);
|
|
1531
|
+
import_cookies2.store.persist();
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// src/utils/handleRequest.ts
|
|
1535
|
+
async function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
|
|
1536
|
+
var _a, _b, _c, _d;
|
|
1537
|
+
emitter.emit("request:start", request);
|
|
1538
|
+
if (request.headers.get("x-msw-bypass") === "true") {
|
|
1539
|
+
emitter.emit("request:end", request);
|
|
1540
|
+
(_a = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a.call(handleRequestOptions, request);
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
const [lookupError, lookupResult] = await (0, import_until2.until)(() => {
|
|
1544
|
+
return getResponse(request, handlers, handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext);
|
|
1545
|
+
});
|
|
1546
|
+
if (lookupError) {
|
|
1547
|
+
emitter.emit("unhandledException", lookupError, request);
|
|
1548
|
+
throw lookupError;
|
|
1549
|
+
}
|
|
1550
|
+
const { handler, response: response2 } = lookupResult;
|
|
1551
|
+
if (!handler) {
|
|
1552
|
+
onUnhandledRequest(request, handlers, options.onUnhandledRequest);
|
|
1553
|
+
emitter.emit("request:unhandled", request);
|
|
1554
|
+
emitter.emit("request:end", request);
|
|
1555
|
+
(_b = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b.call(handleRequestOptions, request);
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
if (!response2) {
|
|
1559
|
+
devUtils.warn(`Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.
|
|
1560
|
+
|
|
1561
|
+
\u2022 %s
|
|
1562
|
+
%s`, response2, handler.info.header, handler.info.callFrame);
|
|
1563
|
+
emitter.emit("request:end", request);
|
|
1564
|
+
(_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
if (response2.passthrough) {
|
|
1568
|
+
emitter.emit("request:end", request);
|
|
1569
|
+
(_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
readResponseCookies(request, response2);
|
|
1573
|
+
emitter.emit("request:match", request);
|
|
1574
|
+
return new Promise((resolve) => {
|
|
1575
|
+
var _a2, _b2, _c2;
|
|
1576
|
+
const requiredLookupResult = lookupResult;
|
|
1577
|
+
const transformedResponse = ((_a2 = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _a2.call(handleRequestOptions, response2)) || response2;
|
|
1578
|
+
(_b2 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _b2.call(handleRequestOptions, transformedResponse, requiredLookupResult);
|
|
1579
|
+
setTimeout(() => {
|
|
1580
|
+
var _a3;
|
|
1581
|
+
(_a3 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponseSent) == null ? void 0 : _a3.call(handleRequestOptions, transformedResponse, requiredLookupResult);
|
|
1582
|
+
emitter.emit("request:end", request);
|
|
1583
|
+
resolve(transformedResponse);
|
|
1584
|
+
}, (_c2 = response2.delay) != null ? _c2 : 0);
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
// src/utils/worker/createRequestListener.ts
|
|
1589
|
+
var createRequestListener = (context, options) => {
|
|
1590
|
+
return async (event, message) => {
|
|
1591
|
+
const channel = createBroadcastChannel(event);
|
|
1592
|
+
try {
|
|
1593
|
+
const request = parseWorkerRequest(message.payload);
|
|
1594
|
+
await handleRequest(request, context.requestHandlers, options, context.emitter, {
|
|
1595
|
+
transformResponse(response2) {
|
|
1596
|
+
return __spreadProps(__spreadValues({}, response2), {
|
|
1597
|
+
headers: response2.headers.all()
|
|
1598
|
+
});
|
|
1599
|
+
},
|
|
1600
|
+
onPassthroughResponse() {
|
|
1601
|
+
return channel.send({
|
|
1602
|
+
type: "MOCK_NOT_FOUND"
|
|
1603
|
+
});
|
|
1604
|
+
},
|
|
1605
|
+
onMockedResponse(response2) {
|
|
1606
|
+
channel.send({
|
|
1607
|
+
type: "MOCK_SUCCESS",
|
|
1608
|
+
payload: response2
|
|
1609
|
+
});
|
|
1610
|
+
},
|
|
1611
|
+
onMockedResponseSent(response2, { handler, publicRequest, parsedRequest }) {
|
|
1612
|
+
if (!options.quiet) {
|
|
1613
|
+
handler.log(publicRequest, response2, handler, parsedRequest);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
});
|
|
1617
|
+
} catch (error2) {
|
|
1618
|
+
if (error2 instanceof NetworkError) {
|
|
1619
|
+
return channel.send({
|
|
1620
|
+
type: "NETWORK_ERROR",
|
|
1621
|
+
payload: {
|
|
1622
|
+
name: error2.name,
|
|
1623
|
+
message: error2.message
|
|
1624
|
+
}
|
|
1625
|
+
});
|
|
1626
|
+
}
|
|
1627
|
+
if (error2 instanceof Error) {
|
|
1628
|
+
channel.send({
|
|
1629
|
+
type: "INTERNAL_ERROR",
|
|
1630
|
+
payload: {
|
|
1631
|
+
status: 500,
|
|
1632
|
+
body: JSON.stringify({
|
|
1633
|
+
errorType: error2.constructor.name,
|
|
1634
|
+
message: error2.message,
|
|
1635
|
+
location: error2.stack
|
|
1636
|
+
})
|
|
1637
|
+
}
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
};
|
|
1642
|
+
};
|
|
1643
|
+
|
|
1644
|
+
// src/utils/internal/requestIntegrityCheck.ts
|
|
1645
|
+
init_cjs_shims();
|
|
1646
|
+
async function requestIntegrityCheck(context, serviceWorker) {
|
|
1647
|
+
context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
|
|
1648
|
+
const { payload: actualChecksum } = await context.events.once("INTEGRITY_CHECK_RESPONSE");
|
|
1649
|
+
if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
|
|
1650
|
+
throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
|
|
1651
|
+
}
|
|
1652
|
+
return serviceWorker;
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
// src/utils/deferNetworkRequestsUntil.ts
|
|
1656
|
+
init_cjs_shims();
|
|
1657
|
+
var import_until3 = require("@open-draft/until");
|
|
1658
|
+
function deferNetworkRequestsUntil(predicatePromise) {
|
|
1659
|
+
const originalXhrSend = window.XMLHttpRequest.prototype.send;
|
|
1660
|
+
window.XMLHttpRequest.prototype.send = function(...args) {
|
|
1661
|
+
(0, import_until3.until)(() => predicatePromise).then(() => {
|
|
1662
|
+
window.XMLHttpRequest.prototype.send = originalXhrSend;
|
|
1663
|
+
this.send(...args);
|
|
1664
|
+
});
|
|
1665
|
+
};
|
|
1666
|
+
const originalFetch = window.fetch;
|
|
1667
|
+
window.fetch = async (...args) => {
|
|
1668
|
+
await (0, import_until3.until)(() => predicatePromise);
|
|
1669
|
+
window.fetch = originalFetch;
|
|
1670
|
+
return window.fetch(...args);
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
// src/utils/worker/createResponseListener.ts
|
|
1675
|
+
init_cjs_shims();
|
|
1676
|
+
function createResponseListener(context) {
|
|
1677
|
+
return (_, message) => {
|
|
1678
|
+
var _a;
|
|
1679
|
+
const { payload: responseJson } = message;
|
|
1680
|
+
if ((_a = responseJson.type) == null ? void 0 : _a.includes("opaque")) {
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
const response2 = new Response(responseJson.body || null, responseJson);
|
|
1684
|
+
const isMockedResponse = response2.headers.get("x-powered-by") === "msw";
|
|
1685
|
+
if (isMockedResponse) {
|
|
1686
|
+
context.emitter.emit("response:mocked", response2, responseJson.requestId);
|
|
1687
|
+
} else {
|
|
1688
|
+
context.emitter.emit("response:bypass", response2, responseJson.requestId);
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
// src/setupWorker/start/utils/validateWorkerScope.ts
|
|
1694
|
+
init_cjs_shims();
|
|
1695
|
+
function validateWorkerScope(registration, options) {
|
|
1696
|
+
if (!(options == null ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
|
|
1697
|
+
devUtils.warn(`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.
|
|
1698
|
+
|
|
1699
|
+
- (Recommended) Register the worker at the root level ("/") of your application.
|
|
1700
|
+
- Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.`);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
// src/setupWorker/start/createStartHandler.ts
|
|
1705
|
+
var createStartHandler = (context) => {
|
|
1706
|
+
return function start(options, customOptions) {
|
|
1707
|
+
const startWorkerInstance = async () => {
|
|
1708
|
+
context.events.removeAllListeners();
|
|
1709
|
+
context.workerChannel.on("REQUEST", createRequestListener(context, options));
|
|
1710
|
+
context.workerChannel.on("RESPONSE", createResponseListener(context));
|
|
1711
|
+
const instance = await getWorkerInstance(options.serviceWorker.url, options.serviceWorker.options, options.findWorker);
|
|
1712
|
+
const [worker, registration] = instance;
|
|
1713
|
+
if (!worker) {
|
|
1714
|
+
const missingWorkerMessage = (customOptions == null ? void 0 : customOptions.findWorker) ? devUtils.formatMessage(`Failed to locate the Service Worker registration using a custom "findWorker" predicate.
|
|
1715
|
+
|
|
1716
|
+
Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
|
|
1717
|
+
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
|
|
1718
|
+
`, options.serviceWorker.url) : devUtils.formatMessage(`Failed to locate the Service Worker registration.
|
|
1719
|
+
|
|
1720
|
+
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.
|
|
1721
|
+
|
|
1722
|
+
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);
|
|
1723
|
+
throw new Error(missingWorkerMessage);
|
|
1724
|
+
}
|
|
1725
|
+
context.worker = worker;
|
|
1726
|
+
context.registration = registration;
|
|
1727
|
+
context.events.addListener(window, "beforeunload", () => {
|
|
1728
|
+
if (worker.state !== "redundant") {
|
|
1729
|
+
context.workerChannel.send("CLIENT_CLOSED");
|
|
1730
|
+
}
|
|
1731
|
+
window.clearInterval(context.keepAliveInterval);
|
|
1732
|
+
});
|
|
1733
|
+
const [integrityError] = await (0, import_until4.until)(() => requestIntegrityCheck(context, worker));
|
|
1734
|
+
if (integrityError) {
|
|
1735
|
+
devUtils.error(`Detected outdated Service Worker: ${integrityError.message}
|
|
1736
|
+
|
|
1737
|
+
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
|
|
1738
|
+
|
|
1739
|
+
$ npx msw init <PUBLIC_DIR>
|
|
1740
|
+
|
|
1741
|
+
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
|
|
1742
|
+
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues `);
|
|
1743
|
+
}
|
|
1744
|
+
context.keepAliveInterval = window.setInterval(() => context.workerChannel.send("KEEPALIVE_REQUEST"), 5e3);
|
|
1745
|
+
validateWorkerScope(registration, context.startOptions);
|
|
1746
|
+
return registration;
|
|
1747
|
+
};
|
|
1748
|
+
const workerRegistration = startWorkerInstance().then(async (registration) => {
|
|
1749
|
+
const pendingInstance = registration.installing || registration.waiting;
|
|
1750
|
+
if (pendingInstance) {
|
|
1751
|
+
await new Promise((resolve) => {
|
|
1752
|
+
pendingInstance.addEventListener("statechange", () => {
|
|
1753
|
+
if (pendingInstance.state === "activated") {
|
|
1754
|
+
return resolve();
|
|
1755
|
+
}
|
|
1756
|
+
});
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
await enableMocking(context, options).catch((error2) => {
|
|
1760
|
+
throw new Error(`Failed to enable mocking: ${error2 == null ? void 0 : error2.message}`);
|
|
1761
|
+
});
|
|
1762
|
+
return registration;
|
|
1763
|
+
});
|
|
1764
|
+
if (options.waitUntilReady) {
|
|
1765
|
+
deferNetworkRequestsUntil(workerRegistration);
|
|
1766
|
+
}
|
|
1767
|
+
return workerRegistration;
|
|
1768
|
+
};
|
|
1769
|
+
};
|
|
1770
|
+
|
|
1771
|
+
// src/setupWorker/stop/createStop.ts
|
|
1772
|
+
init_cjs_shims();
|
|
1773
|
+
|
|
1774
|
+
// src/setupWorker/stop/utils/printStopMessage.ts
|
|
1775
|
+
init_cjs_shims();
|
|
1776
|
+
function printStopMessage(args = {}) {
|
|
1777
|
+
if (args.quiet) {
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
console.log(`%c${devUtils.formatMessage("Mocking disabled.")}`, "color:orangered;font-weight:bold;");
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
// src/setupWorker/stop/createStop.ts
|
|
1784
|
+
var createStop = (context) => {
|
|
1785
|
+
return function stop() {
|
|
1786
|
+
var _a;
|
|
1787
|
+
if (!context.isMockingEnabled) {
|
|
1788
|
+
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.');
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
context.workerChannel.send("MOCK_DEACTIVATE");
|
|
1792
|
+
context.isMockingEnabled = false;
|
|
1793
|
+
window.clearInterval(context.keepAliveInterval);
|
|
1794
|
+
printStopMessage({ quiet: (_a = context.startOptions) == null ? void 0 : _a.quiet });
|
|
1795
|
+
};
|
|
1796
|
+
};
|
|
1797
|
+
|
|
1798
|
+
// src/utils/internal/requestHandlerUtils.ts
|
|
1799
|
+
init_cjs_shims();
|
|
1800
|
+
function use(currentHandlers, ...handlers) {
|
|
1801
|
+
currentHandlers.unshift(...handlers);
|
|
1802
|
+
}
|
|
1803
|
+
function restoreHandlers(handlers) {
|
|
1804
|
+
handlers.forEach((handler) => {
|
|
1805
|
+
handler.markAsSkipped(false);
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
function resetHandlers(initialHandlers, ...nextHandlers) {
|
|
1809
|
+
return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
// src/setupWorker/start/utils/prepareStartHandler.ts
|
|
1813
|
+
init_cjs_shims();
|
|
1814
|
+
var DEFAULT_START_OPTIONS = {
|
|
1815
|
+
serviceWorker: {
|
|
1816
|
+
url: "/mockServiceWorker.js",
|
|
1817
|
+
options: null
|
|
1818
|
+
},
|
|
1819
|
+
quiet: false,
|
|
1820
|
+
waitUntilReady: true,
|
|
1821
|
+
onUnhandledRequest: "warn",
|
|
1822
|
+
findWorker(scriptURL, mockServiceWorkerUrl) {
|
|
1823
|
+
return scriptURL === mockServiceWorkerUrl;
|
|
1824
|
+
}
|
|
1825
|
+
};
|
|
1826
|
+
function resolveStartOptions(initialOptions) {
|
|
1827
|
+
return mergeRight(DEFAULT_START_OPTIONS, initialOptions || {});
|
|
1828
|
+
}
|
|
1829
|
+
function prepareStartHandler(handler, context) {
|
|
1830
|
+
return (initialOptions) => {
|
|
1831
|
+
context.startOptions = resolveStartOptions(initialOptions);
|
|
1832
|
+
return handler(context.startOptions, initialOptions || {});
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
// src/setupWorker/start/createFallbackStart.ts
|
|
1837
|
+
init_cjs_shims();
|
|
1838
|
+
|
|
1839
|
+
// src/utils/worker/createFallbackRequestListener.ts
|
|
1840
|
+
init_cjs_shims();
|
|
1841
|
+
var import_interceptors = require("@mswjs/interceptors");
|
|
1842
|
+
var import_fetch3 = require("@mswjs/interceptors/lib/interceptors/fetch");
|
|
1843
|
+
var import_XMLHttpRequest = require("@mswjs/interceptors/lib/interceptors/XMLHttpRequest");
|
|
1844
|
+
|
|
1845
|
+
// src/utils/request/parseIsomorphicRequest.ts
|
|
1846
|
+
init_cjs_shims();
|
|
1847
|
+
function parseIsomorphicRequest(request) {
|
|
1848
|
+
const mockedRequest = {
|
|
1849
|
+
id: request.id,
|
|
1850
|
+
url: request.url,
|
|
1851
|
+
method: request.method,
|
|
1852
|
+
body: parseBody(request.body, request.headers),
|
|
1853
|
+
credentials: request.credentials || "same-origin",
|
|
1854
|
+
headers: request.headers,
|
|
1855
|
+
cookies: {},
|
|
1856
|
+
redirect: "manual",
|
|
1857
|
+
referrer: "",
|
|
1858
|
+
keepalive: false,
|
|
1859
|
+
cache: "default",
|
|
1860
|
+
mode: "cors",
|
|
1861
|
+
referrerPolicy: "no-referrer",
|
|
1862
|
+
integrity: "",
|
|
1863
|
+
destination: "document",
|
|
1864
|
+
bodyUsed: false,
|
|
1865
|
+
passthrough
|
|
1866
|
+
};
|
|
1867
|
+
setRequestCookies(mockedRequest);
|
|
1868
|
+
return mockedRequest;
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
// src/utils/worker/createFallbackRequestListener.ts
|
|
1872
|
+
function createFallbackRequestListener(context, options) {
|
|
1873
|
+
const interceptor = (0, import_interceptors.createInterceptor)({
|
|
1874
|
+
modules: [import_fetch3.interceptFetch, import_XMLHttpRequest.interceptXMLHttpRequest],
|
|
1875
|
+
async resolver(request) {
|
|
1876
|
+
const mockedRequest = parseIsomorphicRequest(request);
|
|
1877
|
+
return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
|
|
1878
|
+
transformResponse(response2) {
|
|
1879
|
+
return {
|
|
1880
|
+
status: response2.status,
|
|
1881
|
+
statusText: response2.statusText,
|
|
1882
|
+
headers: response2.headers.all(),
|
|
1883
|
+
body: response2.body
|
|
1884
|
+
};
|
|
1885
|
+
},
|
|
1886
|
+
onMockedResponseSent(response2, { handler, publicRequest, parsedRequest }) {
|
|
1887
|
+
if (!options.quiet) {
|
|
1888
|
+
handler.log(publicRequest, response2, handler, parsedRequest);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
});
|
|
1894
|
+
interceptor.apply();
|
|
1895
|
+
return interceptor;
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
// src/setupWorker/start/createFallbackStart.ts
|
|
1899
|
+
function createFallbackStart(context) {
|
|
1900
|
+
return async function start(options) {
|
|
1901
|
+
context.fallbackInterceptor = createFallbackRequestListener(context, options);
|
|
1902
|
+
printStartMessage({
|
|
1903
|
+
message: "Mocking enabled (fallback mode).",
|
|
1904
|
+
quiet: options.quiet
|
|
1905
|
+
});
|
|
1906
|
+
return void 0;
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
// src/setupWorker/stop/createFallbackStop.ts
|
|
1911
|
+
init_cjs_shims();
|
|
1912
|
+
function createFallbackStop(context) {
|
|
1913
|
+
return function stop() {
|
|
1914
|
+
var _a, _b;
|
|
1915
|
+
(_a = context.fallbackInterceptor) == null ? void 0 : _a.restore();
|
|
1916
|
+
printStopMessage({ quiet: (_b = context.startOptions) == null ? void 0 : _b.quiet });
|
|
1917
|
+
};
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// src/utils/internal/pipeEvents.ts
|
|
1921
|
+
init_cjs_shims();
|
|
1922
|
+
function pipeEvents(source, destination) {
|
|
1923
|
+
const rawEmit = source.emit;
|
|
1924
|
+
if (rawEmit._isPiped) {
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
source.emit = function(event, ...data2) {
|
|
1928
|
+
destination.emit(event, ...data2);
|
|
1929
|
+
return rawEmit.call(this, event, ...data2);
|
|
1930
|
+
};
|
|
1931
|
+
source.emit._isPiped = true;
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
// src/setupWorker/setupWorker.ts
|
|
1935
|
+
var listeners = [];
|
|
1936
|
+
function setupWorker(...requestHandlers) {
|
|
1937
|
+
requestHandlers.forEach((handler) => {
|
|
1938
|
+
if (Array.isArray(handler))
|
|
1939
|
+
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).'));
|
|
1940
|
+
});
|
|
1941
|
+
if ((0, import_is_node_process3.isNodeProcess)()) {
|
|
1942
|
+
throw new Error(devUtils.formatMessage("Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead."));
|
|
1943
|
+
}
|
|
1944
|
+
const emitter = new import_strict_event_emitter.StrictEventEmitter();
|
|
1945
|
+
const publicEmitter = new import_strict_event_emitter.StrictEventEmitter();
|
|
1946
|
+
pipeEvents(emitter, publicEmitter);
|
|
1947
|
+
const context = {
|
|
1948
|
+
isMockingEnabled: false,
|
|
1949
|
+
startOptions: void 0,
|
|
1950
|
+
worker: null,
|
|
1951
|
+
registration: null,
|
|
1952
|
+
requestHandlers: [...requestHandlers],
|
|
1953
|
+
emitter,
|
|
1954
|
+
workerChannel: {
|
|
1955
|
+
on(eventType, callback) {
|
|
1956
|
+
context.events.addListener(navigator.serviceWorker, "message", (event) => {
|
|
1957
|
+
if (event.source !== context.worker) {
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
const message = jsonParse(event.data);
|
|
1961
|
+
if (!message) {
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
if (message.type === eventType) {
|
|
1965
|
+
callback(event, message);
|
|
1966
|
+
}
|
|
1967
|
+
});
|
|
1968
|
+
},
|
|
1969
|
+
send(type) {
|
|
1970
|
+
var _a;
|
|
1971
|
+
(_a = context.worker) == null ? void 0 : _a.postMessage(type);
|
|
1972
|
+
}
|
|
1973
|
+
},
|
|
1974
|
+
events: {
|
|
1975
|
+
addListener(target, eventType, callback) {
|
|
1976
|
+
target.addEventListener(eventType, callback);
|
|
1977
|
+
listeners.push({ eventType, target, callback });
|
|
1978
|
+
return () => {
|
|
1979
|
+
target.removeEventListener(eventType, callback);
|
|
1980
|
+
};
|
|
1981
|
+
},
|
|
1982
|
+
removeAllListeners() {
|
|
1983
|
+
for (const { target, eventType, callback } of listeners) {
|
|
1984
|
+
target.removeEventListener(eventType, callback);
|
|
1985
|
+
}
|
|
1986
|
+
listeners = [];
|
|
1987
|
+
},
|
|
1988
|
+
once(eventType) {
|
|
1989
|
+
const bindings = [];
|
|
1990
|
+
return new Promise((resolve, reject) => {
|
|
1991
|
+
const handleIncomingMessage = (event) => {
|
|
1992
|
+
try {
|
|
1993
|
+
const message = JSON.parse(event.data);
|
|
1994
|
+
if (message.type === eventType) {
|
|
1995
|
+
resolve(message);
|
|
1996
|
+
}
|
|
1997
|
+
} catch (error2) {
|
|
1998
|
+
reject(error2);
|
|
1999
|
+
}
|
|
2000
|
+
};
|
|
2001
|
+
bindings.push(context.events.addListener(navigator.serviceWorker, "message", handleIncomingMessage), context.events.addListener(navigator.serviceWorker, "messageerror", reject));
|
|
2002
|
+
}).finally(() => {
|
|
2003
|
+
bindings.forEach((unbind) => unbind());
|
|
2004
|
+
});
|
|
2005
|
+
}
|
|
2006
|
+
},
|
|
2007
|
+
useFallbackMode: !("serviceWorker" in navigator) || location.protocol === "file:"
|
|
2008
|
+
};
|
|
2009
|
+
const startHandler = context.useFallbackMode ? createFallbackStart(context) : createStartHandler(context);
|
|
2010
|
+
const stopHandler = context.useFallbackMode ? createFallbackStop(context) : createStop(context);
|
|
2011
|
+
return {
|
|
2012
|
+
start: prepareStartHandler(startHandler, context),
|
|
2013
|
+
stop() {
|
|
2014
|
+
context.events.removeAllListeners();
|
|
2015
|
+
context.emitter.removeAllListeners();
|
|
2016
|
+
publicEmitter.removeAllListeners();
|
|
2017
|
+
stopHandler();
|
|
2018
|
+
},
|
|
2019
|
+
use(...handlers) {
|
|
2020
|
+
use(context.requestHandlers, ...handlers);
|
|
2021
|
+
},
|
|
2022
|
+
restoreHandlers() {
|
|
2023
|
+
restoreHandlers(context.requestHandlers);
|
|
2024
|
+
},
|
|
2025
|
+
resetHandlers(...nextHandlers) {
|
|
2026
|
+
context.requestHandlers = resetHandlers(requestHandlers, ...nextHandlers);
|
|
2027
|
+
},
|
|
2028
|
+
printHandlers() {
|
|
2029
|
+
context.requestHandlers.forEach((handler) => {
|
|
2030
|
+
const { header, callFrame } = handler.info;
|
|
2031
|
+
const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
|
|
2032
|
+
console.groupCollapsed(`${pragma} ${header}`);
|
|
2033
|
+
if (callFrame) {
|
|
2034
|
+
console.log(`Declaration: ${callFrame}`);
|
|
2035
|
+
}
|
|
2036
|
+
console.log("Handler:", handler);
|
|
2037
|
+
if (handler instanceof RestHandler) {
|
|
2038
|
+
console.log("Match:", `https://mswjs.io/repl?path=${handler.info.path}`);
|
|
2039
|
+
}
|
|
2040
|
+
console.groupEnd();
|
|
2041
|
+
});
|
|
2042
|
+
},
|
|
2043
|
+
events: {
|
|
2044
|
+
on(...args) {
|
|
2045
|
+
return publicEmitter.on(...args);
|
|
2046
|
+
},
|
|
2047
|
+
removeListener(...args) {
|
|
2048
|
+
return publicEmitter.removeListener(...args);
|
|
2049
|
+
},
|
|
2050
|
+
removeAllListeners(...args) {
|
|
2051
|
+
return publicEmitter.removeAllListeners(...args);
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
// src/rest.ts
|
|
2058
|
+
init_cjs_shims();
|
|
2059
|
+
function createRestHandler(method) {
|
|
2060
|
+
return (path, resolver) => {
|
|
2061
|
+
return new RestHandler(method, path, resolver);
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
var rest = {
|
|
2065
|
+
all: createRestHandler(/.+/),
|
|
2066
|
+
head: createRestHandler("HEAD" /* HEAD */),
|
|
2067
|
+
get: createRestHandler("GET" /* GET */),
|
|
2068
|
+
post: createRestHandler("POST" /* POST */),
|
|
2069
|
+
put: createRestHandler("PUT" /* PUT */),
|
|
2070
|
+
delete: createRestHandler("DELETE" /* DELETE */),
|
|
2071
|
+
patch: createRestHandler("PATCH" /* PATCH */),
|
|
2072
|
+
options: createRestHandler("OPTIONS" /* OPTIONS */)
|
|
2073
|
+
};
|
|
2074
|
+
|
|
2075
|
+
// src/graphql.ts
|
|
2076
|
+
init_cjs_shims();
|
|
2077
|
+
var import_graphql2 = require("graphql");
|
|
2078
|
+
function createScopedGraphQLHandler(operationType, url) {
|
|
2079
|
+
return (operationName, resolver) => {
|
|
2080
|
+
return new GraphQLHandler(operationType, operationName, url, resolver);
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
function createGraphQLOperationHandler(url) {
|
|
2084
|
+
return (resolver) => {
|
|
2085
|
+
return new GraphQLHandler("all", new RegExp(".*"), url, resolver);
|
|
2086
|
+
};
|
|
2087
|
+
}
|
|
2088
|
+
var standardGraphQLHandlers = {
|
|
2089
|
+
operation: createGraphQLOperationHandler("*"),
|
|
2090
|
+
query: createScopedGraphQLHandler(import_graphql2.OperationTypeNode.QUERY, "*"),
|
|
2091
|
+
mutation: createScopedGraphQLHandler(import_graphql2.OperationTypeNode.MUTATION, "*")
|
|
2092
|
+
};
|
|
2093
|
+
function createGraphQLLink(url) {
|
|
2094
|
+
return {
|
|
2095
|
+
operation: createGraphQLOperationHandler(url),
|
|
2096
|
+
query: createScopedGraphQLHandler(import_graphql2.OperationTypeNode.QUERY, url),
|
|
2097
|
+
mutation: createScopedGraphQLHandler(import_graphql2.OperationTypeNode.MUTATION, url)
|
|
2098
|
+
};
|
|
2099
|
+
}
|
|
2100
|
+
var graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
|
|
2101
|
+
link: createGraphQLLink
|
|
2102
|
+
});
|
|
2103
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2104
|
+
0 && (module.exports = {
|
|
2105
|
+
GraphQLHandler,
|
|
2106
|
+
RESTMethods,
|
|
2107
|
+
RequestHandler,
|
|
2108
|
+
RestHandler,
|
|
2109
|
+
cleanUrl,
|
|
2110
|
+
compose,
|
|
2111
|
+
context,
|
|
2112
|
+
createResponseComposition,
|
|
2113
|
+
defaultContext,
|
|
2114
|
+
defaultResponse,
|
|
2115
|
+
graphql,
|
|
2116
|
+
graphqlContext,
|
|
2117
|
+
handleRequest,
|
|
2118
|
+
matchRequestUrl,
|
|
2119
|
+
parseIsomorphicRequest,
|
|
2120
|
+
response,
|
|
2121
|
+
rest,
|
|
2122
|
+
restContext,
|
|
2123
|
+
setupWorker
|
|
2124
|
+
});
|
|
2125
|
+
//# sourceMappingURL=index.js.map
|