All files / src requestBuilder.ts

88.8% Statements 111/125
78.82% Branches 67/85
93.75% Functions 15/16
89.43% Lines 110/123

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398                                      103x 103x                 75x 75x                                             871x 871x 871x 871x 871x             54x 54x             171x             491x                   511x 511x 511x   511x   672x 534x   534x     30x 30x     501x 501x     1x 1x     2x 2x                 511x             440x 440x           440x 33x   12x 12x       12x 12x     8x 8x       8x 8x 16x   8x 8x       13x 13x 28x   13x   13x                 440x             762x 100x               535x 2x   533x 2x   531x 1x   530x     530x 362x   168x 114x     54x                             625x 625x 625x     625x 1x         624x       624x   624x 1x   623x   623x 623x 762x 762x     662x 662x 660x   130x       530x           623x             509x               1160x                           510x   510x 500x   495x     5x       407x                                 510x     510x 510x     510x 532x       407x     407x     391x               391x           391x                   16x     16x 3x 3x                     13x 510x 10x           3x      
import type { JsonValue } from 'type-fest';
import { USER_AGENT } from './consts';
import {
	type ExecuteOptions,
	type HttpBodyType,
	type HttpExecuteConfig,
	type JsonObject,
	ParameterLocation,
} from './types';
import { binaryDownloadFromResponse, isJsonContentType } from './utils/binary-response';
import { StackOneAPIError } from './utils/error-stackone-api';
 
interface SerializationOptions {
	maxDepth?: number;
	strictValidation?: boolean;
}
 
class ParameterSerializationError extends Error {
	constructor(message: string, options?: ErrorOptions) {
		super(message, options);
		this.name = 'ParameterSerializationError';
	}
}
 
/**
 * Convert a JsonValue to a string representation suitable for URLs and form data.
 * Objects and arrays are JSON-stringified, primitives are converted directly.
 */
function stringifyValue(value: JsonValue): string {
	Eif (typeof value === 'string') {
		return value;
	}
	if (typeof value === 'number' || typeof value === 'boolean') {
		return String(value);
	}
	if (value === null) {
		return '';
	}
	// Arrays and objects
	return JSON.stringify(value);
}
 
/**
 * 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: JsonObject): [string, JsonObject, JsonObject] {
		let url = this.url;
		const bodyParams: JsonObject = {};
		const queryParams: JsonObject = {};
 
		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(stringifyValue(value)));
					break;
				case ParameterLocation.QUERY:
					// Add to query parameters
					queryParams[key] = value;
					break;
				case ParameterLocation.HEADER:
					// Add to headers
					this.headers[key] = stringifyValue(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: JsonObject): 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, stringifyValue(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, stringifyValue(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');
		}
		Iif (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`,
			);
		}
 
		Iif (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>)) {
					Eif (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 E{
			// 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: JsonObject): [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.
	 *
	 * For JSON responses, returns the parsed API response.
	 *
	 * For file downloads (any non-JSON Content-Type, e.g. a `*_unified_download_file` action),
	 * returns a description of the file:
	 * `{ content: Buffer, contentType: string, statusCode: number, headers: Record<string, string>,
	 * fileName: string | null }`. Note `content` is a raw `Buffer`, not a `JsonValue`: it
	 * JSON-stringifies to a `{ type: 'Buffer', data: [...] }` byte array, so callers that
	 * re-serialize tool results (e.g. for an LLM) should strip or transform this key.
	 */
	async execute(params: JsonObject, options?: ExecuteOptions): Promise<JsonObject> {
		// 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) {
			// Convert headers to a plain object for JSON serialization
			const headersObj =
				fetchOptions.headers instanceof Headers
					? Object.fromEntries(fetchOptions.headers.entries())
					: Array.isArray(fetchOptions.headers)
						? Object.fromEntries(fetchOptions.headers)
						: (fetchOptions.headers ?? {});
 
			// Convert body to a JSON-serialisable value
			const bodyValue =
				fetchOptions.body instanceof FormData
					? '[FormData]'
					: typeof fetchOptions.body === 'string'
						? fetchOptions.body
						: null;
 
			return {
				url: urlWithQuery.toString(),
				method: this.method,
				headers: headersObj,
				body: bodyValue,
				mappedParams: params,
			} satisfies JsonObject;
		}
 
		// 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,
			);
		}
 
		// Branch on Content-Type: JSON bodies are parsed as before; any non-JSON body is a file
		// download (raw binary served with the file's own MIME type and a Content-Disposition
		// header) and must not be forced through response.json(), which throws on binary content.
		const contentType = response.headers.get('content-type') ?? '';
		if (isJsonContentType(contentType)) {
			return (await response.json()) as JsonObject;
		}
 
		// Return the raw bytes plus metadata. `content` is a Buffer, which is not representable in
		// type-fest's JsonValue (and JSON-stringifies to a byte array, not the file); the double-cast
		// is the documented escape hatch for returning a non-JSON value from this JsonObject method.
		return (await binaryDownloadFromResponse(response)) as unknown as JsonObject;
	}
}