polite-crawler 0.6.0 → 0.6.1

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 (58) hide show
  1. package/README.md +39 -0
  2. package/build/api.d.mts +288 -0
  3. package/build/api.mjs +203 -0
  4. package/build/api.mjs.map +1 -0
  5. package/build/{browser-DCd_d0oU.mjs → browser-C_dFMvO3.mjs} +2 -2
  6. package/build/{browser-DCd_d0oU.mjs.map → browser-C_dFMvO3.mjs.map} +1 -1
  7. package/build/classify.d.mts +1 -2
  8. package/build/{cli-daemon-BTT_6ec8.mjs → cli-daemon-DRI1tL5D.mjs} +2 -2
  9. package/build/{cli-daemon-BTT_6ec8.mjs.map → cli-daemon-DRI1tL5D.mjs.map} +1 -1
  10. package/build/{cli-recipes-m_vX7Fu-.mjs → cli-recipes-B1zg7et3.mjs} +2 -2
  11. package/build/{cli-recipes-m_vX7Fu-.mjs.map → cli-recipes-B1zg7et3.mjs.map} +1 -1
  12. package/build/cli.mjs +19 -19
  13. package/build/cli.mjs.map +1 -1
  14. package/build/{daemon-CWpToMtq.mjs → daemon-l6FPe6lD.mjs} +5 -5
  15. package/build/{daemon-CWpToMtq.mjs.map → daemon-l6FPe6lD.mjs.map} +1 -1
  16. package/build/{diff-9UN0TNNe.mjs → diff-CSNW27zD.mjs} +3 -3
  17. package/build/{diff-9UN0TNNe.mjs.map → diff-CSNW27zD.mjs.map} +1 -1
  18. package/build/{extract-CW-Pzo2l.mjs → extract-Bn0ueYEx.mjs} +3 -3
  19. package/build/{extract-CW-Pzo2l.mjs.map → extract-Bn0ueYEx.mjs.map} +1 -1
  20. package/build/hours.d.mts +1 -2
  21. package/build/hours.mjs +1 -1
  22. package/build/hours.mjs.map +1 -1
  23. package/build/html-oS_ueu9U.d.mts +1 -2
  24. package/build/index.d.mts +2 -3
  25. package/build/index.mjs +14 -14
  26. package/build/log-CB5bADmd.mjs.map +1 -1
  27. package/build/{ollama-BDZjLDOK.mjs → ollama-B7eNmGhl.mjs} +2 -2
  28. package/build/{ollama-BDZjLDOK.mjs.map → ollama-B7eNmGhl.mjs.map} +1 -1
  29. package/build/{open-D-PoX1Lt.mjs → open-Cq2hknsi.mjs} +11 -11
  30. package/build/{open-D-PoX1Lt.mjs.map → open-Cq2hknsi.mjs.map} +1 -1
  31. package/build/politeness.d.mts +1 -2
  32. package/build/politeness.mjs.map +1 -1
  33. package/build/reaction-BWTIe95J.mjs +82 -0
  34. package/build/reaction-BWTIe95J.mjs.map +1 -0
  35. package/build/{recipe-CJrxYoRL.mjs → recipe-Bcp8MCvO.mjs} +3 -3
  36. package/build/{recipe-CJrxYoRL.mjs.map → recipe-Bcp8MCvO.mjs.map} +1 -1
  37. package/build/{recipe-product-DbuYUSYG.mjs → recipe-product-DE-yzyXS.mjs} +4 -4
  38. package/build/{recipe-product-DbuYUSYG.mjs.map → recipe-product-DE-yzyXS.mjs.map} +1 -1
  39. package/build/render-B0NrFDkJ.mjs.map +1 -1
  40. package/build/robots.d.mts +1 -2
  41. package/build/rolldown-runtime-D3KUYPsf.mjs +12 -0
  42. package/build/{runtime-jYXBNvyC.mjs → runtime-Cn_acsHC.mjs} +30 -46
  43. package/build/runtime-Cn_acsHC.mjs.map +1 -0
  44. package/build/signals.d.mts +1 -2
  45. package/build/{transformers-C_ziG8yf.mjs → transformers-Cb-KaPge.mjs} +2 -2
  46. package/build/{transformers-C_ziG8yf.mjs.map → transformers-Cb-KaPge.mjs.map} +1 -1
  47. package/build/urls.d.mts +1 -2
  48. package/build/{version-D6jptm-z.mjs → version-BwsBOkFU.mjs} +2 -2
  49. package/build/{version-D6jptm-z.mjs.map → version-BwsBOkFU.mjs.map} +1 -1
  50. package/build/{wacz-e3aVS4rN.mjs → wacz-BkeG0_Pn.mjs} +4 -4
  51. package/build/{wacz-e3aVS4rN.mjs.map → wacz-BkeG0_Pn.mjs.map} +1 -1
  52. package/build/{warc-Cn9IXXKK.mjs → warc-BPYg_Nzp.mjs} +3 -3
  53. package/build/{warc-Cn9IXXKK.mjs.map → warc-BPYg_Nzp.mjs.map} +1 -1
  54. package/build/{webbotauth-W3GXY3dy.mjs → webbotauth-DbiWmibz.mjs} +2 -2
  55. package/build/{webbotauth-W3GXY3dy.mjs.map → webbotauth-DbiWmibz.mjs.map} +1 -1
  56. package/package.json +5 -1
  57. package/build/rolldown-runtime-BJohB4LM.mjs +0 -13
  58. package/build/runtime-jYXBNvyC.mjs.map +0 -1
package/README.md CHANGED
@@ -49,6 +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
53
 
53
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`.
54
55
 
@@ -295,6 +296,8 @@ The engine of the recipes is `registerRecipe`, `rankHoursLinks`, `namesVenue`, `
295
296
 
296
297
  The engine of the archived fallback and of the signatures is `archiveExtractor`, `archivedDocId`, and the `fallback` and `archiveDespiteRobots` of `PageOptions`. It also includes `range`, `signalLines` and `originalHeaderPrefix` of `FetchRequest`, `ai_input` of `ExtractedDoc`, `sign` of `RenderOptions` and `signer` of `CrawlerOptions`.
