@lexapi/client 0.1.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
@@ -20,25 +20,49 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AS_OF_REASONS: () => AS_OF_REASONS,
23
24
  AuthenticationError: () => AuthenticationError,
25
+ CITATION_PROVENANCES: () => CITATION_PROVENANCES,
26
+ CITATION_RESOLUTIONS: () => CITATION_RESOLUTIONS,
27
+ CITATION_TYPES: () => CITATION_TYPES,
24
28
  CreditsExhaustedError: () => CreditsExhaustedError,
25
29
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
26
30
  DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
31
+ DocumentWithdrawnError: () => DocumentWithdrawnError,
32
+ IncompleteExportError: () => IncompleteExportError,
27
33
  InternalServerError: () => InternalServerError,
28
34
  InvalidCelexError: () => InvalidCelexError,
29
35
  InvalidParamsError: () => InvalidParamsError,
36
+ InvalidResponseError: () => InvalidResponseError,
30
37
  InvalidUrlError: () => InvalidUrlError,
31
38
  LexAPI: () => LexAPI,
32
39
  LexAPIError: () => LexAPIError,
40
+ NationalAllowanceExhaustedError: () => NationalAllowanceExhaustedError,
41
+ NationalSemanticFilterUnreachableError: () => NationalSemanticFilterUnreachableError,
42
+ NationalSemanticNotEnabledError: () => NationalSemanticNotEnabledError,
43
+ NationalSemanticUnavailableError: () => NationalSemanticUnavailableError,
33
44
  NetworkError: () => NetworkError,
34
45
  NotFoundError: () => NotFoundError,
35
46
  RateLimitedError: () => RateLimitedError,
47
+ RequestAbortedError: () => RequestAbortedError,
48
+ ServiceUnavailableError: () => ServiceUnavailableError,
36
49
  TierForbiddenError: () => TierForbiddenError,
37
50
  TimeoutError: () => TimeoutError,
38
51
  UpstreamError: () => UpstreamError,
39
52
  VERSION: () => VERSION,
53
+ WEBHOOK_DELIVERY_HEADER: () => WEBHOOK_DELIVERY_HEADER,
54
+ WEBHOOK_ID_HEADER: () => WEBHOOK_ID_HEADER,
55
+ WEBHOOK_SIGNATURE_HEADER: () => WEBHOOK_SIGNATURE_HEADER,
56
+ WebhookSignatureError: () => WebhookSignatureError,
40
57
  WebhooksAPI: () => WebhooksAPI,
41
- getCreditUsage: () => getCreditUsage
58
+ computeSignature: () => computeSignature,
59
+ getCreditUsage: () => getCreditUsage,
60
+ isLexAPIError: () => isLexAPIError,
61
+ isNationalDecision: () => isNationalDecision,
62
+ normalizeRetryAfterSeconds: () => normalizeRetryAfterSeconds,
63
+ parseResponseHeaders: () => parseResponseHeaders,
64
+ verifySignature: () => verifySignature,
65
+ verifyWebhook: () => verifyWebhook
42
66
  });
43
67
  module.exports = __toCommonJS(index_exports);
44
68
 
@@ -50,10 +74,43 @@ var STATUS_TO_CODE = {
50
74
  403: "TIER_FORBIDDEN",
51
75
  404: "NOT_FOUND",
52
76
  429: "RATE_LIMITED",
77
+ 500: "INTERNAL",
53
78
  502: "UPSTREAM_ERROR",
54
- 504: "TIMEOUT"
79
+ 503: "SERVICE_UNAVAILABLE",
80
+ 504: "TIMEOUT",
81
+ // Cloudflare edge errors (non-JSON bodies). SDK contract §1.3.
82
+ 520: "UPSTREAM_ERROR",
83
+ 521: "UPSTREAM_ERROR",
84
+ 522: "UPSTREAM_ERROR",
85
+ 523: "UPSTREAM_ERROR",
86
+ 524: "TIMEOUT"
55
87
  };
88
+ var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
89
+ function collectKinds(ctor) {
90
+ const kinds = [];
91
+ let current = ctor;
92
+ while (typeof current === "function") {
93
+ const kind = current.kind;
94
+ if (Object.prototype.hasOwnProperty.call(current, "kind") && typeof kind === "string") {
95
+ kinds.push(kind);
96
+ }
97
+ current = Object.getPrototypeOf(current);
98
+ }
99
+ return kinds;
100
+ }
101
+ function brandedHasInstance(ctor, value) {
102
+ if (typeof value !== "object" || value === null) return false;
103
+ if (Function.prototype[Symbol.hasInstance].call(ctor, value)) return true;
104
+ if (!Object.prototype.hasOwnProperty.call(ctor, "kind")) return false;
105
+ const kinds = value[ERROR_KINDS];
106
+ return Array.isArray(kinds) && kinds.includes(ctor.kind);
107
+ }
56
108
  var LexAPIError = class _LexAPIError extends Error {
109
+ /** Stable class tag used by the cross-build `instanceof` brand check. */
110
+ static kind = "LexAPIError";
111
+ static [Symbol.hasInstance](value) {
112
+ return brandedHasInstance(this, value);
113
+ }
57
114
  /** Stable machine-readable code (`error.code`, or derived from the HTTP status for legacy bodies). */
58
115
  code;
59
116
  /** HTTP status. `0` for client-side failures (network error, client-side timeout). */
@@ -61,27 +118,41 @@ var LexAPIError = class _LexAPIError extends Error {
61
118
  /** The `error.details` object from the typed envelope, when present. */
62
119
  details;
63
120
  /**
64
- * 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).
65
123
  * Sourced from the `Retry-After` response HEADER first; the JSON
66
124
  * `retryAfter` body field is only a fallback because it historically
67
125
  * carried buggy epoch-seconds values (epoch-looking values are
68
126
  * normalized to a delta).
69
127
  */
70
128
  retryAfter;
71
- constructor(code, message, status, details, retryAfter) {
129
+ /**
130
+ * The parsed JSON error body, verbatim. Useful for legacy-shape fields the
131
+ * typed properties don't cover (`upgradeUrl` on tier gates, `current` /
132
+ * `limit` on the webhook ceiling, `usage` on legacy quota 429s).
133
+ */
134
+ body;
135
+ /** Parsed response headers, when the error came from an HTTP response. */
136
+ headers;
137
+ constructor(code, message, status, details, retryAfter, context) {
72
138
  super(`[${code}] ${message} (HTTP ${status})`);
73
139
  this.name = "LexAPIError";
74
140
  this.code = code;
75
141
  this.status = status;
76
142
  this.details = details;
77
143
  this.retryAfter = retryAfter;
144
+ this.body = context?.body;
145
+ this.headers = context?.headers;
146
+ Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
78
147
  }
79
148
  /**
80
149
  * Build the most specific error subclass for a non-2xx response.
81
150
  * Accepts both the typed envelope and the legacy bare `{error, message}` shape.
82
151
  */
83
- static fromResponse(status, body, headerRetryAfter) {
84
- let code = STATUS_TO_CODE[status] ?? "INTERNAL";
152
+ static fromResponse(status, body, headerRetryAfter, headers) {
153
+ const statusCode = STATUS_TO_CODE[status];
154
+ let code = statusCode ?? "INTERNAL";
155
+ let typedCode = false;
85
156
  let message = `HTTP ${status}`;
86
157
  let details;
87
158
  let retryAfter = headerRetryAfter;
@@ -91,125 +162,373 @@ var LexAPIError = class _LexAPIError extends Error {
91
162
  const err = record["error"];
92
163
  if (typeof err === "object" && err !== null) {
93
164
  const e = err;
94
- if (typeof e["code"] === "string") code = e["code"];
165
+ if (typeof e["code"] === "string") {
166
+ code = e["code"];
167
+ typedCode = true;
168
+ }
95
169
  if (typeof e["message"] === "string") message = e["message"];
96
170
  details = e["details"];
97
171
  } else if (typeof err === "string") {
172
+ if (typeof record["code"] === "string" && record["code"] !== "") {
173
+ code = record["code"];
174
+ typedCode = true;
175
+ }
98
176
  message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
99
- } else if (typeof record["message"] === "string") {
100
- message = record["message"];
177
+ details = record["details"];
178
+ } else {
179
+ if (typeof record["code"] === "string" && record["code"] !== "") {
180
+ code = record["code"];
181
+ typedCode = true;
182
+ }
183
+ if (typeof record["message"] === "string") message = record["message"];
184
+ details = record["details"];
101
185
  }
102
- if (retryAfter === void 0) {
186
+ if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
103
187
  const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
104
188
  if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
105
189
  }
106
190
  resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
107
191
  }
192
+ const context = { body, ...headers ? { headers } : {} };
193
+ if (!typedCode && statusCode === void 0 && status < 500) {
194
+ return new _LexAPIError(code, message, status, details, retryAfter, context);
195
+ }
196
+ if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
197
+ return new RateLimitedError(
198
+ message,
199
+ status,
200
+ details,
201
+ void 0,
202
+ context,
203
+ code === "QUOTA_EXHAUSTED" ? "QUOTA_EXHAUSTED" : "RATE_LIMITED"
204
+ );
205
+ }
108
206
  switch (code) {
109
207
  case "NOT_FOUND":
110
- return new NotFoundError(message, status, details, retryAfter);
208
+ return new NotFoundError(message, status, details, retryAfter, context);
111
209
  case "INVALID_CELEX":
112
- return new InvalidCelexError(message, status, details, retryAfter);
210
+ return new InvalidCelexError(message, status, details, retryAfter, context);
113
211
  case "INVALID_URL":
114
- return new InvalidUrlError(message, status, details, retryAfter);
212
+ return new InvalidUrlError(message, status, details, retryAfter, context);
115
213
  case "INVALID_PARAMS":
116
- return new InvalidParamsError(message, status, details, retryAfter);
214
+ return new InvalidParamsError(message, status, details, retryAfter, context);
117
215
  case "RATE_LIMITED":
118
- return new RateLimitedError(message, status, details, retryAfter);
216
+ return new RateLimitedError(message, status, details, retryAfter, context);
119
217
  case "TIER_FORBIDDEN":
120
- return new TierForbiddenError(message, status, details, retryAfter);
218
+ return new TierForbiddenError(message, status, details, retryAfter, context);
121
219
  case "CREDITS_EXHAUSTED":
122
- return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt);
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);
123
231
  case "UPSTREAM_ERROR":
124
- return new UpstreamError(message, status, details, retryAfter);
232
+ return new UpstreamError(message, status, details, retryAfter, context);
125
233
  case "TIMEOUT":
126
- return new TimeoutError(message, status, details, retryAfter);
234
+ return new TimeoutError(message, status, details, retryAfter, context);
127
235
  case "UNAUTHORIZED":
128
- return new AuthenticationError(message, status, details, retryAfter);
236
+ return new AuthenticationError(message, status, details, retryAfter, context);
237
+ case "SERVICE_UNAVAILABLE":
238
+ return new ServiceUnavailableError(message, status, details, retryAfter, context);
129
239
  case "INTERNAL":
130
- return new InternalServerError(message, status, details, retryAfter);
240
+ return new InternalServerError(message, status, details, retryAfter, context);
131
241
  default:
132
- return new _LexAPIError(code, message, status, details, retryAfter);
242
+ return new _LexAPIError(code, message, status, details, retryAfter, context);
133
243
  }
134
244
  }
135
245
  };
