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