Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

mockServiceWorker.js

287 lines7.5 KB

1/* eslint-disable */
2/* tslint:disable */
3​
4/**
5 * Mock Service Worker (2.1.7).
6 * @see https://github.com/mswjs/msw
7 * - Please do NOT modify this file.
8 * - Please do NOT serve this file on production.
9 */
10​
11const INTEGRITY_CHECKSUM = '223d191a56023cd36aa88c802961b911'
12const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13const activeClientIds = new Set()
14​
15self.addEventListener('install', function () {
16 self.skipWaiting()
17})
18​
19self.addEventListener('activate', function (event) {
20 event.waitUntil(self.clients.claim())
21})
22​
23self.addEventListener('message', async function (event) {
24 const clientId = event.source.id
25​
26 if (!clientId || !self.clients) {
27 return
28 }
29​
30 const client = await self.clients.get(clientId)
31​
32 if (!client) {
33 return
34 }
35​
36 const allClients = await self.clients.matchAll({
37 type: 'window',
38 })
39​
40 switch (event.data) {
41 case 'KEEPALIVE_REQUEST': {
42 sendToClient(client, {
43 type: 'KEEPALIVE_RESPONSE',
44 })
45 break
46 }
47​
48 case 'INTEGRITY_CHECK_REQUEST': {
49 sendToClient(client, {
50 type: 'INTEGRITY_CHECK_RESPONSE',
51 payload: INTEGRITY_CHECKSUM,
52 })
53 break
54 }
55​
56 case 'MOCK_ACTIVATE': {
57 activeClientIds.add(clientId)
58​
59 sendToClient(client, {
60 type: 'MOCKING_ENABLED',
61 payload: true,
62 })
63 break
64 }
65​
66 case 'MOCK_DEACTIVATE': {
67 activeClientIds.delete(clientId)
68 break
69 }
70​
71 case 'CLIENT_CLOSED': {
72 activeClientIds.delete(clientId)
73​
74 const remainingClients = allClients.filter((client) => {
75 return client.id !== clientId
76 })
77​
78 // Unregister itself when there are no more clients
79 if (remainingClients.length === 0) {
80 self.registration.unregister()
81 }
82​
83 break
84 }
85 }
86})
87​
88self.addEventListener('fetch', function (event) {
89 const { request } = event
90​
91 // Bypass navigation requests.
92 if (request.mode === 'navigate') {
93 return
94 }
95​
96 // Opening the DevTools triggers the "only-if-cached" request
97 // that cannot be handled by the worker. Bypass such requests.
98 if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
99 return
100 }
101​
102 // Bypass all requests when there are no active clients.
103 // Prevents the self-unregistered worked from handling requests
104 // after it's been deleted (still remains active until the next reload).
105 if (activeClientIds.size === 0) {
106 return
107 }
108​
109 // Generate unique request ID.
110 const requestId = crypto.randomUUID()
111 event.respondWith(handleRequest(event, requestId))
112})
113​
114async function handleRequest(event, requestId) {
115 const client = await resolveMainClient(event)
116 const response = await getResponse(event, client, requestId)
117​
118 // Send back the response clone for the "response:*" life-cycle events.
119 // Ensure MSW is active and ready to handle the message, otherwise
120 // this message will pend indefinitely.
121 if (client && activeClientIds.has(client.id)) {
122 ;(async function () {
123 const responseClone = response.clone()
124​
125 sendToClient(
126 client,
127 {
128 type: 'RESPONSE',
129 payload: {
130 requestId,
131 isMockedResponse: IS_MOCKED_RESPONSE in response,
132 type: responseClone.type,
133 status: responseClone.status,
134 statusText: responseClone.statusText,
135 body: responseClone.body,
136 headers: Object.fromEntries(responseClone.headers.entries()),
137 },
138 },
139 [responseClone.body],
140 )
141 })()
142 }
143​
144 return response
146​
147// Resolve the main client for the given event.
148// Client that issues a request doesn't necessarily equal the client
149// that registered the worker. It's with the latter the worker should
150// communicate with during the response resolving phase.
151async function resolveMainClient(event) {
152 const client = await self.clients.get(event.clientId)
153​
154 if (client?.frameType === 'top-level') {
155 return client
156 }
157​
158 const allClients = await self.clients.matchAll({
159 type: 'window',
160 })
161​
162 return allClients
163 .filter((client) => {
164 // Get only those clients that are currently visible.
165 return client.visibilityState === 'visible'
166 })
167 .find((client) => {
168 // Find the client ID that's recorded in the
169 // set of clients that have registered the worker.
170 return activeClientIds.has(client.id)
171 })
173​
174async function getResponse(event, client, requestId) {
175 const { request } = event
176​
177 // Clone the request because it might've been already used
178 // (i.e. its body has been read and sent to the client).
179 const requestClone = request.clone()
180​
181 function passthrough() {
182 const headers = Object.fromEntries(requestClone.headers.entries())
183​
184 // Remove internal MSW request header so the passthrough request
185 // complies with any potential CORS preflight checks on the server.
186 // Some servers forbid unknown request headers.
187 delete headers['x-msw-intention']
188​
189 return fetch(requestClone, { headers })
190 }
191​
192 // Bypass mocking when the client is not active.
193 if (!client) {
194 return passthrough()
195 }
196​
197 // Bypass initial page load requests (i.e. static assets).
198 // The absence of the immediate/parent client in the map of the active clients
199 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
200 // and is not ready to handle requests.
201 if (!activeClientIds.has(client.id)) {
202 return passthrough()
203 }
204​
205 // Bypass requests with the explicit bypass header.
206 // Such requests can be issued by "ctx.fetch()".
207 const mswIntention = request.headers.get('x-msw-intention')
208 if (['bypass', 'passthrough'].includes(mswIntention)) {
209 return passthrough()
210 }
211​
212 // Notify the client that a request has been intercepted.
213 const requestBuffer = await request.arrayBuffer()
214 const clientMessage = await sendToClient(
215 client,
216 {
217 type: 'REQUEST',
218 payload: {
219 id: requestId,
220 url: request.url,
221 mode: request.mode,
222 method: request.method,
223 headers: Object.fromEntries(request.headers.entries()),
224 cache: request.cache,
225 credentials: request.credentials,
226 destination: request.destination,
227 integrity: request.integrity,
228 redirect: request.redirect,
229 referrer: request.referrer,
230 referrerPolicy: request.referrerPolicy,
231 body: requestBuffer,
232 keepalive: request.keepalive,
233 },
234 },
235 [requestBuffer],
236 )
237​
238 switch (clientMessage.type) {
239 case 'MOCK_RESPONSE': {
240 return respondWithMock(clientMessage.data)
241 }
242​
243 case 'MOCK_NOT_FOUND': {
244 return passthrough()
245 }
246 }
247​
248 return passthrough()
250​
251function sendToClient(client, message, transferrables = []) {
252 return new Promise((resolve, reject) => {
253 const channel = new MessageChannel()
254​
255 channel.port1.onmessage = (event) => {
256 if (event.data && event.data.error) {
257 return reject(event.data.error)
258 }
259​
260 resolve(event.data)
261 }
262​
263 client.postMessage(
264 message,
265 [channel.port2].concat(transferrables.filter(Boolean)),
266 )
267 })
269​
270async function respondWithMock(response) {
271 // Setting response status code to 0 is a no-op.
272 // However, when responding with a "Response.error()", the produced Response
273 // instance will have status code set to 0. Since it's not possible to create
274 // a Response instance with status code 0, handle that use-case separately.
275 if (response.status === 0) {
276 return Response.error()
277 }
278​
279 const mockedResponse = new Response(response.body, response)
280​
281 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
282 value: true,
283 enumerable: true,
284 })
285​
286 return mockedResponse