136
246
  var NotFoundError = class extends LexAPIError {
137
- constructor(message, status = 404, details, retryAfter) {
138
- super("NOT_FOUND", message, status, details, retryAfter);
247
+ static kind = "NotFoundError";
248
+ constructor(message, status = 404, details, retryAfter, context) {
249
+ super("NOT_FOUND", message, status, details, retryAfter, context);
139
250
  this.name = "NotFoundError";
140
251
  }
141
252
  };
142
253
  var InvalidCelexError = class extends LexAPIError {
143
- constructor(message, status = 400, details, retryAfter) {
144
- super("INVALID_CELEX", message, status, details, retryAfter);
254
+ static kind = "InvalidCelexError";
255
+ constructor(message, status = 400, details, retryAfter, context) {
256
+ super("INVALID_CELEX", message, status, details, retryAfter, context);
145
257
  this.name = "InvalidCelexError";
146
258
  }
147
259
  };
148
260
  var InvalidUrlError = class extends LexAPIError {
149
- constructor(message, status = 400, details, retryAfter) {
150
- super("INVALID_URL", message, status, details, retryAfter);
261
+ static kind = "InvalidUrlError";
262
+ constructor(message, status = 400, details, retryAfter, context) {
263
+ super("INVALID_URL", message, status, details, retryAfter, context);
151
264
  this.name = "InvalidUrlError";
152
265
  }
153
266
  };
154
267
  var InvalidParamsError = class extends LexAPIError {
155
- constructor(message, status = 400, details, retryAfter) {
156
- super("INVALID_PARAMS", message, status, details, retryAfter);
268
+ static kind = "InvalidParamsError";
269
+ constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
270
+ super(code, message, status, details, retryAfter, context);
157
271
  this.name = "InvalidParamsError";
158
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
+ }
159
290
  };
160
291
  var AuthenticationError = class extends LexAPIError {
161
- constructor(message, status = 401, details, retryAfter) {
162
- super("UNAUTHORIZED", message, status, details, retryAfter);
292
+ static kind = "AuthenticationError";
293
+ constructor(message, status = 401, details, retryAfter, context) {
294
+ super("UNAUTHORIZED", message, status, details, retryAfter, context);
163
295
  this.name = "AuthenticationError";
164
296
  }
165
297
  };
166
298
  var RateLimitedError = class extends LexAPIError {
167
- constructor(message, status = 429, details, retryAfter) {
168
- super("RATE_LIMITED", message, status, details, retryAfter);
299
+ static kind = "RateLimitedError";
300
+ constructor(message, status = 429, details, retryAfter, context, code = "RATE_LIMITED") {
301
+ super(code, message, status, details, retryAfter, context);
169
302
  this.name = "RateLimitedError";
170
303
  }
304
+ /** `RateLimit-*` headers from the 429 response (limit / remaining / reset seconds). */
305
+ get rateLimit() {
306
+ return this.headers?.rateLimit;
307
+ }
308
+ /**
309
+ * `true` for a legacy-plan quota 429 (daily call quota, or the monthly
310
+ * semantic quota) rather than the per-minute limiter (SDK contract §1.2):
311
+ * `code` is `QUOTA_EXHAUSTED`, or — servers before lex-api #304, which
312
+ * send no code — the body carries `usage.resetsAt` with neither a
313
+ * `Retry-After` header nor a `retryAfter` body field. It cannot succeed
314
+ * before `resetsAt`, so the SDK does not retry it and `retryAfter` is
315
+ * `undefined`.
316
+ */
317
+ get quotaExhausted() {
318
+ return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
319
+ }
320
+ /** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
321
+ get resetsAt() {
322
+ return readString(bodyField(this.body, "resetsAt")) ?? readString(detailsField(bodyField(this.body, "usage"), "resetsAt"));
323
+ }
171
324
  };
172
325
  var TierForbiddenError = class extends LexAPIError {
173
- constructor(message, status = 403, details, retryAfter) {
174
- super("TIER_FORBIDDEN", message, status, details, retryAfter);
326
+ static kind = "TierForbiddenError";
327
+ constructor(message, status = 403, details, retryAfter, context) {
328
+ super("TIER_FORBIDDEN", message, status, details, retryAfter, context);
175
329
  this.name = "TierForbiddenError";
176
330
  }
177
331
  };
178
332
  var CreditsExhaustedError = class extends LexAPIError {
333
+ static kind = "CreditsExhaustedError";
179
334
  /** When the monthly credit allowance resets (ISO date-time), when the server said so. */
180
335
  resetsAt;
181
- constructor(message, status = 402, details, retryAfter, resetsAt) {
182
- super("CREDITS_EXHAUSTED", message, status, details, retryAfter);
336
+ constructor(message, status = 402, details, retryAfter, resetsAt, context) {
337
+ super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
183
338
  this.name = "CreditsExhaustedError";
184
339
  this.resetsAt = resetsAt;
185
340
  }
341
+ /** The refused operation's credit weight (`details.weight`). */
342
+ get weight() {
343
+ return readNumber(this.details?.weight);
344
+ }
345
+ /** Credits left in the pool (`details.available`). */
346
+ get available() {
347
+ return readNumber(this.details?.available);
348
+ }
349
+ /** The refused operation (`details.operation`). */
350
+ get operation() {
351
+ return readString(this.details?.operation);
352
+ }
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
+ }
186
380
  };
187
381
  var UpstreamError = class extends LexAPIError {
188
- constructor(message, status = 502, details, retryAfter) {
189
- super("UPSTREAM_ERROR", message, status, details, retryAfter);
382
+ static kind = "UpstreamError";
383
+ constructor(message, status = 502, details, retryAfter, context) {
384
+ super("UPSTREAM_ERROR", message, status, details, retryAfter, context);
190
385
  this.name = "UpstreamError";
191
386
  }
192
387
  };
193
388
  var TimeoutError = class extends LexAPIError {
194
- constructor(message, status = 0, details, retryAfter) {
195
- super("TIMEOUT", message, status, details, retryAfter);
389
+ static kind = "TimeoutError";
390
+ constructor(message, status = 0, details, retryAfter, context) {
391
+ super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
196
392
  this.name = "TimeoutError";
197
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
+ }
403
+ };
404
+ var ServiceUnavailableError = class extends LexAPIError {
405
+ static kind = "ServiceUnavailableError";
406
+ constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
407
+ super(code, message, status, details, retryAfter, context);
408
+ this.name = "ServiceUnavailableError";
409
+ }
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
+ }
198
479
  };
199
480
  var InternalServerError = class extends LexAPIError {
200
- constructor(message, status = 500, details, retryAfter) {
201
- super("INTERNAL", message, status, details, retryAfter);
481
+ static kind = "InternalServerError";
482
+ constructor(message, status = 500, details, retryAfter, context) {
483
+ super("INTERNAL", message, status, details, retryAfter, context);
202
484
  this.name = "InternalServerError";
203
485
  }
204
486
  };
205
487
  var NetworkError = class extends LexAPIError {
488
+ static kind = "NetworkError";
206
489
  cause;
207
490
  constructor(message, cause) {
208
- super("NETWORK_ERROR", message, 0);
491
+ super("CONNECTION_ERROR", message, 0);
209
492
  this.name = "NetworkError";
210
493
  this.cause = cause;
211
494
  }
212
495
  };
496
+ var RequestAbortedError = class extends LexAPIError {
497
+ static kind = "RequestAbortedError";
498
+ cause;
499
+ constructor(message, cause) {
500
+ super("ABORTED", message, 0);
501
+ this.name = "RequestAbortedError";
502
+ this.cause = cause;
503
+ }
504
+ };
505
+ var InvalidResponseError = class extends LexAPIError {
506
+ static kind = "InvalidResponseError";
507
+ constructor(message, status, rawText, context) {
508
+ super("INVALID_RESPONSE", message, status, void 0, void 0, {
509
+ ...context,
510
+ body: rawText === void 0 ? void 0 : rawText.slice(0, 500)
511
+ });
512
+ this.name = "InvalidResponseError";
513
+ }
514
+ };
515
+ var IncompleteExportError = class extends LexAPIError {
516
+ static kind = "IncompleteExportError";
517
+ /** Rows yielded before the stream ended. */
518
+ rowsRead;
519
+ /**
520
+ * @param details the server's `_error` line body (`{ code, message }`) when
521
+ * one arrived; `undefined` for a missing or `complete: false` trailer.
522
+ */
523
+ constructor(message, rowsRead, details) {
524
+ super("INCOMPLETE_EXPORT", message, 0, details);
525
+ this.name = "IncompleteExportError";
526
+ this.rowsRead = rowsRead;
527
+ }
528
+ };
529
+ function isLexAPIError(value, errorClass) {
530
+ return value instanceof (errorClass ?? LexAPIError);
531
+ }
213
532
  function normalizeRetryAfterSeconds(value) {
214
533
  if (!Number.isFinite(value)) return 0;
215
534
  if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
@@ -228,54 +547,211 @@ function detailsField(details, key) {
228
547
  }
229
548
  return void 0;
230
549
  }
550
+ function isQuota429(body, headers) {
551
+ if (detailsField(body, "code") === "QUOTA_EXHAUSTED") return true;
552
+ const resetsAt = detailsField(detailsField(body, "usage"), "resetsAt");
553
+ if (typeof resetsAt !== "string") return false;
554
+ if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
555
+ return detailsField(body, "retryAfter") === void 0;
556
+ }
557
+ function detailsOrBodyField(details, body, key) {
558
+ const fromDetails = detailsField(details, key);
559
+ return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
560
+ }
561
+ function bodyField(body, key) {
562
+ return detailsField(body, key);
563
+ }
231
564
  function usageField(record, key) {
232
565
  return detailsField(record["usage"], key);
233
566
  }
234
567
 
568
+ // src/headers.ts
569
+ function str(headers, name) {
570
+ const value = headers.get(name);
571
+ return value === null ? void 0 : value;
572
+ }
573
+ function int(headers, name) {
574
+ const value = headers.get(name);
575
+ if (value === null) return void 0;
576
+ const parsed = Number.parseInt(value, 10);
577
+ return Number.isNaN(parsed) ? void 0 : parsed;
578
+ }
579
+ function compact(obj) {
580
+ const out = {};
581
+ for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
582
+ return Object.keys(out).length ? out : void 0;
583
+ }
584
+ function parseResponseHeaders(source) {
585
+ const h = "headers" in source ? source.headers : source;
586
+ const textAvailable = str(h, "x-text-available");
587
+ const ignored = str(h, "x-ignored-documenttypes");
588
+ const parsed = {
589
+ source: str(h, "x-source"),
590
+ searchSource: str(h, "x-search-source"),
591
+ searchCache: str(h, "x-search-cache"),
592
+ language: str(h, "x-language"),
593
+ languageFallback: str(h, "x-language-fallback"),
594
+ textAvailable: textAvailable === void 0 ? void 0 : textAvailable !== "false",
595
+ corpusVersion: int(h, "x-corpus-version"),
596
+ corpusFetchedAt: str(h, "x-corpus-fetchedat"),
597
+ cache: str(h, "x-cache"),
598
+ warning: str(h, "x-warning"),
599
+ ignoredDocumentTypes: ignored === void 0 ? void 0 : ignored.split(",").filter(Boolean),
600
+ postFilteredBy: str(h, "x-postfiltered-by"),
601
+ postFilteredKept: str(h, "x-postfiltered-kept"),
602
+ documentTypeFanOut: int(h, "x-documenttype-fanout"),
603
+ languageFilter: str(h, "x-language-filter"),
604
+ languageKept: str(h, "x-language-kept"),
605
+ batch: compact({
606
+ corpusHits: int(h, "x-batch-corpus-hits"),
607
+ cellarServed: int(h, "x-batch-cellar-served"),
608
+ ojRecovered: int(h, "x-batch-oj-recovered"),
609
+ liveFetches: int(h, "x-batch-live-fetches"),
610
+ textUnavailable: int(h, "x-batch-text-unavailable")
611
+ }),
612
+ retryAfter: str(h, "retry-after"),
613
+ apiVersion: str(h, "x-lexapi-version")?.trim() || void 0,
614
+ release: str(h, "x-lexapi-release"),
615
+ languagePartialKept: int(h, "x-language-partial-kept"),
616
+ cacheAge: int(h, "x-cache-age"),
617
+ rateLimit: compact({
618
+ limit: int(h, "ratelimit-limit"),
619
+ remaining: int(h, "ratelimit-remaining"),
620
+ reset: int(h, "ratelimit-reset"),
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")
627
+ })
628
+ };
629
+ return compact(parsed) ?? {};
630
+ }
631
+
235
632
  // src/version.ts
236
- var VERSION = "0.1.0";
633
+ var VERSION = "0.4.0";
237
634
 
238
635
  // src/http.ts
239
636
  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]);
637
+ var DEFAULT_TIMEOUT_MS = 95e3;
638
+ var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
639
+ // DNS
640
+ "ENOTFOUND",
641
+ "EAI_AGAIN",
642
+ // TCP connect
643
+ "ECONNREFUSED",
644
+ "EHOSTUNREACH",
645
+ "ENETUNREACH",
646
+ "UND_ERR_CONNECT_TIMEOUT",
647
+ // TLS certificate verification (handshake)
648
+ "CERT_HAS_EXPIRED",
649
+ "CERT_NOT_YET_VALID",
650
+ "CERT_REVOKED",
651
+ "CERT_UNTRUSTED",
652
+ "CERT_REJECTED",
653
+ "CERT_SIGNATURE_FAILURE",
654
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
655
+ "SELF_SIGNED_CERT_IN_CHAIN",
656
+ "UNABLE_TO_GET_ISSUER_CERT",
657
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
658
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
659
+ "HOSTNAME_MISMATCH",
660
+ "ERR_TLS_CERT_ALTNAME_INVALID",
661
+ // TLS handshake alerts / protocol negotiation
662
+ "ERR_SSL_WRONG_VERSION_NUMBER",
663
+ "ERR_SSL_UNSUPPORTED_PROTOCOL",
664
+ "ERR_SSL_NO_PROTOCOLS_AVAILABLE",
665
+ "ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE",
666
+ "ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION",
667
+ "ERR_SSL_TLSV1_ALERT_UNKNOWN_CA",
668
+ "ERR_SSL_SSLV3_ALERT_BAD_CERTIFICATE",
669
+ "ERR_SSL_SSLV3_ALERT_CERTIFICATE_EXPIRED"
670
+ ]);
671
+ var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
672
+ var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
673
+ var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
674
+ var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
675
+ function isNeverReachedError(error, depth = 0) {
676
+ if (depth > 6 || typeof error !== "object" || error === null) return false;
677
+ const { code, syscall, cause, errors } = error;
678
+ if (typeof code === "string") {
679
+ if (NEVER_REACHED_CODES.has(code)) return true;
680
+ if (CONNECT_SYSCALL_CODES.has(code) && syscall === "connect") return true;
681
+ }
682
+ if (Array.isArray(errors) && errors.length > 0 && errors.every((e) => isNeverReachedError(e, depth + 1))) {
683
+ return true;
684
+ }
685
+ return isNeverReachedError(cause, depth + 1);
686
+ }
687
+ function isAppOrigin(error) {
688
+ return error.headers?.apiVersion !== void 0 || error.headers?.rateLimit?.limit !== void 0;
689
+ }
242
690
  function isBrowserRuntime() {
243
691
  return typeof window !== "undefined" && typeof document !== "undefined";
244
692
  }
693
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
245
694
  var HttpClient = class {
695
+ #apiKey;
246
696
  opts;
247
697
  userAgent;
248
698
  constructor(opts) {
249
- this.opts = opts;
699
+ const { apiKey, ...rest } = opts;
700
+ this.#apiKey = apiKey;
701
+ this.opts = rest;
250
702
  this.userAgent = opts.userAgentSuffix ? `lexapi-typescript/${VERSION} ${opts.userAgentSuffix}` : `lexapi-typescript/${VERSION}`;
251
703
  }
252
- /** Perform a request and parse the JSON body (204 yields `undefined`). */
704
+ /** API base URL. */
705
+ get baseUrl() {
706
+ return this.opts.baseUrl;
707
+ }
708
+ /** Client-level per-attempt timeout (ms). */
709
+ get timeoutMs() {
710
+ return this.opts.timeoutMs;
711
+ }
712
+ /** Redacted view for `JSON.stringify` — never includes the API key. */
713
+ toJSON() {
714
+ return { baseUrl: this.opts.baseUrl, apiKey: "[redacted]" };
715
+ }
716
+ /** Redacted view for `util.inspect` / `console.log`. */
717
+ [INSPECT]() {
718
+ return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
719
+ }
720
+ /** Perform a request and parse the JSON body (204 / empty body yields `{}`). */
253
721
  async requestJson(options) {
254
722
  const { data } = await this.requestJsonWithResponse(options);
255
723
  return data;
256
724
  }
257
- /** Like `requestJson`, but also exposes the raw `Response` (for header signals). */
725
+ /**
726
+ * Like `requestJson`, but also exposes the raw `Response` (for header
727
+ * signals). The body is read inside the attempt, under its timeout.
728
+ */
258
729
  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 };
730
+ return this.execute(options, async (response, ctx) => ({
731
+ data: await readJsonBody(response, ctx.touch),
732
+ response
733
+ }));
264
734
  }
265
735
  /**
266
736
  * 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.
737
+ * consuming the body (streaming endpoints such as `/export`). The attempt
738
+ * timeout covers only the response headers; the caller applies its own
739
+ * idle timeout to body reads. Non-2xx responses are parsed and thrown as
740
+ * typed errors; the retry policy applies before the first body byte.
270
741
  */
271
742
  async requestRaw(options) {
272
- const { method, path, query, body } = options;
743
+ return this.execute(options, async (response) => response);
744
+ }
745
+ async execute(options, onSuccess) {
746
+ const { method, path, query, body, signal } = options;
273
747
  const url = `${this.opts.baseUrl}${path}${buildQuery(query)}`;
274
748
  const timeoutMs = options.timeoutMs ?? this.opts.timeoutMs;
275
- const { maxRetries, baseDelayMs, maxDelayMs } = this.opts.retry;
749
+ const { maxRetries, baseDelayMs, maxDelayMs, retryReadOnlyPosts } = this.opts.retry;
750
+ const isGet = method === "GET";
751
+ const free = isGet && options.free === true;
276
752
  const headers = {
277
- "x-api-key": this.opts.apiKey,
278
- accept: "application/json"
753
+ "x-api-key": this.#apiKey,
754
+ accept: options.accept ?? "application/json"
279
755
  };
280
756
  if (!isBrowserRuntime()) {
281
757
  headers["user-agent"] = this.userAgent;
@@ -285,190 +761,453 @@ var HttpClient = class {
285
761
  headers["content-type"] = "application/json";
286
762
  serializedBody = JSON.stringify(body);
287
763
  }
764
+ let incompleteRetried = false;
288
765
  for (let attempt = 0; ; attempt++) {
766
+ throwIfAborted(signal, method, path);
767
+ const controller = new AbortController();
768
+ let timedOut = false;
769
+ let timer;
770
+ const touch = () => {
771
+ if (timer !== void 0) clearTimeout(timer);
772
+ timer = setTimeout(() => {
773
+ timedOut = true;
774
+ controller.abort();
775
+ }, timeoutMs);
776
+ };
777
+ touch();
778
+ const onAbort = () => controller.abort();
779
+ signal?.addEventListener("abort", onAbort, { once: true });
780
+ let error;
289
781
  let response;
782
+ let retryTransport = false;
290
783
  try {
291
- response = await this.fetchWithTimeout(url, {
784
+ response = await this.opts.fetchFn(url, {
292
785
  method,
293
786
  headers,
294
787
  ...serializedBody !== void 0 ? { body: serializedBody } : {},
295
- timeoutMs
788
+ signal: controller.signal
296
789
  });
790
+ touch();
791
+ if (response.ok) {
792
+ return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
793
+ }
794
+ error = await parseErrorResponse(response, touch);
297
795
  } catch (cause) {
298
- if (cause instanceof TimeoutError) throw cause;
299
- if (attempt < maxRetries && method === "GET") {
300
- await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs));
301
- continue;
796
+ if (signal?.aborted) {
797
+ throw new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason);
302
798
  }
303
- throw new NetworkError(`Network error calling ${method} ${path}`, cause);
799
+ if (cause instanceof LexAPIError && !timedOut) throw cause;
800
+ const failure = timedOut ? new TimeoutError(`No response bytes for ${timeoutMs}ms (${method} ${path})`, 0) : new NetworkError(
801
+ response === void 0 ? `Network error calling ${method} ${path}` : `Connection lost while reading the response to ${method} ${path}`,
802
+ cause
803
+ );
804
+ const neverReached = !timedOut && response === void 0 && isNeverReachedError(cause);
805
+ retryTransport = attempt < maxRetries && (neverReached || free);
806
+ if (!retryTransport) throw failure;
807
+ error = failure;
808
+ } finally {
809
+ if (timer !== void 0) clearTimeout(timer);
810
+ signal?.removeEventListener("abort", onAbort);
304
811
  }
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);
812
+ if (retryTransport) {
813
+ await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
312
814
  continue;
313
815
  }
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);
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;
819
+ const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
820
+ await sleep(waitMs, signal, method, path);
821
+ continue;
330
822
  }
331
- throw cause;
332
- } finally {
333
- clearTimeout(timer);
823
+ throw error;
334
824
  }
