@paxosglobal/sdk 0.0.0-stage → 0.1.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.
Files changed (212) hide show
  1. package/AGENTS.md +268 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +191 -0
  4. package/README.md +445 -2
  5. package/dist/auth.d.ts +60 -0
  6. package/dist/auth.js +248 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +353 -0
  9. package/dist/client.js +967 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/constants.d.ts +16 -0
  12. package/dist/constants.js +17 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/decimal-fields.d.ts +16 -0
  15. package/dist/decimal-fields.js +570 -0
  16. package/dist/decimal-fields.js.map +1 -0
  17. package/dist/decimal.d.ts +25 -0
  18. package/dist/decimal.js +93 -0
  19. package/dist/decimal.js.map +1 -0
  20. package/dist/decode.d.ts +34 -0
  21. package/dist/decode.js +118 -0
  22. package/dist/decode.js.map +1 -0
  23. package/dist/enums.d.ts +1080 -0
  24. package/dist/enums.js +1031 -0
  25. package/dist/enums.js.map +1 -0
  26. package/dist/errors.d.ts +142 -0
  27. package/dist/errors.js +261 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/generated-types.d.ts +13629 -0
  30. package/dist/generated-types.js +3 -0
  31. package/dist/generated-types.js.map +1 -0
  32. package/dist/index.d.ts +32 -0
  33. package/dist/index.js +31 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/models.d.ts +299 -0
  36. package/dist/models.js +3 -0
  37. package/dist/models.js.map +1 -0
  38. package/dist/paxos-client.d.ts +107 -0
  39. package/dist/paxos-client.js +157 -0
  40. package/dist/paxos-client.js.map +1 -0
  41. package/dist/query-keys.d.ts +1 -0
  42. package/dist/query-keys.js +31 -0
  43. package/dist/query-keys.js.map +1 -0
  44. package/dist/response-defaults.d.ts +2 -0
  45. package/dist/response-defaults.js +109 -0
  46. package/dist/response-defaults.js.map +1 -0
  47. package/dist/services/account-members.d.ts +32 -0
  48. package/dist/services/account-members.js +46 -0
  49. package/dist/services/account-members.js.map +1 -0
  50. package/dist/services/accounts.d.ts +74 -0
  51. package/dist/services/accounts.js +71 -0
  52. package/dist/services/accounts.js.map +1 -0
  53. package/dist/services/address-verification.d.ts +72 -0
  54. package/dist/services/address-verification.js +64 -0
  55. package/dist/services/address-verification.js.map +1 -0
  56. package/dist/services/api-credentials.d.ts +44 -0
  57. package/dist/services/api-credentials.js +42 -0
  58. package/dist/services/api-credentials.js.map +1 -0
  59. package/dist/services/claims.d.ts +68 -0
  60. package/dist/services/claims.js +67 -0
  61. package/dist/services/claims.js.map +1 -0
  62. package/dist/services/cross-chain-transfer.d.ts +71 -0
  63. package/dist/services/cross-chain-transfer.js +68 -0
  64. package/dist/services/cross-chain-transfer.js.map +1 -0
  65. package/dist/services/crypto-deposits.d.ts +30 -0
  66. package/dist/services/crypto-deposits.js +39 -0
  67. package/dist/services/crypto-deposits.js.map +1 -0
  68. package/dist/services/crypto-withdrawals.d.ts +60 -0
  69. package/dist/services/crypto-withdrawals.js +42 -0
  70. package/dist/services/crypto-withdrawals.js.map +1 -0
  71. package/dist/services/deposit-addresses.d.ts +54 -0
  72. package/dist/services/deposit-addresses.js +36 -0
  73. package/dist/services/deposit-addresses.js.map +1 -0
  74. package/dist/services/events.d.ts +53 -0
  75. package/dist/services/events.js +39 -0
  76. package/dist/services/events.js.map +1 -0
  77. package/dist/services/exchange.d.ts +52 -0
  78. package/dist/services/exchange.js +30 -0
  79. package/dist/services/exchange.js.map +1 -0
  80. package/dist/services/fees.d.ts +15 -0
  81. package/dist/services/fees.js +24 -0
  82. package/dist/services/fees.js.map +1 -0
  83. package/dist/services/fiat-transfers.d.ts +133 -0
  84. package/dist/services/fiat-transfers.js +127 -0
  85. package/dist/services/fiat-transfers.js.map +1 -0
  86. package/dist/services/identity-controls.d.ts +43 -0
  87. package/dist/services/identity-controls.js +42 -0
  88. package/dist/services/identity-controls.js.map +1 -0
  89. package/dist/services/identity-documents.d.ts +45 -0
  90. package/dist/services/identity-documents.js +50 -0
  91. package/dist/services/identity-documents.js.map +1 -0
  92. package/dist/services/identity.d.ts +122 -0
  93. package/dist/services/identity.js +66 -0
  94. package/dist/services/identity.js.map +1 -0
  95. package/dist/services/index.d.ts +89 -0
  96. package/dist/services/index.js +55 -0
  97. package/dist/services/index.js.map +1 -0
  98. package/dist/services/institution-members.d.ts +30 -0
  99. package/dist/services/institution-members.js +44 -0
  100. package/dist/services/institution-members.js.map +1 -0
  101. package/dist/services/internal-transfers.d.ts +15 -0
  102. package/dist/services/internal-transfers.js +26 -0
  103. package/dist/services/internal-transfers.js.map +1 -0
  104. package/dist/services/issuer-quotes.d.ts +72 -0
  105. package/dist/services/issuer-quotes.js +66 -0
  106. package/dist/services/issuer-quotes.js.map +1 -0
  107. package/dist/services/limits.d.ts +20 -0
  108. package/dist/services/limits.js +23 -0
  109. package/dist/services/limits.js.map +1 -0
  110. package/dist/services/market-data.d.ts +15 -0
  111. package/dist/services/market-data.js +23 -0
  112. package/dist/services/market-data.js.map +1 -0
  113. package/dist/services/monitoring-addresses.d.ts +64 -0
  114. package/dist/services/monitoring-addresses.js +68 -0
  115. package/dist/services/monitoring-addresses.js.map +1 -0
  116. package/dist/services/orchestration-rules.d.ts +53 -0
  117. package/dist/services/orchestration-rules.js +47 -0
  118. package/dist/services/orchestration-rules.js.map +1 -0
  119. package/dist/services/orchestrations.d.ts +70 -0
  120. package/dist/services/orchestrations.js +45 -0
  121. package/dist/services/orchestrations.js.map +1 -0
  122. package/dist/services/orders.d.ts +86 -0
  123. package/dist/services/orders.js +67 -0
  124. package/dist/services/orders.js.map +1 -0
  125. package/dist/services/paxos-transfers.d.ts +24 -0
  126. package/dist/services/paxos-transfers.js +35 -0
  127. package/dist/services/paxos-transfers.js.map +1 -0
  128. package/dist/services/payments.d.ts +46 -0
  129. package/dist/services/payments.js +35 -0
  130. package/dist/services/payments.js.map +1 -0
  131. package/dist/services/payout-groups.d.ts +59 -0
  132. package/dist/services/payout-groups.js +59 -0
  133. package/dist/services/payout-groups.js.map +1 -0
  134. package/dist/services/pricing.d.ts +67 -0
  135. package/dist/services/pricing.js +42 -0
  136. package/dist/services/pricing.js.map +1 -0
  137. package/dist/services/profiles.d.ts +106 -0
  138. package/dist/services/profiles.js +84 -0
  139. package/dist/services/profiles.js.map +1 -0
  140. package/dist/services/quote-executions.d.ts +51 -0
  141. package/dist/services/quote-executions.js +41 -0
  142. package/dist/services/quote-executions.js.map +1 -0
  143. package/dist/services/quotes.d.ts +44 -0
  144. package/dist/services/quotes.js +48 -0
  145. package/dist/services/quotes.js.map +1 -0
  146. package/dist/services/reward-addresses.d.ts +80 -0
  147. package/dist/services/reward-addresses.js +79 -0
  148. package/dist/services/reward-addresses.js.map +1 -0
  149. package/dist/services/rewards-statements.d.ts +35 -0
  150. package/dist/services/rewards-statements.js +32 -0
  151. package/dist/services/rewards-statements.js.map +1 -0
  152. package/dist/services/rewards.d.ts +34 -0
  153. package/dist/services/rewards.js +37 -0
  154. package/dist/services/rewards.js.map +1 -0
  155. package/dist/services/sandbox-deposits.d.ts +15 -0
  156. package/dist/services/sandbox-deposits.js +22 -0
  157. package/dist/services/sandbox-deposits.js.map +1 -0
  158. package/dist/services/sandbox-fiat-transfers.d.ts +15 -0
  159. package/dist/services/sandbox-fiat-transfers.js +24 -0
  160. package/dist/services/sandbox-fiat-transfers.js.map +1 -0
  161. package/dist/services/sandbox-identity.d.ts +39 -0
  162. package/dist/services/sandbox-identity.js +60 -0
  163. package/dist/services/sandbox-identity.js.map +1 -0
  164. package/dist/services/settlement.d.ts +76 -0
  165. package/dist/services/settlement.js +79 -0
  166. package/dist/services/settlement.js.map +1 -0
  167. package/dist/services/stablecoin-conversion.d.ts +70 -0
  168. package/dist/services/stablecoin-conversion.js +65 -0
  169. package/dist/services/stablecoin-conversion.js.map +1 -0
  170. package/dist/services/statements.d.ts +44 -0
  171. package/dist/services/statements.js +35 -0
  172. package/dist/services/statements.js.map +1 -0
  173. package/dist/services/tax-documentation.d.ts +21 -0
  174. package/dist/services/tax-documentation.js +33 -0
  175. package/dist/services/tax-documentation.js.map +1 -0
  176. package/dist/services/tax-forms.d.ts +45 -0
  177. package/dist/services/tax-forms.js +38 -0
  178. package/dist/services/tax-forms.js.map +1 -0
  179. package/dist/services/transfers.d.ts +96 -0
  180. package/dist/services/transfers.js +37 -0
  181. package/dist/services/transfers.js.map +1 -0
  182. package/dist/services/travel-rule.d.ts +32 -0
  183. package/dist/services/travel-rule.js +30 -0
  184. package/dist/services/travel-rule.js.map +1 -0
  185. package/dist/services/user-audit-logs.d.ts +45 -0
  186. package/dist/services/user-audit-logs.js +27 -0
  187. package/dist/services/user-audit-logs.js.map +1 -0
  188. package/dist/services/webhooks.d.ts +58 -0
  189. package/dist/services/webhooks.js +42 -0
  190. package/dist/services/webhooks.js.map +1 -0
  191. package/dist/signing.d.ts +33 -0
  192. package/dist/signing.js +186 -0
  193. package/dist/signing.js.map +1 -0
  194. package/dist/testing/fixtures.d.ts +40 -0
  195. package/dist/testing/fixtures.js +131 -0
  196. package/dist/testing/fixtures.js.map +1 -0
  197. package/dist/testing/index.d.ts +28 -0
  198. package/dist/testing/index.js +28 -0
  199. package/dist/testing/index.js.map +1 -0
  200. package/dist/testing/mock-server.d.ts +121 -0
  201. package/dist/testing/mock-server.js +276 -0
  202. package/dist/testing/mock-server.js.map +1 -0
  203. package/dist/timeouts.d.ts +13 -0
  204. package/dist/timeouts.js +71 -0
  205. package/dist/timeouts.js.map +1 -0
  206. package/dist/types.d.ts +6 -0
  207. package/dist/types.js +7 -0
  208. package/dist/types.js.map +1 -0
  209. package/dist/version.d.ts +1 -0
  210. package/dist/version.js +2 -0
  211. package/dist/version.js.map +1 -0
  212. package/package.json +67 -4
