@beliq/sdk 0.7.2 → 0.7.4

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 CHANGED
@@ -4,6 +4,47 @@
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.4 - 2026-11-16
8
+
9
+ - A `429` carrying `DOCUMENT_CEILING_REACHED` is thrown at once and not
10
+ retried, like `QUOTA_EXCEEDED`, and `retryClass` returns `none` for it,
11
+ where it returned `count`. The API sends it when an org on usage billing
12
+ reaches its extra-document cap, or the ceiling above its monthly quota,
13
+ with a `Retry-After` to the end of the billing window. Raising the cap or
14
+ the plan clears it sooner. Before, the client retried it up to
15
+ `maxRetries` times.
16
+ - `ApiErrorCode` gains `DOCUMENT_CEILING_REACHED`, and the four admission
17
+ codes of the API document 0.27.0: `DOCUMENT_PROFILE_NOT_ACCEPTED`,
18
+ `FLOW_OUTSIDE_FRENCH_PERIMETER`, `RECIPIENT_ADDRESS_INVALID` and
19
+ `SEND_CANNOT_COMPOSE_FOR_NETWORK`.
20
+ - The README and the `package.json` description open with one sentence on
21
+ what beliq is.
22
+ - The vendored `openapi.json` is document `0.28.1` of the API, up from
23
+ `0.26.0`.
24
+
25
+ ## 0.7.3 - 2026-11-08
26
+
27
+ - `retryClass(error)` says how the client's retry loop treats a failure:
28
+ `budget` (retried until `retryBudgetMs` is spent), `count` (up to
29
+ `maxRetries` times) or `none`. The loop uses the same function. A caller
30
+ that turns the client's retry off, such as a connector inside a host with a
31
+ 30-second step limit, can hand a `budget` failure to the host's own retry.
32
+ The `RetryClass` type is exported too.
33
+ - `BeliqApiError` has `retryAfterSeconds`: the response's `Retry-After` when
34
+ it gave whole seconds, otherwise `undefined`. The retry loop now reads the
35
+ header the same way, as RFC 9110 delay-seconds: a value such as `1.5` or
36
+ `0x1E` was read as a number of seconds before and is now backed off from
37
+ like a missing header.
38
+ - Every method takes a `signal` (`generate` in a new second argument, `me`
39
+ in a new first one, the others in their options). It ends the call at once, during an
40
+ attempt or a wait between retries, with the signal's reason, and nothing is
41
+ sent when it is aborted already.
42
+ - A certificate that fails verification, or one for another name, is no
43
+ longer retried: it is thrown on the first attempt, as the Python SDK does.
44
+ It was retried up to 3 times. An OpenSSL error (`ERR_SSL_*`) is still
45
+ retried up to 3 times, since it can also come after the request was sent;
46
+ the Python SDK raises one from the handshake at once.
47
+
7
48
  ## 0.7.2 - 2026-11-07
8
49
 
9
50
  - `ValidationResult` has `rulesetSupersededOn`, from the API document
@@ -305,8 +346,8 @@ the changes below.
305
346
  currency) are typed on the invoice.
306
347
  - A scheduled ruleset change reports its capabilities.
307
348
  - The README's quick-start invoice is one the API accepts as-is.
308
- - An em-dash scrub gate runs over the whole tree before publish, and the
309
- release workflow carries job timeouts and refuses a tag that is not on `main`.
349
+ - The release workflow carries job timeouts and refuses a tag that is not on
350
+ `main`.
310
351
  - The `js-yaml` override floor is raised above GHSA-2883-xcg3-v3hh.
311
352
 
312
353
  ## 0.3.1 - 2026-09-02
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @beliq/sdk
2
2
 
