polite-crawler 0.6.2 → 0.7.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.
Files changed (44) hide show
  1. package/README.md +66 -1
  2. package/build/api.d.mts +274 -20
  3. package/build/api.mjs +455 -4
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-DBvq5TU3.mjs → cli-daemon-Bke7kU1e.mjs} +2 -2
  6. package/build/{cli-daemon-DBvq5TU3.mjs.map → cli-daemon-Bke7kU1e.mjs.map} +1 -1
  7. package/build/{cli-recipes-C--_YyuP.mjs → cli-recipes-CUFd9ORK.mjs} +2 -2
  8. package/build/{cli-recipes-C--_YyuP.mjs.map → cli-recipes-CUFd9ORK.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-BkJp3wXR.mjs → daemon-Dh32XlZq.mjs} +3 -3
  11. package/build/{daemon-BkJp3wXR.mjs.map → daemon-Dh32XlZq.mjs.map} +1 -1
  12. package/build/{diff-DcbpHrxv.mjs → diff-ZEIt8xv3.mjs} +2 -2
  13. package/build/{diff-DcbpHrxv.mjs.map → diff-ZEIt8xv3.mjs.map} +1 -1
  14. package/build/{extract-DpycIF0M.mjs → extract-B_Tsv1UC.mjs} +3 -3
  15. package/build/{extract-DpycIF0M.mjs.map → extract-B_Tsv1UC.mjs.map} +1 -1
  16. package/build/html.d.mts +83 -2
  17. package/build/html.mjs +844 -1
  18. package/build/html.mjs.map +1 -0
  19. package/build/index.d.mts +15 -10
  20. package/build/index.mjs +12 -11
  21. package/build/{open-BIvV3pHE.mjs → open-Dx1gCR6l.mjs} +77 -55
  22. package/build/open-Dx1gCR6l.mjs.map +1 -0
  23. package/build/politeness.d.mts +33 -0
  24. package/build/politeness.mjs.map +1 -1
  25. package/build/{recipe-rECpzNa-.mjs → recipe-BO3V_1Kr.mjs} +4 -4
  26. package/build/{recipe-rECpzNa-.mjs.map → recipe-BO3V_1Kr.mjs.map} +1 -1
  27. package/build/{recipe-product-tVKjy4xu.mjs → recipe-product-BOQMCTGh.mjs} +6 -5
  28. package/build/{recipe-product-tVKjy4xu.mjs.map → recipe-product-BOQMCTGh.mjs.map} +1 -1
  29. package/build/{runtime-Hyr9qD0-.mjs → runtime-BVC7iOG4.mjs} +4 -3
  30. package/build/{runtime-Hyr9qD0-.mjs.map → runtime-BVC7iOG4.mjs.map} +1 -1
  31. package/build/text.d.mts +10 -0
  32. package/build/text.mjs +188 -0
  33. package/build/text.mjs.map +1 -0
  34. package/build/{version-D1VudHdM.mjs → version-DxUGcHQr.mjs} +2 -2
  35. package/build/{version-D1VudHdM.mjs.map → version-DxUGcHQr.mjs.map} +1 -1
  36. package/build/{wacz-D_Onr46C.mjs → wacz-DjgklRod.mjs} +3 -3
  37. package/build/{wacz-D_Onr46C.mjs.map → wacz-DjgklRod.mjs.map} +1 -1
  38. package/build/{warc-l7lECYMZ.mjs → warc-CgkNdXyG.mjs} +2 -2
  39. package/build/{warc-l7lECYMZ.mjs.map → warc-CgkNdXyG.mjs.map} +1 -1
  40. package/package.json +7 -1
  41. package/build/html-CawWTgMQ.mjs +0 -1030
  42. package/build/html-CawWTgMQ.mjs.map +0 -1
  43. package/build/html-oS_ueu9U.d.mts +0 -92
  44. package/build/open-BIvV3pHE.mjs.map +0 -1
package/build/api.mjs CHANGED
@@ -1,7 +1,12 @@
1
- import { classify } from "./classify.mjs";
1
+ import { classify, parseRetryAfter } from "./classify.mjs";
2
2
  import { policyFor, restAfter, validatorsToSend } from "./politeness.mjs";
