-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrequestBuilder.ts
More file actions
342 lines (307 loc) · 9.15 KB
/
requestBuilder.ts
File metadata and controls
342 lines (307 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { USER_AGENT } from './consts';
import {
type ExecuteOptions,
type HttpBodyType,
type HttpExecuteConfig,
type JsonDict,
ParameterLocation,
} from './types';
import { StackOneAPIError } from './utils/errors';
interface SerializationOptions {
maxDepth?: number;
strictValidation?: boolean;
}
class ParameterSerializationError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ParameterSerializationError';
}
}
/**
* Builds and executes HTTP requests for tools declared with kind:'http'.
*/
export class RequestBuilder {
private method: string;
private url: string;
private bodyType: HttpBodyType;
private params: HttpExecuteConfig['params'];
private headers: Record<string, string>;
constructor(config: HttpExecuteConfig, headers: Record<string, string> = {}) {
this.method = config.method;
this.url = config.url;
this.bodyType = config.bodyType;
this.params = config.params;
this.headers = { ...headers };
}
/**
* Set headers for the request
*/
setHeaders(headers: Record<string, string>): RequestBuilder {
this.headers = { ...this.headers, ...headers };
return this;
}
/**
* Get the current headers
*/
getHeaders(): Record<string, string> {
return { ...this.headers };
}
/**
* Prepare headers for the API request
*/
prepareHeaders(): Record<string, string> {
return {
'User-Agent': USER_AGENT,
...this.headers,
};
}
/**
* Prepare URL and parameters for the API request
*/
prepareRequestParams(params: JsonDict): [string, JsonDict, JsonDict] {
let url = this.url;
const bodyParams: JsonDict = {};
const queryParams: JsonDict = {};
for (const [key, value] of Object.entries(params)) {
// Find the parameter configuration in the params array
const paramConfig = this.params.find((p) => p.name === key);
const paramLocation = paramConfig?.location;
switch (paramLocation) {
case ParameterLocation.PATH:
// Replace path parameter in URL
url = url.replace(`{${key}}`, encodeURIComponent(String(value)));
break;
case ParameterLocation.QUERY:
// Add to query parameters
queryParams[key] = value;
break;
case ParameterLocation.HEADER:
// Add to headers
this.headers[key] = String(value);
break;
case ParameterLocation.BODY:
// Add to body parameters
bodyParams[key] = value;
break;
default:
paramLocation satisfies undefined; // exhaustive check
// Default to body parameters
bodyParams[key] = value;
break;
}
}
return [url, bodyParams, queryParams];
}
/**
* Build the fetch options for the request
*/
buildFetchOptions(bodyParams: JsonDict): RequestInit {
const headers = this.prepareHeaders();
const fetchOptions: RequestInit = {
method: this.method,
headers,
};
// Handle different body types
if (Object.keys(bodyParams).length > 0) {
switch (this.bodyType) {
case 'json': {
const headersRecord = fetchOptions.headers as Record<string, string>;
fetchOptions.headers = {
...headersRecord,
'Content-Type': 'application/json',
};
fetchOptions.body = JSON.stringify(bodyParams);
break;
}
case 'form': {
const headersRecord = fetchOptions.headers as Record<string, string>;
fetchOptions.headers = {
...headersRecord,
'Content-Type': 'application/x-www-form-urlencoded',
};
const formBody = new URLSearchParams();
for (const [key, value] of Object.entries(bodyParams)) {
formBody.append(key, String(value));
}
fetchOptions.body = formBody.toString();
break;
}
case 'multipart-form': {
// Handle file uploads
const formData = new FormData();
for (const [key, value] of Object.entries(bodyParams)) {
formData.append(key, String(value));
}
fetchOptions.body = formData;
// Don't set Content-Type for FormData, it will be set automatically with the boundary
break;
}
default: {
this.bodyType satisfies never;
throw new Error(`Unsupported HTTP body type: ${String(this.bodyType)}`);
}
}
}
return fetchOptions;
}
/**
* Validates parameter keys to prevent injection attacks
*/
private validateParameterKey(key: string): void {
if (!/^[a-zA-Z0-9_.-]+$/.test(key)) {
throw new ParameterSerializationError(`Invalid parameter key: ${key}`);
}
}
/**
* Safely serializes values to strings with special type handling
*/
private serializeValue(value: unknown): string {
if (value instanceof Date) {
return value.toISOString();
}
if (value instanceof RegExp) {
return value.toString();
}
if (typeof value === 'function') {
throw new ParameterSerializationError('Functions cannot be serialized as parameters');
}
if (value == null) {
return '';
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number' || typeof value === 'boolean') {
return String(value);
}
// For objects and arrays, use JSON serialization
return JSON.stringify(value);
}
/**
* Serialize an object into deep object query parameters with security protections
* Converts {filter: {updated_after: "2020-01-01", job_id: "123"}}
* to filter[updated_after]=2020-01-01&filter[job_id]=123
*/
private serializeDeepObject(
obj: unknown,
prefix: string,
depth = 0,
visited = new WeakSet<object>(),
options: SerializationOptions = {},
): [string, string][] {
const maxDepth = options.maxDepth ?? 10;
const strictValidation = options.strictValidation ?? true;
const params: [string, string][] = [];
// Recursion depth protection
if (depth > maxDepth) {
throw new ParameterSerializationError(
`Maximum nesting depth (${maxDepth}) exceeded for parameter serialization`,
);
}
if (obj == null) {
return params;
}
if (typeof obj === 'object' && !Array.isArray(obj)) {
// Circular reference protection
if (visited.has(obj)) {
throw new ParameterSerializationError('Circular reference detected in parameter object');
}
visited.add(obj);
try {
for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
if (strictValidation) {
this.validateParameterKey(key);
}
const nestedKey = `${prefix}[${key}]`;
if (value != null) {
if (this.shouldUseDeepObjectSerialization(key, value)) {
// Recursively handle nested objects
params.push(
...this.serializeDeepObject(value, nestedKey, depth + 1, visited, options),
);
} else {
params.push([nestedKey, this.serializeValue(value)]);
}
}
}
} finally {
// Remove from visited set to allow the same object in different branches
visited.delete(obj);
}
} else {
// For non-object values, use the prefix as-is
params.push([prefix, this.serializeValue(obj)]);
}
return params;
}
/**
* Check if a parameter should use deep object serialization
* Applies to all plain object parameters (excludes special types and arrays)
*/
private shouldUseDeepObjectSerialization(_key: string, value: unknown): boolean {
return (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
!(value instanceof Date) &&
!(value instanceof RegExp) &&
typeof value !== 'function'
);
}
/**
* Builds all query parameters with optimized batching
*/
private buildQueryParameters(queryParams: JsonDict): [string, string][] {
const allParams: [string, string][] = [];
for (const [key, value] of Object.entries(queryParams)) {
if (this.shouldUseDeepObjectSerialization(key, value)) {
// Use deep object serialization for complex parameters
allParams.push(...this.serializeDeepObject(value, key));
} else {
// Use safe string conversion for primitive values
allParams.push([key, this.serializeValue(value)]);
}
}
return allParams;
}
/**
* Execute the request
*/
async execute(params: JsonDict, options?: ExecuteOptions): Promise<JsonDict> {
// Prepare request parameters
const [url, bodyParams, queryParams] = this.prepareRequestParams(params);
// Prepare URL with query parameters using optimized batching
const urlWithQuery = new URL(url);
const serializedParams = this.buildQueryParameters(queryParams);
// Batch append all parameters
for (const [paramKey, paramValue] of serializedParams) {
urlWithQuery.searchParams.append(paramKey, paramValue);
}
// Build fetch options
const fetchOptions = this.buildFetchOptions(bodyParams);
// If dryRun is true, return the request details instead of making the API call
if (options?.dryRun) {
return {
url: urlWithQuery.toString(),
method: this.method,
headers: fetchOptions.headers,
body: fetchOptions.body instanceof FormData ? '[FormData]' : fetchOptions.body,
mappedParams: params,
};
}
// Execute the request
const response = await fetch(urlWithQuery.toString(), fetchOptions);
// Check if the response is OK
if (!response.ok) {
const responseBody = await response.json().catch(() => null);
throw new StackOneAPIError(
`API request failed with status ${response.status} for ${url}`,
response.status,
responseBody,
bodyParams,
);
}
// Parse the response
return (await response.json()) as JsonDict;
}
}