polite-crawler 0.6.1 → 0.6.3

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 (35) hide show
  1. package/README.md +87 -13
  2. package/build/api.d.mts +318 -21
  3. package/build/api.mjs +445 -5
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-DRI1tL5D.mjs → cli-daemon-Dh7_akeK.mjs} +2 -2
  6. package/build/{cli-daemon-DRI1tL5D.mjs.map → cli-daemon-Dh7_akeK.mjs.map} +1 -1
  7. package/build/{cli-recipes-B1zg7et3.mjs → cli-recipes-DnmjTnyY.mjs} +2 -2
  8. package/build/{cli-recipes-B1zg7et3.mjs.map → cli-recipes-DnmjTnyY.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-l6FPe6lD.mjs → daemon-Skkq_MW8.mjs} +3 -3
  11. package/build/{daemon-l6FPe6lD.mjs.map → daemon-Skkq_MW8.mjs.map} +1 -1
  12. package/build/{diff-CSNW27zD.mjs → diff-BUGMvIqe.mjs} +2 -2
  13. package/build/{diff-CSNW27zD.mjs.map → diff-BUGMvIqe.mjs.map} +1 -1
  14. package/build/{extract-Bn0ueYEx.mjs → extract-Cm_bF25a.mjs} +2 -2
  15. package/build/{extract-Bn0ueYEx.mjs.map → extract-Cm_bF25a.mjs.map} +1 -1
  16. package/build/index.d.mts +13 -9
  17. package/build/index.mjs +10 -10
  18. package/build/{open-Cq2hknsi.mjs → open-Cw4NVDBE.mjs} +75 -54
  19. package/build/open-Cw4NVDBE.mjs.map +1 -0
  20. package/build/politeness.d.mts +27 -0
  21. package/build/politeness.mjs.map +1 -1
  22. package/build/{recipe-Bcp8MCvO.mjs → recipe-CRT_I64C.mjs} +3 -3
  23. package/build/{recipe-Bcp8MCvO.mjs.map → recipe-CRT_I64C.mjs.map} +1 -1
  24. package/build/{recipe-product-DE-yzyXS.mjs → recipe-product-n0fZKTxE.mjs} +4 -4
  25. package/build/{recipe-product-DE-yzyXS.mjs.map → recipe-product-n0fZKTxE.mjs.map} +1 -1
  26. package/build/{runtime-Cn_acsHC.mjs → runtime-BYb320jE.mjs} +2 -2
  27. package/build/{runtime-Cn_acsHC.mjs.map → runtime-BYb320jE.mjs.map} +1 -1
  28. package/build/{version-BwsBOkFU.mjs → version-bKln1r5i.mjs} +2 -2
  29. package/build/{version-BwsBOkFU.mjs.map → version-bKln1r5i.mjs.map} +1 -1
  30. package/build/{wacz-BkeG0_Pn.mjs → wacz-fsby_Qur.mjs} +3 -3
  31. package/build/{wacz-BkeG0_Pn.mjs.map → wacz-fsby_Qur.mjs.map} +1 -1
  32. package/build/{warc-BPYg_Nzp.mjs → warc-C9VpeTjp.mjs} +2 -2
  33. package/build/{warc-BPYg_Nzp.mjs.map → warc-C9VpeTjp.mjs.map} +1 -1
  34. package/package.json +3 -1
  35. package/build/open-Cq2hknsi.mjs.map +0 -1
