@bagaar/ember-graphql-mocking 0.8.0 → 0.10.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,41 @@
5
5
 
6
6
 
7
7
 
8
+
9
+
10
+ ## v0.10.0 (2024-02-08)
11
+
12
+ #### :boom: Breaking Change
13
+ * [#195](https://github.com/Bagaar/ember-graphql-mocking/pull/195) Remove automatic inclusion/exclusion of msw's worker file ([@bertdeblock](https://github.com/bertdeblock))
14
+ * [#194](https://github.com/Bagaar/ember-graphql-mocking/pull/194) Convert to TS ([@bertdeblock](https://github.com/bertdeblock))
15
+ * [#193](https://github.com/Bagaar/ember-graphql-mocking/pull/193) Don't leak msw `worker.start` return value ([@bertdeblock](https://github.com/bertdeblock))
16
+
17
+ #### :rocket: Enhancement
18
+ * [#194](https://github.com/Bagaar/ember-graphql-mocking/pull/194) Convert to TS ([@bertdeblock](https://github.com/bertdeblock))
19
+
20
+ #### :bug: Bug Fix
21
+ * [#193](https://github.com/Bagaar/ember-graphql-mocking/pull/193) Don't leak msw `worker.start` return value ([@bertdeblock](https://github.com/bertdeblock))
22
+
23
+ #### Committers: 1
24
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
25
+
26
+ ## v0.9.0 (2023-11-27)
27
+
28
+ #### :boom: Breaking Change
29
+ * [#191](https://github.com/Bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
30
+ * [#189](https://github.com/Bagaar/ember-graphql-mocking/pull/189) Drop support for Ember v4.4 ([@bertdeblock](https://github.com/bertdeblock))
31
+ * [#177](https://github.com/Bagaar/ember-graphql-mocking/pull/177) Drop support for Node.js v16 ([@bertdeblock](https://github.com/bertdeblock))
32
+
33
+ #### :rocket: Enhancement
34
+ * [#191](https://github.com/Bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
35
+
36
+ #### :house: Internal
37
+ * [#176](https://github.com/Bagaar/ember-graphql-mocking/pull/176) Update dependencies ([@bertdeblock](https://github.com/bertdeblock))
38
+ * [#175](https://github.com/Bagaar/ember-graphql-mocking/pull/175) Update to Ember v5.4 ([@bertdeblock](https://github.com/bertdeblock))
39
+
40
+ #### Committers: 1
41
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
42
+
8
43
  ## v0.8.0 (2023-07-06)
9
44
 
10
45
  #### :boom: Breaking Change
package/README.md CHANGED
@@ -1,17 +1,16 @@
1
1
  # Ember GraphQL Mocking
2
2
 
3
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)
4
+ [![NPM Version](https://badge.fury.io/js/%40bagaar%2Fember-graphql-mocking.svg)](https://badge.fury.io/js/%40bagaar%2Fember-graphql-mocking)
6
5
 
7
6
  Ember addon for mocking GraphQL requests using [Mock Service Worker (MSW)](https://github.com/mswjs/msw).
8
7
 
9
8
  ## Compatibility
10
9
 
11
- - Ember.js v4.4 or above
12
- - Ember CLI v4.4 or above
13
- - Node.js v16 or above
14
- - MSW v1 or above
10
+ - Ember.js v4.8 or above
11
+ - Ember CLI v4.8 or above
12
+ - Node.js v18 or above
13
+ - MSW v2 or above
15
14
 
16
15
  ## Installation
17
16
 
@@ -57,7 +56,8 @@ setup(QUnit.assert);
57
56
  start();
58
57
  ```
59
58
 
60
- > **NOTE:** Make sure to use `QUnit.begin`, as `setupEmberGraphqlMocking` returns a Promise.
59
+ > [!NOTE]
60
+ > Make sure to use `QUnit.begin`, as `setupEmberGraphqlMocking` returns a Promise.
61
61
 
62
62
  If you want to pass along additional [start options](https://mswjs.io/docs/api/setup-worker/start#options)
63
63
  to MSW's service worker, you can do so by defining an `mswStartOptions` object:
@@ -82,7 +82,8 @@ QUnit.begin(() =>
82
82
 
83
83
  `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.
84
84
 
85
- > **NOTE:** Make sure that your operations are [named](https://graphql.org/learn/queries/#operation-name) in order for `@bagaar/ember-graphql-mocking` to function properly.
85
+ > [!NOTE]
86
+ > Make sure that your operations are [named](https://graphql.org/learn/queries/#operation-name) in order for `@bagaar/ember-graphql-mocking` to function properly.
86
87
 
87
88
  ```javascript
88
89
  // tests/acceptance/my-acceptance-test.js
@@ -116,9 +117,11 @@ module('Acceptance | ember graphql mocking', function (hooks) {
116
117
  });
117
118
  ```
118
119
 
119
- > **NOTE:** Calling `mockResolvers` multiple times within a single test, will simply merge all resolvers into a single root.
120
+ > [!NOTE]
121
+ > Calling `mockResolvers` multiple times within a single test, will simply merge all resolvers into a single root.
120
122
 
121
- 💡 Working versions of these code examples can be found in [this addon's `tests` folder](./tests/).
123
+ > [!NOTE]
124
+ > Working versions of these code examples can be found in [this addon's `tests` folder](./tests/).
122
125
 
123
126
  ## Contributing
124
127
 
@@ -0,0 +1,125 @@
1
+ import { assert } from '@ember/debug';
2
+ import { type setupApplicationTest } from 'ember-qunit';
3
+ import { buildASTSchema, graphql, type DocumentNode } from 'graphql';
4
+ import merge from 'lodash.merge';
5
+ import { graphql as mswGraphql, HttpResponse } from 'msw';
6
+ import { setupWorker, type SetupWorker, type StartOptions } from 'msw/browser';
7
+
8
+ interface Options {
9
+ mswStartOptions: StartOptions;
10
+ }
11
+
12
+ type WindowWithTestem = typeof window & { Testem: unknown };
13
+
14
+ const IS_TESTEM = Boolean((window as WindowWithTestem).Testem);
15
+ const DEFAULT_OPTIONS: Options = {
16
+ mswStartOptions: {
17
+ quiet: IS_TESTEM,
18
+ serviceWorker: {
19
+ options: {
20
+ scope: IS_TESTEM ? window.location.pathname : '/tests',
21
+ },
22
+ },
23
+ },
24
+ };
25
+
26
+ let isSetupGraphqlTestCalled = false;
27
+ let root: object | null = null;
28
+ let worker: SetupWorker | null = null;
29
+
30
+ export async function setupEmberGraphqlMocking(
31
+ schemaDocument: DocumentNode,
32
+ providedOptions?: Options,
33
+ ) {
34
+ const options = merge({}, DEFAULT_OPTIONS, providedOptions);
35
+
36
+ createWorker();
37
+ createGraphqlOperationHandler(schemaDocument);
38
+
39
+ await startWorker(options.mswStartOptions);
40
+ }
41
+
42
+ export function setupGraphqlTest(
43
+ hooks: Parameters<typeof setupApplicationTest>[0],
44
+ ) {
45
+ assert(
46
+ 'Cannot call `setupGraphqlTest` without providing the `hooks` argument. Please make sure to call `setupGraphqlTest(hooks);`.',
47
+ hooks,
48
+ );
49
+
50
+ hooks.before(() => {
51
+ isSetupGraphqlTestCalled = true;
52
+ });
53
+
54
+ hooks.after(() => {
55
+ isSetupGraphqlTestCalled = false;
56
+ });
57
+
58
+ hooks.afterEach(clearRoot);
59
+ }
60
+
61
+ export function mockResolvers(resolvers: object) {
62
+ assert(
63
+ 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',
64
+ isSetupGraphqlTestCalled,
65
+ );
66
+
67
+ root = { ...root, ...resolvers };
68
+ }
69
+
70
+ export function getWorker() {
71
+ assert(
72
+ 'Cannot call `getWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',
73
+ worker,
74
+ );
75
+
76
+ return worker;
77
+ }
78
+
79
+ export function destroyWorker() {
80
+ assert(
81
+ 'Cannot call `destroyWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',
82
+ worker,
83
+ );
84
+
85
+ worker.stop();
86
+
87
+ worker = null;
88
+ }
89
+
90
+ function createWorker() {
91
+ worker = setupWorker();
92
+ }
93
+
94
+ function createGraphqlOperationHandler(schemaDocument: DocumentNode) {
95
+ assert('[BUG] `worker` is not set.', worker);
96
+
97
+ const schema = buildASTSchema(schemaDocument);
98
+ const graphqlOperation = mswGraphql.operation(async ({ request }) => {
99
+ const { query, variables } = (await request.json()) || {
100
+ query: '',
101
+ variables: {},
102
+ };
103
+
104
+ const { data, errors } = await graphql({
105
+ rootValue: root,
106
+ schema,
107
+ source: query,
108
+ variableValues: variables,
109
+ });
110
+
111
+ return HttpResponse.json({ data, errors });
112
+ });
113
+
114
+ worker.use(graphqlOperation);
115
+ }
116
+
117
+ async function startWorker(mswStartOptions: Options['mswStartOptions']) {
118
+ assert('[BUG] `worker` is not set.', worker);
119
+
120
+ await worker.start(mswStartOptions);
121
+ }
122
+
123
+ function clearRoot() {
124
+ root = null;
125
+ }
@@ -0,0 +1,13 @@
1
+ import { type setupApplicationTest } from 'ember-qunit';
2
+ import { type DocumentNode } from 'graphql';
3
+ import { type SetupWorker, type StartOptions } from 'msw/browser';
4
+ interface Options {
5
+ mswStartOptions: StartOptions;
6
+ }
7
+ export declare function setupEmberGraphqlMocking(schemaDocument: DocumentNode, providedOptions?: Options): Promise<void>;
8
+ export declare function setupGraphqlTest(hooks: Parameters<typeof setupApplicationTest>[0]): void;
9
+ export declare function mockResolvers(resolvers: object): void;
10
+ export declare function getWorker(): SetupWorker;
11
+ export declare function destroyWorker(): void;
12
+ export {};
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../addon-test-support/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAA2B,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AAGrE,OAAO,EAAe,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/E,UAAU,OAAO;IACf,eAAe,EAAE,YAAY,CAAC;CAC/B;AAoBD,wBAAsB,wBAAwB,CAC5C,cAAc,EAAE,YAAY,EAC5B,eAAe,CAAC,EAAE,OAAO,iBAQ1B;AAED,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,QAgBlD;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,QAO9C;AAED,wBAAgB,SAAS,gBAOxB;AAED,wBAAgB,aAAa,SAS5B"}
package/index.js CHANGED
@@ -3,19 +3,9 @@
3
3
  module.exports = {
4
4
  name: require('./package').name,
5
5
 
6
- treeForPublic(tree) {
7
- const host = this._findHost();
8
- const shouldExcludePublicFiles = host.env === 'production';
9
-
10
- if (shouldExcludePublicFiles) {
11
- return;
12
- }
13
-
14
- const funnel = require('broccoli-funnel');
15
- const mergeTrees = require('broccoli-merge-trees');
16
-
17
- return mergeTrees([tree, funnel(host.trees.public)], {
18
- overwrite: true,
19
- });
6
+ options: {
7
+ 'ember-cli-babel': {
8
+ enableTypeScriptTransform: true,
9
+ },
20
10
  },
21
11
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bagaar/ember-graphql-mocking",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Ember addon for mocking GraphQL requests using Mock Service Worker (MSW).",
5
5
  "keywords": [
6
6
  "ember-addon"
@@ -8,6 +8,21 @@
8
8
  "repository": "https://github.com/Bagaar/ember-graphql-mocking",
9
9
  "license": "MIT",
10
10
  "author": "Bagaar",
11
+ "typesVersions": {
12
+ "*": {
13
+ "test-support": [
14
+ "declarations/addon-test-support/index.d.ts"
15
+ ],
16
+ "test-support/*": [
17
+ "declarations/addon-test-support/*",
18
+ "declarations/addon-test-support/*/index.d.ts"
19
+ ],
20
+ "*": [
21
+ "declarations/addon/*",
22
+ "declarations/addon/*/index.d.ts"
23
+ ]
24
+ }
25
+ },
11
26
  "directories": {
12
27
  "doc": "doc",
13
28
  "test": "tests"
@@ -22,6 +37,9 @@
22
37
  "lint:hbs:fix": "ember-template-lint . --fix",
23
38
  "lint:js": "eslint . --cache",
24
39
  "lint:js:fix": "eslint . --fix",
40
+ "lint:types": "tsc --noEmit",
41
+ "prepack": "tsc --project tsconfig.declarations.json",
42
+ "postpack": "rimraf declarations",
25
43
  "prepare": "husky install",
26
44
  "start": "ember serve",
27
45
  "test": "concurrently \"npm:lint\" \"npm:test:*\" --names \"lint,test:\"",
@@ -34,68 +52,73 @@
34
52
  ]
35
53
  },
36
54
  "dependencies": {
37
- "broccoli-funnel": "^3.0.5",
38
- "broccoli-merge-trees": "^4.2.0",
39
- "ember-auto-import": "^2.6.3",
40
- "ember-cli-babel": "^7.26.11",
41
- "graphql": "^16.7.1",
55
+ "@babel/core": "^7.23.3",
56
+ "ember-auto-import": "^2.7.0",
57
+ "ember-cli-babel": "^8.2.0",
42
58
  "lodash.merge": "^4.6.2"
43
59
  },
44
60
  "devDependencies": {
45
- "@babel/eslint-parser": "^7.22.5",
46
- "@babel/plugin-proposal-decorators": "^7.22.5",
47
- "@commitlint/cli": "^17.6.6",
48
- "@commitlint/config-conventional": "^17.6.6",
61
+ "@apollo/client": "^3.9.4",
62
+ "@commitlint/cli": "^18.4.3",
63
+ "@commitlint/config-conventional": "^18.4.3",
49
64
  "@ember/optional-features": "^2.0.0",
50
- "@ember/string": "^3.1.1",
51
- "@ember/test-helpers": "^3.1.0",
52
- "@embroider/test-setup": "^3.0.1",
65
+ "@ember/test-helpers": "^3.2.1",
66
+ "@embroider/test-setup": "^3.0.3",
53
67
  "@glimmer/component": "^1.1.2",
54
68
  "@glimmer/tracking": "^1.1.2",
55
- "@release-it-plugins/lerna-changelog": "^5.0.0",
69
+ "@release-it-plugins/lerna-changelog": "^6.0.0",
70
+ "@tsconfig/ember": "^3.0.3",
71
+ "@types/lodash.merge": "^4.6.9",
72
+ "@types/qunit": "^2.19.10",
73
+ "@types/rsvp": "^4.0.9",
74
+ "@typescript-eslint/eslint-plugin": "^6.19.1",
75
+ "@typescript-eslint/parser": "^6.19.1",
56
76
  "broccoli-asset-rev": "^3.0.0",
57
- "concurrently": "^8.2.0",
58
- "ember-apollo-client": "^4.1.1",
59
- "ember-cli": "~5.1.0",
60
- "ember-cli-clean-css": "^2.0.0",
77
+ "concurrently": "^8.2.2",
78
+ "ember-cli": "~5.6.0",
79
+ "ember-cli-clean-css": "^3.0.0",
61
80
  "ember-cli-dependency-checker": "^3.3.2",
62
- "ember-cli-htmlbars": "^6.2.0",
81
+ "ember-cli-htmlbars": "^6.3.0",
63
82
  "ember-cli-inject-live-reload": "^2.1.0",
64
83
  "ember-cli-sri": "^2.1.1",
65
84
  "ember-cli-terser": "^4.0.2",
66
- "ember-fetch": "^8.1.2",
67
85
  "ember-load-initializers": "^2.1.2",
68
- "ember-page-title": "^7.0.0",
69
- "ember-qunit": "^7.0.0",
70
- "ember-resolver": "^10.1.1",
71
- "ember-source": "~5.1.1",
86
+ "ember-page-title": "^8.2.0",
87
+ "ember-qunit": "^8.0.2",
88
+ "ember-resolver": "^11.0.1",
89
+ "ember-source": "~5.6.0",
72
90
  "ember-source-channel-url": "^3.0.0",
73
- "ember-template-lint": "^5.11.0",
74
- "ember-try": "^2.0.0",
75
- "eslint": "^8.43.0",
76
- "eslint-config-prettier": "^8.8.0",
77
- "eslint-plugin-ember": "^11.9.0",
78
- "eslint-plugin-n": "^16.0.1",
79
- "eslint-plugin-prettier": "^4.2.1",
80
- "eslint-plugin-qunit": "^8.0.0",
81
- "husky": "^8.0.3",
91
+ "ember-template-lint": "^5.13.0",
92
+ "ember-try": "^3.0.0",
93
+ "eslint": "^8.56.0",
94
+ "eslint-config-prettier": "^9.1.0",
95
+ "eslint-plugin-ember": "^12.0.0",
96
+ "eslint-plugin-n": "^16.6.2",
97
+ "eslint-plugin-prettier": "^5.1.3",
98
+ "eslint-plugin-qunit": "^8.0.1",
99
+ "graphql": "^16.8.1",
100
+ "husky": "^9.0.10",
82
101
  "loader.js": "^4.7.0",
83
- "msw": "^1.2.2",
84
- "prettier": "^2.8.8",
85
- "qunit": "^2.19.4",
86
- "qunit-dom": "^2.0.0",
87
- "release-it": "^15.11.0",
88
- "stylelint": "^15.9.0",
89
- "stylelint-config-standard": "^34.0.0",
90
- "stylelint-prettier": "^3.0.0",
91
- "webpack": "^5.88.1"
102
+ "msw": "^2.0.9",
103
+ "prettier": "^3.2.4",
104
+ "qunit": "^2.20.0",
105
+ "qunit-dom": "^3.0.0",
106
+ "release-it": "^17.0.3",
107
+ "rimraf": "^5.0.1",
108
+ "stylelint": "^16.2.1",
109
+ "stylelint-config-standard": "^36.0.0",
110
+ "stylelint-prettier": "^5.0.0",
111
+ "typescript": "^5.3.3",
112
+ "webpack": "^5.89.0"
92
113
  },
93
114
  "peerDependencies": {
94
- "ember-source": "^4.4.0 || ^5.0.0",
95
- "msw": "^1.0.1"
115
+ "ember-qunit": "^8.0.0",
116
+ "ember-source": ">= 4.8.0",
117
+ "graphql": "^16.0.0",
118
+ "msw": "^2.0.0"
96
119
  },
97
120
  "engines": {
98
- "node": "16.* || >= 18"
121
+ "node": ">= 18"
99
122
  },
100
123
  "publishConfig": {
101
124
  "access": "public",
@@ -108,7 +131,7 @@
108
131
  "configPath": "tests/dummy/config"
109
132
  },
110
133
  "msw": {
111
- "workerDirectory": "public"
134
+ "workerDirectory": "tests/dummy/public"
112
135
  },
113
136
  "release-it": {
114
137
  "plugins": {
@@ -1,83 +0,0 @@
1
- import { assert } from '@ember/debug';
2
- import { buildASTSchema, graphql } from 'graphql';
3
- import merge from 'lodash.merge';
4
- import { graphql as mswGraphql, setupWorker } from 'msw';
5
-
6
- const IS_TESTEM = Boolean(window.Testem);
7
- const DEFAULT_OPTIONS = {
8
- mswStartOptions: {
9
- quiet: IS_TESTEM,
10
- serviceWorker: {
11
- options: {
12
- scope: IS_TESTEM ? window.location.pathname : '/tests',
13
- },
14
- },
15
- },
16
- };
17
-
18
- let isSetupGraphqlTestCalled = false;
19
- let root = null;
20
- let worker = null;
21
-
22
- export function setupEmberGraphqlMocking(schemaDocument, providedOptions) {
23
- const options = merge({}, DEFAULT_OPTIONS, providedOptions);
24
-
25
- createWorker();
26
- createGraphqlOperationHandler(schemaDocument);
27
-
28
- return startWorker(options.mswStartOptions);
29
- }
30
-
31
- export function setupGraphqlTest(hooks) {
32
- hooks.before(() => (isSetupGraphqlTestCalled = true));
33
- hooks.after(() => (isSetupGraphqlTestCalled = false));
34
- hooks.afterEach(clearRoot);
35
- }
36
-
37
- export function mockResolvers(resolvers) {
38
- assert(
39
- 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',
40
- isSetupGraphqlTestCalled
41
- );
42
-
43
- root = { ...root, ...resolvers };
44
- }
45
-
46
- export function getWorker() {
47
- return worker;
48
- }
49
-
50
- export function destroyWorker() {
51
- worker.stop();
52
-
53
- worker = null;
54
- }
55
-
56
- function createWorker() {
57
- worker = setupWorker();
58
- }
59
-
60
- function createGraphqlOperationHandler(schemaDocument) {
61
- const schema = buildASTSchema(schemaDocument);
62
- const graphqlOperation = mswGraphql.operation(async (req, res, ctx) => {
63
- const { query } = await req.json();
64
- const queryResult = await graphql({
65
- rootValue: root,
66
- schema,
67
- source: query,
68
- variableValues: req.variables,
69
- });
70
-
71
- return res(ctx.data(queryResult.data), ctx.errors(queryResult.errors));
72
- });
73
-
74
- worker.use(graphqlOperation);
75
- }
76
-
77
- function startWorker(mswStartOptions) {
78
- return worker.start(mswStartOptions);
79
- }
80
-
81
- function clearRoot() {
82
- root = null;
83
- }
@@ -1,303 +0,0 @@
1
- /* eslint-disable */
2
- /* tslint:disable */
3
-
4
- /**
5
- * Mock Service Worker (1.2.2).
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 = '3d6b9f06410d179a7f7404d4bf4c3c70'
12
- const activeClientIds = new Set()
13
-
14
- self.addEventListener('install', function () {
15
- self.skipWaiting()
16
- })
17
-
18
- self.addEventListener('activate', function (event) {
19
- event.waitUntil(self.clients.claim())
20
- })
21
-
22
- self.addEventListener('message', async function (event) {
23
- const clientId = event.source.id
24
-
25
- if (!clientId || !self.clients) {
26
- return
27
- }
28
-
29
- const client = await self.clients.get(clientId)
30
-
31
- if (!client) {
32
- return
33
- }
34
-
35
- const allClients = await self.clients.matchAll({
36
- type: 'window',
37
- })
38
-
39
- switch (event.data) {
40
- case 'KEEPALIVE_REQUEST': {
41
- sendToClient(client, {
42
- type: 'KEEPALIVE_RESPONSE',
43
- })
44
- break
45
- }
46
-
47
- case 'INTEGRITY_CHECK_REQUEST': {
48
- sendToClient(client, {
49
- type: 'INTEGRITY_CHECK_RESPONSE',
50
- payload: INTEGRITY_CHECKSUM,
51
- })
52
- break
53
- }
54
-
55
- case 'MOCK_ACTIVATE': {
56
- activeClientIds.add(clientId)
57
-
58
- sendToClient(client, {
59
- type: 'MOCKING_ENABLED',
60
- payload: true,
61
- })
62
- break
63
- }
64
-
65
- case 'MOCK_DEACTIVATE': {
66
- activeClientIds.delete(clientId)
67
- break
68
- }
69
-
70
- case 'CLIENT_CLOSED': {
71
- activeClientIds.delete(clientId)
72
-
73
- const remainingClients = allClients.filter((client) => {
74
- return client.id !== clientId
75
- })
76
-
77
- // Unregister itself when there are no more clients
78
- if (remainingClients.length === 0) {
79
- self.registration.unregister()
80
- }
81
-
82
- break
83
- }
84
- }
85
- })
86
-
87
- self.addEventListener('fetch', function (event) {
88
- const { request } = event
89
- const accept = request.headers.get('accept') || ''
90
-
91
- // Bypass server-sent events.
92
- if (accept.includes('text/event-stream')) {
93
- return
94
- }
95
-
96
- // Bypass navigation requests.
97
- if (request.mode === 'navigate') {
98
- return
99
- }
100
-
101
- // Opening the DevTools triggers the "only-if-cached" request
102
- // that cannot be handled by the worker. Bypass such requests.
103
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
104
- return
105
- }
106
-
107
- // Bypass all requests when there are no active clients.
108
- // Prevents the self-unregistered worked from handling requests
109
- // after it's been deleted (still remains active until the next reload).
110
- if (activeClientIds.size === 0) {
111
- return
112
- }
113
-
114
- // Generate unique request ID.
115
- const requestId = Math.random().toString(16).slice(2)
116
-
117
- event.respondWith(
118
- handleRequest(event, requestId).catch((error) => {
119
- if (error.name === 'NetworkError') {
120
- console.warn(
121
- '[MSW] Successfully emulated a network error for the "%s %s" request.',
122
- request.method,
123
- request.url,
124
- )
125
- return
126
- }
127
-
128
- // At this point, any exception indicates an issue with the original request/response.
129
- console.error(
130
- `\
131
- [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.`,
132
- request.method,
133
- request.url,
134
- `${error.name}: ${error.message}`,
135
- )
136
- }),
137
- )
138
- })
139
-
140
- async function handleRequest(event, requestId) {
141
- const client = await resolveMainClient(event)
142
- const response = await getResponse(event, client, requestId)
143
-
144
- // Send back the response clone for the "response:*" life-cycle events.
145
- // Ensure MSW is active and ready to handle the message, otherwise
146
- // this message will pend indefinitely.
147
- if (client && activeClientIds.has(client.id)) {
148
- ;(async function () {
149
- const clonedResponse = response.clone()
150
- sendToClient(client, {
151
- type: 'RESPONSE',
152
- payload: {
153
- requestId,
154
- type: clonedResponse.type,
155
- ok: clonedResponse.ok,
156
- status: clonedResponse.status,
157
- statusText: clonedResponse.statusText,
158
- body:
159
- clonedResponse.body === null ? null : await clonedResponse.text(),
160
- headers: Object.fromEntries(clonedResponse.headers.entries()),
161
- redirected: clonedResponse.redirected,
162
- },
163
- })
164
- })()
165
- }
166
-
167
- return response
168
- }
169
-
170
- // Resolve the main client for the given event.
171
- // Client that issues a request doesn't necessarily equal the client
172
- // that registered the worker. It's with the latter the worker should
173
- // communicate with during the response resolving phase.
174
- async function resolveMainClient(event) {
175
- const client = await self.clients.get(event.clientId)
176
-
177
- if (client?.frameType === 'top-level') {
178
- return client
179
- }
180
-
181
- const allClients = await self.clients.matchAll({
182
- type: 'window',
183
- })
184
-
185
- return allClients
186
- .filter((client) => {
187
- // Get only those clients that are currently visible.
188
- return client.visibilityState === 'visible'
189
- })
190
- .find((client) => {
191
- // Find the client ID that's recorded in the
192
- // set of clients that have registered the worker.
193
- return activeClientIds.has(client.id)
194
- })
195
- }
196
-
197
- async function getResponse(event, client, requestId) {
198
- const { request } = event
199
- const clonedRequest = request.clone()
200
-
201
- function passthrough() {
202
- // Clone the request because it might've been already used
203
- // (i.e. its body has been read and sent to the client).
204
- const headers = Object.fromEntries(clonedRequest.headers.entries())
205
-
206
- // Remove MSW-specific request headers so the bypassed requests
207
- // comply with the server's CORS preflight check.
208
- // Operate with the headers as an object because request "Headers"
209
- // are immutable.
210
- delete headers['x-msw-bypass']
211
-
212
- return fetch(clonedRequest, { headers })
213
- }
214
-
215
- // Bypass mocking when the client is not active.
216
- if (!client) {
217
- return passthrough()
218
- }
219
-
220
- // Bypass initial page load requests (i.e. static assets).
221
- // The absence of the immediate/parent client in the map of the active clients
222
- // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
223
- // and is not ready to handle requests.
224
- if (!activeClientIds.has(client.id)) {
225
- return passthrough()
226
- }
227
-
228
- // Bypass requests with the explicit bypass header.
229
- // Such requests can be issued by "ctx.fetch()".
230
- if (request.headers.get('x-msw-bypass') === 'true') {
231
- return passthrough()
232
- }
233
-
234
- // Notify the client that a request has been intercepted.
235
- const clientMessage = await sendToClient(client, {
236
- type: 'REQUEST',
237
- payload: {
238
- id: requestId,
239
- url: request.url,
240
- method: request.method,
241
- headers: Object.fromEntries(request.headers.entries()),
242
- cache: request.cache,
243
- mode: request.mode,
244
- credentials: request.credentials,
245
- destination: request.destination,
246
- integrity: request.integrity,
247
- redirect: request.redirect,
248
- referrer: request.referrer,
249
- referrerPolicy: request.referrerPolicy,
250
- body: await request.text(),
251
- bodyUsed: request.bodyUsed,
252
- keepalive: request.keepalive,
253
- },
254
- })
255
-
256
- switch (clientMessage.type) {
257
- case 'MOCK_RESPONSE': {
258
- return respondWithMock(clientMessage.data)
259
- }
260
-
261
- case 'MOCK_NOT_FOUND': {
262
- return passthrough()
263
- }
264
-
265
- case 'NETWORK_ERROR': {
266
- const { name, message } = clientMessage.data
267
- const networkError = new Error(message)
268
- networkError.name = name
269
-
270
- // Rejecting a "respondWith" promise emulates a network error.
271
- throw networkError
272
- }
273
- }
274
-
275
- return passthrough()
276
- }
277
-
278
- function sendToClient(client, message) {
279
- return new Promise((resolve, reject) => {
280
- const channel = new MessageChannel()
281
-
282
- channel.port1.onmessage = (event) => {
283
- if (event.data && event.data.error) {
284
- return reject(event.data.error)
285
- }
286
-
287
- resolve(event.data)
288
- }
289
-
290
- client.postMessage(message, [channel.port2])
291
- })
292
- }
293
-
294
- function sleep(timeMs) {
295
- return new Promise((resolve) => {
296
- setTimeout(resolve, timeMs)
297
- })
298
- }
299
-
300
- async function respondWithMock(response) {
301
- await sleep(response.delay)
302
- return new Response(response.body, response)
303
- }