3
3
  import { n as reactToOutcome, t as outcomeResult } from "./reaction-BWTIe95J.mjs";
4
- // src/api.ts
4
+ import { instantsOf, localTime, offsetChanges } from "@mark1russell7/algebra/clock";
5
+ // src/api-error.ts
6
+ /**
7
+ * The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import
8
+ * it and do not import each other.
9
+ */
5
10
  /**
6
11
  * An error of the send or of the token. The `redact` function of the send examined its message.
7
12
  *
@@ -10,6 +15,446 @@ import { n as reactToOutcome, t as outcomeResult } from "./reaction-BWTIe95J.mjs
10
15
  var ApiError = class extends Error {
11
16
  name = "ApiError";
12
17
  };
18
+ /**
19
+ * The names of `ApiError` and of each class that extends it. A new class of error adds its name here,
20
+ * and the test of the guards fails when it does not.
21
+ */
22
+ const NAMES = /* @__PURE__ */ new Set(["ApiError", "QuotaError"]);
23
+ /**
24
+ * This function tells if a value is an error of `polite-crawler/api`: an `ApiError`, or a
25
+ * `QuotaError`, which extends it. The error can come from this copy of the package or from another
26
+ * copy, of this version or of an earlier one. `instanceof` is false across two copies, so the
27
+ * function also accepts an `Error` with one of their names.
28
+ *
29
+ * @beta
30
+ */
31
+ const isApiError = (value) => value instanceof ApiError || value instanceof Error && NAMES.has(value.name);
32
+ // src/quota.ts
33
+ /**
34
+ * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day
35
+ * or month in a time zone, or a rolling window. The gate counts each call before it starts, and it
36
+ * refuses a call over the quota before the provider does. `withQuota` puts a gate on any async
37
+ * function: a `fetch`, a transport or a different client.
38
+ *
39
+ * The count is not lower than the count of the provider. A rolling window puts each call in a time
40
+ * bucket, and a bucket counts until all of it is out of the window. The answer of the provider can
41
+ * make the count larger, but not smaller.
42
+ *
43
+ * The civil time of a calendar window comes from `@mark1russell7/algebra/clock`. The module imports
44
+ * no Node.js module, so a browser can use it. Each export is beta.
45
+ */
46
+ /**
47
+ * The refusal of a call over its quota. The gate refused the call before the call started.
48
+ *
49
+ * @beta
50
+ */
51
+ var QuotaError = class extends ApiError {
52
+ name = "QuotaError";
53
+ /** This value is the key of the quota. */
54
+ key;
55
+ /** The gate gives units again from this time, in milliseconds since the epoch. */
56
+ resetAt;
57
+ constructor(message, key, resetAt) {
58
+ super(message);
59
+ this.key = key;
60
+ this.resetAt = resetAt;
61
+ }
62
+ };
63
+ /**
64
+ * This function tells if a value is a `QuotaError`. The error can come from this copy of the package
65
+ * or from another copy, of this version or of an earlier one. `instanceof` is false across two copies.
66
+ * So the function also accepts an `Error` named `QuotaError`, with a string `key` and a finite number
67
+ * `resetAt`. A package that gets a transport of `withQuota` uses it to tell a refusal of the quota from
68
+ * another failure. That package needs no dependency on this package.
69
+ *
70
+ * @beta
71
+ */
72
+ const isQuotaError = (value) => value instanceof QuotaError || value instanceof Error && value.name === "QuotaError" && typeof value.key === "string" && Number.isFinite(value.resetAt);
73
+ const MAX_BUCKETS = 1e3;
74
+ const DEFAULT_BUCKETS = 60;
75
+ const HOUR_MS = 36e5;
76
+ /** The largest time of a `Date`, in milliseconds from the epoch. */
77
+ const MAX_TIME = 864e13;
78
+ const iso = (t) => new Date(t).toISOString();
79
+ /** This function gives the clock time of `t` in a zone, as the milliseconds of that clock time in UTC. */
80
+ const wallOf = (t, timeZone) => {
81
+ const local = localTime(t, timeZone);
82
+ if (local === void 0) throw new ApiError(`The time ${String(t)} is not a date.`);
83
+ const { year, month, day, hour, minute, second } = local;
84
+ return Date.UTC(year, month - 1, day, hour, minute, second);
85
+ };
86
+ /**
87
+ * This function gives the first time at which the clock of the zone shows the clock time `wall`.
88
+ * In the gap of a change forward, the clock does not show `wall`. The function then gives the time
89
+ * of the change: the end of the gap.
90
+ */
91
+ const firstAt = (wall, timeZone) => {
92
+ const [first] = instantsOf(wall, timeZone) ?? [];
93
+ if (first !== void 0) return first;
94
+ const change = (offsetChanges(wall - 15 * HOUR_MS, wall + 13 * HOUR_MS, timeZone) ?? []).find((at) => wallOf(at - 1, timeZone) < wall && wallOf(at, timeZone) >= wall);
95
+ if (change === void 0) throw new ApiError(`The clock of ${timeZone} does not show or jump over ${iso(wall)}.`);
96
+ return change;
97
+ };
98
+ /** This function gives the calendar window of the time `t`: its start, and the start of the next window. */
99
+ const calendarOf = (unit, timeZone, hour, t) => {
100
+ const wall = new Date(wallOf(t, timeZone));
101
+ const year = wall.getUTCFullYear();
102
+ const month = wall.getUTCMonth();
103
+ const day = wall.getUTCDate();
104
+ const startOf = (back) => firstAt(unit === "day" ? Date.UTC(year, month, day - back, hour) : Date.UTC(year, month - back, 1, hour), timeZone);
105
+ const start = startOf(0);
106
+ return start <= t ? [start, startOf(-1)] : [startOf(1), start];
107
+ };
108
+ const spanOf = (window) => {
109
+ if (window.kind === "rolling") {
110
+ const buckets = window.buckets ?? DEFAULT_BUCKETS;
111
+ if (!Number.isFinite(window.ms) || window.ms <= 0) throw new ApiError(`The rolling window is not a positive number: ${String(window.ms)}.`);
112
+ if (!Number.isInteger(buckets) || buckets < 1 || buckets > MAX_BUCKETS) throw new ApiError(`The count of buckets is not a whole number from 1 to ${String(MAX_BUCKETS)}: ${String(buckets)}.`);
113
+ const { ms } = window;
114
+ const size = Math.ceil(ms / buckets);
115
+ return {
116
+ bucket: (t) => {
117
+ const start = Math.floor(t / size) * size;
118
+ return [start, start + size];
119
+ },
120
+ counting: (t) => (start) => start + size + ms > t,
121
+ freeAt: (start) => start + size + ms
122
+ };
123
+ }
124
+ const hour = window.hour ?? 0;
125
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) throw new ApiError(`The hour of the window is not a whole number from 0 to 23: ${String(hour)}.`);
126
+ if (localTime(0, window.timeZone) === void 0) throw new ApiError(`The time zone of the window is not an IANA time zone: ${window.timeZone}.`);
127
+ const { unit, timeZone } = window;
128
+ return {
129
+ bucket: (t) => calendarOf(unit, timeZone, hour, t),
130
+ counting: (t) => {
131
+ const [first] = calendarOf(unit, timeZone, hour, t);
132
+ return (start) => start >= first;
133
+ },
134
+ freeAt: (start) => calendarOf(unit, timeZone, hour, start)[1]
135
+ };
136
+ };
137
+ const isTime = (value) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;
138
+ /**
139
+ * This function gives the record of a store, or undefined for a value that is not a record. It
140
+ * removes each item that is not valid and keeps the other items, so the count stays as high as the
141
+ * record lets it.
142
+ */
143
+ const recordOf = (value) => {
144
+ if (typeof value !== "object" || value === null) return void 0;
145
+ const { spent, blockedUntil, readAt } = value;
146
+ if (!Array.isArray(spent)) return void 0;
147
+ const items = [];
148
+ for (const item of spent) {
149
+ if (!Array.isArray(item) || item.length !== 2) continue;
150
+ const [start, units] = item;
151
+ if (isTime(start) && isTime(units) && units >= 0) items.push([start, units]);
152
+ }
153
+ items.sort((a, b) => a[0] - b[0]);
154
+ return {
155
+ spent: items,
156
+ ...isTime(blockedUntil) ? { blockedUntil } : {},
157
+ ...isTime(readAt) ? { readAt } : {}
158
+ };
159
+ };
160
+ /** This function removes the buckets that do not count at the time `t`, and an ended refusal. */
161
+ const prune = (span, record, t) => {
162
+ const counts = span.counting(t);
163
+ const spent = (record?.spent ?? []).filter(([start]) => counts(start));
164
+ const blockedUntil = record?.blockedUntil;
165
+ const readAt = record?.readAt;
166
+ return {
167
+ spent,
168
+ ...blockedUntil !== void 0 && blockedUntil > t ? { blockedUntil } : {},
169
+ ...readAt === void 0 ? {} : { readAt }
170
+ };
171
+ };
172
+ const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
173
+ /** This function adds units to the bucket of the time `t`. */
174
+ const add = (span, record, t, units) => {
175
+ const [start] = span.bucket(t);
176
+ const spent = record.spent.map(([at, count]) => at === start ? [at, count + units] : [at, count]);
177
+ if (!spent.some(([at]) => at === start)) spent.push([start, units]);
178
+ spent.sort((a, b) => a[0] - b[0]);
179
+ return {
180
+ ...record,
181
+ spent
182
+ };
183
+ };
184
+ /** This function gives the time when `need` units of the oldest buckets stop counting. */
185
+ const freeTime = (span, record, need) => {
186
+ let freed = 0;
187
+ for (const [start, units] of record.spent) {
188
+ freed += units;
189
+ if (freed >= need) return span.freeAt(start);
190
+ }
191
+ };
192
+ /**
193
+ * This function makes the gate of one key.
194
+ *
195
+ * @throws ApiError when the quota or its window is not valid.
196
+ * @beta
197
+ */
198
+ function quotaGate(quota, options) {
199
+ const span = spanOf(quota.window);
200
+ const { limit, name } = quota;
201
+ const reserve = quota.reserve ?? 0;
202
+ if (!Number.isFinite(limit) || limit <= 0) throw new ApiError(`The limit of the quota ${name} is not a positive number: ${String(limit)}.`);
203
+ if (!Number.isFinite(reserve) || reserve < 0 || reserve >= limit) throw new ApiError(`The reserve of the quota ${name} is not from 0 to less than the limit: ${String(reserve)}.`);
204
+ const { key, maxBlockMs } = options;
205
+ if (maxBlockMs !== void 0 && (!Number.isFinite(maxBlockMs) || maxBlockMs <= 0)) throw new ApiError(`The longest block of the quota ${name} is not a positive number: ${String(maxBlockMs)}.`);
206
+ const blockBound = (t) => maxBlockMs === void 0 ? span.freeAt(span.bucket(t)[0]) : t + maxBlockMs;
207
+ const store = options.store ?? memoryQuotaStore();
208
+ const now = options.now ?? Date.now;
209
+ const allowed = limit - reserve;
210
+ const stateOf = (record, t) => {
211
+ const used = usedOf(record);
212
+ const resetAt = record.spent.length === 0 ? void 0 : span.freeAt(record.spent[0][0]);
213
+ return {
214
+ used,
215
+ left: record.blockedUntil === void 0 ? Math.max(0, allowed - used) : 0,
216
+ ...resetAt === void 0 ? {} : { resetAt },
217
+ ...record.blockedUntil === void 0 ? {} : { blockedUntil: record.blockedUntil },
218
+ at: t
219
+ };
220
+ };
221
+ const bounded = (record, t) => {
222
+ const { blockedUntil } = record;
223
+ const bound = blockBound(t);
224
+ return blockedUntil !== void 0 && blockedUntil > bound ? {
225
+ ...record,
226
+ blockedUntil: bound
227
+ } : record;
228
+ };
229
+ const change = (step) => {
230
+ const t = now();
231
+ const record = store.changeQuota(name, key, (stored) => bounded(step(bounded(prune(span, recordOf(stored), t), t), t), t));
232
+ return stateOf(prune(span, recordOf(record), t), t);
233
+ };
234
+ const state = () => change((record) => record);
235
+ return {
236
+ quota,
237
+ key,
238
+ take(cost = 1) {
239
+ if (!Number.isFinite(cost) || cost < 0) throw new ApiError(`The cost of a call is not a number of 0 or more: ${String(cost)}.`);
240
+ if (cost === 0) return state();
241
+ if (cost > allowed) throw new ApiError(`A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(allowed)}.`);
242
+ let refused;
243
+ const taken = change((record, t) => {
244
+ const used = usedOf(record);
245
+ const free = used + cost > allowed ? freeTime(span, record, used + cost - allowed) ?? span.bucket(t)[1] : void 0;
246
+ const { blockedUntil } = record;
247
+ if (blockedUntil !== void 0) {
248
+ const resetAt = Math.max(blockedUntil, free ?? blockedUntil);
249
+ refused = new QuotaError(`The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` + (resetAt > blockedUntil ? ` The window has the units of the call at ${iso(resetAt)}.` : ""), key, resetAt);
250
+ return record;
251
+ }
252
+ if (free !== void 0) {
253
+ refused = new QuotaError(`The quota ${name} of ${key} refused a call of ${String(cost)} units: ${String(used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. It gives units again at ${iso(free)}.`, key, free);
254
+ return record;
255
+ }
256
+ return add(span, record, t, cost);
257
+ });
258
+ if (refused !== void 0) throw refused;
259
+ return taken;
260
+ },
261
+ note(reading) {
262
+ return change((record, t) => {
263
+ let next = record;
264
+ const { remaining, resetAt } = reading;
265
+ if (remaining !== void 0 && Number.isFinite(remaining) && remaining >= 0) {
266
+ const more = limit - remaining - usedOf(next);
267
+ if (more > 0) next = add(span, next, t, more);
268
+ next = {
269
+ ...next,
270
+ readAt: Math.max(next.readAt ?? t, t)
271
+ };
272
+ }
273
+ if ((remaining === void 0 || remaining <= 0) && resetAt !== void 0 && Number.isFinite(resetAt) && resetAt > t) next = {
274
+ ...next,
275
+ blockedUntil: Math.max(next.blockedUntil ?? 0, resetAt)
276
+ };
277
+ return next;
278
+ });
279
+ },
280
+ state,
281
+ giveBack(cost, at) {
282
+ if (!Number.isFinite(cost) || cost < 0) throw new ApiError(`The cost of a give-back is not a number of 0 or more: ${String(cost)}.`);
283
+ if (!isTime(at)) throw new ApiError(`The time of a give-back is not a time: ${String(at)}.`);
284
+ if (cost === 0) return state();
285
+ return change((record) => {
286
+ if (record.readAt !== void 0 && record.readAt >= at) return record;
287
+ const [start] = span.bucket(at);
288
+ const spent = record.spent.flatMap(([from, units]) => from !== start ? [[from, units]] : units > cost ? [[from, units - cost]] : []);
289
+ return {
290
+ ...record,
291
+ spent
292
+ };
293
+ });
294
+ }
295
+ };
296
+ }
297
+ /**
298
+ * This function makes a store of records in memory. Each gate of one process can share it.
299
+ *
300
+ * @beta
301
+ */
302
+ function memoryQuotaStore() {
303
+ const records = /* @__PURE__ */ new Map();
304
+ return { changeQuota(quota, key, step) {
305
+ let keys = records.get(quota);
306
+ if (keys === void 0) {
307
+ keys = /* @__PURE__ */ new Map();
308
+ records.set(quota, keys);
309
+ }
310
+ const next = step(keys.get(key));
311
+ keys.set(key, next);
312
+ return next;
313
+ } };
314
+ }
315
+ const isGateList = (gate) => Array.isArray(gate);
316
+ /** This function checks the gates of `withQuota`: a list has gates that can give back units. */
317
+ const gateList = (gate) => {
318
+ if (!isGateList(gate)) return [gate];
319
+ if (gate.length === 0) throw new ApiError("The list of gates of withQuota is empty.");
320
+ const seen = /* @__PURE__ */ new Set();
321
+ for (const each of gate) {
322
+ const named = `the quota ${each.quota.name} of ${each.key}`;
323
+ if (gate.length > 1 && each.giveBack === void 0) throw new ApiError(`The gate of ${named} cannot give back units, so it cannot be in a list.`);
324
+ const id = JSON.stringify([each.quota.name, each.key]);
325
+ if (seen.has(id)) throw new ApiError(`Two gates of the list have ${named}.`);
326
+ seen.add(id);
327
+ }
328
+ return [...gate];
329
+ };
330
+ /**
331
+ * This function gives an error to `onError`. An error that `onError` throws is lost. Thus the other
332
+ * give-backs still occur, and the caller gets the refusal or the result of the call.
333
+ */
334
+ const report = (onError, error) => {
335
+ try {
336
+ onError?.(error);
337
+ } catch {}
338
+ };
339
+ /** This function gives back the units of each gate that counted them, and gives each error to `onError`. */
340
+ const giveBackAll = (taken, cost, onError) => {
341
+ for (const [gate, at] of taken) try {
342
+ if (at === void 0) throw new ApiError(`The gate of the quota ${gate.quota.name} of ${gate.key} gave no time for its units, so it cannot give them back.`);
343
+ gate.giveBack?.(cost, at);
344
+ } catch (error) {
345
+ report(onError, error);
346
+ }
347
+ };
348
+ /**
349
+ * This function counts `cost` units in each gate, or in none. When a gate refuses, the gates that
350
+ * counted give back the units: the call did not start. The next gates still answer, so the
351
+ * `QuotaError` has the latest time of a reset.
352
+ */
353
+ const takeAll = (gates, cost, onError) => {
354
+ const taken = [];
355
+ let refusal;
356
+ try {
357
+ for (const gate of gates) try {
358
+ taken.push([gate, gate.take(cost).at]);
359
+ } catch (error) {
360
+ if (!isQuotaError(error) || gates.length === 1) throw error;
361
+ if (refusal === void 0 || error.resetAt > refusal.resetAt) refusal = error;
362
+ }
363
+ if (refusal !== void 0) throw refusal;
364
+ } catch (error) {
365
+ giveBackAll(taken, cost, onError);
366
+ throw error;
367
+ }
368
+ };
369
+ /**
370
+ * This function puts a gate, or a list of gates, on an async function, and keeps the type of the
371
+ * function. Each call counts its units first. A call over the quota throws `QuotaError`, and the
372
+ * function does not start.
373
+ *
374
+ * Give the result to a client that takes a function of this type. For example, `withQuota(gate,
375
+ * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`.
376
+ *
377
+ * For two quotas of one key, give a list: `withQuota([perMinute, perDay], fetch)`. The list counts
378
+ * the call in each gate or in none. Do not put one gate in the function of another. The outer gate
379
+ * cannot know if a request went out before the inner gate refused (`send` retries). So it keeps
380
+ * the units of the call.
381
+ *
382
+ * @throws ApiError when the list is empty, or when a gate of a list of two or more has no
383
+ * `giveBack`. Also when two gates of the list have one quota name and key.
384
+ * @beta
385
+ */
386
+ function withQuota(gate, call, options = {}) {
387
+ const gates = gateList(gate);
388
+ const { cost, read, onError } = options;
389
+ return async (...args) => {
390
+ takeAll(gates, typeof cost === "function" ? cost(...args) : cost ?? 1, onError);
391
+ const result = await call(...args);
392
+ for (const each of gates) try {
393
+ const reading = read?.(result, each);
394
+ if (reading !== void 0) each.note(reading);
395
+ } catch (error) {
396
+ report(onError, error);
397
+ }
398
+ return result;
399
+ };
400
+ }
401
+ const COUNT = /^\d{1,15}$/;
402
+ const SECONDS = /^\d{1,12}(?:\.\d{1,3})?$/;
403
+ const RESET = /^\d{1,15}(?:\.\d{1,3})?$/;
404
+ /**
405
+ * This function gives the time of a reset, in milliseconds since the epoch, from the number of a
406
+ * reset header. The three forms of the header do not overlap:
407
+ *
408
+ * - under `SECONDS_SINCE_EPOCH_FROM` (10^9): seconds until the reset, from `now`
409
+ * - from 10^9 to under `MILLISECONDS_SINCE_EPOCH_FROM` (10^11): seconds since the epoch
410
+ * - from 10^11: milliseconds since the epoch
411
+ */
412
+ const resetTimeOf = (value, now) => value < 1e9 ? now + value * 1e3 : value < 1e11 ? value * 1e3 : value;
413
+ /**
414
+ * This function reads the count of a provider from the headers of an answer. `get` gives the value
415
+ * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or
416
+ * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of
417
+ * `resetAfter` can also be an HTTP date, as in `Retry-After`. The value of `resetAt` can be in each
418
+ * of three forms, which the function tells apart by their size.
419
+ *
420
+ * A reset with no count tells that the provider refuses the key until that time. The answer can
421
+ * have a reset header, and no `remaining` header with a number. Then the gate stops the key until
422
+ * the reset, also after a successful answer.
423
+ *
424
+ * @returns the reading, or undefined when no header has a value.
425
+ * @beta
426
+ */
427
+ function readQuotaHeaders(get, names, now) {
428
+ const text = (name) => name === void 0 ? void 0 : get(name.toLowerCase())?.trim();
429
+ const value = (name, form) => {
430
+ const found = text(name);
431
+ return found !== void 0 && form.test(found) ? Number(found) : void 0;
432
+ };
433
+ const remaining = value(names.remaining, COUNT);
434
+ const at = value(names.resetAt, RESET);
435
+ const afterText = text(names.resetAfter);
436
+ const after = afterText === void 0 ? void 0 : SECONDS.test(afterText) ? Number(afterText) * 1e3 : parseRetryAfter(afterText, now);
437
+ const resetAt = after !== void 0 ? now + after : at === void 0 ? void 0 : resetTimeOf(at, now);
438
+ if (remaining === void 0 && resetAt === void 0) return void 0;
439
+ return {
440
+ ...remaining === void 0 ? {} : { remaining },
441
+ ...resetAt === void 0 ? {} : { resetAt }
442
+ };
443
+ }
444
+ // src/api.ts
445
+ /**
446
+ * The polite send of a documented API. It keeps the pace of each host with the scheduler of the
447
+ * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each
448
+ * answer. The send stores no page, because the terms of some APIs forbid a store.
449
+ *
450
+ * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.
451
+ * The module imports no Node.js module, and it uses no type of a platform except the signal.
452
+ *
453
+ * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,
454
+ * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent
455
+ * and a time limit. `poll` sends conditional requests. Each export is beta: a minor version can
456
+ * change it.
457
+ */
13
458
  const unchanged = (text) => text;
