@bagaar/ember-graphql-mocking 0.3.0

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.
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+
4
+ ./node_modules/.bin/commitlint --edit "$1"
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+
2
+ ## v0.3.0 (2022-02-02)
3
+
4
+ #### :house: Internal
5
+ * [#16](https://github.com/Bagaar/ember-graphql-mocking/pull/16) Update publish config ([@bertdeblock](https://github.com/bertdeblock))
6
+
7
+ #### Committers: 1
8
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
9
+
10
+
11
+ ## v0.2.2 (2022-02-02)
12
+
13
+ #### :house: Internal
14
+ * [#14](https://github.com/Bagaar/ember-graphql-mocking/pull/14) Release setup ([@bertdeblock](https://github.com/bertdeblock))
15
+
16
+ #### Committers: 1
17
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
18
+
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # Ember GraphQL Mocking
2
+
3
+ [![CI](https://github.com/Bagaar/ember-graphql-mocking/workflows/CI/badge.svg)](https://github.com/Bagaar/ember-graphql-mocking/actions?query=workflow%3ACI)
4
+ [![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
5
+ [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
6
+
7
+ Ember addon for mocking GraphQL requests using [Mock Service Worker (MSW)](https://github.com/mswjs/msw).
8
+
9
+ > :warning: Experimental mocking package used at Bagaar. You probably shouldn't use this for now.
10
+
11
+ ## Compatibility
12
+
13
+ - Ember.js v3.24 or above (lower probably works as well, but isn't tested explicitly)
14
+ - Ember CLI v3.24 or above
15
+ - Node.js v12 or above
16
+
17
+ ## Installation
18
+
19
+ ```shell
20
+ ember install bagaar/ember-graphql-mocking#v0.1.1
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### 1. Set up Ember GraphQL Mocking
26
+
27
+ In `tests/test-helper.js`:
28
+ 1. Import `setupEmberGraphqlMocking`
29
+ 2. Import your GraphQL schema
30
+ 3. Call `setupEmberGraphqlMocking` with your GraphQL schema, _before_ calling `start`
31
+
32
+ ```javascript
33
+ // tests/test-helper.js
34
+
35
+ import Application from 'my-app/app';
36
+ import config from 'my-app/config/environment';
37
+ import * as QUnit from 'qunit';
38
+ import { setApplication } from '@ember/test-helpers';
39
+ import { setup } from 'qunit-dom';
40
+ import { start } from 'ember-qunit';
41
+ import { setupEmberGraphqlMocking } from '@bagaar/ember-graphql-mocking/test-support'; // 1.
42
+ import schema from 'my-app/graphql/schema'; // 2.
43
+
44
+ setApplication(Application.create(config.APP));
45
+
46
+ setup(QUnit.assert);
47
+
48
+ setupEmberGraphqlMocking(schema); // 3.
49
+
50
+ start();
51
+ ```
52
+
53
+ ### 2. Write an Acceptance Test
54
+
55
+ 1. Import `mockResolvers` and `setupGraphqlTest`
56
+ 2. Call `setupGraphqlTest` with `hooks`
57
+ 3. Call `mockResolvers` to mock the necessary resolver(s) per test
58
+
59
+ `setupGraphqlTest` will make sure that all resolvers are cleared in between tests.
60
+
61
+ `mockResolvers` accepts an object that consists of one or more resolvers. The key must be the name of the mocked operation, the value can either be a response object _or_ a function that returns a response object.
62
+
63
+ > **NOTE:** Make sure that your operations are named in order for `@bagaar/ember-graphql-mocking` to function properly.
64
+
65
+ ```javascript
66
+ // tests/acceptance/my-acceptance-test.js
67
+
68
+ import { module, test } from 'qunit';
69
+ import { visit, currentURL } from '@ember/test-helpers';
70
+ import { setupApplicationTest } from 'ember-qunit';
71
+ import { mockResolvers, setupGraphqlTest } from '@bagaar/ember-graphql-mocking/test-support'; // 1.
72
+
73
+ module('Acceptance | ember graphql mocking', function (hooks) {
74
+ setupApplicationTest(hooks);
75
+ setupGraphqlTest(hooks); // 2.
76
+
77
+ test('visiting /', async function (assert) {
78
+ mockResolvers({ // 3.
79
+ me: {
80
+ id: '1',
81
+ firstName: 'John',
82
+ lastName: 'Doe',
83
+ },
84
+ });
85
+
86
+ await visit('/');
87
+
88
+ assert.strictEqual(currentURL(), '/');
89
+
90
+ assert.dom('[data-test-me-id]').hasText('1');
91
+ assert.dom('[data-test-me-first-name]').hasText('John');
92
+ assert.dom('[data-test-me-last-name]').hasText('Doe');
93
+ });
94
+ });
95
+ ```
96
+
97
+ 💡 Working versions of these code examples can be found in [this addon's `tests` folder](./tests/).
98
+
99
+ ## Contributing
100
+
101
+ See the [Contributing](CONTRIBUTING.md) guide for details.
102
+
103
+ ## License
104
+
105
+ This project is licensed under the [MIT License](LICENSE.md).
package/RELEASE.md ADDED
@@ -0,0 +1,60 @@
1
+ # Release Process
2
+
3
+ Releases are mostly automated using
4
+ [release-it](https://github.com/release-it/release-it/) and
5
+ [lerna-changelog](https://github.com/lerna/lerna-changelog/).
6
+
7
+ ## Preparation
8
+
9
+ Since the majority of the actual release process is automated, the primary
10
+ remaining task prior to releasing is confirming that all pull requests that
11
+ have been merged since the last release have been labeled with the appropriate
12
+ `lerna-changelog` labels and the titles have been updated to ensure they
13
+ represent something that would make sense to our users. Some great information
14
+ on why this is important can be found at
15
+ [keepachangelog.com](https://keepachangelog.com/en/1.0.0/), but the overall
16
+ guiding principle here is that changelogs are for humans, not machines.
17
+
18
+ When reviewing merged PR's the labels to be used are:
19
+
20
+ * breaking - Used when the PR is considered a breaking change.
21
+ * enhancement - Used when the PR adds a new feature or enhancement.
22
+ * bug - Used when the PR fixes a bug included in a previous release.
23
+ * documentation - Used when the PR adds or updates documentation.
24
+ * internal - Used for internal changes that still require a mention in the
25
+ changelog/release notes.
26
+
27
+ ## Release
28
+
29
+ Once the prep work is completed, the actual release is straight forward:
30
+
31
+ * First, ensure that you have installed your projects dependencies:
32
+
33
+ ```sh
34
+ yarn install
35
+ ```
36
+
37
+ * Second, ensure that you have obtained a
38
+ [GitHub personal access token][generate-token] with the `repo` scope (no
39
+ other permissions are needed). Make sure the token is available as the
40
+ `GITHUB_AUTH` environment variable.
41
+
42
+ For instance:
43
+
44
+ ```bash
45
+ export GITHUB_AUTH=abc123def456
46
+ ```
47
+
48
+ [generate-token]: https://github.com/settings/tokens/new?scopes=repo&description=GITHUB_AUTH+env+variable
49
+
50
+ * And last (but not least 😁) do your release.
51
+
52
+ ```sh
53
+ npx release-it
54
+ ```
55
+
56
+ [release-it](https://github.com/release-it/release-it/) manages the actual
57
+ release process. It will prompt you to to choose the version number after which
58
+ you will have the chance to hand tweak the changelog to be used (for the
59
+ `CHANGELOG.md` and GitHub release), then `release-it` continues on to tagging,
60
+ pushing the tag and commits, etc.
@@ -0,0 +1,82 @@
1
+ import { assert } from '@ember/debug';
2
+ import { buildASTSchema, graphql } from 'graphql';
3
+ import { graphql as mswGraphql, setupWorker } from 'msw';
4
+ import { done as qunitDone } from 'qunit';
5
+
6
+ const IS_TESTEM = Boolean(window.Testem);
7
+ const DEFAULT_OPTIONS = {
8
+ quiet: IS_TESTEM,
9
+ scope: IS_TESTEM ? window.location.pathname : '/tests',
10
+ };
11
+
12
+ let isSetupGraphqlTestCalled = false;
13
+ let root = null;
14
+ let worker = null;
15
+
16
+ export function setupEmberGraphqlMocking(schemaDocument, providedOptions) {
17
+ const options = {
18
+ ...DEFAULT_OPTIONS,
19
+ ...providedOptions,
20
+ };
21
+
22
+ createWorker(options);
23
+ createGraphqlOperationHandler(schemaDocument);
24
+ qunitDone(destroyWorker);
25
+ }
26
+
27
+ export function setupGraphqlTest(hooks) {
28
+ hooks.before(() => (isSetupGraphqlTestCalled = true));
29
+ hooks.after(() => (isSetupGraphqlTestCalled = false));
30
+ hooks.afterEach(clearRoot);
31
+ }
32
+
33
+ export function mockResolvers(resolvers) {
34
+ assert(
35
+ 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',
36
+ isSetupGraphqlTestCalled
37
+ );
38
+
39
+ root = { ...root, ...resolvers };
40
+ }
41
+
42
+ export function getWorker() {
43
+ return worker;
44
+ }
45
+
46
+ function createWorker(options) {
47
+ worker = setupWorker();
48
+
49
+ worker.start({
50
+ quiet: options.quiet,
51
+ serviceWorker: {
52
+ options: {
53
+ scope: options.scope,
54
+ },
55
+ },
56
+ });
57
+ }
58
+
59
+ function destroyWorker() {
60
+ worker.stop();
61
+ worker = null;
62
+ }
63
+
64
+ function createGraphqlOperationHandler(schemaDocument) {
65
+ const schema = buildASTSchema(schemaDocument);
66
+ const graphqlOperation = mswGraphql.operation(async (req, res, ctx) => {
67
+ const queryResult = await graphql({
68
+ rootValue: root,
69
+ schema,
70
+ source: req.body.query,
71
+ variableValues: req.variables,
72
+ });
73
+
74
+ return res(ctx.data(queryResult.data), ctx.errors(queryResult.errors));
75
+ });
76
+
77
+ worker.use(graphqlOperation);
78
+ }
79
+
80
+ function clearRoot() {
81
+ root = null;
82
+ }
@@ -0,0 +1,5 @@
1
+ 'use strict';
2
+
3
+ module.exports = function (/* environment, appConfig */) {
4
+ return {};
5
+ };
package/index.js ADDED
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ const funnel = require('broccoli-funnel');
4
+ const mergeTrees = require('broccoli-merge-trees');
5
+
6
+ module.exports = {
7
+ name: require('./package').name,
8
+
9
+ treeForPublic(tree) {
10
+ const host = this._findHost();
11
+ const shouldExcludePublicFiles = host.env === 'production';
12
+
13
+ if (shouldExcludePublicFiles) {
14
+ return;
15
+ }
16
+
17
+ return mergeTrees([tree, funnel(host.trees.public)], {
18
+ overwrite: true,
19
+ });
20
+ },
21
+ };
package/package.json ADDED
@@ -0,0 +1,117 @@
1
+ {
2
+ "name": "@bagaar/ember-graphql-mocking",
3
+ "version": "0.3.0",
4
+ "description": "Ember addon for mocking GraphQL requests using Mock Service Worker (MSW).",
5
+ "keywords": [
6
+ "ember-addon"
7
+ ],
8
+ "repository": "https://github.com/Bagaar/ember-graphql-mocking",
9
+ "license": "MIT",
10
+ "author": "Bagaar",
11
+ "directories": {
12
+ "doc": "doc",
13
+ "test": "tests"
14
+ },
15
+ "scripts": {
16
+ "build": "ember build --environment=production",
17
+ "lint": "npm-run-all --aggregate-output --continue-on-error --parallel \"lint:!(fix)\"",
18
+ "lint:fix": "npm-run-all --aggregate-output --continue-on-error --parallel lint:*:fix",
19
+ "lint:hbs": "ember-template-lint .",
20
+ "lint:hbs:fix": "ember-template-lint . --fix",
21
+ "lint:js": "eslint . --cache",
22
+ "lint:js:fix": "eslint . --fix",
23
+ "prepare": "husky install",
24
+ "start": "ember serve",
25
+ "test": "npm-run-all lint test:*",
26
+ "test:ember": "ember test",
27
+ "test:ember-compatibility": "ember try:each"
28
+ },
29
+ "commitlint": {
30
+ "extends": [
31
+ "@commitlint/config-conventional"
32
+ ]
33
+ },
34
+ "dependencies": {
35
+ "broccoli-funnel": "^3.0.5",
36
+ "broccoli-merge-trees": "^4.2.0",
37
+ "ember-auto-import": "^2.2.4",
38
+ "ember-cli-babel": "^7.26.11",
39
+ "graphql": "^16.3.0",
40
+ "msw": "0.36.7",
41
+ "qunit": "^2.17.2"
42
+ },
43
+ "devDependencies": {
44
+ "@commitlint/cli": "^16.1.0",
45
+ "@commitlint/config-conventional": "^16.0.0",
46
+ "@ember/optional-features": "^2.0.0",
47
+ "@ember/test-helpers": "^2.6.0",
48
+ "@embroider/test-setup": "^1.0.0",
49
+ "@glimmer/component": "^1.0.4",
50
+ "@glimmer/tracking": "^1.0.4",
51
+ "babel-eslint": "^10.1.0",
52
+ "broccoli-asset-rev": "^3.0.0",
53
+ "ember-apollo-client": "^3.1.1",
54
+ "ember-cli": "~4.1.1",
55
+ "ember-cli-dependency-checker": "^3.2.0",
56
+ "ember-cli-htmlbars": "^6.0.1",
57
+ "ember-cli-inject-live-reload": "^2.1.0",
58
+ "ember-cli-sri": "^2.1.1",
59
+ "ember-cli-terser": "^4.0.2",
60
+ "ember-disable-prototype-extensions": "^1.1.3",
61
+ "ember-export-application-global": "^2.0.1",
62
+ "ember-fetch": "^8.0.4",
63
+ "ember-load-initializers": "^2.1.2",
64
+ "ember-page-title": "^7.0.0",
65
+ "ember-qunit": "^5.1.5",
66
+ "ember-resolver": "^8.0.3",
67
+ "ember-source": "~4.1.0",
68
+ "ember-source-channel-url": "^3.0.0",
69
+ "ember-template-lint": "^4.0.0",
70
+ "ember-try": "^2.0.0",
71
+ "eslint": "^7.32.0",
72
+ "eslint-config-prettier": "^8.3.0",
73
+ "eslint-plugin-ember": "^10.5.8",
74
+ "eslint-plugin-node": "^11.1.0",
75
+ "eslint-plugin-prettier": "^4.0.0",
76
+ "eslint-plugin-qunit": "^7.2.0",
77
+ "husky": "^7.0.4",
78
+ "loader.js": "^4.7.0",
79
+ "npm-run-all": "^4.1.5",
80
+ "prettier": "^2.5.1",
81
+ "qunit-dom": "^2.0.0",
82
+ "release-it": "^14.2.1",
83
+ "release-it-lerna-changelog": "^4.0.1",
84
+ "webpack": "^5.65.0"
85
+ },
86
+ "engines": {
87
+ "node": "12.* || 14.* || >= 16"
88
+ },
89
+ "publishConfig": {
90
+ "access": "public",
91
+ "registry": "https://registry.npmjs.org"
92
+ },
93
+ "ember": {
94
+ "edition": "octane"
95
+ },
96
+ "ember-addon": {
97
+ "configPath": "tests/dummy/config"
98
+ },
99
+ "msw": {
100
+ "workerDirectory": "public"
101
+ },
102
+ "release-it": {
103
+ "plugins": {
104
+ "release-it-lerna-changelog": {
105
+ "infile": "CHANGELOG.md",
106
+ "launchEditor": false
107
+ }
108
+ },
109
+ "git": {
110
+ "tagName": "v${version}"
111
+ },
112
+ "github": {
113
+ "release": true,
114
+ "tokenRef": "GITHUB_AUTH"
115
+ }
116
+ }
117
+ }
@@ -0,0 +1,338 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+
4
+ /**
5
+ * Mock Service Worker (0.36.7).
6
+ * @see https://github.com/mswjs/msw
7
+ * - Please do NOT modify this file.
8
+ * - Please do NOT serve this file on production.
9
+ */
10
+
11
+ const INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'
12
+ const bypassHeaderName = 'x-msw-bypass'
13
+ const activeClientIds = new Set()
14
+
15
+ self.addEventListener('install', function () {
16
+ return self.skipWaiting()
17
+ })
18
+
19
+ self.addEventListener('activate', async function (event) {
20
+ return self.clients.claim()
21
+ })
22
+
23
+ self.addEventListener('message', async function (event) {
24
+ const clientId = 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
+
38
+ switch (event.data) {
39
+ case 'KEEPALIVE_REQUEST': {
40
+ sendToClient(client, {
41
+ type: 'KEEPALIVE_RESPONSE',
42
+ })
43
+ break
44
+ }
45
+
46
+ case 'INTEGRITY_CHECK_REQUEST': {
47
+ sendToClient(client, {
48
+ type: 'INTEGRITY_CHECK_RESPONSE',
49
+ payload: INTEGRITY_CHECKSUM,
50
+ })
51
+ break
52
+ }
53
+
54
+ case 'MOCK_ACTIVATE': {
55
+ activeClientIds.add(clientId)
56
+
57
+ sendToClient(client, {
58
+ type: 'MOCKING_ENABLED',
59
+ payload: true,
60
+ })
61
+ break
62
+ }
63
+
64
+ case 'MOCK_DEACTIVATE': {
65
+ activeClientIds.delete(clientId)
66
+ break
67
+ }
68
+
69
+ case 'CLIENT_CLOSED': {
70
+ activeClientIds.delete(clientId)
71
+
72
+ const remainingClients = allClients.filter((client) => {
73
+ return client.id !== clientId
74
+ })
75
+
76
+ // Unregister itself when there are no more clients
77
+ if (remainingClients.length === 0) {
78
+ self.registration.unregister()
79
+ }
80
+
81
+ break
82
+ }
83
+ }
84
+ })
85
+
86
+ // Resolve the "main" client for the given event.
87
+ // Client that issues a request doesn't necessarily equal the client
88
+ // that registered the worker. It's with the latter the worker should
89
+ // communicate with during the response resolving phase.
90
+ async function resolveMainClient(event) {
91
+ const client = await self.clients.get(event.clientId)
92
+
93
+ if (client.frameType === 'top-level') {
94
+ return client
95
+ }
96
+
97
+ const allClients = await self.clients.matchAll()
98
+
99
+ return allClients
100
+ .filter((client) => {
101
+ // Get only those clients that are currently visible.
102
+ return client.visibilityState === 'visible'
103
+ })
104
+ .find((client) => {
105
+ // Find the client ID that's recorded in the
106
+ // set of clients that have registered the worker.
107
+ return activeClientIds.has(client.id)
108
+ })
109
+ }
110
+
111
+ async function handleRequest(event, requestId) {
112
+ const client = await resolveMainClient(event)
113
+ const response = await getResponse(event, client, requestId)
114
+
115
+ // Send back the response clone for the "response:*" life-cycle events.
116
+ // Ensure MSW is active and ready to handle the message, otherwise
117
+ // this message will pend indefinitely.
118
+ if (client && activeClientIds.has(client.id)) {
119
+ ;(async function () {
120
+ const clonedResponse = response.clone()
121
+ sendToClient(client, {
122
+ type: 'RESPONSE',
123
+ payload: {
124
+ requestId,
125
+ type: clonedResponse.type,
126
+ ok: clonedResponse.ok,
127
+ status: clonedResponse.status,
128
+ statusText: clonedResponse.statusText,
129
+ body:
130
+ clonedResponse.body === null ? null : await clonedResponse.text(),
131
+ headers: serializeHeaders(clonedResponse.headers),
132
+ redirected: clonedResponse.redirected,
133
+ },
134
+ })
135
+ })()
136
+ }
137
+
138
+ return response
139
+ }
140
+
141
+ async function getResponse(event, client, requestId) {
142
+ const { request } = event
143
+ const requestClone = request.clone()
144
+ const getOriginalResponse = () => fetch(requestClone)
145
+
146
+ // Bypass mocking when the request client is not active.
147
+ if (!client) {
148
+ return getOriginalResponse()
149
+ }
150
+
151
+ // Bypass initial page load requests (i.e. static assets).
152
+ // The absence of the immediate/parent client in the map of the active clients
153
+ // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
154
+ // and is not ready to handle requests.
155
+ if (!activeClientIds.has(client.id)) {
156
+ return await getOriginalResponse()
157
+ }
158
+
159
+ // Bypass requests with the explicit bypass header
160
+ if (requestClone.headers.get(bypassHeaderName) === 'true') {
161
+ const cleanRequestHeaders = serializeHeaders(requestClone.headers)
162
+
163
+ // Remove the bypass header to comply with the CORS preflight check.
164
+ delete cleanRequestHeaders[bypassHeaderName]
165
+
166
+ const originalRequest = new Request(requestClone, {
167
+ headers: new Headers(cleanRequestHeaders),
168
+ })
169
+
170
+ return fetch(originalRequest)
171
+ }
172
+
173
+ // Send the request to the client-side MSW.
174
+ const reqHeaders = serializeHeaders(request.headers)
175
+ const body = await request.text()
176
+
177
+ const clientMessage = await sendToClient(client, {
178
+ type: 'REQUEST',
179
+ payload: {
180
+ id: requestId,
181
+ url: request.url,
182
+ method: request.method,
183
+ headers: reqHeaders,
184
+ cache: request.cache,
185
+ mode: request.mode,
186
+ credentials: request.credentials,
187
+ destination: request.destination,
188
+ integrity: request.integrity,
189
+ redirect: request.redirect,
190
+ referrer: request.referrer,
191
+ referrerPolicy: request.referrerPolicy,
192
+ body,
193
+ bodyUsed: request.bodyUsed,
194
+ keepalive: request.keepalive,
195
+ },
196
+ })
197
+
198
+ switch (clientMessage.type) {
199
+ case 'MOCK_SUCCESS': {
200
+ return delayPromise(
201
+ () => respondWithMock(clientMessage),
202
+ clientMessage.payload.delay,
203
+ )
204
+ }
205
+
206
+ case 'MOCK_NOT_FOUND': {
207
+ return getOriginalResponse()
208
+ }
209
+
210
+ case 'NETWORK_ERROR': {
211
+ const { name, message } = clientMessage.payload
212
+ const networkError = new Error(message)
213
+ networkError.name = name
214
+
215
+ // Rejecting a request Promise emulates a network error.
216
+ throw networkError
217
+ }
218
+
219
+ case 'INTERNAL_ERROR': {
220
+ const parsedBody = JSON.parse(clientMessage.payload.body)
221
+
222
+ console.error(
223
+ `\
224
+ [MSW] Uncaught exception in the request handler for "%s %s":
225
+
226
+ ${parsedBody.location}
227
+
228
+ This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
229
+ `,
230
+ request.method,
231
+ request.url,
232
+ )
233
+
234
+ return respondWithMock(clientMessage)
235
+ }
236
+ }
237
+
238
+ return getOriginalResponse()
239
+ }
240
+
241
+ self.addEventListener('fetch', function (event) {
242
+ const { request } = event
243
+ const accept = request.headers.get('accept') || ''
244
+
245
+ // Bypass server-sent events.
246
+ if (accept.includes('text/event-stream')) {
247
+ return
248
+ }
249
+
250
+ // Bypass navigation requests.
251
+ if (request.mode === 'navigate') {
252
+ return
253
+ }
254
+
255
+ // Opening the DevTools triggers the "only-if-cached" request
256
+ // that cannot be handled by the worker. Bypass such requests.
257
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
258
+ return
259
+ }
260
+
261
+ // Bypass all requests when there are no active clients.
262
+ // Prevents the self-unregistered worked from handling requests
263
+ // after it's been deleted (still remains active until the next reload).
264
+ if (activeClientIds.size === 0) {
265
+ return
266
+ }
267
+
268
+ const requestId = uuidv4()
269
+
270
+ return event.respondWith(
271
+ handleRequest(event, requestId).catch((error) => {
272
+ if (error.name === 'NetworkError') {
273
+ console.warn(
274
+ '[MSW] Successfully emulated a network error for the "%s %s" request.',
275
+ request.method,
276
+ request.url,
277
+ )
278
+ return
279
+ }
280
+
281
+ // At this point, any exception indicates an issue with the original request/response.
282
+ console.error(
283
+ `\
284
+ [MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
285
+ request.method,
286
+ request.url,
287
+ `${error.name}: ${error.message}`,
288
+ )
289
+ }),
290
+ )
291
+ })
292
+
293
+ function serializeHeaders(headers) {
294
+ const reqHeaders = {}
295
+ headers.forEach((value, name) => {
296
+ reqHeaders[name] = reqHeaders[name]
297
+ ? [].concat(reqHeaders[name]).concat(value)
298
+ : value
299
+ })
300
+ return reqHeaders
301
+ }
302
+
303
+ function sendToClient(client, message) {
304
+ return new Promise((resolve, reject) => {
305
+ const channel = new MessageChannel()
306
+
307
+ channel.port1.onmessage = (event) => {
308
+ if (event.data && event.data.error) {
309
+ return reject(event.data.error)
310
+ }
311
+
312
+ resolve(event.data)
313
+ }
314
+
315
+ client.postMessage(JSON.stringify(message), [channel.port2])
316
+ })
317
+ }
318
+
319
+ function delayPromise(cb, duration) {
320
+ return new Promise((resolve) => {
321
+ setTimeout(() => resolve(cb()), duration)
322
+ })
323
+ }
324
+
325
+ function respondWithMock(clientMessage) {
326
+ return new Response(clientMessage.payload.body, {
327
+ ...clientMessage.payload,
328
+ headers: clientMessage.payload.headers,
329
+ })
330
+ }
331
+
332
+ function uuidv4() {
333
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
334
+ const r = (Math.random() * 16) | 0
335
+ const v = c == 'x' ? r : (r & 0x3) | 0x8
336
+ return v.toString(16)
337
+ })
338
+ }