import type { AfterResponseHook, BeforeErrorHook, BeforeRequestHook, BeforeRetryHook, HookContext } from './types.ts'; export async function runBeforeRequest( hooks: ReadonlyArray, ctx: HookContext ): Promise { for (const hook of hooks) { const result = await hook(ctx); if (result instanceof Response) return result; } return undefined; } export async function runBeforeRetry( hooks: ReadonlyArray, ctx: HookContext & { error: unknown; retryDelay: number } ): Promise { for (const hook of hooks) { await hook(ctx); } } export async function runAfterResponse( hooks: ReadonlyArray, ctx: HookContext, response: Response ): Promise { let current = response; for (const hook of hooks) { const result = await hook({ ...ctx, response: current }); if (result instanceof Response) current = result; } return current; } export async function runBeforeError( hooks: ReadonlyArray, ctx: HookContext & { response?: Response }, error: unknown ): Promise { let current: Response | undefined = ctx.response; for (const hook of hooks) { const result = await hook({ ...ctx, response: current, error }); if (result instanceof Response) current = result; } // Only return when the hook actually swapped in a fresh response. if (current !== undefined && current !== ctx.response) return current; return undefined; }