335
825
  }
336
826
  };
337
- async function parseErrorResponse(response) {
338
- let body;
827
+ function shouldRetryStatus(error, call) {
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;
831
+ if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
832
+ if (NEVER_REACHED_STATUSES.has(status)) return true;
833
+ if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
834
+ if (isAppOrigin(error)) return call.isGet || call.readOnly;
835
+ return call.free;
836
+ }
837
+ if (PROXY_STATUSES.has(status)) return call.free;
838
+ return false;
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
+ }
847
+ async function readBodyText(response, touch) {
848
+ if (response.body === null || touch === void 0) return response.text();
849
+ const reader = response.body.getReader();
850
+ const decoder = new TextDecoder();
851
+ const parts = [];
852
+ for (; ; ) {
853
+ const { done, value } = await reader.read();
854
+ if (done) break;
855
+ touch();
856
+ parts.push(decoder.decode(value, { stream: true }));
857
+ }
858
+ parts.push(decoder.decode());
859
+ return parts.join("");
860
+ }
861
+ async function readJsonBody(response, touch) {
862
+ if (response.status === 204) return {};
863
+ const text = await readBodyText(response, touch);
864
+ if (text.trim() === "") return {};
339
865
  try {
340
- body = await response.json();
866
+ return JSON.parse(text);
341
867
  } catch {
868
+ throw new InvalidResponseError(
869
+ `Expected a JSON body (HTTP ${response.status}, content-type ${response.headers.get("content-type") ?? "none"})`,
870
+ response.status,
871
+ text,
872
+ { headers: parseResponseHeaders(response) }
873
+ );
874
+ }
875
+ }
876
+ function throwIfAborted(signal, method, path) {
877
+ if (signal?.aborted) {
878
+ throw new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason);
879
+ }
880
+ }
881
+ async function parseErrorResponse(response, touch) {
882
+ let body;
883
+ try {
884
+ const text = await readBodyText(response, touch);
885
+ body = text.trim() === "" ? void 0 : JSON.parse(text);
886
+ } catch (cause) {
887
+ if (!(cause instanceof SyntaxError)) throw cause;
342
888
  body = void 0;
343
889
  }
344
- return LexAPIError.fromResponse(response.status, body, headerRetryAfterSeconds(response));
890
+ const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
891
+ return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
345
892
  }