297
298
 
299
+ Each export of `polite-crawler/api` is the engine too. This includes the reaction of the crawler: `outcomeResult` and `reactToOutcome`, with `OutcomeFacts`, `ReactionContext` and `HostReaction`.
300
+
298
301
  Version 0.2.0 removed five exports from the root entry point: `checkedRenderer`, `renderedKey`, `pageDocId`, `renderAndIndex` and `pageExtractor`. No documented use needed them. `durationMs` stays in the engine, because `polite-crawler-mcp` uses it.
299
302
 
300
303
  ## Hybrid search
@@ -1248,6 +1251,42 @@ User-agent: PoliteCrawler
1248
1251
  Disallow: /
1249
1252
  ```
1250
1253
 
1254
+ ## Send to a documented API
1255
+
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
+
1258
+ ```ts
1259
+ import { send, type Transport } from "polite-crawler/api";
1260
+ import { HostScheduler, realClock } from "polite-crawler/politeness";
1261
+
1262
+ const scheduler = new HostScheduler(realClock, 4);
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
+ };
1274
+
1275
+ const answer = await send(pace, transport, {
1276
+ source: "Example API",
1277
+ host: "api.example.com",
1278
+ minIntervalMs: 500,
1279
+ what: "the product P-1",
1280
+ exchange: { method: "GET", url: "https://api.example.com/products/P-1", headers: {}, body: null },
1281
+ });
1282
+ ```
1283
+
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.
1285
+ - **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
+ - **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
+ - **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
+ - **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
+
1251
1290
  ## Stored copies and conditional requests
1252
1291
 
1253
1292
  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.
@@ -0,0 +1,288 @@
1
+ /**
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.
8
+ *
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.
11
+ */
12
+ import { Classified, Outcome } from "./classify.mjs";
13
+ import { HostCounts, HostResult, HostStateStore, HostStop, Paced, PolicyOptions, PolitenessPolicy, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict } from "./politeness.mjs";
14
+ /**
15
+ * These are the facts of one answer that set the reaction of its host. `classify` gives the
16
+ * outcome and the wait that the server asked for.
17
+ *
18
+ * @beta
19
+ */
20
+ interface OutcomeFacts {
21
+ /** This value is the outcome of the answer. */
22
+ readonly outcome: Outcome;
23
+ /** This value is the status of the answer. The value 0 is a request with no answer. */
24
+ readonly status: number;
25
+ /** This value is the wait that the server asked for (`Retry-After`). */
26
+ readonly retryAfterMs?: number | undefined;
27
+ /**
28
+ * A refusal (`blocked`) with one of these statuses does not stop the host. The crawler spares
29
+ * 401 and 403 for robots.txt (RFC 9309). An API client spares a 401 before it gets a new token.
30
+ */
31
+ readonly spare?: readonly number[] | undefined;
32
+ /** This result replaces the result of the outcome, and the host gets only its rest. A cancelled request is `neutral`. */
33
+ readonly result?: HostResult | undefined;
34
+ }
35
+ /**
36
+ * These values set the reaction to one answer.
37
+ *
38
+ * @beta
39
+ */
40
+ interface ReactionContext {
41
+ /** This value is the policy of the host. */
42
+ readonly policy: PolitenessPolicy;
43
+ /** This value is the time of the answer, in milliseconds since the epoch. */
44
+ readonly now: number;
45
+ /** This value is the rest of the host that `restAfter` gives for the request. */
46
+ readonly restMs: number;
47
+ /** This function gives a number in [0, 1) for the jitter of a backoff. */
48
+ readonly random: () => number;
49
+ }
50
+ /**
51
+ * This value tells how one answer changes its host, after its counts changed.
52
+ *
53
+ * @beta
54
+ */
55
+ interface HostReaction {
56
+ /** This value is the rest of the host before its next request, in milliseconds. */
57
+ readonly restMs: number;
58
+ /**
59
+ * This value tells why the rest is longer than the rest of `restAfter`: a backoff, or the
60
+ * `Retry-After` of the server. A longer rest parks the host.
61
+ */
62
+ readonly longer: "backoff" | "retry-after" | undefined;
63
+ /** This value is the stop of the host, when the answer stops it. */
64
+ readonly stop: HostStop | undefined;
65
+ }
66
+ /**
67
+ * This function tells how one answer changes the counts of its host. Give the result to
68
+ * `HostStateStore.record`. These are the rules:
69
+ *
70
+ * - A 429, 502, 503 or 504 is a wait.
71
+ * - A different error and a request with no answer are failures. A client error (`isClientError`) is neutral.
72
+ * - Each other outcome is a success. A refusal is a success too, because its stop is the reaction.
73
+ *
74
+ * @beta
75
+ */
76
+ export declare const outcomeResult: (facts: OutcomeFacts) => HostResult;
77
+ /**
78
+ * This function gives the reaction of a host to one answer, with the counts that `record` gave for
79
+ * the result of `outcomeResult`. The `Crawler` and the send of `polite-crawler/api` use it. These
80
+ * are the rules, with the times of the policy:
81
+ *
82
+ * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter. A
83
+ * `Retry-After` longer than `maxRetryAfterMs` stops the host for that time, up to 30 days.
84
+ * - A failure parks the host for a backoff with jitter. After `maxFailures` failures in sequence, the host also stops.
85
+ * - A 401 or a 403 stops the host for `blockedStopMs`. A 402 and a bot challenge stop it longer.
86
+ * - Each other answer gives the rest of `restAfter`.
87
+ *
88
+ * The function is pure, so a simulation and a study can use the reactions of the crawler.
89
+ *
90
+ * @beta
91
+ */
92
+ export declare const reactToOutcome: (facts: OutcomeFacts, counts: HostCounts, context: ReactionContext) => HostReaction;
93
+ /**
94
+ * One request of a client to an API.
95
+ *
96
+ * @beta
97
+ */
98
+ export interface Exchange {
99
+ /** This value is the method of the request, for example `GET` or `POST`. */
100
+ readonly method: string;
101
+ readonly url: string;
102
+ /** These are the headers of the request. Each name is in lowercase. */
103
+ readonly headers: Readonly<Record<string, string>>;
104
+ /** This value is the body of the request, or null. */
105
+ readonly body: string | null;
106
+ }
107
+ /**
108
+ * The answer of an API to one exchange.
109
+ *
110
+ * @beta
111
+ */
112
+ export interface Reply {
113
+ readonly status: number;
114
+ /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */
115
+ readonly statusText: string;
116
+ /** These are the headers of the answer. Each name is in lowercase. */
117
+ readonly headers: Readonly<Record<string, string>>;
118
+ readonly body: string;
119
+ }
120
+ /**
121
+ * The part of a signal that the send reads. An `AbortSignal` has it.
122
+ *
123
+ * @beta
124
+ */
125
+ export interface Signal {
126
+ readonly aborted: boolean;
127
+ }
128
+ /**
129
+ * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an
130
+ * error when the API gives no answer, and when the signal stops the request.
131
+ *
132
+ * @beta
133
+ */
134
+ export type Transport<S extends Signal = AbortSignal> = (exchange: Exchange, signal: S | undefined) => Promise<Reply>;
135
+ /**
136
+ * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.
137
+ *
138
+ * @beta
139
+ */
140
+ export interface ApiScheduler<S extends Signal = AbortSignal> {
141
+ 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">;
144
+ }
145
+ /**
146
+ * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.
147
+ *
148
+ * @beta
149
+ */
150
+ export interface Pace<S extends Signal = AbortSignal> {
151
+ /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */
152
+ readonly scheduler: ApiScheduler<S>;
153
+ /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */
154
+ readonly now: () => number;
155
+ /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */
156
+ readonly policy?: PolicyOptions | undefined;
157
+ /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */
158
+ readonly random?: (() => number) | undefined;
159
+ }
160
+ /**
161
+ * This function removes each secret from the text of an error. `secrets` holds the secrets of the
162
+ * exchange: its keys and its token.
163
+ *
164
+ * @beta
165
+ */
166
+ 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
+ /**
176
+ * One exchange of a client, and its context for the pace and the messages.
177
+ *
178
+ * @beta
179
+ */
180
+ export interface Send {
181
+ /** This value is the name of the API in a message, for example `Example API`. */
182
+ readonly source: string;
183
+ /** This value is the host of the URL. The scheduler keeps one pace for each host. */
184
+ readonly host: string;
185
+ /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */
186
+ readonly minIntervalMs?: number | undefined;
187
+ /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */
188
+ readonly what: string;
189
+ readonly exchange: Exchange;
190
+ /** These are the secrets of the exchange. The send gives them to `redact`. */
191
+ readonly secrets?: readonly string[] | undefined;
192
+ /**
193
+ * This function removes the secrets from the text of each error. The default changes nothing.
194
+ * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.
195
+ */
196
+ readonly redact?: Redact | undefined;
197
+ /** With true, a 401 does not stop the host. The client then gets a new token one time. */
198
+ readonly tokenRetry?: boolean | undefined;
199
+ }
200
+ /**
201
+ * An answer, and what it means for the host.
202
+ *
203
+ * @beta
204
+ */
205
+ export interface Answer {
206
+ readonly reply: Reply;
207
+ readonly classified: Classified;
208
+ }
209
+ /**
210
+ * This function gives the status line of an answer for a message, with no control character.
211
+ *
212
+ * @beta
213
+ */
214
+ export declare function statusLine(reply: Reply): string;
215
+ /**
216
+ * This function sends one exchange at the pace of its host. The scheduler waits the rest of the
217
+ * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for
218
+ * the `Crawler`:
219
+ *
220
+ * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.
221
+ * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.
222
+ * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.
223
+ *
224
+ * The function gives each answer, with each status. The caller reads the status.
225
+ *
226
+ * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.
227
+ * @throws the reason of the signal, when the signal stops the exchange.
228
+ * @beta
229
+ */
230
+ export declare function send<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, input: Send, signal?: S): Promise<Answer>;
231
+ /**
232
+ * The token of a client credentials grant, and the time when the client stops its use.
233
+ *
234
+ * @beta
235
+ */
236
+ export interface Grant {
237
+ readonly token: string;
238
+ /** The client uses the token before this time, in milliseconds since the epoch. */
239
+ readonly until: number;
240
+ }
241
+ /**
242
+ * A client stops the use of a token this time before its end.
243
+ *
244
+ * @beta
245
+ */
246
+ export declare const TOKEN_MARGIN_MS: number;
247
+ /**
248
+ * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant
249
+ * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or
250
+ * for half of a short life.
251
+ *
252
+ * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The
253
+ * message has no part of the body, and `redact` examined it.
254
+ * @beta
255
+ */
256
+ export declare function readGrant(reply: Reply, source: string, issuedAt: number, secrets?: readonly string[], redact?: Redact): Grant;
257
+ /**
258
+ * A store of one token. The exchanges that wait for a token at one time share one grant.
259
+ *
260
+ * @beta
261
+ */
262
+ export interface Tokens<S extends Signal = AbortSignal> {
263
+ /** This method gives a token that the client can use. With no such token, it gets a new token. */
264
+ get(signal?: S): Promise<string>;
265
+ /**
266
+ * This method forgets the token after an answer 401. With a token, it forgets only that token,
267
+ * so a second 401 of an old token does not drop a newer token.
268
+ */
269
+ drop(token?: string): void;
270
+ }
271
+ /**
272
+ * This function makes a store of one token. The store gets a new token from `grant` when the token
273
+ * ends. `now` gives the time in milliseconds since the epoch.
274
+ *
275
+ * @beta
276
+ */
277
+ export declare function tokenStore<S extends Signal = AbortSignal>(grant: (signal: S | undefined) => Promise<Grant>, now: () => number): Tokens<S>;
278
+ /**
279
+ * This function sends an exchange with a token. `headers` gives the headers of the token, for
280
+ * example `authorization`. After an answer 401, the function forgets the token, gets a new token,
281
+ * and sends the exchange one more time. A second 401 stops the host. The token goes into the
282
+ * secrets of the messages.
283
+ *
284
+ * @throws ApiError as `send` does, and the error of the grant.
285
+ * @beta
286
+ */
287
+ 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 };
package/build/api.mjs ADDED
@@ -0,0 +1,203 @@
1
+ import { classify } from "./classify.mjs";
2
+ import { policyFor, restAfter } from "./politeness.mjs";
3
+ import { n as reactToOutcome, t as outcomeResult } from "./reaction-BWTIe95J.mjs";
4
+ // src/api.ts
5
+ /**
6
+ * An error of the send or of the token. The `redact` function of the send examined its message.
7
+ *
8
+ * @beta
9
+ */
10
+ var ApiError = class extends Error {
11
+ name = "ApiError";
12
+ };
13
+ const unchanged = (text) => text;
14
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
15
+ /**
16
+ * This function gives the status line of an answer for a message, with no control character.
17
+ *
18
+ * @beta
19
+ */
20
+ function statusLine(reply) {
21
+ const reason = reply.statusText.replace(/\p{Cc}/gu, " ").trim().slice(0, 80);
22
+ return reason === "" ? String(reply.status) : `${String(reply.status)} ${reason}`;
23
+ }
24
+ /**
25
+ * This function sends one exchange at the pace of its host. The scheduler waits the rest of the
26
+ * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for
27
+ * the `Crawler`:
28
+ *
29
+ * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.
30
+ * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.
31
+ * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.
32
+ *
33
+ * The function gives each answer, with each status. The caller reads the status.
34
+ *
35
+ * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.
36
+ * @throws the reason of the signal, when the signal stops the exchange.
37
+ * @beta
38
+ */
39
+ async function send(pace, transport, input, signal) {
40
+ const { scheduler } = pace;
41
+ const { host } = input;
42
+ const policy = policyFor(pace.policy, host);
43
+ const random = pace.random ?? Math.random;
44
+ const redact = (text) => (input.redact ?? unchanged)(text, input.secrets ?? []);
45
+ const spare = input.tokenRetry === true ? [401] : void 0;
46
+ const settle = (facts, elapsedMs) => {
47
+ const now = pace.now();
48
+ const restMs = restAfter(policy, {
49
+ kind: "api",
50
+ elapsedMs,
51
+ minIntervalMs: input.minIntervalMs
52
+ }).ms;
53
+ const counts = scheduler.store.record(host, outcomeResult(facts));
54
+ const reaction = reactToOutcome(facts, counts, {
55
+ policy,
56
+ now,
57
+ restMs,
58
+ random
59
+ });
60
+ if (reaction.stop !== void 0) scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);
61
+ return reaction.restMs;
62
+ };
63
+ let attempt;
64
+ try {
65
+ attempt = await scheduler.run(host, async () => {
66
+ const started = pace.now();
67
+ let reply;
68
+ try {
69
+ reply = await transport(input.exchange, signal);
70
+ } catch (error) {
71
+ const facts = {
72
+ outcome: "error",
73
+ status: 0,
74
+ ...signal?.aborted === true ? { result: "neutral" } : {}
75
+ };
76
+ return {
77
+ value: { error },
78
+ delayMs: settle(facts, pace.now() - started)
79
+ };
80
+ }
81
+ const classified = classify(reply.status, (name) => reply.headers[name.toLowerCase()], pace.now());
82
+ const facts = {
83
+ outcome: classified.outcome,
84
+ status: reply.status,
85
+ retryAfterMs: classified.retryAfterMs,
86
+ spare
87
+ };
88
+ return {
89
+ value: {
90
+ reply,
91
+ classified
92
+ },
93
+ delayMs: settle(facts, pace.now() - started)
94
+ };
95
+ }, signal);
96
+ } catch (error) {
97
+ if (signal?.aborted === true) throw error;
98
+ throw new ApiError(redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`));
99
+ }
100
+ if ("error" in attempt) {
101
+ if (signal?.aborted === true) throw attempt.error;
102
+ throw new ApiError(redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`));
103
+ }
104
+ return attempt;
105
+ }
106
+ /**
107
+ * A client stops the use of a token this time before its end.
108
+ *
109
+ * @beta
110
+ */
111
+ const TOKEN_MARGIN_MS = 6e4;
112
+ /** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */
113
+ const TOKEN = /^[!-~]{8,4096}$/;
114
+ const fieldOf = (value, key) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key) ? value[key] : void 0;
115
+ /**
116
+ * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant
117
+ * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or
118
+ * for half of a short life.
119
+ *
120
+ * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The
121
+ * message has no part of the body, and `redact` examined it.
122
+ * @beta
123
+ */
124
+ function readGrant(reply, source, issuedAt, secrets = [], redact = unchanged) {
125
+ if (reply.status < 200 || reply.status > 299) throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));
126
+ let body;
127
+ try {
128
+ body = JSON.parse(reply.body);
129
+ } catch {
130
+ throw new ApiError(`The token answer of ${source} is not JSON.`);
131
+ }
132
+ const token = fieldOf(body, "access_token");
133
+ const expiresIn = fieldOf(body, "expires_in");
134
+ if (typeof token !== "string" || !TOKEN.test(token)) throw new ApiError(`The token answer of ${source} has no valid access_token.`);
135
+ if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) throw new ApiError(`The token answer of ${source} has no valid expires_in.`);
136
+ const lifeMs = expiresIn * 1e3;
137
+ return {
138
+ token,
139
+ until: issuedAt + (lifeMs > 12e4 ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2)
140
+ };
141
+ }
142
+ /**
143
+ * This function makes a store of one token. The store gets a new token from `grant` when the token
144
+ * ends. `now` gives the time in milliseconds since the epoch.
145
+ *
146
+ * @beta
147
+ */
148
+ function tokenStore(grant, now) {
149
+ let held;
150
+ let pending;
151
+ return {
152
+ async get(signal) {
153
+ if (held !== void 0 && now() < held.until) return held.token;
154
+ pending ??= grant(signal).finally(() => {
155
+ pending = void 0;
156
+ });
157
+ const next = await pending;
158
+ held = next;
159
+ return next.token;
160
+ },
161
+ drop(token) {
162
+ if (token === void 0 || held?.token === token) held = void 0;
163
+ }
164
+ };
165
+ }
166
+ /**
167
+ * This function sends an exchange with a token. `headers` gives the headers of the token, for
168
+ * example `authorization`. After an answer 401, the function forgets the token, gets a new token,
169
+ * and sends the exchange one more time. A second 401 stops the host. The token goes into the
170
+ * secrets of the messages.
171
+ *
172
+ * @throws ApiError as `send` does, and the error of the grant.
173
+ * @beta
174
+ */
175
+ async function sendWithToken(pace, transport, tokens, input, headers, signal) {
176
+ const once = async (tokenRetry) => {
177
+ const token = await tokens.get(signal);
178
+ const exchange = {
179
+ ...input.exchange,
180
+ headers: {
181
+ ...input.exchange.headers,
182
+ ...headers(token)
183
+ }
184
+ };
185
+ const secrets = [...input.secrets ?? [], token];
186
+ return {
187
+ answer: await send(pace, transport, {
188
+ ...input,
189
+ exchange,
190
+ secrets,
191
+ tokenRetry
192
+ }, signal),
193
+ token
194
+ };
195
+ };
196
+ const first = await once(true);
197
+ if (first.answer.reply.status !== 401) return first.answer;
198
+ tokens.drop(first.token);
199
+ return (await once(false)).answer;
200
+ }
201
+ export { ApiError, TOKEN_MARGIN_MS, outcomeResult, reactToOutcome, readGrant, send, sendWithToken, statusLine, tokenStore };
202
+
203
+ //# sourceMappingURL=api.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["/**\n * The polite send of a documented API. It keeps the pace of each host with the scheduler of the\n * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each\n * answer. The send stores no page, because the terms of some APIs forbid a store.\n *\n * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.\n * The module imports no Node.js module, and it uses no type of a platform except the signal.\n *\n * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,\n * `tokenStore` and `sendWithToken`. Each export is beta: a minor version can change it.\n */\nimport type { Classified } from \"./classify.ts\";\nimport { classify } from \"./classify.ts\";\nimport type { HostStateStore, Paced, PolicyOptions } from \"./politeness.ts\";\nimport { policyFor, restAfter } from \"./politeness.ts\";\nimport type { OutcomeFacts } from \"./reaction.ts\";\nimport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\n\n/**\n * One request of a client to an API.\n *\n * @beta\n */\nexport interface Exchange {\n /** This value is the method of the request, for example `GET` or `POST`. */\n readonly method: string;\n readonly url: string;\n /** These are the headers of the request. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the request, or null. */\n readonly body: string | null;\n}\n\n/**\n * The answer of an API to one exchange.\n *\n * @beta\n */\nexport interface Reply {\n readonly status: number;\n /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */\n readonly statusText: string;\n /** These are the headers of the answer. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\n/**\n * The part of a signal that the send reads. An `AbortSignal` has it.\n *\n * @beta\n */\nexport interface Signal {\n readonly aborted: boolean;\n}\n\n/**\n * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an\n * error when the API gives no answer, and when the signal stops the request.\n *\n * @beta\n */\nexport type Transport<S extends Signal = AbortSignal> = (\n exchange: Exchange,\n signal: S | undefined,\n) => Promise<Reply>;\n\n/**\n * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.\n *\n * @beta\n */\nexport interface ApiScheduler<S extends Signal = AbortSignal> {\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;\n /** This store keeps the counts and the stops of each host. */\n readonly store: Pick<HostStateStore, \"record\" | \"stop\">;\n}\n\n/**\n * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.\n *\n * @beta\n */\nexport interface Pace<S extends Signal = AbortSignal> {\n /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */\n readonly scheduler: ApiScheduler<S>;\n /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */\n readonly now: () => number;\n /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */\n readonly policy?: PolicyOptions | undefined;\n /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * This function removes each secret from the text of an error. `secrets` holds the secrets of the\n * exchange: its keys and its token.\n *\n * @beta\n */\nexport type Redact = (text: string, secrets: readonly string[]) => string;\n\n/**\n * An error of the send or of the token. The `redact` function of the send examined its message.\n *\n * @beta\n */\nexport class ApiError extends Error {\n override readonly name: string = \"ApiError\";\n}\n\n/**\n * One exchange of a client, and its context for the pace and the messages.\n *\n * @beta\n */\nexport interface Send {\n /** This value is the name of the API in a message, for example `Example API`. */\n readonly source: string;\n /** This value is the host of the URL. The scheduler keeps one pace for each host. */\n readonly host: string;\n /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */\n readonly minIntervalMs?: number | undefined;\n /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */\n readonly what: string;\n readonly exchange: Exchange;\n /** These are the secrets of the exchange. The send gives them to `redact`. */\n readonly secrets?: readonly string[] | undefined;\n /**\n * This function removes the secrets from the text of each error. The default changes nothing.\n * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.\n */\n readonly redact?: Redact | undefined;\n /** With true, a 401 does not stop the host. The client then gets a new token one time. */\n readonly tokenRetry?: boolean | undefined;\n}\n\n/**\n * An answer, and what it means for the host.\n *\n * @beta\n */\nexport interface Answer {\n readonly reply: Reply;\n readonly classified: Classified;\n}\n\nconst unchanged: Redact = (text) => text;\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function gives the status line of an answer for a message, with no control character.\n *\n * @beta\n */\nexport function statusLine(reply: Reply): string {\n const reason = reply.statusText\n .replace(/\\p{Cc}/gu, \" \")\n .trim()\n .slice(0, 80);\n return reason === \"\" ? String(reply.status) : `${String(reply.status)} ${reason}`;\n}\n\n/**\n * This function sends one exchange at the pace of its host. The scheduler waits the rest of the\n * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for\n * the `Crawler`:\n *\n * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.\n * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.\n * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.\n *\n * The function gives each answer, with each status. The caller reads the status.\n *\n * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function send<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n input: Send,\n signal?: S,\n): Promise<Answer> {\n const { scheduler } = pace;\n const { host } = input;\n const policy = policyFor(pace.policy, host);\n const random = pace.random ?? Math.random;\n const redact = (text: string): string => (input.redact ?? unchanged)(text, input.secrets ?? []);\n const spare = input.tokenRetry === true ? [401] : undefined;\n // the reaction of the host, inside the slot of the request, as the crawler does it\n const settle = (facts: OutcomeFacts, elapsedMs: number): number => {\n const now = pace.now();\n const restMs = restAfter(policy, {\n kind: \"api\",\n elapsedMs,\n minIntervalMs: input.minIntervalMs,\n }).ms;\n const counts = scheduler.store.record(host, outcomeResult(facts));\n const reaction = reactToOutcome(facts, counts, { policy, now, restMs, random });\n if (reaction.stop !== undefined)\n scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);\n return reaction.restMs;\n };\n let attempt: Answer | { readonly error: unknown };\n try {\n attempt = await scheduler.run<Answer | { readonly error: unknown }>(\n host,\n async () => {\n const started = pace.now();\n let reply: Reply;\n try {\n reply = await transport(input.exchange, signal);\n } catch (error) {\n // a request that the caller stopped is no fault of the host\n const cancelled = signal?.aborted === true;\n const facts: OutcomeFacts = {\n outcome: \"error\",\n status: 0,\n ...(cancelled ? { result: \"neutral\" as const } : {}),\n };\n return { value: { error }, delayMs: settle(facts, pace.now() - started) };\n }\n const classified = classify(\n reply.status,\n (name) => reply.headers[name.toLowerCase()],\n pace.now(),\n );\n const facts: OutcomeFacts = {\n outcome: classified.outcome,\n status: reply.status,\n retryAfterMs: classified.retryAfterMs,\n spare,\n };\n return { value: { reply, classified }, delayMs: settle(facts, pace.now() - started) };\n },\n signal,\n );\n } catch (error) {\n if (signal?.aborted === true) throw error;\n throw new ApiError(\n redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`),\n );\n }\n if (\"error\" in attempt) {\n if (signal?.aborted === true) throw attempt.error;\n throw new ApiError(\n redact(`${input.source} gave no answer to ${input.what}: ${messageOf(attempt.error)}`),\n );\n }\n return attempt;\n}\n\n/**\n * The token of a client credentials grant, and the time when the client stops its use.\n *\n * @beta\n */\nexport interface Grant {\n readonly token: string;\n /** The client uses the token before this time, in milliseconds since the epoch. */\n readonly until: number;\n}\n\n/**\n * A client stops the use of a token this time before its end.\n *\n * @beta\n */\nexport const TOKEN_MARGIN_MS: number = 60_000;\n\n/** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */\nconst TOKEN = /^[!-~]{8,4096}$/;\n\nconst fieldOf = (value: unknown, key: string): unknown =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)\n ? (value as Record<string, unknown>)[key]\n : undefined;\n\n/**\n * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant\n * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or\n * for half of a short life.\n *\n * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The\n * message has no part of the body, and `redact` examined it.\n * @beta\n */\nexport function readGrant(\n reply: Reply,\n source: string,\n issuedAt: number,\n secrets: readonly string[] = [],\n redact: Redact = unchanged,\n): Grant {\n if (reply.status < 200 || reply.status > 299) {\n throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));\n }\n let body: unknown;\n try {\n body = JSON.parse(reply.body);\n } catch {\n throw new ApiError(`The token answer of ${source} is not JSON.`);\n }\n const token = fieldOf(body, \"access_token\");\n const expiresIn = fieldOf(body, \"expires_in\");\n if (typeof token !== \"string\" || !TOKEN.test(token)) {\n throw new ApiError(`The token answer of ${source} has no valid access_token.`);\n }\n if (typeof expiresIn !== \"number\" || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new ApiError(`The token answer of ${source} has no valid expires_in.`);\n }\n const lifeMs = expiresIn * 1000;\n return {\n token,\n until: issuedAt + (lifeMs > 2 * TOKEN_MARGIN_MS ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2),\n };\n}\n\n/**\n * A store of one token. The exchanges that wait for a token at one time share one grant.\n *\n * @beta\n */\nexport interface Tokens<S extends Signal = AbortSignal> {\n /** This method gives a token that the client can use. With no such token, it gets a new token. */\n get(signal?: S): Promise<string>;\n /**\n * This method forgets the token after an answer 401. With a token, it forgets only that token,\n * so a second 401 of an old token does not drop a newer token.\n */\n drop(token?: string): void;\n}\n\n/**\n * This function makes a store of one token. The store gets a new token from `grant` when the token\n * ends. `now` gives the time in milliseconds since the epoch.\n *\n * @beta\n */\nexport function tokenStore<S extends Signal = AbortSignal>(\n grant: (signal: S | undefined) => Promise<Grant>,\n now: () => number,\n): Tokens<S> {\n let held: Grant | undefined;\n let pending: Promise<Grant> | undefined;\n return {\n async get(signal) {\n if (held !== undefined && now() < held.until) return held.token;\n pending ??= grant(signal).finally(() => {\n pending = undefined;\n });\n const next = await pending;\n held = next;\n return next.token;\n },\n drop(token) {\n if (token === undefined || held?.token === token) held = undefined;\n },\n };\n}\n\n/**\n * This function sends an exchange with a token. `headers` gives the headers of the token, for\n * example `authorization`. After an answer 401, the function forgets the token, gets a new token,\n * and sends the exchange one more time. A second 401 stops the host. The token goes into the\n * secrets of the messages.\n *\n * @throws ApiError as `send` does, and the error of the grant.\n * @beta\n */\nexport async function sendWithToken<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n tokens: Tokens<S>,\n input: Send,\n headers: (token: string) => Readonly<Record<string, string>>,\n signal?: S,\n): Promise<Answer> {\n const once = async (tokenRetry: boolean): Promise<{ answer: Answer; token: string }> => {\n const token = await tokens.get(signal);\n const exchange = {\n ...input.exchange,\n headers: { ...input.exchange.headers, ...headers(token) },\n };\n const secrets = [...(input.secrets ?? []), token];\n const answer = await send(pace, transport, { ...input, exchange, secrets, tokenRetry }, signal);\n return { answer, token };\n };\n const first = await once(true);\n if (first.answer.reply.status !== 401) return first.answer;\n tokens.drop(first.token);\n return (await once(false)).answer;\n}\n"],"mappings":"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"}
@@ -1,4 +1,4 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
2
  import { n as RenderRefused, t as NO_PLAYWRIGHT } from "./render-B0NrFDkJ.mjs";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { existsSync } from "node:fs";