3
+ beliq is the platform for European e-invoicing: one API to generate, validate, convert and parse e-invoices, with the rule pack, version and check depth on its verdicts.
4
+
3
5
  Official Node/TypeScript SDK for the [beliq](https://beliq.eu) API: validate, generate, convert and parse EU e-invoices (XRechnung, ZUGFeRD, Factur-X, Peppol BIS) from Node.js. A validation result names the rule pack that judged the document, its version and, in `verificationBadgeLabel` when the API states one, how deep the check went. [How verification works](https://docs.beliq.eu/compliance/how-verification-works/) explains each depth.
4
6
 
5
7
  beliq produces and checks the document. Transmission (Peppol, plateforme agréée, KSeF, SDI), archiving, and tax-authority reporting stay with your access point.
@@ -113,8 +115,9 @@ numbers.
113
115
  | 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
116
  | `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED` | up to `maxRetries` times |
115
117
  | `503` `ENGINE_UNAVAILABLE`, and any other `502` or `503` with a beliq error code | up to `maxRetries` times |
116
- | Any other thrown error, such as a connection lost after the request was sent | up to `maxRetries` times |
117
- | `429` `QUOTA_EXCEEDED`, `504`, this client's own timeout, and every other status | never |
118
+ | 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 |
119
+ | 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 |
120
+ | `429` `QUOTA_EXCEEDED` or `DOCUMENT_CEILING_REACHED`, `504`, this client's own timeout, and every other status | never |
118
121
 
119
122
  Every wait follows the server's `Retry-After` in full, plus up to 250 ms of
120
123
  jitter. Without one, the client backs off exponentially from 500 ms with jitter,
@@ -132,6 +135,59 @@ that meets one like it ends with the last error.
132
135
 
133
136
  `maxRetries: 0` turns retrying off, and so does `retryBudgetMs: 0`.
134
137
 
138
+ ### Retrying in a host with a time limit
139
+
140
+ Some hosts end a step long before an outage is over: an automation platform
141
+ that gives a step 30 seconds, or an MCP client that waits 60. There, turn the
142
+ client's retry off and hand an outage to the host's own retry:
143
+
144
+ ```ts
145
+ import { Beliq, retryClass } from '@beliq/sdk';
146
+
147
+ const beliq = new Beliq({ apiKey, retryBudgetMs: 0, timeoutMs: 25_000 });
148
+
149
+ try {
150
+ return await beliq.validate(xml);
151
+ } catch (err) {
152
+ if (retryClass(err) === 'budget') {
153
+ // A refused connection carries no header, so `wait` can be undefined.
154
+ const wait = (err as { retryAfterSeconds?: number }).retryAfterSeconds;
155
+ // Tell the host to try the step again after `wait` seconds.
156
+ }
157
+ throw err;
158
+ }
159
+ ```
160
+
161
+ `retryClass(error)` answers `budget`, `count` or `none`: the class of the
162
+ table above, "until the budget is spent", "up to `maxRetries` times" or
163
+ "never". The client's own retry loop uses the same function, so it is the
164
+ class the client acted on. An abort by your own `signal` (below) is not
165
+ classified: the loop ends at once, so check `signal.aborted` first.
166
+
167
+ `retryBudgetMs: 0` turns off the retries by count as well. The example hands
168
+ only the budget class to the host, so a `429` `RATE_LIMITED`, a `503`
169
+ `ENGINE_UNAVAILABLE` and a connection lost after the send then fail the step.
170
+ Hand those to the host too only if it bounds how often it retries: a repeat of
171
+ `ENGINE_UNAVAILABLE` runs the same slow document again.
172
+
173
+ `BeliqApiError` carries `retryAfterSeconds`, the response's `Retry-After` when
174
+ it gave whole seconds, and `undefined` for an HTTP date, any other form or no
175
+ header, as the loop reads it.
176
+
177
+ Every method takes a `signal`, an `AbortSignal` that ends the call at once,
178
+ during an attempt or a wait, with the signal's reason. A worker that stops on
179
+ `SIGTERM` passes one, so it does not sit in a `Retry-After` wait. Nothing is
180
+ sent when the signal is aborted already; an attempt already sent may still have
181
+ run on beliq's side.
182
+
183
+ ```ts
184
+ const stop = new AbortController();
185
+ process.once('SIGTERM', () => stop.abort());
186
+ await beliq.validate(xml, { signal: stop.signal });
187
+ await beliq.generate(input, { signal: stop.signal });
188
+ await beliq.me({ signal: stop.signal });
189
+ ```
190
+
135
191
  What a retry costs:
136
192
 
137
193
  - Most `DATABASE_UNAVAILABLE` answers come before any quota unit is spent, and a
@@ -158,10 +214,11 @@ What a retry costs:
158
214
  mean the work is still running on beliq's side, and a retry runs the same
159
215
  document again from the start, so it would likely run out of time again.
160
216
 
161
- A `429` carrying `QUOTA_EXCEEDED` is not retried either. `RATE_LIMITED` and
162
- `ACCOUNT_THROTTLED` clear on their own, but a spent monthly allowance only returns
163
- when your billing window turns, so the error is raised straight away and names the
164
- cause instead of sleeping against it.
217
+ A `429` carrying `QUOTA_EXCEEDED` or `DOCUMENT_CEILING_REACHED` is not retried
218
+ either. `RATE_LIMITED` and `ACCOUNT_THROTTLED` clear on their own, but a spent
219
+ monthly allowance, or the extra-document ceiling above it, does not return before
220
+ your billing window turns unless you raise your cap or your plan. So the error is
221
+ raised straight away and names the cause instead of sleeping against it.
165
222
 
166
223
  The default deadline is generous because beliq runs the full Schematron rule set
167
224
  over each document, and a generate or validate can legitimately take tens of
@@ -173,8 +230,8 @@ shorter than the server's own turns completed work into an unknown outcome. Set
173
230
 
174
231
  | Method | Endpoint | Input | Returns |
175
232
  |---|---|---|---|
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 }` |
233
+ | `me(options?)` | GET /v1/me | none | `AccountInfo` (no quota cost) |
234
+ | `generate(input, options?)` | POST /v1/generate | EN 16931 invoice object | `{ contentType, bytes, xml?, sha256?, validationResult?, meta }` |
178
235
  | `validate(document, options?)` | POST /v1/validate | XML or PDF | `ValidationResult` |
179
236
  | `parse(document, options?)` | POST /v1/parse | XML or PDF | `ParseResult` |
180
237
  | `convert(document, options)` | POST /v1/convert | XML or PDF | `{ contentType, bytes, meta }` |
@@ -259,7 +316,6 @@ npm install
259
316
  npm run build # tsup: dual ESM + CJS + d.ts
260
317
  npm run typecheck
261
318
  npm run lint
262
- npm run scrub:check # no em-dash in any tracked file
263
319
  npm test # unit tests (no network)
264
320
  BELIQ_API_KEY=blq_xxx npm run test:integration # hits the live API; draws quota
265
321
  ```
