Spaces:
Paused
Paused
Include updated package-lock.json (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- node_modules/msw/src/core/passthrough.test.ts +11 -0
- node_modules/msw/src/core/passthrough.ts +25 -0
- node_modules/msw/src/core/sharedOptions.ts +71 -0
- node_modules/msw/src/core/sse.ts +1017 -0
- node_modules/msw/src/core/typeUtils.ts +26 -0
- node_modules/msw/src/core/utils/HttpResponse/decorators.ts +61 -0
- node_modules/msw/src/core/utils/cookieStore.ts +95 -0
- node_modules/msw/src/core/utils/executeHandlers.ts +67 -0
- node_modules/msw/src/core/utils/handleRequest.test.ts +574 -0
- node_modules/msw/src/core/utils/handleRequest.ts +117 -0
- node_modules/msw/src/core/utils/internal/Disposable.ts +33 -0
- node_modules/msw/src/core/utils/internal/attachSiblingHandlers.ts +28 -0
- node_modules/msw/src/core/utils/internal/checkGlobals.ts +17 -0
- node_modules/msw/src/core/utils/internal/devUtils.test.ts +21 -0
- node_modules/msw/src/core/utils/internal/devUtils.ts +44 -0
- node_modules/msw/src/core/utils/internal/getCallFrame.test.ts +154 -0
- node_modules/msw/src/core/utils/internal/getCallFrame.ts +35 -0
- node_modules/msw/src/core/utils/internal/hasRefCounted.test.ts +37 -0
- node_modules/msw/src/core/utils/internal/hasRefCounted.ts +15 -0
- node_modules/msw/src/core/utils/internal/isHandlerKind.test.ts +62 -0
- node_modules/msw/src/core/utils/internal/isHandlerKind.ts +17 -0
- node_modules/msw/src/core/utils/internal/isIterable.test.ts +23 -0
- node_modules/msw/src/core/utils/internal/isIterable.ts +32 -0
- node_modules/msw/src/core/utils/internal/isObject.test.ts +20 -0
- node_modules/msw/src/core/utils/internal/isObject.ts +6 -0
- node_modules/msw/src/core/utils/internal/isStringEqual.test.ts +45 -0
- node_modules/msw/src/core/utils/internal/isStringEqual.ts +6 -0
- node_modules/msw/src/core/utils/internal/jsonParse.test.ts +13 -0
- node_modules/msw/src/core/utils/internal/jsonParse.ts +13 -0
- node_modules/msw/src/core/utils/internal/mergeRight.test.ts +43 -0
- node_modules/msw/src/core/utils/internal/mergeRight.ts +30 -0
- node_modules/msw/src/core/utils/internal/parseGraphQLRequest.test.ts +97 -0
- node_modules/msw/src/core/utils/internal/parseGraphQLRequest.ts +214 -0
- node_modules/msw/src/core/utils/internal/parseMultipartData.test.ts +76 -0
- node_modules/msw/src/core/utils/internal/parseMultipartData.ts +106 -0
- node_modules/msw/src/core/utils/internal/pipeEvents.test.ts +14 -0
- node_modules/msw/src/core/utils/internal/pipeEvents.ts +26 -0
- node_modules/msw/src/core/utils/internal/toReadonlyArray.test.ts +30 -0
- node_modules/msw/src/core/utils/internal/toReadonlyArray.ts +8 -0
- node_modules/msw/src/core/utils/internal/tryCatch.test.ts +29 -0
- node_modules/msw/src/core/utils/internal/tryCatch.ts +11 -0
- node_modules/msw/src/core/utils/logging/getStatusCodeColor.test.ts +22 -0
- node_modules/msw/src/core/utils/logging/getStatusCodeColor.ts +20 -0
- node_modules/msw/src/core/utils/logging/getTimestamp.test.ts +32 -0
- node_modules/msw/src/core/utils/logging/getTimestamp.ts +17 -0
- node_modules/msw/src/core/utils/logging/serializeRequest.test.ts +23 -0
- node_modules/msw/src/core/utils/logging/serializeRequest.ts +23 -0
- node_modules/msw/src/core/utils/logging/serializeResponse.test.ts +77 -0
- node_modules/msw/src/core/utils/logging/serializeResponse.ts +31 -0
- node_modules/msw/src/core/utils/matching/matchRequestUrl.test.ts +267 -0
node_modules/msw/src/core/passthrough.test.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @vitest-environment node
|
| 2 |
+
import { passthrough } from './passthrough'
|
| 3 |
+
|
| 4 |
+
it('creates a 302 response with the intention header', () => {
|
| 5 |
+
const response = passthrough()
|
| 6 |
+
|
| 7 |
+
expect(response).toBeInstanceOf(Response)
|
| 8 |
+
expect(response.status).toBe(302)
|
| 9 |
+
expect(response.statusText).toBe('Passthrough')
|
| 10 |
+
expect(response.headers.get('x-msw-intention')).toBe('passthrough')
|
| 11 |
+
})
|
node_modules/msw/src/core/passthrough.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { HttpResponse } from './HttpResponse'
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Performs the intercepted request as-is.
|
| 5 |
+
*
|
| 6 |
+
* This stops request handler lookup so no other handlers
|
| 7 |
+
* can affect this request past this point.
|
| 8 |
+
* Unlike `bypass()`, this will not trigger an additional request.
|
| 9 |
+
*
|
| 10 |
+
* @example
|
| 11 |
+
* http.get('/resource', () => {
|
| 12 |
+
* return passthrough()
|
| 13 |
+
* })
|
| 14 |
+
*
|
| 15 |
+
* @see {@link https://mswjs.io/docs/api/passthrough `passthrough()` API reference}
|
| 16 |
+
*/
|
| 17 |
+
export function passthrough(): HttpResponse<any> {
|
| 18 |
+
return new Response(null, {
|
| 19 |
+
status: 302,
|
| 20 |
+
statusText: 'Passthrough',
|
| 21 |
+
headers: {
|
| 22 |
+
'x-msw-intention': 'passthrough',
|
| 23 |
+
},
|
| 24 |
+
}) as HttpResponse<any>
|
| 25 |
+
}
|
node_modules/msw/src/core/sharedOptions.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Emitter, DefaultEventMap } from 'rettime'
|
| 2 |
+
import type { UnhandledRequestStrategy } from './utils/request/onUnhandledRequest'
|
| 3 |
+
|
| 4 |
+
export interface SharedOptions {
|
| 5 |
+
/**
|
| 6 |
+
* Specifies how to react to a request that has no corresponding
|
| 7 |
+
* request handler. Warns on unhandled requests by default.
|
| 8 |
+
*
|
| 9 |
+
* @example worker.start({ onUnhandledRequest: 'bypass' })
|
| 10 |
+
* @example worker.start({ onUnhandledRequest: 'warn' })
|
| 11 |
+
* @example server.listen({ onUnhandledRequest: 'error' })
|
| 12 |
+
*/
|
| 13 |
+
onUnhandledRequest?: UnhandledRequestStrategy
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
* @deprecated
|
| 18 |
+
* Please use `HttpNetworkFrameEventMap` or `WebSocketNetworkFrameEventMap` instead.
|
| 19 |
+
*/
|
| 20 |
+
export type LifeCycleEventsMap = {
|
| 21 |
+
'request:start': [
|
| 22 |
+
args: {
|
| 23 |
+
request: Request
|
| 24 |
+
requestId: string
|
| 25 |
+
},
|
| 26 |
+
]
|
| 27 |
+
'request:match': [
|
| 28 |
+
args: {
|
| 29 |
+
request: Request
|
| 30 |
+
requestId: string
|
| 31 |
+
},
|
| 32 |
+
]
|
| 33 |
+
'request:unhandled': [
|
| 34 |
+
args: {
|
| 35 |
+
request: Request
|
| 36 |
+
requestId: string
|
| 37 |
+
},
|
| 38 |
+
]
|
| 39 |
+
'request:end': [
|
| 40 |
+
args: {
|
| 41 |
+
request: Request
|
| 42 |
+
requestId: string
|
| 43 |
+
},
|
| 44 |
+
]
|
| 45 |
+
'response:mocked': [
|
| 46 |
+
args: {
|
| 47 |
+
response: Response
|
| 48 |
+
request: Request
|
| 49 |
+
requestId: string
|
| 50 |
+
},
|
| 51 |
+
]
|
| 52 |
+
'response:bypass': [
|
| 53 |
+
args: {
|
| 54 |
+
response: Response
|
| 55 |
+
request: Request
|
| 56 |
+
requestId: string
|
| 57 |
+
},
|
| 58 |
+
]
|
| 59 |
+
unhandledException: [
|
| 60 |
+
args: {
|
| 61 |
+
error: Error
|
| 62 |
+
request: Request
|
| 63 |
+
requestId: string
|
| 64 |
+
},
|
| 65 |
+
]
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
export type LifeCycleEventEmitter<EventMap extends DefaultEventMap> = Pick<
|
| 69 |
+
Emitter<EventMap>,
|
| 70 |
+
'on' | 'removeListener' | 'removeAllListeners'
|
| 71 |
+
>
|
node_modules/msw/src/core/sse.ts
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { invariant } from 'outvariant'
|
| 2 |
+
import { DeferredPromise } from '@open-draft/deferred-promise'
|
| 3 |
+
import { Emitter } from 'strict-event-emitter'
|
| 4 |
+
import type { ResponseResolver } from './handlers/RequestHandler'
|
| 5 |
+
import {
|
| 6 |
+
HttpHandler,
|
| 7 |
+
type HttpRequestResolverExtras,
|
| 8 |
+
type HttpRequestParsedResult,
|
| 9 |
+
} from './handlers/HttpHandler'
|
| 10 |
+
import type { ResponseResolutionContext } from '#core/utils/executeHandlers'
|
| 11 |
+
import type { Path, PathParams } from './utils/matching/matchRequestUrl'
|
| 12 |
+
import { delay } from './delay'
|
| 13 |
+
import { getTimestamp } from './utils/logging/getTimestamp'
|
| 14 |
+
import { devUtils } from './utils/internal/devUtils'
|
| 15 |
+
import { colors } from './ws/utils/attachWebSocketLogger'
|
| 16 |
+
import { toPublicUrl } from './utils/request/toPublicUrl'
|
| 17 |
+
|
| 18 |
+
type EventMapConstraint = {
|
| 19 |
+
message?: unknown
|
| 20 |
+
[key: string]: unknown
|
| 21 |
+
[key: symbol | number]: never
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export type ServerSentEventResolverExtras<
|
| 25 |
+
EventMap extends EventMapConstraint,
|
| 26 |
+
Params extends PathParams,
|
| 27 |
+
> = HttpRequestResolverExtras<Params> & {
|
| 28 |
+
client: ServerSentEventClient<EventMap>
|
| 29 |
+
server: ServerSentEventServer
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export type ServerSentEventResolver<
|
| 33 |
+
EventMap extends EventMapConstraint,
|
| 34 |
+
Params extends PathParams,
|
| 35 |
+
> = ResponseResolver<ServerSentEventResolverExtras<EventMap, Params>, any, any>
|
| 36 |
+
|
| 37 |
+
export type ServerSentEventRequestHandler = <
|
| 38 |
+
EventMap extends EventMapConstraint = { message: unknown },
|
| 39 |
+
Params extends PathParams<keyof Params> = PathParams,
|
| 40 |
+
RequestPath extends Path = Path,
|
| 41 |
+
>(
|
| 42 |
+
path: RequestPath,
|
| 43 |
+
resolver: ServerSentEventResolver<EventMap, Params>,
|
| 44 |
+
) => HttpHandler
|
| 45 |
+
|
| 46 |
+
export type ServerSentEventMessage<
|
| 47 |
+
EventMap extends EventMapConstraint = { message: unknown },
|
| 48 |
+
> =
|
| 49 |
+
| ToEventDiscriminatedUnion<EventMap & { message: unknown }>
|
| 50 |
+
| {
|
| 51 |
+
id?: never
|
| 52 |
+
event?: never
|
| 53 |
+
data?: never
|
| 54 |
+
retry: number
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* Intercept Server-Sent Events (SSE).
|
| 59 |
+
*
|
| 60 |
+
* @example
|
| 61 |
+
* sse('http://localhost:4321', ({ client }) => {
|
| 62 |
+
* client.send({ data: 'hello world' })
|
| 63 |
+
* })
|
| 64 |
+
*
|
| 65 |
+
* @see {@link https://mswjs.io/docs/sse/ Mocking Server-Sent Events}
|
| 66 |
+
* @see {@link https://mswjs.io/docs/api/sse `sse()` API reference}
|
| 67 |
+
*/
|
| 68 |
+
export const sse: ServerSentEventRequestHandler = (path, resolver) => {
|
| 69 |
+
return new ServerSentEventHandler(path, resolver)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
const SSE_RESPONSE_INIT: ResponseInit = {
|
| 73 |
+
headers: {
|
| 74 |
+
'content-type': 'text/event-stream',
|
| 75 |
+
'cache-control': 'no-cache',
|
| 76 |
+
connection: 'keep-alive',
|
| 77 |
+
},
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
class ServerSentEventHandler<
|
| 81 |
+
EventMap extends EventMapConstraint,
|
| 82 |
+
> extends HttpHandler {
|
| 83 |
+
#emitter: Emitter<ServerSentEventClientEventMap>
|
| 84 |
+
|
| 85 |
+
constructor(path: Path, resolver: ServerSentEventResolver<EventMap, any>) {
|
| 86 |
+
invariant(
|
| 87 |
+
typeof EventSource !== 'undefined',
|
| 88 |
+
'Failed to construct a Server-Sent Event handler for path "%s": the EventSource API is not supported in this environment',
|
| 89 |
+
path,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
super('GET', path, async (info) => {
|
| 93 |
+
const { client, server, response } = createEventStream<EventMap>(
|
| 94 |
+
info.request,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
client[kClientEmitter] = this.#emitter
|
| 98 |
+
|
| 99 |
+
await resolver({
|
| 100 |
+
...info,
|
| 101 |
+
client,
|
| 102 |
+
server,
|
| 103 |
+
})
|
| 104 |
+
|
| 105 |
+
return response
|
| 106 |
+
})
|
| 107 |
+
|
| 108 |
+
this.#emitter = new Emitter<ServerSentEventClientEventMap>()
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
async predicate(args: {
|
| 112 |
+
request: Request
|
| 113 |
+
parsedResult: HttpRequestParsedResult
|
| 114 |
+
resolutionContext?: ResponseResolutionContext
|
| 115 |
+
}) {
|
| 116 |
+
if (args.request.headers.get('accept') !== 'text/event-stream') {
|
| 117 |
+
return false
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
const matches = await super.predicate(args)
|
| 121 |
+
|
| 122 |
+
if (matches && !args.resolutionContext?.quiet) {
|
| 123 |
+
/**
|
| 124 |
+
* @note Log the intercepted request early.
|
| 125 |
+
* Normally, the `this.log()` method is called when the handler returns a response.
|
| 126 |
+
* For SSE, call that method earlier so the logs are in correct order.
|
| 127 |
+
*/
|
| 128 |
+
await super.log({
|
| 129 |
+
request: args.request,
|
| 130 |
+
/**
|
| 131 |
+
* @note Construct a placeholder response since SSE response
|
| 132 |
+
* is being streamed and cannot be cloned/consumed for logging.
|
| 133 |
+
*/
|
| 134 |
+
response: new Response('[streaming]', SSE_RESPONSE_INIT),
|
| 135 |
+
})
|
| 136 |
+
|
| 137 |
+
this.#attachClientLogger(args.request, this.#emitter)
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
return matches
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
async log(_args: { request: Request; response: Response }): Promise<void> {
|
| 144 |
+
/**
|
| 145 |
+
* @note Skip the default `this.log()` logic so that when this handler is logged
|
| 146 |
+
* upon handling the request, nothing is printed (we log SSE requests early).
|
| 147 |
+
*/
|
| 148 |
+
return
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
#attachClientLogger(
|
| 152 |
+
request: Request,
|
| 153 |
+
emitter: Emitter<ServerSentEventClientEventMap>,
|
| 154 |
+
): void {
|
| 155 |
+
const publicUrl = toPublicUrl(request.url)
|
| 156 |
+
|
| 157 |
+
/* eslint-disable no-console */
|
| 158 |
+
emitter.on('message', (payload) => {
|
| 159 |
+
console.groupCollapsed(
|
| 160 |
+
devUtils.formatMessage(
|
| 161 |
+
`${getTimestamp()} SSE %s %c⇣%c ${payload.event}`,
|
| 162 |
+
),
|
| 163 |
+
publicUrl,
|
| 164 |
+
`color:${colors.mocked}`,
|
| 165 |
+
'color:inherit',
|
| 166 |
+
)
|
| 167 |
+
console.log(payload.frames)
|
| 168 |
+
console.groupEnd()
|
| 169 |
+
})
|
| 170 |
+
|
| 171 |
+
emitter.on('error', () => {
|
| 172 |
+
console.groupCollapsed(
|
| 173 |
+
devUtils.formatMessage(`${getTimestamp()} SSE %s %c\u00D7%c error`),
|
| 174 |
+
publicUrl,
|
| 175 |
+
`color: ${colors.system}`,
|
| 176 |
+
'color:inherit',
|
| 177 |
+
)
|
| 178 |
+
console.log('Handler:', this)
|
| 179 |
+
console.groupEnd()
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
emitter.on('close', () => {
|
| 183 |
+
console.groupCollapsed(
|
| 184 |
+
devUtils.formatMessage(`${getTimestamp()} SSE %s %c■%c close`),
|
| 185 |
+
publicUrl,
|
| 186 |
+
`colors:${colors.system}`,
|
| 187 |
+
'color:inherit',
|
| 188 |
+
)
|
| 189 |
+
console.log('Handler:', this)
|
| 190 |
+
console.groupEnd()
|
| 191 |
+
})
|
| 192 |
+
/* eslint-enable no-console */
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
type Values<T> = T[keyof T]
|
| 197 |
+
type Identity<T> = { [K in keyof T]: T[K] } & unknown
|
| 198 |
+
type ToEventDiscriminatedUnion<T> = Values<{
|
| 199 |
+
[K in keyof T]: Identity<
|
| 200 |
+
(K extends 'message'
|
| 201 |
+
? {
|
| 202 |
+
id?: string
|
| 203 |
+
event?: K
|
| 204 |
+
data?: T[K]
|
| 205 |
+
retry?: never
|
| 206 |
+
}
|
| 207 |
+
: {
|
| 208 |
+
id?: string
|
| 209 |
+
event: K
|
| 210 |
+
data?: T[K]
|
| 211 |
+
retry?: never
|
| 212 |
+
}) &
|
| 213 |
+
// Make the `data` field conditionally required through an intersection.
|
| 214 |
+
(undefined extends T[K] ? unknown : { data: unknown })
|
| 215 |
+
>
|
| 216 |
+
}>
|
| 217 |
+
|
| 218 |
+
type ServerSentEventClientEventMap = {
|
| 219 |
+
message: [payload: EventStreamMessage]
|
| 220 |
+
error: []
|
| 221 |
+
close: []
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
const kClientEmitter = Symbol.for('kClientEmitter')
|
| 225 |
+
|
| 226 |
+
class ServerSentEventClient<
|
| 227 |
+
EventMap extends EventMapConstraint = { message: unknown },
|
| 228 |
+
> {
|
| 229 |
+
private [kClientEmitter]?: Emitter<ServerSentEventClientEventMap>
|
| 230 |
+
|
| 231 |
+
#encoder: TextEncoder
|
| 232 |
+
#writer: WritableStreamDefaultWriter
|
| 233 |
+
|
| 234 |
+
constructor(writable: WritableStream) {
|
| 235 |
+
this.#encoder = new TextEncoder()
|
| 236 |
+
this.#writer = writable.getWriter()
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
/**
|
| 240 |
+
* Sends the given payload to the intercepted `EventSource`.
|
| 241 |
+
*/
|
| 242 |
+
public send(payload: ServerSentEventMessage<EventMap>): void {
|
| 243 |
+
if ('retry' in payload && payload.retry != null) {
|
| 244 |
+
this.#sendRetry(payload.retry)
|
| 245 |
+
return
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
this.#sendMessage({
|
| 249 |
+
id: payload.id,
|
| 250 |
+
event: payload.event,
|
| 251 |
+
data:
|
| 252 |
+
typeof payload.data === 'object'
|
| 253 |
+
? JSON.stringify(payload.data)
|
| 254 |
+
: payload.data,
|
| 255 |
+
})
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/**
|
| 259 |
+
* Dispatches the given event on the intercepted `EventSource`.
|
| 260 |
+
*/
|
| 261 |
+
public dispatchEvent(event: Event) {
|
| 262 |
+
if (event instanceof MessageEvent) {
|
| 263 |
+
/**
|
| 264 |
+
* @note Use the internal send mechanism to skip normalization
|
| 265 |
+
* of the message data (already normalized by the server).
|
| 266 |
+
*/
|
| 267 |
+
this.#sendMessage({
|
| 268 |
+
id: event.lastEventId || undefined,
|
| 269 |
+
event: event.type === 'message' ? undefined : event.type,
|
| 270 |
+
data: event.data,
|
| 271 |
+
})
|
| 272 |
+
return
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
if (event.type === 'error') {
|
| 276 |
+
this.error()
|
| 277 |
+
return
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
if (event.type === 'close') {
|
| 281 |
+
this.close()
|
| 282 |
+
return
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/**
|
| 287 |
+
* Errors the underlying `EventSource`, closing the connection with an error.
|
| 288 |
+
* This is equivalent to aborting the connection and will produce a `TypeError: Failed to fetch`
|
| 289 |
+
* error.
|
| 290 |
+
*/
|
| 291 |
+
public error(): void {
|
| 292 |
+
this.#writer.abort().catch((error) => {
|
| 293 |
+
console.error(error)
|
| 294 |
+
devUtils.error(
|
| 295 |
+
'Failed to abort server-side EventSource. Please see the original error above.',
|
| 296 |
+
)
|
| 297 |
+
})
|
| 298 |
+
this[kClientEmitter]?.emit('error')
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
/**
|
| 302 |
+
* Closes the underlying `EventSource`, closing the connection.
|
| 303 |
+
*/
|
| 304 |
+
public close(): void {
|
| 305 |
+
this.#writer.close().catch((error) => {
|
| 306 |
+
console.error(error)
|
| 307 |
+
devUtils.error(
|
| 308 |
+
'Failed to close server-side EventSource. Please see the original error above.',
|
| 309 |
+
)
|
| 310 |
+
})
|
| 311 |
+
this[kClientEmitter]?.emit('close')
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
#sendRetry(retry: number): void {
|
| 315 |
+
this.#writer
|
| 316 |
+
.write(this.#encoder.encode(`retry:${retry}\n\n`))
|
| 317 |
+
.catch((error) => {
|
| 318 |
+
console.error(error)
|
| 319 |
+
devUtils.error(
|
| 320 |
+
'Failed to send a retry packet to server-side EventSource. Please see the original error above.',
|
| 321 |
+
)
|
| 322 |
+
})
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
#sendMessage(message: {
|
| 326 |
+
id?: string
|
| 327 |
+
event?: unknown
|
| 328 |
+
data: unknown | undefined
|
| 329 |
+
}): void {
|
| 330 |
+
const frames: Array<string> = []
|
| 331 |
+
|
| 332 |
+
if (message.id) {
|
| 333 |
+
frames.push(`id:${message.id}`)
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
if (message.event) {
|
| 337 |
+
frames.push(`event:${message.event.toString()}`)
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
if (message.data != null) {
|
| 341 |
+
/**
|
| 342 |
+
* Split data on line terminators (LF, CR, or CRLF) and translate them to individual frames.
|
| 343 |
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
|
| 344 |
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream
|
| 345 |
+
*/
|
| 346 |
+
for (const line of message.data.toString().split(/\r\n|\r|\n/)) {
|
| 347 |
+
frames.push(`data:${line}`)
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
frames.push('', '')
|
| 352 |
+
|
| 353 |
+
this.#writer
|
| 354 |
+
.write(this.#encoder.encode(frames.join('\n')))
|
| 355 |
+
.catch((error) => {
|
| 356 |
+
console.error(error)
|
| 357 |
+
devUtils.error(
|
| 358 |
+
'Failed to send a message to server-side EventSource. Please see the original error above.',
|
| 359 |
+
)
|
| 360 |
+
})
|
| 361 |
+
|
| 362 |
+
this[kClientEmitter]?.emit('message', {
|
| 363 |
+
id: message.id,
|
| 364 |
+
event: message.event?.toString() || 'message',
|
| 365 |
+
data: message.data,
|
| 366 |
+
frames,
|
| 367 |
+
})
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
class ServerSentEventServer {
|
| 372 |
+
#request: Request
|
| 373 |
+
#client: ServerSentEventClient<ServerSentEventClientEventMap>
|
| 374 |
+
|
| 375 |
+
constructor(args: { request: Request; client: ServerSentEventClient<any> }) {
|
| 376 |
+
this.#request = args.request
|
| 377 |
+
this.#client = args.client
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
/**
|
| 381 |
+
* Establishes the actual connection for this SSE request
|
| 382 |
+
* and returns the `EventSource` instance.
|
| 383 |
+
*/
|
| 384 |
+
public connect(): EventSource {
|
| 385 |
+
const source = new ObservableEventSource(this.#request.url, {
|
| 386 |
+
withCredentials: this.#request.credentials === 'include',
|
| 387 |
+
headers: {
|
| 388 |
+
/**
|
| 389 |
+
* @note Mark this request as passthrough so it doesn't trigger
|
| 390 |
+
* an infinite loop matching against the existing request handler.
|
| 391 |
+
*/
|
| 392 |
+
accept: 'msw/passthrough',
|
| 393 |
+
},
|
| 394 |
+
signal: this.#request.signal,
|
| 395 |
+
})
|
| 396 |
+
|
| 397 |
+
source[kOnAnyMessage] = (event) => {
|
| 398 |
+
Object.defineProperties(event, {
|
| 399 |
+
target: {
|
| 400 |
+
value: this,
|
| 401 |
+
enumerable: true,
|
| 402 |
+
writable: true,
|
| 403 |
+
configurable: true,
|
| 404 |
+
},
|
| 405 |
+
})
|
| 406 |
+
|
| 407 |
+
// Schedule the server-to-client forwarding for the next tick
|
| 408 |
+
// so the user can prevent the message event.
|
| 409 |
+
queueMicrotask(() => {
|
| 410 |
+
if (!event.defaultPrevented) {
|
| 411 |
+
this.#client.dispatchEvent(event)
|
| 412 |
+
}
|
| 413 |
+
})
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
// Forward stream errors from the actual server to the client.
|
| 417 |
+
source.addEventListener('error', (event) => {
|
| 418 |
+
Object.defineProperties(event, {
|
| 419 |
+
target: {
|
| 420 |
+
value: this,
|
| 421 |
+
enumerable: true,
|
| 422 |
+
writable: true,
|
| 423 |
+
configurable: true,
|
| 424 |
+
},
|
| 425 |
+
})
|
| 426 |
+
|
| 427 |
+
queueMicrotask(() => {
|
| 428 |
+
// Allow the user to opt-out from this forwarding.
|
| 429 |
+
if (!event.defaultPrevented) {
|
| 430 |
+
this.#client.dispatchEvent(event)
|
| 431 |
+
}
|
| 432 |
+
})
|
| 433 |
+
})
|
| 434 |
+
|
| 435 |
+
return source
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
interface ObservableEventSourceInit extends EventSourceInit {
|
| 440 |
+
headers?: HeadersInit
|
| 441 |
+
signal?: AbortSignal
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
type EventHandler<EventType extends Event> = (
|
| 445 |
+
this: EventSource,
|
| 446 |
+
event: EventType,
|
| 447 |
+
) => any
|
| 448 |
+
|
| 449 |
+
const kRequest = Symbol('kRequest')
|
| 450 |
+
const kReconnectionTime = Symbol('kReconnectionTime')
|
| 451 |
+
const kLastEventId = Symbol('kLastEventId')
|
| 452 |
+
const kAbortController = Symbol('kAbortController')
|
| 453 |
+
const kOnOpen = Symbol('kOnOpen')
|
| 454 |
+
const kOnMessage = Symbol('kOnMessage')
|
| 455 |
+
const kOnAnyMessage = Symbol('kOnAnyMessage')
|
| 456 |
+
const kOnError = Symbol('kOnError')
|
| 457 |
+
|
| 458 |
+
class ObservableEventSource extends EventTarget implements EventSource {
|
| 459 |
+
static readonly CONNECTING = 0
|
| 460 |
+
static readonly OPEN = 1
|
| 461 |
+
static readonly CLOSED = 2
|
| 462 |
+
|
| 463 |
+
public readonly CONNECTING = ObservableEventSource.CONNECTING
|
| 464 |
+
public readonly OPEN = ObservableEventSource.OPEN
|
| 465 |
+
public readonly CLOSED = ObservableEventSource.CLOSED
|
| 466 |
+
|
| 467 |
+
public readyState: number
|
| 468 |
+
public url: string
|
| 469 |
+
public withCredentials: boolean
|
| 470 |
+
|
| 471 |
+
private [kRequest]: Request
|
| 472 |
+
private [kReconnectionTime]: number
|
| 473 |
+
private [kLastEventId]: string
|
| 474 |
+
private [kAbortController]: AbortController
|
| 475 |
+
private [kOnOpen]: EventHandler<Event> | null = null
|
| 476 |
+
private [kOnMessage]: EventHandler<MessageEvent> | null = null
|
| 477 |
+
private [kOnAnyMessage]: EventHandler<MessageEvent> | null = null
|
| 478 |
+
private [kOnError]: EventHandler<Event> | null = null
|
| 479 |
+
|
| 480 |
+
constructor(url: string | URL, init?: ObservableEventSourceInit) {
|
| 481 |
+
super()
|
| 482 |
+
|
| 483 |
+
this.url = new URL(url).href
|
| 484 |
+
this.withCredentials = init?.withCredentials ?? false
|
| 485 |
+
|
| 486 |
+
this.readyState = this.CONNECTING
|
| 487 |
+
|
| 488 |
+
// Support custom request init.
|
| 489 |
+
const headers = new Headers(init?.headers || {})
|
| 490 |
+
headers.append('accept', 'text/event-stream')
|
| 491 |
+
|
| 492 |
+
this[kAbortController] = new AbortController()
|
| 493 |
+
this[kReconnectionTime] = 2000
|
| 494 |
+
this[kLastEventId] = ''
|
| 495 |
+
this[kRequest] = new Request(this.url, {
|
| 496 |
+
method: 'GET',
|
| 497 |
+
headers,
|
| 498 |
+
credentials: this.withCredentials ? 'include' : 'omit',
|
| 499 |
+
signal: this[kAbortController].signal,
|
| 500 |
+
})
|
| 501 |
+
|
| 502 |
+
if (init?.signal) {
|
| 503 |
+
if (init.signal.aborted) {
|
| 504 |
+
this.close()
|
| 505 |
+
return
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
init.signal.addEventListener('abort', () => this.close(), {
|
| 509 |
+
once: true,
|
| 510 |
+
signal: this[kAbortController].signal,
|
| 511 |
+
})
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
this.connect()
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
get onopen(): EventHandler<Event> | null {
|
| 518 |
+
return this[kOnOpen]
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
set onopen(handler: EventHandler<Event>) {
|
| 522 |
+
if (this[kOnOpen]) {
|
| 523 |
+
this.removeEventListener('open', this[kOnOpen])
|
| 524 |
+
}
|
| 525 |
+
this[kOnOpen] = handler.bind(this)
|
| 526 |
+
this.addEventListener('open', this[kOnOpen])
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
get onmessage(): EventHandler<MessageEvent> | null {
|
| 530 |
+
return this[kOnMessage]
|
| 531 |
+
}
|
| 532 |
+
set onmessage(handler: EventHandler<MessageEvent>) {
|
| 533 |
+
if (this[kOnMessage]) {
|
| 534 |
+
this.removeEventListener('message', { handleEvent: this[kOnMessage] })
|
| 535 |
+
}
|
| 536 |
+
this[kOnMessage] = handler.bind(this)
|
| 537 |
+
this.addEventListener('message', { handleEvent: this[kOnMessage] })
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
get onerror(): EventHandler<Event> | null {
|
| 541 |
+
return this[kOnError]
|
| 542 |
+
}
|
| 543 |
+
set onerror(handler: EventHandler<Event>) {
|
| 544 |
+
if (this[kOnError]) {
|
| 545 |
+
this.removeEventListener('error', { handleEvent: this[kOnError] })
|
| 546 |
+
}
|
| 547 |
+
this[kOnError] = handler.bind(this)
|
| 548 |
+
this.addEventListener('error', { handleEvent: this[kOnError] })
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
public addEventListener<K extends keyof EventSourceEventMap>(
|
| 552 |
+
type: K,
|
| 553 |
+
listener: EventHandler<EventSourceEventMap[K]>,
|
| 554 |
+
options?: boolean | AddEventListenerOptions,
|
| 555 |
+
): void
|
| 556 |
+
public addEventListener(
|
| 557 |
+
type: string,
|
| 558 |
+
listener: EventHandler<MessageEvent>,
|
| 559 |
+
options?: boolean | AddEventListenerOptions,
|
| 560 |
+
): void
|
| 561 |
+
public addEventListener(
|
| 562 |
+
type: string,
|
| 563 |
+
listener: EventListenerOrEventListenerObject,
|
| 564 |
+
options?: boolean | AddEventListenerOptions,
|
| 565 |
+
): void
|
| 566 |
+
|
| 567 |
+
public addEventListener(
|
| 568 |
+
type: string,
|
| 569 |
+
listener: EventHandler<MessageEvent> | EventListenerOrEventListenerObject,
|
| 570 |
+
options?: boolean | AddEventListenerOptions,
|
| 571 |
+
): void {
|
| 572 |
+
super.addEventListener(
|
| 573 |
+
type,
|
| 574 |
+
listener as EventListenerOrEventListenerObject,
|
| 575 |
+
options,
|
| 576 |
+
)
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
public removeEventListener<K extends keyof EventSourceEventMap>(
|
| 580 |
+
type: K,
|
| 581 |
+
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
|
| 582 |
+
options?: boolean | EventListenerOptions,
|
| 583 |
+
): void
|
| 584 |
+
public removeEventListener(
|
| 585 |
+
type: string,
|
| 586 |
+
listener: (this: EventSource, event: MessageEvent) => any,
|
| 587 |
+
options?: boolean | EventListenerOptions,
|
| 588 |
+
): void
|
| 589 |
+
public removeEventListener(
|
| 590 |
+
type: string,
|
| 591 |
+
listener: EventListenerOrEventListenerObject,
|
| 592 |
+
options?: boolean | EventListenerOptions,
|
| 593 |
+
): void
|
| 594 |
+
|
| 595 |
+
public removeEventListener(
|
| 596 |
+
type: string,
|
| 597 |
+
listener: EventHandler<MessageEvent> | EventListenerOrEventListenerObject,
|
| 598 |
+
options?: boolean | AddEventListenerOptions,
|
| 599 |
+
): void {
|
| 600 |
+
super.removeEventListener(
|
| 601 |
+
type,
|
| 602 |
+
listener as EventListenerOrEventListenerObject,
|
| 603 |
+
options,
|
| 604 |
+
)
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
public dispatchEvent(event: Event): boolean {
|
| 608 |
+
return super.dispatchEvent(event)
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
public close(): void {
|
| 612 |
+
this[kAbortController].abort()
|
| 613 |
+
this.readyState = this.CLOSED
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
private async connect() {
|
| 617 |
+
await fetch(this[kRequest])
|
| 618 |
+
.then((response) => {
|
| 619 |
+
this.processResponse(response)
|
| 620 |
+
})
|
| 621 |
+
.catch(() => {
|
| 622 |
+
// Fail the connection on request errors instead of
|
| 623 |
+
// throwing a generic "Failed to fetch" error.
|
| 624 |
+
this.failConnection()
|
| 625 |
+
})
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
private processResponse(response: Response): void {
|
| 629 |
+
if (!response.body) {
|
| 630 |
+
this.failConnection()
|
| 631 |
+
return
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
if (isNetworkError(response)) {
|
| 635 |
+
this.reestablishConnection()
|
| 636 |
+
return
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
if (
|
| 640 |
+
response.status !== 200 ||
|
| 641 |
+
response.headers.get('content-type') !== 'text/event-stream'
|
| 642 |
+
) {
|
| 643 |
+
this.failConnection()
|
| 644 |
+
return
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
this.announceConnection()
|
| 648 |
+
this.interpretResponseBody(response)
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
private announceConnection(): void {
|
| 652 |
+
queueMicrotask(() => {
|
| 653 |
+
if (this.readyState !== this.CLOSED) {
|
| 654 |
+
this.readyState = this.OPEN
|
| 655 |
+
this.dispatchEvent(new Event('open'))
|
| 656 |
+
}
|
| 657 |
+
})
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
private interpretResponseBody(response: Response): void {
|
| 661 |
+
const parsingStream = new EventSourceParsingStream({
|
| 662 |
+
message: (message) => {
|
| 663 |
+
if (message.id) {
|
| 664 |
+
this[kLastEventId] = message.id
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
const messageEvent = new MessageEvent(
|
| 668 |
+
message.event ? message.event : 'message',
|
| 669 |
+
{
|
| 670 |
+
data: message.data,
|
| 671 |
+
origin: this[kRequest].url,
|
| 672 |
+
lastEventId: this[kLastEventId],
|
| 673 |
+
cancelable: true,
|
| 674 |
+
},
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
this[kOnAnyMessage]?.(messageEvent)
|
| 678 |
+
this.dispatchEvent(messageEvent)
|
| 679 |
+
},
|
| 680 |
+
retry: (reconnectionTime) => {
|
| 681 |
+
this[kReconnectionTime] = reconnectionTime
|
| 682 |
+
},
|
| 683 |
+
abort: () => {
|
| 684 |
+
throw new Error('Stream abort is not implemented')
|
| 685 |
+
},
|
| 686 |
+
close: () => {
|
| 687 |
+
this.failConnection()
|
| 688 |
+
},
|
| 689 |
+
})
|
| 690 |
+
|
| 691 |
+
response
|
| 692 |
+
.body!.pipeTo(parsingStream)
|
| 693 |
+
.then(() => {
|
| 694 |
+
this.processResponseEndOfBody(response)
|
| 695 |
+
})
|
| 696 |
+
.catch(() => {
|
| 697 |
+
this.failConnection()
|
| 698 |
+
})
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
private processResponseEndOfBody(response: Response): void {
|
| 702 |
+
if (!isNetworkError(response)) {
|
| 703 |
+
this.reestablishConnection()
|
| 704 |
+
}
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
private async reestablishConnection(): Promise<void> {
|
| 708 |
+
queueMicrotask(() => {
|
| 709 |
+
if (this.readyState === this.CLOSED) {
|
| 710 |
+
return
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
this.readyState = this.CONNECTING
|
| 714 |
+
this.dispatchEvent(new Event('error'))
|
| 715 |
+
})
|
| 716 |
+
|
| 717 |
+
const signal = this[kAbortController].signal
|
| 718 |
+
|
| 719 |
+
if (signal.aborted) {
|
| 720 |
+
return
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
const aborted = new DeferredPromise<void>()
|
| 724 |
+
const onAbort = () => aborted.resolve()
|
| 725 |
+
signal.addEventListener('abort', onAbort, { once: true })
|
| 726 |
+
|
| 727 |
+
await Promise.race([delay(this[kReconnectionTime]), aborted]).finally(
|
| 728 |
+
() => {
|
| 729 |
+
signal.removeEventListener('abort', onAbort)
|
| 730 |
+
},
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
if (signal.aborted) {
|
| 734 |
+
return
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
queueMicrotask(async () => {
|
| 738 |
+
if (this.readyState !== this.CONNECTING) {
|
| 739 |
+
return
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
if (this[kLastEventId] !== '') {
|
| 743 |
+
this[kRequest].headers.set('last-event-id', this[kLastEventId])
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
await this.connect()
|
| 747 |
+
})
|
| 748 |
+
}
|
| 749 |
+
|
| 750 |
+
private failConnection(): void {
|
| 751 |
+
queueMicrotask(() => {
|
| 752 |
+
if (this.readyState !== this.CLOSED) {
|
| 753 |
+
this.readyState = this.CLOSED
|
| 754 |
+
this.dispatchEvent(new Event('error'))
|
| 755 |
+
}
|
| 756 |
+
})
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
/**
|
| 761 |
+
* Checks if the given `Response` instance is a network error.
|
| 762 |
+
* @see https://fetch.spec.whatwg.org/#concept-network-error
|
| 763 |
+
*/
|
| 764 |
+
function isNetworkError(response: Response): boolean {
|
| 765 |
+
return (
|
| 766 |
+
response.type === 'error' &&
|
| 767 |
+
response.status === 0 &&
|
| 768 |
+
response.statusText === '' &&
|
| 769 |
+
Array.from(response.headers.entries()).length === 0 &&
|
| 770 |
+
response.body === null
|
| 771 |
+
)
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
const enum ControlCharacters {
|
| 775 |
+
NewLine = 10,
|
| 776 |
+
CarriageReturn = 13,
|
| 777 |
+
Space = 32,
|
| 778 |
+
Colon = 58,
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
interface EventSourceMessage {
|
| 782 |
+
id?: string
|
| 783 |
+
event?: string
|
| 784 |
+
data?: string
|
| 785 |
+
}
|
| 786 |
+
|
| 787 |
+
class EventSourceParsingStream extends WritableStream {
|
| 788 |
+
private decoder: TextDecoder
|
| 789 |
+
|
| 790 |
+
private buffer?: Uint8Array
|
| 791 |
+
private position: number
|
| 792 |
+
private fieldLength?: number
|
| 793 |
+
private discardTrailingNewline = false
|
| 794 |
+
|
| 795 |
+
private message: EventSourceMessage = {
|
| 796 |
+
id: undefined,
|
| 797 |
+
event: undefined,
|
| 798 |
+
data: undefined,
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
constructor(
|
| 802 |
+
private underlyingSink: {
|
| 803 |
+
message: (message: EventSourceMessage) => void
|
| 804 |
+
retry?: (reconnectionTime: number) => void
|
| 805 |
+
abort?: (reason: any) => void
|
| 806 |
+
close?: () => void
|
| 807 |
+
},
|
| 808 |
+
) {
|
| 809 |
+
super({
|
| 810 |
+
write: (chunk) => {
|
| 811 |
+
this.processResponseBodyChunk(chunk)
|
| 812 |
+
},
|
| 813 |
+
abort: (reason) => {
|
| 814 |
+
this.underlyingSink.abort?.(reason)
|
| 815 |
+
},
|
| 816 |
+
close: () => {
|
| 817 |
+
this.underlyingSink.close?.()
|
| 818 |
+
},
|
| 819 |
+
})
|
| 820 |
+
|
| 821 |
+
this.decoder = new TextDecoder()
|
| 822 |
+
this.position = 0
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
private resetMessage(): void {
|
| 826 |
+
this.message = {
|
| 827 |
+
id: undefined,
|
| 828 |
+
event: undefined,
|
| 829 |
+
data: undefined,
|
| 830 |
+
}
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
private processResponseBodyChunk(chunk: Uint8Array): void {
|
| 834 |
+
if (this.buffer == null) {
|
| 835 |
+
this.buffer = chunk
|
| 836 |
+
this.position = 0
|
| 837 |
+
this.fieldLength = -1
|
| 838 |
+
} else {
|
| 839 |
+
const nextBuffer = new Uint8Array(this.buffer.length + chunk.length)
|
| 840 |
+
nextBuffer.set(this.buffer)
|
| 841 |
+
nextBuffer.set(chunk, this.buffer.length)
|
| 842 |
+
this.buffer = nextBuffer
|
| 843 |
+
}
|
| 844 |
+
|
| 845 |
+
const bufferLength = this.buffer.length
|
| 846 |
+
let lineStart = 0
|
| 847 |
+
|
| 848 |
+
while (this.position < bufferLength) {
|
| 849 |
+
if (this.discardTrailingNewline) {
|
| 850 |
+
if (this.buffer[this.position] === ControlCharacters.NewLine) {
|
| 851 |
+
lineStart = ++this.position
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
this.discardTrailingNewline = false
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
let lineEnd = -1
|
| 858 |
+
|
| 859 |
+
for (; this.position < bufferLength && lineEnd === -1; ++this.position) {
|
| 860 |
+
switch (this.buffer[this.position]) {
|
| 861 |
+
case ControlCharacters.Colon: {
|
| 862 |
+
if (this.fieldLength === -1) {
|
| 863 |
+
this.fieldLength = this.position - lineStart
|
| 864 |
+
}
|
| 865 |
+
break
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
case ControlCharacters.CarriageReturn: {
|
| 869 |
+
this.discardTrailingNewline = true
|
| 870 |
+
break
|
| 871 |
+
}
|
| 872 |
+
|
| 873 |
+
case ControlCharacters.NewLine: {
|
| 874 |
+
lineEnd = this.position
|
| 875 |
+
break
|
| 876 |
+
}
|
| 877 |
+
}
|
| 878 |
+
}
|
| 879 |
+
|
| 880 |
+
if (lineEnd === -1) {
|
| 881 |
+
break
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
this.processLine(
|
| 885 |
+
this.buffer.subarray(lineStart, lineEnd),
|
| 886 |
+
this.fieldLength!,
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
lineStart = this.position
|
| 890 |
+
this.fieldLength = -1
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
if (lineStart === bufferLength) {
|
| 894 |
+
this.buffer = undefined
|
| 895 |
+
} else if (lineStart !== 0) {
|
| 896 |
+
this.buffer = this.buffer.subarray(lineStart)
|
| 897 |
+
this.position -= lineStart
|
| 898 |
+
}
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
private processLine(line: Uint8Array, fieldLength: number): void {
|
| 902 |
+
// New line indicates the end of the message. Dispatch it.
|
| 903 |
+
if (line.length === 0) {
|
| 904 |
+
// Prevent dispatching the message if the data is an empty string.
|
| 905 |
+
// That is a no-op per spec.
|
| 906 |
+
if (this.message.data === undefined) {
|
| 907 |
+
this.message.event = undefined
|
| 908 |
+
return
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
this.underlyingSink.message(this.message)
|
| 912 |
+
this.resetMessage()
|
| 913 |
+
return
|
| 914 |
+
}
|
| 915 |
+
|
| 916 |
+
// Otherwise, keep accumulating message fields until the new line.
|
| 917 |
+
if (fieldLength > 0) {
|
| 918 |
+
const field = this.decoder.decode(line.subarray(0, fieldLength))
|
| 919 |
+
const valueOffset =
|
| 920 |
+
fieldLength +
|
| 921 |
+
(line[fieldLength + 1] === ControlCharacters.Space ? 2 : 1)
|
| 922 |
+
const value = this.decoder.decode(line.subarray(valueOffset))
|
| 923 |
+
|
| 924 |
+
switch (field) {
|
| 925 |
+
case 'data': {
|
| 926 |
+
this.message.data = this.message.data
|
| 927 |
+
? this.message.data + '\n' + value
|
| 928 |
+
: value
|
| 929 |
+
break
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
case 'event': {
|
| 933 |
+
this.message.event = value
|
| 934 |
+
break
|
| 935 |
+
}
|
| 936 |
+
|
| 937 |
+
case 'id': {
|
| 938 |
+
this.message.id = value
|
| 939 |
+
break
|
| 940 |
+
}
|
| 941 |
+
|
| 942 |
+
case 'retry': {
|
| 943 |
+
/**
|
| 944 |
+
* Apply the retry immediately. Don't buffer onto the current message.
|
| 945 |
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
|
| 946 |
+
*/
|
| 947 |
+
if (/^\d+$/.test(value)) {
|
| 948 |
+
this.underlyingSink.retry?.(parseInt(value, 10))
|
| 949 |
+
}
|
| 950 |
+
break
|
| 951 |
+
}
|
| 952 |
+
}
|
| 953 |
+
}
|
| 954 |
+
}
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
interface EventStreamMessage {
|
| 958 |
+
id?: string
|
| 959 |
+
event: string
|
| 960 |
+
data?: unknown
|
| 961 |
+
frames: Array<string>
|
| 962 |
+
}
|
| 963 |
+
|
| 964 |
+
interface EventStream<EventMap extends EventMapConstraint> {
|
| 965 |
+
client: ServerSentEventClient<EventMap>
|
| 966 |
+
server: ServerSentEventServer
|
| 967 |
+
response: Response
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
/**
|
| 971 |
+
* Create an event stream out of the given Fetch API `Request`.
|
| 972 |
+
* Returns the following properties:
|
| 973 |
+
* - `client`, to operate on the intercepted request;
|
| 974 |
+
* - `server`, to establish and manage the actual server connection;
|
| 975 |
+
* - `response`, a `Response` to use as the mock response's body.
|
| 976 |
+
*
|
| 977 |
+
* @example
|
| 978 |
+
* http.post('/resource', ({ request }) => {
|
| 979 |
+
* const { client, server, response } = createEventStream(request)
|
| 980 |
+
* client.send({ data: 'hello world' })
|
| 981 |
+
* return response
|
| 982 |
+
* })
|
| 983 |
+
*/
|
| 984 |
+
function createEventStream<EventMap extends EventMapConstraint>(
|
| 985 |
+
request: Request,
|
| 986 |
+
): EventStream<EventMap> {
|
| 987 |
+
invariant(
|
| 988 |
+
!request.signal.aborted,
|
| 989 |
+
'Failed to call "createEventStream" on the "%s %s" request: request aborted',
|
| 990 |
+
request.method,
|
| 991 |
+
request.url,
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
const { readable, writable } = new TransformStream()
|
| 995 |
+
|
| 996 |
+
const client = new ServerSentEventClient<EventMap>(writable)
|
| 997 |
+
const server = new ServerSentEventServer({
|
| 998 |
+
request,
|
| 999 |
+
client,
|
| 1000 |
+
})
|
| 1001 |
+
|
| 1002 |
+
const response = new Response(readable, SSE_RESPONSE_INIT)
|
| 1003 |
+
|
| 1004 |
+
request.signal.addEventListener(
|
| 1005 |
+
'abort',
|
| 1006 |
+
() => {
|
| 1007 |
+
client.close()
|
| 1008 |
+
},
|
| 1009 |
+
{ once: true },
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
return {
|
| 1013 |
+
client,
|
| 1014 |
+
server,
|
| 1015 |
+
response,
|
| 1016 |
+
}
|
| 1017 |
+
}
|
node_modules/msw/src/core/typeUtils.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
type Fn = (...arg: any[]) => any
|
| 2 |
+
|
| 3 |
+
export type MaybePromise<T> = T | Promise<T>
|
| 4 |
+
|
| 5 |
+
export type RequiredDeep<
|
| 6 |
+
Type,
|
| 7 |
+
U extends Record<string, unknown> | Fn | undefined = undefined,
|
| 8 |
+
> = Type extends Fn
|
| 9 |
+
? Type
|
| 10 |
+
: /**
|
| 11 |
+
* @note The "Fn" type satisfies the predicate below.
|
| 12 |
+
* It must always come first, before the Record check.
|
| 13 |
+
*/
|
| 14 |
+
Type extends Record<string, any>
|
| 15 |
+
? {
|
| 16 |
+
[Key in keyof Type]-?: NonNullable<Type[Key]> extends NonNullable<U>
|
| 17 |
+
? NonNullable<Type[Key]>
|
| 18 |
+
: RequiredDeep<NonNullable<Type[Key]>, U>
|
| 19 |
+
}
|
| 20 |
+
: Type
|
| 21 |
+
|
| 22 |
+
/**
|
| 23 |
+
* @fixme Remove this once TS 5.4 is the lowest supported version.
|
| 24 |
+
* Because "NoInfer" is a built-in type utility there.
|
| 25 |
+
*/
|
| 26 |
+
export type NoInfer<T> = [T][T extends any ? 0 : never]
|
node_modules/msw/src/core/utils/HttpResponse/decorators.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import statuses from '../../../shims/statuses'
|
| 2 |
+
import type { HttpResponseInit } from '../../HttpResponse'
|
| 3 |
+
|
| 4 |
+
const { message } = statuses
|
| 5 |
+
|
| 6 |
+
const kSetCookie = Symbol('kSetCookie')
|
| 7 |
+
|
| 8 |
+
export interface HttpResponseDecoratedInit extends HttpResponseInit {
|
| 9 |
+
status: number
|
| 10 |
+
statusText: string
|
| 11 |
+
headers: Headers
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export function normalizeResponseInit(
|
| 15 |
+
init: HttpResponseInit = {},
|
| 16 |
+
): HttpResponseDecoratedInit {
|
| 17 |
+
const status = init?.status || 200
|
| 18 |
+
const statusText = init?.statusText || message[status] || ''
|
| 19 |
+
const headers = new Headers(init?.headers)
|
| 20 |
+
|
| 21 |
+
return {
|
| 22 |
+
...init,
|
| 23 |
+
headers,
|
| 24 |
+
status,
|
| 25 |
+
statusText,
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
export function decorateResponse(
|
| 30 |
+
response: Response,
|
| 31 |
+
init: HttpResponseDecoratedInit,
|
| 32 |
+
): Response {
|
| 33 |
+
// Allow mocking the response type.
|
| 34 |
+
if (init.type) {
|
| 35 |
+
Object.defineProperty(response, 'type', {
|
| 36 |
+
value: init.type,
|
| 37 |
+
enumerable: true,
|
| 38 |
+
writable: false,
|
| 39 |
+
})
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
const responseCookies = init.headers.get('set-cookie')
|
| 43 |
+
|
| 44 |
+
if (responseCookies) {
|
| 45 |
+
// Record the raw "Set-Cookie" response header provided
|
| 46 |
+
// in the HeadersInit. This is later used to store these cookies
|
| 47 |
+
// in cookie jar and return the right cookies in the "cookies"
|
| 48 |
+
// response resolver argument.
|
| 49 |
+
Object.defineProperty(response, kSetCookie, {
|
| 50 |
+
value: responseCookies,
|
| 51 |
+
enumerable: false,
|
| 52 |
+
writable: false,
|
| 53 |
+
})
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
return response
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
export function getRawSetCookie(response: Response): string | undefined {
|
| 60 |
+
return Reflect.get(response, kSetCookie)
|
| 61 |
+
}
|
node_modules/msw/src/core/utils/cookieStore.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isNodeProcess } from 'is-node-process'
|
| 2 |
+
import { invariant } from 'outvariant'
|
| 3 |
+
import {
|
| 4 |
+
Cookie,
|
| 5 |
+
CookieJar,
|
| 6 |
+
MemoryCookieStore,
|
| 7 |
+
type SerializedCookie,
|
| 8 |
+
type MemoryCookieStoreIndex,
|
| 9 |
+
} from 'tough-cookie'
|
| 10 |
+
import { jsonParse } from './internal/jsonParse'
|
| 11 |
+
|
| 12 |
+
class CookieStore {
|
| 13 |
+
#storageKey = '__msw-cookie-store__'
|
| 14 |
+
#jar: CookieJar
|
| 15 |
+
#memoryStore: MemoryCookieStore
|
| 16 |
+
|
| 17 |
+
constructor() {
|
| 18 |
+
if (!isNodeProcess()) {
|
| 19 |
+
invariant(
|
| 20 |
+
typeof localStorage !== 'undefined',
|
| 21 |
+
'Failed to create a CookieStore: `localStorage` is not available in this environment. This is likely an issue with your environment, which has been detected as browser (or browser-like) environment and must implement global browser APIs correctly.',
|
| 22 |
+
)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
this.#memoryStore = new MemoryCookieStore()
|
| 26 |
+
this.#memoryStore.idx = this.getCookieStoreIndex()
|
| 27 |
+
this.#jar = new CookieJar(this.#memoryStore)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
public getCookies(url: string): Array<Cookie> {
|
| 31 |
+
return this.#jar.getCookiesSync(url)
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
public async setCookie(cookieName: string, url: string): Promise<void> {
|
| 35 |
+
await this.#jar.setCookie(cookieName, url)
|
| 36 |
+
this.persist()
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
private getCookieStoreIndex(): MemoryCookieStoreIndex {
|
| 40 |
+
if (
|
| 41 |
+
typeof localStorage === 'undefined' ||
|
| 42 |
+
typeof localStorage.getItem !== 'function'
|
| 43 |
+
) {
|
| 44 |
+
return {}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
const cookiesString = localStorage.getItem(this.#storageKey)
|
| 48 |
+
if (cookiesString == null) {
|
| 49 |
+
return {}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
const rawCookies = jsonParse<Array<Record<string, unknown>>>(cookiesString)
|
| 53 |
+
if (rawCookies == null) {
|
| 54 |
+
return {}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
const cookies: MemoryCookieStoreIndex = {}
|
| 58 |
+
|
| 59 |
+
for (const rawCookie of rawCookies) {
|
| 60 |
+
const cookie = Cookie.fromJSON(rawCookie)
|
| 61 |
+
|
| 62 |
+
if (cookie != null && cookie.domain != null && cookie.path != null) {
|
| 63 |
+
cookies[cookie.domain] ||= {}
|
| 64 |
+
cookies[cookie.domain][cookie.path] ||= {}
|
| 65 |
+
cookies[cookie.domain][cookie.path][cookie.key] = cookie
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return cookies
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
private persist(): void {
|
| 73 |
+
if (
|
| 74 |
+
typeof localStorage === 'undefined' ||
|
| 75 |
+
typeof localStorage.setItem !== 'function'
|
| 76 |
+
) {
|
| 77 |
+
return
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
const data: Array<SerializedCookie> = []
|
| 81 |
+
const { idx } = this.#memoryStore
|
| 82 |
+
|
| 83 |
+
for (const domain in idx) {
|
| 84 |
+
for (const path in idx[domain]) {
|
| 85 |
+
for (const key in idx[domain][path]) {
|
| 86 |
+
data.push(idx[domain][path][key].toJSON())
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
localStorage.setItem(this.#storageKey, JSON.stringify(data))
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
export const cookieStore = new CookieStore()
|
node_modules/msw/src/core/utils/executeHandlers.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { RequestHandler } from '../handlers/RequestHandler'
|
| 2 |
+
import { type RequestHandlerExecutionResult } from '../handlers/RequestHandler'
|
| 3 |
+
|
| 4 |
+
export interface HandlersExecutionResult {
|
| 5 |
+
handler: RequestHandler
|
| 6 |
+
parsedResult?: any
|
| 7 |
+
response?: Response
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export interface ResponseResolutionContext {
|
| 11 |
+
/**
|
| 12 |
+
* A base url to use when resolving relative urls.
|
| 13 |
+
* @note This is primarily used by the `@mswjs/http-middleware`
|
| 14 |
+
* to resolve relative urls in the context of the running server
|
| 15 |
+
*/
|
| 16 |
+
baseUrl?: string
|
| 17 |
+
quiet?: boolean
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
/**
|
| 21 |
+
* Executes the list of request handlers against the given request.
|
| 22 |
+
* Returns the execution result object containing any matching request
|
| 23 |
+
* handler and any mocked response it returned.
|
| 24 |
+
*/
|
| 25 |
+
export const executeHandlers = async <Handlers extends Array<RequestHandler>>({
|
| 26 |
+
request,
|
| 27 |
+
requestId,
|
| 28 |
+
handlers,
|
| 29 |
+
resolutionContext,
|
| 30 |
+
}: {
|
| 31 |
+
request: Request
|
| 32 |
+
requestId: string
|
| 33 |
+
handlers: Handlers
|
| 34 |
+
resolutionContext?: ResponseResolutionContext
|
| 35 |
+
}): Promise<HandlersExecutionResult | null> => {
|
| 36 |
+
let matchingHandler: RequestHandler | null = null
|
| 37 |
+
let result: RequestHandlerExecutionResult<any> | null = null
|
| 38 |
+
|
| 39 |
+
for (const handler of handlers) {
|
| 40 |
+
result = await handler.run({ request, requestId, resolutionContext })
|
| 41 |
+
|
| 42 |
+
// If the handler produces some result for this request,
|
| 43 |
+
// it automatically becomes matching.
|
| 44 |
+
if (result !== null) {
|
| 45 |
+
matchingHandler = handler
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// Stop the lookup if this handler returns a mocked response.
|
| 49 |
+
// If it doesn't, it will still be considered the last matching
|
| 50 |
+
// handler until any of them returns a response. This way we can
|
| 51 |
+
// distinguish between fallthrough handlers without responses
|
| 52 |
+
// and the lack of a matching handler.
|
| 53 |
+
if (result?.response) {
|
| 54 |
+
break
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
if (matchingHandler) {
|
| 59 |
+
return {
|
| 60 |
+
handler: matchingHandler,
|
| 61 |
+
parsedResult: result?.parsedResult,
|
| 62 |
+
response: result?.response,
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
return null
|
| 67 |
+
}
|
node_modules/msw/src/core/utils/handleRequest.test.ts
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @vitest-environment jsdom
|
| 2 |
+
import { Emitter } from 'strict-event-emitter'
|
| 3 |
+
import { createRequestId } from '@mswjs/interceptors'
|
| 4 |
+
import type { LifeCycleEventsMap, SharedOptions } from '../sharedOptions'
|
| 5 |
+
import type { RequestHandler } from '../handlers/RequestHandler'
|
| 6 |
+
import { http } from '../http'
|
| 7 |
+
import type { HandleRequestOptions } from './handleRequest'
|
| 8 |
+
import { handleRequest } from './handleRequest'
|
| 9 |
+
import type { RequiredDeep } from '../typeUtils'
|
| 10 |
+
import { HttpResponse } from '../HttpResponse'
|
| 11 |
+
import { passthrough } from '../passthrough'
|
| 12 |
+
|
| 13 |
+
const options: RequiredDeep<SharedOptions> = {
|
| 14 |
+
onUnhandledRequest: vi.fn(),
|
| 15 |
+
}
|
| 16 |
+
const handleRequestOptions: Partial<Record<keyof HandleRequestOptions, any>> = {
|
| 17 |
+
onPassthroughResponse: vi.fn(),
|
| 18 |
+
onMockedResponse: vi.fn(),
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
function setup() {
|
| 22 |
+
const emitter = new Emitter<LifeCycleEventsMap>()
|
| 23 |
+
const listener = vi.fn()
|
| 24 |
+
|
| 25 |
+
const createMockListener = (name: string) => {
|
| 26 |
+
return (...args: any) => {
|
| 27 |
+
listener(name, ...args)
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
emitter.on('request:start', createMockListener('request:start'))
|
| 32 |
+
emitter.on('request:match', createMockListener('request:match'))
|
| 33 |
+
emitter.on('request:unhandled', createMockListener('request:unhandled'))
|
| 34 |
+
emitter.on('request:end', createMockListener('request:end'))
|
| 35 |
+
emitter.on('response:mocked', createMockListener('response:mocked'))
|
| 36 |
+
emitter.on('response:bypass', createMockListener('response:bypass'))
|
| 37 |
+
|
| 38 |
+
const events = listener.mock.calls
|
| 39 |
+
return { emitter, events }
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
beforeEach(() => {
|
| 43 |
+
vi.spyOn(global.console, 'warn').mockImplementation(() => void 0)
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
afterEach(() => {
|
| 47 |
+
vi.resetAllMocks()
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
test('returns undefined for a request with the "accept: msw/passthrough" header equal to "bypass"', async () => {
|
| 51 |
+
const { emitter, events } = setup()
|
| 52 |
+
|
| 53 |
+
const requestId = createRequestId()
|
| 54 |
+
const request = new Request(new URL('http://localhost/user'), {
|
| 55 |
+
headers: new Headers({
|
| 56 |
+
accept: 'msw/passthrough',
|
| 57 |
+
}),
|
| 58 |
+
})
|
| 59 |
+
const handlers: Array<RequestHandler> = []
|
| 60 |
+
|
| 61 |
+
const result = await handleRequest(
|
| 62 |
+
request,
|
| 63 |
+
requestId,
|
| 64 |
+
handlers,
|
| 65 |
+
options,
|
| 66 |
+
emitter,
|
| 67 |
+
handleRequestOptions,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
expect(result).toBeUndefined()
|
| 71 |
+
expect(events).toEqual([
|
| 72 |
+
['request:start', { request, requestId }],
|
| 73 |
+
['request:end', { request, requestId }],
|
| 74 |
+
])
|
| 75 |
+
expect(options.onUnhandledRequest).not.toHaveBeenCalled()
|
| 76 |
+
expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith(
|
| 77 |
+
1,
|
| 78 |
+
request,
|
| 79 |
+
)
|
| 80 |
+
expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled()
|
| 81 |
+
})
|
| 82 |
+
|
| 83 |
+
test('does not bypass a request with "accept: msw/*" header set to arbitrary value', async () => {
|
| 84 |
+
const { emitter } = setup()
|
| 85 |
+
|
| 86 |
+
const request = new Request(new URL('http://localhost/user'), {
|
| 87 |
+
headers: new Headers({
|
| 88 |
+
accept: 'msw/invalid',
|
| 89 |
+
}),
|
| 90 |
+
})
|
| 91 |
+
const handlers: Array<RequestHandler> = [
|
| 92 |
+
http.get('/user', () => {
|
| 93 |
+
return HttpResponse.text('hello world')
|
| 94 |
+
}),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
const result = await handleRequest(
|
| 98 |
+
request,
|
| 99 |
+
createRequestId(),
|
| 100 |
+
handlers,
|
| 101 |
+
options,
|
| 102 |
+
emitter,
|
| 103 |
+
handleRequestOptions,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
expect(result).not.toBeUndefined()
|
| 107 |
+
expect(options.onUnhandledRequest).not.toHaveBeenCalled()
|
| 108 |
+
expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1)
|
| 109 |
+
})
|
| 110 |
+
|
| 111 |
+
test('reports request as unhandled when it has no matching request handlers', async () => {
|
| 112 |
+
const { emitter, events } = setup()
|
| 113 |
+
|
| 114 |
+
const requestId = createRequestId()
|
| 115 |
+
const request = new Request(new URL('http://localhost/user'))
|
| 116 |
+
const handlers: Array<RequestHandler> = []
|
| 117 |
+
|
| 118 |
+
const result = await handleRequest(
|
| 119 |
+
request,
|
| 120 |
+
requestId,
|
| 121 |
+
handlers,
|
| 122 |
+
options,
|
| 123 |
+
emitter,
|
| 124 |
+
handleRequestOptions,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
expect(result).toBeUndefined()
|
| 128 |
+
expect(events).toEqual([
|
| 129 |
+
['request:start', { request, requestId }],
|
| 130 |
+
['request:unhandled', { request, requestId }],
|
| 131 |
+
['request:end', { request, requestId }],
|
| 132 |
+
])
|
| 133 |
+
expect(options.onUnhandledRequest).toHaveBeenNthCalledWith(1, request, {
|
| 134 |
+
warning: expect.any(Function),
|
| 135 |
+
error: expect.any(Function),
|
| 136 |
+
})
|
| 137 |
+
expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith(
|
| 138 |
+
1,
|
| 139 |
+
request,
|
| 140 |
+
)
|
| 141 |
+
expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled()
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
test('returns undefined on a request handler that returns no response', async () => {
|
| 145 |
+
const { emitter, events } = setup()
|
| 146 |
+
|
| 147 |
+
const requestId = createRequestId()
|
| 148 |
+
const request = new Request(new URL('http://localhost/user'))
|
| 149 |
+
const handlers: Array<RequestHandler> = [
|
| 150 |
+
http.get('/user', () => {
|
| 151 |
+
// Intentionally blank response resolver.
|
| 152 |
+
return
|
| 153 |
+
}),
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
const result = await handleRequest(
|
| 157 |
+
request,
|
| 158 |
+
requestId,
|
| 159 |
+
handlers,
|
| 160 |
+
options,
|
| 161 |
+
emitter,
|
| 162 |
+
handleRequestOptions,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
expect(result).toBeUndefined()
|
| 166 |
+
expect(events).toEqual([
|
| 167 |
+
['request:start', { request, requestId }],
|
| 168 |
+
['request:end', { request, requestId }],
|
| 169 |
+
])
|
| 170 |
+
expect(options.onUnhandledRequest).not.toHaveBeenCalled()
|
| 171 |
+
expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith(
|
| 172 |
+
1,
|
| 173 |
+
request,
|
| 174 |
+
)
|
| 175 |
+
expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled()
|
| 176 |
+
|
| 177 |
+
/**
|
| 178 |
+
* @note Returning undefined from a resolver no longer prints a warning.
|
| 179 |
+
*/
|
| 180 |
+
expect(console.warn).toHaveBeenCalledTimes(0)
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
test('returns the mocked response for a request with a matching request handler', async () => {
|
| 184 |
+
const { emitter, events } = setup()
|
| 185 |
+
|
| 186 |
+
const requestId = createRequestId()
|
| 187 |
+
const request = new Request(new URL('http://localhost/user'))
|
| 188 |
+
const mockedResponse = HttpResponse.json({ firstName: 'John' })
|
| 189 |
+
const handlers: Array<RequestHandler> = [
|
| 190 |
+
http.get('/user', () => {
|
| 191 |
+
return mockedResponse
|
| 192 |
+
}),
|
| 193 |
+
]
|
| 194 |
+
const lookupResult = {
|
| 195 |
+
handler: handlers[0],
|
| 196 |
+
response: mockedResponse,
|
| 197 |
+
request,
|
| 198 |
+
parsedResult: {
|
| 199 |
+
match: { matches: true, params: {} },
|
| 200 |
+
cookies: {},
|
| 201 |
+
},
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
const result = await handleRequest(
|
| 205 |
+
request,
|
| 206 |
+
requestId,
|
| 207 |
+
handlers,
|
| 208 |
+
options,
|
| 209 |
+
emitter,
|
| 210 |
+
handleRequestOptions,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
expect(result).toEqual(mockedResponse)
|
| 214 |
+
expect(events).toEqual([
|
| 215 |
+
['request:start', { request, requestId }],
|
| 216 |
+
['request:match', { request, requestId }],
|
| 217 |
+
['request:end', { request, requestId }],
|
| 218 |
+
])
|
| 219 |
+
expect(handleRequestOptions.onPassthroughResponse).not.toHaveBeenCalled()
|
| 220 |
+
|
| 221 |
+
expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1)
|
| 222 |
+
const [mockedResponseParam, lookupResultParam] =
|
| 223 |
+
handleRequestOptions.onMockedResponse.mock.calls[0]
|
| 224 |
+
|
| 225 |
+
expect(mockedResponseParam.status).toBe(mockedResponse.status)
|
| 226 |
+
expect(mockedResponseParam.statusText).toBe(mockedResponse.statusText)
|
| 227 |
+
expect(Object.fromEntries(mockedResponseParam.headers.entries())).toEqual(
|
| 228 |
+
Object.fromEntries(mockedResponse.headers.entries()),
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
expect(lookupResultParam).toEqual({
|
| 232 |
+
handler: lookupResult.handler,
|
| 233 |
+
parsedResult: lookupResult.parsedResult,
|
| 234 |
+
response: expect.objectContaining({
|
| 235 |
+
status: lookupResult.response.status,
|
| 236 |
+
statusText: lookupResult.response.statusText,
|
| 237 |
+
}),
|
| 238 |
+
})
|
| 239 |
+
})
|
| 240 |
+
|
| 241 |
+
it('returns undefined without warning on a passthrough request', async () => {
|
| 242 |
+
const { emitter, events } = setup()
|
| 243 |
+
|
| 244 |
+
const requestId = createRequestId()
|
| 245 |
+
const request = new Request(new URL('http://localhost/user'))
|
| 246 |
+
const handlers: Array<RequestHandler> = [
|
| 247 |
+
http.get('/user', () => {
|
| 248 |
+
return passthrough()
|
| 249 |
+
}),
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
const result = await handleRequest(
|
| 253 |
+
request,
|
| 254 |
+
requestId,
|
| 255 |
+
handlers,
|
| 256 |
+
options,
|
| 257 |
+
emitter,
|
| 258 |
+
handleRequestOptions,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
expect(result).toBeUndefined()
|
| 262 |
+
expect(events).toEqual([
|
| 263 |
+
['request:start', { request, requestId }],
|
| 264 |
+
['request:end', { request, requestId }],
|
| 265 |
+
])
|
| 266 |
+
expect(options.onUnhandledRequest).not.toHaveBeenCalled()
|
| 267 |
+
expect(handleRequestOptions.onPassthroughResponse).toHaveBeenNthCalledWith(
|
| 268 |
+
1,
|
| 269 |
+
request,
|
| 270 |
+
)
|
| 271 |
+
expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled()
|
| 272 |
+
})
|
| 273 |
+
|
| 274 |
+
it('calls the handler with the requestId', async () => {
|
| 275 |
+
const { emitter } = setup()
|
| 276 |
+
|
| 277 |
+
const requestId = createRequestId()
|
| 278 |
+
const request = new Request(new URL('http://localhost/user'))
|
| 279 |
+
const handlerFn = vi.fn()
|
| 280 |
+
const handlers: Array<RequestHandler> = [http.get('/user', handlerFn)]
|
| 281 |
+
|
| 282 |
+
await handleRequest(
|
| 283 |
+
request,
|
| 284 |
+
requestId,
|
| 285 |
+
handlers,
|
| 286 |
+
options,
|
| 287 |
+
emitter,
|
| 288 |
+
handleRequestOptions,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
expect(handlerFn).toHaveBeenCalledWith(expect.objectContaining({ requestId }))
|
| 292 |
+
})
|
| 293 |
+
|
| 294 |
+
it('marks the first matching one-time handler as used', async () => {
|
| 295 |
+
const { emitter } = setup()
|
| 296 |
+
|
| 297 |
+
const oneTimeHandler = http.get(
|
| 298 |
+
'/resource',
|
| 299 |
+
() => {
|
| 300 |
+
return HttpResponse.text('One-time')
|
| 301 |
+
},
|
| 302 |
+
{ once: true },
|
| 303 |
+
)
|
| 304 |
+
const anotherHandler = http.get('/resource', () => {
|
| 305 |
+
return HttpResponse.text('Another')
|
| 306 |
+
})
|
| 307 |
+
const handlers: Array<RequestHandler> = [oneTimeHandler, anotherHandler]
|
| 308 |
+
|
| 309 |
+
const requestId = createRequestId()
|
| 310 |
+
const request = new Request('http://localhost/resource')
|
| 311 |
+
const firstResult = await handleRequest(
|
| 312 |
+
request,
|
| 313 |
+
requestId,
|
| 314 |
+
handlers,
|
| 315 |
+
options,
|
| 316 |
+
emitter,
|
| 317 |
+
handleRequestOptions,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
expect(await firstResult?.text()).toBe('One-time')
|
| 321 |
+
expect(oneTimeHandler.isUsed).toBe(true)
|
| 322 |
+
expect(anotherHandler.isUsed).toBe(false)
|
| 323 |
+
|
| 324 |
+
const secondResult = await handleRequest(
|
| 325 |
+
request,
|
| 326 |
+
requestId,
|
| 327 |
+
handlers,
|
| 328 |
+
options,
|
| 329 |
+
emitter,
|
| 330 |
+
handleRequestOptions,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
expect(await secondResult?.text()).toBe('Another')
|
| 334 |
+
expect(anotherHandler.isUsed).toBe(true)
|
| 335 |
+
expect(oneTimeHandler.isUsed).toBe(true)
|
| 336 |
+
})
|
| 337 |
+
|
| 338 |
+
it('does not mark non-matching one-time handlers as used', async () => {
|
| 339 |
+
const { emitter } = setup()
|
| 340 |
+
|
| 341 |
+
const oneTimeHandler = http.get(
|
| 342 |
+
'/resource',
|
| 343 |
+
() => {
|
| 344 |
+
return HttpResponse.text('One-time')
|
| 345 |
+
},
|
| 346 |
+
{ once: true },
|
| 347 |
+
)
|
| 348 |
+
const anotherHandler = http.get(
|
| 349 |
+
'/another',
|
| 350 |
+
() => {
|
| 351 |
+
return HttpResponse.text('Another')
|
| 352 |
+
},
|
| 353 |
+
{ once: true },
|
| 354 |
+
)
|
| 355 |
+
const handlers: Array<RequestHandler> = [oneTimeHandler, anotherHandler]
|
| 356 |
+
|
| 357 |
+
const requestId = createRequestId()
|
| 358 |
+
const firstResult = await handleRequest(
|
| 359 |
+
new Request('http://localhost/another'),
|
| 360 |
+
requestId,
|
| 361 |
+
handlers,
|
| 362 |
+
options,
|
| 363 |
+
emitter,
|
| 364 |
+
handleRequestOptions,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
expect(await firstResult?.text()).toBe('Another')
|
| 368 |
+
expect(oneTimeHandler.isUsed).toBe(false)
|
| 369 |
+
expect(anotherHandler.isUsed).toBe(true)
|
| 370 |
+
|
| 371 |
+
const secondResult = await handleRequest(
|
| 372 |
+
new Request('http://localhost/resource'),
|
| 373 |
+
requestId,
|
| 374 |
+
handlers,
|
| 375 |
+
options,
|
| 376 |
+
emitter,
|
| 377 |
+
handleRequestOptions,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
expect(await secondResult?.text()).toBe('One-time')
|
| 381 |
+
expect(anotherHandler.isUsed).toBe(true)
|
| 382 |
+
expect(oneTimeHandler.isUsed).toBe(true)
|
| 383 |
+
})
|
| 384 |
+
|
| 385 |
+
it('handles parallel requests with one-time handlers', async () => {
|
| 386 |
+
const { emitter } = setup()
|
| 387 |
+
|
| 388 |
+
const oneTimeHandler = http.get(
|
| 389 |
+
'/resource',
|
| 390 |
+
() => {
|
| 391 |
+
return HttpResponse.text('One-time')
|
| 392 |
+
},
|
| 393 |
+
{ once: true },
|
| 394 |
+
)
|
| 395 |
+
const anotherHandler = http.get('/resource', () => {
|
| 396 |
+
return HttpResponse.text('Another')
|
| 397 |
+
})
|
| 398 |
+
const handlers: Array<RequestHandler> = [oneTimeHandler, anotherHandler]
|
| 399 |
+
|
| 400 |
+
const requestId = createRequestId()
|
| 401 |
+
const request = new Request('http://localhost/resource')
|
| 402 |
+
const firstResultPromise = handleRequest(
|
| 403 |
+
request,
|
| 404 |
+
requestId,
|
| 405 |
+
handlers,
|
| 406 |
+
options,
|
| 407 |
+
emitter,
|
| 408 |
+
handleRequestOptions,
|
| 409 |
+
)
|
| 410 |
+
const secondResultPromise = handleRequest(
|
| 411 |
+
request,
|
| 412 |
+
requestId,
|
| 413 |
+
handlers,
|
| 414 |
+
options,
|
| 415 |
+
emitter,
|
| 416 |
+
handleRequestOptions,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
const firstResult = await firstResultPromise
|
| 420 |
+
const secondResult = await secondResultPromise
|
| 421 |
+
|
| 422 |
+
expect(await firstResult?.text()).toBe('One-time')
|
| 423 |
+
expect(await secondResult?.text()).toBe('Another')
|
| 424 |
+
expect(oneTimeHandler.isUsed).toBe(true)
|
| 425 |
+
expect(anotherHandler.isUsed).toBe(true)
|
| 426 |
+
})
|
| 427 |
+
|
| 428 |
+
describe('[Private] - resolutionContext - used for extensions', () => {
|
| 429 |
+
describe('#baseUrl', () => {
|
| 430 |
+
test('when defined, handle requests to that base url only defining pathnames in the handler', async () => {
|
| 431 |
+
const { emitter } = setup()
|
| 432 |
+
|
| 433 |
+
const baseUrl = 'http://this-base-url-works.com'
|
| 434 |
+
const handleRequestOptionsWithBaseUrl: HandleRequestOptions = {
|
| 435 |
+
...handleRequestOptions,
|
| 436 |
+
resolutionContext: { baseUrl },
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
const handler = http.get('/resource', () => {
|
| 440 |
+
return HttpResponse.text('Mocked response')
|
| 441 |
+
})
|
| 442 |
+
|
| 443 |
+
const handlers: Array<RequestHandler> = [handler]
|
| 444 |
+
|
| 445 |
+
const requestId = createRequestId()
|
| 446 |
+
const request = new Request(new URL('/resource', baseUrl))
|
| 447 |
+
const response = await handleRequest(
|
| 448 |
+
request,
|
| 449 |
+
requestId,
|
| 450 |
+
handlers,
|
| 451 |
+
options,
|
| 452 |
+
emitter,
|
| 453 |
+
handleRequestOptionsWithBaseUrl,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
expect(await response?.text()).toBe('Mocked response')
|
| 457 |
+
})
|
| 458 |
+
|
| 459 |
+
test('when defined, do not handle requests to different base urls when defining pathnames in the handler', async () => {
|
| 460 |
+
const { emitter } = setup()
|
| 461 |
+
|
| 462 |
+
const baseUrl = 'http://this-base-url-works.com'
|
| 463 |
+
const handleRequestOptionsWithBaseUrl: HandleRequestOptions = {
|
| 464 |
+
...handleRequestOptions,
|
| 465 |
+
resolutionContext: { baseUrl },
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
const handler = http.get('/resource', () => {
|
| 469 |
+
return HttpResponse.text('Mocked response')
|
| 470 |
+
})
|
| 471 |
+
|
| 472 |
+
const handlers: Array<RequestHandler> = [handler]
|
| 473 |
+
|
| 474 |
+
const requestId = createRequestId()
|
| 475 |
+
const request = new Request(
|
| 476 |
+
new URL('/resource', `http://not-the-base-url.com`),
|
| 477 |
+
)
|
| 478 |
+
const response = await handleRequest(
|
| 479 |
+
request,
|
| 480 |
+
requestId,
|
| 481 |
+
handlers,
|
| 482 |
+
options,
|
| 483 |
+
emitter,
|
| 484 |
+
handleRequestOptionsWithBaseUrl,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
expect(response).toBeUndefined()
|
| 488 |
+
})
|
| 489 |
+
})
|
| 490 |
+
})
|
| 491 |
+
|
| 492 |
+
describe('handler with custom predicate', () => {
|
| 493 |
+
test('matches if custom predicate returns true', async () => {
|
| 494 |
+
const { emitter, events } = setup()
|
| 495 |
+
|
| 496 |
+
const requestId = createRequestId()
|
| 497 |
+
const request = new Request(new URL('http://localhost/login'), {
|
| 498 |
+
method: 'POST',
|
| 499 |
+
body: JSON.stringify({ username: 'test', password: 'password' }),
|
| 500 |
+
headers: { 'Content-Type': 'application/json' },
|
| 501 |
+
})
|
| 502 |
+
const handlers: Array<RequestHandler> = [
|
| 503 |
+
http.post(
|
| 504 |
+
async ({ request }) => {
|
| 505 |
+
const body = await request.clone().json()
|
| 506 |
+
return body.username === 'test' && body.password === 'password'
|
| 507 |
+
},
|
| 508 |
+
() =>
|
| 509 |
+
HttpResponse.json({
|
| 510 |
+
success: true,
|
| 511 |
+
}),
|
| 512 |
+
),
|
| 513 |
+
]
|
| 514 |
+
|
| 515 |
+
const result = await handleRequest(
|
| 516 |
+
request,
|
| 517 |
+
requestId,
|
| 518 |
+
handlers,
|
| 519 |
+
options,
|
| 520 |
+
emitter,
|
| 521 |
+
handleRequestOptions,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
expect(result).toBeDefined()
|
| 525 |
+
expect(await result?.json()).toStrictEqual({ success: true })
|
| 526 |
+
expect(events).toEqual([
|
| 527 |
+
['request:start', { request, requestId }],
|
| 528 |
+
['request:match', { request, requestId }],
|
| 529 |
+
['request:end', { request, requestId }],
|
| 530 |
+
])
|
| 531 |
+
expect(handleRequestOptions.onMockedResponse).toHaveBeenCalledTimes(1)
|
| 532 |
+
})
|
| 533 |
+
|
| 534 |
+
test('does not match if custom predicate returns false', async () => {
|
| 535 |
+
const { emitter, events } = setup()
|
| 536 |
+
|
| 537 |
+
const requestId = createRequestId()
|
| 538 |
+
const request = new Request(new URL('http://localhost/login'), {
|
| 539 |
+
method: 'POST',
|
| 540 |
+
body: JSON.stringify({ username: 'test', password: 'passwordd' }),
|
| 541 |
+
headers: { 'Content-Type': 'application/json' },
|
| 542 |
+
})
|
| 543 |
+
const handlers: Array<RequestHandler> = [
|
| 544 |
+
http.post(
|
| 545 |
+
async ({ request }) => {
|
| 546 |
+
const body = await request.clone().json()
|
| 547 |
+
return body.username === 'test' && body.password === 'password'
|
| 548 |
+
},
|
| 549 |
+
() =>
|
| 550 |
+
HttpResponse.json({
|
| 551 |
+
success: true,
|
| 552 |
+
}),
|
| 553 |
+
),
|
| 554 |
+
]
|
| 555 |
+
|
| 556 |
+
const result = await handleRequest(
|
| 557 |
+
request,
|
| 558 |
+
requestId,
|
| 559 |
+
handlers,
|
| 560 |
+
options,
|
| 561 |
+
emitter,
|
| 562 |
+
handleRequestOptions,
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
expect(result).toBeUndefined()
|
| 566 |
+
expect(events).toEqual([
|
| 567 |
+
['request:start', { request, requestId }],
|
| 568 |
+
['request:unhandled', { request, requestId }],
|
| 569 |
+
['request:end', { request, requestId }],
|
| 570 |
+
])
|
| 571 |
+
expect(options.onUnhandledRequest).toHaveBeenCalledTimes(1)
|
| 572 |
+
expect(handleRequestOptions.onPassthroughResponse).toHaveBeenCalledTimes(1)
|
| 573 |
+
})
|
| 574 |
+
})
|
node_modules/msw/src/core/utils/handleRequest.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { until } from 'until-async'
|
| 2 |
+
import type { Emitter } from 'strict-event-emitter'
|
| 3 |
+
import type { LifeCycleEventsMap, SharedOptions } from '../sharedOptions'
|
| 4 |
+
import type { RequiredDeep } from '../typeUtils'
|
| 5 |
+
import type { RequestHandler } from '../handlers/RequestHandler'
|
| 6 |
+
import {
|
| 7 |
+
type HandlersExecutionResult,
|
| 8 |
+
type ResponseResolutionContext,
|
| 9 |
+
executeHandlers,
|
| 10 |
+
} from './executeHandlers'
|
| 11 |
+
import { onUnhandledRequest } from './request/onUnhandledRequest'
|
| 12 |
+
import { storeResponseCookies } from './request/storeResponseCookies'
|
| 13 |
+
|
| 14 |
+
export interface HandleRequestOptions {
|
| 15 |
+
/**
|
| 16 |
+
* `resolutionContext` is not part of the general public api
|
| 17 |
+
* but is exposed to aid in creating extensions like
|
| 18 |
+
* `@mswjs/http-middleware`.
|
| 19 |
+
*/
|
| 20 |
+
resolutionContext?: ResponseResolutionContext
|
| 21 |
+
|
| 22 |
+
/**
|
| 23 |
+
* Invoked whenever a request is performed as-is.
|
| 24 |
+
*/
|
| 25 |
+
onPassthroughResponse?(request: Request): void
|
| 26 |
+
|
| 27 |
+
/**
|
| 28 |
+
* Invoked when the mocked response is ready to be sent.
|
| 29 |
+
*/
|
| 30 |
+
onMockedResponse?(
|
| 31 |
+
response: Response,
|
| 32 |
+
handler: RequiredDeep<HandlersExecutionResult>,
|
| 33 |
+
): void
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
export async function handleRequest(
|
| 37 |
+
request: Request,
|
| 38 |
+
requestId: string,
|
| 39 |
+
handlers: Array<RequestHandler>,
|
| 40 |
+
options: RequiredDeep<SharedOptions>,
|
| 41 |
+
emitter: Emitter<LifeCycleEventsMap>,
|
| 42 |
+
handleRequestOptions?: HandleRequestOptions,
|
| 43 |
+
): Promise<Response | undefined> {
|
| 44 |
+
emitter.emit('request:start', { request, requestId })
|
| 45 |
+
|
| 46 |
+
// Perform requests wrapped in "bypass()" as-is.
|
| 47 |
+
if (request.headers.get('accept')?.includes('msw/passthrough')) {
|
| 48 |
+
emitter.emit('request:end', { request, requestId })
|
| 49 |
+
handleRequestOptions?.onPassthroughResponse?.(request)
|
| 50 |
+
return
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
// Resolve a mocked response from the list of request handlers.
|
| 54 |
+
const [lookupError, lookupResult] = await until(() => {
|
| 55 |
+
return executeHandlers({
|
| 56 |
+
request,
|
| 57 |
+
requestId,
|
| 58 |
+
handlers,
|
| 59 |
+
resolutionContext: handleRequestOptions?.resolutionContext,
|
| 60 |
+
})
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
if (lookupError) {
|
| 64 |
+
// Allow developers to react to unhandled exceptions in request handlers.
|
| 65 |
+
emitter.emit('unhandledException', {
|
| 66 |
+
error: lookupError,
|
| 67 |
+
request,
|
| 68 |
+
requestId,
|
| 69 |
+
})
|
| 70 |
+
throw lookupError
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// If the handler lookup returned nothing, no request handler was found
|
| 74 |
+
// matching this request. Report the request as unhandled.
|
| 75 |
+
if (!lookupResult) {
|
| 76 |
+
await onUnhandledRequest(request, options.onUnhandledRequest)
|
| 77 |
+
emitter.emit('request:unhandled', { request, requestId })
|
| 78 |
+
emitter.emit('request:end', { request, requestId })
|
| 79 |
+
handleRequestOptions?.onPassthroughResponse?.(request)
|
| 80 |
+
return
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
const { response } = lookupResult
|
| 84 |
+
|
| 85 |
+
// When the handled request returned no mocked response, warn the developer,
|
| 86 |
+
// as it may be an oversight on their part. Perform the request as-is.
|
| 87 |
+
if (!response) {
|
| 88 |
+
emitter.emit('request:end', { request, requestId })
|
| 89 |
+
handleRequestOptions?.onPassthroughResponse?.(request)
|
| 90 |
+
return
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// Perform the request as-is when the developer explicitly returned "req.passthrough()".
|
| 94 |
+
// This produces no warning as the request was handled.
|
| 95 |
+
if (
|
| 96 |
+
response.status === 302 &&
|
| 97 |
+
response.headers.get('x-msw-intention') === 'passthrough'
|
| 98 |
+
) {
|
| 99 |
+
emitter.emit('request:end', { request, requestId })
|
| 100 |
+
handleRequestOptions?.onPassthroughResponse?.(request)
|
| 101 |
+
return
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// Store all the received response cookies in the cookie jar.
|
| 105 |
+
await storeResponseCookies(request, response)
|
| 106 |
+
|
| 107 |
+
emitter.emit('request:match', { request, requestId })
|
| 108 |
+
|
| 109 |
+
const requiredLookupResult =
|
| 110 |
+
lookupResult as RequiredDeep<HandlersExecutionResult>
|
| 111 |
+
|
| 112 |
+
handleRequestOptions?.onMockedResponse?.(response, requiredLookupResult)
|
| 113 |
+
|
| 114 |
+
emitter.emit('request:end', { request, requestId })
|
| 115 |
+
|
| 116 |
+
return response
|
| 117 |
+
}
|
node_modules/msw/src/core/utils/internal/Disposable.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { devUtils } from './devUtils'
|
| 2 |
+
|
| 3 |
+
export type DisposableSubscription = () => void
|
| 4 |
+
|
| 5 |
+
export class Disposable {
|
| 6 |
+
protected subscriptions: Array<DisposableSubscription> = []
|
| 7 |
+
|
| 8 |
+
public dispose() {
|
| 9 |
+
let subscription: DisposableSubscription | undefined
|
| 10 |
+
const errors: Array<Error> = []
|
| 11 |
+
|
| 12 |
+
while ((subscription = this.subscriptions.shift())) {
|
| 13 |
+
try {
|
| 14 |
+
subscription()
|
| 15 |
+
} catch (error) {
|
| 16 |
+
if (error instanceof Error) {
|
| 17 |
+
errors.push(error)
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
if (errors.length > 0) {
|
| 23 |
+
console.error(
|
| 24 |
+
new AggregateError(
|
| 25 |
+
errors,
|
| 26 |
+
devUtils.formatMessage(
|
| 27 |
+
'Failed to dispose of some side effects. This is likely an issue with MSW, please report it on GitHub: https://github.com/mswjs/msw/issues',
|
| 28 |
+
),
|
| 29 |
+
),
|
| 30 |
+
)
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
}
|
node_modules/msw/src/core/utils/internal/attachSiblingHandlers.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { invariant } from 'outvariant'
|
| 2 |
+
import type { AnyHandler } from '../../experimental/handlers-controller'
|
| 3 |
+
|
| 4 |
+
const kSiblingHandlers = Symbol('kSiblingHandlers')
|
| 5 |
+
|
| 6 |
+
export function attachSiblingHandlers<T extends AnyHandler>(
|
| 7 |
+
owner: T,
|
| 8 |
+
siblings: Array<AnyHandler>,
|
| 9 |
+
): T {
|
| 10 |
+
invariant(
|
| 11 |
+
getSiblingHandlers(owner).length === 0,
|
| 12 |
+
'Failed to merge handlers: the owner "%s" handler is already merged',
|
| 13 |
+
owner.kind,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
Object.defineProperty(owner, kSiblingHandlers, {
|
| 17 |
+
value: siblings,
|
| 18 |
+
enumerable: false,
|
| 19 |
+
writable: false,
|
| 20 |
+
configurable: false,
|
| 21 |
+
})
|
| 22 |
+
|
| 23 |
+
return owner
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export function getSiblingHandlers(owner: AnyHandler): Array<AnyHandler> {
|
| 27 |
+
return Reflect.get(owner, kSiblingHandlers) || []
|
| 28 |
+
}
|
node_modules/msw/src/core/utils/internal/checkGlobals.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { invariant } from 'outvariant'
|
| 2 |
+
import { devUtils } from './devUtils'
|
| 3 |
+
|
| 4 |
+
export function checkGlobals() {
|
| 5 |
+
/**
|
| 6 |
+
* MSW expects the "URL" constructor to be defined.
|
| 7 |
+
* It's not present in React Native so suggest a polyfill
|
| 8 |
+
* instead of failing silently.
|
| 9 |
+
* @see https://github.com/mswjs/msw/issues/1408
|
| 10 |
+
*/
|
| 11 |
+
invariant(
|
| 12 |
+
typeof URL !== 'undefined',
|
| 13 |
+
devUtils.formatMessage(
|
| 14 |
+
`Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`,
|
| 15 |
+
),
|
| 16 |
+
)
|
| 17 |
+
}
|
node_modules/msw/src/core/utils/internal/devUtils.test.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { InternalError } from './devUtils'
|
| 2 |
+
|
| 3 |
+
describe(InternalError, () => {
|
| 4 |
+
it('creates an InternalError instance', () => {
|
| 5 |
+
const error = new InternalError('Message')
|
| 6 |
+
|
| 7 |
+
expect(error.name).toBe('InternalError')
|
| 8 |
+
expect(error.message).toBe('Message')
|
| 9 |
+
expect(error.toString()).toBe('InternalError: Message')
|
| 10 |
+
expect(error.stack).toMatch(/\w+/)
|
| 11 |
+
})
|
| 12 |
+
|
| 13 |
+
it('passes the identity check', () => {
|
| 14 |
+
const error = new InternalError('Message')
|
| 15 |
+
expect(error instanceof InternalError).toBe(true)
|
| 16 |
+
expect(error instanceof Error).toBe(true)
|
| 17 |
+
|
| 18 |
+
const extraneousError = new Error('Message')
|
| 19 |
+
expect(extraneousError).not.toBeInstanceOf(InternalError)
|
| 20 |
+
})
|
| 21 |
+
})
|
node_modules/msw/src/core/utils/internal/devUtils.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { format } from 'outvariant'
|
| 2 |
+
|
| 3 |
+
const LIBRARY_PREFIX = '[MSW]'
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Formats a given message by appending the library's prefix string.
|
| 7 |
+
*/
|
| 8 |
+
function formatMessage(message: string, ...positionals: any[]): string {
|
| 9 |
+
const interpolatedMessage = format(message, ...positionals)
|
| 10 |
+
return `${LIBRARY_PREFIX} ${interpolatedMessage}`
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* Prints a library-specific warning.
|
| 15 |
+
*/
|
| 16 |
+
function warn(message: string, ...positionals: any[]): void {
|
| 17 |
+
console.warn(formatMessage(message, ...positionals))
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
/**
|
| 21 |
+
* Prints a library-specific error.
|
| 22 |
+
*/
|
| 23 |
+
function error(message: string, ...positionals: any[]): void {
|
| 24 |
+
console.error(formatMessage(message, ...positionals))
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
export const devUtils = {
|
| 28 |
+
formatMessage,
|
| 29 |
+
warn,
|
| 30 |
+
error,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/**
|
| 34 |
+
* Internal error instance.
|
| 35 |
+
* Used to differentiate the library errors that must be forwarded
|
| 36 |
+
* to the user from the unhandled exceptions. Use this if you don't
|
| 37 |
+
* wish for the error to be coerced to a 500 fallback response.
|
| 38 |
+
*/
|
| 39 |
+
export class InternalError extends Error {
|
| 40 |
+
constructor(message: string) {
|
| 41 |
+
super(message)
|
| 42 |
+
this.name = 'InternalError'
|
| 43 |
+
}
|
| 44 |
+
}
|
node_modules/msw/src/core/utils/internal/getCallFrame.test.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @vitest-environment jsdom
|
| 3 |
+
*/
|
| 4 |
+
import { getCallFrame } from './getCallFrame'
|
| 5 |
+
|
| 6 |
+
class ErrorWithStack extends Error {
|
| 7 |
+
constructor(stack: string[] | undefined | null) {
|
| 8 |
+
super('')
|
| 9 |
+
this.stack = stack?.join('\n')
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
test('supports Node.js (Linux, MacOS) error stack', () => {
|
| 14 |
+
const linuxError = new ErrorWithStack([
|
| 15 |
+
'Error: ',
|
| 16 |
+
' at getCallFrame (/Users/mock/github/msw/lib/node/index.js:3735:22)',
|
| 17 |
+
' at Object.get (/Users/mock/github/msw/lib/node/index.js:3776:29)',
|
| 18 |
+
' at Object.<anonymous> (/Users/mock/github/msw/test/msw-api/setup-server/listHandlers.test.ts:13:8)', // <-- this one
|
| 19 |
+
' at Runtime._execModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:1299:24)',
|
| 20 |
+
' at Runtime._loadModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:898:12)',
|
| 21 |
+
' at Runtime.requireModule (/Users/mock/github/msw/node_modules/jest-runtime/build/index.js:746:10)',
|
| 22 |
+
' at jasmine2 (/Users/mock/github/msw/node_modules/jest-jasmine2/build/index.js:230:13)',
|
| 23 |
+
' at runTestInternal (/Users/mock/github/msw/node_modules/jest-runner/build/runTest.js:380:22)',
|
| 24 |
+
' at runTest (/Users/mock/github/msw/node_modules/jest-runner/build/runTest.js:472:34)',
|
| 25 |
+
])
|
| 26 |
+
expect(getCallFrame(linuxError)).toEqual(
|
| 27 |
+
'/Users/mock/github/msw/test/msw-api/setup-server/listHandlers.test.ts:13:8',
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
const macOsError = new ErrorWithStack([
|
| 31 |
+
'Error: ',
|
| 32 |
+
' at getCallFrame (/Users/mock/git/msw/lib/node/index.js:3735:22)',
|
| 33 |
+
' at graphQLRequestHandler (/Users/mock/git/msw/lib/node/index.js:7071:25)',
|
| 34 |
+
' at Object.query (/Users/mock/git/msw/lib/node/index.js:7182:18)',
|
| 35 |
+
' at Object.<anonymous> (/Users/mock/git/msw/test/msw-api/setup-server/listHandlers.test.ts:14:11)', // <-- this one
|
| 36 |
+
' at Runtime._execModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:1299:24)',
|
| 37 |
+
' at Runtime._loadModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:898:12)',
|
| 38 |
+
' at Runtime.requireModule (/Users/mock/git/msw/node_modules/jest-runtime/build/index.js:746:10)',
|
| 39 |
+
' at jasmine2 (/Users/mock/git/msw/node_modules/jest-jasmine2/build/index.js:230:13)',
|
| 40 |
+
' at runTestInternal (/Users/mock/git/msw/node_modules/jest-runner/build/runTest.js:380:22)',
|
| 41 |
+
' at runTest (/Users/mock/git/msw/node_modules/jest-runner/build/runTest.js:472:34)',
|
| 42 |
+
])
|
| 43 |
+
|
| 44 |
+
expect(getCallFrame(macOsError)).toEqual(
|
| 45 |
+
'/Users/mock/git/msw/test/msw-api/setup-server/listHandlers.test.ts:14:11',
|
| 46 |
+
)
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
test('supports Node.js (Windows) error stack', () => {
|
| 50 |
+
const error = new ErrorWithStack([
|
| 51 |
+
'Error: ',
|
| 52 |
+
' at getCallFrame (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:3735:22)',
|
| 53 |
+
' at graphQLRequestHandler (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:7071:25)',
|
| 54 |
+
' at Object.query (C:\\Users\\mock\\git\\msw\\lib\\node\\index.js:7182:18)',
|
| 55 |
+
' at Object.<anonymous> (C:\\Users\\mock\\git\\msw\\test\\msw-api\\setup-server\\listHandlers.test.ts:75:13)', // <-- this one
|
| 56 |
+
' at Object.asyncJestTest (C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\jasmineAsyncInstall.js:106:37)',
|
| 57 |
+
' at C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:45:12',
|
| 58 |
+
' at new Promise (<anonymous>)',
|
| 59 |
+
' at mapper (C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:28:19)',
|
| 60 |
+
' at C:\\Users\\mock\\git\\msw\\node_modules\\jest-jasmine2\\build\\queueRunner.js:75:41',
|
| 61 |
+
])
|
| 62 |
+
|
| 63 |
+
expect(getCallFrame(error)).toBe(
|
| 64 |
+
'C:\\Users\\mock\\git\\msw\\test\\msw-api\\setup-server\\listHandlers.test.ts:75:13',
|
| 65 |
+
)
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
test('supports Chrome and Edge error stack', () => {
|
| 69 |
+
const error = new ErrorWithStack([
|
| 70 |
+
'Error',
|
| 71 |
+
' at getCallFrame (webpack:///./lib/browser/getCallFrame-deps.js?:272:20)',
|
| 72 |
+
' at Object.eval [as get] (webpack:///./lib/browser/rest-deps.js?:1402:90)',
|
| 73 |
+
' at eval (webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113)', // <-- this one
|
| 74 |
+
' at Module../test/msw-api/setup-worker/listHandlers.mocks.ts (http://localhost:59464/main.js:1376:1)',
|
| 75 |
+
' at __webpack_require__ (http://localhost:59464/main.js:790:30)',
|
| 76 |
+
' at fn (http://localhost:59464/main.js:101:20)',
|
| 77 |
+
' at eval (webpack:///multi_(webpack)-dev-server/client?:4:18)',
|
| 78 |
+
' at Object.0 (http://localhost:59464/main.js:1399:1)',
|
| 79 |
+
' at __webpack_require__ (http://localhost:59464/main.js:790:30)',
|
| 80 |
+
' at http://localhost:59464/main.js:857:37',
|
| 81 |
+
])
|
| 82 |
+
|
| 83 |
+
expect(getCallFrame(error)).toBe(
|
| 84 |
+
'webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113',
|
| 85 |
+
)
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
test('supports Firefox (MacOS, Windows) error stack', () => {
|
| 89 |
+
const error = new ErrorWithStack([
|
| 90 |
+
'getCallFrame@webpack:///./lib/browser/getCallFrame-deps.js?:272:20',
|
| 91 |
+
'createRestHandler/<@webpack:///./lib/browser/rest-deps.js?:1402:90',
|
| 92 |
+
'@webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113', // <-- this one
|
| 93 |
+
'./test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:1',
|
| 94 |
+
'__webpack_require__@http://localhost:59464/main.js:790:30',
|
| 95 |
+
'fn@http://localhost:59464/main.js:101:20',
|
| 96 |
+
'@webpack:///multi_(webpack)-dev-server/client?:4:18',
|
| 97 |
+
'0@http://localhost:59464/main.js:1399:1',
|
| 98 |
+
'__webpack_require__@http://localhost:59464/main.js:790:30',
|
| 99 |
+
'@http://localhost:59464/main.js:857:37',
|
| 100 |
+
])
|
| 101 |
+
|
| 102 |
+
expect(getCallFrame(error)).toBe(
|
| 103 |
+
'webpack:///./test/msw-api/setup-worker/listHandlers.mocks.ts?:6:113',
|
| 104 |
+
)
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
test('supports Safari (MacOS) error stack', () => {
|
| 108 |
+
const errorOne = new ErrorWithStack([
|
| 109 |
+
'getCallFrame',
|
| 110 |
+
'',
|
| 111 |
+
'eval code',
|
| 112 |
+
'eval@[native code]',
|
| 113 |
+
'./test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:5', // <-- this one
|
| 114 |
+
'__webpack_require__@http://localhost:59464/main.js:790:34',
|
| 115 |
+
'fn@http://localhost:59464/main.js:101:39',
|
| 116 |
+
'eval code',
|
| 117 |
+
'eval@[native code]',
|
| 118 |
+
'http://localhost:59464/main.js:1399:5',
|
| 119 |
+
'__webpack_require__@http://localhost:59464/main.js:790:34',
|
| 120 |
+
'http://localhost:59464/main.js:857:37',
|
| 121 |
+
'global code@http://localhost:59464/main.js:858:12',
|
| 122 |
+
])
|
| 123 |
+
|
| 124 |
+
expect(getCallFrame(errorOne)).toBe(
|
| 125 |
+
'./test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:59464/main.js:1376:5',
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
const errorTwo = new ErrorWithStack([
|
| 129 |
+
'getCallFrame',
|
| 130 |
+
'graphQLRequestHandler',
|
| 131 |
+
'eval code',
|
| 132 |
+
'eval@[native code]',
|
| 133 |
+
'./test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:56460/main.js:1376:5', // <-- this one
|
| 134 |
+
'__webpack_require__@http://localhost:56460/main.js:790:34',
|
| 135 |
+
'fn@http://localhost:56460/main.js:101:39',
|
| 136 |
+
'eval code',
|
| 137 |
+
'eval@[native code]',
|
| 138 |
+
'http://localhost:56460/main.js:1399:5',
|
| 139 |
+
'__webpack_require__@http://localhost:56460/main.js:790:34',
|
| 140 |
+
'http://localhost:56460/main.js:857:37',
|
| 141 |
+
'global code@http://localhost:56460/main.js:858:12',
|
| 142 |
+
])
|
| 143 |
+
|
| 144 |
+
expect(getCallFrame(errorTwo)).toBe(
|
| 145 |
+
'./test/msw-api/setup-worker/listHandlers.mocks.ts@http://localhost:56460/main.js:1376:5',
|
| 146 |
+
)
|
| 147 |
+
})
|
| 148 |
+
|
| 149 |
+
test('handles the undefined stack trace', () => {
|
| 150 |
+
expect(() => getCallFrame(new ErrorWithStack(undefined))).not.toThrow(
|
| 151 |
+
TypeError,
|
| 152 |
+
)
|
| 153 |
+
expect(() => getCallFrame(new ErrorWithStack(null))).not.toThrow(TypeError)
|
| 154 |
+
})
|
node_modules/msw/src/core/utils/internal/getCallFrame.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Ignore the source files traces for local testing.
|
| 2 |
+
const SOURCE_FRAME = /[/\\]msw[/\\]src[/\\](.+)/
|
| 3 |
+
|
| 4 |
+
const BUILD_FRAME =
|
| 5 |
+
/(node_modules)?[/\\]lib[/\\](core|browser|node|native|iife)[/\\]|^[^/\\]*$/
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* Return the stack trace frame of a function's invocation.
|
| 9 |
+
*/
|
| 10 |
+
export function getCallFrame(error: Error) {
|
| 11 |
+
// In <IE11, new Error may return an undefined stack
|
| 12 |
+
const stack = error.stack
|
| 13 |
+
|
| 14 |
+
if (!stack) {
|
| 15 |
+
return
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const frames: string[] = stack.split('\n').slice(1)
|
| 19 |
+
|
| 20 |
+
// Get the first frame that doesn't reference the library's internal trace.
|
| 21 |
+
// Assume that frame is the invocation frame.
|
| 22 |
+
const declarationFrame = frames.find((frame) => {
|
| 23 |
+
return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame))
|
| 24 |
+
})
|
| 25 |
+
|
| 26 |
+
if (!declarationFrame) {
|
| 27 |
+
return
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// Extract file reference from the stack frame.
|
| 31 |
+
const declarationPath = declarationFrame
|
| 32 |
+
.replace(/\s*at [^()]*\(([^)]+)\)/, '$1')
|
| 33 |
+
.replace(/^@/, '')
|
| 34 |
+
return declarationPath
|
| 35 |
+
}
|
node_modules/msw/src/core/utils/internal/hasRefCounted.test.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { hasRefCounted } from './hasRefCounted'
|
| 2 |
+
|
| 3 |
+
it('returns true for objects with ref and unref methods', () => {
|
| 4 |
+
expect(
|
| 5 |
+
hasRefCounted({
|
| 6 |
+
ref() {},
|
| 7 |
+
unref() {},
|
| 8 |
+
}),
|
| 9 |
+
).toBe(true)
|
| 10 |
+
})
|
| 11 |
+
|
| 12 |
+
it('returns false for a non-refcounted object', () => {
|
| 13 |
+
expect(hasRefCounted({})).toBe(false)
|
| 14 |
+
expect(hasRefCounted({ ref() {} })).toBe(false)
|
| 15 |
+
expect(hasRefCounted({ unref() {} })).toBe(false)
|
| 16 |
+
})
|
| 17 |
+
|
| 18 |
+
it('returns false for non-object values', () => {
|
| 19 |
+
expect(
|
| 20 |
+
hasRefCounted(
|
| 21 |
+
// @ts-expect-error Runtime value.
|
| 22 |
+
null,
|
| 23 |
+
),
|
| 24 |
+
).toBe(false)
|
| 25 |
+
expect(
|
| 26 |
+
hasRefCounted(
|
| 27 |
+
// @ts-expect-error Runtime value.
|
| 28 |
+
123,
|
| 29 |
+
),
|
| 30 |
+
).toBe(false)
|
| 31 |
+
expect(
|
| 32 |
+
hasRefCounted(
|
| 33 |
+
// @ts-expect-error Runtime value.
|
| 34 |
+
'invalid',
|
| 35 |
+
),
|
| 36 |
+
).toBe(false)
|
| 37 |
+
})
|
node_modules/msw/src/core/utils/internal/hasRefCounted.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isObject } from './isObject'
|
| 2 |
+
|
| 3 |
+
export function hasRefCounted<T extends object>(
|
| 4 |
+
value: T,
|
| 5 |
+
): value is T & NodeJS.RefCounted {
|
| 6 |
+
return (
|
| 7 |
+
/**
|
| 8 |
+
* @note Guard against non-object values.
|
| 9 |
+
* E.g. `setTimeout` returns an object in Node.js but a number in the browser.
|
| 10 |
+
*/
|
| 11 |
+
isObject(value) &&
|
| 12 |
+
typeof Reflect.get(value, 'ref') === 'function' &&
|
| 13 |
+
typeof Reflect.get(value, 'unref') === 'function'
|
| 14 |
+
)
|
| 15 |
+
}
|
node_modules/msw/src/core/utils/internal/isHandlerKind.test.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { GraphQLHandler } from '../../handlers/GraphQLHandler'
|
| 2 |
+
import { HttpHandler } from '../../handlers/HttpHandler'
|
| 3 |
+
import { RequestHandler } from '../../handlers/RequestHandler'
|
| 4 |
+
import { WebSocketHandler } from '../../handlers/WebSocketHandler'
|
| 5 |
+
import { isHandlerKind } from './isHandlerKind'
|
| 6 |
+
|
| 7 |
+
it('returns true if expected a request handler and given a request handler', () => {
|
| 8 |
+
expect(isHandlerKind('request')(new HttpHandler('*', '*', () => {}))).toBe(
|
| 9 |
+
true,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
expect(
|
| 13 |
+
isHandlerKind('request')(new GraphQLHandler('all', '*', '*', () => {})),
|
| 14 |
+
).toBe(true)
|
| 15 |
+
})
|
| 16 |
+
|
| 17 |
+
it('returns true if expected a request handler and given a custom request handler', () => {
|
| 18 |
+
class MyHandler extends RequestHandler {
|
| 19 |
+
constructor() {
|
| 20 |
+
super({ info: { header: '*' }, resolver: () => {} })
|
| 21 |
+
}
|
| 22 |
+
predicate = () => false
|
| 23 |
+
log() {}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
expect(isHandlerKind('request')(new MyHandler())).toBe(true)
|
| 27 |
+
})
|
| 28 |
+
|
| 29 |
+
it('returns false if expected a request handler but given event handler', () => {
|
| 30 |
+
expect(isHandlerKind('request')(new WebSocketHandler('*'))).toBe(false)
|
| 31 |
+
})
|
| 32 |
+
|
| 33 |
+
it('returns false if expected a request handler but given arbitrary object', () => {
|
| 34 |
+
expect(isHandlerKind('request')(undefined)).toBe(false)
|
| 35 |
+
expect(isHandlerKind('request')(null)).toBe(false)
|
| 36 |
+
expect(isHandlerKind('request')({})).toBe(false)
|
| 37 |
+
expect(isHandlerKind('request')([])).toBe(false)
|
| 38 |
+
expect(isHandlerKind('request')(123)).toBe(false)
|
| 39 |
+
expect(isHandlerKind('request')('hello')).toBe(false)
|
| 40 |
+
})
|
| 41 |
+
|
| 42 |
+
it('returns true if expected an event handler and given an event handler', () => {
|
| 43 |
+
expect(isHandlerKind('websocket')(new WebSocketHandler('*'))).toBe(true)
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
it('returns true if expected an event handler and given a custom event handler', () => {
|
| 47 |
+
class MyEventHandler extends WebSocketHandler {
|
| 48 |
+
constructor() {
|
| 49 |
+
super('*')
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
expect(isHandlerKind('websocket')(new MyEventHandler())).toBe(true)
|
| 53 |
+
})
|
| 54 |
+
|
| 55 |
+
it('returns false if expected an event handler but given arbitrary object', () => {
|
| 56 |
+
expect(isHandlerKind('websocket')(undefined)).toBe(false)
|
| 57 |
+
expect(isHandlerKind('websocket')(null)).toBe(false)
|
| 58 |
+
expect(isHandlerKind('websocket')({})).toBe(false)
|
| 59 |
+
expect(isHandlerKind('websocket')([])).toBe(false)
|
| 60 |
+
expect(isHandlerKind('websocket')(123)).toBe(false)
|
| 61 |
+
expect(isHandlerKind('websocket')('hello')).toBe(false)
|
| 62 |
+
})
|
node_modules/msw/src/core/utils/internal/isHandlerKind.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { AnyHandler } from '../../experimental/handlers-controller'
|
| 2 |
+
import type { RequestHandler } from '../../handlers/RequestHandler'
|
| 3 |
+
import type { WebSocketHandler } from '../../handlers/WebSocketHandler'
|
| 4 |
+
import { isObject } from './isObject'
|
| 5 |
+
|
| 6 |
+
/**
|
| 7 |
+
* A filter function that ensures that the provided argument
|
| 8 |
+
* is a handler of the given kind. This helps differentiate
|
| 9 |
+
* between different kinds of handlers, e.g. request and event handlers.
|
| 10 |
+
*/
|
| 11 |
+
export function isHandlerKind<K extends AnyHandler['kind']>(kind: K) {
|
| 12 |
+
return (
|
| 13 |
+
input: unknown,
|
| 14 |
+
): input is K extends 'websocket' ? WebSocketHandler : RequestHandler => {
|
| 15 |
+
return isObject(input) && 'kind' in input && input.kind === kind
|
| 16 |
+
}
|
| 17 |
+
}
|
node_modules/msw/src/core/utils/internal/isIterable.test.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isIterable } from './isIterable'
|
| 2 |
+
|
| 3 |
+
test('returns true given an iterator', () => {
|
| 4 |
+
expect(
|
| 5 |
+
isIterable(
|
| 6 |
+
(function* () {
|
| 7 |
+
yield 2
|
| 8 |
+
})(),
|
| 9 |
+
),
|
| 10 |
+
).toEqual(true)
|
| 11 |
+
})
|
| 12 |
+
|
| 13 |
+
test('returns false given a regular function', () => {
|
| 14 |
+
expect(
|
| 15 |
+
isIterable(
|
| 16 |
+
(function () {
|
| 17 |
+
return null
|
| 18 |
+
})(),
|
| 19 |
+
),
|
| 20 |
+
).toEqual(false)
|
| 21 |
+
|
| 22 |
+
expect(isIterable((() => null)())).toEqual(false)
|
| 23 |
+
})
|
node_modules/msw/src/core/utils/internal/isIterable.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* This is the same as TypeScript's `Iterable`, but with all three type parameters.
|
| 3 |
+
* @todo Remove once TypeScript 5.6 is the minimum.
|
| 4 |
+
*/
|
| 5 |
+
export interface Iterable<T, TReturn, TNext> {
|
| 6 |
+
[Symbol.iterator](): Iterator<T, TReturn, TNext>
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
/**
|
| 10 |
+
* This is the same as TypeScript's `AsyncIterable`, but with all three type parameters.
|
| 11 |
+
* @todo Remove once TypeScript 5.6 is the minimum.
|
| 12 |
+
*/
|
| 13 |
+
export interface AsyncIterable<T, TReturn, TNext> {
|
| 14 |
+
[Symbol.asyncIterator](): AsyncIterator<T, TReturn, TNext>
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Determines if the given function is an iterator.
|
| 19 |
+
*/
|
| 20 |
+
export function isIterable<IteratorType>(
|
| 21 |
+
fn: any,
|
| 22 |
+
): fn is
|
| 23 |
+
| Iterable<IteratorType, IteratorType, IteratorType>
|
| 24 |
+
| AsyncIterable<IteratorType, IteratorType, IteratorType> {
|
| 25 |
+
if (!fn) {
|
| 26 |
+
return false
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
return (
|
| 30 |
+
Reflect.has(fn, Symbol.iterator) || Reflect.has(fn, Symbol.asyncIterator)
|
| 31 |
+
)
|
| 32 |
+
}
|
node_modules/msw/src/core/utils/internal/isObject.test.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isObject } from './isObject'
|
| 2 |
+
|
| 3 |
+
test('returns true given an object', () => {
|
| 4 |
+
expect(isObject({})).toBe(true)
|
| 5 |
+
expect(isObject({ a: 1 })).toBe(true)
|
| 6 |
+
})
|
| 7 |
+
|
| 8 |
+
test('returns false given a non-object value', () => {
|
| 9 |
+
expect(isObject(1)).toBe(false)
|
| 10 |
+
expect(isObject('string')).toBe(false)
|
| 11 |
+
expect(isObject([])).toBe(false)
|
| 12 |
+
expect(
|
| 13 |
+
isObject(function () {
|
| 14 |
+
return 2
|
| 15 |
+
}),
|
| 16 |
+
).toBe(false)
|
| 17 |
+
expect(isObject(false)).toBe(false)
|
| 18 |
+
expect(isObject(undefined)).toBe(false)
|
| 19 |
+
expect(isObject(null)).toBe(false)
|
| 20 |
+
})
|
node_modules/msw/src/core/utils/internal/isObject.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Determines if the given value is an object.
|
| 3 |
+
*/
|
| 4 |
+
export function isObject(value: any): value is Record<string, any> {
|
| 5 |
+
return value != null && typeof value === 'object' && !Array.isArray(value)
|
| 6 |
+
}
|
node_modules/msw/src/core/utils/internal/isStringEqual.test.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isStringEqual } from './isStringEqual'
|
| 2 |
+
|
| 3 |
+
describe('isStringEqual', () => {
|
| 4 |
+
describe('given two uppercase strings', () => {
|
| 5 |
+
describe('and the strings are equal', () => {
|
| 6 |
+
it('should return true', () => {
|
| 7 |
+
expect(isStringEqual('GET', 'GET')).toBe(true)
|
| 8 |
+
})
|
| 9 |
+
})
|
| 10 |
+
|
| 11 |
+
describe('and the strings are not equal', () => {
|
| 12 |
+
it('should return false', () => {
|
| 13 |
+
expect(isStringEqual('GET', 'POST')).toBe(false)
|
| 14 |
+
})
|
| 15 |
+
})
|
| 16 |
+
})
|
| 17 |
+
|
| 18 |
+
describe('given two lowercase strings', () => {
|
| 19 |
+
describe('and the strings are equal', () => {
|
| 20 |
+
it('should return true', () => {
|
| 21 |
+
expect(isStringEqual('get', 'get')).toBe(true)
|
| 22 |
+
})
|
| 23 |
+
})
|
| 24 |
+
|
| 25 |
+
describe('and the strings are not equal', () => {
|
| 26 |
+
it('should return false', () => {
|
| 27 |
+
expect(isStringEqual('get', 'post')).toBe(false)
|
| 28 |
+
})
|
| 29 |
+
})
|
| 30 |
+
})
|
| 31 |
+
|
| 32 |
+
describe('given two strings cased differently', () => {
|
| 33 |
+
describe('and the strings are equal', () => {
|
| 34 |
+
it('should return true', () => {
|
| 35 |
+
expect(isStringEqual('get', 'GET')).toBe(true)
|
| 36 |
+
})
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
describe('and the strings are not equal', () => {
|
| 40 |
+
it('should return false', () => {
|
| 41 |
+
expect(isStringEqual('get', 'POST')).toBe(false)
|
| 42 |
+
})
|
| 43 |
+
})
|
| 44 |
+
})
|
| 45 |
+
})
|
node_modules/msw/src/core/utils/internal/isStringEqual.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Performs a case-insensitive comparison of two given strings.
|
| 3 |
+
*/
|
| 4 |
+
export function isStringEqual(actual: string, expected: string): boolean {
|
| 5 |
+
return actual.toLowerCase() === expected.toLowerCase()
|
| 6 |
+
}
|
node_modules/msw/src/core/utils/internal/jsonParse.test.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { jsonParse } from './jsonParse'
|
| 2 |
+
|
| 3 |
+
test('parses a given valid JSON string', () => {
|
| 4 |
+
expect(jsonParse(`{"property":"value"}`)).toEqual({
|
| 5 |
+
property: 'value',
|
| 6 |
+
})
|
| 7 |
+
})
|
| 8 |
+
|
| 9 |
+
test('returns undefined without an error given an invalid JSON string', () => {
|
| 10 |
+
const parse = () => jsonParse(`{"property:val"ue$}`)
|
| 11 |
+
expect(parse).not.toThrow()
|
| 12 |
+
expect(parse()).toBeUndefined()
|
| 13 |
+
})
|
node_modules/msw/src/core/utils/internal/jsonParse.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Parses a given value into a JSON.
|
| 3 |
+
* Does not throw an exception on an invalid JSON string.
|
| 4 |
+
*/
|
| 5 |
+
export function jsonParse<ValueType extends Record<string, any>>(
|
| 6 |
+
value: any,
|
| 7 |
+
): ValueType | undefined {
|
| 8 |
+
try {
|
| 9 |
+
return JSON.parse(value)
|
| 10 |
+
} catch {
|
| 11 |
+
return undefined
|
| 12 |
+
}
|
| 13 |
+
}
|
node_modules/msw/src/core/utils/internal/mergeRight.test.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { mergeRight } from './mergeRight'
|
| 2 |
+
|
| 3 |
+
test('shallowly merges two given objects', () => {
|
| 4 |
+
expect(mergeRight({ a: 1, b: 2 }, { b: 3, c: 4 })).toEqual({
|
| 5 |
+
a: 1,
|
| 6 |
+
b: 3,
|
| 7 |
+
c: 4,
|
| 8 |
+
})
|
| 9 |
+
})
|
| 10 |
+
|
| 11 |
+
test('deeply merges two given objects', () => {
|
| 12 |
+
expect(
|
| 13 |
+
mergeRight(
|
| 14 |
+
{
|
| 15 |
+
a: 'string',
|
| 16 |
+
b: [1, 2],
|
| 17 |
+
c: {
|
| 18 |
+
d: 2,
|
| 19 |
+
},
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
a: 'another-string',
|
| 23 |
+
b: [3],
|
| 24 |
+
c: {
|
| 25 |
+
e: 'five',
|
| 26 |
+
f: {
|
| 27 |
+
g: true,
|
| 28 |
+
},
|
| 29 |
+
},
|
| 30 |
+
},
|
| 31 |
+
),
|
| 32 |
+
).toEqual({
|
| 33 |
+
a: 'another-string',
|
| 34 |
+
b: [1, 2, 3],
|
| 35 |
+
c: {
|
| 36 |
+
d: 2,
|
| 37 |
+
e: 'five',
|
| 38 |
+
f: {
|
| 39 |
+
g: true,
|
| 40 |
+
},
|
| 41 |
+
},
|
| 42 |
+
})
|
| 43 |
+
})
|
node_modules/msw/src/core/utils/internal/mergeRight.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isObject } from './isObject'
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Deeply merges two given objects with the right one
|
| 5 |
+
* having a priority during property assignment.
|
| 6 |
+
*/
|
| 7 |
+
export function mergeRight(
|
| 8 |
+
left: Record<string, any>,
|
| 9 |
+
right: Record<string, any>,
|
| 10 |
+
) {
|
| 11 |
+
return Object.entries(right).reduce(
|
| 12 |
+
(result, [key, rightValue]) => {
|
| 13 |
+
const leftValue = result[key]
|
| 14 |
+
|
| 15 |
+
if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
|
| 16 |
+
result[key] = leftValue.concat(rightValue)
|
| 17 |
+
return result
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
if (isObject(leftValue) && isObject(rightValue)) {
|
| 21 |
+
result[key] = mergeRight(leftValue, rightValue)
|
| 22 |
+
return result
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
result[key] = rightValue
|
| 26 |
+
return result
|
| 27 |
+
},
|
| 28 |
+
Object.assign({}, left),
|
| 29 |
+
)
|
| 30 |
+
}
|
node_modules/msw/src/core/utils/internal/parseGraphQLRequest.test.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @vitest-environment jsdom
|
| 3 |
+
*/
|
| 4 |
+
import { encodeBuffer } from '@mswjs/interceptors'
|
| 5 |
+
import { OperationTypeNode } from 'graphql'
|
| 6 |
+
import type { ParsedGraphQLRequest } from './parseGraphQLRequest'
|
| 7 |
+
import { parseGraphQLRequest } from './parseGraphQLRequest'
|
| 8 |
+
|
| 9 |
+
test('returns true given a GraphQL-compatible request', async () => {
|
| 10 |
+
const getRequest = new Request(
|
| 11 |
+
new URL(
|
| 12 |
+
'http://localhost:8080/graphql?query=mutation Login { user { id } }',
|
| 13 |
+
),
|
| 14 |
+
)
|
| 15 |
+
expect(await parseGraphQLRequest(getRequest)).toEqual<
|
| 16 |
+
ParsedGraphQLRequest<any>
|
| 17 |
+
>({
|
| 18 |
+
operationType: OperationTypeNode.MUTATION,
|
| 19 |
+
operationName: 'Login',
|
| 20 |
+
query: `mutation Login { user { id } }`,
|
| 21 |
+
variables: undefined,
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
const postRequest = new Request(new URL('http://localhost:8080/graphql'), {
|
| 25 |
+
method: 'POST',
|
| 26 |
+
headers: new Headers({ 'Content-Type': 'application/json' }),
|
| 27 |
+
body: encodeBuffer(
|
| 28 |
+
JSON.stringify({
|
| 29 |
+
query: `query GetUser { user { firstName } }`,
|
| 30 |
+
}),
|
| 31 |
+
),
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
expect(await parseGraphQLRequest(postRequest)).toEqual<
|
| 35 |
+
ParsedGraphQLRequest<any>
|
| 36 |
+
>({
|
| 37 |
+
operationType: OperationTypeNode.QUERY,
|
| 38 |
+
operationName: 'GetUser',
|
| 39 |
+
query: `query GetUser { user { firstName } }`,
|
| 40 |
+
variables: undefined,
|
| 41 |
+
})
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
test('throws an exception given an invalid GraphQL request', async () => {
|
| 45 |
+
const getRequest = new Request(
|
| 46 |
+
new URL('http://localhost:8080/graphql?query=mutation Login() { user { {}'),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
await expect(parseGraphQLRequest(getRequest)).rejects.toThrowError(
|
| 50 |
+
'[MSW] Failed to intercept a GraphQL request to "GET http://localhost:8080/graphql": cannot parse query. See the error message from the parser below.',
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
const postRequest = new Request(new URL('http://localhost:8080/graphql'), {
|
| 54 |
+
method: 'POST',
|
| 55 |
+
headers: new Headers({ 'Content-Type': 'application/json' }),
|
| 56 |
+
body: encodeBuffer(
|
| 57 |
+
JSON.stringify({
|
| 58 |
+
query: `query GetUser() { user {{}`,
|
| 59 |
+
}),
|
| 60 |
+
),
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
await expect(parseGraphQLRequest(postRequest)).rejects.toThrowError(
|
| 64 |
+
'[MSW] Failed to intercept a GraphQL request to "POST http://localhost:8080/graphql": cannot parse query. See the error message from the parser below.\n\nSyntax Error: Expected "$", found ")".',
|
| 65 |
+
)
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
test('returns false given a GraphQL-incompatible request', async () => {
|
| 69 |
+
const getRequest = new Request(new URL('http://localhost:8080/graphql'), {
|
| 70 |
+
headers: new Headers({ 'Content-Type': 'application/json' }),
|
| 71 |
+
})
|
| 72 |
+
expect(await parseGraphQLRequest(getRequest)).toBeUndefined()
|
| 73 |
+
|
| 74 |
+
const postRequest = new Request(new URL('http://localhost:8080/graphql'), {
|
| 75 |
+
method: 'POST',
|
| 76 |
+
headers: new Headers({ 'Content-Type': 'application/json' }),
|
| 77 |
+
body: encodeBuffer(
|
| 78 |
+
JSON.stringify({
|
| 79 |
+
queryUser: true,
|
| 80 |
+
}),
|
| 81 |
+
),
|
| 82 |
+
})
|
| 83 |
+
expect(await parseGraphQLRequest(postRequest)).toBeUndefined()
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
test('does not read the original request body', async () => {
|
| 87 |
+
const request = new Request(new URL('http://localhost/api'), {
|
| 88 |
+
method: 'POST',
|
| 89 |
+
body: JSON.stringify({ payload: 'value' }),
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
await parseGraphQLRequest(request)
|
| 93 |
+
|
| 94 |
+
// Must not read the original request body because GraphQL parsing
|
| 95 |
+
// is an internal operation that must not lock the body stream.
|
| 96 |
+
expect(request.bodyUsed).toBe(false)
|
| 97 |
+
})
|
node_modules/msw/src/core/utils/internal/parseGraphQLRequest.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
DocumentNode,
|
| 3 |
+
OperationDefinitionNode,
|
| 4 |
+
OperationTypeNode,
|
| 5 |
+
} from 'graphql'
|
| 6 |
+
import type { GraphQLVariables } from '../../handlers/GraphQLHandler'
|
| 7 |
+
import { toPublicUrl } from '../request/toPublicUrl'
|
| 8 |
+
import { devUtils } from './devUtils'
|
| 9 |
+
import { jsonParse } from './jsonParse'
|
| 10 |
+
import { parseMultipartData } from './parseMultipartData'
|
| 11 |
+
|
| 12 |
+
interface GraphQLInput {
|
| 13 |
+
query: string | null
|
| 14 |
+
variables?: GraphQLVariables
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export interface ParsedGraphQLQuery {
|
| 18 |
+
operationType: OperationTypeNode
|
| 19 |
+
operationName?: string
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
export type ParsedGraphQLRequest<
|
| 23 |
+
VariablesType extends GraphQLVariables = GraphQLVariables,
|
| 24 |
+
> =
|
| 25 |
+
| (ParsedGraphQLQuery & {
|
| 26 |
+
query: string
|
| 27 |
+
variables?: VariablesType
|
| 28 |
+
})
|
| 29 |
+
| undefined
|
| 30 |
+
|
| 31 |
+
export function parseDocumentNode(node: DocumentNode): ParsedGraphQLQuery {
|
| 32 |
+
const operationDef = node.definitions.find((definition) => {
|
| 33 |
+
return definition.kind === 'OperationDefinition'
|
| 34 |
+
}) as OperationDefinitionNode
|
| 35 |
+
|
| 36 |
+
return {
|
| 37 |
+
operationType: operationDef?.operation,
|
| 38 |
+
operationName: operationDef?.name?.value,
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
async function parseQuery(query: string): Promise<ParsedGraphQLQuery | Error> {
|
| 43 |
+
/**
|
| 44 |
+
* @note Use `require` to get the "graphql" module here.
|
| 45 |
+
* It has to be scoped to this function because this module leaks to the
|
| 46 |
+
* root export. It has to be `require` because tools like Jest have trouble
|
| 47 |
+
* handling dynamic imports. It gets replaced with a dynamic import on build time.
|
| 48 |
+
*/
|
| 49 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 50 |
+
const { parse } = require('graphql')
|
| 51 |
+
|
| 52 |
+
try {
|
| 53 |
+
const ast = parse(query)
|
| 54 |
+
return parseDocumentNode(ast)
|
| 55 |
+
} catch (error) {
|
| 56 |
+
return error as Error
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
export type GraphQLParsedOperationsMap = Record<string, string[]>
|
| 61 |
+
export type GraphQLMultipartRequestBody = {
|
| 62 |
+
operations: string
|
| 63 |
+
map?: string
|
| 64 |
+
} & {
|
| 65 |
+
[fileName: string]: File
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
function extractMultipartVariables<VariablesType extends GraphQLVariables>(
|
| 69 |
+
variables: VariablesType,
|
| 70 |
+
map: GraphQLParsedOperationsMap,
|
| 71 |
+
files: Record<string, File>,
|
| 72 |
+
) {
|
| 73 |
+
const operations = { variables }
|
| 74 |
+
|
| 75 |
+
for (const [key, pathArray] of Object.entries(map)) {
|
| 76 |
+
if (!(key in files)) {
|
| 77 |
+
throw new Error(`Given files do not have a key '${key}' .`)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
for (const dotPath of pathArray) {
|
| 81 |
+
const [lastPath, ...reversedPaths] = dotPath.split('.').reverse()
|
| 82 |
+
const paths = reversedPaths.reverse()
|
| 83 |
+
let target: Record<string, any> = operations
|
| 84 |
+
|
| 85 |
+
for (const path of paths) {
|
| 86 |
+
if (!(path in target)) {
|
| 87 |
+
throw new Error(`Property '${path}' is not in operations.`)
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
target = target[path]
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
target[lastPath] = files[key]
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
return operations.variables
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
async function getGraphQLInput(request: Request): Promise<GraphQLInput | null> {
|
| 101 |
+
switch (request.method) {
|
| 102 |
+
case 'GET': {
|
| 103 |
+
const url = new URL(request.url)
|
| 104 |
+
const query = url.searchParams.get('query')
|
| 105 |
+
const variables = url.searchParams.get('variables') || ''
|
| 106 |
+
|
| 107 |
+
return {
|
| 108 |
+
query,
|
| 109 |
+
variables: jsonParse(variables),
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
case 'POST': {
|
| 114 |
+
// Clone the request so we could read its body without locking
|
| 115 |
+
// the body stream to the downward consumers.
|
| 116 |
+
const requestClone = request.clone()
|
| 117 |
+
|
| 118 |
+
// Handle multipart body GraphQL operations.
|
| 119 |
+
if (
|
| 120 |
+
request.headers.get('content-type')?.includes('multipart/form-data')
|
| 121 |
+
) {
|
| 122 |
+
const responseJson = parseMultipartData<GraphQLMultipartRequestBody>(
|
| 123 |
+
await requestClone.text(),
|
| 124 |
+
request.headers,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if (!responseJson) {
|
| 128 |
+
return null
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
const { operations, map, ...files } = responseJson
|
| 132 |
+
const parsedOperations =
|
| 133 |
+
jsonParse<{ query?: string; variables?: GraphQLVariables }>(
|
| 134 |
+
operations,
|
| 135 |
+
) || {}
|
| 136 |
+
|
| 137 |
+
if (!parsedOperations.query) {
|
| 138 |
+
return null
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
const parsedMap = jsonParse<GraphQLParsedOperationsMap>(map || '') || {}
|
| 142 |
+
const variables = parsedOperations.variables
|
| 143 |
+
? extractMultipartVariables(
|
| 144 |
+
parsedOperations.variables,
|
| 145 |
+
parsedMap,
|
| 146 |
+
files,
|
| 147 |
+
)
|
| 148 |
+
: {}
|
| 149 |
+
|
| 150 |
+
return {
|
| 151 |
+
query: parsedOperations.query,
|
| 152 |
+
variables,
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
// Handle plain POST GraphQL operations.
|
| 157 |
+
const requestJson: {
|
| 158 |
+
query: string
|
| 159 |
+
variables?: GraphQLVariables
|
| 160 |
+
operations?: any /** @todo Annotate this */
|
| 161 |
+
} = await requestClone.json().catch(() => null)
|
| 162 |
+
|
| 163 |
+
if (requestJson?.query) {
|
| 164 |
+
const { query, variables } = requestJson
|
| 165 |
+
|
| 166 |
+
return {
|
| 167 |
+
query,
|
| 168 |
+
variables,
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
return null
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
default:
|
| 175 |
+
return null
|
| 176 |
+
}
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
/**
|
| 180 |
+
* Determines if a given request can be considered a GraphQL request.
|
| 181 |
+
* Does not parse the query and does not guarantee its validity.
|
| 182 |
+
*/
|
| 183 |
+
export async function parseGraphQLRequest(
|
| 184 |
+
request: Request,
|
| 185 |
+
): Promise<ParsedGraphQLRequest> {
|
| 186 |
+
const input = await getGraphQLInput(request)
|
| 187 |
+
|
| 188 |
+
if (!input || !input.query) {
|
| 189 |
+
return
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
const { query, variables } = input
|
| 193 |
+
const parsedResult = await parseQuery(query)
|
| 194 |
+
|
| 195 |
+
if (parsedResult instanceof Error) {
|
| 196 |
+
const requestPublicUrl = toPublicUrl(request.url)
|
| 197 |
+
|
| 198 |
+
throw new Error(
|
| 199 |
+
devUtils.formatMessage(
|
| 200 |
+
'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
|
| 201 |
+
request.method,
|
| 202 |
+
requestPublicUrl,
|
| 203 |
+
parsedResult.message,
|
| 204 |
+
),
|
| 205 |
+
)
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
return {
|
| 209 |
+
query: input.query,
|
| 210 |
+
operationType: parsedResult.operationType,
|
| 211 |
+
operationName: parsedResult.operationName,
|
| 212 |
+
variables,
|
| 213 |
+
}
|
| 214 |
+
}
|
node_modules/msw/src/core/utils/internal/parseMultipartData.test.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @vitest-environment jsdom
|
| 3 |
+
*/
|
| 4 |
+
import { parseMultipartData } from './parseMultipartData'
|
| 5 |
+
|
| 6 |
+
test('parses a given valid multipart string', async () => {
|
| 7 |
+
expect.assertions(3)
|
| 8 |
+
await testMultipartDataWithContentType(
|
| 9 |
+
'multipart/form-data; boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab',
|
| 10 |
+
)
|
| 11 |
+
})
|
| 12 |
+
|
| 13 |
+
test('parses a given valid multipart string given non-pretty content-type', async () => {
|
| 14 |
+
expect.assertions(3)
|
| 15 |
+
// node-fetch will serialize content-type in this format, which is valid according to HTTP
|
| 16 |
+
// https://github.com/node-fetch/node-fetch/blob/d8fc32d6b29bd43d1ad377e80b3e439fe37f2904/test/main.js#L1438
|
| 17 |
+
await testMultipartDataWithContentType(
|
| 18 |
+
'multipart/form-data;boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab',
|
| 19 |
+
)
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
test('parses a given valid multipart string given content-type with extra spaces', async () => {
|
| 23 |
+
expect.assertions(3)
|
| 24 |
+
await testMultipartDataWithContentType(
|
| 25 |
+
'multipart/form-data; boundary=WebKitFormBoundaryvZ1cVXWyK0ilQdab',
|
| 26 |
+
)
|
| 27 |
+
})
|
| 28 |
+
|
| 29 |
+
async function testMultipartDataWithContentType(
|
| 30 |
+
contentType: string,
|
| 31 |
+
): Promise<void> {
|
| 32 |
+
const body = `\
|
| 33 |
+
------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r
|
| 34 |
+
Content-Disposition: form-data; name="file"; filename="file1.txt"\r
|
| 35 |
+
Content-Type: application/octet-stream\r
|
| 36 |
+
\r
|
| 37 |
+
file content\r
|
| 38 |
+
------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r
|
| 39 |
+
Content-Disposition: form-data; name="text"\r
|
| 40 |
+
\r
|
| 41 |
+
text content\r
|
| 42 |
+
------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r
|
| 43 |
+
Content-Disposition: form-data; name="text2"\r
|
| 44 |
+
\r
|
| 45 |
+
another text content\r
|
| 46 |
+
------WebKitFormBoundaryvZ1cVXWyK0ilQdab\r
|
| 47 |
+
Content-Disposition: form-data; name="text2"\r
|
| 48 |
+
\r
|
| 49 |
+
\r
|
| 50 |
+
another text content 2\r
|
| 51 |
+
\r
|
| 52 |
+
------WebKitFormBoundaryvZ1cVXWyK0ilQdab--`
|
| 53 |
+
const headers = new Headers({
|
| 54 |
+
'content-type': contentType,
|
| 55 |
+
})
|
| 56 |
+
const parsed = parseMultipartData(body, headers)
|
| 57 |
+
|
| 58 |
+
// Workaround: JSDOM does not have `Blob.text` implementation.
|
| 59 |
+
// see https://github.com/jsdom/jsdom/issues/2555
|
| 60 |
+
expect(parsed).toHaveProperty('file.name', 'file1.txt')
|
| 61 |
+
|
| 62 |
+
expect(parsed).toHaveProperty('text', 'text content')
|
| 63 |
+
expect(parsed).toHaveProperty('text2', [
|
| 64 |
+
'another text content',
|
| 65 |
+
'\r\nanother text content 2\r\n',
|
| 66 |
+
])
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
test('returns undefined without an error given an invalid multipart string', () => {
|
| 70 |
+
const headers = new Headers({
|
| 71 |
+
'content-type': 'multipart/form-data; boundary=dummyBoundary',
|
| 72 |
+
})
|
| 73 |
+
const parse = () => parseMultipartData(`{"invalid": ["multipart"]}`, headers)
|
| 74 |
+
expect(parse).not.toThrow()
|
| 75 |
+
expect(parse()).toBeUndefined()
|
| 76 |
+
})
|
node_modules/msw/src/core/utils/internal/parseMultipartData.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { stringToHeaders } from 'headers-polyfill'
|
| 2 |
+
import { type DefaultRequestMultipartBody } from '../../handlers/RequestHandler'
|
| 3 |
+
|
| 4 |
+
interface ParsedContentHeaders {
|
| 5 |
+
name: string
|
| 6 |
+
filename?: string
|
| 7 |
+
contentType: string
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
interface ContentDispositionDirective {
|
| 11 |
+
[key: string]: string | undefined
|
| 12 |
+
name: string
|
| 13 |
+
filename?: string
|
| 14 |
+
'form-data': string
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
function parseContentHeaders(headersString: string): ParsedContentHeaders {
|
| 18 |
+
const headers = stringToHeaders(headersString)
|
| 19 |
+
const contentType = headers.get('content-type') || 'text/plain'
|
| 20 |
+
const disposition = headers.get('content-disposition')
|
| 21 |
+
|
| 22 |
+
if (!disposition) {
|
| 23 |
+
throw new Error('"Content-Disposition" header is required.')
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
const directives = disposition.split(';').reduce((acc, chunk) => {
|
| 27 |
+
const [name, ...rest] = chunk.trim().split('=')
|
| 28 |
+
acc[name] = rest.join('=')
|
| 29 |
+
return acc
|
| 30 |
+
}, {} as ContentDispositionDirective)
|
| 31 |
+
|
| 32 |
+
const name = directives.name?.slice(1, -1)
|
| 33 |
+
const filename = directives.filename?.slice(1, -1)
|
| 34 |
+
|
| 35 |
+
return {
|
| 36 |
+
name,
|
| 37 |
+
filename,
|
| 38 |
+
contentType,
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* Parses a given string as a multipart/form-data.
|
| 44 |
+
* Does not throw an exception on an invalid multipart string.
|
| 45 |
+
*/
|
| 46 |
+
export function parseMultipartData<T extends DefaultRequestMultipartBody>(
|
| 47 |
+
data: string,
|
| 48 |
+
headers?: Headers,
|
| 49 |
+
): T | undefined {
|
| 50 |
+
const contentType = headers?.get('content-type')
|
| 51 |
+
|
| 52 |
+
if (!contentType) {
|
| 53 |
+
return undefined
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
const [, ...directives] = contentType.split(/; */)
|
| 57 |
+
const boundary = directives
|
| 58 |
+
.filter((d) => d.startsWith('boundary='))
|
| 59 |
+
.map((s) => s.replace(/^boundary=/, ''))[0]
|
| 60 |
+
|
| 61 |
+
if (!boundary) {
|
| 62 |
+
return undefined
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
const boundaryRegExp = new RegExp(
|
| 66 |
+
`--+${boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`,
|
| 67 |
+
)
|
| 68 |
+
const fields = data
|
| 69 |
+
.split(boundaryRegExp)
|
| 70 |
+
.filter((chunk) => chunk.startsWith('\r\n') && chunk.endsWith('\r\n'))
|
| 71 |
+
.map((chunk) => chunk.trimStart().replace(/\r\n$/, ''))
|
| 72 |
+
|
| 73 |
+
if (!fields.length) {
|
| 74 |
+
return undefined
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
const parsedBody: DefaultRequestMultipartBody = {}
|
| 78 |
+
|
| 79 |
+
try {
|
| 80 |
+
for (const field of fields) {
|
| 81 |
+
const [contentHeaders, ...rest] = field.split('\r\n\r\n')
|
| 82 |
+
const contentBody = rest.join('\r\n\r\n')
|
| 83 |
+
const { contentType, filename, name } =
|
| 84 |
+
parseContentHeaders(contentHeaders)
|
| 85 |
+
|
| 86 |
+
const value =
|
| 87 |
+
filename === undefined
|
| 88 |
+
? contentBody
|
| 89 |
+
: new File([contentBody], filename, { type: contentType })
|
| 90 |
+
|
| 91 |
+
const parsedValue = parsedBody[name]
|
| 92 |
+
|
| 93 |
+
if (parsedValue === undefined) {
|
| 94 |
+
parsedBody[name] = value
|
| 95 |
+
} else if (Array.isArray(parsedValue)) {
|
| 96 |
+
parsedBody[name] = [...parsedValue, value]
|
| 97 |
+
} else {
|
| 98 |
+
parsedBody[name] = [parsedValue, value]
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
return parsedBody as T
|
| 103 |
+
} catch {
|
| 104 |
+
return undefined
|
| 105 |
+
}
|
| 106 |
+
}
|
node_modules/msw/src/core/utils/internal/pipeEvents.test.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Emitter } from 'strict-event-emitter'
|
| 2 |
+
import { pipeEvents } from './pipeEvents'
|
| 3 |
+
|
| 4 |
+
it('pipes events from the source emitter to the destination emitter', () => {
|
| 5 |
+
const source = new Emitter()
|
| 6 |
+
const destination = new Emitter()
|
| 7 |
+
pipeEvents(source, destination)
|
| 8 |
+
|
| 9 |
+
const callback = vi.fn()
|
| 10 |
+
destination.on('hello', callback)
|
| 11 |
+
|
| 12 |
+
source.emit('hello', 'world', { data: true })
|
| 13 |
+
expect(callback).toHaveBeenNthCalledWith(1, 'world', { data: true })
|
| 14 |
+
})
|
node_modules/msw/src/core/utils/internal/pipeEvents.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Emitter } from 'strict-event-emitter'
|
| 2 |
+
import { type EventMap } from 'strict-event-emitter'
|
| 3 |
+
|
| 4 |
+
/**
|
| 5 |
+
* Pipes all emitted events from one emitter to another.
|
| 6 |
+
*/
|
| 7 |
+
export function pipeEvents<Events extends EventMap>(
|
| 8 |
+
source: Emitter<Events>,
|
| 9 |
+
destination: Emitter<Events>,
|
| 10 |
+
): void {
|
| 11 |
+
const rawEmit: typeof source.emit & { _isPiped?: boolean } = source.emit
|
| 12 |
+
|
| 13 |
+
if (rawEmit._isPiped) {
|
| 14 |
+
return
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const sourceEmit: typeof source.emit & { _isPiped?: boolean } =
|
| 18 |
+
function sourceEmit(this: typeof source, event, ...data) {
|
| 19 |
+
destination.emit(event, ...data)
|
| 20 |
+
return rawEmit.call(this, event, ...data)
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
sourceEmit._isPiped = true
|
| 24 |
+
|
| 25 |
+
source.emit = sourceEmit
|
| 26 |
+
}
|
node_modules/msw/src/core/utils/internal/toReadonlyArray.test.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { toReadonlyArray } from './toReadonlyArray'
|
| 2 |
+
|
| 3 |
+
it('creates a copy of an array', () => {
|
| 4 |
+
expect(toReadonlyArray([1, 2, 3])).toEqual([1, 2, 3])
|
| 5 |
+
})
|
| 6 |
+
|
| 7 |
+
it('does not affect the source array', () => {
|
| 8 |
+
const source = ['a', 'b', 'c']
|
| 9 |
+
toReadonlyArray(source)
|
| 10 |
+
|
| 11 |
+
expect(source.push('d')).toBe(4)
|
| 12 |
+
expect(source).toEqual(['a', 'b', 'c', 'd'])
|
| 13 |
+
})
|
| 14 |
+
|
| 15 |
+
it('forbids modifying the array copy', () => {
|
| 16 |
+
const source = [1, 2, 3]
|
| 17 |
+
const copy = toReadonlyArray(source)
|
| 18 |
+
|
| 19 |
+
expect(() => {
|
| 20 |
+
// @ts-expect-error Intentional runtime misusage.
|
| 21 |
+
copy[2] = 1
|
| 22 |
+
}).toThrow(/Cannot assign to read only property '\d+' of object/)
|
| 23 |
+
|
| 24 |
+
expect(() => {
|
| 25 |
+
// @ts-expect-error Intentional runtime misusage.
|
| 26 |
+
copy.push(4)
|
| 27 |
+
}).toThrow(/Cannot add property \d+, object is not extensible/)
|
| 28 |
+
|
| 29 |
+
expect(source).toEqual([1, 2, 3])
|
| 30 |
+
})
|
node_modules/msw/src/core/utils/internal/toReadonlyArray.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Creates an immutable copy of the given array.
|
| 3 |
+
*/
|
| 4 |
+
export function toReadonlyArray<T>(source: Array<T>): ReadonlyArray<T> {
|
| 5 |
+
const clone = [...source] as Array<T>
|
| 6 |
+
Object.freeze(clone)
|
| 7 |
+
return clone
|
| 8 |
+
}
|
node_modules/msw/src/core/utils/internal/tryCatch.test.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { tryCatch } from './tryCatch'
|
| 2 |
+
|
| 3 |
+
test('returns the function payload', () => {
|
| 4 |
+
const result = tryCatch(() => 'hello')
|
| 5 |
+
expect(result).toEqual('hello')
|
| 6 |
+
})
|
| 7 |
+
|
| 8 |
+
test('silences exceptions by default', () => {
|
| 9 |
+
const result = tryCatch(() => {
|
| 10 |
+
throw new Error('Exception')
|
| 11 |
+
})
|
| 12 |
+
|
| 13 |
+
expect(result).toBeUndefined()
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
+
test('executes a custom callback function when an exception occurs', async () => {
|
| 17 |
+
await new Promise<void>((resolve) => {
|
| 18 |
+
tryCatch(
|
| 19 |
+
() => {
|
| 20 |
+
throw new Error('Exception')
|
| 21 |
+
},
|
| 22 |
+
(error) => {
|
| 23 |
+
expect(error).toBeInstanceOf(Error)
|
| 24 |
+
expect(error.message).toEqual('Exception')
|
| 25 |
+
resolve()
|
| 26 |
+
},
|
| 27 |
+
)
|
| 28 |
+
})
|
| 29 |
+
})
|
node_modules/msw/src/core/utils/internal/tryCatch.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export function tryCatch<Fn extends (...args: any[]) => any>(
|
| 2 |
+
fn: Fn,
|
| 3 |
+
onException?: (error: Error) => void,
|
| 4 |
+
): ReturnType<Fn> | undefined {
|
| 5 |
+
try {
|
| 6 |
+
const result = fn()
|
| 7 |
+
return result
|
| 8 |
+
} catch (error) {
|
| 9 |
+
onException?.(error as Error)
|
| 10 |
+
}
|
| 11 |
+
}
|
node_modules/msw/src/core/utils/logging/getStatusCodeColor.test.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getStatusCodeColor } from './getStatusCodeColor'
|
| 2 |
+
|
| 3 |
+
test('returns a green color for status codes lower than 300', () => {
|
| 4 |
+
expect(getStatusCodeColor(100)).toBe('#69AB32')
|
| 5 |
+
expect(getStatusCodeColor(200)).toBe('#69AB32')
|
| 6 |
+
expect(getStatusCodeColor(204)).toBe('#69AB32')
|
| 7 |
+
})
|
| 8 |
+
|
| 9 |
+
test('returns a yellow color for status codes between 201 and 400', () => {
|
| 10 |
+
expect(getStatusCodeColor(300)).toBe('#F0BB4B')
|
| 11 |
+
expect(getStatusCodeColor(304)).toBe('#F0BB4B')
|
| 12 |
+
})
|
| 13 |
+
|
| 14 |
+
test('returns a red color for status codes higher than 400', () => {
|
| 15 |
+
expect(getStatusCodeColor(400)).toBe('#E95F5D')
|
| 16 |
+
expect(getStatusCodeColor(404)).toBe('#E95F5D')
|
| 17 |
+
expect(getStatusCodeColor(500)).toBe('#E95F5D')
|
| 18 |
+
})
|
| 19 |
+
|
| 20 |
+
test('returns a red color for unknown status code', () => {
|
| 21 |
+
expect(getStatusCodeColor(700)).toBe('#E95F5D')
|
| 22 |
+
})
|
node_modules/msw/src/core/utils/logging/getStatusCodeColor.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export enum StatusCodeColor {
|
| 2 |
+
Success = '#69AB32',
|
| 3 |
+
Warning = '#F0BB4B',
|
| 4 |
+
Danger = '#E95F5D',
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* Returns a HEX color for a given response status code number.
|
| 9 |
+
*/
|
| 10 |
+
export function getStatusCodeColor(status: number): StatusCodeColor {
|
| 11 |
+
if (status < 300) {
|
| 12 |
+
return StatusCodeColor.Success
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
if (status < 400) {
|
| 16 |
+
return StatusCodeColor.Warning
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
return StatusCodeColor.Danger
|
| 20 |
+
}
|
node_modules/msw/src/core/utils/logging/getTimestamp.test.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getTimestamp } from './getTimestamp'
|
| 2 |
+
|
| 3 |
+
beforeAll(() => {
|
| 4 |
+
vi.useFakeTimers()
|
| 5 |
+
})
|
| 6 |
+
|
| 7 |
+
afterAll(() => {
|
| 8 |
+
vi.useRealTimers()
|
| 9 |
+
})
|
| 10 |
+
|
| 11 |
+
test('returns a timestamp string of the invocation time', () => {
|
| 12 |
+
vi.setSystemTime(new Date('2024-01-01 12:4:8'))
|
| 13 |
+
const timestamp = getTimestamp()
|
| 14 |
+
expect(timestamp).toBe('12:04:08')
|
| 15 |
+
})
|
| 16 |
+
|
| 17 |
+
test('returns a timestamp with milliseconds', () => {
|
| 18 |
+
vi.setSystemTime(new Date('2024-01-01 12:4:8'))
|
| 19 |
+
expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.000')
|
| 20 |
+
|
| 21 |
+
vi.setSystemTime(new Date('2024-01-01 12:4:8.000'))
|
| 22 |
+
expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.000')
|
| 23 |
+
|
| 24 |
+
vi.setSystemTime(new Date('2024-01-01 12:4:8.4'))
|
| 25 |
+
expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.400')
|
| 26 |
+
|
| 27 |
+
vi.setSystemTime(new Date('2024-01-01 12:4:8.123'))
|
| 28 |
+
expect(getTimestamp({ milliseconds: true })).toBe('12:04:08.123')
|
| 29 |
+
|
| 30 |
+
vi.setSystemTime(new Date('2024-01-01 12:00:00'))
|
| 31 |
+
expect(getTimestamp({ milliseconds: true })).toBe('12:00:00.000')
|
| 32 |
+
})
|
node_modules/msw/src/core/utils/logging/getTimestamp.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface GetTimestampOptions {
|
| 2 |
+
milliseconds?: boolean
|
| 3 |
+
}
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Returns a timestamp string in a "HH:MM:SS" format.
|
| 7 |
+
*/
|
| 8 |
+
export function getTimestamp(options?: GetTimestampOptions): string {
|
| 9 |
+
const now = new Date()
|
| 10 |
+
const timestamp = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
|
| 11 |
+
|
| 12 |
+
if (options?.milliseconds) {
|
| 13 |
+
return `${timestamp}.${now.getMilliseconds().toString().padStart(3, '0')}`
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
return timestamp
|
| 17 |
+
}
|
node_modules/msw/src/core/utils/logging/serializeRequest.test.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodeBuffer } from '@mswjs/interceptors'
|
| 2 |
+
import { serializeRequest } from './serializeRequest'
|
| 3 |
+
|
| 4 |
+
test('serializes given Request instance into a plain object', async () => {
|
| 5 |
+
const request = await serializeRequest(
|
| 6 |
+
new Request(new URL('http://test.mswjs.io/user'), {
|
| 7 |
+
method: 'POST',
|
| 8 |
+
headers: new Headers({
|
| 9 |
+
'Content-Type': 'text/plain',
|
| 10 |
+
'X-Header': 'secret',
|
| 11 |
+
}),
|
| 12 |
+
body: encodeBuffer('text-body'),
|
| 13 |
+
}),
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
expect(request.method).toBe('POST')
|
| 17 |
+
expect(request.url.href).toBe('http://test.mswjs.io/user')
|
| 18 |
+
expect(request.headers).toEqual({
|
| 19 |
+
'content-type': 'text/plain',
|
| 20 |
+
'x-header': 'secret',
|
| 21 |
+
})
|
| 22 |
+
expect(request.body).toBe('text-body')
|
| 23 |
+
})
|
node_modules/msw/src/core/utils/logging/serializeRequest.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface LoggedRequest {
|
| 2 |
+
url: URL
|
| 3 |
+
method: string
|
| 4 |
+
headers: Record<string, string>
|
| 5 |
+
body: string
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
/**
|
| 9 |
+
* Formats a mocked request for introspection in browser's console.
|
| 10 |
+
*/
|
| 11 |
+
export async function serializeRequest(
|
| 12 |
+
request: Request,
|
| 13 |
+
): Promise<LoggedRequest> {
|
| 14 |
+
const requestClone = request.clone()
|
| 15 |
+
const requestText = await requestClone.text()
|
| 16 |
+
|
| 17 |
+
return {
|
| 18 |
+
url: new URL(request.url),
|
| 19 |
+
method: request.method,
|
| 20 |
+
headers: Object.fromEntries(request.headers.entries()),
|
| 21 |
+
body: requestText,
|
| 22 |
+
}
|
| 23 |
+
}
|
node_modules/msw/src/core/utils/logging/serializeResponse.test.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @vitest-environment node
|
| 3 |
+
*/
|
| 4 |
+
import { encodeBuffer } from '@mswjs/interceptors'
|
| 5 |
+
import { serializeResponse } from './serializeResponse'
|
| 6 |
+
|
| 7 |
+
it('serializes response without body', async () => {
|
| 8 |
+
const result = await serializeResponse(new Response(null))
|
| 9 |
+
|
| 10 |
+
expect(result.status).toBe(200)
|
| 11 |
+
expect(result.statusText).toBe('OK')
|
| 12 |
+
expect(result.headers).toEqual({})
|
| 13 |
+
expect(result.body).toBe('')
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
+
it('serializes a plain text response', async () => {
|
| 17 |
+
const result = await serializeResponse(
|
| 18 |
+
new Response('hello world', {
|
| 19 |
+
status: 201,
|
| 20 |
+
statusText: 'Created',
|
| 21 |
+
headers: {
|
| 22 |
+
'Content-Type': 'text/plain',
|
| 23 |
+
},
|
| 24 |
+
}),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
expect(result.status).toBe(201)
|
| 28 |
+
expect(result.statusText).toBe('Created')
|
| 29 |
+
expect(result.headers).toEqual({
|
| 30 |
+
'content-type': 'text/plain',
|
| 31 |
+
})
|
| 32 |
+
expect(result.body).toBe('hello world')
|
| 33 |
+
})
|
| 34 |
+
|
| 35 |
+
it('serializes a JSON response', async () => {
|
| 36 |
+
const response = new Response(JSON.stringify({ users: ['John'] }), {
|
| 37 |
+
headers: {
|
| 38 |
+
'Content-Type': 'application/json',
|
| 39 |
+
},
|
| 40 |
+
})
|
| 41 |
+
const result = await serializeResponse(response)
|
| 42 |
+
|
| 43 |
+
expect(result.headers).toEqual({
|
| 44 |
+
'content-type': 'application/json',
|
| 45 |
+
})
|
| 46 |
+
expect(result.body).toBe(JSON.stringify({ users: ['John'] }))
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
it('serializes a ArrayBuffer response', async () => {
|
| 50 |
+
const data = encodeBuffer('hello world')
|
| 51 |
+
const response = new Response(data)
|
| 52 |
+
const result = await serializeResponse(response)
|
| 53 |
+
|
| 54 |
+
expect(result.body).toBe('hello world')
|
| 55 |
+
})
|
| 56 |
+
|
| 57 |
+
it('serializes a Blob response', async () => {
|
| 58 |
+
const response = new Response(new Blob(['hello world']))
|
| 59 |
+
const result = await serializeResponse(response)
|
| 60 |
+
|
| 61 |
+
expect(result.body).toBe('hello world')
|
| 62 |
+
})
|
| 63 |
+
|
| 64 |
+
it('serializes a FormData response', async () => {
|
| 65 |
+
const data = new FormData()
|
| 66 |
+
data.set('firstName', 'Alice')
|
| 67 |
+
data.set('age', '32')
|
| 68 |
+
const response = new Response(data)
|
| 69 |
+
const result = await serializeResponse(response)
|
| 70 |
+
|
| 71 |
+
expect(result.body).toContain(
|
| 72 |
+
`Content-Disposition: form-data; name="firstName"\r\n\r\nAlice`,
|
| 73 |
+
)
|
| 74 |
+
expect(result.body).toContain(
|
| 75 |
+
`Content-Disposition: form-data; name="age"\r\n\r\n32`,
|
| 76 |
+
)
|
| 77 |
+
})
|
node_modules/msw/src/core/utils/logging/serializeResponse.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import statuses from '../../../shims/statuses'
|
| 2 |
+
|
| 3 |
+
const { message } = statuses
|
| 4 |
+
|
| 5 |
+
export interface SerializedResponse {
|
| 6 |
+
status: number
|
| 7 |
+
statusText: string
|
| 8 |
+
headers: Record<string, any>
|
| 9 |
+
body: string
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
export async function serializeResponse(
|
| 13 |
+
response: Response,
|
| 14 |
+
): Promise<SerializedResponse> {
|
| 15 |
+
const responseClone = response.clone()
|
| 16 |
+
const responseText = await responseClone.text()
|
| 17 |
+
|
| 18 |
+
// Normalize the response status and status text when logging
|
| 19 |
+
// since the default Response instance doesn't infer status texts
|
| 20 |
+
// from status codes. This has no effect on the actual response instance.
|
| 21 |
+
const responseStatus = responseClone.status || 200
|
| 22 |
+
const responseStatusText =
|
| 23 |
+
responseClone.statusText || message[responseStatus] || 'OK'
|
| 24 |
+
|
| 25 |
+
return {
|
| 26 |
+
status: responseStatus,
|
| 27 |
+
statusText: responseStatusText,
|
| 28 |
+
headers: Object.fromEntries(responseClone.headers.entries()),
|
| 29 |
+
body: responseText,
|
| 30 |
+
}
|
| 31 |
+
}
|
node_modules/msw/src/core/utils/matching/matchRequestUrl.test.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @vitest-environment jsdom
|
| 2 |
+
import { coercePath, matchRequestUrl } from './matchRequestUrl'
|
| 3 |
+
|
| 4 |
+
describe('matchRequestUrl', () => {
|
| 5 |
+
test('returns true when matches against an exact URL', () => {
|
| 6 |
+
expect(
|
| 7 |
+
matchRequestUrl(
|
| 8 |
+
new URL('https://test.mswjs.io'),
|
| 9 |
+
'https://test.mswjs.io',
|
| 10 |
+
),
|
| 11 |
+
).toEqual({
|
| 12 |
+
matches: true,
|
| 13 |
+
params: {},
|
| 14 |
+
})
|
| 15 |
+
})
|
| 16 |
+
|
| 17 |
+
test('returns true when matched against a wildcard', () => {
|
| 18 |
+
expect(matchRequestUrl(new URL('https://test.mswjs.io'), '*')).toEqual({
|
| 19 |
+
matches: true,
|
| 20 |
+
params: {
|
| 21 |
+
'0': 'https://test.mswjs.io/',
|
| 22 |
+
},
|
| 23 |
+
})
|
| 24 |
+
})
|
| 25 |
+
|
| 26 |
+
test('returns true when matched against a RegExp', () => {
|
| 27 |
+
expect(
|
| 28 |
+
matchRequestUrl(new URL('https://test.mswjs.io'), /test\.mswjs\.io/),
|
| 29 |
+
).toEqual({
|
| 30 |
+
matches: true,
|
| 31 |
+
params: {},
|
| 32 |
+
})
|
| 33 |
+
})
|
| 34 |
+
|
| 35 |
+
test('returns path parameters when matched', () => {
|
| 36 |
+
expect(
|
| 37 |
+
matchRequestUrl(
|
| 38 |
+
new URL('https://test.mswjs.io/user/abc-123'),
|
| 39 |
+
'https://test.mswjs.io/user/:userId',
|
| 40 |
+
),
|
| 41 |
+
).toEqual({
|
| 42 |
+
matches: true,
|
| 43 |
+
params: {
|
| 44 |
+
userId: 'abc-123',
|
| 45 |
+
},
|
| 46 |
+
})
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
test('decodes path parameters', () => {
|
| 50 |
+
const url = 'http://example.com:5001/example'
|
| 51 |
+
|
| 52 |
+
expect(
|
| 53 |
+
matchRequestUrl(
|
| 54 |
+
new URL(`https://test.mswjs.io/reflect-url/${encodeURIComponent(url)}`),
|
| 55 |
+
'https://test.mswjs.io/reflect-url/:url',
|
| 56 |
+
),
|
| 57 |
+
).toEqual({
|
| 58 |
+
matches: true,
|
| 59 |
+
params: {
|
| 60 |
+
url,
|
| 61 |
+
},
|
| 62 |
+
})
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
test('returns false when does not match against the request URL', () => {
|
| 66 |
+
expect(
|
| 67 |
+
matchRequestUrl(new URL('https://test.mswjs.io'), 'https://google.com'),
|
| 68 |
+
).toEqual({
|
| 69 |
+
matches: false,
|
| 70 |
+
params: {},
|
| 71 |
+
})
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
test('returns true when matching optional path parameters', () => {
|
| 75 |
+
expect(
|
| 76 |
+
matchRequestUrl(
|
| 77 |
+
new URL('https://test.mswjs.io/user/123'),
|
| 78 |
+
'https://test.mswjs.io/user/:userId?',
|
| 79 |
+
),
|
| 80 |
+
).toEqual({
|
| 81 |
+
matches: true,
|
| 82 |
+
params: {
|
| 83 |
+
userId: '123',
|
| 84 |
+
},
|
| 85 |
+
})
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
test('returns true when matching URLs with wildcard ports', () => {
|
| 89 |
+
expect
|
| 90 |
+
.soft(
|
| 91 |
+
matchRequestUrl(new URL('http://localhost:3000'), 'http://localhost:*'),
|
| 92 |
+
)
|
| 93 |
+
.toEqual({
|
| 94 |
+
matches: true,
|
| 95 |
+
params: {
|
| 96 |
+
'0': '3000/',
|
| 97 |
+
},
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
expect
|
| 101 |
+
.soft(
|
| 102 |
+
matchRequestUrl(
|
| 103 |
+
new URL('http://localhost:3000'),
|
| 104 |
+
'http://localhost:*/',
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
.toEqual({
|
| 108 |
+
matches: true,
|
| 109 |
+
params: {
|
| 110 |
+
'0': '3000',
|
| 111 |
+
},
|
| 112 |
+
})
|
| 113 |
+
})
|
| 114 |
+
|
| 115 |
+
test('returns true when matching URLs with wildcard ports and pathnames', () => {
|
| 116 |
+
expect(
|
| 117 |
+
matchRequestUrl(
|
| 118 |
+
new URL('http://localhost:3000/resource'),
|
| 119 |
+
'http://localhost:*/resource',
|
| 120 |
+
),
|
| 121 |
+
).toEqual({
|
| 122 |
+
matches: true,
|
| 123 |
+
params: {
|
| 124 |
+
'0': '3000',
|
| 125 |
+
},
|
| 126 |
+
})
|
| 127 |
+
})
|
| 128 |
+
|
| 129 |
+
test('matches wildcard ports with other wildcard parameters', () => {
|
| 130 |
+
expect(
|
| 131 |
+
matchRequestUrl(
|
| 132 |
+
new URL('http://subdomain.localhost:3000/user/settings'),
|
| 133 |
+
'http://*.localhost:*/user/*',
|
| 134 |
+
),
|
| 135 |
+
).toEqual({
|
| 136 |
+
matches: true,
|
| 137 |
+
params: {
|
| 138 |
+
'0': 'subdomain',
|
| 139 |
+
'1': '3000',
|
| 140 |
+
'2': 'settings',
|
| 141 |
+
},
|
| 142 |
+
})
|
| 143 |
+
})
|
| 144 |
+
|
| 145 |
+
test('matches wildcard ports that also match a part of the pathname', () => {
|
| 146 |
+
expect(
|
| 147 |
+
matchRequestUrl(
|
| 148 |
+
new URL('http://localhost:3000/user/settings'),
|
| 149 |
+
'http://localhost:*/settings',
|
| 150 |
+
),
|
| 151 |
+
).toEqual({
|
| 152 |
+
matches: true,
|
| 153 |
+
params: {
|
| 154 |
+
'0': '3000/user',
|
| 155 |
+
},
|
| 156 |
+
})
|
| 157 |
+
})
|
| 158 |
+
|
| 159 |
+
test('returns true for matching WebSocket URL', () => {
|
| 160 |
+
expect(
|
| 161 |
+
matchRequestUrl(new URL('ws://test.mswjs.io'), 'ws://test.mswjs.io'),
|
| 162 |
+
).toEqual({
|
| 163 |
+
matches: true,
|
| 164 |
+
params: {},
|
| 165 |
+
})
|
| 166 |
+
expect(
|
| 167 |
+
matchRequestUrl(new URL('wss://test.mswjs.io'), 'wss://test.mswjs.io'),
|
| 168 |
+
).toEqual({
|
| 169 |
+
matches: true,
|
| 170 |
+
params: {},
|
| 171 |
+
})
|
| 172 |
+
})
|
| 173 |
+
|
| 174 |
+
test('returns false for non-matching WebSocket URL', () => {
|
| 175 |
+
expect(
|
| 176 |
+
matchRequestUrl(new URL('ws://test.mswjs.io'), 'ws://foo.mswjs.io'),
|
| 177 |
+
).toEqual({
|
| 178 |
+
matches: false,
|
| 179 |
+
params: {},
|
| 180 |
+
})
|
| 181 |
+
expect(
|
| 182 |
+
matchRequestUrl(new URL('wss://test.mswjs.io'), 'wss://completely.diff'),
|
| 183 |
+
).toEqual({
|
| 184 |
+
matches: false,
|
| 185 |
+
params: {},
|
| 186 |
+
})
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
test('returns path parameters when matched a WebSocket URL', () => {
|
| 190 |
+
expect(
|
| 191 |
+
matchRequestUrl(
|
| 192 |
+
new URL('wss://test.mswjs.io'),
|
| 193 |
+
'wss://:service.mswjs.io',
|
| 194 |
+
),
|
| 195 |
+
).toEqual({
|
| 196 |
+
matches: true,
|
| 197 |
+
params: {
|
| 198 |
+
service: 'test',
|
| 199 |
+
},
|
| 200 |
+
})
|
| 201 |
+
})
|
| 202 |
+
|
| 203 |
+
test('returns true for matching WebSocket URLs with wildcard ports', () => {
|
| 204 |
+
expect(
|
| 205 |
+
matchRequestUrl(new URL('ws://localhost:3000'), 'ws://localhost:*'),
|
| 206 |
+
).toEqual({
|
| 207 |
+
matches: true,
|
| 208 |
+
params: {
|
| 209 |
+
'0': '3000/',
|
| 210 |
+
},
|
| 211 |
+
})
|
| 212 |
+
})
|
| 213 |
+
})
|
| 214 |
+
|
| 215 |
+
describe('coercePath', () => {
|
| 216 |
+
test('escapes the colon in protocol', () => {
|
| 217 |
+
expect(coercePath('https://example.com')).toEqual('https\\://example.com')
|
| 218 |
+
expect(coercePath('https://example.com/:userId')).toEqual(
|
| 219 |
+
'https\\://example.com/:userId',
|
| 220 |
+
)
|
| 221 |
+
expect(coercePath('http://localhost:3000')).toEqual(
|
| 222 |
+
'http\\://localhost\\:3000',
|
| 223 |
+
)
|
| 224 |
+
})
|
| 225 |
+
|
| 226 |
+
test('escapes the colon before the port number', () => {
|
| 227 |
+
expect(coercePath('localhost:8080')).toEqual('localhost\\:8080')
|
| 228 |
+
expect(coercePath('http://127.0.0.1:8080')).toEqual(
|
| 229 |
+
'http\\://127.0.0.1\\:8080',
|
| 230 |
+
)
|
| 231 |
+
expect(coercePath('https://example.com:1234')).toEqual(
|
| 232 |
+
'https\\://example.com\\:1234',
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
expect(coercePath('localhost:8080/:5678')).toEqual('localhost\\:8080/:5678')
|
| 236 |
+
expect(coercePath('https://example.com:8080/:5678')).toEqual(
|
| 237 |
+
'https\\://example.com\\:8080/:5678',
|
| 238 |
+
)
|
| 239 |
+
expect(coercePath('http://localhost:*')).toEqual(
|
| 240 |
+
'http\\://localhost\\:(.*)',
|
| 241 |
+
)
|
| 242 |
+
expect(coercePath('ws://localhost:*')).toEqual('ws\\://localhost\\:(.*)')
|
| 243 |
+
})
|
| 244 |
+
|
| 245 |
+
test('replaces wildcard with an unnnamed capturing group', () => {
|
| 246 |
+
expect(coercePath('*')).toEqual('(.*)')
|
| 247 |
+
expect(coercePath('**')).toEqual('(.*)')
|
| 248 |
+
expect(coercePath('/us*')).toEqual('/us(.*)')
|
| 249 |
+
expect(coercePath('/user/*')).toEqual('/user/(.*)')
|
| 250 |
+
expect(coercePath('https://example.com/user/*')).toEqual(
|
| 251 |
+
'https\\://example.com/user/(.*)',
|
| 252 |
+
)
|
| 253 |
+
expect(coercePath('https://example.com/us*')).toEqual(
|
| 254 |
+
'https\\://example.com/us(.*)',
|
| 255 |
+
)
|
| 256 |
+
})
|
| 257 |
+
|
| 258 |
+
test('preserves path parameter modifiers', () => {
|
| 259 |
+
expect(coercePath(':name*')).toEqual(':name*')
|
| 260 |
+
expect(coercePath('/foo/:name*')).toEqual('/foo/:name*')
|
| 261 |
+
expect(coercePath('/foo/**:name*')).toEqual('/foo/(.*):name*')
|
| 262 |
+
expect(coercePath('**/foo/*/:name*')).toEqual('(.*)/foo/(.*)/:name*')
|
| 263 |
+
expect(coercePath('/foo/:first/bar/:second*/*')).toEqual(
|
| 264 |
+
'/foo/:first/bar/:second*/(.*)',
|
| 265 |
+
)
|
| 266 |
+
})
|
| 267 |
+
})
|