14
459
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
15
460
  /**
@@ -29,10 +474,12 @@ function statusLine(reply) {
29
474
  * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.
30
475
  * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.
31
476
  * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.
477
+ * - A `QuotaError` of the transport (`withQuota`) does not change the host.
32
478
  *
33
479
  * The function gives each answer, with each status. The caller reads the status.
34
480
  *
35
481
  * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.
482
+ * @throws QuotaError of the transport, as it is, when a quota refuses the exchange.
36
483
  * @throws the reason of the signal, when the signal stops the exchange.
37
484
  * @beta
38
485
  */
@@ -68,6 +515,10 @@ async function send(pace, transport, input, signal) {
68
515
  try {
69
516
  reply = await transport(input.exchange, signal);
70
517
  } catch (error) {
518
+ if (isQuotaError(error)) return {
519
+ value: { error },
520
+ delayMs: 0
521
+ };
71
522
  const facts = {
72
523
  outcome: "error",
73
524
  status: 0,
@@ -98,7 +549,7 @@ async function send(pace, transport, input, signal) {
98
549
  throw new ApiError(redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`));
99
550
  }
100
551
  if ("error" in attempt) {
101
- if (signal?.aborted === true) throw attempt.error;
552
+ if (signal?.aborted === true || isQuotaError(attempt.error)) throw attempt.error;
102
553
  throw new ApiError(redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`));
103
554
  }
104
555
  return attempt;
@@ -320,6 +771,6 @@ async function poll(pace, transport, conditions, input, signal) {
320
771
  changed
321
772
  };
322
773
  }
323
- export { API_TIMEOUT_MS, ApiError, TOKEN_MARGIN_MS, fetchTransport, outcomeResult, poll, reactToOutcome, readGrant, send, sendWithToken, statusLine, tokenStore };
774
+ export { API_TIMEOUT_MS, ApiError, QuotaError, TOKEN_MARGIN_MS, fetchTransport, isApiError, isQuotaError, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
324
775
 
325
776
  //# sourceMappingURL=api.mjs.map