@@ -1,6 +1,6 @@
1
- import { P as PlainObject } from './types-B-aV1djO.cjs';
1
+ import { P as PlainObject } from './types-u5eeJLoG.cjs';
2
2
  import { ValidationResult } from './index.cjs';
3
- export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-B-aV1djO.cjs';
3
+ export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-u5eeJLoG.cjs';
4
4
 
5
5
  type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
6
6
  /** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
package/dist/helpers.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { P as PlainObject } from './types-B-aV1djO.js';
1
+ import { P as PlainObject } from './types-u5eeJLoG.js';
2
2
  import { ValidationResult } from './index.js';
3
- export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-B-aV1djO.js';
3
+ export { D as DEFAULT_BASE_URL, a as DocumentInput, G as GeneratePreset, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, i as compactQuery, j as decodeUtf8, k as isPlainObject, l as isProfileAllowedForStandard, m as mergeDeep, p as profilesForStandard, s as sniffContentType, t as toBytes } from './types-u5eeJLoG.js';
4
4
 
5
5
  type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
6
6
  /** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
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, { code: err?.code, status, details: err?.details });
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
@@ -281,7 +299,10 @@ var LIVE_CONVERT_TARGET_FORMATS = [
281
299
  ];
282
300
 
283
301
  // src/transport.ts
284
- var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
302
+ var QUOTA_EXHAUSTED_CODES = /* @__PURE__ */ new Set([
303
+ "QUOTA_EXCEEDED",
304
+ "DOCUMENT_CEILING_REACHED"
305
+ ]);
285
306
  var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
286
307
  var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
287
308
  "ECONNREFUSED",
@@ -291,15 +312,57 @@ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
291
312
  "EHOSTUNREACH",
292
313
  "UND_ERR_CONNECT_TIMEOUT"
293
314
  ]);
