@beliq/sdk 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +66 -10
- package/dist/helpers.cjs +4 -0
- package/dist/helpers.d.cts +6 -2
- package/dist/helpers.d.ts +6 -2
- package/dist/helpers.js +4 -0
- package/dist/index.cjs +56 -22
- package/dist/index.d.cts +35 -8
- package/dist/index.d.ts +35 -8
- package/dist/index.js +55 -22
- package/dist/{types-Bc3c79Ss.d.cts → types-l-8PFJA8.d.cts} +21 -5
- package/dist/{types-Bc3c79Ss.d.ts → types-l-8PFJA8.d.ts} +21 -5
- package/package.json +1 -1
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.1 - 2026-11-06
|
|
8
|
+
|
|
9
|
+
- `validate` takes a `ruleset` option, sent as the `Beliq-Ruleset` header: a
|
|
10
|
+
channel (`latest` or `previous`) or comma-separated `<artifactKey>:<version>`
|
|
11
|
+
pins. Unset, no header is sent, as before, so an organisation's default
|
|
12
|
+
channel still applies. The new `RulesetChannel` type is the channel names the
|
|
13
|
+
API reports in `rulesetChannel`.
|
|
14
|
+
- `BuiltRequest` from `@beliq/sdk/helpers` has an optional `headers` field, and
|
|
15
|
+
`BuildParams` an optional `ruleset`.
|
|
16
|
+
|
|
17
|
+
## 0.7.0 - 2026-11-06
|
|
18
|
+
|
|
19
|
+
A minor, because a call that meets an outage can now take up to 15 minutes to
|
|
20
|
+
return, plus the last attempt's deadline, where 0.6 gave up after 3 retries,
|
|
21
|
+
and a `^0.6.0` range does not reach a minor.
|
|
22
|
+
|
|
23
|
+
- The client retries an outage by a time budget, the new option
|
|
24
|
+
`retryBudgetMs`, default `DEFAULT_RETRY_BUDGET_MS` (900000, 15 minutes from
|
|
25
|
+
the start of the first attempt). It covers a `503` `DATABASE_UNAVAILABLE`, a
|
|
26
|
+
`502` or `503` with no beliq error code, and a connection that could not be
|
|
27
|
+
opened (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`,
|
|
28
|
+
`EHOSTUNREACH`, `UND_ERR_CONNECT_TIMEOUT`).
|
|
29
|
+
0.6 retried each of them 3 times, about 2 minutes at `Retry-After: 30`. No
|
|
30
|
+
attempt starts after the budget.
|
|
31
|
+
- Every wait follows the server's `Retry-After` in full. 0.6 cut the header to
|
|
32
|
+
30 s. A `Retry-After` longer than the budget left ends the call at once with
|
|
33
|
+
that error.
|
|
34
|
+
- Without a `Retry-After`, no backoff wait reaches 30 s. Before, the wait
|
|
35
|
+
doubled with every attempt and had no ceiling.
|
|
36
|
+
- `maxRetries` keeps its default of 3 for everything else that is retried: a
|
|
37
|
+
`429` `RATE_LIMITED` or `ACCOUNT_THROTTLED`, a `503` `ENGINE_UNAVAILABLE` and
|
|
38
|
+
any other `502` or `503` with a beliq error code, and any other thrown error.
|
|
39
|
+
When you set `maxRetries`, `DEFAULT_MAX_RETRIES` included, it bounds every
|
|
40
|
+
retry, the budget's included, so `maxRetries: 0` still turns retrying off.
|
|
41
|
+
- The README and the option comments no longer say that a retry never costs a
|
|
42
|
+
second quota unit. A `DATABASE_UNAVAILABLE` after the charge is refunded only
|
|
43
|
+
when the database lets it, a test key's units are never refunded, and a
|
|
44
|
+
connection lost after the request was sent can mean the first request was
|
|
45
|
+
charged. The README's table lists what is retried, which 0.6's README
|
|
46
|
+
understated: it left out the thrown errors.
|
|
47
|
+
|
|
7
48
|
## 0.6.0 - 2026-11-03
|
|
8
49
|
|
|
9
50
|
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,
|
|
96
|
-
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
|
109
|
-
|
|
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
|
|
@@ -143,6 +186,19 @@ const ok = createHash('sha256').update(doc.bytes).digest('hex') === doc.sha256;
|
|
|
143
186
|
console.log(doc.validationResult?.valid, doc.meta.rulesetSha256, ok);
|
|
144
187
|
```
|
|
145
188
|
|
|
189
|
+
### Choosing the ruleset
|
|
190
|
+
|
|
191
|
+
`validate` checks a document against the latest rules unless you choose otherwise. `ruleset` chooses: `'previous'` runs the retained rules before the latest, where the format has any, and comma-separated `<artifactKey>:<version>` pins run exact versions, with the keys and versions `GET /v1/rulesets` lists. The SDK sends the value as given, in the `Beliq-Ruleset` header. Left unset, it sends no header, and the API runs your organisation's default channel, which is `latest` unless your organisation chose `previous` in the dashboard.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const result = await beliq.validate(xml, { ruleset: 'previous' });
|
|
195
|
+
console.log(result.rulesetChannel, result.rulesetFellBack, result.rulesetArtifacts);
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The result says what applied. `rulesetChannel` and `rulesetFellBack` say which channel: `rulesetFellBack: true` means the format had nothing for `previous` to reach, so the latest rules ran. Under exact pins `rulesetChannel` reads `latest`, whatever version a pin ran. `rulesetArtifacts` and the per-format version fields, such as `schematronVersion`, say which rules ran, and `rulesetSunsetsOn` says until when a retained ruleset is served. `GET /v1/rulesets` gives each format's `previousChannel`: what `previous` reaches for it today.
|
|
199
|
+
|
|
200
|
+
The API answers a malformed value with a 400 `VALIDATION_ERROR` before any quota is used. It answers a pin to a version it no longer serves with a 422 `VALIDATION_ERROR`, and that request uses up a document. The API's `Beliq-Ruleset-Resolved` response header is not returned: it is built from the request, so for pins it repeats the pins sent even when a pinned artifact did not run. `rulesetArtifacts` says what ran.
|
|
201
|
+
|
|
146
202
|
### Curated option lists
|
|
147
203
|
|
|
148
204
|
`LIVE_GENERATE_PRESETS` is the set of public generate targets beliq.eu itself offers, each mapping to the API `standard` (plus `profile`/`facturxProfile`) it needs. NLCIUS is a Peppol BIS profile and lives here rather than in `LIVE_GENERATE_STANDARDS`. Connectors build their dropdowns from these lists.
|
package/dist/helpers.cjs
CHANGED
|
@@ -137,6 +137,10 @@ function buildRequest(params) {
|
|
|
137
137
|
query: withAdvancedQuery(query, params.advanced),
|
|
138
138
|
rawBody: params.rawBody,
|
|
139
139
|
contentType: params.rawContentType ?? "application/xml",
|
|
140
|
+
// No header unless the caller chose one: without it the API runs the
|
|
141
|
+
// organisation's default channel, which a sent `latest` would override.
|
|
142
|
+
// `!= null`: a plain-JS caller's null means unset too, not the string "null".
|
|
143
|
+
...params.ruleset != null ? { headers: { "Beliq-Ruleset": params.ruleset } } : {},
|
|
140
144
|
outputKind: "json"
|
|
141
145
|
};
|
|
142
146
|
}
|
package/dist/helpers.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as PlainObject } from './types-
|
|
1
|
+
import { P as PlainObject } from './types-l-8PFJA8.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-
|
|
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-l-8PFJA8.cjs';
|
|
4
4
|
|
|
5
5
|
type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
|
|
6
6
|
/** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
|
|
@@ -22,6 +22,8 @@ interface BuildParams {
|
|
|
22
22
|
rawContentType?: string;
|
|
23
23
|
validateFormat?: string;
|
|
24
24
|
franceCtc?: boolean;
|
|
25
|
+
/** Sent as the `Beliq-Ruleset` header, as given; unset sends no header. */
|
|
26
|
+
ruleset?: string;
|
|
25
27
|
parseFormat?: string;
|
|
26
28
|
sourceFormat?: string;
|
|
27
29
|
targetFormat?: string;
|
|
@@ -42,6 +44,8 @@ interface BuiltRequest {
|
|
|
42
44
|
contentType?: string;
|
|
43
45
|
/** Accept header; set when the caller wants a JSON envelope from an otherwise-binary op. */
|
|
44
46
|
accept?: string;
|
|
47
|
+
/** Further request headers, such as `Beliq-Ruleset` on validate. */
|
|
48
|
+
headers?: Record<string, string>;
|
|
45
49
|
outputKind: OutputKind;
|
|
46
50
|
}
|
|
47
51
|
declare function buildRequest(params: BuildParams): BuiltRequest;
|
package/dist/helpers.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as PlainObject } from './types-
|
|
1
|
+
import { P as PlainObject } from './types-l-8PFJA8.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-
|
|
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-l-8PFJA8.js';
|
|
4
4
|
|
|
5
5
|
type Operation = 'me' | 'generate' | 'validate' | 'parse' | 'convert';
|
|
6
6
|
/** 'json' => parse the `{ success, data }` envelope; 'binary' => return raw bytes. */
|
|
@@ -22,6 +22,8 @@ interface BuildParams {
|
|
|
22
22
|
rawContentType?: string;
|
|
23
23
|
validateFormat?: string;
|
|
24
24
|
franceCtc?: boolean;
|
|
25
|
+
/** Sent as the `Beliq-Ruleset` header, as given; unset sends no header. */
|
|
26
|
+
ruleset?: string;
|
|
25
27
|
parseFormat?: string;
|
|
26
28
|
sourceFormat?: string;
|
|
27
29
|
targetFormat?: string;
|
|
@@ -42,6 +44,8 @@ interface BuiltRequest {
|
|
|
42
44
|
contentType?: string;
|
|
43
45
|
/** Accept header; set when the caller wants a JSON envelope from an otherwise-binary op. */
|
|
44
46
|
accept?: string;
|
|
47
|
+
/** Further request headers, such as `Beliq-Ruleset` on validate. */
|
|
48
|
+
headers?: Record<string, string>;
|
|
45
49
|
outputKind: OutputKind;
|
|
46
50
|
}
|
|
47
51
|
declare function buildRequest(params: BuildParams): BuiltRequest;
|
package/dist/helpers.js
CHANGED
|
@@ -85,6 +85,10 @@ function buildRequest(params) {
|
|
|
85
85
|
query: withAdvancedQuery(query, params.advanced),
|
|
86
86
|
rawBody: params.rawBody,
|
|
87
87
|
contentType: params.rawContentType ?? "application/xml",
|
|
88
|
+
// No header unless the caller chose one: without it the API runs the
|
|
89
|
+
// organisation's default channel, which a sent `latest` would override.
|
|
90
|
+
// `!= null`: a plain-JS caller's null means unset too, not the string "null".
|
|
91
|
+
...params.ruleset != null ? { headers: { "Beliq-Ruleset": params.ruleset } } : {},
|
|
88
92
|
outputKind: "json"
|
|
89
93
|
};
|
|
90
94
|
}
|
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,
|
|
@@ -137,6 +138,10 @@ function buildRequest(params) {
|
|
|
137
138
|
query: withAdvancedQuery(query, params.advanced),
|
|
138
139
|
rawBody: params.rawBody,
|
|
139
140
|
contentType: params.rawContentType ?? "application/xml",
|
|
141
|
+
// No header unless the caller chose one: without it the API runs the
|
|
142
|
+
// organisation's default channel, which a sent `latest` would override.
|
|
143
|
+
// `!= null`: a plain-JS caller's null means unset too, not the string "null".
|
|
144
|
+
...params.ruleset != null ? { headers: { "Beliq-Ruleset": params.ruleset } } : {},
|
|
140
145
|
outputKind: "json"
|
|
141
146
|
};
|
|
142
147
|
}
|
|
@@ -211,6 +216,7 @@ function errorFromResponse(status, bytes) {
|
|
|
211
216
|
var DEFAULT_BASE_URL = "https://api.beliq.eu";
|
|
212
217
|
var DEFAULT_TIMEOUT_MS = 9e4;
|
|
213
218
|
var DEFAULT_MAX_RETRIES = 3;
|
|
219
|
+
var DEFAULT_RETRY_BUDGET_MS = 9e5;
|
|
214
220
|
var LIVE_GENERATE_STANDARDS = [
|
|
215
221
|
"xrechnung",
|
|
216
222
|
"zugferd",
|
|
@@ -275,14 +281,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
|
|
|
275
281
|
];
|
|
276
282
|
|
|
277
283
|
// src/transport.ts
|
|
278
|
-
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
|
|
279
284
|
var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
285
|
+
var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
|
|
286
|
+
var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
|
|
287
|
+
"ECONNREFUSED",
|
|
288
|
+
"ENOTFOUND",
|
|
289
|
+
"EAI_AGAIN",
|
|
290
|
+
"ENETUNREACH",
|
|
291
|
+
"EHOSTUNREACH",
|
|
292
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
293
|
+
]);
|
|
294
|
+
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;
|
|
297
|
+
if (!code) return "budget";
|
|
298
|
+
return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
|
|
299
|
+
}
|
|
300
|
+
function classifyThrown(err) {
|
|
301
|
+
const code = err?.cause?.code;
|
|
302
|
+
return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
|
|
283
303
|
}
|
|
284
|
-
var MAX_RETRY_AFTER_MS = 3e4;
|
|
285
304
|
var BACKOFF_BASE_MS = 500;
|
|
305
|
+
var BACKOFF_CEILING_MS = 3e4;
|
|
306
|
+
var RETRY_AFTER_JITTER_MS = 250;
|
|
286
307
|
function authHeaders(config) {
|
|
287
308
|
return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
|
|
288
309
|
}
|
|
@@ -296,29 +317,34 @@ function buildUrl(baseUrl, path, query) {
|
|
|
296
317
|
const qs = params.toString();
|
|
297
318
|
return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
|
|
298
319
|
}
|
|
299
|
-
function retryDelayMs(res, attempt) {
|
|
320
|
+
function retryDelayMs(res, attempt, config) {
|
|
300
321
|
const header = res?.headers.get("retry-after");
|
|
301
322
|
if (header) {
|
|
302
323
|
const seconds = Number(header);
|
|
303
324
|
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
304
|
-
return
|
|
325
|
+
return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
305
326
|
}
|
|
306
327
|
}
|
|
307
|
-
const
|
|
328
|
+
const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
|
|
329
|
+
const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
|
|
330
|
+
const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
|
|
308
331
|
return backoff + Math.random() * backoff;
|
|
309
332
|
}
|
|
310
333
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
311
334
|
async function send(config, req) {
|
|
312
|
-
const headers = { ...authHeaders(config) };
|
|
335
|
+
const headers = { ...req.headers, ...authHeaders(config) };
|
|
313
336
|
if (req.contentType) headers["Content-Type"] = req.contentType;
|
|
314
337
|
if (req.accept) headers["Accept"] = req.accept;
|
|
315
338
|
const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
|
|
316
339
|
const url = buildUrl(config.baseUrl, req.path, req.query);
|
|
317
|
-
|
|
318
|
-
|
|
340
|
+
const started = performance.now();
|
|
341
|
+
let countedRetries = 0;
|
|
342
|
+
for (let attempt = 0; ; attempt++) {
|
|
319
343
|
const controller = new AbortController();
|
|
320
344
|
const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
|
|
321
345
|
let res;
|
|
346
|
+
let failure;
|
|
347
|
+
let retryClass;
|
|
322
348
|
try {
|
|
323
349
|
res = await config.fetchImpl(url, {
|
|
324
350
|
method: req.method,
|
|
@@ -329,26 +355,31 @@ async function send(config, req) {
|
|
|
329
355
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
330
356
|
if (res.ok) return { status: res.status, headers: res.headers, bytes };
|
|
331
357
|
const apiError = errorFromResponse(res.status, bytes);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
throw apiError;
|
|
335
|
-
}
|
|
358
|
+
failure = apiError;
|
|
359
|
+
retryClass = classifyStatus(apiError.status, apiError.code);
|
|
336
360
|
} catch (err) {
|
|
337
|
-
if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
|
|
338
361
|
if (controller.signal.aborted) {
|
|
339
362
|
throw new BeliqApiError(
|
|
340
363
|
`beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
|
|
341
364
|
{ status: 0, code: "TIMEOUT" }
|
|
342
365
|
);
|
|
343
366
|
}
|
|
344
|
-
|
|
345
|
-
|
|
367
|
+
failure = err;
|
|
368
|
+
retryClass = classifyThrown(err);
|
|
346
369
|
} finally {
|
|
347
370
|
if (timer) clearTimeout(timer);
|
|
348
371
|
}
|
|
349
|
-
|
|
372
|
+
if (retryClass === void 0) throw failure;
|
|
373
|
+
if (config.maxRetries !== void 0) {
|
|
374
|
+
if (attempt >= config.maxRetries) throw failure;
|
|
375
|
+
} else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
|
|
376
|
+
throw failure;
|
|
377
|
+
}
|
|
378
|
+
const delay = retryDelayMs(res, attempt, config);
|
|
379
|
+
if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
|
|
380
|
+
if (retryClass === "count") countedRetries++;
|
|
381
|
+
await sleep(delay);
|
|
350
382
|
}
|
|
351
|
-
throw lastError;
|
|
352
383
|
}
|
|
353
384
|
|
|
354
385
|
// src/client.ts
|
|
@@ -427,7 +458,8 @@ var Beliq = class {
|
|
|
427
458
|
auth: options.auth ?? "header",
|
|
428
459
|
fetchImpl,
|
|
429
460
|
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
430
|
-
maxRetries: options.maxRetries
|
|
461
|
+
maxRetries: options.maxRetries,
|
|
462
|
+
retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
|
|
431
463
|
};
|
|
432
464
|
}
|
|
433
465
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
@@ -475,7 +507,8 @@ var Beliq = class {
|
|
|
475
507
|
operation: "validate",
|
|
476
508
|
...this.#rawParams(document, options),
|
|
477
509
|
validateFormat: options.format,
|
|
478
|
-
franceCtc: options.franceCtc
|
|
510
|
+
franceCtc: options.franceCtc,
|
|
511
|
+
ruleset: options.ruleset
|
|
479
512
|
});
|
|
480
513
|
}
|
|
481
514
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
@@ -529,6 +562,7 @@ var Beliq = class {
|
|
|
529
562
|
BeliqApiError,
|
|
530
563
|
DEFAULT_BASE_URL,
|
|
531
564
|
DEFAULT_MAX_RETRIES,
|
|
565
|
+
DEFAULT_RETRY_BUDGET_MS,
|
|
532
566
|
DEFAULT_TIMEOUT_MS,
|
|
533
567
|
LIVE_CONVERT_SOURCE_FORMATS,
|
|
534
568
|
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
|
|
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-l-8PFJA8.cjs';
|
|
2
2
|
import { PlainObject } from './helpers.cjs';
|
|
3
|
-
export {
|
|
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-l-8PFJA8.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,
|
|
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
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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;
|
|
@@ -62,6 +73,22 @@ interface DocumentOptions {
|
|
|
62
73
|
interface ValidateOptions extends DocumentOptions {
|
|
63
74
|
format?: ValidateFormat;
|
|
64
75
|
franceCtc?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* The rules to validate against, sent as the `Beliq-Ruleset` header: a channel
|
|
78
|
+
* (`latest` or `previous`), or comma-separated exact pins as
|
|
79
|
+
* `<artifactKey>:<version>`, the keys and versions `GET /v1/rulesets` lists.
|
|
80
|
+
* Left unset, no header is sent, and the API runs the key's organisation
|
|
81
|
+
* default, which is `latest` unless the organisation chose `previous`.
|
|
82
|
+
*
|
|
83
|
+
* The result says what applied: `rulesetChannel` and `rulesetFellBack` which
|
|
84
|
+
* channel, `rulesetArtifacts` and the per-format version fields which rules
|
|
85
|
+
* ran, and `rulesetSunsetsOn` until when a retained ruleset is served. Under
|
|
86
|
+
* exact pins `rulesetChannel` reads `latest`, whatever version a pin ran.
|
|
87
|
+
* The API answers a malformed value with a 400 `VALIDATION_ERROR` before any
|
|
88
|
+
* quota is used, and a pin to a version it no longer serves with a 422
|
|
89
|
+
* `VALIDATION_ERROR`, which uses up a document.
|
|
90
|
+
*/
|
|
91
|
+
ruleset?: RulesetChannel | (string & {});
|
|
65
92
|
}
|
|
66
93
|
interface ParseOptions extends DocumentOptions {
|
|
67
94
|
format?: ParseFormat;
|
|
@@ -166,5 +193,5 @@ declare class BeliqApiError extends Error {
|
|
|
166
193
|
});
|
|
167
194
|
}
|
|
168
195
|
|
|
169
|
-
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, Standard, ValidateFormat, ValidationResult };
|
|
196
|
+
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult };
|
|
170
197
|
export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };
|
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
|
|
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-l-8PFJA8.js';
|
|
2
2
|
import { PlainObject } from './helpers.js';
|
|
3
|
-
export {
|
|
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-l-8PFJA8.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,
|
|
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
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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;
|
|
@@ -62,6 +73,22 @@ interface DocumentOptions {
|
|
|
62
73
|
interface ValidateOptions extends DocumentOptions {
|
|
63
74
|
format?: ValidateFormat;
|
|
64
75
|
franceCtc?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* The rules to validate against, sent as the `Beliq-Ruleset` header: a channel
|
|
78
|
+
* (`latest` or `previous`), or comma-separated exact pins as
|
|
79
|
+
* `<artifactKey>:<version>`, the keys and versions `GET /v1/rulesets` lists.
|
|
80
|
+
* Left unset, no header is sent, and the API runs the key's organisation
|
|
81
|
+
* default, which is `latest` unless the organisation chose `previous`.
|
|
82
|
+
*
|
|
83
|
+
* The result says what applied: `rulesetChannel` and `rulesetFellBack` which
|
|
84
|
+
* channel, `rulesetArtifacts` and the per-format version fields which rules
|
|
85
|
+
* ran, and `rulesetSunsetsOn` until when a retained ruleset is served. Under
|
|
86
|
+
* exact pins `rulesetChannel` reads `latest`, whatever version a pin ran.
|
|
87
|
+
* The API answers a malformed value with a 400 `VALIDATION_ERROR` before any
|
|
88
|
+
* quota is used, and a pin to a version it no longer serves with a 422
|
|
89
|
+
* `VALIDATION_ERROR`, which uses up a document.
|
|
90
|
+
*/
|
|
91
|
+
ruleset?: RulesetChannel | (string & {});
|
|
65
92
|
}
|
|
66
93
|
interface ParseOptions extends DocumentOptions {
|
|
67
94
|
format?: ParseFormat;
|
|
@@ -166,5 +193,5 @@ declare class BeliqApiError extends Error {
|
|
|
166
193
|
});
|
|
167
194
|
}
|
|
168
195
|
|
|
169
|
-
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, Standard, ValidateFormat, ValidationResult };
|
|
196
|
+
export { AccountInfo, ApiErrorCode, Beliq, BeliqApiError, ConvertSourceFormat, ConvertTargetFormat, DocumentInput, FacturxProfile, GenerateProfile, Invoice, ParseFormat, ParseResult, RulesetArtifact, RulesetChannel, Standard, ValidateFormat, ValidationResult };
|
|
170
197
|
export type { BeliqOptions, ConvertMeta, ConvertOptions, ConvertResult, DocumentOptions, GenerateInput, GenerateMeta, GenerateResult, LostElement, LostElementsTruncated, ParseOptions, ValidateOptions };
|
package/dist/index.js
CHANGED
|
@@ -97,6 +97,10 @@ function buildRequest(params) {
|
|
|
97
97
|
query: withAdvancedQuery(query, params.advanced),
|
|
98
98
|
rawBody: params.rawBody,
|
|
99
99
|
contentType: params.rawContentType ?? "application/xml",
|
|
100
|
+
// No header unless the caller chose one: without it the API runs the
|
|
101
|
+
// organisation's default channel, which a sent `latest` would override.
|
|
102
|
+
// `!= null`: a plain-JS caller's null means unset too, not the string "null".
|
|
103
|
+
...params.ruleset != null ? { headers: { "Beliq-Ruleset": params.ruleset } } : {},
|
|
100
104
|
outputKind: "json"
|
|
101
105
|
};
|
|
102
106
|
}
|
|
@@ -171,6 +175,7 @@ function errorFromResponse(status, bytes) {
|
|
|
171
175
|
var DEFAULT_BASE_URL = "https://api.beliq.eu";
|
|
172
176
|
var DEFAULT_TIMEOUT_MS = 9e4;
|
|
173
177
|
var DEFAULT_MAX_RETRIES = 3;
|
|
178
|
+
var DEFAULT_RETRY_BUDGET_MS = 9e5;
|
|
174
179
|
var LIVE_GENERATE_STANDARDS = [
|
|
175
180
|
"xrechnung",
|
|
176
181
|
"zugferd",
|
|
@@ -235,14 +240,29 @@ var LIVE_CONVERT_TARGET_FORMATS = [
|
|
|
235
240
|
];
|
|
236
241
|
|
|
237
242
|
// src/transport.ts
|
|
238
|
-
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503]);
|
|
239
243
|
var QUOTA_EXHAUSTED_CODE = "QUOTA_EXCEEDED";
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
244
|
+
var DATABASE_UNAVAILABLE_CODE = "DATABASE_UNAVAILABLE";
|
|
245
|
+
var BEFORE_SEND_CODES = /* @__PURE__ */ new Set([
|
|
246
|
+
"ECONNREFUSED",
|
|
247
|
+
"ENOTFOUND",
|
|
248
|
+
"EAI_AGAIN",
|
|
249
|
+
"ENETUNREACH",
|
|
250
|
+
"EHOSTUNREACH",
|
|
251
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
252
|
+
]);
|
|
253
|
+
function classifyStatus(status, code) {
|
|
254
|
+
if (status === 429) return code === QUOTA_EXHAUSTED_CODE ? void 0 : "count";
|
|
255
|
+
if (status !== 502 && status !== 503) return void 0;
|
|
256
|
+
if (!code) return "budget";
|
|
257
|
+
return status === 503 && code === DATABASE_UNAVAILABLE_CODE ? "budget" : "count";
|
|
258
|
+
}
|
|
259
|
+
function classifyThrown(err) {
|
|
260
|
+
const code = err?.cause?.code;
|
|
261
|
+
return typeof code === "string" && BEFORE_SEND_CODES.has(code) ? "budget" : "count";
|
|
243
262
|
}
|
|
244
|
-
var MAX_RETRY_AFTER_MS = 3e4;
|
|
245
263
|
var BACKOFF_BASE_MS = 500;
|
|
264
|
+
var BACKOFF_CEILING_MS = 3e4;
|
|
265
|
+
var RETRY_AFTER_JITTER_MS = 250;
|
|
246
266
|
function authHeaders(config) {
|
|
247
267
|
return config.auth === "bearer" ? { Authorization: `Bearer ${config.apiKey}` } : { "X-API-Key": config.apiKey };
|
|
248
268
|
}
|
|
@@ -256,29 +276,34 @@ function buildUrl(baseUrl, path, query) {
|
|
|
256
276
|
const qs = params.toString();
|
|
257
277
|
return qs ? `${baseUrl}${path}?${qs}` : `${baseUrl}${path}`;
|
|
258
278
|
}
|
|
259
|
-
function retryDelayMs(res, attempt) {
|
|
279
|
+
function retryDelayMs(res, attempt, config) {
|
|
260
280
|
const header = res?.headers.get("retry-after");
|
|
261
281
|
if (header) {
|
|
262
282
|
const seconds = Number(header);
|
|
263
283
|
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
264
|
-
return
|
|
284
|
+
return seconds * 1e3 + Math.random() * RETRY_AFTER_JITTER_MS;
|
|
265
285
|
}
|
|
266
286
|
}
|
|
267
|
-
const
|
|
287
|
+
const base = config.backoffBaseMs ?? BACKOFF_BASE_MS;
|
|
288
|
+
const ceiling = config.backoffCeilingMs ?? BACKOFF_CEILING_MS;
|
|
289
|
+
const backoff = Math.min(base * 2 ** attempt, ceiling / 2);
|
|
268
290
|
return backoff + Math.random() * backoff;
|
|
269
291
|
}
|
|
270
292
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
271
293
|
async function send(config, req) {
|
|
272
|
-
const headers = { ...authHeaders(config) };
|
|
294
|
+
const headers = { ...req.headers, ...authHeaders(config) };
|
|
273
295
|
if (req.contentType) headers["Content-Type"] = req.contentType;
|
|
274
296
|
if (req.accept) headers["Accept"] = req.accept;
|
|
275
297
|
const body = req.jsonBody !== void 0 ? JSON.stringify(req.jsonBody) : req.rawBody;
|
|
276
298
|
const url = buildUrl(config.baseUrl, req.path, req.query);
|
|
277
|
-
|
|
278
|
-
|
|
299
|
+
const started = performance.now();
|
|
300
|
+
let countedRetries = 0;
|
|
301
|
+
for (let attempt = 0; ; attempt++) {
|
|
279
302
|
const controller = new AbortController();
|
|
280
303
|
const timer = config.timeoutMs > 0 ? setTimeout(() => controller.abort(), config.timeoutMs) : void 0;
|
|
281
304
|
let res;
|
|
305
|
+
let failure;
|
|
306
|
+
let retryClass;
|
|
282
307
|
try {
|
|
283
308
|
res = await config.fetchImpl(url, {
|
|
284
309
|
method: req.method,
|
|
@@ -289,26 +314,31 @@ async function send(config, req) {
|
|
|
289
314
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
290
315
|
if (res.ok) return { status: res.status, headers: res.headers, bytes };
|
|
291
316
|
const apiError = errorFromResponse(res.status, bytes);
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
throw apiError;
|
|
295
|
-
}
|
|
317
|
+
failure = apiError;
|
|
318
|
+
retryClass = classifyStatus(apiError.status, apiError.code);
|
|
296
319
|
} catch (err) {
|
|
297
|
-
if (err instanceof BeliqApiError && !isRetryable(err.status, err.code)) throw err;
|
|
298
320
|
if (controller.signal.aborted) {
|
|
299
321
|
throw new BeliqApiError(
|
|
300
322
|
`beliq: request to ${req.path} exceeded ${config.timeoutMs}ms`,
|
|
301
323
|
{ status: 0, code: "TIMEOUT" }
|
|
302
324
|
);
|
|
303
325
|
}
|
|
304
|
-
|
|
305
|
-
|
|
326
|
+
failure = err;
|
|
327
|
+
retryClass = classifyThrown(err);
|
|
306
328
|
} finally {
|
|
307
329
|
if (timer) clearTimeout(timer);
|
|
308
330
|
}
|
|
309
|
-
|
|
331
|
+
if (retryClass === void 0) throw failure;
|
|
332
|
+
if (config.maxRetries !== void 0) {
|
|
333
|
+
if (attempt >= config.maxRetries) throw failure;
|
|
334
|
+
} else if (retryClass === "count" && countedRetries >= DEFAULT_MAX_RETRIES) {
|
|
335
|
+
throw failure;
|
|
336
|
+
}
|
|
337
|
+
const delay = retryDelayMs(res, attempt, config);
|
|
338
|
+
if (performance.now() - started + delay > config.retryBudgetMs) throw failure;
|
|
339
|
+
if (retryClass === "count") countedRetries++;
|
|
340
|
+
await sleep(delay);
|
|
310
341
|
}
|
|
311
|
-
throw lastError;
|
|
312
342
|
}
|
|
313
343
|
|
|
314
344
|
// src/client.ts
|
|
@@ -387,7 +417,8 @@ var Beliq = class {
|
|
|
387
417
|
auth: options.auth ?? "header",
|
|
388
418
|
fetchImpl,
|
|
389
419
|
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
390
|
-
maxRetries: options.maxRetries
|
|
420
|
+
maxRetries: options.maxRetries,
|
|
421
|
+
retryBudgetMs: options.retryBudgetMs ?? DEFAULT_RETRY_BUDGET_MS
|
|
391
422
|
};
|
|
392
423
|
}
|
|
393
424
|
/** Account, plan, and quota context for the key. Does not consume quota. */
|
|
@@ -435,7 +466,8 @@ var Beliq = class {
|
|
|
435
466
|
operation: "validate",
|
|
436
467
|
...this.#rawParams(document, options),
|
|
437
468
|
validateFormat: options.format,
|
|
438
|
-
franceCtc: options.franceCtc
|
|
469
|
+
franceCtc: options.franceCtc,
|
|
470
|
+
ruleset: options.ruleset
|
|
439
471
|
});
|
|
440
472
|
}
|
|
441
473
|
/** Parse a document into a structured EN 16931 invoice. */
|
|
@@ -488,6 +520,7 @@ export {
|
|
|
488
520
|
BeliqApiError,
|
|
489
521
|
DEFAULT_BASE_URL,
|
|
490
522
|
DEFAULT_MAX_RETRIES,
|
|
523
|
+
DEFAULT_RETRY_BUDGET_MS,
|
|
491
524
|
DEFAULT_TIMEOUT_MS,
|
|
492
525
|
LIVE_CONVERT_SOURCE_FORMATS,
|
|
493
526
|
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
|
-
/**
|
|
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
|
|
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
|
|
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`.
|
|
@@ -1965,6 +1979,8 @@ type ParseWarning = ParseResult['warnings'][number];
|
|
|
1965
1979
|
type ParseWarningCode = ParseWarning['code'];
|
|
1966
1980
|
/** The JSON-mode generate envelope (Accept: application/json): the seal. */
|
|
1967
1981
|
type GenerateResponse = Json200Data<'generateInvoice'>;
|
|
1982
|
+
/** A ruleset channel: what `rulesetChannel` reports and `Beliq-Ruleset` accepts by name. */
|
|
1983
|
+
type RulesetChannel = NonNullable<ValidationResult['rulesetChannel']>;
|
|
1968
1984
|
/** One row of the ruleset fingerprint (key, version, file hash). */
|
|
1969
1985
|
type RulesetArtifact = NonNullable<ValidationResult['rulesetArtifacts']>[number];
|
|
1970
1986
|
/** The EN 16931 invoice generate accepts, and every option it carries. */
|
|
@@ -1982,5 +1998,5 @@ type ParseFormat = NonNullable<Query<'parseInvoice'>['format']>;
|
|
|
1982
1998
|
type ConvertSourceFormat = NonNullable<Query<'convertInvoice'>['sourceFormat']>;
|
|
1983
1999
|
type ConvertTargetFormat = Query<'convertInvoice'>['targetFormat'];
|
|
1984
2000
|
|
|
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
|
|
1986
|
-
export type { AccountInfo as A,
|
|
2001
|
+
export { DEFAULT_TIMEOUT_MS as B, 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 y, DEFAULT_RETRY_BUDGET_MS as z };
|
|
2002
|
+
export type { AccountInfo as A, ConvertTargetFormat as C, GenerateBody as E, FacturxProfile as F, GeneratePreset as G, GenerateResponse as H, Invoice as I, ParseWarning as J, ParseWarningCode as K, Severity as M, ValidationFormat as N, ValidationIssue as O, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, RulesetChannel as q, ParseFormat as r, ParseResult as u, ConvertSourceFormat as v, ApiErrorCode as w, ApiError as x };
|
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
|
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`.
|
|
@@ -1965,6 +1979,8 @@ type ParseWarning = ParseResult['warnings'][number];
|
|
|
1965
1979
|
type ParseWarningCode = ParseWarning['code'];
|
|
1966
1980
|
/** The JSON-mode generate envelope (Accept: application/json): the seal. */
|
|
1967
1981
|
type GenerateResponse = Json200Data<'generateInvoice'>;
|
|
1982
|
+
/** A ruleset channel: what `rulesetChannel` reports and `Beliq-Ruleset` accepts by name. */
|
|
1983
|
+
type RulesetChannel = NonNullable<ValidationResult['rulesetChannel']>;
|
|
1968
1984
|
/** One row of the ruleset fingerprint (key, version, file hash). */
|
|
1969
1985
|
type RulesetArtifact = NonNullable<ValidationResult['rulesetArtifacts']>[number];
|
|
1970
1986
|
/** The EN 16931 invoice generate accepts, and every option it carries. */
|
|
@@ -1982,5 +1998,5 @@ type ParseFormat = NonNullable<Query<'parseInvoice'>['format']>;
|
|
|
1982
1998
|
type ConvertSourceFormat = NonNullable<Query<'convertInvoice'>['sourceFormat']>;
|
|
1983
1999
|
type ConvertTargetFormat = Query<'convertInvoice'>['targetFormat'];
|
|
1984
2000
|
|
|
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
|
|
1986
|
-
export type { AccountInfo as A,
|
|
2001
|
+
export { DEFAULT_TIMEOUT_MS as B, 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 y, DEFAULT_RETRY_BUDGET_MS as z };
|
|
2002
|
+
export type { AccountInfo as A, ConvertTargetFormat as C, GenerateBody as E, FacturxProfile as F, GeneratePreset as G, GenerateResponse as H, Invoice as I, ParseWarning as J, ParseWarningCode as K, Severity as M, ValidationFormat as N, ValidationIssue as O, PlainObject as P, RulesetArtifact as R, Standard as S, ValidationResult as V, DocumentInput as a, GenerateProfile as n, ValidateFormat as o, RulesetChannel as q, ParseFormat as r, ParseResult as u, ConvertSourceFormat as v, ApiErrorCode as w, ApiError as x };
|
package/package.json
CHANGED