@lexapi/client 0.1.0 → 0.2.0

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