msw 2.7.3 → 2.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,29 +1,17 @@
1
- > **MSW 2.0 is finally here! 🎉** Read the [Release notes](https://github.com/mswjs/msw/releases/tag/v2.0.0) and please follow the [**Migration guidelines**](https://mswjs.io/docs/migrations/1.x-to-2.x) to upgrade. If you're having any questions while upgrading, please reach out in our [Discord server](https://kettanaito.com/discord).
2
- >
3
- > We've also recorded the most comprehensive introduction to MSW ever. Learn how to mock APIs like a pro in our official video course:
4
-
5
- <a href="https://egghead.io/courses/mock-rest-and-graphql-apis-with-mock-service-worker-8d471ece?af=8mci9b" target="_blank">
6
- <img src="media/egghead-banner.png" alt="Mock REST and GraphQL APIs with Mock Service Worker" />
7
- </a>
8
-
9
- <br />
10
1
  <br />
11
2
 
12
3
  <p align="center">
13
- <img src="media/msw-logo.svg" width="100" alt="Mock Service Worker logo" />
4
+ <img src="media/msw-logo.svg" width="100" alt="The Mock Service Worker logo" />
14
5
  </p>
15
6
 
16
7
  <h1 align="center">Mock Service Worker</h1>
17
8
  <p align="center">Industry standard API mocking for JavaScript.</p>
18
9
 
19
10
  <p align="center">
20
- <a href="https://www.npmjs.com/package/msw" target="_blank"><img src="https://img.shields.io/npm/v/msw.svg?style=for-the-badge&label=Latest&color=black" alt="Package version" /></a>
21
- <a href="https://www.npmjs.com/package/msw" target="_blank"><img src="https://img.shields.io/npm/dm/msw?style=for-the-badge&color=black" alt="Downloads per month" /></a>
22
- <a href="https://kettanaito.com/discord" target="_blank"><img src="https://img.shields.io/badge/chat-online-green?style=for-the-badge&color=black" alt="Discord server" /></a>
11
+ <a href="https://kettanaito.com/discord" target="_blank">Join our Discord server</a>
23
12
  </p>
24
13
 
25
14
  <br />
26
-
27
15
  <br />
28
16
 
29
17
  ## Features
@@ -36,11 +24,11 @@
36
24
 
37
25
  > "_I found MSW and was thrilled that not only could I still see the mocked responses in my DevTools, but that the mocks didn't have to be written in a Service Worker and could instead live alongside the rest of my app. This made it silly easy to adopt. The fact that I can use it for testing as well makes MSW a huge productivity booster._"
38
26
  >
39
- > [Kent C. Dodds](https://twitter.com/kentcdodds)
27
+ > [Kent C. Dodds](https://twitter.com/kentcdodds)
40
28
 
41
29
  ## Documentation
42
30
 
43
- This README will give you a brief overview on the library but there's no better place to start with Mock Service Worker than its official documentation.
31
+ This README will give you a brief overview of the library, but there's no better place to start with Mock Service Worker than its official documentation.
44
32
 
45
33
  - [Documentation](https://mswjs.io/docs)
46
34
  - [**Getting started**](https://mswjs.io/docs/getting-started)
@@ -50,6 +38,13 @@ This README will give you a brief overview on the library but there's no better
50
38
 
51
39
  - See the list of [**Usage examples**](https://github.com/mswjs/examples)
52
40
 
41
+ ## Courses
42
+
43
+ We've partnered with Egghead to bring you quality paid materials to learn the best practices of API mocking on the web. Please give them a shot! The royalties earned from them help sustain the project's development. Thank you.
44
+
45
+ - 🚀 [**Mocking REST and GraphQL APIs with Mock Service Worker**](https://egghead.io/courses/mock-rest-and-graphql-apis-with-mock-service-worker-8d471ece?af=8mci9b)
46
+ - 🔌 [Mocking (and testing) WebSocket APIs with Mock Service Worker](https://egghead.io/courses/mocking-websocket-apis-with-mock-service-worker-9933b7f5)
47
+
53
48
  ## Browser
54
49
 
55
50
  - [Learn more about using MSW in a browser](https://mswjs.io/docs/integrations/browser)
@@ -68,12 +63,11 @@ In-browser usage is what sets Mock Service Worker apart from other tools. Utiliz
68
63
  - This library intercepts requests on the network level, which means _after_ they have been performed and "left" your application. As a result, the entirety of your code runs, giving you more confidence when mocking;
69
64
  - Imagine your application as a box. Every API mocking library out there opens your box and removes the part that does the request, placing a blackbox in its stead. Mock Service Worker leaves your box intact, 1-1 as it is in production. Instead, MSW lives in a separate box next to yours;
70
65
  - No more stubbing of `fetch`, `axios`, `react-query`, you-name-it;
71
- - You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters of bloated configurations.
66
+ - You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters or bloated configurations.
72
67
 
73
68
  ### Usage example
74
69
 
75
70
  ```js
76
- // src/mocks.js
77
71
  // 1. Import the library.
78
72
  import { http, HttpResponse } from 'msw'
79
73
  import { setupWorker } from 'msw/browser'
@@ -93,7 +87,7 @@ const worker = setupWorker(
93
87
  }),
94
88
  )
95
89
 
96
- // 3. Start request interception by starting the Service Worker.
90
+ // 3. Start mocking by starting the Service Worker.
97
91
  await worker.start()
98
92
  ```
99
93
 
@@ -101,7 +95,7 @@ Performing a `GET https://github.com/octocat` request in your application will r
101
95
 
102
96
  ![Chrome DevTools Network screenshot with the request mocked](https://github.com/mswjs/msw/blob/main/media/msw-quick-look-network.png?raw=true)
103
97
 
104
- > **Tip:** Did you know that although Service Worker runs in a separate thread, your mock definition executes entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need.
98
+ > **Tip:** Did you know that although Service Worker runs in a separate thread, your request handlers execute entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need.
105
99
 
106
100
  ## Node.js
107
101
 
@@ -119,77 +113,48 @@ There's no such thing as Service Workers in Node.js. Instead, MSW implements a [
119
113
 
120
114
  ### Usage example
121
115
 
122
- Take a look at the example of an integration test in Vitest that uses [React Testing Library](https://github.com/testing-library/react-testing-library) and Mock Service Worker:
116
+ Here's an example of using Mock Service Worker while developing your Express server:
123
117
 
124
118
  ```js
125
- // test/Dashboard.test.js
126
-
127
- import React from 'react'
119
+ import express from 'express'
128
120
  import { http, HttpResponse } from 'msw'
129
121
  import { setupServer } from 'msw/node'
130
- import { render, screen, waitFor } from '@testing-library/react'
131
- import Dashboard from '../src/components/Dashboard'
132
-
133
- const server = setupServer(
134
- // Describe network behavior with request handlers.
135
- // Tip: move the handlers into their own module and
136
- // import it across your browser and Node.js setups!
137
- http.get('/posts', ({ request, params, cookies }) => {
138
- return HttpResponse.json([
139
- {
140
- id: 'f8dd058f-9006-4174-8d49-e3086bc39c21',
141
- title: `Avoid Nesting When You're Testing`,
142
- },
143
- {
144
- id: '8ac96078-6434-4959-80ed-cc834e7fef61',
145
- title: `How I Built A Modern Website In 2021`,
146
- },
147
- ])
148
- }),
149
- )
150
-
151
- // Enable request interception.
152
- beforeAll(() => server.listen())
153
-
154
- // Reset handlers so that each test could alter them
155
- // without affecting other, unrelated tests.
156
- afterEach(() => server.resetHandlers())
157
-
158
- // Don't forget to clean up afterwards.
159
- afterAll(() => server.close())
160
122
 
161
- it('displays the list of recent posts', async () => {
162
- render(<Dashboard />)
163
-
164
- // 🕗 Wait for the posts request to be finished.
165
- await waitFor(() => {
166
- expect(
167
- screen.getByLabelText('Fetching latest posts...'),
168
- ).not.toBeInTheDocument()
169
- })
170
-
171
- // Assert that the correct posts have loaded.
172
- expect(
173
- screen.getByRole('link', { name: /Avoid Nesting When You're Testing/ }),
174
- ).toBeVisible()
123
+ const app = express()
124
+ const server = setupServer()
125
+
126
+ app.get(
127
+ '/checkout/session',
128
+ server.boundary((req, res) => {
129
+ // Describe the network for this Express route.
130
+ server.use(
131
+ http.get(
132
+ 'https://api.stripe.com/v1/checkout/sessions/:id',
133
+ ({ params }) => {
134
+ return HttpResponse.json({
135
+ id: params.id,
136
+ mode: 'payment',
137
+ status: 'open',
138
+ })
139
+ },
140
+ ),
141
+ )
175
142
 
176
- expect(
177
- screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
178
- ).toBeVisible()
179
- })
143
+ // Continue with processing the checkout session.
144
+ handleSession(req, res)
145
+ }),
146
+ )
180
147
  ```
181
148
 
182
- > Don't get overwhelmed! We've prepared a step-by-step [**Getting started**](https://mswjs.io/docs/getting-started) tutorial that you can follow to learn how to integrate Mock Service Worker into your project.
183
-
184
- Despite the API being called `setupServer`, there are no actual servers involved! The name was chosen for familiarity, and the API was designed to resemble operating with an actual server.
149
+ > This example showcases [`server.boundary()`](https://mswjs.io/docs/api/setup-server/boundary) to scope request interception to a particular closure, which is extremely handy!
185
150
 
186
151
  ## Sponsors
187
152
 
188
- Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, and countless others. Despite that, this library remains a hobby project maintained in spare time and has no opportunity to financially support even a single full-time contributor.
153
+ Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, Netflix, and countless others. Despite that, it remains a hobby project maintained in a spare time and has no opportunity to financially support even a single full-time contributor.
189
154
 
190
155
  **You can change that!** Consider [sponsoring the effort](https://github.com/sponsors/mswjs) behind one of the most innovative approaches around API mocking. Raise a topic of open source sponsorships with your boss and colleagues. Let's build sustainable open source together!
191
156
 
192
- ### Golden Sponsors
157
+ ### Golden sponsors
193
158
 
194
159
  > Become our _golden sponsor_ and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.
195
160
  >
@@ -232,7 +197,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
232
197
  </tr>
233
198
  </table>
234
199
 
235
- ### Silver Sponsors
200
+ ### Silver sponsors
236
201
 
237
202
  > Become our _silver sponsor_ and get your profile image and link featured right here.
238
203
  >
@@ -260,7 +225,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
260
225
  </tr>
261
226
  </table>
262
227
 
263
- ### Bronze Sponsors
228
+ ### Bronze sponsors
264
229
 
265
230
  > Become our _bronze sponsor_ and get your profile image and link featured in this section.
266
231
  >
@@ -288,7 +253,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
288
253
  </tr>
289
254
  </table>
290
255
 
291
- ## Awards & Mentions
256
+ ## Awards & mentions
292
257
 
293
258
  We've been extremely humbled to receive awards and mentions from the community for all the innovation and reach Mock Service Worker brings to the JavaScript ecosystem.
294
259
 
@@ -61,6 +61,7 @@ interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {
61
61
  type GraphQLResponseBody<BodyType extends DefaultBodyType> = {
62
62
  data?: BodyType | null;
63
63
  errors?: readonly Partial<GraphQLError>[] | null;
64
+ extensions?: Record<string, any>;
64
65
  } | null | undefined;
65
66
  declare function isDocumentNode(value: DocumentNode | any): value is DocumentNode;
66
67
  declare class GraphQLHandler extends RequestHandler<GraphQLHandlerInfo, GraphQLRequestParsedResult, GraphQLResolverExtras<any>> {
@@ -61,6 +61,7 @@ interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {
61
61
  type GraphQLResponseBody<BodyType extends DefaultBodyType> = {
62
62
  data?: BodyType | null;
63
63
  errors?: readonly Partial<GraphQLError>[] | null;
64
+ extensions?: Record<string, any>;
64
65
  } | null | undefined;
65
66
  declare function isDocumentNode(value: DocumentNode | any): value is DocumentNode;
66
67
  declare class GraphQLHandler extends RequestHandler<GraphQLHandlerInfo, GraphQLRequestParsedResult, GraphQLResolverExtras<any>> {
@@ -1,6 +1,6 @@
1
1
  import { DocumentNode } from 'graphql';
2
2
  import { c as RequestHandlerOptions, a as ResponseResolver } from './HttpResponse-BRDnWbjc.mjs';
3
- import { a as GraphQLQuery, b as GraphQLVariables, e as GraphQLHandlerNameSelector, G as GraphQLHandler, f as GraphQLResolverExtras, g as GraphQLResponseBody } from './GraphQLHandler-D4_CxZQj.mjs';
3
+ import { a as GraphQLQuery, b as GraphQLVariables, e as GraphQLHandlerNameSelector, G as GraphQLHandler, f as GraphQLResolverExtras, g as GraphQLResponseBody } from './GraphQLHandler-BNMGdWQe.mjs';
4
4
  import { Path } from './utils/matching/matchRequestUrl.mjs';
5
5
  import '@mswjs/interceptors';
6
6
  import './utils/internal/isIterable.mjs';
@@ -1,6 +1,6 @@
1
1
  import { DocumentNode } from 'graphql';
2
2
  import { c as RequestHandlerOptions, a as ResponseResolver } from './HttpResponse-Cy7ytzUn.js';
3
- import { a as GraphQLQuery, b as GraphQLVariables, e as GraphQLHandlerNameSelector, G as GraphQLHandler, f as GraphQLResolverExtras, g as GraphQLResponseBody } from './GraphQLHandler-Pox7fIFM.js';
3
+ import { a as GraphQLQuery, b as GraphQLVariables, e as GraphQLHandlerNameSelector, G as GraphQLHandler, f as GraphQLResolverExtras, g as GraphQLResponseBody } from './GraphQLHandler-D1CSV926.js';
4
4
  import { Path } from './utils/matching/matchRequestUrl.js';
5
5
  import '@mswjs/interceptors';
6
6
  import './utils/internal/isIterable.js';
@@ -1,7 +1,7 @@
1
1
  import 'graphql';
2
2
  import '../HttpResponse-BRDnWbjc.mjs';
3
3
  import '../utils/matching/matchRequestUrl.mjs';
4
- export { E as ExpectedOperationTypeNode, G as GraphQLHandler, l as GraphQLHandlerInfo, e as GraphQLHandlerNameSelector, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, m as GraphQLRequestParsedResult, f as GraphQLResolverExtras, g as GraphQLResponseBody, b as GraphQLVariables, n as isDocumentNode } from '../GraphQLHandler-D4_CxZQj.mjs';
4
+ export { E as ExpectedOperationTypeNode, G as GraphQLHandler, l as GraphQLHandlerInfo, e as GraphQLHandlerNameSelector, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, m as GraphQLRequestParsedResult, f as GraphQLResolverExtras, g as GraphQLResponseBody, b as GraphQLVariables, n as isDocumentNode } from '../GraphQLHandler-BNMGdWQe.mjs';
5
5
  import '@mswjs/interceptors';
6
6
  import '../utils/internal/isIterable.mjs';
7
7
  import '../typeUtils.mjs';
@@ -1,7 +1,7 @@
1
1
  import 'graphql';
2
2
  import '../HttpResponse-Cy7ytzUn.js';
3
3
  import '../utils/matching/matchRequestUrl.js';
4
- export { E as ExpectedOperationTypeNode, G as GraphQLHandler, l as GraphQLHandlerInfo, e as GraphQLHandlerNameSelector, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, m as GraphQLRequestParsedResult, f as GraphQLResolverExtras, g as GraphQLResponseBody, b as GraphQLVariables, n as isDocumentNode } from '../GraphQLHandler-Pox7fIFM.js';
4
+ export { E as ExpectedOperationTypeNode, G as GraphQLHandler, l as GraphQLHandlerInfo, e as GraphQLHandlerNameSelector, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, m as GraphQLRequestParsedResult, f as GraphQLResolverExtras, g as GraphQLResponseBody, b as GraphQLVariables, n as isDocumentNode } from '../GraphQLHandler-D1CSV926.js';
5
5
  import '@mswjs/interceptors';
6
6
  import '../utils/internal/isIterable.js';
7
7
  import '../typeUtils.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import type { DocumentNode, GraphQLError, OperationTypeNode } from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\n\nexport type ExpectedOperationTypeNode = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any>\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: ExpectedOperationTypeNode\n operationName: GraphQLHandlerNameSelector\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n }\n | null\n | undefined\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n constructor(\n operationType: ExpectedOperationTypeNode,\n operationName: GraphQLHandlerNameSelector,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n let resolvedOperationName = operationName\n\n if (isDocumentNode(operationName)) {\n const parsedNode = parseDocumentNode(operationName)\n\n if (parsedNode.operationType !== operationType) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"${operationType}\", but got \"${parsedNode.operationType}\").`,\n )\n }\n\n if (!parsedNode.operationName) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`,\n )\n }\n\n resolvedOperationName = parsedNode.operationName\n }\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: resolvedOperationName,\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n // eslint-disable-next-line no-console\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return { match, cookies }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return { match, cookies }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n const hasMatchingOperationName =\n this.info.operationName instanceof RegExp\n ? this.info.operationName.test(args.parsedResult.operationName || '')\n : args.parsedResult.operationName === this.info.operationName\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n // eslint-disable-next-line no-console\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n // eslint-disable-next-line no-console\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,4BAMO;AACP,0BAA6B;AAC7B,gCAAmC;AACnC,8BAAiC;AACjC,+BAAkC;AAClC,6BAA6C;AAC7C,iCAKO;AACP,yBAA4B;AAC5B,sBAAyB;AACzB,+BAAqC;AAyD9B,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEO,MAAM,uBAAuB,qCAIlC;AAAA,EACQ;AAAA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,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAGhD,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AAEvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import type { DocumentNode, GraphQLError, OperationTypeNode } from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\n\nexport type ExpectedOperationTypeNode = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any>\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: ExpectedOperationTypeNode\n operationName: GraphQLHandlerNameSelector\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n constructor(\n operationType: ExpectedOperationTypeNode,\n operationName: GraphQLHandlerNameSelector,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n let resolvedOperationName = operationName\n\n if (isDocumentNode(operationName)) {\n const parsedNode = parseDocumentNode(operationName)\n\n if (parsedNode.operationType !== operationType) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"${operationType}\", but got \"${parsedNode.operationType}\").`,\n )\n }\n\n if (!parsedNode.operationName) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`,\n )\n }\n\n resolvedOperationName = parsedNode.operationName\n }\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: resolvedOperationName,\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n // eslint-disable-next-line no-console\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return { match, cookies }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return { match, cookies }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n const hasMatchingOperationName =\n this.info.operationName instanceof RegExp\n ? this.info.operationName.test(args.parsedResult.operationName || '')\n : args.parsedResult.operationName === this.info.operationName\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n // eslint-disable-next-line no-console\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n // eslint-disable-next-line no-console\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,4BAMO;AACP,0BAA6B;AAC7B,gCAAmC;AACnC,8BAAiC;AACjC,+BAAkC;AAClC,6BAA6C;AAC7C,iCAKO;AACP,yBAA4B;AAC5B,sBAAyB;AACzB,+BAAqC;AA0D9B,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A,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,UAAM,0CAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,UAAM,4CAAkB,KAAK,QAAQ;AAC5D,UAAM,kBAAc,8CAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAGhD,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AAEvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import type { DocumentNode, GraphQLError, OperationTypeNode } from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\n\nexport type ExpectedOperationTypeNode = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any>\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: ExpectedOperationTypeNode\n operationName: GraphQLHandlerNameSelector\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n }\n | null\n | undefined\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n constructor(\n operationType: ExpectedOperationTypeNode,\n operationName: GraphQLHandlerNameSelector,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n let resolvedOperationName = operationName\n\n if (isDocumentNode(operationName)) {\n const parsedNode = parseDocumentNode(operationName)\n\n if (parsedNode.operationType !== operationType) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"${operationType}\", but got \"${parsedNode.operationType}\").`,\n )\n }\n\n if (!parsedNode.operationName) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`,\n )\n }\n\n resolvedOperationName = parsedNode.operationName\n }\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: resolvedOperationName,\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n // eslint-disable-next-line no-console\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return { match, cookies }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return { match, cookies }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n const hasMatchingOperationName =\n this.info.operationName instanceof RegExp\n ? this.info.operationName.test(args.parsedResult.operationName || '')\n : args.parsedResult.operationName === this.info.operationName\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n // eslint-disable-next-line no-console\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n // eslint-disable-next-line no-console\n console.groupEnd()\n }\n}\n"],"mappings":"AACA;AAAA,EAEE;AAAA,OAIK;AACP,SAAS,oBA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,MAG1B;AACD,WAAO;AAAA,MACL,OAAO,KAAK,aAAa,SAAS;AAAA,MAClC,eAAe,KAAK,aAAa,iBAAiB;AAAA,MAClD,WAAW,KAAK,aAAa,aAAa,CAAC;AAAA,MAC3C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,MAAM,iBAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,MAAM,kBAAkB,KAAK,QAAQ;AAC5D,UAAM,cAAc,mBAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAGhD,YAAQ;AAAA,MACN,SAAS;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AAEvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import type { DocumentNode, GraphQLError, OperationTypeNode } from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\n\nexport type ExpectedOperationTypeNode = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any>\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: ExpectedOperationTypeNode\n operationName: GraphQLHandlerNameSelector\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n constructor(\n operationType: ExpectedOperationTypeNode,\n operationName: GraphQLHandlerNameSelector,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n let resolvedOperationName = operationName\n\n if (isDocumentNode(operationName)) {\n const parsedNode = parseDocumentNode(operationName)\n\n if (parsedNode.operationType !== operationType) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"${operationType}\", but got \"${parsedNode.operationType}\").`,\n )\n }\n\n if (!parsedNode.operationName) {\n throw new Error(\n `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`,\n )\n }\n\n resolvedOperationName = parsedNode.operationName\n }\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: resolvedOperationName,\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n // eslint-disable-next-line no-console\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return { match, cookies }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return { match, cookies }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider naming this operation or using \"graphql.operation()\" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n const hasMatchingOperationName =\n this.info.operationName instanceof RegExp\n ? this.info.operationName.test(args.parsedResult.operationName || '')\n : args.parsedResult.operationName === this.info.operationName\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n // eslint-disable-next-line no-console\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n // eslint-disable-next-line no-console\n console.groupEnd()\n }\n}\n"],"mappings":"AACA;AAAA,EAEE;AAAA,OAIK;AACP,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAgB,uBAA6B;AAC7C;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AA0D9B,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEO,MAAM,uBAAuB,eAIlC;AAAA,EACQ;AAAA,EAER,OAAO,qBAAqB,oBAAI,QAG9B;AAAA,EAEF,YACE,eACA,eACA,UACA,UACA,SACA;AACA,QAAI,wBAAwB;AAE5B,QAAI,eAAe,aAAa,GAAG;AACjC,YAAM,aAAa,kBAAkB,aAAa;AAElD,UAAI,WAAW,kBAAkB,eAAe;AAC9C,cAAM,IAAI;AAAA,UACR,2GAA2G,aAAa,eAAe,WAAW,aAAa;AAAA,QACjK;AAAA,MACF;AAEA,UAAI,CAAC,WAAW,eAAe;AAC7B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,8BAAwB,WAAW;AAAA,IACrC;AAEA,UAAM,SACJ,kBAAkB,QACd,GAAG,aAAa,aAAa,SAAS,SAAS,CAAC,MAChD,GAAG,aAAa,IAAI,qBAAqB,aAAa,SAAS,SAAS,CAAC;AAE/E,UAAM;AAAA,MACJ,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA,eAAe;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAED,SAAK,WAAW;AAAA,EAClB;AAAA;A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,KAAK,KAAK,yBAAyB,SAC/B,KAAK,KAAK,cAAc,KAAK,KAAK,aAAa,iBAAiB,EAAE,IAClE,KAAK,aAAa,kBAAkB,KAAK,KAAK;AAEpD,WACE,KAAK,aAAa,MAAM,WACxB,4BACA;AAAA,EAEJ;AAAA,EAEU,mBAAmB,MAG1B;AACD,WAAO;AAAA,MACL,OAAO,KAAK,aAAa,SAAS;AAAA,MAClC,eAAe,KAAK,aAAa,iBAAiB;AAAA,MAClD,WAAW,KAAK,aAAa,aAAa,CAAC;AAAA,MAC3C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,MAAM,iBAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,MAAM,kBAAkB,KAAK,QAAQ;AAC5D,UAAM,cAAc,mBAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAGhD,YAAQ;AAAA,MACN,SAAS;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AAEvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