package/build/api.mjs CHANGED
@@ -1,7 +1,12 @@
1
- import { classify } from "./classify.mjs";
2
- import { policyFor, restAfter } from "./politeness.mjs";
1
+ import { classify, parseRetryAfter } from "./classify.mjs";
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,313 @@ 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
+ // src/quota.ts
19
+ /**
20
+ * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day
21
+ * or month in a time zone, or a rolling window. The gate counts each call before it starts, and it
22
+ * refuses a call over the quota before the provider does. `withQuota` puts a gate on any async
23
+ * function: a `fetch`, a transport or a different client.
24
+ *
25
+ * The count is not lower than the count of the provider. A rolling window puts each call in a time
26
+ * bucket, and a bucket counts until all of it is out of the window. The answer of the provider can
27
+ * make the count larger, but not smaller.
28
+ *
29
+ * The civil time of a calendar window comes from `@mark1russell7/algebra/clock`. The module imports
30
+ * no Node.js module, so a browser can use it. Each export is beta.
31
+ */
32
+ /**
33
+ * The refusal of a call over its quota. The gate refused the call before the call started.
34
+ *
35
+ * @beta
36
+ */
37
+ var QuotaError = class extends ApiError {
38
+ name = "QuotaError";
39
+ /** This value is the key of the quota. */
40
+ key;
41
+ /** The gate gives units again from this time, in milliseconds since the epoch. */
42
+ resetAt;
43
+ constructor(message, key, resetAt) {
44
+ super(message);
45
+ this.key = key;
46
+ this.resetAt = resetAt;
47
+ }
48
+ };
49
+ const MAX_BUCKETS = 1e3;
50
+ const DEFAULT_BUCKETS = 60;
51
+ const HOUR_MS = 36e5;
52
+ /** The largest time of a `Date`, in milliseconds from the epoch. */
53
+ const MAX_TIME = 864e13;
54
+ const iso = (t) => new Date(t).toISOString();
55
+ /** This function gives the clock time of `t` in a zone, as the milliseconds of that clock time in UTC. */
56
+ const wallOf = (t, timeZone) => {
57
+ const local = localTime(t, timeZone);
58
+ if (local === void 0) throw new ApiError(`The time ${String(t)} is not a date.`);
59
+ const { year, month, day, hour, minute, second } = local;
60
+ return Date.UTC(year, month - 1, day, hour, minute, second);
61
+ };
62
+ /**
63
+ * This function gives the first time at which the clock of the zone shows the clock time `wall`.
64
+ * In the gap of a change forward, the clock does not show `wall`. The function then gives the time
65
+ * of the change: the end of the gap.
66
+ */
67
+ const firstAt = (wall, timeZone) => {
68
+ const [first] = instantsOf(wall, timeZone) ?? [];
69
+ if (first !== void 0) return first;
70
+ const change = (offsetChanges(wall - 15 * HOUR_MS, wall + 13 * HOUR_MS, timeZone) ?? []).find((at) => wallOf(at - 1, timeZone) < wall && wallOf(at, timeZone) >= wall);
71
+ if (change === void 0) throw new ApiError(`The clock of ${timeZone} does not show or jump over ${iso(wall)}.`);
72
+ return change;
73
+ };
74
+ /** This function gives the calendar window of the time `t`: its start, and the start of the next window. */
75
+ const calendarOf = (unit, timeZone, hour, t) => {
76
+ const wall = new Date(wallOf(t, timeZone));
77
+ const year = wall.getUTCFullYear();
78
+ const month = wall.getUTCMonth();
79
+ const day = wall.getUTCDate();
80
+ const startOf = (back) => firstAt(unit === "day" ? Date.UTC(year, month, day - back, hour) : Date.UTC(year, month - back, 1, hour), timeZone);
81
+ const start = startOf(0);
82
+ return start <= t ? [start, startOf(-1)] : [startOf(1), start];
83
+ };
84
+ const spanOf = (window) => {
85
+ if (window.kind === "rolling") {
86
+ const buckets = window.buckets ?? DEFAULT_BUCKETS;
87
+ if (!Number.isFinite(window.ms) || window.ms <= 0) throw new ApiError(`The rolling window is not a positive number: ${String(window.ms)}.`);
88
+ 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)}.`);
89
+ const { ms } = window;
90
+ const size = Math.ceil(ms / buckets);
91
+ return {
92
+ bucket: (t) => {
93
+ const start = Math.floor(t / size) * size;
94
+ return [start, start + size];
95
+ },
96
+ counting: (t) => (start) => start + size + ms > t,
97
+ freeAt: (start) => start + size + ms
98
+ };
99
+ }
100
+ const hour = window.hour ?? 0;
101
+ 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)}.`);
102
+ if (localTime(0, window.timeZone) === void 0) throw new ApiError(`The time zone of the window is not an IANA time zone: ${window.timeZone}.`);
103
+ const { unit, timeZone } = window;
104
+ return {
105
+ bucket: (t) => calendarOf(unit, timeZone, hour, t),
106
+ counting: (t) => {
107
+ const [first] = calendarOf(unit, timeZone, hour, t);
108
+ return (start) => start >= first;
109
+ },
110
+ freeAt: (start) => calendarOf(unit, timeZone, hour, start)[1]
111
+ };
112
+ };
113
+ const isTime = (value) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;
114
+ /**
115
+ * This function gives the record of a store, or undefined for a value that is not a record. It
116
+ * removes each item that is not valid and keeps the other items, so the count stays as high as the
117
+ * record lets it.
118
+ */
119
+ const recordOf = (value) => {
120
+ if (typeof value !== "object" || value === null) return void 0;
121
+ const { spent, blockedUntil } = value;
122
+ if (!Array.isArray(spent)) return void 0;
123
+ const items = [];
124
+ for (const item of spent) {
125
+ if (!Array.isArray(item) || item.length !== 2) continue;
126
+ const [start, units] = item;
127
+ if (isTime(start) && isTime(units) && units >= 0) items.push([start, units]);
128
+ }
129
+ items.sort((a, b) => a[0] - b[0]);
130
+ return isTime(blockedUntil) ? {
131
+ spent: items,
132
+ blockedUntil
133
+ } : { spent: items };
134
+ };
135
+ /** This function removes the buckets that do not count at the time `t`, and an ended refusal. */
136
+ const prune = (span, record, t) => {
137
+ const counts = span.counting(t);
138
+ const spent = (record?.spent ?? []).filter(([start]) => counts(start));
139
+ const blockedUntil = record?.blockedUntil;
140
+ return blockedUntil !== void 0 && blockedUntil > t ? {
141
+ spent,
142
+ blockedUntil
143
+ } : { spent };
144
+ };
145
+ const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
146
+ /** This function adds units to the bucket of the time `t`. */
147
+ const add = (span, record, t, units) => {
148
+ const [start] = span.bucket(t);
149
+ const spent = record.spent.map(([at, count]) => at === start ? [at, count + units] : [at, count]);
150
+ if (!spent.some(([at]) => at === start)) spent.push([start, units]);
151
+ spent.sort((a, b) => a[0] - b[0]);
152
+ return {
153
+ ...record,
154
+ spent
155
+ };
156
+ };
157
+ /** This function gives the time when `need` units of the oldest buckets stop counting. */
158
+ const freeTime = (span, record, need) => {
159
+ let freed = 0;
160
+ for (const [start, units] of record.spent) {
161
+ freed += units;
162
+ if (freed >= need) return span.freeAt(start);
163
+ }
164
+ };
165
+ /**
166
+ * This function makes the gate of one key.
167
+ *
168
+ * @throws ApiError when the quota or its window is not valid.
169
+ * @beta
170
+ */
171
+ function quotaGate(quota, options) {
172
+ const span = spanOf(quota.window);
173
+ const { limit, name } = quota;
174
+ const reserve = quota.reserve ?? 0;
175
+ if (!Number.isFinite(limit) || limit <= 0) throw new ApiError(`The limit of the quota ${name} is not a positive number: ${String(limit)}.`);
176
+ 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)}.`);
177
+ const { key } = options;
178
+ const store = options.store ?? memoryQuotaStore();
179
+ const now = options.now ?? Date.now;
180
+ const allowed = limit - reserve;
181
+ const stateOf = (record) => {
182
+ const used = usedOf(record);
183
+ const resetAt = record.spent.length === 0 ? void 0 : span.freeAt(record.spent[0][0]);
184
+ return {
185
+ used,
186
+ left: record.blockedUntil === void 0 ? Math.max(0, allowed - used) : 0,
187
+ ...resetAt === void 0 ? {} : { resetAt },
188
+ ...record.blockedUntil === void 0 ? {} : { blockedUntil: record.blockedUntil }
189
+ };
190
+ };
191
+ const change = (step) => {
192
+ const t = now();
193
+ const record = store.changeQuota(name, key, (stored) => step(prune(span, recordOf(stored), t), t));
194
+ return stateOf(prune(span, recordOf(record), t));
195
+ };
196
+ const state = () => change((record) => record);
197
+ return {
198
+ quota,
199
+ key,
200
+ take(cost = 1) {
201
+ if (!Number.isFinite(cost) || cost < 0) throw new ApiError(`The cost of a call is not a number of 0 or more: ${String(cost)}.`);
202
+ if (cost === 0) return state();
203
+ if (cost > allowed) throw new ApiError(`A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(allowed)}.`);
204
+ let refused;
205
+ const taken = change((record, t) => {
206
+ const used = usedOf(record);
207
+ const free = used + cost > allowed ? freeTime(span, record, used + cost - allowed) ?? span.bucket(t)[1] : void 0;
208
+ const { blockedUntil } = record;
209
+ if (blockedUntil !== void 0) {
210
+ const resetAt = Math.max(blockedUntil, free ?? blockedUntil);
211
+ 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);
212
+ return record;
213
+ }
214
+ if (free !== void 0) {
215
+ 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);
216
+ return record;
217
+ }
218
+ return add(span, record, t, cost);
219
+ });
220
+ if (refused !== void 0) throw refused;
221
+ return taken;
222
+ },
223
+ note(reading) {
224
+ return change((record, t) => {
225
+ let next = record;
226
+ const { remaining, resetAt } = reading;
227
+ if (remaining !== void 0 && Number.isFinite(remaining) && remaining >= 0) {
228
+ const more = limit - remaining - usedOf(next);
229
+ if (more > 0) next = add(span, next, t, more);
230
+ }
231
+ if ((remaining === void 0 || remaining <= 0) && resetAt !== void 0 && Number.isFinite(resetAt) && resetAt > t) next = {
232
+ ...next,
233
+ blockedUntil: Math.max(next.blockedUntil ?? 0, resetAt)
234
+ };
235
+ return next;
236
+ });
237
+ },
238
+ state
239
+ };
240
+ }
241
+ /**
242
+ * This function makes a store of records in memory. Each gate of one process can share it.
243
+ *
244
+ * @beta
245
+ */
246
+ function memoryQuotaStore() {
247
+ const records = /* @__PURE__ */ new Map();
248
+ return { changeQuota(quota, key, step) {
249
+ let keys = records.get(quota);
250
+ if (keys === void 0) {
251
+ keys = /* @__PURE__ */ new Map();
252
+ records.set(quota, keys);
253
+ }
254
+ const next = step(keys.get(key));
255
+ keys.set(key, next);
256
+ return next;
257
+ } };
258
+ }
259
+ /**
260
+ * This function puts a gate on an async function, and keeps the type of the function. Each call
261
+ * counts its units first. A call over the quota throws `QuotaError`, and the function does not start.
262
+ *
263
+ * Give the result to a client that takes a function of this type. For example, `withQuota(gate,
264
+ * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`. Put two gates on
265
+ * one function for two quotas of one key.
266
+ *
267
+ * @beta
268
+ */
269
+ function withQuota(gate, call, options = {}) {
270
+ const { cost, read, onError } = options;
271
+ return async (...args) => {
272
+ gate.take(typeof cost === "function" ? cost(...args) : cost ?? 1);
273
+ const result = await call(...args);
274
+ try {
275
+ const reading = read?.(result);
276
+ if (reading !== void 0) gate.note(reading);
277
+ } catch (error) {
278
+ onError?.(error);
279
+ }
280
+ return result;
281
+ };
282
+ }
283
+ const COUNT = /^\d{1,15}$/;
284
+ const SECONDS = /^\d{1,12}(?:\.\d{1,3})?$/;
285
+ /**
286
+ * This function reads the count of a provider from the headers of an answer. `get` gives the value
287
+ * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or
288
+ * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of
289
+ * `resetAfter` can also be an HTTP date, as in `Retry-After`.
290
+ *
291
+ * @returns the reading, or undefined when no header has a value.
292
+ * @beta
293
+ */
294
+ function readQuotaHeaders(get, names, now) {
295
+ const text = (name) => name === void 0 ? void 0 : get(name.toLowerCase())?.trim();
296
+ const value = (name, form) => {
297
+ const found = text(name);
298
+ return found !== void 0 && form.test(found) ? Number(found) : void 0;
299
+ };
300
+ const remaining = value(names.remaining, COUNT);
301
+ const at = value(names.resetAt, SECONDS);
302
+ const afterText = text(names.resetAfter);
303
+ const after = afterText === void 0 ? void 0 : SECONDS.test(afterText) ? Number(afterText) * 1e3 : parseRetryAfter(afterText, now);
304
+ const resetAt = after !== void 0 ? now + after : at === void 0 ? void 0 : at * 1e3;
305
+ if (remaining === void 0 && resetAt === void 0) return void 0;
306
+ return {
307
+ ...remaining === void 0 ? {} : { remaining },
308
+ ...resetAt === void 0 ? {} : { resetAt }
309
+ };
310
+ }
311
+ // src/api.ts
312
+ /**
313
+ * The polite send of a documented API. It keeps the pace of each host with the scheduler of the
314
+ * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each
315
+ * answer. The send stores no page, because the terms of some APIs forbid a store.
316
+ *
317
+ * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.
318
+ * The module imports no Node.js module, and it uses no type of a platform except the signal.
319
+ *
320
+ * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,
321
+ * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent
322
+ * and a time limit. `poll` sends conditional requests. Each export is beta: a minor version can
323
+ * change it.
324
+ */
13
325
  const unchanged = (text) => text;
14
326
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
15
327
  /**
@@ -29,10 +341,12 @@ function statusLine(reply) {
29
341
  * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.
30
342
  * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.
31
343
  * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.
344
+ * - A `QuotaError` of the transport (`withQuota`) does not change the host.
32
345
  *
33
346
  * The function gives each answer, with each status. The caller reads the status.
34
347
  *
35
348
  * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.
349
+ * @throws QuotaError of the transport, as it is, when a quota refuses the exchange.
36
350
  * @throws the reason of the signal, when the signal stops the exchange.
37
351
  * @beta
38
352
  */
@@ -68,6 +382,10 @@ async function send(pace, transport, input, signal) {
68
382
  try {
69
383
  reply = await transport(input.exchange, signal);
70
384
  } catch (error) {
385
+ if (error instanceof QuotaError) return {
386
+ value: { error },
387
+ delayMs: 0
388
+ };
71
389
  const facts = {
72
390
  outcome: "error",
73
391
  status: 0,
@@ -98,7 +416,7 @@ async function send(pace, transport, input, signal) {
98
416
  throw new ApiError(redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`));