@@ -58,4 +58,4 @@ const checkedRenderer = (renderer, check = () => browserMissing()) => {
58
58
  };
59
59
  export { browser_exports as n, checkedRenderer as r, browserMissing as t };
60
60
 
61
- //# sourceMappingURL=browser-DCd_d0oU.mjs.map
61
+ //# sourceMappingURL=browser-C_dFMvO3.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser-DCd_d0oU.mjs","names":[],"sources":["../src/browser.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { Renderer } from \"./render.ts\";\nimport { NO_PLAYWRIGHT, RenderRefused } from \"./render.ts\";\n\n/** The text of the note when `playwright-core` is installed, but its browser is not. */\nexport const NO_BROWSER =\n \"rendering needs a browser: npx playwright-core install chromium-headless-shell\";\n\n/** This is the part of `playwright-core` that the check uses. */\ninterface Chromium {\n executablePath(): string;\n}\n\n/**\n * This function tells if the default renderer can start a browser. It gives no value when it can,\n * and the reason when it cannot. The command line and the MCP server use it one time at start.\n * Then a missing browser costs no wait and no error capture for each page that needs JavaScript.\n *\n * The check does not start the browser. It finds the full Chromium build or the headless shell of\n * the same revision on the disk. When the check cannot find the answer, it gives no value, and the\n * renderer then tries.\n *\n * @beta\n */\nexport const browserMissing = async (\n load: () => Promise<{ readonly chromium: { executablePath(): string } }> = () =>\n import(\"playwright-core\"),\n): Promise<string | undefined> => {\n let chromium: Chromium;\n try {\n ({ chromium } = await load());\n } catch {\n return NO_PLAYWRIGHT;\n }\n try {\n const executable = chromium.executablePath();\n if (existsSync(executable)) return undefined;\n // the headless shell is in a folder next to the folder of the full build, with the same revision\n let folder = dirname(executable);\n while (dirname(folder) !== folder && !/^chromium-\\d+$/.test(basename(folder)))\n folder = dirname(folder);\n const revision = /^chromium-(\\d+)$/.exec(basename(folder))?.[1];\n if (revision === undefined) return undefined;\n return existsSync(join(dirname(folder), `chromium_headless_shell-${revision}`))\n ? undefined\n : NO_BROWSER;\n } catch {\n return undefined;\n }\n};\n\n/**\n * This function gives a renderer that checks one time, before its first page, that the browser is\n * on the disk (`browserMissing`). With no browser, each page gets a `RenderRefused` with the reason\n * `browser` at once, and the renderer opens nothing. `createRuntime` puts its default renderer in\n * it, so a library with no browser costs no wait and no error capture.\n *\n * This export is internal: the root entry point does not have it since 0.2.0.\n */\nexport const checkedRenderer = (\n renderer: Renderer,\n check: () => Promise<string | undefined> = () => browserMissing(),\n): Renderer => {\n let missing: Promise<string | undefined> | undefined;\n return {\n async render(url, options) {\n missing ??= check().catch(() => undefined);\n const reason = await missing;\n if (reason !== undefined) throw new RenderRefused(\"browser\", reason);\n return renderer.render(url, options);\n },\n close: () => renderer.close(),\n };\n};\n"],"mappings":";;;;;;;AAMA,MAAa,aACX;;;;;;;;;;;;AAkBF,MAAa,iBAAiB,OAC5B,aACE,OAAO,uBACuB;CAChC,IAAI;CACJ,IAAI;EACF,CAAC,CAAE,YAAa,MAAM,KAAK;CAC7B,QAAQ;EACN,OAAO;CACT;CACA,IAAI;EACF,MAAM,aAAa,SAAS,eAAe;EAC3C,IAAI,WAAW,UAAU,GAAG,OAAO,KAAA;EAEnC,IAAI,SAAS,QAAQ,UAAU;EAC/B,OAAO,QAAQ,MAAM,MAAM,UAAU,CAAC,iBAAiB,KAAK,SAAS,MAAM,CAAC,GAC1E,SAAS,QAAQ,MAAM;EACzB,MAAM,WAAW,mBAAmB,KAAK,SAAS,MAAM,CAAC,CAAC,GAAG;EAC7D,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO,WAAW,KAAK,QAAQ,MAAM,GAAG,2BAA2B,UAAU,CAAC,IAC1E,KAAA,IACA;CACN,QAAQ;EACN;CACF;AACF;;;;;;;;;AAUA,MAAa,mBACX,UACA,cAAiD,eAAe,MACnD;CACb,IAAI;CACJ,OAAO;EACL,MAAM,OAAO,KAAK,SAAS;GACzB,YAAY,MAAM,CAAC,CAAC,YAAY,KAAA,CAAS;GACzC,MAAM,SAAS,MAAM;GACrB,IAAI,WAAW,KAAA,GAAW,MAAM,IAAI,cAAc,WAAW,MAAM;GACnE,OAAO,SAAS,OAAO,KAAK,OAAO;EACrC;EACA,aAAa,SAAS,MAAM;CAC9B;AACF"}
1
+ {"version":3,"file":"browser-C_dFMvO3.mjs","names":[],"sources":["../src/browser.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { Renderer } from \"./render.ts\";\nimport { NO_PLAYWRIGHT, RenderRefused } from \"./render.ts\";\n\n/** The text of the note when `playwright-core` is installed, but its browser is not. */\nexport const NO_BROWSER =\n \"rendering needs a browser: npx playwright-core install chromium-headless-shell\";\n\n/** This is the part of `playwright-core` that the check uses. */\ninterface Chromium {\n executablePath(): string;\n}\n\n/**\n * This function tells if the default renderer can start a browser. It gives no value when it can,\n * and the reason when it cannot. The command line and the MCP server use it one time at start.\n * Then a missing browser costs no wait and no error capture for each page that needs JavaScript.\n *\n * The check does not start the browser. It finds the full Chromium build or the headless shell of\n * the same revision on the disk. When the check cannot find the answer, it gives no value, and the\n * renderer then tries.\n *\n * @beta\n */\nexport const browserMissing = async (\n load: () => Promise<{ readonly chromium: { executablePath(): string } }> = () =>\n import(\"playwright-core\"),\n): Promise<string | undefined> => {\n let chromium: Chromium;\n try {\n ({ chromium } = await load());\n } catch {\n return NO_PLAYWRIGHT;\n }\n try {\n const executable = chromium.executablePath();\n if (existsSync(executable)) return undefined;\n // the headless shell is in a folder next to the folder of the full build, with the same revision\n let folder = dirname(executable);\n while (dirname(folder) !== folder && !/^chromium-\\d+$/.test(basename(folder)))\n folder = dirname(folder);\n const revision = /^chromium-(\\d+)$/.exec(basename(folder))?.[1];\n if (revision === undefined) return undefined;\n return existsSync(join(dirname(folder), `chromium_headless_shell-${revision}`))\n ? undefined\n : NO_BROWSER;\n } catch {\n return undefined;\n }\n};\n\n/**\n * This function gives a renderer that checks one time, before its first page, that the browser is\n * on the disk (`browserMissing`). With no browser, each page gets a `RenderRefused` with the reason\n * `browser` at once, and the renderer opens nothing. `createRuntime` puts its default renderer in\n * it, so a library with no browser costs no wait and no error capture.\n *\n * This export is internal: the root entry point does not have it since 0.2.0.\n */\nexport const checkedRenderer = (\n renderer: Renderer,\n check: () => Promise<string | undefined> = () => browserMissing(),\n): Renderer => {\n let missing: Promise<string | undefined> | undefined;\n return {\n async render(url, options) {\n missing ??= check().catch(() => undefined);\n const reason = await missing;\n if (reason !== undefined) throw new RenderRefused(\"browser\", reason);\n return renderer.render(url, options);\n },\n close: () => renderer.close(),\n };\n};\n"],"mappings":";;;;;;;AAMA,MAAa,aACX;;;;;;;;;;;;AAkBF,MAAa,iBAAiB,OAC5B,aACE,OAAO,uBACuB;CAChC,IAAI;CACJ,IAAI;EACF,CAAC,CAAE,YAAa,MAAM,KAAK;CAC7B,QAAQ;EACN,OAAO;CACT;CACA,IAAI;EACF,MAAM,aAAa,SAAS,eAAe;EAC3C,IAAI,WAAW,UAAU,GAAG,OAAO,KAAA;EAEnC,IAAI,SAAS,QAAQ,UAAU;EAC/B,OAAO,QAAQ,MAAM,MAAM,UAAU,CAAC,iBAAiB,KAAK,SAAS,MAAM,CAAC,GAC1E,SAAS,QAAQ,MAAM;EACzB,MAAM,WAAW,mBAAmB,KAAK,SAAS,MAAM,CAAC,CAAC,GAAG;EAC7D,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO,WAAW,KAAK,QAAQ,MAAM,GAAG,2BAA2B,UAAU,CAAC,IAC1E,KAAA,IACA;CACN,QAAQ;EACN;CACF;AACF;;;;;;;;;AAUA,MAAa,mBACX,UACA,cAAiD,eAAe,MACnD;CACb,IAAI;CACJ,OAAO;EACL,MAAM,OAAO,KAAK,SAAS;GACzB,YAAY,MAAM,CAAC,CAAC,YAAY,KAAA,CAAS;GACzC,MAAM,SAAS,MAAM;GACrB,IAAI,WAAW,KAAA,GAAW,MAAM,IAAI,cAAc,WAAW,MAAM;GACnE,OAAO,SAAS,OAAO,KAAK,OAAO;EACrC;EACA,aAAa,SAAS,MAAM;CAC9B;AACF"}
@@ -44,5 +44,4 @@ export declare const STOPS_HOST: ReadonlySet<Outcome>;
44
44
  * different request can succeed. Thus the failure count of the host does not change.
45
45
  */
46
46
  export declare const isClientError: (status: number) => boolean;
47
- export declare const classify: (status: number, header: (name: string) => string | undefined, now: number) => Classified;
48
- //# sourceMappingURL=classify.d.mts.map
47
+ export declare const classify: (status: number, header: (name: string) => string | undefined, now: number) => Classified;
@@ -6,7 +6,7 @@ import { n as describeDaemonStatus } from "./cli.mjs";
6
6
  * error at start rejects, so the command exits with 1.
7
7
  */
8
8
  const daemonCommand = async (line, options, io) => {
9
- const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-CWpToMtq.mjs").then((n) => n.a);
9
+ const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-l6FPe6lD.mjs").then((n) => n.a);
10
10
  if (line.action === "status") {
11
11
  const state = readDaemonState(options.dir);
12
12
  io.out(io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir));
@@ -34,4 +34,4 @@ const daemonCommand = async (line, options, io) => {
34
34
  };
35
35
  export { daemonCommand };
36
36
 
37
- //# sourceMappingURL=cli-daemon-BTT_6ec8.mjs.map
37
+ //# sourceMappingURL=cli-daemon-DRI1tL5D.mjs.map