@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Andrzej Pasterczyk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,22 @@
1
+ import type * as Stuntman from '@stuntman/shared';
2
+ type ClientOptions = {
3
+ protocol?: 'http' | 'https';
4
+ host?: string;
5
+ port?: number;
6
+ timeout?: number;
7
+ };
8
+ export declare class Client {
9
+ private options;
10
+ private get baseUrl();
11
+ constructor(options?: ClientOptions);
12
+ private fetch;
13
+ getRules(): Promise<Stuntman.LiveRule[]>;
14
+ getRule(id: string): Promise<Stuntman.LiveRule>;
15
+ disableRule(id: string): Promise<void>;
16
+ enableRule(id: string): Promise<void>;
17
+ removeRule(id: string): Promise<void>;
18
+ addRule(rule: Stuntman.SerializableRule): Promise<Stuntman.Rule>;
19
+ getTraffic(rule: Stuntman.Rule): Promise<Record<string, Stuntman.LogEntry>>;
20
+ getTraffic(ruleIdOrLabel: string): Promise<Record<string, Stuntman.LogEntry>>;
21
+ }
22
+ export {};
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Client = void 0;
7
+ const serialize_javascript_1 = __importDefault(require("serialize-javascript"));
8
+ const clientError_1 = require("./clientError");
9
+ const shared_1 = require("@stuntman/shared");
10
+ const SERIALIZE_JAVASCRIPT_OPTIONS = {
11
+ unsafe: true,
12
+ ignoreFunction: true,
13
+ };
14
+ const getFunctionParams = (func) => {
15
+ const funstr = func.toString();
16
+ const params = funstr.slice(funstr.indexOf('(') + 1, funstr.indexOf(')')).match(/([^\s,]+)/g) || new Array();
17
+ if (params.includes('=')) {
18
+ throw new Error('default argument values are not supported');
19
+ }
20
+ return params;
21
+ };
22
+ const serializeApiFunction = (fn, variables) => {
23
+ const variableInitializer = [];
24
+ const functionParams = getFunctionParams(fn);
25
+ if (variables) {
26
+ for (const varName of Object.keys(variables)) {
27
+ let varValue = variables[varName];
28
+ if (varValue === undefined || varValue === null || typeof varValue === 'number' || typeof varValue === 'boolean') {
29
+ varValue = `${varValue}`;
30
+ }
31
+ else if (typeof varValue === 'string') {
32
+ varValue = `${(0, serialize_javascript_1.default)(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS)}`;
33
+ }
34
+ else {
35
+ varValue = `eval('(${(0, serialize_javascript_1.default)(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS).replace(/'/g, "\\'")})')`;
36
+ }
37
+ variableInitializer.push(`const ${varName} = ${varValue};`);
38
+ }
39
+ }
40
+ const functionString = fn.toString();
41
+ const serializedHeader = `return ((${functionParams.map((_param, index) => `____arg${index}`).join(',')}) => {`;
42
+ const serializedParams = `${functionParams
43
+ .map((_param, index) => `const ${functionParams[index]} = ____arg${index};`)
44
+ .join('\n')}`;
45
+ const serializedVariables = `${variableInitializer.join('\n')}`;
46
+ // prettier-ignore
47
+ const serializedFunction = `return (${functionString.substring(0, functionString.indexOf('('))}()${functionString.substring(functionString.indexOf(')') + 1)})(); })(${functionParams.map((_param, index) => `____arg${index}`).join(',')})`;
48
+ if (!serializedParams && !serializedVariables) {
49
+ return `${serializedHeader}${serializedFunction}`;
50
+ }
51
+ return [serializedHeader, serializedParams, serializedVariables, serializedFunction].filter((x) => !!x).join('\n');
52
+ };
53
+ const keysOf = (obj) => {
54
+ return Array.from(Object.keys(obj));
55
+ };
56
+ const serializeRemotableFunctions = (obj) => {
57
+ const objectKeys = keysOf(obj);
58
+ if (!objectKeys || objectKeys.length === 0) {
59
+ return obj;
60
+ }
61
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
62
+ // @ts-ignore
63
+ const output = {};
64
+ for (const key of objectKeys) {
65
+ if (typeof obj[key] === 'object') {
66
+ if ('localFn' in obj[key]) {
67
+ const remotableFunction = obj[key];
68
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
69
+ // @ts-ignore
70
+ output[key] = {
71
+ remoteFn: serializeApiFunction(remotableFunction.localFn, remotableFunction.localVariables),
72
+ localFn: remotableFunction.localFn.toString(),
73
+ localVariables: (0, serialize_javascript_1.default)(remotableFunction.localVariables, SERIALIZE_JAVASCRIPT_OPTIONS),
74
+ };
75
+ }
76
+ else {
77
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
78
+ // @ts-ignore
79
+ output[key] = serializeRemotableFunctions(obj[key]);
80
+ }
81
+ }
82
+ else {
83
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
84
+ // @ts-ignore
85
+ output[key] = obj[key];
86
+ }
87
+ }
88
+ return output;
89
+ };
90
+ class Client {
91
+ get baseUrl() {
92
+ return `${this.options.protocol}://${this.options.host}${this.options.port ? `:${this.options.port}` : ''}`;
93
+ }
94
+ constructor(options) {
95
+ this.options = {
96
+ ...options,
97
+ timeout: (options === null || options === void 0 ? void 0 : options.timeout) || 60000,
98
+ host: (options === null || options === void 0 ? void 0 : options.host) || 'localhost',
99
+ protocol: (options === null || options === void 0 ? void 0 : options.protocol) || 'http',
100
+ port: (options === null || options === void 0 ? void 0 : options.port) || (options === null || options === void 0 ? void 0 : options.protocol) ? (options.protocol === 'https' ? 443 : 80) : shared_1.DEFAULT_API_PORT,
101
+ };
102
+ }
103
+ async fetch(url, init) {
104
+ var _a;
105
+ const controller = new AbortController();
106
+ const timeout = setTimeout(() => {
107
+ controller.abort();
108
+ }, this.options.timeout);
109
+ try {
110
+ const response = await fetch(url, { ...init, signal: (_a = init === null || init === void 0 ? void 0 : init.signal) !== null && _a !== void 0 ? _a : controller.signal });
111
+ if (!response.ok) {
112
+ const text = await response.text();
113
+ let json;
114
+ try {
115
+ json = JSON.parse(text);
116
+ }
117
+ catch (kiss) {
118
+ // and swallow
119
+ }
120
+ if ('error' in json) {
121
+ throw new clientError_1.ClientError(json.error);
122
+ }
123
+ throw new Error(`Unexpected errror: ${text}`);
124
+ }
125
+ return response;
126
+ }
127
+ finally {
128
+ clearTimeout(timeout);
129
+ }
130
+ }
131
+ async getRules() {
132
+ const response = await this.fetch(`${this.baseUrl}/rules`);
133
+ return response.json();
134
+ }
135
+ async getRule(id) {
136
+ const response = await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}`);
137
+ return response.json();
138
+ }
139
+ async disableRule(id) {
140
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/disable`);
141
+ }
142
+ async enableRule(id) {
143
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/enable`);
144
+ }
145
+ async removeRule(id) {
146
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/remove`);
147
+ }
148
+ async addRule(rule) {
149
+ const serializedRule = serializeRemotableFunctions(rule);
150
+ const response = await this.fetch(`${this.baseUrl}/rule`, {
151
+ method: 'POST',
152
+ body: JSON.stringify(serializedRule),
153
+ headers: { 'content-type': 'application/json' },
154
+ });
155
+ return response.json();
156
+ }
157
+ async getTraffic(ruleOrIdOrLabel) {
158
+ const ruleId = typeof ruleOrIdOrLabel === 'object' ? ruleOrIdOrLabel.id : ruleOrIdOrLabel;
159
+ const response = await this.fetch(`${this.baseUrl}/traffic${ruleId ? `/${encodeURIComponent(ruleId)}` : ''}`);
160
+ return response.json();
161
+ }
162
+ }
163
+ exports.Client = Client;
@@ -0,0 +1,18 @@
1
+ import { AppError } from '@stuntman/shared';
2
+ import type * as Stuntman from '@stuntman/shared';
3
+ export declare enum HttpCode {
4
+ OK = 200,
5
+ NO_CONTENT = 204,
6
+ BAD_REQUEST = 400,
7
+ UNAUTHORIZED = 401,
8
+ NOT_FOUND = 404,
9
+ CONFLICT = 409,
10
+ UNPROCESSABLE_ENTITY = 422,
11
+ INTERNAL_SERVER_ERROR = 500
12
+ }
13
+ export declare class ClientError extends AppError {
14
+ readonly originalStack?: string;
15
+ constructor(args: Stuntman.AppError & {
16
+ stack?: string;
17
+ });
18
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientError = exports.HttpCode = void 0;
4
+ const shared_1 = require("@stuntman/shared");
5
+ var HttpCode;
6
+ (function (HttpCode) {
7
+ HttpCode[HttpCode["OK"] = 200] = "OK";
8
+ HttpCode[HttpCode["NO_CONTENT"] = 204] = "NO_CONTENT";
9
+ HttpCode[HttpCode["BAD_REQUEST"] = 400] = "BAD_REQUEST";
10
+ HttpCode[HttpCode["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
11
+ HttpCode[HttpCode["NOT_FOUND"] = 404] = "NOT_FOUND";
12
+ HttpCode[HttpCode["CONFLICT"] = 409] = "CONFLICT";
13
+ HttpCode[HttpCode["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
14
+ HttpCode[HttpCode["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
15
+ })(HttpCode = exports.HttpCode || (exports.HttpCode = {}));
16
+ class ClientError extends shared_1.AppError {
17
+ constructor(args) {
18
+ super(args);
19
+ this.originalStack = args.stack;
20
+ }
21
+ }
22
+ exports.ClientError = ClientError;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
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));
@@ -0,0 +1 @@
1
+ export { Client as StuntmanClient } from './apiClient';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StuntmanClient = void 0;
4
+ var apiClient_1 = require("./apiClient");
5
+ Object.defineProperty(exports, "StuntmanClient", { enumerable: true, get: function () { return apiClient_1.Client; } });
@@ -0,0 +1,77 @@
1
+ import type * as Stuntman from '@stuntman/shared';
2
+ type KeyValueMatcher = string | RegExp | {
3
+ key: string;
4
+ value?: string | RegExp;
5
+ };
6
+ type ObjectValueMatcher = string | RegExp | number | boolean | null;
7
+ type ObjectKeyValueMatcher = {
8
+ key: string;
9
+ value?: ObjectValueMatcher;
10
+ };
11
+ type GQLRequestMatcher = {
12
+ operationName?: string | RegExp;
13
+ variables?: ObjectKeyValueMatcher[];
14
+ query?: string | RegExp;
15
+ type?: 'query' | 'mutation';
16
+ methodName?: string | RegExp;
17
+ };
18
+ type MatchBuilderVariables = {
19
+ filter?: string | RegExp;
20
+ hostname?: string | RegExp;
21
+ pathname?: string | RegExp;
22
+ port?: number | string | RegExp;
23
+ searchParams?: KeyValueMatcher[];
24
+ headers?: KeyValueMatcher[];
25
+ bodyText?: string | RegExp | null;
26
+ bodyJson?: ObjectKeyValueMatcher[];
27
+ bodyGql?: GQLRequestMatcher;
28
+ };
29
+ declare class RuleBuilderBaseBase {
30
+ protected rule: Stuntman.SerializableRule;
31
+ protected _matchBuilderVariables: MatchBuilderVariables;
32
+ constructor(rule?: Stuntman.SerializableRule, _matchBuilderVariables?: MatchBuilderVariables);
33
+ }
34
+ declare class RuleBuilderBase extends RuleBuilderBaseBase {
35
+ limitedUse(hitCount: number): this;
36
+ singleUse(): this;
37
+ storeTraffic(): this;
38
+ disabled(): void;
39
+ }
40
+ declare class RuleBuilder extends RuleBuilderBase {
41
+ raisePriority(by?: number): this;
42
+ decreasePriority(by?: number): this;
43
+ customTtl(ttlSeconds: number): this;
44
+ customId(id: string): this;
45
+ onRequestTo(filter: string | RegExp): RuleBuilderInitialized;
46
+ onRequestToHostname(hostname: string | RegExp): RuleBuilderInitialized;
47
+ onRequestToPathname(pathname: string | RegExp): RuleBuilderInitialized;
48
+ onAnyRequest(): RuleBuilderInitialized;
49
+ }
50
+ declare class RuleBuilderInitialized extends RuleBuilderBase {
51
+ withHostname(hostname: string | RegExp): this;
52
+ withPathname(pathname: string | RegExp): this;
53
+ withPort(port: number | string | RegExp): this;
54
+ withSearchParam(key: string | RegExp): RuleBuilderInitialized;
55
+ withSearchParam(key: string, value?: string | RegExp): RuleBuilderInitialized;
56
+ withSearchParams(params: KeyValueMatcher[]): RuleBuilderInitialized;
57
+ withHeader(key: string | RegExp): RuleBuilderInitialized;
58
+ withHeader(key: string, value?: string | RegExp): RuleBuilderInitialized;
59
+ withHeaders(headers: KeyValueMatcher[]): RuleBuilderInitialized;
60
+ withBodyText(includes: string): RuleBuilderInitialized;
61
+ withBodyText(matches: RegExp): RuleBuilderInitialized;
62
+ withoutBody(): RuleBuilderInitialized;
63
+ withBodyJson(hasKey: string): RuleBuilderInitialized;
64
+ withBodyJson(hasKey: string, withValue: ObjectValueMatcher): RuleBuilderInitialized;
65
+ withBodyJson(matches: ObjectKeyValueMatcher): RuleBuilderInitialized;
66
+ withBodyGql(gqlMatcher: GQLRequestMatcher): RuleBuilderInitialized;
67
+ proxyPass(): Stuntman.SerializableRule;
68
+ mockResponse(staticResponse: Stuntman.Response): Stuntman.SerializableRule;
69
+ mockResponse(generationFunction: Stuntman.RemotableFunction<Stuntman.ResponseGenerationFn>): Stuntman.SerializableRule;
70
+ modifyRequest(modifyFunction: Stuntman.RemotableFunction<Stuntman.RequestManipulationFn>): RuleBuilderRequestInitialized;
71
+ modifyResponse(modifyFunction: Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>): Stuntman.SerializableRule;
72
+ }
73
+ declare class RuleBuilderRequestInitialized extends RuleBuilderBase {
74
+ modifyResponse(modifyFunction: Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>): Stuntman.SerializableRule;
75
+ }
76
+ export declare const ruleBuilder: () => RuleBuilder;
77
+ export {};