buster/apps/web/public/mockServiceWorker.js

302 lines
8.0 KiB
JavaScript
Raw Normal View History

2025-07-24 05:45:40 +08:00
/* tslint:disable */
2025-03-04 02:46:51 +08:00
/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/
2025-07-24 05:45:40 +08:00
const PACKAGE_VERSION = '2.7.3';
const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f';
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse');
const activeClientIds = new Set();
2025-03-04 02:46:51 +08:00
self.addEventListener('install', function () {
2025-07-24 05:45:40 +08:00
self.skipWaiting();
});
2025-03-04 02:46:51 +08:00
self.addEventListener('activate', function (event) {
2025-07-24 05:45:40 +08:00
event.waitUntil(self.clients.claim());
});
2025-03-04 02:46:51 +08:00
self.addEventListener('message', async function (event) {
2025-07-24 05:45:40 +08:00
const clientId = event.source.id;
2025-03-04 02:46:51 +08:00
if (!clientId || !self.clients) {
2025-07-24 05:45:40 +08:00
return;
2025-03-04 02:46:51 +08:00
}
2025-07-24 05:45:40 +08:00
const client = await self.clients.get(clientId);
2025-03-04 02:46:51 +08:00
if (!client) {
2025-07-24 05:45:40 +08:00
return;
2025-03-04 02:46:51 +08:00
}
const allClients = await self.clients.matchAll({
2025-07-24 05:45:40 +08:00
type: 'window'
});
2025-03-04 02:46:51 +08:00
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
2025-07-24 05:45:40 +08:00
type: 'KEEPALIVE_RESPONSE'
});
break;
2025-03-04 02:46:51 +08:00
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
2025-07-24 05:45:40 +08:00
checksum: INTEGRITY_CHECKSUM
}
});
break;
2025-03-04 02:46:51 +08:00
}
case 'MOCK_ACTIVATE': {
2025-07-24 05:45:40 +08:00
activeClientIds.add(clientId);
2025-03-04 02:46:51 +08:00
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
2025-07-24 05:45:40 +08:00
frameType: client.frameType
}
}
});
break;
2025-03-04 02:46:51 +08:00
}
case 'MOCK_DEACTIVATE': {
2025-07-24 05:45:40 +08:00
activeClientIds.delete(clientId);
break;
2025-03-04 02:46:51 +08:00
}
case 'CLIENT_CLOSED': {
2025-07-24 05:45:40 +08:00
activeClientIds.delete(clientId);
2025-03-04 02:46:51 +08:00
const remainingClients = allClients.filter((client) => {
2025-07-24 05:45:40 +08:00
return client.id !== clientId;
});
2025-03-04 02:46:51 +08:00
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
2025-07-24 05:45:40 +08:00
self.registration.unregister();
2025-03-04 02:46:51 +08:00
}
2025-07-24 05:45:40 +08:00
break;
2025-03-04 02:46:51 +08:00
}
}
2025-07-24 05:45:40 +08:00
});
2025-03-04 02:46:51 +08:00
self.addEventListener('fetch', function (event) {
2025-07-24 05:45:40 +08:00
const { request } = event;
2025-03-04 02:46:51 +08:00
// Bypass navigation requests.
if (request.mode === 'navigate') {
2025-07-24 05:45:40 +08:00
return;
2025-03-04 02:46:51 +08:00
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
2025-07-24 05:45:40 +08:00
return;
2025-03-04 02:46:51 +08:00
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been deleted (still remains active until the next reload).
if (activeClientIds.size === 0) {
2025-07-24 05:45:40 +08:00
return;
2025-03-04 02:46:51 +08:00
}
// Generate unique request ID.
2025-07-24 05:45:40 +08:00
const requestId = crypto.randomUUID();
event.respondWith(handleRequest(event, requestId));
});
2025-03-04 02:46:51 +08:00
async function handleRequest(event, requestId) {
2025-07-24 05:45:40 +08:00
const client = await resolveMainClient(event);
const response = await getResponse(event, client, requestId);
2025-03-04 02:46:51 +08:00
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
2025-07-24 05:45:40 +08:00
(async function () {
const responseClone = response.clone();
2025-03-04 02:46:51 +08:00
sendToClient(
client,
{
type: 'RESPONSE',
payload: {
requestId,
isMockedResponse: IS_MOCKED_RESPONSE in response,
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
body: responseClone.body,
2025-07-24 05:45:40 +08:00
headers: Object.fromEntries(responseClone.headers.entries())
}
2025-03-04 02:46:51 +08:00
},
2025-07-24 05:45:40 +08:00
[responseClone.body]
);
})();
2025-03-04 02:46:51 +08:00
}
2025-07-24 05:45:40 +08:00
return response;
2025-03-04 02:46:51 +08:00
}
// Resolve the main client for the given event.
// Client that issues a request doesn't necessarily equal the client
// that registered the worker. It's with the latter the worker should
// communicate with during the response resolving phase.
async function resolveMainClient(event) {
2025-07-24 05:45:40 +08:00
const client = await self.clients.get(event.clientId);
2025-03-04 02:46:51 +08:00
if (activeClientIds.has(event.clientId)) {
2025-07-24 05:45:40 +08:00
return client;
2025-03-04 02:46:51 +08:00
}
if (client?.frameType === 'top-level') {
2025-07-24 05:45:40 +08:00
return client;
2025-03-04 02:46:51 +08:00
}
const allClients = await self.clients.matchAll({
2025-07-24 05:45:40 +08:00
type: 'window'
});
2025-03-04 02:46:51 +08:00
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
2025-07-24 05:45:40 +08:00
return client.visibilityState === 'visible';
2025-03-04 02:46:51 +08:00
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
2025-07-24 05:45:40 +08:00
return activeClientIds.has(client.id);
});
2025-03-04 02:46:51 +08:00
}
async function getResponse(event, client, requestId) {
2025-07-24 05:45:40 +08:00
const { request } = event;
2025-03-04 02:46:51 +08:00
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
2025-07-24 05:45:40 +08:00
const requestClone = request.clone();
2025-03-04 02:46:51 +08:00
function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
2025-07-24 05:45:40 +08:00
const headers = new Headers(requestClone.headers);
2025-03-04 02:46:51 +08:00
// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
2025-07-24 05:45:40 +08:00
const acceptHeader = headers.get('accept');
2025-03-04 02:46:51 +08:00
if (acceptHeader) {
2025-07-24 05:45:40 +08:00
const values = acceptHeader.split(',').map((value) => value.trim());
const filteredValues = values.filter((value) => value !== 'msw/passthrough');
2025-03-04 02:46:51 +08:00
if (filteredValues.length > 0) {
2025-07-24 05:45:40 +08:00
headers.set('accept', filteredValues.join(', '));
2025-03-04 02:46:51 +08:00
} else {
2025-07-24 05:45:40 +08:00
headers.delete('accept');
2025-03-04 02:46:51 +08:00
}
}
2025-07-24 05:45:40 +08:00
return fetch(requestClone, { headers });
2025-03-04 02:46:51 +08:00
}
// Bypass mocking when the client is not active.
if (!client) {
2025-07-24 05:45:40 +08:00
return passthrough();
2025-03-04 02:46:51 +08:00
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
2025-07-24 05:45:40 +08:00
return passthrough();
2025-03-04 02:46:51 +08:00
}
// Notify the client that a request has been intercepted.
2025-07-24 05:45:40 +08:00
const requestBuffer = await request.arrayBuffer();
2025-03-04 02:46:51 +08:00
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: requestBuffer,
2025-07-24 05:45:40 +08:00
keepalive: request.keepalive
}
2025-03-04 02:46:51 +08:00
},
2025-07-24 05:45:40 +08:00
[requestBuffer]
);
2025-03-04 02:46:51 +08:00
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
2025-07-24 05:45:40 +08:00
return respondWithMock(clientMessage.data);
2025-03-04 02:46:51 +08:00
}
case 'PASSTHROUGH': {
2025-07-24 05:45:40 +08:00
return passthrough();
2025-03-04 02:46:51 +08:00
}
}
2025-07-24 05:45:40 +08:00
return passthrough();
2025-03-04 02:46:51 +08:00
}
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
2025-07-24 05:45:40 +08:00
const channel = new MessageChannel();
2025-03-04 02:46:51 +08:00
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
2025-07-24 05:45:40 +08:00
return reject(event.data.error);
2025-03-04 02:46:51 +08:00
}
2025-07-24 05:45:40 +08:00
resolve(event.data);
};
2025-03-04 02:46:51 +08:00
2025-07-24 05:45:40 +08:00
client.postMessage(message, [channel.port2].concat(transferrables.filter(Boolean)));
});
2025-03-04 02:46:51 +08:00
}
async function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
2025-07-24 05:45:40 +08:00
return Response.error();
2025-03-04 02:46:51 +08:00
}
2025-07-24 05:45:40 +08:00
const mockedResponse = new Response(response.body, response);
2025-03-04 02:46:51 +08:00
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
2025-07-24 05:45:40 +08:00
enumerable: true
});
2025-03-04 02:46:51 +08:00
2025-07-24 05:45:40 +08:00
return mockedResponse;
2025-03-04 02:46:51 +08:00
}