@beliq/sdk 0.7.2 → 0.7.3
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 +23 -0
- package/README.md +57 -3
- package/dist/index.cjs +111 -36
- package/dist/index.d.cts +58 -5
- package/dist/index.d.ts +58 -5
- package/dist/index.js +109 -35
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,29 @@
|
|
|
4
4
|
resolves 0.4.x and never reaches 0.5.0. Additive spec syncs ship as patches for
|
|
5
5
|
that reason, and a minor is reserved for a change that needs consumers to opt in.
|
|
6
6
|
|
|
7
|
+
## 0.7.3 - 2026-11-08
|
|
8
|
+
|
|
9
|
+
- `retryClass(error)` says how the client's retry loop treats a failure:
|
|
10
|
+
`budget` (retried until `retryBudgetMs` is spent), `count` (up to
|
|
11
|
+
`maxRetries` times) or `none`. The loop uses the same function. A caller
|
|
12
|
+
that turns the client's retry off, such as a connector inside a host with a
|
|
13
|
+
30-second step limit, can hand a `budget` failure to the host's own retry.
|
|
14
|
+
The `RetryClass` type is exported too.
|
|
15
|
+
- `BeliqApiError` has `retryAfterSeconds`: the response's `Retry-After` when
|
|
16
|
+
it gave whole seconds, otherwise `undefined`. The retry loop now reads the
|
|
17
|
+
header the same way, as RFC 9110 delay-seconds: a value such as `1.5` or
|
|
18
|
+
`0x1E` was read as a number of seconds before and is now backed off from
|
|
19
|
+
like a missing header.
|
|
20
|
+
- Every method takes a `signal` (`generate` in a new second argument, `me`
|
|
21
|
+
in a new first one, the others in their options). It ends the call at once, during an
|
|
22
|
+
attempt or a wait between retries, with the signal's reason, and nothing is
|
|
23
|
+
sent when it is aborted already.
|
|
24
|
+
- A certificate that fails verification, or one for another name, is no
|
|
25
|
+
longer retried: it is thrown on the first attempt, as the Python SDK does.
|
|
26
|
+
It was retried up to 3 times. An OpenSSL error (`ERR_SSL_*`) is still
|
|
27
|
+
retried up to 3 times, since it can also come after the request was sent;
|
|
28
|
+
the Python SDK raises one from the handshake at once.
|
|
29
|
+
|
|
7
30
|
## 0.7.2 - 2026-11-07
|
|
8
31
|
|
|
9
32
|
- `ValidationResult` has `rulesetSupersededOn`, from the API document
|
package/README.md
CHANGED
|
@@ -113,7 +113,8 @@ numbers.
|
|
|
113
113
|
| A connection that could not be opened: a `cause.code` of `ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `UND_ERR_CONNECT_TIMEOUT` | until the budget is spent |
|
|
114
114
|
| `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED` | up to `maxRetries` times |
|
|
115
115
|
| `503` `ENGINE_UNAVAILABLE`, and any other `502` or `503` with a beliq error code | up to `maxRetries` times |
|
|
116
|
-
|
|
|
116
|
+
| A certificate that fails verification: a `cause.code` from Node's [X509 certificate error codes](https://nodejs.org/api/tls.html#x509-certificate-error-codes), or `ERR_TLS_CERT_ALTNAME_INVALID` | never |
|
|
117
|
+
| Any other thrown error, such as a connection lost after the request was sent, or an OpenSSL error (`ERR_SSL_*`), which can come after the send too | up to `maxRetries` times |
|
|
117
118
|
| `429` `QUOTA_EXCEEDED`, `504`, this client's own timeout, and every other status | never |
|
|
118
119
|
|
|
119
120
|
Every wait follows the server's `Retry-After` in full, plus up to 250 ms of
|
|
@@ -132,6 +133,59 @@ that meets one like it ends with the last error.
|
|
|
132
133
|
|
|
133
134
|
`maxRetries: 0` turns retrying off, and so does `retryBudgetMs: 0`.
|
|
134
135
|
|
|
136
|
+
### Retrying in a host with a time limit
|
|
137
|
+
|
|
138
|
+
Some hosts end a step long before an outage is over: an automation platform
|
|
139
|
+
that gives a step 30 seconds, or an MCP client that waits 60. There, turn the
|
|
140
|
+
client's retry off and hand an outage to the host's own retry:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { Beliq, retryClass } from '@beliq/sdk';
|
|
144
|
+
|
|
145
|
+
const beliq = new Beliq({ apiKey, retryBudgetMs: 0, timeoutMs: 25_000 });
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
return await beliq.validate(xml);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
if (retryClass(err) === 'budget') {
|
|
151
|
+
// A refused connection carries no header, so `wait` can be undefined.
|
|
152
|
+
const wait = (err as { retryAfterSeconds?: number }).retryAfterSeconds;
|
|
153
|
+
// Tell the host to try the step again after `wait` seconds.
|
|
154
|
+
}
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`retryClass(error)` answers `budget`, `count` or `none`: the class of the
|
|
160
|
+
table above, "until the budget is spent", "up to `maxRetries` times" or
|
|
161
|
+
"never". The client's own retry loop uses the same function, so it is the
|
|
162
|
+
class the client acted on. An abort by your own `signal` (below) is not
|
|
163
|
+
classified: the loop ends at once, so check `signal.aborted` first.
|
|
164
|
+
|
|
165
|
+
`retryBudgetMs: 0` turns off the retries by count as well. The example hands
|
|
166
|
+
only the budget class to the host, so a `429` `RATE_LIMITED`, a `503`
|
|
167
|
+
`ENGINE_UNAVAILABLE` and a connection lost after the send then fail the step.
|
|
168
|
+
Hand those to the host too only if it bounds how often it retries: a repeat of
|
|
169
|
+
`ENGINE_UNAVAILABLE` runs the same slow document again.
|
|
170
|
+
|
|
171
|
+
`BeliqApiError` carries `retryAfterSeconds`, the response's `Retry-After` when
|
|
172
|
+
it gave whole seconds, and `undefined` for an HTTP date, any other form or no
|
|
173
|
+
header, as the loop reads it.
|
|
174
|
+
|
|
175
|
+
Every method takes a `signal`, an `AbortSignal` that ends the call at once,
|
|
176
|
+
during an attempt or a wait, with the signal's reason. A worker that stops on
|
|
177
|
+
`SIGTERM` passes one, so it does not sit in a `Retry-After` wait. Nothing is
|
|
178
|
+
sent when the signal is aborted already; an attempt already sent may still have
|
|
179
|
+
run on beliq's side.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
const stop = new AbortController();
|
|
183
|
+
process.once('SIGTERM', () => stop.abort());
|
|
184
|
+
await beliq.validate(xml, { signal: stop.signal });
|
|
185
|
+
await beliq.generate(input, { signal: stop.signal });
|
|
186
|
+
await beliq.me({ signal: stop.signal });
|
|
187
|
+
```
|
|
188
|
+
|
|
135
189
|
What a retry costs:
|
|
136
190
|
|
|
137
191
|
- Most `DATABASE_UNAVAILABLE` answers come before any quota unit is spent, and a
|
|
@@ -173,8 +227,8 @@ shorter than the server's own turns completed work into an unknown outcome. Set
|
|
|
173
227
|
|
|
174
228
|
| Method | Endpoint | Input | Returns |
|
|
175
229
|
|---|---|---|---|
|
|
176
|
-
| `me()` | GET /v1/me | none | `AccountInfo` (no quota cost) |
|
|
177
|
-
| `generate(input)` | POST /v1/generate | EN 16931 invoice object | `{ contentType, bytes, xml?, sha256?, validationResult?, meta }` |
|
|
230
|
+
| `me(options?)` | GET /v1/me | none | `AccountInfo` (no quota cost) |
|
|
231
|
+
| `generate(input, options?)` | POST /v1/generate | EN 16931 invoice object | `{ contentType, bytes, xml?, sha256?, validationResult?, meta }` |
|
|
178
232
|
| `validate(document, options?)` | POST /v1/validate | XML or PDF | `ValidationResult` |
|
|
179
233
|
| `parse(document, options?)` | POST /v1/parse | XML or PDF | `ParseResult` |
|
|
180
234
|
| `convert(document, options)` | POST /v1/convert | XML or PDF | `{ contentType, bytes, meta }` |
|
package/dist/index.cjs
CHANGED
|
@@ -35,7 +35,8 @@ __export(index_exports, {
|
|
|
35
35
|
LIVE_PROFILES_BY_STANDARD: () => LIVE_PROFILES_BY_STANDARD,
|
|
36
36
|
LIVE_VALIDATE_FORMATS: () => LIVE_VALIDATE_FORMATS,
|
|
37
37
|
isProfileAllowedForStandard: () => isProfileAllowedForStandard,
|
|
38
|
-
profilesForStandard: () => profilesForStandard
|
|
38
|
+
profilesForStandard: () => profilesForStandard,
|
|
39
|
+
retryClass: () => retryClass
|
|
39
40
|
});
|
|
40
41
|
module.exports = __toCommonJS(index_exports);
|
|
41
42
|
|
|
@@ -182,14 +183,26 @@ var BeliqApiError = class extends Error {
|
|
|
182
183
|
code;
|
|
183
184
|
status;
|
|
184
185
|
details;
|
|
186
|
+
/**
|
|
187
|
+
* The response's `Retry-After` in seconds, when it gave one as whole seconds
|
|
188
|
+
* (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
|
|
189
|
+
* the header the same way, so this is the wait it would have taken.
|
|
190
|
+
*/
|
|
191
|
+
retryAfterSeconds;
|
|
185
192
|
constructor(message, opts) {
|
|
186
193
|
super(message);
|
|
187
194
|
this.name = "BeliqApiError";
|
|
188
195
|
this.code = opts.code;
|
|
189
196
|
this.status = opts.status;
|
|
190
197
|
this.details = opts.details;
|
|
198
|
+
this.retryAfterSeconds = opts.retryAfterSeconds;
|
|
191
199
|
}
|
|
192
200
|
};
|
|
201
|
+
var DELAY_SECONDS = /^\d+$/;
|
|
202
|
+
function parseRetryAfterSeconds(headers) {
|
|
203
|
+
const header = headers?.get("retry-after");
|
|
204
|
+
return header !== null && header !== void 0 && DELAY_SECONDS.test(header) ? Number(header) : void 0;
|
|
205
|
+
}
|
|
193
206
|
function parseEnvelope(bytes) {
|
|
194
207
|
let text;
|
|
195
208
|
try {
|
|
@@ -205,11 +218,16 @@ function parseEnvelope(bytes) {
|
|
|
205
218
|
return null;
|
|
206
219
|
}
|
|
207
220
|
}
|
|
208
|
-
function errorFromResponse(status, bytes) {
|
|
221
|
+
function errorFromResponse(status, bytes, headers) {
|
|
209
222
|
const envelope = parseEnvelope(bytes);
|
|
210
223
|
const err = envelope?.error;
|
|
211
224
|
const message = err?.message ?? envelope?.message ?? `beliq request failed with status ${status}`;
|
|
212
|
-
return new BeliqApiError(message, {
|
|
225
|
+
return new BeliqApiError(message, {
|
|
226
|
+
code: err?.code,
|
|
227
|
+
status,
|
|
228
|
+
details: err?.details,
|
|
229
|
+
retryAfterSeconds: parseRetryAfterSeconds(headers)
|
|
230
|
+
});
|
|
213
231
|
}
|
|
214
232
|
|
|
215
233
|
// src/constants.ts
|
|
@@ -291,15 +309,57 @@ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
|
|
|
291
309
|
"EHOSTUNREACH",
|
|
292
310
|
"UND_ERR_CONNECT_TIMEOUT"
|
|
293
311
|
]);
|
|
312
|
+
var CERTIFICATE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
313
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
314
|
+
"UNABLE_TO_GET_CRL",
|
|
315
|
+
"UNABLE_TO_DECRYPT_CERT_SIGNATURE",
|
|
316
|
+
"UNABLE_TO_DECRYPT_CRL_SIGNATURE",
|
|
317
|
+
"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
|
|
318
|
+
"CERT_SIGNATURE_FAILURE",
|
|
319
|
+
"CRL_SIGNATURE_FAILURE",
|
|
320
|
+
"CERT_NOT_YET_VALID",
|
|
321
|
+
"CERT_HAS_EXPIRED",
|
|
322
|
+
"CRL_NOT_YET_VALID",
|
|
323
|
+
"CRL_HAS_EXPIRED",
|
|
324
|
+
"ERROR_IN_CERT_NOT_BEFORE_FIELD",
|
|
325
|
+
"ERROR_IN_CERT_NOT_AFTER_FIELD",
|
|
326
|
+
"ERROR_IN_CRL_LAST_UPDATE_FIELD",
|
|
327
|
+
"ERROR_IN_CRL_NEXT_UPDATE_FIELD",
|
|
328
|
+
"OUT_OF_MEM",
|
|
329
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
330
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
331
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
332
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
333
|
+
"CERT_CHAIN_TOO_LONG",
|
|
334
|
+
"CERT_REVOKED",
|
|
335
|
+
"INVALID_CA",
|
|
336
|
+
"PATH_LENGTH_EXCEEDED",
|
|
337
|
+
"INVALID_PURPOSE",
|
|
338
|
+
"CERT_UNTRUSTED",
|
|
339
|
+
"CERT_REJECTED",
|
|
340
|
+
"HOSTNAME_MISMATCH"
|
|
341
|
+
]);
|
|
342
|
+
function isCertificateFailure(code) {
|
|
343
|
+
return CERTIFICATE_ERROR_CODES.has(code) || code === "ERR_TLS_CERT_ALTNAME_INVALID";
|
|
344
|
+
}
|
|
294
345
|
function classifyStatus(status, code) {
|
|
295
|
-
if (status === 429) return code === QUOTA_EXHAUSTED_CODE ?
|
|
296
|
-
if (status !== 502 && status !== 503) return
|
|
346
|
+
if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? "none" : "count";
|
|
347
|
+
if (status !== 502 && status !== 503) return "none";
|
|
297
348
|
if (!code) return "budget";
|
|
298
349
|
return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
|
|
299
350
|
}
|
|
300
351
|
function classifyThrown(err) {
|
|
301
352
|
const code = err?.cause?.code;
|
|
302
|
-
|
|
353
|
+
if (typeof code !== "string") return "count";
|
|
354
|
+
if (isCertificateFailure(code)) return "none";
|
|
355
|
+
return BEFORE_SEND_CODES.has(code) ? "budget" : "count";
|
|
356
|
+
}
|
|
357
|
+
function retryClass(error) {
|
|
358
|
+
if (error instanceof BeliqApiError || error?.name === "BeliqApiError" && typeof error.status === "number") {
|
|
359
|
+
const apiError = error;
|
|
360
|
+
return classifyStatus(apiError.status, apiError.code);
|
|
361
|
+
}
|
|
362
|
+
return classifyThrown(error);
|
|
303
363
|
}
|
|
304
364
|
var BACKOFF_BASE_MS = 500;
|
|
305
365
|
var BACKOFF_CEILING_MS = 3e4;
|
|
@@ -318,20 +378,28 @@ function buildUrl(baseUrl, path, query) {
|
|
|
318
378
|
return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
|
|
319
379
|
}
|
|
320
380
|
function retryDelayMs(res, attempt, config) {
|
|
321
|
-
const
|
|
322
|
-
if (
|
|
323
|
-
const seconds = Number(header);
|
|
324
|
-
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
325
|
-
return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
381
|
+
const seconds = parseRetryAfterSeconds(res?.headers);
|
|
382
|
+
if (seconds !== void 0) return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
328
383
|
const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
|
|
329
384
|
const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
|
|
330
385
|
const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
|
|
331
386
|
return backoff + Math.random() * backoff;
|
|
332
387
|
}
|
|
333
|
-
|
|
334
|
-
|
|
388
|
+
function sleep(ms, signal) {
|
|
389
|
+
return new Promise((resolve, reject) => {
|
|
390
|
+
signal?.throwIfAborted();
|
|
391
|
+
const onAbort = () => {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
reject(signal?.reason);
|
|
394
|
+
};
|
|
395
|
+
const timer = setTimeout(() => {
|
|
396
|
+
signal?.removeEventListener("abort", onAbort);
|
|
397
|
+
resolve();
|
|
398
|
+
}, ms);
|
|
399
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
async function send(config, req, signal) {
|
|
335
403
|
const headers = { ...req.headers, ...authHeaders(config) };
|
|
336
404
|
if (req.contentType) headers["Content-Type"] = req.contentType;
|
|
337
405
|
if (req.accept) headers["Accept"] = req.accept;
|
|
@@ -340,11 +408,14 @@ async function send(config, req) {
|
|
|
340
408
|
const started = performance.now();
|
|
341
409
|
let countedRetries = 0;
|
|
342
410
|
for (let attempt = 0; ; attempt++) {
|
|
411
|
+
signal?.throwIfAborted();
|
|
343
412
|
const controller = new AbortController();
|
|
413
|
+
const onCallerAbort = () => controller.abort();
|
|
414
|
+
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
344
415
|
const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
|
|
345
416
|
let res;
|
|
346
417
|
let failure;
|
|
347
|
-
let
|
|
418
|
+
let kind;
|
|
348
419
|
try {
|
|
349
420
|
res = await config.fetchImpl(url, {
|
|
350
421
|
method: req.method,
|
|
@@ -354,10 +425,10 @@ async function send(config, req) {
|
|
|
354
425
|
});
|
|
355
426
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
356
427
|
if (res.ok) return { status: res.status, headers: res.headers, bytes };
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
retryClass = classifyStatus(apiError.status, apiError.code);
|
|
428
|
+
failure = errorFromResponse(res.status, bytes, res.headers);
|
|
429
|
+
kind = retryClass(failure);
|
|
360
430
|
} catch (err) {
|
|
431
|
+
signal?.throwIfAborted();
|
|
361
432
|
if (controller.signal.aborted) {
|
|
362
433
|
throw new BeliqApiError(
|
|
363
434
|
`beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
|
|
@@ -365,20 +436,21 @@ async function send(config, req) {
|
|
|
365
436
|
);
|
|
366
437
|
}
|
|
367
438
|
failure = err;
|
|
368
|
-
|
|
439
|
+
kind = retryClass(err);
|
|
369
440
|
} finally {
|
|
370
441
|
if (timer) clearTimeout(timer);
|
|
442
|
+
signal?.removeEventListener("abort", onCallerAbort);
|
|
371
443
|
}
|
|
372
|
-
if (
|
|
444
|
+
if (kind === "none") throw failure;
|
|
373
445
|
if (config.maxRetries !== void 0) {
|
|
374
446
|
if (attempt >= config.maxRetries) throw failure;
|
|
375
|
-
} else if (
|
|
447
|
+
} else if (kind === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
|
|
376
448
|
throw failure;
|
|
377
449
|
}
|
|
378
450
|
const delay = retryDelayMs(res, attempt, config);
|
|
379
451
|
if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
|
|
380
|
-
if (
|
|
381
|
-
await sleep(delay);
|
|
452
|
+
if (kind === "count") countedRetries++;
|
|
453
|
+
await sleep(delay, signal);
|
|
382
454
|
}
|
|
383
455
|
}
|
|
384
456
|
|
|
@@ -463,19 +535,20 @@ var Beliq = class {
|
|
|
463
535
|
};
|
|
464
536
|
}
|
|
465
537
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
466
|
-
async me() {
|
|
467
|
-
return this.#json({ operation: "me" });
|
|
538
|
+
async me(options = {}) {
|
|
539
|
+
return this.#json({ operation: "me" }, options.signal);
|
|
468
540
|
}
|
|
469
541
|
/** Generate an e-invoice from an EN 16931 object. */
|
|
470
|
-
async generate(input) {
|
|
542
|
+
async generate(input, options = {}) {
|
|
471
543
|
const res = await send(
|
|
472
544
|
this.#config,
|
|
473
|
-
buildRequest({ operation: "generate", ...input, sealed: input.seal })
|
|
545
|
+
buildRequest({ operation: "generate", ...input, sealed: input.seal }),
|
|
546
|
+
options.signal
|
|
474
547
|
);
|
|
475
548
|
const meta = generateMeta(res.headers);
|
|
476
549
|
if (input.seal) {
|
|
477
550
|
const envelope = parseEnvelope(res.bytes);
|
|
478
|
-
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
|
|
551
|
+
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
|
|
479
552
|
const data = envelope?.data;
|
|
480
553
|
if (!data || data.output === void 0) {
|
|
481
554
|
throw new BeliqApiError("beliq: seal response was not a JSON envelope", {
|
|
@@ -509,7 +582,7 @@ var Beliq = class {
|
|
|
509
582
|
validateFormat: options.format,
|
|
510
583
|
franceCtc: options.franceCtc,
|
|
511
584
|
ruleset: options.ruleset
|
|
512
|
-
});
|
|
585
|
+
}, options.signal);
|
|
513
586
|
}
|
|
514
587
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
515
588
|
async parse(document, options = {}) {
|
|
@@ -517,7 +590,7 @@ var Beliq = class {
|
|
|
517
590
|
operation: "parse",
|
|
518
591
|
...this.#rawParams(document, options),
|
|
519
592
|
parseFormat: options.format
|
|
520
|
-
});
|
|
593
|
+
}, options.signal);
|
|
521
594
|
}
|
|
522
595
|
/** Convert a document between EN 16931 formats. */
|
|
523
596
|
async convert(document, options) {
|
|
@@ -530,7 +603,8 @@ var Beliq = class {
|
|
|
530
603
|
targetFormat: options.targetFormat,
|
|
531
604
|
targetProfile: options.targetProfile,
|
|
532
605
|
dropFranceCtcOverlay: options.dropFranceCtcOverlay
|
|
533
|
-
})
|
|
606
|
+
}),
|
|
607
|
+
options.signal
|
|
534
608
|
);
|
|
535
609
|
return {
|
|
536
610
|
contentType: res.headers.get("content-type") ?? "application/octet-stream",
|
|
@@ -546,10 +620,10 @@ var Beliq = class {
|
|
|
546
620
|
advanced: options.advanced
|
|
547
621
|
};
|
|
548
622
|
}
|
|
549
|
-
async #json(params) {
|
|
550
|
-
const res = await send(this.#config, buildRequest(params));
|
|
623
|
+
async #json(params, signal) {
|
|
624
|
+
const res = await send(this.#config, buildRequest(params), signal);
|
|
551
625
|
const envelope = parseEnvelope(res.bytes);
|
|
552
|
-
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
|
|
626
|
+
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
|
|
553
627
|
if (!envelope || envelope.data === void 0) {
|
|
554
628
|
throw new BeliqApiError("beliq: response was not a JSON envelope", { status: res.status });
|
|
555
629
|
}
|
|
@@ -573,5 +647,6 @@ var Beliq = class {
|
|
|
573
647
|
LIVE_PROFILES_BY_STANDARD,
|
|
574
648
|
LIVE_VALIDATE_FORMATS,
|
|
575
649
|
isProfileAllowedForStandard,
|
|
576
|
-
profilesForStandard
|
|
650
|
+
profilesForStandard,
|
|
651
|
+
retryClass
|
|
577
652
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -60,7 +60,17 @@ interface GenerateInput {
|
|
|
60
60
|
/** Raw JSON deep-merged into the request body. */
|
|
61
61
|
advanced?: PlainObject;
|
|
62
62
|
}
|
|
63
|
-
|
|
63
|
+
/** Options every method takes. */
|
|
64
|
+
interface RequestOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Ends the call at once with the signal's reason, during an attempt or a
|
|
67
|
+
* wait between retries, so a worker that stops does not sit in a
|
|
68
|
+
* `Retry-After` wait. Nothing is sent when it is aborted already. An attempt
|
|
69
|
+
* already sent may still have run on beliq's side.
|
|
70
|
+
*/
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
}
|
|
73
|
+
interface DocumentOptions extends RequestOptions {
|
|
64
74
|
/** Override the sniffed request content type (application/xml | application/pdf). */
|
|
65
75
|
contentType?: string;
|
|
66
76
|
/**
|
|
@@ -169,9 +179,9 @@ declare class Beliq {
|
|
|
169
179
|
readonly livemode: boolean;
|
|
170
180
|
constructor(options: BeliqOptions);
|
|
171
181
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
172
|
-
me(): Promise<AccountInfo>;
|
|
182
|
+
me(options?: RequestOptions): Promise<AccountInfo>;
|
|
173
183
|
/** Generate an e-invoice from an EN 16931 object. */
|
|
174
|
-
generate(input: GenerateInput): Promise<GenerateResult>;
|
|
184
|
+
generate(input: GenerateInput, options?: RequestOptions): Promise<GenerateResult>;
|
|
175
185
|
/** Validate a document. The result names the rules that ran and, in `verificationBadgeLabel` when the API states one, the check depth. */
|
|
176
186
|
validate(document: DocumentInput, options?: ValidateOptions): Promise<ValidationResult>;
|
|
177
187
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
@@ -189,12 +199,55 @@ declare class BeliqApiError extends Error {
|
|
|
189
199
|
readonly code?: ApiErrorCode | string;
|
|
190
200
|
readonly status: number;
|
|
191
201
|
readonly details?: Record<string, unknown>;
|
|
202
|
+
/**
|
|
203
|
+
* The response's `Retry-After` in seconds, when it gave one as whole seconds
|
|
204
|
+
* (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
|
|
205
|
+
* the header the same way, so this is the wait it would have taken.
|
|
206
|
+
*/
|
|
207
|
+
readonly retryAfterSeconds?: number;
|
|
192
208
|
constructor(message: string, opts: {
|
|
193
209
|
code?: ApiErrorCode | string;
|
|
194
210
|
status: number;
|
|
195
211
|
details?: Record<string, unknown>;
|
|
212
|
+
retryAfterSeconds?: number;
|
|
196
213
|
});
|
|
197
214
|
}
|
|
198
215
|
|
|
199
|
-
|
|
200
|
-
|
|
216
|
+
/**
|
|
217
|
+
* How a failure is retried.
|
|
218
|
+
*
|
|
219
|
+
* `budget`: an outage a wait can outlast, retried until the time budget is spent.
|
|
220
|
+
* A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code (the edge
|
|
221
|
+
* answered, or the pod that held the connection is gone), and a connection that
|
|
222
|
+
* could not be opened.
|
|
223
|
+
*
|
|
224
|
+
* `count`: retried up to `maxRetries` times. A 429 other than `QUOTA_EXCEEDED`,
|
|
225
|
+
* since each one counts toward the account's throttle; a 502 or 503 with any
|
|
226
|
+
* other beliq code, `ENGINE_UNAVAILABLE` included, since an engine timeout
|
|
227
|
+
* answers that code too and a budget would run the same slow document dozens of
|
|
228
|
+
* times; and a thrown error that may have come after the request was sent.
|
|
229
|
+
* beliq may have run and charged that request, but it does not charge a repeat
|
|
230
|
+
* of a charged request within 15 minutes, up to 10 repeats (beliq's own values,
|
|
231
|
+
* which no standard sets), and every attempt sends the same bytes.
|
|
232
|
+
*
|
|
233
|
+
* `none`: not retried. A 504 and this client's own timeout mean the work may
|
|
234
|
+
* still be running on beliq's side, and a repeat runs the same document again
|
|
235
|
+
* from the start, likely into the same deadline. A certificate failure and
|
|
236
|
+
* every other status are final too.
|
|
237
|
+
*/
|
|
238
|
+
type RetryClass = 'budget' | 'count' | 'none';
|
|
239
|
+
/**
|
|
240
|
+
* How the client's retry loop treats a failure that a `Beliq` method threw, so
|
|
241
|
+
* a caller that turns the client's retry off can hand the failure to a retry
|
|
242
|
+
* of its own. The loop uses this same function, so its answer is the one the
|
|
243
|
+
* loop acted on: `budget` was retried until `retryBudgetMs` was spent, `count`
|
|
244
|
+
* up to `maxRetries` times, `none` not at all. It reads a `BeliqApiError` by its
|
|
245
|
+
* status and code, `TIMEOUT` (this client's own deadline) as `none`, and any
|
|
246
|
+
* other error by its `cause.code`, as `fetch` throws it. An abort by the
|
|
247
|
+
* caller's own `signal` throws the signal's reason, which the loop never
|
|
248
|
+
* classifies: check the signal's `aborted` before asking this.
|
|
249
|
+
*/
|
|
250
|
+
declare function retryClass(error: unknown): RetryClass;
|
|
251
|
+
|
|
252
|
+
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult, retryClass };
|
|
253
|
+
export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, RequestOptions, RetryClass, ValidateOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -60,7 +60,17 @@ interface GenerateInput {
|
|
|
60
60
|
/** Raw JSON deep-merged into the request body. */
|
|
61
61
|
advanced?: PlainObject;
|
|
62
62
|
}
|
|
63
|
-
|
|
63
|
+
/** Options every method takes. */
|
|
64
|
+
interface RequestOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Ends the call at once with the signal's reason, during an attempt or a
|
|
67
|
+
* wait between retries, so a worker that stops does not sit in a
|
|
68
|
+
* `Retry-After` wait. Nothing is sent when it is aborted already. An attempt
|
|
69
|
+
* already sent may still have run on beliq's side.
|
|
70
|
+
*/
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
}
|
|
73
|
+
interface DocumentOptions extends RequestOptions {
|
|
64
74
|
/** Override the sniffed request content type (application/xml | application/pdf). */
|
|
65
75
|
contentType?: string;
|
|
66
76
|
/**
|
|
@@ -169,9 +179,9 @@ declare class Beliq {
|
|
|
169
179
|
readonly livemode: boolean;
|
|
170
180
|
constructor(options: BeliqOptions);
|
|
171
181
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
172
|
-
me(): Promise<AccountInfo>;
|
|
182
|
+
me(options?: RequestOptions): Promise<AccountInfo>;
|
|
173
183
|
/** Generate an e-invoice from an EN 16931 object. */
|
|
174
|
-
generate(input: GenerateInput): Promise<GenerateResult>;
|
|
184
|
+
generate(input: GenerateInput, options?: RequestOptions): Promise<GenerateResult>;
|
|
175
185
|
/** Validate a document. The result names the rules that ran and, in `verificationBadgeLabel` when the API states one, the check depth. */
|
|
176
186
|
validate(document: DocumentInput, options?: ValidateOptions): Promise<ValidationResult>;
|
|
177
187
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
@@ -189,12 +199,55 @@ declare class BeliqApiError extends Error {
|
|
|
189
199
|
readonly code?: ApiErrorCode | string;
|
|
190
200
|
readonly status: number;
|
|
191
201
|
readonly details?: Record<string, unknown>;
|
|
202
|
+
/**
|
|
203
|
+
* The response's `Retry-After` in seconds, when it gave one as whole seconds
|
|
204
|
+
* (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
|
|
205
|
+
* the header the same way, so this is the wait it would have taken.
|
|
206
|
+
*/
|
|
207
|
+
readonly retryAfterSeconds?: number;
|
|
192
208
|
constructor(message: string, opts: {
|
|
193
209
|
code?: ApiErrorCode | string;
|
|
194
210
|
status: number;
|
|
195
211
|
details?: Record<string, unknown>;
|
|
212
|
+
retryAfterSeconds?: number;
|
|
196
213
|
});
|
|
197
214
|
}
|
|
198
215
|
|
|
199
|
-
|
|
200
|
-
|
|
216
|
+
/**
|
|
217
|
+
* How a failure is retried.
|
|
218
|
+
*
|
|
219
|
+
* `budget`: an outage a wait can outlast, retried until the time budget is spent.
|
|
220
|
+
* A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code (the edge
|
|
221
|
+
* answered, or the pod that held the connection is gone), and a connection that
|
|
222
|
+
* could not be opened.
|
|
223
|
+
*
|
|
224
|
+
* `count`: retried up to `maxRetries` times. A 429 other than `QUOTA_EXCEEDED`,
|
|
225
|
+
* since each one counts toward the account's throttle; a 502 or 503 with any
|
|
226
|
+
* other beliq code, `ENGINE_UNAVAILABLE` included, since an engine timeout
|
|
227
|
+
* answers that code too and a budget would run the same slow document dozens of
|
|
228
|
+
* times; and a thrown error that may have come after the request was sent.
|
|
229
|
+
* beliq may have run and charged that request, but it does not charge a repeat
|
|
230
|
+
* of a charged request within 15 minutes, up to 10 repeats (beliq's own values,
|
|
231
|
+
* which no standard sets), and every attempt sends the same bytes.
|
|
232
|
+
*
|
|
233
|
+
* `none`: not retried. A 504 and this client's own timeout mean the work may
|
|
234
|
+
* still be running on beliq's side, and a repeat runs the same document again
|
|
235
|
+
* from the start, likely into the same deadline. A certificate failure and
|
|
236
|
+
* every other status are final too.
|
|
237
|
+
*/
|
|
238
|
+
type RetryClass = 'budget' | 'count' | 'none';
|
|
239
|
+
/**
|
|
240
|
+
* How the client's retry loop treats a failure that a `Beliq` method threw, so
|
|
241
|
+
* a caller that turns the client's retry off can hand the failure to a retry
|
|
242
|
+
* of its own. The loop uses this same function, so its answer is the one the
|
|
243
|
+
* loop acted on: `budget` was retried until `retryBudgetMs` was spent, `count`
|
|
244
|
+
* up to `maxRetries` times, `none` not at all. It reads a `BeliqApiError` by its
|
|
245
|
+
* status and code, `TIMEOUT` (this client's own deadline) as `none`, and any
|
|
246
|
+
* other error by its `cause.code`, as `fetch` throws it. An abort by the
|
|
247
|
+
* caller's own `signal` throws the signal's reason, which the loop never
|
|
248
|
+
* classifies: check the signal's `aborted` before asking this.
|
|
249
|
+
*/
|
|
250
|
+
declare function retryClass(error: unknown): RetryClass;
|
|
251
|
+
|
|
252
|
+
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult, retryClass };
|
|
253
|
+
export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, RequestOptions, RetryClass, ValidateOptions };
|
package/dist/index.js
CHANGED
|
@@ -141,14 +141,26 @@ var BeliqApiError = class extends Error {
|
|
|
141
141
|
code;
|
|
142
142
|
status;
|
|
143
143
|
details;
|
|
144
|
+
/**
|
|
145
|
+
* The response's `Retry-After` in seconds, when it gave one as whole seconds
|
|
146
|
+
* (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
|
|
147
|
+
* the header the same way, so this is the wait it would have taken.
|
|
148
|
+
*/
|
|
149
|
+
retryAfterSeconds;
|
|
144
150
|
constructor(message, opts) {
|
|
145
151
|
super(message);
|
|
146
152
|
this.name = "BeliqApiError";
|
|
147
153
|
this.code = opts.code;
|
|
148
154
|
this.status = opts.status;
|
|
149
155
|
this.details = opts.details;
|
|
156
|
+
this.retryAfterSeconds = opts.retryAfterSeconds;
|
|
150
157
|
}
|
|
151
158
|
};
|
|
159
|
+
var DELAY_SECONDS = /^\d+$/;
|
|
160
|
+
function parseRetryAfterSeconds(headers) {
|
|
161
|
+
const header = headers?.get("retry-after");
|
|
162
|
+
return header !== null && header !== void 0 && DELAY_SECONDS.test(header) ? Number(header) : void 0;
|
|
163
|
+
}
|
|
152
164
|
function parseEnvelope(bytes) {
|
|
153
165
|
let text;
|
|
154
166
|
try {
|
|
@@ -164,11 +176,16 @@ function parseEnvelope(bytes) {
|
|
|
164
176
|
return null;
|
|
165
177
|
}
|
|
166
178
|
}
|
|
167
|
-
function errorFromResponse(status, bytes) {
|
|
179
|
+
function errorFromResponse(status, bytes, headers) {
|
|
168
180
|
const envelope = parseEnvelope(bytes);
|
|
169
181
|
const err = envelope?.error;
|
|
170
182
|
const message = err?.message ?? envelope?.message ?? `beliq request failed with status ${status}`;
|
|
171
|
-
return new BeliqApiError(message, {
|
|
183
|
+
return new BeliqApiError(message, {
|
|
184
|
+
code: err?.code,
|
|
185
|
+
status,
|
|
186
|
+
details: err?.details,
|
|
187
|
+
retryAfterSeconds: parseRetryAfterSeconds(headers)
|
|
188
|
+
});
|
|
172
189
|
}
|
|
173
190
|
|
|
174
191
|
// src/constants.ts
|
|
@@ -250,15 +267,57 @@ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
|
|
|
250
267
|
"EHOSTUNREACH",
|
|
251
268
|
"UND_ERR_CONNECT_TIMEOUT"
|
|
252
269
|
]);
|
|
270
|
+
var CERTIFICATE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
271
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
272
|
+
"UNABLE_TO_GET_CRL",
|
|
273
|
+
"UNABLE_TO_DECRYPT_CERT_SIGNATURE",
|
|
274
|
+
"UNABLE_TO_DECRYPT_CRL_SIGNATURE",
|
|
275
|
+
"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
|
|
276
|
+
"CERT_SIGNATURE_FAILURE",
|
|
277
|
+
"CRL_SIGNATURE_FAILURE",
|
|
278
|
+
"CERT_NOT_YET_VALID",
|
|
279
|
+
"CERT_HAS_EXPIRED",
|
|
280
|
+
"CRL_NOT_YET_VALID",
|
|
281
|
+
"CRL_HAS_EXPIRED",
|
|
282
|
+
"ERROR_IN_CERT_NOT_BEFORE_FIELD",
|
|
283
|
+
"ERROR_IN_CERT_NOT_AFTER_FIELD",
|
|
284
|
+
"ERROR_IN_CRL_LAST_UPDATE_FIELD",
|
|
285
|
+
"ERROR_IN_CRL_NEXT_UPDATE_FIELD",
|
|
286
|
+
"OUT_OF_MEM",
|
|
287
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
288
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
289
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
290
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
291
|
+
"CERT_CHAIN_TOO_LONG",
|
|
292
|
+
"CERT_REVOKED",
|
|
293
|
+
"INVALID_CA",
|
|
294
|
+
"PATH_LENGTH_EXCEEDED",
|
|
295
|
+
"INVALID_PURPOSE",
|
|
296
|
+
"CERT_UNTRUSTED",
|
|
297
|
+
"CERT_REJECTED",
|
|
298
|
+
"HOSTNAME_MISMATCH"
|
|
299
|
+
]);
|
|
300
|
+
function isCertificateFailure(code) {
|
|
301
|
+
return CERTIFICATE_ERROR_CODES.has(code) || code === "ERR_TLS_CERT_ALTNAME_INVALID";
|
|
302
|
+
}
|
|
253
303
|
function classifyStatus(status, code) {
|
|
254
|
-
if (status === 429) return code === QUOTA_EXHAUSTED_CODE ?
|
|
255
|
-
if (status !== 502 && status !== 503) return
|
|
304
|
+
if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? "none" : "count";
|
|
305
|
+
if (status !== 502 && status !== 503) return "none";
|
|
256
306
|
if (!code) return "budget";
|
|
257
307
|
return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
|
|
258
308
|
}
|
|
259
309
|
function classifyThrown(err) {
|
|
260
310
|
const code = err?.cause?.code;
|
|
261
|
-
|
|
311
|
+
if (typeof code !== "string") return "count";
|
|
312
|
+
if (isCertificateFailure(code)) return "none";
|
|
313
|
+
return BEFORE_SEND_CODES.has(code) ? "budget" : "count";
|
|
314
|
+
}
|
|
315
|
+
function retryClass(error) {
|
|
316
|
+
if (error instanceof BeliqApiError || error?.name === "BeliqApiError" && typeof error.status === "number") {
|
|
317
|
+
const apiError = error;
|
|
318
|
+
return classifyStatus(apiError.status, apiError.code);
|
|
319
|
+
}
|
|
320
|
+
return classifyThrown(error);
|
|
262
321
|
}
|
|
263
322
|
var BACKOFF_BASE_MS = 500;
|
|
264
323
|
var BACKOFF_CEILING_MS = 3e4;
|
|
@@ -277,20 +336,28 @@ function buildUrl(baseUrl, path, query) {
|
|
|
277
336
|
return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
|
|
278
337
|
}
|
|
279
338
|
function retryDelayMs(res, attempt, config) {
|
|
280
|
-
const
|
|
281
|
-
if (
|
|
282
|
-
const seconds = Number(header);
|
|
283
|
-
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
284
|
-
return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
339
|
+
const seconds = parseRetryAfterSeconds(res?.headers);
|
|
340
|
+
if (seconds !== void 0) return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
287
341
|
const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
|
|
288
342
|
const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
|
|
289
343
|
const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
|
|
290
344
|
return backoff + Math.random() * backoff;
|
|
291
345
|
}
|
|
292
|
-
|
|
293
|
-
|
|
346
|
+
function sleep(ms, signal) {
|
|
347
|
+
return new Promise((resolve, reject) => {
|
|
348
|
+
signal?.throwIfAborted();
|
|
349
|
+
const onAbort = () => {
|
|
350
|
+
clearTimeout(timer);
|
|
351
|
+
reject(signal?.reason);
|
|
352
|
+
};
|
|
353
|
+
const timer = setTimeout(() => {
|
|
354
|
+
signal?.removeEventListener("abort", onAbort);
|
|
355
|
+
resolve();
|
|
356
|
+
}, ms);
|
|
357
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
async function send(config, req, signal) {
|
|
294
361
|
const headers = { ...req.headers, ...authHeaders(config) };
|
|
295
362
|
if (req.contentType) headers["Content-Type"] = req.contentType;
|
|
296
363
|
if (req.accept) headers["Accept"] = req.accept;
|
|
@@ -299,11 +366,14 @@ async function send(config, req) {
|
|
|
299
366
|
const started = performance.now();
|
|
300
367
|
let countedRetries = 0;
|
|
301
368
|
for (let attempt = 0; ; attempt++) {
|
|
369
|
+
signal?.throwIfAborted();
|
|
302
370
|
const controller = new AbortController();
|
|
371
|
+
const onCallerAbort = () => controller.abort();
|
|
372
|
+
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
303
373
|
const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
|
|
304
374
|
let res;
|
|
305
375
|
let failure;
|
|
306
|
-
let
|
|
376
|
+
let kind;
|
|
307
377
|
try {
|
|
308
378
|
res = await config.fetchImpl(url, {
|
|
309
379
|
method: req.method,
|
|
@@ -313,10 +383,10 @@ async function send(config, req) {
|
|
|
313
383
|
});
|
|
314
384
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
315
385
|
if (res.ok) return { status: res.status, headers: res.headers, bytes };
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
retryClass = classifyStatus(apiError.status, apiError.code);
|
|
386
|
+
failure = errorFromResponse(res.status, bytes, res.headers);
|
|
387
|
+
kind = retryClass(failure);
|
|
319
388
|
} catch (err) {
|
|
389
|
+
signal?.throwIfAborted();
|
|
320
390
|
if (controller.signal.aborted) {
|
|
321
391
|
throw new BeliqApiError(
|
|
322
392
|
`beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
|
|
@@ -324,20 +394,21 @@ async function send(config, req) {
|
|
|
324
394
|
);
|
|
325
395
|
}
|
|
326
396
|
failure = err;
|
|
327
|
-
|
|
397
|
+
kind = retryClass(err);
|
|
328
398
|
} finally {
|
|
329
399
|
if (timer) clearTimeout(timer);
|
|
400
|
+
signal?.removeEventListener("abort", onCallerAbort);
|
|
330
401
|
}
|
|
331
|
-
if (
|
|
402
|
+
if (kind === "none") throw failure;
|
|
332
403
|
if (config.maxRetries !== void 0) {
|
|
333
404
|
if (attempt >= config.maxRetries) throw failure;
|
|
334
|
-
} else if (
|
|
405
|
+
} else if (kind === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
|
|
335
406
|
throw failure;
|
|
336
407
|
}
|
|
337
408
|
const delay = retryDelayMs(res, attempt, config);
|
|
338
409
|
if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
|
|
339
|
-
if (
|
|
340
|
-
await sleep(delay);
|
|
410
|
+
if (kind === "count") countedRetries++;
|
|
411
|
+
await sleep(delay, signal);
|
|
341
412
|
}
|
|
342
413
|
}
|
|
343
414
|
|
|
@@ -422,19 +493,20 @@ var Beliq = class {
|
|
|
422
493
|
};
|
|
423
494
|
}
|
|
424
495
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
425
|
-
async me() {
|
|
426
|
-
return this.#json({ operation: "me" });
|
|
496
|
+
async me(options = {}) {
|
|
497
|
+
return this.#json({ operation: "me" }, options.signal);
|
|
427
498
|
}
|
|
428
499
|
/** Generate an e-invoice from an EN 16931 object. */
|
|
429
|
-
async generate(input) {
|
|
500
|
+
async generate(input, options = {}) {
|
|
430
501
|
const res = await send(
|
|
431
502
|
this.#config,
|
|
432
|
-
buildRequest({ operation: "generate", ...input, sealed: input.seal })
|
|
503
|
+
buildRequest({ operation: "generate", ...input, sealed: input.seal }),
|
|
504
|
+
options.signal
|
|
433
505
|
);
|
|
434
506
|
const meta = generateMeta(res.headers);
|
|
435
507
|
if (input.seal) {
|
|
436
508
|
const envelope = parseEnvelope(res.bytes);
|
|
437
|
-
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
|
|
509
|
+
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
|
|
438
510
|
const data = envelope?.data;
|
|
439
511
|
if (!data || data.output === void 0) {
|
|
440
512
|
throw new BeliqApiError("beliq: seal response was not a JSON envelope", {
|
|
@@ -468,7 +540,7 @@ var Beliq = class {
|
|
|
468
540
|
validateFormat: options.format,
|
|
469
541
|
franceCtc: options.franceCtc,
|
|
470
542
|
ruleset: options.ruleset
|
|
471
|
-
});
|
|
543
|
+
}, options.signal);
|
|
472
544
|
}
|
|
473
545
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
474
546
|
async parse(document, options = {}) {
|
|
@@ -476,7 +548,7 @@ var Beliq = class {
|
|
|
476
548
|
operation: "parse",
|
|
477
549
|
...this.#rawParams(document, options),
|
|
478
550
|
parseFormat: options.format
|
|
479
|
-
});
|
|
551
|
+
}, options.signal);
|
|
480
552
|
}
|
|
481
553
|
/** Convert a document between EN 16931 formats. */
|
|
482
554
|
async convert(document, options) {
|
|
@@ -489,7 +561,8 @@ var Beliq = class {
|
|
|
489
561
|
targetFormat: options.targetFormat,
|
|
490
562
|
targetProfile: options.targetProfile,
|
|
491
563
|
dropFranceCtcOverlay: options.dropFranceCtcOverlay
|
|
492
|
-
})
|
|
564
|
+
}),
|
|
565
|
+
options.signal
|
|
493
566
|
);
|
|
494
567
|
return {
|
|
495
568
|
contentType: res.headers.get("content-type") ?? "application/octet-stream",
|
|
@@ -505,10 +578,10 @@ var Beliq = class {
|
|
|
505
578
|
advanced: options.advanced
|
|
506
579
|
};
|
|
507
580
|
}
|
|
508
|
-
async #json(params) {
|
|
509
|
-
const res = await send(this.#config, buildRequest(params));
|
|
581
|
+
async #json(params, signal) {
|
|
582
|
+
const res = await send(this.#config, buildRequest(params), signal);
|
|
510
583
|
const envelope = parseEnvelope(res.bytes);
|
|
511
|
-
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
|
|
584
|
+
if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
|
|
512
585
|
if (!envelope || envelope.data === void 0) {
|
|
513
586
|
throw new BeliqApiError("beliq: response was not a JSON envelope", { status: res.status });
|
|
514
587
|
}
|
|
@@ -531,5 +604,6 @@ export {
|
|
|
531
604
|
LIVE_PROFILES_BY_STANDARD,
|
|
532
605
|
LIVE_VALIDATE_FORMATS,
|
|
533
606
|
isProfileAllowedForStandard,
|
|
534
|
-
profilesForStandard
|
|
607
|
+
profilesForStandard,
|
|
608
|
+
retryClass
|
|
535
609
|
};
|
package/package.json
CHANGED