@stuntman/client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
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 ADDED
@@ -0,0 +1,16 @@
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
+ }