import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
function isProviderError(error){return!(error instanceof Error)||!("status"in error)||!("headers"in error)?!1:(error.status===void 0||typeof error.status=="number")&&(error.headers===void 0||error.headers instanceof Headers)}function isRetryableProviderError(error){let shouldRetry=error.headers?.get("x-should-retry");return shouldRetry==="true"?!0:shouldRetry==="false"?!1:error.status===void 0?!0:error.status===408||error.status===409||error.status===429||typeof error.status=="number"&&error.status>=500}function validateServerRetryDelayMs(delayMs,maxRetryDelayMs,providerErrorMessage){let maxDelayMs=maxRetryDelayMs??6e4;if(maxDelayMs>0&&delayMs>maxDelayMs)throw new Error(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxDelayMs/1e3)}s). ${providerErrorMessage}`);return delayMs}function getRetryDelayMs(error,retryIndex,maxRetryDelayMs){let retryAfterMs=error.headers?.get("retry-after-ms");if(retryAfterMs){let value=Number.parseFloat(retryAfterMs);if(!Number.isNaN(value))return validateServerRetryDelayMs(value,maxRetryDelayMs,error.message)}let retryAfter=error.headers?.get("retry-after");if(retryAfter){let seconds=Number.parseFloat(retryAfter),delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3;return validateServerRetryDelayMs(delayMs,maxRetryDelayMs,error.message)}return Math.min(.5*2**retryIndex,8)*1e3*(1-Math.random()*.25)}function createAbortError(){let error=new Error("Request aborted");return error.name="AbortError",error}function abortableSleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(createAbortError());return}let onAbort=()=>{clearTimeout(timeout),reject(createAbortError())},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},Math.max(0,ms));signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryProviderRequest(request,options={}){let maxRetries=options.maxRetries??0,retriesRemaining=maxRetries;for(;;)try{return await request()}catch(error){if(options.signal?.aborted)throw createAbortError();if(retriesRemaining<=0||!isProviderError(error)||!isRetryableProviderError(error))throw error;let retryIndex=maxRetries-retriesRemaining;retriesRemaining--,await abortableSleep(getRetryDelayMs(error,retryIndex,options.maxRetryDelayMs),options.signal)}}export{retryProviderRequest};
