( fetchOverride: ClientOptions['fetch'], source: string | undefined, )
| 356 | export const CLIENT_REQUEST_ID_HEADER = 'x-client-request-id' |
| 357 | |
| 358 | function buildFetch( |
| 359 | fetchOverride: ClientOptions['fetch'], |
| 360 | source: string | undefined, |
| 361 | ): ClientOptions['fetch'] { |
| 362 | // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins |
| 363 | let inner = fetchOverride ?? globalThis.fetch |
| 364 | |
| 365 | // Wrap with x402 payment handler for automatic 402 Payment Required handling |
| 366 | try { |
| 367 | const { wrapFetchWithX402, isX402Enabled } = |
| 368 | require('../x402/index.js') as typeof import('../x402/index.js') |
| 369 | if (isX402Enabled()) { |
| 370 | inner = wrapFetchWithX402(inner as typeof globalThis.fetch) as typeof inner |
| 371 | } |
| 372 | } catch { |
| 373 | // x402 module not available, skip |
| 374 | } |
| 375 | |
| 376 | // Only send to the first-party API — Bedrock/Vertex/Foundry don't log it |
| 377 | // and unknown headers risk rejection by strict proxies (inc-4029 class). |
| 378 | const injectClientRequestId = |
| 379 | getAPIProvider() === 'firstParty' && isFirstPartyAnthropicBaseUrl() |
| 380 | return (input, init) => { |
| 381 | // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins |
| 382 | const headers = new Headers(init?.headers) |
| 383 | // Generate a client-side request ID so timeouts (which return no server |
| 384 | // request ID) can still be correlated with server logs by the API team. |
| 385 | // Callers that want to track the ID themselves can pre-set the header. |
| 386 | if (injectClientRequestId && !headers.has(CLIENT_REQUEST_ID_HEADER)) { |
| 387 | headers.set(CLIENT_REQUEST_ID_HEADER, randomUUID()) |
| 388 | } |
| 389 | try { |
| 390 | // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins |
| 391 | const url = input instanceof Request ? input.url : String(input) |
| 392 | const id = headers.get(CLIENT_REQUEST_ID_HEADER) |
| 393 | logForDebugging( |
| 394 | `[API REQUEST] ${new URL(url).pathname}${id ? ` ${CLIENT_REQUEST_ID_HEADER}=${id}` : ''} source=${source ?? 'unknown'}`, |
| 395 | ) |
| 396 | } catch { |
| 397 | // never let logging crash the fetch |
| 398 | } |
| 399 | return inner(input, { ...init, headers }) |
| 400 | } |
| 401 | } |
| 402 |
no test coverage detected