triqai 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +63 -2
- package/dist/index.cjs +750 -144
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +87 -26
- package/dist/index.d.ts +87 -26
- package/dist/index.js +750 -145
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// package.json
|
|
2
|
-
var version = "0.
|
|
2
|
+
var version = "0.4.1";
|
|
3
3
|
|
|
4
4
|
// src/errors.ts
|
|
5
5
|
var TriqaiError = class extends Error {
|
|
@@ -117,11 +117,492 @@ var ConnectionError = class extends TriqaiError {
|
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
119
|
var TimeoutError = class extends TriqaiError {
|
|
120
|
-
constructor(message) {
|
|
121
|
-
super(message, 0, { code: "timeout" });
|
|
120
|
+
constructor(message, opts) {
|
|
121
|
+
super(message, 0, { code: opts?.code ?? "timeout" });
|
|
122
122
|
this.name = "TimeoutError";
|
|
123
123
|
}
|
|
124
124
|
};
|
|
125
|
+
var PacingTimeoutError = class extends TimeoutError {
|
|
126
|
+
constructor(message) {
|
|
127
|
+
super(message, { code: "pacing_timeout" });
|
|
128
|
+
this.name = "PacingTimeoutError";
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// src/abort.ts
|
|
133
|
+
var callbacks = /* @__PURE__ */ new WeakMap();
|
|
134
|
+
function onAbort(signal, callback) {
|
|
135
|
+
if (signal.aborted) {
|
|
136
|
+
callback();
|
|
137
|
+
return () => {
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
let set = callbacks.get(signal);
|
|
141
|
+
if (!set) {
|
|
142
|
+
const created = /* @__PURE__ */ new Set();
|
|
143
|
+
set = created;
|
|
144
|
+
callbacks.set(signal, created);
|
|
145
|
+
signal.addEventListener("abort", () => {
|
|
146
|
+
callbacks.delete(signal);
|
|
147
|
+
for (const run of [...created]) run();
|
|
148
|
+
}, { once: true });
|
|
149
|
+
}
|
|
150
|
+
const own = set;
|
|
151
|
+
own.add(callback);
|
|
152
|
+
return () => {
|
|
153
|
+
own.delete(callback);
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function abortReason(signal) {
|
|
157
|
+
return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
158
|
+
}
|
|
159
|
+
function throwIfAborted(signal) {
|
|
160
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/pacing.ts
|
|
164
|
+
var DEFAULT_CONCURRENCY = 5;
|
|
165
|
+
var COLD_LIMIT = 5;
|
|
166
|
+
var MAX_SHARED_PAUSE_MS = 6e4;
|
|
167
|
+
var LEASE_MS = 1e3;
|
|
168
|
+
var MIN_RATE = 0.1;
|
|
169
|
+
var MAX_CONCURRENCY = 1e3;
|
|
170
|
+
var MAX_TIMER_DELAY = 2147483647;
|
|
171
|
+
var EPSILON = 1e-9;
|
|
172
|
+
var WaiterQueue = class {
|
|
173
|
+
items = [];
|
|
174
|
+
head = 0;
|
|
175
|
+
push(waiter) {
|
|
176
|
+
this.items.push(waiter);
|
|
177
|
+
}
|
|
178
|
+
unshiftAll(waiters) {
|
|
179
|
+
if (waiters.length === 0) return;
|
|
180
|
+
this.items = [...waiters, ...this.items.slice(this.head)];
|
|
181
|
+
this.head = 0;
|
|
182
|
+
}
|
|
183
|
+
peek() {
|
|
184
|
+
while (this.head < this.items.length && this.items[this.head].state !== "queued") this.head++;
|
|
185
|
+
if (this.head === this.items.length) {
|
|
186
|
+
this.items = [];
|
|
187
|
+
this.head = 0;
|
|
188
|
+
return void 0;
|
|
189
|
+
}
|
|
190
|
+
if (this.head > 1024 && this.head * 2 > this.items.length) {
|
|
191
|
+
this.items = this.items.slice(this.head);
|
|
192
|
+
this.head = 0;
|
|
193
|
+
}
|
|
194
|
+
return this.items[this.head];
|
|
195
|
+
}
|
|
196
|
+
shift() {
|
|
197
|
+
const waiter = this.peek();
|
|
198
|
+
if (waiter) this.head++;
|
|
199
|
+
return waiter;
|
|
200
|
+
}
|
|
201
|
+
/** Removes and returns the queued waiters that match, in order. */
|
|
202
|
+
extract(match) {
|
|
203
|
+
const taken = [];
|
|
204
|
+
const kept = [];
|
|
205
|
+
for (let i = this.head; i < this.items.length; i++) {
|
|
206
|
+
const waiter = this.items[i];
|
|
207
|
+
if (waiter.state !== "queued") continue;
|
|
208
|
+
(match(waiter) ? taken : kept).push(waiter);
|
|
209
|
+
}
|
|
210
|
+
this.items = kept;
|
|
211
|
+
this.head = 0;
|
|
212
|
+
return taken;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
var Pacer = class {
|
|
216
|
+
/** How long a call may wait for its first attempt. */
|
|
217
|
+
maxWait;
|
|
218
|
+
maxConcurrency;
|
|
219
|
+
maxRate;
|
|
220
|
+
serverConcurrency;
|
|
221
|
+
serverRate;
|
|
222
|
+
/** When the concurrency limit became known; earlier requests do not lower the window. */
|
|
223
|
+
concurrencyKnownAt;
|
|
224
|
+
/** Enrichments allowed in flight now; lowered by concurrency 429s, then regrown. */
|
|
225
|
+
window;
|
|
226
|
+
successes = 0;
|
|
227
|
+
/** When the window was last lowered; earlier requests do not regrow it. */
|
|
228
|
+
loweredAt = -Infinity;
|
|
229
|
+
/** Enrichment slots held, by queued retries as well as requests in flight. */
|
|
230
|
+
active = 0;
|
|
231
|
+
/** Requests granted and not yet finished. */
|
|
232
|
+
inFlight = 0;
|
|
233
|
+
tokens;
|
|
234
|
+
refilledAt;
|
|
235
|
+
ratePausedUntil = -Infinity;
|
|
236
|
+
slotPausedUntil = -Infinity;
|
|
237
|
+
pumpedAt = -Infinity;
|
|
238
|
+
slotRetries = new WaiterQueue();
|
|
239
|
+
slotQueue = new WaiterQueue();
|
|
240
|
+
rateRetries = new WaiterQueue();
|
|
241
|
+
rateQueue = new WaiterQueue();
|
|
242
|
+
/** Waiters with a future `notBefore`, earliest first. */
|
|
243
|
+
delayed = [];
|
|
244
|
+
/** Grants not yet taken up by their calls. */
|
|
245
|
+
leased = /* @__PURE__ */ new Set();
|
|
246
|
+
timer;
|
|
247
|
+
constructor(options = {}, defaultMaxWait = 3e5) {
|
|
248
|
+
const { maxConcurrency, requestsPerSecond, maxWait = defaultMaxWait } = options;
|
|
249
|
+
if (maxConcurrency !== void 0 && !(Number.isInteger(maxConcurrency) && maxConcurrency >= 1)) {
|
|
250
|
+
throw new Error("pacing.maxConcurrency must be a positive integer");
|
|
251
|
+
}
|
|
252
|
+
if (requestsPerSecond !== void 0 && !(Number.isFinite(requestsPerSecond) && requestsPerSecond > 0)) {
|
|
253
|
+
throw new Error("pacing.requestsPerSecond must be a positive number");
|
|
254
|
+
}
|
|
255
|
+
if (!(Number.isFinite(maxWait) && maxWait > 0 && maxWait <= MAX_TIMER_DELAY)) {
|
|
256
|
+
throw new Error(`pacing.maxWait must be greater than 0 and at most ${MAX_TIMER_DELAY}ms`);
|
|
257
|
+
}
|
|
258
|
+
this.maxConcurrency = maxConcurrency;
|
|
259
|
+
this.maxRate = requestsPerSecond;
|
|
260
|
+
this.maxWait = maxWait;
|
|
261
|
+
this.concurrencyKnownAt = maxConcurrency === void 0 ? Infinity : -Infinity;
|
|
262
|
+
this.window = this.concurrencyLimit();
|
|
263
|
+
this.refilledAt = Date.now();
|
|
264
|
+
this.tokens = this.burst();
|
|
265
|
+
}
|
|
266
|
+
/** Waits until a request may be sent. Rejects on abort or when `deadline` passes. */
|
|
267
|
+
acquire(options) {
|
|
268
|
+
return this.admit({ ...options, hasSlot: false, retry: false, notBefore: -Infinity });
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Queues a waiter and resolves when it is granted, without taking the grant
|
|
272
|
+
* up. Callers must claim it; `acquire` and `Permit.retry` do.
|
|
273
|
+
* @internal
|
|
274
|
+
*/
|
|
275
|
+
wait(init) {
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const waiter = {
|
|
278
|
+
...init,
|
|
279
|
+
state: "queued",
|
|
280
|
+
leaseUntil: 0,
|
|
281
|
+
resolve,
|
|
282
|
+
reject,
|
|
283
|
+
timer: void 0,
|
|
284
|
+
unsubscribe: void 0
|
|
285
|
+
};
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
const { signal } = init;
|
|
288
|
+
if (signal?.aborted) return this.settleEarly(waiter, abortReason(signal));
|
|
289
|
+
if (now >= init.deadline || init.notBefore >= init.deadline) return this.settleEarly(waiter, init.expired());
|
|
290
|
+
if (Number.isFinite(init.deadline)) {
|
|
291
|
+
waiter.timer = setTimeout(() => {
|
|
292
|
+
this.fail(waiter, waiter.expired());
|
|
293
|
+
this.pump();
|
|
294
|
+
}, Math.min(MAX_TIMER_DELAY, Math.max(0, init.deadline - now)));
|
|
295
|
+
}
|
|
296
|
+
if (signal) {
|
|
297
|
+
waiter.unsubscribe = onAbort(signal, () => {
|
|
298
|
+
this.fail(waiter, abortReason(signal));
|
|
299
|
+
this.pump();
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
this.place(waiter, now);
|
|
303
|
+
this.pump();
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
/** Takes up a grant. False when it went back to the pool first. @internal */
|
|
307
|
+
claim(waiter) {
|
|
308
|
+
if (waiter.state !== "leased") return false;
|
|
309
|
+
waiter.state = "active";
|
|
310
|
+
this.leased.delete(waiter);
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
/** Updates the limits from a response's rate-limit headers. */
|
|
314
|
+
observe(headers, slot, status, sentAt) {
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
this.refill(now);
|
|
317
|
+
const concurrency = parseLimit(headers["x-ratelimit-concurrency-limit"]);
|
|
318
|
+
if (concurrency !== void 0 && concurrency > 0) {
|
|
319
|
+
const limit2 = Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(concurrency)));
|
|
320
|
+
if (limit2 !== this.serverConcurrency) {
|
|
321
|
+
if (this.serverConcurrency === void 0) this.concurrencyKnownAt = Math.min(this.concurrencyKnownAt, now);
|
|
322
|
+
this.serverConcurrency = limit2;
|
|
323
|
+
this.window = this.concurrencyLimit();
|
|
324
|
+
this.successes = 0;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const scope = headers["x-ratelimit-scope"];
|
|
328
|
+
const limit = parseLimit(headers["x-ratelimit-limit"]);
|
|
329
|
+
if (limit !== void 0 && limit > 0 && scope !== "concurrency") {
|
|
330
|
+
const rateWasKnown = Number.isFinite(this.rate());
|
|
331
|
+
this.serverRate = Math.max(MIN_RATE, limit);
|
|
332
|
+
const remaining = parseLimit(headers["x-ratelimit-remaining"]);
|
|
333
|
+
if (!rateWasKnown) {
|
|
334
|
+
this.tokens = remaining ?? this.burst();
|
|
335
|
+
} else if (remaining !== void 0) {
|
|
336
|
+
const elapsed = Math.max(0, now - sentAt);
|
|
337
|
+
this.tokens = Math.min(this.tokens, remaining + elapsed * this.rate() / 1e3);
|
|
338
|
+
}
|
|
339
|
+
this.tokens = Math.min(this.tokens, this.burst());
|
|
340
|
+
}
|
|
341
|
+
if (slot && status >= 200 && status < 300 && sentAt > this.loweredAt) {
|
|
342
|
+
if (this.window < this.concurrencyLimit() && ++this.successes >= this.window) {
|
|
343
|
+
this.window++;
|
|
344
|
+
this.successes = 0;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
this.pump();
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Pauses the limit a 429 names for `delayMs` (at most MAX_SHARED_PAUSE_MS).
|
|
351
|
+
* A 429 without a scope comes from a limit that covers every request.
|
|
352
|
+
*/
|
|
353
|
+
pause(scope, delayMs, slot, sentAt) {
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
const until = now + Math.min(Math.max(0, delayMs), MAX_SHARED_PAUSE_MS);
|
|
356
|
+
if (scope === "concurrency") {
|
|
357
|
+
this.slotPausedUntil = Math.max(this.slotPausedUntil, until);
|
|
358
|
+
if (slot && sentAt >= this.concurrencyKnownAt) {
|
|
359
|
+
this.window = Math.max(1, Math.min(this.window - 1, this.active - 1));
|
|
360
|
+
this.successes = 0;
|
|
361
|
+
this.loweredAt = now;
|
|
362
|
+
}
|
|
363
|
+
this.holdBackSlots();
|
|
364
|
+
} else {
|
|
365
|
+
this.ratePausedUntil = Math.max(this.ratePausedUntil, until);
|
|
366
|
+
if (scope === "rps") {
|
|
367
|
+
this.refill(now);
|
|
368
|
+
this.tokens = Math.min(this.tokens, 0);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
this.pump();
|
|
372
|
+
}
|
|
373
|
+
async admit(init) {
|
|
374
|
+
let waiter = await this.wait(init);
|
|
375
|
+
while (!this.claim(waiter)) {
|
|
376
|
+
waiter = await this.wait({ ...init, hasSlot: false, retry: true });
|
|
377
|
+
}
|
|
378
|
+
return this.permit(waiter);
|
|
379
|
+
}
|
|
380
|
+
permit(waiter) {
|
|
381
|
+
return {
|
|
382
|
+
release: () => this.release(waiter),
|
|
383
|
+
retry: (options) => {
|
|
384
|
+
if (waiter.state !== "active") return this.acquire({ ...options, slot: waiter.slot });
|
|
385
|
+
const { hasSlot } = waiter;
|
|
386
|
+
waiter.hasSlot = false;
|
|
387
|
+
waiter.state = "done";
|
|
388
|
+
this.inFlight--;
|
|
389
|
+
return this.admit({ ...options, slot: waiter.slot, hasSlot, retry: true });
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
release(waiter) {
|
|
394
|
+
if (waiter.state !== "active") return;
|
|
395
|
+
waiter.state = "done";
|
|
396
|
+
this.inFlight--;
|
|
397
|
+
if (waiter.hasSlot) {
|
|
398
|
+
waiter.hasSlot = false;
|
|
399
|
+
this.active--;
|
|
400
|
+
}
|
|
401
|
+
this.pump();
|
|
402
|
+
}
|
|
403
|
+
concurrencyLimit() {
|
|
404
|
+
const server = this.serverConcurrency ?? (this.maxConcurrency === void 0 ? DEFAULT_CONCURRENCY : Infinity);
|
|
405
|
+
return Math.min(this.maxConcurrency ?? Infinity, server);
|
|
406
|
+
}
|
|
407
|
+
rate() {
|
|
408
|
+
return Math.min(this.maxRate ?? Infinity, this.serverRate ?? Infinity);
|
|
409
|
+
}
|
|
410
|
+
/** The API's bucket holds as many tokens as its concurrency limit. */
|
|
411
|
+
burst() {
|
|
412
|
+
const rate = this.rate();
|
|
413
|
+
if (!Number.isFinite(rate)) return Infinity;
|
|
414
|
+
const own = this.maxRate === void 0 ? Infinity : Math.ceil(this.maxRate);
|
|
415
|
+
return Math.max(1, Math.min(this.serverConcurrency ?? Math.ceil(rate), own));
|
|
416
|
+
}
|
|
417
|
+
refill(now) {
|
|
418
|
+
const rate = this.rate();
|
|
419
|
+
if (Number.isFinite(rate)) {
|
|
420
|
+
const elapsed = Math.max(0, now - this.refilledAt);
|
|
421
|
+
this.tokens = Math.min(this.burst(), this.tokens + elapsed * rate / 1e3);
|
|
422
|
+
}
|
|
423
|
+
this.refilledAt = now;
|
|
424
|
+
}
|
|
425
|
+
/** Puts a queued waiter where it can next make progress. */
|
|
426
|
+
place(waiter, now) {
|
|
427
|
+
const ready = waiter.hasSlot ? Math.max(waiter.notBefore, this.slotPausedUntil) : waiter.notBefore;
|
|
428
|
+
if (ready > now) {
|
|
429
|
+
waiter.notBefore = ready;
|
|
430
|
+
this.delay(waiter);
|
|
431
|
+
} else if (waiter.slot && !waiter.hasSlot) {
|
|
432
|
+
(waiter.retry ? this.slotRetries : this.slotQueue).push(waiter);
|
|
433
|
+
} else {
|
|
434
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
delay(waiter) {
|
|
438
|
+
let low = 0;
|
|
439
|
+
let high = this.delayed.length;
|
|
440
|
+
while (low < high) {
|
|
441
|
+
const mid = low + high >>> 1;
|
|
442
|
+
if (this.delayed[mid].notBefore <= waiter.notBefore) low = mid + 1;
|
|
443
|
+
else high = mid;
|
|
444
|
+
}
|
|
445
|
+
this.delayed.splice(low, 0, waiter);
|
|
446
|
+
}
|
|
447
|
+
nextDelayed() {
|
|
448
|
+
while (this.delayed.length > 0 && this.delayed[0].state !== "queued") this.delayed.shift();
|
|
449
|
+
return this.delayed[0];
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* After a concurrency 429, requests that hold a slot but have not been sent
|
|
453
|
+
* give it back and wait for the pause; a queued retry keeps its slot.
|
|
454
|
+
*/
|
|
455
|
+
holdBackSlots() {
|
|
456
|
+
const returned = [];
|
|
457
|
+
for (const queue of [this.rateRetries, this.rateQueue]) {
|
|
458
|
+
for (const waiter of queue.extract((w) => w.hasSlot)) {
|
|
459
|
+
if (waiter.retry) {
|
|
460
|
+
waiter.notBefore = Math.max(waiter.notBefore, this.slotPausedUntil);
|
|
461
|
+
this.delay(waiter);
|
|
462
|
+
} else {
|
|
463
|
+
waiter.hasSlot = false;
|
|
464
|
+
this.active--;
|
|
465
|
+
returned.push(waiter);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
this.slotQueue.unshiftAll(returned);
|
|
470
|
+
}
|
|
471
|
+
pump() {
|
|
472
|
+
const now = Date.now();
|
|
473
|
+
if (now < this.pumpedAt) this.clampAfterClockStep(now);
|
|
474
|
+
this.pumpedAt = now;
|
|
475
|
+
this.reclaim(now);
|
|
476
|
+
for (let waiter = this.nextDelayed(); waiter && waiter.notBefore <= now; waiter = this.nextDelayed()) {
|
|
477
|
+
this.delayed.shift();
|
|
478
|
+
if (waiter.hasSlot && this.active > this.window) {
|
|
479
|
+
waiter.hasSlot = false;
|
|
480
|
+
this.active--;
|
|
481
|
+
}
|
|
482
|
+
this.place(waiter, now);
|
|
483
|
+
}
|
|
484
|
+
if (now >= this.slotPausedUntil) {
|
|
485
|
+
while (this.active < this.window) {
|
|
486
|
+
const waiter = this.slotRetries.shift() ?? this.slotQueue.shift();
|
|
487
|
+
if (!waiter) break;
|
|
488
|
+
waiter.hasSlot = true;
|
|
489
|
+
this.active++;
|
|
490
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (now >= this.ratePausedUntil) {
|
|
494
|
+
this.refill(now);
|
|
495
|
+
const limited = Number.isFinite(this.rate());
|
|
496
|
+
for (; ; ) {
|
|
497
|
+
const queue = this.rateRetries.peek() ? this.rateRetries : this.rateQueue;
|
|
498
|
+
const waiter = queue.peek();
|
|
499
|
+
if (!waiter) break;
|
|
500
|
+
if (limited) {
|
|
501
|
+
if (this.tokens < 1 - EPSILON) break;
|
|
502
|
+
this.tokens -= 1;
|
|
503
|
+
} else if (this.inFlight >= COLD_LIMIT) {
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
queue.shift();
|
|
507
|
+
this.grant(waiter, now);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
this.schedule(now);
|
|
511
|
+
}
|
|
512
|
+
grant(waiter, now) {
|
|
513
|
+
waiter.state = "leased";
|
|
514
|
+
waiter.leaseUntil = now + LEASE_MS;
|
|
515
|
+
this.leased.add(waiter);
|
|
516
|
+
this.inFlight++;
|
|
517
|
+
this.detach(waiter);
|
|
518
|
+
waiter.resolve(waiter);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* A wall clock that steps backwards must not stretch a pause, a lease or a
|
|
522
|
+
* retry's wait beyond their own maximums. Mapping every time through the same
|
|
523
|
+
* `min` keeps the delayed queue in order.
|
|
524
|
+
*/
|
|
525
|
+
clampAfterClockStep(now) {
|
|
526
|
+
this.ratePausedUntil = Math.min(this.ratePausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
527
|
+
this.slotPausedUntil = Math.min(this.slotPausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
528
|
+
for (const waiter of this.leased) waiter.leaseUntil = Math.min(waiter.leaseUntil, now + LEASE_MS);
|
|
529
|
+
for (const waiter of this.delayed) waiter.notBefore = Math.min(waiter.notBefore, now + MAX_SHARED_PAUSE_MS);
|
|
530
|
+
}
|
|
531
|
+
/** Returns grants not taken up in time to the pool. */
|
|
532
|
+
reclaim(now) {
|
|
533
|
+
for (const waiter of this.leased) {
|
|
534
|
+
if (waiter.leaseUntil > now) continue;
|
|
535
|
+
this.leased.delete(waiter);
|
|
536
|
+
waiter.state = "done";
|
|
537
|
+
this.inFlight--;
|
|
538
|
+
if (waiter.hasSlot) {
|
|
539
|
+
waiter.hasSlot = false;
|
|
540
|
+
this.active--;
|
|
541
|
+
}
|
|
542
|
+
if (Number.isFinite(this.rate())) this.tokens = Math.min(this.burst(), this.tokens + 1);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/** Keeps at most one shared timer, and none while nothing waits. */
|
|
546
|
+
schedule(now) {
|
|
547
|
+
let wake = Infinity;
|
|
548
|
+
const slotWaiting = this.slotRetries.peek() ?? this.slotQueue.peek();
|
|
549
|
+
if (slotWaiting && this.slotPausedUntil > now) wake = this.slotPausedUntil;
|
|
550
|
+
const rateWaiting = this.rateRetries.peek() ?? this.rateQueue.peek();
|
|
551
|
+
if (rateWaiting) {
|
|
552
|
+
const rate = this.rate();
|
|
553
|
+
if (this.ratePausedUntil > now) wake = Math.min(wake, this.ratePausedUntil);
|
|
554
|
+
else if (Number.isFinite(rate) && this.tokens < 1 - EPSILON) {
|
|
555
|
+
wake = Math.min(wake, now + (1 - this.tokens) * 1e3 / rate);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const next = this.nextDelayed();
|
|
559
|
+
if (next) wake = Math.min(wake, next.notBefore);
|
|
560
|
+
if ((slotWaiting || rateWaiting || next) && this.leased.size > 0) {
|
|
561
|
+
for (const waiter of this.leased) wake = Math.min(wake, waiter.leaseUntil);
|
|
562
|
+
}
|
|
563
|
+
if (this.timer !== void 0) {
|
|
564
|
+
clearTimeout(this.timer);
|
|
565
|
+
this.timer = void 0;
|
|
566
|
+
}
|
|
567
|
+
if (wake === Infinity) return;
|
|
568
|
+
const delay = Math.min(MAX_TIMER_DELAY, Math.max(1, Math.ceil(wake - now)));
|
|
569
|
+
this.timer = setTimeout(() => {
|
|
570
|
+
this.timer = void 0;
|
|
571
|
+
this.pump();
|
|
572
|
+
}, delay);
|
|
573
|
+
}
|
|
574
|
+
fail(waiter, reason) {
|
|
575
|
+
if (waiter.state !== "queued") return;
|
|
576
|
+
waiter.state = "done";
|
|
577
|
+
this.detach(waiter);
|
|
578
|
+
if (waiter.hasSlot) {
|
|
579
|
+
waiter.hasSlot = false;
|
|
580
|
+
this.active--;
|
|
581
|
+
}
|
|
582
|
+
waiter.reject(reason);
|
|
583
|
+
}
|
|
584
|
+
/** Rejects a waiter before it is queued, freeing a slot it was handed. */
|
|
585
|
+
settleEarly(waiter, reason) {
|
|
586
|
+
waiter.state = "done";
|
|
587
|
+
if (waiter.hasSlot) {
|
|
588
|
+
waiter.hasSlot = false;
|
|
589
|
+
this.active--;
|
|
590
|
+
this.pump();
|
|
591
|
+
}
|
|
592
|
+
waiter.reject(reason);
|
|
593
|
+
}
|
|
594
|
+
detach(waiter) {
|
|
595
|
+
if (waiter.timer !== void 0) clearTimeout(waiter.timer);
|
|
596
|
+
waiter.timer = void 0;
|
|
597
|
+
waiter.unsubscribe?.();
|
|
598
|
+
waiter.unsubscribe = void 0;
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
function parseLimit(value) {
|
|
602
|
+
if (value === void 0 || !/^\s*\d+(?:\.\d+)?\s*$/.test(value)) return void 0;
|
|
603
|
+
const n = Number(value);
|
|
604
|
+
return Number.isFinite(n) ? n : void 0;
|
|
605
|
+
}
|
|
125
606
|
|
|
126
607
|
// src/http-client.ts
|
|
127
608
|
var DEFAULT_BASE_URL = "https://api.triqai.com";
|
|
@@ -130,8 +611,9 @@ var DEFAULT_RETRY_DELAY = 500;
|
|
|
130
611
|
var DEFAULT_MAX_RETRY_DELAY = 3e4;
|
|
131
612
|
var DEFAULT_TIMEOUT = 6e4;
|
|
132
613
|
var DEFAULT_MAX_RETRY_TIME = 3e5;
|
|
133
|
-
var
|
|
614
|
+
var MAX_TIMER_DELAY2 = 2147483647;
|
|
134
615
|
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 500, 503, 504]);
|
|
616
|
+
var MAX_RESET_WAIT_MS = 1e4;
|
|
135
617
|
var HttpClient = class {
|
|
136
618
|
apiKey;
|
|
137
619
|
baseUrl;
|
|
@@ -143,6 +625,7 @@ var HttpClient = class {
|
|
|
143
625
|
defaultHeaders;
|
|
144
626
|
onRequest;
|
|
145
627
|
onResponse;
|
|
628
|
+
pacer;
|
|
146
629
|
constructor(apiKey, config = {}) {
|
|
147
630
|
if (!apiKey) {
|
|
148
631
|
throw new Error(
|
|
@@ -156,23 +639,30 @@ var HttpClient = class {
|
|
|
156
639
|
this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
|
|
157
640
|
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
|
|
158
641
|
this.maxRetryTime = config.maxRetryTime ?? DEFAULT_MAX_RETRY_TIME;
|
|
159
|
-
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime >
|
|
160
|
-
throw new Error(`maxRetryTime must be greater than 0 and at most ${
|
|
642
|
+
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime > MAX_TIMER_DELAY2) {
|
|
643
|
+
throw new Error(`maxRetryTime must be greater than 0 and at most ${MAX_TIMER_DELAY2}ms`);
|
|
161
644
|
}
|
|
162
645
|
this.defaultHeaders = config.defaultHeaders ?? {};
|
|
163
646
|
this.onRequest = config.onRequest;
|
|
164
647
|
this.onResponse = config.onResponse;
|
|
648
|
+
const pacing = config.pacing === void 0 ? pacingByDefault() : config.pacing;
|
|
649
|
+
if (pacing !== true && pacing !== false && !isPlainObject(pacing)) {
|
|
650
|
+
throw new Error("pacing must be a boolean or an options object");
|
|
651
|
+
}
|
|
652
|
+
if (pacing !== false) this.pacer = new Pacer(pacing === true ? {} : pacing, this.maxRetryTime);
|
|
165
653
|
}
|
|
166
|
-
async get(path, query) {
|
|
167
|
-
return this.request("GET", path, void 0, query);
|
|
654
|
+
async get(path, query, options) {
|
|
655
|
+
return this.request("GET", path, void 0, query, void 0, options);
|
|
168
656
|
}
|
|
169
|
-
async post(path, body) {
|
|
170
|
-
return this.request("POST", path, body);
|
|
657
|
+
async post(path, body, options) {
|
|
658
|
+
return this.request("POST", path, body, void 0, void 0, options);
|
|
171
659
|
}
|
|
172
|
-
async delete(path, body) {
|
|
173
|
-
return this.request("DELETE", path, body);
|
|
660
|
+
async delete(path, body, options) {
|
|
661
|
+
return this.request("DELETE", path, body, void 0, void 0, options);
|
|
174
662
|
}
|
|
175
|
-
async request(method, path, body, query, extraHeaders) {
|
|
663
|
+
async request(method, path, body, query, extraHeaders, options) {
|
|
664
|
+
const signal = options?.signal;
|
|
665
|
+
throwIfAborted(signal);
|
|
176
666
|
const url = this.buildUrl(path, query);
|
|
177
667
|
const headers = {
|
|
178
668
|
"X-API-Key": this.apiKey,
|
|
@@ -184,116 +674,161 @@ var HttpClient = class {
|
|
|
184
674
|
if (body !== void 0) {
|
|
185
675
|
headers["Content-Type"] = "application/json";
|
|
186
676
|
}
|
|
187
|
-
const
|
|
677
|
+
const pacer = this.pacer;
|
|
678
|
+
const takesSlot = pacer !== void 0 && takesEnrichmentSlot(method, url);
|
|
679
|
+
let deadline = pacer ? Infinity : performance.now() + this.maxRetryTime;
|
|
680
|
+
const minRetryMs = pacer ? Math.min(1e3, this.timeout / 2) : 0;
|
|
188
681
|
const serializedBody = body !== void 0 ? JSON.stringify(body) : void 0;
|
|
189
682
|
let lastError;
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
683
|
+
let retryAt;
|
|
684
|
+
let permit;
|
|
685
|
+
const budgetExhausted = () => lastError ?? new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
686
|
+
try {
|
|
687
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
688
|
+
if (attempt > 0) {
|
|
689
|
+
const delay = retryAt === void 0 ? this.calculateDelay(attempt, lastError) : Math.max(0, retryAt - performance.now());
|
|
690
|
+
retryAt = void 0;
|
|
691
|
+
const cutoff = deadline - minRetryMs;
|
|
692
|
+
if (delay >= cutoff - performance.now()) {
|
|
693
|
+
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
694
|
+
}
|
|
695
|
+
if (permit) {
|
|
696
|
+
const wallOffset = Date.now() - performance.now();
|
|
697
|
+
permit = await permit.retry({
|
|
698
|
+
notBefore: Date.now() + delay,
|
|
699
|
+
deadline: cutoff + wallOffset,
|
|
700
|
+
signal,
|
|
701
|
+
expired: budgetExhausted
|
|
702
|
+
});
|
|
703
|
+
} else {
|
|
704
|
+
await sleep(delay, signal);
|
|
705
|
+
}
|
|
706
|
+
} else if (pacer) {
|
|
707
|
+
permit = await pacer.acquire({
|
|
708
|
+
slot: takesSlot,
|
|
709
|
+
deadline: Date.now() + pacer.maxWait,
|
|
710
|
+
signal,
|
|
711
|
+
expired: () => new PacingTimeoutError(
|
|
712
|
+
`Request waited ${pacer.maxWait}ms for its turn under pacing and was not sent: ${method} ${path}`
|
|
713
|
+
)
|
|
714
|
+
});
|
|
715
|
+
deadline = performance.now() + this.maxRetryTime;
|
|
716
|
+
}
|
|
717
|
+
throwIfAborted(signal);
|
|
718
|
+
const remainingMs = deadline - performance.now();
|
|
719
|
+
if (pacer && attempt > 0 && remainingMs < minRetryMs) {
|
|
194
720
|
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
195
721
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
203
|
-
const startMs = Date.now();
|
|
204
|
-
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
205
|
-
try {
|
|
206
|
-
const controller = new AbortController();
|
|
207
|
-
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
208
|
-
let response;
|
|
209
|
-
let responseBody;
|
|
722
|
+
if (remainingMs <= 0) {
|
|
723
|
+
throw new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
724
|
+
}
|
|
725
|
+
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
726
|
+
const startMs = Date.now();
|
|
727
|
+
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
210
728
|
try {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
729
|
+
const controller = new AbortController();
|
|
730
|
+
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
731
|
+
const unlink = signal ? onAbort(signal, () => controller.abort()) : void 0;
|
|
732
|
+
let response;
|
|
733
|
+
let responseBody;
|
|
734
|
+
try {
|
|
735
|
+
response = await fetch(url, {
|
|
736
|
+
method,
|
|
737
|
+
headers,
|
|
738
|
+
body: serializedBody,
|
|
739
|
+
signal: controller.signal
|
|
740
|
+
});
|
|
741
|
+
responseBody = await response.json().catch((err) => {
|
|
742
|
+
if (err instanceof SyntaxError || !response.ok) return null;
|
|
743
|
+
throw err;
|
|
744
|
+
});
|
|
745
|
+
if (controller.signal.aborted && response.ok) {
|
|
746
|
+
throw new DOMException("The operation was aborted.", "AbortError");
|
|
747
|
+
}
|
|
748
|
+
} finally {
|
|
749
|
+
clearTimeout(timeoutId);
|
|
750
|
+
unlink?.();
|
|
223
751
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
const durationMs = Date.now() - startMs;
|
|
229
|
-
this.onResponse?.({
|
|
230
|
-
status: response.status,
|
|
231
|
-
headers: responseHeaders,
|
|
232
|
-
body: responseBody,
|
|
233
|
-
durationMs,
|
|
234
|
-
retryCount: attempt
|
|
235
|
-
});
|
|
236
|
-
if (response.ok) {
|
|
237
|
-
return {
|
|
238
|
-
data: responseBody,
|
|
752
|
+
const responseHeaders = parseHeaders(response.headers);
|
|
753
|
+
const durationMs = Date.now() - startMs;
|
|
754
|
+
pacer?.observe(responseHeaders, takesSlot, response.status, startMs);
|
|
755
|
+
this.onResponse?.({
|
|
239
756
|
status: response.status,
|
|
240
757
|
headers: responseHeaders,
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
758
|
+
body: responseBody,
|
|
759
|
+
durationMs,
|
|
760
|
+
retryCount: attempt
|
|
761
|
+
});
|
|
762
|
+
if (response.ok) {
|
|
763
|
+
return {
|
|
764
|
+
data: responseBody,
|
|
765
|
+
status: response.status,
|
|
766
|
+
headers: responseHeaders,
|
|
767
|
+
rateLimitInfo: parseRateLimitHeaders(responseHeaders)
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
const error = this.mapError(response.status, responseBody, responseHeaders);
|
|
771
|
+
lastError = error;
|
|
772
|
+
if (pacer && error instanceof RateLimitError) {
|
|
773
|
+
const delay = this.rateLimitDelay(attempt + 1, error, responseHeaders);
|
|
774
|
+
retryAt = performance.now() + delay;
|
|
775
|
+
pacer.pause(error.rateLimitInfo.scope, delay, takesSlot, startMs);
|
|
776
|
+
}
|
|
777
|
+
const shouldRetry = this.canRetry(
|
|
258
778
|
attempt,
|
|
259
779
|
method,
|
|
260
780
|
headers,
|
|
261
|
-
isRetryableError(
|
|
781
|
+
isRetryableError(error)
|
|
262
782
|
);
|
|
263
|
-
if (!
|
|
264
|
-
throw err;
|
|
265
|
-
}
|
|
266
|
-
lastError = err;
|
|
267
|
-
continue;
|
|
268
|
-
}
|
|
269
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
270
|
-
lastError = new TimeoutError(
|
|
271
|
-
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
272
|
-
);
|
|
273
|
-
if (!this.canRetry(attempt, method, headers, true)) {
|
|
783
|
+
if (!shouldRetry) {
|
|
274
784
|
throw lastError;
|
|
275
785
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
786
|
+
} catch (err) {
|
|
787
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
788
|
+
if (err instanceof TriqaiError) {
|
|
789
|
+
const canRetry = this.canRetry(
|
|
790
|
+
attempt,
|
|
791
|
+
method,
|
|
792
|
+
headers,
|
|
793
|
+
isRetryableError(err)
|
|
794
|
+
);
|
|
795
|
+
if (!canRetry) {
|
|
796
|
+
throw err;
|
|
797
|
+
}
|
|
798
|
+
lastError = err;
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
802
|
+
lastError = new TimeoutError(
|
|
803
|
+
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
804
|
+
);
|
|
805
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
806
|
+
throw lastError;
|
|
807
|
+
}
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (isNetworkError(err)) {
|
|
811
|
+
lastError = new ConnectionError(
|
|
812
|
+
`Network error: ${err instanceof Error ? err.message : String(err)}`
|
|
813
|
+
);
|
|
814
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
815
|
+
throw lastError;
|
|
816
|
+
}
|
|
817
|
+
continue;
|
|
284
818
|
}
|
|
285
|
-
|
|
819
|
+
throw err;
|
|
286
820
|
}
|
|
287
|
-
throw err;
|
|
288
821
|
}
|
|
822
|
+
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
823
|
+
} finally {
|
|
824
|
+
permit?.release();
|
|
289
825
|
}
|
|
290
|
-
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
291
826
|
}
|
|
292
827
|
/**
|
|
293
828
|
* Variant that injects custom headers (used by resources for Idempotency-Key etc.).
|
|
294
829
|
*/
|
|
295
|
-
async postWithHeaders(path, body, headers, query) {
|
|
296
|
-
return this.request("POST", path, body, query, headers);
|
|
830
|
+
async postWithHeaders(path, body, headers, query, options) {
|
|
831
|
+
return this.request("POST", path, body, query, headers, options);
|
|
297
832
|
}
|
|
298
833
|
buildUrl(path, query) {
|
|
299
834
|
const isAbsoluteUrl = /^https?:\/\//i.test(path);
|
|
@@ -322,6 +857,22 @@ var HttpClient = class {
|
|
|
322
857
|
const exponential = Math.min(this.retryDelay * Math.pow(2, attempt - 1), this.maxRetryDelay / 1.2);
|
|
323
858
|
return exponential * (1 + 0.2 * Math.random());
|
|
324
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* The wait after a 429. Without Retry-After, the limit's reset time is used
|
|
862
|
+
* when it is near, measured against the response's Date header so the
|
|
863
|
+
* client's clock does not matter; otherwise the normal backoff.
|
|
864
|
+
*/
|
|
865
|
+
rateLimitDelay(attempt, error, headers) {
|
|
866
|
+
const { retryAfter, reset } = error.rateLimitInfo;
|
|
867
|
+
if (!retryAfter && reset !== void 0) {
|
|
868
|
+
const serverNow = headers.date === void 0 ? NaN : Date.parse(headers.date);
|
|
869
|
+
const untilReset = Date.parse(reset) - (Number.isNaN(serverNow) ? Date.now() : serverNow);
|
|
870
|
+
if (untilReset > 0 && untilReset <= MAX_RESET_WAIT_MS) {
|
|
871
|
+
return untilReset + Math.min(untilReset * 0.2, 1e3) * Math.random();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return this.calculateDelay(attempt, error);
|
|
875
|
+
}
|
|
325
876
|
canRetry(attempt, method, headers, retryableSignal) {
|
|
326
877
|
return retryableSignal && attempt < this.maxRetries && isIdempotent(method, headers);
|
|
327
878
|
}
|
|
@@ -454,7 +1005,7 @@ function isNetworkError(err) {
|
|
|
454
1005
|
const message = err.message.toLowerCase();
|
|
455
1006
|
const hasNetworkSignal = message.includes("fetch") || message.includes("network") || message.includes("econnreset") || message.includes("enotfound") || message.includes("econnrefused") || message.includes("etimedout");
|
|
456
1007
|
if (err instanceof TypeError) {
|
|
457
|
-
return hasNetworkSignal;
|
|
1008
|
+
return hasNetworkSignal || message === "terminated";
|
|
458
1009
|
}
|
|
459
1010
|
if (err.name === "NetworkError") {
|
|
460
1011
|
return true;
|
|
@@ -465,8 +1016,38 @@ function isNetworkError(err) {
|
|
|
465
1016
|
}
|
|
466
1017
|
return false;
|
|
467
1018
|
}
|
|
468
|
-
function
|
|
469
|
-
|
|
1019
|
+
function takesEnrichmentSlot(method, url) {
|
|
1020
|
+
if (method !== "POST") return false;
|
|
1021
|
+
const path = url.split("?")[0].replace(/\/+$/, "");
|
|
1022
|
+
return path.endsWith("/v1/transactions/enrich");
|
|
1023
|
+
}
|
|
1024
|
+
function pacingByDefault() {
|
|
1025
|
+
const g = globalThis;
|
|
1026
|
+
if (typeof g.process?.versions?.node !== "string") return false;
|
|
1027
|
+
if (g.Deno !== void 0 || g.EdgeRuntime !== void 0 || g.WebSocketPair !== void 0) return false;
|
|
1028
|
+
return g.navigator?.userAgent !== "Cloudflare-Workers";
|
|
1029
|
+
}
|
|
1030
|
+
function isPlainObject(value) {
|
|
1031
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1032
|
+
const proto = Object.getPrototypeOf(value);
|
|
1033
|
+
return proto === Object.prototype || proto === null;
|
|
1034
|
+
}
|
|
1035
|
+
function sleep(ms, signal) {
|
|
1036
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1037
|
+
return new Promise((resolve, reject) => {
|
|
1038
|
+
if (signal.aborted) {
|
|
1039
|
+
reject(abortReason(signal));
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
const timer = setTimeout(() => {
|
|
1043
|
+
unsubscribe();
|
|
1044
|
+
resolve();
|
|
1045
|
+
}, ms);
|
|
1046
|
+
const unsubscribe = onAbort(signal, () => {
|
|
1047
|
+
clearTimeout(timer);
|
|
1048
|
+
reject(abortReason(signal));
|
|
1049
|
+
});
|
|
1050
|
+
});
|
|
470
1051
|
}
|
|
471
1052
|
|
|
472
1053
|
// src/resources/banks.ts
|
|
@@ -475,13 +1056,13 @@ var Banks = class {
|
|
|
475
1056
|
this.http = http;
|
|
476
1057
|
}
|
|
477
1058
|
/** Exact, case-insensitive name lookup with an optional country of origin. Costs zero credits. */
|
|
478
|
-
async search(params) {
|
|
479
|
-
const resp = await this.http.get("/v1/banks", { ...params });
|
|
1059
|
+
async search(params, options) {
|
|
1060
|
+
const resp = await this.http.get("/v1/banks", { ...params }, options);
|
|
480
1061
|
return resp.data.data;
|
|
481
1062
|
}
|
|
482
1063
|
/** Retrieve stored bank details by UUID. */
|
|
483
|
-
async get(id) {
|
|
484
|
-
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}
|
|
1064
|
+
async get(id, options) {
|
|
1065
|
+
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}`, void 0, options);
|
|
485
1066
|
return resp.data.data.bank;
|
|
486
1067
|
}
|
|
487
1068
|
};
|
|
@@ -497,6 +1078,7 @@ var Categories = class {
|
|
|
497
1078
|
* Returns the full category tree used for transaction classification,
|
|
498
1079
|
* including MCC, SIC, and NAICS codes.
|
|
499
1080
|
*
|
|
1081
|
+
* @param options - Optional `signal` to cancel the call.
|
|
500
1082
|
* @returns Array of category info objects and the total count.
|
|
501
1083
|
*
|
|
502
1084
|
* @example
|
|
@@ -505,8 +1087,8 @@ var Categories = class {
|
|
|
505
1087
|
* console.log(`${total} categories available`);
|
|
506
1088
|
* ```
|
|
507
1089
|
*/
|
|
508
|
-
async list() {
|
|
509
|
-
const resp = await this.http.get("/v1/categories");
|
|
1090
|
+
async list(options) {
|
|
1091
|
+
const resp = await this.http.get("/v1/categories", void 0, options);
|
|
510
1092
|
return {
|
|
511
1093
|
categories: resp.data.data.categories,
|
|
512
1094
|
total: resp.data.data.total,
|
|
@@ -524,6 +1106,7 @@ var Intermediaries = class {
|
|
|
524
1106
|
* Get an intermediary (payment processor / platform) by ID.
|
|
525
1107
|
*
|
|
526
1108
|
* @param id - Intermediary UUID.
|
|
1109
|
+
* @param options - Optional `signal` to cancel the call.
|
|
527
1110
|
* @returns The intermediary data (name, icon, description, website, domain, etc.).
|
|
528
1111
|
*
|
|
529
1112
|
* @example
|
|
@@ -532,9 +1115,11 @@ var Intermediaries = class {
|
|
|
532
1115
|
* console.log(intermediary.name); // "PayPal", "Square", etc.
|
|
533
1116
|
* ```
|
|
534
1117
|
*/
|
|
535
|
-
async get(id) {
|
|
1118
|
+
async get(id, options) {
|
|
536
1119
|
const resp = await this.http.get(
|
|
537
|
-
`/v1/intermediaries/${encodeURIComponent(id)}
|
|
1120
|
+
`/v1/intermediaries/${encodeURIComponent(id)}`,
|
|
1121
|
+
void 0,
|
|
1122
|
+
options
|
|
538
1123
|
);
|
|
539
1124
|
return resp.data.data.intermediary;
|
|
540
1125
|
}
|
|
@@ -617,12 +1202,12 @@ var IssueReports = class {
|
|
|
617
1202
|
* console.log(report.id, report.status);
|
|
618
1203
|
* ```
|
|
619
1204
|
*/
|
|
620
|
-
async create(params) {
|
|
1205
|
+
async create(params, options) {
|
|
621
1206
|
const resp = await this.http.post("/v1/report-issue", {
|
|
622
1207
|
transaction_id: params.transactionId,
|
|
623
1208
|
description: params.description,
|
|
624
1209
|
fields: params.fields
|
|
625
|
-
});
|
|
1210
|
+
}, options);
|
|
626
1211
|
return resp.data.data.issueReport;
|
|
627
1212
|
}
|
|
628
1213
|
/**
|
|
@@ -639,12 +1224,12 @@ var IssueReports = class {
|
|
|
639
1224
|
* }
|
|
640
1225
|
* ```
|
|
641
1226
|
*/
|
|
642
|
-
async list(params) {
|
|
1227
|
+
async list(params, options) {
|
|
643
1228
|
const fetchPage = async (page, size) => {
|
|
644
1229
|
const query = { page, size };
|
|
645
1230
|
if (params?.status) query.status = params.status;
|
|
646
1231
|
if (params?.transactionId) query.transaction_id = params.transactionId;
|
|
647
|
-
const resp = await this.http.get("/v1/report-issue", query);
|
|
1232
|
+
const resp = await this.http.get("/v1/report-issue", query, options);
|
|
648
1233
|
const pageInfo = {
|
|
649
1234
|
page: resp.data.meta.page,
|
|
650
1235
|
size: resp.data.meta.size,
|
|
@@ -659,11 +1244,14 @@ var IssueReports = class {
|
|
|
659
1244
|
* Get a single issue report by ID.
|
|
660
1245
|
*
|
|
661
1246
|
* @param id - Issue report UUID.
|
|
1247
|
+
* @param options - Optional `signal` to cancel the call.
|
|
662
1248
|
* @returns The issue report details.
|
|
663
1249
|
*/
|
|
664
|
-
async get(id) {
|
|
1250
|
+
async get(id, options) {
|
|
665
1251
|
const resp = await this.http.get(
|
|
666
|
-
`/v1/report-issue/${encodeURIComponent(id)}
|
|
1252
|
+
`/v1/report-issue/${encodeURIComponent(id)}`,
|
|
1253
|
+
void 0,
|
|
1254
|
+
options
|
|
667
1255
|
);
|
|
668
1256
|
return resp.data.data.issueReport;
|
|
669
1257
|
}
|
|
@@ -678,6 +1266,7 @@ var Locations = class {
|
|
|
678
1266
|
* Get a location by ID.
|
|
679
1267
|
*
|
|
680
1268
|
* @param id - Location UUID.
|
|
1269
|
+
* @param options - Optional `signal` to cancel the call.
|
|
681
1270
|
* @returns The location data (name, formatted address, coordinates, phone, rating, etc.).
|
|
682
1271
|
*
|
|
683
1272
|
* @example
|
|
@@ -686,9 +1275,11 @@ var Locations = class {
|
|
|
686
1275
|
* console.log(location.formatted, location.structured.city);
|
|
687
1276
|
* ```
|
|
688
1277
|
*/
|
|
689
|
-
async get(id) {
|
|
1278
|
+
async get(id, options) {
|
|
690
1279
|
const resp = await this.http.get(
|
|
691
|
-
`/v1/locations/${encodeURIComponent(id)}
|
|
1280
|
+
`/v1/locations/${encodeURIComponent(id)}`,
|
|
1281
|
+
void 0,
|
|
1282
|
+
options
|
|
692
1283
|
);
|
|
693
1284
|
return resp.data.data.location;
|
|
694
1285
|
}
|
|
@@ -703,6 +1294,7 @@ var Merchants = class {
|
|
|
703
1294
|
* Get a merchant by ID.
|
|
704
1295
|
*
|
|
705
1296
|
* @param id - Merchant UUID.
|
|
1297
|
+
* @param options - Optional `signal` to cancel the call.
|
|
706
1298
|
* @returns The merchant data (name, icon, website, domain, aliases, etc.).
|
|
707
1299
|
*
|
|
708
1300
|
* @example
|
|
@@ -711,9 +1303,11 @@ var Merchants = class {
|
|
|
711
1303
|
* console.log(merchant.name, merchant.website);
|
|
712
1304
|
* ```
|
|
713
1305
|
*/
|
|
714
|
-
async get(id) {
|
|
1306
|
+
async get(id, options) {
|
|
715
1307
|
const resp = await this.http.get(
|
|
716
|
-
`/v1/merchants/${encodeURIComponent(id)}
|
|
1308
|
+
`/v1/merchants/${encodeURIComponent(id)}`,
|
|
1309
|
+
void 0,
|
|
1310
|
+
options
|
|
717
1311
|
);
|
|
718
1312
|
return resp.data.data.merchant;
|
|
719
1313
|
}
|
|
@@ -737,7 +1331,7 @@ var Transactions = class {
|
|
|
737
1331
|
* Enrich a transaction with merchant, category, location, and entity data.
|
|
738
1332
|
*
|
|
739
1333
|
* @param request - The transaction to enrich (title, country, type, and optional options).
|
|
740
|
-
* @param options - Optional
|
|
1334
|
+
* @param options - Optional idempotency key and `signal` to cancel the call.
|
|
741
1335
|
* @returns The enriched transaction data.
|
|
742
1336
|
*
|
|
743
1337
|
* @example
|
|
@@ -757,7 +1351,9 @@ var Transactions = class {
|
|
|
757
1351
|
const resp = await this.http.postWithHeaders(
|
|
758
1352
|
"/v1/transactions/enrich",
|
|
759
1353
|
request,
|
|
760
|
-
headers
|
|
1354
|
+
headers,
|
|
1355
|
+
void 0,
|
|
1356
|
+
{ signal: options?.signal }
|
|
761
1357
|
);
|
|
762
1358
|
return resp.data;
|
|
763
1359
|
}
|
|
@@ -778,7 +1374,7 @@ var Transactions = class {
|
|
|
778
1374
|
* }
|
|
779
1375
|
* ```
|
|
780
1376
|
*/
|
|
781
|
-
async list(params) {
|
|
1377
|
+
async list(params, options) {
|
|
782
1378
|
const fetchPage = async (page, size) => {
|
|
783
1379
|
const query = {
|
|
784
1380
|
page,
|
|
@@ -790,7 +1386,7 @@ var Transactions = class {
|
|
|
790
1386
|
if (params?.endDate) {
|
|
791
1387
|
query.endDate = params.endDate instanceof Date ? params.endDate.toISOString() : params.endDate;
|
|
792
1388
|
}
|
|
793
|
-
const resp = await this.http.get("/v1/transactions", query);
|
|
1389
|
+
const resp = await this.http.get("/v1/transactions", query, options);
|
|
794
1390
|
const { transactions, pagination } = resp.data.data;
|
|
795
1391
|
return new Page(transactions, pagination, fetchPage);
|
|
796
1392
|
};
|
|
@@ -807,23 +1403,26 @@ var Transactions = class {
|
|
|
807
1403
|
* const { count } = await triqai.transactions.count({ afterDate: "2026-01-01T00:00:00Z" });
|
|
808
1404
|
* ```
|
|
809
1405
|
*/
|
|
810
|
-
async count(params) {
|
|
1406
|
+
async count(params, options) {
|
|
811
1407
|
const query = {};
|
|
812
1408
|
if (params?.afterDate) {
|
|
813
1409
|
query.afterDate = params.afterDate instanceof Date ? params.afterDate.toISOString() : params.afterDate;
|
|
814
1410
|
}
|
|
815
|
-
const resp = await this.http.get("/v1/transactions/count", query);
|
|
1411
|
+
const resp = await this.http.get("/v1/transactions/count", query, options);
|
|
816
1412
|
return resp.data.data;
|
|
817
1413
|
}
|
|
818
1414
|
/**
|
|
819
1415
|
* Get a single transaction by ID.
|
|
820
1416
|
*
|
|
821
1417
|
* @param id - Transaction UUID.
|
|
1418
|
+
* @param options - Optional `signal` to cancel the call.
|
|
822
1419
|
* @returns The enriched transaction record.
|
|
823
1420
|
*/
|
|
824
|
-
async get(id) {
|
|
1421
|
+
async get(id, options) {
|
|
825
1422
|
const resp = await this.http.get(
|
|
826
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1423
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1424
|
+
void 0,
|
|
1425
|
+
options
|
|
827
1426
|
);
|
|
828
1427
|
return resp.data.data.transaction;
|
|
829
1428
|
}
|
|
@@ -831,11 +1430,14 @@ var Transactions = class {
|
|
|
831
1430
|
* Delete a transaction by ID.
|
|
832
1431
|
*
|
|
833
1432
|
* @param id - Transaction UUID.
|
|
1433
|
+
* @param options - Optional `signal` to cancel the call.
|
|
834
1434
|
* @returns Confirmation with the deleted transaction ID.
|
|
835
1435
|
*/
|
|
836
|
-
async delete(id) {
|
|
1436
|
+
async delete(id, options) {
|
|
837
1437
|
const resp = await this.http.delete(
|
|
838
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1438
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1439
|
+
void 0,
|
|
1440
|
+
options
|
|
839
1441
|
);
|
|
840
1442
|
return resp.data.data;
|
|
841
1443
|
}
|
|
@@ -858,9 +1460,9 @@ var Transactions = class {
|
|
|
858
1460
|
* });
|
|
859
1461
|
* ```
|
|
860
1462
|
*/
|
|
861
|
-
async batchDelete(request) {
|
|
1463
|
+
async batchDelete(request, options) {
|
|
862
1464
|
const body = "afterDate" in request && request.afterDate instanceof Date ? { ...request, afterDate: request.afterDate.toISOString() } : request;
|
|
863
|
-
const resp = await this.http.delete("/v1/transactions/batch", body);
|
|
1465
|
+
const resp = await this.http.delete("/v1/transactions/batch", body, options);
|
|
864
1466
|
return resp.data.data;
|
|
865
1467
|
}
|
|
866
1468
|
};
|
|
@@ -910,8 +1512,8 @@ var Triqai = class {
|
|
|
910
1512
|
* console.log(health.data.version); // "1.1.9"
|
|
911
1513
|
* ```
|
|
912
1514
|
*/
|
|
913
|
-
async health() {
|
|
914
|
-
const resp = await this.http.get("/health");
|
|
1515
|
+
async health(options) {
|
|
1516
|
+
const resp = await this.http.get("/health", void 0, options);
|
|
915
1517
|
return resp.data;
|
|
916
1518
|
}
|
|
917
1519
|
/**
|
|
@@ -926,8 +1528,8 @@ var Triqai = class {
|
|
|
926
1528
|
* console.log(info.data.endpoints);
|
|
927
1529
|
* ```
|
|
928
1530
|
*/
|
|
929
|
-
async apiInfo() {
|
|
930
|
-
const resp = await this.http.get("/v1");
|
|
1531
|
+
async apiInfo(options) {
|
|
1532
|
+
const resp = await this.http.get("/v1", void 0, options);
|
|
931
1533
|
return resp.data;
|
|
932
1534
|
}
|
|
933
1535
|
/**
|
|
@@ -936,10 +1538,11 @@ var Triqai = class {
|
|
|
936
1538
|
*
|
|
937
1539
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
938
1540
|
* @param query - Optional query parameters.
|
|
1541
|
+
* @param options - Optional `signal` to cancel the call.
|
|
939
1542
|
* @returns The full HTTP response including headers and rate limit info.
|
|
940
1543
|
*/
|
|
941
|
-
async rawGet(path, query) {
|
|
942
|
-
return this.http.get(path, query);
|
|
1544
|
+
async rawGet(path, query, options) {
|
|
1545
|
+
return this.http.get(path, query, options);
|
|
943
1546
|
}
|
|
944
1547
|
/**
|
|
945
1548
|
* Make a raw POST request to any API path.
|
|
@@ -947,26 +1550,28 @@ var Triqai = class {
|
|
|
947
1550
|
*
|
|
948
1551
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
949
1552
|
* @param body - Request body.
|
|
1553
|
+
* @param options - Optional `signal` to cancel the call.
|
|
950
1554
|
* @returns The full HTTP response including headers and rate limit info.
|
|
951
1555
|
*/
|
|
952
|
-
async rawPost(path, body) {
|
|
953
|
-
return this.http.post(path, body);
|
|
1556
|
+
async rawPost(path, body, options) {
|
|
1557
|
+
return this.http.post(path, body, options);
|
|
954
1558
|
}
|
|
955
1559
|
/**
|
|
956
1560
|
* Make a raw DELETE request to any API path.
|
|
957
1561
|
* Useful for accessing endpoints not yet covered by a resource class.
|
|
958
1562
|
*
|
|
959
1563
|
* @param path - API path (e.g. "/v1/some-resource/uuid").
|
|
1564
|
+
* @param options - Optional `signal` to cancel the call.
|
|
960
1565
|
* @returns The full HTTP response including headers and rate limit info.
|
|
961
1566
|
*/
|
|
962
|
-
async rawDelete(path) {
|
|
963
|
-
return this.http.delete(path);
|
|
1567
|
+
async rawDelete(path, options) {
|
|
1568
|
+
return this.http.delete(path, void 0, options);
|
|
964
1569
|
}
|
|
965
1570
|
};
|
|
966
1571
|
|
|
967
1572
|
// src/index.ts
|
|
968
1573
|
var index_default = Triqai;
|
|
969
1574
|
|
|
970
|
-
export { AuthenticationError, AuthorizationError, ClientDisconnectedError, ConnectionError, DuplicateRequestError, GatewayTimeoutError, GoneError, InsufficientCreditsError, InternalServerError, NotFoundError, Page, RateLimitError, ServiceUnavailableError, TimeoutError, Triqai, TriqaiError, ValidationError, index_default as default };
|
|
1575
|
+
export { AuthenticationError, AuthorizationError, ClientDisconnectedError, ConnectionError, DuplicateRequestError, GatewayTimeoutError, GoneError, InsufficientCreditsError, InternalServerError, NotFoundError, PacingTimeoutError, Page, RateLimitError, ServiceUnavailableError, TimeoutError, Triqai, TriqaiError, ValidationError, index_default as default };
|
|
971
1576
|
//# sourceMappingURL=index.js.map
|
|
972
1577
|
//# sourceMappingURL=index.js.map
|