@lexapi/client 0.1.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/dist/index.js ADDED
@@ -0,0 +1,954 @@
1
+ // src/errors.ts
2
+ var STATUS_TO_CODE = {
3
+ 400: "INVALID_PARAMS",
4
+ 401: "UNAUTHORIZED",
5
+ 402: "CREDITS_EXHAUSTED",
6
+ 403: "TIER_FORBIDDEN",
7
+ 404: "NOT_FOUND",
8
+ 429: "RATE_LIMITED",
9
+ 502: "UPSTREAM_ERROR",
10
+ 504: "TIMEOUT"
11
+ };
12
+ var LexAPIError = class _LexAPIError extends Error {
13
+ /** Stable machine-readable code (`error.code`, or derived from the HTTP status for legacy bodies). */
14
+ code;
15
+ /** HTTP status. `0` for client-side failures (network error, client-side timeout). */
16
+ status;
17
+ /** The `error.details` object from the typed envelope, when present. */
18
+ details;
19
+ /**
20
+ * Seconds to wait before retrying, when the server said so (429).
21
+ * Sourced from the `Retry-After` response HEADER first; the JSON
22
+ * `retryAfter` body field is only a fallback because it historically
23
+ * carried buggy epoch-seconds values (epoch-looking values are
24
+ * normalized to a delta).
25
+ */
26
+ retryAfter;
27
+ constructor(code, message, status, details, retryAfter) {
28
+ super(`[${code}] ${message} (HTTP ${status})`);
29
+ this.name = "LexAPIError";
30
+ this.code = code;
31
+ this.status = status;
32
+ this.details = details;
33
+ this.retryAfter = retryAfter;
34
+ }
35
+ /**
36
+ * Build the most specific error subclass for a non-2xx response.
37
+ * Accepts both the typed envelope and the legacy bare `{error, message}` shape.
38
+ */
39
+ static fromResponse(status, body, headerRetryAfter) {
40
+ let code = STATUS_TO_CODE[status] ?? "INTERNAL";
41
+ let message = `HTTP ${status}`;
42
+ let details;
43
+ let retryAfter = headerRetryAfter;
44
+ let resetsAt;
45
+ if (typeof body === "object" && body !== null) {
46
+ const record = body;
47
+ const err = record["error"];
48
+ if (typeof err === "object" && err !== null) {
49
+ const e = err;
50
+ if (typeof e["code"] === "string") code = e["code"];
51
+ if (typeof e["message"] === "string") message = e["message"];
52
+ details = e["details"];
53
+ } else if (typeof err === "string") {
54
+ message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
55
+ } else if (typeof record["message"] === "string") {
56
+ message = record["message"];
57
+ }
58
+ if (retryAfter === void 0) {
59
+ const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
60
+ if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
61
+ }
62
+ resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
63
+ }
64
+ switch (code) {
65
+ case "NOT_FOUND":
66
+ return new NotFoundError(message, status, details, retryAfter);
67
+ case "INVALID_CELEX":
68
+ return new InvalidCelexError(message, status, details, retryAfter);
69
+ case "INVALID_URL":
70
+ return new InvalidUrlError(message, status, details, retryAfter);
71
+ case "INVALID_PARAMS":
72
+ return new InvalidParamsError(message, status, details, retryAfter);
73
+ case "RATE_LIMITED":
74
+ return new RateLimitedError(message, status, details, retryAfter);
75
+ case "TIER_FORBIDDEN":
76
+ return new TierForbiddenError(message, status, details, retryAfter);
77
+ case "CREDITS_EXHAUSTED":
78
+ return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt);
79
+ case "UPSTREAM_ERROR":
80
+ return new UpstreamError(message, status, details, retryAfter);
81
+ case "TIMEOUT":
82
+ return new TimeoutError(message, status, details, retryAfter);
83
+ case "UNAUTHORIZED":
84
+ return new AuthenticationError(message, status, details, retryAfter);
85
+ case "INTERNAL":
86
+ return new InternalServerError(message, status, details, retryAfter);
87
+ default:
88
+ return new _LexAPIError(code, message, status, details, retryAfter);
89
+ }
90
+ }
91
+ };
92
+ var NotFoundError = class extends LexAPIError {
93
+ constructor(message, status = 404, details, retryAfter) {
94
+ super("NOT_FOUND", message, status, details, retryAfter);
95
+ this.name = "NotFoundError";
96
+ }
97
+ };
98
+ var InvalidCelexError = class extends LexAPIError {
99
+ constructor(message, status = 400, details, retryAfter) {
100
+ super("INVALID_CELEX", message, status, details, retryAfter);
101
+ this.name = "InvalidCelexError";
102
+ }
103
+ };
104
+ var InvalidUrlError = class extends LexAPIError {
105
+ constructor(message, status = 400, details, retryAfter) {
106
+ super("INVALID_URL", message, status, details, retryAfter);
107
+ this.name = "InvalidUrlError";
108
+ }
109
+ };
110
+ var InvalidParamsError = class extends LexAPIError {
111
+ constructor(message, status = 400, details, retryAfter) {
112
+ super("INVALID_PARAMS", message, status, details, retryAfter);
113
+ this.name = "InvalidParamsError";
114
+ }
115
+ };
116
+ var AuthenticationError = class extends LexAPIError {
117
+ constructor(message, status = 401, details, retryAfter) {
118
+ super("UNAUTHORIZED", message, status, details, retryAfter);
119
+ this.name = "AuthenticationError";
120
+ }
121
+ };
122
+ var RateLimitedError = class extends LexAPIError {
123
+ constructor(message, status = 429, details, retryAfter) {
124
+ super("RATE_LIMITED", message, status, details, retryAfter);
125
+ this.name = "RateLimitedError";
126
+ }
127
+ };
128
+ var TierForbiddenError = class extends LexAPIError {
129
+ constructor(message, status = 403, details, retryAfter) {
130
+ super("TIER_FORBIDDEN", message, status, details, retryAfter);
131
+ this.name = "TierForbiddenError";
132
+ }
133
+ };
134
+ var CreditsExhaustedError = class extends LexAPIError {
135
+ /** When the monthly credit allowance resets (ISO date-time), when the server said so. */
136
+ resetsAt;
137
+ constructor(message, status = 402, details, retryAfter, resetsAt) {
138
+ super("CREDITS_EXHAUSTED", message, status, details, retryAfter);
139
+ this.name = "CreditsExhaustedError";
140
+ this.resetsAt = resetsAt;
141
+ }
142
+ };
143
+ var UpstreamError = class extends LexAPIError {
144
+ constructor(message, status = 502, details, retryAfter) {
145
+ super("UPSTREAM_ERROR", message, status, details, retryAfter);
146
+ this.name = "UpstreamError";
147
+ }
148
+ };
149
+ var TimeoutError = class extends LexAPIError {
150
+ constructor(message, status = 0, details, retryAfter) {
151
+ super("TIMEOUT", message, status, details, retryAfter);
152
+ this.name = "TimeoutError";
153
+ }
154
+ };
155
+ var InternalServerError = class extends LexAPIError {
156
+ constructor(message, status = 500, details, retryAfter) {
157
+ super("INTERNAL", message, status, details, retryAfter);
158
+ this.name = "InternalServerError";
159
+ }
160
+ };
161
+ var NetworkError = class extends LexAPIError {
162
+ cause;
163
+ constructor(message, cause) {
164
+ super("NETWORK_ERROR", message, 0);
165
+ this.name = "NetworkError";
166
+ this.cause = cause;
167
+ }
168
+ };
169
+ function normalizeRetryAfterSeconds(value) {
170
+ if (!Number.isFinite(value)) return 0;
171
+ if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
172
+ if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
173
+ return Math.max(0, value);
174
+ }
175
+ function readNumber(value) {
176
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
177
+ }
178
+ function readString(value) {
179
+ return typeof value === "string" ? value : void 0;
180
+ }
181
+ function detailsField(details, key) {
182
+ if (typeof details === "object" && details !== null) {
183
+ return details[key];
184
+ }
185
+ return void 0;
186
+ }
187
+ function usageField(record, key) {
188
+ return detailsField(record["usage"], key);
189
+ }
190
+
191
+ // src/version.ts
192
+ var VERSION = "0.1.0";
193
+
194
+ // src/http.ts
195
+ var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
196
+ var DEFAULT_TIMEOUT_MS = 6e4;
197
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
198
+ function isBrowserRuntime() {
199
+ return typeof window !== "undefined" && typeof document !== "undefined";
200
+ }
201
+ var HttpClient = class {
202
+ opts;
203
+ userAgent;
204
+ constructor(opts) {
205
+ this.opts = opts;
206
+ this.userAgent = opts.userAgentSuffix ? `lexapi-typescript/${VERSION} ${opts.userAgentSuffix}` : `lexapi-typescript/${VERSION}`;
207
+ }
208
+ /** Perform a request and parse the JSON body (204 yields `undefined`). */
209
+ async requestJson(options) {
210
+ const { data } = await this.requestJsonWithResponse(options);
211
+ return data;
212
+ }
213
+ /** Like `requestJson`, but also exposes the raw `Response` (for header signals). */
214
+ async requestJsonWithResponse(options) {
215
+ const response = await this.requestRaw(options);
216
+ if (response.status === 204) {
217
+ return { data: void 0, response };
218
+ }
219
+ return { data: await response.json(), response };
220
+ }
221
+ /**
222
+ * Perform a request and return the raw successful `Response` without
223
+ * consuming the body (used by streaming endpoints such as `/export`).
224
+ * Non-2xx responses are parsed and thrown as typed errors; the retry
225
+ * policy applies before the first body byte is consumed.
226
+ */
227
+ async requestRaw(options) {
228
+ const { method, path, query, body } = options;
229
+ const url = `${this.opts.baseUrl}${path}${buildQuery(query)}`;
230
+ const timeoutMs = options.timeoutMs ?? this.opts.timeoutMs;
231
+ const { maxRetries, baseDelayMs, maxDelayMs } = this.opts.retry;
232
+ const headers = {
233
+ "x-api-key": this.opts.apiKey,
234
+ accept: "application/json"
235
+ };
236
+ if (!isBrowserRuntime()) {
237
+ headers["user-agent"] = this.userAgent;
238
+ }
239
+ let serializedBody;
240
+ if (body !== void 0) {
241
+ headers["content-type"] = "application/json";
242
+ serializedBody = JSON.stringify(body);
243
+ }
244
+ for (let attempt = 0; ; attempt++) {
245
+ let response;
246
+ try {
247
+ response = await this.fetchWithTimeout(url, {
248
+ method,
249
+ headers,
250
+ ...serializedBody !== void 0 ? { body: serializedBody } : {},
251
+ timeoutMs
252
+ });
253
+ } catch (cause) {
254
+ if (cause instanceof TimeoutError) throw cause;
255
+ if (attempt < maxRetries && method === "GET") {
256
+ await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs));
257
+ continue;
258
+ }
259
+ throw new NetworkError(`Network error calling ${method} ${path}`, cause);
260
+ }
261
+ if (response.ok) return response;
262
+ const error = await parseErrorResponse(response);
263
+ const retryable = RETRYABLE_STATUSES.has(response.status) && (method === "GET" || response.status === 429);
264
+ if (attempt < maxRetries && retryable) {
265
+ const serverWaitSeconds = serverDirectedWaitSeconds(response, error);
266
+ const waitMs = serverWaitSeconds !== void 0 ? Math.min(serverWaitSeconds * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
267
+ await sleep(waitMs);
268
+ continue;
269
+ }
270
+ throw error;
271
+ }
272
+ }
273
+ async fetchWithTimeout(url, init) {
274
+ const controller = new AbortController();
275
+ const timer = setTimeout(() => controller.abort(), init.timeoutMs);
276
+ try {
277
+ return await this.opts.fetchFn(url, {
278
+ method: init.method,
279
+ headers: init.headers,
280
+ ...init.body !== void 0 ? { body: init.body } : {},
281
+ signal: controller.signal
282
+ });
283
+ } catch (cause) {
284
+ if (controller.signal.aborted) {
285
+ throw new TimeoutError(`Request timed out after ${init.timeoutMs}ms`, 0);
286
+ }
287
+ throw cause;
288
+ } finally {
289
+ clearTimeout(timer);
290
+ }
291
+ }
292
+ };
293
+ async function parseErrorResponse(response) {
294
+ let body;
295
+ try {
296
+ body = await response.json();
297
+ } catch {
298
+ body = void 0;
299
+ }
300
+ return LexAPIError.fromResponse(response.status, body, headerRetryAfterSeconds(response));
301
+ }
302
+ function headerRetryAfterSeconds(response) {
303
+ const header = response.headers.get("retry-after");
304
+ if (header === null) return void 0;
305
+ const seconds = Number(header);
306
+ if (Number.isFinite(seconds)) return Math.max(0, seconds);
307
+ const date = Date.parse(header);
308
+ if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
309
+ return void 0;
310
+ }
311
+ function serverDirectedWaitSeconds(response, error) {
312
+ const header = headerRetryAfterSeconds(response);
313
+ if (header !== void 0) return header;
314
+ const rateLimitReset = response.headers.get("ratelimit-reset");
315
+ if (rateLimitReset !== null) {
316
+ const seconds = Number(rateLimitReset);
317
+ if (Number.isFinite(seconds)) return normalizeRetryAfterSeconds(seconds);
318
+ }
319
+ return error.retryAfter;
320
+ }
321
+ function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
322
+ return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
323
+ }
324
+ function sleep(ms) {
325
+ return new Promise((resolve) => setTimeout(resolve, ms));
326
+ }
327
+ function buildQuery(query) {
328
+ if (!query) return "";
329
+ const params = new URLSearchParams();
330
+ for (const [key, value] of Object.entries(query)) {
331
+ if (value !== void 0) params.set(key, String(value));
332
+ }
333
+ const qs = params.toString();
334
+ return qs ? `?${qs}` : "";
335
+ }
336
+
337
+ // src/export.ts
338
+ async function* ndjsonLines(body) {
339
+ const reader = body.getReader();
340
+ const decoder = new TextDecoder();
341
+ let buffer = "";
342
+ try {
343
+ for (; ; ) {
344
+ const { done, value } = await reader.read();
345
+ if (done) break;
346
+ buffer += decoder.decode(value, { stream: true });
347
+ let newline;
348
+ while ((newline = buffer.indexOf("\n")) !== -1) {
349
+ const line = buffer.slice(0, newline).trim();
350
+ buffer = buffer.slice(newline + 1);
351
+ if (line) yield line;
352
+ }
353
+ }
354
+ buffer += decoder.decode();
355
+ const tail = buffer.trim();
356
+ if (tail) yield tail;
357
+ } finally {
358
+ reader.releaseLock();
359
+ }
360
+ }
361
+ function parseLine(line) {
362
+ try {
363
+ return JSON.parse(line);
364
+ } catch (cause) {
365
+ throw new LexAPIError(
366
+ "INTERNAL",
367
+ `Malformed NDJSON line in export stream: ${line.slice(0, 120)}`,
368
+ 0,
369
+ cause
370
+ );
371
+ }
372
+ }
373
+ var ExportStreamImpl = class {
374
+ meta;
375
+ done;
376
+ headers;
377
+ lines;
378
+ pendingFirstRow;
379
+ consumed = false;
380
+ constructor(lines, headers) {
381
+ this.lines = lines;
382
+ this.headers = headers;
383
+ }
384
+ /** Read the leading line so `meta` is available before iteration starts. */
385
+ async init() {
386
+ const first = await this.lines.next();
387
+ if (first.done) return;
388
+ const parsed = parseLine(first.value);
389
+ if ("_meta" in parsed) {
390
+ this.meta = parsed;
391
+ } else if ("_done" in parsed) {
392
+ this.done = parsed;
393
+ } else {
394
+ this.pendingFirstRow = parsed;
395
+ }
396
+ }
397
+ async *[Symbol.asyncIterator]() {
398
+ if (this.consumed) {
399
+ throw new LexAPIError("INTERNAL", "Export stream already consumed (single-pass)", 0);
400
+ }
401
+ this.consumed = true;
402
+ if (this.pendingFirstRow !== void 0) {
403
+ yield this.pendingFirstRow;
404
+ this.pendingFirstRow = void 0;
405
+ }
406
+ if (this.done !== void 0) return;
407
+ for (; ; ) {
408
+ const next = await this.lines.next();
409
+ if (next.done) return;
410
+ const parsed = parseLine(next.value);
411
+ if ("_done" in parsed) {
412
+ this.done = parsed;
413
+ return;
414
+ }
415
+ if ("_meta" in parsed) continue;
416
+ yield parsed;
417
+ }
418
+ }
419
+ };
420
+ async function createExportStream(response) {
421
+ if (response.body === null) {
422
+ throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
423
+ }
424
+ const totalHeader = response.headers.get("x-export-total");
425
+ const streamingHeader = response.headers.get("x-export-streaming");
426
+ const truncatedHeader = response.headers.get("x-export-truncated");
427
+ const stream = new ExportStreamImpl(ndjsonLines(response.body), {
428
+ total: totalHeader !== null ? Number(totalHeader) : void 0,
429
+ streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
430
+ truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
431
+ });
432
+ await stream.init();
433
+ return stream;
434
+ }
435
+
436
+ // src/webhooks.ts
437
+ var WebhooksAPI = class {
438
+ http;
439
+ constructor(http) {
440
+ this.http = http;
441
+ }
442
+ /**
443
+ * `GET /webhooks` — every webhook owned by the caller, newest first.
444
+ * The `secret` is never returned here (only once, on creation).
445
+ */
446
+ async list(options) {
447
+ return this.http.requestJson({
448
+ method: "GET",
449
+ path: "/webhooks",
450
+ timeoutMs: options?.timeoutMs
451
+ });
452
+ }
453
+ /**
454
+ * `POST /webhooks` — subscribe a URL to documents matching saved search
455
+ * criteria. If `secret` is omitted the server generates one and returns
456
+ * it in this response ONLY — store it. Rejected with 400 when the tier
457
+ * webhook ceiling is reached (FREE=0, STARTER=2, PROFESSIONAL=10,
458
+ * BUSINESS=50).
459
+ */
460
+ async create(request, options) {
461
+ return this.http.requestJson({
462
+ method: "POST",
463
+ path: "/webhooks",
464
+ body: request,
465
+ timeoutMs: options?.timeoutMs
466
+ });
467
+ }
468
+ /** `GET /webhooks/{id}` — full details including the 20 most recent deliveries. */
469
+ async get(id, options) {
470
+ return this.http.requestJson({
471
+ method: "GET",
472
+ path: `/webhooks/${encodeURIComponent(id)}`,
473
+ timeoutMs: options?.timeoutMs
474
+ });
475
+ }
476
+ /**
477
+ * `PUT /webhooks/{id}` — partial update; only supplied fields change.
478
+ * Setting `status: "ACTIVE"` also resets `consecutiveFailures` to 0
479
+ * (re-enables an auto-paused webhook).
480
+ */
481
+ async update(id, request, options) {
482
+ return this.http.requestJson({
483
+ method: "PUT",
484
+ path: `/webhooks/${encodeURIComponent(id)}`,
485
+ body: request,
486
+ timeoutMs: options?.timeoutMs
487
+ });
488
+ }
489
+ /**
490
+ * `DELETE /webhooks/{id}` — permanently deletes the webhook and its
491
+ * delivery history. Resolves on 204; a repeat delete throws
492
+ * `NotFoundError`.
493
+ */
494
+ async delete(id, options) {
495
+ await this.http.requestJson({
496
+ method: "DELETE",
497
+ path: `/webhooks/${encodeURIComponent(id)}`,
498
+ timeoutMs: options?.timeoutMs
499
+ });
500
+ }
501
+ /**
502
+ * `POST /webhooks/{id}/test` — synchronously POSTs a `webhook.test`
503
+ * payload (HMAC-SHA256 signed via `X-Webhook-Signature`) to the webhook
504
+ * URL and returns the upstream result. 10 s timeout; redirects are not
505
+ * followed.
506
+ */
507
+ async test(id, options) {
508
+ return this.http.requestJson({
509
+ method: "POST",
510
+ path: `/webhooks/${encodeURIComponent(id)}/test`,
511
+ timeoutMs: options?.timeoutMs
512
+ });
513
+ }
514
+ /** `GET /webhooks/{id}/deliveries` — delivery history, most recent first. */
515
+ async deliveries(id, params = {}, options) {
516
+ return this.http.requestJson({
517
+ method: "GET",
518
+ path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
519
+ query: { limit: params.limit, offset: params.offset },
520
+ timeoutMs: options?.timeoutMs
521
+ });
522
+ }
523
+ };
524
+
525
+ // src/client.ts
526
+ var LexAPI = class {
527
+ http;
528
+ /** Webhook subscriptions (`client.webhooks.list/create/get/update/delete/test/deliveries`). */
529
+ webhooks;
530
+ constructor(options = {}) {
531
+ const apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env["LEXAPI_API_KEY"] : void 0);
532
+ if (!apiKey) {
533
+ throw new Error("apiKey is required (or set LEXAPI_API_KEY)");
534
+ }
535
+ this.http = new HttpClient({
536
+ apiKey,
537
+ baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
538
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
539
+ fetchFn: options.fetch ?? fetch,
540
+ retry: {
541
+ maxRetries: options.retry?.maxRetries ?? 3,
542
+ baseDelayMs: options.retry?.baseDelayMs ?? 500,
543
+ maxDelayMs: options.retry?.maxDelayMs ?? 3e4
544
+ },
545
+ userAgentSuffix: options.userAgentSuffix
546
+ });
547
+ this.webhooks = new WebhooksAPI(this.http);
548
+ }
549
+ /**
550
+ * `GET /info` — API capabilities, subscription tier, and current usage.
551
+ * Free operation (0 credits); useful as a connection probe.
552
+ */
553
+ async getInfo(options) {
554
+ return this.http.requestJson({
555
+ method: "GET",
556
+ path: "/info",
557
+ timeoutMs: options?.timeoutMs
558
+ });
559
+ }
560
+ /**
561
+ * `POST /search` — search EUR-Lex with structured filters.
562
+ *
563
+ * At least one filter is required. Truncation and partial-result signals
564
+ * are surfaced on the response rather than hidden: check `truncated` /
565
+ * `truncatedAt` / `truncatedReason` (tier-capped pagination), `partial` /
566
+ * `partialReason` (an upstream page timed out), `postFilteredBy`
567
+ * (controller-side post-filter dropped rows — `"date"` means raising
568
+ * `maxPages` widens recall), `ignoredDocumentTypes`, and `xWarning`
569
+ * (the `X-Warning` response header, e.g. `maxPages` tier clamping).
570
+ */
571
+ async search(request, options) {
572
+ const { data, response } = await this.http.requestJsonWithResponse({
573
+ method: "POST",
574
+ path: "/search",
575
+ body: request,
576
+ timeoutMs: options?.timeoutMs
577
+ });
578
+ return withHeaderSignals(data, response);
579
+ }
580
+ /**
581
+ * `POST /documentContent` — fetch a single fully-parsed document by CELEX.
582
+ *
583
+ * Corpus-first with live-scrape fallback (`bypassCorpus: true` forces a
584
+ * live read). Use `include`/`fields`/`articleId` to trim the payload.
585
+ */
586
+ async getDocument(request, options) {
587
+ return this.http.requestJson({
588
+ method: "POST",
589
+ path: "/documentContent",
590
+ body: request,
591
+ timeoutMs: options?.timeoutMs
592
+ });
593
+ }
594
+ /**
595
+ * `POST /documentContent/batch` — fetch multiple documents in one request.
596
+ *
597
+ * The batch is clamped to the tier ceiling (FREE=1, STARTER=5,
598
+ * PROFESSIONAL=20, BUSINESS=50). Clamping is surfaced, not silent: check
599
+ * `trimmed` / `trimmedTo` / `trimmedReason` on the body and `xWarning`
600
+ * (the `X-Warning` header). Per-CELEX failures are collected in `errors`
601
+ * instead of aborting the batch.
602
+ */
603
+ async getDocumentsBatch(request, options) {
604
+ const { data, response } = await this.http.requestJsonWithResponse({
605
+ method: "POST",
606
+ path: "/documentContent/batch",
607
+ body: request,
608
+ timeoutMs: options?.timeoutMs
609
+ });
610
+ return withHeaderSignals(data, response);
611
+ }
612
+ /**
613
+ * `GET /documents/recent` — recently-published documents (last `days`
614
+ * days, default 7). Page fetching is tier-clamped like `/search`;
615
+ * `xWarning` carries the `X-Warning` header when clamping fired, and
616
+ * `languageFilter` reports rows dropped by the language post-filter.
617
+ */
618
+ async getRecentDocuments(params = {}, options) {
619
+ const { data, response } = await this.http.requestJsonWithResponse({
620
+ method: "GET",
621
+ path: "/documents/recent",
622
+ query: {
623
+ days: params.days,
624
+ documentType: params.documentType,
625
+ author: params.author,
626
+ domain: params.domain,
627
+ subdomain: params.subdomain,
628
+ language: params.language,
629
+ limit: params.limit
630
+ },
631
+ timeoutMs: options?.timeoutMs
632
+ });
633
+ return withHeaderSignals(data, response);
634
+ }
635
+ /**
636
+ * `POST /documents/url` — fetch a document by any EUR-Lex URL. The
637
+ * response is shaped like `getDocument` plus `sourceUrl` and
638
+ * `extractedCelex` echo-backs.
639
+ */
640
+ async getDocumentByUrl(request, options) {
641
+ return this.http.requestJson({
642
+ method: "POST",
643
+ path: "/documents/url",
644
+ body: request,
645
+ timeoutMs: options?.timeoutMs
646
+ });
647
+ }
648
+ /**
649
+ * `POST /documents/metadata` — metadata only (title, dates, ECLI/ELI,
650
+ * keywords, subjects). Skips the body parse: significantly faster and
651
+ * cheaper than `getDocument`.
652
+ */
653
+ async getDocumentMetadata(request, options) {
654
+ return this.http.requestJson({
655
+ method: "POST",
656
+ path: "/documents/metadata",
657
+ body: request,
658
+ timeoutMs: options?.timeoutMs
659
+ });
660
+ }
661
+ /**
662
+ * `POST /resolve` — resolve any legal identifier (bare CELEX, EUR-Lex
663
+ * URL, ELI URI, or ECLI) to the canonical CELEX plus access URLs.
664
+ */
665
+ async resolve(identifier, options) {
666
+ return this.http.requestJson({
667
+ method: "POST",
668
+ path: "/resolve",
669
+ body: { identifier },
670
+ timeoutMs: options?.timeoutMs
671
+ });
672
+ }
673
+ // ── Point-in-time versions ────────────────────────────────────────
674
+ // Requires lex-api PR #72 deployed. Versions are LexAPI observation
675
+ // snapshots (content-hash changes between fetches), NOT legal in-force
676
+ // reconstructions; history begins at first ingestion.
677
+ /**
678
+ * `GET /documents/{celex}/versions` — version history, newest first,
679
+ * current version included and flagged. 1 credit.
680
+ */
681
+ async listDocumentVersions(celex, params = {}, options) {
682
+ return this.http.requestJson({
683
+ method: "GET",
684
+ path: `/documents/${encodeURIComponent(celex)}/versions`,
685
+ query: { language: params.language },
686
+ timeoutMs: options?.timeoutMs
687
+ });
688
+ }
689
+ /**
690
+ * `GET /documents/{celex}/versions/{version}` — one immutable snapshot
691
+ * including `parsedContent`. `corpusVersion` mirrors the
692
+ * `X-Corpus-Version` response header. 1 credit.
693
+ */
694
+ async getDocumentVersion(celex, version, params = {}, options) {
695
+ const { data, response } = await this.http.requestJsonWithResponse({
696
+ method: "GET",
697
+ path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
698
+ query: { language: params.language },
699
+ timeoutMs: options?.timeoutMs
700
+ });
701
+ return withCorpusVersion(data, response);
702
+ }
703
+ /**
704
+ * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
705
+ * current on `date` (`YYYY-MM-DD`, end-of-day UTC inclusive). Dates
706
+ * before the document entered the corpus reject with `NotFoundError`
707
+ * carrying the tracking start date. 1 credit.
708
+ */
709
+ async getDocumentAtDate(celex, date, params = {}, options) {
710
+ const { data, response } = await this.http.requestJsonWithResponse({
711
+ method: "GET",
712
+ path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
713
+ query: { language: params.language },
714
+ timeoutMs: options?.timeoutMs
715
+ });
716
+ return withCorpusVersion(data, response);
717
+ }
718
+ // ── Citations ─────────────────────────────────────────────────────
719
+ /**
720
+ * `POST /citations/extract` — crawl a document's EUR-Lex metadata page
721
+ * for citations and persist them into the graph. Idempotent: an already
722
+ * processed document returns immediately with `alreadyExtracted: true`.
723
+ */
724
+ async extractCitations(celexNumber, options) {
725
+ return this.http.requestJson({
726
+ method: "POST",
727
+ path: "/citations/extract",
728
+ body: { celexNumber },
729
+ timeoutMs: options?.timeoutMs
730
+ });
731
+ }
732
+ /**
733
+ * `GET /citations/cites/{celexNumber}` — documents this one cites
734
+ * (outbound edges), grouped by target. The document must first have been
735
+ * crawled via `extractCitations` to appear here.
736
+ */
737
+ async getCites(celexNumber, params = {}, options) {
738
+ return this.http.requestJson({
739
+ method: "GET",
740
+ path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
741
+ query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
742
+ timeoutMs: options?.timeoutMs
743
+ });
744
+ }
745
+ /**
746
+ * `GET /citations/cited-by/{celexNumber}` — documents that cite this one
747
+ * (inbound edges), grouped by source.
748
+ */
749
+ async getCitedBy(celexNumber, params = {}, options) {
750
+ return this.http.requestJson({
751
+ method: "GET",
752
+ path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
753
+ query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
754
+ timeoutMs: options?.timeoutMs
755
+ });
756
+ }
757
+ /**
758
+ * `GET /citations/network/{celexNumber}` — inbound and outbound
759
+ * neighbourhood in one call, paginated per direction.
760
+ *
761
+ * If the server-side wall-clock budget expires the endpoint still
762
+ * returns 200 with `partial: true`, an EMPTY `network`, and `null`
763
+ * paging totals — check `partial` before treating the network as empty.
764
+ */
765
+ async getCitationNetwork(celexNumber, params = {}, options) {
766
+ return this.http.requestJson({
767
+ method: "GET",
768
+ path: `/citations/network/${encodeURIComponent(celexNumber)}`,
769
+ query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
770
+ timeoutMs: options?.timeoutMs
771
+ });
772
+ }
773
+ /**
774
+ * `GET /citations/path/{from}/{to}` — shortest citation path (BFS over
775
+ * outbound edges). `found: false` is a graceful HTTP 200, not an error.
776
+ * Default `maxDepth` 3 (max 8); the visited set is bounded to 5000 nodes.
777
+ */
778
+ async getCitationPath(from, to, params = {}, options) {
779
+ return this.http.requestJson({
780
+ method: "GET",
781
+ path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
782
+ query: { maxDepth: params.maxDepth },
783
+ timeoutMs: options?.timeoutMs
784
+ });
785
+ }
786
+ /**
787
+ * `GET /citations/related/{celexNumber}` — bibliographic-coupling
788
+ * neighbours (documents sharing the most outbound citation targets with
789
+ * the seed). Returns a graceful empty list with `message` when the seed
790
+ * has no outbound citations to couple on.
791
+ */
792
+ async getRelatedDocuments(celexNumber, params = {}, options) {
793
+ return this.http.requestJson({
794
+ method: "GET",
795
+ path: `/citations/related/${encodeURIComponent(celexNumber)}`,
796
+ query: { limit: params.limit },
797
+ timeoutMs: options?.timeoutMs
798
+ });
799
+ }
800
+ /** `GET /citations/stats` — global citation graph statistics. */
801
+ async getCitationStats(options) {
802
+ return this.http.requestJson({
803
+ method: "GET",
804
+ path: "/citations/stats",
805
+ timeoutMs: options?.timeoutMs
806
+ });
807
+ }
808
+ // ── Semantic search ───────────────────────────────────────────────
809
+ /**
810
+ * `POST /search/semantic` — embedding-based semantic search over CJEU
811
+ * case law. Use this (not `search`) for *concept* queries; EUR-Lex
812
+ * keyword matching is literal.
813
+ *
814
+ * **Billing:** 5 credits per call — **15 credits with `hyde: true`**
815
+ * (HyDE query rewriting: an LLM drafts the passage a relevant judgment
816
+ * would contain and retrieval fuses both rankings; ~1–3 s extra
817
+ * latency). HyDE is best-effort: on LLM failure the search falls back
818
+ * to plain retrieval, the response reports `hyde: false`, and the
819
+ * 10-credit premium is **refunded automatically** — verify via
820
+ * `credits.operation_weight`.
821
+ *
822
+ * The response exposes `hint` (present only on low-confidence,
823
+ * best-effort result sets — its presence is itself the signal), `hyde`
824
+ * (whether HyDE actually ran), and `hypotheticalDocument` (the drafted
825
+ * passage, present only when HyDE ran).
826
+ *
827
+ * Fewer results than `limit`? The upstream's ~0.7 default relevance
828
+ * floor cut in — pass `minScore: 0.5` (or `0`) to widen recall.
829
+ *
830
+ * Persistent document identity is `(metadata.celex_id,
831
+ * metadata.document_type)`; `case_id` is snapshot-scoped and does not
832
+ * survive index rebuilds.
833
+ */
834
+ async semanticSearch(request, options) {
835
+ return this.http.requestJson({
836
+ method: "POST",
837
+ path: "/search/semantic",
838
+ body: semanticWireBody(request),
839
+ timeoutMs: options?.timeoutMs
840
+ });
841
+ }
842
+ /**
843
+ * `POST /legislation/semantic` — embedding-based semantic search over EU
844
+ * legislation; results are article-level matches (`article_ref`,
845
+ * `law_id`, `law_title`, `score`).
846
+ *
847
+ * Costs 5 credits. The `hyde` option is case-law only and is therefore
848
+ * not accepted here (the server ignores it on this endpoint). The same
849
+ * ~0.7 default relevance floor applies — lower `minScore` to widen
850
+ * recall; `hint` is present only on low-confidence result sets.
851
+ */
852
+ async semanticLegislationSearch(request, options) {
853
+ return this.http.requestJson({
854
+ method: "POST",
855
+ path: "/legislation/semantic",
856
+ body: semanticWireBody(request),
857
+ timeoutMs: options?.timeoutMs
858
+ });
859
+ }
860
+ // ── Export ────────────────────────────────────────────────────────
861
+ /**
862
+ * `GET /export` — stream matching corpus rows as NDJSON (BUSINESS tier;
863
+ * 402 `TierForbidden`/`CreditsExhausted`-style envelope otherwise).
864
+ *
865
+ * Returns a single-pass async iterator over document rows. The leading
866
+ * `_meta` envelope is parsed before this resolves (`stream.meta`); the
867
+ * trailing `_done` line is exposed as `stream.done` after iteration
868
+ * finishes — check `done.truncated` / `headers.truncated` to detect the
869
+ * server row cap (`X-Export-Truncated: 1`) instead of assuming the
870
+ * export was complete.
871
+ *
872
+ * ```ts
873
+ * const stream = await client.export({ documentType: "regulation", limit: 1000 });
874
+ * console.log(stream.meta, stream.headers.total);
875
+ * for await (const row of stream) process(row.celex, row.parsedContent);
876
+ * if (stream.done?.truncated) console.warn("row cap hit — paginate with fetchedSince");
877
+ * ```
878
+ */
879
+ async export(params = {}, options) {
880
+ const response = await this.http.requestRaw({
881
+ method: "GET",
882
+ path: "/export",
883
+ query: {
884
+ documentType: params.documentType,
885
+ author: params.author,
886
+ subdomain: params.subdomain,
887
+ language: params.language,
888
+ dateFrom: params.dateFrom,
889
+ dateTo: params.dateTo,
890
+ fetchedSince: params.fetchedSince,
891
+ includeHtml: params.includeHtml,
892
+ includeContent: params.includeContent,
893
+ limit: params.limit
894
+ },
895
+ timeoutMs: options?.timeoutMs
896
+ });
897
+ return createExportStream(response);
898
+ }
899
+ };
900
+ function semanticWireBody(request) {
901
+ const body = { query: request.query };
902
+ if (request.limit !== void 0) body["limit"] = request.limit;
903
+ if (request.minScore !== void 0) body["min_score"] = request.minScore;
904
+ if (request.language !== void 0) body["language"] = request.language;
905
+ if (request.includeText) body["include"] = ["text"];
906
+ if (request.filters !== void 0) body["filters"] = request.filters;
907
+ if (request.hyde !== void 0) body["hyde"] = request.hyde;
908
+ return body;
909
+ }
910
+ function withHeaderSignals(data, response) {
911
+ const warning = response.headers.get("x-warning");
912
+ if (warning !== null && typeof data === "object" && data !== null) {
913
+ return { ...data, xWarning: warning };
914
+ }
915
+ return data;
916
+ }
917
+ function withCorpusVersion(data, response) {
918
+ const raw = response.headers.get("x-corpus-version");
919
+ const parsed = raw === null ? Number.NaN : Number.parseInt(raw, 10);
920
+ if (!Number.isNaN(parsed)) {
921
+ return { ...data, corpusVersion: parsed };
922
+ }
923
+ return data;
924
+ }
925
+
926
+ // src/credits.ts
927
+ function getCreditUsage(response) {
928
+ return {
929
+ unitsCharged: response.credits?.operation_weight,
930
+ creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
931
+ resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
932
+ };
933
+ }
934
+ export {
935
+ AuthenticationError,
936
+ CreditsExhaustedError,
937
+ DEFAULT_BASE_URL,
938
+ DEFAULT_TIMEOUT_MS,
939
+ InternalServerError,
940
+ InvalidCelexError,
941
+ InvalidParamsError,
942
+ InvalidUrlError,
943
+ LexAPI,
944
+ LexAPIError,
945
+ NetworkError,
946
+ NotFoundError,
947
+ RateLimitedError,
948
+ TierForbiddenError,
949
+ TimeoutError,
950
+ UpstreamError,
951
+ VERSION,
952
+ WebhooksAPI,
953
+ getCreditUsage
954
+ };