@lexapi/client 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,88 @@
1
+ // src/retryHints.ts
2
+ function normalizeRetryAfterSeconds(value) {
3
+ if (!Number.isFinite(value)) return 0;
4
+ if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
5
+ if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
6
+ return Math.max(0, value);
7
+ }
8
+ function trimSpaces(value) {
9
+ return value.replace(/^[ \t]+|[ \t]+$/g, "");
10
+ }
11
+ function decimalSeconds(raw) {
12
+ if (typeof raw !== "string") return void 0;
13
+ const value = trimSpaces(raw);
14
+ if (!/^[0-9]+(\.[0-9]+)?$/.test(value)) return void 0;
15
+ const seconds = Number(value);
16
+ return Number.isFinite(seconds) ? normalizeRetryAfterSeconds(seconds) : void 0;
17
+ }
18
+ function bodySeconds(value) {
19
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
20
+ return normalizeRetryAfterSeconds(value);
21
+ }
22
+ var DAYS = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
23
+ var LONG_DAYS = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
24
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
25
+ var MONTH = MONTHS.join("|");
26
+ var TIME = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
27
+ var ZONE = "(?:GMT|UTC|\\+0000)";
28
+ var IMF_FIXDATE = new RegExp(`^(?:${DAYS}), ([0-9]{2}) (${MONTH}) ([0-9]{4}) ${TIME} ${ZONE}$`, "i");
29
+ var RFC850_DATE = new RegExp(`^(?:${LONG_DAYS}), ([0-9]{2})-(${MONTH})-([0-9]{2}) ${TIME} ${ZONE}$`, "i");
30
+ var ASCTIME_DATE = new RegExp(`^(?:${DAYS}) (${MONTH}) ([0-9]{2}| [0-9]) ${TIME} ([0-9]{4})$`, "i");
31
+ function dateKey(year, month, day, h, m, s) {
32
+ return ((((year * 12 + month) * 31 + day) * 24 + h) * 60 + m) * 60 + s;
33
+ }
34
+ function fullYear(twoDigits, month, day, h, m, s, now) {
35
+ const at = new Date(now);
36
+ const limit = dateKey(at.getUTCFullYear() + 50, at.getUTCMonth(), at.getUTCDate(), at.getUTCHours(), at.getUTCMinutes(), at.getUTCSeconds());
37
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
38
+ let year = Math.floor(at.getUTCFullYear() / 100) * 100 + 100 + twoDigits;
39
+ while (dateKey(year, monthIndex, day, h, m, s) > limit) year -= 100;
40
+ return year;
41
+ }
42
+ function utcMs(year, month, day, h, m, s) {
43
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
44
+ if (monthIndex < 0 || h > 23 || m > 59 || s > 59 || day < 1) return void 0;
45
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
46
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][monthIndex];
47
+ if (day > daysInMonth) return void 0;
48
+ const date = /* @__PURE__ */ new Date(0);
49
+ date.setUTCFullYear(year, monthIndex, day);
50
+ date.setUTCHours(h, m, s, 0);
51
+ return date.getTime();
52
+ }
53
+ function httpDateMs(value, now = Date.now()) {
54
+ let match = IMF_FIXDATE.exec(value);
55
+ if (match) {
56
+ const [, day, month, year, h, m, s] = match;
57
+ return utcMs(Number(year), month, Number(day), Number(h), Number(m), Number(s));
58
+ }
59
+ match = RFC850_DATE.exec(value);
60
+ if (match) {
61
+ const [, day, month, year, h, m, s] = match;
62
+ const [d, hh, mm, ss] = [Number(day), Number(h), Number(m), Number(s)];
63
+ return utcMs(fullYear(Number(year), month, d, hh, mm, ss, now), month, d, hh, mm, ss);
64
+ }
65
+ match = ASCTIME_DATE.exec(value);
66
+ if (match) {
67
+ const [, month, day, h, m, s, year] = match;
68
+ return utcMs(Number(year), month, Number(day.trim()), Number(h), Number(m), Number(s));
69
+ }
70
+ return void 0;
71
+ }
72
+ function retryAfterHeaderSeconds(raw) {
73
+ if (typeof raw !== "string") return void 0;
74
+ const value = trimSpaces(raw);
75
+ if (/^[0-9]/.test(value)) return decimalSeconds(value);
76
+ const now = Date.now();
77
+ const date = httpDateMs(value, now);
78
+ return date === void 0 ? void 0 : Math.max(0, Math.round((date - now) / 1e3));
79
+ }
80
+ var MAX_TIMER_MS = 2 ** 31 - 1;
81
+ function timerDelay(ms) {
82
+ if (Number.isNaN(ms)) return 0;
83
+ return Math.min(Math.max(ms, 0), MAX_TIMER_MS);
84
+ }
85
+
1
86
  // src/errors.ts
