PageSourceSearch

https://berrynherb.com/mockServiceWorker.js

js berrynherb.com collected 2026-10-08 17:35:46 UTC 9,080 bytes, 348 lines download raw bytes

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.11.2'
11const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
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    // Clone the response so both the client and the library could consume it.
141    const responseClone = response.clone()
142
143    sendToClient(
144      client,
145      {
146        type: 'RESPONSE',
147        payload: {
148          isMockedResponse: IS_MOCKED_RESPONSE in response,
149          request: {
150            id: requestId,
151            ...serializedRequest,
152          },
153          response: {
154            type: responseClone.type,
155            status: responseClone.status,
156            statusText: responseClone.statusText,
157            headers: Object.fromEntries(responseClone.headers.entries()),
158            body: responseClone.body,
159          },
160        },
161      },
162      responseClone.body ? [serializedRequest.body, responseClone.body] : [],
163    )
164  }
165
166  return response
167}
168
169/**
170 * Resolve the main client for the given event.
171 * Client that issues a request doesn't necessarily equal the client
172 * that registered the worker. It's with the latter the worker should
173 * communicate with during the response resolving phase.
174 * @param {FetchEvent} event
175 * @returns {Promise<Client | undefined>}
176 */
177async function resolveMainClient(event) {
178  const client = await self.clients.get(event.clientId)
179
180  if (activeClientIds.has(event.clientId)) {
181    return client
182  }
183
184  if (client?.frameType === 'top-level') {
185    return client
186  }
187
188  const allClients = await self.clients.matchAll({
189    type: 'window',
190  })
191
192  return allClients
193    .filter((client) => {
194      // Get only those clients that are currently visible.
195      return client.visibilityState === 'visible'
196    })
197    .find((client) => {
198      // Find the client ID that's recorded in the
199      // set of clients that have registered the worker.
200      return activeClientIds.has(client.id)
201    })
202}
203
204/**
205 * @param {FetchEvent} event
206 * @param {Client | undefined} client
207 * @param {string} requestId
208 * @returns {Promise<Response>}
209 */
210async function getResponse(event, client, requestId, requestInterceptedAt) {
211  // Clone the request because it might've been already used
212  // (i.e. its body has been read and sent to the client).
213  const requestClone = event.request.clone()
214
215  function passthrough() {
216    // Cast the request headers to a new Headers instance
217    // so the headers can be manipulated with.
218    const headers = new Headers(requestClone.headers)
219
220    // Remove the "accept" header value that marked this request as passthrough.
221    // This prevents request alteration and also keeps it compliant with the
222    // user-defined CORS policies.
223    const acceptHeader = headers.get('accept')
224    if (acceptHeader) {
225      const values = acceptHeader.split(',').map((value) => value.trim())
226      const filteredValues = values.filter(
227        (value) => value !== 'msw/passthrough',
228      )
229
230      if (filteredValues.length > 0) {
231        headers.set('accept', filteredValues.join(', '))
232      } else {
233        headers.delete('accept')
234      }
235    }
236
237    return fetch(requestClone, { headers })
238  }
239
240  // Bypass mocking when the client is not active.
241  if (!client) {
242    return passthrough()
243  }
244
245  // Bypass initial page load requests (i.e. static assets).
246  // The absence of the immediate/parent client in the map of the active clients
247  // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
248  // and is not ready to handle requests.
249  if (!activeClientIds.has(client.id)) {
250    return passthrough()
251  }
252
253  // Notify the client that a request has been intercepted.
254  const serializedRequest = await serializeRequest(event.request)
255  const clientMessage = await sendToClient(
256    client,
257    {
258      type: 'REQUEST',
259      payload: {
260        id: requestId,
261        interceptedAt: requestInterceptedAt,
262        ...serializedRequest,
263      },
264    },
265    [serializedRequest.body],
266  )
267
268  switch (clientMessage.type) {
269    case 'MOCK_RESPONSE': {
270      return respondWithMock(clientMessage.data)
271    }
272
273    case 'PASSTHROUGH': {
274      return passthrough()
275    }
276  }
277
278  return passthrough()
279}
280
281/**
282 * @param {Client} client
283 * @param {any} message
284 * @param {Array<Transferable>} transferrables
285 * @returns {Promise<any>}
286 */
287function sendToClient(client, message, transferrables = []) {
288  return new Promise((resolve, reject) => {
289    const channel = new MessageChannel()
290
291    channel.port1.onmessage = (event) => {
292      if (event.data && event.data.error) {
293        return reject(event.data.error)
294      }
295
296      resolve(event.data)
297    }
298
299    client.postMessage(message, [
300      channel.port2,
301      ...transferrables.filter(Boolean),
302    ])
303  })
304}
305
306/**
307 * @param {Response} response
308 * @returns {Response}
309 */
310function respondWithMock(response) {
311  // Setting response status code to 0 is a no-op.
312  // However, when responding with a "Response.error()", the produced Response
313  // instance will have status code set to 0. Since it's not possible to create
314  // a Response instance with status code 0, handle that use-case separately.
315  if (response.status === 0) {
316    return Response.error()
317  }
318
319  const mockedResponse = new Response(response.body, response)
320
321  Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
322    value: true,
323    enumerable: true,
324  })
325
326  return mockedResponse
327}
328
329/**
330 * @param {Request} request
331 */
332async function serializeRequest(request) {
333  return {
334    url: request.url,
335    mode: request.mode,
336    method: request.method,
337    headers: Object.fromEntries(request.headers.entries()),
338    cache: request.cache,
339    credentials: request.credentials,
340    destination: request.destination,
341    integrity: request.integrity,
342    redirect: request.redirect,
343    referrer: request.referrer,
344    referrerPolicy: request.referrerPolicy,
345    body: await request.arrayBuffer(),
346    keepalive: request.keepalive,
347  }
348}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.