msw 2.2.4 → 2.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,13 +2,14 @@
2
2
  /* tslint:disable */
3
3
 
4
4
  /**
5
- * Mock Service Worker (2.2.4).
5
+ * Mock Service Worker.
6
6
  * @see https://github.com/mswjs/msw
7
7
  * - Please do NOT modify this file.
8
8
  * - Please do NOT serve this file on production.
9
9
  */
10
10
 
11
- const INTEGRITY_CHECKSUM = '223d191a56023cd36aa88c802961b911'
11
+ const PACKAGE_VERSION = '2.2.6'
12
+ const INTEGRITY_CHECKSUM = '26357c79639bfa20d64c0efca2a87423'
12
13
  const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
14
  const activeClientIds = new Set()
14
15
 
@@ -48,7 +49,10 @@ self.addEventListener('message', async function (event) {
48
49
  case 'INTEGRITY_CHECK_REQUEST': {
49
50
  sendToClient(client, {
50
51
  type: 'INTEGRITY_CHECK_RESPONSE',
51
- payload: INTEGRITY_CHECKSUM,
52
+ payload: {
53
+ packageVersion: PACKAGE_VERSION,
54
+ checksum: INTEGRITY_CHECKSUM,
55
+ },
52
56
  })
53
57
  break
54
58
  }
@@ -202,13 +206,6 @@ async function getResponse(event, client, requestId) {
202
206
  return passthrough()
203
207
  }
204
208
 
205
- // Bypass requests with the explicit bypass header.
206
- // Such requests can be issued by "ctx.fetch()".
207
- const mswIntention = request.headers.get('x-msw-intention')
208
- if (['bypass', 'passthrough'].includes(mswIntention)) {
209
- return passthrough()
210
- }
211
-
212
209
  // Notify the client that a request has been intercepted.
213
210
  const requestBuffer = await request.arrayBuffer()
214
211
  const clientMessage = await sendToClient(
@@ -240,7 +237,7 @@ async function getResponse(event, client, requestId) {
240
237
  return respondWithMock(clientMessage.data)
241
238
  }
242
239
 
243
- case 'MOCK_NOT_FOUND': {
240
+ case 'PASSTHROUGH': {
244
241
  return passthrough()
245
242
  }
246
243
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "msw",
3
- "version": "2.2.4",
3
+ "version": "2.2.6",
4
4
  "description": "Seamless REST/GraphQL API mocking library for browser and Node.js.",
5
5
  "main": "./lib/core/index.js",
6
6
  "module": "./lib/core/index.mjs",
@@ -73,10 +73,7 @@
73
73
  "url": "https://github.com/kettanaito"
74
74
  },
75
75
  "license": "MIT",
76
- "funding": {
77
- "type": "opencollective",
78
- "url": "https://opencollective.com/mswjs"
79
- },
76
+ "funding": "https://github.com/sponsors/mswjs",
80
77
  "files": [
81
78
  "config/constants.js",
82
79
  "config/scripts/postinstall.js",
@@ -54,7 +54,10 @@ export type ServiceWorkerIncomingResponse = Pick<
54
54
  */
55
55
  export interface ServiceWorkerIncomingEventsMap {
56
56
  MOCKING_ENABLED: boolean
57
- INTEGRITY_CHECK_RESPONSE: string
57
+ INTEGRITY_CHECK_RESPONSE: {
58
+ packageVersion: string
59
+ checksum: string
60
+ }
58
61
  KEEPALIVE_RESPONSE: never
59
62
  REQUEST: ServiceWorkerIncomingRequest
60
63
  RESPONSE: ServiceWorkerIncomingResponse
@@ -48,7 +48,7 @@ export const createRequestListener = (
48
48
  context.emitter,
49
49
  {
50
50
  onPassthroughResponse() {
51
- messageChannel.postMessage('NOT_FOUND')
51
+ messageChannel.postMessage('PASSTHROUGH')
52
52
  },
53
53
  async onMockedResponse(response, { handler, parsedResult }) {
54
54
  // Clone the mocked response so its body could be read
@@ -21,6 +21,8 @@ export function createResponseListener(context: SetupWorkerInternalContext) {
21
21
  const request = context.requests.get(requestId)!
22
22
  context.requests.delete(requestId)
23
23
 
24
+ console.log('RESPONSE LISTENER', responseJson, context.requests)
25
+
24
26
  /**
25
27
  * CORS requests with `mode: "no-cors"` result in "opaque" responses.
26
28
  * That kind of responses cannot be manipulated in JavaScript due
@@ -1,10 +1,9 @@
1
- import { until } from '@open-draft/until'
2
1
  import { devUtils } from '~/core/utils/internal/devUtils'
3
2
  import { getWorkerInstance } from './utils/getWorkerInstance'
4
3
  import { enableMocking } from './utils/enableMocking'
5
4
  import { SetupWorkerInternalContext, StartHandler } from '../glossary'
6
5
  import { createRequestListener } from './createRequestListener'
7
- import { requestIntegrityCheck } from '../../utils/requestIntegrityCheck'
6
+ import { checkWorkerIntegrity } from '../../utils/checkWorkerIntegrity'
8
7
  import { createResponseListener } from './createResponseListener'
9
8
  import { validateWorkerScope } from './utils/validateWorkerScope'
10
9
 
@@ -74,23 +73,14 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
74
73
  window.clearInterval(context.keepAliveInterval)
75
74
  })
76
75
 
77
- // Check if the active Service Worker is the latest published one
78
- const integrityCheckResult = await until(() =>
79
- requestIntegrityCheck(context, worker),
80
- )
81
-
82
- if (integrityCheckResult.error) {
83
- devUtils.error(`\
84
- Detected outdated Service Worker: ${integrityCheckResult.error.message}
85
-
86
- The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
87
-
88
- $ npx msw init <PUBLIC_DIR>
89
-
90
- This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
91
- If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
92
- `)
93
- }
76
+ // Check if the active Service Worker has been generated
77
+ // by the currently installed version of MSW.
78
+ await checkWorkerIntegrity(context).catch((error) => {
79
+ devUtils.error(
80
+ 'Error while checking the worker script integrity. Please report this on GitHub (https://github.com/mswjs/msw/issues), including the original error below.',
81
+ )
82
+ console.error(error)
83
+ })
94
84
 
95
85
  context.keepAliveInterval = window.setInterval(
96
86
  () => context.workerChannel.send('KEEPALIVE_REQUEST'),
@@ -16,7 +16,7 @@ interface WorkerChannelEventsMap {
16
16
  data: StringifiedResponse,
17
17
  transfer?: [ReadableStream<Uint8Array>],
18
18
  ]
19
- NOT_FOUND: []
19
+ PASSTHROUGH: []
20
20
  }
21
21
 
22
22
  export class WorkerChannel {
@@ -0,0 +1,34 @@
1
+ import { devUtils } from '~/core/utils/internal/devUtils'
2
+ import type { SetupWorkerInternalContext } from '../setupWorker/glossary'
3
+
4
+ /**
5
+ * Check whether the registered Service Worker has been
6
+ * generated by the installed version of the library.
7
+ * Prints a warning message if the worker scripts mismatch.
8
+ */
9
+ export async function checkWorkerIntegrity(
10
+ context: SetupWorkerInternalContext,
11
+ ): Promise<void> {
12
+ // Request the integrity checksum from the registered worker.
13
+ context.workerChannel.send('INTEGRITY_CHECK_REQUEST')
14
+
15
+ const { payload } = await context.events.once('INTEGRITY_CHECK_RESPONSE')
16
+
17
+ // Compare the response from the Service Worker and the
18
+ // global variable set during the build.
19
+
20
+ // The integrity is validated based on the worker script's checksum
21
+ // that's derived from its minified content during the build.
22
+ // The "SERVICE_WORKER_CHECKSUM" global variable is injected by the build.
23
+ if (payload.checksum !== SERVICE_WORKER_CHECKSUM) {
24
+ devUtils.warn(
25
+ `The currently registered Service Worker has been generated by a different version of MSW (${payload.packageVersion}) and may not be fully compatible with the installed version.
26
+
27
+ It's recommended you update your worker script by running this command:
28
+
29
+ \u2022 npx msw init <PUBLIC_DIR>
30
+
31
+ You can also automate this process and make the worker script update automatically upon the library installations. Read more: https://mswjs.io/docs/cli/init.`,
32
+ )
33
+ }
34
+ }
@@ -45,3 +45,25 @@ it('returns bypassed request given request instance', async () => {
45
45
  'x-msw-intention': 'bypass',
46
46
  })
47
47
  })
48
+
49
+ it('allows modifying the bypassed request instance', async () => {
50
+ const original = new Request('http://localhost/resource', {
51
+ method: 'POST',
52
+ body: 'hello world',
53
+ })
54
+ const request = bypass(original, {
55
+ method: 'PUT',
56
+ headers: { 'x-modified-header': 'yes' },
57
+ })
58
+
59
+ expect(request.method).toBe('PUT')
60
+ expect(Object.fromEntries(request.headers.entries())).toEqual({
61
+ 'x-msw-intention': 'bypass',
62
+ 'x-modified-header': 'yes',
63
+ })
64
+ expect(original.bodyUsed).toBe(false)
65
+ expect(request.bodyUsed).toBe(false)
66
+
67
+ expect(await request.text()).toBe('hello world')
68
+ expect(original.bodyUsed).toBe(false)
69
+ })
@@ -15,7 +15,15 @@ export type BypassRequestInput = string | URL | Request
15
15
  * @see {@link https://mswjs.io/docs/api/bypass `bypass()` API reference}
16
16
  */
17
17
  export function bypass(input: BypassRequestInput, init?: RequestInit): Request {
18
- const request = input instanceof Request ? input : new Request(input, init)
18
+ // Always create a new Request instance.
19
+ // This way, the "init" modifications will propagate
20
+ // to the bypass request instance automatically.
21
+ const request = new Request(
22
+ // If given a Request instance, clone it not to exhaust
23
+ // the original request's body.
24
+ input instanceof Request ? input.clone() : input,
25
+ init,
26
+ )
19
27
 
20
28
  invariant(
21
29
  !request.bodyUsed,
@@ -52,7 +52,7 @@ export async function handleRequest(
52
52
  ): Promise<Response | undefined> {
53
53
  emitter.emit('request:start', { request, requestId })
54
54
 
55
- // Perform bypassed requests (i.e. issued via "ctx.fetch") as-is.
55
+ // Perform bypassed requests (i.e. wrapped in "bypass()") as-is.
56
56
  if (request.headers.get('x-msw-intention') === 'bypass') {
57
57
  emitter.emit('request:end', { request, requestId })
58
58
  handleRequestOptions?.onPassthroughResponse?.(request)
@@ -2,12 +2,13 @@
2
2
  /* tslint:disable */
3
3
 
4
4
  /**
5
- * Mock Service Worker (<PACKAGE_VERSION>).
5
+ * Mock Service Worker.
6
6
  * @see https://github.com/mswjs/msw
7
7
  * - Please do NOT modify this file.
8
8
  * - Please do NOT serve this file on production.
9
9
  */
10
10
 
11
+ const PACKAGE_VERSION = '<PACKAGE_VERSION>'
11
12
  const INTEGRITY_CHECKSUM = '<INTEGRITY_CHECKSUM>'
12
13
  const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
14
  const activeClientIds = new Set()
@@ -48,7 +49,10 @@ self.addEventListener('message', async function (event) {
48
49
  case 'INTEGRITY_CHECK_REQUEST': {
49
50
  sendToClient(client, {
50
51
  type: 'INTEGRITY_CHECK_RESPONSE',
51
- payload: INTEGRITY_CHECKSUM,
52
+ payload: {
53
+ packageVersion: PACKAGE_VERSION,
54
+ checksum: INTEGRITY_CHECKSUM,
55
+ },
52
56
  })
53
57
  break
54
58
  }
@@ -202,13 +206,6 @@ async function getResponse(event, client, requestId) {
202
206
  return passthrough()
203
207
  }
204
208
 
205
- // Bypass requests with the explicit bypass header.
206
- // Such requests can be issued by "ctx.fetch()".
207
- const mswIntention = request.headers.get('x-msw-intention')
208
- if (['bypass', 'passthrough'].includes(mswIntention)) {
209
- return passthrough()
210
- }
211
-
212
209
  // Notify the client that a request has been intercepted.
213
210
  const requestBuffer = await request.arrayBuffer()
214
211
  const clientMessage = await sendToClient(
@@ -240,7 +237,7 @@ async function getResponse(event, client, requestId) {
240
237
  return respondWithMock(clientMessage.data)
241
238
  }
242
239
 
243
- case 'MOCK_NOT_FOUND': {
240
+ case 'PASSTHROUGH': {
244
241
  return passthrough()
245
242
  }
246
243
  }
@@ -1,23 +0,0 @@
1
- import type { SetupWorkerInternalContext } from '../setupWorker/glossary'
2
-
3
- export async function requestIntegrityCheck(
4
- context: SetupWorkerInternalContext,
5
- serviceWorker: ServiceWorker,
6
- ): Promise<ServiceWorker> {
7
- // Signal Service Worker to report back its integrity
8
- context.workerChannel.send('INTEGRITY_CHECK_REQUEST')
9
-
10
- const { payload: actualChecksum } = await context.events.once(
11
- 'INTEGRITY_CHECK_RESPONSE',
12
- )
13
-
14
- // Compare the response from the Service Worker and the
15
- // global variable set during the build.
16
- if (actualChecksum !== SERVICE_WORKER_CHECKSUM) {
17
- throw new Error(
18
- `Currently active Service Worker (${actualChecksum}) is behind the latest published one (${SERVICE_WORKER_CHECKSUM}).`,
19
- )
20
- }
21
-
22
- return serviceWorker
23
- }