authorgravatar for julius0216@outlook.comJulius Marminge <julius0216@outlook.com> 2026-03-10 18:49:04-07:00
committergravatar for julius0216@outlook.comJulius Marminge <julius0216@outlook.com> 2026-03-10 18:49:04-07:00
log82a50da8b1f72da407a0c596a7be6b62e2ead284
tree03015f7c5c3b9f1c01d2f4509c7df6af51951775
parent7ddcb239c5ce4031653afbc404a860ccf5606549

revert formatting on mockServiceWorker.js


1 files changed, 106 insertions(+), 93 deletions(-)

apps/web/public/mockServiceWorker.js+106-93
...@@ -7,111 +7,114 @@...@@ -7,111 +7,114 @@
7 * - Please do NOT modify this file.7 * - Please do NOT modify this file.
8 */8 */
99
10const PACKAGE_VERSION = "2.12.10";10const PACKAGE_VERSION = '2.12.9'
11const INTEGRITY_CHECKSUM = "4db4a41e972cec1b64cc569c66952d82";11const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
12const IS_MOCKED_RESPONSE = Symbol("isMockedResponse");12const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13const activeClientIds = new Set();13const activeClientIds = new Set()
1414
15addEventListener("install", function () {15addEventListener('install', function () {
16 self.skipWaiting();16 self.skipWaiting()
17});17})
1818
19addEventListener("activate", function (event) {19addEventListener('activate', function (event) {
20 event.waitUntil(self.clients.claim());20 event.waitUntil(self.clients.claim())
21});21})
2222
23addEventListener("message", async function (event) {23addEventListener('message', async function (event) {
24 const clientId = Reflect.get(event.source || {}, "id");24 const clientId = Reflect.get(event.source || {}, 'id')
2525
26 if (!clientId || !self.clients) {26 if (!clientId || !self.clients) {
27 return;27 return
28 }28 }
2929
30 const client = await self.clients.get(clientId);30 const client = await self.clients.get(clientId)
3131
32 if (!client) {32 if (!client) {
33 return;33 return
34 }34 }
3535
36 const allClients = await self.clients.matchAll({36 const allClients = await self.clients.matchAll({
37 type: "window",37 type: 'window',
38 });38 })
3939
40 switch (event.data) {40 switch (event.data) {
41 case "KEEPALIVE_REQUEST": {41 case 'KEEPALIVE_REQUEST': {
42 sendToClient(client, {42 sendToClient(client, {
43 type: "KEEPALIVE_RESPONSE",43 type: 'KEEPALIVE_RESPONSE',
44 });44 })
45 break;45 break
46 }46 }
4747
48 case "INTEGRITY_CHECK_REQUEST": {48 case 'INTEGRITY_CHECK_REQUEST': {
49 sendToClient(client, {49 sendToClient(client, {
50 type: "INTEGRITY_CHECK_RESPONSE",50 type: 'INTEGRITY_CHECK_RESPONSE',
51 payload: {51 payload: {
52 packageVersion: PACKAGE_VERSION,52 packageVersion: PACKAGE_VERSION,
53 checksum: INTEGRITY_CHECKSUM,53 checksum: INTEGRITY_CHECKSUM,
54 },54 },
55 });55 })
56 break;56 break
57 }57 }
5858
59 case "MOCK_ACTIVATE": {59 case 'MOCK_ACTIVATE': {
60 activeClientIds.add(clientId);60 activeClientIds.add(clientId)
6161
62 sendToClient(client, {62 sendToClient(client, {
63 type: "MOCKING_ENABLED",63 type: 'MOCKING_ENABLED',
64 payload: {64 payload: {
65 client: {65 client: {
66 id: client.id,66 id: client.id,
67 frameType: client.frameType,67 frameType: client.frameType,
68 },68 },
69 },69 },
70 });70 })
71 break;71 break
72 }72 }
7373
74 case "CLIENT_CLOSED": {74 case 'CLIENT_CLOSED': {
75 activeClientIds.delete(clientId);75 activeClientIds.delete(clientId)
7676
77 const remainingClients = allClients.filter((client) => {77 const remainingClients = allClients.filter((client) => {
78 return client.id !== clientId;78 return client.id !== clientId
79 });79 })
8080
81 // Unregister itself when there are no more clients81 // Unregister itself when there are no more clients
82 if (remainingClients.length === 0) {82 if (remainingClients.length === 0) {
83 self.registration.unregister();83 self.registration.unregister()
84 }84 }
8585
86 break;86 break
87 }87 }
88 }88 }
89});89})
9090
91addEventListener("fetch", function (event) {91addEventListener('fetch', function (event) {
92 const requestInterceptedAt = Date.now();92 const requestInterceptedAt = Date.now()
9393
94 // Bypass navigation requests.94 // Bypass navigation requests.
95 if (event.request.mode === "navigate") {95 if (event.request.mode === 'navigate') {
96 return;96 return
97 }97 }
9898
99 // Opening the DevTools triggers the "only-if-cached" request99 // Opening the DevTools triggers the "only-if-cached" request
100 // that cannot be handled by the worker. Bypass such requests.100 // that cannot be handled by the worker. Bypass such requests.
101 if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {101 if (
102 return;102 event.request.cache === 'only-if-cached' &&
103 event.request.mode !== 'same-origin'
104 ) {
105 return
103 }106 }
104107
105 // Bypass all requests when there are no active clients.108 // Bypass all requests when there are no active clients.
106 // Prevents the self-unregistered worked from handling requests109 // Prevents the self-unregistered worked from handling requests
107 // after it's been terminated (still remains active until the next reload).110 // after it's been terminated (still remains active until the next reload).
108 if (activeClientIds.size === 0) {111 if (activeClientIds.size === 0) {
109 return;112 return
110 }113 }
111114
112 const requestId = crypto.randomUUID();115 const requestId = crypto.randomUUID()
113 event.respondWith(handleRequest(event, requestId, requestInterceptedAt));116 event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
114});117})
115118
116/**119/**
117 * @param {FetchEvent} event120 * @param {FetchEvent} event
...@@ -119,23 +122,28 @@ addEventListener("fetch", function (event) {...@@ -119,23 +122,28 @@ addEventListener("fetch", function (event) {
119 * @param {number} requestInterceptedAt122 * @param {number} requestInterceptedAt
120 */123 */
121async function handleRequest(event, requestId, requestInterceptedAt) {124async function handleRequest(event, requestId, requestInterceptedAt) {
122 const client = await resolveMainClient(event);125 const client = await resolveMainClient(event)
123 const requestCloneForEvents = event.request.clone();126 const requestCloneForEvents = event.request.clone()
124 const response = await getResponse(event, client, requestId, requestInterceptedAt);127 const response = await getResponse(
128 event,
129 client,
130 requestId,
131 requestInterceptedAt,
132 )
125133
126 // Send back the response clone for the "response:*" life-cycle events.134 // Send back the response clone for the "response:*" life-cycle events.
127 // Ensure MSW is active and ready to handle the message, otherwise135 // Ensure MSW is active and ready to handle the message, otherwise
128 // this message will pend indefinitely.136 // this message will pend indefinitely.
129 if (client && activeClientIds.has(client.id)) {137 if (client && activeClientIds.has(client.id)) {
130 const serializedRequest = await serializeRequest(requestCloneForEvents);138 const serializedRequest = await serializeRequest(requestCloneForEvents)
131139
132 // Clone the response so both the client and the library could consume it.140 // Clone the response so both the client and the library could consume it.
133 const responseClone = response.clone();141 const responseClone = response.clone()
134142
135 sendToClient(143 sendToClient(
136 client,144 client,
137 {145 {
138 type: "RESPONSE",146 type: 'RESPONSE',
139 payload: {147 payload: {
140 isMockedResponse: IS_MOCKED_RESPONSE in response,148 isMockedResponse: IS_MOCKED_RESPONSE in response,
141 request: {149 request: {
...@@ -152,10 +160,10 @@ async function handleRequest(event, requestId, requestInterceptedAt) {...@@ -152,10 +160,10 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
152 },160 },
153 },161 },
154 responseClone.body ? [serializedRequest.body, responseClone.body] : [],162 responseClone.body ? [serializedRequest.body, responseClone.body] : [],
155 );163 )
156 }164 }
157165
158 return response;166 return response
159}167}
160168
161/**169/**
...@@ -167,30 +175,30 @@ async function handleRequest(event, requestId, requestInterceptedAt) {...@@ -167,30 +175,30 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
167 * @returns {Promise<Client | undefined>}175 * @returns {Promise<Client | undefined>}
168 */176 */
169async function resolveMainClient(event) {177async function resolveMainClient(event) {
170 const client = await self.clients.get(event.clientId);178 const client = await self.clients.get(event.clientId)
171179
172 if (activeClientIds.has(event.clientId)) {180 if (activeClientIds.has(event.clientId)) {
173 return client;181 return client
174 }182 }
175183
176 if (client?.frameType === "top-level") {184 if (client?.frameType === 'top-level') {
177 return client;185 return client
178 }186 }
179187
180 const allClients = await self.clients.matchAll({188 const allClients = await self.clients.matchAll({
181 type: "window",189 type: 'window',
182 });190 })
183191
184 return allClients192 return allClients
185 .filter((client) => {193 .filter((client) => {
186 // Get only those clients that are currently visible.194 // Get only those clients that are currently visible.
187 return client.visibilityState === "visible";195 return client.visibilityState === 'visible'
188 })196 })
189 .find((client) => {197 .find((client) => {
190 // Find the client ID that's recorded in the198 // Find the client ID that's recorded in the
191 // set of clients that have registered the worker.199 // set of clients that have registered the worker.
192 return activeClientIds.has(client.id);200 return activeClientIds.has(client.id)
193 });201 })
194}202}
195203
196/**204/**
...@@ -203,34 +211,36 @@ async function resolveMainClient(event) {...@@ -203,34 +211,36 @@ async function resolveMainClient(event) {
203async function getResponse(event, client, requestId, requestInterceptedAt) {211async function getResponse(event, client, requestId, requestInterceptedAt) {
204 // Clone the request because it might've been already used212 // Clone the request because it might've been already used
205 // (i.e. its body has been read and sent to the client).213 // (i.e. its body has been read and sent to the client).
206 const requestClone = event.request.clone();214 const requestClone = event.request.clone()
207215
208 function passthrough() {216 function passthrough() {
209 // Cast the request headers to a new Headers instance217 // Cast the request headers to a new Headers instance
210 // so the headers can be manipulated with.218 // so the headers can be manipulated with.
211 const headers = new Headers(requestClone.headers);219 const headers = new Headers(requestClone.headers)
212220
213 // Remove the "accept" header value that marked this request as passthrough.221 // Remove the "accept" header value that marked this request as passthrough.
214 // This prevents request alteration and also keeps it compliant with the222 // This prevents request alteration and also keeps it compliant with the
215 // user-defined CORS policies.223 // user-defined CORS policies.
216 const acceptHeader = headers.get("accept");224 const acceptHeader = headers.get('accept')
217 if (acceptHeader) {225 if (acceptHeader) {
218 const values = acceptHeader.split(",").map((value) => value.trim());226 const values = acceptHeader.split(',').map((value) => value.trim())
219 const filteredValues = values.filter((value) => value !== "msw/passthrough");227 const filteredValues = values.filter(
228 (value) => value !== 'msw/passthrough',
229 )
220230
221 if (filteredValues.length > 0) {231 if (filteredValues.length > 0) {
222 headers.set("accept", filteredValues.join(", "));232 headers.set('accept', filteredValues.join(', '))
223 } else {233 } else {
224 headers.delete("accept");234 headers.delete('accept')
225 }235 }
226 }236 }
227237
228 return fetch(requestClone, { headers });238 return fetch(requestClone, { headers })
229 }239 }
230240
231 // Bypass mocking when the client is not active.241 // Bypass mocking when the client is not active.
232 if (!client) {242 if (!client) {
233 return passthrough();243 return passthrough()
234 }244 }
235245
236 // Bypass initial page load requests (i.e. static assets).246 // Bypass initial page load requests (i.e. static assets).
...@@ -238,15 +248,15 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {...@@ -238,15 +248,15 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
238 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet248 // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
239 // and is not ready to handle requests.249 // and is not ready to handle requests.
240 if (!activeClientIds.has(client.id)) {250 if (!activeClientIds.has(client.id)) {
241 return passthrough();251 return passthrough()
242 }252 }
243253
244 // Notify the client that a request has been intercepted.254 // Notify the client that a request has been intercepted.
245 const serializedRequest = await serializeRequest(event.request);255 const serializedRequest = await serializeRequest(event.request)
246 const clientMessage = await sendToClient(256 const clientMessage = await sendToClient(
247 client,257 client,
248 {258 {
249 type: "REQUEST",259 type: 'REQUEST',
250 payload: {260 payload: {
251 id: requestId,261 id: requestId,
252 interceptedAt: requestInterceptedAt,262 interceptedAt: requestInterceptedAt,
...@@ -254,19 +264,19 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {...@@ -254,19 +264,19 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
254 },264 },
255 },265 },
256 [serializedRequest.body],266 [serializedRequest.body],
257 );267 )
258268
259 switch (clientMessage.type) {269 switch (clientMessage.type) {
260 case "MOCK_RESPONSE": {270 case 'MOCK_RESPONSE': {
261 return respondWithMock(clientMessage.data);271 return respondWithMock(clientMessage.data)
262 }272 }
263273
264 case "PASSTHROUGH": {274 case 'PASSTHROUGH': {
265 return passthrough();275 return passthrough()
266 }276 }
267 }277 }
268278
269 return passthrough();279 return passthrough()
270}280}
271281
272/**282/**
...@@ -277,18 +287,21 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {...@@ -277,18 +287,21 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
277 */287 */
278function sendToClient(client, message, transferrables = []) {288function sendToClient(client, message, transferrables = []) {
279 return new Promise((resolve, reject) => {289 return new Promise((resolve, reject) => {
280 const channel = new MessageChannel();290 const channel = new MessageChannel()
281291
282 channel.port1.onmessage = (event) => {292 channel.port1.onmessage = (event) => {
283 if (event.data && event.data.error) {293 if (event.data && event.data.error) {
284 return reject(event.data.error);294 return reject(event.data.error)
285 }295 }
286296
287 resolve(event.data);297 resolve(event.data)
288 };298 }
289299
290 client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);300 client.postMessage(message, [
291 });301 channel.port2,
302 ...transferrables.filter(Boolean),
303 ])
304 })
292}305}
293306
294/**307/**
...@@ -301,17 +314,17 @@ function respondWithMock(response) {...@@ -301,17 +314,17 @@ function respondWithMock(response) {
301 // instance will have status code set to 0. Since it's not possible to create314 // instance will have status code set to 0. Since it's not possible to create
302 // a Response instance with status code 0, handle that use-case separately.315 // a Response instance with status code 0, handle that use-case separately.
303 if (response.status === 0) {316 if (response.status === 0) {
304 return Response.error();317 return Response.error()
305 }318 }
306319
307 const mockedResponse = new Response(response.body, response);320 const mockedResponse = new Response(response.body, response)
308321
309 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {322 Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
310 value: true,323 value: true,
311 enumerable: true,324 enumerable: true,
312 });325 })
313326
314 return mockedResponse;327 return mockedResponse
315}328}
316329
317/**330/**
...@@ -332,5 +345,5 @@ async function serializeRequest(request) {...@@ -332,5 +345,5 @@ async function serializeRequest(request) {
332 referrerPolicy: request.referrerPolicy,345 referrerPolicy: request.referrerPolicy,
333 body: await request.arrayBuffer(),346 body: await request.arrayBuffer(),
334 keepalive: request.keepalive,347 keepalive: request.keepalive,
335 };348 }
336}349}