@baukit/api-runtime 0.18.3 → 0.19.0

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 CHANGED
@@ -3,7 +3,8 @@
3
3
  import createClient from 'openapi-fetch';
4
4
  import type { Client, ClientOptions } from 'openapi-fetch';
5
5
 
6
- import { fullJitterBackoffMs } from './backoff.js';
6
+ import type { ApiError, HttpError } from './errors.js';
7
+ import { fetchSettings, runFetch } from './fetch.js';
7
8
 
8
9
  export {
9
10
  unverifiedDisplayIdentityHintsFromJwt,
@@ -17,11 +18,19 @@ export {
17
18
  type SignInUser,
18
19
  } from './sign-in-session.js';
19
20
 
20
- /** The request ID header accepted and returned by `baukit-http`. */
21
- export const REQUEST_ID_HEADER = 'x-request-id' as const;
22
-
23
- /** The request header that carries a mutation's idempotency key. */
24
- export const IDEMPOTENCY_KEY_HEADER = 'idempotency-key' as const;
21
+ export { IDEMPOTENCY_KEY_HEADER, REQUEST_ID_HEADER } from './headers.js';
22
+ export {
23
+ ApiError,
24
+ HttpError,
25
+ isApiError,
26
+ isHttpError,
27
+ isNetworkError,
28
+ NetworkError,
29
+ normalizeResponseError,
30
+ parseApiErrorEnvelope,
31
+ type ApiErrorEnvelope,
32
+ type JsonValue,
33
+ } from './errors.js';
25
34
 
26
35
  /** An explicitly selected API environment. */
27
36
  export interface ApiEnvironmentConfig {
@@ -123,137 +132,6 @@ export interface ApiRuntime extends ApiEnvironmentConfig {
123
132
  readonly fetch: FetchImplementation;
124
133
  }
125
134
 
126
- /** JSON values accepted in Baukit error details. */
127
- export type JsonValue =
128
- null | boolean | number | string | readonly JsonValue[] | { readonly [key: string]: JsonValue };
129
-
130
- /** A validated Baukit error envelope. */
131
- export interface ApiErrorEnvelope<Code extends string = string> {
132
- readonly error: {
133
- readonly code: Code;
134
- readonly message: string;
135
- readonly requestId: string;
136
- readonly details: Readonly<Record<string, JsonValue>>;
137
- };
138
- }
139
-
140
- /** A non-success response using Baukit's standard JSON error envelope. */
141
- export class ApiError<Code extends string = string> extends Error {
142
- readonly kind = 'api' as const;
143
- readonly code: Code;
144
- readonly requestId: string;
145
- readonly details: Readonly<Record<string, JsonValue>>;
146
- readonly status: number;
147
-
148
- constructor(envelope: ApiErrorEnvelope<Code>, status: number) {
149
- super(envelope.error.message);
150
- this.name = 'ApiError';
151
- this.code = envelope.error.code;
152
- this.requestId = envelope.error.requestId;
153
- this.details = envelope.error.details;
154
- this.status = status;
155
- }
156
- }
157
-
158
- /** A transport failure where no HTTP response was available (including CORS failures). */
159
- export class NetworkError extends Error {
160
- readonly kind = 'network' as const;
161
- readonly requestId: string;
162
- readonly aborted: boolean;
163
-
164
- constructor(message: string, requestId: string, cause: unknown, aborted = false) {
165
- super(message, { cause });
166
- this.name = 'NetworkError';
167
- this.requestId = requestId;
168
- this.aborted = aborted;
169
- }
170
- }
171
-
172
- /** A non-success HTTP response that did not contain a valid Baukit error envelope. */
173
- export class HttpError extends Error {
174
- readonly kind = 'http' as const;
175
- readonly status: number;
176
- readonly requestId: string | null;
177
- readonly body: unknown;
178
-
179
- constructor(response: Response, body: unknown) {
180
- const suffix = response.statusText === '' ? '' : ` ${response.statusText}`;
181
- super(`HTTP ${String(response.status)}${suffix}`);
182
- this.name = 'HttpError';
183
- this.status = response.status;
184
- this.requestId = response.headers.get(REQUEST_ID_HEADER);
185
- this.body = body;
186
- }
187
- }
188
-
189
- /** Narrows an unknown value to an ApiError, optionally with one specific code. */
190
- export function isApiError(value: unknown): value is ApiError;
191
- export function isApiError<Code extends string>(
192
- value: unknown,
193
- code: Code,
194
- ): value is ApiError<Code>;
195
- export function isApiError(value: unknown, code?: string): value is ApiError {
196
- return value instanceof ApiError && (code === undefined || value.code === code);
197
- }
198
-
199
- /** Narrows an unknown value to a NetworkError. */
200
- export function isNetworkError(value: unknown): value is NetworkError {
201
- return value instanceof NetworkError;
202
- }
203
-
204
- /** Narrows an unknown value to an HttpError. */
205
- export function isHttpError(value: unknown): value is HttpError {
206
- return value instanceof HttpError;
207
- }
208
-
209
- /** Parses the exact Baukit error envelope shape, returning null for any other value. */
210
- export function parseApiErrorEnvelope(value: unknown, status: number): ApiError | null {
211
- if (!isRecord(value) || !isRecord(value['error'])) {
212
- return null;
213
- }
214
-
215
- const error = value['error'];
216
- if (
217
- typeof error['code'] !== 'string' ||
218
- typeof error['message'] !== 'string' ||
219
- typeof error['requestId'] !== 'string' ||
220
- !isJsonObject(error['details'])
221
- ) {
222
- return null;
223
- }
224
-
225
- return new ApiError(
226
- {
227
- error: {
228
- code: error['code'],
229
- message: error['message'],
230
- requestId: error['requestId'],
231
- details: error['details'],
232
- },
233
- },
234
- status,
235
- );
236
- }
237
-
238
- /** Converts a non-success HTTP response into an ApiError or HttpError. */
239
- export async function normalizeResponseError(response: Response): Promise<ApiError | HttpError> {
240
- let body: unknown;
241
- try {
242
- const text = await response.clone().text();
243
- if (text !== '') {
244
- try {
245
- body = JSON.parse(text) as unknown;
246
- } catch {
247
- body = text;
248
- }
249
- }
250
- } catch {
251
- body = undefined;
252
- }
253
-
254
- return parseApiErrorEnvelope(body, response.status) ?? new HttpError(response, body);
255
- }
256
-
257
135
  /** Creates the fetch runtime used by standalone callers and generated clients. */
258
136
  export function createApiRuntime(options: ApiRuntimeOptions): ApiRuntime {
259
137
  const baseUrl = normalizeBaseUrl(options.baseUrl);
@@ -275,191 +153,8 @@ export function createApiClient<Paths extends object>(
275
153
 
276
154
  /** Creates a standalone fetch wrapper with auth, request IDs, errors, and safe retries. */
277
155
  export function createApiFetch(options: ApiRuntimeOptions): FetchImplementation {
278
- const baseUrl = normalizeBaseUrl(options.baseUrl);
279
- const requestConstructor = options.requestConstructor ?? globalThis.Request;
280
- const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
281
- const requestIdFactory = options.requestIdFactory ?? createUuid;
282
- const retry = normalizeRetryOptions(options.retry);
283
-
284
- return async (input, init) => {
285
- const requestId = requestIdFactory();
286
- let request: Request;
287
- try {
288
- request = createRequest(input, init, baseUrl, requestConstructor);
289
- request = await decorateRequest(request, requestId, requestConstructor, options);
290
- } catch (cause) {
291
- if (cause instanceof NetworkError) {
292
- throw cause;
293
- }
294
- throw networkError(cause, requestId, init?.signal ?? null);
295
- }
296
-
297
- let replaySource = cloneRequest(request);
298
- let useOriginalRequest = true;
299
- let retries = 0;
300
- let unauthorizedReplayUsed = false;
301
- for (;;) {
302
- throwIfAborted(request.signal, requestId);
303
- try {
304
- const attempt = useOriginalRequest ? request : replaySource?.clone();
305
- if (attempt === undefined) {
306
- throw new TypeError('API request body cannot be replayed');
307
- }
308
- useOriginalRequest = false;
309
- const response = await transport(attempt);
310
- throwIfAborted(request.signal, requestId);
311
- if (
312
- replaySource !== undefined &&
313
- shouldRetryResponse(request, response.status, retries, retry)
314
- ) {
315
- await retryDelay(retries, retry, request.signal, requestId);
316
- retries += 1;
317
- continue;
318
- }
319
-
320
- if (response.ok) {
321
- return response;
322
- }
323
-
324
- const error = await normalizeResponseError(response);
325
- if (response.status === 401 && isApiError(error, 'profile_erased')) {
326
- try {
327
- await options.onProfileErased?.({
328
- error,
329
- request: replaySource?.clone() ?? request,
330
- response,
331
- canRetry: false,
332
- });
333
- } catch {
334
- throwIfAborted(request.signal, requestId);
335
- throw error;
336
- }
337
- throwIfAborted(request.signal, requestId);
338
- throw error;
339
- }
340
- if (
341
- response.status === 401 &&
342
- unauthorizedReplayUsed &&
343
- options.onUnauthorizedExhausted !== undefined
344
- ) {
345
- try {
346
- await options.onUnauthorizedExhausted({
347
- error,
348
- request: replaySource?.clone() ?? request,
349
- response,
350
- canRetry: false,
351
- });
352
- } catch {
353
- // Terminal authentication observers cannot replace the normalized API failure.
354
- }
355
- throwIfAborted(request.signal, requestId);
356
- }
357
- if (
358
- response.status === 401 &&
359
- options.onUnauthorized !== undefined &&
360
- !unauthorizedReplayUsed
361
- ) {
362
- let recovery: unknown;
363
- try {
364
- recovery = await options.onUnauthorized({
365
- error,
366
- request: replaySource?.clone() ?? request,
367
- response,
368
- canRetry: replaySource !== undefined,
369
- });
370
- } catch {
371
- // Re-authentication failures must not replace the normalized API failure.
372
- }
373
- throwIfAborted(request.signal, requestId);
374
- if (recovery === 'retry-once' && replaySource !== undefined) {
375
- unauthorizedReplayUsed = true;
376
- try {
377
- request = await decorateRequest(
378
- replaySource.clone(),
379
- requestId,
380
- requestConstructor,
381
- options,
382
- );
383
- } catch (cause) {
384
- throwIfAborted(request.signal, requestId);
385
- if (cause instanceof NetworkError) {
386
- throw cause;
387
- }
388
- throw error;
389
- }
390
- replaySource = cloneRequest(request);
391
- if (replaySource === undefined) {
392
- throw error;
393
- }
394
- useOriginalRequest = true;
395
- retries = 0;
396
- continue;
397
- }
398
- }
399
- throw error;
400
- } catch (cause) {
401
- if (cause instanceof ApiError || cause instanceof HttpError) {
402
- throw cause;
403
- }
404
-
405
- const aborted = request.signal.aborted || isAbortError(cause);
406
- if (
407
- !aborted &&
408
- replaySource !== undefined &&
409
- shouldRetryMethod(request, retry) &&
410
- retries < retry.maxRetries
411
- ) {
412
- await retryDelay(retries, retry, request.signal, requestId);
413
- retries += 1;
414
- continue;
415
- }
416
- throw new NetworkError(
417
- aborted ? 'API request was aborted' : 'API network request failed',
418
- requestId,
419
- cause,
420
- aborted,
421
- );
422
- }
423
- }
424
- };
425
- }
426
-
427
- async function decorateRequest(
428
- request: Request,
429
- requestId: string,
430
- requestConstructor: typeof Request,
431
- options: ApiRuntimeOptions,
432
- ): Promise<Request> {
433
- throwIfAborted(request.signal, requestId);
434
- const headers = new Headers(request.headers);
435
- headers.set(REQUEST_ID_HEADER, requestId);
436
-
437
- if (options.tokenProvider !== undefined) {
438
- const token = await options.tokenProvider();
439
- throwIfAborted(request.signal, requestId);
440
- headers.delete('authorization');
441
- if (token !== null) {
442
- headers.set('authorization', `Bearer ${token}`);
443
- }
444
- }
445
-
446
- if (options.traceparentProvider !== undefined) {
447
- const traceparent = await options.traceparentProvider(request);
448
- throwIfAborted(request.signal, requestId);
449
- if (traceparent !== null) {
450
- headers.set('traceparent', traceparent);
451
- }
452
- }
453
-
454
- return new requestConstructor(request, { headers });
455
- }
456
-
457
- function cloneRequest(request: Request): Request | undefined {
458
- try {
459
- return request.clone();
460
- } catch {
461
- return undefined;
462
- }
156
+ const settings = fetchSettings(options, normalizeBaseUrl(options.baseUrl));
157
+ return (input, init) => runFetch(settings, input, init);
463
158
  }
464
159
 
465
160
  /** Expected request fields used by MockFetch assertions. */
@@ -542,27 +237,6 @@ export class MockFetch {
542
237
  }
543
238
  }
544
239
 
545
- interface NormalizedRetryOptions {
546
- readonly maxRetries: number;
547
- readonly baseDelayMs: number;
548
- readonly maxDelayMs: number;
549
- readonly methods: ReadonlySet<RetryableMethod>;
550
- readonly random: () => number;
551
- readonly sleep: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
552
- }
553
-
554
- const KEYED_RETRY_ONLY = new Set(['POST', 'PATCH']);
555
- const RETRYABLE_METHODS = new Set<string>([
556
- 'GET',
557
- 'HEAD',
558
- 'OPTIONS',
559
- 'PUT',
560
- 'DELETE',
561
- 'POST',
562
- 'PATCH',
563
- ]);
564
- const RETRYABLE_STATUSES = new Set([502, 503, 504]);
565
-
566
240
  function normalizeBaseUrl(baseUrl: string): string {
567
241
  let parsed: URL;
568
242
  try {
@@ -578,175 +252,3 @@ function normalizeBaseUrl(baseUrl: string): string {
578
252
  }
579
253
  return parsed.toString().replace(/\/$/u, '');
580
254
  }
581
-
582
- function createRequest(
583
- input: RequestInfo | URL,
584
- init: RequestInit | undefined,
585
- baseUrl: string,
586
- requestConstructor: typeof Request,
587
- ): Request {
588
- if (typeof input === 'string' || input instanceof URL) {
589
- return new requestConstructor(new URL(input.toString(), `${baseUrl}/`), init);
590
- }
591
- return new requestConstructor(input, init);
592
- }
593
-
594
- function createUuid(): string {
595
- const cryptoApi = (globalThis as unknown as { readonly crypto?: Crypto }).crypto;
596
- if (typeof cryptoApi?.randomUUID === 'function') {
597
- return cryptoApi.randomUUID();
598
- }
599
-
600
- const bytes = new Uint8Array(16);
601
- if (typeof cryptoApi?.getRandomValues === 'function') {
602
- cryptoApi.getRandomValues(bytes);
603
- } else {
604
- for (let index = 0; index < bytes.length; index += 1) {
605
- bytes[index] = Math.floor(Math.random() * 256);
606
- }
607
- }
608
- bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
609
- bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
610
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
611
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
612
- }
613
-
614
- function normalizeRetryOptions(options: RetryOptions | false | undefined): NormalizedRetryOptions {
615
- const maxRetries = options === false ? 0 : (options?.maxRetries ?? 2);
616
- const baseDelayMs = options === false ? 100 : (options?.baseDelayMs ?? 100);
617
- const maxDelayMs = options === false ? 2_000 : (options?.maxDelayMs ?? 2_000);
618
- assertFiniteNonNegativeInteger(maxRetries, 'maxRetries');
619
- assertFiniteNonNegative(baseDelayMs, 'baseDelayMs');
620
- assertFiniteNonNegative(maxDelayMs, 'maxDelayMs');
621
- const requestedMethods = options === false ? [] : (options?.methods ?? ['GET', 'HEAD']);
622
- const methods = new Set(
623
- requestedMethods.filter((method): method is RetryableMethod => RETRYABLE_METHODS.has(method)),
624
- );
625
- return {
626
- maxRetries,
627
- baseDelayMs,
628
- maxDelayMs,
629
- methods,
630
- random: options === false ? Math.random : (options?.random ?? Math.random),
631
- sleep: options === false ? abortableSleep : (options?.sleep ?? abortableSleep),
632
- };
633
- }
634
-
635
- function assertFiniteNonNegative(value: number, name: string): void {
636
- if (!Number.isFinite(value) || value < 0) {
637
- throw new Error(`${name} must be a finite non-negative number`);
638
- }
639
- }
640
-
641
- function assertFiniteNonNegativeInteger(value: number, name: string): void {
642
- assertFiniteNonNegative(value, name);
643
- if (!Number.isInteger(value)) {
644
- throw new Error(`${name} must be an integer`);
645
- }
646
- }
647
-
648
- function shouldRetryMethod(request: Request, retry: NormalizedRetryOptions): boolean {
649
- const method = request.method;
650
- if (!retry.methods.has(method as RetryableMethod)) {
651
- return false;
652
- }
653
- return !KEYED_RETRY_ONLY.has(method) || request.headers.has(IDEMPOTENCY_KEY_HEADER);
654
- }
655
-
656
- function shouldRetryResponse(
657
- request: Request,
658
- status: number,
659
- retries: number,
660
- retry: NormalizedRetryOptions,
661
- ): boolean {
662
- return (
663
- retries < retry.maxRetries &&
664
- shouldRetryMethod(request, retry) &&
665
- RETRYABLE_STATUSES.has(status)
666
- );
667
- }
668
-
669
- async function retryDelay(
670
- retryIndex: number,
671
- retry: NormalizedRetryOptions,
672
- signal: AbortSignal,
673
- requestId: string,
674
- ): Promise<void> {
675
- try {
676
- await retry.sleep(fullJitterBackoffMs(retryIndex, retry), signal);
677
- } catch (cause) {
678
- throw new NetworkError('API request was aborted', requestId, cause, true);
679
- }
680
- throwIfAborted(signal, requestId);
681
- }
682
-
683
- function abortableSleep(delayMs: number, signal: AbortSignal | null): Promise<void> {
684
- if (signal === null) {
685
- return new Promise((resolve) => {
686
- globalThis.setTimeout(resolve, delayMs);
687
- });
688
- }
689
- if (signal.aborted) {
690
- return Promise.reject(abortReason(signal));
691
- }
692
- return new Promise((resolve, reject) => {
693
- const onAbort = (): void => {
694
- globalThis.clearTimeout(timer);
695
- reject(abortReason(signal));
696
- };
697
- const timer = globalThis.setTimeout(() => {
698
- signal.removeEventListener('abort', onAbort);
699
- resolve();
700
- }, delayMs);
701
- signal.addEventListener('abort', onAbort, { once: true });
702
- });
703
- }
704
-
705
- function abortReason(signal: AbortSignal): Error {
706
- return signal.reason instanceof Error
707
- ? signal.reason
708
- : new Error('API request was aborted', { cause: signal.reason });
709
- }
710
-
711
- function throwIfAborted(signal: AbortSignal, requestId: string): void {
712
- if (signal.aborted) {
713
- throw new NetworkError('API request was aborted', requestId, signal.reason, true);
714
- }
715
- }
716
-
717
- function networkError(cause: unknown, requestId: string, signal: AbortSignal | null): NetworkError {
718
- const aborted = signal?.aborted === true || isAbortError(cause);
719
- return new NetworkError(
720
- aborted ? 'API request was aborted' : 'API network request failed',
721
- requestId,
722
- cause,
723
- aborted,
724
- );
725
- }
726
-
727
- function isAbortError(value: unknown): boolean {
728
- return value instanceof Error && value.name === 'AbortError';
729
- }
730
-
731
- function isRecord(value: unknown): value is Record<string, unknown> {
732
- return typeof value === 'object' && value !== null && !Array.isArray(value);
733
- }
734
-
735
- function isJsonObject(value: unknown): value is Readonly<Record<string, JsonValue>> {
736
- return isRecord(value) && Object.values(value).every(isJsonValue);
737
- }
738
-
739
- function isJsonValue(value: unknown): value is JsonValue {
740
- if (
741
- value === null ||
742
- typeof value === 'string' ||
743
- typeof value === 'boolean' ||
744
- (typeof value === 'number' && Number.isFinite(value))
745
- ) {
746
- return true;
747
- }
748
- if (Array.isArray(value)) {
749
- return value.every(isJsonValue);
750
- }
751
- return isJsonObject(value);
752
- }