315
+ var CERTIFICATE_ERROR_CODES = /* @__PURE__ */ new Set([
316
+ "UNABLE_TO_GET_ISSUER_CERT",
317
+ "UNABLE_TO_GET_CRL",
318
+ "UNABLE_TO_DECRYPT_CERT_SIGNATURE",
319
+ "UNABLE_TO_DECRYPT_CRL_SIGNATURE",
320
+ "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
321
+ "CERT_SIGNATURE_FAILURE",
322
+ "CRL_SIGNATURE_FAILURE",
323
+ "CERT_NOT_YET_VALID",
324
+ "CERT_HAS_EXPIRED",
325
+ "CRL_NOT_YET_VALID",
326
+ "CRL_HAS_EXPIRED",
327
+ "ERROR_IN_CERT_NOT_BEFORE_FIELD",
328
+ "ERROR_IN_CERT_NOT_AFTER_FIELD",
329
+ "ERROR_IN_CRL_LAST_UPDATE_FIELD",
330
+ "ERROR_IN_CRL_NEXT_UPDATE_FIELD",
331
+ "OUT_OF_MEM",
332
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
333
+ "SELF_SIGNED_CERT_IN_CHAIN",
334
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
335
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
336
+ "CERT_CHAIN_TOO_LONG",
337
+ "CERT_REVOKED",
338
+ "INVALID_CA",
339
+ "PATH_LENGTH_EXCEEDED",
340
+ "INVALID_PURPOSE",
341
+ "CERT_UNTRUSTED",
342
+ "CERT_REJECTED",
343
+ "HOSTNAME_MISMATCH"
344
+ ]);
345
+ function isCertificateFailure(code) {
346
+ return CERTIFICATE_ERROR_CODES.has(code) || code === "ERR_TLS_CERT_ALTNAME_INVALID";
347
+ }
294
348
  function classifyStatus(status, code) {
295
- if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
296
- if (status !== 502 && status !== 503) return void 0;
349
+ if (status === 429) return code !== void 0 && QUOTA_EXHAUSTED_CODES.has(code) ? "none" : "count";
350
+ if (status !== 502 && status !== 503) return "none";
297
351
  if (!code) return "budget";
298
352
  return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
299
353
  }
300
354
  function classifyThrown(err) {
301
355
  const code = err?.cause?.code;
302
- return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
356
+ if (typeof code !== "string") return "count";
357
+ if (isCertificateFailure(code)) return "none";
358
+ return BEFORE_SEND_CODES.has(code) ? "budget" : "count";
359
+ }
360
+ function retryClass(error) {
361
+ if (error instanceof BeliqApiError || error?.name === "BeliqApiError" && typeof error.status === "number") {
362
+ const apiError = error;
363
+ return classifyStatus(apiError.status, apiError.code);
364
+ }
365
+ return classifyThrown(error);
303
366
  }
304
367
  var BACKOFF_BASE_MS = 500;
305
368
  var BACKOFF_CEILING_MS = 3e4;
@@ -318,20 +381,28 @@ function buildUrl(baseUrl, path, query) {
318
381
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
319
382
  }
320
383
  function retryDelayMs(res, attempt, config) {
321
- const header = res?.headers.get("retry-after");
322
- if (header) {
323
- const seconds = Number(header);
324
- if (Number.isFinite(seconds) && seconds >= 0) {
325
- return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
326
- }
327
- }
384
+ const seconds = parseRetryAfterSeconds(res?.headers);
385
+ if (seconds !== void 0) return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
328
386
  const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
329
387
  const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
330
388
  const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
331
389
  return backoff + Math.random() * backoff;
332
390
  }