@@ -3,7 +3,7 @@ export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as Defaul
3
3
  export { HttpRequestHandler, HttpResponseResolver, http } from './http.mjs';
4
4
  export { HttpHandler, HttpMethods, HttpRequestParsedResult, RequestQuery } from './handlers/HttpHandler.mjs';
5
5
  export { GraphQLRequestHandler, GraphQLResponseResolver, graphql } from './graphql.mjs';
6
- export { G as GraphQLHandler, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, b as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-D4_CxZQj.mjs';
6
+ export { G as GraphQLHandler, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, b as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-BNMGdWQe.mjs';
7
7
  export { WebSocketEventListener, WebSocketLink, ws } from './ws.mjs';
8
8
  export { WebSocketHandler, WebSocketHandlerConnection, WebSocketHandlerEventMap } from './handlers/WebSocketHandler.mjs';
9
9
  export { Match, Path, PathParams, matchRequestUrl } from './utils/matching/matchRequestUrl.mjs';
@@ -3,7 +3,7 @@ export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as Defaul
3
3
  export { HttpRequestHandler, HttpResponseResolver, http } from './http.js';
4
4
  export { HttpHandler, HttpMethods, HttpRequestParsedResult, RequestQuery } from './handlers/HttpHandler.js';
5
5
  export { GraphQLRequestHandler, GraphQLResponseResolver, graphql } from './graphql.js';
6
- export { G as GraphQLHandler, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, b as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-Pox7fIFM.js';
6
+ export { G as GraphQLHandler, d as GraphQLJsonRequestBody, a as GraphQLQuery, c as GraphQLRequestBody, b as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-D1CSV926.js';
7
7
  export { WebSocketEventListener, WebSocketLink, ws } from './ws.js';
8
8
  export { WebSocketHandler, WebSocketHandlerConnection, WebSocketHandlerEventMap } from './handlers/WebSocketHandler.js';
9
9
  export { Match, Path, PathParams, matchRequestUrl } from './utils/matching/matchRequestUrl.js';
@@ -1,5 +1,5 @@
1
1
  import 'graphql';
2
- export { j as GraphQLMultipartRequestBody, i as GraphQLParsedOperationsMap, h as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, k as parseGraphQLRequest } from '../../GraphQLHandler-D4_CxZQj.mjs';
2
+ export { j as GraphQLMultipartRequestBody, i as GraphQLParsedOperationsMap, h as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, k as parseGraphQLRequest } from '../../GraphQLHandler-BNMGdWQe.mjs';
3
3
  import '../../HttpResponse-BRDnWbjc.mjs';
4
4
  import '@mswjs/interceptors';
5
5
  import './isIterable.mjs';
@@ -1,5 +1,5 @@
1
1
  import 'graphql';
2
- export { j as GraphQLMultipartRequestBody, i as GraphQLParsedOperationsMap, h as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, k as parseGraphQLRequest } from '../../GraphQLHandler-Pox7fIFM.js';
2
+ export { j as GraphQLMultipartRequestBody, i as GraphQLParsedOperationsMap, h as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, k as parseGraphQLRequest } from '../../GraphQLHandler-D1CSV926.js';
3
3
  import '../../HttpResponse-Cy7ytzUn.js';
4
4
  import '@mswjs/interceptors';
5
5
  import './isIterable.js';
@@ -29,7 +29,7 @@ function getAbsoluteUrl(path, baseUrl) {
29
29
  if (path.startsWith("*")) {
30
30
  return path;
31
31
  }
32
- const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
32
+ const origin = baseUrl || typeof location !== "undefined" && location.href;
33
33
  return origin ? (
34
34
  // Encode and decode the path to preserve escaped characters.
35
35
  decodeURI(new URL(encodeURI(path), origin).href)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/utils/url/getAbsoluteUrl.ts"],"sourcesContent":["import { isAbsoluteUrl } from './isAbsoluteUrl'\n\n/**\n * Returns an absolute URL based on the given path.\n */\nexport function getAbsoluteUrl(path: string, baseUrl?: string): string {\n // already absolute URL\n if (isAbsoluteUrl(path)) {\n return path\n }\n\n // Ignore path with pattern start with *\n if (path.startsWith('*')) {\n return path\n }\n\n // Resolve a relative request URL against a given custom \"baseUrl\"\n // or the document baseURI (in the case of browser/browser-like environments).\n const origin =\n baseUrl || (typeof document !== 'undefined' && document.baseURI)\n\n return origin\n ? // Encode and decode the path to preserve escaped characters.\n decodeURI(new URL(encodeURI(path), origin).href)\n : path\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA8B;AAKvB,SAAS,eAAe,MAAc,SAA0B;AAErE,UAAI,oCAAc,IAAI,GAAG;AACvB,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,WAAW,GAAG,GAAG;AACxB,WAAO;AAAA,EACT;AAIA,QAAM,SACJ,WAAY,OAAO,aAAa,eAAe,SAAS;AAE1D,SAAO;AAAA;AAAA,IAEH,UAAU,IAAI,IAAI,UAAU,IAAI,GAAG,MAAM,EAAE,IAAI;AAAA,MAC/C;AACN;","names":[]}
1
+ {"version":3,"sources":["../../../../src/core/utils/url/getAbsoluteUrl.ts"],"sourcesContent":["import { isAbsoluteUrl } from './isAbsoluteUrl'\n\n/**\n * Returns an absolute URL based on the given path.\n */\nexport function getAbsoluteUrl(path: string, baseUrl?: string): string {\n // already absolute URL\n if (isAbsoluteUrl(path)) {\n return path\n }\n\n // Ignore path with pattern start with *\n if (path.startsWith('*')) {\n return path\n }\n\n // Resolve a relative request URL against a given custom \"baseUrl\"\n // or the document baseURI (in the case of browser/browser-like environments).\n const origin = baseUrl || (typeof location !== 'undefined' && location.href)\n\n return origin\n ? // Encode and decode the path to preserve escaped characters.\n decodeURI(new URL(encodeURI(path), origin).href)\n : path\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA8B;AAKvB,SAAS,eAAe,MAAc,SAA0B;AAErE,UAAI,oCAAc,IAAI,GAAG;AACvB,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,WAAW,GAAG,GAAG;AACxB,WAAO;AAAA,EACT;AAIA,QAAM,SAAS,WAAY,OAAO,aAAa,eAAe,SAAS;AAEvE,SAAO;AAAA;AAAA,IAEH,UAAU,IAAI,IAAI,UAAU,IAAI,GAAG,MAAM,EAAE,IAAI;AAAA,MAC/C;AACN;","names":[]}
@@ -6,7 +6,7 @@ function getAbsoluteUrl(path, baseUrl) {
6
6
  if (path.startsWith("*")) {
7
7
  return path;
8
8
  }
9
- const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
9
+ const origin = baseUrl || typeof location !== "undefined" && location.href;
10
10
  return origin ? (
11
11
  // Encode and decode the path to preserve escaped characters.
12
12
  decodeURI(new URL(encodeURI(path), origin).href)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/utils/url/getAbsoluteUrl.ts"],"sourcesContent":["import { isAbsoluteUrl } from './isAbsoluteUrl'\n\n/**\n * Returns an absolute URL based on the given path.\n */\nexport function getAbsoluteUrl(path: string, baseUrl?: string): string {\n // already absolute URL\n if (isAbsoluteUrl(path)) {\n return path\n }\n\n // Ignore path with pattern start with *\n if (path.startsWith('*')) {\n return path\n }\n\n // Resolve a relative request URL against a given custom \"baseUrl\"\n // or the document baseURI (in the case of browser/browser-like environments).\n const origin =\n baseUrl || (typeof document !== 'undefined' && document.baseURI)\n\n return origin\n ? // Encode and decode the path to preserve escaped characters.\n decodeURI(new URL(encodeURI(path), origin).href)\n : path\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAKvB,SAAS,eAAe,MAAc,SAA0B;AAErE,MAAI,cAAc,IAAI,GAAG;AACvB,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,WAAW,GAAG,GAAG;AACxB,WAAO;AAAA,EACT;AAIA,QAAM,SACJ,WAAY,OAAO,aAAa,eAAe,SAAS;AAE1D,SAAO;AAAA;AAAA,IAEH,UAAU,IAAI,IAAI,UAAU,IAAI,GAAG,MAAM,EAAE,IAAI;AAAA,MAC/C;AACN;","names":[]}
1
+ {"version":3,"sources":["../../../../src/core/utils/url/getAbsoluteUrl.ts"],"sourcesContent":["import { isAbsoluteUrl } from './isAbsoluteUrl'\n\n/**\n * Returns an absolute URL based on the given path.\n */\nexport function getAbsoluteUrl(path: string, baseUrl?: string): string {\n // already absolute URL\n if (isAbsoluteUrl(path)) {\n return path\n }\n\n // Ignore path with pattern start with *\n if (path.startsWith('*')) {\n return path\n }\n\n // Resolve a relative request URL against a given custom \"baseUrl\"\n // or the document baseURI (in the case of browser/browser-like environments).\n const origin = baseUrl || (typeof location !== 'undefined' && location.href)\n\n return origin\n ? // Encode and decode the path to preserve escaped characters.\n decodeURI(new URL(encodeURI(path), origin).href)\n : path\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAKvB,SAAS,eAAe,MAAc,SAA0B;AAErE,MAAI,cAAc,IAAI,GAAG;AACvB,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,WAAW,GAAG,GAAG;AACxB,WAAO;AAAA,EACT;AAIA,QAAM,SAAS,WAAY,OAAO,aAAa,eAAe,SAAS;AAEvE,SAAO;AAAA;AAAA,IAEH,UAAU,IAAI,IAAI,UAAU,IAAI,GAAG,MAAM,EAAE,IAAI;AAAA,MAC/C;AACN;","names":[]}
package/lib/iife/index.js CHANGED
@@ -14830,7 +14830,7 @@ ${operationTypes.join("\n")}
14830
14830
  if (path.startsWith("*")) {
14831
14831
  return path;
14832
14832
  }
14833
- const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
14833
+ const origin = baseUrl || typeof location !== "undefined" && location.href;
14834
14834
  return origin ? (
14835
14835
  // Encode and decode the path to preserve escaped characters.
14836
14836
  decodeURI(new URL(encodeURI(path), origin).href)