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