@stuntman/client 0.1.0 → 0.1.1
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/{src/clientTestExample.ts → README.md} +11 -4
- package/package.json +9 -2
- package/src/apiClient.ts +0 -181
- package/src/clientError.ts +0 -22
- package/src/index.ts +0 -1
- package/src/ruleBuilder.ts +0 -458
- package/tsconfig.json +0 -16
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
|
|
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
|
-
.
|
|
11
|
-
.
|
|
16
|
+
.onRequestToHostname('example.com')
|
|
17
|
+
.withSearchParam('user', uniqueQaUserEmail)
|
|
12
18
|
.mockResponse({
|
|
13
|
-
localFn: (req
|
|
19
|
+
localFn: (req) => {
|
|
14
20
|
if (JSON.parse(req.body).email !== uniqueQaUserEmail) {
|
|
15
21
|
return {
|
|
16
22
|
status: 500,
|
|
@@ -22,3 +28,4 @@ const rule = ruleBuilder()
|
|
|
22
28
|
});
|
|
23
29
|
|
|
24
30
|
client.addRule(rule).then((x) => console.log(x));
|
|
31
|
+
```
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stuntman/client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
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.
|
|
35
|
+
"@stuntman/shared": "^0.1.1",
|
|
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",
|
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
|
-
}
|
package/src/clientError.ts
DELETED
|
@@ -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';
|
package/src/ruleBuilder.ts
DELETED
|
@@ -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
|
-
}
|