@lexapi/client 0.2.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,11 +5,429 @@ 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
+
259
+ ## [0.4.0] — 2026-11-11
260
+
261
+ Cross-border citation graph. **Requires LexAPI API 2.13.0.** Additive at runtime: no existing
262
+ signature or field changes meaning. Type-level changes to check when upgrading:
263
+
264
+ - `CitationType` gains `"transposition"` — an exhaustive `switch` over it needs a new case.
265
+ - `citationType` params are now `OneOrMany<CitationType>`: code that reads the param back as a
266
+ single value must handle a list.
267
+ - `NationalDocumentContent` gains the required `textSource` and `ocr` fields — objects you build
268
+ yourself (test fixtures, mocks) need them (`null` is valid for both).
269
+
270
+ ### Added
271
+
272
+ - **`getTransposition(celexNumber, params?, options?)`** (`GET /citations/transposition/{celexNumber}`,
273
+ 5 credits, every plan): the measures the member states notified to the Commission for an EU act
274
+ (CELEX sector 3), grouped by country, from the Publications Office's Cellar records. Every answer
275
+ carries `note` — a notification is not a finding that the measure transposes the act, or
276
+ transposes it completely. On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the measures
277
+ LexAPI holds are filled in (`id`, `resolved`, `resolution`, `resolutionBasis`, `counts.resolved`,
278
+ `source.lanes`) and documents whose national source records the relation are added
279
+ (`provenance: "source"`); otherwise those fields are `null` (`termsRequired: true` while the
280
+ national-source terms are not accepted). Params: `jurisdictions`, `resolvedOnly`, `language`.
281
+ Types: `TranspositionParams`, `TranspositionResponse`, `TranspositionCountry`,
282
+ `TranspositionMeasure`.
283
+ - **`getCounterparts(id, params?, options?)`** (`GET /citations/counterparts/{id}`, 20 credits,
284
+ BUSINESS and above): a national document's counterparts in the other live jurisdictions, through
285
+ the EU acts it transposes or implements, ranked 1–3. A lookup past the server's budget throws
286
+ `TimeoutError` (503, `partial`), refunded; the SDK does not retry it — retry yourself, or narrow
287
+ with `jurisdictions`. Other 503s keep the existing retry policy. Types: `CounterpartsParams`, `CounterpartsResponse`,
288
+ `CounterpartVia`, `Counterpart`.
289
+ - **Edge filters** on `getCites`, `getCitedBy`, `getCitationNetwork`, `getCitationPath` and
290
+ `getRelatedDocuments` (and the `paginate*` helpers): `citationType` now takes one value or a
291
+ list, plus `provenance`, `jurisdictions` and `resolution` (each one value or a list, sent
292
+ comma-separated). `CitationFilterParams`; `CitationPathParams` and `RelatedDocumentsParams` gain
293
+ `citationType` too.
294
+ - **`unresolved: true`** on `getCites` (new `CitesParams`) and `getCitationNetwork` for a national
295
+ document id: `unresolved` (`UnresolvedReference[]`) and `unresolvedTruncated` on the response.
296
+ - **Provenance and resolution on every edge**: `CitationEdgeDetail.provenance` /
297
+ `.resolution`, and `CitationNeighbour.edgeDetails` (`CitationEdgeKind[]`). Types
298
+ `CitationProvenance`, `CitationResolution`; runtime lists `CITATION_TYPES`,
299
+ `CITATION_PROVENANCES`, `CITATION_RESOLUTIONS`.
300
+ - **Node identity** (`CitationNode`: `id`, `jurisdiction`, `documentKind`) on cites / cited-by
301
+ groups, network neighbours, path nodes and related documents. `celexNumber` is unchanged.
302
+ - **`CitationType`** gains `"transposition"`.
303
+ - **Totals**: `totalEdges` and `countsSource` (`"stats"` | `"counted"`, API 2.10.0) on
304
+ `getCites` / `getCitedBy`; `paging.citesEdgeTotal`, `paging.citedByEdgeTotal` and
305
+ `paging.countsSource` (`null` when partial) on `getCitationNetwork`.
306
+ - **`getCitationStats({ includeNational: true })`**: `stats.byJurisdiction`, `stats.byProvenance`,
307
+ `stats.transposition`.
308
+ - **Coverage**: `NationalJurisdictionCoverage.citationGraph` (`NationalCitationGraph`) — extraction
309
+ `methods` (incl. `unmeasured` rate → `not-collected` | `source-empty`), `edges`,
310
+ `decisionResolutionRate`, `actEuRate`, `textPatternRate`, `transposition`, `precision`,
311
+ `measuredAt`, `nimResolvedRate`, `nimMeasuredAt`, `floors`.
312
+ - **National content**: `content.textSource` (`html` | `pdf-text` | `ocr` | `null`) and
313
+ `content.ocr` (`NationalOcrInfo` | `null`) — API 2.9.0.
314
+ - **`InvalidParamsError.param` / `.value` / `.allowed`**: the refused parameter, the value sent
315
+ (when the server echoes it) and its allowed values, read
316
+ from either error shape. **`TimeoutError.partial` / `.serverTimeoutMs`** for a budget timeout.
317
+ - **Incomplete national semantic searches**: `partial` (`true`) and `partialReason`
318
+ (`NationalSearchPartialReason`, `"SEARCH_INCOMPLETE"`) on `NationalSemanticCaseLawResponse` and
319
+ `NationalSemanticLegislationResponse` — the national index could not complete the search and the
320
+ results may be missing better matches; `hint` says whether a retry or a rephrased query / changed
321
+ filters may complete it. With nothing left to return the call fails instead:
322
+ `NationalSemanticUnavailableError` (503) now exposes `.partialReason` (`"SEARCH_INCOMPLETE"`), and
323
+ its `retryAfter` falls back to the body's `retryAfter` when the header is missing.
324
+ - **`NationalSemanticFilterUnreachableError`** (extends `InvalidParamsError`, code
325
+ `NATIONAL_SEMANTIC_FILTER_UNREACHABLE`, 422, `.jurisdiction`, `.partialReason`): the national index
326
+ cannot search this slice (jurisdiction, document kind, filters) completely and there is nothing
327
+ left to return. Not retryable as is — rephrase the query or change the filters. Refunded.
328
+ - **`/resolve`**: optional `ResolveResponse.verified` and the `ResolvedVia` value `"eli-cellar"`
329
+ (servers that send them; `verified: false` means the CELEX was not confirmed by a lookup).
330
+
331
+ ### Changed
332
+
333
+ - A `422 NATIONAL_SEMANTIC_FILTER_UNREACHABLE` is now a `NationalSemanticFilterUnreachableError`,
334
+ a subclass of `InvalidParamsError` (previously the base `LexAPIError`): `catch` blocks for
335
+ `InvalidParamsError` now also see it. The request may be valid — it is a coverage limit of the
336
+ national index, not a malformed request, and `.param` is absent.
337
+ - An incomplete national semantic search `503` without a retry wait (the same search has
338
+ repeatedly come back incomplete) is not retried automatically, even with `retryReadOnlyPosts`.
339
+ With a wait it keeps the existing 503 policy, but is retried at most once per call. A
340
+ `retry.maxDelayMs` below the server's wait shortens that wait. A `503` is never a `RateLimitedError`, whatever
341
+ `Retry-After` / `retryAfter` it carries — only a `429` is.
342
+
343
+ ## [0.3.0] — 2026-10-28
344
+
345
+ Adds national (member-state, and non-EU) law support. **Requires LexAPI API 2.8.0.**
346
+
347
+ ### National document shape (API 2.8.0)
348
+
349
+ The national types follow the normalized cross-jurisdiction contract — a client written for one
350
+ country now works for every other:
351
+
352
+ - `NationalDocumentSummary` (listing rows, documents, and every semantic hit's `document`): every
353
+ field is required and `null` when the source has nothing — `title`, `documentType`, `ecli`,
354
+ `eli`, `dateOfDocument` (`YYYY-MM-DD`), `validTo`, `inForce` — plus the new **`documentKind`**
355
+ (`"act"` | `"decision"`, type `NationalDocumentKind`).
356
+ - `NationalDocument` gains **`decision: NationalDecision | null`** (`court`, `chamber`,
357
+ `caseNumbers[]`, `citedNorms[]` of `NationalCitedNorm { text, documentId }`) and `content` is the
358
+ closed `NationalDocumentContent` (`fullText`, `articles: NationalArticle[]`, `textLanguages`,
359
+ `textLanguage`, `embeddedForeignText`, `repeal: NationalRepeal | null`, `source`, `details`) instead
360
+ of the EU `DocumentContent`. Articles are `{ number, title, section, text, inForceFrom, inForceTo,
361
+ details }`. `textAvailability` is required; `textBasis` is `NationalTextBasis | null`. Source-
362
+ specific keys (Austria's `gericht`, Germany's `aktenzeichen`, unit ids, …) live only under
363
+ `content.details` / `articles[].details` — read `decision` instead.
364
+ - New helper **`isNationalDecision(document)`** — a type guard narrowing to
365
+ `NationalDecisionDocument` (non-null `decision`).
366
+ - `NationalSemanticCaseLawResult` / `NationalSemanticLegislationResult`: required `document`
367
+ (`NationalDocumentSummary`), `documentId`, `jurisdiction`, `attribution`; legislation hits always
368
+ carry `law_title`, `article_ref`, `section`, `language`, `in_force`, `valid_from`, `valid_to`,
369
+ `law_type` (each nullable).
370
+
371
+ ### Added
372
+
373
+ - **National law**: `getNationalCoverage()` (`GET /national/coverage`, public, free — which
374
+ jurisdictions are live, what each covers, sources and their attribution), `getNationalDocument()`
375
+ (`GET /{jurisdiction}/documents/{id}`, 1 credit), `listNationalDocuments()` /
376
+ `paginateNationalDocuments()` (`GET /{jurisdiction}/documents`, 3 credits flat per call — pagination
377
+ does not multiply the price; cursor paging past the first 1,000 rows, newest-first
378
+ by document date), `nationalSemanticSearch()`
379
+ (`POST /{jurisdiction}/search/semantic`, 5 credits — `hyde` accepted but never rewrites or
380
+ changes price here) and `nationalLegislationSemanticSearch()`
381
+ (`POST /{jurisdiction}/legislation/semantic`, 5 credits; no `hyde`/`asOf` — and never forwards a
382
+ bypassed `hyde` either, now that the server validates it strictly as a boolean on this route
383
+ too). New types:
384
+ `NationalCoverageResponse`, `NationalDocument`, `NationalDocumentSummary`,
385
+ `NationalDocumentResponse`, `NationalDocumentListParams`, `NationalDocumentListResponse`,
386
+ `NationalSemanticCaseLawOptions`/`Result`/`Response`, `NationalSemanticLegislationOptions`/
387
+ `Result`/`Response`, `NationalSource`, `NationalJurisdictionCoverage` and friends. Every
388
+ document/result carries `attribution` — always show it alongside the text.
389
+ - **`NationalAllowanceExhaustedError`** (`NATIONAL_ALLOWANCE_EXHAUSTED`, 402): FREE/STARTER/
390
+ PROFESSIONAL get national law within a monthly allowance of calls; BUSINESS and above have no
391
+ separate limit. Typed `jurisdiction`/`limit`/`remaining`/`resetsAt`/`upgradeUrl` getters.
392
+ - **`NationalSemanticNotEnabledError`** (409 `NATIONAL_SEMANTIC_NOT_ENABLED` — a jurisdiction has
393
+ no semantic index at all) and **`NationalSemanticUnavailableError`** (503
394
+ `NATIONAL_SEMANTIC_UNAVAILABLE` — temporarily unreachable; extends `ServiceUnavailableError`, so
395
+ `instanceof ServiceUnavailableError` still holds). Both legacy-shape bodies; `.jurisdiction` is
396
+ read off the raw `body`, not `details`.
397
+ - **`DocumentWithdrawnError`** (`DOCUMENT_WITHDRAWN`, 410): a national document
398
+ its source withdrew (a takedown, a pseudonymisation fix) is served nowhere — no title, no
399
+ metadata, no text. Thrown by `getNationalDocument` (typed envelope, `details: {id, jurisdiction,
400
+ withdrawnAt}`) and by the citation methods for a withdrawn national id (legacy shape, the same
401
+ three fields as top-level siblings instead). `.id`/`.jurisdiction`/`.withdrawnAt` read whichever
402
+ shape answered. Not retryable; nothing is ever charged for it.
403
+ - **`result.headers.nationalAllowance`** (`{ limit, remaining, resetsAt }`), parsed from
404
+ `X-National-Limit`/`X-National-Remaining`/`X-National-Reset` — present only for
405
+ FREE/STARTER/PROFESSIONAL callers on the four national document/semantic endpoints (also on the
406
+ 402 error itself, via `err.headers`).
407
+ - **`includeNational`** on all six citation-graph methods (`getCites`, `getCitedBy`,
408
+ `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats`): also
409
+ returns/follows national documents of live jurisdictions as neighbours — BUSINESS, SCALE and
410
+ ENTERPRISE only (`403 TierForbiddenError` below that). `celexNumber` and `getCitationPath`'s
411
+ `from`/`to` accept a national document id directly (e.g. `"AT-NOR-10001597"`); an id whose
412
+ jurisdiction is not live is a plain `404 NotFoundError`. `getCitationStats` gained an optional
413
+ `params` argument before `options`.
414
+ Back-compatible with 0.2.0's `getCitationStats(options?)`: a first argument shaped like
415
+ `CallOptions` (`timeoutMs`/`signal`, not `includeNational`) is still honoured as the per-call
416
+ options rather than silently read as `params` — this can't be caught at the type level for a
417
+ non-literal variable or a JS caller, so it's detected at runtime too. Every response type
418
+ carries an optional `includeNational` boolean, present once the flag was honoured.
419
+ - The national methods URL-encode the `jurisdiction` path segment (lower-cased, as before), like every other caller-supplied segment — a stray `/` or `?` in that argument can no longer reach a different route.
420
+ - `paginateNationalDocuments` strips `page` from its params at runtime (not just via the
421
+ `Omit<…, "page">` type, which only guards TypeScript callers) — passing both `page` and
422
+ `cursor` to the underlying `GET` is a 400 ("Use either cursor or page, not both").
423
+
424
+ National semantic responses (`nationalSemanticSearch`/`nationalLegislationSemanticSearch`) carry
425
+ the `credits` block, like every other credit-metered route.
426
+
8
427
  ## [0.2.0] — 2026-10-26
9
428
 
10
- Full re-sync with the LexAPI API (validated against lex-api `main` @ `633eb67`, PR #298, and
11
- `openapi.yaml` / `docs.md` at that commit). Every endpoint, parameter, response field and error shape
12
- 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.
13
431
 
14
432
  ### Added
15
433
 
@@ -111,37 +529,35 @@ was audited against the spec **and** the server controllers.
111
529
  the `exports` map now points `require` at `index.d.cts`.
112
530
  - Legacy error bodies dropped their `details` (e.g. which `/search` parameter failed validation).
113
531
  - Docs/README: the export tier gate is a `403` (not `402`) and covers BUSINESS, SCALE and
114
- ENTERPRISE; tier limits include SCALE; "not yet published" and "requires lex-api PR #72" notes
115
- removed; webhook ceilings updated.
532
+ ENTERPRISE; tier limits include SCALE; outdated notes removed; webhook ceilings updated.
116
533
  - Export streams never report a failed export as complete. A `_done` trailer with
117
534
  `complete: false`, or any line whose only key is `_error`, now throws `IncompleteExportError`
118
535
  (after the rows that did arrive) and leaves `stream.complete` false; before, any `_done` line
119
536
  counted as complete and an `_error` line was yielded as an `ExportRow`. The error line's body is
120
537
  on the exception's `details` and on the new `stream.error`. Unknown `_done` fields
121
- (`truncatedBy`, `credits`) are kept on `stream.done`. (PLAN.md §1.8; lex-api #303.)
122
- - 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
123
540
  `error`) is now the error's `code`, ahead of the status-derived one. A 429 with
124
541
  `code: "QUOTA_EXHAUSTED"` (a legacy plan's used-up daily or monthly-semantic quota) is a
125
542
  `RateLimitedError` with `code === "QUOTA_EXHAUSTED"`, `quotaExhausted` true, `retryAfter`
126
543
  `undefined` and `resetsAt` from the body's `resetsAt`; it is never retried. `QUOTA_EXHAUSTED`
127
544
  joins `ErrorCode`. Servers without the `code` are still recognised by the old shape check.
128
- (PLAN.md §1.2/§1.3.)
129
- - 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
130
547
  `changedSince` (rows whose text changed); `fetchedSince` / `changedSince` also take a `Date`
131
548
  (sent as UTC). A `limit` that is not a positive integer throws `RangeError` before the request
132
549
  (the API answers 400). `ExportDoneInfo` types `truncatedBy` and `credits`. Docs describe the
133
- per-row billing and the filter semantics of API 2.3.0. **Publish only after lex-api #303 is
134
- deployed.**
550
+ per-row billing and the filter semantics of API 2.3.0.
135
551
  - `stream.truncated` reads `_done.truncated` first once the trailer has been read. From API
136
552
  2.3.0 that flag is authoritative: set when matching rows remain unreached (`truncatedBy`:
137
553
  `limit`, `max_rows`, `credits` or `recovered` — both join the type) and never derived from the row
138
554
  count. The `X-Export-Truncated` header and `_meta.truncated` come from an up-front count that
139
555
  may be a minute old and never caps the stream, so they are now only the fallback before the
140
- trailer arrives. (PLAN.md §1.8; lex-api #303.)
556
+ trailer arrives. (SDK contract §1.8.)
141
557
 
142
558
  ### Changed
143
559
 
144
- 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
145
561
  `lexapi-python`) — **an SDK retries only when the retry cannot charge the caller twice**:
146
562
 
147
563
  - **Retry decision table (§1.2).** 429 that is not a quota: every call. Never reached the server (DNS failure,
@@ -152,7 +568,7 @@ Retries, timeouts and error codes now follow the shared SDK contract (PLAN.md §
152
568
  timeout): **free calls only** (`getInfo`, webhook reads). Never: quota 429, 4xx, 500.
153
569
  0.1 retried every 502/503/504 and every network error on a GET, including when a proxy answered after the API
154
570
  had charged the call (no refund), and never retried a POST that provably never left the machine.
155
- - **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
156
572
  app's rate limiter sets `RateLimit-*` on every billable app response; proxies never do). A JSON error body alone
157
573
  is not enough.
158
574
  - **New opt-in `retry.retryReadOnlyPosts`** (default off): the eight read-only POSTs (`search`, `getDocument`,
@@ -222,5 +638,5 @@ Initial release: request core (auth, retries with `Retry-After`, typed errors, c
222
638
  search and document endpoints, citations, semantic search (incl. HyDE), webhooks, NDJSON export,
223
639
  point-in-time versions.
224
640
 
225
- [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
226
642
  [0.1.0]: https://www.npmjs.com/package/@lexapi/client/v/0.1.0