346
893
  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);
894
+ const raw = response.headers.get("retry-after");
895
+ if (raw === null) return void 0;
896
+ const header = raw.trim();
897
+ if (header === "") return void 0;
898
+ if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
899
+ if (/^[-+]?\d/.test(header)) return void 0;
351
900
  const date = Date.parse(header);
352
901
  if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
353
902
  return void 0;
354
903
  }
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;
904
+ function resetHeaderSeconds(response, name) {
905
+ const raw = response.headers.get(name);
906
+ if (raw === null || raw.trim() === "") return void 0;
907
+ const seconds = Number(raw);
908
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
909
+ return normalizeRetryAfterSeconds(seconds);
364
910
  }
365
911
  function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
366
912
  return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
367
913
  }
368
- function sleep(ms) {
369
- return new Promise((resolve) => setTimeout(resolve, ms));
914
+ function sleep(ms, signal, method, path) {
915
+ return new Promise((resolve, reject) => {
916
+ if (signal?.aborted) {
917
+ reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
918
+ return;
919
+ }
920
+ const onAbort = () => {
921
+ clearTimeout(timer);
922
+ reject(new RequestAbortedError(`Request ${method} ${path} was aborted during a retry wait`, signal?.reason));
923
+ };
924
+ const timer = setTimeout(() => {
925
+ signal?.removeEventListener("abort", onAbort);
926
+ resolve();
927
+ }, ms);
928
+ signal?.addEventListener("abort", onAbort, { once: true });
929
+ });
370
930
  }
371
931
  function buildQuery(query) {
372
932
  if (!query) return "";
373
933
  const params = new URLSearchParams();
374
934
  for (const [key, value] of Object.entries(query)) {
375
- if (value !== void 0) params.set(key, String(value));
935
+ if (value === void 0) continue;
936
+ if (Array.isArray(value)) {
937
+ for (const item of value) {
938
+ params.append(key, String(item));
939
+ }
940
+ } else {
941
+ params.set(key, String(value));
942
+ }
376
943
  }
377
944
  const qs = params.toString();
378
945
  return qs ? `?${qs}` : "";
379
946
  }
380
947
 
381
948
  // src/export.ts
382
- async function* ndjsonLines(body) {
383
- const reader = body.getReader();
384
- const decoder = new TextDecoder();
385
- let buffer = "";
386
- try {
949
+ var NdjsonReader = class {
950
+ constructor(body, options) {
951
+ this.options = options;
952
+ this.reader = body.getReader();
953
+ const { signal } = options;
954
+ if (signal?.aborted) this.cancel();
955
+ else signal?.addEventListener("abort", this.onAbort, { once: true });
956
+ }
957
+ reader;
958
+ decoder = new TextDecoder();
959
+ /** Pieces of the line currently being received. */
960
+ partial = [];
961
+ /** Complete lines not yet handed out. */
962
+ ready = [];
963
+ eof = false;
964
+ released = false;
965
+ /** Data rows handed out so far (for error messages). */
966
+ rows = 0;
967
+ /** Releases the connection the moment the caller aborts — even while nobody is reading. */
968
+ onAbort = () => this.cancel();
969
+ /** Next trimmed, non-empty line, or `undefined` at EOF. */
970
+ async nextLine() {
971
+ const { signal } = this.options;
972
+ if (signal?.aborted) {
973
+ this.cancel();
974
+ throw new RequestAbortedError("Export stream was aborted", signal.reason);
975
+ }
387
976
  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;
977
+ const line = this.ready.shift();
978
+ if (line !== void 0) return line;
979
+ if (this.eof) {
980
+ const tail = this.partial.join("").trim();
981
+ this.partial = [];
982
+ return tail || void 0;
983
+ }
984
+ const chunk = await this.read();
985
+ if (chunk === void 0) {
986
+ this.eof = true;
987
+ this.ingest(this.decoder.decode());
988
+ this.release();
989
+ } else {
990
+ this.ingest(this.decoder.decode(chunk, { stream: true }));
396
991
  }
397
992
  }
398
- buffer += decoder.decode();
399
- const tail = buffer.trim();
400
- if (tail) yield tail;
401
- } finally {
402
- reader.releaseLock();
403
993
  }
994
+ ingest(text) {
995
+ let pos = 0;
996
+ for (; ; ) {
997
+ const newline = text.indexOf("\n", pos);
998
+ if (newline === -1) break;
999
+ this.partial.push(text.slice(pos, newline));
1000
+ const line = this.partial.join("").trim();
1001
+ this.partial = [];
1002
+ if (line) this.ready.push(line);
1003
+ pos = newline + 1;
1004
+ }
1005
+ if (pos < text.length) this.partial.push(text.slice(pos));
1006
+ }
1007
+ async read() {
1008
+ const { idleTimeoutMs, signal } = this.options;
1009
+ if (signal?.aborted) {
1010
+ this.cancel();
1011
+ throw new RequestAbortedError("Export stream was aborted", signal.reason);
1012
+ }
1013
+ let timer;
1014
+ let onAbort;
1015
+ const interruptions = new Promise((_, reject) => {
1016
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
1017
+ timer = setTimeout(() => {
1018
+ reject(
1019
+ new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
1020
+ );
1021
+ }, idleTimeoutMs);
1022
+ }
1023
+ if (signal) {
1024
+ onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
1025
+ signal.addEventListener("abort", onAbort, { once: true });
1026
+ }
1027
+ });
1028
+ try {
1029
+ const result = await Promise.race([this.reader.read(), interruptions]);
1030
+ if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
1031
+ return result.done ? void 0 : result.value;
1032
+ } catch (cause) {
1033
+ this.cancel();
1034
+ if (cause instanceof LexAPIError) throw cause;
1035
+ throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
1036
+ } finally {
1037
+ if (timer !== void 0) clearTimeout(timer);
1038
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Cancel the body immediately (even while a read is pending) and release
1043
+ * the connection. Not awaited: a tee'd (cloned) body only settles
1044
+ * `cancel()` once every branch is cancelled.
1045
+ */
1046
+ cancel() {
1047
+ if (this.released) return;
1048
+ this.eof = true;
1049
+ void this.reader.cancel().catch(() => void 0);
1050
+ this.release();
1051
+ }
1052
+ release() {
1053
+ if (this.released) return;
1054
+ this.released = true;
1055
+ this.options.signal?.removeEventListener("abort", this.onAbort);
1056
+ try {
1057
+ this.reader.releaseLock();
1058
+ } catch {
1059
+ }
1060
+ }
1061
+ };
1062
+ function liftEnvelope(parsed, key) {
1063
+ const inner = parsed[key];
1064
+ if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
1065
+ return { ...inner, ...parsed };
1066
+ }
1067
+ return parsed;
1068
+ }
1069
+ function errorLine(parsed) {
1070
+ const keys = Object.keys(parsed);
1071
+ if (keys.length !== 1 || keys[0] !== "_error") return void 0;
1072
+ const value = parsed._error;
1073
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: String(value) };
404
1074
  }
405
1075
  function parseLine(line) {
406
1076
  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
- );
1077
+ const value = JSON.parse(line);
1078
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1079
+ } catch {
1080
+ return void 0;
415
1081
  }
416
1082
  }
417
1083
  var ExportStreamImpl = class {
418
1084
  meta;
419
1085
  done;
1086
+ error;
420
1087
  headers;
421
1088
  lines;
422
1089
  pendingFirstRow;
423
1090
  consumed = false;
1091
+ invalidLines = 0;
1092
+ get complete() {
1093
+ return this.done !== void 0 && this.done.complete !== false && this.error === void 0;
1094
+ }
1095
+ incomplete(reason) {
1096
+ return new IncompleteExportError(
1097
+ `Export stream is incomplete after ${this.lines.rows} rows: ${reason}`,
1098
+ this.lines.rows,
1099
+ this.error
1100
+ );
1101
+ }
1102
+ failureReason() {
1103
+ if (this.error !== void 0) {
1104
+ return `the server reported an error mid-stream (${String(this.error.code ?? "UNKNOWN")}: ${String(this.error.message ?? "")})`;
1105
+ }
1106
+ return "its _done trailer says complete: false";
1107
+ }
1108
+ get rowsRead() {
1109
+ return this.lines.rows;
1110
+ }
1111
+ get truncated() {
1112
+ if (typeof this.done?.truncated === "boolean") return this.done.truncated;
1113
+ if (this.headers.truncated !== void 0) return this.headers.truncated;
1114
+ if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
1115
+ return void 0;
1116
+ }
424
1117
  constructor(lines, headers) {
425
1118
  this.lines = lines;
426
1119
  this.headers = headers;
427
1120
  }
1121
+ async cancel() {
1122
+ this.consumed = true;
1123
+ this.lines.cancel();
1124
+ }
428
1125
  /** Read the leading line so `meta` is available before iteration starts. */
429
1126
  async init() {
430
- const first = await this.lines.next();
431
- if (first.done) return;
432
- const parsed = parseLine(first.value);
1127
+ let parsed;
1128
+ for (; ; ) {
1129
+ const first = await this.lines.nextLine();
1130
+ if (first === void 0) return;
1131
+ parsed = parseLine(first);
1132
+ if (parsed !== void 0) {
1133
+ const error = errorLine(parsed);
1134
+ if (error === void 0) break;
1135
+ this.error = error;
1136
+ continue;
1137
+ }
1138
+ this.invalidLines++;
1139
+ }
433
1140
  if ("_meta" in parsed) {
434
- this.meta = parsed;
1141
+ this.meta = liftEnvelope(parsed, "_meta");
435
1142
  } else if ("_done" in parsed) {
436
- this.done = parsed;
1143
+ this.done = liftEnvelope(parsed, "_done");
1144
+ this.lines.cancel();
437
1145
  } else {
438
1146
  this.pendingFirstRow = parsed;
439
1147
  }
440
1148
  }
441
1149
  async *[Symbol.asyncIterator]() {
442
1150
  if (this.consumed) {
443
- throw new LexAPIError("INTERNAL", "Export stream already consumed (single-pass)", 0);
1151
+ if (this.complete) return;
1152
+ if (this.done !== void 0 || this.error !== void 0) throw this.incomplete(this.failureReason());
1153
+ throw new IncompleteExportError(
1154
+ `Export stream was ended before its _done trailer (after ${this.lines.rows} rows) \u2014 call export() again to re-read`,
1155
+ this.lines.rows
1156
+ );
444
1157
  }
445
1158
  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;
1159
+ try {
1160
+ if (this.pendingFirstRow !== void 0) {
1161
+ const row = this.pendingFirstRow;
1162
+ this.pendingFirstRow = void 0;
1163
+ this.lines.rows++;
1164
+ yield row;
1165
+ }
1166
+ if (this.done !== void 0) {
1167
+ if (!this.complete) throw this.incomplete(this.failureReason());
457
1168
  return;
458
1169
  }
459
- if ("_meta" in parsed) continue;
460
- yield parsed;
1170
+ for (; ; ) {
1171
+ const line = await this.lines.nextLine();
1172
+ if (line === void 0) {
1173
+ if (this.error !== void 0) throw this.incomplete(this.failureReason());
1174
+ throw new IncompleteExportError(
1175
+ `Export stream ended without its _done trailer after ${this.lines.rows} rows \u2014 the export is incomplete`,
1176
+ this.lines.rows
1177
+ );
1178
+ }
1179
+ const parsed = parseLine(line);
1180
+ if (parsed === void 0) {
1181
+ this.invalidLines++;
1182
+ continue;
1183
+ }
1184
+ if ("_done" in parsed) {
1185
+ this.done = liftEnvelope(parsed, "_done");
1186
+ if (!this.complete) throw this.incomplete(this.failureReason());
1187
+ return;
1188
+ }
1189
+ if ("_meta" in parsed) continue;
1190
+ const error = errorLine(parsed);
1191
+ if (error !== void 0) {
1192
+ this.error = error;
1193
+ continue;
1194
+ }
1195
+ this.lines.rows++;
1196
+ yield parsed;
1197
+ }
1198
+ } finally {
1199
+ this.lines.cancel();
461
1200
  }
462
1201
  }
463
1202
  };
