@mswjs/interceptors 0.39.7 → 0.39.8
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/lib/browser/{chunk-PFGO5BSM.js → chunk-2HUMWGRD.js} +15 -3
- package/lib/browser/chunk-2HUMWGRD.js.map +1 -0
- package/lib/browser/{chunk-XX6WKANU.js → chunk-2QICSCCS.js} +9 -17
- package/lib/browser/chunk-2QICSCCS.js.map +1 -0
- package/lib/browser/{chunk-ZXAL3FMU.js → chunk-E3CCOBRX.js} +6 -6
- package/lib/browser/{chunk-ZDGZFWQH.mjs → chunk-E7UVBHVO.mjs} +3 -3
- package/lib/browser/{chunk-F2NPA2FP.js → chunk-H74PGQ4Y.js} +9 -9
- package/lib/browser/{chunk-MMKGBEJO.mjs → chunk-PTTUYYVR.mjs} +5 -13
- package/lib/browser/chunk-PTTUYYVR.mjs.map +1 -0
- package/lib/browser/{chunk-MDMPOBGY.mjs → chunk-Q7K2XAEP.mjs} +4 -4
- package/lib/browser/{chunk-TX5GBTFY.mjs → chunk-VYSDLBSS.mjs} +13 -1
- package/lib/browser/chunk-VYSDLBSS.mjs.map +1 -0
- package/lib/browser/interceptors/WebSocket/index.js +6 -4
- package/lib/browser/interceptors/WebSocket/index.js.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.mjs +5 -3
- package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.js +4 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +3 -3
- package/lib/browser/interceptors/fetch/index.js +4 -4
- package/lib/browser/interceptors/fetch/index.mjs +3 -3
- package/lib/browser/presets/browser.js +6 -6
- package/lib/browser/presets/browser.mjs +4 -4
- package/package.json +1 -1
- package/src/interceptors/WebSocket/index.ts +6 -2
- package/lib/browser/chunk-MMKGBEJO.mjs.map +0 -1
- package/lib/browser/chunk-PFGO5BSM.js.map +0 -1
- package/lib/browser/chunk-TX5GBTFY.mjs.map +0 -1
- package/lib/browser/chunk-XX6WKANU.js.map +0 -1
- /package/lib/browser/{chunk-ZXAL3FMU.js.map → chunk-E3CCOBRX.js.map} +0 -0
- /package/lib/browser/{chunk-ZDGZFWQH.mjs.map → chunk-E7UVBHVO.mjs.map} +0 -0
- /package/lib/browser/{chunk-F2NPA2FP.js.map → chunk-H74PGQ4Y.js.map} +0 -0
- /package/lib/browser/{chunk-MDMPOBGY.mjs.map → chunk-Q7K2XAEP.mjs.map} +0 -0
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/emitAsync.ts
|
|
2
|
+
async function emitAsync(emitter, eventName, ...data) {
|
|
3
|
+
const listeners = emitter.listeners(eventName);
|
|
4
|
+
if (listeners.length === 0) {
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
for (const listener of listeners) {
|
|
8
|
+
await listener.apply(emitter, data);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// src/utils/hasConfigurableGlobal.ts
|
|
2
13
|
function hasConfigurableGlobal(propertyName) {
|
|
3
14
|
const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName);
|
|
4
15
|
if (typeof descriptor === "undefined") {
|
|
@@ -21,5 +32,6 @@ function hasConfigurableGlobal(propertyName) {
|
|
|
21
32
|
|
|
22
33
|
|
|
23
34
|
|
|
24
|
-
|
|
25
|
-
|
|
35
|
+
|
|
36
|
+
exports.emitAsync = emitAsync; exports.hasConfigurableGlobal = hasConfigurableGlobal;
|
|
37
|
+
//# sourceMappingURL=chunk-2HUMWGRD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/emitAsync.ts","../../src/utils/hasConfigurableGlobal.ts"],"names":[],"mappings":";AAOA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,YAAY,QAAQ,UAAU,SAAS;AAE7C,MAAI,UAAU,WAAW,GAAG;AAC1B;AAAA,EACF;AAEA,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF;;;ACpBO,SAAS,sBAAsB,cAA+B;AACnE,QAAM,aAAa,OAAO,yBAAyB,YAAY,YAAY;AAG3E,MAAI,OAAO,eAAe,aAAa;AACrC,WAAO;AAAA,EACT;AAGA,MACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,IAAI,MAAM,aAC5B;AACA,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,MAAM;AACrE,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,YAAQ;AAAA,MACN,mDAAmD;AAAA,IACrD;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT","sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"]}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunk2HUMWGRDjs = require('./chunk-2HUMWGRD.js');
|
|
4
|
+
|
|
5
|
+
// src/RequestController.ts
|
|
2
6
|
var _outvariant = require('outvariant');
|
|
3
7
|
var _deferredpromise = require('@open-draft/deferred-promise');
|
|
4
8
|
|
|
@@ -60,17 +64,6 @@ var RequestController = class {
|
|
|
60
64
|
};
|
|
61
65
|
kResponsePromise, kRequestHandled;
|
|
62
66
|
|
|
63
|
-
// src/utils/emitAsync.ts
|
|
64
|
-
async function emitAsync(emitter, eventName, ...data) {
|
|
65
|
-
const listeners = emitter.listeners(eventName);
|
|
66
|
-
if (listeners.length === 0) {
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
for (const listener of listeners) {
|
|
70
|
-
await listener.apply(emitter, data);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
67
|
// src/utils/handleRequest.ts
|
|
75
68
|
|
|
76
69
|
var _until = require('@open-draft/until');
|
|
@@ -184,7 +177,7 @@ async function handleRequest(options) {
|
|
|
184
177
|
}
|
|
185
178
|
}
|
|
186
179
|
const result = await _until.until.call(void 0, async () => {
|
|
187
|
-
const requestListenersPromise = emitAsync(options.emitter, "request", {
|
|
180
|
+
const requestListenersPromise = _chunk2HUMWGRDjs.emitAsync.call(void 0, options.emitter, "request", {
|
|
188
181
|
requestId: options.requestId,
|
|
189
182
|
request: options.request,
|
|
190
183
|
controller: options.controller
|
|
@@ -209,7 +202,7 @@ async function handleRequest(options) {
|
|
|
209
202
|
const unhandledExceptionController = new RequestController(
|
|
210
203
|
options.request
|
|
211
204
|
);
|
|
212
|
-
await emitAsync(options.emitter, "unhandledException", {
|
|
205
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, options.emitter, "unhandledException", {
|
|
213
206
|
error: result.error,
|
|
214
207
|
request: options.request,
|
|
215
208
|
requestId: options.requestId,
|
|
@@ -241,6 +234,5 @@ async function handleRequest(options) {
|
|
|
241
234
|
|
|
242
235
|
|
|
243
236
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
//# sourceMappingURL=chunk-XX6WKANU.js.map
|
|
237
|
+
exports.RequestController = RequestController; exports.handleRequest = handleRequest;
|
|
238
|
+
//# sourceMappingURL=chunk-2QICSCCS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/handleRequest.ts","../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"names":["DeferredPromise"],"mappings":";;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADFA,IAAM,kBAAkB,OAAO,iBAAiB;AACzC,IAAM,mBAAmB,OAAO,kBAAkB;AAElD,IAAM,oBAAN,MAAwB;AAAA,EAkB7B,YAAoB,SAAkB;AAAlB;AAClB,SAAK,eAAe,IAAI;AACxB,SAAK,gBAAgB,IAAI,IAAI,gBAAgB;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,YAAY,UAA0B;AAC3C,cAAU;AAAA,MACR;AAAA,MACA,CAAC,KAAK,eAAe;AAAA,MACrB;AAAA,MACA,KA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QACvB,MAAM,6BAA6B,gBAAgB;AAAA,MACrD;AASA,UAAI,WAAW,OAAO;AACpB,eAAO,oBAAoB,WAAW,KAAK;AAAA,MAC7C;AAEA,UAAI,WAAW,MAAM;AACnB,eAAO,eAAe,WAAW,IAAI;AAAA,MACvC;AAAA,IACF;AAGA,YAAQ,WAAW,0BAA0B,OAAO,KAAK,CAAC;AAC1D,WAAO;AAAA,EACT;AAQA,MAAI,OAAO,MAAM;AACf,WAAO,eAAe,OAAO,IAAI;AAAA,EACnC;AAGA,SAAO;AACT","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<\n Response | Record<string, any> | undefined\n >;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request controller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: Error | Record<string, any>): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(reason)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n options.onError(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n options.onRequestError(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.onResponse(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n options.onError(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n return await options.controller[kResponsePromise]\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n return false\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"]}
|
|
@@ -6,7 +6,7 @@ var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js');
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunk2QICSCCSjs = require('./chunk-2QICSCCS.js');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
@@ -14,7 +14,7 @@ var _chunkXX6WKANUjs = require('./chunk-XX6WKANU.js');
|
|
|
14
14
|
var _chunkT7TBRNJZjs = require('./chunk-T7TBRNJZ.js');
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
var
|
|
17
|
+
var _chunk2HUMWGRDjs = require('./chunk-2HUMWGRD.js');
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
|
|
@@ -743,13 +743,13 @@ function createXMLHttpRequestProxy({
|
|
|
743
743
|
logger
|
|
744
744
|
);
|
|
745
745
|
xhrRequestController.onRequest = async function({ request, requestId }) {
|
|
746
|
-
const controller = new (0,
|
|
746
|
+
const controller = new (0, _chunk2QICSCCSjs.RequestController)(request);
|
|
747
747
|
this.logger.info("awaiting mocked response...");
|
|
748
748
|
this.logger.info(
|
|
749
749
|
'emitting the "request" event for %s listener(s)...',
|
|
750
750
|
emitter.listenerCount("request")
|
|
751
751
|
);
|
|
752
|
-
const isRequestHandled = await
|
|
752
|
+
const isRequestHandled = await _chunk2QICSCCSjs.handleRequest.call(void 0, {
|
|
753
753
|
request,
|
|
754
754
|
requestId,
|
|
755
755
|
controller,
|
|
@@ -802,7 +802,7 @@ var _XMLHttpRequestInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
802
802
|
super(_XMLHttpRequestInterceptor.interceptorSymbol);
|
|
803
803
|
}
|
|
804
804
|
checkEnvironment() {
|
|
805
|
-
return
|
|
805
|
+
return _chunk2HUMWGRDjs.hasConfigurableGlobal.call(void 0, "XMLHttpRequest");
|
|
806
806
|
}
|
|
807
807
|
setup() {
|
|
808
808
|
const logger = this.logger.extend("setup");
|
|
@@ -843,4 +843,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
|
|
|
843
843
|
|
|
844
844
|
|
|
845
845
|
exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor;
|
|
846
|
-
//# sourceMappingURL=chunk-
|
|
846
|
+
//# sourceMappingURL=chunk-E3CCOBRX.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
import {
|
|
7
7
|
RequestController,
|
|
8
8
|
handleRequest
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-PTTUYYVR.mjs";
|
|
10
10
|
import {
|
|
11
11
|
FetchResponse,
|
|
12
12
|
IS_PATCHED_MODULE,
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
} from "./chunk-3RXCRGL2.mjs";
|
|
15
15
|
import {
|
|
16
16
|
hasConfigurableGlobal
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-VYSDLBSS.mjs";
|
|
18
18
|
import {
|
|
19
19
|
INTERNAL_REQUEST_ID_HEADER_NAME,
|
|
20
20
|
Interceptor,
|
|
@@ -843,4 +843,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
|
|
|
843
843
|
export {
|
|
844
844
|
XMLHttpRequestInterceptor
|
|
845
845
|
};
|
|
846
|
-
//# sourceMappingURL=chunk-
|
|
846
|
+
//# sourceMappingURL=chunk-E7UVBHVO.mjs.map
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
var _chunkXX6WKANUjs = require('./chunk-XX6WKANU.js');
|
|
4
|
+
var _chunk2QICSCCSjs = require('./chunk-2QICSCCS.js');
|
|
6
5
|
|
|
7
6
|
|
|
8
7
|
|
|
@@ -11,7 +10,8 @@ var _chunkXX6WKANUjs = require('./chunk-XX6WKANU.js');
|
|
|
11
10
|
var _chunkT7TBRNJZjs = require('./chunk-T7TBRNJZ.js');
|
|
12
11
|
|
|
13
12
|
|
|
14
|
-
|
|
13
|
+
|
|
14
|
+
var _chunk2HUMWGRDjs = require('./chunk-2HUMWGRD.js');
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
|
|
@@ -172,7 +172,7 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
172
172
|
super(_FetchInterceptor.symbol);
|
|
173
173
|
}
|
|
174
174
|
checkEnvironment() {
|
|
175
|
-
return
|
|
175
|
+
return _chunk2HUMWGRDjs.hasConfigurableGlobal.call(void 0, "fetch");
|
|
176
176
|
}
|
|
177
177
|
async setup() {
|
|
178
178
|
const pureFetch = globalThis.fetch;
|
|
@@ -188,14 +188,14 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
188
188
|
_chunkT7TBRNJZjs.setRawRequest.call(void 0, request, input);
|
|
189
189
|
}
|
|
190
190
|
const responsePromise = new (0, _deferredpromise.DeferredPromise)();
|
|
191
|
-
const controller = new (0,
|
|
191
|
+
const controller = new (0, _chunk2QICSCCSjs.RequestController)(request);
|
|
192
192
|
this.logger.info("[%s] %s", request.method, request.url);
|
|
193
193
|
this.logger.info("awaiting for the mocked response...");
|
|
194
194
|
this.logger.info(
|
|
195
195
|
'emitting the "request" event for %s listener(s)...',
|
|
196
196
|
this.emitter.listenerCount("request")
|
|
197
197
|
);
|
|
198
|
-
const isRequestHandled = await
|
|
198
|
+
const isRequestHandled = await _chunk2QICSCCSjs.handleRequest.call(void 0, {
|
|
199
199
|
request,
|
|
200
200
|
requestId,
|
|
201
201
|
emitter: this.emitter,
|
|
@@ -226,7 +226,7 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
226
226
|
}
|
|
227
227
|
if (this.emitter.listenerCount("response") > 0) {
|
|
228
228
|
this.logger.info('emitting the "response" event...');
|
|
229
|
-
await
|
|
229
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, this.emitter, "response", {
|
|
230
230
|
// Clone the mocked response for the "response" event listener.
|
|
231
231
|
// This way, the listener can read the response and not lock its body
|
|
232
232
|
// for the actual fetch consumer.
|
|
@@ -260,7 +260,7 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
260
260
|
if (this.emitter.listenerCount("response") > 0) {
|
|
261
261
|
this.logger.info('emitting the "response" event...');
|
|
262
262
|
const responseClone = response.clone();
|
|
263
|
-
await
|
|
263
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, this.emitter, "response", {
|
|
264
264
|
response: responseClone,
|
|
265
265
|
isMockedResponse: false,
|
|
266
266
|
request: requestCloneForResponseEvent,
|
|
@@ -293,4 +293,4 @@ FetchInterceptor.symbol = Symbol("fetch");
|
|
|
293
293
|
|
|
294
294
|
|
|
295
295
|
exports.FetchInterceptor = FetchInterceptor;
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
296
|
+
//# sourceMappingURL=chunk-H74PGQ4Y.js.map
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
emitAsync
|
|
3
|
+
} from "./chunk-VYSDLBSS.mjs";
|
|
4
|
+
|
|
1
5
|
// src/RequestController.ts
|
|
2
6
|
import { invariant } from "outvariant";
|
|
3
7
|
import { DeferredPromise } from "@open-draft/deferred-promise";
|
|
@@ -60,17 +64,6 @@ var RequestController = class {
|
|
|
60
64
|
};
|
|
61
65
|
kResponsePromise, kRequestHandled;
|
|
62
66
|
|
|
63
|
-
// src/utils/emitAsync.ts
|
|
64
|
-
async function emitAsync(emitter, eventName, ...data) {
|
|
65
|
-
const listeners = emitter.listeners(eventName);
|
|
66
|
-
if (listeners.length === 0) {
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
for (const listener of listeners) {
|
|
70
|
-
await listener.apply(emitter, data);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
67
|
// src/utils/handleRequest.ts
|
|
75
68
|
import { DeferredPromise as DeferredPromise2 } from "@open-draft/deferred-promise";
|
|
76
69
|
import { until } from "@open-draft/until";
|
|
@@ -240,7 +233,6 @@ async function handleRequest(options) {
|
|
|
240
233
|
|
|
241
234
|
export {
|
|
242
235
|
RequestController,
|
|
243
|
-
emitAsync,
|
|
244
236
|
handleRequest
|
|
245
237
|
};
|
|
246
|
-
//# sourceMappingURL=chunk-
|
|
238
|
+
//# sourceMappingURL=chunk-PTTUYYVR.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/handleRequest.ts","../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<\n Response | Record<string, any> | undefined\n >;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request controller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: Error | Record<string, any>): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(reason)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n options.onError(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n options.onRequestError(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.onResponse(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n options.onError(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n return await options.controller[kResponsePromise]\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n return false\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"],"mappings":";;;;;AAAA,SAAS,iBAAi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D,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,OAAO;AAGhB,QAAI,MAAM,oBAAoB,OAAO,KAAK,GAAG;AAC3C,aAAO;AAAA,IACT;AAKA,QAAI,QAAQ,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AAI3D,YAAM,+BAA+B,IAAI;AAAA,QACvC,QAAQ;AAAA,MACV;AAEA,YAAM,UAAU,QAAQ,SAAS,sBAAsB;AAAA,QACrD,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ;AAAA,QACjB,WAAW,QAAQ;AAAA,QACnB,YAAY;AAAA,MACd,CAAC,EAAE,KAAK,MAAM;AAKZ,YACE,6BAA6B,gBAAgB,EAAE,UAAU,WACzD;AACA,uCAA6B,gBAAgB,EAAE,QAAQ,MAAS;AAAA,QAClE;AAAA,MACF,CAAC;AAED,YAAM,aAAa,MAAM;AAAA,QACvB,MAAM,6BAA6B,gBAAgB;AAAA,MACrD;AASA,UAAI,WAAW,OAAO;AACpB,eAAO,oBAAoB,WAAW,KAAK;AAAA,MAC7C;AAEA,UAAI,WAAW,MAAM;AACnB,eAAO,eAAe,WAAW,IAAI;AAAA,MACvC;AAAA,IACF;AAGA,YAAQ,WAAW,0BAA0B,OAAO,KAAK,CAAC;AAC1D,WAAO;AAAA,EACT;AAQA,MAAI,OAAO,MAAM;AACf,WAAO,eAAe,OAAO,IAAI;AAAA,EACnC;AAGA,SAAO;AACT;","names":["DeferredPromise","DeferredPromise"]}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
RequestController,
|
|
3
|
-
emitAsync,
|
|
4
3
|
handleRequest
|
|
5
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-PTTUYYVR.mjs";
|
|
6
5
|
import {
|
|
7
6
|
FetchResponse,
|
|
8
7
|
IS_PATCHED_MODULE,
|
|
@@ -10,8 +9,9 @@ import {
|
|
|
10
9
|
setRawRequest
|
|
11
10
|
} from "./chunk-3RXCRGL2.mjs";
|
|
12
11
|
import {
|
|
12
|
+
emitAsync,
|
|
13
13
|
hasConfigurableGlobal
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-VYSDLBSS.mjs";
|
|
15
15
|
import {
|
|
16
16
|
Interceptor,
|
|
17
17
|
createRequestId
|
|
@@ -293,4 +293,4 @@ FetchInterceptor.symbol = Symbol("fetch");
|
|
|
293
293
|
export {
|
|
294
294
|
FetchInterceptor
|
|
295
295
|
};
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
296
|
+
//# sourceMappingURL=chunk-Q7K2XAEP.mjs.map
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
// src/utils/emitAsync.ts
|
|
2
|
+
async function emitAsync(emitter, eventName, ...data) {
|
|
3
|
+
const listeners = emitter.listeners(eventName);
|
|
4
|
+
if (listeners.length === 0) {
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
for (const listener of listeners) {
|
|
8
|
+
await listener.apply(emitter, data);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
1
12
|
// src/utils/hasConfigurableGlobal.ts
|
|
2
13
|
function hasConfigurableGlobal(propertyName) {
|
|
3
14
|
const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName);
|
|
@@ -20,6 +31,7 @@ function hasConfigurableGlobal(propertyName) {
|
|
|
20
31
|
}
|
|
21
32
|
|
|
22
33
|
export {
|
|
34
|
+
emitAsync,
|
|
23
35
|
hasConfigurableGlobal
|
|
24
36
|
};
|
|
25
|
-
//# sourceMappingURL=chunk-
|
|
37
|
+
//# sourceMappingURL=chunk-VYSDLBSS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/emitAsync.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";AAOA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,YAAY,QAAQ,UAAU,SAAS;AAE7C,MAAI,UAAU,WAAW,GAAG;AAC1B;AAAA,EACF;AAEA,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF;;;ACpBO,SAAS,sBAAsB,cAA+B;AACnE,QAAM,aAAa,OAAO,yBAAyB,YAAY,YAAY;AAG3E,MAAI,OAAO,eAAe,aAAa;AACrC,WAAO;AAAA,EACT;AAGA,MACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,IAAI,MAAM,aAC5B;AACA,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,MAAM;AACrE,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,YAAQ;AAAA,MACN,mDAAmD;AAAA,IACrD;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
var _chunk2HUMWGRDjs = require('../../chunk-2HUMWGRD.js');
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
|
|
@@ -637,7 +638,7 @@ var _WebSocketInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
637
638
|
super(_WebSocketInterceptor.symbol);
|
|
638
639
|
}
|
|
639
640
|
checkEnvironment() {
|
|
640
|
-
return
|
|
641
|
+
return _chunk2HUMWGRDjs.hasConfigurableGlobal.call(void 0, "WebSocket");
|
|
641
642
|
}
|
|
642
643
|
setup() {
|
|
643
644
|
const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(
|
|
@@ -652,14 +653,15 @@ var _WebSocketInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
652
653
|
};
|
|
653
654
|
const socket = new WebSocketOverride(url, protocols);
|
|
654
655
|
const transport = new WebSocketClassTransport(socket);
|
|
655
|
-
queueMicrotask(() => {
|
|
656
|
+
queueMicrotask(async () => {
|
|
656
657
|
try {
|
|
657
658
|
const server = new WebSocketServerConnection(
|
|
658
659
|
socket,
|
|
659
660
|
transport,
|
|
660
661
|
createConnection
|
|
661
662
|
);
|
|
662
|
-
const hasConnectionListeners = this.emitter.
|
|
663
|
+
const hasConnectionListeners = this.emitter.listenerCount("connection") > 0;
|
|
664
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, this.emitter, "connection", {
|
|
663
665
|
client: new WebSocketClientConnection(socket, transport),
|
|
664
666
|
server,
|
|
665
667
|
info: {
|