@lexapi/client 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # @lexapi/client (TypeScript)
2
2
 
3
- Official TypeScript SDK for [LexAPI](https://lex-api.com) — European legal data, made queryable. EUR-Lex, CJEU case law, and the Official Journal behind one REST API.
3
+ Official TypeScript SDK for [LexAPI](https://lex-api.com/?ref=npm-sdk) — European legal data, made queryable. EUR-Lex legislation, CJEU case law and the Official Journal behind one REST API, parsed to article level.
4
4
 
5
- > **Status: pre-release (0.x).** Not yet published to npm. See [PLAN.md](PLAN.md) for the endpoint coverage matrix.
5
+ [![npm](https://img.shields.io/npm/v/@lexapi/client)](https://www.npmjs.com/package/@lexapi/client) · [API docs](https://lex-api.com/docs?ref=npm-sdk) · [Changelog](CHANGELOG.md)
6
6
 
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- npm install @lexapi/client # not yet published
10
+ npm install @lexapi/client
11
11
  ```
12
12
 
13
- Requires Node ≥ 18 (native `fetch`); also works on Deno, Bun, and edge runtimes. **Server-side use 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
+ 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
 
@@ -18,11 +18,28 @@ Requires Node ≥ 18 (native `fetch`); also works on Deno, Bun, and edge runtime
18
18
  import { LexAPI } from "@lexapi/client";
19
19
 
20
20
  const client = new LexAPI({ apiKey: "lex_..." }); // or set LEXAPI_API_KEY
21
- const info = await client.getInfo();
22
- console.log(info.subscription, info.usage);
21
+ const info = await client.getInfo(); // free (0 credits)
22
+ console.log(info.subscription?.tier, info.credits?.remaining);
23
23
  ```
24
24
 
25
- Keys come from the [LexAPI dashboard](https://lex-api.com) and are prefixed `lex_`.
25
+ Keys come from the [LexAPI dashboard](https://lex-api.com/dashboard?ref=npm-sdk) and are prefixed `lex_`.
26
+
27
+ ## What each call costs
28
+
29
+ LexAPI bills a monthly credit pool ([plans](https://lex-api.com/pricing?ref=npm-sdk)). The SDK method docs repeat these:
30
+
31
+ | Credits | Calls |
32
+ | --- | --- |
33
+ | 0 | `getInfo`; webhook management and deliveries |
34
+ | 1 | `resolve`, `getCites`, `getCitedBy`, the version endpoints |
35
+ | 3 per page | `search` (`maxPages`), `getRecentDocuments` (~10 results per page) — unfetched pages refunded |
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
+ | 5 → 1 | `extractCitations` — refunded to 1 when the document was `alreadyExtracted` |
38
+ | 5 | `semanticSearch`, `semanticLegislationSearch` (+ per live `asOf` fetch, see below) |
39
+ | 15 | `semanticSearch({ hyde: true })` — refunded to 5 if HyDE falls back |
40
+ | 20 | `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats` |
41
+
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.
26
43
 
27
44
  ## Search & documents
28
45
 
@@ -35,150 +52,308 @@ const hits = await client.search({
35
52
  maxPages: 2,
36
53
  });
37
54
  if (hits.truncated) console.warn(hits.truncatedReason); // tier-capped pagination
38
- if (hits.partial) console.warn(hits.partialReason); // an upstream page timed out
39
- if (hits.xWarning) console.warn(hits.xWarning); // X-Warning header (e.g. maxPages clamped)
55
+ if (hits.partial) console.warn(hits.partialReason); // a page timed out — or source: "corpus"
56
+ if (hits.hint) console.log(hits.hint); // zero results → try semantic search
57
+ console.log(hits.headers?.searchSource, hits.headers?.searchCache); // "soap" | "cellar" | "corpus", "hit" | "miss" | "bypass"
58
+ await client.search({ query: "*", year: 2024, subdomain: "EU_CASE_LAW", fresh: true }); // filter-only, skip the 1 h cache
40
59
 
41
- // Single document (POST /documentContent) with payload control
42
- const { document } = await client.getDocument({
60
+ // Single document (POST /documentContent)
61
+ const { document, headers } = await client.getDocument({
43
62
  celexNumber: "32016R0679",
44
63
  include: ["metadata", "articles"],
45
64
  articleId: "17",
46
65
  });
66
+ console.log(headers?.source); // "corpus" (1 credit) | "cellar" | "cellar-oj" (4) | "live" (5)
47
67
 
48
68
  // Batch (POST /documentContent/batch) — per-CELEX errors don't abort the batch
49
69
  const batch = await client.getDocumentsBatch({ celexNumbers: ["32016R0679", "62018CJ0311"] });
50
70
  if (batch.trimmed) console.warn(`clamped to ${batch.trimmedTo}: ${batch.trimmedReason}`);
51
- batch.errors.forEach((e) => console.warn(`${e.celexNumber}: ${e.error}`));
71
+ batch.errors.forEach((e) => console.warn(`${e.celex}: ${e.error}`)); // { celex, error: <message> }
72
+ console.log(batch.textUnavailable, batch.headers?.batch); // source counts — they overlap; see BatchSourceCounts
52
73
 
53
74
  // Recent documents, metadata-only reads, URL + identifier resolution
54
- const recent = await client.getRecentDocuments({ days: 7, documentType: "judgment" });
75
+ const recent = await client.getRecentDocuments({ days: 7, documentType: "regulation" }); // one type; use search() for several
55
76
  const meta = await client.getDocumentMetadata({ celexNumber: "32016R0679" });
56
77
  const byUrl = await client.getDocumentByUrl({ url: "https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679" });
57
- const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311", ... }
78
+ const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311", resolvedVia: "ecli-corpus" }
58
79
  ```
59
80
 
60
- Truncation/partial signals are always surfaced on the result (`truncated`, `partial`, `postFilteredBy`, `trimmed`/`trimmedTo`, and `xWarning` from the `X-Warning` header) — never swallowed.
81
+ ### Text availability and languages
61
82
 
62
- ## Citations
83
+ A document can exist while EUR-Lex publishes no text for it. That is a `200` with metadata, `content: null` and a `textAvailability` verdict — billed 1 credit, not 5. **Check it before reading `content`:**
63
84
 
64
85
  ```ts
65
- await client.extractCitations("32016R0679"); // crawl + persist (idempotent)
66
- const outbound = await client.getCites("32016R0679", { citationType: "repeal" });
67
- const inbound = await client.getCitedBy("32016R0679", { limit: 50 });
68
-
69
- const network = await client.getCitationNetwork("62018CJ0311", { limit: 100 });
70
- if (network.partial) console.warn(network.message); // server budget expired — network is EMPTY, not zero
86
+ const { document } = await client.getDocument({ celexNumber: "32008R1272", language: "de" });
87
+ const ta = document.textAvailability;
88
+ if (ta && !ta.available) {
89
+ console.log(ta.reason); // not_in_language | not_published_yet | no_machine_readable_rendition | too_large | unknown
90
+ console.log(ta.availableLanguages); // null = unknown, [] = known to be none
91
+ console.log(ta.latestConsolidated?.celex); // base acts: the consolidated version to fetch instead
92
+ }
93
+ ```
71
94
 
72
- const path = await client.getCitationPath("32016R0679", "31995L0046", { maxDepth: 5 });
73
- if (!path.found) console.log(path.message); // graceful 200, not an error
95
+ `language` localizes the whole document and falls back to English (`languageRequested` / `languageFallback`). Pass `acceptLanguages: ["fr", "de"]` (or `"any"`) to get the authentic text in one call when the requested language has none. `titleLanguage` is present only when the title is not in the language you asked for.
74
96
 
75
- const related = await client.getRelatedDocuments("32016R0679"); // bibliographic coupling
76
- const stats = await client.getCitationStats();
77
- ```
97
+ Truncation/partial signals are always surfaced on the result (`truncated`, `partial`, `postFilteredBy`, `trimmed`/`trimmedTo`, `xWarning`) — never swallowed.
78
98
 
79
99
  ## Semantic search
80
100
 
81
101
  ```ts
82
102
  // Case law (POST /search/semantic) — 5 credits
83
- const hits = await client.semanticSearch({
103
+ const cases = await client.semanticSearch({
84
104
  query: "transfer of personal data to third countries",
85
105
  limit: 10,
86
106
  minScore: 0.5, // unset applies the upstream's ~0.7 relevance floor
87
- includeText: true, // full document text per hit instead of ~600-char snippets
107
+ includeText: true, // full text per hit instead of the default ~600-char `snippet`
88
108
  });
89
- if (hits.hint) console.warn(hits.hint); // present only on low-confidence result sets
109
+ if (cases.hint) console.warn(cases.hint); // present only on low-confidence result sets
90
110
 
91
- // HyDE query rewriting — 15 credits instead of 5, ~1-3s extra latency.
92
- // Best-effort: on LLM failure it falls back to plain retrieval, the response
93
- // reports hyde: false, and the 10-credit premium is refunded automatically.
111
+ // HyDE query rewriting — 15 credits instead of 5, ~1-3 s extra latency.
112
+ // Best-effort: on LLM failure the response reports hyde: false and the premium is refunded.
94
113
  const hyde = await client.semanticSearch({ query: "credit scoring article 22", hyde: true });
95
- console.log(hyde.hyde, hyde.hypotheticalDocument, hyde.credits?.operation_weight);
114
+ console.log(hyde.hyde, hyde.hypotheticalDocument);
96
115
 
97
- // Legislation (POST /legislation/semantic) — article-level matches; no hyde option
116
+ // Legislation (POST /legislation/semantic) — article-level matches, limit ≤ 50
98
117
  const articles = await client.semanticLegislationSearch({ query: "right to be forgotten" });
99
- console.log(articles.results[0]?.article_ref, articles.results[0]?.law_id);
118
+ for (const hit of articles.results) {
119
+ console.log(hit.law_id, hit.article_ref, hit.score, hit.snippet);
120
+ if (hit.consolidated) {
121
+ // One hit per article: the consolidated text, labelled. Consolidated texts are not
122
+ // authentic — cite hit.baseCelex (the Official Journal act); hit.baseAct is its own match.
123
+ console.log(hit.consolidatedAsOf, hit.baseCelex, hit.consolidatedNote, hit.baseAct?.score);
124
+ }
125
+ }
100
126
  ```
101
127
 
102
128
  Persistent identity for case-law hits is `(metadata.celex_id, metadata.document_type)` — `case_id` is snapshot-scoped and does not survive index rebuilds.
103
129
 
130
+ ### The text in force on a date (`asOf`)
131
+
132
+ ```ts
133
+ const asOf = await client.semanticLegislationSearch({ query: "own funds requirements", asOf: "2019-06-01" });
134
+
135
+ console.log(asOf.asOfSummary); // { liveFetches, unresolved }
136
+ for (const hit of asOf.results) {
137
+ if (hit.asOfResolved) {
138
+ console.log(hit.asOfVersion); // { celex, date, kind: "consolidated" | "as_published" }
139
+ console.log(hit.matchedVersion); // when the text was swapped: what the index actually matched
140
+ } else {
141
+ console.log(hit.asOfReason); // e.g. "not_yet_in_force", "fetch_timeout" — the hit keeps its latest text
142
+ }
143
+ }
144
+ ```
145
+
146
+ 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.
147
+
148
+ ## Citations
149
+
150
+ ```ts
151
+ await client.extractCitations("32016R0679"); // crawl + persist (idempotent)
152
+ const outbound = await client.getCites("32016R0679", { citationType: "repeal" });
153
+ const inbound = await client.getCitedBy("32008R1272", { citationType: "corrigendum" });
154
+ console.log(inbound.relationSync?.status); // fresh | refreshed | pending | …
155
+
156
+ for await (const page of client.paginateCitedBy("32016R0679", { limit: 200 })) {
157
+ page.citedBy.forEach((g) => console.log(g.celexNumber, g.titleSource)); // 1 credit per page
158
+ }
159
+
160
+ const network = await client.getCitationNetwork("62018CJ0311", { limit: 100 });
161
+ if (network.partial) console.warn(network.message); // server budget expired — network is EMPTY, not zero
162
+
163
+ const path = await client.getCitationPath("32016R0679", "31995L0046", { maxDepth: 5 });
164
+ if (!path.found) console.log(path.message); // graceful 200, not an error
165
+
166
+ const related = await client.getRelatedDocuments("32016R0679", { limit: 10 }); // bibliographic coupling
167
+ const stats = await client.getCitationStats();
168
+ ```
169
+
170
+ `citationType` is one of `reference`, `amendment`, `repeal`, `corrigendum`, `implementation`, `legal-basis`, `proposal`. All graph reads accept `language` for neighbour titles.
171
+
104
172
  ## Webhooks
105
173
 
106
174
  ```ts
107
175
  const created = await client.webhooks.create({
108
- name: "New CJEU judgments",
176
+ name: "Chemicals compliance watch",
109
177
  url: "https://example.com/webhooks/lexapi",
110
- searchCriteria: { documentType: "judgment", author: ["court-of-justice"] },
178
+ searchCriteria: { documentType: "regulation", query: "chemical*" }, // documents.new (titles)
179
+ watchCelex: ["32006R1907", "32008R1272"], // watchlist.changes
111
180
  });
112
181
  console.log(created.webhook.secret); // returned ONLY here — store it (HMAC-SHA256 signing key)
113
182
 
114
- const { webhooks } = await client.webhooks.list();
115
- const detail = await client.webhooks.get(created.webhook.id); // includes recentDeliveries
116
- await client.webhooks.update(created.webhook.id, { status: "ACTIVE" }); // resets consecutiveFailures
117
- await client.webhooks.test(created.webhook.id); // synchronous signed test delivery
118
- const history = await client.webhooks.deliveries(created.webhook.id, { limit: 50 });
119
- await client.webhooks.delete(created.webhook.id); // 204 → resolves void
183
+ const { webhooks } = await client.webhooks.list(); // criteriaErrors, watchCelex, deliveryCount
184
+ const detail = await client.webhooks.get(created.webhook.id); // retryPolicy, recentDeliveries
185
+ const resumed = await client.webhooks.update(created.webhook.id, { status: "ACTIVE" });
186
+ console.log(resumed.requeuedDeliveries);
187
+ await client.webhooks.update(created.webhook.id, { searchCriteria: null }); // keep only the watch list
188
+ await client.webhooks.test(created.webhook.id); // synchronous signed test delivery
189
+ for await (const page of client.webhooks.paginateDeliveries(created.webhook.id)) console.log(page.deliveries.length);
190
+ await client.webhooks.delete(created.webhook.id);
120
191
  ```
121
192
 
122
- ## Corpus export (BUSINESS tier)
193
+ 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.
123
194
 
124
- `export()` streams NDJSON rows via the fetch body stream — constant memory regardless of result size:
195
+ ### Receiving deliveries
125
196
 
126
197
  ```ts
127
- const stream = await client.export({ documentType: "regulation", dateFrom: "2024-01-01", limit: 10_000 });
198
+ import { verifyWebhook } from "@lexapi/client";
199
+
200
+ // Express: keep the RAW body — the signature is over the exact bytes sent.
201
+ app.post("/webhooks/lexapi", express.raw({ type: "application/json" }), async (req, res) => {
202
+ try {
203
+ const event = await verifyWebhook(req.body, req.get("x-webhook-signature"), process.env.LEXAPI_WEBHOOK_SECRET!);
204
+ // Verified signature + 5-minute replay window. Dedupe on event.delivery?.id (stable across retries).
205
+ if (event.event === "watchlist.changes") {
206
+ for (const c of event.data.changes) console.log(c.watchedCelex, c.relation, c.document.celex);
207
+ } else if (event.event === "documents.new") {
208
+ console.log(event.data.count, event.data.totalAvailable);
209
+ }
210
+ res.sendStatus(200); // respond within 10 s
211
+ } catch {
212
+ res.sendStatus(401);
213
+ }
214
+ });
215
+ ```
216
+
217
+ `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).
218
+
219
+ ## Corpus export (BUSINESS, SCALE, ENTERPRISE)
128
220
 
129
- console.log(stream.meta); // leading _meta envelope (parsed before iteration)
130
- console.log(stream.headers.total); // X-Export-Total header
221
+ `export()` streams NDJSON rows via the fetch body stream — constant memory regardless of result size. BUSINESS, SCALE and ENTERPRISE only; lower tiers get a 403 `TierForbiddenError`.
222
+
223
+ **Billing (credit plans, API 2.3.0):** 1 credit per row written, at least 1 per export. The call is admitted for 1 credit, the matching rows are counted, and the rest of 1 credit per row it can return is reserved; a pool that cannot cover it throws `CreditsExhaustedError` before anything streams. Unwritten rows are refunded when the stream ends: `stream.done?.credits?.charged`.
224
+
225
+ **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
+
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)).
228
+
229
+ ```ts
230
+ const stream = await client.export({ documentTypeCode: "regulation", dateFrom: "2024-01-01", limit: 10_000 });
231
+
232
+ console.log(stream.meta?.totalMatching, stream.headers.total); // leading _meta envelope / X-Export-Total
131
233
 
132
234
  for await (const row of stream) {
133
235
  process(row.celex, row.documentTypeCode, row.parsedContent);
134
236
  }
135
237
 
136
- console.log(stream.done); // trailing _done line (available after iteration)
137
- if (stream.done?.truncated) console.warn("row cap hit — narrow filters or resume via fetchedSince");
238
+ console.log(stream.done?.written, stream.done?.skippedStubs);
239
+ if (stream.truncated) console.warn(`rows not reached (${stream.done?.truncatedBy}) — narrow filters or resume via changedSince`);
240
+ ```
241
+
242
+ 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`.
243
+
244
+ ## Point-in-time versions
245
+
246
+ 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 })`.)
247
+
248
+ ```ts
249
+ const history = await client.listDocumentVersions("32016R0679");
250
+ console.log(history.currentVersion, history.trackedSince);
251
+
252
+ const snapshot = await client.getDocumentVersion("32016R0679", 2);
253
+ console.log(snapshot.document.parsedContent, snapshot.corpusVersion);
254
+
255
+ const atDate = await client.getDocumentAtDate("32016R0679", "2026-03-20");
256
+ console.log(atDate.asOf, atDate.document.version);
257
+ ```
258
+
259
+ Each call costs 1 credit. Dates before the document entered the corpus reject with `NotFoundError` carrying the tracking start date.
260
+
261
+ ## Response headers
262
+
263
+ Every JSON result carries `headers` — the LexAPI response headers, parsed:
264
+
265
+ ```ts
266
+ const r = await client.getDocument({ celexNumber: "32016R0679" });
267
+ r.headers?.source; // X-Source: corpus | cellar | cellar-oj | live
268
+ r.headers?.rateLimit; // { limit, remaining, reset (seconds), policy }
269
+ r.headers?.languageFallback; // X-Language-Fallback
270
+ r.headers?.textAvailable; // X-Text-Available
271
+ r.headers?.corpusVersion; // X-Corpus-Version
138
272
  ```
139
273
 
140
- The `_meta`/`_done` envelope lines are never yielded as rows; the stream is single-pass.
274
+ Also: `searchSource`, `searchCache`, `warning`, `ignoredDocumentTypes`, `postFilteredBy`, `documentTypeFanOut`, `batch`. The older `xWarning` (and `corpusVersion` on version responses) are still set.
141
275
 
142
276
  ## Configuration
143
277
 
144
278
  ```ts
145
279
  const client = new LexAPI({
146
- apiKey: "lex_...", // or LEXAPI_API_KEY env var
280
+ apiKey: "lex_...", // or LEXAPI_API_KEY env var
147
281
  baseUrl: "https://lex-api.com/api/v1", // default
148
- timeoutMs: 60_000, // per attempt; per-call override: client.getInfo({ timeoutMs: 5_000 })
149
- retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000 },
150
- fetch: myFetch, // injectable transport (testing / polyfills)
151
- userAgentSuffix: "my-app/1.0", // appended to `lexapi-typescript/<version>`
282
+ timeoutMs: 95_000, // per attempt, incl. the body; per-call: client.getInfo({ timeoutMs: 5_000 })
283
+ retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000, retryReadOnlyPosts: false },
284
+ fetch: myFetch, // injectable transport (testing / polyfills)
285
+ userAgentSuffix: "my-app/1.0", // appended to `lexapi-typescript/<version>`
152
286
  });
153
287
  ```
154
288
 
155
- ## Retries
289
+ ## Retries, timeouts and cancellation
290
+
291
+ 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):
292
+
293
+ | Failure | GET, billed | GET, free (`getInfo`, webhook reads) | Read-only POST | Mutating call |
294
+ |---|---|---|---|---|
295
+ | 429, not a quota | retry | retry | retry | retry |
296
+ | 429 reporting an exhausted quota (`RateLimitedError.quotaExhausted`) | no | no | no | no |
297
+ | Never reached the server (DNS failure, connection refused/unreachable, connect timeout, TLS handshake failure; Cloudflare 521/522/523) | retry | retry | retry | retry |
298
+ | App-origin 502 / 503 / 504 | retry | retry | only with `retry: { retryReadOnlyPosts: true }` | no |
299
+ | Proxy-origin 502 / 503 / 504, 520, 524 | no | retry | no | no |
300
+ | Any other transport error (reset, connection closed — `fetch` cannot tell before-response from mid-response — read error, `REQUEST_TIMEOUT`) | no | retry | no | no |
301
+ | 400 / 401 / 402 / 403 / 404 / 500 and anything else | no | no | no | no |
302
+
303
+ - **Read-only POSTs** are `search`, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl`, `getDocumentMetadata`, `resolve`, `semanticSearch`, `semanticLegislationSearch`. **Mutating calls** are the webhook writes and `extractCitations` (it persists edges).
304
+ - **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`.
156
306
 
157
- Failed requests are retried up to 3 times (configurable via `retry`) with exponential backoff + full jitter:
307
+ **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.
158
308
 
159
- - **Retried:** HTTP 429, 502, 503, 504 and transport-level network errors.
160
- - **Server-directed waits win:** the `Retry-After` response **header** is honored first (then `RateLimit-Reset`, then the JSON `retryAfter` body field — epoch-guarded, since that field historically carried buggy absolute timestamps).
161
- - **Non-idempotent safety:** non-GET requests are retried **only on 429** — never on 5xx or network errors, where the request may already have been applied.
162
- - Client-side timeouts throw `TimeoutError` and are not retried.
309
+ **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).
310
+
311
+ ```ts
312
+ const controller = new AbortController();
313
+ req.on("close", () => controller.abort());
314
+ await client.semanticSearch({ query: "gdpr" }, { signal: controller.signal });
315
+ ```
163
316
 
164
317
  ## Typed errors
165
318
 
166
- Every non-2xx response maps to a typed error carrying `code`, `status`, `details`, and `retryAfter`:
319
+ Every non-2xx response maps to a typed error carrying `code`, `status`, `message`, `details`, `retryAfter`, the raw `body` and parsed `headers`:
167
320
 
168
321
  ```ts
169
- import { CreditsExhaustedError, NotFoundError, RateLimitedError } from "@lexapi/client";
322
+ import { CreditsExhaustedError, NotFoundError, RateLimitedError, TierForbiddenError } from "@lexapi/client";
170
323
 
171
324
  try {
172
- await client.getInfo();
325
+ await client.semanticSearch({ query: "gdpr" });
173
326
  } catch (err) {
174
- if (err instanceof RateLimitedError) console.log(`retry in ${err.retryAfter}s`);
175
- else if (err instanceof CreditsExhaustedError) console.log(`credits reset at ${err.resetsAt}`);
327
+ if (err instanceof RateLimitedError && err.quotaExhausted) console.log(`legacy quota resets ${err.resetsAt}`);
328
+ else if (err instanceof RateLimitedError) console.log(`retry in ${err.retryAfter}s`, err.rateLimit);
329
+ else if (err instanceof CreditsExhaustedError) console.log(`need ${err.weight}, have ${err.available}; resets ${err.resetsAt}`);
330
+ else if (err instanceof TierForbiddenError) console.log((err.body as { upgradeUrl?: string })?.upgradeUrl);
176
331
  else if (err instanceof NotFoundError) console.log("no such document");
177
332
  else throw err;
178
333
  }
179
334
  ```
180
335
 
181
- Subclasses: `NotFoundError`, `InvalidCelexError`, `InvalidUrlError`, `InvalidParamsError`, `AuthenticationError` (401), `RateLimitedError`, `TierForbiddenError`, `CreditsExhaustedError`, `UpstreamError`, `TimeoutError`, `InternalServerError`, `NetworkError`. Both the typed envelope (`{success: false, error: {code, message, details}}`) and the legacy bare `{error, message}` shape are parsed; unknown codes stay on the base `LexAPIError` with the raw code string.
336
+ | Class | `code` | HTTP |
337
+ | --- | --- | --- |
338
+ | `NotFoundError` | `NOT_FOUND` | 404 |
339
+ | `InvalidCelexError` / `InvalidUrlError` / `InvalidParamsError` | `INVALID_CELEX` / `INVALID_URL` / `INVALID_PARAMS` | 400 |
340
+ | `AuthenticationError` | `UNAUTHORIZED` (derived) | 401 |
341
+ | `CreditsExhaustedError` | `CREDITS_EXHAUSTED` | 402 |
342
+ | `TierForbiddenError` | `TIER_FORBIDDEN` | 403 |
343
+ | `RateLimitedError` | `RATE_LIMITED`, `QUOTA_EXHAUSTED` | 429 — `QUOTA_EXHAUSTED` (legacy plans' used-up quota) is never retried; `resetsAt` says when it refills |
344
+ | `InternalServerError` | `INTERNAL` | 500 |
345
+ | `UpstreamError` | `UPSTREAM_ERROR` | 502; Cloudflare 520–523 |
346
+ | `ServiceUnavailableError` | `SERVICE_UNAVAILABLE` (derived) | 503 |
347
+ | `TimeoutError` | `TIMEOUT` (504, 524) / `REQUEST_TIMEOUT` (status 0, the SDK's own timeout) | |
348
+ | `NetworkError` | `CONNECTION_ERROR` | 0 (transport failure, or the connection dropped — incl. mid-export) |
349
+ | `RequestAbortedError` | `ABORTED` | 0 (your `signal` fired) |
350
+ | `InvalidResponseError` | `INVALID_RESPONSE` | a 2xx whose body was not JSON (e.g. a proxy HTML page) |
351
+ | `IncompleteExportError` | `INCOMPLETE_EXPORT` | 0 — an export ended without a complete `_done` trailer, or the server sent an `_error` line (`rowsRead`, `details`) |
352
+ | `LexAPIError` (base) | `INTERNAL` | any other status (e.g. 409, 413), with `status` kept |
353
+
354
+ **`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.
355
+
356
+ 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.
182
357
 
183
358
  ## Credit visibility
184
359
 
@@ -187,39 +362,19 @@ Every response keeps its raw `usage` / `credits` blocks; `getCreditUsage` normal
187
362
  ```ts
188
363
  import { getCreditUsage } from "@lexapi/client";
189
364
 
190
- const info = await client.getInfo();
191
- const { unitsCharged, creditsRemaining, resetsAt } = getCreditUsage(info);
365
+ const { unitsCharged, creditsRemaining, resetsAt } = getCreditUsage(await client.getInfo());
192
366
  ```
193
367
 
194
368
  `unitsCharged` maps `credits.operation_weight` (0 for free ops like `/info`); `creditsRemaining` falls back to `usage.remaining` on legacy daily-call accounts.
195
369
 
196
- ## Point-in-time versions
197
-
198
- > Requires a LexAPI deployment with the point-in-time endpoints (lex-api PR #72).
199
- > Versions are LexAPI *observation snapshots* — the document as fetched — not
200
- > legal in-force reconstructions; history begins at first ingestion.
201
-
202
- ```ts
203
- const history = await client.listDocumentVersions("32016R0679");
204
- console.log(history.currentVersion, history.trackedSince);
205
-
206
- const snapshot = await client.getDocumentVersion("32016R0679", 2);
207
- console.log(snapshot.document.parsedContent);
208
-
209
- const asOf = await client.getDocumentAtDate("32016R0679", "2026-03-20");
210
- console.log(asOf.asOf, asOf.document.version);
211
- ```
212
-
213
- Each call costs 1 credit. Dates before the document entered the corpus reject
214
- with `NotFoundError` carrying the tracking start date.
215
-
216
370
  ## Development
217
371
 
218
372
  ```bash
219
- npm install
220
- npm run lint # tsc --noEmit (strict)
221
- npm test # vitest
222
- npm run build # tsup -> dist/ (ESM + CJS + d.ts)
373
+ npm ci
374
+ npm run lint # tsc --noEmit (strict)
375
+ npm test # vitest (Node ≥ 20)
376
+ npm run build # tsup -> dist/ (ESM + CJS + d.ts / d.cts)
377
+ npm run smoke:dist # framework-free check of the built bundles (runs on Node 18+)
223
378
  ```
224
379
 
225
- Zero runtime dependencies. Docs: <https://lex-api.com/docs>
380
+ See [PLAN.md](PLAN.md) for the endpoint coverage matrix and SDK contract. Docs: <https://lex-api.com/docs?ref=npm-sdk>