@heroku/heroku-fetch 0.2.0 → 0.2.1

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/dist/browser.d.ts CHANGED
@@ -9,4 +9,4 @@
9
9
  */
10
10
  export { HerokuApiClient } from './client/index.js';
11
11
  export { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from './errors.js';
12
- export type { HerokuApiClientOptions, HerokuError, HerokuErrorResponse, HerokuService, RequestOptions, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
12
+ export type * from './public-types.js';
@@ -2,7 +2,7 @@
2
2
  * Default providers for browser environments
3
3
  * These are minimal since browsers don't have file system or CLI access
4
4
  */
5
- import type { TokenProvider, TwoFactorOptions } from '../types.js';
5
+ import type { FetchLike, TokenProvider, TwoFactorOptions } from '../types.js';
6
6
  /**
7
7
  * Get default token provider for browsers (none - must be explicitly provided)
8
8
  */
@@ -20,3 +20,15 @@ export declare function getDefaultTwoFactorOptions(): TwoFactorOptions | undefin
20
20
  * a TypeError in some bundlers.
21
21
  */
22
22
  export declare function getDefaultDispatcher(): Promise<undefined>;
23
+ /**
24
+ * Get a default `fetch` for the browser: the global `fetch`, with no
25
+ * dispatcher. Browsers route through their own proxy stack, so there is
26
+ * nothing to pair. Mirrors the Node `getDefaultFetch()` so consumers can call
27
+ * it uniformly across environments.
28
+ *
29
+ * Bound to `globalThis` because the browser `fetch` is a WebIDL method that
30
+ * brand-checks its receiver: a detached reference (`const f = fetch; f(...)`)
31
+ * throws `Illegal invocation`, and consumers call this returned reference
32
+ * detached.
33
+ */
34
+ export declare function getDefaultFetch(): Promise<FetchLike>;
@@ -25,3 +25,17 @@ export function getDefaultTwoFactorOptions() {
25
25
  export async function getDefaultDispatcher() {
26
26
  return undefined;
27
27
  }
28
+ /**
29
+ * Get a default `fetch` for the browser: the global `fetch`, with no
30
+ * dispatcher. Browsers route through their own proxy stack, so there is
31
+ * nothing to pair. Mirrors the Node `getDefaultFetch()` so consumers can call
32
+ * it uniformly across environments.
33
+ *
34
+ * Bound to `globalThis` because the browser `fetch` is a WebIDL method that
35
+ * brand-checks its receiver: a detached reference (`const f = fetch; f(...)`)
36
+ * throws `Illegal invocation`, and consumers call this returned reference
37
+ * detached.
38
+ */
39
+ export async function getDefaultFetch() {
40
+ return globalThis.fetch.bind(globalThis);
41
+ }
@@ -5,14 +5,75 @@
5
5
  * used by the ky HTTP client.
6
6
  */
7
7
  import type { AfterResponseHook, BeforeRequestHook } from 'ky';
8
- import type { TwoFactorOptions } from '../types.js';
8
+ import type { ResponseMetadata, TwoFactorOptions } from '../types.js';
9
+ import { type RequestIdStore } from './request-id.js';
9
10
  /**
10
- * Create a beforeRequest hook that adds authentication and custom headers
11
+ * Create a beforeRequest hook that attaches the bearer token.
12
+ *
13
+ * Static headers (the `Accept` default and any consumer-supplied custom
14
+ * headers) are set on the ky instance via its `headers` option, so ky merges
15
+ * them with per-call headers (per-call winning) before this hook runs. Only the
16
+ * token is resolved here, since it comes from an async provider and so can't be
17
+ * a static instance header.
18
+ */
19
+ export declare function createBeforeRequestHook(getToken: () => Promise<string | undefined>, debug?: boolean): BeforeRequestHook;
20
+ /**
21
+ * Create a beforeRequest hook that sets the accumulating `Request-Id`
22
+ * correlation header (with the 7KB overflow guard).
11
23
  */
12
- export declare function createBeforeRequestHook(getToken: () => Promise<string | undefined>, defaultAccept: string | undefined, customHeaders?: Record<string, string>, debug?: boolean): BeforeRequestHook;
24
+ export declare function createRequestIdBeforeHook(store: RequestIdStore): BeforeRequestHook;
13
25
  /**
14
- * Create an afterResponse hook that handles 2FA challenges and errors
26
+ * Create an afterResponse hook that feeds the server's echoed `Request-Id`s
27
+ * back into the accumulating store so later requests carry the full chain.
28
+ *
29
+ * Runs only on the success path: it is registered after the error-handling
30
+ * hook, which throws on a non-ok response and stops the chain.
31
+ */
32
+ export declare function createRequestIdAfterHook(store: RequestIdStore): AfterResponseHook;
33
+ /**
34
+ * Create an afterResponse hook that surfaces server warning headers to the
35
+ * user via the injected `warn` callback, deduped per client.
36
+ *
37
+ * Reads `x-heroku-warning` first, then `warning-message`. Each value is
38
+ * normalized (a leading `warning:` prefix stripped, then trimmed) and emitted
39
+ * at most once per unique normalized string over the client's lifetime.
40
+ *
41
+ * Note: the Fetch `Headers` API collapses repeated values of a header into one
42
+ * comma-joined string, so this reads a single string per header.
43
+ */
44
+ export declare function createWarningAfterHook(shownWarnings: Set<string>, warn: (message: string) => void): AfterResponseHook;
45
+ /**
46
+ * Create an afterResponse hook that surfaces structured success-path metadata
47
+ * (request-id, warnings) via the injected callback, so consumers get request
48
+ * correlation and warnings without re-parsing headers. Registered after the
49
+ * error-handling hook, so it only sees responses the client accepted.
50
+ */
51
+ export declare function createMetadataAfterHook(onMetadata: (metadata: ResponseMetadata) => void): AfterResponseHook;
52
+ /**
53
+ * Create an afterResponse hook that detects a 2FA challenge (a 412, or a 403
54
+ * carrying the `two_factor` error id) and, when a 2FA handler is configured and
55
+ * the request isn't already carrying a code, prompts for one and forces a
56
+ * retry.
57
+ *
58
+ * Registered before {@link createErrorAfterHook} so it sees the challenge
59
+ * response before it is thrown as an error. The retry is driven by ky's
60
+ * `ky.retry` (returned from {@link handle2FAChallenge}), which re-issues the
61
+ * request through this same client; the retried response then runs back through
62
+ * the full afterResponse chain — error handling, Request-Id, warnings,
63
+ * metadata, consumer hooks — exactly once.
64
+ *
65
+ * The `Heroku-Two-Factor-Code` header the retry carries is also the loop guard:
66
+ * if a request already bears a code and is still challenged (e.g. a wrong
67
+ * code), it is left to {@link createErrorAfterHook} to throw rather than
68
+ * retried again. This is per-request state, so concurrent requests on one
69
+ * client don't interfere. Returns the original response untouched when it isn't
70
+ * a handleable 2FA challenge.
71
+ */
72
+ export declare function create2FAAfterHook(twoFactorOptions: TwoFactorOptions | undefined): AfterResponseHook;
73
+ /**
74
+ * Create an afterResponse hook that throws a typed error on a non-ok response.
75
+ *
76
+ * Registered before the Request-Id, warning, metadata, and consumer hooks, so
77
+ * those run only on the success path (this throws and stops the chain first).
15
78
  */
16
- export declare function createAfterResponseHook(twoFactorOptions: TwoFactorOptions | undefined, twoFactorAttemptedRef: {
17
- value: boolean;
18
- }): AfterResponseHook;
79
+ export declare function createErrorAfterHook(): AfterResponseHook;
@@ -7,24 +7,26 @@
7
7
  import { debugAuth, debugRequest, debugResponse } from '../debug-loggers.js';
8
8
  import { logScrubbed } from '../redact.js';
9
9
  import { handleErrorResponse } from './http-error-handler.js';
10
+ import { REQUEST_ID_HEADER } from './request-id.js';
10
11
  import { handle2FAChallenge, is2FAError } from './two-factor-authentication-handler.js';
11
12
  /**
12
- * Create a beforeRequest hook that adds authentication and custom headers
13
+ * Upper bound on the per-client set of already-surfaced warnings. Dedupe stays
14
+ * a sliding window of the most recent warnings rather than the client's entire
15
+ * lifetime, so a long-lived client with many distinct warnings can't grow the
16
+ * set without limit.
13
17
  */
14
- export function createBeforeRequestHook(getToken, defaultAccept, customHeaders, debug) {
18
+ const MAX_SHOWN_WARNINGS = 256;
19
+ /**
20
+ * Create a beforeRequest hook that attaches the bearer token.
21
+ *
22
+ * Static headers (the `Accept` default and any consumer-supplied custom
23
+ * headers) are set on the ky instance via its `headers` option, so ky merges
24
+ * them with per-call headers (per-call winning) before this hook runs. Only the
25
+ * token is resolved here, since it comes from an async provider and so can't be
26
+ * a static instance header.
27
+ */
28
+ export function createBeforeRequestHook(getToken, debug) {
15
29
  return async ({ request }) => {
16
- // Apply the service's default Accept header when the caller
17
- // hasn't set one. Services that don't declare one (e.g. `custom`)
18
- // skip this entirely.
19
- if (defaultAccept && !request.headers.has('Accept')) {
20
- request.headers.set('Accept', defaultAccept);
21
- }
22
- // Add custom headers from options
23
- if (customHeaders) {
24
- for (const [key, value] of Object.entries(customHeaders)) {
25
- request.headers.set(key, value);
26
- }
27
- }
28
30
  // Add authorization header.
29
31
  //
30
32
  // We deliberately don't strip this on cross-origin redirects: the
@@ -47,18 +49,142 @@ export function createBeforeRequestHook(getToken, defaultAccept, customHeaders,
47
49
  };
48
50
  }
49
51
  /**
50
- * Create an afterResponse hook that handles 2FA challenges and errors
52
+ * Create a beforeRequest hook that sets the accumulating `Request-Id`
53
+ * correlation header (with the 7KB overflow guard).
54
+ */
55
+ export function createRequestIdBeforeHook(store) {
56
+ return ({ request }) => {
57
+ request.headers.set(REQUEST_ID_HEADER, store.nextHeaderValue());
58
+ };
59
+ }
60
+ /**
61
+ * Create an afterResponse hook that feeds the server's echoed `Request-Id`s
62
+ * back into the accumulating store so later requests carry the full chain.
63
+ *
64
+ * Runs only on the success path: it is registered after the error-handling
65
+ * hook, which throws on a non-ok response and stops the chain.
66
+ */
67
+ export function createRequestIdAfterHook(store) {
68
+ return ({ response }) => {
69
+ const header = response.headers.get(REQUEST_ID_HEADER);
70
+ if (header) {
71
+ store.track(...splitRequestIds(header));
72
+ }
73
+ };
74
+ }
75
+ /**
76
+ * Split a `Request-Id` header into its individual ids, trimming surrounding
77
+ * whitespace and dropping empty segments, so a server that joins with `", "`
78
+ * (or leaves a trailing comma) doesn't produce padded or empty ids.
79
+ */
80
+ function splitRequestIds(header) {
81
+ return header.split(',').map(id => id.trim()).filter(Boolean);
82
+ }
83
+ /**
84
+ * Create an afterResponse hook that surfaces server warning headers to the
85
+ * user via the injected `warn` callback, deduped per client.
86
+ *
87
+ * Reads `x-heroku-warning` first, then `warning-message`. Each value is
88
+ * normalized (a leading `warning:` prefix stripped, then trimmed) and emitted
89
+ * at most once per unique normalized string over the client's lifetime.
90
+ *
91
+ * Note: the Fetch `Headers` API collapses repeated values of a header into one
92
+ * comma-joined string, so this reads a single string per header.
93
+ */
94
+ export function createWarningAfterHook(shownWarnings, warn) {
95
+ return ({ response }) => {
96
+ const normalized = normalizedWarning(response);
97
+ // The `has` check gates the `warn()` emission below, not the set insertion
98
+ // (which is already idempotent): it's what makes a repeat warning silent.
99
+ if (!normalized || shownWarnings.has(normalized))
100
+ return;
101
+ if (shownWarnings.size >= MAX_SHOWN_WARNINGS) {
102
+ // Bound memory on a long-lived client: evict the oldest surfaced warning
103
+ // (Sets iterate in insertion order) so dedupe becomes a sliding window
104
+ // rather than growing unbounded for the client's whole lifetime.
105
+ const oldest = shownWarnings.values().next().value;
106
+ if (oldest !== undefined)
107
+ shownWarnings.delete(oldest);
108
+ }
109
+ shownWarnings.add(normalized);
110
+ warn(normalized);
111
+ };
112
+ }
113
+ /**
114
+ * Create an afterResponse hook that surfaces structured success-path metadata
115
+ * (request-id, warnings) via the injected callback, so consumers get request
116
+ * correlation and warnings without re-parsing headers. Registered after the
117
+ * error-handling hook, so it only sees responses the client accepted.
118
+ */
119
+ export function createMetadataAfterHook(onMetadata) {
120
+ return ({ request, response }) => {
121
+ const normalized = normalizedWarning(response);
122
+ const requestIdHeader = response.headers.get(REQUEST_ID_HEADER);
123
+ onMetadata({
124
+ requestIds: requestIdHeader ? splitRequestIds(requestIdHeader) : [],
125
+ status: response.status,
126
+ url: request.url,
127
+ warnings: normalized ? [normalized] : [],
128
+ });
129
+ };
130
+ }
131
+ /**
132
+ * The warning a response carries, normalized (leading `warning:` prefix
133
+ * stripped, trimmed), or `undefined` if none. Reads `x-heroku-warning` first,
134
+ * then `warning-message`. Shared by the warn-surfacing and metadata hooks so
135
+ * both apply the same normalization.
136
+ */
137
+ function normalizedWarning(response) {
138
+ const raw = response.headers.get('x-heroku-warning') ?? response.headers.get('warning-message');
139
+ if (!raw)
140
+ return undefined;
141
+ return raw.replace(/^\s*warning:?\s*/i, '').trim() || undefined;
142
+ }
143
+ /**
144
+ * Create an afterResponse hook that detects a 2FA challenge (a 412, or a 403
145
+ * carrying the `two_factor` error id) and, when a 2FA handler is configured and
146
+ * the request isn't already carrying a code, prompts for one and forces a
147
+ * retry.
148
+ *
149
+ * Registered before {@link createErrorAfterHook} so it sees the challenge
150
+ * response before it is thrown as an error. The retry is driven by ky's
151
+ * `ky.retry` (returned from {@link handle2FAChallenge}), which re-issues the
152
+ * request through this same client; the retried response then runs back through
153
+ * the full afterResponse chain — error handling, Request-Id, warnings,
154
+ * metadata, consumer hooks — exactly once.
155
+ *
156
+ * The `Heroku-Two-Factor-Code` header the retry carries is also the loop guard:
157
+ * if a request already bears a code and is still challenged (e.g. a wrong
158
+ * code), it is left to {@link createErrorAfterHook} to throw rather than
159
+ * retried again. This is per-request state, so concurrent requests on one
160
+ * client don't interfere. Returns the original response untouched when it isn't
161
+ * a handleable 2FA challenge.
51
162
  */
52
- export function createAfterResponseHook(twoFactorOptions, twoFactorAttemptedRef) {
163
+ export function create2FAAfterHook(twoFactorOptions) {
53
164
  return async ({ request, response }) => {
54
- debugResponse('%s %s -> %d', request.method, request.url, response.status);
55
- // Handle 2FA challenge (can be 403 or 412)
165
+ // Cheap guards first, so the body-reading is2FAError() probe below is only
166
+ // reached when it can matter: skip when no 2FA handler is configured, or
167
+ // when the request already carries a code (the retry — also the loop guard).
168
+ if (!twoFactorOptions || request.headers.has('Heroku-Two-Factor-Code')) {
169
+ return response;
170
+ }
56
171
  const is2FAChallenge = response.status === 412
57
172
  || (response.status === 403 && await is2FAError(response));
58
- if (is2FAChallenge && twoFactorOptions && !twoFactorAttemptedRef.value) {
59
- return handle2FAChallenge(request, twoFactorOptions, twoFactorAttemptedRef);
173
+ if (is2FAChallenge) {
174
+ return handle2FAChallenge(request, twoFactorOptions);
60
175
  }
61
- // Handle errors
176
+ return response;
177
+ };
178
+ }
179
+ /**
180
+ * Create an afterResponse hook that throws a typed error on a non-ok response.
181
+ *
182
+ * Registered before the Request-Id, warning, metadata, and consumer hooks, so
183
+ * those run only on the success path (this throws and stops the chain first).
184
+ */
185
+ export function createErrorAfterHook() {
186
+ return async ({ request, response }) => {
187
+ debugResponse('%s %s -> %d', request.method, request.url, response.status);
62
188
  if (!response.ok) {
63
189
  await handleErrorResponse(response);
64
190
  }
@@ -10,8 +10,9 @@ export declare class HerokuApiClient {
10
10
  private clientPromise;
11
11
  private kyOptions;
12
12
  private options;
13
+ private readonly requestIds;
14
+ private readonly shownWarnings;
13
15
  private tokenProvider?;
14
- private twoFactorAttempted;
15
16
  constructor(options?: HerokuApiClientOptions);
16
17
  /**
17
18
  * Make a DELETE request
@@ -42,8 +43,14 @@ export declare class HerokuApiClient {
42
43
  */
43
44
  stream(path: string, options?: RequestOptions): Promise<Response>;
44
45
  /**
45
- * Lazily construct ky with an env-aware undici dispatcher (Node)
46
- * or no dispatcher (browser). Cached after the first call.
46
+ * Lazily construct ky over a fetch that is proxy-aware on Node (undici's own
47
+ * fetch paired with an env-var dispatcher) and the global fetch in the
48
+ * browser. Cached after the first call.
49
+ *
50
+ * We drive ky through `fetch` rather than ky's `dispatcher` option because
51
+ * ky calls the global `fetch`, which on Node 22 is backed by a different
52
+ * undici than our dispatcher and rejects it (`invalid onRequestStart
53
+ * method`). `getDefaultFetch()` returns a fetch from the matching undici.
47
54
  */
48
55
  private getClient;
49
56
  /**
@@ -5,15 +5,20 @@
5
5
  * Supports multiple services (platform, data, particleboard), authentication,
6
6
  * two-factor authentication, and comprehensive error handling.
7
7
  */
8
- import { getDefaultDispatcher, getDefaultTokenProvider, getDefaultTwoFactorOptions } from '@heroku/heroku-fetch/client/environment-defaults.js';
8
+ import { getDefaultFetch, getDefaultTokenProvider, getDefaultTwoFactorOptions } from '@heroku/heroku-fetch/client/environment-defaults.js';
9
9
  import ky from 'ky';
10
10
  import { debugAuth, debugRequest } from '../debug-loggers.js';
11
- import { createAfterResponseHook, createBeforeRequestHook } from './http-request-hooks.js';
11
+ import { create2FAAfterHook, createBeforeRequestHook, createErrorAfterHook, createMetadataAfterHook, createRequestIdAfterHook, createRequestIdBeforeHook, createWarningAfterHook, } from './http-request-hooks.js';
12
+ import { RequestIdStore } from './request-id.js';
12
13
  import { SERVICE_CONFIGS } from './service-configurations.js';
13
14
  export class HerokuApiClient {
14
15
  constructor(options = {}) {
15
16
  this.clientPromise = null;
16
- this.twoFactorAttempted = { value: false };
17
+ // Per-client cross-cutting request state: the Request-Id accumulation and the
18
+ // set of warnings already surfaced, so dedupe spans a multi-request session
19
+ // but resets per client and parallel clients stay isolated.
20
+ this.requestIds = new RequestIdStore();
21
+ this.shownWarnings = new Set();
17
22
  this.options = {
18
23
  service: options.service || 'platform',
19
24
  timeout: options.timeout || 30000,
@@ -37,18 +42,44 @@ export class HerokuApiClient {
37
42
  }
38
43
  debugAuth('Initializing client for service: %s, baseUrl: %s', this.options.service, baseUrl);
39
44
  // Stash the ky options; the actual ky instance is built lazily so
40
- // we can await getDefaultDispatcher() (Node loads undici
41
- // dynamically for env-var proxy support).
45
+ // we can await getDefaultFetch() (Node loads undici dynamically for
46
+ // env-var proxy support).
47
+ // Static headers go on the instance so ky merges them with per-call headers
48
+ // (per-call winning). A per-client `defaultAccept` override wins over the
49
+ // shared service default; services that declare no default (e.g. `custom`)
50
+ // and no override contribute no Accept at all.
51
+ const defaultAccept = options.defaultAccept ?? serviceConfig.defaultAccept;
52
+ const headers = { ...options.headers };
53
+ // Case-insensitive check: a consumer may have supplied Accept under any
54
+ // casing, and ky merges headers case-insensitively (last write wins), so a
55
+ // plain `'Accept' in headers` test would miss a lowercase `accept` and let
56
+ // our default clobber the consumer's choice.
57
+ if (defaultAccept && !new Headers(options.headers).has('accept')) {
58
+ headers.Accept = defaultAccept;
59
+ }
42
60
  this.kyOptions = {
61
+ headers,
43
62
  hooks: {
63
+ // Order matters: the 2FA hook runs first (so it sees a challenge before
64
+ // it's thrown as an error and can force a retry), then the error hook
65
+ // throws on a non-ok response — so the Request-Id tracking, warning, and
66
+ // metadata hooks after it run only on the success path.
44
67
  afterResponse: [
45
- createAfterResponseHook(this.options.twoFactor, this.twoFactorAttempted),
68
+ create2FAAfterHook(this.options.twoFactor),
69
+ createErrorAfterHook(),
70
+ createRequestIdAfterHook(this.requestIds),
71
+ createWarningAfterHook(this.shownWarnings, message => this.options.warn?.(message)),
72
+ createMetadataAfterHook(metadata => this.options.onResponseMetadata?.(metadata)),
73
+ // Consumer hooks run last: they see the resolved success-path
74
+ // response (the error-handling built-in above throws on non-2xx).
75
+ ...(options.hooks?.afterResponse ?? []),
46
76
  ],
47
77
  beforeRequest: [
48
- createBeforeRequestHook(() => this.getToken(),
49
- // A per-client override wins over the shared service default, but
50
- // is still only applied when the request has no Accept of its own.
51
- options.defaultAccept ?? serviceConfig.defaultAccept, options.headers, this.options.debug),
78
+ createBeforeRequestHook(() => this.getToken(), this.options.debug),
79
+ createRequestIdBeforeHook(this.requestIds),
80
+ // Consumer hooks run last: they see (and may override) the fully
81
+ // prepared request after auth and Request-Id are attached.
82
+ ...(options.hooks?.beforeRequest ?? []),
52
83
  ],
53
84
  },
54
85
  prefix: baseUrl,
@@ -96,11 +127,19 @@ export class HerokuApiClient {
96
127
  setOption(key, value) {
97
128
  if (key === 'token') {
98
129
  this.tokenProvider = value;
130
+ return;
99
131
  }
100
- else {
132
+ // Only these are re-read on each request, so changing them takes effect.
133
+ // Everything else — hooks, headers, the Accept default, the 2FA handler,
134
+ // and the base URL derived from service/region — is baked into the cached
135
+ // ky instance at construction; mutating it here would silently no-op, so
136
+ // reject it rather than lie about the change landing.
137
+ if (key === 'timeout' || key === 'warn' || key === 'onResponseMetadata') {
101
138
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
102
139
  this.options[key] = value;
140
+ return;
103
141
  }
142
+ throw new Error(`setOption: "${key}" is fixed at construction and cannot be changed on an existing client; pass it to the constructor instead.`);
104
143
  }
105
144
  /**
106
145
  * Create a streaming request (returns the Response object for stream access)
@@ -108,29 +147,33 @@ export class HerokuApiClient {
108
147
  async stream(path, options) {
109
148
  debugRequest('STREAM %s', path);
110
149
  const kyOptions = {
111
- headers: options?.headers,
150
+ // Only set these when the caller supplied them: a literal `undefined`
151
+ // overrides (and for headers, clears) what ky merges from the instance,
152
+ // rather than leaving the instance value untouched.
153
+ ...(options?.headers && { headers: options.headers }),
154
+ ...(options?.searchParams && { searchParams: options.searchParams }),
155
+ ...(options?.signal && { signal: options.signal }),
112
156
  method: 'GET',
113
- searchParams: options?.searchParams,
114
- signal: options?.signal,
115
157
  timeout: options?.timeout || this.options.timeout,
116
158
  };
117
159
  const client = await this.getClient();
118
160
  return client(path, kyOptions);
119
161
  }
120
162
  /**
121
- * Lazily construct ky with an env-aware undici dispatcher (Node)
122
- * or no dispatcher (browser). Cached after the first call.
163
+ * Lazily construct ky over a fetch that is proxy-aware on Node (undici's own
164
+ * fetch paired with an env-var dispatcher) and the global fetch in the
165
+ * browser. Cached after the first call.
166
+ *
167
+ * We drive ky through `fetch` rather than ky's `dispatcher` option because
168
+ * ky calls the global `fetch`, which on Node 22 is backed by a different
169
+ * undici than our dispatcher and rejects it (`invalid onRequestStart
170
+ * method`). `getDefaultFetch()` returns a fetch from the matching undici.
123
171
  */
124
172
  async getClient() {
125
173
  if (!this.clientPromise) {
126
174
  this.clientPromise = (async () => {
127
- const dispatcher = await getDefaultDispatcher();
128
- // ky's type definitions don't include `dispatcher`; it's
129
- // passed through to fetch as undici expects it.
130
- const opts = dispatcher
131
- ? { ...this.kyOptions, dispatcher }
132
- : this.kyOptions;
133
- return ky.create(opts);
175
+ const fetch = await getDefaultFetch();
176
+ return ky.create({ ...this.kyOptions, fetch });
134
177
  })();
135
178
  }
136
179
  return this.clientPromise;
@@ -152,10 +195,13 @@ export class HerokuApiClient {
152
195
  */
153
196
  async request(path, options) {
154
197
  const kyOptions = {
155
- headers: options?.headers,
198
+ // Only set these when the caller supplied them: a literal `undefined`
199
+ // overrides (and for headers, clears) what ky merges from the instance,
200
+ // rather than leaving the instance value untouched.
201
+ ...(options?.headers && { headers: options.headers }),
202
+ ...(options?.searchParams && { searchParams: options.searchParams }),
203
+ ...(options?.signal && { signal: options.signal }),
156
204
  method: options?.method || 'GET',
157
- searchParams: options?.searchParams,
158
- signal: options?.signal,
159
205
  timeout: options?.timeout || this.options.timeout,
160
206
  };
161
207
  if (options?.body !== undefined) {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Default providers for Node.js environments
3
3
  */
4
- import type { TokenProvider, TwoFactorOptions } from '../types.js';
4
+ import type { FetchLike, TokenProvider, TwoFactorOptions } from '../types.js';
5
5
  /**
6
6
  * Get default token provider for Node.js (reads the HEROKU_API_KEY env var)
7
7
  *
@@ -20,7 +20,29 @@ export declare function getDefaultTokenProvider(): TokenProvider;
20
20
  */
21
21
  export declare function getDefaultTwoFactorOptions(): TwoFactorOptions;
22
22
  /**
23
- * Get an undici Dispatcher that routes Node's fetch through an
23
+ * Get a `fetch` that is already paired with the proxy dispatcher from
24
+ * `getDefaultDispatcher()`, drawn from the **same undici copy**.
25
+ *
26
+ * This exists because of a cross-undici-version trap: `getDefaultDispatcher()`
27
+ * builds its `EnvHttpProxyAgent` from the npm `undici` this package depends on
28
+ * (v8), but Node's built-in global `fetch` is backed by a *different* bundled
29
+ * undici (v6 on Node 22) whose dispatcher handler interface is incompatible.
30
+ * Handing an npm-undici dispatcher to global `fetch` fails
31
+ * (`InvalidArgumentError: invalid onRequestStart method`). So the dispatcher
32
+ * must be driven by undici's *own* `fetch`, and because the brand check on
33
+ * `Request` is per-copy, a `Request` built by the global constructor isn't
34
+ * recognized by undici's `fetch` and has to be decomposed into `(url, init)`.
35
+ *
36
+ * This function hides all of that: callers get a plain `FetchLike`.
37
+ * - No proxy env var set → the global `fetch` (no dispatcher needed; it is the
38
+ * one case that already works).
39
+ * - Proxy set → undici's `fetch` carrying the dispatcher, decomposing any
40
+ * `Request` input first.
41
+ * - undici not loadable (e.g. Bun) → the global `fetch`, unproxied.
42
+ */
43
+ export declare function getDefaultFetch(): Promise<FetchLike>;
44
+ /**
45
+ * Get an undici Dispatcher that routes requests through an
24
46
  * `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`-aware proxy agent.
25
47
  *
26
48
  * Returns `undefined` when no proxy env var is set, so we don't
@@ -33,7 +55,11 @@ export declare function getDefaultTwoFactorOptions(): TwoFactorOptions;
33
55
  * ship undici); callers should skip the option in that case so ky
34
56
  * falls back to native fetch.
35
57
  *
36
- * ky forwards the `dispatcher` option through to the underlying
37
- * fetch — see https://github.com/sindresorhus/ky#proxy-support-nodejs.
58
+ * WARNING: the returned dispatcher comes from the npm `undici` this package
59
+ * depends on and must be driven by that same undici's `fetch` — NOT Node's
60
+ * built-in global `fetch`, which bundles a different, incompatible undici and
61
+ * throws `invalid onRequestStart method`. Most callers should use
62
+ * `getDefaultFetch()` instead, which pairs the two correctly and returns a
63
+ * ready-to-use `fetch`.
38
64
  */
39
65
  export declare function getDefaultDispatcher(): Promise<undefined | unknown>;
@@ -30,7 +30,42 @@ export function getDefaultTwoFactorOptions() {
30
30
  };
31
31
  }
32
32
  /**
33
- * Get an undici Dispatcher that routes Node's fetch through an
33
+ * Get a `fetch` that is already paired with the proxy dispatcher from
34
+ * `getDefaultDispatcher()`, drawn from the **same undici copy**.
35
+ *
36
+ * This exists because of a cross-undici-version trap: `getDefaultDispatcher()`
37
+ * builds its `EnvHttpProxyAgent` from the npm `undici` this package depends on
38
+ * (v8), but Node's built-in global `fetch` is backed by a *different* bundled
39
+ * undici (v6 on Node 22) whose dispatcher handler interface is incompatible.
40
+ * Handing an npm-undici dispatcher to global `fetch` fails
41
+ * (`InvalidArgumentError: invalid onRequestStart method`). So the dispatcher
42
+ * must be driven by undici's *own* `fetch`, and because the brand check on
43
+ * `Request` is per-copy, a `Request` built by the global constructor isn't
44
+ * recognized by undici's `fetch` and has to be decomposed into `(url, init)`.
45
+ *
46
+ * This function hides all of that: callers get a plain `FetchLike`.
47
+ * - No proxy env var set → the global `fetch` (no dispatcher needed; it is the
48
+ * one case that already works).
49
+ * - Proxy set → undici's `fetch` carrying the dispatcher, decomposing any
50
+ * `Request` input first.
51
+ * - undici not loadable (e.g. Bun) → the global `fetch`, unproxied.
52
+ */
53
+ export async function getDefaultFetch() {
54
+ const dispatcher = await getDefaultDispatcher();
55
+ if (!dispatcher) {
56
+ return (input, init) => fetch(input, init);
57
+ }
58
+ try {
59
+ const { fetch: undiciFetch } = await import('undici');
60
+ return (input, init) => fetchThroughDispatcher(undiciFetch, dispatcher, input, init);
61
+ }
62
+ catch (error) {
63
+ await logScrubbed(debugRequest, 'undici fetch not available; using global fetch without proxy (%o)', error);
64
+ return (input, init) => fetch(input, init);
65
+ }
66
+ }
67
+ /**
68
+ * Get an undici Dispatcher that routes requests through an
34
69
  * `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`-aware proxy agent.
35
70
  *
36
71
  * Returns `undefined` when no proxy env var is set, so we don't
@@ -43,8 +78,12 @@ export function getDefaultTwoFactorOptions() {
43
78
  * ship undici); callers should skip the option in that case so ky
44
79
  * falls back to native fetch.
45
80
  *
46
- * ky forwards the `dispatcher` option through to the underlying
47
- * fetch — see https://github.com/sindresorhus/ky#proxy-support-nodejs.
81
+ * WARNING: the returned dispatcher comes from the npm `undici` this package
82
+ * depends on and must be driven by that same undici's `fetch` — NOT Node's
83
+ * built-in global `fetch`, which bundles a different, incompatible undici and
84
+ * throws `invalid onRequestStart method`. Most callers should use
85
+ * `getDefaultFetch()` instead, which pairs the two correctly and returns a
86
+ * ready-to-use `fetch`.
48
87
  */
49
88
  export async function getDefaultDispatcher() {
50
89
  if (!hasProxyEnv()) {
@@ -68,3 +107,37 @@ function hasProxyEnv() {
68
107
  || process.env.HTTPS_PROXY
69
108
  || process.env.https_proxy);
70
109
  }
110
+ /**
111
+ * Drive undici's `fetch` with a dispatcher from the same undici copy.
112
+ *
113
+ * A `string` / `URL` input is forwarded as-is. A `Request` input may have been
114
+ * built by the global constructor (a different undici copy), which undici's
115
+ * `fetch` won't recognize, so it is decomposed into `(url, init)`. The body is
116
+ * buffered — the Heroku API requests this transport sends carry small JSON
117
+ * payloads, not streamed uploads. An explicit `init` wins over the Request's
118
+ * own fields (matching `fetch` semantics); the dispatcher is always applied.
119
+ */
120
+ async function fetchThroughDispatcher(undiciFetch, dispatcher, input, init) {
121
+ if (typeof input === 'string' || input instanceof URL) {
122
+ const withDispatcher = { ...init, dispatcher };
123
+ return undiciFetch(input, withDispatcher);
124
+ }
125
+ const headers = {};
126
+ // Headers isn't iterable under the project's ES2020+DOM lib (no DOM.Iterable),
127
+ // so forEach is the available copy idiom here.
128
+ // eslint-disable-next-line unicorn/no-array-for-each
129
+ input.headers.forEach((value, key) => {
130
+ headers[key] = value;
131
+ });
132
+ const hasBody = input.method !== 'GET' && input.method !== 'HEAD';
133
+ const withDispatcher = {
134
+ body: hasBody ? await input.arrayBuffer() : undefined,
135
+ headers,
136
+ method: input.method,
137
+ redirect: input.redirect,
138
+ signal: input.signal,
139
+ ...init,
140
+ dispatcher,
141
+ };
142
+ return undiciFetch(input.url, withDispatcher);
143
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Request-Id correlation store.
3
+ *
4
+ * Each client accumulates the `Request-Id`s it has generated and the ones the
5
+ * server echoes back, and sends the running list on every request so a chain of
6
+ * related calls can be correlated server-side. The store is per-client, so
7
+ * parallel clients don't cross-contaminate and the accumulation resets when a
8
+ * client is discarded.
9
+ */
10
+ /** The header the Heroku API reads/echoes for request correlation. */
11
+ export declare const REQUEST_ID_HEADER = "Request-Id";
12
+ export declare class RequestIdStore {
13
+ private readonly generate;
14
+ private ids;
15
+ private readonly idSet;
16
+ /**
17
+ * @param generate UUID generator; defaults to the platform's
18
+ * `crypto.randomUUID` (present on Node 18+ and in browsers). Injectable for
19
+ * deterministic tests. Wrapped in an arrow rather than passed as a bare
20
+ * `globalThis.crypto.randomUUID` because it's a method that brand-checks its
21
+ * receiver — called unbound it throws `this` must be of type `Crypto`.
22
+ */
23
+ constructor(generate?: () => string);
24
+ /** Current accumulated ids joined for the header (comma, no space). */
25
+ get headerValue(): string;
26
+ /** Generate a new id, prepend it to the accumulated list, return the list. */
27
+ create(): string[];
28
+ /**
29
+ * The header value to send on the next request: generate+accumulate a fresh
30
+ * id, then apply the overflow guard. On overflow the OLDEST ids are dropped
31
+ * (the chain is prepend-ordered, so the tail is oldest) until the header fits
32
+ * — keeping the newest end so correlation with the immediately preceding
33
+ * requests survives instead of being severed by a full reset. A lone id that
34
+ * already exceeds the cap is kept as-is. Always returns the comma-joined
35
+ * string.
36
+ */
37
+ nextHeaderValue(): string;
38
+ /** Prepend server-returned ids not already tracked (dedupe), return the list. */
39
+ track(...ids: string[]): string[];
40
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Request-Id correlation store.
3
+ *
4
+ * Each client accumulates the `Request-Id`s it has generated and the ones the
5
+ * server echoes back, and sends the running list on every request so a chain of
6
+ * related calls can be correlated server-side. The store is per-client, so
7
+ * parallel clients don't cross-contaminate and the accumulation resets when a
8
+ * client is discarded.
9
+ */
10
+ /** The header the Heroku API reads/echoes for request correlation. */
11
+ export const REQUEST_ID_HEADER = 'Request-Id';
12
+ /**
13
+ * Cap the accumulated header at 7KB. Long-running polls (e.g. `pg:wait`) have
14
+ * been observed to push the accumulated `Request-Id` header past 8KB — Node's
15
+ * default max header size — which fails the request. 7KB leaves room for the
16
+ * other headers. Measured in bytes (not characters) via TextEncoder so it
17
+ * matches what goes on the wire without depending on Node's Buffer.
18
+ */
19
+ const MAX_REQUEST_ID_BYTES = 1024 * 7;
20
+ function byteLength(value) {
21
+ return new TextEncoder().encode(value).length;
22
+ }
23
+ export class RequestIdStore {
24
+ /**
25
+ * @param generate UUID generator; defaults to the platform's
26
+ * `crypto.randomUUID` (present on Node 18+ and in browsers). Injectable for
27
+ * deterministic tests. Wrapped in an arrow rather than passed as a bare
28
+ * `globalThis.crypto.randomUUID` because it's a method that brand-checks its
29
+ * receiver — called unbound it throws `this` must be of type `Crypto`.
30
+ */
31
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins -- global `crypto` is available on Node 22 (and in browsers); the lint engine's compatibility table conservatively marks it 23+. Using node:crypto would break the Node-agnostic core.
32
+ constructor(generate = () => globalThis.crypto.randomUUID()) {
33
+ this.generate = generate;
34
+ this.ids = [];
35
+ // Mirrors `ids` for O(1) membership in track(), so dedupe stays linear in the
36
+ // ids being added rather than scanning the whole accumulated chain per id.
37
+ this.idSet = new Set();
38
+ }
39
+ /** Current accumulated ids joined for the header (comma, no space). */
40
+ get headerValue() {
41
+ return this.ids.join(',');
42
+ }
43
+ /** Generate a new id, prepend it to the accumulated list, return the list. */
44
+ create() {
45
+ const id = this.generate();
46
+ this.ids = [id, ...this.ids];
47
+ this.idSet.add(id);
48
+ return this.ids;
49
+ }
50
+ /**
51
+ * The header value to send on the next request: generate+accumulate a fresh
52
+ * id, then apply the overflow guard. On overflow the OLDEST ids are dropped
53
+ * (the chain is prepend-ordered, so the tail is oldest) until the header fits
54
+ * — keeping the newest end so correlation with the immediately preceding
55
+ * requests survives instead of being severed by a full reset. A lone id that
56
+ * already exceeds the cap is kept as-is. Always returns the comma-joined
57
+ * string.
58
+ */
59
+ nextHeaderValue() {
60
+ this.create();
61
+ while (this.ids.length > 1 && byteLength(this.headerValue) > MAX_REQUEST_ID_BYTES) {
62
+ const dropped = this.ids.pop();
63
+ if (dropped !== undefined) {
64
+ this.idSet.delete(dropped);
65
+ }
66
+ }
67
+ return this.headerValue;
68
+ }
69
+ /** Prepend server-returned ids not already tracked (dedupe), return the list. */
70
+ track(...ids) {
71
+ const novel = ids.filter(id => !this.idSet.has(id));
72
+ for (const id of novel) {
73
+ this.idSet.add(id);
74
+ }
75
+ this.ids = [...novel, ...this.ids];
76
+ return this.ids;
77
+ }
78
+ }
@@ -3,14 +3,28 @@
3
3
  *
4
4
  * Handles detection and processing of 2FA challenges from the API.
5
5
  */
6
+ import ky from 'ky';
6
7
  import type { TwoFactorOptions } from '../types.js';
7
8
  /**
8
9
  * Check if a 403 response is a 2FA error by checking the error id
9
10
  */
10
11
  export declare function is2FAError(response: Response): Promise<boolean>;
11
12
  /**
12
- * Handle a 2FA challenge by prompting for a code and retrying the request
13
+ * Handle a 2FA challenge by prompting for a code and forcing a retry of the
14
+ * request with the `Heroku-Two-Factor-Code` header attached.
15
+ *
16
+ * Returns ky's forced-retry marker (`ky.retry`) so ky re-issues the request
17
+ * through this same client — reusing its fetch, auth, and the original
18
+ * request's per-call timeout and abort signal — and runs the retried response
19
+ * back through the full afterResponse chain (error handling, Request-Id,
20
+ * warnings, metadata, and consumer hooks) exactly once. The forced retry counts
21
+ * against `retry.limit` and is observable in `beforeRetry` as a
22
+ * `ForceRetryError`.
23
+ *
24
+ * Because it draws on the same retry budget as ky's transport retries, a
25
+ * request that already exhausted `retry.limit` on network/timeout retries would
26
+ * surface the raw `ForceRetryError` rather than re-issuing. In practice a 2FA
27
+ * challenge arrives on the first attempt (before any transport retry), so the
28
+ * budget is intact; this edge only matters if that assumption ever breaks.
13
29
  */
14
- export declare function handle2FAChallenge(request: Request, twoFactorOptions: TwoFactorOptions, twoFactorAttemptedRef: {
15
- value: boolean;
16
- }): Promise<Response>;
30
+ export declare function handle2FAChallenge(request: Request, twoFactorOptions: TwoFactorOptions): Promise<ReturnType<typeof ky.retry>>;
@@ -24,30 +24,33 @@ export async function is2FAError(response) {
24
24
  return false;
25
25
  }
26
26
  /**
27
- * Handle a 2FA challenge by prompting for a code and retrying the request
27
+ * Handle a 2FA challenge by prompting for a code and forcing a retry of the
28
+ * request with the `Heroku-Two-Factor-Code` header attached.
29
+ *
30
+ * Returns ky's forced-retry marker (`ky.retry`) so ky re-issues the request
31
+ * through this same client — reusing its fetch, auth, and the original
32
+ * request's per-call timeout and abort signal — and runs the retried response
33
+ * back through the full afterResponse chain (error handling, Request-Id,
34
+ * warnings, metadata, and consumer hooks) exactly once. The forced retry counts
35
+ * against `retry.limit` and is observable in `beforeRetry` as a
36
+ * `ForceRetryError`.
37
+ *
38
+ * Because it draws on the same retry budget as ky's transport retries, a
39
+ * request that already exhausted `retry.limit` on network/timeout retries would
40
+ * surface the raw `ForceRetryError` rather than re-issuing. In practice a 2FA
41
+ * challenge arrives on the first attempt (before any transport retry), so the
42
+ * budget is intact; this edge only matters if that assumption ever breaks.
28
43
  */
29
- export async function handle2FAChallenge(request, twoFactorOptions, twoFactorAttemptedRef) {
30
- twoFactorAttemptedRef.value = true;
44
+ export async function handle2FAChallenge(request, twoFactorOptions) {
31
45
  debugAuth('2FA challenge detected, invoking callback');
32
46
  try {
33
47
  const twoFactorCode = await twoFactorOptions.onChallenge();
34
48
  debugAuth('2FA code received, retrying request');
35
- // Retry the request with 2FA code
36
- const headers = {};
37
- // eslint-disable-next-line unicorn/no-array-for-each
38
- request.headers.forEach((value, key) => {
39
- headers[key] = value;
40
- });
41
- headers['Heroku-Two-Factor-Code'] = twoFactorCode;
42
- const retryRequest = new Request(request, {
43
- headers,
44
- });
45
- const retryResponse = await ky(retryRequest);
46
- twoFactorAttemptedRef.value = false;
47
- return retryResponse;
49
+ const headers = new Headers(request.headers);
50
+ headers.set('Heroku-Two-Factor-Code', twoFactorCode);
51
+ return ky.retry({ code: 'TWO_FACTOR', request: new Request(request, { headers }) });
48
52
  }
49
53
  catch (error) {
50
- twoFactorAttemptedRef.value = false;
51
54
  await logScrubbed(debugError, '2FA retry failed: %O', error);
52
55
  throw error;
53
56
  }
package/dist/index.d.ts CHANGED
@@ -2,4 +2,4 @@ export { cliTwoFactorPrompt, createCliTwoFactorPrompt, } from './cli/cli-two-fac
2
2
  export { HerokuApiClient } from './client/index.js';
3
3
  export { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from './errors.js';
4
4
  export { getApiHost, getApiUrl, } from './host.js';
5
- export type { HerokuApiClientOptions, HerokuError, HerokuErrorResponse, HerokuService, RequestOptions, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
5
+ export type * from './public-types.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The package's public type surface, in one place so the Node (`index.ts`) and
3
+ * browser (`browser.ts`) entry points export an identical set and can't drift.
4
+ * Types only — runtime values (the client class, errors, helpers) are exported
5
+ * directly from each entry point, which differ by environment.
6
+ */
7
+ export type { FetchLike, HerokuAfterResponseHook, HerokuApiClientOptions, HerokuBeforeRequestHook, HerokuError, HerokuErrorResponse, HerokuHooks, HerokuService, RequestOptions, ResponseMetadata, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The package's public type surface, in one place so the Node (`index.ts`) and
3
+ * browser (`browser.ts`) entry points export an identical set and can't drift.
4
+ * Types only — runtime values (the client class, errors, helpers) are exported
5
+ * directly from each entry point, which differ by environment.
6
+ */
7
+ export {};
package/dist/types.d.ts CHANGED
@@ -1,4 +1,52 @@
1
1
  export type HerokuService = 'custom' | 'data' | 'particleboard' | 'platform';
2
+ /**
3
+ * A `beforeRequest` hook: runs after the client's built-ins have prepared the
4
+ * `Request` and may inspect or mutate it, or return a replacement `Request`/
5
+ * `Response`. Structurally a subset of the underlying ky hook, but typed only
6
+ * on the standard `Request`/`Response` so the public API isn't welded to ky's
7
+ * major version — a ky upgrade that reshapes its own hook types can't become a
8
+ * breaking change here.
9
+ */
10
+ export type HerokuBeforeRequestHook = (context: {
11
+ request: Request;
12
+ }) => Promise<Request | Response | void> | Request | Response | void;
13
+ /**
14
+ * An `afterResponse` hook: runs on the resolved success-path response (the
15
+ * built-in error hook throws on a non-2xx first) and may return a replacement
16
+ * `Response`. Typed only on the standard `Request`/`Response`, for the same
17
+ * decoupling reason as {@link HerokuBeforeRequestHook}.
18
+ */
19
+ export type HerokuAfterResponseHook = (context: {
20
+ request: Request;
21
+ response: Response;
22
+ }) => Promise<Response | void> | Response | void;
23
+ /**
24
+ * Consumer-supplied ky hooks, merged with the client's built-in pipeline.
25
+ *
26
+ * Built-in hooks run first in each phase; the hooks here run after them:
27
+ * - `beforeRequest`: the built-ins attach auth, the `Accept` default, and the
28
+ * `Request-Id` header; your hooks then see (and may override) the fully
29
+ * prepared request before it goes out.
30
+ * - `afterResponse`: the built-ins handle 2FA, throw typed errors on non-2xx,
31
+ * track `Request-Id`s, and surface warnings. Your hooks run *after* that, so
32
+ * they only see the resolved success-path response — a non-2xx response has
33
+ * already been thrown as a typed error and never reaches them.
34
+ *
35
+ * Resolved once at construction: the ky instance is built lazily and cached,
36
+ * so hooks cannot be changed per request.
37
+ */
38
+ export interface HerokuHooks {
39
+ afterResponse?: readonly HerokuAfterResponseHook[];
40
+ beforeRequest?: readonly HerokuBeforeRequestHook[];
41
+ }
42
+ /**
43
+ * A `fetch`-shaped function. Returned by `getDefaultFetch()` on the
44
+ * `@heroku/heroku-fetch/client/environment-defaults.js` subpath: a drop-in
45
+ * `fetch` that, on Node, is already paired with the proxy dispatcher from the
46
+ * same undici copy, so proxy routing works. Pass it anywhere a `fetch` is
47
+ * accepted. See `getDefaultFetch` for why the pairing matters.
48
+ */
49
+ export type FetchLike = (input: Request | string | URL, init?: Parameters<typeof fetch>[1]) => Promise<Response>;
2
50
  /**
3
51
  * A bearer token, or a function resolving one at request time. A provider may
4
52
  * return `undefined` (sync or async) to send the request with no `Authorization`
@@ -7,6 +55,31 @@ export type HerokuService = 'custom' | 'data' | 'particleboard' | 'platform';
7
55
  * `AuthenticationError`.
8
56
  */
9
57
  export type TokenProvider = (() => Promise<string | undefined> | string | undefined) | string;
58
+ /**
59
+ * Structured, success-path metadata about a completed response, surfaced via
60
+ * the `onResponseMetadata` option so consumers can read request correlation and
61
+ * warnings without re-parsing headers. The bare `Response` is still returned
62
+ * from `get`/`post`/etc. unchanged — this is an additive side channel.
63
+ */
64
+ export interface ResponseMetadata {
65
+ /**
66
+ * The `Request-Id`s the server echoed for this response, newest first. The
67
+ * server returns them comma-joined; this is that header split into the
68
+ * individual ids (matching the client's internal correlation tracking).
69
+ * Empty when the response carried no `Request-Id`.
70
+ */
71
+ requestIds: readonly string[];
72
+ /** HTTP status code of the response. */
73
+ status: number;
74
+ /** Final request URL. */
75
+ url: string;
76
+ /**
77
+ * Warnings this response carried (normalized the same way the `warn`
78
+ * callback receives them). Empty when the response carried none. Not deduped
79
+ * against prior responses — reflects what *this* response carried.
80
+ */
81
+ warnings: readonly string[];
82
+ }
10
83
  export interface TwoFactorOptions {
11
84
  /** Callback function to prompt for 2FA code */
12
85
  onChallenge: () => Promise<string> | string;
@@ -41,6 +114,22 @@ export interface HerokuApiClientOptions {
41
114
  defaultAccept?: string;
42
115
  /** Additional custom headers */
43
116
  headers?: Record<string, string>;
117
+ /**
118
+ * Consumer ky hooks merged after the client's built-in hooks. See
119
+ * {@link HerokuHooks} for ordering and the success-path caveat.
120
+ */
121
+ hooks?: HerokuHooks;
122
+ /**
123
+ * Callback invoked on the success path with structured {@link ResponseMetadata}
124
+ * for each completed response — request-ids and warnings without re-parsing
125
+ * headers. Runs only after built-in error handling accepts the response (a
126
+ * non-2xx is thrown as a typed error and never reaches it). Omitted → no-op.
127
+ *
128
+ * Fires once per HTTP response, not once per logical operation: a caller that
129
+ * makes several requests (pagination, polling) receives several callbacks,
130
+ * with no built-in way to correlate them beyond the per-response metadata.
131
+ */
132
+ onResponseMetadata?: (metadata: ResponseMetadata) => void;
44
133
  /** Service region (e.g., 'eu', 'us') */
45
134
  region?: string;
46
135
  /** Heroku service type (platform, data, particleboard, custom) */
@@ -51,6 +140,14 @@ export interface HerokuApiClientOptions {
51
140
  token?: TokenProvider;
52
141
  /** Two-factor authentication configuration */
53
142
  twoFactor?: TwoFactorOptions;
143
+ /**
144
+ * Callback for surfacing user-facing warnings the client raises — currently
145
+ * server `x-heroku-warning` / `warning-message` response headers. Called once
146
+ * per unique (normalized) warning over the client's lifetime. Keeps the
147
+ * client environment-agnostic: a host can log or display warnings however it
148
+ * likes. Omitted → warnings are dropped.
149
+ */
150
+ warn?: (message: string) => void;
54
151
  }
55
152
  export interface RequestOptions {
56
153
  /** Additional headers for this request */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heroku/heroku-fetch",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "A JavaScript/TypeScript API client for Heroku APIs",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -52,7 +52,7 @@
52
52
  "dependencies": {
53
53
  "@heroku/js-blanket": "^1.2.0",
54
54
  "debug": "^4.3.4",
55
- "ky": "^2.0.2",
55
+ "ky": "^2.2.0",
56
56
  "undici": "^8.11.2"
57
57
  },
58
58
  "optionalDependencies": {