@lexapi/client 0.2.0 → 0.4.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,174 @@ 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
+ ## [0.4.0] — 2026-11-11
9
+
10
+ Cross-border citation graph. **Requires LexAPI API 2.13.0.** Additive at runtime: no existing
11
+ signature or field changes meaning. Type-level changes to check when upgrading:
12
+
13
+ - `CitationType` gains `"transposition"` — an exhaustive `switch` over it needs a new case.
14
+ - `citationType` params are now `OneOrMany<CitationType>`: code that reads the param back as a
15
+ single value must handle a list.
16
+ - `NationalDocumentContent` gains the required `textSource` and `ocr` fields — objects you build
17
+ yourself (test fixtures, mocks) need them (`null` is valid for both).
18
+
19
+ ### Added
20
+
21
+ - **`getTransposition(celexNumber, params?, options?)`** (`GET /citations/transposition/{celexNumber}`,
22
+ 5 credits, every plan): the measures the member states notified to the Commission for an EU act
23
+ (CELEX sector 3), grouped by country, from the Publications Office's Cellar records. Every answer
24
+ carries `note` — a notification is not a finding that the measure transposes the act, or
25
+ transposes it completely. On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the measures
26
+ LexAPI holds are filled in (`id`, `resolved`, `resolution`, `resolutionBasis`, `counts.resolved`,
27
+ `source.lanes`) and documents whose national source records the relation are added
28
+ (`provenance: "source"`); otherwise those fields are `null` (`termsRequired: true` while the
29
+ national-source terms are not accepted). Params: `jurisdictions`, `resolvedOnly`, `language`.
30
+ Types: `TranspositionParams`, `TranspositionResponse`, `TranspositionCountry`,
31
+ `TranspositionMeasure`.
32
+ - **`getCounterparts(id, params?, options?)`** (`GET /citations/counterparts/{id}`, 20 credits,
33
+ BUSINESS and above): a national document's counterparts in the other live jurisdictions, through
34
+ the EU acts it transposes or implements, ranked 1–3. A lookup past the server's budget throws
35
+ `TimeoutError` (503, `partial`), refunded; the SDK does not retry it — retry yourself, or narrow
36
+ with `jurisdictions`. Other 503s keep the existing retry policy. Types: `CounterpartsParams`, `CounterpartsResponse`,
37
+ `CounterpartVia`, `Counterpart`.
38
+ - **Edge filters** on `getCites`, `getCitedBy`, `getCitationNetwork`, `getCitationPath` and
39
+ `getRelatedDocuments` (and the `paginate*` helpers): `citationType` now takes one value or a
40
+ list, plus `provenance`, `jurisdictions` and `resolution` (each one value or a list, sent
41
+ comma-separated). `CitationFilterParams`; `CitationPathParams` and `RelatedDocumentsParams` gain
42
+ `citationType` too.
43
+ - **`unresolved: true`** on `getCites` (new `CitesParams`) and `getCitationNetwork` for a national
44
+ document id: `unresolved` (`UnresolvedReference[]`) and `unresolvedTruncated` on the response.
45
+ - **Provenance and resolution on every edge**: `CitationEdgeDetail.provenance` /
46
+ `.resolution`, and `CitationNeighbour.edgeDetails` (`CitationEdgeKind[]`). Types
47
+ `CitationProvenance`, `CitationResolution`; runtime lists `CITATION_TYPES`,
48
+ `CITATION_PROVENANCES`, `CITATION_RESOLUTIONS`.
49
+ - **Node identity** (`CitationNode`: `id`, `jurisdiction`, `documentKind`) on cites / cited-by
50
+ groups, network neighbours, path nodes and related documents. `celexNumber` is unchanged.
51
+ - **`CitationType`** gains `"transposition"`.
52
+ - **Totals**: `totalEdges` and `countsSource` (`"stats"` | `"counted"`, API 2.10.0) on
53
+ `getCites` / `getCitedBy`; `paging.citesEdgeTotal`, `paging.citedByEdgeTotal` and
54
+ `paging.countsSource` (`null` when partial) on `getCitationNetwork`.
55
+ - **`getCitationStats({ includeNational: true })`**: `stats.byJurisdiction`, `stats.byProvenance`,
56
+ `stats.transposition`.
57
+ - **Coverage**: `NationalJurisdictionCoverage.citationGraph` (`NationalCitationGraph`) — extraction
58
+ `methods` (incl. `unmeasured` rate → `not-collected` | `source-empty`), `edges`,
59
+ `decisionResolutionRate`, `actEuRate`, `textPatternRate`, `transposition`, `precision`,
60
+ `measuredAt`, `nimResolvedRate`, `nimMeasuredAt`, `floors`.
61
+ - **National content**: `content.textSource` (`html` | `pdf-text` | `ocr` | `null`) and
62
+ `content.ocr` (`NationalOcrInfo` | `null`) — API 2.9.0.
63
+ - **`InvalidParamsError.param` / `.value` / `.allowed`**: the refused parameter, the value sent
64
+ (when the server echoes it) and its allowed values, read
65
+ from either error shape. **`TimeoutError.partial` / `.serverTimeoutMs`** for a budget timeout.
66
+ - **Incomplete national semantic searches**: `partial` (`true`) and `partialReason`
67
+ (`NationalSearchPartialReason`, `"SEARCH_INCOMPLETE"`) on `NationalSemanticCaseLawResponse` and
68
+ `NationalSemanticLegislationResponse` — the national index could not complete the search and the
69
+ results may be missing better matches; `hint` says whether a retry or a rephrased query / changed
70
+ filters may complete it. With nothing left to return the call fails instead:
71
+ `NationalSemanticUnavailableError` (503) now exposes `.partialReason` (`"SEARCH_INCOMPLETE"`), and
72
+ its `retryAfter` falls back to the body's `retryAfter` when the header is missing.
73
+ - **`NationalSemanticFilterUnreachableError`** (extends `InvalidParamsError`, code
74
+ `NATIONAL_SEMANTIC_FILTER_UNREACHABLE`, 422, `.jurisdiction`, `.partialReason`): the national index
75
+ cannot search this slice (jurisdiction, document kind, filters) completely and there is nothing
76
+ left to return. Not retryable as is — rephrase the query or change the filters. Refunded.
77
+ - **`/resolve`**: optional `ResolveResponse.verified` and the `ResolvedVia` value `"eli-cellar"`
78
+ (servers that send them; `verified: false` means the CELEX was not confirmed by a lookup).
79
+
80
+ ### Changed
81
+
82
+ - A `422 NATIONAL_SEMANTIC_FILTER_UNREACHABLE` is now a `NationalSemanticFilterUnreachableError`,
83
+ a subclass of `InvalidParamsError` (previously the base `LexAPIError`): `catch` blocks for
84
+ `InvalidParamsError` now also see it. The request may be valid — it is a coverage limit of the
85
+ national index, not a malformed request, and `.param` is absent.
86
+ - An incomplete national semantic search `503` without a retry wait (the same search has
87
+ repeatedly come back incomplete) is not retried automatically, even with `retryReadOnlyPosts`.
88
+ With a wait it keeps the existing 503 policy, but is retried at most once per call. A
89
+ `retry.maxDelayMs` below the server's wait shortens that wait. A `503` is never a `RateLimitedError`, whatever
90
+ `Retry-After` / `retryAfter` it carries — only a `429` is.
91
+
92
+ ## [0.3.0] — 2026-10-28
93
+
94
+ Adds national (member-state, and non-EU) law support. **Requires LexAPI API 2.8.0.**
95
+
96
+ ### National document shape (API 2.8.0)
97
+
98
+ The national types follow the normalized cross-jurisdiction contract — a client written for one
99
+ country now works for every other:
100
+
101
+ - `NationalDocumentSummary` (listing rows, documents, and every semantic hit's `document`): every
102
+ field is required and `null` when the source has nothing — `title`, `documentType`, `ecli`,
103
+ `eli`, `dateOfDocument` (`YYYY-MM-DD`), `validTo`, `inForce` — plus the new **`documentKind`**
104
+ (`"act"` | `"decision"`, type `NationalDocumentKind`).
105
+ - `NationalDocument` gains **`decision: NationalDecision | null`** (`court`, `chamber`,
106
+ `caseNumbers[]`, `citedNorms[]` of `NationalCitedNorm { text, documentId }`) and `content` is the
107
+ closed `NationalDocumentContent` (`fullText`, `articles: NationalArticle[]`, `textLanguages`,
108
+ `textLanguage`, `embeddedForeignText`, `repeal: NationalRepeal | null`, `source`, `details`) instead
109
+ of the EU `DocumentContent`. Articles are `{ number, title, section, text, inForceFrom, inForceTo,
110
+ details }`. `textAvailability` is required; `textBasis` is `NationalTextBasis | null`. Source-
111
+ specific keys (Austria's `gericht`, Germany's `aktenzeichen`, unit ids, …) live only under
112
+ `content.details` / `articles[].details` — read `decision` instead.
113
+ - New helper **`isNationalDecision(document)`** — a type guard narrowing to
114
+ `NationalDecisionDocument` (non-null `decision`).
115
+ - `NationalSemanticCaseLawResult` / `NationalSemanticLegislationResult`: required `document`
116
+ (`NationalDocumentSummary`), `documentId`, `jurisdiction`, `attribution`; legislation hits always
117
+ carry `law_title`, `article_ref`, `section`, `language`, `in_force`, `valid_from`, `valid_to`,
118
+ `law_type` (each nullable).
119
+
120
+ ### Added
121
+
122
+ - **National law**: `getNationalCoverage()` (`GET /national/coverage`, public, free — which
123
+ jurisdictions are live, what each covers, sources and their attribution), `getNationalDocument()`
124
+ (`GET /{jurisdiction}/documents/{id}`, 1 credit), `listNationalDocuments()` /
125
+ `paginateNationalDocuments()` (`GET /{jurisdiction}/documents`, 3 credits flat per call — pagination
126
+ does not multiply the price; cursor paging past the first 1,000 rows, newest-first
127
+ by document date), `nationalSemanticSearch()`
128
+ (`POST /{jurisdiction}/search/semantic`, 5 credits — `hyde` accepted but never rewrites or
129
+ changes price here) and `nationalLegislationSemanticSearch()`
130
+ (`POST /{jurisdiction}/legislation/semantic`, 5 credits; no `hyde`/`asOf` — and never forwards a
131
+ bypassed `hyde` either, now that the server validates it strictly as a boolean on this route
132
+ too). New types:
133
+ `NationalCoverageResponse`, `NationalDocument`, `NationalDocumentSummary`,
134
+ `NationalDocumentResponse`, `NationalDocumentListParams`, `NationalDocumentListResponse`,
135
+ `NationalSemanticCaseLawOptions`/`Result`/`Response`, `NationalSemanticLegislationOptions`/
136
+ `Result`/`Response`, `NationalSource`, `NationalJurisdictionCoverage` and friends. Every
137
+ document/result carries `attribution` — always show it alongside the text.
138
+ - **`NationalAllowanceExhaustedError`** (`NATIONAL_ALLOWANCE_EXHAUSTED`, 402): FREE/STARTER/
139
+ PROFESSIONAL get national law within a monthly allowance of calls; BUSINESS and above have no
140
+ separate limit. Typed `jurisdiction`/`limit`/`remaining`/`resetsAt`/`upgradeUrl` getters.
141
+ - **`NationalSemanticNotEnabledError`** (409 `NATIONAL_SEMANTIC_NOT_ENABLED` — a jurisdiction has
142
+ no semantic index at all) and **`NationalSemanticUnavailableError`** (503
143
+ `NATIONAL_SEMANTIC_UNAVAILABLE` — temporarily unreachable; extends `ServiceUnavailableError`, so
144
+ `instanceof ServiceUnavailableError` still holds). Both legacy-shape bodies; `.jurisdiction` is
145
+ read off the raw `body`, not `details`.
146
+ - **`DocumentWithdrawnError`** (`DOCUMENT_WITHDRAWN`, 410): a national document
147
+ its source withdrew (a takedown, a pseudonymisation fix) is served nowhere — no title, no
148
+ metadata, no text. Thrown by `getNationalDocument` (typed envelope, `details: {id, jurisdiction,
149
+ withdrawnAt}`) and by the citation methods for a withdrawn national id (legacy shape, the same
150
+ three fields as top-level siblings instead). `.id`/`.jurisdiction`/`.withdrawnAt` read whichever
151
+ shape answered. Not retryable; nothing is ever charged for it.
152
+ - **`result.headers.nationalAllowance`** (`{ limit, remaining, resetsAt }`), parsed from
153
+ `X-National-Limit`/`X-National-Remaining`/`X-National-Reset` — present only for
154
+ FREE/STARTER/PROFESSIONAL callers on the four national document/semantic endpoints (also on the
155
+ 402 error itself, via `err.headers`).
156
+ - **`includeNational`** on all six citation-graph methods (`getCites`, `getCitedBy`,
157
+ `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats`): also
158
+ returns/follows national documents of live jurisdictions as neighbours — BUSINESS, SCALE and
159
+ ENTERPRISE only (`403 TierForbiddenError` below that). `celexNumber` and `getCitationPath`'s
160
+ `from`/`to` accept a national document id directly (e.g. `"AT-NOR-10001597"`); an id whose
161
+ jurisdiction is not live is a plain `404 NotFoundError`. `getCitationStats` gained an optional
162
+ `params` argument before `options`.
163
+ Back-compatible with 0.2.0's `getCitationStats(options?)`: a first argument shaped like
164
+ `CallOptions` (`timeoutMs`/`signal`, not `includeNational`) is still honoured as the per-call
165
+ options rather than silently read as `params` — this can't be caught at the type level for a
166
+ non-literal variable or a JS caller, so it's detected at runtime too. Every response type
167
+ carries an optional `includeNational` boolean, present once the flag was honoured.
168
+ - 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.
169
+ - `paginateNationalDocuments` strips `page` from its params at runtime (not just via the
170
+ `Omit<…, "page">` type, which only guards TypeScript callers) — passing both `page` and
171
+ `cursor` to the underlying `GET` is a 400 ("Use either cursor or page, not both").
172
+
173
+ National semantic responses (`nationalSemanticSearch`/`nationalLegislationSemanticSearch`) carry
174
+ the `credits` block, like every other credit-metered route.
175
+
8
176
  ## [0.2.0] — 2026-10-26
9
177
 
10
178
  Full re-sync with the LexAPI API (validated against lex-api `main` @ `633eb67`, PR #298, and
package/README.md CHANGED
@@ -36,10 +36,16 @@ 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
+ | 5 | `getTransposition` — every plan |
39
40
  | 15 | `semanticSearch({ hyde: true })` — refunded to 5 if HyDE falls back |
40
41
  | 20 | `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats` |
42
+ | 20 | `getCounterparts` — BUSINESS, SCALE and ENTERPRISE only |
43
+ | 0 | `getNationalCoverage` (public) |
44
+ | 1 | `getNationalDocument` — every national read is a corpus read, so the 5-credit reservation always settles to 1 (an unknown id too) |
45
+ | 3 per call | `listNationalDocuments` — flat; pagination does not multiply the price |
46
+ | 5 | `nationalSemanticSearch`, `nationalLegislationSemanticSearch` — `hyde` never raises this for national case law |
41
47
 
42
- 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.
48
+ 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.
43
49
 
44
50
  ## Search & documents
45
51
 
@@ -75,7 +81,8 @@ console.log(batch.textUnavailable, batch.headers?.batch); // source counts — t
75
81
  const recent = await client.getRecentDocuments({ days: 7, documentType: "regulation" }); // one type; use search() for several
76
82
  const meta = await client.getDocumentMetadata({ celexNumber: "32016R0679" });
77
83
  const byUrl = await client.getDocumentByUrl({ url: "https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679" });
78
- const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311", resolvedVia: "ecli-corpus" }
84
+ const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311", resolvedVia: "ecli-corpus", verified: true }
85
+ // ELIs resolve via "eli-corpus" or "eli-cellar"; resolvedVia "eli" + verified: false = unconfirmed pattern guess, resolve again later
79
86
  ```
80
87
 
81
88
  ### Text availability and languages
@@ -165,9 +172,152 @@ if (!path.found) console.log(path.message); // graceful 200, not an er
165
172
 
166
173
  const related = await client.getRelatedDocuments("32016R0679", { limit: 10 }); // bibliographic coupling
167
174
  const stats = await client.getCitationStats();
175
+
176
+ // National documents in the graph (BUSINESS, SCALE, ENTERPRISE only — 403 TierForbiddenError below that):
177
+ const withNational = await client.getCitedBy("32016R0679", { includeNational: true });
178
+ console.log(withNational.includeNational); // present once honoured; absent while no jurisdiction is live
179
+ const nationalEdges = await client.getCites("AT-NOR-10001597"); // a national id works directly, no flag needed
180
+ ```
181
+
182
+ `citationType` is one of `reference`, `amendment`, `repeal`, `corrigendum`, `implementation`, `legal-basis`, `proposal`, `transposition` (`CITATION_TYPES`). All graph reads accept `language` for neighbour titles, and `includeNational` (`getCites`, `getCitedBy`, `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats`) to also return/follow national documents of live jurisdictions — BUSINESS, SCALE and ENTERPRISE only. `celexNumber` (and `getCitationPath`'s `from`/`to`) accept a national document id (e.g. `"AT-NOR-10001597"`) directly, with or without the flag; such an id whose jurisdiction isn't live is a plain `NotFoundError`.
183
+
184
+ ### Provenance, filters and node identity
185
+
186
+ Every edge says where it comes from (`provenance`: `notice`, `cellar`, `notice+cellar`,
187
+ `cellar-nim`, `source`, `resolver`) and how its target was identified (`resolution`: `id`, `key`,
188
+ `abbreviation`, `text-pattern`; `null` on EUR-Lex / Cellar edges) — on `citations[]` of
189
+ `getCites` / `getCitedBy` and on `edgeDetails[]` of network neighbours. Every node carries `id`,
190
+ `jurisdiction` (`EU`, `AT`, …) and `documentKind` (`act` | `decision` | `null`) next to
191
+ `celexNumber`.
192
+
193
+ ```ts
194
+ const edges = await client.getCitedBy("32016L0680", {
195
+ citationType: ["transposition", "implementation"], // one value or a list (sent comma-separated)
196
+ provenance: ["source", "cellar-nim"],
197
+ jurisdictions: ["eu", "at", "de"], // a national code implies includeNational (BUSINESS+)
198
+ resolution: ["id", "key"], // leave out abbreviation matches
199
+ });
200
+ for (const g of edges.citedBy) console.log(g.jurisdiction, g.id, g.citations?.map((c) => c.provenance));
201
+ console.log(edges.totalEdges, edges.countsSource); // page until offset + limit >= totalEdges
202
+
203
+ const refs = await client.getCites("DE-JUD-BFH-KBRE202550123", { unresolved: true }); // national id: references with no edge
204
+ for (const r of refs.unresolved ?? []) console.log(r.kind, r.text, r.status, r.targetId);
205
+ ```
206
+
207
+ `getCitationNetwork`, `getCitationPath` and `getRelatedDocuments` take the same four filters;
208
+ `getCitationNetwork` also takes `unresolved`. An unknown value is an `InvalidParamsError` with
209
+ `err.param` and `err.allowed`, refunded. `countsSource` (`stats` | `counted`, and
210
+ `paging.countsSource` on the network) says where the totals were read from; both are exact.
211
+ With `includeNational: true`, `getCitationStats` adds `byJurisdiction`, `byProvenance` and
212
+ `transposition`.
213
+
214
+ ### Notified measures and counterparts
215
+
216
+ ```ts
217
+ const t = await client.getTransposition("32016L0680", { jurisdictions: ["es", "cz"] }); // 5 credits, every plan
218
+ console.log(t.note); // a notification is not a finding that the measure transposes the act
219
+ for (const c of t.jurisdictions) {
220
+ for (const m of c.measures) console.log(c.jurisdiction, m.title, m.officialJournal.date, m.id ?? "(not held)");
221
+ }
222
+ console.log(t.source.cellar?.attribution); // keep with anything you republish
223
+
224
+ const cp = await client.getCounterparts("AT-NOR-10001597"); // 20 credits, BUSINESS+
225
+ for (const v of cp.via) {
226
+ for (const c of v.counterparts) console.log(v.euAct.id, c.rank, c.jurisdiction, c.id ?? c.title);
227
+ }
228
+ ```
229
+
230
+ `getTransposition` lists the measures the member states notified to the Commission for an EU act
231
+ (CELEX sector 3), from the Publications Office's Cellar records. On BUSINESS, SCALE and ENTERPRISE,
232
+ for live jurisdictions, it also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
233
+ `counts.resolved`, `source.lanes`) and adds the documents whose national source records that they
234
+ transpose or implement the act; `resolvedOnly: true` keeps only those. Otherwise those fields are
235
+ `null` (and `termsRequired: true` while the national-source terms are not accepted). A CELEX that
236
+ is not an EU act is a `NotFoundError`.
237
+
238
+ `getCounterparts` returns a national document's counterparts in the other live jurisdictions,
239
+ through the EU acts it transposes or implements, ranked `1` (the national source records it), `2`
240
+ (a notified measure LexAPI holds) or `3` (a notified measure LexAPI does not hold, `id: null`). A
241
+ lookup past the server's budget throws `TimeoutError` (503, `err.partial`), refunded. The SDK does
242
+ not retry it; retry yourself, or narrow with `jurisdictions`.
243
+
244
+ ## National law
245
+
246
+ Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS, SCALE and ENTERPRISE get full
247
+ access; FREE, STARTER and PROFESSIONAL get it within a monthly allowance of national calls. A
248
+ jurisdiction that isn't launched yet answers 404, exactly like a path that doesn't exist — check
249
+ `getNationalCoverage()` first.
250
+
251
+ ```ts
252
+ const coverage = await client.getNationalCoverage(); // public, free — no allowance consumed
253
+ for (const j of coverage.jurisdictions) {
254
+ if (j.live) console.log(j.code, j.name, j.legislation.documents, j.sources.map((s) => s.attribution));
255
+ }
256
+
257
+ const { document } = await client.getNationalDocument("AT", "AT-NOR-10001597"); // 1 credit
258
+ console.log(document.attribution); // always show this alongside the text
259
+ for (const a of document.content?.articles ?? []) console.log(a.number, a.title, a.text ?? "(no text)");
260
+
261
+ const page = await client.listNationalDocuments("AT", { q: "Datenschutz", limit: 20 }); // 3 credits flat
262
+ for await (const p of client.paginateNationalDocuments("AT", { q: "Datenschutz", limit: 100 })) {
263
+ console.log(p.results.length, p.hasMore); // cursor paging — reaches past the first 1,000 rows, `page` doesn't
264
+ }
265
+
266
+ const hits = await client.nationalSemanticSearch("AT", { query: "Datenschutz bei Bankgeschäften" }); // 5 credits
267
+ for (const h of hits.results) console.log(h.document.documentKind, h.document.ecli, h.document.dateOfDocument);
268
+ const articles = await client.nationalLegislationSemanticSearch("DE", { query: "Kündigungsfrist" }); // 5 credits
269
+ if (articles.partial) console.warn(articles.hint); // SEARCH_INCOMPLETE: results may be missing better matches
168
270
  ```
169
271
 
170
- `citationType` is one of `reference`, `amendment`, `repeal`, `corrigendum`, `implementation`, `legal-basis`, `proposal`. All graph reads accept `language` for neighbour titles.
272
+ **Incomplete national searches.** When the national index could not complete a semantic search,
273
+ results may be incomplete: with hits left the answer carries `partial: true`,
274
+ `partialReason: "SEARCH_INCOMPLETE"` and a `hint` (retry, or rephrase / change the filters). With
275
+ nothing left to return it throws instead — `NationalSemanticUnavailableError` (503,
276
+ `partialReason: "SEARCH_INCOMPLETE"`, `retryAfter` when a retry may help — retried at most once per call, and only with `retryReadOnlyPosts`) or
277
+ `NationalSemanticFilterUnreachableError` (422, not retryable as is). Both are refunded; an empty
278
+ answer would not have meant "no matches".
279
+
280
+ **One shape for every country (requires LexAPI API 2.8.0).** National documents have the same
281
+ fields, types and formats in every jurisdiction, so code written for one country works for all of
282
+ them. Every field is always present — one the source does not provide is `null` (or `[]`), never
283
+ missing:
284
+
285
+ - `documentKind` (`"act"` | `"decision"`) tells legislation from case law everywhere; `documentType`
286
+ is the source's own label, in its language.
287
+ - `decision` — on a decision, `{ court, chamber, caseNumbers, citedNorms: [{ text, documentId }] }`,
288
+ read server-side from whichever fields the source uses (also when the decision has no text);
289
+ `null` for acts. `isNationalDecision(document)` narrows it.
290
+ - `content` (or `null` when there is no text — see `textAvailability`) is always
291
+ `{ fullText, articles, textLanguages, textLanguage, embeddedForeignText, textSource, ocr, repeal, source, details }`;
292
+ every article is `{ number, title, section, text, inForceFrom, inForceTo, details }` (`text: null`
293
+ when the source publishes no text for that unit). What a source adds beyond these fields is under
294
+ `content.details` / `articles[].details` — source-specific, keys differ by country.
295
+ - Semantic hits carry `document` (the listing's summary of the matched document); legislation hits
296
+ always carry `law_title`, `article_ref`, `section`, `language`, `in_force`, `valid_from`,
297
+ `valid_to` and `law_type`, `null` when the index has nothing.
298
+
299
+ ```ts
300
+ import { isNationalDecision } from "@lexapi/client";
301
+
302
+ const { document: d } = await client.getNationalDocument("DE", "DE-JUD-BFH-KBRE202550123");
303
+ if (isNationalDecision(d)) {
304
+ console.log(d.decision.court, d.decision.caseNumbers.join(", ")); // "BFH 3. Senat" "III R 27/24"
305
+ for (const n of d.decision.citedNorms) console.log(n.text, n.documentId ?? "(not identified)");
306
+ }
307
+ ```
308
+
309
+ A document its source withdrew (a takedown, a pseudonymisation fix) throws `DocumentWithdrawnError` (410) from `getNationalDocument` and from the citation methods for a withdrawn national id — nothing of it is served, not even the title; drop any copy you hold.
310
+
311
+ `getNationalCoverage()` also reports each live jurisdiction's `citationGraph`: its extraction
312
+ `methods` (with `unmeasured` rates and their reason codes), `edges`, the measured rates
313
+ (`decisionResolutionRate`, `actEuRate`, `textPatternRate`, `nimResolvedRate`), `transposition`,
314
+ `precision` and `floors` — `null` wherever nothing was measured. National `content` also carries
315
+ `textSource` (`html` | `pdf-text` | `ocr` | `null`) and `ocr` (engine and confidence when the text
316
+ was machine-read — never the official text).
317
+
318
+ A used-up allowance is `NationalAllowanceExhaustedError` (402); its headroom is also on
319
+ `result.headers.nationalAllowance` (`{ limit, remaining, resetsAt }`) on every admitted call from a
320
+ plan below BUSINESS.
171
321
 
172
322
  ## Webhooks
173
323
 
@@ -224,7 +374,7 @@ app.post("/webhooks/lexapi", express.raw({ type: "application/json" }), async (r
224
374
 
225
375
  **Filters:** `documentType` matches the stored label exactly, ignoring case; `documentTypeCode: "regulation"` selects the family (incl. implementing and delegated regulations); `author` matches whole values; `dateFrom` / `dateTo` are `YYYY-MM-DD`; `changedSince` returns rows whose text changed (the cheapest incremental sync) and `fetchedSince` rows written to at all — both an ISO date or a date-time with a timezone, or a `Date`; `limit` is a positive integer (anything else throws `RangeError`).
226
376
 
227
- Licensing: exported content may not be used to train or evaluate ML models without a separate licence ([Terms §6](https://lex-api.com/terms?ref=npm-sdk#acceptable-use)).
377
+ Licensing: exported content may not be used to train or evaluate ML models without a separate licence ([Terms §6](https://lex-api.com/terms?ref=npm-sdk#acceptable-use)). For training data, [Arieta Data](https://data.arietalabs.com/?ref=npm-sdk), a sister product from Arieta Labs, licenses datasets drawn from the same corpus for training, retrieval and evaluation.
228
378
 
229
379
  ```ts
230
380
  const stream = await client.export({ documentTypeCode: "regulation", dateFrom: "2024-01-01", limit: 10_000 });
@@ -273,6 +423,8 @@ r.headers?.corpusVersion; // X-Corpus-Version
273
423
 
274
424
  Also: `searchSource`, `searchCache`, `warning`, `ignoredDocumentTypes`, `postFilteredBy`, `documentTypeFanOut`, `batch`. The older `xWarning` (and `corpusVersion` on version responses) are still set.
275
425
 
426
+ On the four national document/semantic endpoints, `headers.nationalAllowance` (`{ limit, remaining, resetsAt }`, from `X-National-Limit`/`X-National-Remaining`/`X-National-Reset`) reports the monthly national-call allowance left — present only for FREE/STARTER/PROFESSIONAL callers (absent for BUSINESS and above, and for `getNationalCoverage`).
427
+
276
428
  ## Configuration
277
429
 
278
430
  ```ts
@@ -302,7 +454,7 @@ The SDK retries automatically **only when a retry cannot charge you twice** (the
302
454
 
303
455
  - **Read-only POSTs** are `search`, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl`, `getDocumentMetadata`, `resolve`, `semanticSearch`, `semanticLegislationSearch`. **Mutating calls** are the webhook writes and `extractCitations` (it persists edges).
304
456
  - **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.
305
- - **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. `X-RateLimit-*` is not read. Every hint is clamped to the 30 s cap; numbers above 1e12 / 1e9 are read as epoch ms / s. A quota 429 has `retryAfter: undefined`.
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`.
306
458
 
307
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.
308
460
 
@@ -336,15 +488,20 @@ try {
336
488
  | Class | `code` | HTTP |
337
489
  | --- | --- | --- |
338
490
  | `NotFoundError` | `NOT_FOUND` | 404 |
339
- | `InvalidCelexError` / `InvalidUrlError` / `InvalidParamsError` | `INVALID_CELEX` / `INVALID_URL` / `INVALID_PARAMS` | 400 |
491
+ | `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
+ | `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 |
340
493
  | `AuthenticationError` | `UNAUTHORIZED` (derived) | 401 |
341
494
  | `CreditsExhaustedError` | `CREDITS_EXHAUSTED` | 402 |
495
+ | `NationalAllowanceExhaustedError` | `NATIONAL_ALLOWANCE_EXHAUSTED` | 402 — FREE/STARTER/PROFESSIONAL's monthly national-law call allowance is used up; `resetsAt`/`limit`/`upgradeUrl` |
496
+ | `NationalSemanticNotEnabledError` | `NATIONAL_SEMANTIC_NOT_ENABLED` | 409 — this jurisdiction has no semantic index to search; `.jurisdiction`; not retryable, refunded |
342
497
  | `TierForbiddenError` | `TIER_FORBIDDEN` | 403 |
343
498
  | `RateLimitedError` | `RATE_LIMITED`, `QUOTA_EXHAUSTED` | 429 — `QUOTA_EXHAUSTED` (legacy plans' used-up quota) is never retried; `resetsAt` says when it refills |
344
499
  | `InternalServerError` | `INTERNAL` | 500 |
345
500
  | `UpstreamError` | `UPSTREAM_ERROR` | 502; Cloudflare 520–523 |
346
501
  | `ServiceUnavailableError` | `SERVICE_UNAVAILABLE` (derived) | 503 |
347
- | `TimeoutError` | `TIMEOUT` (504, 524) / `REQUEST_TIMEOUT` (status 0, the SDK's own timeout) | |
502
+ | `NationalSemanticUnavailableError` (extends `ServiceUnavailableError`) | `NATIONAL_SEMANTIC_UNAVAILABLE` | 503 — a jurisdiction's semantic index is temporarily unreachable, or could not complete this search with nothing left to return (`.partialReason === "SEARCH_INCOMPLETE"`, `retryAfter` — absent once the same search has repeatedly come back incomplete, and then not retried); `.jurisdiction`; retry later |
503
+ | `NationalSemanticFilterUnreachableError` (extends `InvalidParamsError`) | `NATIONAL_SEMANTIC_FILTER_UNREACHABLE` | 422 — the national index cannot search this slice (jurisdiction, document kind, filters) completely and there is nothing left to return; a coverage limit, not a malformed request (the request may be valid; `.param` is absent); `.jurisdiction`, `.partialReason`; not retryable as is — rephrase the query or change the filters; refunded |
504
+ | `TimeoutError` | `TIMEOUT` (504, 524; 503 from `getCounterparts`, with `.partial` / `.serverTimeoutMs`) / `REQUEST_TIMEOUT` (status 0, the SDK's own timeout) | |
348
505
  | `NetworkError` | `CONNECTION_ERROR` | 0 (transport failure, or the connection dropped — incl. mid-export) |
349
506
  | `RequestAbortedError` | `ABORTED` | 0 (your `signal` fired) |
350
507
  | `InvalidResponseError` | `INVALID_RESPONSE` | a 2xx whose body was not JSON (e.g. a proxy HTML page) |