@stuntman/client 0.1.0 → 0.1.2

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.
@@ -1,4 +1,10 @@
1
- import type * as Stuntman from '@stuntman/shared';
1
+ # Stuntman API client
2
+
3
+ Client for [Stuntman](https://github.com/andrzej-woof/stuntman) proxy/mock server API
4
+
5
+ ## Example usage
6
+
7
+ ```ts
2
8
  import { Client } from './apiClient';
3
9
  import { ruleBuilder } from './ruleBuilder';
4
10
 
@@ -7,10 +13,10 @@ const client = new Client();
7
13
  const uniqueQaUserEmail = 'unique_qa_email@example.com';
8
14
  const rule = ruleBuilder()
9
15
  .limitedUse(2)
10
- .onAnyRequest()
11
- .withBodyJson('test', 'value')
16
+ .onRequestToHostname('example.com')
17
+ .withSearchParam('user', uniqueQaUserEmail)
12
18
  .mockResponse({
13
- localFn: (req: Stuntman.Request) => {
19
+ localFn: (req) => {
14
20
  if (JSON.parse(req.body).email !== uniqueQaUserEmail) {
15
21
  return {
16
22
  status: 500,
@@ -22,3 +28,6 @@ const rule = ruleBuilder()
22
28
  });
23
29
 
24
30
  client.addRule(rule).then((x) => console.log(x));
31
+ ```
32
+
33
+ Check [example app](https://github.com/andrzej-woof/stuntman/tree/master/packages/example#readme) for more samples
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { Client as StuntmanClient } from './apiClient';
2
+ export { ruleBuilder } from './ruleBuilder';
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StuntmanClient = void 0;
3
+ exports.ruleBuilder = exports.StuntmanClient = void 0;
4
4
  var apiClient_1 = require("./apiClient");
5
5
  Object.defineProperty(exports, "StuntmanClient", { enumerable: true, get: function () { return apiClient_1.Client; } });
6
+ var ruleBuilder_1 = require("./ruleBuilder");
7
+ Object.defineProperty(exports, "ruleBuilder", { enumerable: true, get: function () { return ruleBuilder_1.ruleBuilder; } });
@@ -13,43 +13,52 @@ class RuleBuilderBaseBase {
13
13
  priority: shared_1.DEFAULT_RULE_PRIORITY,
14
14
  matches: {
15
15
  localFn: (req) => {
16
+ var _a, _b, _c;
16
17
  const ___url = new URL(req.url);
17
18
  const ___headers = req.rawHeaders;
18
19
  const arrayIndexerRegex = /\[(?<arrayIndex>[0-9]*)\]/i;
19
- const matchObject = (obj, path, value) => {
20
+ const matchObject = (obj, path, value, parentPath) => {
20
21
  var _a, _b;
21
22
  if (!obj) {
22
- return false;
23
+ return { result: false, description: `${parentPath} is falsey` };
23
24
  }
24
25
  const [rawKey, ...rest] = path.split('.');
25
26
  const key = rawKey.replace(arrayIndexerRegex, '');
26
27
  const shouldBeArray = arrayIndexerRegex.test(rawKey);
27
28
  const arrayIndex = Number((_b = (_a = arrayIndexerRegex.exec(rawKey)) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.arrayIndex);
28
29
  const actualValue = key ? obj[key] : obj;
30
+ const currentPath = `${parentPath ? `${parentPath}.` : ''}${rawKey}`;
29
31
  if (value === undefined && actualValue === undefined) {
30
- return false;
32
+ return { result: false, description: `${currentPath}=undefined` };
31
33
  }
32
34
  if (rest.length === 0) {
33
35
  if (shouldBeArray &&
34
36
  (!Array.isArray(actualValue) ||
35
37
  !(!Number.isInteger(arrayIndex) && actualValue.length > Number(arrayIndex)))) {
36
- return false;
38
+ return { result: false, description: `${currentPath} empty array` };
37
39
  }
38
40
  if (value === undefined) {
39
- return shouldBeArray
41
+ const result = shouldBeArray
40
42
  ? !Number.isInteger(arrayIndex) || actualValue.length >= Number(arrayIndex)
41
43
  : actualValue !== undefined;
44
+ return { result, description: `${currentPath}` };
42
45
  }
43
46
  if (!shouldBeArray) {
44
- return value instanceof RegExp ? value.test(actualValue) : value === actualValue;
47
+ const result = value instanceof RegExp ? value.test(actualValue) : value === actualValue;
48
+ return { result, description: `${currentPath}` };
45
49
  }
46
50
  }
47
51
  if (shouldBeArray) {
48
- return Number.isInteger(arrayIndex)
49
- ? matchObject(actualValue[Number(arrayIndex)], rest.join('.'), value)
50
- : actualValue.some((arrayValue) => matchObject(arrayValue, rest.join('.'), value));
52
+ if (Number.isInteger(arrayIndex)) {
53
+ return matchObject(actualValue[Number(arrayIndex)], rest.join('.'), value, currentPath);
54
+ }
55
+ const hasArrayMatch = actualValue.some((arrayValue) => matchObject(arrayValue, rest.join('.'), value, currentPath));
56
+ return { result: hasArrayMatch, description: `array match ${currentPath}` };
51
57
  }
52
- return typeof actualValue !== 'object' ? false : matchObject(actualValue, rest.join('.'), value);
58
+ if (typeof actualValue !== 'object') {
59
+ return { result: false, description: `${currentPath} not an object` };
60
+ }
61
+ return matchObject(actualValue, rest.join('.'), value, currentPath);
53
62
  };
54
63
  const ___matchesValue = (matcher, value) => {
55
64
  if (matcher === undefined) {
@@ -70,32 +79,49 @@ class RuleBuilderBaseBase {
70
79
  return true;
71
80
  };
72
81
  if (!___matchesValue(matchBuilderVariables.filter, req.url)) {
73
- return false;
82
+ return {
83
+ result: false,
84
+ description: `url ${req.url} doesn't match ${(_a = matchBuilderVariables.filter) === null || _a === void 0 ? void 0 : _a.toString()}`,
85
+ };
74
86
  }
75
87
  if (!___matchesValue(matchBuilderVariables.hostname, ___url.hostname)) {
76
- return false;
88
+ return {
89
+ result: false,
90
+ description: `hostname ${___url.hostname} doesn't match ${(_b = matchBuilderVariables.hostname) === null || _b === void 0 ? void 0 : _b.toString()}`,
91
+ };
77
92
  }
78
93
  if (!___matchesValue(matchBuilderVariables.pathname, ___url.pathname)) {
79
- return false;
94
+ return {
95
+ result: false,
96
+ description: `pathname ${___url.pathname} doesn't match ${(_c = matchBuilderVariables.pathname) === null || _c === void 0 ? void 0 : _c.toString()}`,
97
+ };
80
98
  }
81
99
  if (matchBuilderVariables.searchParams) {
82
100
  for (const searchParamMatcher of matchBuilderVariables.searchParams) {
83
101
  if (typeof searchParamMatcher === 'string') {
84
- return ___url.searchParams.has(searchParamMatcher);
102
+ const result = ___url.searchParams.has(searchParamMatcher);
103
+ return { result, description: `searchParams.has("${searchParamMatcher}")` };
85
104
  }
86
105
  if (searchParamMatcher instanceof RegExp) {
87
- return Array.from(___url.searchParams.keys()).some((key) => searchParamMatcher.test(key));
106
+ const result = Array.from(___url.searchParams.keys()).some((key) => searchParamMatcher.test(key));
107
+ return { result, description: `searchParams.keys() matches ${searchParamMatcher.toString()}` };
88
108
  }
89
109
  if (!___url.searchParams.has(searchParamMatcher.key)) {
90
- return false;
110
+ return { result: false, description: `searchParams.has("${searchParamMatcher.key}")` };
91
111
  }
92
112
  if (searchParamMatcher.value) {
93
113
  const value = ___url.searchParams.get(searchParamMatcher.key);
94
114
  if (value === null) {
95
- return false;
115
+ return {
116
+ result: false,
117
+ description: `searchParams.get("${searchParamMatcher.key}") === null`,
118
+ };
96
119
  }
97
120
  if (!___matchesValue(searchParamMatcher.value, value)) {
98
- return false;
121
+ return {
122
+ result: false,
123
+ description: `searchParams.get("${searchParamMatcher.key}") = "${searchParamMatcher.value}"`,
124
+ };
99
125
  }
100
126
  }
101
127
  }
@@ -103,31 +129,50 @@ class RuleBuilderBaseBase {
103
129
  if (matchBuilderVariables.headers) {
104
130
  for (const headerMatcher of matchBuilderVariables.headers) {
105
131
  if (typeof headerMatcher === 'string') {
106
- return ___headers.has(headerMatcher);
132
+ const result = ___headers.has(headerMatcher);
133
+ return { result, description: `headers.has("${headerMatcher}")` };
107
134
  }
108
135
  if (headerMatcher instanceof RegExp) {
109
- return ___headers.toHeaderPairs().some(([key]) => headerMatcher.test(key));
136
+ const result = ___headers.toHeaderPairs().some(([key]) => headerMatcher.test(key));
137
+ return { result, description: `headers.keys matches ${headerMatcher.toString()}` };
110
138
  }
111
139
  if (!___headers.has(headerMatcher.key)) {
112
- return false;
140
+ return { result: false, description: `headers.has("${headerMatcher.key}")` };
113
141
  }
114
142
  if (headerMatcher.value) {
115
143
  const value = ___headers.get(headerMatcher.key);
116
144
  if (value === null) {
117
- return false;
145
+ return { result: false, description: `headers.get("${headerMatcher.key}") === null` };
118
146
  }
119
147
  if (!___matchesValue(headerMatcher.value, value)) {
120
- return false;
148
+ return {
149
+ result: false,
150
+ description: `headerMatcher.get("${headerMatcher.key}") = "${headerMatcher.value}"`,
151
+ };
121
152
  }
122
153
  }
123
154
  }
124
155
  }
125
156
  if (matchBuilderVariables.bodyText === null && !!req.body) {
126
- return false;
157
+ return { result: false, description: `empty body` };
127
158
  }
128
159
  if (matchBuilderVariables.bodyText) {
129
- if (!___matchesValue(matchBuilderVariables.bodyText, req.body)) {
130
- return false;
160
+ if (!req.body) {
161
+ return { result: false, description: `empty body` };
162
+ }
163
+ if (matchBuilderVariables.bodyText instanceof RegExp) {
164
+ if (!___matchesValue(matchBuilderVariables.bodyText, req.body)) {
165
+ return {
166
+ result: false,
167
+ description: `body text doesn't match ${matchBuilderVariables.bodyText.toString()}`,
168
+ };
169
+ }
170
+ }
171
+ else if (!req.body.includes(matchBuilderVariables.bodyText)) {
172
+ return {
173
+ result: false,
174
+ description: `body text doesn't include "${matchBuilderVariables.bodyText}"`,
175
+ };
131
176
  }
132
177
  }
133
178
  if (matchBuilderVariables.bodyJson) {
@@ -136,47 +181,63 @@ class RuleBuilderBaseBase {
136
181
  json = JSON.parse(req.body);
137
182
  }
138
183
  catch (kiss) {
139
- return false;
184
+ return { result: false, description: `unparseable json` };
140
185
  }
141
186
  if (!json) {
142
- return false;
187
+ return { result: false, description: `empty json object` };
143
188
  }
144
189
  for (const jsonMatcher of Array.isArray(matchBuilderVariables.bodyJson)
145
190
  ? matchBuilderVariables.bodyJson
146
191
  : [matchBuilderVariables.bodyJson]) {
147
192
  if (!matchObject(json, jsonMatcher.key, jsonMatcher.value)) {
148
- return false;
193
+ return { result: false, description: `$.${jsonMatcher.key} != "${jsonMatcher.value}"` };
149
194
  }
150
195
  }
151
196
  }
152
197
  if (matchBuilderVariables.bodyGql) {
153
198
  if (!req.gqlBody) {
154
- return false;
199
+ return { result: false, description: `not a gql body` };
155
200
  }
156
201
  if (!___matchesValue(matchBuilderVariables.bodyGql.methodName, req.gqlBody.methodName)) {
157
- return false;
202
+ return {
203
+ result: false,
204
+ description: `methodName "${matchBuilderVariables.bodyGql.methodName}" !== "${req.gqlBody.methodName}"`,
205
+ };
158
206
  }
159
207
  if (!___matchesValue(matchBuilderVariables.bodyGql.operationName, req.gqlBody.operationName)) {
160
- return false;
208
+ return {
209
+ result: false,
210
+ description: `operationName "${matchBuilderVariables.bodyGql.operationName}" !== "${req.gqlBody.operationName}"`,
211
+ };
161
212
  }
162
213
  if (!___matchesValue(matchBuilderVariables.bodyGql.query, req.gqlBody.query)) {
163
- return false;
214
+ return {
215
+ result: false,
216
+ description: `query "${matchBuilderVariables.bodyGql.query}" !== "${req.gqlBody.query}"`,
217
+ };
164
218
  }
165
219
  if (!___matchesValue(matchBuilderVariables.bodyGql.type, req.gqlBody.type)) {
166
- return false;
220
+ return {
221
+ result: false,
222
+ description: `type "${matchBuilderVariables.bodyGql.type}" !== "${req.gqlBody.type}"`,
223
+ };
167
224
  }
168
225
  if (!matchBuilderVariables.bodyGql.variables) {
169
- return true;
226
+ return { result: true, description: `no variables to match` };
170
227
  }
171
228
  for (const jsonMatcher of Array.isArray(matchBuilderVariables.bodyGql.variables)
172
229
  ? matchBuilderVariables.bodyGql.variables
173
230
  : [matchBuilderVariables.bodyGql.variables]) {
174
- if (!matchObject(req.gqlBody.variables, jsonMatcher.key, jsonMatcher.value)) {
175
- return false;
231
+ const matchObjectResult = matchObject(req.gqlBody.variables, jsonMatcher.key, jsonMatcher.value);
232
+ if (!matchObjectResult.result) {
233
+ return {
234
+ result: false,
235
+ description: `GQL variable ${jsonMatcher.key} != "${jsonMatcher.value}". Detail: ${matchObjectResult.description}`,
236
+ };
176
237
  }
177
238
  }
178
239
  }
179
- return true;
240
+ return { result: true, description: 'match' };
180
241
  },
181
242
  localVariables: { matchBuilderVariables: this._matchBuilderVariables },
182
243
  },
@@ -243,8 +304,7 @@ class RuleBuilder extends RuleBuilderBase {
243
304
  return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
244
305
  }
245
306
  onAnyRequest() {
246
- this.rule.matches = { localFn: () => true };
247
- return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
307
+ return this.onRequestTo(/.*/);
248
308
  }
249
309
  }
250
310
  class RuleBuilderInitialized extends RuleBuilderBase {
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@stuntman/client",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Stuntman - HTTP proxy / mock API client",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/andrzej-woof/stuntman.git"
9
9
  },
10
+ "homepage": "https://github.com/andrzej-woof/stuntman#readme",
10
11
  "bugs": {
11
12
  "url": "https://github.com/andrzej-woof/stuntman/issues"
12
13
  },
@@ -31,7 +32,7 @@
31
32
  "author": "Andrzej Pasterczyk",
32
33
  "license": "MIT",
33
34
  "dependencies": {
34
- "@stuntman/shared": "^0.1.0",
35
+ "@stuntman/shared": "^0.1.2",
35
36
  "serialize-javascript": "6.0.1",
36
37
  "uuid": "9.0.0"
37
38
  },
@@ -39,6 +40,12 @@
39
40
  "@types/serialize-javascript": "5.0.2",
40
41
  "@types/uuid": "9.0.0"
41
42
  },
43
+ "files": [
44
+ "dist/",
45
+ "README.md",
46
+ "LICENSE",
47
+ "CHANGELOG.md"
48
+ ],
42
49
  "scripts": {
43
50
  "test": "echo \"Error: no test specified\" && exit 1",
44
51
  "clean": "rm -fr dist",
@@ -1 +0,0 @@
1
- export {};
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const apiClient_1 = require("./apiClient");
4
- const ruleBuilder_1 = require("./ruleBuilder");
5
- const client = new apiClient_1.Client();
6
- const uniqueQaUserEmail = 'unique_qa_email@example.com';
7
- const rule = (0, ruleBuilder_1.ruleBuilder)()
8
- .limitedUse(2)
9
- .onAnyRequest()
10
- .withBodyJson('test', 'value')
11
- .mockResponse({
12
- localFn: (req) => {
13
- if (JSON.parse(req.body).email !== uniqueQaUserEmail) {
14
- return {
15
- status: 500,
16
- };
17
- }
18
- return { status: 201 };
19
- },
20
- localVariables: { uniqueQaUserEmail },
21
- });
22
- client.addRule(rule).then((x) => console.log(x));
package/src/apiClient.ts DELETED
@@ -1,181 +0,0 @@
1
- import serializeJavascript from 'serialize-javascript';
2
- import { ClientError } from './clientError';
3
- import { DEFAULT_API_PORT } from '@stuntman/shared';
4
- import type * as Stuntman from '@stuntman/shared';
5
-
6
- type ClientOptions = {
7
- protocol?: 'http' | 'https';
8
- host?: string;
9
- port?: number;
10
- timeout?: number;
11
- };
12
-
13
- const SERIALIZE_JAVASCRIPT_OPTIONS: serializeJavascript.SerializeJSOptions = {
14
- unsafe: true,
15
- ignoreFunction: true,
16
- };
17
-
18
- const getFunctionParams = (func: () => any) => {
19
- const funstr = func.toString();
20
- const params = funstr.slice(funstr.indexOf('(') + 1, funstr.indexOf(')')).match(/([^\s,]+)/g) || new Array<string>();
21
- if (params.includes('=')) {
22
- throw new Error('default argument values are not supported');
23
- }
24
- return params;
25
- };
26
-
27
- const serializeApiFunction = (fn: (...args: any[]) => any, variables?: Stuntman.LocalVariables): string => {
28
- const variableInitializer: string[] = [];
29
- const functionParams = getFunctionParams(fn);
30
- if (variables) {
31
- for (const varName of Object.keys(variables)) {
32
- let varValue = variables[varName];
33
- if (varValue === undefined || varValue === null || typeof varValue === 'number' || typeof varValue === 'boolean') {
34
- varValue = `${varValue}`;
35
- } else if (typeof varValue === 'string') {
36
- varValue = `${serializeJavascript(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS)}`;
37
- } else {
38
- varValue = `eval('(${serializeJavascript(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS).replace(
39
- /'/g,
40
- "\\'"
41
- )})')`;
42
- }
43
- variableInitializer.push(`const ${varName} = ${varValue};`);
44
- }
45
- }
46
- const functionString = fn.toString();
47
- const serializedHeader = `return ((${functionParams.map((_param, index) => `____arg${index}`).join(',')}) => {`;
48
- const serializedParams = `${functionParams
49
- .map((_param, index) => `const ${functionParams[index]} = ____arg${index};`)
50
- .join('\n')}`;
51
- const serializedVariables = `${variableInitializer.join('\n')}`;
52
- // prettier-ignore
53
- const serializedFunction = `return (${functionString.substring(0, functionString.indexOf('('))}()${functionString.substring(functionString.indexOf(')')+1)})(); })(${functionParams.map((_param, index) => `____arg${index}`).join(',')})`;
54
- if (!serializedParams && !serializedVariables) {
55
- return `${serializedHeader}${serializedFunction}`;
56
- }
57
- return [serializedHeader, serializedParams, serializedVariables, serializedFunction].filter((x) => !!x).join('\n');
58
- };
59
-
60
- const keysOf = <T extends object>(obj: T): Array<keyof T> => {
61
- return Array.from(Object.keys(obj)) as any;
62
- };
63
- const serializeRemotableFunctions = <T>(obj: any): Stuntman.WithSerializedFunctions<T> => {
64
- const objectKeys = keysOf(obj);
65
- if (!objectKeys || objectKeys.length === 0) {
66
- return obj;
67
- }
68
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
69
- // @ts-ignore
70
- const output: WithSerializedFunctions<T> = {};
71
- for (const key of objectKeys) {
72
- if (typeof obj[key] === 'object') {
73
- if ('localFn' in obj[key]) {
74
- const remotableFunction = obj[key] as Stuntman.RemotableFunction<(...args: any[]) => any>;
75
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
76
- // @ts-ignore
77
- output[key] = {
78
- remoteFn: serializeApiFunction(remotableFunction.localFn, remotableFunction.localVariables),
79
- localFn: remotableFunction.localFn.toString(),
80
- localVariables: serializeJavascript(remotableFunction.localVariables, SERIALIZE_JAVASCRIPT_OPTIONS),
81
- };
82
- } else {
83
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
84
- // @ts-ignore
85
- output[key] = serializeRemotableFunctions<any>(obj[key]);
86
- }
87
- } else {
88
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
89
- // @ts-ignore
90
- output[key] = obj[key];
91
- }
92
- }
93
- return output;
94
- };
95
-
96
- export class Client {
97
- // TODO websockets connection to API and hooks `onIntereceptedRequest`, `onInterceptedResponse`
98
-
99
- private options: ClientOptions;
100
-
101
- private get baseUrl() {
102
- return `${this.options.protocol}://${this.options.host}${this.options.port ? `:${this.options.port}` : ''}`;
103
- }
104
-
105
- constructor(options?: ClientOptions) {
106
- this.options = {
107
- ...options,
108
- timeout: options?.timeout || 60000,
109
- host: options?.host || 'localhost',
110
- protocol: options?.protocol || 'http',
111
- port: options?.port || options?.protocol ? (options.protocol === 'https' ? 443 : 80) : DEFAULT_API_PORT,
112
- };
113
- }
114
-
115
- private async fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {
116
- const controller = new AbortController();
117
- const timeout = setTimeout(() => {
118
- controller.abort();
119
- }, this.options.timeout);
120
- try {
121
- const response = await fetch(url, { ...init, signal: init?.signal ?? controller.signal });
122
- if (!response.ok) {
123
- const text = await response.text();
124
- let json: any;
125
- try {
126
- json = JSON.parse(text);
127
- } catch (kiss) {
128
- // and swallow
129
- }
130
- if ('error' in json) {
131
- throw new ClientError(json.error);
132
- }
133
- throw new Error(`Unexpected errror: ${text}`);
134
- }
135
- return response;
136
- } finally {
137
- clearTimeout(timeout);
138
- }
139
- }
140
-
141
- async getRules(): Promise<Stuntman.LiveRule[]> {
142
- const response = await this.fetch(`${this.baseUrl}/rules`);
143
- return response.json() as unknown as Promise<Stuntman.LiveRule[]>;
144
- }
145
-
146
- async getRule(id: string): Promise<Stuntman.LiveRule> {
147
- const response = await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}`);
148
- return response.json() as unknown as Stuntman.LiveRule;
149
- }
150
-
151
- async disableRule(id: string): Promise<void> {
152
- await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/disable`);
153
- }
154
-
155
- async enableRule(id: string): Promise<void> {
156
- await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/enable`);
157
- }
158
-
159
- async removeRule(id: string): Promise<void> {
160
- await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/remove`);
161
- }
162
-
163
- async addRule(rule: Stuntman.SerializableRule): Promise<Stuntman.Rule> {
164
- const serializedRule = serializeRemotableFunctions<Stuntman.SerializableRule>(rule);
165
- const response = await this.fetch(`${this.baseUrl}/rule`, {
166
- method: 'POST',
167
- body: JSON.stringify(serializedRule),
168
- headers: { 'content-type': 'application/json' },
169
- });
170
- return response.json() as unknown as Stuntman.Rule;
171
- }
172
-
173
- // TODO improve filtering by timestamp from - to, multiple labels, etc.
174
- async getTraffic(rule: Stuntman.Rule): Promise<Record<string, Stuntman.LogEntry>>;
175
- async getTraffic(ruleIdOrLabel: string): Promise<Record<string, Stuntman.LogEntry>>;
176
- async getTraffic(ruleOrIdOrLabel: string | Stuntman.Rule): Promise<Record<string, Stuntman.LogEntry>> {
177
- const ruleId = typeof ruleOrIdOrLabel === 'object' ? ruleOrIdOrLabel.id : ruleOrIdOrLabel;
178
- const response = await this.fetch(`${this.baseUrl}/traffic${ruleId ? `/${encodeURIComponent(ruleId)}` : ''}`);
179
- return response.json() as unknown as Record<string, Stuntman.LogEntry>;
180
- }
181
- }
@@ -1,22 +0,0 @@
1
- import { AppError } from '@stuntman/shared';
2
- import type * as Stuntman from '@stuntman/shared';
3
-
4
- export enum HttpCode {
5
- OK = 200,
6
- NO_CONTENT = 204,
7
- BAD_REQUEST = 400,
8
- UNAUTHORIZED = 401,
9
- NOT_FOUND = 404,
10
- CONFLICT = 409,
11
- UNPROCESSABLE_ENTITY = 422,
12
- INTERNAL_SERVER_ERROR = 500,
13
- }
14
-
15
- export class ClientError extends AppError {
16
- public readonly originalStack?: string;
17
-
18
- constructor(args: Stuntman.AppError & { stack?: string }) {
19
- super(args);
20
- this.originalStack = args.stack;
21
- }
22
- }
package/src/index.ts DELETED
@@ -1 +0,0 @@
1
- export { Client as StuntmanClient } from './apiClient';
@@ -1,458 +0,0 @@
1
- import { v4 as uuidv4 } from 'uuid';
2
- import type * as Stuntman from '@stuntman/shared';
3
- import { DEFAULT_RULE_PRIORITY, DEFAULT_RULE_TTL_SECONDS, MAX_RULE_TTL_SECONDS, MIN_RULE_TTL_SECONDS } from '@stuntman/shared';
4
-
5
- type KeyValueMatcher = string | RegExp | { key: string; value?: string | RegExp };
6
- type ObjectValueMatcher = string | RegExp | number | boolean | null;
7
- type ObjectKeyValueMatcher = { key: string; value?: ObjectValueMatcher };
8
- type GQLRequestMatcher = {
9
- operationName?: string | RegExp;
10
- variables?: ObjectKeyValueMatcher[];
11
- query?: string | RegExp;
12
- type?: 'query' | 'mutation';
13
- methodName?: string | RegExp;
14
- };
15
-
16
- type MatchBuilderVariables = {
17
- filter?: string | RegExp;
18
- hostname?: string | RegExp;
19
- pathname?: string | RegExp;
20
- port?: number | string | RegExp;
21
- searchParams?: KeyValueMatcher[];
22
- headers?: KeyValueMatcher[];
23
- bodyText?: string | RegExp | null;
24
- bodyJson?: ObjectKeyValueMatcher[];
25
- bodyGql?: GQLRequestMatcher;
26
- };
27
-
28
- // eslint-disable-next-line no-var
29
- declare var matchBuilderVariables: MatchBuilderVariables;
30
-
31
- // TODO add fluent match on multipart from data
32
-
33
- class RuleBuilderBaseBase {
34
- protected rule: Stuntman.SerializableRule;
35
- protected _matchBuilderVariables: MatchBuilderVariables;
36
-
37
- constructor(rule?: Stuntman.SerializableRule, _matchBuilderVariables?: MatchBuilderVariables) {
38
- this._matchBuilderVariables = _matchBuilderVariables || {};
39
- this.rule = rule || {
40
- id: uuidv4(),
41
- ttlSeconds: DEFAULT_RULE_TTL_SECONDS,
42
- priority: DEFAULT_RULE_PRIORITY,
43
- matches: {
44
- localFn: (req: Stuntman.Request): boolean => {
45
- const ___url = new URL(req.url);
46
- const ___headers = req.rawHeaders;
47
-
48
- const arrayIndexerRegex = /\[(?<arrayIndex>[0-9]*)\]/i;
49
- const matchObject = (obj: any, path: string, value?: string | RegExp | number | boolean | null): boolean => {
50
- if (!obj) {
51
- return false;
52
- }
53
- const [rawKey, ...rest] = path.split('.');
54
- const key = rawKey.replace(arrayIndexerRegex, '');
55
- const shouldBeArray = arrayIndexerRegex.test(rawKey);
56
- const arrayIndex = Number(arrayIndexerRegex.exec(rawKey)?.groups?.arrayIndex);
57
- const actualValue = key ? obj[key] : obj;
58
- if (value === undefined && actualValue === undefined) {
59
- return false;
60
- }
61
- if (rest.length === 0) {
62
- if (
63
- shouldBeArray &&
64
- (!Array.isArray(actualValue) ||
65
- !(!Number.isInteger(arrayIndex) && actualValue.length > Number(arrayIndex)))
66
- ) {
67
- return false;
68
- }
69
- if (value === undefined) {
70
- return shouldBeArray
71
- ? !Number.isInteger(arrayIndex) || actualValue.length >= Number(arrayIndex)
72
- : actualValue !== undefined;
73
- }
74
- if (!shouldBeArray) {
75
- return value instanceof RegExp ? value.test(actualValue) : value === actualValue;
76
- }
77
- }
78
- if (shouldBeArray) {
79
- return Number.isInteger(arrayIndex)
80
- ? matchObject(actualValue[Number(arrayIndex)], rest.join('.'), value)
81
- : (actualValue as Array<any>).some((arrayValue) =>
82
- matchObject(arrayValue, rest.join('.'), value)
83
- );
84
- }
85
- return typeof actualValue !== 'object' ? false : matchObject(actualValue, rest.join('.'), value);
86
- };
87
-
88
- const ___matchesValue = (matcher: number | string | RegExp | undefined, value?: string | number): boolean => {
89
- if (matcher === undefined) {
90
- return true;
91
- }
92
- if (typeof matcher !== 'string' && !(matcher instanceof RegExp) && typeof matcher !== 'number') {
93
- throw new Error('invalid matcher');
94
- }
95
- if (typeof matcher === 'string' && matcher !== value) {
96
- return false;
97
- }
98
- if (matcher instanceof RegExp && (typeof value !== 'string' || !matcher.test(value))) {
99
- return false;
100
- }
101
- if (typeof matcher === 'number' && (typeof value !== 'number' || matcher !== value)) {
102
- return false;
103
- }
104
- return true;
105
- };
106
- if (!___matchesValue(matchBuilderVariables.filter, req.url)) {
107
- return false;
108
- }
109
- if (!___matchesValue(matchBuilderVariables.hostname, ___url.hostname)) {
110
- return false;
111
- }
112
- if (!___matchesValue(matchBuilderVariables.pathname, ___url.pathname)) {
113
- return false;
114
- }
115
- if (matchBuilderVariables.searchParams) {
116
- for (const searchParamMatcher of matchBuilderVariables.searchParams) {
117
- if (typeof searchParamMatcher === 'string') {
118
- return ___url.searchParams.has(searchParamMatcher);
119
- }
120
- if (searchParamMatcher instanceof RegExp) {
121
- return Array.from(___url.searchParams.keys()).some((key) => searchParamMatcher.test(key));
122
- }
123
- if (!___url.searchParams.has(searchParamMatcher.key)) {
124
- return false;
125
- }
126
- if (searchParamMatcher.value) {
127
- const value = ___url.searchParams.get(searchParamMatcher.key);
128
- if (value === null) {
129
- return false;
130
- }
131
- if (!___matchesValue(searchParamMatcher.value, value)) {
132
- return false;
133
- }
134
- }
135
- }
136
- }
137
- if (matchBuilderVariables.headers) {
138
- for (const headerMatcher of matchBuilderVariables.headers) {
139
- if (typeof headerMatcher === 'string') {
140
- return ___headers.has(headerMatcher);
141
- }
142
- if (headerMatcher instanceof RegExp) {
143
- return ___headers.toHeaderPairs().some(([key]) => headerMatcher.test(key));
144
- }
145
- if (!___headers.has(headerMatcher.key)) {
146
- return false;
147
- }
148
- if (headerMatcher.value) {
149
- const value = ___headers.get(headerMatcher.key);
150
- if (value === null) {
151
- return false;
152
- }
153
- if (!___matchesValue(headerMatcher.value, value as string)) {
154
- return false;
155
- }
156
- }
157
- }
158
- }
159
- if (matchBuilderVariables.bodyText === null && !!req.body) {
160
- return false;
161
- }
162
- if (matchBuilderVariables.bodyText) {
163
- if (!___matchesValue(matchBuilderVariables.bodyText, req.body)) {
164
- return false;
165
- }
166
- }
167
- if (matchBuilderVariables.bodyJson) {
168
- let json: any;
169
- try {
170
- json = JSON.parse(req.body);
171
- } catch (kiss) {
172
- return false;
173
- }
174
- if (!json) {
175
- return false;
176
- }
177
- for (const jsonMatcher of Array.isArray(matchBuilderVariables.bodyJson)
178
- ? matchBuilderVariables.bodyJson
179
- : [matchBuilderVariables.bodyJson]) {
180
- if (!matchObject(json, jsonMatcher.key, jsonMatcher.value)) {
181
- return false;
182
- }
183
- }
184
- }
185
- if (matchBuilderVariables.bodyGql) {
186
- if (!req.gqlBody) {
187
- return false;
188
- }
189
- if (!___matchesValue(matchBuilderVariables.bodyGql.methodName, req.gqlBody.methodName)) {
190
- return false;
191
- }
192
- if (!___matchesValue(matchBuilderVariables.bodyGql.operationName, req.gqlBody.operationName)) {
193
- return false;
194
- }
195
- if (!___matchesValue(matchBuilderVariables.bodyGql.query, req.gqlBody.query)) {
196
- return false;
197
- }
198
- if (!___matchesValue(matchBuilderVariables.bodyGql.type, req.gqlBody.type)) {
199
- return false;
200
- }
201
- if (!matchBuilderVariables.bodyGql.variables) {
202
- return true;
203
- }
204
- for (const jsonMatcher of Array.isArray(matchBuilderVariables.bodyGql.variables)
205
- ? matchBuilderVariables.bodyGql.variables
206
- : [matchBuilderVariables.bodyGql.variables]) {
207
- if (!matchObject(req.gqlBody.variables, jsonMatcher.key, jsonMatcher.value)) {
208
- return false;
209
- }
210
- }
211
- }
212
- return true;
213
- },
214
- localVariables: { matchBuilderVariables: this._matchBuilderVariables },
215
- },
216
- };
217
- }
218
- }
219
-
220
- class RuleBuilderBase extends RuleBuilderBaseBase {
221
- limitedUse(hitCount: number) {
222
- if (Number.isNaN(hitCount) || !Number.isFinite(hitCount) || !Number.isInteger(hitCount) || hitCount <= 0) {
223
- throw new Error('Invalid hitCount');
224
- }
225
- this.rule.removeAfterUse = hitCount;
226
- return this;
227
- }
228
-
229
- singleUse() {
230
- return this.limitedUse(1);
231
- }
232
-
233
- storeTraffic() {
234
- this.rule.storeTraffic = true;
235
- return this;
236
- }
237
-
238
- disabled() {
239
- this.rule.isEnabled = false;
240
- }
241
- }
242
-
243
- class RuleBuilder extends RuleBuilderBase {
244
- raisePriority(by?: number) {
245
- const subtract = by ?? 1;
246
- if (subtract >= DEFAULT_RULE_PRIORITY) {
247
- throw new Error(`Unable to raise priority over the default ${DEFAULT_RULE_PRIORITY}`);
248
- }
249
- this.rule.priority = DEFAULT_RULE_PRIORITY - subtract;
250
- return this;
251
- }
252
-
253
- decreasePriority(by?: number) {
254
- const add = by ?? 1;
255
- this.rule.priority = DEFAULT_RULE_PRIORITY + add;
256
- return this;
257
- }
258
-
259
- customTtl(ttlSeconds: number) {
260
- if (Number.isNaN(ttlSeconds) || !Number.isInteger(ttlSeconds) || !Number.isFinite(ttlSeconds) || ttlSeconds < 0) {
261
- throw new Error('Invalid ttl');
262
- }
263
- if (ttlSeconds < MIN_RULE_TTL_SECONDS || ttlSeconds > MAX_RULE_TTL_SECONDS) {
264
- throw new Error(
265
- `ttl of ${ttlSeconds} seconds is outside range min: ${MIN_RULE_TTL_SECONDS}, max:${MAX_RULE_TTL_SECONDS}`
266
- );
267
- }
268
- this.rule.ttlSeconds = ttlSeconds;
269
- return this;
270
- }
271
-
272
- customId(id: string) {
273
- this.rule.id = id;
274
- return this;
275
- }
276
-
277
- onRequestTo(filter: string | RegExp): RuleBuilderInitialized {
278
- this._matchBuilderVariables.filter = filter;
279
- return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
280
- }
281
-
282
- onRequestToHostname(hostname: string | RegExp): RuleBuilderInitialized {
283
- this._matchBuilderVariables.hostname = hostname;
284
- return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
285
- }
286
-
287
- onRequestToPathname(pathname: string | RegExp): RuleBuilderInitialized {
288
- this._matchBuilderVariables.pathname = pathname;
289
- return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
290
- }
291
-
292
- onAnyRequest(): RuleBuilderInitialized {
293
- this.rule.matches = { localFn: () => true };
294
- return new RuleBuilderInitialized(this.rule, this._matchBuilderVariables);
295
- }
296
- }
297
-
298
- class RuleBuilderInitialized extends RuleBuilderBase {
299
- withHostname(hostname: string | RegExp) {
300
- this._matchBuilderVariables.hostname = hostname;
301
- return this;
302
- }
303
-
304
- withPathname(pathname: string | RegExp) {
305
- this._matchBuilderVariables.pathname = pathname;
306
- return this;
307
- }
308
-
309
- withPort(port: number | string | RegExp) {
310
- this._matchBuilderVariables.port = port;
311
- return this;
312
- }
313
-
314
- withSearchParam(key: string | RegExp): RuleBuilderInitialized;
315
- withSearchParam(key: string, value?: string | RegExp): RuleBuilderInitialized;
316
- withSearchParam(key: string | RegExp, value?: string | RegExp): RuleBuilderInitialized {
317
- if (!this._matchBuilderVariables.searchParams) {
318
- this._matchBuilderVariables.searchParams = [];
319
- }
320
- if (!key) {
321
- throw new Error('key cannot be empty');
322
- }
323
- if (!value) {
324
- this._matchBuilderVariables.searchParams.push(key);
325
- return this;
326
- }
327
- if (key instanceof RegExp) {
328
- throw new Error('Unsupported regex param key with value');
329
- }
330
- this._matchBuilderVariables.searchParams.push({ key, value });
331
- return this;
332
- }
333
-
334
- withSearchParams(params: KeyValueMatcher[]): RuleBuilderInitialized {
335
- if (!this._matchBuilderVariables.searchParams) {
336
- this._matchBuilderVariables.searchParams = [];
337
- }
338
- for (const param of params) {
339
- if (typeof param === 'string' || param instanceof RegExp) {
340
- this.withSearchParam(param);
341
- } else {
342
- this.withSearchParam(param.key, param.value);
343
- }
344
- }
345
- return this;
346
- }
347
-
348
- withHeader(key: string | RegExp): RuleBuilderInitialized;
349
- withHeader(key: string, value?: string | RegExp): RuleBuilderInitialized;
350
- withHeader(key: string | RegExp, value?: string | RegExp): RuleBuilderInitialized {
351
- if (!this._matchBuilderVariables.headers) {
352
- this._matchBuilderVariables.headers = [];
353
- }
354
- if (!key) {
355
- throw new Error('key cannot be empty');
356
- }
357
- if (!value) {
358
- this._matchBuilderVariables.headers.push(key);
359
- return this;
360
- }
361
- if (key instanceof RegExp) {
362
- throw new Error('Unsupported regex param key with value');
363
- }
364
- this._matchBuilderVariables.headers.push({ key, value });
365
- return this;
366
- }
367
-
368
- withHeaders(headers: KeyValueMatcher[]): RuleBuilderInitialized {
369
- if (!this._matchBuilderVariables.headers) {
370
- this._matchBuilderVariables.headers = [];
371
- }
372
- for (const header of headers) {
373
- if (typeof header === 'string' || header instanceof RegExp) {
374
- this.withHeader(header);
375
- } else {
376
- this.withHeader(header.key, header.value);
377
- }
378
- }
379
- return this;
380
- }
381
-
382
- withBodyText(includes: string): RuleBuilderInitialized;
383
- withBodyText(matches: RegExp): RuleBuilderInitialized;
384
- withBodyText(includesOrMatches: string | RegExp): RuleBuilderInitialized {
385
- this._matchBuilderVariables.bodyText = includesOrMatches;
386
- return this;
387
- }
388
-
389
- withoutBody(): RuleBuilderInitialized {
390
- this._matchBuilderVariables.bodyText = null;
391
- return this;
392
- }
393
-
394
- withBodyJson(hasKey: string): RuleBuilderInitialized;
395
- withBodyJson(hasKey: string, withValue: ObjectValueMatcher): RuleBuilderInitialized;
396
- withBodyJson(matches: ObjectKeyValueMatcher): RuleBuilderInitialized;
397
- withBodyJson(keyOrMatcher: string | ObjectKeyValueMatcher, withValue?: ObjectValueMatcher): RuleBuilderInitialized {
398
- const keyRegex = /^(?:(?:[a-z0-9_-]+)|(?:\[[0-9]*\]))(?:\.(?:(?:[a-z0-9_-]+)|(?:\[[0-9]*\])))*$/i;
399
- if (!this._matchBuilderVariables.bodyJson) {
400
- this._matchBuilderVariables.bodyJson = [];
401
- }
402
- if (typeof keyOrMatcher === 'string') {
403
- if (!keyRegex.test(keyOrMatcher)) {
404
- throw new Error('invalid key');
405
- }
406
- this._matchBuilderVariables.bodyJson.push({ key: keyOrMatcher, value: withValue });
407
- return this;
408
- }
409
- if (withValue !== undefined) {
410
- throw new Error('invalid usage');
411
- }
412
- if (!keyRegex.test(keyOrMatcher.key)) {
413
- throw new Error('invalid key');
414
- }
415
- this._matchBuilderVariables.bodyJson.push(keyOrMatcher);
416
- return this;
417
- }
418
-
419
- withBodyGql(gqlMatcher: GQLRequestMatcher): RuleBuilderInitialized {
420
- this._matchBuilderVariables.bodyGql = gqlMatcher;
421
- return this;
422
- }
423
-
424
- proxyPass(): Stuntman.SerializableRule {
425
- return this.rule;
426
- }
427
-
428
- mockResponse(staticResponse: Stuntman.Response): Stuntman.SerializableRule;
429
- mockResponse(generationFunction: Stuntman.RemotableFunction<Stuntman.ResponseGenerationFn>): Stuntman.SerializableRule;
430
- mockResponse(
431
- response: Stuntman.Response | Stuntman.RemotableFunction<Stuntman.ResponseGenerationFn>
432
- ): Stuntman.SerializableRule {
433
- this.rule.actions = { mockResponse: response };
434
- return this.rule;
435
- }
436
-
437
- modifyRequest(modifyFunction: Stuntman.RemotableFunction<Stuntman.RequestManipulationFn>): RuleBuilderRequestInitialized {
438
- this.rule.actions = { modifyRequest: modifyFunction };
439
- return new RuleBuilderRequestInitialized(this.rule, this._matchBuilderVariables);
440
- }
441
-
442
- modifyResponse(modifyFunction: Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>): Stuntman.SerializableRule {
443
- this.rule.actions = { modifyResponse: modifyFunction };
444
- return this.rule;
445
- }
446
- }
447
-
448
- class RuleBuilderRequestInitialized extends RuleBuilderBase {
449
- modifyResponse(modifyFunction: Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>): Stuntman.SerializableRule {
450
- if (!this.rule.actions) {
451
- throw new Error('rule.actions not defined - builder implementation error');
452
- }
453
- this.rule.actions.modifyResponse = modifyFunction;
454
- return this.rule;
455
- }
456
- }
457
-
458
- export const ruleBuilder = () => new RuleBuilder();
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2018",
4
- "module": "commonjs",
5
- "rootDir": "src",
6
- "declaration": true,
7
- "outDir": "dist",
8
- "esModuleInterop": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "strict": true,
11
- "skipLibCheck": true,
12
- "typeRoots": ["node_modules/@types"],
13
- "allowJs": true,
14
- "moduleResolution": "node16"
15
- }
16
- }