464
- async function createExportStream(response) {
1203
+ async function createExportStream(response, options = {}) {
465
1204
  if (response.body === null) {
466
1205
  throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
467
1206
  }
468
1207
  const totalHeader = response.headers.get("x-export-total");
469
1208
  const streamingHeader = response.headers.get("x-export-streaming");
470
1209
  const truncatedHeader = response.headers.get("x-export-truncated");
471
- const stream = new ExportStreamImpl(ndjsonLines(response.body), {
1210
+ const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
472
1211
  total: totalHeader !== null ? Number(totalHeader) : void 0,
473
1212
  streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
474
1213
  truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
@@ -483,87 +1222,139 @@ var WebhooksAPI = class {
483
1222
  constructor(http) {
484
1223
  this.http = http;
485
1224
  }
1225
+ async call(options) {
1226
+ const { data, response } = await this.http.requestJsonWithResponse(options);
1227
+ if (typeof data !== "object" || data === null) return data;
1228
+ return { ...data, headers: parseResponseHeaders(response) };
1229
+ }
486
1230
  /**
487
1231
  * `GET /webhooks` — every webhook owned by the caller, newest first.
488
1232
  * The `secret` is never returned here (only once, on creation).
489
1233
  */
490
1234
  async list(options) {
491
- return this.http.requestJson({
1235
+ return this.call({
492
1236
  method: "GET",
493
1237
  path: "/webhooks",
494
- timeoutMs: options?.timeoutMs
1238
+ free: true,
1239
+ timeoutMs: options?.timeoutMs,
1240
+ signal: options?.signal
495
1241
  });
496
1242
  }
497
1243
  /**
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).
1244
+ * `POST /webhooks` — needs `searchCriteria`, `watchCelex`, or both. If
1245
+ * `secret` is omitted the server generates one and returns it in this
1246
+ * response ONLY — store it. Rejected with 400 (`InvalidParamsError`):
1247
+ * unsupported criteria or a watch list above the plan limit carry a
1248
+ * `details` list; the tier webhook ceiling (FREE=0, STARTER=2,
1249
+ * PROFESSIONAL=10, BUSINESS=50, SCALE=100, ENTERPRISE=100) has no
1250
+ * `details` — read `current` / `limit` from `error.body`.
503
1251
  */
504
1252
  async create(request, options) {
505
- return this.http.requestJson({
1253
+ return this.call({
506
1254
  method: "POST",
507
1255
  path: "/webhooks",
508
1256
  body: request,
509
- timeoutMs: options?.timeoutMs
1257
+ timeoutMs: options?.timeoutMs,
1258
+ signal: options?.signal
510
1259
  });
511
1260
  }
512
- /** `GET /webhooks/{id}` — full details including the 20 most recent deliveries. */
1261
+ /** `GET /webhooks/{id}` — full details incl. `retryPolicy` and the 20 most recent deliveries. */
513
1262
  async get(id, options) {
514
- return this.http.requestJson({
1263
+ return this.call({
515
1264
  method: "GET",
516
1265
  path: `/webhooks/${encodeURIComponent(id)}`,
517
- timeoutMs: options?.timeoutMs
1266
+ free: true,
1267
+ timeoutMs: options?.timeoutMs,
1268
+ signal: options?.signal
518
1269
  });
519
1270
  }
520
1271
  /**
521
1272
  * `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).
1273
+ * `watchCelex` replaces the whole list; `searchCriteria: null` removes the
1274
+ * criteria (one of the two must remain). Setting `status: "ACTIVE"`
1275
+ * resets `consecutiveFailures`; moving a `FAILED` or `PAUSED` webhook to
1276
+ * `ACTIVE` also re-queues its deliveries from the last 7 days that ran out
1277
+ * of retries (count in `requeuedDeliveries`, 0 otherwise).
524
1278
  */
525
1279
  async update(id, request, options) {
526
- return this.http.requestJson({
1280
+ return this.call({
527
1281
  method: "PUT",
528
1282
  path: `/webhooks/${encodeURIComponent(id)}`,
529
1283
  body: request,
530
- timeoutMs: options?.timeoutMs
1284
+ timeoutMs: options?.timeoutMs,
1285
+ signal: options?.signal
531
1286
  });
532
1287
  }
533
1288
  /**
534
1289
  * `DELETE /webhooks/{id}` — permanently deletes the webhook and its
535
- * delivery history. Resolves on 204; a repeat delete throws
536
- * `NotFoundError`.
1290
+ * delivery history. Resolves with the server's `{ success, message }`
1291
+ * (an empty object plus `headers` on a bodiless 204); a repeat delete
1292
+ * throws `NotFoundError`.
537
1293
  */
538
1294
  async delete(id, options) {
539
- await this.http.requestJson({
1295
+ return this.call({
540
1296
  method: "DELETE",
541
1297
  path: `/webhooks/${encodeURIComponent(id)}`,
542
- timeoutMs: options?.timeoutMs
1298
+ timeoutMs: options?.timeoutMs,
1299
+ signal: options?.signal
543
1300
  });
544
1301
  }
545
1302
  /**
546
1303
  * `POST /webhooks/{id}/test` — synchronously POSTs a `webhook.test`
547
1304
  * payload (HMAC-SHA256 signed via `X-Webhook-Signature`) to the webhook
548
1305
  * URL and returns the upstream result. 10 s timeout; redirects are not
549
- * followed.
1306
+ * followed; not recorded in the delivery history.
550
1307
  */
551
1308
  async test(id, options) {
552
- return this.http.requestJson({
1309
+ return this.call({
553
1310
  method: "POST",
554
1311
  path: `/webhooks/${encodeURIComponent(id)}/test`,
555
- timeoutMs: options?.timeoutMs
1312
+ timeoutMs: options?.timeoutMs,
1313
+ signal: options?.signal
556
1314
  });
557
1315
  }
558
1316
  /** `GET /webhooks/{id}/deliveries` — delivery history, most recent first. */
559
1317
  async deliveries(id, params = {}, options) {
560
- return this.http.requestJson({
1318
+ return this.call({
561
1319
  method: "GET",
562
1320
  path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
1321
+ free: true,
563
1322
  query: { limit: params.limit, offset: params.offset },
564
- timeoutMs: options?.timeoutMs
1323
+ timeoutMs: options?.timeoutMs,
1324
+ signal: options?.signal
565
1325
  });
566
1326
  }
1327
+ /**
1328
+ * Walk the whole delivery history page by page (`limit` per page, default
1329
+ * 50), starting at `offset`, newest first (SDK contract §1.4). Each
1330
+ * delivery is yielded at most once (deduplicated on `id`): a delivery
1331
+ * created during the walk shifts later pages by one. Stops on an empty page
1332
+ * or when the offset reaches `total`. Pages are free (0 credits).
1333
+ *
1334
+ * ```ts
1335
+ * for await (const page of client.webhooks.paginateDeliveries(id)) {
1336
+ * for (const d of page.deliveries) console.log(d.status, d.responseStatus);
1337
+ * }
1338
+ * ```
1339
+ */
1340
+ async *paginateDeliveries(id, params = {}, options) {
1341
+ const limit = params.limit ?? 50;
1342
+ let offset = params.offset ?? 0;
1343
+ const seen = /* @__PURE__ */ new Set();
1344
+ for (; ; ) {
1345
+ const page = await this.deliveries(id, { limit, offset }, options);
1346
+ const count = page.deliveries.length;
1347
+ const fresh = page.deliveries.filter((d) => {
1348
+ if (typeof d.id !== "string") return true;
1349
+ if (seen.has(d.id)) return false;
1350
+ seen.add(d.id);
1351
+ return true;
1352
+ });
1353
+ yield { ...page, deliveries: fresh };
1354
+ offset += count;
1355
+ if (count === 0 || page.total !== void 0 && offset >= page.total) return;
1356
+ }
1357
+ }
567
1358
  };
568
1359
 
569
1360
  // src/client.ts
@@ -584,83 +1375,125 @@ var LexAPI = class {
584
1375
  retry: {
585
1376
  maxRetries: options.retry?.maxRetries ?? 3,
586
1377
  baseDelayMs: options.retry?.baseDelayMs ?? 500,
587
- maxDelayMs: options.retry?.maxDelayMs ?? 3e4
1378
+ maxDelayMs: options.retry?.maxDelayMs ?? 3e4,
1379
+ retryReadOnlyPosts: options.retry?.retryReadOnlyPosts ?? false
588
1380
  },
589
1381
  userAgentSuffix: options.userAgentSuffix
590
1382
  });
591
1383
  this.webhooks = new WebhooksAPI(this.http);
592
1384
  }
1385
+ /** Redacted view for `JSON.stringify` — never includes the API key. */
1386
+ toJSON() {
1387
+ return { client: "LexAPI", http: this.http.toJSON() };
1388
+ }
1389
+ /** Redacted view for `util.inspect` / `console.log` — never includes the API key. */
1390
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1391
+ return `LexAPI { baseUrl: '${this.http.baseUrl}', apiKey: '[redacted]' }`;
1392
+ }
1393
+ /** Perform a JSON request and attach the parsed response headers (+ legacy header fields). */
1394
+ async call(options, extra = {}) {
1395
+ const { data, response } = await this.http.requestJsonWithResponse(options);
1396
+ return withHeaders(data, response, extra.corpusVersion === true);
1397
+ }
593
1398
  /**
594
1399
  * `GET /info` — API capabilities, subscription tier, and current usage.
595
1400
  * Free operation (0 credits); useful as a connection probe.
596
1401
  */
597
1402
  async getInfo(options) {
598
- return this.http.requestJson({
1403
+ return this.call({
599
1404
  method: "GET",
600
1405
  path: "/info",
601
- timeoutMs: options?.timeoutMs
1406
+ free: true,
1407
+ timeoutMs: options?.timeoutMs,
1408
+ signal: options?.signal
602
1409
  });
603
1410
  }
604
1411
  /**
605
1412
  * `POST /search` — search EUR-Lex with structured filters.
606
1413
  *
1414
+ * **Cost: 3 credits per result page** (`maxPages`, tier-clamped), charged
1415
+ * upfront and refunded for pages never fetched; a search that fails
1416
+ * before its first page is refunded in full. Identical searches within
1417
+ * 60 minutes are served from a result cache (`headers.searchCache: "hit"`,
1418
+ * same price) — pass `fresh: true` to force a re-fetch.
1419
+ *
607
1420
  * 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).
1421
+ * are surfaced, not hidden: `truncated` / `truncatedAt` / `truncatedReason`
1422
+ * (tier-capped pagination), `partial` / `partialReason` (an upstream page
1423
+ * timed out, or `source: "corpus"` — EUR-Lex unreachable, answered from
1424
+ * the corpus mirror), `postFilteredBy` (`"date"` → raise `maxPages`),
1425
+ * `ignoredDocumentTypes`, `hint` (zero results → try semantic search), and
1426
+ * `xWarning` (the `X-Warning` header, e.g. `maxPages` clamped).
614
1427
  */
615
1428
  async search(request, options) {
616
- const { data, response } = await this.http.requestJsonWithResponse({
1429
+ return this.call({
617
1430
  method: "POST",
618
1431
  path: "/search",
619
1432
  body: request,
620
- timeoutMs: options?.timeoutMs
1433
+ idempotent: true,
1434
+ timeoutMs: options?.timeoutMs,
1435
+ signal: options?.signal
621
1436
  });
622
- return withHeaderSignals(data, response);
623
1437
  }
624
1438
  /**
625
1439
  * `POST /documentContent` — fetch a single fully-parsed document by CELEX.
626
1440
  *
627
- * Corpus-first with live-scrape fallback (`bypassCorpus: true` forces a
628
- * live read). Use `include`/`fields`/`articleId` to trim the payload.
1441
+ * **Cost: 5 credits, settled by source** — 1 from the LexAPI corpus
1442
+ * (`headers.source === "corpus"`), 4 from the Publications Office Cellar
1443
+ * API (`"cellar"` / `"cellar-oj"`), 5 for a browser fetch (`"live"`).
1444
+ *
1445
+ * Check `document.textAvailability.available` before reading
1446
+ * `document.content`: a document whose text EUR-Lex does not publish is a
1447
+ * 200 with metadata and `content: null` (billed 1 credit), with the reason
1448
+ * and — for base acts — a pointer to the consolidated version. Use
1449
+ * `language` / `acceptLanguages` for other renditions and
1450
+ * `include`/`fields`/`articleId` to trim the payload.
629
1451
  */
630
1452
  async getDocument(request, options) {
631
- return this.http.requestJson({
1453
+ return this.call({
632
1454
  method: "POST",
633
1455
  path: "/documentContent",
634
1456
  body: request,
635
- timeoutMs: options?.timeoutMs
1457
+ idempotent: true,
1458
+ timeoutMs: options?.timeoutMs,
1459
+ signal: options?.signal
636
1460
  });
637
1461
  }
638
1462
  /**
639
1463
  * `POST /documentContent/batch` — fetch multiple documents in one request.
640
1464
  *
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.
1465
+ * **Cost: 5 credits per processed item, settled by source** (corpus 1,
1466
+ * Cellar / OJ 4, browser 5; `headers.batch` has the source counts). The
1467
+ * batch is clamped to the tier ceiling (FREE=1, STARTER=5,
1468
+ * PROFESSIONAL=20, BUSINESS+=50); trimmed items are not charged. Clamping
1469
+ * is surfaced: `trimmed` / `trimmedTo` / `trimmedReason` and `xWarning`.
1470
+ * Per-CELEX failures are collected in `errors`; text-unavailable items
1471
+ * stay in `documents` (counted in `textUnavailable`).
646
1472
  */
647
1473
  async getDocumentsBatch(request, options) {
648
- const { data, response } = await this.http.requestJsonWithResponse({
1474
+ return this.call({
649
1475
  method: "POST",
650
1476
  path: "/documentContent/batch",
651
1477
  body: request,
652
- timeoutMs: options?.timeoutMs
1478
+ idempotent: true,
1479
+ timeoutMs: options?.timeoutMs,
1480
+ signal: options?.signal
653
1481
  });
654
- return withHeaderSignals(data, response);
655
1482
  }
656
1483
  /**
657
1484
  * `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.
1485
+ * days, default 7; up to `limit`, default 50).
1486
+ *
1487
+ * **Cost: 3 credits per result page** (~10 results each, tier-capped);
1488
+ * unfiltered requests are answered from Cellar in one query
1489
+ * (`headers.source === "cellar"`) and settle at a single page. `author`
1490
+ * arrays are sent as repeated query parameters; `documentType` and
1491
+ * `subdomain` take ONE value — EUR-Lex applies only the first of several
1492
+ * on this path (use `search` for multi-type / multi-subdomain queries). `languageFilter`
1493
+ * reports rows dropped by the language post-filter.
661
1494
  */
662
1495
  async getRecentDocuments(params = {}, options) {
663
- const { data, response } = await this.http.requestJsonWithResponse({
1496
+ return this.call({
664
1497
  method: "GET",
665
1498
  path: "/documents/recent",
666
1499
  query: {
@@ -672,62 +1505,72 @@ var LexAPI = class {
672
1505
  language: params.language,
673
1506
  limit: params.limit
674
1507
  },
675
- timeoutMs: options?.timeoutMs
1508
+ timeoutMs: options?.timeoutMs,
1509
+ signal: options?.signal
676
1510
  });
677
- return withHeaderSignals(data, response);
678
1511
  }
679
1512
  /**
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.
1513
+ * `POST /documents/url` — fetch a document by any EUR-Lex URL. Shaped like
1514
+ * `getDocument` plus `sourceUrl` and `extractedCelex` echo-backs. Same
1515
+ * settle-by-source pricing (corpus 1, Cellar 4, browser 5).
683
1516
  */
684
1517
  async getDocumentByUrl(request, options) {
685
- return this.http.requestJson({
1518
+ return this.call({
686
1519
  method: "POST",
687
1520
  path: "/documents/url",
688
1521
  body: request,
689
- timeoutMs: options?.timeoutMs
1522
+ idempotent: true,
1523
+ timeoutMs: options?.timeoutMs,
1524
+ signal: options?.signal
690
1525
  });
691
1526
  }
692
1527
  /**
693
1528
  * `POST /documents/metadata` — metadata only (title, dates, ECLI/ELI,
694
- * keywords, subjects). Skips the body parse: significantly faster and
695
- * cheaper than `getDocument`.
1529
+ * keywords, subjects, URLs). Skips the body parse: faster than
1530
+ * `getDocument`. **Cost: 5 credits, settled by source** (corpus 1, Cellar 4).
696
1531
  */
697
1532
  async getDocumentMetadata(request, options) {
698
- return this.http.requestJson({
1533
+ return this.call({
699
1534
  method: "POST",
700
1535
  path: "/documents/metadata",
701
1536
  body: request,
702
- timeoutMs: options?.timeoutMs
1537
+ idempotent: true,
1538
+ timeoutMs: options?.timeoutMs,
1539
+ signal: options?.signal
703
1540
  });
704
1541
  }
705
1542
  /**
706
1543
  * `POST /resolve` — resolve any legal identifier (bare CELEX, EUR-Lex
707
1544
  * URL, ELI URI, or ECLI) to the canonical CELEX plus access URLs.
1545
+ * 1 credit. ECLIs (and unmappable ELIs) resolve via the corpus
1546
+ * (`resolvedVia: "ecli-corpus"` / `"eli-corpus"`).
708
1547
  */
709
1548
  async resolve(identifier, options) {
710
- return this.http.requestJson({
1549
+ return this.call({
711
1550
  method: "POST",
712
1551
  path: "/resolve",
713
1552
  body: { identifier },
714
- timeoutMs: options?.timeoutMs
1553
+ idempotent: true,
1554
+ timeoutMs: options?.timeoutMs,
1555
+ signal: options?.signal
715
1556
  });
716
1557
  }
717
1558
  // ── 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.
1559
+ // Versions are LexAPI observation snapshots (content-hash changes between
1560
+ // fetches), NOT legal in-force reconstructions; history begins at first
1561
+ // ingestion. For the text in force on a date, use a consolidated CELEX or
1562
+ // semanticLegislationSearch({ asOf }).
721
1563
  /**
722
1564
  * `GET /documents/{celex}/versions` — version history, newest first,
723
1565
  * current version included and flagged. 1 credit.
724
1566
  */
725
1567
  async listDocumentVersions(celex, params = {}, options) {
726
- return this.http.requestJson({
1568
+ return this.call({
727
1569
  method: "GET",
728
1570
  path: `/documents/${encodeURIComponent(celex)}/versions`,
729
1571
  query: { language: params.language },
730
- timeoutMs: options?.timeoutMs
1572
+ timeoutMs: options?.timeoutMs,
1573
+ signal: options?.signal
731
1574
  });
732
1575
  }
733
1576
  /**
@@ -736,13 +1579,13 @@ var LexAPI = class {
736
1579
  * `X-Corpus-Version` response header. 1 credit.
737
1580
  */
738
1581
  async getDocumentVersion(celex, version, params = {}, options) {
739
- const { data, response } = await this.http.requestJsonWithResponse({
1582
+ return this.call({
740
1583
  method: "GET",
741
1584
  path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
742
1585
  query: { language: params.language },
743
- timeoutMs: options?.timeoutMs
744
- });
745
- return withCorpusVersion(data, response);
1586
+ timeoutMs: options?.timeoutMs,
1587
+ signal: options?.signal
1588
+ }, { corpusVersion: true });
746
1589
  }
747
1590
  /**
748
1591
  * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
@@ -751,102 +1594,404 @@ var LexAPI = class {
751
1594
  * carrying the tracking start date. 1 credit.
752
1595
  */
753
1596
  async getDocumentAtDate(celex, date, params = {}, options) {
754
- const { data, response } = await this.http.requestJsonWithResponse({
1597
+ return this.call({
755
1598
  method: "GET",
756
1599
  path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
757
1600
  query: { language: params.language },
758
- timeoutMs: options?.timeoutMs
759
- });
760
- return withCorpusVersion(data, response);
1601
+ timeoutMs: options?.timeoutMs,
1602
+ signal: options?.signal
1603
+ }, { corpusVersion: true });
761
1604
  }
762
1605
  // ── Citations ─────────────────────────────────────────────────────
763
1606
  /**
764
1607
  * `POST /citations/extract` — crawl a document's EUR-Lex metadata page
765
1608
  * for citations and persist them into the graph. Idempotent: an already
766
- * processed document returns immediately with `alreadyExtracted: true`.
1609
+ * processed document returns `alreadyExtracted: true`. 5 credits,
1610
+ * refunded to 1 on `alreadyExtracted`.
767
1611
  */
768
1612
  async extractCitations(celexNumber, options) {
769
- return this.http.requestJson({
1613
+ return this.call({
770
1614
  method: "POST",
771
1615
  path: "/citations/extract",
772
1616
  body: { celexNumber },
773
- timeoutMs: options?.timeoutMs
1617
+ timeoutMs: options?.timeoutMs,
1618
+ signal: options?.signal
774
1619
  });
775
1620
  }
776
1621
  /**
777
1622
  * `GET /citations/cites/{celexNumber}` — documents this one cites
778
1623
  * (outbound edges), grouped by target. The document must first have been
779
- * crawled via `extractCitations` to appear here.
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.
780
1637
  */
781
1638
  async getCites(celexNumber, params = {}, options) {
782
- return this.http.requestJson({
1639
+ return this.call({
783
1640
  method: "GET",
784
1641
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
785
- query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
786
- timeoutMs: options?.timeoutMs
1642
+ query: { ...edgeQuery(params), unresolved: params.unresolved },
1643
+ timeoutMs: options?.timeoutMs,
1644
+ signal: options?.signal
787
1645
  });
788
1646
  }
789
1647
  /**
790
1648
  * `GET /citations/cited-by/{celexNumber}` — documents that cite this one
791
- * (inbound edges), grouped by source.
1649
+ * (inbound edges), grouped by source. 1 credit. For legislation, inbound
1650
+ * amendment / corrigendum / repeal edges are refreshed from Cellar when
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`.
792
1656
  */
793
1657
  async getCitedBy(celexNumber, params = {}, options) {
794
- return this.http.requestJson({
1658
+ return this.call({
795
1659
  method: "GET",
796
1660
  path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
797
- query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
798
- timeoutMs: options?.timeoutMs
1661
+ query: edgeQuery(params),
1662
+ timeoutMs: options?.timeoutMs,
1663
+ signal: options?.signal
799
1664
  });
800
1665
  }
1666
+ /**
1667
+ * Walk every page of `getCites` (offset in edge rows) until a short or
1668
+ * empty page (SDK contract §1.4). Each page is a billed call (1 credit).
1669
+ * Edges are ordered by extraction time only, so edges extracted at the
1670
+ * same instant or during the walk can shift: an edge may repeat or be
1671
+ * missed. A target's edges can straddle a page boundary, so the same
1672
+ * `celexNumber` may appear in two consecutive pages — merge by
1673
+ * `celexNumber` if you need one group per document.
1674
+ */
1675
+ async *paginateCites(celexNumber, params = {}, options) {
1676
+ yield* paginateEdges(
1677
+ (p) => this.getCites(celexNumber, p, options),
1678
+ (page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1679
+ params
1680
+ );
1681
+ }
1682
+ /**
1683
+ * Walk every page of `getCitedBy` (offset in edge rows) until a short or
1684
+ * empty page (SDK contract §1.4). Each page is a billed call (1 credit);
1685
+ * edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
1686
+ * `celexNumber` may appear in two consecutive pages.
1687
+ */
1688
+ async *paginateCitedBy(celexNumber, params = {}, options) {
1689
+ yield* paginateEdges(
1690
+ (p) => this.getCitedBy(celexNumber, p, options),
1691
+ (page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1692
+ params
1693
+ );
1694
+ }
801
1695
  /**
802
1696
  * `GET /citations/network/{celexNumber}` — inbound and outbound
803
- * neighbourhood in one call, paginated per direction.
1697
+ * neighbourhood in one call, paginated per direction. 20 credits.
804
1698
  *
805
1699
  * If the server-side wall-clock budget expires the endpoint still
806
1700
  * returns 200 with `partial: true`, an EMPTY `network`, and `null`
807
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`.
808
1706
  */
809
1707
  async getCitationNetwork(celexNumber, params = {}, options) {
810
- return this.http.requestJson({
1708
+ return this.call({
811
1709
  method: "GET",
812
1710
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
813
- query: { citationType: params.citationType, limit: params.limit, offset: params.offset },
814
- timeoutMs: options?.timeoutMs
1711
+ query: {
1712
+ ...filterQuery(params),
1713
+ limit: params.limit,
1714
+ offset: params.offset,
1715
+ language: params.language,
1716
+ includeNational: params.includeNational,
1717
+ unresolved: params.unresolved
1718
+ },
1719
+ timeoutMs: options?.timeoutMs,
1720
+ signal: options?.signal
815
1721
  });
816
1722
  }
817
1723
  /**
818
1724
  * `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.
1725
+ * outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
1726
+ * not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
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`.
821
1732
  */
822
1733
  async getCitationPath(from, to, params = {}, options) {
823
- return this.http.requestJson({
1734
+ return this.call({
824
1735
  method: "GET",
825
1736
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
826
- query: { maxDepth: params.maxDepth },
827
- timeoutMs: options?.timeoutMs
1737
+ query: {
1738
+ ...filterQuery(params),
1739
+ maxDepth: params.maxDepth,
1740
+ language: params.language,
1741
+ includeNational: params.includeNational
1742
+ },
1743
+ timeoutMs: options?.timeoutMs,
1744
+ signal: options?.signal
828
1745
  });
829
1746
  }
830
1747
  /**
831
1748
  * `GET /citations/related/{celexNumber}` — bibliographic-coupling
832
1749
  * 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.
1750
+ * the seed). 20 credits. Returns a graceful empty list with `message`
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`.
835
1756
  */
836
1757
  async getRelatedDocuments(celexNumber, params = {}, options) {
837
- return this.http.requestJson({
1758
+ return this.call({
838
1759
  method: "GET",
839
1760
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
840
- query: { limit: params.limit },
841
- timeoutMs: options?.timeoutMs
1761
+ query: {
1762
+ ...filterQuery(params),
1763
+ limit: params.limit,
1764
+ language: params.language,
1765
+ includeNational: params.includeNational
1766
+ },
1767
+ timeoutMs: options?.timeoutMs,
1768
+ signal: options?.signal
842
1769
  });
843
1770
  }
844
- /** `GET /citations/stats` — global citation graph statistics. */
845
- async getCitationStats(options) {
846
- return this.http.requestJson({
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
+ }
1780
+ return this.call({
847
1781
  method: "GET",
848
1782
  path: "/citations/stats",
849
- timeoutMs: options?.timeoutMs
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,
1993
+ timeoutMs: options?.timeoutMs,
1994
+ signal: options?.signal
850
1995
  });
851
1996
  }
852
1997
  // ── Semantic search ───────────────────────────────────────────────
@@ -856,89 +2001,118 @@ var LexAPI = class {
856
2001
  * keyword matching is literal.
857
2002
  *
858
2003
  * **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).
2004
+ * (HyDE query rewriting; ~1–3 s extra latency). HyDE is best-effort: on
2005
+ * LLM failure the search falls back to plain retrieval, the response
2006
+ * reports `hyde: false`, and the 10-credit premium is **refunded
2007
+ * automatically**.
870
2008
  *
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.
2009
+ * Hits carry a ~600-char `snippet` by default; `includeText: true`
2010
+ * returns the full text instead. `hint` is present only on
2011
+ * low-confidence result sets. Fewer results than `limit`? The ~0.7
2012
+ * default relevance floor cut in — pass `minScore: 0.5` (or `0`).
873
2013
  *
874
2014
  * Persistent document identity is `(metadata.celex_id,
875
- * metadata.document_type)`; `case_id` is snapshot-scoped and does not
876
- * survive index rebuilds.
2015
+ * metadata.document_type)`; `case_id` is snapshot-scoped.
877
2016
  */
878
2017
  async semanticSearch(request, options) {
879
- return this.http.requestJson({
2018
+ return this.call({
880
2019
  method: "POST",
881
2020
  path: "/search/semantic",
882
2021
  body: semanticWireBody(request),
883
- timeoutMs: options?.timeoutMs
2022
+ idempotent: true,
2023
+ timeoutMs: options?.timeoutMs,
2024
+ signal: options?.signal
884
2025
  });
885
2026
  }
886
2027
  /**
887
2028
  * `POST /legislation/semantic` — embedding-based semantic search over EU
888
2029
  * legislation; results are article-level matches (`article_ref`,
889
- * `law_id`, `law_title`, `score`).
2030
+ * `law_id`, `law_title`, `score`). `limit` is never above 50 here.
2031
+ *
2032
+ * **Consolidated texts:** when an act and its consolidated version match
2033
+ * the same article you get ONE hit — the consolidated article, labelled
2034
+ * `consolidated` / `consolidatedAsOf` / `baseCelex` / `consolidatedNote`,
2035
+ * with the authentic act's own match under `baseAct`. Consolidated texts
2036
+ * are not authentic; cite `baseCelex`.
890
2037
  *
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.
2038
+ * **`asOf` (YYYY-MM-DD):** each hit answers with the version in force on
2039
+ * that date (`asOfResolved`, `asOfVersion`, `matchedVersion`); a hit that
2040
+ * cannot be answered keeps its latest text with `asOfResolved: false` and
2041
+ * an `asOfReason`. The response adds `asOf` and `asOfSummary`.
2042
+ *
2043
+ * **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
2044
+ * version the corpus does not hold reserves 5 and settles by outcome
2045
+ * (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
2046
+ * default. Corpus reads are free; an unaffordable fetch is skipped
2047
+ * (`insufficient_credits`), never a 402. The `hyde` option is case-law only.
895
2048
  */
896
2049
  async semanticLegislationSearch(request, options) {
897
- return this.http.requestJson({
2050
+ return this.call({
898
2051
  method: "POST",
899
2052
  path: "/legislation/semantic",
900
2053
  body: semanticWireBody(request),
901
- timeoutMs: options?.timeoutMs
2054
+ idempotent: true,
2055
+ timeoutMs: options?.timeoutMs,
2056
+ signal: options?.signal
902
2057
  });
903
2058
  }
904
2059
  // ── Export ────────────────────────────────────────────────────────
905
2060
  /**
906
- * `GET /export` — stream matching corpus rows as NDJSON (BUSINESS tier;
907
- * 402 `TierForbidden`/`CreditsExhausted`-style envelope otherwise).
2061
+ * `GET /export` — stream matching corpus rows as NDJSON (BUSINESS, SCALE
2062
+ * and ENTERPRISE; lower tiers get 403 `TierForbiddenError`). Metadata-only
2063
+ * rows are skipped unless `includeStubs: true`.
2064
+ *
2065
+ * Billing (credit plans, API 2.3.0): 1 credit per row written, at least 1
2066
+ * per export. The call is admitted for 1 credit, the matching rows are
2067
+ * counted, and the rest of 1 credit per row it can return is reserved; a
2068
+ * pool that cannot cover it throws `CreditsExhaustedError` before anything
2069
+ * streams. Unwritten rows are refunded when the stream ends; the settled
2070
+ * charge is `stream.done?.credits` (`charged`).
908
2071
  *
909
2072
  * Returns a single-pass async iterator over document rows. The leading
910
2073
  * `_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.
2074
+ * trailing `_done` line is exposed as `stream.done` after iteration —
2075
+ * check `stream.truncated` (`_done.truncated` once read; the header / `_meta`
2076
+ * hints before) to detect rows the export did not reach instead of assuming
2077
+ * it was complete.
915
2078
  *
916
2079
  * ```ts
917
- * const stream = await client.export({ documentType: "regulation", limit: 1000 });
918
- * console.log(stream.meta, stream.headers.total);
2080
+ * const stream = await client.export({ documentTypeCode: "regulation", limit: 1000 });
2081
+ * console.log(stream.meta?.totalMatching, stream.headers.total);
919
2082
  * for await (const row of stream) process(row.celex, row.parsedContent);
920
- * if (stream.done?.truncated) console.warn("row cap hit — paginate with fetchedSince");
2083
+ * if (stream.truncated) console.warn(`not every row reached (${stream.done?.truncatedBy}) — narrow the filters or resume with changedSince`);
921
2084
  * ```
922
2085
  */
923
2086
  async export(params = {}, options) {
2087
+ if (params.limit !== void 0 && !(Number.isInteger(params.limit) && params.limit >= 1)) {
2088
+ throw new RangeError(`limit must be a positive integer, got ${String(params.limit)}`);
2089
+ }
924
2090
  const response = await this.http.requestRaw({
925
2091
  method: "GET",
926
2092
  path: "/export",
2093
+ accept: "application/x-ndjson, application/json",
927
2094
  query: {
928
- documentType: params.documentType,
929
- author: params.author,
930
- subdomain: params.subdomain,
2095
+ documentType: listParam(params.documentType),
2096
+ documentTypeCode: listParam(params.documentTypeCode),
2097
+ author: listParam(params.author),
2098
+ subdomain: listParam(params.subdomain),
931
2099
  language: params.language,
932
2100
  dateFrom: params.dateFrom,
933
2101
  dateTo: params.dateTo,
934
- fetchedSince: params.fetchedSince,
2102
+ fetchedSince: timestampParam(params.fetchedSince),
2103
+ changedSince: timestampParam(params.changedSince),
935
2104
  includeHtml: params.includeHtml,
936
2105
  includeContent: params.includeContent,
2106
+ includeStubs: params.includeStubs,
937
2107
  limit: params.limit
938
2108
  },
939
- timeoutMs: options?.timeoutMs
2109
+ timeoutMs: options?.timeoutMs,
2110
+ signal: options?.signal
2111
+ });
2112
+ return createExportStream(response, {
2113
+ idleTimeoutMs: options?.timeoutMs ?? this.http.timeoutMs,
2114
+ ...options?.signal ? { signal: options.signal } : {}
940
2115
  });
941
- return createExportStream(response);
942
2116
  }
943
2117
  };
944
2118
  function semanticWireBody(request) {
@@ -949,51 +2123,277 @@ function semanticWireBody(request) {
949
2123
  if (request.includeText) body["include"] = ["text"];
950
2124
  if (request.filters !== void 0) body["filters"] = request.filters;
951
2125
  if (request.hyde !== void 0) body["hyde"] = request.hyde;
2126
+ if (request.asOf !== void 0) body["asOf"] = request.asOf;
952
2127
  return body;
953
2128
  }
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 };
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
+ }
2155
+ function edgeQuery(params) {
2156
+ return {
2157
+ ...filterQuery(params),
2158
+ limit: params.limit,
2159
+ offset: params.offset,
2160
+ language: params.language,
2161
+ includeNational: params.includeNational
2162
+ };
2163
+ }
2164
+ function timestampParam(value) {
2165
+ return value instanceof Date ? value.toISOString() : value;
2166
+ }
2167
+ function listParam(value) {
2168
+ if (value === void 0) return void 0;
2169
+ return typeof value === "string" ? value : value.join(",");
2170
+ }
2171
+ async function* paginateEdges(fetchPage, rawRowsIn, params) {
2172
+ const limit = params.limit ?? 100;
2173
+ let offset = params.offset ?? 0;
2174
+ for (; ; ) {
2175
+ const page = await fetchPage({ ...params, limit, offset });
2176
+ yield page;
2177
+ const pageLimit = page.limit && page.limit > 0 ? page.limit : limit;
2178
+ const rows = rawRowsIn(page);
2179
+ offset += rows;
2180
+ if (rows === 0 || rows < pageLimit) return;
958
2181
  }
959
- return data;
960
2182
  }
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 };
2183
+ function withHeaders(data, response, corpusVersion) {
2184
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return data;
2185
+ const headers = parseResponseHeaders(response);
2186
+ const out = { ...data, headers };
2187
+ if (headers.warning !== void 0) out["xWarning"] = headers.warning;
2188
+ if (corpusVersion && headers.corpusVersion !== void 0) {
2189
+ out["corpusVersion"] = headers.corpusVersion;
966
2190
  }
967
- return data;
2191
+ return out;
968
2192
  }
969
2193
 
970
2194
  // src/credits.ts
971
2195
  function getCreditUsage(response) {
972
2196
  return {
973
- unitsCharged: response.credits?.operation_weight,
2197
+ unitsCharged: response.credits?.operation_weight ?? 0,
974
2198
  creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
975
2199
  resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
976
2200
  };
977
2201
  }
2202
+
2203
+ // src/webhookSignature.ts
2204
+ var WEBHOOK_SIGNATURE_HEADER = "x-webhook-signature";
2205
+ var WEBHOOK_DELIVERY_HEADER = "x-webhook-delivery";
2206
+ var WEBHOOK_ID_HEADER = "x-webhook-id";
2207
+ var VERIFICATION_BRAND = /* @__PURE__ */ Symbol.for("@lexapi/client.webhookSignatureError");
2208
+ var WebhookSignatureError = class _WebhookSignatureError extends Error {
2209
+ reason;
2210
+ static [Symbol.hasInstance](value) {
2211
+ if (typeof value !== "object" || value === null) return false;
2212
+ if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
2213
+ return this === _WebhookSignatureError && value[VERIFICATION_BRAND] === true;
2214
+ }
2215
+ constructor(reason, message) {
2216
+ super(message);
2217
+ this.name = "WebhookSignatureError";
2218
+ this.reason = reason;
2219
+ Object.defineProperty(this, VERIFICATION_BRAND, { value: true, enumerable: false });
2220
+ }
2221
+ };
2222
+ function assertSecret(secret) {
2223
+ if (typeof secret !== "string" || secret.length === 0) {
2224
+ throw new WebhookSignatureError(
2225
+ "missing_secret",
2226
+ "Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
2227
+ );
2228
+ }
2229
+ }
2230
+ async function getSubtle() {
2231
+ const globalCrypto = globalThis.crypto;
2232
+ if (globalCrypto?.subtle) return globalCrypto.subtle;
2233
+ const specifier = "node:crypto";
2234
+ const nodeCrypto = await import(
2235
+ /* webpackIgnore: true */
2236
+ /* @vite-ignore */
2237
+ specifier
2238
+ );
2239
+ if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
2240
+ throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
2241
+ }
2242
+ function toBytes(body) {
2243
+ if (typeof body === "string") return new TextEncoder().encode(body);
2244
+ if (body instanceof Uint8Array) return body;
2245
+ return new Uint8Array(body);
2246
+ }
2247
+ function toHex(buffer) {
2248
+ let hex = "";
2249
+ for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
2250
+ return hex;
2251
+ }
2252
+ function timingSafeEqual(a, b) {
2253
+ if (a.length !== b.length) return false;
2254
+ let diff = 0;
2255
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
2256
+ return diff === 0;
2257
+ }
2258
+ async function computeSignature(rawBody, secret) {
2259
+ assertSecret(secret);
2260
+ const subtle = await getSubtle();
2261
+ const key = await subtle.importKey(
2262
+ "raw",
2263
+ new TextEncoder().encode(secret),
2264
+ { name: "HMAC", hash: "SHA-256" },
2265
+ false,
2266
+ ["sign"]
2267
+ );
2268
+ return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
2269
+ }
2270
+ async function verifySignature(rawBody, signature, secret) {
2271
+ const candidate = typeof signature === "string" ? signature.trim().toLowerCase() : "";
2272
+ const expected = await computeSignature(rawBody, secret);
2273
+ if (!/^[0-9a-f]{64}$/.test(candidate)) return false;
2274
+ return timingSafeEqual(expected, candidate);
2275
+ }
2276
+ async function verifyWebhook(rawBody, signature, secret, options = {}) {
2277
+ assertSecret(secret);
2278
+ if (!signature) {
2279
+ throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
2280
+ }
2281
+ if (!await verifySignature(rawBody, signature, secret)) {
2282
+ throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
2283
+ }
2284
+ let payload;
2285
+ try {
2286
+ const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
2287
+ payload = JSON.parse(text);
2288
+ } catch {
2289
+ throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
2290
+ }
2291
+ const toleranceMs = options.toleranceMs ?? 3e5;
2292
+ if (toleranceMs > 0) {
2293
+ const sentAt = Date.parse(String(payload.timestamp));
2294
+ const now = options.now ?? Date.now();
2295
+ if (Number.isNaN(sentAt) || Math.abs(now - sentAt) > toleranceMs) {
2296
+ throw new WebhookSignatureError(
2297
+ "stale_timestamp",
2298
+ `Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
2299
+ );
2300
+ }
2301
+ }
2302
+ return payload;
2303
+ }
2304
+
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
+ ];
2330
+ var AS_OF_REASONS = [
2331
+ "not_yet_adopted",
2332
+ "not_yet_in_force",
2333
+ "no_longer_in_force",
2334
+ "in_force_dates_unknown",
2335
+ "not_in_language",
2336
+ "text_unavailable",
2337
+ "article_not_in_version",
2338
+ "part_not_resolvable",
2339
+ "article_unknown",
2340
+ "version_list_unavailable",
2341
+ "version_lookup_cap",
2342
+ "fetch_budget_exhausted",
2343
+ "fetch_pending",
2344
+ "fetch_capacity",
2345
+ "fetch_failed",
2346
+ "fetch_timeout",
2347
+ "request_deadline",
2348
+ "insufficient_credits",
2349
+ "credit_check_failed"
2350
+ ];
2351
+ function isNationalDecision(document2) {
2352
+ return document2.documentKind === "decision" && document2.decision != null;
2353
+ }
978
2354
  // Annotate the CommonJS export names for ESM import in node:
979
2355
  0 && (module.exports = {
2356
+ AS_OF_REASONS,
980
2357
  AuthenticationError,
2358
+ CITATION_PROVENANCES,
2359
+ CITATION_RESOLUTIONS,
2360
+ CITATION_TYPES,
981
2361
  CreditsExhaustedError,
982
2362
  DEFAULT_BASE_URL,
983
2363
  DEFAULT_TIMEOUT_MS,
2364
+ DocumentWithdrawnError,
2365
+ IncompleteExportError,
984
2366
  InternalServerError,
985
2367
  InvalidCelexError,
986
2368
  InvalidParamsError,
2369
+ InvalidResponseError,
987
2370
  InvalidUrlError,
988
2371
  LexAPI,
989
2372
  LexAPIError,
2373
+ NationalAllowanceExhaustedError,
2374
+ NationalSemanticFilterUnreachableError,
2375
+ NationalSemanticNotEnabledError,
2376
+ NationalSemanticUnavailableError,
990
2377
  NetworkError,
991
2378
  NotFoundError,
992
2379
  RateLimitedError,
2380
+ RequestAbortedError,
2381
+ ServiceUnavailableError,
993
2382
  TierForbiddenError,
994
2383
  TimeoutError,
995
2384
  UpstreamError,
996
2385
  VERSION,
2386
+ WEBHOOK_DELIVERY_HEADER,
2387
+ WEBHOOK_ID_HEADER,
2388
+ WEBHOOK_SIGNATURE_HEADER,
2389
+ WebhookSignatureError,
997
2390
  WebhooksAPI,
998
- getCreditUsage
2391
+ computeSignature,
2392
+ getCreditUsage,
2393
+ isLexAPIError,
2394
+ isNationalDecision,
2395
+ normalizeRetryAfterSeconds,
2396
+ parseResponseHeaders,
2397
+ verifySignature,
2398
+ verifyWebhook
999
2399
  });