@stuntman/client 0.1.4 → 0.1.6

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,23 @@
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
+ apiKey?: string;
8
+ };
9
+ export declare class Client {
10
+ private options;
11
+ private get baseUrl();
12
+ constructor(options?: ClientOptions);
13
+ private fetch;
14
+ getRules(): Promise<Stuntman.LiveRule[]>;
15
+ getRule(id: string): Promise<Stuntman.LiveRule>;
16
+ disableRule(id: string): Promise<void>;
17
+ enableRule(id: string): Promise<void>;
18
+ removeRule(id: string): Promise<void>;
19
+ addRule(rule: Stuntman.SerializableRule): Promise<Stuntman.Rule>;
20
+ getTraffic(rule: Stuntman.Rule): Promise<Stuntman.LogEntry[]>;
21
+ getTraffic(ruleIdOrLabel: string): Promise<Stuntman.LogEntry[]>;
22
+ }
23
+ export {};
@@ -0,0 +1,170 @@
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, {
111
+ ...init,
112
+ headers: {
113
+ ...(this.options.apiKey && { 'x-api-key': this.options.apiKey }),
114
+ ...init === null || init === void 0 ? void 0 : init.headers,
115
+ },
116
+ signal: (_a = init === null || init === void 0 ? void 0 : init.signal) !== null && _a !== void 0 ? _a : controller.signal,
117
+ });
118
+ if (!response.ok) {
119
+ const text = await response.text();
120
+ let json;
121
+ try {
122
+ json = JSON.parse(text);
123
+ }
124
+ catch (kiss) {
125
+ // and swallow
126
+ }
127
+ if (json && 'error' in json) {
128
+ throw new clientError_1.ClientError(json.error);
129
+ }
130
+ throw new Error(`Unexpected errror: ${text}`);
131
+ }
132
+ return response;
133
+ }
134
+ finally {
135
+ clearTimeout(timeout);
136
+ }
137
+ }
138
+ async getRules() {
139
+ const response = await this.fetch(`${this.baseUrl}/rules`);
140
+ return (await response.json());
141
+ }
142
+ async getRule(id) {
143
+ const response = await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}`);
144
+ return (await response.json());
145
+ }
146
+ async disableRule(id) {
147
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/disable`);
148
+ }
149
+ async enableRule(id) {
150
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/enable`);
151
+ }
152
+ async removeRule(id) {
153
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/remove`);
154
+ }
155
+ async addRule(rule) {
156
+ const serializedRule = serializeRemotableFunctions(rule);
157
+ const response = await this.fetch(`${this.baseUrl}/rule`, {
158
+ method: 'POST',
159
+ body: JSON.stringify(serializedRule),
160
+ headers: { 'content-type': 'application/json' },
161
+ });
162
+ return (await response.json());
163
+ }
164
+ async getTraffic(ruleOrIdOrLabel) {
165
+ const ruleId = typeof ruleOrIdOrLabel === 'object' ? ruleOrIdOrLabel.id : ruleOrIdOrLabel;
166
+ const response = await this.fetch(`${this.baseUrl}/traffic${ruleId ? `/${encodeURIComponent(ruleId)}` : ''}`);
167
+ return (await response.json());
168
+ }
169
+ }
170
+ 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,2 @@
1
+ export { Client as StuntmanClient } from './apiClient';
2
+ export { ruleBuilder } from './ruleBuilder';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ruleBuilder = exports.StuntmanClient = void 0;
4
+ var apiClient_1 = require("./apiClient");
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; } });
@@ -0,0 +1,79 @@
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
+ onRequestToPort(port: string | number | RegExp): RuleBuilderInitialized;
49
+ onAnyRequest(): RuleBuilderInitialized;
50
+ }
51
+ declare class RuleBuilderInitialized extends RuleBuilderBase {
52
+ withHostname(hostname: string | RegExp): this;
53
+ withPathname(pathname: string | RegExp): this;
54
+ withPort(port: number | string | RegExp): this;
55
+ withSearchParam(key: string | RegExp): RuleBuilderInitialized;
56
+ withSearchParam(key: string, value?: string | RegExp): RuleBuilderInitialized;
57
+ withSearchParams(params: KeyValueMatcher[]): RuleBuilderInitialized;
58
+ withHeader(key: string | RegExp): RuleBuilderInitialized;
59
+ withHeader(key: string, value?: string | RegExp): RuleBuilderInitialized;
60
+ withHeaders(...headers: KeyValueMatcher[]): RuleBuilderInitialized;
61
+ withBodyText(includes: string): RuleBuilderInitialized;
62
+ withBodyText(matches: RegExp): RuleBuilderInitialized;
63
+ withoutBody(): RuleBuilderInitialized;
64
+ withBodyJson(hasKey: string): RuleBuilderInitialized;
65
+ withBodyJson(hasKey: string, withValue: ObjectValueMatcher): RuleBuilderInitialized;
66
+ withBodyJson(matches: ObjectKeyValueMatcher): RuleBuilderInitialized;
67
+ withBodyGql(gqlMatcher: GQLRequestMatcher): RuleBuilderInitialized;
68
+ proxyPass(): Stuntman.SerializableRule;
69
+ mockResponse(staticResponse: Stuntman.Response): Stuntman.SerializableRule;
70
+ mockResponse(generationFunction: Stuntman.RemotableFunction<Stuntman.ResponseGenerationFn>): Stuntman.SerializableRule;
71
+ mockResponse(localFn: Stuntman.ResponseGenerationFn, localVariables?: Stuntman.LocalVariables): Stuntman.SerializableRule;
72
+ modifyRequest(modifyFunction: Stuntman.RequestManipulationFn | Stuntman.RemotableFunction<Stuntman.RequestManipulationFn>, localVariables?: Stuntman.LocalVariables): RuleBuilderRequestInitialized;
73
+ modifyResponse(modifyFunction: Stuntman.ResponseManipulationFn | Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>, localVariables?: Stuntman.LocalVariables): Stuntman.SerializableRule;
74
+ }
75
+ declare class RuleBuilderRequestInitialized extends RuleBuilderBase {
76
+ modifyResponse(modifyFunction: Stuntman.ResponseManipulationFn | Stuntman.RemotableFunction<Stuntman.ResponseManipulationFn>, localVariables?: Stuntman.LocalVariables): Stuntman.SerializableRule;
77
+ }
78
+ export declare const ruleBuilder: () => RuleBuilder;
79
+ export {};