package/dist/client.js ADDED
@@ -0,0 +1,967 @@
1
+ /**
2
+ * HttpClient — Layer 1 HTTP transport for the Paxos TypeScript SDK.
3
+ *
4
+ * Handles OAuth2 authentication, HTTP transport, retry logic, pagination,
5
+ * and telemetry header injection. All API service classes delegate their
6
+ * HTTP calls to the methods on this class.
7
+ *
8
+ * Users should import PaxosClient from paxos-client.ts (which extends
9
+ * this class and adds all service accessors).
10
+ */
11
+ import { AUTH_SCHEME_BEARER, CONTENT_TYPE_JSON, DEFAULT_CALL_TIMEOUT_MS, ERROR_TITLE_REQUEST_TIMED_OUT, HEADER_ACCEPT, HEADER_AUTHORIZATION, HEADER_CONTENT_TYPE, HEADER_REQUEST_ID, HEADER_SDK_LANGUAGE, HEADER_SDK_VERSION, HEADER_SIGNATURE, } from "./constants.js";
12
+ import { budget, cancellable, timeoutError, validateTimeout } from "./timeouts.js";
13
+ import { TokenManager } from "./auth.js";
14
+ import { NESTED_SCHEMA_REFS, REQUEST_MAP_FIELDS_BY_SCHEMA } from "./decimal-fields.js";
15
+ import { decodeResponse } from "./decode.js";
16
+ import { convertRequestDecimals } from "./decimal.js";
17
+ import { parseError, PaxosApiError, PaxosError, describeNetworkError, PaxosNetworkError, PaxosTimeoutError, PaxosUnauthorizedError, } from "./errors.js";
18
+ import { parseSigningKey, signRequestWithKey } from "./signing.js";
19
+ import { QUERY_WIRE_NAMES } from "./query-keys.js";
20
+ import { SDK_VERSION } from "./version.js";
21
+ const SDK_LANGUAGE = "typescript";
22
+ const PRODUCTION_BASE_URL = "https://api.paxos.com/v2";
23
+ const SANDBOX_BASE_URL = "https://api.sandbox.paxos.com/v2";
24
+ const PRODUCTION_OAUTH_URL = "https://oauth.paxos.com/oauth2/token";
25
+ const SANDBOX_OAUTH_URL = "https://oauth.sandbox.paxos.com/oauth2/token";
26
+ const JSON_CONTENT_TYPE = /^application\/([\w.+-]+\+)?json\b/;
27
+ const MAX_RETRIES = 3;
28
+ const INITIAL_BACKOFF_MS = 500;
29
+ const MAX_BACKOFF_MS = 30_000;
30
+ const SAFE_RETRY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
31
+ const WRITE_METHODS = new Set(["POST", "PUT", "PATCH"]);
32
+ const ERROR_TITLE_PAGINATION_DEADLINE = "Pagination deadline exceeded";
33
+ /** Status codes that warrant a retry with exponential backoff. */
34
+ const RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);
35
+ function attachRaw(value, read) {
36
+ if (typeof value !== "object" || value === null || Array.isArray(value) || Object.hasOwn(value, "rawJson"))
37
+ return;
38
+ let cached;
39
+ let loaded = false;
40
+ Object.defineProperty(value, "rawJson", {
41
+ enumerable: false,
42
+ configurable: true,
43
+ get: () => {
44
+ if (!loaded) {
45
+ cached = read();
46
+ loaded = true;
47
+ }
48
+ return cached;
49
+ },
50
+ });
51
+ }
52
+ /**
53
+ * Result of an auto-paginating list call. It is an `AsyncGenerator` of items,
54
+ * so `for await (const item of ...)` works unchanged, and `pages()` exposes
55
+ * the same traversal one {@link Page} at a time.
56
+ *
57
+ * Pages are fetched lazily, only as the iteration advances. Item iteration and
58
+ * `pages()` are mutually exclusive: calling `pages()` once item iteration has
59
+ * started, or advancing items once `pages()` has been called, throws a
60
+ * `RangeError`. Calling `pages()` again after partial or full consumption is
61
+ * allowed and continues from the next unfetched page. An empty page is yielded
62
+ * by `pages()` once, with its own metadata and the cursor as received unless it repeats the cursor just sent, and then iteration stops. An error is
63
+ * terminal: after a fetch fails, no further pages are fetched and later pulls end,
64
+ * in either view and without the mixing error. An invalid `maxItems` or `maxDuration`
65
+ * fails the first pull once, after which both views are done with no requests made.
66
+ * `return()` and disposal stop further fetching.
67
+ */
68
+ export class PageIterator {
69
+ itemStream;
70
+ pageGen;
71
+ /** @internal */
72
+ constructor(itemStream, pageGen) {
73
+ this.itemStream = itemStream;
74
+ this.pageGen = pageGen;
75
+ }
76
+ mode;
77
+ ended = false;
78
+ async next() {
79
+ if (this.ended)
80
+ return { done: true, value: undefined };
81
+ if (this.mode === "pages")
82
+ throw new RangeError("cannot iterate items after pages() has been called");
83
+ this.mode = "items";
84
+ try {
85
+ return await this.itemStream.next();
86
+ }
87
+ catch (err) {
88
+ this.ended = true;
89
+ throw err;
90
+ }
91
+ }
92
+ async return(value) {
93
+ this.ended = true;
94
+ const result = await this.itemStream.return(value);
95
+ await this.pageGen.return(undefined);
96
+ return result;
97
+ }
98
+ async throw(err) {
99
+ this.ended = true;
100
+ try {
101
+ return await this.itemStream.throw(err);
102
+ }
103
+ finally {
104
+ await this.pageGen.return(undefined);
105
+ }
106
+ }
107
+ [Symbol.asyncIterator]() {
108
+ return this;
109
+ }
110
+ async [Symbol.asyncDispose]() {
111
+ await this.return(undefined);
112
+ }
113
+ /** Iterate whole pages, each with its own `nextCursor` and `metadata`. */
114
+ pages() {
115
+ if (!this.ended) {
116
+ if (this.mode === "items")
117
+ throw new RangeError("cannot call pages() after item iteration has started");
118
+ this.mode = "pages";
119
+ }
120
+ const source = this.pageGen;
121
+ const finish = () => {
122
+ this.ended = true;
123
+ };
124
+ const isEnded = () => this.ended;
125
+ return (async function* () {
126
+ while (!isEnded()) {
127
+ let result;
128
+ try {
129
+ result = await source.next();
130
+ }
131
+ catch (err) {
132
+ finish();
133
+ throw err;
134
+ }
135
+ if (result.done)
136
+ return;
137
+ yield result.value;
138
+ }
139
+ })();
140
+ }
141
+ }
142
+ const CLIENT_OPTION_KEYS = {
143
+ clientId: true,
144
+ clientSecret: true,
145
+ sandbox: true,
146
+ baseUrl: true,
147
+ scopes: true,
148
+ maxRetries: true,
149
+ callTimeout: true,
150
+ callAttemptTimeout: true,
151
+ fetch: true,
152
+ beforeRequest: true,
153
+ afterResponse: true,
154
+ tokenUrl: true,
155
+ signingKey: true,
156
+ keyId: true,
157
+ logger: true,
158
+ };
159
+ /**
160
+ * HttpClient is the Layer 1 HTTP transport.
161
+ *
162
+ * Use {@link PaxosClient} (from paxos-client.ts) instead of this class
163
+ * directly — it extends HttpClient and adds all service accessors.
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * const client = new PaxosClient({
168
+ * clientId: process.env.PAXOS_CLIENT_ID!,
169
+ * clientSecret: process.env.PAXOS_CLIENT_SECRET!,
170
+ * scopes: [Scope.TRANSFER_READ_TRANSFER],
171
+ * sandbox: true,
172
+ * });
173
+ *
174
+ * const transfer = await client.transfers.getTransfer("txn_123");
175
+ * ```
176
+ */
177
+ export class HttpClient {
178
+ baseUrl;
179
+ isSandbox;
180
+ #tokenManager;
181
+ requestFailures = new WeakSet();
182
+ tokenFailures = new WeakSet();
183
+ maxRetries;
184
+ #rejectedTokens = new WeakMap();
185
+ callTimeout;
186
+ fetchFn;
187
+ attemptTimeout;
188
+ beforeRequestHook;
189
+ afterResponseHook;
190
+ #signingKey;
191
+ signingKeyId;
192
+ logger;
193
+ constructor(options) {
194
+ for (const key of Object.keys(options)) {
195
+ if (!Object.hasOwn(CLIENT_OPTION_KEYS, key)) {
196
+ throw new Error(`Unknown PaxosClient option "${key}". Valid options: ${Object.keys(CLIENT_OPTION_KEYS).join(", ")}`);
197
+ }
198
+ }
199
+ if (!options.clientId) {
200
+ throw new Error("clientId is required");
201
+ }
202
+ if (!options.clientSecret) {
203
+ throw new Error("clientSecret is required");
204
+ }
205
+ if (!Array.isArray(options.scopes) ||
206
+ !options.scopes.length ||
207
+ Array.from(options.scopes).some((s) => typeof s !== "string" || !s.trim())) {
208
+ throw new Error("scopes are required: pass at least one OAuth scope, e.g. scopes: [Scope.TRANSFER_READ_TRANSFER]");
209
+ }
210
+ if (options.sandbox && (options.baseUrl || options.tokenUrl)) {
211
+ throw new Error("sandbox cannot be combined with a custom base URL or token URL; set both URLs explicitly with sandbox disabled");
212
+ }
213
+ if (!options.baseUrl !== !options.tokenUrl) {
214
+ throw new Error("base URL and token URL must be set together; pass both, or neither to use the production or sandbox defaults");
215
+ }
216
+ if (options.baseUrl) {
217
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
218
+ }
219
+ else if (options.sandbox) {
220
+ this.baseUrl = SANDBOX_BASE_URL;
221
+ }
222
+ else {
223
+ this.baseUrl = PRODUCTION_BASE_URL;
224
+ }
225
+ this.maxRetries = resolveMaxRetries(options.maxRetries, MAX_RETRIES);
226
+ this.isSandbox = options.sandbox ?? false;
227
+ this.callTimeout = resolveCallTimeout(options, DEFAULT_CALL_TIMEOUT_MS);
228
+ validateTimeout(options.callAttemptTimeout, "callAttemptTimeout");
229
+ this.attemptTimeout = options.callAttemptTimeout ?? null;
230
+ this.beforeRequestHook = options.beforeRequest;
231
+ this.afterResponseHook = options.afterResponse;
232
+ if (options.logger) {
233
+ this.logger = options.logger;
234
+ }
235
+ else if (typeof process !== "undefined" && process.env?.PAXOS_LOG_LEVEL?.toLowerCase() === "debug") {
236
+ this.logger = (_level, message) => console.error(message);
237
+ }
238
+ const custom = options.fetch;
239
+ this.fetchFn = custom ? (input, init) => custom(input, init) : (input, init) => globalThis.fetch(input, init);
240
+ const tokenUrl = options.tokenUrl
241
+ ? options.tokenUrl.replace(/\/$/, "")
242
+ : options.sandbox
243
+ ? SANDBOX_OAUTH_URL
244
+ : PRODUCTION_OAUTH_URL;
245
+ this.#tokenManager = new TokenManager(options.clientId, options.clientSecret, tokenUrl, options.scopes, this.attemptTimeout, this.fetchFn);
246
+ const hasKey = !!options.signingKey;
247
+ const hasKeyId = !!options.keyId;
248
+ if (hasKey !== hasKeyId) {
249
+ throw new Error("both signingKey and keyId must be provided for request signing");
250
+ }
251
+ if (hasKey && hasKeyId) {
252
+ this.#signingKey = parseSigningKey(options.signingKey);
253
+ this.signingKeyId = options.keyId;
254
+ }
255
+ }
256
+ /**
257
+ * Perform a GET request and return the parsed response body.
258
+ * Query parameters are serialized from `params`, omitting undefined/null values.
259
+ * `op.responseSchema` names the response's schema in the spec, so decimal fields are
260
+ * converted for that schema only (see `decodeResponse`).
261
+ */
262
+ async get(path, params, opts, op) {
263
+ const { data } = await this.request("GET", path, { params: params }, opts, undefined, op?.responseSchema);
264
+ return data;
265
+ }
266
+ /**
267
+ * Perform a POST request with a JSON body and return the parsed response body.
268
+ */
269
+ async post(path, body, opts, op) {
270
+ const { data } = await this.request("POST", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
271
+ return data;
272
+ }
273
+ /**
274
+ * Perform a PUT request with a JSON body and return the parsed response body.
275
+ */
276
+ async put(path, body, opts, op) {
277
+ const { data } = await this.request("PUT", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
278
+ return data;
279
+ }
280
+ /**
281
+ * Perform a PATCH request with a JSON body and return the parsed response body.
282
+ */
283
+ async patch(path, body, opts, op) {
284
+ const { data } = await this.request("PATCH", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
285
+ return data;
286
+ }
287
+ /**
288
+ * Perform a DELETE request and return the parsed response body (if any).
289
+ * Query parameters are serialized from `params`, omitting undefined/null values.
290
+ */
291
+ async delete(path, params, opts, op) {
292
+ const { data } = await this.request("DELETE", path, { params: params }, opts, undefined, op?.responseSchema);
293
+ return data;
294
+ }
295
+ /**
296
+ * Perform a GET request and return both the parsed body and response metadata.
297
+ */
298
+ async getWithMetadata(path, params, opts, op) {
299
+ return this.request("GET", path, { params: params }, opts, undefined, op?.responseSchema);
300
+ }
301
+ /**
302
+ * Perform a POST request and return both the parsed body and response metadata.
303
+ */
304
+ async postWithMetadata(path, body, opts, op) {
305
+ return this.request("POST", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
306
+ }
307
+ /**
308
+ * Perform a PUT request and return both the parsed body and response metadata.
309
+ */
310
+ async putWithMetadata(path, body, opts, op) {
311
+ return this.request("PUT", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
312
+ }
313
+ /**
314
+ * Perform a PATCH request and return both the parsed body and response metadata.
315
+ */
316
+ async patchWithMetadata(path, body, opts, op) {
317
+ return this.request("PATCH", path, { body, bodySchemaKey: op?.requestSchema, replayProtected: op?.replayProtected }, opts, undefined, op?.responseSchema);
318
+ }
319
+ /**
320
+ * Perform a DELETE request and return both the parsed body and response metadata.
321
+ * Query parameters are serialized from `params`, omitting undefined/null values.
322
+ */
323
+ async deleteWithMetadata(path, params, opts, op) {
324
+ return this.request("DELETE", path, { params: params }, opts, undefined, op?.responseSchema);
325
+ }
326
+ /**
327
+ * Auto-paginating iterator over a list endpoint.
328
+ *
329
+ * Returns a {@link PageIterator}: iterate it directly to receive individual
330
+ * items, or call `pages()` to receive whole {@link Page}s. Subsequent pages
331
+ * are fetched lazily via the next_page_cursor field.
332
+ *
333
+ * @param path - The API endpoint path.
334
+ * @param itemsField - The JSON field name containing the items array (e.g. "payments").
335
+ * @param params - Optional query parameters.
336
+ * @param opts - Optional per-request configuration. `opts.maxItems` caps the
337
+ * total number of items yielded; `opts.maxDuration` bounds the total
338
+ * wall-clock time across all page fetches and throws {@link PaxosTimeoutError}
339
+ * if exceeded.
340
+ * @param op - `op.responseSchema` is the list response envelope's schema name
341
+ * in the spec, used to decimal-convert the page (and, via its nested-schema
342
+ * refs, the items within it) for that schema only.
343
+ *
344
+ * @example
345
+ * ```typescript
346
+ * for await (const payment of client.paginate<Payment>("/payment/payments", "payments", { profile_id: "p_123" })) {
347
+ * console.log(payment.id);
348
+ * }
349
+ * ```
350
+ *
351
+ * Termination is guaranteed even if the server misbehaves: iteration stops
352
+ * on an absent cursor, an empty page (even if a cursor was still returned),
353
+ * or a cursor identical to the one just requested.
354
+ */
355
+ paginate(path, itemsField, params, opts, op) {
356
+ let deadline;
357
+ const maxItems = opts?.maxItems;
358
+ const pageStream = async function* () {
359
+ if (maxItems !== undefined && !(Number.isInteger(maxItems) && maxItems > 0))
360
+ throw new RangeError("maxItems must be positive");
361
+ validateTimeout(opts?.maxDuration, "maxDuration");
362
+ deadline = opts?.maxDuration != null ? monotonicNow() + opts.maxDuration : undefined;
363
+ const initial = params?.["page_cursor"];
364
+ let cursor = typeof initial === "string" ? initial : undefined;
365
+ let itemCount = 0;
366
+ while (true) {
367
+ if (deadline !== undefined && monotonicNow() >= deadline) {
368
+ throw new PaxosTimeoutError({
369
+ title: ERROR_TITLE_PAGINATION_DEADLINE,
370
+ detail: `Iteration of ${path} did not complete within ${opts.maxDuration}ms (maxDuration)`,
371
+ });
372
+ }
373
+ const queryParams = { ...params };
374
+ delete queryParams["page_cursor"];
375
+ if (cursor) {
376
+ queryParams["page_cursor"] = cursor;
377
+ }
378
+ const { data: response, response: terminal } = await this.request("GET", path, { params: queryParams }, opts, deadline, op?.responseSchema);
379
+ if (typeof response !== "object" || response === null) {
380
+ throw new PaxosApiError({
381
+ status: terminal.statusCode,
382
+ title: "Malformed response",
383
+ detail: "failed to decode response body",
384
+ requestId: terminal.requestId,
385
+ }, { cause: new Error("decode error (unexpected list shape)") });
386
+ }
387
+ const items = response[itemsField];
388
+ if ((items !== undefined && items !== null && !Array.isArray(items)) ||
389
+ (Array.isArray(items) &&
390
+ items.some((item) => typeof item !== "object" || item === null || Array.isArray(item)))) {
391
+ throw new PaxosApiError({
392
+ status: terminal.statusCode,
393
+ title: "Malformed response",
394
+ detail: "failed to decode response body",
395
+ requestId: terminal.requestId,
396
+ }, { cause: new Error("decode error (unexpected list shape)") });
397
+ }
398
+ let pageItems = Array.isArray(items) ? items : [];
399
+ const emptyPage = pageItems.length === 0;
400
+ let capped = false;
401
+ let trimmed = false;
402
+ if (maxItems !== undefined && itemCount + pageItems.length >= maxItems) {
403
+ trimmed = itemCount + pageItems.length > maxItems;
404
+ pageItems = pageItems.slice(0, maxItems - itemCount);
405
+ capped = true;
406
+ }
407
+ itemCount += pageItems.length;
408
+ let pageBody;
409
+ pageItems.forEach((item, index) => attachRaw(item, () => {
410
+ pageBody ??= JSON.parse(terminal.rawBody);
411
+ return pageBody[itemsField][index];
412
+ }));
413
+ const received = response["nextPageCursor"] ?? response["next_page_cursor"];
414
+ const repeated = !!received && received === cursor;
415
+ const last = !received || emptyPage || repeated || capped;
416
+ yield {
417
+ items: pageItems,
418
+ nextCursor: trimmed || repeated ? undefined : received || undefined,
419
+ metadata: { ...terminal },
420
+ };
421
+ if (last)
422
+ return;
423
+ cursor = received;
424
+ }
425
+ }.call(this);
426
+ async function* itemStream() {
427
+ for await (const page of pageStream) {
428
+ for (const item of page.items) {
429
+ opts?.signal?.throwIfAborted();
430
+ if (deadline !== undefined && monotonicNow() >= deadline)
431
+ throw new PaxosTimeoutError({
432
+ title: ERROR_TITLE_PAGINATION_DEADLINE,
433
+ detail: "maxDuration exceeded between items",
434
+ });
435
+ yield item;
436
+ }
437
+ }
438
+ }
439
+ return new PageIterator(itemStream(), pageStream);
440
+ }
441
+ /** Fresh HTTP-attempt cap, clipped to the remaining call and pagination deadlines. */
442
+ effectiveRequestTimeout(opts, paginationDeadline, callDeadline) {
443
+ const attempt = opts?.callAttemptTimeout !== undefined ? opts.callAttemptTimeout : this.attemptTimeout;
444
+ const deadlines = [paginationDeadline, callDeadline].filter((d) => d !== undefined);
445
+ return Math.max(0, Math.min(attempt ?? Infinity, ...deadlines.map((d) => d - monotonicNow())));
446
+ }
447
+ /** Log a debug message if the logger is configured. */
448
+ logDebug(message, data) {
449
+ if (this.logger) {
450
+ this.logger("debug", message, data);
451
+ }
452
+ }
453
+ /**
454
+ * Core HTTP execution method used by all service classes.
455
+ *
456
+ * Handles:
457
+ * - Bearer token injection
458
+ * - Telemetry headers
459
+ * - 401 token refresh (single retry)
460
+ * - Exponential backoff on 429/5xx
461
+ * - RFC 7807 error parsing
462
+ */
463
+ async request(method, path, options, reqOpts,
464
+ /**
465
+ * Internal: set only by `paginate()`'s per-page call, so that this
466
+ * request's own retries and backoff sleeps (not just a single HTTP
467
+ * attempt) stay inside the `maxDuration` budget instead of silently
468
+ * exceeding it.
469
+ */
470
+ deadline, schemaKey) {
471
+ resolveMaxRetries(reqOpts?.maxRetries, this.maxRetries);
472
+ const callTimeout = resolveCallTimeout(reqOpts ?? {}, this.callTimeout);
473
+ validateTimeout(reqOpts?.callAttemptTimeout, "callAttemptTimeout");
474
+ const extraHeaders = reqOpts?.extraHeaders ? { ...reqOpts.extraHeaders } : undefined;
475
+ for (const name of Object.keys(extraHeaders ?? {})) {
476
+ if (SDK_OWNED_HEADERS.includes(name.toLowerCase())) {
477
+ throw new RangeError(`extraHeaders must not set the SDK-owned header ${name}`);
478
+ }
479
+ }
480
+ const remaining = Math.min(callTimeout ?? Infinity, deadline === undefined ? Infinity : deadline - monotonicNow());
481
+ if (remaining <= 0)
482
+ throw timeoutError("callTimeout/maxDuration");
483
+ const total = budget(Number.isFinite(remaining) ? remaining : null, reqOpts?.signal);
484
+ let metadata;
485
+ let sentRequestId;
486
+ try {
487
+ try {
488
+ return await cancellable(this.requestWithinBudget(method, path, options, { ...reqOpts, extraHeaders, signal: total.signal }, deadline, schemaKey, (value) => {
489
+ metadata = value;
490
+ }, (id) => {
491
+ sentRequestId = id;
492
+ }), total.signal);
493
+ }
494
+ finally {
495
+ if (metadata && reqOpts?.onResponseMetadata && !total.signal.aborted) {
496
+ await cancellable(Promise.resolve(reqOpts.onResponseMetadata({ ...metadata })), total.signal);
497
+ }
498
+ }
499
+ }
500
+ catch (err) {
501
+ if (sentRequestId &&
502
+ (this.requestFailures.has(Object(err)) || this.tokenFailures.has(Object(err)) || err === total.signal.reason)) {
503
+ if (err instanceof PaxosTimeoutError) {
504
+ throw new PaxosTimeoutError({ title: err.title, detail: err.detail, requestId: sentRequestId }, { cause: err.cause });
505
+ }
506
+ if (err instanceof PaxosNetworkError) {
507
+ throw new PaxosNetworkError(err.detail, { cause: err.cause }, sentRequestId);
508
+ }
509
+ }
510
+ throw err;
511
+ }
512
+ finally {
513
+ total.cleanup();
514
+ }
515
+ }
516
+ async requestWithinBudget(method, path, options, reqOpts, deadline, schemaKey, capture, onSend) {
517
+ reqOpts?.signal?.throwIfAborted();
518
+ options = {
519
+ ...options,
520
+ serializedBody: options.body === undefined
521
+ ? undefined
522
+ : JSON.stringify(omitEmptyCollections(convertRequestDecimals(options.body, options.bodySchemaKey), options.bodySchemaKey)),
523
+ };
524
+ let attempt = 0;
525
+ let refreshedAfterUnauthorized = false;
526
+ let lastError;
527
+ const logPath = path.split("?")[0];
528
+ this.logDebug(`paxos: ${method} ${logPath}`);
529
+ // `callTimeout` budgets this call's entire retry sequence (all attempts plus
530
+ // backoff sleeps combined), not any one attempt: computed once, up
531
+ // front, then composed via min() with the (independent) pagination
532
+ // `deadline` wherever a per-attempt timeout is derived, since either may
533
+ // be the tighter bound.
534
+ const maxRetries = resolveMaxRetries(reqOpts?.maxRetries, this.maxRetries);
535
+ const baseTimeout = resolveCallTimeout(reqOpts ?? {}, this.callTimeout);
536
+ const callDeadline = baseTimeout === null ? Infinity : monotonicNow() + baseTimeout;
537
+ while (attempt <= maxRetries) {
538
+ capture?.();
539
+ if (deadline !== undefined && monotonicNow() >= deadline) {
540
+ throw this.markRequestFailure(new PaxosTimeoutError({
541
+ title: ERROR_TITLE_PAGINATION_DEADLINE,
542
+ detail: `Retry/backoff for ${method} ${path} exceeded the remaining maxDuration budget`,
543
+ }));
544
+ }
545
+ if (monotonicNow() >= callDeadline) {
546
+ throw this.markRequestFailure(new PaxosTimeoutError({
547
+ title: "Request timeout exceeded",
548
+ detail: `Retry/backoff for ${method} ${path} exceeded the configured timeout (${baseTimeout}ms)`,
549
+ }));
550
+ }
551
+ try {
552
+ return await this.executeRequest(method, path, options, reqOpts, deadline, callDeadline, schemaKey, capture, onSend);
553
+ }
554
+ catch (err) {
555
+ reqOpts?.signal?.throwIfAborted();
556
+ lastError = err instanceof Error ? err : new Error(String(err));
557
+ // Single retry on 401 — refresh token and retry immediately.
558
+ if (this.requestFailures.has(Object(err)) &&
559
+ err instanceof PaxosUnauthorizedError &&
560
+ !refreshedAfterUnauthorized) {
561
+ capture?.();
562
+ refreshedAfterUnauthorized = true;
563
+ this.#tokenManager.invalidate(this.#rejectedTokens.get(Object(err)));
564
+ continue;
565
+ }
566
+ // Retry on 429 / 5xx with exponential backoff.
567
+ const status = err instanceof PaxosApiError ? err.status : undefined;
568
+ if (this.requestFailures.has(Object(err)) &&
569
+ ((status !== undefined &&
570
+ RETRYABLE_STATUS_CODES.has(status) &&
571
+ (status === 429 || options.replayProtected || !WRITE_METHODS.has(method))) ||
572
+ (SAFE_RETRY_METHODS.has(method) &&
573
+ (err instanceof PaxosTimeoutError || err instanceof PaxosNetworkError))) &&
574
+ attempt < maxRetries) {
575
+ capture?.();
576
+ let delay = computeBackoff(attempt);
577
+ if (deadline !== undefined) {
578
+ delay = Math.min(delay, Math.max(deadline - monotonicNow(), 0));
579
+ }
580
+ delay = Math.min(delay, Math.max(callDeadline - monotonicNow(), 0));
581
+ this.logDebug(`paxos: retry attempt ${attempt + 1}/${maxRetries} after ${status ?? err.name} (backoff ${(delay / 1000).toFixed(1)}s)`);
582
+ await sleep(delay, reqOpts?.signal);
583
+ attempt++;
584
+ continue;
585
+ }
586
+ // Non-retryable error — propagate immediately.
587
+ throw err;
588
+ }
589
+ }
590
+ throw lastError ?? new PaxosError(`Request failed: retry loop exhausted after ${maxRetries} attempts`);
591
+ }
592
+ markRequestFailure(error) {
593
+ this.requestFailures.add(error);
594
+ return error;
595
+ }
596
+ async executeRequest(method, path, options, reqOpts, deadline, callDeadline, schemaKey, capture, onSend) {
597
+ const prevToken = this.#tokenManager.peekToken();
598
+ // A new OAuth exchange gets its own attempt cap. Existing refresh waiters
599
+ // retain their independent total budgets and cannot cancel one another.
600
+ const tokenTimeoutMs = deadline !== undefined || callDeadline !== undefined
601
+ ? this.effectiveRequestTimeout(reqOpts, deadline, callDeadline)
602
+ : undefined;
603
+ if (tokenTimeoutMs !== undefined && tokenTimeoutMs <= 0)
604
+ throw timeoutError("callTimeout/maxDuration");
605
+ const token = await withCancellation(this.#tokenManager.getToken(tokenTimeoutMs === Infinity ? null : tokenTimeoutMs, reqOpts?.signal), reqOpts?.signal).catch((error) => {
606
+ this.tokenFailures.add(Object(error));
607
+ throw error;
608
+ });
609
+ if (!prevToken || prevToken !== token) {
610
+ this.logDebug("paxos: refreshing OAuth2 token");
611
+ }
612
+ const requestId = generateRequestId();
613
+ const requestStart = Date.now();
614
+ let headers = new Headers({
615
+ [HEADER_AUTHORIZATION]: `${AUTH_SCHEME_BEARER} ${token}`,
616
+ [HEADER_CONTENT_TYPE]: CONTENT_TYPE_JSON,
617
+ [HEADER_ACCEPT]: CONTENT_TYPE_JSON,
618
+ [HEADER_SDK_LANGUAGE]: SDK_LANGUAGE,
619
+ [HEADER_SDK_VERSION]: SDK_VERSION,
620
+ [HEADER_REQUEST_ID]: requestId,
621
+ });
622
+ // Apply per-request extra headers.
623
+ if (reqOpts?.extraHeaders) {
624
+ for (const [key, value] of Object.entries(reqOpts.extraHeaders)) {
625
+ headers.set(key, value);
626
+ }
627
+ }
628
+ let url = this.baseUrl + path;
629
+ if (options.params) {
630
+ const qs = serializeParams(options.params);
631
+ if (qs) {
632
+ url += (url.includes("?") ? "&" : "?") + qs;
633
+ }
634
+ }
635
+ const hookBody = options.body !== undefined ? options.serializedBody : undefined;
636
+ if (this.beforeRequestHook) {
637
+ try {
638
+ const owned = snapshotOwnedHeaders(headers);
639
+ const hookReq = { method, url, headers, body: hookBody };
640
+ await cancellable(Promise.resolve(this.beforeRequestHook(hookReq)), reqOpts?.signal);
641
+ if (hookReq.method !== method || hookReq.url !== url || hookReq.body !== hookBody) {
642
+ throw new Error("beforeRequest hook must not change method, url or body");
643
+ }
644
+ if (!(hookReq.headers instanceof Headers)) {
645
+ throw new Error("beforeRequest hook must leave req.headers as a Headers instance");
646
+ }
647
+ headers = hookReq.headers;
648
+ const changed = changedOwnedHeader(owned, headers);
649
+ if (changed)
650
+ throw new Error(`beforeRequest hook must not change SDK-owned header ${changed}`);
651
+ }
652
+ catch (error) {
653
+ this.requestFailures.delete(Object(error));
654
+ throw error;
655
+ }
656
+ }
657
+ const effectiveTimeout = this.effectiveRequestTimeout(reqOpts, deadline, callDeadline);
658
+ if (effectiveTimeout <= 0)
659
+ throw timeoutError("callTimeout/maxDuration");
660
+ // Combine user-provided abort signal with the timeout signal.
661
+ // AbortSignal.any() requires Node 20+; we use a manual AbortController
662
+ // to support Node 18+.
663
+ const signal = budget(Number.isFinite(effectiveTimeout) ? effectiveTimeout : null, reqOpts?.signal, "callAttemptTimeout");
664
+ const timeoutSignal = signal.signal;
665
+ try {
666
+ const fetchOptions = {
667
+ method,
668
+ headers,
669
+ redirect: "error",
670
+ signal: signal.signal,
671
+ };
672
+ let bodyBytes;
673
+ if (options.body !== undefined) {
674
+ const bodyStr = options.serializedBody;
675
+ fetchOptions.body = bodyStr;
676
+ bodyBytes = new TextEncoder().encode(bodyStr);
677
+ }
678
+ if (this.#signingKey && this.signingKeyId) {
679
+ this.logDebug(`paxos: signing request with key ${this.signingKeyId}`);
680
+ const target = new URL(url);
681
+ const signingPath = target.pathname + target.search;
682
+ const jws = signRequestWithKey(this.#signingKey, this.signingKeyId, method, signingPath, bodyBytes ?? new Uint8Array(0));
683
+ headers.set(HEADER_SIGNATURE, jws);
684
+ }
685
+ const sentRequestId = headers.get(HEADER_REQUEST_ID) ?? "";
686
+ onSend?.(sentRequestId);
687
+ let response;
688
+ try {
689
+ response = await cancellable(this.fetchFn(url, fetchOptions), signal.signal);
690
+ }
691
+ catch (fetchErr) {
692
+ // Our own timeout (the per-request timeout, or maxDuration expiring)
693
+ // surfaces as a TimeoutError DOMException — distinguish it from an
694
+ // actual network failure so callers can catch it directly instead of
695
+ // pattern-matching on `status === 0`. A caller's own deliberate
696
+ // cancellation via their `signal` surfaces as AbortError instead and
697
+ // is intentionally NOT reclassified here — cancelling is not timing out.
698
+ if (fetchErr instanceof Error && fetchErr.name === "TimeoutError") {
699
+ throw this.markRequestFailure(new PaxosTimeoutError({ title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: String(fetchErr) }, { cause: fetchErr }));
700
+ }
701
+ signal.signal.throwIfAborted();
702
+ throw this.markRequestFailure(new PaxosNetworkError(describeNetworkError(fetchErr, url), { cause: fetchErr }));
703
+ }
704
+ const metadata = {
705
+ requestId: response.headers.get(HEADER_REQUEST_ID) || sentRequestId || undefined,
706
+ statusCode: response.status,
707
+ rawBody: "",
708
+ };
709
+ capture?.(metadata);
710
+ const elapsed = Date.now() - requestStart;
711
+ this.logDebug(`paxos: ${response.status} ${method} ${path.split("?")[0]} (${elapsed}ms) request_id=${metadata.requestId ?? ""}`);
712
+ const readBody = async () => {
713
+ try {
714
+ return await cancellable(response.text(), signal.signal);
715
+ }
716
+ catch (cause) {
717
+ signal.signal.throwIfAborted();
718
+ throw this.markRequestFailure(new PaxosNetworkError("Failed to read response body", { cause }));
719
+ }
720
+ };
721
+ let bufferedText;
722
+ if (this.afterResponseHook) {
723
+ bufferedText = await readBody();
724
+ try {
725
+ await cancellable(Promise.resolve(this.afterResponseHook({ method, url, headers: new Headers(headers), body: hookBody }, { status: response.status, headers: new Headers(response.headers), body: bufferedText })), reqOpts?.signal);
726
+ }
727
+ catch (error) {
728
+ this.requestFailures.delete(Object(error));
729
+ throw error;
730
+ }
731
+ }
732
+ if (response.status < 200 || response.status >= 300) {
733
+ const errorText = bufferedText ?? (await readBody());
734
+ metadata.rawBody = errorText;
735
+ const body = tryParseJson(errorText, response.statusText);
736
+ const error = parseError(response.status, body, metadata.requestId);
737
+ metadata.requestId = error.requestId;
738
+ if (response.status === 401)
739
+ this.#rejectedTokens.set(error, token);
740
+ throw this.markRequestFailure(error);
741
+ }
742
+ // 204 No Content or empty body.
743
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
744
+ if (bufferedText === undefined)
745
+ await cancellable(response.body?.cancel() ?? Promise.resolve(), signal.signal);
746
+ else
747
+ metadata.rawBody = bufferedText;
748
+ return { data: undefined, response: metadata };
749
+ }
750
+ const malformed = (reason) => this.markRequestFailure(new PaxosApiError({
751
+ status: response.status,
752
+ title: "Malformed response",
753
+ detail: "failed to decode response body",
754
+ requestId: metadata.requestId,
755
+ }, { cause: new Error(reason) }));
756
+ const contentType = (response.headers.get(HEADER_CONTENT_TYPE) ?? "").toLowerCase();
757
+ const responseText = bufferedText ?? (await readBody());
758
+ metadata.rawBody = responseText;
759
+ if (responseText === "")
760
+ return { data: undefined, response: metadata };
761
+ if (!JSON_CONTENT_TYPE.test(contentType))
762
+ throw malformed("Unexpected content type");
763
+ let parsed;
764
+ try {
765
+ parsed = JSON.parse(responseText);
766
+ }
767
+ catch (cause) {
768
+ throw malformed(`JSON parse error (${cause instanceof Error ? cause.name : "Error"})`);
769
+ }
770
+ if (schemaKey && (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)))
771
+ throw malformed("decode error (unexpected response shape)");
772
+ let data;
773
+ try {
774
+ data = decodeResponse(parsed, schemaKey);
775
+ }
776
+ catch (cause) {
777
+ throw malformed(`decode error (${cause instanceof Error ? cause.name : "Error"})`);
778
+ }
779
+ attachRaw(data, () => JSON.parse(responseText));
780
+ return { data, response: metadata };
781
+ }
782
+ catch (err) {
783
+ // Fetch may resolve at headers, then reject a body read with AbortError
784
+ // when its timeout fires. Classify using the signal, not the error name.
785
+ if (!reqOpts?.signal?.aborted && timeoutSignal.aborted) {
786
+ throw this.markRequestFailure(new PaxosTimeoutError({ title: ERROR_TITLE_REQUEST_TIMED_OUT, detail: String(err) }, { cause: err }));
787
+ }
788
+ throw err;
789
+ }
790
+ finally {
791
+ signal.cleanup();
792
+ }
793
+ }
794
+ }
795
+ // ---------------------------------------------------------------------------
796
+ // Helpers
797
+ // ---------------------------------------------------------------------------
798
+ const SDK_OWNED_HEADERS = [
799
+ HEADER_AUTHORIZATION,
800
+ HEADER_CONTENT_TYPE,
801
+ HEADER_ACCEPT,
802
+ HEADER_SDK_LANGUAGE,
803
+ HEADER_SDK_VERSION,
804
+ HEADER_SIGNATURE,
805
+ ].map((name) => name.toLowerCase());
806
+ function snapshotOwnedHeaders(headers) {
807
+ return new Map(SDK_OWNED_HEADERS.map((name) => [name, headers.get(name)]));
808
+ }
809
+ function changedOwnedHeader(before, headers) {
810
+ for (const [name, value] of before) {
811
+ if (headers.get(name) !== value)
812
+ return name;
813
+ }
814
+ return undefined;
815
+ }
816
+ function isPlainObject(value) {
817
+ if (typeof value !== "object" || value === null)
818
+ return false;
819
+ const proto = Object.getPrototypeOf(value);
820
+ return proto === Object.prototype || proto === null;
821
+ }
822
+ export function omitEmptyCollections(value, schemaKey, mapFieldsBySchema = REQUEST_MAP_FIELDS_BY_SCHEMA, nestedSchemaRefs = NESTED_SCHEMA_REFS) {
823
+ if (Array.isArray(value)) {
824
+ return value.map((item) => omitEmptyCollections(item, schemaKey, mapFieldsBySchema, nestedSchemaRefs));
825
+ }
826
+ if (isPlainObject(value)) {
827
+ const mapFields = schemaKey ? mapFieldsBySchema[schemaKey] : undefined;
828
+ const nestedRefs = schemaKey ? nestedSchemaRefs[schemaKey] : undefined;
829
+ const out = {};
830
+ for (const [key, child] of Object.entries(value)) {
831
+ const pruned = omitEmptyCollections(child, nestedRefs?.[key], mapFieldsBySchema, nestedSchemaRefs);
832
+ const empty = Array.isArray(pruned)
833
+ ? pruned.length === 0
834
+ : mapFields?.has(key) === true && isPlainObject(pruned) && Object.keys(pruned).length === 0;
835
+ if (!empty)
836
+ out[key] = pruned;
837
+ }
838
+ return out;
839
+ }
840
+ return value;
841
+ }
842
+ /** Generate a UUID v4 for the Paxos-Request-Id header. */
843
+ function generateRequestId() {
844
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
845
+ return crypto.randomUUID();
846
+ }
847
+ // Fallback for environments without crypto.randomUUID.
848
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
849
+ const r = (Math.random() * 16) | 0;
850
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
851
+ return v.toString(16);
852
+ });
853
+ }
854
+ /**
855
+ * Serialize query parameters to a URL-encoded string.
856
+ * Arrays are serialized as repeated parameters: key=a&key=b.
857
+ * undefined/null values are omitted.
858
+ */
859
+ /**
860
+ * Interpolate path parameters into a URL template with encoding.
861
+ */
862
+ export function buildPath(template, params) {
863
+ let path = template;
864
+ for (const [key, value] of Object.entries(params)) {
865
+ if (typeof value !== "string")
866
+ throw new TypeError(`path parameter ${key} must be a string`);
867
+ if (/^[\s\u0085]*$/.test(value))
868
+ throw new RangeError(`path parameter ${key} must not be empty`);
869
+ path = path.replace(`{${key}}`, encodeURIComponent(value));
870
+ }
871
+ return path;
872
+ }
873
+ function serializeParams(params) {
874
+ const parts = [];
875
+ for (const [key, value] of Object.entries(params)) {
876
+ if (value === undefined || value === null) {
877
+ continue;
878
+ }
879
+ const snakeKey = Object.hasOwn(QUERY_WIRE_NAMES, key) ? QUERY_WIRE_NAMES[key] : key;
880
+ if (Array.isArray(value)) {
881
+ for (const item of value) {
882
+ if (item !== undefined && item !== null) {
883
+ parts.push(`${encodeURIComponent(snakeKey)}=${encodeURIComponent(String(item))}`);
884
+ }
885
+ }
886
+ }
887
+ else {
888
+ parts.push(`${encodeURIComponent(snakeKey)}=${encodeURIComponent(String(value))}`);
889
+ }
890
+ }
891
+ return parts.join("&");
892
+ }
893
+ /**
894
+ * Compute exponential backoff with ±25% jitter.
895
+ *
896
+ * Formula: min(initialBackoff * 2^attempt * jitter(0.75, 1.25), maxBackoff)
897
+ */
898
+ function computeBackoff(attempt) {
899
+ const base = INITIAL_BACKOFF_MS * Math.pow(2, attempt);
900
+ const jitter = 0.75 + Math.random() * 0.5; // uniform [0.75, 1.25]
901
+ return Math.min(base * jitter, MAX_BACKOFF_MS);
902
+ }
903
+ /** Invalid JSON must not hide an HTTP error; transport read failures propagate separately. */
904
+ function tryParseJson(text, statusText) {
905
+ try {
906
+ return JSON.parse(text);
907
+ }
908
+ catch {
909
+ return { title: statusText };
910
+ }
911
+ }
912
+ /** Sleep for a given number of milliseconds. */
913
+ function sleep(ms, signal) {
914
+ return new Promise((resolve, reject) => {
915
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
916
+ // Native timers truncate fractional milliseconds; never wake before a clipped deadline.
917
+ const timer = setTimeout(() => {
918
+ cleanup();
919
+ resolve();
920
+ }, Math.ceil(ms));
921
+ const onAbort = () => {
922
+ clearTimeout(timer);
923
+ cleanup();
924
+ reject(signal.reason);
925
+ };
926
+ signal?.addEventListener("abort", onAbort, { once: true });
927
+ if (signal?.aborted)
928
+ onAbort();
929
+ });
930
+ }
931
+ /**
932
+ * A monotonic clock reading in milliseconds, immune to wall-clock
933
+ * adjustments (NTP corrections, manual clock changes) that could otherwise
934
+ * prevent a `maxDuration` deadline from ever being reached.
935
+ */
936
+ function monotonicNow() {
937
+ return performance.now();
938
+ }
939
+ /** Cancel this caller's wait without cancelling an OAuth refresh shared by others. */
940
+ function withCancellation(promise, signal) {
941
+ if (!signal)
942
+ return promise;
943
+ return new Promise((resolve, reject) => {
944
+ const onAbort = () => {
945
+ signal.removeEventListener("abort", onAbort);
946
+ reject(signal.reason);
947
+ };
948
+ signal.addEventListener("abort", onAbort, { once: true });
949
+ if (signal.aborted)
950
+ onAbort();
951
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
952
+ });
953
+ }
954
+ function resolveCallTimeout(options, fallback) {
955
+ const value = options.callTimeout !== undefined ? options.callTimeout : fallback;
956
+ validateTimeout(value, "callTimeout");
957
+ return value;
958
+ }
959
+ function resolveMaxRetries(value, fallback) {
960
+ if (value === undefined)
961
+ return fallback;
962
+ if (!Number.isInteger(value) || value < 0 || value > 2_147_483_646) {
963
+ throw new RangeError("maxRetries must be an integer between 0 and 2147483646");
964
+ }
965
+ return value;
966
+ }
967
+ //# sourceMappingURL=client.js.map