@beliq/sdk 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -4,6 +4,37 @@
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.0 - 2026-11-06
8
+
9
+ A minor, because a call that meets an outage can now take up to 15 minutes to
10
+ return, plus the last attempt's deadline, where 0.6 gave up after 3 retries,
11
+ and a `^0.6.0` range does not reach a minor.
12
+
13
+ - The client retries an outage by a time budget, the new option
14
+ `retryBudgetMs`, default `DEFAULT_RETRY_BUDGET_MS` (900000, 15 minutes from
15
+ the start of the first attempt). It covers a `503` `DATABASE_UNAVAILABLE`, a
16
+ `502` or `503` with no beliq error code, and a connection that could not be
17
+ opened (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`,
18
+ `EHOSTUNREACH`, `UND_ERR_CONNECT_TIMEOUT`).
19
+ 0.6 retried each of them 3 times, about 2 minutes at `Retry-After: 30`. No
20
+ attempt starts after the budget.
21
+ - Every wait follows the server's `Retry-After` in full. 0.6 cut the header to
22
+ 30 s. A `Retry-After` longer than the budget left ends the call at once with
23
+ that error.
24
+ - Without a `Retry-After`, no backoff wait reaches 30 s. Before, the wait
25
+ doubled with every attempt and had no ceiling.
26
+ - `maxRetries` keeps its default of 3 for everything else that is retried: a
27
+ `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED`, a `503` `ENGINE_UNAVAILABLE` and
28
+ any other `502` or `503` with a beliq error code, and any other thrown error.
29
+ When you set `maxRetries`, `DEFAULT_MAX_RETRIES` included, it bounds every
30
+ retry, the budget's included, so `maxRetries: 0` still turns retrying off.
31
+ - The README and the option comments no longer say that a retry never costs a
32
+ second quota unit. A `DATABASE_UNAVAILABLE` after the charge is refunded only
33
+ when the database lets it, a test key's units are never refunded, and a
34
+ connection lost after the request was sent can mean the first request was
35
+ charged. The README's table lists what is retried, which 0.6's README
36
+ understated: it left out the thrown errors.
37
+
7
38
  ## 0.6.0 - 2026-11-03
8
39
 
9
40
  A minor, because code can stop compiling in two places, and a `^0.5.0` range
package/README.md CHANGED
@@ -92,21 +92,64 @@ backoff around it.
92
92
  ```ts
93
93
  new Beliq({
94
94
  apiKey: 'blq_live_...',
95
- timeoutMs: 90_000, // per-attempt deadline (default)
96
- maxRetries: 3, // extra attempts after the first (default)
95
+ timeoutMs: 90_000, // per-attempt deadline (default)
96
+ retryBudgetMs: 900_000, // how long to keep retrying an outage: 15 minutes (default)
97
97
  });
98
98
  ```
99
99
 
100
- Both defaults are exported as `DEFAULT_TIMEOUT_MS` and `DEFAULT_MAX_RETRIES`, so
101
- you can derive from them instead of repeating the numbers.
102
-
103
- Only `429`, `502` and `503` are retried, honouring the server's `Retry-After`
104
- with jitter. beliq refunds the document's quota unit on a `503`, so a retry never
105
- costs you a second document.
100
+ Leave `maxRetries` unset unless you want to bound every retry: unset, it allows 3
101
+ retries of the failures retried by count and leaves the budget's failures to the
102
+ budget, while any number you pass, `DEFAULT_MAX_RETRIES` included, bounds them
103
+ all.
104
+
105
+ The defaults are exported as `DEFAULT_TIMEOUT_MS`, `DEFAULT_RETRY_BUDGET_MS` and
106
+ `DEFAULT_MAX_RETRIES`, so you can derive from them instead of repeating the
107
+ numbers.
108
+
109
+ | Failure | Retried |
110
+ |---|---|
111
+ | `503` `DATABASE_UNAVAILABLE` | until the budget is spent |
112
+ | `502` or `503` with no beliq error code, which a proxy in front of the API sends | until the budget is spent |
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
+ | `429` `RATE_LIMITED` or `ACCOUNT_THROTTLED` | up to `maxRetries` times |
115
+ | `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
+
119
+ Every wait follows the server's `Retry-After` in full, plus up to 250 ms of
120
+ jitter. Without one, the client backs off exponentially from 500 ms with jitter,
121
+ and no wait reaches 30 s. No attempt starts after the budget, so a `Retry-After`
122
+ longer than the time left ends the call at once with that error, and an outage
123
+ longer than the budget ends it with the last error. A call that meets an outage
124
+ can therefore take up to 15 minutes to return, plus the last attempt's own
125
+ deadline of up to `timeoutMs`. A host name that does not resolve counts as an
126
+ outage too, so a misspelt `baseUrl` takes the whole budget to fail. Where your
127
+ code cannot wait that long, such as inside a request with a time limit of its
128
+ own, pass a shorter `retryBudgetMs`. The 15 minutes are beliq's own choice, not
129
+ a standard's: they outlast two of the three database outages beliq has
130
+ measured, of about 9 and 12 minutes. The third lasted 33 minutes, and a call
131
+ that meets one like it ends with the last error.
132
+
133
+ `maxRetries: 0` turns retrying off, and so does `retryBudgetMs: 0`.
134
+
135
+ What a retry costs:
136
+
137
+ - Most `DATABASE_UNAVAILABLE` answers come before any quota unit is spent, and a
138
+ retry of one of those costs nothing. When the request had spent a unit, beliq
139
+ tries to refund it at once and says on the `x-beliq-quota-refunded` header
140
+ whether that worked. While the database is out, the refund usually cannot be
141
+ applied; https://docs.beliq.eu/api-reference/errors/ says how such a unit is
142
+ reconciled.
143
+ - The unit of an `ENGINE_UNAVAILABLE` is refunded, within the cap that page
144
+ names.
145
+ - A test key's sandbox units are never refunded.
146
+ - A connection lost after the request was sent can mean beliq already processed
147
+ it. A retry of `generate`, `validate`, `parse` or `convert` is then a second
148
+ request and spends a second unit.
106
149
 
107
150
  `504` and this client's own timeout are deliberately **not** retried: both mean
108
- the work may still be running on beliq's side, so retrying risks producing a
109
- second document rather than recovering the first.
151
+ the work may still be running on beliq's side, so a retry would run it, and
152
+ charge it, a second time.
110
153
 
111
154
  A `429` carrying `QUOTA_EXCEEDED` is not retried either. `RATE_LIMITED` and
112
155
  `ACCOUNT_THROTTLED` clear on their own, but a spent monthly allowance only returns
@@ -1,6 +1,6 @@
1
- import { P as PlainObject } from './types-Bc3c79Ss.cjs';
1
+ import { P as PlainObject } from './types-BjW5SogX.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-Bc3c79Ss.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-BjW5SogX.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-Bc3c79Ss.js';
1
+ import { P as PlainObject } from './types-BjW5SogX.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-Bc3c79Ss.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-BjW5SogX.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
@@ -24,6 +24,7 @@ __export(index_exports, {
24
24
  BeliqApiError: () => BeliqApiError,
25
25
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
26
26
  DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
27
+ DEFAULT_RETRY_BUDGET_MS: () => DEFAULT_RETRY_BUDGET_MS,
27
28
  DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
28
29
  LIVE_CONVERT_SOURCE_FORMATS: () => LIVE_CONVERT_SOURCE_FORMATS,
29
30
  LIVE_CONVERT_TARGET_FORMATS: () => LIVE_CONVERT_TARGET_FORMATS,
@@ -211,6 +212,7 @@ function errorFromResponse(status, bytes) {
211
212
  var DEFAULT_BASE_URL = "https://api.beliq.eu";
212
213
  var DEFAULT_TIMEOUT_MS = 9e4;
213
214
  var DEFAULT_MAX_RETRIES = 3;
215
+ var DEFAULT_RETRY_BUDGET_MS = 9e5;
214
216
  var LIVE_GENERATE_STANDARDS = [
215
217
  "xrechnung",
216
218
  "zugferd",
@@ -275,14 +277,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
275
277
  ];
276
278
 
277
279
  // src/transport.ts
278
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
279
280
  var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
280
- function isRetryable(status, code) {
281
- if (!RETRYABLE_STATUSES.has(status)) return false;
282
- return !(status === 429 && code === QUOTA_EXHAUSTED_CODE);
281
+ var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
282
+ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
283
+ "ECONNREFUSED",
284
+ "ENOTFOUND",
285
+ "EAI_AGAIN",
286
+ "ENETUNREACH",
287
+ "EHOSTUNREACH",
288
+ "UND_ERR_CONNECT_TIMEOUT"
289
+ ]);
290
+ function classifyStatus(status, code) {
291
+ if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
292
+ if (status !== 502 && status !== 503) return void 0;
293
+ if (!code) return "budget";
294
+ return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
295
+ }
296
+ function classifyThrown(err) {
297
+ const code = err?.cause?.code;
298
+ return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
283
299
  }
284
- var MAX_RETRY_AFTER_MS = 3e4;
285
300
  var BACKOFF_BASE_MS = 500;
301
+ var BACKOFF_CEILING_MS = 3e4;
302
+ var RETRY_AFTER_JITTER_MS = 250;
286
303
  function authHeaders(config) {
287
304
  return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
288
305
  }
@@ -296,15 +313,17 @@ function buildUrl(baseUrl, path, query) {
296
313
  const qs = params.toString();
297
314
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
298
315
  }
299
- function retryDelayMs(res, attempt) {
316
+ function retryDelayMs(res, attempt, config) {
300
317
  const header = res?.headers.get("retry-after");
301
318
  if (header) {
302
319
  const seconds = Number(header);
303
320
  if (Number.isFinite(seconds) && seconds >= 0) {
304
- return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS) + Math.random() * 250;
321
+ return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
305
322
  }
306
323
  }
307
- const backoff = BACKOFF_BASE_MS * 2 ** attempt;
324
+ const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
325
+ const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
326
+ const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
308
327
  return backoff + Math.random() * backoff;
309
328
  }
310
329
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -314,11 +333,14 @@ async function send(config, req) {
314
333
  if (req.accept) headers["Accept"] = req.accept;
315
334
  const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
316
335
  const url = buildUrl(config.baseUrl, req.path, req.query);
317
- let lastError;
318
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
336
+ const started = performance.now();
337
+ let countedRetries = 0;
338
+ for (let attempt = 0; ; attempt++) {
319
339
  const controller = new AbortController();
320
340
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
321
341
  let res;
342
+ let failure;
343
+ let retryClass;
322
344
  try {
323
345
  res = await config.fetchImpl(url, {
324
346
  method: req.method,
@@ -329,26 +351,31 @@ async function send(config, req) {
329
351
  const bytes = new Uint8Array(await res.arrayBuffer());
330
352
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
331
353
  const apiError = errorFromResponse(res.status, bytes);
332
- lastError = apiError;
333
- if (!isRetryable(apiError.status, apiError.code) || attempt === config.maxRetries) {
334
- throw apiError;
335
- }
354
+ failure = apiError;
355
+ retryClass = classifyStatus(apiError.status, apiError.code);
336
356
  } catch (err) {
337
- if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
338
357
  if (controller.signal.aborted) {
339
358
  throw new BeliqApiError(
340
359
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
341
360
  { status: 0, code: "TIMEOUT" }
342
361
  );
343
362
  }
344
- lastError = err;
345
- if (attempt === config.maxRetries) throw err;
363
+ failure = err;
364
+ retryClass = classifyThrown(err);
346
365
  } finally {
347
366
  if (timer) clearTimeout(timer);
348
367
  }
349
- await sleep(retryDelayMs(res, attempt));
368
+ if (retryClass === void 0) throw failure;
369
+ if (config.maxRetries !== void 0) {
370
+ if (attempt >= config.maxRetries) throw failure;
371
+ } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
372
+ throw failure;
373
+ }
374
+ const delay = retryDelayMs(res, attempt, config);
375
+ if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
376
+ if (retryClass === "count") countedRetries++;
377
+ await sleep(delay);
350
378
  }
351
- throw lastError;
352
379
  }
353
380
 
354
381
  // src/client.ts
@@ -427,7 +454,8 @@ var Beliq = class {
427
454
  auth: options.auth ?? "header",
428
455
  fetchImpl,
429
456
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
430
- maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES
457
+ maxRetries: options.maxRetries,
458
+ retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
431
459
  };
432
460
  }
433
461
  /** Account, plan, and quota context for the key. Does not consume quota. */
@@ -529,6 +557,7 @@ var Beliq = class {
529
557
  BeliqApiError,
530
558
  DEFAULT_BASE_URL,
531
559
  DEFAULT_MAX_RETRIES,
560
+ DEFAULT_RETRY_BUDGET_MS,
532
561
  DEFAULT_TIMEOUT_MS,
533
562
  LIVE_CONVERT_SOURCE_FORMATS,
534
563
  LIVE_CONVERT_TARGET_FORMATS,
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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-Bc3c79Ss.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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BjW5SogX.cjs';
2
2
  import { PlainObject } from './helpers.cjs';
3
- export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_TIMEOUT_MS, z as GenerateBody, G as GeneratePreset, B 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, E as ParseWarning, H as ParseWarningCode, J as Severity, K as ValidationFormat, M as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-Bc3c79Ss.cjs';
3
+ export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_RETRY_BUDGET_MS, z as DEFAULT_TIMEOUT_MS, B as GenerateBody, G as GeneratePreset, E 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, H as ParseWarning, J as ParseWarningCode, K as Severity, M as ValidationFormat, N as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BjW5SogX.cjs';
4
4
 
5
5
  interface BeliqOptions {
6
6
  /** API key from the beliq dashboard (API Keys). */
@@ -16,16 +16,27 @@ interface BeliqOptions {
16
16
  * the full Schematron rule set over a document, so a generate or validate can
17
17
  * take tens of seconds legitimately. Set well above the latency you expect:
18
18
  * a deadline shorter than the server's own means giving up on work that is
19
- * still running, which is the one case a retry can duplicate a document.
20
- * 0 disables the deadline.
19
+ * still running, and this client does not retry its own timeout, since the
20
+ * work may have finished. 0 disables the deadline.
21
21
  */
22
22
  timeoutMs?: number;
23
23
  /**
24
- * Extra attempts after the first (default 3). Retries only 429, 502 and 503,
25
- * honouring `Retry-After`; beliq refunds the quota unit on a 503, so a retry
26
- * costs nothing. 0 disables retrying.
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.
27
29
  */
28
30
  maxRetries?: number;
31
+ /**
32
+ * How long to keep retrying, in ms from the start of the first attempt
33
+ * (default 900000, 15 minutes). A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with
34
+ * no beliq error code, and a connection that could not be opened are retried
35
+ * until it is spent. Every wait follows the server's `Retry-After` in full; no
36
+ * attempt starts after the budget, so a `Retry-After` longer than what is left
37
+ * ends the call at once. 0 disables retrying.
38
+ */
39
+ retryBudgetMs?: number;
29
40
  }
30
41
  interface GenerateInput {
31
42
  standard: Standard;
package/dist/index.d.ts 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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-Bc3c79Ss.js';
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 ParseFormat, r as ParseResult, C as ConvertTargetFormat, u as ConvertSourceFormat, v as ApiErrorCode } from './types-BjW5SogX.js';
2
2
  import { PlainObject } from './helpers.js';
3
- export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_TIMEOUT_MS, z as GenerateBody, G as GeneratePreset, B 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, E as ParseWarning, H as ParseWarningCode, J as Severity, K as ValidationFormat, M as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-Bc3c79Ss.js';
3
+ export { w as ApiError, D as DEFAULT_BASE_URL, x as DEFAULT_MAX_RETRIES, y as DEFAULT_RETRY_BUDGET_MS, z as DEFAULT_TIMEOUT_MS, B as GenerateBody, G as GeneratePreset, E 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, H as ParseWarning, J as ParseWarningCode, K as Severity, M as ValidationFormat, N as ValidationIssue, l as isProfileAllowedForStandard, p as profilesForStandard } from './types-BjW5SogX.js';
4
4
 
5
5
  interface BeliqOptions {
6
6
  /** API key from the beliq dashboard (API Keys). */
@@ -16,16 +16,27 @@ interface BeliqOptions {
16
16
  * the full Schematron rule set over a document, so a generate or validate can
17
17
  * take tens of seconds legitimately. Set well above the latency you expect:
18
18
  * a deadline shorter than the server's own means giving up on work that is
19
- * still running, which is the one case a retry can duplicate a document.
20
- * 0 disables the deadline.
19
+ * still running, and this client does not retry its own timeout, since the
20
+ * work may have finished. 0 disables the deadline.
21
21
  */
22
22
  timeoutMs?: number;
23
23
  /**
24
- * Extra attempts after the first (default 3). Retries only 429, 502 and 503,
25
- * honouring `Retry-After`; beliq refunds the quota unit on a 503, so a retry
26
- * costs nothing. 0 disables retrying.
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.
27
29
  */
28
30
  maxRetries?: number;
31
+ /**
32
+ * How long to keep retrying, in ms from the start of the first attempt
33
+ * (default 900000, 15 minutes). A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with
34
+ * no beliq error code, and a connection that could not be opened are retried
35
+ * until it is spent. Every wait follows the server's `Retry-After` in full; no
36
+ * attempt starts after the budget, so a `Retry-After` longer than what is left
37
+ * ends the call at once. 0 disables retrying.
38
+ */
39
+ retryBudgetMs?: number;
29
40
  }
30
41
  interface GenerateInput {
31
42
  standard: Standard;
package/dist/index.js CHANGED
@@ -171,6 +171,7 @@ function errorFromResponse(status, bytes) {
171
171
  var DEFAULT_BASE_URL = "https://api.beliq.eu";
172
172
  var DEFAULT_TIMEOUT_MS = 9e4;
173
173
  var DEFAULT_MAX_RETRIES = 3;
174
+ var DEFAULT_RETRY_BUDGET_MS = 9e5;
174
175
  var LIVE_GENERATE_STANDARDS = [
175
176
  "xrechnung",
176
177
  "zugferd",
@@ -235,14 +236,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
235
236
  ];
236
237
 
237
238
  // src/transport.ts
238
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
239
239
  var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
240
- function isRetryable(status, code) {
241
- if (!RETRYABLE_STATUSES.has(status)) return false;
242
- return !(status === 429 && code === QUOTA_EXHAUSTED_CODE);
240
+ var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
241
+ var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
242
+ "ECONNREFUSED",
243
+ "ENOTFOUND",
244
+ "EAI_AGAIN",
245
+ "ENETUNREACH",
246
+ "EHOSTUNREACH",
247
+ "UND_ERR_CONNECT_TIMEOUT"
248
+ ]);
249
+ function classifyStatus(status, code) {
250
+ if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
251
+ if (status !== 502 && status !== 503) return void 0;
252
+ if (!code) return "budget";
253
+ return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
254
+ }
255
+ function classifyThrown(err) {
256
+ const code = err?.cause?.code;
257
+ return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
243
258
  }
244
- var MAX_RETRY_AFTER_MS = 3e4;
245
259
  var BACKOFF_BASE_MS = 500;
260
+ var BACKOFF_CEILING_MS = 3e4;
261
+ var RETRY_AFTER_JITTER_MS = 250;
246
262
  function authHeaders(config) {
247
263
  return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
248
264
  }
@@ -256,15 +272,17 @@ function buildUrl(baseUrl, path, query) {
256
272
  const qs = params.toString();
257
273
  return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
258
274
  }
259
- function retryDelayMs(res, attempt) {
275
+ function retryDelayMs(res, attempt, config) {
260
276
  const header = res?.headers.get("retry-after");
261
277
  if (header) {
262
278
  const seconds = Number(header);
263
279
  if (Number.isFinite(seconds) && seconds >= 0) {
264
- return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS) + Math.random() * 250;
280
+ return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
265
281
  }
266
282
  }
267
- const backoff = BACKOFF_BASE_MS * 2 ** attempt;
283
+ const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
284
+ const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
285
+ const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
268
286
  return backoff + Math.random() * backoff;
269
287
  }
270
288
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -274,11 +292,14 @@ async function send(config, req) {
274
292
  if (req.accept) headers["Accept"] = req.accept;
275
293
  const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
276
294
  const url = buildUrl(config.baseUrl, req.path, req.query);
277
- let lastError;
278
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
295
+ const started = performance.now();
296
+ let countedRetries = 0;
297
+ for (let attempt = 0; ; attempt++) {
279
298
  const controller = new AbortController();
280
299
  const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
281
300
  let res;
301
+ let failure;
302
+ let retryClass;
282
303
  try {
283
304
  res = await config.fetchImpl(url, {
284
305
  method: req.method,
@@ -289,26 +310,31 @@ async function send(config, req) {
289
310
  const bytes = new Uint8Array(await res.arrayBuffer());
290
311
  if (res.ok) return { status: res.status, headers: res.headers, bytes };
291
312
  const apiError = errorFromResponse(res.status, bytes);
292
- lastError = apiError;
293
- if (!isRetryable(apiError.status, apiError.code) || attempt === config.maxRetries) {
294
- throw apiError;
295
- }
313
+ failure = apiError;
314
+ retryClass = classifyStatus(apiError.status, apiError.code);
296
315
  } catch (err) {
297
- if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
298
316
  if (controller.signal.aborted) {
299
317
  throw new BeliqApiError(
300
318
  `beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
301
319
  { status: 0, code: "TIMEOUT" }
302
320
  );
303
321
  }
304
- lastError = err;
305
- if (attempt === config.maxRetries) throw err;
322
+ failure = err;
323
+ retryClass = classifyThrown(err);
306
324
  } finally {
307
325
  if (timer) clearTimeout(timer);
308
326
  }
309
- await sleep(retryDelayMs(res, attempt));
327
+ if (retryClass === void 0) throw failure;
328
+ if (config.maxRetries !== void 0) {
329
+ if (attempt >= config.maxRetries) throw failure;
330
+ } else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
331
+ throw failure;
332
+ }
333
+ const delay = retryDelayMs(res, attempt, config);
334
+ if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
335
+ if (retryClass === "count") countedRetries++;
336
+ await sleep(delay);
310
337
  }
311
- throw lastError;
312
338
  }
313
339
 
314
340
  // src/client.ts
@@ -387,7 +413,8 @@ var Beliq = class {
387
413
  auth: options.auth ?? "header",
388
414
  fetchImpl,
389
415
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
390
- maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES
416
+ maxRetries: options.maxRetries,
417
+ retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
391
418
  };
392
419
  }
393
420
  /** Account, plan, and quota context for the key. Does not consume quota. */
@@ -488,6 +515,7 @@ export {
488
515
  BeliqApiError,
489
516
  DEFAULT_BASE_URL,
490
517
  DEFAULT_MAX_RETRIES,
518
+ DEFAULT_RETRY_BUDGET_MS,
491
519
  DEFAULT_TIMEOUT_MS,
492
520
  LIVE_CONVERT_SOURCE_FORMATS,
493
521
  LIVE_CONVERT_TARGET_FORMATS,
@@ -18,8 +18,22 @@ declare const DEFAULT_BASE_URL = "https://api.beliq.eu";
18
18
  * still running, and cannot tell whether the document was produced.
19
19
  */
20
20
  declare const DEFAULT_TIMEOUT_MS = 90000;
21
- /** Extra attempts after the first, for 429 / 502 / 503 only. */
21
+ /**
22
+ * Extra attempts after the first for the failures retried by count: a 429 other
23
+ * than `QUOTA_EXCEEDED`, a 502 or 503 carrying any beliq error code but a 503
24
+ * `DATABASE_UNAVAILABLE`, and any thrown error but a connection that could not
25
+ * be opened, such as a connection lost after the request was sent.
26
+ */
22
27
  declare const DEFAULT_MAX_RETRIES = 3;
28
+ /**
29
+ * How long the client keeps retrying, from the start of the first attempt: 15
30
+ * minutes. A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code,
31
+ * and a connection that could not be opened are retried until it is spent. No
32
+ * standard sets the value: it is beliq's own, sized to outlast two of the three
33
+ * database outages beliq has measured, of about 9 and 12 minutes. The third
34
+ * lasted 33 minutes.
35
+ */
36
+ declare const DEFAULT_RETRY_BUDGET_MS = 900000;
23
37
  /**
24
38
  * Every `standard` POST /v1/generate accepts, in the order its enum lists them.
25
39
  * The four national formats are Schema-checked: their authority publishes a
@@ -1832,9 +1846,9 @@ interface operations {
1832
1846
  previousChannel: {
1833
1847
  /** @description The `versions.json` artefact key this row is about. Often this format's own `versionKey`, but not always: an overlay or a severity table that runs under the format's profiles decides its `previous` too, and names no format of its own. */
1834
1848
  versionKey: string;
1835
- /** @description The version `latest` serves for this artefact today. The other half of the pair to compare against `previousVersion`. */
1849
+ /** @description The version `latest` serves for this artefact on the UTC day of the request. The other half of the pair to compare against `previousVersion`. */
1836
1850
  servingVersion: string;
1837
- /** @description The version `Beliq-Ruleset: previous` resolves to for this artefact today, or null when the channel falls back to `latest` for it. Pin it exactly as `Beliq-Ruleset: <versionKey>:<previousVersion>` to reach it regardless. */
1851
+ /** @description The version `Beliq-Ruleset: previous` resolves to for this artefact on the UTC day of the request, or null when the channel falls back to `latest` for it. Pin it exactly as `Beliq-Ruleset: <versionKey>:<previousVersion>` to reach it regardless. */
1838
1852
  previousVersion: string | null;
1839
1853
  /**
1840
1854
  * @description Why `previous` reaches nothing for this artefact; null exactly when `previousVersion` is set. `sunset` = every retained version is past its `retainedUntil`, so not even an exact pin resolves. `notice-period` = the only retained version is the one standing in for `latest` until a scheduled bump takes effect, so there is nothing behind it yet. `superseded` = the authority made the successor mandatory, so Beliq will not choose the older ruleset on your behalf; an exact pin still reaches it until `retainedUntil`.
@@ -1982,5 +1996,5 @@ type ParseFormat = NonNullable<Query<'parseInvoice'>['format']>;
1982
1996
  type ConvertSourceFormat = NonNullable<Query<'convertInvoice'>['sourceFormat']>;
1983
1997
  type ConvertTargetFormat = Query<'convertInvoice'>['targetFormat'];
1984
1998
 
1985
- export { DEFAULT_BASE_URL as D, LIVE_CONVERT_SOURCE_FORMATS as L, LIVE_CONVERT_TARGET_FORMATS as b, LIVE_GENERATE_PRESETS as c, LIVE_GENERATE_STANDARDS as d, LIVE_PARSE_FORMATS as e, LIVE_PROFILES as f, LIVE_PROFILES_BY_STANDARD as g, LIVE_VALIDATE_FORMATS as h, compactQuery as i, decodeUtf8 as j, isPlainObject as k, isProfileAllowedForStandard as l, mergeDeep as m, profilesForStandard as p, sniffContentType as s, toBytes as t, DEFAULT_MAX_RETRIES as x, DEFAULT_TIMEOUT_MS as y };
1986
- export type { AccountInfo as A, GenerateResponse as B, ConvertTargetFormat as C, ParseWarning as E, FacturxProfile as F, GeneratePreset as G, ParseWarningCode as H, Invoice as I, Severity as J, ValidationFormat as K, ValidationIssue as M, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, ParseFormat as q, ParseResult as r, ConvertSourceFormat as u, ApiErrorCode as v, ApiError as w, GenerateBody as z };
1999
+ export { DEFAULT_BASE_URL as D, LIVE_CONVERT_SOURCE_FORMATS as L, LIVE_CONVERT_TARGET_FORMATS as b, LIVE_GENERATE_PRESETS as c, LIVE_GENERATE_STANDARDS as d, LIVE_PARSE_FORMATS as e, LIVE_PROFILES as f, LIVE_PROFILES_BY_STANDARD as g, LIVE_VALIDATE_FORMATS as h, compactQuery as i, decodeUtf8 as j, isPlainObject as k, isProfileAllowedForStandard as l, mergeDeep as m, profilesForStandard as p, sniffContentType as s, toBytes as t, DEFAULT_MAX_RETRIES as x, DEFAULT_RETRY_BUDGET_MS as y, DEFAULT_TIMEOUT_MS as z };
2000
+ export type { AccountInfo as A, GenerateBody as B, ConvertTargetFormat as C, GenerateResponse as E, FacturxProfile as F, GeneratePreset as G, ParseWarning as H, Invoice as I, ParseWarningCode as J, Severity as K, ValidationFormat as M, ValidationIssue as N, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, ParseFormat as q, ParseResult as r, ConvertSourceFormat as u, ApiErrorCode as v, ApiError as w };
@@ -18,8 +18,22 @@ declare const DEFAULT_BASE_URL = "https://api.beliq.eu";
18
18
  * still running, and cannot tell whether the document was produced.
19
19
  */
20
20
  declare const DEFAULT_TIMEOUT_MS = 90000;
21
- /** Extra attempts after the first, for 429 / 502 / 503 only. */
21
+ /**
22
+ * Extra attempts after the first for the failures retried by count: a 429 other
23
+ * than `QUOTA_EXCEEDED`, a 502 or 503 carrying any beliq error code but a 503
24
+ * `DATABASE_UNAVAILABLE`, and any thrown error but a connection that could not
25
+ * be opened, such as a connection lost after the request was sent.
26
+ */
22
27
  declare const DEFAULT_MAX_RETRIES = 3;
28
+ /**
29
+ * How long the client keeps retrying, from the start of the first attempt: 15
30
+ * minutes. A 503 `DATABASE_UNAVAILABLE`, a 502 or 503 with no beliq error code,
31
+ * and a connection that could not be opened are retried until it is spent. No
32
+ * standard sets the value: it is beliq's own, sized to outlast two of the three
33
+ * database outages beliq has measured, of about 9 and 12 minutes. The third
34
+ * lasted 33 minutes.
35
+ */
36
+ declare const DEFAULT_RETRY_BUDGET_MS = 900000;
23
37
  /**
24
38
  * Every `standard` POST /v1/generate accepts, in the order its enum lists them.
25
39
  * The four national formats are Schema-checked: their authority publishes a
@@ -1832,9 +1846,9 @@ interface operations {
1832
1846
  previousChannel: {
1833
1847
  /** @description The `versions.json` artefact key this row is about. Often this format's own `versionKey`, but not always: an overlay or a severity table that runs under the format's profiles decides its `previous` too, and names no format of its own. */
1834
1848
  versionKey: string;
1835
- /** @description The version `latest` serves for this artefact today. The other half of the pair to compare against `previousVersion`. */
1849
+ /** @description The version `latest` serves for this artefact on the UTC day of the request. The other half of the pair to compare against `previousVersion`. */
1836
1850
  servingVersion: string;
1837
- /** @description The version `Beliq-Ruleset: previous` resolves to for this artefact today, or null when the channel falls back to `latest` for it. Pin it exactly as `Beliq-Ruleset: <versionKey>:<previousVersion>` to reach it regardless. */
1851
+ /** @description The version `Beliq-Ruleset: previous` resolves to for this artefact on the UTC day of the request, or null when the channel falls back to `latest` for it. Pin it exactly as `Beliq-Ruleset: <versionKey>:<previousVersion>` to reach it regardless. */
1838
1852
  previousVersion: string | null;
1839
1853
  /**
1840
1854
  * @description Why `previous` reaches nothing for this artefact; null exactly when `previousVersion` is set. `sunset` = every retained version is past its `retainedUntil`, so not even an exact pin resolves. `notice-period` = the only retained version is the one standing in for `latest` until a scheduled bump takes effect, so there is nothing behind it yet. `superseded` = the authority made the successor mandatory, so Beliq will not choose the older ruleset on your behalf; an exact pin still reaches it until `retainedUntil`.
@@ -1982,5 +1996,5 @@ type ParseFormat = NonNullable<Query<'parseInvoice'>['format']>;
1982
1996
  type ConvertSourceFormat = NonNullable<Query<'convertInvoice'>['sourceFormat']>;
1983
1997
  type ConvertTargetFormat = Query<'convertInvoice'>['targetFormat'];
1984
1998
 
1985
- export { DEFAULT_BASE_URL as D, LIVE_CONVERT_SOURCE_FORMATS as L, LIVE_CONVERT_TARGET_FORMATS as b, LIVE_GENERATE_PRESETS as c, LIVE_GENERATE_STANDARDS as d, LIVE_PARSE_FORMATS as e, LIVE_PROFILES as f, LIVE_PROFILES_BY_STANDARD as g, LIVE_VALIDATE_FORMATS as h, compactQuery as i, decodeUtf8 as j, isPlainObject as k, isProfileAllowedForStandard as l, mergeDeep as m, profilesForStandard as p, sniffContentType as s, toBytes as t, DEFAULT_MAX_RETRIES as x, DEFAULT_TIMEOUT_MS as y };
1986
- export type { AccountInfo as A, GenerateResponse as B, ConvertTargetFormat as C, ParseWarning as E, FacturxProfile as F, GeneratePreset as G, ParseWarningCode as H, Invoice as I, Severity as J, ValidationFormat as K, ValidationIssue as M, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, ParseFormat as q, ParseResult as r, ConvertSourceFormat as u, ApiErrorCode as v, ApiError as w, GenerateBody as z };
1999
+ export { DEFAULT_BASE_URL as D, LIVE_CONVERT_SOURCE_FORMATS as L, LIVE_CONVERT_TARGET_FORMATS as b, LIVE_GENERATE_PRESETS as c, LIVE_GENERATE_STANDARDS as d, LIVE_PARSE_FORMATS as e, LIVE_PROFILES as f, LIVE_PROFILES_BY_STANDARD as g, LIVE_VALIDATE_FORMATS as h, compactQuery as i, decodeUtf8 as j, isPlainObject as k, isProfileAllowedForStandard as l, mergeDeep as m, profilesForStandard as p, sniffContentType as s, toBytes as t, DEFAULT_MAX_RETRIES as x, DEFAULT_RETRY_BUDGET_MS as y, DEFAULT_TIMEOUT_MS as z };
2000
+ export type { AccountInfo as A, GenerateBody as B, ConvertTargetFormat as C, GenerateResponse as E, FacturxProfile as F, GeneratePreset as G, ParseWarning as H, Invoice as I, ParseWarningCode as J, Severity as K, ValidationFormat as M, ValidationIssue as N, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, ParseFormat as q, ParseResult as r, ConvertSourceFormat as u, ApiErrorCode as v, ApiError as w };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beliq/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Official beliq SDK: validate, generate, convert and parse EU e-invoices (XRechnung, ZUGFeRD, Factur-X, Peppol BIS) with the beliq API from Node.js.",
5
5
  "keywords": [
6
6
  "beliq",