333
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
334
- async function send(config, req) {
391
+ function sleep(ms, signal) {
392
+ return new Promise((resolve, reject) => {
393
+ signal?.throwIfAborted();
394
+ const onAbort = () => {
395
+ clearTimeout(timer);
396
+ reject(signal?.reason);
397
+ };
398
+ const timer = setTimeout(() => {
399
+ signal?.removeEventListener("abort", onAbort);
400
+ resolve();
401
+ }, ms);
402
+ signal?.addEventListener("abort", onAbort, { once: true });
403
+ });
404
+ }
405
+ async function send(config, req, signal) {
335
406
  const headers = { ...req.headers, ...authHeaders(config) };
336
407
  if (req.contentType) headers["Content-Type"] = req.contentType;
337
408
  if (req.accept) headers["Accept"] = req.accept;
@@ -340,11 +411,14 @@ async function send(config, req) {
340
411
  const started = performance.now();
341
412
  let countedRetries = 0;
342
413
  for (let attempt = 0; ; attempt++) {
414
+ signal?.throwIfAborted();
343
415
  const controller = new AbortController();
416
+ const onCallerAbort = () => controller.abort();
417
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
344
418
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
345
419
  let res;
346
420
  let failure;
347
- let retryClass;
421
+ let kind;
348
422
  try {
349
423
  res = await config.fetchImpl(url, {
350
424
  method: req.method,
@@ -354,10 +428,10 @@ async function send(config, req) {
354
428
  });
355
429
  const bytes = new Uint8Array(await res.arrayBuffer());
356
430
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
357
- const apiError = errorFromResponse(res.status, bytes);
358
- failure = apiError;
359
- retryClass = classifyStatus(apiError.status, apiError.code);
431
+ failure = errorFromResponse(res.status, bytes, res.headers);
432
+ kind = retryClass(failure);
360
433
  } catch (err) {
434
+ signal?.throwIfAborted();
361
435
  if (controller.signal.aborted) {
362
436
  throw new BeliqApiError(
363
437
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
@@ -365,20 +439,21 @@ async function send(config, req) {
365
439
  );
366
440
  }
367
441
  failure = err;
368
- retryClass = classifyThrown(err);
442
+ kind = retryClass(err);
369
443
  } finally {
370
444
  if (timer) clearTimeout(timer);
445
+ signal?.removeEventListener("abort", onCallerAbort);
371
446
  }
372
- if (retryClass === void 0) throw failure;
447
+ if (kind === "none") throw failure;
373
448
  if (config.maxRetries !== void 0) {
374
449
  if (attempt >= config.maxRetries) throw failure;
375
- } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
450
+ } else if (kind === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
376
451
  throw failure;
377
452
  }
378
453
  const delay = retryDelayMs(res, attempt, config);
379
454
  if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
380
- if (retryClass === "count") countedRetries++;
381
- await sleep(delay);
455
+ if (kind === "count") countedRetries++;
456
+ await sleep(delay, signal);
382
457
  }
383
458
  }
384
459
 
@@ -463,19 +538,20 @@ var Beliq = class {
463
538
  };
464
539
  }
465
540
  /** Account, plan, and quota context for the key. Does not consume quota. */
466
- async me() {
467
- return this.#json({ operation: "me" });
541
+ async me(options = {}) {
542
+ return this.#json({ operation: "me" }, options.signal);
468
543
  }
469
544
  /** Generate an e-invoice from an EN 16931 object. */
470
- async generate(input) {
545
+ async generate(input, options = {}) {
471
546
  const res = await send(
472
547
  this.#config,
473
- buildRequest({ operation: "generate", ...input, sealed: input.seal })
548
+ buildRequest({ operation: "generate", ...input, sealed: input.seal }),
549
+ options.signal
474
550
  );
475
551
  const meta = generateMeta(res.headers);
476
552
  if (input.seal) {
477
553
  const envelope = parseEnvelope(res.bytes);
478
- if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
554
+ if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
479
555
  const data = envelope?.data;
480
556
  if (!data || data.output === void 0) {
481
557
  throw new BeliqApiError("beliq: seal response was not a JSON envelope", {
@@ -509,7 +585,7 @@ var Beliq = class {
509
585
  validateFormat: options.format,
510
586
  franceCtc: options.franceCtc,
511
587
  ruleset: options.ruleset
512
- });
588
+ }, options.signal);
513
589
  }
514
590
  /** Parse a document into a structured EN 16931 invoice. */
515
591
  async parse(document, options = {}) {
@@ -517,7 +593,7 @@ var Beliq = class {
517
593
  operation: "parse",
518
594
  ...this.#rawParams(document, options),
519
595
  parseFormat: options.format
520
- });
596
+ }, options.signal);
521
597
  }
522
598
  /** Convert a document between EN 16931 formats. */
523
599
  async convert(document, options) {
@@ -530,7 +606,8 @@ var Beliq = class {
530
606
  targetFormat: options.targetFormat,
531
607
  targetProfile: options.targetProfile,
532
608
  dropFranceCtcOverlay: options.dropFranceCtcOverlay
533
- })
609
+ }),
610
+ options.signal
534
611
  );
535
612
  return {
536
613
  contentType: res.headers.get("content-type") ?? "application/octet-stream",
@@ -546,10 +623,10 @@ var Beliq = class {
546
623
  advanced: options.advanced
547
624
  };
548
625
  }
