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/README.md CHANGED
@@ -49,7 +49,7 @@ The package is ESM only, and it includes its TypeScript declarations. It has the
49
49
  | `polite-crawler/politeness` | The queue that keeps one request in progress for each host | Yes |
50
50
  | `polite-crawler/signals` | The reader of usage signals (`Content-Signal`) | Yes |
51
51
  | `polite-crawler/urls` | The canonical form of a URL, its cache key and its site. It imports no module. | Yes |
52
- | `polite-crawler/api` | The polite send of a documented API, with the OAuth 2.0 client credentials grant. [Send to a documented API](#send-to-a-documented-api) tells how. | Yes |
52
+ | `polite-crawler/api` | The polite send of a documented API, with conditional polls and the OAuth 2.0 client credentials grant. [Send to a documented API](#send-to-a-documented-api) tells how. | Yes |
53
53
 
54
54
  The entry points that work in a browser import no Node.js module. The package loads no MCP SDK and no `zod`: the MCP server is the package `polite-crawler-mcp`.
55
55
 
@@ -1256,21 +1256,12 @@ Disallow: /
1256
1256
  The entry point `polite-crawler/api` sends the requests of an API client with the same politeness as the crawler. It stores no page. Give it the scheduler of the crawler, so a host has one pace for pages and API requests.
1257
1257
 
1258
1258
  ```ts
1259
- import { send, type Transport } from "polite-crawler/api";
1259
+ import { fetchTransport, send } from "polite-crawler/api";
1260
1260
  import { HostScheduler, realClock } from "polite-crawler/politeness";
1261
1261
 
1262
1262
  const scheduler = new HostScheduler(realClock, 4);
1263
1263
  const pace = { scheduler, now: realClock.now };
1264
- const transport: Transport = async (exchange, signal) => {
1265
- const { method, headers, body } = exchange;
1266
- const response = await fetch(exchange.url, { method, headers, body, redirect: "manual", signal });
1267
- return {
1268
- status: response.status,
1269
- statusText: response.statusText,
1270
- headers: Object.fromEntries(response.headers),
1271
- body: await response.text(),
1272
- };
1273
- };
1264
+ const transport = fetchTransport({ userAgent: "example-app/1.0 (ops@example.com)" });
1274
1265
 
1275
1266
  const answer = await send(pace, transport, {
1276
1267
  source: "Example API",
@@ -1281,12 +1272,95 @@ const answer = await send(pace, transport, {
1281
1272
  });
1282
1273
  ```
1283
1274
 
1284
- - **The transport is a port.** Give `fetch`, a different HTTP client, or a fake in a test. The send changes no part of the exchange.
1275
+ - **The transport is a port.** `fetchTransport` sends with `fetch`. Give a different HTTP client, or a fake in a test. The send changes no part of the exchange.
1276
+ - **A User-Agent and a time limit.** `fetchTransport` needs a User-Agent that names the client and a contact. Some APIs refuse a request with no User-Agent. It stops a request and its body after `timeoutMs` (default 30 seconds), and the send counts that as a failure of the host. It does not follow a redirect.
1285
1277
  - **The reaction is the reaction of the crawler.** `reactToOutcome` sets the rest and the stops of the host after each answer. A 429 waits the `Retry-After`, a 403 stops the host, and five failures in sequence stop it.
1286
1278
  - **Each answer comes back.** The send gives each status to the caller. It throws an `ApiError` only when the API gives no answer, or when the host is stopped.
1287
1279
  - **Tokens.** `tokenStore` keeps one token of the OAuth 2.0 client credentials grant, and `readGrant` reads the answer of the token endpoint. `sendWithToken` gets a new token after a 401 and sends one more time. A second 401 stops the host.
1288
1280
  - **No secret in a message.** Give the keys of the exchange in `secrets`, and a `redact` function. The send gives the text of each error to `redact`. `sendWithToken` adds the token to the secrets. The default `redact` changes nothing, so give one that removes each form of a secret.
1289
1281
 
1282
+ ### Poll an API
1283
+
1284
+ `poll` sends a conditional GET at the pace of the host. It keeps the `ETag` and the `Last-Modified` date of the last answer 2xx of each URL. They go in a store that you give, for example a `Map`. The next poll sends them as `If-None-Match` and `If-Modified-Since`. A poll every 60 seconds then costs a 304 with no body while the data does not change.
1285
+
1286
+ ```ts
1287
+ import { fetchTransport, poll, type Condition } from "polite-crawler/api";
1288
+
1289
+ const conditions = new Map<string, Condition>();
1290
+ const polled = await poll(pace, transport, conditions, {
1291
+ source: "Example alerts",
1292
+ host: "api.example.com",
1293
+ minIntervalMs: 30_000,
1294
+ what: "the active alerts",
1295
+ exchange: {
1296
+ method: "GET",
1297
+ url: "https://api.example.com/alerts/active",
1298
+ headers: { accept: "application/geo+json" },
1299
+ body: null,
1300
+ },
1301
+ });
1302
+ if (polled.changed) {
1303
+ // read polled.reply.body
1304
+ }
1305
+ ```
1306
+
1307
+ - **`changed`** is true only for an answer 2xx with a body that is not the last body of the URL. A 304, the same body again and each other status give false. A 304 has no body: keep the result of the last changed body.
1308
+ - **The poll keeps no page.** The store holds the two validators and the SHA-256 of the last body.
1309
+ - **The validator memo of the crawler.** Some hosts give an `ETag` that changes at each answer. With a store of the scheduler that keeps the validator memo, the poll then sends only `If-Modified-Since`, as the crawler does.
1310
+ - **One store for one set of headers.** A store keeps one entry for each URL. Give a second store to a request with a different `accept` header.
1311
+
1312
+ ### Quotas of a key
1313
+
1314
+ Many free API keys have a quota: a count of calls or messages in each day, month or window. The pace of the host does not count it. `quotaGate` counts the calls of one key, and it refuses a call over the quota before the provider does. `withQuota` puts a gate on an async function and keeps its type. So it fits each path of a call: a `fetch` that a client takes, a transport of `send` and `poll`, or a different client.
1315
+
1316
+ ```ts
1317
+ import { quotaGate, readQuotaHeaders, withQuota } from "polite-crawler/api";
1318
+ import { SqliteHostStateStore } from "polite-crawler";
1319
+
1320
+ // Pushover: 10,000 messages each month for each user account, reset at 00:00 Central Time on the 1st
1321
+ const gate = quotaGate(
1322
+ {
1323
+ name: "Pushover messages",
1324
+ limit: 10_000,
1325
+ reserve: 100,
1326
+ window: { kind: "calendar", unit: "month", timeZone: "America/Chicago" },
1327
+ },
1328
+ { key: "pushover:account-1", store: new SqliteHostStateStore("state/hosts.sqlite") },
1329
+ );
1330
+
1331
+ // a fetch for a client that takes one; only a message counts, not a read of a receipt
1332
+ const fetchWithQuota = withQuota(gate, fetch, {
1333
+ cost: (input) =>
1334
+ new URL(input instanceof Request ? input.url : input).pathname.endsWith("/messages.json") ? 1 : 0,
1335
+ read: (response) =>
1336
+ readQuotaHeaders(
1337
+ (name) => response.headers.get(name),
1338
+ { remaining: "X-Limit-App-Remaining", resetAt: "X-Limit-App-Reset" },
1339
+ Date.now(),
1340
+ ),
1341
+ });
1342
+ ```
1343
+
1344
+ - **A refusal before the call.** A call over the quota throws `QuotaError` with `resetAt`, the time when the gate gives units again. The wrapped function does not start, so no request goes out. `send` and `poll` give the `QuotaError` as it is. The host keeps its state, because a refusal of the quota is not a failure of the host.
1345
+ - **A refusal of the provider.** While the provider refuses the key, `state().left` is 0. Then `resetAt` is the end of the refusal, or a later time when the window has the units of the call.
1346
+ - **The window.** A `calendar` window is a day or a month in an IANA time zone, from the hour `hour`. It follows the clock changes of the zone. A `rolling` window is the last `ms` milliseconds. When the provider does not tell when its count starts again, use a rolling window.
1347
+ - **The length of a rolling window.** A rolling window counts at least as much as a calendar window only when it is as long as the longest calendar window. In a zone with clock changes, a day can have 25 hours, and a month can have 31 days and 1 hour (745 hours). In UTC, a day always has 24 hours.
1348
+ - **The count is not lower than the count of the provider.** A rolling window puts each call in a time bucket (60 in a window by default). A bucket counts until all of it is out of the window. The answer of the provider (`read`) can make the count larger, but not smaller. A count of 0 left, or a reset time with no count, stops the key until that time. `readQuotaHeaders` reads the seconds until the reset, or the HTTP date of the reset, as `Retry-After` gives them.
1349
+ - **The reserve.** The gate keeps `reserve` units unused, for a different program on the same key or for a call that you must make.
1350
+ - **The cost.** A call counts 1 unit, or `cost` units. A cost of 0 counts nothing and refuses nothing. A cost of more than the quota gives in one window is a fault of the caller: the gate throws an `ApiError`.
1351
+ - **The store.** `memoryQuotaStore` keeps the counts in memory. `SqliteHostStateStore` keeps them in its file, so the count of a key stays after a restart and two processes share it. Each change of a count is one transaction. The key names the account that the provider counts. It is not the secret of the key: the store keeps it as text.
1352
+ - **An error after the call.** When `read` or the store fails after the call, the request went out. So `withQuota` gives the result, and it gives the error to `onError`. It does not throw, because a retry after a throw sends the request again.
1353
+ - **Two quotas on one key.** Put two gates on one function, for example `withQuota(perMinute, withQuota(perDay, fetch))`. Give each quota a different name: the store keeps one record for each name and key. The outer gate counts a call before the inner gate examines it. So a refusal of the inner gate keeps a unit of the outer gate. Put the gate of the shortest window outside, so that this unit stops counting soon.
1354
+
1355
+ These are the limits of the first providers, as their documents gave them on 2026-11-14:
1356
+
1357
+ | Provider | Limit | Window | Headers |
1358
+ | --- | --- | --- | --- |
1359
+ | [Pushover](https://pushover.net/api#limits) | 10,000 messages each month for each user account (25,000 for a team). The applications of an account share it. | Calendar month, `America/Chicago`, from 00:00 on the 1st | `X-Limit-App-Remaining`, `X-Limit-App-Reset` (seconds since the epoch) |
1360
+ | [NASA FIRMS](https://firms.modaps.eosdis.nasa.gov/api/map_key/) | 5,000 transactions for each MAP_KEY | Rolling, 10 minutes | none |
1361
+ | [OpenSky Network](https://openskynetwork.github.io/opensky-api/rest.html) | 400 credits a day with no account, 4,000 for a registered user, 8,000 for an active feeder. `/states`, `/tracks` and `/flights` each have a quota: give each one a key. | Rolling, 25 hours (the document gives no reset time or zone, and a day can have 25 hours) | `X-Rate-Limit-Remaining`, `X-Rate-Limit-Retry-After-Seconds` (seconds until the reset) |
1362
+ | [TomTom](https://docs.tomtom.com/pricing) | 200,000 tile requests and 20,000 other map requests each month, free | Rolling, 745 hours (the document gives no reset time or zone, and a month can have 31 days and 1 hour) | none |
1363
+
1290
1364
  ## Stored copies and conditional requests
1291
1365
 
1292
1366
  A fetch uses the stored copy of a URL, with no request, while the copy is younger than `maxAge` (24 hours by default). With `maxAge: "auto"`, the crawler uses the freshness that the server gave: `Cache-Control`, `Expires`, or 10 percent of the age of `Last-Modified`. With `"auto"`, `no-store` and `no-cache` make a copy stale at once. A fixed `maxAge` ignores them. A response that varies on a request header (`Vary`) is used again only for a request with the same value of that header. The store keeps one copy for each URL, so a request with a different value replaces it.
package/build/api.d.mts CHANGED
@@ -1,16 +1,17 @@
1
+ import { Classified, Outcome } from "./classify.mjs";
2
+ import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, QuotaRecord, QuotaStore, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "./politeness.mjs";
1
3
  /**
2
- * The polite send of a documented API. It keeps the pace of each host with the scheduler of the
3
- * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each
4
- * answer. The send stores no page, because the terms of some APIs forbid a store.
5
- *
6
- * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.
7
- * The module imports no Node.js module, and it uses no type of a platform except the signal.
4
+ * The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import
5
+ * it and do not import each other.
6
+ */
7
+ /**
8
+ * An error of the send or of the token. The `redact` function of the send examined its message.
8
9
  *
9
- * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,
10
- * `tokenStore` and `sendWithToken`. Each export is beta: a minor version can change it.
10
+ * @beta
11
11
  */
12
- import { Classified, Outcome } from "./classify.mjs";
13
- import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "./politeness.mjs";
12
+ export declare class ApiError extends Error {
13
+ override readonly name: string;
14
+ }
14
15
  /**
15
16
  * These are the facts of one answer that set the reaction of its host. `classify` gives the
16
17
  * outcome and the wait that the server asked for.
@@ -90,6 +91,202 @@ export declare const outcomeResult: (facts: OutcomeFacts) => HostResult;
90
91
  * @beta
91
92
  */
92
93
  export declare const reactToOutcome: (facts: OutcomeFacts, counts: HostCounts, context: ReactionContext) => HostReaction;
94
+ /**
95
+ * The window of a quota.
96
+ *
97
+ * - `rolling`: the units of the last `ms` milliseconds. Use it when the provider does not tell when
98
+ * its count starts again. It is stricter than each fixed window of the same length or shorter.
99
+ * - `calendar`: the units of a day or a month in the IANA time zone `timeZone`. A window starts at
100
+ * the hour `hour` (default 0) of the first day, in that zone. When the clock jumps over that hour,
101
+ * the window starts at the jump.
102
+ *
103
+ * @beta
104
+ */
105
+ type QuotaWindow = {
106
+ readonly kind: "rolling";
107
+ readonly ms: number;
108
+ /** The window has this count of time buckets. The default is 60. Each call counts until all of its bucket is out of the window. */
109
+ readonly buckets?: number | undefined;
110
+ } | {
111
+ readonly kind: "calendar";
112
+ readonly unit: "day" | "month";
113
+ /** This value is an IANA time zone, for example `America/Chicago` or `UTC`. */
114
+ readonly timeZone: string;
115
+ /** This value is the hour of the start of a window, from 0 to 23. The default is 0. */
116
+ readonly hour?: number | undefined;
117
+ };
118
+ /**
119
+ * A quota of one API key: at most `limit` units in each window.
120
+ *
121
+ * @beta
122
+ */
123
+ interface Quota {
124
+ /**
125
+ * This value names the quota in a message, for example `Example API requests`. A store keeps a
126
+ * record for each name and key, so give each quota of a key a different name.
127
+ */
128
+ readonly name: string;
129
+ /** This value is the count of units that the provider gives in one window. */
130
+ readonly limit: number;
131
+ /** The gate keeps this count of units unused. The default is 0. */
132
+ readonly reserve?: number | undefined;
133
+ readonly window: QuotaWindow;
134
+ }
135
+ /**
136
+ * What an answer of the provider tells of its count.
137
+ *
138
+ * @beta
139
+ */
140
+ interface QuotaReading {
141
+ /** This value is the count of units that the provider gives before its next reset. */
142
+ readonly remaining?: number | undefined;
143
+ /**
144
+ * This value is the time of the next reset of the provider, in milliseconds since the epoch. When
145
+ * `remaining` is 0 or is not there, the gate refuses each call until this time.
146
+ */
147
+ readonly resetAt?: number | undefined;
148
+ }
149
+ /**
150
+ * The state of a quota at one time.
151
+ *
152
+ * @beta
153
+ */
154
+ interface QuotaState {
155
+ /** This value is the count of units in the window. */
156
+ readonly used: number;
157
+ /**
158
+ * This value is the count of units that the gate gives: the limit, less the reserve and `used`.
159
+ * It is 0 while the provider refuses the key.
160
+ */
161
+ readonly left: number;
162
+ /** The units come back from this time, in milliseconds since the epoch. With no unit in the window, it is not there. */
163
+ readonly resetAt?: number | undefined;
164
+ /** The provider refused the key until this time, in milliseconds since the epoch. */
165
+ readonly blockedUntil?: number | undefined;
166
+ }
167
+ /**
168
+ * The refusal of a call over its quota. The gate refused the call before the call started.
169
+ *
170
+ * @beta
171
+ */
172
+ export declare class QuotaError extends ApiError {
173
+ override readonly name: string;
174
+ /** This value is the key of the quota. */
175
+ readonly key: string;
176
+ /** The gate gives units again from this time, in milliseconds since the epoch. */
177
+ readonly resetAt: number;
178
+ constructor(message: string, key: string, resetAt: number);
179
+ }
180
+ /**
181
+ * The gate of one key. It counts the units of the calls, and it refuses a call over the quota.
182
+ *
183
+ * @beta
184
+ */
185
+ interface QuotaGate {
186
+ readonly quota: Quota;
187
+ readonly key: string;
188
+ /**
189
+ * This method counts `cost` units (default 1) for a call that starts at this time, and gives the
190
+ * state. A cost of 0 counts nothing and refuses nothing.
191
+ *
192
+ * @throws QuotaError when the units are more than `left`, or when the provider refused the key.
193
+ * The gate then counts nothing. Its `resetAt` is the end of the refusal of the provider, or a later
194
+ * time when the window has the units of the call.
195
+ * @throws ApiError when the cost is negative or not finite, or when it is more than the quota
196
+ * gives in one window.
197
+ */
198
+ take(cost?: number): QuotaState;
199
+ /** This method adds what an answer of the provider tells. The count can only become larger. */
200
+ note(reading: QuotaReading): QuotaState;
201
+ /** This method gives the state at this time, and changes nothing. */
202
+ state(): QuotaState;
203
+ }
204
+ /**
205
+ * The options of `quotaGate`.
206
+ *
207
+ * @beta
208
+ */
209
+ interface QuotaGateOptions {
210
+ /**
211
+ * This value names the key, for example `example:account-1`. A store keeps it as text, so do not
212
+ * give the secret of the key. Give one name to each account that the provider counts.
213
+ */
214
+ readonly key: string;
215
+ /** This store keeps the records. The default is a new `memoryQuotaStore`. */
216
+ readonly store?: QuotaStore | undefined;
217
+ /** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */
218
+ readonly now?: (() => number) | undefined;
219
+ }
220
+ /**
221
+ * This function makes the gate of one key.
222
+ *
223
+ * @throws ApiError when the quota or its window is not valid.
224
+ * @beta
225
+ */
226
+ export declare function quotaGate(quota: Quota, options: QuotaGateOptions): QuotaGate;
227
+ /**
228
+ * This function makes a store of records in memory. Each gate of one process can share it.
229
+ *
230
+ * @beta
231
+ */
232
+ export declare function memoryQuotaStore(): QuotaStore;
233
+ /**
234
+ * The options of `withQuota`.
235
+ *
236
+ * @beta
237
+ */
238
+ interface WithQuotaOptions<A extends readonly unknown[], R> {
239
+ /**
240
+ * This value is the count of units of a call, or a function of the arguments that gives it. The
241
+ * default is 1. Give 0 for a call that the provider does not count: the gate then does not refuse it.
242
+ */
243
+ readonly cost?: number | ((...args: A) => number) | undefined;
244
+ /** This function reads what the result of a call tells of the count of the provider, for example with `readQuotaHeaders`. */
245
+ readonly read?: ((result: R) => QuotaReading | undefined) | undefined;
246
+ /**
247
+ * This function gets an error of `read` or of the store after the call. The call went out, so
248
+ * `withQuota` gives its result. It does not throw, because a retry after a throw sends the call
249
+ * again. With no function, the error is lost.
250
+ */
251
+ readonly onError?: ((error: unknown) => void) | undefined;
252
+ }
253
+ /**
254
+ * This function puts a gate on an async function, and keeps the type of the function. Each call
255
+ * counts its units first. A call over the quota throws `QuotaError`, and the function does not start.
256
+ *
257
+ * Give the result to a client that takes a function of this type. For example, `withQuota(gate,
258
+ * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`. Put two gates on
259
+ * one function for two quotas of one key.
260
+ *
261
+ * @beta
262
+ */
263
+ export declare function withQuota<A extends readonly unknown[], R>(gate: QuotaGate, call: (...args: A) => Promise<R>, options?: WithQuotaOptions<A, R>): (...args: A) => Promise<R>;
264
+ /**
265
+ * The names of the headers of an answer that tell the count of a provider. Each name is optional.
266
+ *
267
+ * @beta
268
+ */
269
+ interface QuotaHeaders {
270
+ /** This header has the count of units that the provider gives before its reset, for example `x-ratelimit-remaining`. */
271
+ readonly remaining?: string | undefined;
272
+ /** This header has the time of the reset in seconds since the epoch, for example `x-ratelimit-reset`. */
273
+ readonly resetAt?: string | undefined;
274
+ /**
275
+ * This header has the seconds until the reset, or the HTTP date of the reset, as `retry-after`
276
+ * gives them. When it has a value, the gate does not read `resetAt`.
277
+ */
278
+ readonly resetAfter?: string | undefined;
279
+ }
280
+ /**
281
+ * This function reads the count of a provider from the headers of an answer. `get` gives the value
282
+ * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or
283
+ * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of
284
+ * `resetAfter` can also be an HTTP date, as in `Retry-After`.
285
+ *
286
+ * @returns the reading, or undefined when no header has a value.
287
+ * @beta
288
+ */
289
+ export declare function readQuotaHeaders(get: (name: string) => string | null | undefined, names: QuotaHeaders, now: number): QuotaReading | undefined;
93
290
  /**
94
291
  * One request of a client to an API.
95
292
  *
@@ -139,8 +336,12 @@ export type Transport<S extends Signal = AbortSignal> = (exchange: Exchange, sig
139
336
  */
140
337
  export interface ApiScheduler<S extends Signal = AbortSignal> {
141
338
  run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;
142
- /** This store keeps the counts and the stops of each host. */
143
- readonly store: Pick<HostStateStore, "record" | "stop">;
339
+ /**
340
+ * This store keeps the counts and the stops of each host. When it has the validator memo
341
+ * (`validators` and `noteValidators`), `poll` uses it as the crawler does. The two members are optional, as in
342
+ * `HostStateStore`, so a store of `record` and `stop` is sufficient.
343
+ */
344
+ readonly store: Pick<HostStateStore, "record" | "stop" | "validators" | "noteValidators">;
144
345
  }
145
346
  /**
146
347
  * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.
@@ -164,14 +365,6 @@ export interface Pace<S extends Signal = AbortSignal> {
164
365
  * @beta
165
366
  */
166
367
  export type Redact = (text: string, secrets: readonly string[]) => string;
167
- /**
168
- * An error of the send or of the token. The `redact` function of the send examined its message.
169
- *
170
- * @beta
171
- */
172
- export declare class ApiError extends Error {
173
- override readonly name: string;
174
- }
175
368
  /**
176
369
  * One exchange of a client, and its context for the pace and the messages.
177
370
  *
@@ -220,10 +413,12 @@ export declare function statusLine(reply: Reply): string;
220
413
  * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.
221
414
  * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.
222
415
  * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.
416
+ * - A `QuotaError` of the transport (`withQuota`) does not change the host.
223
417
  *
224
418
  * The function gives each answer, with each status. The caller reads the status.
225
419
  *
226
420
  * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.
421
+ * @throws QuotaError of the transport, as it is, when a quota refuses the exchange.
227
422
  * @throws the reason of the signal, when the signal stops the exchange.
228
423
  * @beta
229
424
  */
@@ -285,4 +480,106 @@ export declare function tokenStore<S extends Signal = AbortSignal>(grant: (signa
285
480
  * @beta
286
481
  */
287
482
  export declare function sendWithToken<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, tokens: Tokens<S>, input: Send, headers: (token: string) => Readonly<Record<string, string>>, signal?: S): Promise<Answer>;
288
- export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, ReactionContext, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict };
483
+ /**
484
+ * The part of a `fetch` function that `fetchTransport` uses. The `fetch` of Node.js and of a
485
+ * browser has it.
486
+ *
487
+ * @beta
488
+ */
489
+ export type FetchLike = (url: string, init: {
490
+ readonly method: string;
491
+ readonly headers: Record<string, string>;
492
+ readonly body?: string;
493
+ readonly redirect: "manual";
494
+ readonly signal: AbortSignal;
495
+ }) => Promise<{
496
+ readonly status: number;
497
+ readonly statusText: string;
498
+ readonly headers: {
499
+ forEach(callback: (value: string, name: string) => void): void;
500
+ };
501
+ text(): Promise<string>;
502
+ }>;
503
+ /**
504
+ * The default time limit of `fetchTransport`: 30 seconds for the request and its body.
505
+ *
506
+ * @beta
507
+ */
508
+ export declare const API_TIMEOUT_MS: number;
509
+ /**
510
+ * The options of `fetchTransport`.
511
+ *
512
+ * @beta
513
+ */
514
+ export interface FetchTransportOptions {
515
+ /**
516
+ * This value names the client and a contact, for example `example-app/1.0 (ops@example.com)`.
517
+ * Each request sends it, except a request with its own `user-agent` header. Some APIs, for
518
+ * example `api.weather.gov`, refuse a request with no User-Agent.
519
+ */
520
+ readonly userAgent: string;
521
+ /** This value is the time limit of one request and its body, in milliseconds. The default is `API_TIMEOUT_MS`. */
522
+ readonly timeoutMs?: number | undefined;
523
+ /** This function sends the request. The default is the global `fetch`. */
524
+ readonly fetch?: FetchLike | undefined;
525
+ }
526
+ /**
527
+ * This function makes a transport over `fetch`. The transport sends the User-Agent, does not
528
+ * follow a redirect, and stops a request after the time limit. A request that the time limit
529
+ * stopped throws an error, and `send` counts it as a failure of the host. A request that the
530
+ * signal stopped throws the reason of the signal.
531
+ *
532
+ * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.
533
+ * @beta
534
+ */
535
+ export declare function fetchTransport(options: FetchTransportOptions): Transport;
536
+ /**
537
+ * What a poll keeps of the last answer 2xx of one URL.
538
+ *
539
+ * @beta
540
+ */
541
+ export interface Condition {
542
+ /** This value is the `ETag` header of the answer, when it had one. */
543
+ readonly etag?: string | undefined;
544
+ /** This value is the `Last-Modified` header of the answer, when it had one. */
545
+ readonly lastModified?: string | undefined;
546
+ /** This value is the SHA-256 of the body, in hexadecimal. */
547
+ readonly digest: string;
548
+ }
549
+ /**
550
+ * A store of the conditions of a poll, one for each URL. A `Map` is a store in memory. One store
551
+ * goes with one set of request headers: give a second store to a second `accept` header.
552
+ *
553
+ * @beta
554
+ */
555
+ export interface Conditions {
556
+ get(url: string): Condition | undefined;
557
+ set(url: string, condition: Condition): void;
558
+ }
559
+ /**
560
+ * An answer of a poll.
561
+ *
562
+ * @beta
563
+ */
564
+ export interface Polled extends Answer {
565
+ /**
566
+ * This value is true for an answer 2xx with a body that is not the body of the last answer 2xx
567
+ * of the URL. It is false for a 304, for the same body, and for each other status.
568
+ */
569
+ readonly changed: boolean;
570
+ }
571
+ /**
572
+ * This function sends one conditional GET at the pace of its host, as `send` does. It sends the
573
+ * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and
574
+ * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then
575
+ * the function sends only the date to a host whose ETags do not match, as the crawler does.
576
+ *
577
+ * A 304 gives no body: the caller keeps the result of the last changed body. A server that does
578
+ * not answer 304 can send the same body again. The function then gives `changed: false` too.
579
+ *
580
+ * @throws ApiError as `send` does, and when the method is not GET.
581
+ * @throws the reason of the signal, when the signal stops the exchange.
582
+ * @beta
583
+ */
584
+ export declare function poll<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, conditions: Conditions, input: Send, signal?: S): Promise<Polled>;
585
+ export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, Quota, QuotaGate, QuotaGateOptions, QuotaHeaders, QuotaReading, QuotaRecord, QuotaState, QuotaStore, QuotaWindow, ReactionContext, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict, WithQuotaOptions };