Open History to see the last commit
1/* eslint-disable */
2/* tslint:disable */
3β
4/**
5 * Mock Service Worker.
6 * @see https://github.com/mswjs/msw
7 * - Please do NOT modify this file.
8 */
9β
10const PACKAGE_VERSION = '2.15.0'
11const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
12const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13const activeClientIds = new Set()
14β
15addEventListener('install', function () {
16 self.skipWaiting()
17})
18β
19addEventListener('activate', function (event) {
20 event.waitUntil(self.clients.claim())
21})
22β
23addEventListener('message', async function (event) {
24 const clientId = Reflect.get(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: {
52 packageVersion: PACKAGE_VERSION,
53 checksum: INTEGRITY_CHECKSUM,
54 },
55 })
56 break
57 }
58β
59 case 'MOCK_ACTIVATE': {
60 activeClientIds.add(clientId)
61β
62 sendToClient(client, {
63 type: 'MOCKING_ENABLED',
64 payload: {
65 client: {
66 id: client.id,
67 frameType: client.frameType,
68 },
69 },
70 })
71 break
72 }
73β
74 case 'CLIENT_CLOSED': {
75 activeClientIds.delete(clientId)
76β
77 const remainingClients = allClients.filter((client) => {
78 return client.id !== clientId
79 })
80β
81 // Unregister itself when there are no more clients
82 if (remainingClients.length === 0) {
83 self.registration.unregister()
84 }
85β
86 break
87 }
88 }
89})
90β
91addEventListener('fetch', function (event) {
92 const requestInterceptedAt = Date.now()
93β
94 // Bypass navigation requests.
95 if (event.request.mode === 'navigate') {
96 return
97 }
98β
99 // Opening the DevTools triggers the "only-if-cached" request
100 // that cannot be handled by the worker. Bypass such requests.
101 if (
102 event.request.cache === 'only-if-cached' &&
103 event.request.mode !== 'same-origin'
104 ) {
105 return
106 }
107β
108 // Bypass all requests when there are no active clients.
109 // Prevents the self-unregistered worked from handling requests
110 // after it's been terminated (still remains active until the next reload).
111 if (activeClientIds.size === 0) {
112 return
113 }
114β
115 const requestId = crypto.randomUUID()
116 event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
117})
118β
119/**
120 * @param {FetchEvent} event
121 * @param {string} requestId
122 * @param {number} requestInterceptedAt
123 */
124async function handleRequest(event, requestId, requestInterceptedAt) {
125 const client = await resolveMainClient(event)
126 const requestCloneForEvents = event.request.clone()
127 const response = await getResponse(
128 event,
129 client,
130 requestId,
131 requestInterceptedAt,
132 )
133β
134 // Send back the response clone for the "response:*" life-cycle events.
135 // Ensure MSW is active and ready to handle the message, otherwise
136 // this message will pend indefinitely.
137 if (client && activeClientIds.has(client.id)) {
138 const serializedRequest = await serializeRequest(requestCloneForEvents)
139β
140 // Omit the body of server-sent event stream responses.
141 // Cloning such responses would prevent client-side stream cancelations
142 // from reaching the original stream (a teed stream only cancels its
143 // source once both of its branches cancel) and would buffer the
144 // entire stream into the unconsumed clone indefinitely.
145 const isEventStreamResponse = response.headers
146 .get('content-type')
147 ?.toLowerCase()
148 .startsWith('text/event-stream')
149β
150 // Clone the response so both the client and the library could consume it.
151 const responseClone = isEventStreamResponse ? null : response.clone()
152β
153 sendToClient(
154 client,
155 {
156 type: 'RESPONSE',
157 payload: {
158 isMockedResponse: IS_MOCKED_RESPONSE in response,
159 request: {
160 id: requestId,
161 ...serializedRequest,
162 },
163 response: {
164 type: response.type,
165 status: response.status,
166 statusText: response.statusText,
167 headers: Object.fromEntries(response.headers.entries()),
168 body: responseClone ? responseClone.body : null,
169 },
170 },
171 },
172 responseClone && responseClone.body
173 ? [serializedRequest.body, responseClone.body]
174 : [],
175 )
176 }
177β
178 return response
179}
180β
181/**
182 * Resolve the main client for the given event.
183 * Client that issues a request doesn't necessarily equal the client
184 * that registered the worker. It's with the latter the worker should
185 * communicate with during the response resolving phase.
186 * @param {FetchEvent} event
187 * @returns {Promise<Client | undefined>}
188 */
189async function resolveMainClient(event) {
190 const client = await self.clients.get(event.clientId)
191β
192 if (activeClientIds.has(event.clientId)) {
193 return client
194 }
195β
196 if (client?.frameType === 'top-level') {
197 return client
198 }
199β
200 const allClients = await self.clients.matchAll({
201 type: 'window',
202 })
203β
204 return allClients
205 .filter((client) => {
206 // Get only those clients that are currently visible.
207 return client.visibilityState === 'visible'
208 })
209 .find((client) => {
210 // Find the client ID that's recorded in the
211 // set of clients that have registered the worker.
212 return activeClientIds.has(client.id)
213 })
214}
215β
216/**
217 * @param {FetchEvent} event
218 * @param {Client | undefined} client
219 * @param {string} requestId
220 * @param {number} requestInterceptedAt
221 * @returns {Promise<Response>}
222 */
223async function getResponse(event, client, requestId, requestInterceptedAt) {
224 // Clone the request because it might've been already used
225 // (i.e. its body has been read and sent to the client).
226 const requestClone = event.request.clone()
227β
228 function passthrough() {
229 // Cast the request headers to a new Headers instance
230 // so the headers can be manipulated with.
231 const headers = new Headers(requestClone.headers)
232β
233 // Remove the "accept" header value that marked this request as passthrough.
234 // This prevents request alteration and also keeps it compliant with the
235 // user-defined CORS policies.
236 const acceptHeader = headers.get('accept')
237 if (acceptHeader) {
238 const values = acceptHeader.split(',').map((value) => value.trim())
239 const filteredValues = values.filter(
240 (value) => value !== 'msw/passthrough',
241 )
242β
243 if (filteredValues.length > 0) {
244 headers.set('accept', filteredValues.join(', '))
245 } else {
246 headers.delete('accept')
247 }
248 }
249β
250 return fetch(requestClone, { headers })
251 }
252β
253 // Bypass mocking when the client is not active.
254 if (!client) {
255 return passthrough()
256 }
257β
258 // Bypass initial page load requests (i.e. static assets).
259 // The absence of the immediate/parent client in the map of the active clients
260 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
261 // and is not ready to handle requests.
262 if (!activeClientIds.has(client.id)) {
263 return passthrough()
264 }
265β
266 // Notify the client that a request has been intercepted.
267 const serializedRequest = await serializeRequest(event.request)
268 const clientMessage = await sendToClient(
269 client,
270 {
271 type: 'REQUEST',
272 payload: {
273 id: requestId,
274 interceptedAt: requestInterceptedAt,
275 ...serializedRequest,
276 },
277 },
278 [serializedRequest.body],
279 )
280β
281 switch (clientMessage.type) {
282 case 'MOCK_RESPONSE': {
283 return respondWithMock(clientMessage.data)
284 }
285β
286 case 'PASSTHROUGH': {
287 return passthrough()
288 }
289 }
290β
291 return passthrough()
292}
293β
294/**
295 * @param {Client} client
296 * @param {any} message
297 * @param {Array<Transferable>} transferrables
298 * @returns {Promise<any>}
299 */
300function sendToClient(client, message, transferrables = []) {
301 return new Promise((resolve, reject) => {
302 const channel = new MessageChannel()
303β
304 channel.port1.onmessage = (event) => {
305 if (event.data && event.data.error) {
306 return reject(event.data.error)
307 }
308β
309 resolve(event.data)
310 }
311β
312 client.postMessage(message, [
313 channel.port2,
314 ...transferrables.filter(Boolean),
315 ])
316 })
317}
318β
319/**
320 * @param {Response} response
321 * @returns {Response}
322 */
323function respondWithMock(response) {
324 // Setting response status code to 0 is a no-op.
325 // However, when responding with a "Response.error()", the produced Response
326 // instance will have status code set to 0. Since it's not possible to create
327 // a Response instance with status code 0, handle that use-case separately.
328 if (response.status === 0) {
329 return Response.error()
330 }
331β
332 const mockedResponse = new Response(response.body, response)
333β
334 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
335 value: true,
336 enumerable: true,
337 })
338β
339 return mockedResponse
340}
341β
342/**
343 * @param {Request} request
344 */
345async function serializeRequest(request) {
346 return {
347 url: request.url,
348 mode: request.mode,
349 method: request.method,
350 headers: Object.fromEntries(request.headers.entries()),
351 cache: request.cache,
352 credentials: request.credentials,
353 destination: request.destination,
354 integrity: request.integrity,
355 redirect: request.redirect,
356 referrer: request.referrer,
357 referrerPolicy: request.referrerPolicy,
358 body: await request.arrayBuffer(),
359 keepalive: request.keepalive,
360 }
361}