triqai 0.2.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  // package.json
6
- var version = "0.2.8";
6
+ var version = "0.4.0";
7
7
 
8
8
  // src/errors.ts
9
9
  var TriqaiError = class extends Error {
@@ -67,16 +67,25 @@ var ClientDisconnectedError = class extends TriqaiError {
67
67
  };
68
68
  var DuplicateRequestError = class extends TriqaiError {
69
69
  state;
70
+ /** `payload_mismatch` when the key was already used for a different request. */
71
+ reason;
70
72
  duplicateRequestId;
71
73
  retryAfter;
72
74
  constructor(message, opts) {
73
75
  super(message, 409, { code: "DUPLICATE_REQUEST", ...opts });
74
76
  this.name = "DuplicateRequestError";
75
77
  this.state = opts?.state;
78
+ this.reason = opts?.reason;
76
79
  this.duplicateRequestId = opts?.duplicateRequestId;
77
80
  this.retryAfter = opts?.retryAfter;
78
81
  }
79
82
  };
83
+ var GoneError = class extends TriqaiError {
84
+ constructor(message, opts) {
85
+ super(message, 410, { code: "gone", ...opts });
86
+ this.name = "GoneError";
87
+ }
88
+ };
80
89
  var RateLimitError = class extends TriqaiError {
81
90
  rateLimitInfo;
82
91
  constructor(message, rateLimitInfo, opts) {
@@ -112,11 +121,492 @@ var ConnectionError = class extends TriqaiError {
112
121
  }
113
122
  };
114
123
  var TimeoutError = class extends TriqaiError {
115
- constructor(message) {
116
- super(message, 0, { code: "timeout" });
124
+ constructor(message, opts) {
125
+ super(message, 0, { code: opts?.code ?? "timeout" });
117
126
  this.name = "TimeoutError";
118
127
  }
119
128
  };
129
+ var PacingTimeoutError = class extends TimeoutError {
130
+ constructor(message) {
131
+ super(message, { code: "pacing_timeout" });
132
+ this.name = "PacingTimeoutError";
133
+ }
134
+ };
135
+
136
+ // src/abort.ts
137
+ var callbacks = /* @__PURE__ */ new WeakMap();
138
+ function onAbort(signal, callback) {
139
+ if (signal.aborted) {
140
+ callback();
141
+ return () => {
142
+ };
143
+ }
144
+ let set = callbacks.get(signal);
145
+ if (!set) {
146
+ const created = /* @__PURE__ */ new Set();
147
+ set = created;
148
+ callbacks.set(signal, created);
149
+ signal.addEventListener("abort", () => {
150
+ callbacks.delete(signal);
151
+ for (const run of [...created]) run();
152
+ }, { once: true });
153
+ }
154
+ const own = set;
155
+ own.add(callback);
156
+ return () => {
157
+ own.delete(callback);
158
+ };
159
+ }
160
+ function abortReason(signal) {
161
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
162
+ }
163
+ function throwIfAborted(signal) {
164
+ if (signal?.aborted) throw abortReason(signal);
165
+ }
166
+
167
+ // src/pacing.ts
168
+ var DEFAULT_CONCURRENCY = 5;
169
+ var COLD_LIMIT = 5;
170
+ var MAX_SHARED_PAUSE_MS = 6e4;
171
+ var LEASE_MS = 1e3;
172
+ var MIN_RATE = 0.1;
173
+ var MAX_CONCURRENCY = 1e3;
174
+ var MAX_TIMER_DELAY = 2147483647;
175
+ var EPSILON = 1e-9;
176
+ var WaiterQueue = class {
177
+ items = [];
178
+ head = 0;
179
+ push(waiter) {
180
+ this.items.push(waiter);
181
+ }
182
+ unshiftAll(waiters) {
183
+ if (waiters.length === 0) return;
184
+ this.items = [...waiters, ...this.items.slice(this.head)];
185
+ this.head = 0;
186
+ }
187
+ peek() {
188
+ while (this.head < this.items.length && this.items[this.head].state !== "queued") this.head++;
189
+ if (this.head === this.items.length) {
190
+ this.items = [];
191
+ this.head = 0;
192
+ return void 0;
193
+ }
194
+ if (this.head > 1024 && this.head * 2 > this.items.length) {
195
+ this.items = this.items.slice(this.head);
196
+ this.head = 0;
197
+ }
198
+ return this.items[this.head];
199
+ }
200
+ shift() {
201
+ const waiter = this.peek();
202
+ if (waiter) this.head++;
203
+ return waiter;
204
+ }
205
+ /** Removes and returns the queued waiters that match, in order. */
206
+ extract(match) {
207
+ const taken = [];
208
+ const kept = [];
209
+ for (let i = this.head; i < this.items.length; i++) {
210
+ const waiter = this.items[i];
211
+ if (waiter.state !== "queued") continue;
212
+ (match(waiter) ? taken : kept).push(waiter);
213
+ }
214
+ this.items = kept;
215
+ this.head = 0;
216
+ return taken;
217
+ }
218
+ };
219
+ var Pacer = class {
220
+ /** How long a call may wait for its first attempt. */
221
+ maxWait;
222
+ maxConcurrency;
223
+ maxRate;
224
+ serverConcurrency;
225
+ serverRate;
226
+ /** When the concurrency limit became known; earlier requests do not lower the window. */
227
+ concurrencyKnownAt;
228
+ /** Enrichments allowed in flight now; lowered by concurrency 429s, then regrown. */
229
+ window;
230
+ successes = 0;
231
+ /** When the window was last lowered; earlier requests do not regrow it. */
232
+ loweredAt = -Infinity;
233
+ /** Enrichment slots held, by queued retries as well as requests in flight. */
234
+ active = 0;
235
+ /** Requests granted and not yet finished. */
236
+ inFlight = 0;
237
+ tokens;
238
+ refilledAt;
239
+ ratePausedUntil = -Infinity;
240
+ slotPausedUntil = -Infinity;
241
+ pumpedAt = -Infinity;
242
+ slotRetries = new WaiterQueue();
243
+ slotQueue = new WaiterQueue();
244
+ rateRetries = new WaiterQueue();
245
+ rateQueue = new WaiterQueue();
246
+ /** Waiters with a future `notBefore`, earliest first. */
247
+ delayed = [];
248
+ /** Grants not yet taken up by their calls. */
249
+ leased = /* @__PURE__ */ new Set();
250
+ timer;
251
+ constructor(options = {}, defaultMaxWait = 3e5) {
252
+ const { maxConcurrency, requestsPerSecond, maxWait = defaultMaxWait } = options;
253
+ if (maxConcurrency !== void 0 && !(Number.isInteger(maxConcurrency) && maxConcurrency >= 1)) {
254
+ throw new Error("pacing.maxConcurrency must be a positive integer");
255
+ }
256
+ if (requestsPerSecond !== void 0 && !(Number.isFinite(requestsPerSecond) && requestsPerSecond > 0)) {
257
+ throw new Error("pacing.requestsPerSecond must be a positive number");
258
+ }
259
+ if (!(Number.isFinite(maxWait) && maxWait > 0 && maxWait <= MAX_TIMER_DELAY)) {
260
+ throw new Error(`pacing.maxWait must be greater than 0 and at most ${MAX_TIMER_DELAY}ms`);
261
+ }
262
+ this.maxConcurrency = maxConcurrency;
263
+ this.maxRate = requestsPerSecond;
264
+ this.maxWait = maxWait;
265
+ this.concurrencyKnownAt = maxConcurrency === void 0 ? Infinity : -Infinity;
266
+ this.window = this.concurrencyLimit();
267
+ this.refilledAt = Date.now();
268
+ this.tokens = this.burst();
269
+ }
270
+ /** Waits until a request may be sent. Rejects on abort or when `deadline` passes. */
271
+ acquire(options) {
272
+ return this.admit({ ...options, hasSlot: false, retry: false, notBefore: -Infinity });
273
+ }
274
+ /**
275
+ * Queues a waiter and resolves when it is granted, without taking the grant
276
+ * up. Callers must claim it; `acquire` and `Permit.retry` do.
277
+ * @internal
278
+ */
279
+ wait(init) {
280
+ return new Promise((resolve, reject) => {
281
+ const waiter = {
282
+ ...init,
283
+ state: "queued",
284
+ leaseUntil: 0,
285
+ resolve,
286
+ reject,
287
+ timer: void 0,
288
+ unsubscribe: void 0
289
+ };
290
+ const now = Date.now();
291
+ const { signal } = init;
292
+ if (signal?.aborted) return this.settleEarly(waiter, abortReason(signal));
293
+ if (now >= init.deadline || init.notBefore >= init.deadline) return this.settleEarly(waiter, init.expired());
294
+ if (Number.isFinite(init.deadline)) {
295
+ waiter.timer = setTimeout(() => {
296
+ this.fail(waiter, waiter.expired());
297
+ this.pump();
298
+ }, Math.min(MAX_TIMER_DELAY, Math.max(0, init.deadline - now)));
299
+ }
300
+ if (signal) {
301
+ waiter.unsubscribe = onAbort(signal, () => {
302
+ this.fail(waiter, abortReason(signal));
303
+ this.pump();
304
+ });
305
+ }
306
+ this.place(waiter, now);
307
+ this.pump();
308
+ });
309
+ }
310
+ /** Takes up a grant. False when it went back to the pool first. @internal */
311
+ claim(waiter) {
312
+ if (waiter.state !== "leased") return false;
313
+ waiter.state = "active";
314
+ this.leased.delete(waiter);
315
+ return true;
316
+ }
317
+ /** Updates the limits from a response's rate-limit headers. */
318
+ observe(headers, slot, status, sentAt) {
319
+ const now = Date.now();
320
+ this.refill(now);
321
+ const concurrency = parseLimit(headers["x-ratelimit-concurrency-limit"]);
322
+ if (concurrency !== void 0 && concurrency > 0) {
323
+ const limit2 = Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(concurrency)));
324
+ if (limit2 !== this.serverConcurrency) {
325
+ if (this.serverConcurrency === void 0) this.concurrencyKnownAt = Math.min(this.concurrencyKnownAt, now);
326
+ this.serverConcurrency = limit2;
327
+ this.window = this.concurrencyLimit();
328
+ this.successes = 0;
329
+ }
330
+ }
331
+ const scope = headers["x-ratelimit-scope"];
332
+ const limit = parseLimit(headers["x-ratelimit-limit"]);
333
+ if (limit !== void 0 && limit > 0 && scope !== "concurrency") {
334
+ const rateWasKnown = Number.isFinite(this.rate());
335
+ this.serverRate = Math.max(MIN_RATE, limit);
336
+ const remaining = parseLimit(headers["x-ratelimit-remaining"]);
337
+ if (!rateWasKnown) {
338
+ this.tokens = remaining ?? this.burst();
339
+ } else if (remaining !== void 0) {
340
+ const elapsed = Math.max(0, now - sentAt);
341
+ this.tokens = Math.min(this.tokens, remaining + elapsed * this.rate() / 1e3);
342
+ }
343
+ this.tokens = Math.min(this.tokens, this.burst());
344
+ }
345
+ if (slot && status >= 200 && status < 300 && sentAt > this.loweredAt) {
346
+ if (this.window < this.concurrencyLimit() && ++this.successes >= this.window) {
347
+ this.window++;
348
+ this.successes = 0;
349
+ }
350
+ }
351
+ this.pump();
352
+ }
353
+ /**
354
+ * Pauses the limit a 429 names for `delayMs` (at most MAX_SHARED_PAUSE_MS).
355
+ * A 429 without a scope comes from a limit that covers every request.
356
+ */
357
+ pause(scope, delayMs, slot, sentAt) {
358
+ const now = Date.now();
359
+ const until = now + Math.min(Math.max(0, delayMs), MAX_SHARED_PAUSE_MS);
360
+ if (scope === "concurrency") {
361
+ this.slotPausedUntil = Math.max(this.slotPausedUntil, until);
362
+ if (slot && sentAt >= this.concurrencyKnownAt) {
363
+ this.window = Math.max(1, Math.min(this.window - 1, this.active - 1));
364
+ this.successes = 0;
365
+ this.loweredAt = now;
366
+ }
367
+ this.holdBackSlots();
368
+ } else {
369
+ this.ratePausedUntil = Math.max(this.ratePausedUntil, until);
370
+ if (scope === "rps") {
371
+ this.refill(now);
372
+ this.tokens = Math.min(this.tokens, 0);
373
+ }
374
+ }
375
+ this.pump();
376
+ }
377
+ async admit(init) {
378
+ let waiter = await this.wait(init);
379
+ while (!this.claim(waiter)) {
380
+ waiter = await this.wait({ ...init, hasSlot: false, retry: true });
381
+ }
382
+ return this.permit(waiter);
383
+ }
384
+ permit(waiter) {
385
+ return {
386
+ release: () => this.release(waiter),
387
+ retry: (options) => {
388
+ if (waiter.state !== "active") return this.acquire({ ...options, slot: waiter.slot });
389
+ const { hasSlot } = waiter;
390
+ waiter.hasSlot = false;
391
+ waiter.state = "done";
392
+ this.inFlight--;
393
+ return this.admit({ ...options, slot: waiter.slot, hasSlot, retry: true });
394
+ }
395
+ };
396
+ }
397
+ release(waiter) {
398
+ if (waiter.state !== "active") return;
399
+ waiter.state = "done";
400
+ this.inFlight--;
401
+ if (waiter.hasSlot) {
402
+ waiter.hasSlot = false;
403
+ this.active--;
404
+ }
405
+ this.pump();
406
+ }
407
+ concurrencyLimit() {
408
+ const server = this.serverConcurrency ?? (this.maxConcurrency === void 0 ? DEFAULT_CONCURRENCY : Infinity);
409
+ return Math.min(this.maxConcurrency ?? Infinity, server);
410
+ }
411
+ rate() {
412
+ return Math.min(this.maxRate ?? Infinity, this.serverRate ?? Infinity);
413
+ }
414
+ /** The API's bucket holds as many tokens as its concurrency limit. */
415
+ burst() {
416
+ const rate = this.rate();
417
+ if (!Number.isFinite(rate)) return Infinity;
418
+ const own = this.maxRate === void 0 ? Infinity : Math.ceil(this.maxRate);
419
+ return Math.max(1, Math.min(this.serverConcurrency ?? Math.ceil(rate), own));
420
+ }
421
+ refill(now) {
422
+ const rate = this.rate();
423
+ if (Number.isFinite(rate)) {
424
+ const elapsed = Math.max(0, now - this.refilledAt);
425
+ this.tokens = Math.min(this.burst(), this.tokens + elapsed * rate / 1e3);
426
+ }
427
+ this.refilledAt = now;
428
+ }
429
+ /** Puts a queued waiter where it can next make progress. */
430
+ place(waiter, now) {
431
+ const ready = waiter.hasSlot ? Math.max(waiter.notBefore, this.slotPausedUntil) : waiter.notBefore;
432
+ if (ready > now) {
433
+ waiter.notBefore = ready;
434
+ this.delay(waiter);
435
+ } else if (waiter.slot && !waiter.hasSlot) {
436
+ (waiter.retry ? this.slotRetries : this.slotQueue).push(waiter);
437
+ } else {
438
+ (waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
439
+ }
440
+ }
441
+ delay(waiter) {
442
+ let low = 0;
443
+ let high = this.delayed.length;
444
+ while (low < high) {
445
+ const mid = low + high >>> 1;
446
+ if (this.delayed[mid].notBefore <= waiter.notBefore) low = mid + 1;
447
+ else high = mid;
448
+ }
449
+ this.delayed.splice(low, 0, waiter);
450
+ }
451
+ nextDelayed() {
452
+ while (this.delayed.length > 0 && this.delayed[0].state !== "queued") this.delayed.shift();
453
+ return this.delayed[0];
454
+ }
455
+ /**
456
+ * After a concurrency 429, requests that hold a slot but have not been sent
457
+ * give it back and wait for the pause; a queued retry keeps its slot.
458
+ */
459
+ holdBackSlots() {
460
+ const returned = [];
461
+ for (const queue of [this.rateRetries, this.rateQueue]) {
462
+ for (const waiter of queue.extract((w) => w.hasSlot)) {
463
+ if (waiter.retry) {
464
+ waiter.notBefore = Math.max(waiter.notBefore, this.slotPausedUntil);
465
+ this.delay(waiter);
466
+ } else {
467
+ waiter.hasSlot = false;
468
+ this.active--;
469
+ returned.push(waiter);
470
+ }
471
+ }
472
+ }
473
+ this.slotQueue.unshiftAll(returned);
474
+ }
475
+ pump() {
476
+ const now = Date.now();
477
+ if (now < this.pumpedAt) this.clampAfterClockStep(now);
478
+ this.pumpedAt = now;
479
+ this.reclaim(now);
480
+ for (let waiter = this.nextDelayed(); waiter && waiter.notBefore <= now; waiter = this.nextDelayed()) {
481
+ this.delayed.shift();
482
+ if (waiter.hasSlot && this.active > this.window) {
483
+ waiter.hasSlot = false;
484
+ this.active--;
485
+ }
486
+ this.place(waiter, now);
487
+ }
488
+ if (now >= this.slotPausedUntil) {
489
+ while (this.active < this.window) {
490
+ const waiter = this.slotRetries.shift() ?? this.slotQueue.shift();
491
+ if (!waiter) break;
492
+ waiter.hasSlot = true;
493
+ this.active++;
494
+ (waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
495
+ }
496
+ }
497
+ if (now >= this.ratePausedUntil) {
498
+ this.refill(now);
499
+ const limited = Number.isFinite(this.rate());
500
+ for (; ; ) {
501
+ const queue = this.rateRetries.peek() ? this.rateRetries : this.rateQueue;
502
+ const waiter = queue.peek();
503
+ if (!waiter) break;
504
+ if (limited) {
505
+ if (this.tokens < 1 - EPSILON) break;
506
+ this.tokens -= 1;
507
+ } else if (this.inFlight >= COLD_LIMIT) {
508
+ break;
509
+ }
510
+ queue.shift();
511
+ this.grant(waiter, now);
512
+ }
513
+ }
514
+ this.schedule(now);
515
+ }
516
+ grant(waiter, now) {
517
+ waiter.state = "leased";
518
+ waiter.leaseUntil = now + LEASE_MS;
519
+ this.leased.add(waiter);
520
+ this.inFlight++;
521
+ this.detach(waiter);
522
+ waiter.resolve(waiter);
523
+ }
524
+ /**
525
+ * A wall clock that steps backwards must not stretch a pause, a lease or a
526
+ * retry's wait beyond their own maximums. Mapping every time through the same
527
+ * `min` keeps the delayed queue in order.
528
+ */
529
+ clampAfterClockStep(now) {
530
+ this.ratePausedUntil = Math.min(this.ratePausedUntil, now + MAX_SHARED_PAUSE_MS);
531
+ this.slotPausedUntil = Math.min(this.slotPausedUntil, now + MAX_SHARED_PAUSE_MS);
532
+ for (const waiter of this.leased) waiter.leaseUntil = Math.min(waiter.leaseUntil, now + LEASE_MS);
533
+ for (const waiter of this.delayed) waiter.notBefore = Math.min(waiter.notBefore, now + MAX_SHARED_PAUSE_MS);
534
+ }
535
+ /** Returns grants not taken up in time to the pool. */
536
+ reclaim(now) {
537
+ for (const waiter of this.leased) {
538
+ if (waiter.leaseUntil > now) continue;
539
+ this.leased.delete(waiter);
540
+ waiter.state = "done";
541
+ this.inFlight--;
542
+ if (waiter.hasSlot) {
543
+ waiter.hasSlot = false;
544
+ this.active--;
545
+ }
546
+ if (Number.isFinite(this.rate())) this.tokens = Math.min(this.burst(), this.tokens + 1);
547
+ }
548
+ }
549
+ /** Keeps at most one shared timer, and none while nothing waits. */
550
+ schedule(now) {
551
+ let wake = Infinity;
552
+ const slotWaiting = this.slotRetries.peek() ?? this.slotQueue.peek();
553
+ if (slotWaiting && this.slotPausedUntil > now) wake = this.slotPausedUntil;
554
+ const rateWaiting = this.rateRetries.peek() ?? this.rateQueue.peek();
555
+ if (rateWaiting) {
556
+ const rate = this.rate();
557
+ if (this.ratePausedUntil > now) wake = Math.min(wake, this.ratePausedUntil);
558
+ else if (Number.isFinite(rate) && this.tokens < 1 - EPSILON) {
559
+ wake = Math.min(wake, now + (1 - this.tokens) * 1e3 / rate);
560
+ }
561
+ }
562
+ const next = this.nextDelayed();
563
+ if (next) wake = Math.min(wake, next.notBefore);
564
+ if ((slotWaiting || rateWaiting || next) && this.leased.size > 0) {
565
+ for (const waiter of this.leased) wake = Math.min(wake, waiter.leaseUntil);
566
+ }
567
+ if (this.timer !== void 0) {
568
+ clearTimeout(this.timer);
569
+ this.timer = void 0;
570
+ }
571
+ if (wake === Infinity) return;
572
+ const delay = Math.min(MAX_TIMER_DELAY, Math.max(1, Math.ceil(wake - now)));
573
+ this.timer = setTimeout(() => {
574
+ this.timer = void 0;
575
+ this.pump();
576
+ }, delay);
577
+ }
578
+ fail(waiter, reason) {
579
+ if (waiter.state !== "queued") return;
580
+ waiter.state = "done";
581
+ this.detach(waiter);
582
+ if (waiter.hasSlot) {
583
+ waiter.hasSlot = false;
584
+ this.active--;
585
+ }
586
+ waiter.reject(reason);
587
+ }
588
+ /** Rejects a waiter before it is queued, freeing a slot it was handed. */
589
+ settleEarly(waiter, reason) {
590
+ waiter.state = "done";
591
+ if (waiter.hasSlot) {
592
+ waiter.hasSlot = false;
593
+ this.active--;
594
+ this.pump();
595
+ }
596
+ waiter.reject(reason);
597
+ }
598
+ detach(waiter) {
599
+ if (waiter.timer !== void 0) clearTimeout(waiter.timer);
600
+ waiter.timer = void 0;
601
+ waiter.unsubscribe?.();
602
+ waiter.unsubscribe = void 0;
603
+ }
604
+ };
605
+ function parseLimit(value) {
606
+ if (value === void 0 || !/^\s*\d+(?:\.\d+)?\s*$/.test(value)) return void 0;
607
+ const n = Number(value);
608
+ return Number.isFinite(n) ? n : void 0;
609
+ }
120
610
 
121
611
  // src/http-client.ts
122
612
  var DEFAULT_BASE_URL = "https://api.triqai.com";
@@ -125,8 +615,9 @@ var DEFAULT_RETRY_DELAY = 500;
125
615
  var DEFAULT_MAX_RETRY_DELAY = 3e4;
126
616
  var DEFAULT_TIMEOUT = 6e4;
127
617
  var DEFAULT_MAX_RETRY_TIME = 3e5;
128
- var MAX_TIMER_DELAY = 2147483647;
618
+ var MAX_TIMER_DELAY2 = 2147483647;
129
619
  var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 500, 503, 504]);
620
+ var MAX_RESET_WAIT_MS = 1e4;
130
621
  var HttpClient = class {
131
622
  apiKey;
132
623
  baseUrl;
@@ -138,6 +629,7 @@ var HttpClient = class {
138
629
  defaultHeaders;
139
630
  onRequest;
140
631
  onResponse;
632
+ pacer;
141
633
  constructor(apiKey, config = {}) {
142
634
  if (!apiKey) {
143
635
  throw new Error(
@@ -151,23 +643,30 @@ var HttpClient = class {
151
643
  this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
152
644
  this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
153
645
  this.maxRetryTime = config.maxRetryTime ?? DEFAULT_MAX_RETRY_TIME;
154
- if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime > MAX_TIMER_DELAY) {
155
- throw new Error(`maxRetryTime must be greater than 0 and at most ${MAX_TIMER_DELAY}ms`);
646
+ if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime > MAX_TIMER_DELAY2) {
647
+ throw new Error(`maxRetryTime must be greater than 0 and at most ${MAX_TIMER_DELAY2}ms`);
156
648
  }
157
649
  this.defaultHeaders = config.defaultHeaders ?? {};
158
650
  this.onRequest = config.onRequest;
159
651
  this.onResponse = config.onResponse;
652
+ const pacing = config.pacing === void 0 ? pacingByDefault() : config.pacing;
653
+ if (pacing !== true && pacing !== false && !isPlainObject(pacing)) {
654
+ throw new Error("pacing must be a boolean or an options object");
655
+ }
656
+ if (pacing !== false) this.pacer = new Pacer(pacing === true ? {} : pacing, this.maxRetryTime);
160
657
  }
161
- async get(path, query) {
162
- return this.request("GET", path, void 0, query);
658
+ async get(path, query, options) {
659
+ return this.request("GET", path, void 0, query, void 0, options);
163
660
  }
164
- async post(path, body) {
165
- return this.request("POST", path, body);
661
+ async post(path, body, options) {
662
+ return this.request("POST", path, body, void 0, void 0, options);
166
663
  }
167
- async delete(path) {
168
- return this.request("DELETE", path);
664
+ async delete(path, body, options) {
665
+ return this.request("DELETE", path, body, void 0, void 0, options);
169
666
  }
170
- async request(method, path, body, query, extraHeaders) {
667
+ async request(method, path, body, query, extraHeaders, options) {
668
+ const signal = options?.signal;
669
+ throwIfAborted(signal);
171
670
  const url = this.buildUrl(path, query);
172
671
  const headers = {
173
672
  "X-API-Key": this.apiKey,
@@ -179,115 +678,161 @@ var HttpClient = class {
179
678
  if (body !== void 0) {
180
679
  headers["Content-Type"] = "application/json";
181
680
  }
182
- const deadline = performance.now() + this.maxRetryTime;
681
+ const pacer = this.pacer;
682
+ const takesSlot = pacer !== void 0 && takesEnrichmentSlot(method, url);
683
+ let deadline = pacer ? Infinity : performance.now() + this.maxRetryTime;
684
+ const minRetryMs = pacer ? Math.min(1e3, this.timeout / 2) : 0;
183
685
  const serializedBody = body !== void 0 ? JSON.stringify(body) : void 0;
184
686
  let lastError;
185
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
186
- if (attempt > 0) {
187
- const delay = this.calculateDelay(attempt, lastError);
188
- if (delay >= deadline - performance.now()) {
687
+ let retryAt;
688
+ let permit;
689
+ const budgetExhausted = () => lastError ?? new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
690
+ try {
691
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
692
+ if (attempt > 0) {
693
+ const delay = retryAt === void 0 ? this.calculateDelay(attempt, lastError) : Math.max(0, retryAt - performance.now());
694
+ retryAt = void 0;
695
+ const cutoff = deadline - minRetryMs;
696
+ if (delay >= cutoff - performance.now()) {
697
+ throw lastError ?? new TimeoutError("Request retry budget exhausted");
698
+ }
699
+ if (permit) {
700
+ const wallOffset = Date.now() - performance.now();
701
+ permit = await permit.retry({
702
+ notBefore: Date.now() + delay,
703
+ deadline: cutoff + wallOffset,
704
+ signal,
705
+ expired: budgetExhausted
706
+ });
707
+ } else {
708
+ await sleep(delay, signal);
709
+ }
710
+ } else if (pacer) {
711
+ permit = await pacer.acquire({
712
+ slot: takesSlot,
713
+ deadline: Date.now() + pacer.maxWait,
714
+ signal,
715
+ expired: () => new PacingTimeoutError(
716
+ `Request waited ${pacer.maxWait}ms for its turn under pacing and was not sent: ${method} ${path}`
717
+ )
718
+ });
719
+ deadline = performance.now() + this.maxRetryTime;
720
+ }
721
+ throwIfAborted(signal);
722
+ const remainingMs = deadline - performance.now();
723
+ if (pacer && attempt > 0 && remainingMs < minRetryMs) {
189
724
  throw lastError ?? new TimeoutError("Request retry budget exhausted");
190
725
  }
191
- await sleep(delay);
192
- }
193
- const remainingMs = deadline - performance.now();
194
- if (remainingMs <= 0) {
195
- throw new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
196
- }
197
- const attemptTimeout = Math.min(this.timeout, remainingMs);
198
- const startMs = Date.now();
199
- this.onRequest?.({ method, url, headers: { ...headers }, body });
200
- try {
201
- const controller = new AbortController();
202
- const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
203
- let response;
204
- let responseBody;
726
+ if (remainingMs <= 0) {
727
+ throw new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
728
+ }
729
+ const attemptTimeout = Math.min(this.timeout, remainingMs);
730
+ const startMs = Date.now();
731
+ this.onRequest?.({ method, url, headers: { ...headers }, body });
205
732
  try {
206
- response = await fetch(url, {
207
- method,
208
- headers,
209
- body: serializedBody,
210
- signal: controller.signal
211
- });
212
- responseBody = await response.json().catch((err) => {
213
- if (err instanceof SyntaxError || !response.ok) return null;
214
- throw err;
215
- });
216
- if (controller.signal.aborted && response.ok) {
217
- throw new DOMException("The operation was aborted.", "AbortError");
733
+ const controller = new AbortController();
734
+ const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
735
+ const unlink = signal ? onAbort(signal, () => controller.abort()) : void 0;
736
+ let response;
737
+ let responseBody;
738
+ try {
739
+ response = await fetch(url, {
740
+ method,
741
+ headers,
742
+ body: serializedBody,
743
+ signal: controller.signal
744
+ });
745
+ responseBody = await response.json().catch((err) => {
746
+ if (err instanceof SyntaxError || !response.ok) return null;
747
+ throw err;
748
+ });
749
+ if (controller.signal.aborted && response.ok) {
750
+ throw new DOMException("The operation was aborted.", "AbortError");
751
+ }
752
+ } finally {
753
+ clearTimeout(timeoutId);
754
+ unlink?.();
218
755
  }
219
- } finally {
220
- clearTimeout(timeoutId);
221
- }
222
- const responseHeaders = parseHeaders(response.headers);
223
- const durationMs = Date.now() - startMs;
224
- this.onResponse?.({
225
- status: response.status,
226
- headers: responseHeaders,
227
- body: responseBody,
228
- durationMs,
229
- retryCount: attempt
230
- });
231
- if (response.ok) {
232
- return {
233
- data: responseBody,
756
+ const responseHeaders = parseHeaders(response.headers);
757
+ const durationMs = Date.now() - startMs;
758
+ pacer?.observe(responseHeaders, takesSlot, response.status, startMs);
759
+ this.onResponse?.({
234
760
  status: response.status,
235
761
  headers: responseHeaders,
236
- rateLimitInfo: parseRateLimitHeaders(responseHeaders)
237
- };
238
- }
239
- const shouldRetry = this.canRetry(
240
- attempt,
241
- method,
242
- headers,
243
- RETRYABLE_STATUS_CODES.has(response.status)
244
- );
245
- lastError = this.mapError(response.status, responseBody, responseHeaders);
246
- if (!shouldRetry) {
247
- throw lastError;
248
- }
249
- } catch (err) {
250
- if (err instanceof TriqaiError) {
251
- const canRetry = this.canRetry(
762
+ body: responseBody,
763
+ durationMs,
764
+ retryCount: attempt
765
+ });
766
+ if (response.ok) {
767
+ return {
768
+ data: responseBody,
769
+ status: response.status,
770
+ headers: responseHeaders,
771
+ rateLimitInfo: parseRateLimitHeaders(responseHeaders)
772
+ };
773
+ }
774
+ const error = this.mapError(response.status, responseBody, responseHeaders);
775
+ lastError = error;
776
+ if (pacer && error instanceof RateLimitError) {
777
+ const delay = this.rateLimitDelay(attempt + 1, error, responseHeaders);
778
+ retryAt = performance.now() + delay;
779
+ pacer.pause(error.rateLimitInfo.scope, delay, takesSlot, startMs);
780
+ }
781
+ const shouldRetry = this.canRetry(
252
782
  attempt,
253
783
  method,
254
784
  headers,
255
- RETRYABLE_STATUS_CODES.has(err.statusCode)
256
- );
257
- if (!canRetry) {
258
- throw err;
259
- }
260
- lastError = err;
261
- continue;
262
- }
263
- if (err instanceof DOMException && err.name === "AbortError") {
264
- lastError = new TimeoutError(
265
- `Request timed out after ${attemptTimeout}ms: ${method} ${path}`
785
+ isRetryableError(error)
266
786
  );
267
- if (!this.canRetry(attempt, method, headers, true)) {
787
+ if (!shouldRetry) {
268
788
  throw lastError;
269
789
  }
270
- continue;
271
- }
272
- if (isNetworkError(err)) {
273
- lastError = new ConnectionError(
274
- `Network error: ${err instanceof Error ? err.message : String(err)}`
275
- );
276
- if (!this.canRetry(attempt, method, headers, true)) {
277
- throw lastError;
790
+ } catch (err) {
791
+ if (signal?.aborted) throw abortReason(signal);
792
+ if (err instanceof TriqaiError) {
793
+ const canRetry = this.canRetry(
794
+ attempt,
795
+ method,
796
+ headers,
797
+ isRetryableError(err)
798
+ );
799
+ if (!canRetry) {
800
+ throw err;
801
+ }
802
+ lastError = err;
803
+ continue;
278
804
  }
279
- continue;
805
+ if (err instanceof DOMException && err.name === "AbortError") {
806
+ lastError = new TimeoutError(
807
+ `Request timed out after ${attemptTimeout}ms: ${method} ${path}`
808
+ );
809
+ if (!this.canRetry(attempt, method, headers, true)) {
810
+ throw lastError;
811
+ }
812
+ continue;
813
+ }
814
+ if (isNetworkError(err)) {
815
+ lastError = new ConnectionError(
816
+ `Network error: ${err instanceof Error ? err.message : String(err)}`
817
+ );
818
+ if (!this.canRetry(attempt, method, headers, true)) {
819
+ throw lastError;
820
+ }
821
+ continue;
822
+ }
823
+ throw err;
280
824
  }
281
- throw err;
282
825
  }
826
+ throw lastError ?? new TriqaiError("Request failed after retries", 0);
827
+ } finally {
828
+ permit?.release();
283
829
  }
284
- throw lastError ?? new TriqaiError("Request failed after retries", 0);
285
830
  }
286
831
  /**
287
832
  * Variant that injects custom headers (used by resources for Idempotency-Key etc.).
288
833
  */
289
- async postWithHeaders(path, body, headers, query) {
290
- return this.request("POST", path, body, query, headers);
834
+ async postWithHeaders(path, body, headers, query, options) {
835
+ return this.request("POST", path, body, query, headers, options);
291
836
  }
292
837
  buildUrl(path, query) {
293
838
  const isAbsoluteUrl = /^https?:\/\//i.test(path);
@@ -308,7 +853,7 @@ var HttpClient = class {
308
853
  return qs ? `${base}?${qs}` : base;
309
854
  }
310
855
  calculateDelay(attempt, lastError) {
311
- const retryAfter = lastError instanceof RateLimitError ? lastError.rateLimitInfo.retryAfter : lastError instanceof ServiceUnavailableError ? lastError.retryAfter : void 0;
856
+ const retryAfter = lastError instanceof RateLimitError ? lastError.rateLimitInfo.retryAfter : lastError instanceof ServiceUnavailableError || lastError instanceof DuplicateRequestError ? lastError.retryAfter : void 0;
312
857
  if (retryAfter) {
313
858
  const minimumDelay = retryAfter * 1e3;
314
859
  return minimumDelay + Math.min(minimumDelay * 0.2, 1e3) * Math.random();
@@ -316,6 +861,22 @@ var HttpClient = class {
316
861
  const exponential = Math.min(this.retryDelay * Math.pow(2, attempt - 1), this.maxRetryDelay / 1.2);
317
862
  return exponential * (1 + 0.2 * Math.random());
318
863
  }
864
+ /**
865
+ * The wait after a 429. Without Retry-After, the limit's reset time is used
866
+ * when it is near, measured against the response's Date header so the
867
+ * client's clock does not matter; otherwise the normal backoff.
868
+ */
869
+ rateLimitDelay(attempt, error, headers) {
870
+ const { retryAfter, reset } = error.rateLimitInfo;
871
+ if (!retryAfter && reset !== void 0) {
872
+ const serverNow = headers.date === void 0 ? NaN : Date.parse(headers.date);
873
+ const untilReset = Date.parse(reset) - (Number.isNaN(serverNow) ? Date.now() : serverNow);
874
+ if (untilReset > 0 && untilReset <= MAX_RESET_WAIT_MS) {
875
+ return untilReset + Math.min(untilReset * 0.2, 1e3) * Math.random();
876
+ }
877
+ }
878
+ return this.calculateDelay(attempt, error);
879
+ }
319
880
  canRetry(attempt, method, headers, retryableSignal) {
320
881
  return retryableSignal && attempt < this.maxRetries && isIdempotent(method, headers);
321
882
  }
@@ -343,10 +904,13 @@ var HttpClient = class {
343
904
  return new DuplicateRequestError(parsed.message, {
344
905
  ...opts,
345
906
  state: details?.state,
907
+ reason: details?.reason,
346
908
  duplicateRequestId: details?.requestId,
347
909
  retryAfter: details?.retryAfterSeconds
348
910
  });
349
911
  }
912
+ case 410:
913
+ return new GoneError(parsed.message, opts);
350
914
  case 422: {
351
915
  const fieldErrors = parsed.error?.details?.fieldErrors;
352
916
  return new ValidationError(parsed.message, fieldErrors, opts);
@@ -428,6 +992,12 @@ function parseErrorBody(body) {
428
992
  meta: meta?.generatedAt ? meta : void 0
429
993
  };
430
994
  }
995
+ function isRetryableError(err) {
996
+ if (err instanceof DuplicateRequestError) {
997
+ return err.reason === void 0 && (err.state === "in_progress" || err.state === "completed");
998
+ }
999
+ return RETRYABLE_STATUS_CODES.has(err.statusCode);
1000
+ }
431
1001
  function isIdempotent(method, headers) {
432
1002
  if (method === "GET" || method === "DELETE") return true;
433
1003
  return Object.entries(headers).some(
@@ -450,8 +1020,38 @@ function isNetworkError(err) {
450
1020
  }
451
1021
  return false;
452
1022
  }
453
- function sleep(ms) {
454
- return new Promise((resolve) => setTimeout(resolve, ms));
1023
+ function takesEnrichmentSlot(method, url) {
1024
+ if (method !== "POST") return false;
1025
+ const path = url.split("?")[0].replace(/\/+$/, "");
1026
+ return path.endsWith("/v1/transactions/enrich");
1027
+ }
1028
+ function pacingByDefault() {
1029
+ const g = globalThis;
1030
+ if (typeof g.process?.versions?.node !== "string") return false;
1031
+ if (g.Deno !== void 0 || g.EdgeRuntime !== void 0 || g.WebSocketPair !== void 0) return false;
1032
+ return g.navigator?.userAgent !== "Cloudflare-Workers";
1033
+ }
1034
+ function isPlainObject(value) {
1035
+ if (typeof value !== "object" || value === null) return false;
1036
+ const proto = Object.getPrototypeOf(value);
1037
+ return proto === Object.prototype || proto === null;
1038
+ }
1039
+ function sleep(ms, signal) {
1040
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
1041
+ return new Promise((resolve, reject) => {
1042
+ if (signal.aborted) {
1043
+ reject(abortReason(signal));
1044
+ return;
1045
+ }
1046
+ const timer = setTimeout(() => {
1047
+ unsubscribe();
1048
+ resolve();
1049
+ }, ms);
1050
+ const unsubscribe = onAbort(signal, () => {
1051
+ clearTimeout(timer);
1052
+ reject(abortReason(signal));
1053
+ });
1054
+ });
455
1055
  }
456
1056
 
457
1057
  // src/resources/banks.ts
@@ -460,13 +1060,13 @@ var Banks = class {
460
1060
  this.http = http;
461
1061
  }
462
1062
  /** Exact, case-insensitive name lookup with an optional country of origin. Costs zero credits. */
463
- async search(params) {
464
- const resp = await this.http.get("/v1/banks", { ...params });
1063
+ async search(params, options) {
1064
+ const resp = await this.http.get("/v1/banks", { ...params }, options);
465
1065
  return resp.data.data;
466
1066
  }
467
1067
  /** Retrieve stored bank details by UUID. */
468
- async get(id) {
469
- const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}`);
1068
+ async get(id, options) {
1069
+ const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}`, void 0, options);
470
1070
  return resp.data.data.bank;
471
1071
  }
472
1072
  };
@@ -482,6 +1082,7 @@ var Categories = class {
482
1082
  * Returns the full category tree used for transaction classification,
483
1083
  * including MCC, SIC, and NAICS codes.
484
1084
  *
1085
+ * @param options - Optional `signal` to cancel the call.
485
1086
  * @returns Array of category info objects and the total count.
486
1087
  *
487
1088
  * @example
@@ -490,8 +1091,8 @@ var Categories = class {
490
1091
  * console.log(`${total} categories available`);
491
1092
  * ```
492
1093
  */
493
- async list() {
494
- const resp = await this.http.get("/v1/categories");
1094
+ async list(options) {
1095
+ const resp = await this.http.get("/v1/categories", void 0, options);
495
1096
  return {
496
1097
  categories: resp.data.data.categories,
497
1098
  total: resp.data.data.total,
@@ -509,6 +1110,7 @@ var Intermediaries = class {
509
1110
  * Get an intermediary (payment processor / platform) by ID.
510
1111
  *
511
1112
  * @param id - Intermediary UUID.
1113
+ * @param options - Optional `signal` to cancel the call.
512
1114
  * @returns The intermediary data (name, icon, description, website, domain, etc.).
513
1115
  *
514
1116
  * @example
@@ -517,9 +1119,11 @@ var Intermediaries = class {
517
1119
  * console.log(intermediary.name); // "PayPal", "Square", etc.
518
1120
  * ```
519
1121
  */
520
- async get(id) {
1122
+ async get(id, options) {
521
1123
  const resp = await this.http.get(
522
- `/v1/intermediaries/${encodeURIComponent(id)}`
1124
+ `/v1/intermediaries/${encodeURIComponent(id)}`,
1125
+ void 0,
1126
+ options
523
1127
  );
524
1128
  return resp.data.data.intermediary;
525
1129
  }
@@ -602,12 +1206,12 @@ var IssueReports = class {
602
1206
  * console.log(report.id, report.status);
603
1207
  * ```
604
1208
  */
605
- async create(params) {
1209
+ async create(params, options) {
606
1210
  const resp = await this.http.post("/v1/report-issue", {
607
1211
  transaction_id: params.transactionId,
608
1212
  description: params.description,
609
1213
  fields: params.fields
610
- });
1214
+ }, options);
611
1215
  return resp.data.data.issueReport;
612
1216
  }
613
1217
  /**
@@ -624,12 +1228,12 @@ var IssueReports = class {
624
1228
  * }
625
1229
  * ```
626
1230
  */
627
- async list(params) {
1231
+ async list(params, options) {
628
1232
  const fetchPage = async (page, size) => {
629
1233
  const query = { page, size };
630
1234
  if (params?.status) query.status = params.status;
631
1235
  if (params?.transactionId) query.transaction_id = params.transactionId;
632
- const resp = await this.http.get("/v1/report-issue", query);
1236
+ const resp = await this.http.get("/v1/report-issue", query, options);
633
1237
  const pageInfo = {
634
1238
  page: resp.data.meta.page,
635
1239
  size: resp.data.meta.size,
@@ -644,11 +1248,14 @@ var IssueReports = class {
644
1248
  * Get a single issue report by ID.
645
1249
  *
646
1250
  * @param id - Issue report UUID.
1251
+ * @param options - Optional `signal` to cancel the call.
647
1252
  * @returns The issue report details.
648
1253
  */
649
- async get(id) {
1254
+ async get(id, options) {
650
1255
  const resp = await this.http.get(
651
- `/v1/report-issue/${encodeURIComponent(id)}`
1256
+ `/v1/report-issue/${encodeURIComponent(id)}`,
1257
+ void 0,
1258
+ options
652
1259
  );
653
1260
  return resp.data.data.issueReport;
654
1261
  }
@@ -663,6 +1270,7 @@ var Locations = class {
663
1270
  * Get a location by ID.
664
1271
  *
665
1272
  * @param id - Location UUID.
1273
+ * @param options - Optional `signal` to cancel the call.
666
1274
  * @returns The location data (name, formatted address, coordinates, phone, rating, etc.).
667
1275
  *
668
1276
  * @example
@@ -671,9 +1279,11 @@ var Locations = class {
671
1279
  * console.log(location.formatted, location.structured.city);
672
1280
  * ```
673
1281
  */
674
- async get(id) {
1282
+ async get(id, options) {
675
1283
  const resp = await this.http.get(
676
- `/v1/locations/${encodeURIComponent(id)}`
1284
+ `/v1/locations/${encodeURIComponent(id)}`,
1285
+ void 0,
1286
+ options
677
1287
  );
678
1288
  return resp.data.data.location;
679
1289
  }
@@ -688,6 +1298,7 @@ var Merchants = class {
688
1298
  * Get a merchant by ID.
689
1299
  *
690
1300
  * @param id - Merchant UUID.
1301
+ * @param options - Optional `signal` to cancel the call.
691
1302
  * @returns The merchant data (name, icon, website, domain, aliases, etc.).
692
1303
  *
693
1304
  * @example
@@ -696,9 +1307,11 @@ var Merchants = class {
696
1307
  * console.log(merchant.name, merchant.website);
697
1308
  * ```
698
1309
  */
699
- async get(id) {
1310
+ async get(id, options) {
700
1311
  const resp = await this.http.get(
701
- `/v1/merchants/${encodeURIComponent(id)}`
1312
+ `/v1/merchants/${encodeURIComponent(id)}`,
1313
+ void 0,
1314
+ options
702
1315
  );
703
1316
  return resp.data.data.merchant;
704
1317
  }
@@ -722,7 +1335,7 @@ var Transactions = class {
722
1335
  * Enrich a transaction with merchant, category, location, and entity data.
723
1336
  *
724
1337
  * @param request - The transaction to enrich (title, country, type, and optional options).
725
- * @param options - Optional enrichment controls (force bypass cache, idempotency key).
1338
+ * @param options - Optional idempotency key and `signal` to cancel the call.
726
1339
  * @returns The enriched transaction data.
727
1340
  *
728
1341
  * @example
@@ -739,15 +1352,12 @@ var Transactions = class {
739
1352
  const headers = {
740
1353
  "Idempotency-Key": options?.idempotencyKey ?? await createIdempotencyKey()
741
1354
  };
742
- const query = {};
743
- if (options?.force) {
744
- query.force = "true";
745
- }
746
1355
  const resp = await this.http.postWithHeaders(
747
1356
  "/v1/transactions/enrich",
748
1357
  request,
749
1358
  headers,
750
- Object.keys(query).length > 0 ? query : void 0
1359
+ void 0,
1360
+ { signal: options?.signal }
751
1361
  );
752
1362
  return resp.data;
753
1363
  }
@@ -768,7 +1378,7 @@ var Transactions = class {
768
1378
  * }
769
1379
  * ```
770
1380
  */
771
- async list(params) {
1381
+ async list(params, options) {
772
1382
  const fetchPage = async (page, size) => {
773
1383
  const query = {
774
1384
  page,
@@ -780,21 +1390,43 @@ var Transactions = class {
780
1390
  if (params?.endDate) {
781
1391
  query.endDate = params.endDate instanceof Date ? params.endDate.toISOString() : params.endDate;
782
1392
  }
783
- const resp = await this.http.get("/v1/transactions", query);
1393
+ const resp = await this.http.get("/v1/transactions", query, options);
784
1394
  const { transactions, pagination } = resp.data.data;
785
1395
  return new Page(transactions, pagination, fetchPage);
786
1396
  };
787
1397
  return fetchPage(params?.page ?? 1, params?.size ?? 25);
788
1398
  }
1399
+ /**
1400
+ * Count your organization's transactions.
1401
+ *
1402
+ * @param params - Optional `afterDate` to count only transactions created on or after it.
1403
+ * @returns The number of matching transactions.
1404
+ *
1405
+ * @example
1406
+ * ```ts
1407
+ * const { count } = await triqai.transactions.count({ afterDate: "2026-01-01T00:00:00Z" });
1408
+ * ```
1409
+ */
1410
+ async count(params, options) {
1411
+ const query = {};
1412
+ if (params?.afterDate) {
1413
+ query.afterDate = params.afterDate instanceof Date ? params.afterDate.toISOString() : params.afterDate;
1414
+ }
1415
+ const resp = await this.http.get("/v1/transactions/count", query, options);
1416
+ return resp.data.data;
1417
+ }
789
1418
  /**
790
1419
  * Get a single transaction by ID.
791
1420
  *
792
1421
  * @param id - Transaction UUID.
1422
+ * @param options - Optional `signal` to cancel the call.
793
1423
  * @returns The enriched transaction record.
794
1424
  */
795
- async get(id) {
1425
+ async get(id, options) {
796
1426
  const resp = await this.http.get(
797
- `/v1/transactions/${encodeURIComponent(id)}`
1427
+ `/v1/transactions/${encodeURIComponent(id)}`,
1428
+ void 0,
1429
+ options
798
1430
  );
799
1431
  return resp.data.data.transaction;
800
1432
  }
@@ -802,19 +1434,46 @@ var Transactions = class {
802
1434
  * Delete a transaction by ID.
803
1435
  *
804
1436
  * @param id - Transaction UUID.
1437
+ * @param options - Optional `signal` to cancel the call.
805
1438
  * @returns Confirmation with the deleted transaction ID.
806
1439
  */
807
- async delete(id) {
1440
+ async delete(id, options) {
808
1441
  const resp = await this.http.delete(
809
- `/v1/transactions/${encodeURIComponent(id)}`
1442
+ `/v1/transactions/${encodeURIComponent(id)}`,
1443
+ void 0,
1444
+ options
810
1445
  );
811
1446
  return resp.data.data;
812
1447
  }
1448
+ /**
1449
+ * Delete many transactions in one request.
1450
+ *
1451
+ * Pass exactly one of `all: true` (every transaction in your organization),
1452
+ * `afterDate` (transactions created on or after it), or `ids` (at most 1000
1453
+ * UUIDs). The API rejects any other combination with a 422 `ValidationError`.
1454
+ * A 503 means cleanup is incomplete; like other DELETE requests, it is retried
1455
+ * automatically, and `count` then covers only the final attempt.
1456
+ *
1457
+ * @param request - The single selection mode.
1458
+ * @returns Confirmation with the number of transactions deleted.
1459
+ *
1460
+ * @example
1461
+ * ```ts
1462
+ * const { count } = await triqai.transactions.batchDelete({
1463
+ * ids: ["550e8400-e29b-41d4-a716-446655440000"],
1464
+ * });
1465
+ * ```
1466
+ */
1467
+ async batchDelete(request, options) {
1468
+ const body = "afterDate" in request && request.afterDate instanceof Date ? { ...request, afterDate: request.afterDate.toISOString() } : request;
1469
+ const resp = await this.http.delete("/v1/transactions/batch", body, options);
1470
+ return resp.data.data;
1471
+ }
813
1472
  };
814
1473
 
815
1474
  // src/client.ts
816
1475
  var Triqai = class {
817
- /** Enrich, list, get, and delete transactions. */
1476
+ /** Enrich, list, count, get, and delete transactions. */
818
1477
  transactions;
819
1478
  /** List the full category taxonomy. */
820
1479
  categories;
@@ -857,8 +1516,8 @@ var Triqai = class {
857
1516
  * console.log(health.data.version); // "1.1.9"
858
1517
  * ```
859
1518
  */
860
- async health() {
861
- const resp = await this.http.get("/health");
1519
+ async health(options) {
1520
+ const resp = await this.http.get("/health", void 0, options);
862
1521
  return resp.data;
863
1522
  }
864
1523
  /**
@@ -873,8 +1532,8 @@ var Triqai = class {
873
1532
  * console.log(info.data.endpoints);
874
1533
  * ```
875
1534
  */
876
- async apiInfo() {
877
- const resp = await this.http.get("/v1");
1535
+ async apiInfo(options) {
1536
+ const resp = await this.http.get("/v1", void 0, options);
878
1537
  return resp.data;
879
1538
  }
880
1539
  /**
@@ -883,10 +1542,11 @@ var Triqai = class {
883
1542
  *
884
1543
  * @param path - API path (e.g. "/v1/some-endpoint").
885
1544
  * @param query - Optional query parameters.
1545
+ * @param options - Optional `signal` to cancel the call.
886
1546
  * @returns The full HTTP response including headers and rate limit info.
887
1547
  */
888
- async rawGet(path, query) {
889
- return this.http.get(path, query);
1548
+ async rawGet(path, query, options) {
1549
+ return this.http.get(path, query, options);
890
1550
  }
891
1551
  /**
892
1552
  * Make a raw POST request to any API path.
@@ -894,20 +1554,22 @@ var Triqai = class {
894
1554
  *
895
1555
  * @param path - API path (e.g. "/v1/some-endpoint").
896
1556
  * @param body - Request body.
1557
+ * @param options - Optional `signal` to cancel the call.
897
1558
  * @returns The full HTTP response including headers and rate limit info.
898
1559
  */
899
- async rawPost(path, body) {
900
- return this.http.post(path, body);
1560
+ async rawPost(path, body, options) {
1561
+ return this.http.post(path, body, options);
901
1562
  }
902
1563
  /**
903
1564
  * Make a raw DELETE request to any API path.
904
1565
  * Useful for accessing endpoints not yet covered by a resource class.
905
1566
  *
906
1567
  * @param path - API path (e.g. "/v1/some-resource/uuid").
1568
+ * @param options - Optional `signal` to cancel the call.
907
1569
  * @returns The full HTTP response including headers and rate limit info.
908
1570
  */
909
- async rawDelete(path) {
910
- return this.http.delete(path);
1571
+ async rawDelete(path, options) {
1572
+ return this.http.delete(path, void 0, options);
911
1573
  }
912
1574
  };
913
1575
 
@@ -920,9 +1582,11 @@ exports.ClientDisconnectedError = ClientDisconnectedError;
920
1582
  exports.ConnectionError = ConnectionError;
921
1583
  exports.DuplicateRequestError = DuplicateRequestError;
922
1584
  exports.GatewayTimeoutError = GatewayTimeoutError;
1585
+ exports.GoneError = GoneError;
923
1586
  exports.InsufficientCreditsError = InsufficientCreditsError;
924
1587
  exports.InternalServerError = InternalServerError;
925
1588
  exports.NotFoundError = NotFoundError;
1589
+ exports.PacingTimeoutError = PacingTimeoutError;
926
1590
  exports.Page = Page;
927
1591
  exports.RateLimitError = RateLimitError;
928
1592
  exports.ServiceUnavailableError = ServiceUnavailableError;