549
- async #json(params) {
550
- const res = await send(this.#config, buildRequest(params));
626
+ async #json(params, signal) {
627
+ const res = await send(this.#config, buildRequest(params), signal);
551
628
  const envelope = parseEnvelope(res.bytes);
552
- if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes);
629
+ if (envelope?.success === false) throw errorFromResponse(res.status, res.bytes, res.headers);
553
630
  if (!envelope || envelope.data === void 0) {
554
631
  throw new BeliqApiError("beliq: response was not a JSON envelope", { status: res.status });
555
632
  }
@@ -573,5 +650,6 @@ var Beliq = class {
573
650
  LIVE_PROFILES_BY_STANDARD,
574
651
  LIVE_VALIDATE_FORMATS,
575
652
  isProfileAllowedForStandard,
576
- profilesForStandard
653
+ profilesForStandard,
654
+ retryClass
577
655
  });
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as RulesetChannel, r as ParseFormat, u as ParseResult, C as ConvertTargetFormat, v as ConvertSourceFormat, w as ApiErrorCode } from './types-B-aV1djO.cjs';
1
+ import { A as AccountInfo, S as Standard, I as Invoice, n as GenerateProfile, F as FacturxProfile, V as ValidationResult, R as RulesetArtifact, a as DocumentInput, o as ValidateFormat, q as RulesetChannel, r as ParseFormat, u as ParseResult, C as ConvertTargetFormat, v as ConvertSourceFormat, w as ApiErrorCode } from './types-u5eeJLoG.cjs';
2
2
  import { PlainObject } from './helpers.cjs';
