This commit is contained in:
Nathan Bierema 2024-12-06 17:55:42 -05:00
parent 007f346abe
commit c55c14cbf8

View File

@ -8,8 +8,8 @@
* - Please do NOT serve this file on production. * - Please do NOT serve this file on production.
*/ */
const PACKAGE_VERSION = '2.4.7' const PACKAGE_VERSION = '2.6.7'
const INTEGRITY_CHECKSUM = '26357c79639bfa20d64c0efca2a87423' const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set() const activeClientIds = new Set()
@ -62,7 +62,12 @@ self.addEventListener('message', async function (event) {
sendToClient(client, { sendToClient(client, {
type: 'MOCKING_ENABLED', type: 'MOCKING_ENABLED',
payload: true, payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
}) })
break break
} }
@ -155,6 +160,10 @@ async function handleRequest(event, requestId) {
async function resolveMainClient(event) { async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId) const client = await self.clients.get(event.clientId)
if (activeClientIds.has(event.clientId)) {
return client
}
if (client?.frameType === 'top-level') { if (client?.frameType === 'top-level') {
return client return client
} }
@ -183,12 +192,26 @@ async function getResponse(event, client, requestId) {
const requestClone = request.clone() const requestClone = request.clone()
function passthrough() { function passthrough() {
const headers = Object.fromEntries(requestClone.headers.entries()) // Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)
// Remove internal MSW request header so the passthrough request // Remove the "accept" header value that marked this request as passthrough.
// complies with any potential CORS preflight checks on the server. // This prevents request alteration and also keeps it compliant with the
// Some servers forbid unknown request headers. // user-defined CORS policies.
delete headers['x-msw-intention'] const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)
if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}
return fetch(requestClone, { headers }) return fetch(requestClone, { headers })
} }