@delopay/sdk 0.165.0 → 0.166.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
@@ -1179,6 +1179,289 @@ var Customers = class {
1179
1179
  }
1180
1180
  };
1181
1181
 
1182
+ // src/recordCounter.ts
1183
+ var LF = 10;
1184
+ var CR = 13;
1185
+ var QUOTE = 34;
1186
+ var BACKSLASH = 92;
1187
+ var OPEN_BRACE = 123;
1188
+ var CLOSE_BRACE = 125;
1189
+ var OPEN_BRACKET = 91;
1190
+ var CLOSE_BRACKET = 93;
1191
+ var CsvRecordCounter = class {
1192
+ constructor() {
1193
+ this.inQuotes = false;
1194
+ this.newlines = 0;
1195
+ /** Whether anything but a line break has arrived since the last newline. */
1196
+ this.lineHasContent = false;
1197
+ }
1198
+ push(chunk) {
1199
+ let inQuotes = this.inQuotes;
1200
+ let newlines = this.newlines;
1201
+ let lineHasContent = this.lineHasContent;
1202
+ for (const byte of chunk) {
1203
+ if (byte === QUOTE) {
1204
+ inQuotes = !inQuotes;
1205
+ lineHasContent = true;
1206
+ } else if (inQuotes) {
1207
+ lineHasContent = true;
1208
+ } else if (byte === LF) {
1209
+ newlines++;
1210
+ lineHasContent = false;
1211
+ } else if (byte !== CR) {
1212
+ lineHasContent = true;
1213
+ }
1214
+ }
1215
+ this.inQuotes = inQuotes;
1216
+ this.newlines = newlines;
1217
+ this.lineHasContent = lineHasContent;
1218
+ }
1219
+ get records() {
1220
+ return Math.max(0, this.newlines - 1);
1221
+ }
1222
+ /**
1223
+ * The export writer ends every line — the header and each record — with a
1224
+ * newline, so a whole body ends on one, outside quotes. RFC 4180 lets a
1225
+ * final line break be omitted, but these bodies never omit it, and without
1226
+ * that rule a file cut part-way through its last unquoted field
1227
+ * (`pay_1,12` of `pay_1,123`) would count as one more whole record and
1228
+ * match the figure it was announced with.
1229
+ */
1230
+ get complete() {
1231
+ return this.newlines >= 1 && !this.inQuotes && !this.lineHasContent;
1232
+ }
1233
+ /**
1234
+ * The records that ended. An unterminated tail is not one of them — see
1235
+ * {@link complete}.
1236
+ */
1237
+ finish() {
1238
+ return this.records;
1239
+ }
1240
+ };
1241
+ var SEEKING = 0;
1242
+ var COUNTING = 1;
1243
+ var CLOSED = 2;
1244
+ var JsonArrayRecordCounter = class {
1245
+ constructor() {
1246
+ this.depth = 0;
1247
+ this.inString = false;
1248
+ this.escaped = false;
1249
+ this.topIsObject = false;
1250
+ this.state = SEEKING;
1251
+ this.count = 0;
1252
+ }
1253
+ push(chunk) {
1254
+ if (this.state === CLOSED) return;
1255
+ let { depth, inString, escaped, topIsObject, count } = this;
1256
+ let state = this.state;
1257
+ for (const byte of chunk) {
1258
+ if (inString) {
1259
+ if (escaped) escaped = false;
1260
+ else if (byte === BACKSLASH) escaped = true;
1261
+ else if (byte === QUOTE) inString = false;
1262
+ continue;
1263
+ }
1264
+ if (byte === QUOTE) {
1265
+ inString = true;
1266
+ } else if (byte === OPEN_BRACE || byte === OPEN_BRACKET) {
1267
+ if (depth === 0 && byte === OPEN_BRACE) topIsObject = true;
1268
+ if (byte === OPEN_BRACKET && depth === 1 && topIsObject && state === SEEKING) {
1269
+ state = COUNTING;
1270
+ }
1271
+ depth++;
1272
+ } else if (byte === CLOSE_BRACE || byte === CLOSE_BRACKET) {
1273
+ depth--;
1274
+ if (state === COUNTING) {
1275
+ if (depth === 2) count++;
1276
+ else if (depth === 1) {
1277
+ state = CLOSED;
1278
+ break;
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ this.depth = depth;
1284
+ this.inString = inString;
1285
+ this.escaped = escaped;
1286
+ this.topIsObject = topIsObject;
1287
+ this.state = state;
1288
+ this.count = count;
1289
+ }
1290
+ get records() {
1291
+ return this.count;
1292
+ }
1293
+ /**
1294
+ * Whether the rows array has closed. What follows it is checked by parsing
1295
+ * the whole document, which a cut-off body fails.
1296
+ */
1297
+ get complete() {
1298
+ return this.state === CLOSED;
1299
+ }
1300
+ finish() {
1301
+ return this.count;
1302
+ }
1303
+ };
1304
+
1305
+ // src/exportDownload.ts
1306
+ var RECORD_COUNT_HEADER = "x-delopay-record-count";
1307
+ var LIST_ENVELOPE = { rows: "records", count: "record_count" };
1308
+ var WORKSPACE_ENVELOPE = { rows: "data", count: "total_count" };
1309
+ function parseRecordCount(header) {
1310
+ if (header === null) return null;
1311
+ const trimmed = header.trim();
1312
+ if (!/^\d+$/.test(trimmed)) return null;
1313
+ const value = Number(trimmed);
1314
+ return Number.isSafeInteger(value) ? value : null;
1315
+ }
1316
+ function counterFor(format) {
1317
+ if (format === "csv") return new CsvRecordCounter();
1318
+ if (format === "json") return new JsonArrayRecordCounter();
1319
+ return null;
1320
+ }
1321
+ function isRecord(value) {
1322
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1323
+ }
1324
+ function announced(expected) {
1325
+ return expected === null ? "" : ` of the ${expected} announced`;
1326
+ }
1327
+ function incomplete(message, expected, received, requestId) {
1328
+ return new DelopayError(message, {
1329
+ status: 0,
1330
+ code: "EXPORT_INCOMPLETE",
1331
+ type: "export_incomplete",
1332
+ ...requestId !== void 0 ? { requestId } : {},
1333
+ data: { expected_records: expected, received_records: received }
1334
+ });
1335
+ }
1336
+ async function downloadExport(request, call, options) {
1337
+ const { format } = call;
1338
+ const envelope = call.envelope ?? LIST_ENVELOPE;
1339
+ const onProgress = options?.onProgress;
1340
+ let latest = {
1341
+ phase: "preparing",
1342
+ receivedBytes: 0,
1343
+ totalBytes: null,
1344
+ receivedRecords: 0,
1345
+ expectedRecords: null
1346
+ };
1347
+ const seen = { attempt: -1, counter: null, expected: null, requestId: void 0, listenerError: null };
1348
+ const report = (progress) => {
1349
+ latest = progress;
1350
+ if (!onProgress) return;
1351
+ try {
1352
+ onProgress({ ...progress });
1353
+ } catch (error) {
1354
+ seen.listenerError = { error };
1355
+ throw error;
1356
+ }
1357
+ };
1358
+ report(latest);
1359
+ const onDownloadProgress = (event) => {
1360
+ if (event.attempt !== seen.attempt) {
1361
+ seen.attempt = event.attempt;
1362
+ seen.counter = counterFor(format);
1363
+ seen.expected = format === "pdf" ? null : parseRecordCount(event.headers.get(RECORD_COUNT_HEADER));
1364
+ seen.requestId = event.headers.get("x-request-id") ?? event.headers.get("x-trace-id") ?? void 0;
1365
+ }
1366
+ if (event.chunk.byteLength > 0) seen.counter?.push(event.chunk);
1367
+ report({
1368
+ phase: "receiving",
1369
+ receivedBytes: event.loaded,
1370
+ totalBytes: event.total,
1371
+ receivedRecords: seen.counter?.records ?? 0,
1372
+ expectedRecords: seen.expected
1373
+ });
1374
+ };
1375
+ let result;
1376
+ try {
1377
+ result = await request(call.method, call.path, {
1378
+ ...call.request,
1379
+ ...options?.signal !== void 0 ? { signal: options.signal } : {},
1380
+ ...options?.timeout !== void 0 ? { timeout: options.timeout } : {},
1381
+ onDownloadProgress
1382
+ });
1383
+ } catch (err) {
1384
+ if (seen.listenerError !== null && err === seen.listenerError.error) throw err;
1385
+ if (format === "json" && seen.attempt >= 0 && err instanceof SyntaxError) {
1386
+ const received2 = seen.counter?.records ?? 0;
1387
+ throw incomplete(
1388
+ seen.expected === null ? `Export incomplete: the body ended part-way through the JSON document, after ${received2} records` : `Export incomplete: the server announced ${seen.expected} records, and the body ended part-way through the JSON document after ${received2}`,
1389
+ seen.expected,
1390
+ received2,
1391
+ seen.requestId
1392
+ );
1393
+ }
1394
+ throw err;
1395
+ }
1396
+ const { expected, requestId } = seen;
1397
+ let received = 0;
1398
+ if (format === "json") {
1399
+ const rows = isRecord(result) ? result[envelope.rows] : void 0;
1400
+ if (!Array.isArray(rows)) {
1401
+ throw incomplete(
1402
+ `Export incomplete: the body is not an export envelope with a "${envelope.rows}" array, so it carries 0 records${announced(expected)}`,
1403
+ expected,
1404
+ 0,
1405
+ requestId
1406
+ );
1407
+ }
1408
+ received = rows.length;
1409
+ const declared = isRecord(result) ? result[envelope.count] : void 0;
1410
+ if (typeof declared === "number" && declared !== rows.length) {
1411
+ throw incomplete(
1412
+ `Export incomplete: the file's ${envelope.count} is ${declared}, but it carries ${rows.length} records`,
1413
+ declared,
1414
+ rows.length,
1415
+ requestId
1416
+ );
1417
+ }
1418
+ } else if (format === "csv") {
1419
+ const counter = seen.counter;
1420
+ received = counter?.finish() ?? 0;
1421
+ if (!counter?.complete) {
1422
+ throw incomplete(
1423
+ `Export incomplete: the CSV body ended part-way through a line, after ${received} complete records${announced(expected)}`,
1424
+ expected,
1425
+ received,
1426
+ requestId
1427
+ );
1428
+ }
1429
+ }
1430
+ if (expected !== null && received !== expected) {
1431
+ throw incomplete(
1432
+ `Export incomplete: the server announced ${expected} records, and the body carried ${received}`,
1433
+ expected,
1434
+ received,
1435
+ requestId
1436
+ );
1437
+ }
1438
+ report({
1439
+ phase: "done",
1440
+ receivedBytes: latest.receivedBytes,
1441
+ totalBytes: latest.totalBytes,
1442
+ receivedRecords: received,
1443
+ expectedRecords: expected
1444
+ });
1445
+ return result;
1446
+ }
1447
+ var ACCEPT = {
1448
+ csv: "text/csv",
1449
+ json: "application/json",
1450
+ pdf: "application/pdf"
1451
+ };
1452
+ function negotiated(options, format) {
1453
+ const headers = { ...options.headers, Accept: ACCEPT[format] };
1454
+ return format === "json" ? { ...options, headers } : { ...options, headers, responseType: "blob" };
1455
+ }
1456
+ function runExport(request, method, path, base, options) {
1457
+ const format = options?.format ?? "json";
1458
+ return downloadExport(
1459
+ request,
1460
+ { method, path, request: negotiated(base, format), format },
1461
+ options
1462
+ );
1463
+ }
1464
+
1182
1465
  // src/resources/disputes.ts
1183
1466
  function workspaceQuery(params) {
1184
1467
  if (!params) return void 0;
@@ -1207,9 +1490,28 @@ var Disputes = class {
1207
1490
  async workspaceAggregate(params) {
1208
1491
  return this.request("GET", "/disputes/workspace/aggregate", { query: workspaceQuery(params) });
1209
1492
  }
1210
- /** Export the complete filtered set, or throw on the server's explicit export-limit refusal. */
1211
- async workspaceExport(params) {
1212
- return this.request("GET", "/disputes/workspace/export", { query: workspaceQuery(params) });
1493
+ /**
1494
+ * Export the complete filtered set, or throw on the server's explicit
1495
+ * export-limit refusal. `GET /disputes/workspace/export`
1496
+ *
1497
+ * The body is streamed, and held to the `X-Delopay-Record-Count` the server
1498
+ * announces and to its own `total_count`: a set that arrives short rejects
1499
+ * with `EXPORT_INCOMPLETE` rather than resolving. `options` reports the
1500
+ * download's progress and takes a signal and an idle timeout — see
1501
+ * {@link ExportTransferOptions}.
1502
+ */
1503
+ async workspaceExport(params, options) {
1504
+ return downloadExport(
1505
+ this.request,
1506
+ {
1507
+ method: "GET",
1508
+ path: "/disputes/workspace/export",
1509
+ request: { query: workspaceQuery(params) },
1510
+ format: "json",
1511
+ envelope: WORKSPACE_ENVELOPE
1512
+ },
1513
+ options
1514
+ );
1213
1515
  }
1214
1516
  /**
1215
1517
  * Retrieve a dispute by its ID.
@@ -4366,77 +4668,68 @@ var Export = class {
4366
4668
  this.request = request;
4367
4669
  }
4368
4670
  async transactions(params, options) {
4369
- return this.request(
4370
- "POST",
4371
- "/export/transactions",
4372
- transactionBody(params, options)
4373
- );
4671
+ return runExport(this.request, "POST", "/export/transactions", { body: params ?? {} }, options);
4374
4672
  }
4375
4673
  async transactionsForProfile(params, options) {
4376
- return this.request(
4674
+ return runExport(
4675
+ this.request,
4377
4676
  "POST",
4378
4677
  "/export/profile/transactions",
4379
- transactionBody(params, options)
4678
+ { body: params ?? {} },
4679
+ options
4380
4680
  );
4381
4681
  }
4382
4682
  async refunds(params, options) {
4383
- return this.request("POST", "/refunds/list/export", bodied(params ?? {}, options));
4683
+ return runExport(this.request, "POST", "/refunds/list/export", { body: params ?? {} }, options);
4384
4684
  }
4385
4685
  async refundsForProfile(params, options) {
4386
- return this.request(
4686
+ return runExport(
4687
+ this.request,
4387
4688
  "POST",
4388
4689
  "/refunds/profile/list/export",
4389
- bodied(params ?? {}, options)
4690
+ { body: params ?? {} },
4691
+ options
4390
4692
  );
4391
4693
  }
4392
4694
  async disputes(params, options) {
4393
- return this.request("GET", "/disputes/list/export", queried(params, options));
4695
+ return runExport(this.request, "GET", "/disputes/list/export", queried(params), options);
4394
4696
  }
4395
4697
  async disputesForProfile(params, options) {
4396
- return this.request(
4698
+ return runExport(
4699
+ this.request,
4397
4700
  "GET",
4398
4701
  "/disputes/profile/list/export",
4399
- queried(params, options)
4702
+ queried(params),
4703
+ options
4400
4704
  );
4401
4705
  }
4402
4706
  async payouts(params, options) {
4403
- return this.request("POST", "/payouts/list/export", bodied(params, options));
4707
+ return runExport(this.request, "POST", "/payouts/list/export", { body: params }, options);
4404
4708
  }
4405
4709
  async payoutsForProfile(params, options) {
4406
- return this.request("POST", "/payouts/profile/list/export", bodied(params, options));
4710
+ return runExport(
4711
+ this.request,
4712
+ "POST",
4713
+ "/payouts/profile/list/export",
4714
+ { body: params },
4715
+ options
4716
+ );
4407
4717
  }
4408
4718
  async subscriptions(profileId, params, options) {
4409
- return this.request(
4719
+ return runExport(
4720
+ this.request,
4410
4721
  "GET",
4411
4722
  "/subscriptions/list/export",
4412
- queried(params, options, { "X-Profile-Id": profileId })
4723
+ queried(params, { "X-Profile-Id": profileId }),
4724
+ options
4413
4725
  );
4414
4726
  }
4415
4727
  async auditLog(params, options) {
4416
- return this.request("GET", "/audit/export", queried(params, options));
4728
+ return runExport(this.request, "GET", "/audit/export", queried(params), options);
4417
4729
  }
4418
4730
  };
4419
- var ACCEPT = {
4420
- csv: "text/csv",
4421
- json: "application/json",
4422
- pdf: "application/pdf"
4423
- };
4424
- function negotiated(options, format) {
4425
- const headers = { ...options.headers, Accept: ACCEPT[format] };
4426
- return format === "json" ? { ...options, headers } : { ...options, headers, responseType: "blob" };
4427
- }
4428
- function transactionBody(params, options) {
4429
- const format = options?.format ?? "json";
4430
- return negotiated({ body: { ...params, format } }, format);
4431
- }
4432
- function bodied(body, options) {
4433
- return negotiated({ body }, options?.format ?? "json");
4434
- }
4435
- function queried(params, options, headers) {
4436
- return negotiated(
4437
- { query: params ?? {}, ...headers ? { headers } : {} },
4438
- options?.format ?? "json"
4439
- );
4731
+ function queried(params, headers) {
4732
+ return { query: params ?? {}, ...headers ? { headers } : {} };
4440
4733
  }
4441
4734
 
4442
4735
  // src/resources/featureMatrix.ts
@@ -5809,6 +6102,112 @@ function findIdempotencyKey(headers) {
5809
6102
  }
5810
6103
  function noop() {
5811
6104
  }
6105
+ var ListenerFailure = class {
6106
+ constructor(cause) {
6107
+ this.cause = cause;
6108
+ }
6109
+ };
6110
+ var BodyStreamFailure = class {
6111
+ constructor(cause) {
6112
+ this.cause = cause;
6113
+ }
6114
+ };
6115
+ function abortError() {
6116
+ const error = new Error("The operation was aborted");
6117
+ error.name = "AbortError";
6118
+ return error;
6119
+ }
6120
+ function parseContentLength(header) {
6121
+ if (header === null || !/^\s*\d+\s*$/.test(header)) return null;
6122
+ const value = Number(header);
6123
+ return Number.isSafeInteger(value) ? value : null;
6124
+ }
6125
+ function readChunk(reader, signal) {
6126
+ if (signal.aborted) return Promise.reject(abortError());
6127
+ return new Promise((resolve, reject) => {
6128
+ const onAbort = () => reject(abortError());
6129
+ signal.addEventListener("abort", onAbort, { once: true });
6130
+ reader.read().then(
6131
+ (result) => {
6132
+ signal.removeEventListener("abort", onAbort);
6133
+ resolve(result);
6134
+ },
6135
+ (cause) => {
6136
+ signal.removeEventListener("abort", onAbort);
6137
+ reject(signal.aborted ? abortError() : new BodyStreamFailure(cause));
6138
+ }
6139
+ );
6140
+ });
6141
+ }
6142
+ function concatChunks(chunks, length) {
6143
+ const out = new Uint8Array(length);
6144
+ let offset = 0;
6145
+ for (const chunk of chunks) {
6146
+ out.set(chunk, offset);
6147
+ offset += chunk.byteLength;
6148
+ }
6149
+ return out.buffer;
6150
+ }
6151
+ async function receiveWithProgress(response, responseType, listener, attempt, signal, onActivity) {
6152
+ const headers = response.headers ?? new Headers();
6153
+ const total = parseContentLength(headers.get("content-length"));
6154
+ let loaded = 0;
6155
+ const notify = (chunk) => {
6156
+ try {
6157
+ listener({ loaded, total, chunk: chunk.slice(), headers, attempt });
6158
+ } catch (cause) {
6159
+ throw new ListenerFailure(cause);
6160
+ }
6161
+ };
6162
+ onActivity();
6163
+ notify(new Uint8Array(0));
6164
+ const body = response.body;
6165
+ if (!body || typeof body.getReader !== "function") {
6166
+ if (responseType === "blob") {
6167
+ const blob = await response.blob();
6168
+ const bytes3 = new Uint8Array(await blob.arrayBuffer());
6169
+ loaded = bytes3.byteLength;
6170
+ if (loaded > 0) notify(bytes3);
6171
+ return blob;
6172
+ }
6173
+ if (responseType === "arraybuffer") {
6174
+ const buffer = await response.arrayBuffer();
6175
+ loaded = buffer.byteLength;
6176
+ if (loaded > 0) notify(new Uint8Array(buffer));
6177
+ return buffer;
6178
+ }
6179
+ const text2 = await response.text();
6180
+ const bytes2 = new TextEncoder().encode(text2);
6181
+ loaded = bytes2.byteLength;
6182
+ if (loaded > 0) notify(bytes2);
6183
+ return text2 ? JSON.parse(text2) : void 0;
6184
+ }
6185
+ const reader = body.getReader();
6186
+ const chunks = [];
6187
+ try {
6188
+ for (; ; ) {
6189
+ const { done, value } = await readChunk(reader, signal);
6190
+ if (done) break;
6191
+ if (!value || value.byteLength === 0) continue;
6192
+ chunks.push(value);
6193
+ loaded += value.byteLength;
6194
+ onActivity();
6195
+ notify(value);
6196
+ }
6197
+ } catch (err) {
6198
+ reader.cancel().catch(noop);
6199
+ throw err;
6200
+ }
6201
+ const bytes = concatChunks(chunks, loaded);
6202
+ if (responseType === "blob") {
6203
+ return new Blob([bytes], { type: headers.get("content-type") ?? "" });
6204
+ }
6205
+ if (responseType === "arraybuffer") {
6206
+ return bytes;
6207
+ }
6208
+ const text = new TextDecoder().decode(bytes);
6209
+ return text ? JSON.parse(text) : void 0;
6210
+ }
5812
6211
  function combineSignals(signals) {
5813
6212
  const controller = new AbortController();
5814
6213
  const listeners = [];
@@ -6090,7 +6489,12 @@ var Delopay = class {
6090
6489
  emit("retry", { attempt, maxRetries: this.maxRetries, method, path });
6091
6490
  }
6092
6491
  const timeoutCtrl = new AbortController();
6093
- const timeoutId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);
6492
+ let timeoutId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);
6493
+ const restartIdleTimer = () => {
6494
+ if (timeoutCtrl.signal.aborted) return;
6495
+ clearTimeout(timeoutId);
6496
+ timeoutId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);
6497
+ };
6094
6498
  const combined = combineSignals(
6095
6499
  callerSignal ? [timeoutCtrl.signal, callerSignal] : [timeoutCtrl.signal]
6096
6500
  );
@@ -6148,6 +6552,16 @@ var Delopay = class {
6148
6552
  }
6149
6553
  throw error;
6150
6554
  }
6555
+ if (options?.onDownloadProgress) {
6556
+ return await receiveWithProgress(
6557
+ response,
6558
+ options.responseType,
6559
+ options.onDownloadProgress,
6560
+ attempt,
6561
+ combined.signal,
6562
+ restartIdleTimer
6563
+ );
6564
+ }
6151
6565
  if (options?.responseType === "blob") {
6152
6566
  return await response.blob();
6153
6567
  }
@@ -6160,6 +6574,20 @@ var Delopay = class {
6160
6574
  if (err instanceof DelopayError || err instanceof DelopayAuthenticationError) {
6161
6575
  throw err;
6162
6576
  }
6577
+ if (err instanceof ListenerFailure) {
6578
+ throw err.cause;
6579
+ }
6580
+ if (err instanceof BodyStreamFailure) {
6581
+ const cause = err.cause;
6582
+ const detail = cause instanceof Error ? cause.message : String(cause ?? "body stream failed");
6583
+ lastError = new DelopayError(`Network error: ${detail}`, {
6584
+ status: 0,
6585
+ code: "NETWORK",
6586
+ type: "network_error"
6587
+ });
6588
+ if (isRetryable && attempt < this.maxRetries) continue;
6589
+ throw lastError;
6590
+ }
6163
6591
  if (err instanceof Error && err.name === "AbortError") {
6164
6592
  if (callerSignal?.aborted) {
6165
6593
  throw new DelopayError("Request aborted", {