import { ClientRequest } from 'http'; import { buildCurlCommand } from './parsing'; import { waitForBody } from './streaming'; export type RequestToCurlCallback = (error: Error | null, curl?: string) => void; export function requestToCurl(req: ClientRequest): Promise; export function requestToCurl(req: ClientRequest, timeout: number | boolean): Promise; export function requestToCurl( req: ClientRequest, callback: RequestToCurlCallback, timeout?: number | boolean ): void; export function requestToCurl( req: ClientRequest, callbackOrTimeout?: RequestToCurlCallback | number | boolean, timeoutArg?: number | boolean ): Promise | void { const { callback, timeoutMs } = normalizeArgs(callbackOrTimeout, timeoutArg); const promise = buildCurlWhenReady(req, timeoutMs); if (callback) { promise.then( curl => { callback(null, curl); }, error => { callback(error); } ); return; } return promise; } // eslint-disable-next-line @typescript-eslint/no-namespace export namespace requestToCurl { export let DEFAULT_TIMEOUT_MS: number | undefined; } requestToCurl.DEFAULT_TIMEOUT_MS = (30 * 1000) as number | undefined; async function buildCurlWhenReady(req: ClientRequest, timeoutMs?: number): Promise { const body = await waitForBody(req, timeoutMs); return buildCurlCommand(req, body); } function normalizeArgs( callbackOrTimeout?: RequestToCurlCallback | number | boolean, timeoutArg?: number | boolean ): { callback?: RequestToCurlCallback; timeoutMs?: number } { const callback = typeof callbackOrTimeout === 'function' ? callbackOrTimeout : undefined; const timeoutInput = callback ? timeoutArg : callbackOrTimeout; const normalizedTimeout = typeof timeoutInput === 'function' ? undefined : timeoutInput; const timeoutMs = resolveTimeout(normalizedTimeout); return { callback, timeoutMs }; } function resolveTimeout(timeout?: number | boolean): number | undefined { if (timeout === false) { return undefined; } if (timeout === true) { return requestToCurl.DEFAULT_TIMEOUT_MS; } if (typeof timeout === 'number') { return timeout; } return requestToCurl.DEFAULT_TIMEOUT_MS; }