99
417
  }
100
418
  if ("error" in attempt) {
101
- if (signal?.aborted === true) throw attempt.error;
419
+ if (signal?.aborted === true || attempt.error instanceof QuotaError) throw attempt.error;
102
420
  throw new ApiError(redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`));
103
421
  }
104
422
  return attempt;
@@ -198,6 +516,128 @@ async function sendWithToken(pace, transport, tokens, input, headers, signal) {
198
516
  tokens.drop(first.token);
199
517
  return (await once(false)).answer;
200
518
  }
201
- export { ApiError, TOKEN_MARGIN_MS, outcomeResult, reactToOutcome, readGrant, send, sendWithToken, statusLine, tokenStore };
519
+ /**
520
+ * The default time limit of `fetchTransport`: 30 seconds for the request and its body.
521
+ *
522
+ * @beta
523
+ */
524
+ const API_TIMEOUT_MS = 3e4;
525
+ /** A User-Agent is printable ASCII, from 1 to 512 characters, with no space at an end. */
526
+ const USER_AGENT = /^[!-~](?:[ -~]{0,510}[!-~])?$/;
527
+ /**
528
+ * This function makes a transport over `fetch`. The transport sends the User-Agent, does not
529
+ * follow a redirect, and stops a request after the time limit. A request that the time limit
530
+ * stopped throws an error, and `send` counts it as a failure of the host. A request that the
531
+ * signal stopped throws the reason of the signal.
532
+ *
533
+ * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.
534
+ * @beta
535
+ */
536
+ function fetchTransport(options) {
537
+ const { userAgent } = options;
538
+ if (!USER_AGENT.test(userAgent)) throw new ApiError("The transport needs a User-Agent of 1 to 512 printable ASCII characters, with no space at an end.");
539
+ const timeoutMs = options.timeoutMs ?? 3e4;
540
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new ApiError(`The time limit of the transport is not a positive number: ${String(timeoutMs)}.`);
541
+ const fetchOf = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
542
+ return async (exchange, signal) => {
543
+ const timeout = AbortSignal.timeout(timeoutMs);
544
+ const both = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
545
+ const headers = {
546
+ "user-agent": userAgent,
547
+ ...exchange.headers
548
+ };
549
+ try {
550
+ const response = await fetchOf(exchange.url, {
551
+ method: exchange.method,
552
+ headers,
553
+ ...exchange.body === null ? {} : { body: exchange.body },
554
+ redirect: "manual",
555
+ signal: both
556
+ });
557
+ const body = await response.text();
558
+ const replyHeaders = {};
559
+ response.headers.forEach((value, name) => {
560
+ replyHeaders[name.toLowerCase()] = value;
561
+ });
562
+ return {
563
+ status: response.status,
564
+ statusText: response.statusText,
565
+ headers: replyHeaders,
566
+ body
567
+ };
568
+ } catch (error) {
569
+ if (timeout.aborted && signal?.aborted !== true) throw new Error(`no answer in ${String(Math.ceil(timeoutMs / 1e3))} s`, { cause: error });
570
+ throw error;
571
+ }
572
+ };
573
+ }
574
+ const HEX = "0123456789abcdef";
575
+ /** This function gives the SHA-256 of a text, in hexadecimal. */
576
+ const digestOf = async (text) => {
577
+ const bytes = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
578
+ let hex = "";
579
+ for (const byte of bytes) hex += (HEX[byte >> 4] ?? "") + (HEX[byte & 15] ?? "");
580
+ return hex;
581
+ };
582
+ /**
583
+ * This function sends one conditional GET at the pace of its host, as `send` does. It sends the
584
+ * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and
585
+ * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then
586
+ * the function sends only the date to a host whose ETags do not match, as the crawler does.
587
+ *
588
+ * A 304 gives no body: the caller keeps the result of the last changed body. A server that does
589
+ * not answer 304 can send the same body again. The function then gives `changed: false` too.
590
+ *
591
+ * @throws ApiError as `send` does, and when the method is not GET.
592
+ * @throws the reason of the signal, when the signal stops the exchange.
593
+ * @beta
594
+ */
595
+ async function poll(pace, transport, conditions, input, signal) {
596
+ const { exchange, host } = input;
597
+ if (exchange.method.toUpperCase() !== "GET") throw new ApiError(`A poll sends only GET, not ${exchange.method}.`);
598
+ const { store } = pace.scheduler;
599
+ const last = conditions.get(exchange.url);
600
+ const which = validatorsToSend(store.validators?.(host), {
601
+ etag: last?.etag !== void 0,
602
+ lastModified: last?.lastModified !== void 0
603
+ }, pace.now());
604
+ const headers = { ...exchange.headers };
605
+ if (which.etag && last?.etag !== void 0) headers["if-none-match"] = last.etag;
606
+ if (which.lastModified && last?.lastModified !== void 0) headers["if-modified-since"] = last.lastModified;
607
+ const answer = await send(pace, transport, {
608
+ ...input,
609
+ exchange: {
610
+ ...exchange,
611
+ headers
612
+ }
613
+ }, signal);
614
+ const { reply } = answer;
615
+ let verdict;
616
+ let changed = false;
617
+ if (reply.status === 304) verdict = "not-modified";
618
+ else if (reply.status >= 200 && reply.status <= 299) {
619
+ const digest = await digestOf(reply.body);
620
+ changed = last?.digest !== digest;
621
+ verdict = changed ? "changed" : "same";
622
+ conditions.set(exchange.url, {
623
+ etag: reply.headers["etag"],
624
+ lastModified: reply.headers["last-modified"],
625
+ digest
626
+ });
627
+ }
628
+ const report = {
629
+ etag: headers["if-none-match"] !== void 0,
630
+ lastModified: headers["if-modified-since"] !== void 0
631
+ };
632
+ if (verdict !== void 0 && (report.etag || report.lastModified)) store.noteValidators?.(host, {
633
+ ...report,
634
+ answer: verdict
635
+ }, pace.now());
636
+ return {
637
+ ...answer,
638
+ changed
639
+ };
640
+ }
641
+ export { API_TIMEOUT_MS, ApiError, QuotaError, TOKEN_MARGIN_MS, fetchTransport, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
202
642
 
203
643
  //# sourceMappingURL=api.mjs.map