2
87
  var STATUS_TO_CODE = {
3
88
  400: "INVALID_PARAMS",
@@ -18,6 +103,8 @@ var STATUS_TO_CODE = {
18
103
  524: "TIMEOUT"
19
104
  };
20
105
  var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
106
+ var EXCERPTS = /* @__PURE__ */ new WeakMap();
107
+ var INVALID_BODIES = /* @__PURE__ */ new WeakMap();
21
108
  function collectKinds(ctor) {
22
109
  const kinds = [];
23
110
  let current = ctor;
@@ -53,8 +140,8 @@ var LexAPIError = class _LexAPIError extends Error {
53
140
  * Seconds to wait before retrying, when the server said so (429; also the
54
141
  * 503 of an incomplete national semantic search).
55
142
  * Sourced from the `Retry-After` response HEADER first; the JSON
56
- * `retryAfter` body field is only a fallback because it historically
57
- * carried buggy epoch-seconds values (epoch-looking values are
143
+ * `retryAfter` body field is only a fallback because it can carry
144
+ * epoch-seconds values (epoch-looking values are
58
145
  * normalized to a delta).
59
146
  */
60
147
  retryAfter;
@@ -75,64 +162,89 @@ var LexAPIError = class _LexAPIError extends Error {
75
162
  this.retryAfter = retryAfter;
76
163
  this.body = context?.body;
77
164
  this.headers = context?.headers;
165
+ if (context?.bodyExcerpt !== void 0) EXCERPTS.set(this, context.bodyExcerpt);
78
166
  Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
79
167
  }
168
+ /**
169
+ * For a response body that is not JSON, its first 200 characters (code
170
+ * points); `undefined` otherwise. Raw response text; may contain document
171
+ * text; do not show to a model or log by default. Not an own property of
172
+ * the error, so `console.log` (also with `%o`), `util.inspect` with
173
+ * `showHidden` or with `getters`, `JSON.stringify`, spread and
174
+ * `structuredClone` leave it out (`util.inspect` with `showHidden` and
175
+ * `getters` together shows it); never part of `message`. Assigning to it
176
+ * replaces it (`undefined` clears it).
177
+ */
178
+ get bodyExcerpt() {
179
+ return EXCERPTS.get(this);
180
+ }
181
+ set bodyExcerpt(value) {
182
+ if (value === void 0) EXCERPTS.delete(this);
183
+ else EXCERPTS.set(this, value);
184
+ }
80
185
  /**
81
186
  * Build the most specific error subclass for a non-2xx response.
82
187
  * Accepts both the typed envelope and the legacy bare `{error, message}` shape.
188
+ * `code` and `message` are read only when they are non-empty strings.
83
189
  */
84
- static fromResponse(status, body, headerRetryAfter, headers) {
190
+ static fromResponse(status, body, headerRetryAfter, headers, bodyExcerpt) {
85
191
  const statusCode = STATUS_TO_CODE[status];
86
192
  let code = statusCode ?? "INTERNAL";
87
193
  let typedCode = false;
88
194
  let message = `HTTP ${status}`;
89
195
  let details;
90
196
  let retryAfter = headerRetryAfter;
91
- let resetsAt;
197
+ let resetsAt2;
92
198
  if (typeof body === "object" && body !== null) {
93
199
  const record = body;
94
200
  const err = record["error"];
95
- if (typeof err === "object" && err !== null) {
201
+ const topCode = nonEmptyString(record["code"]);
202
+ const topMessage = nonEmptyString(record["message"]);
203
+ if (typeof err === "object" && err !== null && !Array.isArray(err)) {
96
204
  const e = err;
97
- if (typeof e["code"] === "string") {
98
- code = e["code"];
205
+ const typed = nonEmptyString(e["code"]);
206
+ if (typed !== void 0) {
207
+ code = typed;
99
208
  typedCode = true;
100
209
  }
101
- if (typeof e["message"] === "string") message = e["message"];
210
+ message = nonEmptyString(e["message"]) ?? message;
102
211
  details = e["details"];
103
- } else if (typeof err === "string") {
104
- if (typeof record["code"] === "string" && record["code"] !== "") {
105
- code = record["code"];
212
+ } else if (typeof err === "string" && err !== "") {
213
+ if (topCode !== void 0) {
214
+ code = topCode;
106
215
  typedCode = true;
107
216
  }
108
- message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
217
+ message = topMessage !== void 0 && topMessage !== err ? `${err}: ${topMessage}` : err;
109
218
  details = record["details"];
110
219
  } else {
111
- if (typeof record["code"] === "string" && record["code"] !== "") {
112
- code = record["code"];
220
+ if (topCode !== void 0) {
221
+ code = topCode;
113
222
  typedCode = true;
114
223
  }
115
- if (typeof record["message"] === "string") message = record["message"];
224
+ message = topMessage ?? message;
116
225
  details = record["details"];
117
226
  }
118
227
  if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
119
- const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
120
- if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
228
+ retryAfter = bodyWait(record, details);
121
229
  }
122
- resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
230
+ resetsAt2 = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
123
231
  }
124
- const context = { body, ...headers ? { headers } : {} };
232
+ const context = {
233
+ body,
234
+ ...headers ? { headers } : {},
235
+ ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {}
236
+ };
125
237
  if (!typedCode && statusCode === void 0 && status < 500) {
126
238
  return new _LexAPIError(code, message, status, details, retryAfter, context);
127
239
  }
128
- if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
240
+ if (code === "QUOTA_EXHAUSTED" || status === 429 && hasQuotaCode(body) || status === 429 && code === "RATE_LIMITED" && isQuota429(body, headers)) {
129
241
  return new RateLimitedError(
130
242
  message,
131
243
  status,
132
244
  details,
133
- void 0,
245
+ status === 429 ? void 0 : retryAfter,
134
246
  context,
135
- code === "QUOTA_EXHAUSTED" ? "QUOTA_EXHAUSTED" : "RATE_LIMITED"
247
+ code === "RATE_LIMITED" ? "RATE_LIMITED" : "QUOTA_EXHAUSTED"
136
248
  );
137
249
  }
138
250
  switch (code) {
@@ -148,8 +260,10 @@ var LexAPIError = class _LexAPIError extends Error {
148
260
  return new RateLimitedError(message, status, details, retryAfter, context);
149
261
  case "TIER_FORBIDDEN":
150
262
  return new TierForbiddenError(message, status, details, retryAfter, context);
263
+ case "PAYMENT_PAST_DUE":
264
+ return new PaymentPastDueError(message, status, details, retryAfter, context);
151
265
  case "CREDITS_EXHAUSTED":
152
- return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt, context);
266
+ return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt2, context);
153
267
  case "NATIONAL_ALLOWANCE_EXHAUSTED":
154
268
  return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
155
269
  case "NATIONAL_SEMANTIC_NOT_ENABLED":
@@ -181,7 +295,107 @@ var NotFoundError = class extends LexAPIError {
181
295
  super("NOT_FOUND", message, status, details, retryAfter, context);
182
296
  this.name = "NotFoundError";
183
297
  }
298
+ /**
299
+ * `true` when the API (2.27.0 or later) has no such endpoint
300
+ * (`details.reason` is `"unknown_endpoint"`): a mistyped path, a method
301
+ * newer than the API, or a national route for a country that is not
302
+ * available. Always `false` on APIs before 2.27.0; there the message
303
+ * contains "Unknown API endpoint". Read from `details` only, never from
304
+ * the message.
305
+ */
306
+ get unknownEndpoint() {
307
+ return ownField(this.details, "reason") === "unknown_endpoint";
308
+ }
309
+ // The accessors below read `details` only when it is a plain JSON object,
310
+ // and only its own keys; anything else gives each accessor's default.
311
+ /**
312
+ * `details.reason` when it is a string: `unknown_endpoint`, or on
313
+ * `getDocumentAtDate` (API 2.28.0) `before_tracking` / `boundary_unknown`.
314
+ * `undefined` on a 404 without one (e.g. a document not in the corpus).
315
+ */
316
+ get reason() {
317
+ return readString(ownField(this.details, "reason"));
318
+ }
319
+ /**
320
+ * `true` when `getDocumentAtDate` was asked about a date before the
321
+ * document entered the corpus (`details.reason` is `"before_tracking"`);
322
+ * {@link trackedSince} says when that was.
323
+ */
324
+ get beforeTracking() {
325
+ return ownField(this.details, "reason") === "before_tracking";
326
+ }
327
+ /**
328
+ * `true` when LexAPI has no record of when a version stored before API
329
+ * 2.28.0 began, so it cannot say which snapshot it held on the date and
330
+ * does not guess (`details.reason` is `"boundary_unknown"`). Refunded.
331
+ * Read the {@link candidates} with `getDocumentVersion`.
332
+ */
333
+ get boundaryUnknown() {
334
+ return ownField(this.details, "reason") === "boundary_unknown";
335
+ }
336
+ /** `before_tracking` only: when the document entered the corpus (`details.trackedSince`). */
337
+ get trackedSince() {
338
+ return readString(ownField(this.details, "trackedSince"));
339
+ }
340
+ /**
341
+ * On `before_tracking` for an EU act: the request that answers which
342
+ * version is listed for a date (`legislationAsOf`).
343
+ */
344
+ get inForceLookup() {
345
+ const value = ownField(this.details, "inForceLookup");
346
+ if (!isPlainJsonObject(value)) return void 0;
347
+ const lookup2 = {};
348
+ const method = readString(ownField(value, "method"));
349
+ const path = readString(ownField(value, "path"));
350
+ if (method !== void 0) lookup2.method = method;
351
+ if (path !== void 0) lookup2.path = path;
352
+ return lookup2;
353
+ }
354
+ /**
355
+ * `boundary_unknown` only: the versions the date could fall in — the
356
+ * first 10 items of `details.candidates`
357
+ * that are objects with an integer `version` (`fetchedAt` / `observedFrom`
358
+ * are `null` when not strings). `[]` when there are none. For these
359
+ * versions `fetchedAt` can be the last fetch and later than the date.
360
+ */
361
+ get candidates() {
362
+ return readCandidates(this.details).kept;
363
+ }
364
+ /**
365
+ * `boundary_unknown` only: `true` when more versions matched than
366
+ * {@link candidates} lists (`details.candidatesTruncated` is `true`, or
367
+ * more than 10 usable candidates were sent).
368
+ */
369
+ get candidatesTruncated() {
370
+ return ownField(this.details, "candidatesTruncated") === true || readCandidates(this.details).more;
371
+ }
184
372
  };
373
+ var MAX_SNAPSHOT_CANDIDATES = 10;
374
+ function readCandidates(details) {
375
+ const list = ownField(details, "candidates");
376
+ const kept = [];
377
+ if (!Array.isArray(list)) return { kept, more: false };
378
+ for (const item of list) {
379
+ const version = ownField(item, "version");
380
+ if (typeof version !== "number" || !Number.isInteger(version)) continue;
381
+ if (kept.length === MAX_SNAPSHOT_CANDIDATES) return { kept, more: true };
382
+ const fetchedAt = ownField(item, "fetchedAt");
383
+ const observedFrom = ownField(item, "observedFrom");
384
+ kept.push({
385
+ version: version + 0,
386
+ // -0 → 0
387
+ fetchedAt: typeof fetchedAt === "string" ? fetchedAt : null,
388
+ observedFrom: typeof observedFrom === "string" ? observedFrom : null
389
+ });
390
+ }
391
+ return { kept, more: false };
392
+ }
393
+ function isPlainJsonObject(value) {
394
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
395
+ }
396
+ function ownField(value, key) {
397
+ return isPlainJsonObject(value) && Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
398
+ }
185
399
  var InvalidCelexError = class extends LexAPIError {
186
400
  static kind = "InvalidCelexError";
187
401
  constructor(message, status = 400, details, retryAfter, context) {
@@ -240,14 +454,14 @@ var RateLimitedError = class extends LexAPIError {
240
454
  /**
241
455
  * `true` for a legacy-plan quota 429 (daily call quota, or the monthly
242
456
  * semantic quota) rather than the per-minute limiter (SDK contract §1.2):
243
- * `code` is `QUOTA_EXHAUSTED`, or — servers before lex-api #304, which
457
+ * `code` is `QUOTA_EXHAUSTED`, or — servers before API 2.4.0, which
244
458
  * send no code — the body carries `usage.resetsAt` with neither a
245
459
  * `Retry-After` header nor a `retryAfter` body field. It cannot succeed
246
460
  * before `resetsAt`, so the SDK does not retry it and `retryAfter` is
247
461
  * `undefined`.
248
462
  */
249
463
  get quotaExhausted() {
250
- return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
464
+ return this.code === "QUOTA_EXHAUSTED" || this.status === 429 && this.code === "RATE_LIMITED" && isQuota429(this.body, this.headers);
251
465
  }
252
466
  /** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
253
467
  get resetsAt() {
@@ -256,19 +470,34 @@ var RateLimitedError = class extends LexAPIError {
256
470
  };
257
471
  var TierForbiddenError = class extends LexAPIError {
258
472
  static kind = "TierForbiddenError";
259
- constructor(message, status = 403, details, retryAfter, context) {
260
- super("TIER_FORBIDDEN", message, status, details, retryAfter, context);
473
+ constructor(message, status = 403, details, retryAfter, context, code = "TIER_FORBIDDEN") {
474
+ super(code, message, status, details, retryAfter, context);
261
475
  this.name = "TierForbiddenError";
262
476
  }
263
477
  };
478
+ var PaymentPastDueError = class extends TierForbiddenError {
479
+ static kind = "PaymentPastDueError";
480
+ constructor(message, status = 403, details, retryAfter, context) {
481
+ super(message, status, details, retryAfter, context, "PAYMENT_PAST_DUE");
482
+ this.name = "PaymentPastDueError";
483
+ }
484
+ /** When API access ended (ISO date-time); `undefined` when the server does not say. */
485
+ get accessEndedAt() {
486
+ return readString(detailsOrBodyField(this.details, this.body, "accessEndedAt"));
487
+ }
488
+ /** Where to pay the open invoice (absolute URL of the dashboard's billing page). */
489
+ get billingUrl() {
490
+ return readString(detailsOrBodyField(this.details, this.body, "billingUrl"));
491
+ }
492
+ };
264
493
  var CreditsExhaustedError = class extends LexAPIError {
265
494
  static kind = "CreditsExhaustedError";
266
495
  /** When the monthly credit allowance resets (ISO date-time), when the server said so. */
267
496
  resetsAt;
268
- constructor(message, status = 402, details, retryAfter, resetsAt, context) {
497
+ constructor(message, status = 402, details, retryAfter, resetsAt2, context) {
269
498
  super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
270
499
  this.name = "CreditsExhaustedError";
271
- this.resetsAt = resetsAt;
500
+ this.resetsAt = resetsAt2;
272
501
  }
273
502
  /** The refused operation's credit weight (`details.weight`). */
274
503
  get weight() {
@@ -436,14 +665,25 @@ var RequestAbortedError = class extends LexAPIError {
436
665
  };
437
666
  var InvalidResponseError = class extends LexAPIError {
438
667
  static kind = "InvalidResponseError";
439
- constructor(message, status, rawText, context) {
440
- super("INVALID_RESPONSE", message, status, void 0, void 0, {
441
- ...context,
442
- body: rawText === void 0 ? void 0 : rawText.slice(0, 500)
443
- });
668
+ constructor(message, status, body, context) {
669
+ super("INVALID_RESPONSE", message, status, void 0, void 0, context);
670
+ delete this.body;
671
+ if (body !== void 0) INVALID_BODIES.set(this, body);
444
672
  this.name = "InvalidResponseError";
445
673
  }
446
674
  };
675
+ Object.defineProperty(InvalidResponseError.prototype, "body", {
676
+ get() {
677
+ return INVALID_BODIES.get(this);
678
+ },
679
+ // Assigning replaces the stored value (`undefined` clears it), as on 0.4.0.
680
+ set(value) {
681
+ if (value === void 0) INVALID_BODIES.delete(this);
682
+ else INVALID_BODIES.set(this, value);
683
+ },
684
+ enumerable: false,
685
+ configurable: true
686
+ });
447
687
  var IncompleteExportError = class extends LexAPIError {
448
688
  static kind = "IncompleteExportError";
449
689
  /** Rows yielded before the stream ended. */
@@ -461,15 +701,19 @@ var IncompleteExportError = class extends LexAPIError {
461
701
  function isLexAPIError(value, errorClass) {
462
702
  return value instanceof (errorClass ?? LexAPIError);
463
703
  }
464
- function normalizeRetryAfterSeconds(value) {
465
- if (!Number.isFinite(value)) return 0;
466
- if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
467
- if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
468
- return Math.max(0, value);
469
- }
470
704
  function readNumber(value) {
471
705
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
472
706
  }
707
+ function bodyDetails(body) {
708
+ const err = detailsField(body, "error");
709
+ return typeof err === "object" && err !== null && !Array.isArray(err) ? detailsField(err, "details") : detailsField(body, "details");
710
+ }
711
+ function bodyWait(body, details) {
712
+ return bodySeconds(detailsField(body, "retryAfter")) ?? bodySeconds(detailsField(details, "retryAfter"));
713
+ }
714
+ function nonEmptyString(value) {
715
+ return typeof value === "string" && value !== "" ? value : void 0;
716
+ }
473
717
  function readString(value) {
474
718
  return typeof value === "string" ? value : void 0;
475
719
  }
@@ -479,12 +723,15 @@ function detailsField(details, key) {
479
723
  }
480
724
  return void 0;
481
725
  }
726
+ function hasQuotaCode(body) {
727
+ return detailsField(body, "code") === "QUOTA_EXHAUSTED" || detailsField(bodyField(body, "error"), "code") === "QUOTA_EXHAUSTED";
728
+ }
482
729
  function isQuota429(body, headers) {
483
- if (detailsField(body, "code") === "QUOTA_EXHAUSTED") return true;
484
- const resetsAt = detailsField(detailsField(body, "usage"), "resetsAt");
485
- if (typeof resetsAt !== "string") return false;
486
- if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
487
- return detailsField(body, "retryAfter") === void 0;
730
+ if (hasQuotaCode(body)) return true;
731
+ const resetsAt2 = detailsField(detailsField(body, "usage"), "resetsAt");
732
+ if (typeof resetsAt2 !== "string") return false;
733
+ if (retryAfterHeaderSeconds(headers?.retryAfter) !== void 0) return false;
734
+ return bodyWait(body, bodyDetails(body)) === void 0;
488
735
  }
489
736
  function detailsOrBodyField(details, body, key) {
490
737
  const fromDetails = detailsField(details, key);
@@ -502,11 +749,15 @@ function str(headers, name) {
502
749
  const value = headers.get(name);
503
750
  return value === null ? void 0 : value;
504
751
  }
752
+ function parseHeaderInteger(value) {
753
+ if (typeof value !== "string") return void 0;
754
+ const text2 = value.replace(/^[ \t]+|[ \t]+$/g, "");
755
+ if (!/^[0-9]+$/.test(text2)) return void 0;
756
+ const parsed = Number(text2);
757
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
758
+ }
505
759
  function int(headers, name) {
506
- const value = headers.get(name);
507
- if (value === null) return void 0;
508
- const parsed = Number.parseInt(value, 10);
509
- return Number.isNaN(parsed) ? void 0 : parsed;
760
+ return parseHeaderInteger(headers.get(name));
510
761
  }
511
762
  function compact(obj) {
512
763
  const out = {};
@@ -562,11 +813,12 @@ function parseResponseHeaders(source) {
562
813
  }
563
814
 
564
815
  // src/version.ts
565
- var VERSION = "0.4.0";
816
+ var VERSION = "0.5.0";
566
817
 
567
818
  // src/http.ts
568
819
  var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
569
820
  var DEFAULT_TIMEOUT_MS = 95e3;
821
+ var KIND_NAMES = { object: "an object", string: "a string", boolean: "a boolean" };
570
822
  var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
571
823
  // DNS
572
824
  "ENOTFOUND",
@@ -604,6 +856,33 @@ var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
604
856
  var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
605
857
  var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
606
858
  var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
859
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
860
+ var MAX_REDIRECTS = 5;
861
+ function redirectTarget(location, from) {
862
+ let to;
863
+ try {
864
+ to = new URL(location, from);
865
+ } catch {
866
+ throw new NetworkError("Refused to follow a redirect with an invalid Location header");
867
+ }
868
+ if (to.protocol !== "http:" && to.protocol !== "https:") {
869
+ throw new NetworkError("Refused to follow a redirect to a URL that is not http(s)");
870
+ }
871
+ if (to.username !== "" || to.password !== "") {
872
+ throw new NetworkError(`Refused to follow a redirect to a URL that carries credentials (${to.origin})`);
873
+ }
874
+ const httpsUpgrade = from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
875
+ if (to.origin !== from.origin && !httpsUpgrade) {
876
+ throw new NetworkError(`Refused to follow a redirect to another origin (${to.origin})`);
877
+ }
878
+ return to;
879
+ }
880
+ function discardBody(response) {
881
+ try {
882
+ response.body?.cancel().catch(() => void 0);
883
+ } catch {
884
+ }
885
+ }
607
886
  function isNeverReachedError(error, depth = 0) {
608
887
  if (depth > 6 || typeof error !== "object" || error === null) return false;
609
888
  const { code, syscall, cause, errors } = error;
@@ -649,7 +928,10 @@ var HttpClient = class {
649
928
  [INSPECT]() {
650
929
  return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
651
930
  }
652
- /** Perform a request and parse the JSON body (204 / empty body yields `{}`). */
931
+ /**
932
+ * Perform a request and parse the JSON body. A 2xx that is not the
933
+ * documented shape (`options.shape`) throws `InvalidResponseError`.
934
+ */
653
935
  async requestJson(options) {
654
936
  const { data } = await this.requestJsonWithResponse(options);
655
937
  return data;
@@ -660,7 +942,7 @@ var HttpClient = class {
660
942
  */
661
943
  async requestJsonWithResponse(options) {
662
944
  return this.execute(options, async (response, ctx) => ({
663
- data: await readJsonBody(response, ctx.touch),
945
+ data: await readJsonBody(response, options.shape ?? {}, ctx.touch),
664
946
  response
665
947
  }));
666
948
  }
@@ -701,10 +983,11 @@ var HttpClient = class {
701
983
  let timer;
702
984
  const touch = () => {
703
985
  if (timer !== void 0) clearTimeout(timer);
986
+ if (timeoutMs === Infinity) return;
704
987
  timer = setTimeout(() => {
705
988
  timedOut = true;
706
989
  controller.abort();
707
- }, timeoutMs);
990
+ }, timerDelay(timeoutMs));
708
991
  };
709
992
  touch();
710
993
  const onAbort = () => controller.abort();
@@ -713,12 +996,7 @@ var HttpClient = class {
713
996
  let response;
714
997
  let retryTransport = false;
715
998
  try {
716
- response = await this.opts.fetchFn(url, {
717
- method,
718
- headers,
719
- ...serializedBody !== void 0 ? { body: serializedBody } : {},
720
- signal: controller.signal
721
- });
999
+ response = await this.fetchWithinOrigin(url, method, headers, serializedBody, controller.signal);
722
1000
  touch();
723
1001
  if (response.ok) {
724
1002
  return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
@@ -755,9 +1033,59 @@ var HttpClient = class {
755
1033
  throw error;
756
1034
  }
757
1035
  }
1036
+ /**
1037
+ * `fetch` with redirects followed here rather than by the runtime, which
1038
+ * would repeat every request header to whichever host a redirect names.
1039
+ * Method and body change as `fetch` changes them: a 303, or a 301/302
1040
+ * answer to a POST, continues as a body-less GET; 307/308 repeat the request.
1041
+ * The body of a redirect response is cancelled, so its connection is released.
1042
+ * A response that says it was already redirected (a custom `fetch` that did
1043
+ * not honour `redirect: "manual"`) is refused.
1044
+ */
1045
+ async fetchWithinOrigin(url, method, headers, body, signal) {
1046
+ const fetchFn = this.opts.fetchFn;
1047
+ let target = url;
1048
+ for (let hop = 0; ; hop++) {
1049
+ const response = await fetchFn(target, {
1050
+ method,
1051
+ headers,
1052
+ ...body !== void 0 ? { body } : {},
1053
+ redirect: "manual",
1054
+ signal
1055
+ });
1056
+ if (response.redirected === true) {
1057
+ discardBody(response);
1058
+ throw new NetworkError('The custom fetch followed a redirect itself; it must honour redirect: "manual"');
1059
+ }
1060
+ if (response.type === "opaqueredirect") {
1061
+ throw new NetworkError("The API answered with a redirect, which this runtime does not expose");
1062
+ }
1063
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
1064
+ if (location === null) return response;
1065
+ discardBody(response);
1066
+ let from;
1067
+ try {
1068
+ from = new URL(target);
1069
+ } catch {
1070
+ throw new NetworkError("Refused to follow a redirect from a request URL that is not absolute");
1071
+ }
1072
+ const next = redirectTarget(location, from);
1073
+ if (hop >= MAX_REDIRECTS) {
1074
+ throw new NetworkError(`Too many redirects (more than ${MAX_REDIRECTS})`);
1075
+ }
1076
+ if (response.status === 303 && method !== "GET" || (response.status === 301 || response.status === 302) && method === "POST") {
1077
+ method = "GET";
1078
+ body = void 0;
1079
+ headers = { ...headers };
1080
+ delete headers["content-type"];
1081
+ }
1082
+ target = next.href;
1083
+ }
1084
+ }
758
1085
  };
759
1086
  function shouldRetryStatus(error, call) {
760
1087
  const status = error.status;
1088
+ if (error.code === "PAYMENT_PAST_DUE") return false;
761
1089
  if (status === 503 && isBudgetTimeout(error.body)) return false;
762
1090
  if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
763
1091
  if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
@@ -776,34 +1104,133 @@ function isSearchIncomplete(error) {
776
1104
  const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
777
1105
  return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
778
1106
  }
779
- async function readBodyText(response, touch) {
780
- if (response.body === null || touch === void 0) return response.text();
1107
+ async function readBodyBytes(response, touch) {
1108
+ if (response.body === null || touch === void 0) return new Uint8Array(await response.arrayBuffer());
781
1109
  const reader = response.body.getReader();
782
- const decoder = new TextDecoder();
783
- const parts = [];
1110
+ const chunks = [];
1111
+ let length = 0;
784
1112
  for (; ; ) {
785
1113
  const { done, value } = await reader.read();
786
1114
  if (done) break;
787
1115
  touch();
788
- parts.push(decoder.decode(value, { stream: true }));
1116
+ chunks.push(value);
1117
+ length += value.byteLength;
789
1118
  }
790
- parts.push(decoder.decode());
791
- return parts.join("");
1119
+ const bytes = new Uint8Array(length);
1120
+ let offset = 0;
1121
+ for (const chunk of chunks) {
1122
+ bytes.set(chunk, offset);
1123
+ offset += chunk.byteLength;
1124
+ }
1125
+ return bytes;
792
1126
  }
793
- async function readJsonBody(response, touch) {
794
- if (response.status === 204) return {};
795
- const text = await readBodyText(response, touch);
796
- if (text.trim() === "") return {};
1127
+ var EXCERPT_CHARS = 200;
1128
+ var EXCERPT_BYTES = EXCERPT_CHARS * 4;
1129
+ var NOT_JSON = /* @__PURE__ */ Symbol("not JSON");
1130
+ function parseJsonBytes(bytes) {
797
1131
  try {
798
- return JSON.parse(text);
1132
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
799
1133
  } catch {
800
- throw new InvalidResponseError(
801
- `Expected a JSON body (HTTP ${response.status}, content-type ${response.headers.get("content-type") ?? "none"})`,
802
- response.status,
803
- text,
804
- { headers: parseResponseHeaders(response) }
1134
+ return NOT_JSON;
1135
+ }
1136
+ }
1137
+ function excerptOf(bytes) {
1138
+ if (bytes.byteLength === 0) return void 0;
1139
+ const text2 = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(0, EXCERPT_BYTES));
1140
+ let out = "";
1141
+ let count2 = 0;
1142
+ for (const char of text2) {
1143
+ if (count2++ === EXCERPT_CHARS) break;
1144
+ out += char;
1145
+ }
1146
+ return out;
1147
+ }
1148
+ function mediaTypeOf(response) {
1149
+ const value = response.headers.get("content-type") ?? "";
1150
+ const media = Array.from(value.split(";", 1)[0].replace(/^[ \t]+|[ \t]+$/g, "")).slice(0, 100).join("");
1151
+ return media === "" ? "no content type" : media;
1152
+ }
1153
+ function jsonKind(value) {
1154
+ if (value === null) return "null";
1155
+ if (Array.isArray(value)) return "array";
1156
+ return typeof value;
1157
+ }
1158
+ function isJsonObject(value) {
1159
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1160
+ }
1161
+ var MISSING = /* @__PURE__ */ Symbol("missing");
1162
+ function lookup(body, path) {
1163
+ let value = body;
1164
+ for (const key of path.split(".")) {
1165
+ if (!isJsonObject(value) || !Object.prototype.hasOwnProperty.call(value, key)) return MISSING;
1166
+ value = value[key];
1167
+ }
1168
+ return value;
1169
+ }
1170
+ function shapeProblem(body, shape) {
1171
+ const missing = (path) => `Expected "${path}" in the response; it is missing`;
1172
+ const wrongKind = (path, expected, value) => `Expected "${path}" to be ${KIND_NAMES[expected]}, got ${jsonKind(value)}`;
1173
+ for (const path of shape.required ?? []) {
1174
+ const value = lookup(body, path);
1175
+ if (value === MISSING || value === null) return missing(path);
1176
+ }
1177
+ for (const { path, kind } of shape.fields ?? []) {
1178
+ const value = lookup(body, path);
1179
+ if (value === MISSING || value === null || kind === "string" && value === "") return missing(path);
1180
+ const ok = kind === "object" ? isJsonObject(value) : typeof value === kind;
1181
+ if (!ok) return wrongKind(path, kind, value);
1182
+ }
1183
+ for (const path of shape.optionalObjects ?? []) {
1184
+ const value = lookup(body, path);
1185
+ if (value !== MISSING && value !== null && !isJsonObject(value)) return wrongKind(path, "object", value);
1186
+ }
1187
+ for (const path of shape.lists ?? []) {
1188
+ const value = lookup(body, path);
1189
+ if (value === MISSING || value === null) continue;
1190
+ if (!Array.isArray(value)) return `Expected "${path}" to be a list, got ${jsonKind(value)}`;
1191
+ for (let index = 0; index < value.length; index++) {
1192
+ const item = value[index];
1193
+ if (!isJsonObject(item)) {
1194
+ return `Expected every item of "${path}" to be an object, got ${jsonKind(item)} at index ${index}`;
1195
+ }
1196
+ }
1197
+ }
1198
+ return void 0;
1199
+ }
1200
+ function hasErrorEnvelope(body) {
1201
+ const err = body["error"];
1202
+ return isJsonObject(err) || typeof err === "string" && err !== "";
1203
+ }
1204
+ async function readJsonBody(response, shape, touch) {
1205
+ const status = response.status;
1206
+ const headers = parseResponseHeaders(response);
1207
+ const invalid = (message, body2, bodyExcerpt) => new InvalidResponseError(message, status, body2, { headers, ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {} });
1208
+ if (status === 204) {
1209
+ discardBody(response);
1210
+ if (shape.allowEmpty === true) return {};
1211
+ throw invalid("Expected JSON, got no body");
1212
+ }
1213
+ const bytes = await readBodyBytes(response, touch);
1214
+ if (bytes.byteLength === 0) {
1215
+ if (shape.allowEmpty === true) return {};
1216
+ throw invalid("Expected JSON, got no body");
1217
+ }
1218
+ const body = parseJsonBytes(bytes);
1219
+ if (body === NOT_JSON) {
1220
+ throw invalid(
1221
+ `Expected JSON, got ${mediaTypeOf(response)} that does not parse as JSON (${bytes.byteLength} bytes)`,
1222
+ void 0,
1223
+ excerptOf(bytes)
805
1224
  );
806
1225
  }
1226
+ if (!isJsonObject(body)) throw invalid(`Expected a JSON object, got ${jsonKind(body)}`, body);
1227
+ if (body["success"] === false && shape.successFalseOk !== true) {
1228
+ if (hasErrorEnvelope(body)) throw LexAPIError.fromResponse(status, body, void 0, headers);
1229
+ throw invalid("Response reported success: false without an error", body);
1230
+ }
1231
+ const problem = shapeProblem(body, shape);
1232
+ if (problem !== void 0) throw invalid(problem, body);
1233
+ return body;
807
1234
  }
808
1235
  function throwIfAborted(signal, method, path) {
809
1236
  if (signal?.aborted) {
@@ -811,39 +1238,24 @@ function throwIfAborted(signal, method, path) {
811
1238
  }
812
1239
  }
813
1240
  async function parseErrorResponse(response, touch) {
814
- let body;
815
- try {
816
- const text = await readBodyText(response, touch);
817
- body = text.trim() === "" ? void 0 : JSON.parse(text);
818
- } catch (cause) {
819
- if (!(cause instanceof SyntaxError)) throw cause;
820
- body = void 0;
821
- }
1241
+ const bytes = await readBodyBytes(response, touch);
1242
+ const parsed = bytes.byteLength === 0 ? NOT_JSON : parseJsonBytes(bytes);
1243
+ const body = parsed === NOT_JSON ? void 0 : parsed;
1244
+ const bodyExcerpt = parsed === NOT_JSON ? excerptOf(bytes) : void 0;
822
1245
  const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
823
- return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
1246
+ return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response), bodyExcerpt);
824
1247
  }
825
1248
  function headerRetryAfterSeconds(response) {
826
- const raw = response.headers.get("retry-after");
827
- if (raw === null) return void 0;
828
- const header = raw.trim();
829
- if (header === "") return void 0;
830
- if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
831
- if (/^[-+]?\d/.test(header)) return void 0;
832
- const date = Date.parse(header);
833
- if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
834
- return void 0;
1249
+ return retryAfterHeaderSeconds(response.headers.get("retry-after"));
835
1250
  }
836
1251
  function resetHeaderSeconds(response, name) {
837
- const raw = response.headers.get(name);
838
- if (raw === null || raw.trim() === "") return void 0;
839
- const seconds = Number(raw);
840
- if (!Number.isFinite(seconds) || seconds < 0) return void 0;
841
- return normalizeRetryAfterSeconds(seconds);
1252
+ return decimalSeconds(response.headers.get(name));
842
1253
  }
843
1254
  function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
844
1255
  return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
845
1256
  }
846
1257
  function sleep(ms, signal, method, path) {
1258
+ ms = timerDelay(ms);
847
1259
  return new Promise((resolve, reject) => {
848
1260
  if (signal?.aborted) {
849
1261
  reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
@@ -878,6 +1290,39 @@ function buildQuery(query) {
878
1290
  }
879
1291
 
880
1292
  // src/export.ts
1293
+ var INVALID_LINE = /* @__PURE__ */ Symbol("invalid line");
1294
+ var NO_BYTES = new Uint8Array(0);
1295
+ function heldBytes(previous, chunk) {
1296
+ const n = chunk.length;
1297
+ if (n > 0 && chunk[n - 1] < 128) return NO_BYTES;
1298
+ const tail = n >= 3 ? chunk.subarray(n - 3) : new Uint8Array([...previous, ...chunk].slice(-3));
1299
+ for (let k = 1; k <= tail.length; k++) {
1300
+ const byte = tail[tail.length - k];
1301
+ if ((byte & 192) === 128) continue;
1302
+ const size = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
1303
+ return size > k ? tail.slice(tail.length - k) : NO_BYTES;
1304
+ }
1305
+ return NO_BYTES;
1306
+ }
1307
+ function strictDecoder() {
1308
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1309
+ }
1310
+ function byteView(chunk) {
1311
+ if (chunk instanceof Uint8Array) return chunk;
1312
+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
1313
+ if (ArrayBuffer.isView(chunk)) return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
1314
+ return void 0;
1315
+ }
1316
+ function trimLine(line) {
1317
+ let start = 0;
1318
+ let end = line.length;
1319
+ while (start < end && isLineSpace(line.charCodeAt(start))) start++;
1320
+ while (end > start && isLineSpace(line.charCodeAt(end - 1))) end--;
1321
+ return start === 0 && end === line.length ? line : line.slice(start, end);
1322
+ }
1323
+ function isLineSpace(code) {
1324
+ return code === 32 || code === 9 || code === 13;
1325
+ }
881
1326
  var NdjsonReader = class {
882
1327
  constructor(body, options) {
883
1328
  this.options = options;
@@ -887,54 +1332,175 @@ var NdjsonReader = class {
887
1332
  else signal?.addEventListener("abort", this.onAbort, { once: true });
888
1333
  }
889
1334
  reader;
890
- decoder = new TextDecoder();
891
- /** Pieces of the line currently being received. */
1335
+ /** Decodes the line in progress; holds the bytes of a character split across chunks. */
1336
+ decoder = strictDecoder();
1337
+ /** A copy of the bytes the decoder holds (a character not yet complete), so it can be rebuilt. */
1338
+ carry = NO_BYTES;
1339
+ /** Text pieces of the line in progress. */
892
1340
  partial = [];
1341
+ /** The line in progress already holds bytes that are not UTF-8. */
1342
+ broken = false;
893
1343
  /** Complete lines not yet handed out. */
894
1344
  ready = [];
1345
+ /** No line has been completed yet. */
1346
+ atStart = true;
1347
+ /** The first line of the stream was blank (so the first line handed out is not the stream's first). */
1348
+ firstLineBlank = false;
895
1349
  eof = false;
896
1350
  released = false;
897
1351
  /** Data rows handed out so far (for error messages). */
898
1352
  rows = 0;
899
1353
  /** Releases the connection the moment the caller aborts — even while nobody is reading. */
900
1354
  onAbort = () => this.cancel();
901
- /** Next trimmed, non-empty line, or `undefined` at EOF. */
1355
+ /** Next non-blank line (trimmed), or `INVALID_LINE`, or `undefined` at EOF. */
902
1356
  async nextLine() {
903
1357
  const { signal } = this.options;
904
1358
  if (signal?.aborted) {
905
1359
  this.cancel();
906
1360
  throw new RequestAbortedError("Export stream was aborted", signal.reason);
907
1361
  }
908
- for (; ; ) {
909
- const line = this.ready.shift();
910
- if (line !== void 0) return line;
911
- if (this.eof) {
912
- const tail = this.partial.join("").trim();
913
- this.partial = [];
914
- return tail || void 0;
1362
+ try {
1363
+ for (; ; ) {
1364
+ const line = this.ready.shift();
1365
+ if (line !== void 0) return line;
1366
+ if (this.eof) return void 0;
1367
+ const result = await this.read();
1368
+ if (result.done) {
1369
+ this.finish();
1370
+ this.release();
1371
+ } else {
1372
+ this.ingest(result.value);
1373
+ }
915
1374
  }
916
- const chunk = await this.read();
917
- if (chunk === void 0) {
918
- this.eof = true;
919
- this.ingest(this.decoder.decode());
920
- this.release();
921
- } else {
922
- this.ingest(this.decoder.decode(chunk, { stream: true }));
1375
+ } catch (cause) {
1376
+ this.cancel();
1377
+ if (cause instanceof LexAPIError) throw cause;
1378
+ throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
1379
+ }
1380
+ }
1381
+ ingest(value) {
1382
+ const chunk = byteView(value);
1383
+ if (chunk === void 0) throw new TypeError("Export stream yielded a chunk that is not bytes");
1384
+ if (!this.broken) {
1385
+ let text2;
1386
+ try {
1387
+ text2 = this.decoder.decode(chunk, { stream: true });
1388
+ } catch {
1389
+ this.decoder = strictDecoder();
1390
+ if (this.carry.length > 0) this.decoder.decode(this.carry, { stream: true });
1391
+ }
1392
+ if (text2 !== void 0) {
1393
+ this.carry = heldBytes(this.carry, chunk);
1394
+ let pos = 0;
1395
+ for (; ; ) {
1396
+ const newline = text2.indexOf("\n", pos);
1397
+ if (newline === -1) break;
1398
+ this.partial.push(text2.slice(pos, newline));
1399
+ const line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1400
+ this.partial = [];
1401
+ this.complete(line);
1402
+ pos = newline + 1;
1403
+ }
1404
+ if (pos < text2.length) this.partial.push(pos === 0 ? text2 : text2.slice(pos));
1405
+ return;
923
1406
  }
924
1407
  }
1408
+ this.ingestBytes(chunk);
925
1409
  }
926
- ingest(text) {
1410
+ /** A chunk that is not all UTF-8, or that continues a line that is not. */
1411
+ ingestBytes(chunk) {
1412
+ const first = chunk.indexOf(10);
1413
+ if (first === -1) {
1414
+ this.feed(chunk);
1415
+ return;
1416
+ }
1417
+ const last = chunk.lastIndexOf(10);
1418
+ let line = INVALID_LINE;
1419
+ if (!this.broken) {
1420
+ try {
1421
+ const text2 = this.decoder.decode(chunk.subarray(0, first + 1), { stream: true });
1422
+ this.partial.push(text2.slice(0, -1));
1423
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1424
+ } catch {
1425
+ this.decoder = strictDecoder();
1426
+ }
1427
+ }
1428
+ this.partial = [];
1429
+ this.broken = false;
1430
+ this.carry = NO_BYTES;
1431
+ this.complete(line);
1432
+ if (first < last) this.completeRegion(chunk.subarray(first + 1, last + 1));
1433
+ if (last + 1 < chunk.length) this.feed(chunk.subarray(last + 1));
1434
+ }
1435
+ /** Whole lines, each ending with its line feed. */
1436
+ completeRegion(region) {
1437
+ let text2;
1438
+ try {
1439
+ text2 = this.decoder.decode(region, { stream: true });
1440
+ } catch {
1441
+ this.decoder = strictDecoder();
1442
+ }
1443
+ if (text2 !== void 0) {
1444
+ let pos2 = 0;
1445
+ for (; ; ) {
1446
+ const newline = text2.indexOf("\n", pos2);
1447
+ if (newline === -1) break;
1448
+ this.complete(text2.slice(pos2, newline));
1449
+ pos2 = newline + 1;
1450
+ }
1451
+ return;
1452
+ }
927
1453
  let pos = 0;
928
- for (; ; ) {
929
- const newline = text.indexOf("\n", pos);
930
- if (newline === -1) break;
931
- this.partial.push(text.slice(pos, newline));
932
- const line = this.partial.join("").trim();
933
- this.partial = [];
934
- if (line) this.ready.push(line);
1454
+ while (pos < region.length) {
1455
+ const newline = region.indexOf(10, pos);
1456
+ try {
1457
+ this.complete(this.decoder.decode(region.subarray(pos, newline + 1), { stream: true }).slice(0, -1));
1458
+ } catch {
1459
+ this.decoder = strictDecoder();
1460
+ this.complete(INVALID_LINE);
1461
+ }
935
1462
  pos = newline + 1;
936
1463
  }
937
- if (pos < text.length) this.partial.push(text.slice(pos));
1464
+ }
1465
+ /** Bytes of the line in progress (after a line feed, or continuing a line that is not UTF-8). */
1466
+ feed(bytes) {
1467
+ if (this.broken || bytes.length === 0) return;
1468
+ try {
1469
+ const text2 = this.decoder.decode(bytes, { stream: true });
1470
+ if (text2) this.partial.push(text2);
1471
+ this.carry = heldBytes(this.carry, bytes);
1472
+ } catch {
1473
+ this.broken = true;
1474
+ this.decoder = strictDecoder();
1475
+ this.carry = NO_BYTES;
1476
+ }
1477
+ }
1478
+ /** End of stream: the line in progress, if any. */
1479
+ finish() {
1480
+ this.eof = true;
1481
+ let line = INVALID_LINE;
1482
+ if (!this.broken) {
1483
+ try {
1484
+ this.partial.push(this.decoder.decode());
1485
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1486
+ } catch {
1487
+ }
1488
+ }
1489
+ this.partial = [];
1490
+ this.broken = false;
1491
+ this.complete(line);
1492
+ }
1493
+ /** Queue a complete line: a byte order mark leading the stream is dropped; blank lines are skipped. */
1494
+ complete(line) {
1495
+ const first = this.atStart;
1496
+ this.atStart = false;
1497
+ if (line === INVALID_LINE) {
1498
+ this.ready.push(line);
1499
+ return;
1500
+ }
1501
+ const text2 = trimLine(first && line.charCodeAt(0) === 65279 ? line.slice(1) : line);
1502
+ if (text2) this.ready.push(text2);
1503
+ else if (first) this.firstLineBlank = true;
938
1504
  }
939
1505
  async read() {
940
1506
  const { idleTimeoutMs, signal } = this.options;
@@ -945,12 +1511,12 @@ var NdjsonReader = class {
945
1511
  let timer;
946
1512
  let onAbort;
947
1513
  const interruptions = new Promise((_, reject) => {
948
- if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
1514
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0 && idleTimeoutMs !== Infinity) {
949
1515
  timer = setTimeout(() => {
950
1516
  reject(
951
1517
  new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
952
1518
  );
953
- }, idleTimeoutMs);
1519
+ }, timerDelay(idleTimeoutMs));
954
1520
  }
955
1521
  if (signal) {
956
1522
  onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
@@ -960,7 +1526,7 @@ var NdjsonReader = class {
960
1526
  try {
961
1527
  const result = await Promise.race([this.reader.read(), interruptions]);
962
1528
  if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
963
- return result.done ? void 0 : result.value;
1529
+ return result;
964
1530
  } catch (cause) {
965
1531
  this.cancel();
966
1532
  if (cause instanceof LexAPIError) throw cause;
@@ -994,17 +1560,25 @@ var NdjsonReader = class {
994
1560
  function liftEnvelope(parsed, key) {
995
1561
  const inner = parsed[key];
996
1562
  if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
997
- return { ...inner, ...parsed };
1563
+ return { ...inner, [key]: inner };
998
1564
  }
999
1565
  return parsed;
1000
1566
  }
1567
+ function text(value) {
1568
+ try {
1569
+ return String(value);
1570
+ } catch {
1571
+ return Array.isArray(value) ? "array" : typeof value;
1572
+ }
1573
+ }
1001
1574
  function errorLine(parsed) {
1002
1575
  const keys = Object.keys(parsed);
1003
1576
  if (keys.length !== 1 || keys[0] !== "_error") return void 0;
1004
1577
  const value = parsed._error;
1005
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: String(value) };
1578
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: text(value) };
1006
1579
  }
1007
1580
  function parseLine(line) {
1581
+ if (line === INVALID_LINE) return void 0;
1008
1582
  try {
1009
1583
  const value = JSON.parse(line);
1010
1584
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -1033,7 +1607,7 @@ var ExportStreamImpl = class {
1033
1607
  }
1034
1608
  failureReason() {
1035
1609
  if (this.error !== void 0) {
1036
- return `the server reported an error mid-stream (${String(this.error.code ?? "UNKNOWN")}: ${String(this.error.message ?? "")})`;
1610
+ return `the server reported an error mid-stream (${text(this.error.code ?? "UNKNOWN")}: ${text(this.error.message ?? "")})`;
1037
1611
  }
1038
1612
  return "its _done trailer says complete: false";
1039
1613
  }
@@ -1044,7 +1618,7 @@ var ExportStreamImpl = class {
1044
1618
  if (typeof this.done?.truncated === "boolean") return this.done.truncated;
1045
1619
  if (this.headers.truncated !== void 0) return this.headers.truncated;
1046
1620
  if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
1047
- return void 0;
1621
+ return false;
1048
1622
  }
1049
1623
  constructor(lines, headers) {
1050
1624
  this.lines = lines;
@@ -1056,21 +1630,20 @@ var ExportStreamImpl = class {
1056
1630
  }
1057
1631
  /** Read the leading line so `meta` is available before iteration starts. */
1058
1632
  async init() {
1059
- let parsed;
1060
- for (; ; ) {
1061
- const first = await this.lines.nextLine();
1062
- if (first === void 0) return;
1063
- parsed = parseLine(first);
1064
- if (parsed !== void 0) {
1065
- const error = errorLine(parsed);
1066
- if (error === void 0) break;
1067
- this.error = error;
1068
- continue;
1069
- }
1633
+ const first = await this.lines.nextLine();
1634
+ if (first === void 0) return;
1635
+ const parsed = parseLine(first);
1636
+ if (parsed === void 0) {
1070
1637
  this.invalidLines++;
1638
+ return;
1639
+ }
1640
+ const error = errorLine(parsed);
1641
+ if (error !== void 0) {
1642
+ this.error = error;
1643
+ return;
1071
1644
  }
1072
1645
  if ("_meta" in parsed) {
1073
- this.meta = liftEnvelope(parsed, "_meta");
1646
+ if (!this.lines.firstLineBlank) this.meta = liftEnvelope(parsed, "_meta");
1074
1647
  } else if ("_done" in parsed) {
1075
1648
  this.done = liftEnvelope(parsed, "_done");
1076
1649
  this.lines.cancel();
@@ -1113,12 +1686,12 @@ var ExportStreamImpl = class {
1113
1686
  this.invalidLines++;
1114
1687
  continue;
1115
1688
  }
1689
+ if ("_meta" in parsed) continue;
1116
1690
  if ("_done" in parsed) {
1117
1691
  this.done = liftEnvelope(parsed, "_done");
1118
1692
  if (!this.complete) throw this.incomplete(this.failureReason());
1119
1693
  return;
1120
1694
  }
1121
- if ("_meta" in parsed) continue;
1122
1695
  const error = errorLine(parsed);
1123
1696
  if (error !== void 0) {
1124
1697
  this.error = error;
@@ -1132,6 +1705,10 @@ var ExportStreamImpl = class {
1132
1705
  }
1133
1706
  }
1134
1707
  };
1708
+ function truncatedFlag(value) {
1709
+ const flag = value === null ? void 0 : trimSpaces(value);
1710
+ return flag === "1" ? true : flag === "0" ? false : void 0;
1711
+ }
1135
1712
  async function createExportStream(response, options = {}) {
1136
1713
  if (response.body === null) {
1137
1714
  throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
@@ -1140,14 +1717,63 @@ async function createExportStream(response, options = {}) {
1140
1717
  const streamingHeader = response.headers.get("x-export-streaming");
1141
1718
  const truncatedHeader = response.headers.get("x-export-truncated");
1142
1719
  const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
1143
- total: totalHeader !== null ? Number(totalHeader) : void 0,
1144
- streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
1145
- truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
1720
+ total: parseHeaderInteger(totalHeader),
1721
+ streaming: parseHeaderInteger(streamingHeader),
1722
+ truncated: truncatedFlag(truncatedHeader)
1146
1723
  });
1147
1724
  await stream.init();
1148
1725
  return stream;
1149
1726
  }
1150
1727
 
1728
+ // src/paging.ts
1729
+ function count(value) {
1730
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1731
+ }
1732
+ var REPEATS_BEFORE_THROW = 3;
1733
+ function startingPosition(offset, limit, defaultLimit) {
1734
+ if (offset !== void 0 && count(offset) === void 0) {
1735
+ throw new RangeError(`offset must be a non-negative integer, got ${String(offset)}`);
1736
+ }
1737
+ if (limit !== void 0 && !(count(limit) !== void 0 && limit > 0)) {
1738
+ throw new RangeError(`limit must be a positive integer, got ${String(limit)}`);
1739
+ }
1740
+ return { offset: offset ?? 0, limit: limit ?? defaultLimit };
1741
+ }
1742
+ function stalled(reason, page) {
1743
+ return new InvalidResponseError(`Pagination stopped: ${reason}`, 200, page);
1744
+ }
1745
+ var Token = class {
1746
+ constructor(text2) {
1747
+ this.text = text2;
1748
+ }
1749
+ };
1750
+ function compactForm(value) {
1751
+ let out = "";
1752
+ const stack = [value];
1753
+ while (stack.length > 0) {
1754
+ const item = stack.pop();
1755
+ if (item instanceof Token) out += item.text;
1756
+ else if (typeof item === "string") out += JSON.stringify(item);
1757
+ else if (Array.isArray(item)) {
1758
+ out += "[";
1759
+ stack.push(new Token("]"));
1760
+ for (let i = item.length - 1; i >= 0; i--) {
1761
+ stack.push(item[i]);
1762
+ if (i > 0) stack.push(new Token(","));
1763
+ }
1764
+ } else if (typeof item === "object" && item !== null) {
1765
+ out += "{";
1766
+ stack.push(new Token("}"));
1767
+ const keys = Object.keys(item).sort();
1768
+ for (let i = keys.length - 1; i >= 0; i--) {
1769
+ stack.push(item[keys[i]]);
1770
+ stack.push(new Token(`${i > 0 ? "," : ""}${JSON.stringify(keys[i])}:`));
1771
+ }
1772
+ } else out += String(item);
1773
+ }
1774
+ return out;
1775
+ }
1776
+
1151
1777
  // src/webhooks.ts
1152
1778
  var WebhooksAPI = class {
1153
1779
  http;
@@ -1167,6 +1793,7 @@ var WebhooksAPI = class {
1167
1793
  return this.call({
1168
1794
  method: "GET",
1169
1795
  path: "/webhooks",
1796
+ shape: { lists: ["webhooks"] },
1170
1797
  free: true,
1171
1798
  timeoutMs: options?.timeoutMs,
1172
1799
  signal: options?.signal
@@ -1227,6 +1854,7 @@ var WebhooksAPI = class {
1227
1854
  return this.call({
1228
1855
  method: "DELETE",
1229
1856
  path: `/webhooks/${encodeURIComponent(id)}`,
1857
+ shape: { allowEmpty: true },
1230
1858
  timeoutMs: options?.timeoutMs,
1231
1859
  signal: options?.signal
1232
1860
  });
@@ -1241,6 +1869,7 @@ var WebhooksAPI = class {
1241
1869
  return this.call({
1242
1870
  method: "POST",
1243
1871
  path: `/webhooks/${encodeURIComponent(id)}/test`,
1872
+ shape: { successFalseOk: true },
1244
1873
  timeoutMs: options?.timeoutMs,
1245
1874
  signal: options?.signal
1246
1875
  });
@@ -1250,6 +1879,7 @@ var WebhooksAPI = class {
1250
1879
  return this.call({
1251
1880
  method: "GET",
1252
1881
  path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
1882
+ shape: { lists: ["deliveries"] },
1253
1883
  free: true,
1254
1884
  query: { limit: params.limit, offset: params.offset },
1255
1885
  timeoutMs: options?.timeoutMs,
@@ -1261,7 +1891,13 @@ var WebhooksAPI = class {
1261
1891
  * 50), starting at `offset`, newest first (SDK contract §1.4). Each
1262
1892
  * delivery is yielded at most once (deduplicated on `id`): a delivery
1263
1893
  * created during the walk shifts later pages by one. Stops on an empty page
1264
- * or when the offset reaches `total`. Pages are free (0 credits).
1894
+ * or when the offset reaches `total`. Without a usable `total`, three pages
1895
+ * in a row that bring no unseen `id` throw `InvalidResponseError` (a page
1896
+ * with a usable `total` ends a run). When a walk throws, the pages already
1897
+ * yielded stay valid; the page that showed the stall is not yielded and is
1898
+ * on the error's `body`. A starting `offset` or `limit` that is not a
1899
+ * non-negative (positive) integer is a `RangeError` before any request.
1900
+ * Pages are free (0 credits).
1265
1901
  *
1266
1902
  * ```ts
1267
1903
  * for await (const page of client.webhooks.paginateDeliveries(id)) {
@@ -1270,21 +1906,36 @@ var WebhooksAPI = class {
1270
1906
  * ```
1271
1907
  */
1272
1908
  async *paginateDeliveries(id, params = {}, options) {
1273
- const limit = params.limit ?? 50;
1274
- let offset = params.offset ?? 0;
1909
+ const start = startingPosition(params.offset, params.limit, 50);
1910
+ const limit = start.limit;
1911
+ let offset = start.offset;
1275
1912
  const seen = /* @__PURE__ */ new Set();
1913
+ let repeats = 0;
1276
1914
  for (; ; ) {
1277
1915
  const page = await this.deliveries(id, { limit, offset }, options);
1278
- const count = page.deliveries.length;
1279
- const fresh = page.deliveries.filter((d) => {
1916
+ const listed = page.deliveries;
1917
+ const deliveries = Array.isArray(listed) ? listed : [];
1918
+ const rows = deliveries.length;
1919
+ let readable = 0;
1920
+ let unseen = 0;
1921
+ const fresh = deliveries.filter((d) => {
1280
1922
  if (typeof d.id !== "string") return true;
1923
+ readable++;
1281
1924
  if (seen.has(d.id)) return false;
1282
1925
  seen.add(d.id);
1926
+ unseen++;
1283
1927
  return true;
1284
1928
  });
1929
+ const total = count(page.total);
1930
+ if (total === void 0) {
1931
+ repeats = readable > 0 && unseen === 0 ? repeats + 1 : 0;
1932
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same deliveries", page);
1933
+ } else {
1934
+ repeats = 0;
1935
+ }
1285
1936
  yield { ...page, deliveries: fresh };
1286
- offset += count;
1287
- if (count === 0 || page.total !== void 0 && offset >= page.total) return;
1937
+ offset += rows;
1938
+ if (rows === 0 || total !== void 0 && offset >= total) return;
1288
1939
  }
1289
1940
  }
1290
1941
  };
@@ -1299,11 +1950,16 @@ var LexAPI = class {
1299
1950
  if (!apiKey) {
1300
1951
  throw new Error("apiKey is required (or set LEXAPI_API_KEY)");
1301
1952
  }
1953
+ if (options.fetch === void 0 && typeof globalThis.fetch !== "function") {
1954
+ throw new Error("This runtime has no global fetch; pass one with the `fetch` option");
1955
+ }
1302
1956
  this.http = new HttpClient({
1303
1957
  apiKey,
1304
1958
  baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
1305
1959
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1306
- fetchFn: options.fetch ?? fetch,
1960
+ // Looked up per call and invoked on the global object, which Cloudflare
1961
+ // Workers and browsers require.
1962
+ fetchFn: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
1307
1963
  retry: {
1308
1964
  maxRetries: options.retry?.maxRetries ?? 3,
1309
1965
  baseDelayMs: options.retry?.baseDelayMs ?? 500,
@@ -1361,6 +2017,7 @@ var LexAPI = class {
1361
2017
  return this.call({
1362
2018
  method: "POST",
1363
2019
  path: "/search",
2020
+ shape: { lists: ["results"], required: ["results"] },
1364
2021
  body: request,
1365
2022
  idempotent: true,
1366
2023
  timeoutMs: options?.timeoutMs,
@@ -1385,6 +2042,7 @@ var LexAPI = class {
1385
2042
  return this.call({
1386
2043
  method: "POST",
1387
2044
  path: "/documentContent",
2045
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1388
2046
  body: request,
1389
2047
  idempotent: true,
1390
2048
  timeoutMs: options?.timeoutMs,
@@ -1406,6 +2064,7 @@ var LexAPI = class {
1406
2064
  return this.call({
1407
2065
  method: "POST",
1408
2066
  path: "/documentContent/batch",
2067
+ shape: { lists: ["documents", "errors"] },
1409
2068
  body: request,
1410
2069
  idempotent: true,
1411
2070
  timeoutMs: options?.timeoutMs,
@@ -1428,6 +2087,7 @@ var LexAPI = class {
1428
2087
  return this.call({
1429
2088
  method: "GET",
1430
2089
  path: "/documents/recent",
2090
+ shape: { lists: ["results"] },
1431
2091
  query: {
1432
2092
  days: params.days,
1433
2093
  documentType: params.documentType,
@@ -1450,6 +2110,7 @@ var LexAPI = class {
1450
2110
  return this.call({
1451
2111
  method: "POST",
1452
2112
  path: "/documents/url",
2113
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1453
2114
  body: request,
1454
2115
  idempotent: true,
1455
2116
  timeoutMs: options?.timeoutMs,
@@ -1488,18 +2149,20 @@ var LexAPI = class {
1488
2149
  });
1489
2150
  }
1490
2151
  // ── Point-in-time versions ────────────────────────────────────────
1491
- // Versions are LexAPI observation snapshots (content-hash changes between
1492
- // fetches), NOT legal in-force reconstructions; history begins at first
1493
- // ingestion. For the text in force on a date, use a consolidated CELEX or
1494
- // semanticLegislationSearch({ asOf }).
2152
+ // Versions are LexAPI's fetch snapshots (content-hash changes between
2153
+ // fetches), NOT the law in force on a date; history begins at first
2154
+ // ingestion. For the version of an EU act for a date, use legislationAsOf.
1495
2155
  /**
1496
2156
  * `GET /documents/{celex}/versions` — version history, newest first,
1497
- * current version included and flagged. 1 credit.
2157
+ * current version included and flagged. These are LexAPI's fetch
2158
+ * snapshots, not the law in force on a date; for the version of an EU act
2159
+ * for a date use `legislationAsOf`. 1 credit.
1498
2160
  */
1499
2161
  async listDocumentVersions(celex, params = {}, options) {
1500
2162
  return this.call({
1501
2163
  method: "GET",
1502
2164
  path: `/documents/${encodeURIComponent(celex)}/versions`,
2165
+ shape: { lists: ["versions"] },
1503
2166
  query: { language: params.language },
1504
2167
  timeoutMs: options?.timeoutMs,
1505
2168
  signal: options?.signal
@@ -1508,27 +2171,41 @@ var LexAPI = class {
1508
2171
  /**
1509
2172
  * `GET /documents/{celex}/versions/{version}` — one immutable snapshot
1510
2173
  * including `parsedContent`. `corpusVersion` mirrors the
1511
- * `X-Corpus-Version` response header. 1 credit.
2174
+ * `X-Corpus-Version` response header. This is one of LexAPI's fetch
2175
+ * snapshots, not the law in force on a date; for the version of an EU act
2176
+ * for a date use `legislationAsOf`. 1 credit.
1512
2177
  */
1513
2178
  async getDocumentVersion(celex, version, params = {}, options) {
1514
2179
  return this.call({
1515
2180
  method: "GET",
1516
2181
  path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
2182
+ shape: { fields: [{ path: "document", kind: "object" }] },
1517
2183
  query: { language: params.language },
1518
2184
  timeoutMs: options?.timeoutMs,
1519
2185
  signal: options?.signal
1520
2186
  }, { corpusVersion: true });
1521
2187
  }
1522
2188
  /**
1523
- * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
1524
- * current on `date` (`YYYY-MM-DD`, end-of-day UTC inclusive). Dates
1525
- * before the document entered the corpus reject with `NotFoundError`
1526
- * carrying the tracking start date. 1 credit.
2189
+ * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI held as current
2190
+ * at the end of `date` (`YYYY-MM-DD`, UTC), from its own fetch history
2191
+ * (`kind: "observation_snapshot"`). This is not the law in force on that
2192
+ * date: for the version of an EU act for a date use `legislationAsOf`
2193
+ * (`inForceLookup` points to it). The snapshot was the current one from
2194
+ * `document.observedFrom` until `document.observedUntil` (`null` for the
2195
+ * current version). A future date returns the current version with
2196
+ * `dateInFuture: true`.
2197
+ *
2198
+ * A date before the document entered the corpus rejects with
2199
+ * `NotFoundError` where `beforeTracking` is `true` (`trackedSince`); a date
2200
+ * next to a version stored before API 2.28.0 whose start LexAPI has no
2201
+ * record of rejects with `boundaryUnknown` `true` and `candidates`
2202
+ * (refunded). 1 credit.
1527
2203
  */
1528
2204
  async getDocumentAtDate(celex, date, params = {}, options) {
1529
2205
  return this.call({
1530
2206
  method: "GET",
1531
2207
  path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
2208
+ shape: { fields: [{ path: "document", kind: "object" }] },
1532
2209
  query: { language: params.language },
1533
2210
  timeoutMs: options?.timeoutMs,
1534
2211
  signal: options?.signal
@@ -1545,6 +2222,7 @@ var LexAPI = class {
1545
2222
  return this.call({
1546
2223
  method: "POST",
1547
2224
  path: "/citations/extract",
2225
+ shape: { lists: ["citations"] },
1548
2226
  body: { celexNumber },
1549
2227
  timeoutMs: options?.timeoutMs,
1550
2228
  signal: options?.signal
@@ -1571,6 +2249,7 @@ var LexAPI = class {
1571
2249
  return this.call({
1572
2250
  method: "GET",
1573
2251
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
2252
+ shape: { lists: ["cites", "unresolved"] },
1574
2253
  query: { ...edgeQuery(params), unresolved: params.unresolved },
1575
2254
  timeoutMs: options?.timeoutMs,
1576
2255
  signal: options?.signal
@@ -1590,6 +2269,7 @@ var LexAPI = class {
1590
2269
  return this.call({
1591
2270
  method: "GET",
1592
2271
  path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
2272
+ shape: { lists: ["citedBy"] },
1593
2273
  query: edgeQuery(params),
1594
2274
  timeoutMs: options?.timeoutMs,
1595
2275
  signal: options?.signal
@@ -1603,26 +2283,39 @@ var LexAPI = class {
1603
2283
  * missed. A target's edges can straddle a page boundary, so the same
1604
2284
  * `celexNumber` may appear in two consecutive pages — merge by
1605
2285
  * `celexNumber` if you need one group per document.
2286
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2287
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2288
+ * an `offset` other than the one requested, or, when the answers carry
2289
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2290
+ * repeat the one before (comparing the list only; a page with either
2291
+ * signal ends a run, and its list is still the one the next page is
2292
+ * compared with). When a walk throws, the pages already yielded stay
2293
+ * valid; the page that showed the stall is not yielded and is on the
2294
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2295
+ * (positive) integer is a `RangeError` before any request. A group whose
2296
+ * `citationCount` is 0 but whose edge list is not empty counts its list.
1606
2297
  */
1607
2298
  async *paginateCites(celexNumber, params = {}, options) {
1608
- yield* paginateEdges(
1609
- (p) => this.getCites(celexNumber, p, options),
1610
- (page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1611
- params
1612
- );
2299
+ yield* paginateEdges((p) => this.getCites(celexNumber, p, options), (page) => page.cites, params);
1613
2300
  }
1614
2301
  /**
1615
2302
  * Walk every page of `getCitedBy` (offset in edge rows) until a short or
1616
2303
  * empty page (SDK contract §1.4). Each page is a billed call (1 credit);
1617
2304
  * edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
1618
2305
  * `celexNumber` may appear in two consecutive pages.
2306
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2307
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2308
+ * an `offset` other than the one requested, or, when the answers carry
2309
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2310
+ * repeat the one before (comparing the list only; a page with either
2311
+ * signal ends a run, and its list is still the one the next page is
2312
+ * compared with). When a walk throws, the pages already yielded stay
2313
+ * valid; the page that showed the stall is not yielded and is on the
2314
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2315
+ * (positive) integer is a `RangeError` before any request.
1619
2316
  */
1620
2317
  async *paginateCitedBy(celexNumber, params = {}, options) {
1621
- yield* paginateEdges(
1622
- (p) => this.getCitedBy(celexNumber, p, options),
1623
- (page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1624
- params
1625
- );
2318
+ yield* paginateEdges((p) => this.getCitedBy(celexNumber, p, options), (page) => page.citedBy, params);
1626
2319
  }
1627
2320
  /**
1628
2321
  * `GET /citations/network/{celexNumber}` — inbound and outbound
@@ -1640,6 +2333,7 @@ var LexAPI = class {
1640
2333
  return this.call({
1641
2334
  method: "GET",
1642
2335
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
2336
+ shape: { lists: ["network.cites", "network.citedBy", "unresolved"] },
1643
2337
  query: {
1644
2338
  ...filterQuery(params),
1645
2339
  limit: params.limit,
@@ -1666,6 +2360,7 @@ var LexAPI = class {
1666
2360
  return this.call({
1667
2361
  method: "GET",
1668
2362
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
2363
+ shape: { lists: ["path"] },
1669
2364
  query: {
1670
2365
  ...filterQuery(params),
1671
2366
  maxDepth: params.maxDepth,
@@ -1690,6 +2385,7 @@ var LexAPI = class {
1690
2385
  return this.call({
1691
2386
  method: "GET",
1692
2387
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
2388
+ shape: { lists: ["related"] },
1693
2389
  query: {
1694
2390
  ...filterQuery(params),
1695
2391
  limit: params.limit,
@@ -1712,6 +2408,7 @@ var LexAPI = class {
1712
2408
  return this.call({
1713
2409
  method: "GET",
1714
2410
  path: "/citations/stats",
2411
+ shape: { lists: ["stats.mostCited", "stats.mostCiting"] },
1715
2412
  query: { includeNational: effectiveParams?.includeNational },
1716
2413
  timeoutMs: effectiveOptions?.timeoutMs,
1717
2414
  signal: effectiveOptions?.signal
@@ -1740,6 +2437,7 @@ var LexAPI = class {
1740
2437
  return this.call({
1741
2438
  method: "GET",
1742
2439
  path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
2440
+ shape: { lists: ["jurisdictions"] },
1743
2441
  query: {
1744
2442
  jurisdictions: listParam(params.jurisdictions),
1745
2443
  resolvedOnly: params.resolvedOnly,
@@ -1768,6 +2466,7 @@ var LexAPI = class {
1768
2466
  return this.call({
1769
2467
  method: "GET",
1770
2468
  path: `/citations/counterparts/${encodeURIComponent(id)}`,
2469
+ shape: { lists: ["via"] },
1771
2470
  query: {
1772
2471
  jurisdictions: listParam(params.jurisdictions),
1773
2472
  language: params.language
@@ -1794,6 +2493,7 @@ var LexAPI = class {
1794
2493
  return this.call({
1795
2494
  method: "GET",
1796
2495
  path: "/national/coverage",
2496
+ shape: { lists: ["jurisdictions"] },
1797
2497
  free: true,
1798
2498
  timeoutMs: options?.timeoutMs,
1799
2499
  signal: options?.signal
@@ -1821,6 +2521,7 @@ var LexAPI = class {
1821
2521
  return this.call({
1822
2522
  method: "GET",
1823
2523
  path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
2524
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1824
2525
  query: { language: params.language },
1825
2526
  timeoutMs: options?.timeoutMs,
1826
2527
  signal: options?.signal
@@ -1843,6 +2544,7 @@ var LexAPI = class {
1843
2544
  return this.call({
1844
2545
  method: "GET",
1845
2546
  path: `/${jurisdictionSegment(jurisdiction)}/documents`,
2547
+ shape: { lists: ["results"] },
1846
2548
  query: {
1847
2549
  page: params.page,
1848
2550
  cursor: params.cursor,
@@ -1858,26 +2560,41 @@ var LexAPI = class {
1858
2560
  /**
1859
2561
  * Walk every page of `listNationalDocuments` via `cursor` (works past the
1860
2562
  * 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
1861
- * a separate billed call. Stops after a page with `hasMore: false` (or an
1862
- * empty page). Any `params.page` is ignored and never sent — pass
2563
+ * a separate billed call. Stops after a page whose `hasMore` is not `true`,
2564
+ * whose `nextCursor` is absent, `null` or empty, or that is empty. A
2565
+ * `nextCursor` the walk already sent, or one that is not a string, throws
2566
+ * `InvalidResponseError`; the pages already yielded stay valid, and the
2567
+ * page that showed the stall is not yielded and is on the error's `body`.
2568
+ * Any `params.page` is ignored and never sent — pass
1863
2569
  * `params.cursor` only to resume a walk you saved partway through;
1864
2570
  * `page` together with `cursor` is a 400 ("Use either cursor or page,
1865
2571
  * not both"), so this strips `page` at runtime, not just in the type
1866
2572
  * (`Omit` alone only guards TypeScript callers — a JS caller, or one
1867
- * using `as`, could otherwise still pass it through).
2573
+ * using `as`, could otherwise still pass it through). A `limit` that is
2574
+ * not a positive integer is a `RangeError` before any request.
1868
2575
  */
1869
2576
  async *paginateNationalDocuments(jurisdiction, params = {}, options) {
1870
2577
  const { page: _ignoredPage, ...rest } = params;
2578
+ startingPosition(void 0, rest.limit, 1);
1871
2579
  let cursor = rest.cursor;
2580
+ const sent = /* @__PURE__ */ new Set();
1872
2581
  for (; ; ) {
2582
+ if (typeof cursor === "string") sent.add(cursor);
1873
2583
  const page = await this.listNationalDocuments(
1874
2584
  jurisdiction,
1875
2585
  cursor !== void 0 ? { ...rest, cursor } : { ...rest },
1876
2586
  options
1877
2587
  );
2588
+ const results = page.results;
2589
+ const next = page.nextCursor;
2590
+ const ends = page.hasMore !== true || next === void 0 || next === null || next === "" || !Array.isArray(results) || results.length === 0;
2591
+ if (!ends) {
2592
+ if (typeof next !== "string") throw stalled("the server sent a page cursor that is not a string", page);
2593
+ if (sent.has(next)) throw stalled("the server repeated a page cursor", page);
2594
+ }
1878
2595
  yield page;
1879
- if (!page.hasMore || !page.nextCursor || page.results.length === 0) return;
1880
- cursor = page.nextCursor;
2596
+ if (ends) return;
2597
+ cursor = next;
1881
2598
  }
1882
2599
  }
1883
2600
  /**
@@ -1895,6 +2612,7 @@ var LexAPI = class {
1895
2612
  return this.call({
1896
2613
  method: "POST",
1897
2614
  path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
2615
+ shape: { lists: ["results"], required: ["results"] },
1898
2616
  body: nationalSemanticWireBody(request),
1899
2617
  idempotent: true,
1900
2618
  timeoutMs: options?.timeoutMs,
@@ -1908,7 +2626,17 @@ var LexAPI = class {
1908
2626
  * `attribution` and `document` (the matched act's listing summary) on
1909
2627
  * every hit; the index fields (`law_title`, `article_ref`, `section`,
1910
2628
  * `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
1911
- * always present, `null` when the index has nothing (API 2.8.0). No `hyde`, no `asOf` — both are EU-only.
2629
+ * always present, `null` when the index has nothing (API 2.8.0).
2630
+ *
2631
+ * **`asOf` (API 2.29.0)** labels each hit for a date (`asOfResolved`,
2632
+ * `asOfReason`, `asOfVersion`); the response adds `asOf` and
2633
+ * `asOfSummary`. The search runs over today's texts only. A hit is
2634
+ * resolved only when the publisher's dates, as of LexAPI's last recorded
2635
+ * read of the act (`asOfVersion.checkedAt`), show today's wording already
2636
+ * applied on the date; an unresolved hit keeps today's wording — it is not
2637
+ * established as the text for the date. LexAPI holds such dates for
2638
+ * Austria and Spain.
2639
+ *
1912
2640
  * `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
1913
2641
  * never forwards one on this call even if a caller bypasses the type
1914
2642
  * system — the server now validates `hyde` as a boolean on this route too
@@ -1920,7 +2648,8 @@ var LexAPI = class {
1920
2648
  return this.call({
1921
2649
  method: "POST",
1922
2650
  path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
1923
- body: nationalSemanticWireBody(request, { allowHyde: false }),
2651
+ shape: { lists: ["results"], required: ["results"] },
2652
+ body: nationalSemanticWireBody(request, { allowHyde: false, allowAsOf: true }),
1924
2653
  idempotent: true,
1925
2654
  timeoutMs: options?.timeoutMs,
1926
2655
  signal: options?.signal
@@ -1950,7 +2679,8 @@ var LexAPI = class {
1950
2679
  return this.call({
1951
2680
  method: "POST",
1952
2681
  path: "/search/semantic",
1953
- body: semanticWireBody(request),
2682
+ shape: { lists: ["results"], required: ["results"] },
2683
+ body: semanticWireBody(request, { legislation: false }),
1954
2684
  idempotent: true,
1955
2685
  timeoutMs: options?.timeoutMs,
1956
2686
  signal: options?.signal
@@ -1972,6 +2702,11 @@ var LexAPI = class {
1972
2702
  * cannot be answered keeps its latest text with `asOfResolved: false` and
1973
2703
  * an `asOfReason`. The response adds `asOf` and `asOfSummary`.
1974
2704
  *
2705
+ * **In force today:** EU hits carry `inForce` (with `notInForceReason`,
2706
+ * `endOfValidity`, `entryIntoForce`) when the act's status is known;
2707
+ * `inForce: true` keeps only hits known to be in force today and reports
2708
+ * what it removed in `inForceFilter`.
2709
+ *
1975
2710
  * **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
1976
2711
  * version the corpus does not hold reserves 5 and settles by outcome
1977
2712
  * (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
@@ -1982,7 +2717,59 @@ var LexAPI = class {
1982
2717
  return this.call({
1983
2718
  method: "POST",
1984
2719
  path: "/legislation/semantic",
1985
- body: semanticWireBody(request),
2720
+ shape: { lists: ["results"], required: ["results"] },
2721
+ body: semanticWireBody(request, { legislation: true }),
2722
+ idempotent: true,
2723
+ timeoutMs: options?.timeoutMs,
2724
+ signal: options?.signal
2725
+ });
2726
+ }
2727
+ /**
2728
+ * `POST /legislation/as-of` — the version of an EU regulation, directive
2729
+ * or decision listed for a date: the newest consolidated version dated on
2730
+ * or before it, or the act as published in the Official Journal when none
2731
+ * is. With `provision`, also that article, annex or recital range of the
2732
+ * version. Requires LexAPI API 2.26.0.
2733
+ *
2734
+ * **Unresolved is a normal return, not an error:** when the version or
2735
+ * the text cannot be established the call resolves with
2736
+ * `asOfResolved: false`, an `asOfReason` and no `provision`. Use
2737
+ * `provision.text` only when `asOfResolved` is `true`; `asOfVersion` can
2738
+ * also be present on an unresolved `provision` answer.
2739
+ * An unknown act throws `NotFoundError`; invalid input throws
2740
+ * `InvalidCelexError` / `InvalidParamsError`. An API older than 2.26.0
2741
+ * has no such endpoint and also answers 404 (`NotFoundError`).
2742
+ * `err.unknownEndpoint` is `false` there (the API sends it from 2.27.0):
2743
+ * check `err.message.includes("Unknown API endpoint")`.
2744
+ *
2745
+ * Consolidated versions have no legal force; only the act as published in
2746
+ * the Official Journal (`baseCelex`) is authentic. The answer does not say
2747
+ * whether an individual provision applied on that date, and
2748
+ * `act.inForceToday` is about today, not `asOf`. A retroactive amendment
2749
+ * counts from the date of the amending act.
2750
+ *
2751
+ * **Cost:** 1 credit when no text is fetched; when the provision's text
2752
+ * has to be fetched, 4 (5 when it is fetched live from EUR-Lex) whatever
2753
+ * the answer, and 1 if the fetch fails or finds no text. A fetch reserves
2754
+ * up to 5 credits: a pool holding fewer gets
2755
+ * `asOfReason: "insufficient_credits"`.
2756
+ */
2757
+ async legislationAsOf(request, options) {
2758
+ const body = { document: request.document, asOf: request.asOf };
2759
+ if (request.provision !== void 0) body["provision"] = request.provision;
2760
+ if (request.language !== void 0) body["language"] = request.language;
2761
+ return this.call({
2762
+ method: "POST",
2763
+ path: "/legislation/as-of",
2764
+ shape: {
2765
+ fields: [
2766
+ { path: "document", kind: "string" },
2767
+ { path: "asOfResolved", kind: "boolean" },
2768
+ { path: "act", kind: "object" },
2769
+ { path: "provenance", kind: "object" }
2770
+ ]
2771
+ },
2772
+ body,
1986
2773
  idempotent: true,
1987
2774
  timeoutMs: options?.timeoutMs,
1988
2775
  signal: options?.signal
@@ -2047,7 +2834,7 @@ var LexAPI = class {
2047
2834
  });
2048
2835
  }
2049
2836
  };
2050
- function semanticWireBody(request) {
2837
+ function semanticWireBody(request, { legislation }) {
2051
2838
  const body = { query: request.query };
2052
2839
  if (request.limit !== void 0) body["limit"] = request.limit;
2053
2840
  if (request.minScore !== void 0) body["min_score"] = request.minScore;
@@ -2055,10 +2842,11 @@ function semanticWireBody(request) {
2055
2842
  if (request.includeText) body["include"] = ["text"];
2056
2843
  if (request.filters !== void 0) body["filters"] = request.filters;
2057
2844
  if (request.hyde !== void 0) body["hyde"] = request.hyde;
2058
- if (request.asOf !== void 0) body["asOf"] = request.asOf;
2845
+ if (legislation && request.asOf !== void 0) body["asOf"] = request.asOf;
2846
+ if (legislation && request.inForce !== void 0) body["inForce"] = request.inForce;
2059
2847
  return body;
2060
2848
  }
2061
- function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2849
+ function nationalSemanticWireBody(request, { allowHyde = true, allowAsOf = false } = {}) {
2062
2850
  const body = { query: request.query };
2063
2851
  if (request.limit !== void 0) body["limit"] = request.limit;
2064
2852
  if (request.minScore !== void 0) body["min_score"] = request.minScore;
@@ -2066,6 +2854,7 @@ function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2066
2854
  if (request.includeText) body["include"] = ["text"];
2067
2855
  if (request.filters !== void 0) body["filters"] = request.filters;
2068
2856
  if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
2857
+ if (allowAsOf && request.asOf !== void 0) body["asOf"] = request.asOf;
2069
2858
  return body;
2070
2859
  }
2071
2860
  function jurisdictionSegment(jurisdiction) {
@@ -2100,16 +2889,40 @@ function listParam(value) {
2100
2889
  if (value === void 0) return void 0;
2101
2890
  return typeof value === "string" ? value : value.join(",");
2102
2891
  }
2103
- async function* paginateEdges(fetchPage, rawRowsIn, params) {
2104
- const limit = params.limit ?? 100;
2105
- let offset = params.offset ?? 0;
2892
+ function edgeRows(group) {
2893
+ const listed = Array.isArray(group.citations) ? group.citations.length : 0;
2894
+ const counted = count(group.citationCount);
2895
+ return counted === void 0 || counted === 0 ? listed : counted;
2896
+ }
2897
+ async function* paginateEdges(fetchPage, groupsIn, params) {
2898
+ const start = startingPosition(params.offset, params.limit, 100);
2899
+ const limit = start.limit;
2900
+ let offset = start.offset;
2901
+ let previous;
2902
+ let repeats = 0;
2106
2903
  for (; ; ) {
2107
2904
  const page = await fetchPage({ ...params, limit, offset });
2905
+ const listed = groupsIn(page);
2906
+ const groups = Array.isArray(listed) ? listed : [];
2907
+ const echoed = count(page.offset);
2908
+ const totalEdges = count(page.totalEdges);
2909
+ if (echoed !== void 0 && echoed !== offset) throw stalled("the server did not advance", page);
2910
+ if (echoed === void 0 && totalEdges === void 0) {
2911
+ const form = compactForm(groups);
2912
+ repeats = form === previous ? repeats + 1 : 0;
2913
+ previous = form;
2914
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same page", page);
2915
+ } else {
2916
+ repeats = 0;
2917
+ previous = compactForm(groups);
2918
+ }
2108
2919
  yield page;
2109
- const pageLimit = page.limit && page.limit > 0 ? page.limit : limit;
2110
- const rows = rawRowsIn(page);
2920
+ const echoedLimit = count(page.limit);
2921
+ const pageLimit = echoedLimit !== void 0 && echoedLimit > 0 ? echoedLimit : limit;
2922
+ const rows = groups.reduce((n, g) => n + edgeRows(g), 0);
2111
2923
  offset += rows;
2112
2924
  if (rows === 0 || rows < pageLimit) return;
2925
+ if (totalEdges !== void 0 && offset >= totalEdges) return;
2113
2926
  }
2114
2927
  }
2115
2928
  function withHeaders(data, response, corpusVersion) {
@@ -2124,11 +2937,20 @@ function withHeaders(data, response, corpusVersion) {
2124
2937
  }
2125
2938
 
2126
2939
  // src/credits.ts
2940
+ function figure(value) {
2941
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2942
+ }
2943
+ function resetsAt(fromCredits, fromUsage) {
2944
+ if (typeof fromCredits === "string") return fromCredits;
2945
+ if (typeof fromUsage === "string") return fromUsage;
2946
+ return (fromCredits === null || fromCredits === void 0) && fromUsage === null ? null : void 0;
2947
+ }
2127
2948
  function getCreditUsage(response) {
2949
+ if (typeof response !== "object" || response === null) response = {};
2128
2950
  return {
2129
- unitsCharged: response.credits?.operation_weight ?? 0,
2130
- creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
2131
- resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
2951
+ unitsCharged: figure(response.credits?.operation_weight) ?? 0,
2952
+ creditsRemaining: figure(response.credits?.remaining) ?? figure(response.usage?.remaining),
2953
+ resetsAt: resetsAt(response.credits?.resetsAt, response.usage?.resetsAt)
2132
2954
  };
2133
2955
  }
2134
2956
 
@@ -2158,6 +2980,9 @@ function assertSecret(secret) {
2158
2980
  "Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
2159
2981
  );
2160
2982
  }
2983
+ if (!isWellFormed(secret)) {
2984
+ throw new WebhookSignatureError("missing_secret", "Webhook secret is not well-formed Unicode (lone surrogate)");
2985
+ }
2161
2986
  }
2162
2987
  async function getSubtle() {
2163
2988
  const globalCrypto = globalThis.crypto;
@@ -2171,8 +2996,18 @@ async function getSubtle() {
2171
2996
  if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
2172
2997
  throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
2173
2998
  }
2999
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
3000
+ function isWellFormed(text2) {
3001
+ const native = String.prototype.isWellFormed;
3002
+ return typeof native === "function" ? native.call(text2) : !LONE_SURROGATE.test(text2);
3003
+ }
2174
3004
  function toBytes(body) {
2175
- if (typeof body === "string") return new TextEncoder().encode(body);
3005
+ if (typeof body === "string") {
3006
+ if (!isWellFormed(body)) {
3007
+ throw new WebhookSignatureError("malformed_body", "Webhook body string is not well-formed Unicode (lone surrogate)");
3008
+ }
3009
+ return new TextEncoder().encode(body);
3010
+ }
2176
3011
  if (body instanceof Uint8Array) return body;
2177
3012
  return new Uint8Array(body);
2178
3013
  }
@@ -2181,6 +3016,37 @@ function toHex(buffer) {
2181
3016
  for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
2182
3017
  return hex;
2183
3018
  }
3019
+ function trimHeader(value) {
3020
+ const space = (code) => code === 32 || code === 9 || code === 13 || code === 10;
3021
+ let start = 0;
3022
+ let end = value.length;
3023
+ while (start < end && space(value.charCodeAt(start))) start++;
3024
+ while (end > start && space(value.charCodeAt(end - 1))) end--;
3025
+ return value.slice(start, end);
3026
+ }
3027
+ var TIMESTAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:Z|([+-])([0-9]{2}):([0-9]{2}))$/;
3028
+ function timestampMicros(value) {
3029
+ if (typeof value !== "string") return void 0;
3030
+ const match = TIMESTAMP.exec(value);
3031
+ if (!match) return void 0;
3032
+ const [y, mo, d, h, mi, sec] = match.slice(1, 7).map(Number);
3033
+ const fraction = match[7];
3034
+ const sign = match[8];
3035
+ const offH = sign === void 0 ? 0 : Number(match[9]);
3036
+ const offM = sign === void 0 ? 0 : Number(match[10]);
3037
+ const leap = y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
3038
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];
3039
+ if (y < 1 || days === void 0 || d < 1 || d > days || h > 23 || mi > 59 || sec > 59 || offH > 23 || offM > 59) return void 0;
3040
+ const date = /* @__PURE__ */ new Date(0);
3041
+ date.setUTCFullYear(y, mo - 1, d);
3042
+ date.setUTCHours(h, mi, sec, 0);
3043
+ const micros2 = fraction === void 0 ? 0 : Number(fraction.slice(0, 6).padEnd(6, "0"));
3044
+ const offset = (sign === "-" ? -1 : 1) * (offH * 60 + offM) * 6e7;
3045
+ return BigInt(date.getTime()) * BigInt(1e3) + BigInt(micros2) - BigInt(offset);
3046
+ }
3047
+ function micros(ms) {
3048
+ return BigInt(Math.round(ms * 1e3));
3049
+ }
2184
3050
  function timingSafeEqual(a, b) {
2185
3051
  if (a.length !== b.length) return false;
2186
3052
  let diff = 0;
@@ -2200,31 +3066,49 @@ async function computeSignature(rawBody, secret) {
2200
3066
  return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
2201
3067
  }
2202
3068
  async function verifySignature(rawBody, signature, secret) {
2203
- const candidate = typeof signature === "string" ? signature.trim().toLowerCase() : "";
3069
+ const candidate = typeof signature === "string" ? trimHeader(signature) : "";
3070
+ assertSecret(secret);
3071
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) return false;
2204
3072
  const expected = await computeSignature(rawBody, secret);
2205
- if (!/^[0-9a-f]{64}$/.test(candidate)) return false;
2206
- return timingSafeEqual(expected, candidate);
3073
+ if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
3074
+ return timingSafeEqual(expected, candidate.toLowerCase());
2207
3075
  }
2208
3076
  async function verifyWebhook(rawBody, signature, secret, options = {}) {
2209
3077
  assertSecret(secret);
3078
+ const toleranceMs = options.toleranceMs ?? 3e5;
3079
+ if (typeof toleranceMs !== "number" || Number.isNaN(toleranceMs)) {
3080
+ throw new RangeError(`toleranceMs must be a number, got ${String(toleranceMs)}`);
3081
+ }
2210
3082
  if (!signature) {
2211
3083
  throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
2212
3084
  }
2213
- if (!await verifySignature(rawBody, signature, secret)) {
3085
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) {
3086
+ throw new WebhookSignatureError("invalid_signature", "Webhook body string is not well-formed Unicode (lone surrogate)");
3087
+ }
3088
+ const bytes = toBytes(rawBody);
3089
+ if (!await verifySignature(bytes, signature, secret)) {
2214
3090
  throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
2215
3091
  }
2216
3092
  let payload;
2217
3093
  try {
2218
- const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
2219
- payload = JSON.parse(text);
3094
+ const text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
3095
+ payload = JSON.parse(text2);
2220
3096
  } catch {
2221
3097
  throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
2222
3098
  }
2223
- const toleranceMs = options.toleranceMs ?? 3e5;
2224
- if (toleranceMs > 0) {
2225
- const sentAt = Date.parse(String(payload.timestamp));
3099
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
3100
+ throw new WebhookSignatureError("malformed_body", "Webhook body is not a JSON object");
3101
+ }
3102
+ if (toleranceMs !== 0) {
3103
+ const sentAt = timestampMicros(payload.timestamp);
2226
3104
  const now = options.now ?? Date.now();
2227
- if (Number.isNaN(sentAt) || Math.abs(now - sentAt) > toleranceMs) {
3105
+ let fresh = sentAt !== void 0 && toleranceMs > 0;
3106
+ if (fresh && toleranceMs !== Infinity) {
3107
+ const distance = micros(now) - sentAt;
3108
+ const limit = micros(toleranceMs);
3109
+ fresh = distance <= limit && -distance <= limit;
3110
+ }
3111
+ if (!fresh) {
2228
3112
  throw new WebhookSignatureError(
2229
3113
  "stale_timestamp",
2230
3114
  `Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
@@ -2265,6 +3149,7 @@ var AS_OF_REASONS = [
2265
3149
  "no_longer_in_force",
2266
3150
  "in_force_dates_unknown",
2267
3151
  "not_in_language",
3152
+ "amendment_not_consolidated",
2268
3153
  "text_unavailable",
2269
3154
  "article_not_in_version",
2270
3155
  "part_not_resolvable",
@@ -2280,10 +3165,43 @@ var AS_OF_REASONS = [
2280
3165
  "insufficient_credits",
2281
3166
  "credit_check_failed"
2282
3167
  ];
3168
+ var AS_OF_LOOKUP_REASONS = [
3169
+ "not_yet_adopted",
3170
+ "not_yet_in_force",
3171
+ "no_longer_in_force",
3172
+ "in_force_dates_unknown",
3173
+ "act_type_not_supported",
3174
+ "version_list_unavailable",
3175
+ "version_lookup_cap",
3176
+ "not_in_language",
3177
+ "amendment_not_consolidated",
3178
+ "text_unavailable",
3179
+ "article_not_in_version",
3180
+ "provision_ambiguous",
3181
+ "version_not_parsed",
3182
+ "fetch_budget_exhausted",
3183
+ "fetch_pending",
3184
+ "fetch_capacity",
3185
+ "fetch_failed",
3186
+ "fetch_timeout",
3187
+ "request_deadline",
3188
+ "insufficient_credits",
3189
+ "credit_check_failed"
3190
+ ];
2283
3191
  function isNationalDecision(document2) {
2284
3192
  return document2.documentKind === "decision" && document2.decision != null;
2285
3193
  }
3194
+ var NATIONAL_AS_OF_REASONS = [
3195
+ "provision_amended_since",
3196
+ "no_longer_in_force",
3197
+ "provision_dates_unknown",
3198
+ "asof_not_available"
3199
+ ];
3200
+ function isNationalAsOfVersion(version) {
3201
+ return typeof version === "object" && version !== null && version.kind === "current_unit";
3202
+ }
2286
3203
  export {
3204
+ AS_OF_LOOKUP_REASONS,
2287
3205
  AS_OF_REASONS,
2288
3206
  AuthenticationError,
2289
3207
  CITATION_PROVENANCES,
@@ -2301,12 +3219,14 @@ export {
2301
3219
  InvalidUrlError,
2302
3220
  LexAPI,
2303
3221
  LexAPIError,
3222
+ NATIONAL_AS_OF_REASONS,
2304
3223
  NationalAllowanceExhaustedError,
2305
3224
  NationalSemanticFilterUnreachableError,
2306
3225
  NationalSemanticNotEnabledError,
2307
3226
  NationalSemanticUnavailableError,
2308
3227
  NetworkError,
2309
3228
  NotFoundError,
3229
+ PaymentPastDueError,
2310
3230
  RateLimitedError,
2311
3231
  RequestAbortedError,
2312
3232
  ServiceUnavailableError,
@@ -2322,6 +3242,7 @@ export {
2322
3242
  computeSignature,
2323
3243
  getCreditUsage,
2324
3244
  isLexAPIError,
3245
+ isNationalAsOfVersion,
2325
3246
  isNationalDecision,
2326
3247
  normalizeRetryAfterSeconds,
2327
3248
  parseResponseHeaders,