3
- export { x as ApiError, D as DEFAULT_BASE_URL, y as DEFAULT_MAX_RETRIES, z as DEFAULT_RETRY_BUDGET_MS, B as DEFAULT_TIMEOUT_MS, E as GenerateBody, G as GeneratePreset, H as GenerateResponse, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, J as ParseWarning, K as ParseWarningCode, M as Severity, N as ValidationFormat, O as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-B-aV1djO.cjs';
3
+ export { x as ApiError, D as DEFAULT_BASE_URL, y as DEFAULT_MAX_RETRIES, z as DEFAULT_RETRY_BUDGET_MS, B as DEFAULT_TIMEOUT_MS, E as GenerateBody, G as GeneratePreset, H as GenerateResponse, L as LIVE_CONVERT_SOURCE_FORMATS, b as LIVE_CONVERT_TARGET_FORMATS, c as LIVE_GENERATE_PRESETS, d as LIVE_GENERATE_STANDARDS, e as LIVE_PARSE_FORMATS, f as LIVE_PROFILES, g as LIVE_PROFILES_BY_STANDARD, h as LIVE_VALIDATE_FORMATS, J as ParseWarning, K as ParseWarningCode, M as Severity, N as ValidationFormat, O as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-u5eeJLoG.cjs';
4
4
 
5
5
  interface BeliqOptions {
6
6
  /** API key from the beliq dashboard (API Keys). */
@@ -22,10 +22,11 @@ interface BeliqOptions {
22
22
  timeoutMs?: number;
23
23
  /**
24
24
  * Extra attempts after the first for the failures retried by count (default
25
- * 3): a 429 other than `QUOTA_EXCEEDED`, a 502 or 503 carrying any beliq error
26
- * code but a 503 `DATABASE_UNAVAILABLE`, and any thrown error but a connection
27
- * that could not be opened, such as a connection lost after the request was
28
- * sent. When you set it, it bounds every retry, so 0 disables retrying.
25
+ * 3): a 429 other than `QUOTA_EXCEEDED` and `DOCUMENT_CEILING_REACHED`, a
26
+ * 502 or 503 carrying any beliq error code but a 503 `DATABASE_UNAVAILABLE`,
27
+ * and any thrown error but a connection that could not be opened, such as a
28
+ * connection lost after the request was sent. When you set it, it bounds
29
+ * every retry, so 0 disables retrying.
29
30
  */
30
31
  maxRetries?: number;
31
32
  /**
@@ -60,7 +61,17 @@ interface GenerateInput {
60
61
  /** Raw JSON deep-merged into the request body. */
61
62
  advanced?: PlainObject;
62
63
  }
63
- interface DocumentOptions {
64
+ /** Options every method takes. */
65
+ interface RequestOptions {
66
+ /**
67
+ * Ends the call at once with the signal's reason, during an attempt or a
68
+ * wait between retries, so a worker that stops does not sit in a
69
+ * `Retry-After` wait. Nothing is sent when it is aborted already. An attempt
70
+ * already sent may still have run on beliq's side.
71
+ */
72
+ signal?: AbortSignal;
73
+ }
74
+ interface DocumentOptions extends RequestOptions {
64
75
  /** Override the sniffed request content type (application/xml | application/pdf). */
65
76
  contentType?: string;
66
77
  /**
@@ -169,9 +180,9 @@ declare class Beliq {
169
180
  readonly livemode: boolean;
170
181
  constructor(options: BeliqOptions);
171
182
  /** Account, plan, and quota context for the key. Does not consume quota. */
172
- me(): Promise<AccountInfo>;
183
+ me(options?: RequestOptions): Promise<AccountInfo>;
173
184
  /** Generate an e-invoice from an EN 16931 object. */
174
- generate(input: GenerateInput): Promise<GenerateResult>;
185
+ generate(input: GenerateInput, options?: RequestOptions): Promise<GenerateResult>;
175
186
  /** Validate a document. The result names the rules that ran and, in `verificationBadgeLabel` when the API states one, the check depth. */
176
187
  validate(document: DocumentInput, options?: ValidateOptions): Promise<ValidationResult>;
177
188
  /** Parse a document into a structured EN 16931 invoice. */
@@ -189,12 +200,56 @@ declare class BeliqApiError extends Error {
189
200
  readonly code?: ApiErrorCode | string;
190
201
  readonly status: number;
191
202
  readonly details?: Record<string, unknown>;
203
+ /**
204
+ * The response's `Retry-After` in seconds, when it gave one as whole seconds
205
+ * (RFC 9110 delay-seconds); `undefined` otherwise, an HTTP date included. The retry loop reads
206
+ * the header the same way, so this is the wait it would have taken.
207
+ */
208
+ readonly retryAfterSeconds?: number;
192
209
  constructor(message: string, opts: {
193
210
  code?: ApiErrorCode | string;
194
211
  status: number;
195
212
  details?: Record<string, unknown>;
213
+ retryAfterSeconds?: number;
196
214
  });
197
215
  }
198
216
 
199
- export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult };
200
- export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };
217
+ /**
218
+ * How a failure is retried.
219
+ *
220
+ * `budget`: an outage a wait can outlast, retried until the time budget is spent.
221
+ * A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code (the edge
222
+ * answered, or the pod that held the connection is gone), and a connection that
223
+ * could not be opened.
224
+ *
225
+ * `count`: retried up to `maxRetries` times. A 429 other than `QUOTA_EXCEEDED`
226
+ * and `DOCUMENT_CEILING_REACHED`, since each one counts toward the account's
227
+ * throttle; a 502 or 503 with any other beliq code, `ENGINE_UNAVAILABLE`
228
+ * included, since an engine timeout answers that code too and a budget would run
229
+ * the same slow document dozens of times; and a thrown error that may have come
230
+ * after the request was sent. beliq may have run and charged that request, but
231
+ * it does not charge a repeat of a charged request within 15 minutes, up to 10
232
+ * repeats (beliq's own values, which no standard sets), and every attempt sends
233
+ * the same bytes.
234
+ *
235
+ * `none`: not retried. A 504 and this client's own timeout mean the work may
236
+ * still be running on beliq's side, and a repeat runs the same document again
237
+ * from the start, likely into the same deadline. A certificate failure and
238
+ * every other status are final too.
239
+ */
240
+ type RetryClass = 'budget' | 'count' | 'none';
241
+ /**
242
+ * How the client's retry loop treats a failure that a `Beliq` method threw, so
243
+ * a caller that turns the client's retry off can hand the failure to a retry
244
+ * of its own. The loop uses this same function, so its answer is the one the
245
+ * loop acted on: `budget` was retried until `retryBudgetMs` was spent, `count`
246
+ * up to `maxRetries` times, `none` not at all. It reads a `BeliqApiError` by its
247
+ * status and code, `TIMEOUT` (this client's own deadline) as `none`, and any
248
+ * other error by its `cause.code`, as `fetch` throws it. An abort by the
249
+ * caller's own `signal` throws the signal's reason, which the loop never
250
+ * classifies: check the signal's `aborted` before asking this.
251
+ */
252
+ declare function retryClass(error: unknown): RetryClass;
253
+
254
+ export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult, retryClass };
255
+ export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, RequestOptions, RetryClass, ValidateOptions };