@baukit/api-runtime 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,727 @@
1
+ /// <reference lib="dom" />
2
+
3
+ import createClient from 'openapi-fetch';
4
+ import type { Client, ClientOptions } from 'openapi-fetch';
5
+
6
+ import { fullJitterBackoffMs } from './backoff.js';
7
+
8
+ export {
9
+ unverifiedDisplayIdentityHintsFromJwt,
10
+ type UnverifiedDisplayIdentityFallback,
11
+ type UnverifiedDisplayIdentityHints,
12
+ } from './unverified-display-identity.js';
13
+
14
+ /** The request ID header accepted and returned by `baukit-http`. */
15
+ export const REQUEST_ID_HEADER = 'x-request-id' as const;
16
+
17
+ /** The request header that carries a mutation's idempotency key. */
18
+ export const IDEMPOTENCY_KEY_HEADER = 'idempotency-key' as const;
19
+
20
+ /** An explicitly selected API environment. */
21
+ export interface ApiEnvironmentConfig {
22
+ readonly baseUrl: string;
23
+ readonly environment: string;
24
+ }
25
+
26
+ /** A product-owned map from environment names to API base URLs. */
27
+ export type ApiEnvironmentMap = Readonly<Record<string, string>>;
28
+
29
+ /** Resolves an explicit environment name from a caller-provided map. */
30
+ export function resolveApiEnvironment(
31
+ environment: string,
32
+ environments: ApiEnvironmentMap,
33
+ ): ApiEnvironmentConfig {
34
+ const baseUrl = Object.hasOwn(environments, environment) ? environments[environment] : undefined;
35
+ if (baseUrl === undefined) {
36
+ throw new Error(`Unknown API environment: ${environment}`);
37
+ }
38
+
39
+ return { baseUrl: normalizeBaseUrl(baseUrl), environment };
40
+ }
41
+
42
+ /** Supplies an access token for each logical request. Token lifecycle and caching stay product-owned. */
43
+ export type TokenProvider = () => Promise<string | null>;
44
+
45
+ /** Supplies a W3C `traceparent` value. No tracing provider is installed by this package. */
46
+ export type TraceparentProvider = (request: Request) => string | null | Promise<string | null>;
47
+
48
+ /**
49
+ * HTTP methods that may be opted into automatic retries.
50
+ *
51
+ * `POST` and `PATCH` retry only when the request carries an `Idempotency-Key` header.
52
+ */
53
+ export type RetryableMethod = 'GET' | 'HEAD' | 'OPTIONS' | 'PUT' | 'DELETE' | 'POST' | 'PATCH';
54
+
55
+ /** Retry behavior for transient failures. */
56
+ export interface RetryOptions {
57
+ /** Additional attempts after the initial attempt. Defaults to 2. */
58
+ readonly maxRetries?: number;
59
+ /** Initial backoff ceiling in milliseconds. Defaults to 100. */
60
+ readonly baseDelayMs?: number;
61
+ /** Maximum backoff ceiling in milliseconds. Defaults to 2,000. */
62
+ readonly maxDelayMs?: number;
63
+ /** Methods eligible for retries. Defaults to GET and HEAD. */
64
+ readonly methods?: readonly RetryableMethod[];
65
+ /** Random source used for full jitter. Defaults to `Math.random`. */
66
+ readonly random?: () => number;
67
+ /** Abort-aware delay seam, primarily useful for deterministic tests. */
68
+ readonly sleep?: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
69
+ }
70
+
71
+ /** The fetch shape accepted by browsers, React Native, and `openapi-fetch`. */
72
+ export type FetchImplementation = (
73
+ input: RequestInfo | URL,
74
+ init?: RequestInit,
75
+ ) => Promise<Response>;
76
+
77
+ /** Context delivered when a response has status 401. */
78
+ export interface UnauthorizedContext {
79
+ readonly error: ApiError | HttpError;
80
+ readonly request: Request;
81
+ readonly response: Response;
82
+ /** False when the request body cannot be cloned safely for replay. */
83
+ readonly canRetry: boolean;
84
+ }
85
+
86
+ /** Explicit outcome of a 401 hook. `handled` preserves the original normalized rejection. */
87
+ export type UnauthorizedRecovery = 'handled' | 'retry-once';
88
+
89
+ /** Backward-compatible 401 notification or explicit recovery callback. */
90
+ export type UnauthorizedHandler =
91
+ | ((context: UnauthorizedContext) => void)
92
+ | ((context: UnauthorizedContext) => Promise<void>)
93
+ | ((context: UnauthorizedContext) => UnauthorizedRecovery)
94
+ | ((context: UnauthorizedContext) => Promise<UnauthorizedRecovery>);
95
+
96
+ /** Notification emitted when an explicit credential replay also returns 401. */
97
+ export type UnauthorizedExhaustedHandler = (context: UnauthorizedContext) => void | Promise<void>;
98
+
99
+ /** Options shared by the standalone fetch wrapper and generated clients. */
100
+ export interface ApiRuntimeOptions extends ApiEnvironmentConfig {
101
+ readonly fetch?: FetchImplementation;
102
+ readonly requestConstructor?: typeof Request;
103
+ readonly tokenProvider?: TokenProvider;
104
+ readonly traceparentProvider?: TraceparentProvider;
105
+ readonly requestIdFactory?: () => string;
106
+ readonly onUnauthorized?: UnauthorizedHandler;
107
+ readonly onUnauthorizedExhausted?: UnauthorizedExhaustedHandler;
108
+ readonly retry?: RetryOptions | false;
109
+ }
110
+
111
+ /** A configured runtime that can be handed to a product's generated client. */
112
+ export interface ApiRuntime extends ApiEnvironmentConfig {
113
+ readonly fetch: FetchImplementation;
114
+ }
115
+
116
+ /** JSON values accepted in Baukit error details. */
117
+ export type JsonValue =
118
+ null | boolean | number | string | readonly JsonValue[] | { readonly [key: string]: JsonValue };
119
+
120
+ /** A validated Baukit error envelope. */
121
+ export interface ApiErrorEnvelope<Code extends string = string> {
122
+ readonly error: {
123
+ readonly code: Code;
124
+ readonly message: string;
125
+ readonly requestId: string;
126
+ readonly details: Readonly<Record<string, JsonValue>>;
127
+ };
128
+ }
129
+
130
+ /** A non-success response using Baukit's standard JSON error envelope. */
131
+ export class ApiError<Code extends string = string> extends Error {
132
+ readonly kind = 'api' as const;
133
+ readonly code: Code;
134
+ readonly requestId: string;
135
+ readonly details: Readonly<Record<string, JsonValue>>;
136
+ readonly status: number;
137
+
138
+ constructor(envelope: ApiErrorEnvelope<Code>, status: number) {
139
+ super(envelope.error.message);
140
+ this.name = 'ApiError';
141
+ this.code = envelope.error.code;
142
+ this.requestId = envelope.error.requestId;
143
+ this.details = envelope.error.details;
144
+ this.status = status;
145
+ }
146
+ }
147
+
148
+ /** A transport failure where no HTTP response was available (including CORS failures). */
149
+ export class NetworkError extends Error {
150
+ readonly kind = 'network' as const;
151
+ readonly requestId: string;
152
+ readonly aborted: boolean;
153
+
154
+ constructor(message: string, requestId: string, cause: unknown, aborted = false) {
155
+ super(message, { cause });
156
+ this.name = 'NetworkError';
157
+ this.requestId = requestId;
158
+ this.aborted = aborted;
159
+ }
160
+ }
161
+
162
+ /** A non-success HTTP response that did not contain a valid Baukit error envelope. */
163
+ export class HttpError extends Error {
164
+ readonly kind = 'http' as const;
165
+ readonly status: number;
166
+ readonly requestId: string | null;
167
+ readonly body: unknown;
168
+
169
+ constructor(response: Response, body: unknown) {
170
+ const suffix = response.statusText === '' ? '' : ` ${response.statusText}`;
171
+ super(`HTTP ${String(response.status)}${suffix}`);
172
+ this.name = 'HttpError';
173
+ this.status = response.status;
174
+ this.requestId = response.headers.get(REQUEST_ID_HEADER);
175
+ this.body = body;
176
+ }
177
+ }
178
+
179
+ /** Narrows an unknown value to an ApiError, optionally with one specific code. */
180
+ export function isApiError(value: unknown): value is ApiError;
181
+ export function isApiError<Code extends string>(
182
+ value: unknown,
183
+ code: Code,
184
+ ): value is ApiError<Code>;
185
+ export function isApiError(value: unknown, code?: string): value is ApiError {
186
+ return value instanceof ApiError && (code === undefined || value.code === code);
187
+ }
188
+
189
+ /** Narrows an unknown value to a NetworkError. */
190
+ export function isNetworkError(value: unknown): value is NetworkError {
191
+ return value instanceof NetworkError;
192
+ }
193
+
194
+ /** Narrows an unknown value to an HttpError. */
195
+ export function isHttpError(value: unknown): value is HttpError {
196
+ return value instanceof HttpError;
197
+ }
198
+
199
+ /** Parses the exact Baukit error envelope shape, returning null for any other value. */
200
+ export function parseApiErrorEnvelope(value: unknown, status: number): ApiError | null {
201
+ if (!isRecord(value) || !isRecord(value['error'])) {
202
+ return null;
203
+ }
204
+
205
+ const error = value['error'];
206
+ if (
207
+ typeof error['code'] !== 'string' ||
208
+ typeof error['message'] !== 'string' ||
209
+ typeof error['requestId'] !== 'string' ||
210
+ !isJsonObject(error['details'])
211
+ ) {
212
+ return null;
213
+ }
214
+
215
+ return new ApiError(
216
+ {
217
+ error: {
218
+ code: error['code'],
219
+ message: error['message'],
220
+ requestId: error['requestId'],
221
+ details: error['details'],
222
+ },
223
+ },
224
+ status,
225
+ );
226
+ }
227
+
228
+ /** Converts a non-success HTTP response into an ApiError or HttpError. */
229
+ export async function normalizeResponseError(response: Response): Promise<ApiError | HttpError> {
230
+ let body: unknown;
231
+ try {
232
+ const text = await response.clone().text();
233
+ if (text !== '') {
234
+ try {
235
+ body = JSON.parse(text) as unknown;
236
+ } catch {
237
+ body = text;
238
+ }
239
+ }
240
+ } catch {
241
+ body = undefined;
242
+ }
243
+
244
+ return parseApiErrorEnvelope(body, response.status) ?? new HttpError(response, body);
245
+ }
246
+
247
+ /** Creates the fetch runtime used by standalone callers and generated clients. */
248
+ export function createApiRuntime(options: ApiRuntimeOptions): ApiRuntime {
249
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
250
+ return {
251
+ baseUrl,
252
+ environment: options.environment,
253
+ fetch: createApiFetch({ ...options, baseUrl }),
254
+ };
255
+ }
256
+
257
+ /** Creates an `openapi-fetch` client backed by the Baukit runtime. */
258
+ export function createApiClient<Paths extends object>(
259
+ runtimeOptions: ApiRuntimeOptions,
260
+ clientOptions: Omit<ClientOptions, 'baseUrl' | 'fetch'> = {},
261
+ ): Client<Paths> {
262
+ const runtime = createApiRuntime(runtimeOptions);
263
+ return createClient<Paths>({ ...clientOptions, baseUrl: runtime.baseUrl, fetch: runtime.fetch });
264
+ }
265
+
266
+ /** Creates a standalone fetch wrapper with auth, request IDs, errors, and safe retries. */
267
+ export function createApiFetch(options: ApiRuntimeOptions): FetchImplementation {
268
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
269
+ const requestConstructor = options.requestConstructor ?? globalThis.Request;
270
+ const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
271
+ const requestIdFactory = options.requestIdFactory ?? createUuid;
272
+ const retry = normalizeRetryOptions(options.retry);
273
+
274
+ return async (input, init) => {
275
+ const requestId = requestIdFactory();
276
+ let request: Request;
277
+ try {
278
+ request = createRequest(input, init, baseUrl, requestConstructor);
279
+ request = await decorateRequest(request, requestId, requestConstructor, options);
280
+ } catch (cause) {
281
+ if (cause instanceof NetworkError) {
282
+ throw cause;
283
+ }
284
+ throw networkError(cause, requestId, init?.signal ?? null);
285
+ }
286
+
287
+ let replaySource = cloneRequest(request);
288
+ let useOriginalRequest = true;
289
+ let retries = 0;
290
+ let unauthorizedReplayUsed = false;
291
+ for (;;) {
292
+ throwIfAborted(request.signal, requestId);
293
+ try {
294
+ const attempt = useOriginalRequest ? request : replaySource?.clone();
295
+ if (attempt === undefined) {
296
+ throw new TypeError('API request body cannot be replayed');
297
+ }
298
+ useOriginalRequest = false;
299
+ const response = await transport(attempt);
300
+ throwIfAborted(request.signal, requestId);
301
+ if (
302
+ replaySource !== undefined &&
303
+ shouldRetryResponse(request, response.status, retries, retry)
304
+ ) {
305
+ await retryDelay(retries, retry, request.signal, requestId);
306
+ retries += 1;
307
+ continue;
308
+ }
309
+
310
+ if (response.ok) {
311
+ return response;
312
+ }
313
+
314
+ const error = await normalizeResponseError(response);
315
+ if (
316
+ response.status === 401 &&
317
+ unauthorizedReplayUsed &&
318
+ options.onUnauthorizedExhausted !== undefined
319
+ ) {
320
+ try {
321
+ await options.onUnauthorizedExhausted({
322
+ error,
323
+ request: replaySource?.clone() ?? request,
324
+ response,
325
+ canRetry: false,
326
+ });
327
+ } catch {
328
+ // Terminal authentication observers cannot replace the normalized API failure.
329
+ }
330
+ throwIfAborted(request.signal, requestId);
331
+ }
332
+ if (
333
+ response.status === 401 &&
334
+ options.onUnauthorized !== undefined &&
335
+ !unauthorizedReplayUsed
336
+ ) {
337
+ let recovery: unknown;
338
+ try {
339
+ recovery = await options.onUnauthorized({
340
+ error,
341
+ request: replaySource?.clone() ?? request,
342
+ response,
343
+ canRetry: replaySource !== undefined,
344
+ });
345
+ } catch {
346
+ // Re-authentication failures must not replace the normalized API failure.
347
+ }
348
+ throwIfAborted(request.signal, requestId);
349
+ if (recovery === 'retry-once' && replaySource !== undefined) {
350
+ unauthorizedReplayUsed = true;
351
+ try {
352
+ request = await decorateRequest(
353
+ replaySource.clone(),
354
+ requestId,
355
+ requestConstructor,
356
+ options,
357
+ );
358
+ } catch (cause) {
359
+ throwIfAborted(request.signal, requestId);
360
+ if (cause instanceof NetworkError) {
361
+ throw cause;
362
+ }
363
+ throw error;
364
+ }
365
+ replaySource = cloneRequest(request);
366
+ if (replaySource === undefined) {
367
+ throw error;
368
+ }
369
+ useOriginalRequest = true;
370
+ retries = 0;
371
+ continue;
372
+ }
373
+ }
374
+ throw error;
375
+ } catch (cause) {
376
+ if (cause instanceof ApiError || cause instanceof HttpError) {
377
+ throw cause;
378
+ }
379
+
380
+ const aborted = request.signal.aborted || isAbortError(cause);
381
+ if (
382
+ !aborted &&
383
+ replaySource !== undefined &&
384
+ shouldRetryMethod(request, retry) &&
385
+ retries < retry.maxRetries
386
+ ) {
387
+ await retryDelay(retries, retry, request.signal, requestId);
388
+ retries += 1;
389
+ continue;
390
+ }
391
+ throw new NetworkError(
392
+ aborted ? 'API request was aborted' : 'API network request failed',
393
+ requestId,
394
+ cause,
395
+ aborted,
396
+ );
397
+ }
398
+ }
399
+ };
400
+ }
401
+
402
+ async function decorateRequest(
403
+ request: Request,
404
+ requestId: string,
405
+ requestConstructor: typeof Request,
406
+ options: ApiRuntimeOptions,
407
+ ): Promise<Request> {
408
+ throwIfAborted(request.signal, requestId);
409
+ const headers = new Headers(request.headers);
410
+ headers.set(REQUEST_ID_HEADER, requestId);
411
+
412
+ if (options.tokenProvider !== undefined) {
413
+ const token = await options.tokenProvider();
414
+ throwIfAborted(request.signal, requestId);
415
+ headers.delete('authorization');
416
+ if (token !== null) {
417
+ headers.set('authorization', `Bearer ${token}`);
418
+ }
419
+ }
420
+
421
+ if (options.traceparentProvider !== undefined) {
422
+ const traceparent = await options.traceparentProvider(request);
423
+ throwIfAborted(request.signal, requestId);
424
+ if (traceparent !== null) {
425
+ headers.set('traceparent', traceparent);
426
+ }
427
+ }
428
+
429
+ return new requestConstructor(request, { headers });
430
+ }
431
+
432
+ function cloneRequest(request: Request): Request | undefined {
433
+ try {
434
+ return request.clone();
435
+ } catch {
436
+ return undefined;
437
+ }
438
+ }
439
+
440
+ /** Expected request fields used by MockFetch assertions. */
441
+ export interface MockRequestExpectation {
442
+ readonly method?: string;
443
+ readonly url?: string;
444
+ readonly headers?: Readonly<Record<string, string>>;
445
+ }
446
+
447
+ /** A queued response factory for MockFetch. */
448
+ export type MockFetchHandler = (request: Request) => Response | Promise<Response>;
449
+
450
+ /** A small queued fetch transport for product and package tests. */
451
+ export class MockFetch {
452
+ readonly requests: Request[] = [];
453
+ readonly fetch: FetchImplementation;
454
+ readonly #queue: (Response | Error | MockFetchHandler)[] = [];
455
+
456
+ constructor() {
457
+ this.fetch = async (input, init) => {
458
+ const request = new Request(input, init);
459
+ this.requests.push(request.clone());
460
+ const next = this.#queue.shift();
461
+ if (next === undefined) {
462
+ throw new Error('MockFetch has no queued response');
463
+ }
464
+ if (next instanceof Error) {
465
+ throw next;
466
+ }
467
+ return typeof next === 'function' ? next(request) : next;
468
+ };
469
+ }
470
+
471
+ /** Adds a response, transport error, or response factory to the queue. */
472
+ enqueue(next: Response | Error | MockFetchHandler): this {
473
+ this.#queue.push(next);
474
+ return this;
475
+ }
476
+
477
+ /** Adds a JSON response to the queue. */
478
+ enqueueJson(body: unknown, init: ResponseInit = {}): this {
479
+ const headers = new Headers(init.headers);
480
+ if (!headers.has('content-type')) {
481
+ headers.set('content-type', 'application/json');
482
+ }
483
+ return this.enqueue(new Response(JSON.stringify(body), { ...init, headers }));
484
+ }
485
+
486
+ /** Returns one recorded request or throws a clear assertion error. */
487
+ request(index: number): Request {
488
+ const request = this.requests[index];
489
+ if (request === undefined) {
490
+ throw new Error(`MockFetch request ${String(index)} was not recorded`);
491
+ }
492
+ return request;
493
+ }
494
+
495
+ /** Asserts selected fields of a recorded request without a test-framework dependency. */
496
+ assertRequest(index: number, expected: MockRequestExpectation): void {
497
+ const request = this.request(index);
498
+ if (expected.method !== undefined && request.method !== expected.method.toUpperCase()) {
499
+ throw new Error(`Expected request method ${expected.method}, received ${request.method}`);
500
+ }
501
+ if (expected.url !== undefined && request.url !== expected.url) {
502
+ throw new Error(`Expected request URL ${expected.url}, received ${request.url}`);
503
+ }
504
+ for (const [name, value] of Object.entries(expected.headers ?? {})) {
505
+ const received = request.headers.get(name);
506
+ if (received !== value) {
507
+ throw new Error(`Expected request header ${name}=${value}, received ${String(received)}`);
508
+ }
509
+ }
510
+ }
511
+
512
+ /** Asserts that every queued result has been consumed. */
513
+ assertQueueEmpty(): void {
514
+ if (this.#queue.length !== 0) {
515
+ throw new Error(`MockFetch has ${String(this.#queue.length)} queued result(s) remaining`);
516
+ }
517
+ }
518
+ }
519
+
520
+ interface NormalizedRetryOptions {
521
+ readonly maxRetries: number;
522
+ readonly baseDelayMs: number;
523
+ readonly maxDelayMs: number;
524
+ readonly methods: ReadonlySet<RetryableMethod>;
525
+ readonly random: () => number;
526
+ readonly sleep: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
527
+ }
528
+
529
+ const KEYED_RETRY_ONLY = new Set(['POST', 'PATCH']);
530
+ const RETRYABLE_METHODS = new Set<string>([
531
+ 'GET',
532
+ 'HEAD',
533
+ 'OPTIONS',
534
+ 'PUT',
535
+ 'DELETE',
536
+ 'POST',
537
+ 'PATCH',
538
+ ]);
539
+ const RETRYABLE_STATUSES = new Set([502, 503, 504]);
540
+
541
+ function normalizeBaseUrl(baseUrl: string): string {
542
+ let parsed: URL;
543
+ try {
544
+ parsed = new URL(baseUrl);
545
+ } catch {
546
+ throw new Error(`API base URL must be absolute: ${baseUrl}`);
547
+ }
548
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
549
+ throw new Error(`API base URL must use HTTP or HTTPS: ${baseUrl}`);
550
+ }
551
+ if (parsed.search !== '' || parsed.hash !== '') {
552
+ throw new Error(`API base URL must not contain a query or fragment: ${baseUrl}`);
553
+ }
554
+ return parsed.toString().replace(/\/$/u, '');
555
+ }
556
+
557
+ function createRequest(
558
+ input: RequestInfo | URL,
559
+ init: RequestInit | undefined,
560
+ baseUrl: string,
561
+ requestConstructor: typeof Request,
562
+ ): Request {
563
+ if (typeof input === 'string' || input instanceof URL) {
564
+ return new requestConstructor(new URL(input.toString(), `${baseUrl}/`), init);
565
+ }
566
+ return new requestConstructor(input, init);
567
+ }
568
+
569
+ function createUuid(): string {
570
+ const cryptoApi = (globalThis as unknown as { readonly crypto?: Crypto }).crypto;
571
+ if (typeof cryptoApi?.randomUUID === 'function') {
572
+ return cryptoApi.randomUUID();
573
+ }
574
+
575
+ const bytes = new Uint8Array(16);
576
+ if (typeof cryptoApi?.getRandomValues === 'function') {
577
+ cryptoApi.getRandomValues(bytes);
578
+ } else {
579
+ for (let index = 0; index < bytes.length; index += 1) {
580
+ bytes[index] = Math.floor(Math.random() * 256);
581
+ }
582
+ }
583
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
584
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
585
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
586
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
587
+ }
588
+
589
+ function normalizeRetryOptions(options: RetryOptions | false | undefined): NormalizedRetryOptions {
590
+ const maxRetries = options === false ? 0 : (options?.maxRetries ?? 2);
591
+ const baseDelayMs = options === false ? 100 : (options?.baseDelayMs ?? 100);
592
+ const maxDelayMs = options === false ? 2_000 : (options?.maxDelayMs ?? 2_000);
593
+ assertFiniteNonNegativeInteger(maxRetries, 'maxRetries');
594
+ assertFiniteNonNegative(baseDelayMs, 'baseDelayMs');
595
+ assertFiniteNonNegative(maxDelayMs, 'maxDelayMs');
596
+ const requestedMethods = options === false ? [] : (options?.methods ?? ['GET', 'HEAD']);
597
+ const methods = new Set(
598
+ requestedMethods.filter((method): method is RetryableMethod => RETRYABLE_METHODS.has(method)),
599
+ );
600
+ return {
601
+ maxRetries,
602
+ baseDelayMs,
603
+ maxDelayMs,
604
+ methods,
605
+ random: options === false ? Math.random : (options?.random ?? Math.random),
606
+ sleep: options === false ? abortableSleep : (options?.sleep ?? abortableSleep),
607
+ };
608
+ }
609
+
610
+ function assertFiniteNonNegative(value: number, name: string): void {
611
+ if (!Number.isFinite(value) || value < 0) {
612
+ throw new Error(`${name} must be a finite non-negative number`);
613
+ }
614
+ }
615
+
616
+ function assertFiniteNonNegativeInteger(value: number, name: string): void {
617
+ assertFiniteNonNegative(value, name);
618
+ if (!Number.isInteger(value)) {
619
+ throw new Error(`${name} must be an integer`);
620
+ }
621
+ }
622
+
623
+ function shouldRetryMethod(request: Request, retry: NormalizedRetryOptions): boolean {
624
+ const method = request.method;
625
+ if (!retry.methods.has(method as RetryableMethod)) {
626
+ return false;
627
+ }
628
+ return !KEYED_RETRY_ONLY.has(method) || request.headers.has(IDEMPOTENCY_KEY_HEADER);
629
+ }
630
+
631
+ function shouldRetryResponse(
632
+ request: Request,
633
+ status: number,
634
+ retries: number,
635
+ retry: NormalizedRetryOptions,
636
+ ): boolean {
637
+ return (
638
+ retries < retry.maxRetries &&
639
+ shouldRetryMethod(request, retry) &&
640
+ RETRYABLE_STATUSES.has(status)
641
+ );
642
+ }
643
+
644
+ async function retryDelay(
645
+ retryIndex: number,
646
+ retry: NormalizedRetryOptions,
647
+ signal: AbortSignal,
648
+ requestId: string,
649
+ ): Promise<void> {
650
+ try {
651
+ await retry.sleep(fullJitterBackoffMs(retryIndex, retry), signal);
652
+ } catch (cause) {
653
+ throw new NetworkError('API request was aborted', requestId, cause, true);
654
+ }
655
+ throwIfAborted(signal, requestId);
656
+ }
657
+
658
+ function abortableSleep(delayMs: number, signal: AbortSignal | null): Promise<void> {
659
+ if (signal === null) {
660
+ return new Promise((resolve) => {
661
+ globalThis.setTimeout(resolve, delayMs);
662
+ });
663
+ }
664
+ if (signal.aborted) {
665
+ return Promise.reject(abortReason(signal));
666
+ }
667
+ return new Promise((resolve, reject) => {
668
+ const onAbort = (): void => {
669
+ globalThis.clearTimeout(timer);
670
+ reject(abortReason(signal));
671
+ };
672
+ const timer = globalThis.setTimeout(() => {
673
+ signal.removeEventListener('abort', onAbort);
674
+ resolve();
675
+ }, delayMs);
676
+ signal.addEventListener('abort', onAbort, { once: true });
677
+ });
678
+ }
679
+
680
+ function abortReason(signal: AbortSignal): Error {
681
+ return signal.reason instanceof Error
682
+ ? signal.reason
683
+ : new Error('API request was aborted', { cause: signal.reason });
684
+ }
685
+
686
+ function throwIfAborted(signal: AbortSignal, requestId: string): void {
687
+ if (signal.aborted) {
688
+ throw new NetworkError('API request was aborted', requestId, signal.reason, true);
689
+ }
690
+ }
691
+
692
+ function networkError(cause: unknown, requestId: string, signal: AbortSignal | null): NetworkError {
693
+ const aborted = signal?.aborted === true || isAbortError(cause);
694
+ return new NetworkError(
695
+ aborted ? 'API request was aborted' : 'API network request failed',
696
+ requestId,
697
+ cause,
698
+ aborted,
699
+ );
700
+ }
701
+
702
+ function isAbortError(value: unknown): boolean {
703
+ return value instanceof Error && value.name === 'AbortError';
704
+ }
705
+
706
+ function isRecord(value: unknown): value is Record<string, unknown> {
707
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
708
+ }
709
+
710
+ function isJsonObject(value: unknown): value is Readonly<Record<string, JsonValue>> {
711
+ return isRecord(value) && Object.values(value).every(isJsonValue);
712
+ }
713
+
714
+ function isJsonValue(value: unknown): value is JsonValue {
715
+ if (
716
+ value === null ||
717
+ typeof value === 'string' ||
718
+ typeof value === 'boolean' ||
719
+ (typeof value === 'number' && Number.isFinite(value))
720
+ ) {
721
+ return true;
722
+ }
723
+ if (Array.isArray(value)) {
724
+ return value.every(isJsonValue);
725
+ }
726
+ return isJsonObject(value);
727
+ }