polite-crawler 0.7.8 → 0.7.9
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/README.md +23 -0
- package/build/api.d.mts +173 -1
- package/build/api.mjs +265 -3
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-f2xHraCa.mjs → cli-daemon-CAgWpFlR.mjs} +2 -2
- package/build/{cli-daemon-f2xHraCa.mjs.map → cli-daemon-CAgWpFlR.mjs.map} +1 -1
- package/build/{cli-recipes-ZFyc0wTa.mjs → cli-recipes-C_EdrADI.mjs} +2 -2
- package/build/{cli-recipes-ZFyc0wTa.mjs.map → cli-recipes-C_EdrADI.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-CqQmcYh9.mjs → daemon-CV0QsAVj.mjs} +3 -3
- package/build/{daemon-CqQmcYh9.mjs.map → daemon-CV0QsAVj.mjs.map} +1 -1
- package/build/{diff-BwrS5qLG.mjs → diff-CNfNHuXy.mjs} +2 -2
- package/build/{diff-BwrS5qLG.mjs.map → diff-CNfNHuXy.mjs.map} +1 -1
- package/build/{extract-Dt-zWC9M.mjs → extract-B8hHBo8E.mjs} +2 -2
- package/build/{extract-Dt-zWC9M.mjs.map → extract-B8hHBo8E.mjs.map} +1 -1
- package/build/index.d.mts +1 -1
- package/build/index.mjs +10 -10
- package/build/{open-D2aPACL_.mjs → open-BcalDbaa.mjs} +6 -6
- package/build/{open-D2aPACL_.mjs.map → open-BcalDbaa.mjs.map} +1 -1
- package/build/{recipe-BZCG1pOy.mjs → recipe-BZB54swk.mjs} +3 -3
- package/build/{recipe-BZCG1pOy.mjs.map → recipe-BZB54swk.mjs.map} +1 -1
- package/build/{recipe-product-gd-6XJ4C.mjs → recipe-product-BAccdfw7.mjs} +4 -4
- package/build/{recipe-product-gd-6XJ4C.mjs.map → recipe-product-BAccdfw7.mjs.map} +1 -1
- package/build/{runtime-CD32YZv5.mjs → runtime-CDJUCDB6.mjs} +2 -2
- package/build/{runtime-CD32YZv5.mjs.map → runtime-CDJUCDB6.mjs.map} +1 -1
- package/build/{version-ACvb6zmT.mjs → version-DXlmwMT5.mjs} +2 -2
- package/build/{version-ACvb6zmT.mjs.map → version-DXlmwMT5.mjs.map} +1 -1
- package/build/{wacz-C2egGCSb.mjs → wacz-T_8QbgMZ.mjs} +3 -3
- package/build/{wacz-C2egGCSb.mjs.map → wacz-T_8QbgMZ.mjs.map} +1 -1
- package/build/{warc-DshKROY0.mjs → warc-Brpd-pQg.mjs} +2 -2
- package/build/{warc-DshKROY0.mjs.map → warc-Brpd-pQg.mjs.map} +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1312,6 +1312,29 @@ if (polled.changed) {
|
|
|
1312
1312
|
- **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.
|
|
1313
1313
|
- **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.
|
|
1314
1314
|
|
|
1315
|
+
### Keep the answers of an API
|
|
1316
|
+
|
|
1317
|
+
`poll` tells only if the data changed. A client that needs the data at each request uses `keptFetch`. It keeps the last full answer of each GET with its body. The next GET of the same URL sends the validators. A 304 then gives the kept answer: the status, the body and the kept headers, with the new fields of the 304. Some APIs do not count a 304 in the rate limit, for example the REST API of GitHub. A run that reads the same files again then counts fewer requests.
|
|
1318
|
+
|
|
1319
|
+
```ts
|
|
1320
|
+
import { fetchTransport, keptFetch, keptStore, readKept } from "polite-crawler/api";
|
|
1321
|
+
|
|
1322
|
+
// The entries of the last run, for example from a file of the cache of a CI job
|
|
1323
|
+
const store = keptStore(readKept(JSON.parse(lastRun)));
|
|
1324
|
+
const transport = fetchTransport({
|
|
1325
|
+
userAgent: "example-app/1.0 (+https://example.com/app)",
|
|
1326
|
+
fetch: keptFetch((url, init) => fetch(url, init), store),
|
|
1327
|
+
});
|
|
1328
|
+
// ... the run sends its requests through the transport ...
|
|
1329
|
+
const nextRun = JSON.stringify(store.used());
|
|
1330
|
+
```
|
|
1331
|
+
|
|
1332
|
+
- **The server decides.** A kept answer goes to the client only after a 304 of the server. The key of an answer is its URL and its `accept` header. The server examines the access of each request, so a 304 comes only for a request that can read the answer.
|
|
1333
|
+
- **A store keeps text only.** It keeps an answer 200, 203 or 204 with an `ETag` or a `Last-Modified` date. The answer needs a text, JSON or XML type in UTF-8, and a body of at most `KEPT_BODY_MAX` UTF-16 code units. Each other answer goes to the client as it is. A binary body is not read, so an exchange with `read: "bytes"` gets its bytes.
|
|
1334
|
+
- **Your request stays yours.** A request with its own `If-None-Match`, `If-Modified-Since`, other `If-` header or `Range` goes to the server as it is. So does each request that is not a GET with no body.
|
|
1335
|
+
- **The store stays small.** `used()` gives only the entries that the run read or wrote. Save these, and an answer that no run asks for again goes away. `readKept` drops each entry with a bad shape, so a damaged file gives fewer kept answers and no error.
|
|
1336
|
+
- **A file of answers holds data.** A file of the cache of a public repository can be read by others. Encrypt the file when the answers hold private data.
|
|
1337
|
+
|
|
1315
1338
|
### Quotas of a key
|
|
1316
1339
|
|
|
1317
1340
|
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.
|
package/build/api.d.mts
CHANGED
|
@@ -1,5 +1,165 @@
|
|
|
1
1
|
import { Classified, Outcome } from "./classify.mjs";
|
|
2
2
|
import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, QuotaRecord, QuotaStore, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "./politeness.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* Kept answers. A client keeps the last full answer of a GET with its validators. The next GET of
|
|
5
|
+
* the same key is then a conditional request (RFC 9110 §13.1). An answer 304 then gives the kept
|
|
6
|
+
* answer with the fields of the 304 (RFC 9111 §4.3.4). Some APIs with a rate limit do not count a
|
|
7
|
+
* 304, for example the REST API of GitHub. The store is data, so a client can keep it between two
|
|
8
|
+
* runs. The server examines each validator, so a kept answer goes to the client only after the
|
|
9
|
+
* server tells that it is current. The module imports no Node.js module.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* The kept answer of one key.
|
|
13
|
+
*
|
|
14
|
+
* @beta
|
|
15
|
+
*/
|
|
16
|
+
interface Kept {
|
|
17
|
+
/** This value is the `ETag` header of the answer, when it had one. */
|
|
18
|
+
readonly etag?: string | undefined;
|
|
19
|
+
/** This value is the `Last-Modified` header of the answer, when it had one. */
|
|
20
|
+
readonly lastModified?: string | undefined;
|
|
21
|
+
/** This value is the status of the answer: 200, 203 or 204 (`KEPT_STATUSES`). */
|
|
22
|
+
readonly status: number;
|
|
23
|
+
/** These values are the headers that the store keeps, by name in lowercase. */
|
|
24
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
25
|
+
/** This value is the body of the answer, as text. */
|
|
26
|
+
readonly body: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A store of kept answers, by key. A `Map` is a store in memory. `keptStore` also records the
|
|
30
|
+
* entries that a run uses.
|
|
31
|
+
*
|
|
32
|
+
* @beta
|
|
33
|
+
*/
|
|
34
|
+
interface KeptStore {
|
|
35
|
+
/** This function gives the kept answer of the key, or undefined when the store has none. */
|
|
36
|
+
get(key: string): Kept | undefined;
|
|
37
|
+
/** This function keeps the answer under the key, in place of an earlier one. */
|
|
38
|
+
set(key: string, kept: Kept): void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* An answer as a client reads it: its status, its headers by name in lowercase, and its body.
|
|
42
|
+
*
|
|
43
|
+
* @beta
|
|
44
|
+
*/
|
|
45
|
+
interface KeptAnswer {
|
|
46
|
+
/** The status of the answer. After a 304, it is the status of the kept answer. */
|
|
47
|
+
readonly status: number;
|
|
48
|
+
/** The headers of the answer, by name in lowercase. */
|
|
49
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
50
|
+
/** The body of the answer as text. After a 304, it is the kept body. */
|
|
51
|
+
readonly body: string;
|
|
52
|
+
/** This value is true when the server answered 304 and the answer is the kept answer. */
|
|
53
|
+
readonly notModified: boolean;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The options of `keepAnswer`.
|
|
57
|
+
*
|
|
58
|
+
* @beta
|
|
59
|
+
*/
|
|
60
|
+
interface KeepOptions {
|
|
61
|
+
/** These names are the headers that a kept answer keeps. The default is `KEPT_HEADERS`. */
|
|
62
|
+
readonly headers?: readonly string[] | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* This value is the largest body that the store keeps, in UTF-16 code units. The default is
|
|
65
|
+
* `KEPT_BODY_MAX`.
|
|
66
|
+
*/
|
|
67
|
+
readonly maxBody?: number | undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The headers that a kept answer keeps when the options give no list. `link` keeps the next page
|
|
71
|
+
* of a list.
|
|
72
|
+
*
|
|
73
|
+
* @beta
|
|
74
|
+
*/
|
|
75
|
+
export declare const KEPT_HEADERS: readonly string[];
|
|
76
|
+
/**
|
|
77
|
+
* The largest body that a store keeps when the options give no limit: 1,048,576 UTF-16 code units.
|
|
78
|
+
*
|
|
79
|
+
* @beta
|
|
80
|
+
*/
|
|
81
|
+
export declare const KEPT_BODY_MAX: number;
|
|
82
|
+
/**
|
|
83
|
+
* The statuses that a store keeps. The body of each is the full answer. A 206 has only a part of
|
|
84
|
+
* the body, so a store does not keep it.
|
|
85
|
+
*
|
|
86
|
+
* @beta
|
|
87
|
+
*/
|
|
88
|
+
export declare const KEPT_STATUSES: readonly number[];
|
|
89
|
+
/**
|
|
90
|
+
* This function tells if the headers of a request make it conditional or partial on their own:
|
|
91
|
+
* `If-None-Match`, `If-Modified-Since`, `If-Match`, `If-Unmodified-Since`, `If-Range` or
|
|
92
|
+
* `Range`. The client of such a request reads the answer itself, so a store does not answer for
|
|
93
|
+
* it.
|
|
94
|
+
*
|
|
95
|
+
* @beta
|
|
96
|
+
*/
|
|
97
|
+
export declare function hasValidator(headers: Readonly<Record<string, string>>): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* This function tells if a body of a media type is text in UTF-8. That is a text, JSON or XML type
|
|
100
|
+
* with no charset or with the charset UTF-8. A store keeps only such a body, because `text()` of
|
|
101
|
+
* `fetch` reads a body as UTF-8.
|
|
102
|
+
*
|
|
103
|
+
* @beta
|
|
104
|
+
*/
|
|
105
|
+
export declare function isTextType(contentType: string | undefined): boolean;
|
|
106
|
+
/**
|
|
107
|
+
* This function gives the key of a request in a store: its `accept` header and its URL. A
|
|
108
|
+
* different `accept` header can give a different body, so it gets a different key.
|
|
109
|
+
*
|
|
110
|
+
* @beta
|
|
111
|
+
*/
|
|
112
|
+
export declare function keptKey(url: string, headers: Readonly<Record<string, string>>): string;
|
|
113
|
+
/**
|
|
114
|
+
* This function gives the headers of a conditional request: the headers of the request, and the
|
|
115
|
+
* validators of the kept answer. `If-None-Match` sends its ETag, and `If-Modified-Since` sends its
|
|
116
|
+
* date. The function adds no header to a request that has a validator of its own.
|
|
117
|
+
*
|
|
118
|
+
* @beta
|
|
119
|
+
*/
|
|
120
|
+
export declare function keptRequestHeaders(kept: Kept | undefined, headers: Readonly<Record<string, string>>): Record<string, string>;
|
|
121
|
+
/**
|
|
122
|
+
* This function gives the answer that a client reads, and changes the store.
|
|
123
|
+
*
|
|
124
|
+
* - A 304 for a key with a kept answer gives the kept answer. Its headers get the fields of the
|
|
125
|
+
* 304, as RFC 9111 §4.3.4 tells, and the store keeps the new values of its kept headers.
|
|
126
|
+
* - An answer with a status of `KEPT_STATUSES` and an ETag or a date goes into the store. It needs
|
|
127
|
+
* a text type in UTF-8 and a body in the limit.
|
|
128
|
+
* - Each other answer is as it is, and the store does not change.
|
|
129
|
+
*
|
|
130
|
+
* @beta
|
|
131
|
+
*/
|
|
132
|
+
export declare function keepAnswer(store: KeptStore, key: string, answer: {
|
|
133
|
+
readonly status: number;
|
|
134
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
135
|
+
readonly body: string;
|
|
136
|
+
}, options?: KeepOptions): KeptAnswer;
|
|
137
|
+
/**
|
|
138
|
+
* A store of kept answers in memory that records which entries a run uses.
|
|
139
|
+
*
|
|
140
|
+
* @beta
|
|
141
|
+
*/
|
|
142
|
+
interface KeptMemory extends KeptStore {
|
|
143
|
+
/**
|
|
144
|
+
* This function gives each entry that a `get` found or a `set` wrote, in the order of the first
|
|
145
|
+
* use. A client that saves only these entries keeps no answer that it does not ask for again.
|
|
146
|
+
*/
|
|
147
|
+
used(): [string, Kept][];
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* This function makes a store of kept answers in memory, with the entries of an earlier run.
|
|
151
|
+
*
|
|
152
|
+
* @beta
|
|
153
|
+
*/
|
|
154
|
+
export declare function keptStore(entries?: Iterable<readonly [string, Kept]>): KeptMemory;
|
|
155
|
+
/**
|
|
156
|
+
* This function reads the entries of a store from data, for example from the JSON of the `used`
|
|
157
|
+
* entries of an earlier run. It keeps each entry with a correct shape and drops each other entry.
|
|
158
|
+
* Thus damaged data gives fewer kept answers and no error.
|
|
159
|
+
*
|
|
160
|
+
* @beta
|
|
161
|
+
*/
|
|
162
|
+
export declare function readKept(data: unknown): [string, Kept][];
|
|
3
163
|
/**
|
|
4
164
|
* The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import
|
|
5
165
|
* it and do not import each other.
|
|
@@ -641,6 +801,18 @@ export interface FetchTransportOptions {
|
|
|
641
801
|
* @beta
|
|
642
802
|
*/
|
|
643
803
|
export declare function fetchTransport(options: FetchTransportOptions): Transport;
|
|
804
|
+
/**
|
|
805
|
+
* This function makes a `fetch` with kept answers, for example for `fetchTransport`. A GET with no
|
|
806
|
+
* body and no conditional or range header of its own (`hasValidator`) sends the validators of its
|
|
807
|
+
* kept answer. The key of the answer is `keptKey`. A 304 then gives the kept answer, as
|
|
808
|
+
* `keepAnswer` tells, and a full answer with a text body in UTF-8 goes into the store. The function does not read a body
|
|
809
|
+
* of a different media type, so an exchange that reads `bytes` gets the bytes. Each other request
|
|
810
|
+
* goes to `fetch` as it is. The key does not hold the `authorization` header: the server examines
|
|
811
|
+
* the access of each request before it answers 304.
|
|
812
|
+
*
|
|
813
|
+
* @beta
|
|
814
|
+
*/
|
|
815
|
+
export declare function keptFetch(fetch: FetchLike, store: KeptStore, options?: KeepOptions): FetchLike;
|
|
644
816
|
/**
|
|
645
817
|
* What a poll keeps of the last answer 2xx of one URL.
|
|
646
818
|
*
|
|
@@ -690,4 +862,4 @@ export interface Polled extends Answer {
|
|
|
690
862
|
* @beta
|
|
691
863
|
*/
|
|
692
864
|
export declare function poll<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, conditions: Conditions, input: Send, signal?: S): Promise<Polled>;
|
|
693
|
-
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 };
|
|
865
|
+
export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, KeepOptions, Kept, KeptAnswer, KeptMemory, KeptStore, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, Quota, QuotaGate, QuotaGateOptions, QuotaHeaders, QuotaReading, QuotaRecord, QuotaState, QuotaStore, QuotaWindow, ReactionContext, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict, WithQuotaOptions };
|
package/build/api.mjs
CHANGED
|
@@ -347,6 +347,222 @@ function readQuotaHeaders(get, names, now) {
|
|
|
347
347
|
...resetAt === void 0 ? {} : { resetAt }
|
|
348
348
|
};
|
|
349
349
|
}
|
|
350
|
+
// src/kept.ts
|
|
351
|
+
/**
|
|
352
|
+
* The headers that a kept answer keeps when the options give no list. `link` keeps the next page
|
|
353
|
+
* of a list.
|
|
354
|
+
*
|
|
355
|
+
* @beta
|
|
356
|
+
*/
|
|
357
|
+
const KEPT_HEADERS = [
|
|
358
|
+
"content-type",
|
|
359
|
+
"etag",
|
|
360
|
+
"last-modified",
|
|
361
|
+
"link"
|
|
362
|
+
];
|
|
363
|
+
/**
|
|
364
|
+
* The largest body that a store keeps when the options give no limit: 1,048,576 UTF-16 code units.
|
|
365
|
+
*
|
|
366
|
+
* @beta
|
|
367
|
+
*/
|
|
368
|
+
const KEPT_BODY_MAX = 1048576;
|
|
369
|
+
/**
|
|
370
|
+
* The statuses that a store keeps. The body of each is the full answer. A 206 has only a part of
|
|
371
|
+
* the body, so a store does not keep it.
|
|
372
|
+
*
|
|
373
|
+
* @beta
|
|
374
|
+
*/
|
|
375
|
+
const KEPT_STATUSES = [
|
|
376
|
+
200,
|
|
377
|
+
203,
|
|
378
|
+
204
|
|
379
|
+
];
|
|
380
|
+
/** These fields of a 304 tell of its empty body, so they do not go into the kept answer. */
|
|
381
|
+
const BODY_FIELDS = /* @__PURE__ */ new Set([
|
|
382
|
+
"content-encoding",
|
|
383
|
+
"content-length",
|
|
384
|
+
"transfer-encoding"
|
|
385
|
+
]);
|
|
386
|
+
/** A body of one of these media types is text, so a store can keep it as text. */
|
|
387
|
+
const TEXT_TYPE = /^\s*(?:text\/[\w.+-]+|application\/(?:[\w.-]+\+)?(?:json|xml))\s*(?:;|$)/i;
|
|
388
|
+
/** This pattern finds the charset parameter of a media type. */
|
|
389
|
+
const CHARSET = /;\s*charset\s*=\s*"?([^";\s]+)"?/i;
|
|
390
|
+
/** This function gives the headers with each name in lowercase. */
|
|
391
|
+
const lower = (headers) => {
|
|
392
|
+
const out = {};
|
|
393
|
+
for (const [name, value] of Object.entries(headers)) out[name.toLowerCase()] = value;
|
|
394
|
+
return out;
|
|
395
|
+
};
|
|
396
|
+
/**
|
|
397
|
+
* This function tells if the headers of a request make it conditional or partial on their own:
|
|
398
|
+
* `If-None-Match`, `If-Modified-Since`, `If-Match`, `If-Unmodified-Since`, `If-Range` or
|
|
399
|
+
* `Range`. The client of such a request reads the answer itself, so a store does not answer for
|
|
400
|
+
* it.
|
|
401
|
+
*
|
|
402
|
+
* @beta
|
|
403
|
+
*/
|
|
404
|
+
function hasValidator(headers) {
|
|
405
|
+
return Object.keys(headers).some((name) => {
|
|
406
|
+
const n = name.toLowerCase();
|
|
407
|
+
return n === "range" || n.startsWith("if-");
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* This function tells if a body of a media type is text in UTF-8. That is a text, JSON or XML type
|
|
412
|
+
* with no charset or with the charset UTF-8. A store keeps only such a body, because `text()` of
|
|
413
|
+
* `fetch` reads a body as UTF-8.
|
|
414
|
+
*
|
|
415
|
+
* @beta
|
|
416
|
+
*/
|
|
417
|
+
function isTextType(contentType) {
|
|
418
|
+
const type = contentType ?? "";
|
|
419
|
+
if (!TEXT_TYPE.test(type)) return false;
|
|
420
|
+
const charset = CHARSET.exec(type)?.[1];
|
|
421
|
+
return charset === void 0 || /^utf-?8$/i.test(charset);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* This function gives the key of a request in a store: its `accept` header and its URL. A
|
|
425
|
+
* different `accept` header can give a different body, so it gets a different key.
|
|
426
|
+
*
|
|
427
|
+
* @beta
|
|
428
|
+
*/
|
|
429
|
+
function keptKey(url, headers) {
|
|
430
|
+
return `${lower(headers)["accept"] ?? ""} ${url}`;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* This function gives the headers of a conditional request: the headers of the request, and the
|
|
434
|
+
* validators of the kept answer. `If-None-Match` sends its ETag, and `If-Modified-Since` sends its
|
|
435
|
+
* date. The function adds no header to a request that has a validator of its own.
|
|
436
|
+
*
|
|
437
|
+
* @beta
|
|
438
|
+
*/
|
|
439
|
+
function keptRequestHeaders(kept, headers) {
|
|
440
|
+
const out = { ...headers };
|
|
441
|
+
if (kept === void 0 || hasValidator(headers)) return out;
|
|
442
|
+
if (kept.etag !== void 0) out["if-none-match"] = kept.etag;
|
|
443
|
+
if (kept.lastModified !== void 0) out["if-modified-since"] = kept.lastModified;
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* This function gives the answer that a client reads, and changes the store.
|
|
448
|
+
*
|
|
449
|
+
* - A 304 for a key with a kept answer gives the kept answer. Its headers get the fields of the
|
|
450
|
+
* 304, as RFC 9111 §4.3.4 tells, and the store keeps the new values of its kept headers.
|
|
451
|
+
* - An answer with a status of `KEPT_STATUSES` and an ETag or a date goes into the store. It needs
|
|
452
|
+
* a text type in UTF-8 and a body in the limit.
|
|
453
|
+
* - Each other answer is as it is, and the store does not change.
|
|
454
|
+
*
|
|
455
|
+
* @beta
|
|
456
|
+
*/
|
|
457
|
+
function keepAnswer(store, key, answer, options = {}) {
|
|
458
|
+
const names = new Set((options.headers ?? KEPT_HEADERS).map((name) => name.toLowerCase()));
|
|
459
|
+
const headers = lower(answer.headers);
|
|
460
|
+
const kept = store.get(key);
|
|
461
|
+
if (answer.status === 304 && kept !== void 0) {
|
|
462
|
+
const read = { ...kept.headers };
|
|
463
|
+
const keep = { ...kept.headers };
|
|
464
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
465
|
+
if (BODY_FIELDS.has(name)) continue;
|
|
466
|
+
read[name] = value;
|
|
467
|
+
if (names.has(name)) keep[name] = value;
|
|
468
|
+
}
|
|
469
|
+
store.set(key, {
|
|
470
|
+
...kept,
|
|
471
|
+
etag: headers["etag"] ?? kept.etag,
|
|
472
|
+
lastModified: headers["last-modified"] ?? kept.lastModified,
|
|
473
|
+
headers: keep
|
|
474
|
+
});
|
|
475
|
+
return {
|
|
476
|
+
status: kept.status,
|
|
477
|
+
headers: read,
|
|
478
|
+
body: kept.body,
|
|
479
|
+
notModified: true
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
const etag = headers["etag"];
|
|
483
|
+
const lastModified = headers["last-modified"];
|
|
484
|
+
if (KEPT_STATUSES.includes(answer.status) && (etag !== void 0 || lastModified !== void 0) && isTextType(headers["content-type"]) && answer.body.length <= (options.maxBody ?? 1048576)) {
|
|
485
|
+
const keep = {};
|
|
486
|
+
for (const [name, value] of Object.entries(headers)) if (names.has(name)) keep[name] = value;
|
|
487
|
+
store.set(key, {
|
|
488
|
+
etag,
|
|
489
|
+
lastModified,
|
|
490
|
+
status: answer.status,
|
|
491
|
+
headers: keep,
|
|
492
|
+
body: answer.body
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
return {
|
|
496
|
+
status: answer.status,
|
|
497
|
+
headers,
|
|
498
|
+
body: answer.body,
|
|
499
|
+
notModified: false
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* This function makes a store of kept answers in memory, with the entries of an earlier run.
|
|
504
|
+
*
|
|
505
|
+
* @beta
|
|
506
|
+
*/
|
|
507
|
+
function keptStore(entries = []) {
|
|
508
|
+
const all = new Map(entries);
|
|
509
|
+
const used = /* @__PURE__ */ new Set();
|
|
510
|
+
return {
|
|
511
|
+
get(key) {
|
|
512
|
+
const kept = all.get(key);
|
|
513
|
+
if (kept !== void 0) used.add(key);
|
|
514
|
+
return kept;
|
|
515
|
+
},
|
|
516
|
+
set(key, kept) {
|
|
517
|
+
all.set(key, kept);
|
|
518
|
+
used.add(key);
|
|
519
|
+
},
|
|
520
|
+
used: () => [...used].flatMap((key) => {
|
|
521
|
+
const kept = all.get(key);
|
|
522
|
+
return kept === void 0 ? [] : [[key, kept]];
|
|
523
|
+
})
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
/** This function gives a kept answer from data, or null when the data does not have its shape. */
|
|
527
|
+
const keptOf = (value) => {
|
|
528
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
529
|
+
const { etag, lastModified, status, headers, body } = value;
|
|
530
|
+
if (typeof status !== "number" || !KEPT_STATUSES.includes(status)) return null;
|
|
531
|
+
if (typeof body !== "string") return null;
|
|
532
|
+
if (etag !== void 0 && typeof etag !== "string") return null;
|
|
533
|
+
if (lastModified !== void 0 && typeof lastModified !== "string") return null;
|
|
534
|
+
if (etag === void 0 && lastModified === void 0) return null;
|
|
535
|
+
if (typeof headers !== "object" || headers === null || Array.isArray(headers)) return null;
|
|
536
|
+
const read = {};
|
|
537
|
+
for (const [name, field] of Object.entries(headers)) {
|
|
538
|
+
if (typeof field !== "string") return null;
|
|
539
|
+
read[name.toLowerCase()] = field;
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
etag: typeof etag === "string" ? etag : void 0,
|
|
543
|
+
lastModified: typeof lastModified === "string" ? lastModified : void 0,
|
|
544
|
+
status,
|
|
545
|
+
headers: read,
|
|
546
|
+
body
|
|
547
|
+
};
|
|
548
|
+
};
|
|
549
|
+
/**
|
|
550
|
+
* This function reads the entries of a store from data, for example from the JSON of the `used`
|
|
551
|
+
* entries of an earlier run. It keeps each entry with a correct shape and drops each other entry.
|
|
552
|
+
* Thus damaged data gives fewer kept answers and no error.
|
|
553
|
+
*
|
|
554
|
+
* @beta
|
|
555
|
+
*/
|
|
556
|
+
function readKept(data) {
|
|
557
|
+
if (!Array.isArray(data)) return [];
|
|
558
|
+
const out = [];
|
|
559
|
+
for (const entry of data) {
|
|
560
|
+
if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string") continue;
|
|
561
|
+
const kept = keptOf(entry[1]);
|
|
562
|
+
if (kept !== null) out.push([entry[0], kept]);
|
|
563
|
+
}
|
|
564
|
+
return out;
|
|
565
|
+
}
|
|
350
566
|
// src/api.ts
|
|
351
567
|
/**
|
|
352
568
|
* The polite send of a documented API. It keeps the pace of each host with the scheduler of the
|
|
@@ -359,8 +575,10 @@ function readQuotaHeaders(get, names, now) {
|
|
|
359
575
|
* The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,
|
|
360
576
|
* `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent
|
|
361
577
|
* and a time limit. `poll` sends conditional requests. `freshUntil` gives the end of the freshness
|
|
362
|
-
* of an answer (RFC 9111), so a client that keeps answers knows when to ask again.
|
|
363
|
-
*
|
|
578
|
+
* of an answer (RFC 9111), so a client that keeps answers knows when to ask again. `keptFetch` and
|
|
579
|
+
* `keepAnswer` keep the last full answer of a GET with its body, so a 304 gives the kept answer. The
|
|
580
|
+
* client decides where the store is: a store is data. Each export is beta: a minor version can
|
|
581
|
+
* change it.
|
|
364
582
|
*/
|
|
365
583
|
const unchanged = (text) => text;
|
|
366
584
|
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
@@ -627,6 +845,50 @@ function fetchTransport(options) {
|
|
|
627
845
|
}
|
|
628
846
|
};
|
|
629
847
|
}
|
|
848
|
+
/**
|
|
849
|
+
* This function makes a `fetch` with kept answers, for example for `fetchTransport`. A GET with no
|
|
850
|
+
* body and no conditional or range header of its own (`hasValidator`) sends the validators of its
|
|
851
|
+
* kept answer. The key of the answer is `keptKey`. A 304 then gives the kept answer, as
|
|
852
|
+
* `keepAnswer` tells, and a full answer with a text body in UTF-8 goes into the store. The function does not read a body
|
|
853
|
+
* of a different media type, so an exchange that reads `bytes` gets the bytes. Each other request
|
|
854
|
+
* goes to `fetch` as it is. The key does not hold the `authorization` header: the server examines
|
|
855
|
+
* the access of each request before it answers 304.
|
|
856
|
+
*
|
|
857
|
+
* @beta
|
|
858
|
+
*/
|
|
859
|
+
function keptFetch(fetch, store, options = {}) {
|
|
860
|
+
return async (url, init) => {
|
|
861
|
+
if (!(init.method.toUpperCase() === "GET" && init.body === void 0) || hasValidator(init.headers)) return fetch(url, init);
|
|
862
|
+
const key = keptKey(url, init.headers);
|
|
863
|
+
const kept = store.get(key);
|
|
864
|
+
const response = await fetch(url, {
|
|
865
|
+
...init,
|
|
866
|
+
headers: keptRequestHeaders(kept, init.headers)
|
|
867
|
+
});
|
|
868
|
+
const headers = {};
|
|
869
|
+
response.headers.forEach((value, name) => {
|
|
870
|
+
headers[name.toLowerCase()] = value;
|
|
871
|
+
});
|
|
872
|
+
const unchanged = response.status === 304 && kept !== void 0;
|
|
873
|
+
const full = KEPT_STATUSES.includes(response.status) && isTextType(headers["content-type"]);
|
|
874
|
+
if (!unchanged && !full) return response;
|
|
875
|
+
const body = response.status === 304 ? "" : await response.text();
|
|
876
|
+
const answer = keepAnswer(store, key, {
|
|
877
|
+
status: response.status,
|
|
878
|
+
headers,
|
|
879
|
+
body
|
|
880
|
+
}, options);
|
|
881
|
+
return {
|
|
882
|
+
status: answer.status,
|
|
883
|
+
statusText: answer.notModified ? "" : response.statusText,
|
|
884
|
+
headers: { forEach(callback) {
|
|
885
|
+
for (const [name, value] of Object.entries(answer.headers)) callback(value, name);
|
|
886
|
+
} },
|
|
887
|
+
text: () => Promise.resolve(answer.body),
|
|
888
|
+
arrayBuffer: () => Promise.resolve(new TextEncoder().encode(answer.body).slice().buffer)
|
|
889
|
+
};
|
|
890
|
+
};
|
|
891
|
+
}
|
|
630
892
|
const HEX = "0123456789abcdef";
|
|
631
893
|
/** This function gives the SHA-256 of a text or of bytes, in hexadecimal. */
|
|
632
894
|
const digestOf = async (body) => {
|
|
@@ -695,6 +957,6 @@ async function poll(pace, transport, conditions, input, signal) {
|
|
|
695
957
|
changed
|
|
696
958
|
};
|
|
697
959
|
}
|
|
698
|
-
export { API_TIMEOUT_MS, ApiError, QuotaError, TOKEN_MARGIN_MS, fetchTransport, freshUntil, isApiError, isQuotaError, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
|
|
960
|
+
export { API_TIMEOUT_MS, ApiError, KEPT_BODY_MAX, KEPT_HEADERS, KEPT_STATUSES, QuotaError, TOKEN_MARGIN_MS, fetchTransport, freshUntil, hasValidator, isApiError, isQuotaError, isTextType, keepAnswer, keptFetch, keptKey, keptRequestHeaders, keptStore, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readKept, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
|
|
699
961
|
|
|
700
962
|
//# sourceMappingURL=api.mjs.map
|