@lexapi/client 0.4.0 → 0.5.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
@@ -5,6 +5,257 @@ versioning: [SemVer](https://semver.org/) — while the package is `0.x`, a **mi
5
5
  breaking changes (documented below with a migration note); `npm install @lexapi/client@^0.1.0` never
6
6
  picks up `0.2.0` on its own.
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [0.5.0] — 2026-11-22
11
+
12
+ Targets LexAPI API 3.0.0. API 2.19.0–2.30.0 were not released on their own; they are all part of
13
+ 3.0.0, and items that need a newer API name the version that introduced the feature. Works against
14
+ API 2.18.1 as well: features of later versions are then absent (`legislationAsOf`, API 2.26.0,
15
+ answers 404 there).
16
+
17
+ ### Upgrading from 0.4.0
18
+
19
+ - **Malformed 2xx answers throw.** A 2xx that is empty, not UTF-8 JSON, not an object,
20
+ `success: false`, or lacks `results` / `document` (or carries them in the wrong shape) throws
21
+ `InvalidResponseError` (before: could read as an empty result), except an empty `webhooks.delete`
22
+ answer and `webhooks.test`'s `success: false`, which still resolve. A `success: false` that carries
23
+ an API error throws that error instead. Catch it; the call may have been charged.
24
+ - **Failed payments.** A 403 `PAYMENT_PAST_DUE` (API 2.27.0) throws `PaymentPastDueError` (0.4.0:
25
+ base `LexAPIError`). It extends `TierForbiddenError`: an `instanceof TierForbiddenError` branch
26
+ now catches it (also when narrowing a union type: its `false` branch no longer includes
27
+ `PaymentPastDueError`), so test `PaymentPastDueError` first. Never retried.
28
+ - **Iterators can throw** `InvalidResponseError` when the server stops advancing:
29
+ `paginateCites` / `paginateCitedBy` on a page echoing an `offset` other than the one requested,
30
+ or, when the answers carry neither `totalEdges` nor `offset`, three pages in a row with the same
31
+ list; `webhooks.paginateDeliveries`, when the answers carry no `total`, after three pages in a
32
+ row with no unseen delivery `id`; `paginateNationalDocuments` on a `nextCursor` already sent, or
33
+ not a string. Every iterator throws `RangeError` for an `offset` that is not an integer ≥ 0 or a
34
+ `limit` that is not an integer ≥ 1, before any request. Pages already yielded stay valid.
35
+ - **Webhook verification.** The body must be a UTF-8 JSON object (`malformed_body`) and
36
+ `timestamp` an ISO date-time with `Z` or `±HH:MM` (`stale_timestamp`). `toleranceMs: NaN` is a
37
+ `RangeError` and a negative value rejects every delivery (use `0` to switch the window off).
38
+ LexAPI's deliveries verify as before.
39
+ - **Export.** Lines end at `\n` and must be UTF-8, else they count in `invalidLines` (before: bad
40
+ bytes replaced, row yielded). `stream.truncated` is `false`, not `undefined`, when nothing says.
41
+ - **Retries.** A `Retry-After` / `RateLimit-Reset` / `retryAfter` that is not in a documented form
42
+ counts as absent (normal back-off). A 429 whose top-level `code` or `error.code` is
43
+ `QUOTA_EXHAUSTED` is never retried, whatever other code the body carries.
44
+ - **Redirects.** Followed only within the origin of `baseUrl` (or to the same host over HTTPS on
45
+ the default ports), at most five; any other throws `NetworkError`. Affects a custom `baseUrl`, a
46
+ proxy, or a custom `fetch` (it must honour `redirect: "manual"`).
47
+ - **Error text.** Messages for non-JSON bodies changed, and `InvalidResponseError.body` no longer
48
+ holds response text (see `bodyExcerpt`). Match on `code`, not on messages.
49
+ - **Types.**
50
+ - `NationalSemanticLegislationResult` typed the fields it shares with the EU hit (`id`, `score`,
51
+ `text`, `snippet`, `chapter`, `exact_match_law_id`, `metadata`) as `unknown`; they now have
52
+ their types (`score?: number`, `asOfVersion?: NationalAsOfVersion`, …). Other keys are still
53
+ readable as `unknown`. Code that redeclares them in an `interface … extends`, or assigns a
54
+ fixture of another shape, must follow.
55
+ - An `interface … extends` or subclass that redeclares a newly added optional member (for example
56
+ `observedFrom`, `asOf`, `asOfSummary`) with another type must follow.
57
+ - `getDocumentAtDate` returns `DocumentAtDateResponse`, which is assignable to the
58
+ `DocumentVersionResponse` it returned before.
59
+ - `ExportStream.truncated` is typed `boolean` (was `boolean | undefined`).
60
+ - `NotFoundError` has new read-only accessors (`reason`, `beforeTracking`, `boundaryUnknown`,
61
+ `trackedSince`, `inForceLookup`, `candidates`, `candidatesTruncated`). A subclass that declares
62
+ a property of the same name must rename it.
63
+
64
+ ### Added
65
+
66
+ - **Text availability on case-law hits** (API 2.30.0): with `includeText: true`, every
67
+ `semanticSearch` hit carries `textAvailability` (`SemanticHitTextAvailability`): `{ available: true }`
68
+ when it carries `text`, otherwise `{ available: false, reason }` (`SemanticHitTextUnavailableReason`:
69
+ `not_in_corpus` or `unknown`; the reason is an open string) and the hit keeps its `snippet`. Absent without `includeText`. Not the
70
+ document `TextAvailability`: the reasons differ. The SDK passes the field through as received.
71
+ - **National `asOf` labels** (API 2.29.0): `nationalLegislationSemanticSearch` takes `asOf`
72
+ (a `YYYY-MM-DD` string) and sends it; before, the option did not exist. Each hit carries `asOf`, `asOfResolved`, `asOfReason` (`NationalAsOfReason`, runtime list
73
+ `NATIONAL_AS_OF_REASONS`) and, when resolved, `asOfVersion: NationalAsOfVersion`
74
+ (`{ kind: "current_unit", validFrom, validTo, sourceId, checkedAt }`); the response adds `asOf`
75
+ and `asOfSummary`. The search runs over today's texts only: a hit is resolved only when the
76
+ publisher's dates, as of LexAPI's last recorded read of the act (`checkedAt`), show today's
77
+ wording already applied on the date; an unresolved hit keeps today's wording, which is not
78
+ established as the text for the date. LexAPI holds such dates for Austria and Spain.
79
+ `isNationalAsOfVersion(v)` tells it from the EU `AsOfVersion` by `kind`.
80
+ - **Snapshot timing on the version endpoints** (API 2.28.0): `observedFrom` on every version
81
+ (`listDocumentVersions`, `getDocumentVersion`, `getDocumentAtDate`): when the version began in
82
+ LexAPI's fetch history, `null` when LexAPI has no record of it. `getDocumentAtDate` now returns `DocumentAtDateResponse`
83
+ (a `DocumentVersionResponse` with `kind: "observation_snapshot"`, `document.observedUntil`,
84
+ `inForceLookup`, `dateInFuture` and `xWarning`). These are LexAPI's fetch snapshots, not the law
85
+ in force on a date; for the version of an EU act for a date use `legislationAsOf`.
86
+ - **`NotFoundError` details** (API 2.28.0): `reason` (`details.reason`), `beforeTracking` (with
87
+ `trackedSince` and `inForceLookup`) and `boundaryUnknown` (with `candidates` —
88
+ `{ version, fetchedAt, observedFrom }[]`, at most 10, `[]` when none — and
89
+ `candidatesTruncated`) for the 404s of `getDocumentAtDate`. Read from `details` only, when it is
90
+ a plain object. `unknownEndpoint` is unchanged.
91
+ - **In-force label** (API 2.19.0): `inForce`, `notInForceReason`, `endOfValidity`,
92
+ `entryIntoForce` (`InForceLabel`, `NotInForceReason`) on documents (`getDocument`,
93
+ `getDocumentsBatch`, `getDocumentByUrl`), on `getDocumentMetadata`'s `metadata` and on
94
+ `semanticLegislationSearch` hits; the `inForce` option of `semanticLegislationSearch` (sent when
95
+ set) and the response's `inForceFilter`.
96
+ - **Provenance** (API 2.20.0): `provenance` and `fieldProvenance` (`FieldProvenance`) on documents,
97
+ `getDocumentMetadata`'s `metadata`, single version snapshots and EU semantic hits
98
+ (`EuSemanticCaseLawResult`, `EuSemanticLegislationResult`, now the element types of `results`);
99
+ `fieldProvenance` on `semanticSearch` responses with `hypotheticalDocument`.
100
+ - **`/info` semantic result caps** (API 2.24.0): `subscription.maxSemanticResults` and
101
+ `subscription.maxSemanticLegislationResults`.
102
+ - **`legislationAsOf({ document, asOf, provision?, language? }, options?)`** (`POST /legislation/as-of`,
103
+ 1 credit when no text is fetched; 4, or 5 live from EUR-Lex, when the provision's text is fetched,
104
+ whatever the answer; 1 if the fetch fails). **Requires LexAPI API 2.26.0.** The version of
105
+ an EU regulation, directive or decision listed for a date — the newest consolidated version dated
106
+ on or before it, or the act as published in the Official Journal — and optionally one article,
107
+ annex or recital range of it. An answer that cannot be established is returned, not thrown:
108
+ `asOfResolved: false` with an `asOfReason`; use a text only when `asOfResolved` is `true`.
109
+ Consolidated versions have no legal force (`baseCelex` names the authentic act). Types:
110
+ `LegislationAsOfRequest`, `LegislationAsOfResponse`, `LegislationAsOfVersion`,
111
+ `LegislationAsOfAct`, `LegislationAsOfProvision`, `AsOfLookupReason`, `Provenance`; runtime list
112
+ `AS_OF_LOOKUP_REASONS`.
113
+ - **`PaymentPastDueError`** (403, code `PAYMENT_PAST_DUE`, API 2.27.0): a subscription payment failed
114
+ and was not completed in time; API requests are refused until the payment succeeds. Never
115
+ retried, on any status (a 429 included). `billingUrl` is where to pay the open invoice; `accessEndedAt` is when access ended, when
116
+ the API says so. It extends `TierForbiddenError`. Before API 2.27.0 a failed
117
+ payment was refused at once with a 403 without a code, raised as `TierForbiddenError`.
118
+ `"PAYMENT_PAST_DUE"` is added to `ErrorCode`. Earlier SDK versions raise the base `LexAPIError`
119
+ for this code. `TierForbiddenError`'s constructor takes an optional sixth parameter, the code
120
+ (`"TIER_FORBIDDEN"` by default).
121
+ - **`NotFoundError.unknownEndpoint`**: `true` when the API (2.27.0 or later) has no such endpoint: a
122
+ mistyped path, a method newer than the API, or a national route for a country that is not
123
+ available. Always `false` on APIs before 2.27.0; there the message contains "Unknown API
124
+ endpoint".
125
+ - **`LexAPIError.bodyExcerpt`**: the first 200 characters (code points) of a response body that is
126
+ not JSON (`undefined` otherwise), read through a getter; it is not an own property of the error.
127
+ It may contain document text: do not show it to a model or log it by default.
128
+ `LexAPIErrorContext` takes it too, and `LexAPIError.fromResponse` takes it as an optional fifth
129
+ parameter.
130
+
131
+ ### Changed
132
+
133
+ - **2xx bodies are checked** (`InvalidResponseError`). A `2xx` answer that is not the documented
134
+ shape now throws instead of possibly being read as an empty result: an empty body (also a `204`,
135
+ except for `webhooks.delete`), a body of only whitespace (it returned an empty object), a body
136
+ that is not valid UTF-8 (before, the invalid bytes were replaced and the body was parsed), JSON
137
+ that is not an object, `success: false` (when the body carries the API's error envelope, that
138
+ error is thrown instead, keeping the `2xx` status; `webhooks.test` still resolves with
139
+ `success: false`), and a list field that is not a list or holds items that are not objects.
140
+ `results` is required on `search`, `semanticSearch`, `semanticLegislationSearch` and the national
141
+ semantic searches; `document` must be an object on `getDocument`, `getDocumentByUrl`,
142
+ `getDocumentVersion`, `getDocumentAtDate` and `getNationalDocument` (and `document.content`, when
143
+ present, an object whose `articles` is a list of objects); on `legislationAsOf`, `document` must
144
+ be a non-empty string, `asOfResolved` a boolean, and `act` and `provenance` objects. Unknown
145
+ extra fields are still accepted. To tell a malformed answer from an empty result, catch
146
+ `InvalidResponseError`. The message for a `2xx` body that is not JSON changed: it was, for
147
+ example, `Expected a JSON body (HTTP 200, content-type text/html; charset=utf-8)` and is now
148
+ `Expected JSON, got text/html that does not parse as JSON (1213 bytes)`; do not match on error
149
+ message text, use `code`. An error body that is not valid UTF-8 is treated as not JSON: the error
150
+ carries the code derived from the status and the message `HTTP <status>`.
151
+ - Retry hints are read strictly (SDK contract §1.2): `Retry-After` and `RateLimit-Reset` as decimal
152
+ seconds or, for `Retry-After`, an RFC 9110 HTTP-date (IMF-fixdate or RFC 850 ending in `GMT`,
153
+ `UTC` or `+0000`; asctime has no zone and is read as UTC). Dates with other zone names,
154
+ impossible dates and other text are ignored; a body `retryAfter` only as a
155
+ number ≥ 0. An unusable hint counts as none: the retry uses the normal back-off, a legacy 429 with
156
+ `usage.resetsAt` and no usable hint is a quota 429, and a national 503 whose only hint is unusable
157
+ is not retried.
158
+ - Figures that are not usable numbers read as absent: integer headers (`result.headers`, export
159
+ counts) accept only digits up to 2^53−1, and `getCreditUsage` ignores a figure that is not a finite
160
+ number or a `resetsAt` that is not a string.
161
+ - The iterators throw `InvalidResponseError` when the server stops advancing: a cites/cited-by page
162
+ echoing another `offset`, a national `nextCursor` already sent or not a string, or, without
163
+ `totalEdges`/`offset` (or a deliveries `total`), three pages in a row that repeat the one before.
164
+ The page that shows the stall is not yielded and is on `err.body`. Cites/cited-by walks also end
165
+ once the offset reaches `totalEdges`. A national walk continues only while `hasMore` is `true`.
166
+ A starting `offset` that is not an integer from 0, or a `limit` that is not an integer from 1, up
167
+ to 2^53 − 1, is a `RangeError` before any request.
168
+ - **Webhook verification** (`verifyWebhook`, `verifySignature`, `computeSignature`):
169
+ - The body is decoded as strict UTF-8 before parsing: a body that is not valid UTF-8 (an invalid
170
+ or truncated sequence, an encoded surrogate, an overlong form, latin-1 text) is
171
+ `WebhookSignatureError("malformed_body")`, like a body that is not JSON. Before, invalid bytes
172
+ were replaced with U+FFFD and the body was parsed. One leading byte order mark is ignored, also
173
+ at the start of a string body, which is read as its UTF-8 encoding (the bytes the signature
174
+ covers). The signature check is unchanged.
175
+ - A string body with a lone surrogate (it has no UTF-8 encoding) fails verification:
176
+ `verifySignature` returns `false`, `verifyWebhook` throws `WebhookSignatureError("invalid_signature")`
177
+ and `computeSignature` throws `WebhookSignatureError("malformed_body")`. Before, such a string
178
+ was signed as U+FFFD; `verifyWebhook` parsed the string with the surrogate in it.
179
+ - `verifyWebhook` reports the first failing check, in this order: `missing_secret`,
180
+ `missing_signature` (header absent or empty), `invalid_signature`, `malformed_body`,
181
+ `stale_timestamp`. A body that is JSON but not an object (`null`, an array, a number) is
182
+ `malformed_body`; before, it was returned as the event or failed as `stale_timestamp`.
183
+ - The signed `timestamp` must be `YYYY-MM-DDTHH:MM:SS[.fraction]` followed by `Z` or a `±HH:MM`
184
+ offset, naming a date and time that exist, in years 0001–9999; anything else is
185
+ `stale_timestamp`. Before, any text `Date.parse` accepted was read (a lower-case `z`, RFC 2822
186
+ dates). The distance from now is compared in whole microseconds (fraction digits past the sixth
187
+ are cut), and a delivery exactly at the edge of the window passes.
188
+ - `toleranceMs: NaN` is a `RangeError`, and a negative `toleranceMs` rejects every delivery as
189
+ `stale_timestamp`. Before, both turned the replay check off. `0` still turns it off.
190
+ - A secret with a lone surrogate (it has no UTF-8 encoding) is
191
+ `WebhookSignatureError("missing_secret")` in every helper. Before, it was used with each
192
+ surrogate replaced by U+FFFD.
193
+ - The signature header is trimmed of spaces, tabs, CR and LF only; other padding (a byte order
194
+ mark, a no-break space) fails. Hex digits in either case are accepted, as before.
195
+ - **Export lines and envelope.** Lines end at a line feed byte only and are decoded as strict
196
+ UTF-8, whatever charset the response names: a line that is not UTF-8 is counted in
197
+ `invalidLines` and the next line is read intact. Before, invalid bytes were replaced with U+FFFD
198
+ and the line was parsed. Lines are trimmed of spaces, tabs and CR only (before: all Unicode
199
+ whitespace); one byte order mark at the very start of the stream is ignored, and one anywhere else
200
+ makes its line invalid. `meta` is set only from the very first line of the stream; a `_meta` line
201
+ after it is skipped and not counted, also when it carries `_done` or `_error` (before, such a line
202
+ was read as the trailer). When `_meta` or `_done` holds an object, the fields are read from that
203
+ object only (before, keys beside it on the line were read too and won); the flat
204
+ `{"_meta": true, ...}` form is still read from the line. `X-Export-Truncated` counts only as `1`
205
+ or `0`; any other value is absent and `_meta.truncated` decides (before, it read as `false`).
206
+ `stream.truncated` is `false` when neither the trailer, the header nor `_meta` says (before:
207
+ `undefined`). Chunks that are an `ArrayBuffer` or another byte view are read like `Uint8Array`; a
208
+ chunk that is not bytes ends the stream with `NetworkError` and releases the connection.
209
+ - A 429 whose top-level `code` or typed `error.code` is `QUOTA_EXHAUSTED` is a quota 429
210
+ (`RateLimitedError`, `quotaExhausted`, not retried) whatever other code the body carries. The
211
+ shape test for servers before API 2.4.0 (`usage.resetsAt`, no wait) applies only to a 429 whose
212
+ code is `RATE_LIMITED`; a 429 with another code is retried as before. Off a 429, the code
213
+ `QUOTA_EXHAUSTED` no longer drops a `Retry-After` wait: `retryAfter` keeps it and the retry waits
214
+ it.
215
+
216
+ ### Fixed
217
+
218
+ - `InvalidResponseError` no longer carries the response text on `body`, where `console.log(err)`
219
+ and `JSON.stringify(err)` printed it. The excerpt is on `bodyExcerpt`; for JSON of the wrong shape
220
+ the parsed value is on `body`, read through a getter and not an own property of the error. The
221
+ constructor's third argument is that parsed value.
222
+ - An error body whose `code`, `message` or `error` is an empty string, or whose `error` is an array,
223
+ is read as if that field were absent. Before, an empty `message` replaced `HTTP <status>`, and an
224
+ array `error` was taken for the typed envelope.
225
+ - `AsOfReason` and `AS_OF_REASONS` (`semanticLegislationSearch` with `asOf`) now include
226
+ `amendment_not_consolidated`, which the API returns since 2.25.0.
227
+ - `fetch` is now called correctly on runtimes that require it to be invoked on the global object
228
+ (Cloudflare Workers, browsers) — both the default and the runtime's own `fetch` passed as the
229
+ `fetch` option. The default is also looked up on each request, so a `globalThis.fetch` replaced
230
+ after the client is created is the one used.
231
+ - A runtime with no global `fetch` and no `fetch` option now fails at construction with a clear
232
+ error. Previously a `globalThis.fetch` set to `undefined` constructed and failed at the first call.
233
+ - Waits and timeouts longer than the timer limit (2^31−1 ms) no longer fire at once: a huge server
234
+ wait with `maxDelayMs: Infinity`, or a `timeoutMs` above the limit, is clamped to it.
235
+ `timeoutMs: Infinity` sets no limit.
236
+ - An asctime `Retry-After` date (`Sun Nov 6 08:49:37 1994`) is read as UTC, not local time.
237
+ - `paginateNationalDocuments` checks `limit` before the first request: a value that is not a
238
+ positive integer is a `RangeError`, as on the other iterators. Before, it was sent.
239
+ - Cites/cited-by walks: a page carrying `totalEdges` or an echoed `offset` ends a run of repeated
240
+ pages but is still the page the next one is compared with. Before, the comparison restarted
241
+ after it, so a server repeating the same page threw one request later.
242
+ - Cites/cited-by walks: a group with a `citationCount` of 0 and a non-empty edge list counts its
243
+ list. Before, it counted 0 and the walk ended after that page.
244
+ - A page without its list ended the walk with a `TypeError`; a `citationCount` that is not a count
245
+ mis-stepped the offset (a walk could end early or re-request rows). Both are handled now.
246
+ - An export `_error` line whose value or `code` is an array nested too deep to turn into text ends
247
+ the stream with `IncompleteExportError`. Before, iteration threw a `RangeError`.
248
+ - `verifyWebhook` on a correctly signed body that is JSON `null` throws
249
+ `WebhookSignatureError("malformed_body")`. Before, it threw a `TypeError`.
250
+
251
+ ### Security
252
+
253
+ - Redirects are followed only within the origin of `baseUrl` (or to the same host over HTTPS on the
254
+ default ports), at most five per attempt. Any other redirect is refused with a `NetworkError`
255
+ instead of being followed with the `x-api-key` header. The LexAPI API does not redirect to other
256
+ hosts; this matters with a custom `baseUrl` or a proxy in front of the API. A custom `fetch` must
257
+ honour `redirect: "manual"`; a response it has already redirected is refused.
258
+
8
259
  ## [0.4.0] — 2026-11-11
9
260
 
10
261
  Cross-border citation graph. **Requires LexAPI API 2.13.0.** Additive at runtime: no existing
@@ -175,9 +426,8 @@ the `credits` block, like every other credit-metered route.
175
426
 
176
427
  ## [0.2.0] — 2026-10-26
177
428
 
178
- Full re-sync with the LexAPI API (validated against lex-api `main` @ `633eb67`, PR #298, and
179
- `openapi.yaml` / `docs.md` at that commit). Every endpoint, parameter, response field and error shape
180
- was audited against the spec **and** the server controllers.
429
+ Full re-sync with the LexAPI API (validated against API 2.0.0; later items name their API version).
430
+ Every endpoint, parameter, response field and error shape was checked against the API reference.
181
431
 
182
432
  ### Added
183
433
 
@@ -279,37 +529,35 @@ was audited against the spec **and** the server controllers.
279
529
  the `exports` map now points `require` at `index.d.cts`.
280
530
  - Legacy error bodies dropped their `details` (e.g. which `/search` parameter failed validation).
281
531
  - Docs/README: the export tier gate is a `403` (not `402`) and covers BUSINESS, SCALE and
282
- ENTERPRISE; tier limits include SCALE; "not yet published" and "requires lex-api PR #72" notes
283
- removed; webhook ceilings updated.
532
+ ENTERPRISE; tier limits include SCALE; outdated notes removed; webhook ceilings updated.
284
533
  - Export streams never report a failed export as complete. A `_done` trailer with
285
534
  `complete: false`, or any line whose only key is `_error`, now throws `IncompleteExportError`
286
535
  (after the rows that did arrive) and leaves `stream.complete` false; before, any `_done` line
287
536
  counted as complete and an `_error` line was yielded as an `ExportRow`. The error line's body is
288
537
  on the exception's `details` and on the new `stream.error`. Unknown `_done` fields
289
- (`truncatedBy`, `credits`) are kept on `stream.done`. (PLAN.md §1.8; lex-api #303.)
290
- - A top-level string `code` on a legacy-shape error body (lex-api #304 adds it next to the text
538
+ (`truncatedBy`, `credits`) are kept on `stream.done`. (SDK contract §1.8.)
539
+ - A top-level string `code` on a legacy-shape error body (API 2.4.0 adds it next to the text
291
540
  `error`) is now the error's `code`, ahead of the status-derived one. A 429 with
292
541
  `code: "QUOTA_EXHAUSTED"` (a legacy plan's used-up daily or monthly-semantic quota) is a
293
542
  `RateLimitedError` with `code === "QUOTA_EXHAUSTED"`, `quotaExhausted` true, `retryAfter`
294
543
  `undefined` and `resetsAt` from the body's `resetsAt`; it is never retried. `QUOTA_EXHAUSTED`
295
544
  joins `ErrorCode`. Servers without the `code` are still recognised by the old shape check.
296
- (PLAN.md §1.2/§1.3.)
297
- - Export parameters for API 2.3.0 (lex-api #303): `documentTypeCode` (a type family) and
545
+ (SDK contract §1.2/§1.3.)
546
+ - Export parameters for API 2.3.0: `documentTypeCode` (a type family) and
298
547
  `changedSince` (rows whose text changed); `fetchedSince` / `changedSince` also take a `Date`
299
548
  (sent as UTC). A `limit` that is not a positive integer throws `RangeError` before the request
300
549
  (the API answers 400). `ExportDoneInfo` types `truncatedBy` and `credits`. Docs describe the
301
- per-row billing and the filter semantics of API 2.3.0. **Publish only after lex-api #303 is
302
- deployed.**
550
+ per-row billing and the filter semantics of API 2.3.0.
303
551
  - `stream.truncated` reads `_done.truncated` first once the trailer has been read. From API
304
552
  2.3.0 that flag is authoritative: set when matching rows remain unreached (`truncatedBy`:
305
553
  `limit`, `max_rows`, `credits` or `recovered` — both join the type) and never derived from the row
306
554
  count. The `X-Export-Truncated` header and `_meta.truncated` come from an up-front count that
307
555
  may be a minute old and never caps the stream, so they are now only the fallback before the
308
- trailer arrives. (PLAN.md §1.8; lex-api #303.)
556
+ trailer arrives. (SDK contract §1.8.)
309
557
 
310
558
  ### Changed
311
559
 
312
- Retries, timeouts and error codes now follow the shared SDK contract (PLAN.md §1, identical in
560
+ Retries, timeouts and error codes now follow the shared SDK contract (docs/sdk-contract.md §1, identical in
313
561
  `lexapi-python`) — **an SDK retries only when the retry cannot charge the caller twice**:
314
562
 
315
563
  - **Retry decision table (§1.2).** 429 that is not a quota: every call. Never reached the server (DNS failure,
@@ -320,7 +568,7 @@ Retries, timeouts and error codes now follow the shared SDK contract (PLAN.md §
320
568
  timeout): **free calls only** (`getInfo`, webhook reads). Never: quota 429, 4xx, 500.
321
569
  0.1 retried every 502/503/504 and every network error on a GET, including when a proxy answered after the API
322
570
  had charged the call (no refund), and never retried a POST that provably never left the machine.
323
- - **App-origin** = a non-empty `X-LexAPI-Version` header (lex-api #299 on) or a `RateLimit-Limit` header (the
571
+ - **App-origin** = a non-empty `X-LexAPI-Version` header (API 2.1.0 on) or a `RateLimit-Limit` header (the
324
572
  app's rate limiter sets `RateLimit-*` on every billable app response; proxies never do). A JSON error body alone
325
573
  is not enough.
326
574
  - **New opt-in `retry.retryReadOnlyPosts`** (default off): the eight read-only POSTs (`search`, `getDocument`,
@@ -390,5 +638,5 @@ Initial release: request core (auth, retries with `Retry-After`, typed errors, c
390
638
  search and document endpoints, citations, semantic search (incl. HyDE), webhooks, NDJSON export,
391
639
  point-in-time versions.
392
640
 
393
- [0.2.0]: https://github.com/Lex-API/lexapi-typescript/compare/583b501...v0.2.0
641
+ [0.5.0]: https://www.npmjs.com/package/@lexapi/client/v/0.5.0
394
642
  [0.1.0]: https://www.npmjs.com/package/@lexapi/client/v/0.1.0
package/README.md CHANGED
@@ -10,7 +10,7 @@ Official TypeScript SDK for [LexAPI](https://lex-api.com/?ref=npm-sdk) — Europ
10
10
  npm install @lexapi/client
11
11
  ```
12
12
 
13
- Node ≥ 18 (native `fetch`); the built package is also smoke-tested on Bun and Deno in CI. Zero runtime dependencies, ESM + CommonJS, strict hand-curated types. **Server-side only** — API keys are secrets and must never ship in client-side code (the SDK also skips the `User-Agent` header on browser runtimes, where setting it is forbidden).
13
+ Version 0.5.0 targets LexAPI API 3.0.0. Node ≥ 18 (native `fetch`); the built package is also smoke-tested on Bun and Deno in CI. Zero runtime dependencies, ESM + CommonJS, strict hand-curated types. **Server-side only** — API keys are secrets and must never ship in client-side code (the SDK also skips the `User-Agent` header on browser runtimes, where setting it is forbidden).
14
14
 
15
15
  ## Quickstart
16
16
 
@@ -36,6 +36,7 @@ LexAPI bills a monthly credit pool ([plans](https://lex-api.com/pricing?ref=npm-
36
36
  | 5 → 4 → 1 | `getDocument`, `getDocumentsBatch` (per item), `getDocumentByUrl`, `getDocumentMetadata` — 5 for a live browser fetch, settled to **4** when the Publications Office Cellar API answered, to **1** from the LexAPI corpus (`result.headers.source`); a text-unavailable answer settles at 1 |
37
37
  | 5 → 1 | `extractCitations` — refunded to 1 when the document was `alreadyExtracted` |
38
38
  | 5 | `semanticSearch`, `semanticLegislationSearch` (+ per live `asOf` fetch, see below) |
39
+ | 1 → 4 / 5 | `legislationAsOf` — 1 for the version alone or a provision read from the LexAPI corpus; 4 when the text is fetched (5 live from EUR-Lex), whatever the answer; 1 if the fetch fails |
39
40
  | 5 | `getTransposition` — every plan |
40
41
  | 15 | `semanticSearch({ hyde: true })` — refunded to 5 if HyDE falls back |
41
42
  | 20 | `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats` |
@@ -43,7 +44,7 @@ LexAPI bills a monthly credit pool ([plans](https://lex-api.com/pricing?ref=npm-
43
44
  | 0 | `getNationalCoverage` (public) |
44
45
  | 1 | `getNationalDocument` — every national read is a corpus read, so the 5-credit reservation always settles to 1 (an unknown id too) |
45
46
  | 3 per call | `listNationalDocuments` — flat; pagination does not multiply the price |
46
- | 5 | `nationalSemanticSearch`, `nationalLegislationSemanticSearch` — `hyde` never raises this for national case law |
47
+ | 5 | `nationalSemanticSearch`, `nationalLegislationSemanticSearch` — `hyde` never raises this for national case law; `asOf` adds nothing |
47
48
 
48
49
  Failed requests refund automatically (400/403 and 5xx in full; a 404 settles at 1). Refunds land just after the response, so a response's `credits` block can still show the upfront charge. The national-law call allowance follows the same rule: a failed call (other than a 404) gives its call back too.
49
50
 
@@ -114,6 +115,14 @@ const cases = await client.semanticSearch({
114
115
  includeText: true, // full text per hit instead of the default ~600-char `snippet`
115
116
  });
116
117
  if (cases.hint) console.warn(cases.hint); // present only on low-confidence result sets
118
+ for (const hit of cases.results) {
119
+ // With includeText (API 2.30.0): { available: true } or { available: false, reason }
120
+ const celex = hit.metadata?.celex_id;
121
+ if (hit.textAvailability?.available === false && celex) {
122
+ console.log(hit.textAvailability.reason, hit.snippet); // the snippet is not court text
123
+ const { document } = await client.getDocument({ celexNumber: celex }); // read the document itself
124
+ }
125
+ }
117
126
 
118
127
  // HyDE query rewriting — 15 credits instead of 5, ~1-3 s extra latency.
119
128
  // Best-effort: on LLM failure the response reports hyde: false and the premium is refunded.
@@ -134,6 +143,10 @@ for (const hit of articles.results) {
134
143
 
135
144
  Persistent identity for case-law hits is `(metadata.celex_id, metadata.document_type)` — `case_id` is snapshot-scoped and does not survive index rebuilds.
136
145
 
146
+ With `includeText: true`, every case-law hit carries `textAvailability` (API 2.30.0). A hit whose text LexAPI does not hold carries `{ available: false, reason: "not_in_corpus" }` (or `"unknown"` when LexAPI could not check; a retry may return the text) and keeps its `snippet`; `getDocument` with `metadata.celex_id` reads the document. A case-law `snippet` is cut from the machine-written `summary` when the hit has one, with or without `includeText`: it is not court text. The reason is an open string (do not switch on it exhaustively), and these reasons are not the ones a document's `textAvailability` uses. National hits do not carry `textAvailability`.
147
+
148
+ EU legislation hits, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl` and `getDocumentMetadata` carry the in-force label of the act when its status is known (API 2.19.0): `inForce` (today, UTC), with `notInForceReason`, `endOfValidity` or `entryIntoForce`; all absent when unknown. `semanticLegislationSearch({ inForce: true })` keeps only hits known to be in force today and reports what it removed in `inForceFilter`. Documents, snapshots and EU semantic hits also carry `provenance` and `fieldProvenance` (API 2.20.0).
149
+
137
150
  ### The text in force on a date (`asOf`)
138
151
 
139
152
  ```ts
@@ -152,6 +165,27 @@ for (const hit of asOf.results) {
152
165
 
153
166
  The act must be in force on that date; the version is the act as published before its first consolidation, otherwise the consolidated version in force (later versions never count). `asOf` accepts `1952-01-01` … today (UTC); an invalid date is a 400 `InvalidParamsError`, refunded in full. **Cost:** 5 for the search; each live fetch of a version the corpus doesn't hold reserves 5 and settles by outcome (Cellar 4, browser 5, no text 1, failed 0), at most 3 per request by default. A fetch your pool can't cover is skipped (`asOfReason: "insufficient_credits"`) — never a 402. `AS_OF_REASONS` lists every documented reason.
154
167
 
168
+ ### An act on a date (`legislationAsOf`)
169
+
170
+ ```ts
171
+ // POST /legislation/as-of — needs LexAPI API 2.26.0
172
+ const answer = await client.legislationAsOf({
173
+ document: "32016R0679",
174
+ asOf: "2019-06-01",
175
+ provision: "art_17", // optional: an article, an annex ("anx_III") or recitals ("rct_26-28")
176
+ });
177
+
178
+ if (answer.asOfResolved) {
179
+ console.log(answer.asOfVersion); // { celex: "02016R0679-20160504", kind: "consolidated", date: "2016-05-04" }
180
+ console.log(answer.provision?.text);
181
+ if (answer.consolidated) console.log(answer.baseCelex, answer.consolidatedNote); // cite the authentic act
182
+ } else {
183
+ console.log(answer.asOfReason); // e.g. "not_yet_in_force" — a normal answer, not an error
184
+ }
185
+ ```
186
+
187
+ For an act you already know; `semanticLegislationSearch` with `asOf` (above) is the search by meaning. The answer is the newest consolidated version dated on or before `asOf`, or the act as published in the Official Journal when none is. An answer that cannot be established is returned, not thrown: `asOfResolved: false` with an `asOfReason` and no `provision` — use a text only when `asOfResolved` is `true`. Unresolved answers are not thrown, so a `try`/`catch` never sees them: `fetch_*`, `request_deadline`, `version_list_unavailable` and `version_lookup_cap` are worth asking again; the other reasons are final for that date. Consolidated versions have no legal force; only the act as published in the Official Journal (`baseCelex`) is authentic. `document` is always the act itself; `asOfVersion.celex` (and `date`) name the version the text comes from. `asOfVersion.validUntil`, when present, is the last day that version is the answer. The answer does not say whether an individual provision applied on that date, and `act.inForceToday` is about today, not `asOf`. An unknown act is a 404 `NotFoundError`; invalid input is a 400 (`InvalidCelexError` / `InvalidParamsError`). An API older than 2.26.0 has no such endpoint and also answers 404 (`NotFoundError`). `err.unknownEndpoint` is `false` there (the API sends it from 2.27.0): check `err.message.includes("Unknown API endpoint")`. **Cost:** 1 credit when no text is fetched; when the provision's text has to be fetched, 4 (5 when it is fetched live from EUR-Lex) whatever the answer, and 1 if the fetch fails or finds no text. A fetch reserves up to 5 credits: a pool holding fewer gets `asOfReason: "insufficient_credits"`. `AS_OF_LOOKUP_REASONS` lists every documented reason.
188
+
155
189
  ## Citations
156
190
 
157
191
  ```ts
@@ -267,8 +301,24 @@ const hits = await client.nationalSemanticSearch("AT", { query: "Datenschutz bei
267
301
  for (const h of hits.results) console.log(h.document.documentKind, h.document.ecli, h.document.dateOfDocument);
268
302
  const articles = await client.nationalLegislationSemanticSearch("DE", { query: "Kündigungsfrist" }); // 5 credits
269
303
  if (articles.partial) console.warn(articles.hint); // SEARCH_INCOMPLETE: results may be missing better matches
304
+
305
+ // asOf labels each hit for a date (API 2.29.0); the texts searched and returned are today's
306
+ const dated = await client.nationalLegislationSemanticSearch("AT", { query: "Recht auf Auskunft", asOf: "2020-06-01" });
307
+ for (const h of dated.results) {
308
+ if (h.asOfResolved) console.log(h.article_ref, h.asOfVersion?.validFrom, h.asOfVersion?.checkedAt);
309
+ else console.log(h.article_ref, h.asOfReason); // e.g. "provision_amended_since" — today's wording, not established for the date
310
+ }
270
311
  ```
271
312
 
313
+ **National `asOf` (API 2.29.0).** The search runs over today's texts only: a provision repealed or
314
+ replaced since the date cannot be found, and the text is never swapped. A hit is resolved
315
+ (`asOfResolved: true`, `asOfVersion: { kind: "current_unit", validFrom, validTo, sourceId, checkedAt }`)
316
+ only when the publisher's dates, as of LexAPI's last recorded read of the act (`checkedAt`), show
317
+ that today's wording already applied on the date. An unresolved hit keeps today's wording; it is not
318
+ established as the text for the date (`asOfReason`, listed in `NATIONAL_AS_OF_REASONS`). LexAPI
319
+ holds such dates for Austria and Spain; elsewhere every hit is `asof_not_available`. `asOf` is a
320
+ `YYYY-MM-DD` string. `isNationalAsOfVersion(v)` tells it from the EU `asOfVersion` by `kind`.
321
+
272
322
  **Incomplete national searches.** When the national index could not complete a semantic search,
273
323
  results may be incomplete: with hits left the answer carries `partial: true`,
274
324
  `partialReason: "SEARCH_INCOMPLETE"` and a `hint` (retry, or rephrase / change the filters). With
@@ -340,7 +390,7 @@ for await (const page of client.webhooks.paginateDeliveries(created.webhook.id))
340
390
  await client.webhooks.delete(created.webhook.id);
341
391
  ```
342
392
 
343
- Webhooks per account: FREE 0 · STARTER 2 · PROFESSIONAL 10 · BUSINESS 50 · SCALE 100 · ENTERPRISE 100. Unsupported criteria are refused with a 400 `InvalidParamsError` whose `details` names each problem. Write calls are never retried on 5xx.
393
+ Webhooks per account: FREE 0 · STARTER 2 · PROFESSIONAL 10 · BUSINESS 50 · SCALE 100 · ENTERPRISE 100. Unsupported criteria are refused with a 400 `InvalidParamsError` whose `details` names each problem. Write calls are retried only on a 429 that is neither an exhausted quota nor a failed payment, or when the request never reached the API (connect failure, Cloudflare 521/522/523).
344
394
 
345
395
  ### Receiving deliveries
346
396
 
@@ -364,6 +414,8 @@ app.post("/webhooks/lexapi", express.raw({ type: "application/json" }), async (r
364
414
  });
365
415
  ```
366
416
 
417
+ `verifyWebhook` decodes the body as strict UTF-8 (one leading byte order mark is ignored) and parses it from the same bytes the signature covers; a body that is not valid UTF-8, or not one strict JSON object (no `NaN` or `Infinity`), throws `WebhookSignatureError("malformed_body")`. The error's `reason` is the first check that fails: `missing_secret`, `missing_signature` (header absent or empty), `invalid_signature`, `malformed_body`, `stale_timestamp` (a `timestamp` that is not `YYYY-MM-DDTHH:MM:SS[.fraction]` with `Z` or `±HH:MM` naming a real date and time in years 0001–9999, or further than `toleranceMs` from now; the edge passes). `toleranceMs: 0` turns the window off, a negative value rejects every delivery, and `NaN` is a `RangeError`. A secret with a lone surrogate is `missing_secret`. The header is trimmed of spaces, tabs, CR and LF only. Pass the raw bytes (`Buffer`, `Uint8Array`, `ArrayBuffer`); a string stands for its UTF-8 encoding, and a string with a lone surrogate, which has none, fails verification (`verifySignature` returns `false`, `verifyWebhook` throws `invalid_signature`, `computeSignature` throws `malformed_body`).
418
+
367
419
  `verifySignature(rawBody, signature, secret)` is the signature-only check. Both use Web Crypto (constant-time comparison); an empty `secret` throws `WebhookSignatureError("missing_secret")` (a configuration error, not a bad delivery).
368
420
 
369
421
  ## Corpus export (BUSINESS, SCALE, ENTERPRISE)
@@ -382,31 +434,42 @@ const stream = await client.export({ documentTypeCode: "regulation", dateFrom: "
382
434
  console.log(stream.meta?.totalMatching, stream.headers.total); // leading _meta envelope / X-Export-Total
383
435
 
384
436
  for await (const row of stream) {
385
- process(row.celex, row.documentTypeCode, row.parsedContent);
437
+ handleRow(row.celex, row.documentTypeCode, row.parsedContent);
386
438
  }
387
439
 
388
440
  console.log(stream.done?.written, stream.done?.skippedStubs);
389
441
  if (stream.truncated) console.warn(`rows not reached (${stream.done?.truncatedBy}) — narrow filters or resume via changedSince`);
390
442
  ```
391
443
 
392
- The `_meta`/`_done` envelope lines are never yielded as rows; the stream is single-pass (re-iterating a fully read stream yields nothing; iterating one you ended early raises `IncompleteExportError` — call `export()` again to re-read). Breaking out of the loop (or `stream.cancel()`, or the call's `signal`) releases the connection. **A stream that ends without its `_done` trailer throws `IncompleteExportError`** (so does a `_done` with `complete: false`, or an `_error` line, which is never yielded as a row) after yielding the rows that did arrive — the server stopped mid-export and they are not the whole set (`stream.complete` stays `false`; `stream.rowsRead` counts them). A dropped connection throws `NetworkError`, a stall longer than `timeoutMs` throws `TimeoutError`. Lines that are not JSON objects are counted in `stream.invalidLines`. For "did matching rows remain that this export did not reach?" read `stream.truncated` — after iterating it is the server's authoritative `_done.truncated` (`stream.done?.truncatedBy`: `limit`, `max_rows`, `credits` or `recovered`); before that, a hint from the up-front count. Metadata-only rows are skipped unless `includeStubs: true`.
444
+ The `_meta`/`_done` envelope lines are never yielded as rows; the stream is single-pass (re-iterating a fully read stream yields nothing; iterating one you ended early raises `IncompleteExportError` — call `export()` again to re-read). Breaking out of the loop (or `stream.cancel()`, or the call's `signal`) releases the connection. **A stream that ends without its `_done` trailer throws `IncompleteExportError`** (so does a `_done` with `complete: false`, or an `_error` line, which is never yielded as a row) after yielding the rows that did arrive — the server stopped mid-export and they are not the whole set (`stream.complete` stays `false`; `stream.rowsRead` counts them). A dropped connection throws `NetworkError`, a stall longer than `timeoutMs` throws `TimeoutError`. A line ends at a line feed byte; lines are read as strict UTF-8 whatever charset the response names (one byte order mark at the very start of the stream is ignored) and trimmed of spaces, tabs and CR; lines that are not UTF-8, or not one JSON object, are counted in `stream.invalidLines`, and blank lines are skipped. `stream.meta` comes only from the very first line. For "did matching rows remain that this export did not reach?" read `stream.truncated` — after iterating it is the server's authoritative `_done.truncated` (`stream.done?.truncatedBy`: `limit`, `max_rows`, `credits` or `recovered`); before that, a hint from the up-front count, and `false` when nothing says. Metadata-only rows are skipped unless `includeStubs: true`.
393
445
 
394
446
  ## Point-in-time versions
395
447
 
396
- Versions are LexAPI *observation snapshots* — the document as fetched — not legal in-force reconstructions; history begins at first ingestion. (For the text in force on a date, use a consolidated CELEX or `semanticLegislationSearch({ asOf })`.)
448
+ Versions are LexAPI's fetch snapshots — the document as LexAPI fetched it — not the law in force on a date; history begins at first ingestion. (For the version of an EU act for a date, use `legislationAsOf`.)
397
449
 
398
450
  ```ts
451
+ import { NotFoundError } from "@lexapi/client";
452
+
399
453
  const history = await client.listDocumentVersions("32016R0679");
400
454
  console.log(history.currentVersion, history.trackedSince);
401
455
 
402
456
  const snapshot = await client.getDocumentVersion("32016R0679", 2);
403
457
  console.log(snapshot.document.parsedContent, snapshot.corpusVersion);
404
458
 
405
- const atDate = await client.getDocumentAtDate("32016R0679", "2026-03-20");
406
- console.log(atDate.asOf, atDate.document.version);
459
+ try {
460
+ const atDate = await client.getDocumentAtDate("32016R0679", "2026-04-01");
461
+ console.log(atDate.kind); // "observation_snapshot" — not the law in force on that date
462
+ console.log(atDate.document.observedFrom); // when this version began in LexAPI's fetch history (null: no record of it)
463
+ console.log(atDate.document.observedUntil); // when the next version's text arrived (null: current version)
464
+ if (atDate.inForceLookup) console.log("for the act on a date, use legislationAsOf");
465
+ } catch (err) {
466
+ if (err instanceof NotFoundError && err.beforeTracking) console.log(err.trackedSince); // tracking began later
467
+ else if (err instanceof NotFoundError && err.boundaryUnknown) console.log(err.candidates); // read them with getDocumentVersion
468
+ else throw err;
469
+ }
407
470
  ```
408
471
 
409
- Each call costs 1 credit. Dates before the document entered the corpus reject with `NotFoundError` carrying the tracking start date.
472
+ `fetchedAt` is when a version's text arrived at LexAPI; `observedFrom` is when the version began in LexAPI's fetch history, `null` when LexAPI has no record of it — then `fetchedAt` is the last fetch of its text, not when the version began. A future date returns the current version with `dateInFuture: true` (and `xWarning`). Each call costs 1 credit; a `boundaryUnknown` 404 is refunded. A date before the document entered the corpus rejects with `NotFoundError` (`beforeTracking`, `trackedSince`); a date next to a version stored before API 2.28.0 whose start LexAPI has no record of rejects with `boundaryUnknown` and `candidates` (`{ version, fetchedAt, observedFrom }`, at most 10, `candidatesTruncated` beyond; `[]` when none).
410
473
 
411
474
  ## Response headers
412
475
 
@@ -428,6 +491,8 @@ On the four national document/semantic endpoints, `headers.nationalAllowance` (`
428
491
  ## Configuration
429
492
 
430
493
  ```ts
494
+ import { LexAPI } from "@lexapi/client";
495
+
431
496
  const client = new LexAPI({
432
497
  apiKey: "lex_...", // or LEXAPI_API_KEY env var
433
498
  baseUrl: "https://lex-api.com/api/v1", // default
@@ -438,9 +503,11 @@ const client = new LexAPI({
438
503
  });
439
504
  ```
440
505
 
506
+ Redirects are followed only within the origin of `baseUrl` (or to the same host over HTTPS on the default ports), at most five per attempt; any other redirect is refused with a `NetworkError`, so the API key is never sent to another origin. A custom `fetch` must honour `redirect: "manual"` for this to hold.
507
+
441
508
  ## Retries, timeouts and cancellation
442
509
 
443
- The SDK retries automatically **only when a retry cannot charge you twice** (the shared SDK contract, [PLAN.md §1.2](PLAN.md)). Up to 3 retries (`retry.maxRetries`), exponential backoff with full jitter (base 0.5 s, cap 30 s):
510
+ The SDK retries automatically **only when a retry cannot charge you twice** (the shared SDK contract, [§1.2](https://github.com/Lex-API/lexapi-typescript/blob/main/docs/sdk-contract.md)). Up to 3 retries (`retry.maxRetries`), exponential backoff with full jitter (base 0.5 s, cap 30 s):
444
511
 
445
512
  | Failure | GET, billed | GET, free (`getInfo`, webhook reads) | Read-only POST | Mutating call |
446
513
  |---|---|---|---|---|
@@ -452,11 +519,13 @@ The SDK retries automatically **only when a retry cannot charge you twice** (the
452
519
  | Any other transport error (reset, connection closed — `fetch` cannot tell before-response from mid-response — read error, `REQUEST_TIMEOUT`) | no | retry | no | no |
453
520
  | 400 / 401 / 402 / 403 / 404 / 500 and anything else | no | no | no | no |
454
521
 
455
- - **Read-only POSTs** are `search`, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl`, `getDocumentMetadata`, `resolve`, `semanticSearch`, `semanticLegislationSearch`. **Mutating calls** are the webhook writes and `extractCitations` (it persists edges).
522
+ - **Read-only POSTs** are `search`, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl`, `getDocumentMetadata`, `resolve`, `semanticSearch`, `semanticLegislationSearch`, `legislationAsOf`, `nationalSemanticSearch`, `nationalLegislationSemanticSearch`. **Mutating calls** are the webhook writes and `extractCitations` (it persists edges).
456
523
  - **App-origin** = the response carries a non-empty `X-LexAPI-Version` header or a `RateLimit-Limit` header (the API's rate limiter sets `RateLimit-*` on every billable app response; proxies never do). A JSON error body alone is not enough. Anything else is treated as a proxy answer: the API may have charged the call and not refunded it, so a billed call is not retried.
457
- - **Wait:** `Retry-After` on any status (an empty or unparseable value counts as absent); on a 429 only, then `RateLimit-Reset` and the JSON `retryAfter` field; on a 503 `NATIONAL_SEMANTIC_UNAVAILABLE` (an incomplete national search), the JSON `retryAfter` field. `X-RateLimit-*` is not read. Every hint is clamped to the 30 s cap (`retry.maxDelayMs`; a cap below the server's requested wait shortens it); numbers above 1e12 / 1e9 are read as epoch ms / s. A quota 429 has `retryAfter: undefined`.
524
+ - **Wait:** `Retry-After` on any status (decimal seconds such as `5` or `2.5`, or an HTTP-date in one of the three RFC 9110 forms with `GMT`, `UTC` or `+0000`; anything else counts as absent); on a 429 only, then `RateLimit-Reset` (decimal seconds) and the JSON `retryAfter` field (a number ≥ 0, else absent; the top-level field first, then the one in `details`); on a 503 `NATIONAL_SEMANTIC_UNAVAILABLE` (an incomplete national search), the JSON `retryAfter` field. `X-RateLimit-*` is not read. Every hint is clamped to the 30 s cap (`retry.maxDelayMs`; a cap below the server's requested wait shortens it); numbers above 1e12 / 1e9 are read as epoch ms / s. A quota 429 has `retryAfter: undefined`. An incomplete national search whose only hint is unusable is not retried. No wait is longer than 2^31−1 ms (about 24.8 days), whatever `maxDelayMs` says: a longer timer would fire at once.
458
525
 
459
- **Timeout:** `timeoutMs` (default 95 s) is an *inactivity* limit per attempt: the longest the SDK waits for the next bytes — until the response head, then between body chunks (the timer restarts on every chunk), for JSON bodies and export streams alike. It is not a deadline for the whole call. On expiry you get `TimeoutError` with `code: "REQUEST_TIMEOUT"` (status 0). `fetch` cannot time the connect phase separately, so it counts inside the first window. 95 s lets the API's own 90 s limit on one live EUR-Lex fetch reach you as a typed, refunded 504; a request needing several upstream fetches can still exceed it.
526
+ **Timeout:** `timeoutMs` (default 95 s) is an *inactivity* limit per attempt: the longest the SDK waits for the next bytes — until the response head, then between body chunks (the timer restarts on every chunk), for JSON bodies and export streams alike. It is not a deadline for the whole call. On expiry you get `TimeoutError` with `code: "REQUEST_TIMEOUT"` (status 0). `fetch` cannot time the connect phase separately, so it counts inside the first window. The 95 s default sits above the API's 90 s deadline on document reads, so that timeout comes back as a typed, refunded 504; the CDN ends any wait at 100 s. `timeoutMs: Infinity` sets no limit, and `0` times out at once (on an export stream's body reads, `0` sets no idle limit); a value above 2^31−1 ms is clamped to that.
527
+
528
+ **Iterators:** `paginateCites`, `paginateCitedBy`, `webhooks.paginateDeliveries` and `paginateNationalDocuments` yield each page as it arrives and end by the documented stop conditions (a short or empty page, `totalEdges` / `total` reached, no `nextCursor`, `hasMore` not `true`, a page without its list). They throw `InvalidResponseError` when the server stops advancing: a cites/cited-by page echoing an `offset` other than the one requested; a `nextCursor` already sent in the walk; and, only when the answers carry no usable `totalEdges`/`offset` (cites, cited-by) or `total` (deliveries), three pages in a row that repeat the one before (cites, cited-by: the same list; deliveries: no unseen `id`); a page with such a signal ends a run (on cites/cited-by its list is still the one the next page is compared with). A national `nextCursor` that is not a string throws too. When a walk throws, the pages already yielded stay valid; the page that showed the stall is not yielded and is on `err.body`. A starting `offset` that is not an integer ≥ 0, or a `limit` that is not an integer ≥ 1 (each at most 2^53 − 1), is a `RangeError` before any request (every iterator, `paginateNationalDocuments` included). Cites/cited-by advance by each group's `citationCount`; a group whose count is 0 but whose edge list is not empty counts its list.
460
529
 
461
530
  **Cancellation:** every method takes `{ signal }`. Aborting cancels the in-flight request, any retry wait and an export stream (the connection is released), and rejects with `RequestAbortedError` (`code: "ABORTED"`, `cause` = the signal's reason).
462
531
 
@@ -471,7 +540,7 @@ await client.semanticSearch({ query: "gdpr" }, { signal: controller.signal });
471
540
  Every non-2xx response maps to a typed error carrying `code`, `status`, `message`, `details`, `retryAfter`, the raw `body` and parsed `headers`:
472
541
 
473
542
  ```ts
474
- import { CreditsExhaustedError, NotFoundError, RateLimitedError, TierForbiddenError } from "@lexapi/client";
543
+ import { CreditsExhaustedError, NotFoundError, PaymentPastDueError, RateLimitedError, TierForbiddenError } from "@lexapi/client";
475
544
 
476
545
  try {
477
546
  await client.semanticSearch({ query: "gdpr" });
@@ -479,15 +548,16 @@ try {
479
548
  if (err instanceof RateLimitedError && err.quotaExhausted) console.log(`legacy quota resets ${err.resetsAt}`);
480
549
  else if (err instanceof RateLimitedError) console.log(`retry in ${err.retryAfter}s`, err.rateLimit);
481
550
  else if (err instanceof CreditsExhaustedError) console.log(`need ${err.weight}, have ${err.available}; resets ${err.resetsAt}`);
551
+ else if (err instanceof PaymentPastDueError) console.log(`pay the open invoice: ${err.billingUrl ?? "in the dashboard"}`); // before TierForbiddenError: it extends it
482
552
  else if (err instanceof TierForbiddenError) console.log((err.body as { upgradeUrl?: string })?.upgradeUrl);
483
- else if (err instanceof NotFoundError) console.log("no such document");
553
+ else if (err instanceof NotFoundError) console.log(err.unknownEndpoint || err.message.includes("Unknown API endpoint") ? "no such endpoint" : "no such document");
484
554
  else throw err;
485
555
  }
486
556
  ```
487
557
 
488
558
  | Class | `code` | HTTP |
489
559
  | --- | --- | --- |
490
- | `NotFoundError` | `NOT_FOUND` | 404 |
560
+ | `NotFoundError` | `NOT_FOUND` | 404 — `.unknownEndpoint` is `true` when the API (2.27.0 or later) has no such endpoint: a mistyped path, a method newer than the API, or a national route for a country that is not available. Always `false` on APIs before 2.27.0; there the message contains "Unknown API endpoint". `.reason` is `details.reason`; on `getDocumentAtDate` (API 2.28.0) `.beforeTracking` (with `.trackedSince`, `.inForceLookup`) or `.boundaryUnknown` (with `.candidates`, `.candidatesTruncated`). |
491
561
  | `DocumentWithdrawnError` | `DOCUMENT_WITHDRAWN` | 410 — a national document its source withdrew; nothing of it is served; `.id`/`.jurisdiction`/`.withdrawnAt`; not retryable, drop any copy you hold |
492
562
  | `InvalidCelexError` / `InvalidUrlError` / `InvalidParamsError` | `INVALID_CELEX` / `INVALID_URL` / `INVALID_PARAMS` | 400 — `InvalidParamsError.param` / `.value` / `.allowed` name a refused filter, the value sent and the allowed values |
493
563
  | `AuthenticationError` | `UNAUTHORIZED` (derived) | 401 |
@@ -495,6 +565,7 @@ try {
495
565
  | `NationalAllowanceExhaustedError` | `NATIONAL_ALLOWANCE_EXHAUSTED` | 402 — FREE/STARTER/PROFESSIONAL's monthly national-law call allowance is used up; `resetsAt`/`limit`/`upgradeUrl` |
496
566
  | `NationalSemanticNotEnabledError` | `NATIONAL_SEMANTIC_NOT_ENABLED` | 409 — this jurisdiction has no semantic index to search; `.jurisdiction`; not retryable, refunded |
497
567
  | `TierForbiddenError` | `TIER_FORBIDDEN` | 403 |
568
+ | `PaymentPastDueError` (extends `TierForbiddenError`) | `PAYMENT_PAST_DUE` | 403 — a subscription payment failed and was not completed in time; API requests are refused until the payment succeeds; pay the open invoice in the dashboard (`.billingUrl`; `.accessEndedAt` when known); not retryable. Before API 2.27.0 a failed payment was refused at once with a 403 without a code, raised as `TierForbiddenError`. |
498
569
  | `RateLimitedError` | `RATE_LIMITED`, `QUOTA_EXHAUSTED` | 429 — `QUOTA_EXHAUSTED` (legacy plans' used-up quota) is never retried; `resetsAt` says when it refills |
499
570
  | `InternalServerError` | `INTERNAL` | 500 |
500
571
  | `UpstreamError` | `UPSTREAM_ERROR` | 502; Cloudflare 520–523 |
@@ -504,10 +575,14 @@ try {
504
575
  | `TimeoutError` | `TIMEOUT` (504, 524; 503 from `getCounterparts`, with `.partial` / `.serverTimeoutMs`) / `REQUEST_TIMEOUT` (status 0, the SDK's own timeout) | |
505
576
  | `NetworkError` | `CONNECTION_ERROR` | 0 (transport failure, or the connection dropped — incl. mid-export) |
506
577
  | `RequestAbortedError` | `ABORTED` | 0 (your `signal` fired) |
507
- | `InvalidResponseError` | `INVALID_RESPONSE` | a 2xx whose body was not JSON (e.g. a proxy HTML page) |
578
+ | `InvalidResponseError` | `INVALID_RESPONSE` | a 2xx that is not the documented shape: no body, a body that is not JSON (e.g. a proxy HTML page), JSON that is not an object, `success: false`, a list such as `results` that is missing where the endpoint always sends it, is not a list, or holds items that are not objects, or an object such as `document` that is missing or not an object. Never read as an empty result; unknown extra fields are accepted. The message never quotes the body. |
508
579
  | `IncompleteExportError` | `INCOMPLETE_EXPORT` | 0 — an export ended without a complete `_done` trailer, or the server sent an `_error` line (`rowsRead`, `details`) |
509
580
  | `LexAPIError` (base) | `INTERNAL` | any other status (e.g. 409, 413), with `status` kept |
510
581
 
582
+ `PaymentPastDueError` extends `TierForbiddenError`, so a handler for `TierForbiddenError` still catches a failed payment, as it did before API 2.27.0. To tell the two apart, check `PaymentPastDueError` (or `err.code === "PAYMENT_PAST_DUE"`) first.
583
+
584
+ **Response text on errors.** No error message quotes the response body. For a body that is not JSON, the first 200 characters (code points) are on `err.bodyExcerpt`; for an `InvalidResponseError` about JSON of the wrong shape, the parsed value is on `err.body`. Both are raw response content that may contain document text: do not show them to a model or log them by default. Neither is an own property of the error (both are read through getters), so `console.log(err)`, `util.inspect(err)` and `JSON.stringify(err)` leave them out. A `2xx` answer with `success: false` and an API error in its body throws that error (e.g. `NotFoundError`) with the `2xx` status.
585
+
511
586
  **`instanceof` across builds.** The package ships an ESM and a CommonJS build; in a process that loads both (a CommonJS dependency wrapping the SDK inside an ESM app, Next.js, …) they are two copies of every class. The error classes carry a shared brand (`Symbol.for`), so `err instanceof NotFoundError` is still true for an error thrown by the other copy. `isLexAPIError(err)` / `isLexAPIError(err, NotFoundError)` does the same as a function.
512
587
 
513
588
  Both the typed envelope (`{success: false, error: {code, message, details}}`) and the legacy bare `{error, message, details?}` shape (still used by 429s, API-key 401s, `/search` and webhook validation, the export tier gate and semantic upstream errors) are parsed; unknown codes stay on the base `LexAPIError` with the raw code string.
@@ -532,6 +607,7 @@ npm run lint # tsc --noEmit (strict)
532
607
  npm test # vitest (Node ≥ 20)
533
608
  npm run build # tsup -> dist/ (ESM + CJS + d.ts / d.cts)
534
609
  npm run smoke:dist # framework-free check of the built bundles (runs on Node 18+)
610
+ npm run check:readme # type-check this README's TypeScript examples against dist/
535
611
  ```
536
612
 
537
- See [PLAN.md](PLAN.md) for the endpoint coverage matrix and SDK contract. Docs: <https://lex-api.com/docs?ref=npm-sdk>
613
+ See [docs/sdk-contract.md](https://github.com/Lex-API/lexapi-typescript/blob/main/docs/sdk-contract.md) for the SDK contract. Docs: <https://lex-api.com/docs?ref=npm-sdk>