@lexapi/client 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,9 +22,13 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AS_OF_REASONS: () => AS_OF_REASONS,
24
24
  AuthenticationError: () => AuthenticationError,
25
+ CITATION_PROVENANCES: () => CITATION_PROVENANCES,
26
+ CITATION_RESOLUTIONS: () => CITATION_RESOLUTIONS,
27
+ CITATION_TYPES: () => CITATION_TYPES,
25
28
  CreditsExhaustedError: () => CreditsExhaustedError,
26
29
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
27
30
  DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
31
+ DocumentWithdrawnError: () => DocumentWithdrawnError,
28
32
  IncompleteExportError: () => IncompleteExportError,
29
33
  InternalServerError: () => InternalServerError,
30
34
  InvalidCelexError: () => InvalidCelexError,
@@ -33,6 +37,10 @@ __export(index_exports, {
33
37
  InvalidUrlError: () => InvalidUrlError,
34
38
  LexAPI: () => LexAPI,
35
39
  LexAPIError: () => LexAPIError,
40
+ NationalAllowanceExhaustedError: () => NationalAllowanceExhaustedError,
41
+ NationalSemanticFilterUnreachableError: () => NationalSemanticFilterUnreachableError,
42
+ NationalSemanticNotEnabledError: () => NationalSemanticNotEnabledError,
43
+ NationalSemanticUnavailableError: () => NationalSemanticUnavailableError,
36
44
  NetworkError: () => NetworkError,
37
45
  NotFoundError: () => NotFoundError,
38
46
  RateLimitedError: () => RateLimitedError,
@@ -50,6 +58,7 @@ __export(index_exports, {
50
58
  computeSignature: () => computeSignature,
51
59
  getCreditUsage: () => getCreditUsage,
52
60
  isLexAPIError: () => isLexAPIError,
61
+ isNationalDecision: () => isNationalDecision,
53
62
  normalizeRetryAfterSeconds: () => normalizeRetryAfterSeconds,
54
63
  parseResponseHeaders: () => parseResponseHeaders,
55
64
  verifySignature: () => verifySignature,
@@ -109,7 +118,8 @@ var LexAPIError = class _LexAPIError extends Error {
109
118
  /** The `error.details` object from the typed envelope, when present. */
110
119
  details;
111
120
  /**
112
- * Seconds to wait before retrying, when the server said so (429).
121
+ * Seconds to wait before retrying, when the server said so (429; also the
122
+ * 503 of an incomplete national semantic search).
113
123
  * Sourced from the `Retry-After` response HEADER first; the JSON
114
124
  * `retryAfter` body field is only a fallback because it historically
115
125
  * carried buggy epoch-seconds values (epoch-looking values are
@@ -173,7 +183,7 @@ var LexAPIError = class _LexAPIError extends Error {
173
183
  if (typeof record["message"] === "string") message = record["message"];
174
184
  details = record["details"];
175
185
  }
176
- if (retryAfter === void 0 && status === 429) {
186
+ if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
177
187
  const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
178
188
  if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
179
189
  }
@@ -208,6 +218,16 @@ var LexAPIError = class _LexAPIError extends Error {
208
218
  return new TierForbiddenError(message, status, details, retryAfter, context);
209
219
  case "CREDITS_EXHAUSTED":
210
220
  return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt, context);
221
+ case "NATIONAL_ALLOWANCE_EXHAUSTED":
222
+ return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
223
+ case "NATIONAL_SEMANTIC_NOT_ENABLED":
224
+ return new NationalSemanticNotEnabledError(message, status, details, retryAfter, context);
225
+ case "NATIONAL_SEMANTIC_UNAVAILABLE":
226
+ return new NationalSemanticUnavailableError(message, status, details, retryAfter, context);
227
+ case "NATIONAL_SEMANTIC_FILTER_UNREACHABLE":
228
+ return new NationalSemanticFilterUnreachableError(message, status, details, retryAfter, context);
229
+ case "DOCUMENT_WITHDRAWN":
230
+ return new DocumentWithdrawnError(message, status, details, retryAfter, context);
211
231
  case "UPSTREAM_ERROR":
212
232
  return new UpstreamError(message, status, details, retryAfter, context);
213
233
  case "TIMEOUT":
@@ -246,10 +266,27 @@ var InvalidUrlError = class extends LexAPIError {
246
266
  };
247
267
  var InvalidParamsError = class extends LexAPIError {
248
268
  static kind = "InvalidParamsError";
249
- constructor(message, status = 400, details, retryAfter, context) {
250
- super("INVALID_PARAMS", message, status, details, retryAfter, context);
269
+ constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
270
+ super(code, message, status, details, retryAfter, context);
251
271
  this.name = "InvalidParamsError";
252
272
  }
273
+ /**
274
+ * The parameter that was refused, when the server names it — e.g. an
275
+ * unknown citation-graph filter value (API 2.11.0). Read from `details`
276
+ * (typed envelope) or the top level of the body (legacy shape).
277
+ */
278
+ get param() {
279
+ return readString(detailsOrBodyField(this.details, this.body, "param"));
280
+ }
281
+ /** The refused value of {@link param}, when the server echoes it. */
282
+ get value() {
283
+ return detailsOrBodyField(this.details, this.body, "value");
284
+ }
285
+ /** The allowed values of {@link param}, when the server lists them (may be empty). */
286
+ get allowed() {
287
+ const value = detailsOrBodyField(this.details, this.body, "allowed");
288
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
289
+ }
253
290
  };
254
291
  var AuthenticationError = class extends LexAPIError {
255
292
  static kind = "AuthenticationError";
@@ -314,6 +351,33 @@ var CreditsExhaustedError = class extends LexAPIError {
314
351
  return readString(this.details?.operation);
315
352
  }
316
353
  };
354
+ var NationalAllowanceExhaustedError = class extends LexAPIError {
355
+ static kind = "NationalAllowanceExhaustedError";
356
+ constructor(message, status = 402, details, retryAfter, context) {
357
+ super("NATIONAL_ALLOWANCE_EXHAUSTED", message, status, details, retryAfter, context);
358
+ this.name = "NationalAllowanceExhaustedError";
359
+ }
360
+ /** The jurisdiction code of the refused call (`details.jurisdiction`). */
361
+ get jurisdiction() {
362
+ return readString(this.details?.jurisdiction);
363
+ }
364
+ /** The tier's monthly allowance of national calls (`details.limit`). */
365
+ get limit() {
366
+ return readNumber(this.details?.limit);
367
+ }
368
+ /** Always `0` (`details.remaining`). */
369
+ get remaining() {
370
+ return readNumber(this.details?.remaining);
371
+ }
372
+ /** When the allowance resets (`details.resetsAt`, ISO date-time). */
373
+ get resetsAt() {
374
+ return readString(this.details?.resetsAt);
375
+ }
376
+ /** `/pricing` (`details.upgradeUrl`). */
377
+ get upgradeUrl() {
378
+ return readString(this.details?.upgradeUrl);
379
+ }
380
+ };
317
381
  var UpstreamError = class extends LexAPIError {
318
382
  static kind = "UpstreamError";
319
383
  constructor(message, status = 502, details, retryAfter, context) {
@@ -327,14 +391,92 @@ var TimeoutError = class extends LexAPIError {
327
391
  super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
328
392
  this.name = "TimeoutError";
329
393
  }
394
+ /** `true` when the server answered a budget timeout with `partial: true` (nothing else was returned). */
395
+ get partial() {
396
+ const value = bodyField(this.body, "partial");
397
+ return typeof value === "boolean" ? value : void 0;
398
+ }
399
+ /** The server-side budget that expired, in ms, when the body reports it. */
400
+ get serverTimeoutMs() {
401
+ return readNumber(bodyField(this.body, "timeoutMs"));
402
+ }
330
403
  };
331
404
  var ServiceUnavailableError = class extends LexAPIError {
332
405
  static kind = "ServiceUnavailableError";
333
- constructor(message, status = 503, details, retryAfter, context) {
334
- super("SERVICE_UNAVAILABLE", message, status, details, retryAfter, context);
406
+ constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
407
+ super(code, message, status, details, retryAfter, context);
335
408
  this.name = "ServiceUnavailableError";
336
409
  }
337
410
  };
411
+ var NationalSemanticNotEnabledError = class extends LexAPIError {
412
+ static kind = "NationalSemanticNotEnabledError";
413
+ constructor(message, status = 409, details, retryAfter, context) {
414
+ super("NATIONAL_SEMANTIC_NOT_ENABLED", message, status, details, retryAfter, context);
415
+ this.name = "NationalSemanticNotEnabledError";
416
+ }
417
+ /** ISO 3166-1 alpha-2 jurisdiction code (top-level `jurisdiction` on the raw body). */
418
+ get jurisdiction() {
419
+ return readString(bodyField(this.body, "jurisdiction"));
420
+ }
421
+ };
422
+ var NationalSemanticUnavailableError = class extends ServiceUnavailableError {
423
+ static kind = "NationalSemanticUnavailableError";
424
+ constructor(message, status = 503, details, retryAfter, context) {
425
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_UNAVAILABLE");
426
+ this.name = "NationalSemanticUnavailableError";
427
+ }
428
+ get jurisdiction() {
429
+ return readString(bodyField(this.body, "jurisdiction"));
430
+ }
431
+ /**
432
+ * `"SEARCH_INCOMPLETE"` when the index could not complete this search for a
433
+ * temporary reason and there was nothing left to return (an empty answer
434
+ * would not have meant "no matches"). `retryAfter` is then the wait the
435
+ * server asked for — absent once the same search has repeatedly come back
436
+ * incomplete (try again later, or rephrase or narrow it). `undefined` on
437
+ * the plain "index unavailable" 503.
438
+ */
439
+ get partialReason() {
440
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
441
+ }
442
+ };
443
+ var NationalSemanticFilterUnreachableError = class extends InvalidParamsError {
444
+ static kind = "NationalSemanticFilterUnreachableError";
445
+ constructor(message, status = 422, details, retryAfter, context) {
446
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_FILTER_UNREACHABLE");
447
+ this.name = "NationalSemanticFilterUnreachableError";
448
+ }
449
+ get jurisdiction() {
450
+ return readString(bodyField(this.body, "jurisdiction"));
451
+ }
452
+ /** `"SEARCH_INCOMPLETE"`. */
453
+ get partialReason() {
454
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
455
+ }
456
+ };
457
+ var DocumentWithdrawnError = class extends LexAPIError {
458
+ static kind = "DocumentWithdrawnError";
459
+ constructor(message, status = 410, details, retryAfter, context) {
460
+ super("DOCUMENT_WITHDRAWN", message, status, details, retryAfter, context);
461
+ this.name = "DocumentWithdrawnError";
462
+ }
463
+ field(key) {
464
+ const fromDetails = detailsField(this.details, key);
465
+ return fromDetails !== void 0 ? fromDetails : bodyField(this.body, key);
466
+ }
467
+ /** The withdrawn document's id (e.g. `AT-NOR-10001597`). */
468
+ get id() {
469
+ return readString(this.field("id"));
470
+ }
471
+ /** Upper-case jurisdiction code. */
472
+ get jurisdiction() {
473
+ return readString(this.field("jurisdiction"));
474
+ }
475
+ /** ISO date-time the source withdrew the document; `undefined` when unknown. */
476
+ get withdrawnAt() {
477
+ return readString(this.field("withdrawnAt"));
478
+ }
479
+ };
338
480
  var InternalServerError = class extends LexAPIError {
339
481
  static kind = "InternalServerError";
340
482
  constructor(message, status = 500, details, retryAfter, context) {
@@ -412,6 +554,10 @@ function isQuota429(body, headers) {
412
554
  if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
413
555
  return detailsField(body, "retryAfter") === void 0;
414
556
  }
557
+ function detailsOrBodyField(details, body, key) {
558
+ const fromDetails = detailsField(details, key);
559
+ return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
560
+ }
415
561
  function bodyField(body, key) {
416
562
  return detailsField(body, key);
417
563
  }
@@ -473,13 +619,18 @@ function parseResponseHeaders(source) {
473
619
  remaining: int(h, "ratelimit-remaining"),
474
620
  reset: int(h, "ratelimit-reset"),
475
621
  policy: str(h, "ratelimit-policy")
622
+ }),
623
+ nationalAllowance: compact({
624
+ limit: int(h, "x-national-limit"),
625
+ remaining: int(h, "x-national-remaining"),
626
+ resetsAt: str(h, "x-national-reset")
476
627
  })
477
628
  };
478
629
  return compact(parsed) ?? {};
479
630
  }
480
631
 
481
632
  // src/version.ts
482
- var VERSION = "0.2.0";
633
+ var VERSION = "0.4.0";
483
634
 
484
635
  // src/http.ts
485
636
  var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
@@ -610,6 +761,7 @@ var HttpClient = class {
610
761
  headers["content-type"] = "application/json";
611
762
  serializedBody = JSON.stringify(body);
612
763
  }
764
+ let incompleteRetried = false;
613
765
  for (let attempt = 0; ; attempt++) {
614
766
  throwIfAborted(signal, method, path);
615
767
  const controller = new AbortController();
@@ -661,7 +813,9 @@ var HttpClient = class {
661
813
  await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
662
814
  continue;
663
815
  }
664
- if (attempt < maxRetries && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
816
+ const incomplete = error.status === 503 && isSearchIncomplete(error);
817
+ if (attempt < maxRetries && !(incomplete && incompleteRetried) && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
818
+ if (incomplete) incompleteRetried = true;
665
819
  const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
666
820
  await sleep(waitMs, signal, method, path);
667
821
  continue;
@@ -672,6 +826,8 @@ var HttpClient = class {
672
826
  };
673
827
  function shouldRetryStatus(error, call) {
674
828
  const status = error.status;
829
+ if (status === 503 && isBudgetTimeout(error.body)) return false;
830
+ if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
675
831
  if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
676
832
  if (NEVER_REACHED_STATUSES.has(status)) return true;
677
833
  if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
@@ -681,6 +837,13 @@ function shouldRetryStatus(error, call) {
681
837
  if (PROXY_STATUSES.has(status)) return call.free;
682
838
  return false;
683
839
  }
840
+ function isBudgetTimeout(body) {
841
+ return typeof body === "object" && body !== null && body["partialReason"] === "TIMEOUT";
842
+ }
843
+ function isSearchIncomplete(error) {
844
+ const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
845
+ return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
846
+ }
684
847
  async function readBodyText(response, touch) {
685
848
  if (response.body === null || touch === void 0) return response.text();
686
849
  const reader = response.body.getReader();
@@ -1459,12 +1622,24 @@ var LexAPI = class {
1459
1622
  * `GET /citations/cites/{celexNumber}` — documents this one cites
1460
1623
  * (outbound edges), grouped by target. The document must first have been
1461
1624
  * crawled via `extractCitations` to appear here. 1 credit.
1625
+ *
1626
+ * `celexNumber` may be a national document id (e.g. `AT-NOR-10001597`);
1627
+ * `params.includeNational` also pulls in national neighbours of live
1628
+ * jurisdictions — BUSINESS, SCALE and ENTERPRISE only (`403
1629
+ * TierForbiddenError` below that, refunded in full). A national id whose
1630
+ * jurisdiction is not live is `404 NotFoundError`.
1631
+ *
1632
+ * Filters (API 2.11.0): `citationType`, `provenance`, `jurisdictions` and
1633
+ * `resolution` each take one value or a list (sent comma-separated). On a
1634
+ * national id, `unresolved: true` also returns the references the
1635
+ * document records that could not be turned into an edge
1636
+ * (`unresolved` / `unresolvedTruncated`), at no extra cost.
1462
1637
  */
1463
1638
  async getCites(celexNumber, params = {}, options) {
1464
1639
  return this.call({
1465
1640
  method: "GET",
1466
1641
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
1467
- query: edgeQuery(params),
1642
+ query: { ...edgeQuery(params), unresolved: params.unresolved },
1468
1643
  timeoutMs: options?.timeoutMs,
1469
1644
  signal: options?.signal
1470
1645
  });
@@ -1474,6 +1649,10 @@ var LexAPI = class {
1474
1649
  * (inbound edges), grouped by source. 1 credit. For legislation, inbound
1475
1650
  * amendment / corrigendum / repeal edges are refreshed from Cellar when
1476
1651
  * older than 7 days (waits ≤ ~2.5 s) — see `relationSync`.
1652
+ *
1653
+ * `celexNumber` may be a national document id; `params.includeNational`
1654
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
1655
+ * only (`403 TierForbiddenError` below that). Filters as on `getCites`.
1477
1656
  */
1478
1657
  async getCitedBy(celexNumber, params = {}, options) {
1479
1658
  return this.call({
@@ -1520,16 +1699,22 @@ var LexAPI = class {
1520
1699
  * If the server-side wall-clock budget expires the endpoint still
1521
1700
  * returns 200 with `partial: true`, an EMPTY `network`, and `null`
1522
1701
  * paging totals — check `partial` before treating the network as empty.
1702
+ *
1703
+ * `celexNumber` may be a national document id; `params.includeNational`
1704
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
1705
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1523
1706
  */
1524
1707
  async getCitationNetwork(celexNumber, params = {}, options) {
1525
1708
  return this.call({
1526
1709
  method: "GET",
1527
1710
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
1528
1711
  query: {
1529
- citationType: params.citationType,
1712
+ ...filterQuery(params),
1530
1713
  limit: params.limit,
1531
1714
  offset: params.offset,
1532
- language: params.language
1715
+ language: params.language,
1716
+ includeNational: params.includeNational,
1717
+ unresolved: params.unresolved
1533
1718
  },
1534
1719
  timeoutMs: options?.timeoutMs,
1535
1720
  signal: options?.signal
@@ -1540,12 +1725,21 @@ var LexAPI = class {
1540
1725
  * outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
1541
1726
  * not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
1542
1727
  * to 5000 nodes.
1728
+ *
1729
+ * `from`/`to` may be national document ids; `params.includeNational` also
1730
+ * follows national documents of live jurisdictions along the way —
1731
+ * BUSINESS+ only (`403 TierForbiddenError` below that). See `getCites`.
1543
1732
  */
1544
1733
  async getCitationPath(from, to, params = {}, options) {
1545
1734
  return this.call({
1546
1735
  method: "GET",
1547
1736
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
1548
- query: { maxDepth: params.maxDepth, language: params.language },
1737
+ query: {
1738
+ ...filterQuery(params),
1739
+ maxDepth: params.maxDepth,
1740
+ language: params.language,
1741
+ includeNational: params.includeNational
1742
+ },
1549
1743
  timeoutMs: options?.timeoutMs,
1550
1744
  signal: options?.signal
1551
1745
  });
@@ -1555,21 +1749,247 @@ var LexAPI = class {
1555
1749
  * neighbours (documents sharing the most outbound citation targets with
1556
1750
  * the seed). 20 credits. Returns a graceful empty list with `message`
1557
1751
  * when the seed has no outbound citations to couple on.
1752
+ *
1753
+ * `celexNumber` may be a national document id; `params.includeNational`
1754
+ * also considers national documents of live jurisdictions — BUSINESS+
1755
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1558
1756
  */
1559
1757
  async getRelatedDocuments(celexNumber, params = {}, options) {
1560
1758
  return this.call({
1561
1759
  method: "GET",
1562
1760
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
1563
- query: { limit: params.limit, language: params.language },
1761
+ query: {
1762
+ ...filterQuery(params),
1763
+ limit: params.limit,
1764
+ language: params.language,
1765
+ includeNational: params.includeNational
1766
+ },
1564
1767
  timeoutMs: options?.timeoutMs,
1565
1768
  signal: options?.signal
1566
1769
  });
1567
1770
  }
1568
- /** `GET /citations/stats` — global citation graph statistics. 20 credits. */
1569
- async getCitationStats(options) {
1771
+ async getCitationStats(params, options) {
1772
+ let effectiveParams;
1773
+ let effectiveOptions;
1774
+ if (isLegacyCitationStatsCallOptions(params)) {
1775
+ effectiveOptions = params;
1776
+ } else {
1777
+ effectiveParams = params;
1778
+ effectiveOptions = options;
1779
+ }
1570
1780
  return this.call({
1571
1781
  method: "GET",
1572
1782
  path: "/citations/stats",
1783
+ query: { includeNational: effectiveParams?.includeNational },
1784
+ timeoutMs: effectiveOptions?.timeoutMs,
1785
+ signal: effectiveOptions?.signal
1786
+ });
1787
+ }
1788
+ /**
1789
+ * `GET /citations/transposition/{celexNumber}` — the measures the member
1790
+ * states notified to the Commission for an EU act (CELEX sector 3),
1791
+ * grouped by country, from the Publications Office's Cellar records of the
1792
+ * notifications (API 2.11.0). **A notification is not a finding that the
1793
+ * measure transposes the act, or transposes it completely** — `note` says
1794
+ * so on every answer. 5 credits, every plan; a 5xx is refunded.
1795
+ *
1796
+ * On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the answer
1797
+ * also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
1798
+ * `resolutionBasis`, `counts.resolved`, `source.lanes`) and adds the
1799
+ * documents whose national source records that they transpose or
1800
+ * implement the act (`provenance: "source"`); `resolvedOnly: true` keeps
1801
+ * only the held ones. Below BUSINESS, for a jurisdiction that is not live,
1802
+ * and while the national-source terms are not accepted (`termsRequired:
1803
+ * true` — never a 403) those fields are `null`.
1804
+ *
1805
+ * A CELEX that is not an EU act (sector 3) is `404 NotFoundError`.
1806
+ */
1807
+ async getTransposition(celexNumber, params = {}, options) {
1808
+ return this.call({
1809
+ method: "GET",
1810
+ path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
1811
+ query: {
1812
+ jurisdictions: listParam(params.jurisdictions),
1813
+ resolvedOnly: params.resolvedOnly,
1814
+ language: params.language
1815
+ },
1816
+ timeoutMs: options?.timeoutMs,
1817
+ signal: options?.signal
1818
+ });
1819
+ }
1820
+ /**
1821
+ * `GET /citations/counterparts/{id}` — a national document's counterparts
1822
+ * in the other live jurisdictions, through the EU acts it transposes or
1823
+ * implements (API 2.11.0). Each `via[]` entry is one EU act, with the
1824
+ * other jurisdictions' measures for it ranked `1` (the national source
1825
+ * records the relation), `2` (a notified measure LexAPI holds) or `3` (a
1826
+ * notified Cellar record LexAPI does not hold, `id: null`). An EU act
1827
+ * CELEX as `id` lists its own measures the same way.
1828
+ *
1829
+ * **20 credits; BUSINESS, SCALE and ENTERPRISE only** (`403
1830
+ * TierForbiddenError` below that, refunded). A lookup past its 20-second
1831
+ * server-side budget throws `TimeoutError` (503, `err.partial === true`),
1832
+ * refunded. The SDK does not retry it (the same lookup would hit the same
1833
+ * budget); retry yourself, or narrow with `jurisdictions`.
1834
+ */
1835
+ async getCounterparts(id, params = {}, options) {
1836
+ return this.call({
1837
+ method: "GET",
1838
+ path: `/citations/counterparts/${encodeURIComponent(id)}`,
1839
+ query: {
1840
+ jurisdictions: listParam(params.jurisdictions),
1841
+ language: params.language
1842
+ },
1843
+ timeoutMs: options?.timeoutMs,
1844
+ signal: options?.signal
1845
+ });
1846
+ }
1847
+ // ── National law ──────────────────────────────────────────────────
1848
+ // Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS and
1849
+ // above get full access; FREE/STARTER/PROFESSIONAL get it within a
1850
+ // monthly allowance of national calls (`X-National-Limit`/
1851
+ // `X-National-Remaining`/`X-National-Reset`, `result.headers.nationalAllowance`;
1852
+ // a used-up allowance is `NationalAllowanceExhaustedError`, 402). An
1853
+ // unlaunched or unknown jurisdiction answers 404 exactly like a path that
1854
+ // doesn't exist — call `getNationalCoverage()` first.
1855
+ /**
1856
+ * `GET /national/coverage` — which jurisdictions are live, what each one
1857
+ * covers (legislation / case law, semantic search, sources with their
1858
+ * attribution), and when each was last synced. Public: no API key or
1859
+ * allowance required, free.
1860
+ */
1861
+ async getNationalCoverage(options) {
1862
+ return this.call({
1863
+ method: "GET",
1864
+ path: "/national/coverage",
1865
+ free: true,
1866
+ timeoutMs: options?.timeoutMs,
1867
+ signal: options?.signal
1868
+ });
1869
+ }
1870
+ /**
1871
+ * `GET /{jurisdiction}/documents/{id}` — one national document by its
1872
+ * corpus id (e.g. `"AT-NOR-12345"`), analogous to `getDocument`.
1873
+ *
1874
+ * **Cost: 1 credit** — every national read is a corpus read (there is no
1875
+ * live-fetch fallback), so the 5-credit upfront reservation always
1876
+ * settles to 1 (an unknown id too). Check
1877
+ * `document.textAvailability.available` before reading `content`, and
1878
+ * always show `document.attribution` to the user alongside the text.
1879
+ * The document has one shape for every jurisdiction (API 2.8.0):
1880
+ * `documentKind` (`act` | `decision`), `decision` (court, chamber,
1881
+ * caseNumbers, citedNorms — `null` for acts; see `isNationalDecision`)
1882
+ * and the closed `content` key set.
1883
+ *
1884
+ * A document its source withdrew (a takedown, a pseudonymisation fix)
1885
+ * throws `DocumentWithdrawnError` (410) instead of answering — nothing of
1886
+ * it is served, not even the title; drop any copy you hold.
1887
+ */
1888
+ async getNationalDocument(jurisdiction, id, params = {}, options) {
1889
+ return this.call({
1890
+ method: "GET",
1891
+ path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
1892
+ query: { language: params.language },
1893
+ timeoutMs: options?.timeoutMs,
1894
+ signal: options?.signal
1895
+ });
1896
+ }
1897
+ /**
1898
+ * `GET /{jurisdiction}/documents` — browse a jurisdiction's corpus by
1899
+ * title (`q`), type, and in-force status. Newest-first by the document's
1900
+ * own date.
1901
+ *
1902
+ * **Cost: 3 credits per call** — flat; pagination does not multiply the
1903
+ * price, unlike `search`. **Paging:** `page` only reaches the first 1,000
1904
+ * rows (a 400 past that); page further with `cursor` (each response's
1905
+ * `nextCursor`), which works at any depth — see
1906
+ * `paginateNationalDocuments` for a ready-made walk. A slow page is a
1907
+ * retry-safe `TimeoutError` (504, refunded); the `total` count is capped
1908
+ * at 10,000 and flagged `totalExact: false` past that or on a slow count.
1909
+ */
1910
+ async listNationalDocuments(jurisdiction, params = {}, options) {
1911
+ return this.call({
1912
+ method: "GET",
1913
+ path: `/${jurisdictionSegment(jurisdiction)}/documents`,
1914
+ query: {
1915
+ page: params.page,
1916
+ cursor: params.cursor,
1917
+ limit: params.limit,
1918
+ q: params.q,
1919
+ type: params.documentType,
1920
+ includeRepealed: params.includeRepealed
1921
+ },
1922
+ timeoutMs: options?.timeoutMs,
1923
+ signal: options?.signal
1924
+ });
1925
+ }
1926
+ /**
1927
+ * Walk every page of `listNationalDocuments` via `cursor` (works past the
1928
+ * 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
1929
+ * a separate billed call. Stops after a page with `hasMore: false` (or an
1930
+ * empty page). Any `params.page` is ignored and never sent — pass
1931
+ * `params.cursor` only to resume a walk you saved partway through;
1932
+ * `page` together with `cursor` is a 400 ("Use either cursor or page,
1933
+ * not both"), so this strips `page` at runtime, not just in the type
1934
+ * (`Omit` alone only guards TypeScript callers — a JS caller, or one
1935
+ * using `as`, could otherwise still pass it through).
1936
+ */
1937
+ async *paginateNationalDocuments(jurisdiction, params = {}, options) {
1938
+ const { page: _ignoredPage, ...rest } = params;
1939
+ let cursor = rest.cursor;
1940
+ for (; ; ) {
1941
+ const page = await this.listNationalDocuments(
1942
+ jurisdiction,
1943
+ cursor !== void 0 ? { ...rest, cursor } : { ...rest },
1944
+ options
1945
+ );
1946
+ yield page;
1947
+ if (!page.hasMore || !page.nextCursor || page.results.length === 0) return;
1948
+ cursor = page.nextCursor;
1949
+ }
1950
+ }
1951
+ /**
1952
+ * `POST /{jurisdiction}/search/semantic` — embedding-based semantic
1953
+ * search over a jurisdiction's case law. Same request/response shape as
1954
+ * `semanticSearch`, plus `jurisdiction`/`documentId`/`attribution` and
1955
+ * `document` (the matched decision as the listing returns it — the same
1956
+ * fields in every jurisdiction, API 2.8.0) on every hit.
1957
+ *
1958
+ * **Cost: a flat 5 credits** — `hyde` is accepted but never changes the
1959
+ * price or the billing tier here: the national index never rewrites, so
1960
+ * the response reports `hyde: false` (never `true`) when requested.
1961
+ */
1962
+ async nationalSemanticSearch(jurisdiction, request, options) {
1963
+ return this.call({
1964
+ method: "POST",
1965
+ path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
1966
+ body: nationalSemanticWireBody(request),
1967
+ idempotent: true,
1968
+ timeoutMs: options?.timeoutMs,
1969
+ signal: options?.signal
1970
+ });
1971
+ }
1972
+ /**
1973
+ * `POST /{jurisdiction}/legislation/semantic` — embedding-based semantic
1974
+ * search over a jurisdiction's legislation; article-level matches. Same
1975
+ * shape as `semanticLegislationSearch`, plus `jurisdiction`/`documentId`/
1976
+ * `attribution` and `document` (the matched act's listing summary) on
1977
+ * every hit; the index fields (`law_title`, `article_ref`, `section`,
1978
+ * `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
1979
+ * always present, `null` when the index has nothing (API 2.8.0). No `hyde`, no `asOf` — both are EU-only.
1980
+ * `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
1981
+ * never forwards one on this call even if a caller bypasses the type
1982
+ * system — the server now validates `hyde` as a boolean on this route too
1983
+ * (400 otherwise), so a stray non-boolean value would 400 for nothing.
1984
+ *
1985
+ * **Cost: 5 credits.**
1986
+ */
1987
+ async nationalLegislationSemanticSearch(jurisdiction, request, options) {
1988
+ return this.call({
1989
+ method: "POST",
1990
+ path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
1991
+ body: nationalSemanticWireBody(request, { allowHyde: false }),
1992
+ idempotent: true,
1573
1993
  timeoutMs: options?.timeoutMs,
1574
1994
  signal: options?.signal
1575
1995
  });
@@ -1706,12 +2126,39 @@ function semanticWireBody(request) {
1706
2126
  if (request.asOf !== void 0) body["asOf"] = request.asOf;
1707
2127
  return body;
1708
2128
  }
2129
+ function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2130
+ const body = { query: request.query };
2131
+ if (request.limit !== void 0) body["limit"] = request.limit;
2132
+ if (request.minScore !== void 0) body["min_score"] = request.minScore;
2133
+ if (request.language !== void 0) body["language"] = request.language;
2134
+ if (request.includeText) body["include"] = ["text"];
2135
+ if (request.filters !== void 0) body["filters"] = request.filters;
2136
+ if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
2137
+ return body;
2138
+ }
2139
+ function jurisdictionSegment(jurisdiction) {
2140
+ return encodeURIComponent(jurisdiction.trim().toLowerCase());
2141
+ }
2142
+ function isLegacyCitationStatsCallOptions(value) {
2143
+ if (!value || typeof value !== "object") return false;
2144
+ if ("includeNational" in value) return false;
2145
+ return "timeoutMs" in value || "signal" in value;
2146
+ }
2147
+ function filterQuery(params) {
2148
+ return {
2149
+ citationType: listParam(params.citationType),
2150
+ provenance: listParam(params.provenance),
2151
+ jurisdictions: listParam(params.jurisdictions),
2152
+ resolution: listParam(params.resolution)
2153
+ };
2154
+ }
1709
2155
  function edgeQuery(params) {
1710
2156
  return {
1711
- citationType: params.citationType,
2157
+ ...filterQuery(params),
1712
2158
  limit: params.limit,
1713
2159
  offset: params.offset,
1714
- language: params.language
2160
+ language: params.language,
2161
+ includeNational: params.includeNational
1715
2162
  };
1716
2163
  }
1717
2164
  function timestampParam(value) {
@@ -1856,6 +2303,30 @@ async function verifyWebhook(rawBody, signature, secret, options = {}) {
1856
2303
  }
1857
2304
 
1858
2305
  // src/types.ts
2306
+ var CITATION_TYPES = [
2307
+ "reference",
2308
+ "amendment",
2309
+ "repeal",
2310
+ "corrigendum",
2311
+ "implementation",
2312
+ "legal-basis",
2313
+ "proposal",
2314
+ "transposition"
2315
+ ];
2316
+ var CITATION_PROVENANCES = [
2317
+ "notice",
2318
+ "cellar",
2319
+ "notice+cellar",
2320
+ "cellar-nim",
2321
+ "source",
2322
+ "resolver"
2323
+ ];
2324
+ var CITATION_RESOLUTIONS = [
2325
+ "id",
2326
+ "key",
2327
+ "abbreviation",
2328
+ "text-pattern"
2329
+ ];
1859
2330
  var AS_OF_REASONS = [
1860
2331
  "not_yet_adopted",
1861
2332
  "not_yet_in_force",
@@ -1877,13 +2348,20 @@ var AS_OF_REASONS = [
1877
2348
  "insufficient_credits",
1878
2349
  "credit_check_failed"
1879
2350
  ];
2351
+ function isNationalDecision(document2) {
2352
+ return document2.documentKind === "decision" && document2.decision != null;
2353
+ }
1880
2354
  // Annotate the CommonJS export names for ESM import in node:
1881
2355
  0 && (module.exports = {
1882
2356
  AS_OF_REASONS,
1883
2357
  AuthenticationError,
2358
+ CITATION_PROVENANCES,
2359
+ CITATION_RESOLUTIONS,
2360
+ CITATION_TYPES,
1884
2361
  CreditsExhaustedError,
1885
2362
  DEFAULT_BASE_URL,
1886
2363
  DEFAULT_TIMEOUT_MS,
2364
+ DocumentWithdrawnError,
1887
2365
  IncompleteExportError,
1888
2366
  InternalServerError,
1889
2367
  InvalidCelexError,
@@ -1892,6 +2370,10 @@ var AS_OF_REASONS = [
1892
2370
  InvalidUrlError,
1893
2371
  LexAPI,
1894
2372
  LexAPIError,
2373
+ NationalAllowanceExhaustedError,
2374
+ NationalSemanticFilterUnreachableError,
2375
+ NationalSemanticNotEnabledError,
2376
+ NationalSemanticUnavailableError,
1895
2377
  NetworkError,
1896
2378
  NotFoundError,
1897
2379
  RateLimitedError,
@@ -1909,6 +2391,7 @@ var AS_OF_REASONS = [
1909
2391
  computeSignature,
1910
2392
  getCreditUsage,
1911
2393
  isLexAPIError,
2394
+ isNationalDecision,
1912
2395
  normalizeRetryAfterSeconds,
1913
2396
  parseResponseHeaders,
1914
2397
  verifySignature,