polite-crawler 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -4
- package/build/api.d.mts +76 -11
- package/build/api.mjs +161 -28
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-Dh7_akeK.mjs → cli-daemon-Bke7kU1e.mjs} +2 -2
- package/build/{cli-daemon-Dh7_akeK.mjs.map → cli-daemon-Bke7kU1e.mjs.map} +1 -1
- package/build/{cli-recipes-DnmjTnyY.mjs → cli-recipes-CUFd9ORK.mjs} +2 -2
- package/build/{cli-recipes-DnmjTnyY.mjs.map → cli-recipes-CUFd9ORK.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-Skkq_MW8.mjs → daemon-Dh32XlZq.mjs} +3 -3
- package/build/{daemon-Skkq_MW8.mjs.map → daemon-Dh32XlZq.mjs.map} +1 -1
- package/build/{diff-BUGMvIqe.mjs → diff-ZEIt8xv3.mjs} +2 -2
- package/build/{diff-BUGMvIqe.mjs.map → diff-ZEIt8xv3.mjs.map} +1 -1
- package/build/{extract-Cm_bF25a.mjs → extract-B_Tsv1UC.mjs} +3 -3
- package/build/{extract-Cm_bF25a.mjs.map → extract-B_Tsv1UC.mjs.map} +1 -1
- package/build/html.d.mts +83 -2
- package/build/html.mjs +844 -1
- package/build/html.mjs.map +1 -0
- package/build/index.d.mts +3 -2
- package/build/index.mjs +12 -11
- package/build/{open-Cw4NVDBE.mjs → open-Dx1gCR6l.mjs} +8 -7
- package/build/{open-Cw4NVDBE.mjs.map → open-Dx1gCR6l.mjs.map} +1 -1
- package/build/politeness.d.mts +6 -0
- package/build/politeness.mjs.map +1 -1
- package/build/{recipe-CRT_I64C.mjs → recipe-BO3V_1Kr.mjs} +4 -4
- package/build/{recipe-CRT_I64C.mjs.map → recipe-BO3V_1Kr.mjs.map} +1 -1
- package/build/{recipe-product-n0fZKTxE.mjs → recipe-product-BOQMCTGh.mjs} +6 -5
- package/build/{recipe-product-n0fZKTxE.mjs.map → recipe-product-BOQMCTGh.mjs.map} +1 -1
- package/build/{runtime-BYb320jE.mjs → runtime-BVC7iOG4.mjs} +4 -3
- package/build/{runtime-BYb320jE.mjs.map → runtime-BVC7iOG4.mjs.map} +1 -1
- package/build/text.d.mts +10 -0
- package/build/text.mjs +188 -0
- package/build/text.mjs.map +1 -0
- package/build/{version-bKln1r5i.mjs → version-DxUGcHQr.mjs} +2 -2
- package/build/{version-bKln1r5i.mjs.map → version-DxUGcHQr.mjs.map} +1 -1
- package/build/{wacz-fsby_Qur.mjs → wacz-DjgklRod.mjs} +3 -3
- package/build/{wacz-fsby_Qur.mjs.map → wacz-DjgklRod.mjs.map} +1 -1
- package/build/{warc-C9VpeTjp.mjs → warc-CgkNdXyG.mjs} +2 -2
- package/build/{warc-C9VpeTjp.mjs.map → warc-CgkNdXyG.mjs.map} +1 -1
- package/package.json +5 -1
- package/build/html-CawWTgMQ.mjs +0 -1030
- package/build/html-CawWTgMQ.mjs.map +0 -1
- package/build/html-oS_ueu9U.d.mts +0 -92
package/build/politeness.d.mts
CHANGED
|
@@ -113,6 +113,12 @@ export interface QuotaRecord {
|
|
|
113
113
|
readonly spent: readonly (readonly [start: number, units: number])[];
|
|
114
114
|
/** The provider refused the key until this time, in milliseconds since the epoch. */
|
|
115
115
|
readonly blockedUntil?: number | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* The gate last read the count of the provider at this time, in milliseconds since the epoch. A
|
|
118
|
+
* give-back of units that the gate counted at this time or earlier changes nothing, because the
|
|
119
|
+
* reading can include those units.
|
|
120
|
+
*/
|
|
121
|
+
readonly readAt?: number | undefined;
|
|
116
122
|
}
|
|
117
123
|
/**
|
|
118
124
|
* A store of the records of the keys. `memoryQuotaStore` keeps them in memory, and
|
package/build/politeness.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"politeness.mjs","names":[],"sources":["../src/politeness.ts"],"sourcesContent":["/**\n * The scheduler controls the pace of each host. The speed of a polite crawler is the number of\n * hosts in progress divided by the delay for each host. Thus the scheduler keeps one request in\n * progress for each host, and it waits the delay of the host between two requests. It uses its\n * concurrency across many hosts, as the back queues of the Mercator crawler do.\n *\n * The caller decides the delay after each request, and `run` gets it from the task. Only the caller\n * knows the documented rate of the source, the crawl delay of the site and the duration of the\n * request. A wait holds no global slot, so a host that waits does not block a different host.\n *\n * The state of each host (its next time, its counts and its stop) is in a `HostStateStore`. The\n * default store is in memory. A store that processes share keeps one pace for each host across them.\n */\n\nexport interface Clock {\n readonly now: () => number;\n /** This function waits `ms` milliseconds. When the signal aborts, the wait ends early. */\n readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n}\n\n/** A timer of Node.js holds a maximum of 2^31 − 1 milliseconds. A longer timer fires at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\nexport const realClock: Clock = {\n now: () => Date.now(),\n sleep: (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal?.aborted === true) {\n resolve();\n return;\n }\n // a long wait goes in parts, because a timer longer than the maximum fires at once\n let left = Number.isFinite(ms) ? Math.max(0, ms) : 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n };\n const step = (): void => {\n if (left <= 0) {\n done();\n return;\n }\n const part = Math.min(left, MAX_TIMER_MS);\n left -= part;\n timer = setTimeout(step, part);\n };\n signal?.addEventListener(\"abort\", done, { once: true });\n step();\n }),\n};\n\n/** The crawler does not ask a host again until the stop ends, after a refusal (a challenge, 403 or 402). */\nexport class HostStopped extends Error {\n constructor(\n readonly host: string,\n readonly reason: string,\n /** This value is the end of the stop, in milliseconds since the epoch. `Infinity` is a stop with no end. */\n readonly until: number = Number.POSITIVE_INFINITY,\n ) {\n super(`${host} stopped: ${reason}`);\n }\n}\n\nexport interface Paced<T> {\n readonly value: T;\n /** This value is the time that the host rests before its next request. */\n readonly delayMs: number;\n}\n\n/** A stop keeps the crawler away from a host until a time. */\nexport interface HostStop {\n /** This value is the end of the stop, in milliseconds since the epoch. `Infinity` is a stop with no end. */\n readonly until: number;\n readonly reason: string;\n}\n\n/** These are the counts of a host. Each count gives the results of one kind in sequence. */\nexport interface HostCounts {\n /** This value counts errors and requests with no answer. At the limit of the policy, the host stops. */\n readonly failures: number;\n /** This value counts the requests to wait (429, 502, 503, 504). It sets the backoff and does not stop the host. */\n readonly waits: number;\n}\n\n/**\n * This value tells how one result changes the counts of a host:\n *\n * - `success` sets the two counts to zero.\n * - `failure` adds one to `failures`.\n * - `wait` adds one to `waits`.\n * - `neutral` changes nothing. A client error (a 400) is neutral, because a different request can succeed.\n */\nexport type HostResult = \"success\" | \"failure\" | \"wait\" | \"neutral\";\n\n/**\n * A host state store keeps the state of each host for the scheduler. Its methods are synchronous,\n * and each method is one atomic step on the state of one host. Thus a store can be a table of\n * SQLite that processes share. Times are milliseconds since the epoch.\n *\n * The state of a host has five parts:\n *\n * - the next time: the earliest time of the next request\n * - the lease: the end of the slot of the request in progress, when there is one\n * - the counts (`HostCounts`)\n * - the stop: an end time and a reason, when there is one\n */\nexport interface HostStateStore {\n /**\n * This method asks for the slot of a host at the time `now`. When the host has no rest left\n * and no lease, the store gives the slot to the caller until `now + leaseMs` and gives 0.\n * Otherwise it changes nothing and gives the time to wait in milliseconds: the time to the next\n * time, or to the end of the lease. A store that processes share gives a short wait (one second\n * or less) during a lease, because the holder usually releases it early. The caller asks again after the wait.\n */\n reserve(host: string, now: number, leaseMs: number): number;\n /** This method changes the counts of a host for one result, and it gives the new counts. */\n record(host: string, result: HostResult): HostCounts;\n /**\n * This method ends the lease of the caller. It sets the next time to `nextAt` when `nextAt` is\n * later than the stored next time. Only the holder of the lease uses it.\n */\n release(host: string, nextAt: number): void;\n /** This method sets the next time to `until` when `until` is later. It does not touch the lease. */\n defer(host: string, until: number): void;\n /** This method stops a host until a time. When the host has a stop that ends later, that stop stays. */\n stop(host: string, until: number, reason: string): void;\n /** This method gives the stop of a host at the time `now`. A stop that ended gives no value. */\n stopped(host: string, now: number): HostStop | undefined;\n /**\n * This method removes the stops and the counts of one host, or of each host when there is no\n * host. It keeps the next times and the leases, so a reset cannot make a host go faster than its pace.\n */\n reset(host?: string): void;\n /**\n * This method gives the validator memo of a host, when the store has one. A store without this\n * method and `noteValidators` has no memo. The crawler then sends each validator of a stored copy.\n */\n validators?(host: string): ValidatorMemo | undefined;\n /**\n * This method adds one conditional request to the memo of a host, with the rules of\n * `nextValidatorMemo`, in one atomic step. It gives the new memo.\n */\n noteValidators?(host: string, report: ValidatorReport, now: number): ValidatorMemo;\n}\n\n/**\n * The record of one key in a store: the units of each time bucket, and the end of a refusal of the\n * provider. A record has only numbers, so a store can keep it as JSON.\n *\n * @beta\n */\nexport interface QuotaRecord {\n /** Each item is the start of a bucket in milliseconds since the epoch, and its units. The items are in the order of their start. */\n readonly spent: readonly (readonly [start: number, units: number])[];\n /** The provider refused the key until this time, in milliseconds since the epoch. */\n readonly blockedUntil?: number | undefined;\n}\n\n/**\n * A store of the records of the keys. `memoryQuotaStore` keeps them in memory, and\n * `SqliteHostStateStore` keeps them in its file. A store keeps one record for each quota name and\n * key, so two quotas of one key (for example a minute and a day) count apart.\n *\n * @beta\n */\nexport interface QuotaStore {\n /**\n * This method gives the record of the quota `quota` of `key` to `step`, keeps the record that\n * `step` gives, and gives it. It is one step: a different call cannot change the record between\n * the read and the write.\n */\n changeQuota(\n quota: string,\n key: string,\n step: (record: QuotaRecord | undefined) => QuotaRecord,\n ): QuotaRecord;\n}\n\n/** This value tells the result that the crawler learned for one validator of a host. */\nexport type ValidatorVerdict = \"unknown\" | \"works\" | \"fails\";\n\n/**\n * This value tells what one conditional request got:\n *\n * - `not-modified`: a 304.\n * - `same`: a 200 with the body that the store has. Thus the validator did not match.\n * - `changed`: a 200 with a different body. This answer tells nothing about the validator.\n */\nexport type ValidatorAnswer = \"not-modified\" | \"same\" | \"changed\";\n\n/** This report tells the validators that one conditional request sent, and the answer that it got. */\nexport interface ValidatorReport {\n /** This value is true when the request sent `If-None-Match`. */\n readonly etag: boolean;\n /** This value is true when the request sent `If-Modified-Since`. */\n readonly lastModified: boolean;\n readonly answer: ValidatorAnswer;\n}\n\n/**\n * A validator memo holds what the crawler learned about the validators of one host. A server\n * examines `If-None-Match` first, and it ignores `If-Modified-Since` when the request has the two\n * (RFC 9110, section 13.1.3). Thus a host with unstable ETags does not answer 304 to a request with\n * the two validators at any time. Its stable `Last-Modified` date does not help. `nextValidatorMemo`\n * gives the rules.\n */\nexport interface ValidatorMemo {\n /** This value is true when the crawler leaves out `If-None-Match` for the host and sends only `If-Modified-Since`. */\n readonly skipEtag: boolean;\n /** This value tells if a request with `If-None-Match` got a 304 (`works`) or the stored body again (`fails`). */\n readonly etag: ValidatorVerdict;\n /** This value tells the same for a request with only `If-Modified-Since`. */\n readonly lastModified: ValidatorVerdict;\n /** This value counts the stored bodies in sequence that came back to a request with `If-None-Match`. */\n readonly etagMisses: number;\n /** This value counts the stored bodies in sequence that came back to a request with only `If-Modified-Since`. */\n readonly dateMisses: number;\n /** This value counts the requests with only `If-Modified-Since` since the crawler stopped the ETag, or since the last probe. */\n readonly sinceProbe: number;\n /** This time (milliseconds since the epoch) is the last time that the crawler stopped or started the ETag, or probed it. */\n readonly changedAt: number;\n}\n\n/** These are the limits of the validator memo. */\nexport interface ValidatorLimits {\n /** After this number of stored bodies in sequence, a validator fails. The value is 3. */\n readonly misses: number;\n /** After this number of requests with only `If-Modified-Since`, the next request sends the ETag again (a probe). The value is 20. */\n readonly probeEvery: number;\n /** After this time with no probe, the next request is a probe. The value is 7 days. */\n readonly probeAgeMs: number;\n}\n\n/** These are the limits of the validator memo of the crawler. */\nexport const VALIDATOR_MEMO: ValidatorLimits = {\n misses: 3,\n probeEvery: 20,\n probeAgeMs: 7 * 24 * 60 * 60 * 1000,\n};\n\nconst EMPTY_MEMO: ValidatorMemo = {\n skipEtag: false,\n etag: \"unknown\",\n lastModified: \"unknown\",\n etagMisses: 0,\n dateMisses: 0,\n sinceProbe: 0,\n changedAt: 0,\n};\n\n/**\n * This function tells which validators the next conditional request to a host sends. It sends\n * each validator of the stored copy, except when the memo stopped the ETag and the copy has a\n * `Last-Modified` date. Then it sends only `If-Modified-Since`, and the ETag too for a probe.\n * A probe comes after `probeEvery` requests or after `probeAgeMs`.\n */\nexport const validatorsToSend = (\n memo: ValidatorMemo | undefined,\n stored: { readonly etag: boolean; readonly lastModified: boolean },\n now: number,\n): { readonly etag: boolean; readonly lastModified: boolean } => {\n if (memo?.skipEtag !== true || !stored.etag || !stored.lastModified) return stored;\n const probe =\n memo.sinceProbe >= VALIDATOR_MEMO.probeEvery ||\n now - memo.changedAt >= VALIDATOR_MEMO.probeAgeMs;\n return { etag: probe, lastModified: true };\n};\n\n/**\n * This function adds one conditional request to the memo of a host, and gives the new memo.\n * These are the rules, with the limits of `VALIDATOR_MEMO`:\n *\n * 1. A 304 to a request with `If-None-Match` marks the ETag `works`. After a probe, the crawler sends the ETag again.\n * 2. After `misses` stored bodies in sequence with `If-None-Match`, the ETag fails. When the request also sent\n * `If-Modified-Since`, the crawler stops the ETag for the host.\n * 3. A probe that gets a 200 keeps the ETag stopped, and the count to the next probe starts again.\n * 4. After `misses` stored bodies in sequence with only `If-Modified-Since`, that validator fails too. Then the\n * crawler sends the two validators again, because they cost nothing. It tries the date alone again after `probeAgeMs`.\n * 5. A changed body tells nothing about a validator.\n */\nexport const nextValidatorMemo = (\n memo: ValidatorMemo | undefined,\n report: ValidatorReport,\n now: number,\n): ValidatorMemo => {\n const next: { -readonly [K in keyof ValidatorMemo]: ValidatorMemo[K] } = {\n ...(memo ?? EMPTY_MEMO),\n };\n if (report.etag) {\n const probe = next.skipEtag;\n if (report.answer === \"not-modified\") {\n next.etag = \"works\";\n next.etagMisses = 0;\n if (probe) {\n next.skipEtag = false;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n } else if (probe) {\n if (report.answer === \"same\") next.etagMisses += 1;\n next.sinceProbe = 0;\n next.changedAt = now;\n } else if (report.answer === \"same\") {\n next.etagMisses += 1;\n if (next.etagMisses >= VALIDATOR_MEMO.misses) {\n next.etag = \"fails\";\n // a date that failed gets a new try only after probeAgeMs, so the memo does not swing at each request\n const dateLeft =\n next.lastModified !== \"fails\" || now - next.changedAt >= VALIDATOR_MEMO.probeAgeMs;\n if (report.lastModified && dateLeft) {\n next.skipEtag = true;\n next.dateMisses = 0;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n }\n }\n } else if (report.lastModified) {\n if (next.skipEtag) next.sinceProbe += 1;\n if (report.answer === \"not-modified\") {\n next.lastModified = \"works\";\n next.dateMisses = 0;\n } else if (report.answer === \"same\") {\n next.dateMisses += 1;\n if (next.dateMisses >= VALIDATOR_MEMO.misses) {\n next.lastModified = \"fails\";\n if (next.skipEtag) {\n next.skipEtag = false;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n }\n }\n }\n return next;\n};\n\ninterface MemoryState {\n nextAt: number;\n leasedUntil: number;\n failures: number;\n waits: number;\n stop: HostStop | undefined;\n}\n\n/**\n * This store keeps the state of each host in memory, for one process. It removes the state of an\n * idle host (no rest left, no lease, no counts and no stop) when it holds more than `maxHosts` hosts.\n * It keeps the validator memos of the `maxHosts` hosts that it used last.\n */\nexport class MemoryHostStateStore implements HostStateStore {\n private readonly states = new Map<string, MemoryState>();\n /** The validator memos, the memo used last at the end. */\n private readonly memos = new Map<string, ValidatorMemo>();\n private sweepAt: number;\n\n constructor(private readonly maxHosts: number = 10_000) {\n this.sweepAt = maxHosts;\n }\n\n /** This value is the number of hosts that the store holds. */\n get size(): number {\n return this.states.size;\n }\n\n private state(host: string): MemoryState {\n let state = this.states.get(host);\n if (state === undefined) {\n state = { nextAt: 0, leasedUntil: 0, failures: 0, waits: 0, stop: undefined };\n this.states.set(host, state);\n }\n return state;\n }\n\n private sweep(now: number): void {\n for (const [host, state] of this.states) {\n const idle =\n state.nextAt <= now &&\n state.leasedUntil <= now &&\n state.failures === 0 &&\n state.waits === 0 &&\n (state.stop === undefined || state.stop.until <= now);\n if (idle) this.states.delete(host);\n }\n // the next sweep comes after a tenth more hosts, so a store of busy hosts does not sweep at each request\n this.sweepAt = Math.max(this.maxHosts, Math.ceil(this.states.size * 1.1));\n }\n\n reserve(host: string, now: number, leaseMs: number): number {\n if (this.states.size > this.sweepAt) this.sweep(now);\n const state = this.state(host);\n if (state.leasedUntil > now) return state.leasedUntil - now;\n if (state.nextAt > now) return state.nextAt - now;\n state.leasedUntil = now + leaseMs;\n return 0;\n }\n\n record(host: string, result: HostResult): HostCounts {\n const state = this.state(host);\n if (result === \"success\") {\n state.failures = 0;\n state.waits = 0;\n } else if (result === \"failure\") state.failures += 1;\n else if (result === \"wait\") state.waits += 1;\n return { failures: state.failures, waits: state.waits };\n }\n\n release(host: string, nextAt: number): void {\n const state = this.state(host);\n state.leasedUntil = 0;\n if (nextAt > state.nextAt) state.nextAt = nextAt;\n }\n\n defer(host: string, until: number): void {\n const state = this.state(host);\n if (until > state.nextAt) state.nextAt = until;\n }\n\n stop(host: string, until: number, reason: string): void {\n const state = this.state(host);\n if (state.stop === undefined || state.stop.until < until) state.stop = { until, reason };\n }\n\n stopped(host: string, now: number): HostStop | undefined {\n const stop = this.states.get(host)?.stop;\n return stop !== undefined && stop.until > now ? stop : undefined;\n }\n\n reset(host?: string): void {\n const clear = (state: MemoryState): void => {\n state.failures = 0;\n state.waits = 0;\n state.stop = undefined;\n };\n if (host === undefined) for (const state of this.states.values()) clear(state);\n else {\n const state = this.states.get(host);\n if (state !== undefined) clear(state);\n }\n }\n\n validators(host: string): ValidatorMemo | undefined {\n return this.memos.get(host);\n }\n\n noteValidators(host: string, report: ValidatorReport, now: number): ValidatorMemo {\n const memo = nextValidatorMemo(this.memos.get(host), report, now);\n // the memo of each change goes to the end, so the first memo is the memo used longest ago\n this.memos.delete(host);\n this.memos.set(host, memo);\n if (this.memos.size > this.maxHosts) this.memos.delete(this.memos.keys().next().value!);\n return memo;\n }\n}\n\n/** These options change the scheduler. */\nexport interface SchedulerOptions {\n /** This store keeps the state of each host. The default is a `MemoryHostStateStore`. */\n readonly store?: HostStateStore | undefined;\n /** This value is the longest slot of one request. A slot that a crashed process holds ends after it. The default is 5 minutes. */\n readonly leaseMs?: number | undefined;\n /** A host rests this long after a task that throws an error, or a task that gives no valid delay. The default is 1 second. */\n readonly fallbackDelayMs?: number | undefined;\n}\n\nconst aborted = (signal: AbortSignal): Error =>\n signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The wait was aborted\", \"AbortError\");\n\nexport class HostScheduler {\n /** This store keeps the state of each host. */\n readonly store: HostStateStore;\n private readonly chains = new Map<string, Promise<unknown>>();\n private active = 0;\n private readonly queue: Array<() => void> = [];\n private readonly leaseMs: number;\n private readonly fallbackDelayMs: number;\n\n constructor(\n private readonly clock: Clock,\n private readonly maxActive: number,\n options: SchedulerOptions = {},\n ) {\n if (!Number.isInteger(maxActive) || maxActive < 1) {\n throw new RangeError(`maxActive must be an integer of 1 or more, not ${String(maxActive)}`);\n }\n this.store = options.store ?? new MemoryHostStateStore();\n this.leaseMs = options.leaseMs ?? 300_000;\n this.fallbackDelayMs = options.fallbackDelayMs ?? 1000;\n }\n\n private acquire(signal: AbortSignal | undefined): Promise<void> {\n if (this.active < this.maxActive) {\n this.active += 1;\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const grant = (): void => {\n signal?.removeEventListener(\"abort\", cancel);\n resolve();\n };\n const cancel = (): void => {\n const at = this.queue.indexOf(grant);\n if (at !== -1) this.queue.splice(at, 1);\n reject(aborted(signal!));\n };\n this.queue.push(grant);\n signal?.addEventListener(\"abort\", cancel, { once: true });\n });\n }\n\n private release(): void {\n // the slot goes to the next waiter directly, so a new request cannot take it in between\n const next = this.queue.shift();\n if (next !== undefined) next();\n else this.active -= 1;\n }\n\n private async sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n if (signal === undefined) {\n await this.clock.sleep(ms);\n return;\n }\n if (signal.aborted) throw aborted(signal);\n await new Promise<void>((resolve, reject) => {\n const cancel = (): void => reject(aborted(signal));\n signal.addEventListener(\"abort\", cancel, { once: true });\n this.clock.sleep(ms, signal).then(\n () => {\n signal.removeEventListener(\"abort\", cancel);\n resolve();\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", cancel);\n reject(error);\n },\n );\n });\n }\n\n /**\n * This method starts one request on a host, in sequence, after the rest of the host. When the\n * signal aborts during the wait, the promise rejects with the reason of the signal.\n */\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: AbortSignal): Promise<T> {\n const previous = this.chains.get(host) ?? Promise.resolve();\n const result = previous.then(async () => {\n // after a wait, the time is at least the end of the wait, also on a clock that a test holds still\n let waited = Number.NEGATIVE_INFINITY;\n for (;;) {\n if (signal?.aborted === true) throw aborted(signal);\n const now = Math.max(this.clock.now(), waited);\n const stop = this.store.stopped(host, now);\n if (stop !== undefined) throw new HostStopped(host, stop.reason, stop.until);\n const wait = this.store.reserve(host, now, this.leaseMs);\n if (!(wait > 0)) break;\n await this.sleep(wait, signal);\n waited = now + wait;\n }\n try {\n await this.acquire(signal);\n } catch (error) {\n this.store.release(host, this.clock.now());\n throw error;\n }\n let nextAt = this.clock.now() + this.fallbackDelayMs;\n try {\n const { value, delayMs } = await task();\n const rest = Number.isFinite(delayMs) && delayMs >= 0 ? delayMs : this.fallbackDelayMs;\n nextAt = this.clock.now() + rest;\n return value;\n } catch (error) {\n nextAt = this.clock.now() + this.fallbackDelayMs;\n throw error;\n } finally {\n this.store.release(host, nextAt);\n this.release();\n }\n });\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n this.chains.set(host, tail);\n // a host with no queued request keeps no chain\n void tail.then(() => {\n if (this.chains.get(host) === tail) this.chains.delete(host);\n });\n return result;\n }\n\n /** The server asked for a pause (Retry-After), or a backoff chose one. */\n park(host: string, untilMs: number): void {\n this.store.defer(host, untilMs);\n }\n\n /** This method stops a host until `untilMs`. With no time, the stop has no end. */\n stop(host: string, reason: string, untilMs: number = Number.POSITIVE_INFINITY): void {\n this.store.stop(host, untilMs, reason);\n }\n\n stoppedReason(host: string): string | undefined {\n return this.store.stopped(host, this.clock.now())?.reason;\n }\n\n /** This method gives the stop of a host, with its end, when the host is stopped. */\n stopOf(host: string): HostStop | undefined {\n return this.store.stopped(host, this.clock.now());\n }\n\n /** This value counts the failures of a host in sequence, for the backoff. A success sets it to zero. */\n failed(host: string): number {\n return this.store.record(host, \"failure\").failures;\n }\n\n /** This value counts the requests to wait (429, 503) of a host in sequence. They do not stop the host. */\n waited(host: string): number {\n return this.store.record(host, \"wait\").waits;\n }\n\n succeeded(host: string): void {\n this.store.record(host, \"success\");\n }\n\n /** This method removes the stops and the counts of one host, or of each host. The pace stays. */\n reset(host?: string): void {\n this.store.reset(host);\n }\n}\n\n/**\n * This function gives an exponential backoff with full jitter, from the analysis of AWS. The wait\n * is random, up to base × 2^(try − 1), with a maximum. The jitter keeps retries apart.\n */\nexport const backoffMs = (\n attempt: number,\n baseMs: number,\n capMs: number,\n random: () => number,\n): number => Math.floor(random() * Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1)));\n\n/**\n * This function gives an exponential backoff with equal jitter. The wait is half of\n * base × 2^(try − 1), with a maximum, and a random part up to the other half. Thus each backoff\n * is at least half of its step, and it is not lost under the rest of the host.\n */\nexport const equalJitterMs = (\n attempt: number,\n baseMs: number,\n capMs: number,\n random: () => number,\n): number => {\n const step = Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1));\n return Math.floor(step / 2 + random() * (step / 2));\n};\n\n/** These are the facts of one request that set the rest of its host. */\nexport interface RestInput {\n /** This value is the kind of the request: a web page, a documented API, or a render in the browser. */\n readonly kind: \"page\" | \"api\" | \"render\";\n /** This value is the duration of the request, in milliseconds. */\n readonly elapsedMs: number;\n /** This value is the `crawl-delay` of robots.txt, in seconds. */\n readonly crawlDelaySeconds?: number | undefined;\n /** This value is the documented pace of the source. It replaces the interval of the policy for the kind. */\n readonly minIntervalMs?: number | undefined;\n /** This value is the wait that the server asked for (`Retry-After`). */\n readonly retryAfterMs?: number | undefined;\n}\n\n/** The rest of a host after a request, and the reason for its length. */\nexport interface Rest {\n readonly ms: number;\n readonly reason: \"pace\" | \"slow\" | \"retry-after\" | \"crawl-delay\";\n}\n\n/**\n * This function gives the rest of a host after one request, as the crawler calculates it. These\n * are the parts:\n *\n * - The interval of the kind (3 seconds for a page), or the documented pace of the source.\n * - The `crawl-delay` of robots.txt, up to `crawlDelayCapMs`, when it is longer.\n * - After a page or a render, `elapsedFactor` times the duration of the request, up to `elapsedCapMs`.\n * - The `Retry-After` of the server, when it is longer.\n *\n * The backoff after an error or a request to wait comes on top, with jitter. The function is\n * pure, so a simulation and a study can use the pace of the crawler.\n */\nexport const restAfter = (policy: PolitenessPolicy, input: RestInput): Rest => {\n const interval =\n input.minIntervalMs ??\n (input.kind === \"page\"\n ? policy.pageIntervalMs\n : input.kind === \"api\"\n ? policy.apiIntervalMs\n : policy.renderIntervalMs);\n const crawlDelay = Math.min(\n policy.crawlDelayCapMs,\n Math.max(0, (input.crawlDelaySeconds ?? 0) * 1000),\n );\n let ms = Math.max(interval, crawlDelay);\n let reason: Rest[\"reason\"] = crawlDelay > interval ? \"crawl-delay\" : \"pace\";\n if (input.kind !== \"api\") {\n const slow = Math.min(policy.elapsedCapMs, policy.elapsedFactor * Math.max(0, input.elapsedMs));\n if (slow > ms) {\n ms = slow;\n reason = \"slow\";\n }\n }\n if (input.retryAfterMs !== undefined && input.retryAfterMs > ms) {\n ms = input.retryAfterMs;\n reason = \"retry-after\";\n }\n return { ms, reason };\n};\n\n/**\n * The politeness policy holds each limit of the crawler. Each value has a default, and a host can\n * have values of its own. The times are in milliseconds.\n */\nexport interface PolitenessPolicy {\n /** This value is the shortest rest of a host between two page requests. The default is 3 seconds. */\n readonly pageIntervalMs: number;\n /** This value is the shortest rest of a host between two API requests. The default is 1 second. */\n readonly apiIntervalMs: number;\n /** This value is the shortest rest of a host after a render. The default is 5 seconds. */\n readonly renderIntervalMs: number;\n /** After a page, the host rests this number of times the duration of the request. The default is 5. */\n readonly elapsedFactor: number;\n /** This value is the maximum of the rest that comes from the duration. The default is 30 seconds. */\n readonly elapsedCapMs: number;\n /** This value is the maximum `crawl-delay` that the crawler obeys. The default is 60 seconds. */\n readonly crawlDelayCapMs: number;\n /** This value is the maximum number of redirects for one fetch. The default is 5. */\n readonly maxRedirects: number;\n /** This value is the maximum size of a body after decompression. The default is 5 MiB. */\n readonly maxBytes: number;\n /** This value is the deadline of one request, the body included. The default is 90 seconds. */\n readonly requestTimeoutMs: number;\n /** This value is the deadline of one render. The default is 20 seconds. */\n readonly renderTimeoutMs: number;\n /** After this number of failures in sequence, the host stops. The default is 5. */\n readonly maxFailures: number;\n /** This value is the stop after too many failures. The default is 1 hour. */\n readonly failureStopMs: number;\n /** This value is the stop after a 401 or a 403. The default is 1 hour. */\n readonly blockedStopMs: number;\n /** This value is the stop after a bot challenge. The default is 24 hours. */\n readonly challengeStopMs: number;\n /** This value is the stop after a 402. The default is 24 hours. */\n readonly paymentStopMs: number;\n /** The crawler obeys a `Retry-After` up to this value. A longer wait stops the host for that time. The default is 1 hour. */\n readonly maxRetryAfterMs: number;\n /** This value is the first step of the backoff after an error or a request to wait. The default is 5 seconds. */\n readonly backoffBaseMs: number;\n /** This value is the maximum step of the backoff. The default is 300 seconds. */\n readonly backoffCapMs: number;\n /** The crawler keeps a robots.txt for this time. The default is 24 hours. */\n readonly robotsTtlMs: number;\n /** The crawler keeps an unreachable robots.txt verdict for this time first, with a backoff. The default is 5 minutes. */\n readonly robotsRetryMs: number;\n /** This value is the maximum time for an unreachable robots.txt verdict. The default is 1 hour. */\n readonly robotsRetryCapMs: number;\n /** A stored robots.txt younger than this age replaces a robots.txt that the crawler cannot read. The default is 30 days. */\n readonly robotsStaleMs: number;\n /** This value is the maximum freshness that the crawler gives a response with no freshness of its own. The default is 24 hours. */\n readonly heuristicFreshnessCapMs: number;\n}\n\n/**\n * This value is the longest stop that a `Retry-After` can give: 30 days. A wait longer than\n * `maxRetryAfterMs` stops the host for the time that the server asks, up to this value.\n */\nexport const MAX_STOP_MS: number = 30 * 24 * 60 * 60 * 1000;\n\nexport const DEFAULT_POLICY: PolitenessPolicy = {\n pageIntervalMs: 3000,\n apiIntervalMs: 1000,\n renderIntervalMs: 5000,\n elapsedFactor: 5,\n elapsedCapMs: 30_000,\n crawlDelayCapMs: 60_000,\n maxRedirects: 5,\n maxBytes: 5 * 1024 * 1024,\n requestTimeoutMs: 90_000,\n renderTimeoutMs: 20_000,\n maxFailures: 5,\n failureStopMs: 60 * 60 * 1000,\n blockedStopMs: 60 * 60 * 1000,\n challengeStopMs: 24 * 60 * 60 * 1000,\n paymentStopMs: 24 * 60 * 60 * 1000,\n maxRetryAfterMs: 60 * 60 * 1000,\n backoffBaseMs: 5000,\n backoffCapMs: 300_000,\n robotsTtlMs: 24 * 60 * 60 * 1000,\n robotsRetryMs: 5 * 60 * 1000,\n robotsRetryCapMs: 60 * 60 * 1000,\n robotsStaleMs: 30 * 24 * 60 * 60 * 1000,\n heuristicFreshnessCapMs: 24 * 60 * 60 * 1000,\n};\n\n/**\n * These options change the politeness policy. The values at the top apply to each host. The\n * `hosts` map gives values for one host (`api.example.org`) or for the hosts under a name\n * (`*.example.org`). The most specific entry wins.\n */\nexport interface PolicyOptions extends Partial<PolitenessPolicy> {\n readonly hosts?: Readonly<Record<string, Partial<PolitenessPolicy>>> | undefined;\n}\n\nconst INTEGER_KEYS: ReadonlySet<string> = new Set([\"maxRedirects\", \"maxFailures\"]);\n\nconst checked = (values: Partial<PolitenessPolicy>, where: string): Partial<PolitenessPolicy> => {\n for (const [key, value] of Object.entries(values)) {\n if (!(key in DEFAULT_POLICY))\n throw new RangeError(`${where}: ${key} is not a politeness setting`);\n const good =\n typeof value === \"number\" &&\n value >= 0 &&\n (Number.isFinite(value) || key.endsWith(\"StopMs\")) &&\n (!INTEGER_KEYS.has(key) || Number.isInteger(value));\n if (!good)\n throw new RangeError(`${where}: ${key} must be a number of 0 or more, not ${String(value)}`);\n }\n return values;\n};\n\n/** This function examines the options of a policy. It throws a `RangeError` for a value that is not a valid number. */\nexport const checkPolicy = (options: PolicyOptions | undefined): void => {\n if (options === undefined) return;\n const { hosts, ...base } = options;\n checked(base, \"politeness\");\n for (const [host, values] of Object.entries(hosts ?? {}))\n checked(values, `politeness.hosts[\"${host}\"]`);\n};\n\n/** This function gives the policy of one host: the defaults, then the general options, then the entries for the host. */\nexport const policyFor = (options: PolicyOptions | undefined, host: string): PolitenessPolicy => {\n if (options === undefined) return DEFAULT_POLICY;\n const { hosts, ...base } = options;\n const name = host.toLowerCase().replace(/\\.$/, \"\");\n const matching = Object.entries(hosts ?? {})\n .map(([key, values]) => ({ key: key.toLowerCase(), values }))\n .filter(({ key }) => key === name || (key.startsWith(\"*.\") && name.endsWith(key.slice(1))))\n // an exact name wins, and a longer pattern wins over a shorter one\n .sort(\n (a, b) => (a.key === name ? 1 : 0) - (b.key === name ? 1 : 0) || a.key.length - b.key.length,\n );\n return Object.assign(\n {},\n DEFAULT_POLICY,\n base,\n ...matching.map(({ values }) => values),\n ) as PolitenessPolicy;\n};\n"],"mappings":";;AAqBA,MAAM,eAAe,KAAK,KAAK;AAE/B,MAAa,YAAmB;CAC9B,WAAW,KAAK,IAAI;CACpB,QAAQ,IAAI,WACV,IAAI,SAAe,YAAY;EAC7B,IAAI,QAAQ,YAAY,MAAM;GAC5B,QAAQ;GACR;EACF;EAEA,IAAI,OAAO,OAAO,SAAS,EAAE,IAAI,KAAK,IAAI,GAAG,EAAE,IAAI;EACnD,IAAI;EACJ,MAAM,aAAmB;GACvB,IAAI,UAAU,KAAA,GAAW,aAAa,KAAK;GAC3C,QAAQ,oBAAoB,SAAS,IAAI;GACzC,QAAQ;EACV;EACA,MAAM,aAAmB;GACvB,IAAI,QAAQ,GAAG;IACb,KAAK;IACL;GACF;GACA,MAAM,OAAO,KAAK,IAAI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AAO;CAClC,MAAM,EAAE,OAAO,GAAG,SAAS;CAC3B,MAAM,OAAO,KAAK,YAAY,CAAC,CAAC,QAAQ,OAAO,EAAE;CACjD,MAAM,WAAW,OAAO,QAAQ,SAAS,CAAC,CAAC,CAAC,CACzC,KAAK,CAAC,KAAK,aAAa;EAAE,KAAK,IAAI,YAAY;EAAG;CAAO,EAAE,CAAC,CAC5D,QAAQ,EAAE,UAAU,QAAQ,QAAS,IAAI,WAAW,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC,CAAE,CAAC,CAE1F,MACE,GAAG,OAAO,EAAE,QAAQ,OAAO,IAAI,MAAM,EAAE,QAAQ,OAAO,IAAI,MAAM,EAAE,IAAI,SAAS,EAAE,IAAI,MACxF;CACF,OAAO,OAAO,OACZ,CAAC,GACD,gBACA,MACA,GAAG,SAAS,KAAK,EAAE,aAAa,MAAM,CACxC;AACF"}
|
|
1
|
+
{"version":3,"file":"politeness.mjs","names":[],"sources":["../src/politeness.ts"],"sourcesContent":["/**\n * The scheduler controls the pace of each host. The speed of a polite crawler is the number of\n * hosts in progress divided by the delay for each host. Thus the scheduler keeps one request in\n * progress for each host, and it waits the delay of the host between two requests. It uses its\n * concurrency across many hosts, as the back queues of the Mercator crawler do.\n *\n * The caller decides the delay after each request, and `run` gets it from the task. Only the caller\n * knows the documented rate of the source, the crawl delay of the site and the duration of the\n * request. A wait holds no global slot, so a host that waits does not block a different host.\n *\n * The state of each host (its next time, its counts and its stop) is in a `HostStateStore`. The\n * default store is in memory. A store that processes share keeps one pace for each host across them.\n */\n\nexport interface Clock {\n readonly now: () => number;\n /** This function waits `ms` milliseconds. When the signal aborts, the wait ends early. */\n readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n}\n\n/** A timer of Node.js holds a maximum of 2^31 − 1 milliseconds. A longer timer fires at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\nexport const realClock: Clock = {\n now: () => Date.now(),\n sleep: (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal?.aborted === true) {\n resolve();\n return;\n }\n // a long wait goes in parts, because a timer longer than the maximum fires at once\n let left = Number.isFinite(ms) ? Math.max(0, ms) : 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n };\n const step = (): void => {\n if (left <= 0) {\n done();\n return;\n }\n const part = Math.min(left, MAX_TIMER_MS);\n left -= part;\n timer = setTimeout(step, part);\n };\n signal?.addEventListener(\"abort\", done, { once: true });\n step();\n }),\n};\n\n/** The crawler does not ask a host again until the stop ends, after a refusal (a challenge, 403 or 402). */\nexport class HostStopped extends Error {\n constructor(\n readonly host: string,\n readonly reason: string,\n /** This value is the end of the stop, in milliseconds since the epoch. `Infinity` is a stop with no end. */\n readonly until: number = Number.POSITIVE_INFINITY,\n ) {\n super(`${host} stopped: ${reason}`);\n }\n}\n\nexport interface Paced<T> {\n readonly value: T;\n /** This value is the time that the host rests before its next request. */\n readonly delayMs: number;\n}\n\n/** A stop keeps the crawler away from a host until a time. */\nexport interface HostStop {\n /** This value is the end of the stop, in milliseconds since the epoch. `Infinity` is a stop with no end. */\n readonly until: number;\n readonly reason: string;\n}\n\n/** These are the counts of a host. Each count gives the results of one kind in sequence. */\nexport interface HostCounts {\n /** This value counts errors and requests with no answer. At the limit of the policy, the host stops. */\n readonly failures: number;\n /** This value counts the requests to wait (429, 502, 503, 504). It sets the backoff and does not stop the host. */\n readonly waits: number;\n}\n\n/**\n * This value tells how one result changes the counts of a host:\n *\n * - `success` sets the two counts to zero.\n * - `failure` adds one to `failures`.\n * - `wait` adds one to `waits`.\n * - `neutral` changes nothing. A client error (a 400) is neutral, because a different request can succeed.\n */\nexport type HostResult = \"success\" | \"failure\" | \"wait\" | \"neutral\";\n\n/**\n * A host state store keeps the state of each host for the scheduler. Its methods are synchronous,\n * and each method is one atomic step on the state of one host. Thus a store can be a table of\n * SQLite that processes share. Times are milliseconds since the epoch.\n *\n * The state of a host has five parts:\n *\n * - the next time: the earliest time of the next request\n * - the lease: the end of the slot of the request in progress, when there is one\n * - the counts (`HostCounts`)\n * - the stop: an end time and a reason, when there is one\n */\nexport interface HostStateStore {\n /**\n * This method asks for the slot of a host at the time `now`. When the host has no rest left\n * and no lease, the store gives the slot to the caller until `now + leaseMs` and gives 0.\n * Otherwise it changes nothing and gives the time to wait in milliseconds: the time to the next\n * time, or to the end of the lease. A store that processes share gives a short wait (one second\n * or less) during a lease, because the holder usually releases it early. The caller asks again after the wait.\n */\n reserve(host: string, now: number, leaseMs: number): number;\n /** This method changes the counts of a host for one result, and it gives the new counts. */\n record(host: string, result: HostResult): HostCounts;\n /**\n * This method ends the lease of the caller. It sets the next time to `nextAt` when `nextAt` is\n * later than the stored next time. Only the holder of the lease uses it.\n */\n release(host: string, nextAt: number): void;\n /** This method sets the next time to `until` when `until` is later. It does not touch the lease. */\n defer(host: string, until: number): void;\n /** This method stops a host until a time. When the host has a stop that ends later, that stop stays. */\n stop(host: string, until: number, reason: string): void;\n /** This method gives the stop of a host at the time `now`. A stop that ended gives no value. */\n stopped(host: string, now: number): HostStop | undefined;\n /**\n * This method removes the stops and the counts of one host, or of each host when there is no\n * host. It keeps the next times and the leases, so a reset cannot make a host go faster than its pace.\n */\n reset(host?: string): void;\n /**\n * This method gives the validator memo of a host, when the store has one. A store without this\n * method and `noteValidators` has no memo. The crawler then sends each validator of a stored copy.\n */\n validators?(host: string): ValidatorMemo | undefined;\n /**\n * This method adds one conditional request to the memo of a host, with the rules of\n * `nextValidatorMemo`, in one atomic step. It gives the new memo.\n */\n noteValidators?(host: string, report: ValidatorReport, now: number): ValidatorMemo;\n}\n\n/**\n * The record of one key in a store: the units of each time bucket, and the end of a refusal of the\n * provider. A record has only numbers, so a store can keep it as JSON.\n *\n * @beta\n */\nexport interface QuotaRecord {\n /** Each item is the start of a bucket in milliseconds since the epoch, and its units. The items are in the order of their start. */\n readonly spent: readonly (readonly [start: number, units: number])[];\n /** The provider refused the key until this time, in milliseconds since the epoch. */\n readonly blockedUntil?: number | undefined;\n /**\n * The gate last read the count of the provider at this time, in milliseconds since the epoch. A\n * give-back of units that the gate counted at this time or earlier changes nothing, because the\n * reading can include those units.\n */\n readonly readAt?: number | undefined;\n}\n\n/**\n * A store of the records of the keys. `memoryQuotaStore` keeps them in memory, and\n * `SqliteHostStateStore` keeps them in its file. A store keeps one record for each quota name and\n * key, so two quotas of one key (for example a minute and a day) count apart.\n *\n * @beta\n */\nexport interface QuotaStore {\n /**\n * This method gives the record of the quota `quota` of `key` to `step`, keeps the record that\n * `step` gives, and gives it. It is one step: a different call cannot change the record between\n * the read and the write.\n */\n changeQuota(\n quota: string,\n key: string,\n step: (record: QuotaRecord | undefined) => QuotaRecord,\n ): QuotaRecord;\n}\n\n/** This value tells the result that the crawler learned for one validator of a host. */\nexport type ValidatorVerdict = \"unknown\" | \"works\" | \"fails\";\n\n/**\n * This value tells what one conditional request got:\n *\n * - `not-modified`: a 304.\n * - `same`: a 200 with the body that the store has. Thus the validator did not match.\n * - `changed`: a 200 with a different body. This answer tells nothing about the validator.\n */\nexport type ValidatorAnswer = \"not-modified\" | \"same\" | \"changed\";\n\n/** This report tells the validators that one conditional request sent, and the answer that it got. */\nexport interface ValidatorReport {\n /** This value is true when the request sent `If-None-Match`. */\n readonly etag: boolean;\n /** This value is true when the request sent `If-Modified-Since`. */\n readonly lastModified: boolean;\n readonly answer: ValidatorAnswer;\n}\n\n/**\n * A validator memo holds what the crawler learned about the validators of one host. A server\n * examines `If-None-Match` first, and it ignores `If-Modified-Since` when the request has the two\n * (RFC 9110, section 13.1.3). Thus a host with unstable ETags does not answer 304 to a request with\n * the two validators at any time. Its stable `Last-Modified` date does not help. `nextValidatorMemo`\n * gives the rules.\n */\nexport interface ValidatorMemo {\n /** This value is true when the crawler leaves out `If-None-Match` for the host and sends only `If-Modified-Since`. */\n readonly skipEtag: boolean;\n /** This value tells if a request with `If-None-Match` got a 304 (`works`) or the stored body again (`fails`). */\n readonly etag: ValidatorVerdict;\n /** This value tells the same for a request with only `If-Modified-Since`. */\n readonly lastModified: ValidatorVerdict;\n /** This value counts the stored bodies in sequence that came back to a request with `If-None-Match`. */\n readonly etagMisses: number;\n /** This value counts the stored bodies in sequence that came back to a request with only `If-Modified-Since`. */\n readonly dateMisses: number;\n /** This value counts the requests with only `If-Modified-Since` since the crawler stopped the ETag, or since the last probe. */\n readonly sinceProbe: number;\n /** This time (milliseconds since the epoch) is the last time that the crawler stopped or started the ETag, or probed it. */\n readonly changedAt: number;\n}\n\n/** These are the limits of the validator memo. */\nexport interface ValidatorLimits {\n /** After this number of stored bodies in sequence, a validator fails. The value is 3. */\n readonly misses: number;\n /** After this number of requests with only `If-Modified-Since`, the next request sends the ETag again (a probe). The value is 20. */\n readonly probeEvery: number;\n /** After this time with no probe, the next request is a probe. The value is 7 days. */\n readonly probeAgeMs: number;\n}\n\n/** These are the limits of the validator memo of the crawler. */\nexport const VALIDATOR_MEMO: ValidatorLimits = {\n misses: 3,\n probeEvery: 20,\n probeAgeMs: 7 * 24 * 60 * 60 * 1000,\n};\n\nconst EMPTY_MEMO: ValidatorMemo = {\n skipEtag: false,\n etag: \"unknown\",\n lastModified: \"unknown\",\n etagMisses: 0,\n dateMisses: 0,\n sinceProbe: 0,\n changedAt: 0,\n};\n\n/**\n * This function tells which validators the next conditional request to a host sends. It sends\n * each validator of the stored copy, except when the memo stopped the ETag and the copy has a\n * `Last-Modified` date. Then it sends only `If-Modified-Since`, and the ETag too for a probe.\n * A probe comes after `probeEvery` requests or after `probeAgeMs`.\n */\nexport const validatorsToSend = (\n memo: ValidatorMemo | undefined,\n stored: { readonly etag: boolean; readonly lastModified: boolean },\n now: number,\n): { readonly etag: boolean; readonly lastModified: boolean } => {\n if (memo?.skipEtag !== true || !stored.etag || !stored.lastModified) return stored;\n const probe =\n memo.sinceProbe >= VALIDATOR_MEMO.probeEvery ||\n now - memo.changedAt >= VALIDATOR_MEMO.probeAgeMs;\n return { etag: probe, lastModified: true };\n};\n\n/**\n * This function adds one conditional request to the memo of a host, and gives the new memo.\n * These are the rules, with the limits of `VALIDATOR_MEMO`:\n *\n * 1. A 304 to a request with `If-None-Match` marks the ETag `works`. After a probe, the crawler sends the ETag again.\n * 2. After `misses` stored bodies in sequence with `If-None-Match`, the ETag fails. When the request also sent\n * `If-Modified-Since`, the crawler stops the ETag for the host.\n * 3. A probe that gets a 200 keeps the ETag stopped, and the count to the next probe starts again.\n * 4. After `misses` stored bodies in sequence with only `If-Modified-Since`, that validator fails too. Then the\n * crawler sends the two validators again, because they cost nothing. It tries the date alone again after `probeAgeMs`.\n * 5. A changed body tells nothing about a validator.\n */\nexport const nextValidatorMemo = (\n memo: ValidatorMemo | undefined,\n report: ValidatorReport,\n now: number,\n): ValidatorMemo => {\n const next: { -readonly [K in keyof ValidatorMemo]: ValidatorMemo[K] } = {\n ...(memo ?? EMPTY_MEMO),\n };\n if (report.etag) {\n const probe = next.skipEtag;\n if (report.answer === \"not-modified\") {\n next.etag = \"works\";\n next.etagMisses = 0;\n if (probe) {\n next.skipEtag = false;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n } else if (probe) {\n if (report.answer === \"same\") next.etagMisses += 1;\n next.sinceProbe = 0;\n next.changedAt = now;\n } else if (report.answer === \"same\") {\n next.etagMisses += 1;\n if (next.etagMisses >= VALIDATOR_MEMO.misses) {\n next.etag = \"fails\";\n // a date that failed gets a new try only after probeAgeMs, so the memo does not swing at each request\n const dateLeft =\n next.lastModified !== \"fails\" || now - next.changedAt >= VALIDATOR_MEMO.probeAgeMs;\n if (report.lastModified && dateLeft) {\n next.skipEtag = true;\n next.dateMisses = 0;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n }\n }\n } else if (report.lastModified) {\n if (next.skipEtag) next.sinceProbe += 1;\n if (report.answer === \"not-modified\") {\n next.lastModified = \"works\";\n next.dateMisses = 0;\n } else if (report.answer === \"same\") {\n next.dateMisses += 1;\n if (next.dateMisses >= VALIDATOR_MEMO.misses) {\n next.lastModified = \"fails\";\n if (next.skipEtag) {\n next.skipEtag = false;\n next.sinceProbe = 0;\n next.changedAt = now;\n }\n }\n }\n }\n return next;\n};\n\ninterface MemoryState {\n nextAt: number;\n leasedUntil: number;\n failures: number;\n waits: number;\n stop: HostStop | undefined;\n}\n\n/**\n * This store keeps the state of each host in memory, for one process. It removes the state of an\n * idle host (no rest left, no lease, no counts and no stop) when it holds more than `maxHosts` hosts.\n * It keeps the validator memos of the `maxHosts` hosts that it used last.\n */\nexport class MemoryHostStateStore implements HostStateStore {\n private readonly states = new Map<string, MemoryState>();\n /** The validator memos, the memo used last at the end. */\n private readonly memos = new Map<string, ValidatorMemo>();\n private sweepAt: number;\n\n constructor(private readonly maxHosts: number = 10_000) {\n this.sweepAt = maxHosts;\n }\n\n /** This value is the number of hosts that the store holds. */\n get size(): number {\n return this.states.size;\n }\n\n private state(host: string): MemoryState {\n let state = this.states.get(host);\n if (state === undefined) {\n state = { nextAt: 0, leasedUntil: 0, failures: 0, waits: 0, stop: undefined };\n this.states.set(host, state);\n }\n return state;\n }\n\n private sweep(now: number): void {\n for (const [host, state] of this.states) {\n const idle =\n state.nextAt <= now &&\n state.leasedUntil <= now &&\n state.failures === 0 &&\n state.waits === 0 &&\n (state.stop === undefined || state.stop.until <= now);\n if (idle) this.states.delete(host);\n }\n // the next sweep comes after a tenth more hosts, so a store of busy hosts does not sweep at each request\n this.sweepAt = Math.max(this.maxHosts, Math.ceil(this.states.size * 1.1));\n }\n\n reserve(host: string, now: number, leaseMs: number): number {\n if (this.states.size > this.sweepAt) this.sweep(now);\n const state = this.state(host);\n if (state.leasedUntil > now) return state.leasedUntil - now;\n if (state.nextAt > now) return state.nextAt - now;\n state.leasedUntil = now + leaseMs;\n return 0;\n }\n\n record(host: string, result: HostResult): HostCounts {\n const state = this.state(host);\n if (result === \"success\") {\n state.failures = 0;\n state.waits = 0;\n } else if (result === \"failure\") state.failures += 1;\n else if (result === \"wait\") state.waits += 1;\n return { failures: state.failures, waits: state.waits };\n }\n\n release(host: string, nextAt: number): void {\n const state = this.state(host);\n state.leasedUntil = 0;\n if (nextAt > state.nextAt) state.nextAt = nextAt;\n }\n\n defer(host: string, until: number): void {\n const state = this.state(host);\n if (until > state.nextAt) state.nextAt = until;\n }\n\n stop(host: string, until: number, reason: string): void {\n const state = this.state(host);\n if (state.stop === undefined || state.stop.until < until) state.stop = { until, reason };\n }\n\n stopped(host: string, now: number): HostStop | undefined {\n const stop = this.states.get(host)?.stop;\n return stop !== undefined && stop.until > now ? stop : undefined;\n }\n\n reset(host?: string): void {\n const clear = (state: MemoryState): void => {\n state.failures = 0;\n state.waits = 0;\n state.stop = undefined;\n };\n if (host === undefined) for (const state of this.states.values()) clear(state);\n else {\n const state = this.states.get(host);\n if (state !== undefined) clear(state);\n }\n }\n\n validators(host: string): ValidatorMemo | undefined {\n return this.memos.get(host);\n }\n\n noteValidators(host: string, report: ValidatorReport, now: number): ValidatorMemo {\n const memo = nextValidatorMemo(this.memos.get(host), report, now);\n // the memo of each change goes to the end, so the first memo is the memo used longest ago\n this.memos.delete(host);\n this.memos.set(host, memo);\n if (this.memos.size > this.maxHosts) this.memos.delete(this.memos.keys().next().value!);\n return memo;\n }\n}\n\n/** These options change the scheduler. */\nexport interface SchedulerOptions {\n /** This store keeps the state of each host. The default is a `MemoryHostStateStore`. */\n readonly store?: HostStateStore | undefined;\n /** This value is the longest slot of one request. A slot that a crashed process holds ends after it. The default is 5 minutes. */\n readonly leaseMs?: number | undefined;\n /** A host rests this long after a task that throws an error, or a task that gives no valid delay. The default is 1 second. */\n readonly fallbackDelayMs?: number | undefined;\n}\n\nconst aborted = (signal: AbortSignal): Error =>\n signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The wait was aborted\", \"AbortError\");\n\nexport class HostScheduler {\n /** This store keeps the state of each host. */\n readonly store: HostStateStore;\n private readonly chains = new Map<string, Promise<unknown>>();\n private active = 0;\n private readonly queue: Array<() => void> = [];\n private readonly leaseMs: number;\n private readonly fallbackDelayMs: number;\n\n constructor(\n private readonly clock: Clock,\n private readonly maxActive: number,\n options: SchedulerOptions = {},\n ) {\n if (!Number.isInteger(maxActive) || maxActive < 1) {\n throw new RangeError(`maxActive must be an integer of 1 or more, not ${String(maxActive)}`);\n }\n this.store = options.store ?? new MemoryHostStateStore();\n this.leaseMs = options.leaseMs ?? 300_000;\n this.fallbackDelayMs = options.fallbackDelayMs ?? 1000;\n }\n\n private acquire(signal: AbortSignal | undefined): Promise<void> {\n if (this.active < this.maxActive) {\n this.active += 1;\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const grant = (): void => {\n signal?.removeEventListener(\"abort\", cancel);\n resolve();\n };\n const cancel = (): void => {\n const at = this.queue.indexOf(grant);\n if (at !== -1) this.queue.splice(at, 1);\n reject(aborted(signal!));\n };\n this.queue.push(grant);\n signal?.addEventListener(\"abort\", cancel, { once: true });\n });\n }\n\n private release(): void {\n // the slot goes to the next waiter directly, so a new request cannot take it in between\n const next = this.queue.shift();\n if (next !== undefined) next();\n else this.active -= 1;\n }\n\n private async sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n if (signal === undefined) {\n await this.clock.sleep(ms);\n return;\n }\n if (signal.aborted) throw aborted(signal);\n await new Promise<void>((resolve, reject) => {\n const cancel = (): void => reject(aborted(signal));\n signal.addEventListener(\"abort\", cancel, { once: true });\n this.clock.sleep(ms, signal).then(\n () => {\n signal.removeEventListener(\"abort\", cancel);\n resolve();\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", cancel);\n reject(error);\n },\n );\n });\n }\n\n /**\n * This method starts one request on a host, in sequence, after the rest of the host. When the\n * signal aborts during the wait, the promise rejects with the reason of the signal.\n */\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: AbortSignal): Promise<T> {\n const previous = this.chains.get(host) ?? Promise.resolve();\n const result = previous.then(async () => {\n // after a wait, the time is at least the end of the wait, also on a clock that a test holds still\n let waited = Number.NEGATIVE_INFINITY;\n for (;;) {\n if (signal?.aborted === true) throw aborted(signal);\n const now = Math.max(this.clock.now(), waited);\n const stop = this.store.stopped(host, now);\n if (stop !== undefined) throw new HostStopped(host, stop.reason, stop.until);\n const wait = this.store.reserve(host, now, this.leaseMs);\n if (!(wait > 0)) break;\n await this.sleep(wait, signal);\n waited = now + wait;\n }\n try {\n await this.acquire(signal);\n } catch (error) {\n this.store.release(host, this.clock.now());\n throw error;\n }\n let nextAt = this.clock.now() + this.fallbackDelayMs;\n try {\n const { value, delayMs } = await task();\n const rest = Number.isFinite(delayMs) && delayMs >= 0 ? delayMs : this.fallbackDelayMs;\n nextAt = this.clock.now() + rest;\n return value;\n } catch (error) {\n nextAt = this.clock.now() + this.fallbackDelayMs;\n throw error;\n } finally {\n this.store.release(host, nextAt);\n this.release();\n }\n });\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n this.chains.set(host, tail);\n // a host with no queued request keeps no chain\n void tail.then(() => {\n if (this.chains.get(host) === tail) this.chains.delete(host);\n });\n return result;\n }\n\n /** The server asked for a pause (Retry-After), or a backoff chose one. */\n park(host: string, untilMs: number): void {\n this.store.defer(host, untilMs);\n }\n\n /** This method stops a host until `untilMs`. With no time, the stop has no end. */\n stop(host: string, reason: string, untilMs: number = Number.POSITIVE_INFINITY): void {\n this.store.stop(host, untilMs, reason);\n }\n\n stoppedReason(host: string): string | undefined {\n return this.store.stopped(host, this.clock.now())?.reason;\n }\n\n /** This method gives the stop of a host, with its end, when the host is stopped. */\n stopOf(host: string): HostStop | undefined {\n return this.store.stopped(host, this.clock.now());\n }\n\n /** This value counts the failures of a host in sequence, for the backoff. A success sets it to zero. */\n failed(host: string): number {\n return this.store.record(host, \"failure\").failures;\n }\n\n /** This value counts the requests to wait (429, 503) of a host in sequence. They do not stop the host. */\n waited(host: string): number {\n return this.store.record(host, \"wait\").waits;\n }\n\n succeeded(host: string): void {\n this.store.record(host, \"success\");\n }\n\n /** This method removes the stops and the counts of one host, or of each host. The pace stays. */\n reset(host?: string): void {\n this.store.reset(host);\n }\n}\n\n/**\n * This function gives an exponential backoff with full jitter, from the analysis of AWS. The wait\n * is random, up to base × 2^(try − 1), with a maximum. The jitter keeps retries apart.\n */\nexport const backoffMs = (\n attempt: number,\n baseMs: number,\n capMs: number,\n random: () => number,\n): number => Math.floor(random() * Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1)));\n\n/**\n * This function gives an exponential backoff with equal jitter. The wait is half of\n * base × 2^(try − 1), with a maximum, and a random part up to the other half. Thus each backoff\n * is at least half of its step, and it is not lost under the rest of the host.\n */\nexport const equalJitterMs = (\n attempt: number,\n baseMs: number,\n capMs: number,\n random: () => number,\n): number => {\n const step = Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1));\n return Math.floor(step / 2 + random() * (step / 2));\n};\n\n/** These are the facts of one request that set the rest of its host. */\nexport interface RestInput {\n /** This value is the kind of the request: a web page, a documented API, or a render in the browser. */\n readonly kind: \"page\" | \"api\" | \"render\";\n /** This value is the duration of the request, in milliseconds. */\n readonly elapsedMs: number;\n /** This value is the `crawl-delay` of robots.txt, in seconds. */\n readonly crawlDelaySeconds?: number | undefined;\n /** This value is the documented pace of the source. It replaces the interval of the policy for the kind. */\n readonly minIntervalMs?: number | undefined;\n /** This value is the wait that the server asked for (`Retry-After`). */\n readonly retryAfterMs?: number | undefined;\n}\n\n/** The rest of a host after a request, and the reason for its length. */\nexport interface Rest {\n readonly ms: number;\n readonly reason: \"pace\" | \"slow\" | \"retry-after\" | \"crawl-delay\";\n}\n\n/**\n * This function gives the rest of a host after one request, as the crawler calculates it. These\n * are the parts:\n *\n * - The interval of the kind (3 seconds for a page), or the documented pace of the source.\n * - The `crawl-delay` of robots.txt, up to `crawlDelayCapMs`, when it is longer.\n * - After a page or a render, `elapsedFactor` times the duration of the request, up to `elapsedCapMs`.\n * - The `Retry-After` of the server, when it is longer.\n *\n * The backoff after an error or a request to wait comes on top, with jitter. The function is\n * pure, so a simulation and a study can use the pace of the crawler.\n */\nexport const restAfter = (policy: PolitenessPolicy, input: RestInput): Rest => {\n const interval =\n input.minIntervalMs ??\n (input.kind === \"page\"\n ? policy.pageIntervalMs\n : input.kind === \"api\"\n ? policy.apiIntervalMs\n : policy.renderIntervalMs);\n const crawlDelay = Math.min(\n policy.crawlDelayCapMs,\n Math.max(0, (input.crawlDelaySeconds ?? 0) * 1000),\n );\n let ms = Math.max(interval, crawlDelay);\n let reason: Rest[\"reason\"] = crawlDelay > interval ? \"crawl-delay\" : \"pace\";\n if (input.kind !== \"api\") {\n const slow = Math.min(policy.elapsedCapMs, policy.elapsedFactor * Math.max(0, input.elapsedMs));\n if (slow > ms) {\n ms = slow;\n reason = \"slow\";\n }\n }\n if (input.retryAfterMs !== undefined && input.retryAfterMs > ms) {\n ms = input.retryAfterMs;\n reason = \"retry-after\";\n }\n return { ms, reason };\n};\n\n/**\n * The politeness policy holds each limit of the crawler. Each value has a default, and a host can\n * have values of its own. The times are in milliseconds.\n */\nexport interface PolitenessPolicy {\n /** This value is the shortest rest of a host between two page requests. The default is 3 seconds. */\n readonly pageIntervalMs: number;\n /** This value is the shortest rest of a host between two API requests. The default is 1 second. */\n readonly apiIntervalMs: number;\n /** This value is the shortest rest of a host after a render. The default is 5 seconds. */\n readonly renderIntervalMs: number;\n /** After a page, the host rests this number of times the duration of the request. The default is 5. */\n readonly elapsedFactor: number;\n /** This value is the maximum of the rest that comes from the duration. The default is 30 seconds. */\n readonly elapsedCapMs: number;\n /** This value is the maximum `crawl-delay` that the crawler obeys. The default is 60 seconds. */\n readonly crawlDelayCapMs: number;\n /** This value is the maximum number of redirects for one fetch. The default is 5. */\n readonly maxRedirects: number;\n /** This value is the maximum size of a body after decompression. The default is 5 MiB. */\n readonly maxBytes: number;\n /** This value is the deadline of one request, the body included. The default is 90 seconds. */\n readonly requestTimeoutMs: number;\n /** This value is the deadline of one render. The default is 20 seconds. */\n readonly renderTimeoutMs: number;\n /** After this number of failures in sequence, the host stops. The default is 5. */\n readonly maxFailures: number;\n /** This value is the stop after too many failures. The default is 1 hour. */\n readonly failureStopMs: number;\n /** This value is the stop after a 401 or a 403. The default is 1 hour. */\n readonly blockedStopMs: number;\n /** This value is the stop after a bot challenge. The default is 24 hours. */\n readonly challengeStopMs: number;\n /** This value is the stop after a 402. The default is 24 hours. */\n readonly paymentStopMs: number;\n /** The crawler obeys a `Retry-After` up to this value. A longer wait stops the host for that time. The default is 1 hour. */\n readonly maxRetryAfterMs: number;\n /** This value is the first step of the backoff after an error or a request to wait. The default is 5 seconds. */\n readonly backoffBaseMs: number;\n /** This value is the maximum step of the backoff. The default is 300 seconds. */\n readonly backoffCapMs: number;\n /** The crawler keeps a robots.txt for this time. The default is 24 hours. */\n readonly robotsTtlMs: number;\n /** The crawler keeps an unreachable robots.txt verdict for this time first, with a backoff. The default is 5 minutes. */\n readonly robotsRetryMs: number;\n /** This value is the maximum time for an unreachable robots.txt verdict. The default is 1 hour. */\n readonly robotsRetryCapMs: number;\n /** A stored robots.txt younger than this age replaces a robots.txt that the crawler cannot read. The default is 30 days. */\n readonly robotsStaleMs: number;\n /** This value is the maximum freshness that the crawler gives a response with no freshness of its own. The default is 24 hours. */\n readonly heuristicFreshnessCapMs: number;\n}\n\n/**\n * This value is the longest stop that a `Retry-After` can give: 30 days. A wait longer than\n * `maxRetryAfterMs` stops the host for the time that the server asks, up to this value.\n */\nexport const MAX_STOP_MS: number = 30 * 24 * 60 * 60 * 1000;\n\nexport const DEFAULT_POLICY: PolitenessPolicy = {\n pageIntervalMs: 3000,\n apiIntervalMs: 1000,\n renderIntervalMs: 5000,\n elapsedFactor: 5,\n elapsedCapMs: 30_000,\n crawlDelayCapMs: 60_000,\n maxRedirects: 5,\n maxBytes: 5 * 1024 * 1024,\n requestTimeoutMs: 90_000,\n renderTimeoutMs: 20_000,\n maxFailures: 5,\n failureStopMs: 60 * 60 * 1000,\n blockedStopMs: 60 * 60 * 1000,\n challengeStopMs: 24 * 60 * 60 * 1000,\n paymentStopMs: 24 * 60 * 60 * 1000,\n maxRetryAfterMs: 60 * 60 * 1000,\n backoffBaseMs: 5000,\n backoffCapMs: 300_000,\n robotsTtlMs: 24 * 60 * 60 * 1000,\n robotsRetryMs: 5 * 60 * 1000,\n robotsRetryCapMs: 60 * 60 * 1000,\n robotsStaleMs: 30 * 24 * 60 * 60 * 1000,\n heuristicFreshnessCapMs: 24 * 60 * 60 * 1000,\n};\n\n/**\n * These options change the politeness policy. The values at the top apply to each host. The\n * `hosts` map gives values for one host (`api.example.org`) or for the hosts under a name\n * (`*.example.org`). The most specific entry wins.\n */\nexport interface PolicyOptions extends Partial<PolitenessPolicy> {\n readonly hosts?: Readonly<Record<string, Partial<PolitenessPolicy>>> | undefined;\n}\n\nconst INTEGER_KEYS: ReadonlySet<string> = new Set([\"maxRedirects\", \"maxFailures\"]);\n\nconst checked = (values: Partial<PolitenessPolicy>, where: string): Partial<PolitenessPolicy> => {\n for (const [key, value] of Object.entries(values)) {\n if (!(key in DEFAULT_POLICY))\n throw new RangeError(`${where}: ${key} is not a politeness setting`);\n const good =\n typeof value === \"number\" &&\n value >= 0 &&\n (Number.isFinite(value) || key.endsWith(\"StopMs\")) &&\n (!INTEGER_KEYS.has(key) || Number.isInteger(value));\n if (!good)\n throw new RangeError(`${where}: ${key} must be a number of 0 or more, not ${String(value)}`);\n }\n return values;\n};\n\n/** This function examines the options of a policy. It throws a `RangeError` for a value that is not a valid number. */\nexport const checkPolicy = (options: PolicyOptions | undefined): void => {\n if (options === undefined) return;\n const { hosts, ...base } = options;\n checked(base, \"politeness\");\n for (const [host, values] of Object.entries(hosts ?? {}))\n checked(values, `politeness.hosts[\"${host}\"]`);\n};\n\n/** This function gives the policy of one host: the defaults, then the general options, then the entries for the host. */\nexport const policyFor = (options: PolicyOptions | undefined, host: string): PolitenessPolicy => {\n if (options === undefined) return DEFAULT_POLICY;\n const { hosts, ...base } = options;\n const name = host.toLowerCase().replace(/\\.$/, \"\");\n const matching = Object.entries(hosts ?? {})\n .map(([key, values]) => ({ key: key.toLowerCase(), values }))\n .filter(({ key }) => key === name || (key.startsWith(\"*.\") && name.endsWith(key.slice(1))))\n // an exact name wins, and a longer pattern wins over a shorter one\n .sort(\n (a, b) => (a.key === name ? 1 : 0) - (b.key === name ? 1 : 0) || a.key.length - b.key.length,\n );\n return Object.assign(\n {},\n DEFAULT_POLICY,\n base,\n ...matching.map(({ values }) => values),\n ) as PolitenessPolicy;\n};\n"],"mappings":";;AAqBA,MAAM,eAAe,KAAK,KAAK;AAE/B,MAAa,YAAmB;CAC9B,WAAW,KAAK,IAAI;CACpB,QAAQ,IAAI,WACV,IAAI,SAAe,YAAY;EAC7B,IAAI,QAAQ,YAAY,MAAM;GAC5B,QAAQ;GACR;EACF;EAEA,IAAI,OAAO,OAAO,SAAS,EAAE,IAAI,KAAK,IAAI,GAAG,EAAE,IAAI;EACnD,IAAI;EACJ,MAAM,aAAmB;GACvB,IAAI,UAAU,KAAA,GAAW,aAAa,KAAK;GAC3C,QAAQ,oBAAoB,SAAS,IAAI;GACzC,QAAQ;EACV;EACA,MAAM,aAAmB;GACvB,IAAI,QAAQ,GAAG;IACb,KAAK;IACL;GACF;GACA,MAAM,OAAO,KAAK,IAAI,MAAM,YAAY;GACxC,QAAQ;GACR,QAAQ,WAAW,MAAM,IAAI;EAC/B;EACA,QAAQ,iBAAiB,SAAS,MAAM,EAAE,MAAM,KAAK,CAAC;EACtD,KAAK;CACP,CAAC;AACL;;AAGA,IAAa,cAAb,cAAiC,MAAM;CAE1B;CACA;CAEA;CAJX,YACW,MACA,QAEA,QAAgB,OAAO,mBAChC;EACA,MAAM,GAAG,KAAK,YAAY,QAAQ;EALzB,KAAA,OAAA;EACA,KAAA,SAAA;EAEA,KAAA,QAAA;CAGX;AACF;;AAmLA,MAAa,iBAAkC;CAC7C,QAAQ;CACR,YAAY;CACZ,YAAY;AACd;AAEA,MAAM,aAA4B;CAChC,UAAU;CACV,MAAM;CACN,cAAc;CACd,YAAY;CACZ,YAAY;CACZ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O,OACZ,CAAC,GACD,gBACA,MACA,GAAG,SAAS,KAAK,EAAE,aAAa,MAAM,CACxC;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as durationMs } from "./version-
|
|
2
|
-
import { b as fallbackReason, c as isHeldBack, d as recordOverride, g as archivedCopy, i as fetchAndIndex, n as HELD_BACK, s as heldBackMeta, y as archivedOf } from "./runtime-
|
|
3
|
-
import {
|
|
1
|
+
import { i as durationMs } from "./version-DxUGcHQr.mjs";
|
|
2
|
+
import { b as fallbackReason, c as isHeldBack, d as recordOverride, g as archivedCopy, i as fetchAndIndex, n as HELD_BACK, s as heldBackMeta, y as archivedOf } from "./runtime-BVC7iOG4.mjs";
|
|
3
|
+
import { decodeBody } from "./text.mjs";
|
|
4
4
|
// src/recipe.ts
|
|
5
5
|
/**
|
|
6
6
|
* This function reads a body as JSON, in the encoding that the response declares. A body that is
|
|
@@ -281,4 +281,4 @@ const runRecipe = async (target, recipe, input, options = {}) => {
|
|
|
281
281
|
};
|
|
282
282
|
export { readJson as a, runtimeOf as c, defineRecipe as i, RESERVED_RECIPES as n, registerRecipe as o, deadlineOf as r, runRecipe as s, RECIPE_LIMITS as t };
|
|
283
283
|
|
|
284
|
-
//# sourceMappingURL=recipe-
|
|
284
|
+
//# sourceMappingURL=recipe-BO3V_1Kr.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recipe-CRT_I64C.mjs","names":[],"sources":["../src/recipe.ts"],"sourcesContent":["/*\n * The recipe SDK. A recipe tells the crawler what to fetch and how to read it into documents.\n *\n * - `defineRecipe` declares a recipe: its name, the request for an input, and its extractor.\n * - `runRecipe` fetches one input through the crawler and gives the documents of the capture.\n * - `registerRecipe` gives the extractor to the extractors of a runtime. `openCrawler` and\n * `createRuntime` take `recipes` and register them at open, so `reindex` reads their captures.\n *\n * Each fetch of a recipe is a fetch of the crawler. Thus robots.txt (for a page), the pace of each\n * host, the stops, the egress policy and the capture log apply. The documents are versions in the\n * index, so `find`, `read`, `verify`, `extract`, `diff` and the time travel use them.\n */\nimport type { FetchRequest } from \"./crawler.ts\";\nimport type { Doc, ExtractedDoc, VersionText } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedCopy, archivedOf, fallbackReason } from \"./fallback.ts\";\nimport type { CrawlRuntime, Extractor, Extractors, Indexed, PageOptions } from \"./runtime.ts\";\nimport { HELD_BACK, fetchAndIndex, heldBackMeta, isHeldBack, recordOverride } from \"./runtime.ts\";\nimport type { AiInput } from \"./signals.ts\";\nimport { decodeBody } from \"./text.ts\";\n\n/** The capture that an extractor reads: the final URL of the response and its content type. */\nexport interface RecipeCapture {\n readonly url: string;\n readonly contentType: string | null;\n}\n\n/**\n * This function reads one captured body into the documents that it holds. It is pure: the same\n * body and capture always give the same documents. It sends no request. It can answer later.\n */\nexport type RecipeExtract = (\n body: Uint8Array,\n capture: RecipeCapture,\n) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;\n\n/** The request of a recipe for one input: the URL, and the parts that change with the input. */\nexport interface RecipeRequest {\n readonly url: string;\n /** This value replaces the `accept` of the recipe for this request. */\n readonly accept?: string | undefined;\n /** These headers go with the request. The crawler does not write them into the capture. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** These query parameters hold secrets. The capture shows `REDACTED` in their place. */\n readonly secretParams?: readonly string[] | undefined;\n}\n\n/** These values declare a recipe. Only `name` and `extract` are necessary. */\nexport interface RecipeDefinition<Input = string> {\n /**\n * This name goes into each capture record of the recipe, so it is part of each capture id.\n * `reindex` finds the extractor by it. Do not change it after the first capture.\n */\n readonly name: string;\n /** This text tells what the recipe reads. */\n readonly description?: string | undefined;\n /**\n * The value `page` (the default) is a web page: robots.txt applies. The value `api` is a\n * documented API with terms of its own: robots.txt does not apply, and the pace still does.\n */\n readonly mode?: \"api\" | \"page\" | undefined;\n /** This value is the `Accept` header. The defaults are HTML for a page and JSON for an API. */\n readonly accept?: string | undefined;\n /** This value is the documented pace of the source: the shortest time between two of its requests. */\n readonly minInterval?: Duration | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** This value is the most bytes of a body that the crawler keeps. */\n readonly maxBytes?: number | undefined;\n /** This function gives the request for an input. With no function, the input is the URL. */\n readonly fetch?: ((input: Input) => string | RecipeRequest) | undefined;\n /** This function reads a captured body into documents. It is pure, and it sends no request. */\n readonly extract: RecipeExtract;\n}\n\n/** These options build the request of a recipe for one input (`Recipe.request`). */\nexport interface RecipeRequestOptions {\n /** This value replaces the `maxAge` of the recipe. The value `0` asks the source again. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for a recipe of the mode `page`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** This name connects the captures to the job that asked for them. */\n readonly job?: string | undefined;\n /** When this signal aborts, the crawler stops the fetch. */\n readonly signal?: AbortSignal | undefined;\n /** This label goes into each capture record of the request. */\n readonly scope?: string | undefined;\n /** These labels go into each capture record of the request. They are not part of the capture id. */\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** No request starts at or after this time (milliseconds since the epoch, on the clock of the crawler). */\n readonly deadline?: number | undefined;\n}\n\n/** A recipe that `defineRecipe` made. Give it to `runRecipe`, to `registerRecipe` or to `openCrawler`. */\nexport interface Recipe<Input = string> {\n readonly name: string;\n readonly description: string | null;\n readonly mode: \"api\" | \"page\";\n readonly accept: string;\n /**\n * This extractor reads the captures of the recipe. It checks the documents of the definition.\n *\n * @beta\n */\n readonly extractor: Extractor;\n /**\n * This method gives the request of the crawler for one input. A value that is not a URL throws a `TypeError`.\n *\n * @beta\n */\n request(input: Input, options?: RecipeRequestOptions): FetchRequest;\n}\n\n/**\n * This function reads a body as JSON, in the encoding that the response declares. A body that is\n * not JSON (a page about maintenance, or a login page) throws an error that names the URL and the\n * content type. In an extractor, the runtime then reports that error.\n */\nexport const readJson = (body: Uint8Array, capture: RecipeCapture): unknown => {\n const text = decodeBody(body, capture.contentType);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new Error(\n `${capture.url} answered ${capture.contentType ?? \"a body of no stated type\"}, not JSON`,\n );\n }\n};\n\n/**\n * These recipe names belong to the crawler: the page reader, the archived fallback, robots.txt,\n * and the sitemaps and feeds of `discover`. A recipe cannot use them.\n */\nexport const RESERVED_RECIPES: readonly string[] = [\n \"page\",\n \"archive-copy\",\n \"archive-index\",\n \"robots.txt\",\n \"sitemap\",\n \"feed\",\n];\n\n/**\n * These are the limits of a recipe.\n *\n * @beta\n */\nexport const RECIPE_LIMITS: {\n /** The longest recipe name. */\n readonly nameChars: number;\n /** The longest document id. */\n readonly docIdChars: number;\n} = { nameChars: 64, docIdChars: 2048 };\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\nconst PAGE_ACCEPT = \"text/html,application/xhtml+xml;q=0.9,*/*;q=0.5\";\nconst API_ACCEPT = \"application/json\";\nconst AI_INPUTS: readonly AiInput[] = [\"yes\", \"no\", \"unset\"];\n\n/** This function tells what is wrong with one document of an extractor, or gives undefined. */\nconst faultOf = (value: unknown, seen: Set<string>): string | undefined => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return \"a document must be an object\";\n const doc = value as Record<string, unknown>;\n const id = doc[\"doc\"];\n if (typeof id !== \"string\" || id.length === 0 || id.length > RECIPE_LIMITS.docIdChars)\n return `doc must be a text of 1 to ${String(RECIPE_LIMITS.docIdChars)} characters`;\n // the archived fallback labels the copies of third parties, and only it makes these\n if (id.startsWith(\"archive:\"))\n return `the id ${id} starts with archive:, which is for the archived copies`;\n if (seen.has(id)) return `two documents have the id ${id}`;\n seen.add(id);\n const kind = doc[\"kind\"];\n if (typeof kind !== \"string\" || kind.length === 0) return \"kind must be a text that is not empty\";\n if (kind === \"archived\") return \"the kind archived is for the archived copies\";\n if (typeof doc[\"title\"] !== \"string\") return \"title must be a text\";\n if (typeof doc[\"text\"] !== \"string\") return \"text must be a text\";\n if (doc[\"url\"] !== null && typeof doc[\"url\"] !== \"string\") return \"url must be a text or null\";\n const meta = doc[\"meta\"];\n if (meta === null || typeof meta !== \"object\" || Array.isArray(meta))\n return \"meta must be an object\";\n try {\n JSON.stringify(meta);\n } catch {\n return \"meta must be JSON: no cycle and no BigInt\";\n }\n const merge = doc[\"merge\"];\n if (merge !== undefined && merge !== \"latest\" && merge !== \"richest\")\n return 'merge must be \"latest\" or \"richest\"';\n if (doc[\"full_text\"] !== undefined && typeof doc[\"full_text\"] !== \"string\")\n return \"full_text must be a text\";\n const aiInput = doc[\"ai_input\"];\n if (aiInput !== undefined && !AI_INPUTS.includes(aiInput as AiInput))\n return 'ai_input must be \"yes\", \"no\" or \"unset\"';\n return undefined;\n};\n\n/** This function gives the documents of an extractor, or throws an error that names the first fault. */\nconst checkedDocs = (name: string, docs: unknown): ReadonlyArray<ExtractedDoc> => {\n if (!Array.isArray(docs))\n throw new TypeError(`the recipe ${name} gave ${typeof docs}, not an array of documents`);\n const seen = new Set<string>();\n for (const [index, doc] of docs.entries()) {\n const fault = faultOf(doc, seen);\n if (fault !== undefined)\n throw new TypeError(\n `the recipe ${name} gave a document that is not valid (${String(index)}): ${fault}`,\n );\n }\n return docs as ReadonlyArray<ExtractedDoc>;\n};\n\n/**\n * This function declares a recipe. It checks the definition at once: a name that is not valid, a\n * reserved name or a duration that it cannot read throws an error. The extractor of the recipe\n * checks each document of `extract`. A document that is not valid makes the extractor throw, and\n * the runtime reports it as an error of the extractor.\n */\nexport const defineRecipe = <Input = string>(\n definition: RecipeDefinition<Input>,\n): Recipe<Input> => {\n const name = definition.name;\n if (typeof name !== \"string\" || name.length > RECIPE_LIMITS.nameChars || !NAME.test(name)) {\n throw new RangeError(\n `a recipe name is 1 to ${String(RECIPE_LIMITS.nameChars)} letters, digits and . _ : -, and it starts with a letter or a digit, not ${JSON.stringify(name) ?? \"undefined\"}`,\n );\n }\n if (RESERVED_RECIPES.includes(name)) {\n throw new RangeError(\n `the recipe name ${name} belongs to the crawler: give the recipe a name of its own`,\n );\n }\n if (typeof definition.extract !== \"function\") {\n throw new TypeError(\n `the recipe ${name} needs extract, a function that reads a body into documents`,\n );\n }\n const mode = definition.mode ?? \"page\";\n if (mode !== \"page\" && mode !== \"api\") {\n throw new RangeError(\n `the mode of the recipe ${name} must be \"page\" or \"api\", not ${String(mode)}`,\n );\n }\n const accept = definition.accept ?? (mode === \"api\" ? API_ACCEPT : PAGE_ACCEPT);\n const minIntervalMs =\n definition.minInterval === undefined ? undefined : durationMs(definition.minInterval);\n const maxAgeOf = (value: Duration): number | \"auto\" =>\n value === \"auto\" ? \"auto\" : durationMs(value);\n const maxAge = maxAgeOf(definition.maxAge ?? \"24h\");\n const maxBytes = definition.maxBytes;\n if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1)) {\n throw new RangeError(`maxBytes of the recipe ${name} must be a whole number of 1 or more`);\n }\n const extract = definition.extract;\n const extractor: Extractor = async (body, capture) =>\n checkedDocs(name, await extract(body, { url: capture.url, contentType: capture.contentType }));\n const fetch = definition.fetch;\n return {\n name,\n description: definition.description ?? null,\n mode,\n accept,\n extractor,\n request(input, options = {}) {\n const asked: unknown = fetch === undefined ? input : fetch(input);\n const target = typeof asked === \"string\" ? { url: asked } : (asked as RecipeRequest | null);\n const url = target?.url;\n let parsed: URL | undefined;\n try {\n parsed = typeof url === \"string\" ? new URL(url) : undefined;\n } catch {\n parsed = undefined;\n }\n if (parsed === undefined || (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")) {\n throw new TypeError(\n `the recipe ${name} needs an http or https URL for its input, not ${JSON.stringify(url) ?? String(url)}`,\n );\n }\n return {\n url: parsed.href,\n mode,\n recipe: name,\n accept: target?.accept ?? accept,\n headers: target?.headers,\n secretParams: target?.secretParams,\n minIntervalMs,\n maxAgeMs: options.maxAge === undefined ? maxAge : maxAgeOf(options.maxAge),\n maxBytes,\n onBehalfOf: options.onBehalfOf,\n job: options.job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline: options.deadline,\n };\n },\n };\n};\n\n/**\n * This function gives the extractor of a recipe to the extractors of a runtime. A second\n * registration of the same recipe does nothing. A different extractor with the same name throws\n * an error, because `reindex` must read each capture with one extractor.\n *\n * @beta\n */\nexport const registerRecipe = <Input>(extractors: Extractors, recipe: Recipe<Input>): void => {\n const known = extractors.get(recipe.name);\n if (known === recipe.extractor) return;\n if (known !== undefined) {\n throw new Error(\n `the recipe ${recipe.name} has a different extractor in this runtime: give each recipe a name of its own`,\n );\n }\n extractors.register(recipe.name, recipe.extractor);\n};\n\n/** These options control one run of a recipe. */\nexport interface RecipeRunOptions extends Omit<RecipeRequestOptions, \"deadline\"> {\n /** No request starts after this time from the start of the run, for example `\"30s\"`. */\n readonly budget?: Duration | undefined;\n /** This value is true when a person gave this input directly. It is the only way to see a held-back document. The crawler logs it. */\n readonly userProvided?: boolean | undefined;\n /**\n * The value `archive` gives a copy from a public web archive when the site refuses the page or is\n * down. Only a recipe of the mode `page` takes it. The page reader reads the copy.\n */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n /** The value true also gives an archived copy of a page that the current robots.txt disallows. */\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** One document of a run of a recipe: the version of the capture of the run. */\nexport interface RecipeDoc {\n readonly doc: string;\n readonly kind: string;\n /** This value is the title. A held-back document shows no title. */\n readonly title: string;\n readonly url: string | null;\n /** This value is the metadata. A held-back document shows only the structural fields. */\n readonly meta: Readonly<Record<string, unknown>>;\n /** This value is the length of the text. `read` gives the text. */\n readonly chars: number;\n /** This id is the capture of this version. A citation names it. */\n readonly capture: string;\n readonly fetched_at: string;\n readonly held_back: boolean;\n /** This value tells that the document is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n}\n\n/** The result of `runRecipe`. */\nexport interface RecipeResult {\n readonly recipe: string;\n /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */\n readonly url: string;\n readonly outcome: string;\n readonly status: number;\n /** These documents came from the capture of the run, in the order of the extractor. */\n readonly docs: readonly RecipeDoc[];\n /** This id is the capture of the documents. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n /** This value is true when the stored copy answered, and the crawler sent no request. */\n readonly from_cache: boolean;\n /** This value is true when a document is held back. */\n readonly held_back: boolean;\n /** This text is the error of the extractor, when it threw for the capture. */\n readonly error: string | null;\n /** This value tells that the documents are an archived copy, not a fresh fetch. */\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\n/** A recipe operates on a runtime, or on a crawler that has one (`crawler.runtime`). */\nexport type RecipeTarget = CrawlRuntime | { readonly runtime: CrawlRuntime };\n\n/** This function gives the runtime of a target. */\nexport const runtimeOf = (target: RecipeTarget): CrawlRuntime =>\n \"crawler\" in target ? target : target.runtime;\n\n/** This function gives the deadline of a budget, on the clock of the runtime. */\nexport const deadlineOf = (\n runtime: CrawlRuntime,\n budget: Duration | undefined,\n): number | undefined =>\n budget === undefined ? undefined : Date.parse(runtime.now()) + durationMs(budget);\n\n/** This function gives one document of a run, with the rule for a held-back document. */\nconst recipeDoc = async (\n runtime: CrawlRuntime,\n doc: Doc,\n capture: string | undefined,\n userProvided: boolean,\n action: string,\n): Promise<RecipeDoc> => {\n const current = runtime.index.get(doc.doc) ?? doc;\n const version: VersionText | Doc =\n (capture === undefined ? undefined : runtime.index.versionText(doc.doc, capture)) ?? current;\n const aiInput: AiInput =\n current.ai_input === \"no\" || version.ai_input === \"no\" ? \"no\" : version.ai_input;\n const held = isHeldBack({ ai_input: aiInput }, userProvided);\n if (aiInput === \"no\" && userProvided) await recordOverride(runtime, current, action);\n const archived = archivedOf(version.meta);\n return {\n doc: doc.doc,\n kind: version.kind,\n title: held ? \"\" : version.title,\n url: version.url,\n meta: held ? heldBackMeta(version.meta) : version.meta,\n chars: version.text.length,\n capture: version.capture,\n fetched_at: version.fetched_at,\n held_back: held,\n ...(archived === undefined ? {} : { archived }),\n };\n};\n\nconst noteOf = (parts: ReadonlyArray<string | null | undefined>): string | null => {\n const kept = parts.filter((part): part is string => typeof part === \"string\" && part.length > 0);\n return kept.length > 0 ? kept.join(\"; \") : null;\n};\n\n/**\n * This function starts a recipe for one input. It fetches the request through the crawler, and it\n * reads the capture with the extractor of the recipe. It gives the documents of that capture.\n * These are its rules:\n *\n * - The runtime registers the recipe the first time that it gets it. Give the recipe to\n * `openCrawler` too, so that `reindex` reads its captures before the first fetch.\n * - A stored copy younger than `maxAge` answers with no request. When the extractor cannot read a\n * stored copy, the crawler asks the source one more time.\n * - An extractor that throws gives no document, and `error` tells why. The fetch still succeeds.\n * - A document that asked not to be AI input shows no title and only its structural metadata,\n * unless `userProvided`. The crawler logs each `userProvided` read of a held-back document.\n * - With `fallback: \"archive\"`, a page that the site refuses gets an archived copy, with\n * `archived`. The page reader reads the copy. The extractor of the recipe reads only live\n * captures. Thus its documents do not mix a live answer and an old copy of a third party.\n */\nexport const runRecipe = async <Input>(\n target: RecipeTarget,\n recipe: Recipe<Input>,\n input: Input,\n options: RecipeRunOptions = {},\n): Promise<RecipeResult> => {\n const runtime = runtimeOf(target);\n if (options.fallback === \"archive\" && recipe.mode !== \"page\") {\n throw new RangeError(\n `the recipe ${recipe.name} reads an API: an archived copy is for a page, so give fallback only to a recipe of the mode page`,\n );\n }\n registerRecipe(runtime.extractors, recipe);\n const deadline = deadlineOf(runtime, options.budget);\n const request = recipe.request(input, { ...options, deadline });\n let indexed: Indexed = await fetchAndIndex(runtime, request);\n // a stored answer that the extractor cannot read is no answer: it would give the same error until maxAge\n if (indexed.error !== undefined && indexed.blocked === undefined && indexed.fetched.fromCache) {\n indexed = await fetchAndIndex(runtime, { ...request, maxAgeMs: 0 });\n }\n const userProvided = options.userProvided ?? false;\n const action = options.job ?? `recipe ${recipe.name}`;\n const fetched = indexed.fetched;\n const notes: Array<string | undefined> = [fetched.note, indexed.error];\n if (indexed.docs.length === 0 && options.fallback === \"archive\") {\n const reason = fallbackReason(indexed);\n if (reason !== undefined) {\n const page: PageOptions = {\n render: \"never\",\n maxAgeMs: request.maxAgeMs,\n onBehalfOf: request.onBehalfOf,\n job: request.job,\n signal: request.signal,\n scope: request.scope,\n labels: request.labels,\n deadline,\n fallback: \"archive\",\n archiveDespiteRobots: options.archiveDespiteRobots,\n };\n const answer = await archivedCopy(runtime, request.url, reason, page);\n if (answer.doc !== undefined && answer.archived !== undefined) {\n const doc = await recipeDoc(runtime, answer.doc, answer.doc.capture, userProvided, action);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs: [doc],\n capture: doc.capture,\n fetched_at: doc.fetched_at,\n from_cache: answer.fromCache,\n held_back: doc.held_back,\n error: indexed.error ?? null,\n archived: answer.archived,\n note: noteOf([\n ...notes,\n ...answer.notes,\n \"the page reader read the archived copy, not the extractor of the recipe\",\n doc.held_back ? HELD_BACK : undefined,\n ]),\n };\n }\n notes.push(...answer.notes);\n }\n }\n const capture = fetched.capture;\n const docs: RecipeDoc[] = [];\n for (const doc of indexed.docs)\n docs.push(await recipeDoc(runtime, doc, capture, userProvided, action));\n const held = docs.some((doc) => doc.held_back);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs,\n capture: docs[0]?.capture ?? capture ?? null,\n fetched_at: docs[0]?.fetched_at ?? fetched.fetchedAt ?? null,\n from_cache: fetched.fromCache,\n held_back: held,\n error: indexed.error ?? null,\n note: noteOf([...notes, held ? HELD_BACK : undefined]),\n };\n};\n"],"mappings":";;;;;;;;;AAwHA,MAAa,YAAY,MAAkB,YAAoC;CAC7E,MAAM,OAAO,WAAW,MAAM,QAAQ,WAAW;CACjD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,MACR,GAAG,QAAQ,IAAI,YAAY,QAAQ,eAAe,2BAA2B,WAC/E;CACF;AACF;;;;;AAMA,MAAa,mBAAsC;CACjD;CAC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SAAS;KACxB,UAAU,OAAO;KACjB,MAAM,OAAO;MACX,GAAG;MACH,GAAG,OAAO;MACV;MACA,IAAI,YAAY,YAAY,KAAA;KAC9B,CAAC;IACH;GACF;GACA,MAAM,KAAK,GAAG,OAAO,KAAK;EAC5B;CACF;CACA,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAoB,CAAC;CAC3B,KAAK,MAAM,OAAO,QAAQ,MACxB,KAAK,KAAK,MAAM,UAAU,SAAS,KAAK,SAAS,cAAc,MAAM,CAAC;CACxE,MAAM,OAAO,KAAK,MAAM,QAAQ,IAAI,SAAS;CAC7C,OAAO;EACL,QAAQ,OAAO;EACf,KAAK,QAAQ;EACb,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB;EACA,SAAS,KAAK,EAAE,EAAE,WAAW,WAAW;EACxC,YAAY,KAAK,EAAE,EAAE,cAAc,QAAQ,aAAa;EACxD,YAAY,QAAQ;EACpB,WAAW;EACX,OAAO,QAAQ,SAAS;EACxB,MAAM,OAAO,CAAC,GAAG,OAAO,OAAO,YAAY,KAAA,CAAS,CAAC;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"recipe-BO3V_1Kr.mjs","names":[],"sources":["../src/recipe.ts"],"sourcesContent":["/*\n * The recipe SDK. A recipe tells the crawler what to fetch and how to read it into documents.\n *\n * - `defineRecipe` declares a recipe: its name, the request for an input, and its extractor.\n * - `runRecipe` fetches one input through the crawler and gives the documents of the capture.\n * - `registerRecipe` gives the extractor to the extractors of a runtime. `openCrawler` and\n * `createRuntime` take `recipes` and register them at open, so `reindex` reads their captures.\n *\n * Each fetch of a recipe is a fetch of the crawler. Thus robots.txt (for a page), the pace of each\n * host, the stops, the egress policy and the capture log apply. The documents are versions in the\n * index, so `find`, `read`, `verify`, `extract`, `diff` and the time travel use them.\n */\nimport type { FetchRequest } from \"./crawler.ts\";\nimport type { Doc, ExtractedDoc, VersionText } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedCopy, archivedOf, fallbackReason } from \"./fallback.ts\";\nimport type { CrawlRuntime, Extractor, Extractors, Indexed, PageOptions } from \"./runtime.ts\";\nimport { HELD_BACK, fetchAndIndex, heldBackMeta, isHeldBack, recordOverride } from \"./runtime.ts\";\nimport type { AiInput } from \"./signals.ts\";\nimport { decodeBody } from \"./text.ts\";\n\n/** The capture that an extractor reads: the final URL of the response and its content type. */\nexport interface RecipeCapture {\n readonly url: string;\n readonly contentType: string | null;\n}\n\n/**\n * This function reads one captured body into the documents that it holds. It is pure: the same\n * body and capture always give the same documents. It sends no request. It can answer later.\n */\nexport type RecipeExtract = (\n body: Uint8Array,\n capture: RecipeCapture,\n) => ReadonlyArray<ExtractedDoc> | Promise<ReadonlyArray<ExtractedDoc>>;\n\n/** The request of a recipe for one input: the URL, and the parts that change with the input. */\nexport interface RecipeRequest {\n readonly url: string;\n /** This value replaces the `accept` of the recipe for this request. */\n readonly accept?: string | undefined;\n /** These headers go with the request. The crawler does not write them into the capture. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** These query parameters hold secrets. The capture shows `REDACTED` in their place. */\n readonly secretParams?: readonly string[] | undefined;\n}\n\n/** These values declare a recipe. Only `name` and `extract` are necessary. */\nexport interface RecipeDefinition<Input = string> {\n /**\n * This name goes into each capture record of the recipe, so it is part of each capture id.\n * `reindex` finds the extractor by it. Do not change it after the first capture.\n */\n readonly name: string;\n /** This text tells what the recipe reads. */\n readonly description?: string | undefined;\n /**\n * The value `page` (the default) is a web page: robots.txt applies. The value `api` is a\n * documented API with terms of its own: robots.txt does not apply, and the pace still does.\n */\n readonly mode?: \"api\" | \"page\" | undefined;\n /** This value is the `Accept` header. The defaults are HTML for a page and JSON for an API. */\n readonly accept?: string | undefined;\n /** This value is the documented pace of the source: the shortest time between two of its requests. */\n readonly minInterval?: Duration | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** This value is the most bytes of a body that the crawler keeps. */\n readonly maxBytes?: number | undefined;\n /** This function gives the request for an input. With no function, the input is the URL. */\n readonly fetch?: ((input: Input) => string | RecipeRequest) | undefined;\n /** This function reads a captured body into documents. It is pure, and it sends no request. */\n readonly extract: RecipeExtract;\n}\n\n/** These options build the request of a recipe for one input (`Recipe.request`). */\nexport interface RecipeRequestOptions {\n /** This value replaces the `maxAge` of the recipe. The value `0` asks the source again. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for a recipe of the mode `page`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n /** This name connects the captures to the job that asked for them. */\n readonly job?: string | undefined;\n /** When this signal aborts, the crawler stops the fetch. */\n readonly signal?: AbortSignal | undefined;\n /** This label goes into each capture record of the request. */\n readonly scope?: string | undefined;\n /** These labels go into each capture record of the request. They are not part of the capture id. */\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** No request starts at or after this time (milliseconds since the epoch, on the clock of the crawler). */\n readonly deadline?: number | undefined;\n}\n\n/** A recipe that `defineRecipe` made. Give it to `runRecipe`, to `registerRecipe` or to `openCrawler`. */\nexport interface Recipe<Input = string> {\n readonly name: string;\n readonly description: string | null;\n readonly mode: \"api\" | \"page\";\n readonly accept: string;\n /**\n * This extractor reads the captures of the recipe. It checks the documents of the definition.\n *\n * @beta\n */\n readonly extractor: Extractor;\n /**\n * This method gives the request of the crawler for one input. A value that is not a URL throws a `TypeError`.\n *\n * @beta\n */\n request(input: Input, options?: RecipeRequestOptions): FetchRequest;\n}\n\n/**\n * This function reads a body as JSON, in the encoding that the response declares. A body that is\n * not JSON (a page about maintenance, or a login page) throws an error that names the URL and the\n * content type. In an extractor, the runtime then reports that error.\n */\nexport const readJson = (body: Uint8Array, capture: RecipeCapture): unknown => {\n const text = decodeBody(body, capture.contentType);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw new Error(\n `${capture.url} answered ${capture.contentType ?? \"a body of no stated type\"}, not JSON`,\n );\n }\n};\n\n/**\n * These recipe names belong to the crawler: the page reader, the archived fallback, robots.txt,\n * and the sitemaps and feeds of `discover`. A recipe cannot use them.\n */\nexport const RESERVED_RECIPES: readonly string[] = [\n \"page\",\n \"archive-copy\",\n \"archive-index\",\n \"robots.txt\",\n \"sitemap\",\n \"feed\",\n];\n\n/**\n * These are the limits of a recipe.\n *\n * @beta\n */\nexport const RECIPE_LIMITS: {\n /** The longest recipe name. */\n readonly nameChars: number;\n /** The longest document id. */\n readonly docIdChars: number;\n} = { nameChars: 64, docIdChars: 2048 };\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\nconst PAGE_ACCEPT = \"text/html,application/xhtml+xml;q=0.9,*/*;q=0.5\";\nconst API_ACCEPT = \"application/json\";\nconst AI_INPUTS: readonly AiInput[] = [\"yes\", \"no\", \"unset\"];\n\n/** This function tells what is wrong with one document of an extractor, or gives undefined. */\nconst faultOf = (value: unknown, seen: Set<string>): string | undefined => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return \"a document must be an object\";\n const doc = value as Record<string, unknown>;\n const id = doc[\"doc\"];\n if (typeof id !== \"string\" || id.length === 0 || id.length > RECIPE_LIMITS.docIdChars)\n return `doc must be a text of 1 to ${String(RECIPE_LIMITS.docIdChars)} characters`;\n // the archived fallback labels the copies of third parties, and only it makes these\n if (id.startsWith(\"archive:\"))\n return `the id ${id} starts with archive:, which is for the archived copies`;\n if (seen.has(id)) return `two documents have the id ${id}`;\n seen.add(id);\n const kind = doc[\"kind\"];\n if (typeof kind !== \"string\" || kind.length === 0) return \"kind must be a text that is not empty\";\n if (kind === \"archived\") return \"the kind archived is for the archived copies\";\n if (typeof doc[\"title\"] !== \"string\") return \"title must be a text\";\n if (typeof doc[\"text\"] !== \"string\") return \"text must be a text\";\n if (doc[\"url\"] !== null && typeof doc[\"url\"] !== \"string\") return \"url must be a text or null\";\n const meta = doc[\"meta\"];\n if (meta === null || typeof meta !== \"object\" || Array.isArray(meta))\n return \"meta must be an object\";\n try {\n JSON.stringify(meta);\n } catch {\n return \"meta must be JSON: no cycle and no BigInt\";\n }\n const merge = doc[\"merge\"];\n if (merge !== undefined && merge !== \"latest\" && merge !== \"richest\")\n return 'merge must be \"latest\" or \"richest\"';\n if (doc[\"full_text\"] !== undefined && typeof doc[\"full_text\"] !== \"string\")\n return \"full_text must be a text\";\n const aiInput = doc[\"ai_input\"];\n if (aiInput !== undefined && !AI_INPUTS.includes(aiInput as AiInput))\n return 'ai_input must be \"yes\", \"no\" or \"unset\"';\n return undefined;\n};\n\n/** This function gives the documents of an extractor, or throws an error that names the first fault. */\nconst checkedDocs = (name: string, docs: unknown): ReadonlyArray<ExtractedDoc> => {\n if (!Array.isArray(docs))\n throw new TypeError(`the recipe ${name} gave ${typeof docs}, not an array of documents`);\n const seen = new Set<string>();\n for (const [index, doc] of docs.entries()) {\n const fault = faultOf(doc, seen);\n if (fault !== undefined)\n throw new TypeError(\n `the recipe ${name} gave a document that is not valid (${String(index)}): ${fault}`,\n );\n }\n return docs as ReadonlyArray<ExtractedDoc>;\n};\n\n/**\n * This function declares a recipe. It checks the definition at once: a name that is not valid, a\n * reserved name or a duration that it cannot read throws an error. The extractor of the recipe\n * checks each document of `extract`. A document that is not valid makes the extractor throw, and\n * the runtime reports it as an error of the extractor.\n */\nexport const defineRecipe = <Input = string>(\n definition: RecipeDefinition<Input>,\n): Recipe<Input> => {\n const name = definition.name;\n if (typeof name !== \"string\" || name.length > RECIPE_LIMITS.nameChars || !NAME.test(name)) {\n throw new RangeError(\n `a recipe name is 1 to ${String(RECIPE_LIMITS.nameChars)} letters, digits and . _ : -, and it starts with a letter or a digit, not ${JSON.stringify(name) ?? \"undefined\"}`,\n );\n }\n if (RESERVED_RECIPES.includes(name)) {\n throw new RangeError(\n `the recipe name ${name} belongs to the crawler: give the recipe a name of its own`,\n );\n }\n if (typeof definition.extract !== \"function\") {\n throw new TypeError(\n `the recipe ${name} needs extract, a function that reads a body into documents`,\n );\n }\n const mode = definition.mode ?? \"page\";\n if (mode !== \"page\" && mode !== \"api\") {\n throw new RangeError(\n `the mode of the recipe ${name} must be \"page\" or \"api\", not ${String(mode)}`,\n );\n }\n const accept = definition.accept ?? (mode === \"api\" ? API_ACCEPT : PAGE_ACCEPT);\n const minIntervalMs =\n definition.minInterval === undefined ? undefined : durationMs(definition.minInterval);\n const maxAgeOf = (value: Duration): number | \"auto\" =>\n value === \"auto\" ? \"auto\" : durationMs(value);\n const maxAge = maxAgeOf(definition.maxAge ?? \"24h\");\n const maxBytes = definition.maxBytes;\n if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1)) {\n throw new RangeError(`maxBytes of the recipe ${name} must be a whole number of 1 or more`);\n }\n const extract = definition.extract;\n const extractor: Extractor = async (body, capture) =>\n checkedDocs(name, await extract(body, { url: capture.url, contentType: capture.contentType }));\n const fetch = definition.fetch;\n return {\n name,\n description: definition.description ?? null,\n mode,\n accept,\n extractor,\n request(input, options = {}) {\n const asked: unknown = fetch === undefined ? input : fetch(input);\n const target = typeof asked === \"string\" ? { url: asked } : (asked as RecipeRequest | null);\n const url = target?.url;\n let parsed: URL | undefined;\n try {\n parsed = typeof url === \"string\" ? new URL(url) : undefined;\n } catch {\n parsed = undefined;\n }\n if (parsed === undefined || (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")) {\n throw new TypeError(\n `the recipe ${name} needs an http or https URL for its input, not ${JSON.stringify(url) ?? String(url)}`,\n );\n }\n return {\n url: parsed.href,\n mode,\n recipe: name,\n accept: target?.accept ?? accept,\n headers: target?.headers,\n secretParams: target?.secretParams,\n minIntervalMs,\n maxAgeMs: options.maxAge === undefined ? maxAge : maxAgeOf(options.maxAge),\n maxBytes,\n onBehalfOf: options.onBehalfOf,\n job: options.job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline: options.deadline,\n };\n },\n };\n};\n\n/**\n * This function gives the extractor of a recipe to the extractors of a runtime. A second\n * registration of the same recipe does nothing. A different extractor with the same name throws\n * an error, because `reindex` must read each capture with one extractor.\n *\n * @beta\n */\nexport const registerRecipe = <Input>(extractors: Extractors, recipe: Recipe<Input>): void => {\n const known = extractors.get(recipe.name);\n if (known === recipe.extractor) return;\n if (known !== undefined) {\n throw new Error(\n `the recipe ${recipe.name} has a different extractor in this runtime: give each recipe a name of its own`,\n );\n }\n extractors.register(recipe.name, recipe.extractor);\n};\n\n/** These options control one run of a recipe. */\nexport interface RecipeRunOptions extends Omit<RecipeRequestOptions, \"deadline\"> {\n /** No request starts after this time from the start of the run, for example `\"30s\"`. */\n readonly budget?: Duration | undefined;\n /** This value is true when a person gave this input directly. It is the only way to see a held-back document. The crawler logs it. */\n readonly userProvided?: boolean | undefined;\n /**\n * The value `archive` gives a copy from a public web archive when the site refuses the page or is\n * down. Only a recipe of the mode `page` takes it. The page reader reads the copy.\n */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n /** The value true also gives an archived copy of a page that the current robots.txt disallows. */\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** One document of a run of a recipe: the version of the capture of the run. */\nexport interface RecipeDoc {\n readonly doc: string;\n readonly kind: string;\n /** This value is the title. A held-back document shows no title. */\n readonly title: string;\n readonly url: string | null;\n /** This value is the metadata. A held-back document shows only the structural fields. */\n readonly meta: Readonly<Record<string, unknown>>;\n /** This value is the length of the text. `read` gives the text. */\n readonly chars: number;\n /** This id is the capture of this version. A citation names it. */\n readonly capture: string;\n readonly fetched_at: string;\n readonly held_back: boolean;\n /** This value tells that the document is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n}\n\n/** The result of `runRecipe`. */\nexport interface RecipeResult {\n readonly recipe: string;\n /** This URL is the URL of the capture. Its secrets show as `REDACTED`. */\n readonly url: string;\n readonly outcome: string;\n readonly status: number;\n /** These documents came from the capture of the run, in the order of the extractor. */\n readonly docs: readonly RecipeDoc[];\n /** This id is the capture of the documents. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n /** This value is true when the stored copy answered, and the crawler sent no request. */\n readonly from_cache: boolean;\n /** This value is true when a document is held back. */\n readonly held_back: boolean;\n /** This text is the error of the extractor, when it threw for the capture. */\n readonly error: string | null;\n /** This value tells that the documents are an archived copy, not a fresh fetch. */\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\n/** A recipe operates on a runtime, or on a crawler that has one (`crawler.runtime`). */\nexport type RecipeTarget = CrawlRuntime | { readonly runtime: CrawlRuntime };\n\n/** This function gives the runtime of a target. */\nexport const runtimeOf = (target: RecipeTarget): CrawlRuntime =>\n \"crawler\" in target ? target : target.runtime;\n\n/** This function gives the deadline of a budget, on the clock of the runtime. */\nexport const deadlineOf = (\n runtime: CrawlRuntime,\n budget: Duration | undefined,\n): number | undefined =>\n budget === undefined ? undefined : Date.parse(runtime.now()) + durationMs(budget);\n\n/** This function gives one document of a run, with the rule for a held-back document. */\nconst recipeDoc = async (\n runtime: CrawlRuntime,\n doc: Doc,\n capture: string | undefined,\n userProvided: boolean,\n action: string,\n): Promise<RecipeDoc> => {\n const current = runtime.index.get(doc.doc) ?? doc;\n const version: VersionText | Doc =\n (capture === undefined ? undefined : runtime.index.versionText(doc.doc, capture)) ?? current;\n const aiInput: AiInput =\n current.ai_input === \"no\" || version.ai_input === \"no\" ? \"no\" : version.ai_input;\n const held = isHeldBack({ ai_input: aiInput }, userProvided);\n if (aiInput === \"no\" && userProvided) await recordOverride(runtime, current, action);\n const archived = archivedOf(version.meta);\n return {\n doc: doc.doc,\n kind: version.kind,\n title: held ? \"\" : version.title,\n url: version.url,\n meta: held ? heldBackMeta(version.meta) : version.meta,\n chars: version.text.length,\n capture: version.capture,\n fetched_at: version.fetched_at,\n held_back: held,\n ...(archived === undefined ? {} : { archived }),\n };\n};\n\nconst noteOf = (parts: ReadonlyArray<string | null | undefined>): string | null => {\n const kept = parts.filter((part): part is string => typeof part === \"string\" && part.length > 0);\n return kept.length > 0 ? kept.join(\"; \") : null;\n};\n\n/**\n * This function starts a recipe for one input. It fetches the request through the crawler, and it\n * reads the capture with the extractor of the recipe. It gives the documents of that capture.\n * These are its rules:\n *\n * - The runtime registers the recipe the first time that it gets it. Give the recipe to\n * `openCrawler` too, so that `reindex` reads its captures before the first fetch.\n * - A stored copy younger than `maxAge` answers with no request. When the extractor cannot read a\n * stored copy, the crawler asks the source one more time.\n * - An extractor that throws gives no document, and `error` tells why. The fetch still succeeds.\n * - A document that asked not to be AI input shows no title and only its structural metadata,\n * unless `userProvided`. The crawler logs each `userProvided` read of a held-back document.\n * - With `fallback: \"archive\"`, a page that the site refuses gets an archived copy, with\n * `archived`. The page reader reads the copy. The extractor of the recipe reads only live\n * captures. Thus its documents do not mix a live answer and an old copy of a third party.\n */\nexport const runRecipe = async <Input>(\n target: RecipeTarget,\n recipe: Recipe<Input>,\n input: Input,\n options: RecipeRunOptions = {},\n): Promise<RecipeResult> => {\n const runtime = runtimeOf(target);\n if (options.fallback === \"archive\" && recipe.mode !== \"page\") {\n throw new RangeError(\n `the recipe ${recipe.name} reads an API: an archived copy is for a page, so give fallback only to a recipe of the mode page`,\n );\n }\n registerRecipe(runtime.extractors, recipe);\n const deadline = deadlineOf(runtime, options.budget);\n const request = recipe.request(input, { ...options, deadline });\n let indexed: Indexed = await fetchAndIndex(runtime, request);\n // a stored answer that the extractor cannot read is no answer: it would give the same error until maxAge\n if (indexed.error !== undefined && indexed.blocked === undefined && indexed.fetched.fromCache) {\n indexed = await fetchAndIndex(runtime, { ...request, maxAgeMs: 0 });\n }\n const userProvided = options.userProvided ?? false;\n const action = options.job ?? `recipe ${recipe.name}`;\n const fetched = indexed.fetched;\n const notes: Array<string | undefined> = [fetched.note, indexed.error];\n if (indexed.docs.length === 0 && options.fallback === \"archive\") {\n const reason = fallbackReason(indexed);\n if (reason !== undefined) {\n const page: PageOptions = {\n render: \"never\",\n maxAgeMs: request.maxAgeMs,\n onBehalfOf: request.onBehalfOf,\n job: request.job,\n signal: request.signal,\n scope: request.scope,\n labels: request.labels,\n deadline,\n fallback: \"archive\",\n archiveDespiteRobots: options.archiveDespiteRobots,\n };\n const answer = await archivedCopy(runtime, request.url, reason, page);\n if (answer.doc !== undefined && answer.archived !== undefined) {\n const doc = await recipeDoc(runtime, answer.doc, answer.doc.capture, userProvided, action);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs: [doc],\n capture: doc.capture,\n fetched_at: doc.fetched_at,\n from_cache: answer.fromCache,\n held_back: doc.held_back,\n error: indexed.error ?? null,\n archived: answer.archived,\n note: noteOf([\n ...notes,\n ...answer.notes,\n \"the page reader read the archived copy, not the extractor of the recipe\",\n doc.held_back ? HELD_BACK : undefined,\n ]),\n };\n }\n notes.push(...answer.notes);\n }\n }\n const capture = fetched.capture;\n const docs: RecipeDoc[] = [];\n for (const doc of indexed.docs)\n docs.push(await recipeDoc(runtime, doc, capture, userProvided, action));\n const held = docs.some((doc) => doc.held_back);\n return {\n recipe: recipe.name,\n url: fetched.url,\n outcome: fetched.outcome,\n status: fetched.status,\n docs,\n capture: docs[0]?.capture ?? capture ?? null,\n fetched_at: docs[0]?.fetched_at ?? fetched.fetchedAt ?? null,\n from_cache: fetched.fromCache,\n held_back: held,\n error: indexed.error ?? null,\n note: noteOf([...notes, held ? HELD_BACK : undefined]),\n };\n};\n"],"mappings":";;;;;;;;;AAwHA,MAAa,YAAY,MAAkB,YAAoC;CAC7E,MAAM,OAAO,WAAW,MAAM,QAAQ,WAAW;CACjD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,MACR,GAAG,QAAQ,IAAI,YAAY,QAAQ,eAAe,2BAA2B,WAC/E;CACF;AACF;;;;;AAMA,MAAa,mBAAsC;CACjD;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAa,gBAKT;CAAE,WAAW;CAAI,YAAY;AAAK;AAEtC,MAAM,OAAO;AACb,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,YAAgC;CAAC;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EAC5B;CACF;CACA,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAoB,CAAC;CAC3B,KAAK,MAAM,OAAO,QAAQ,MACxB,KAAK,KAAK,MAAM,UAAU,SAAS,KAAK,SAAS,cAAc,MAAM,CAAC;CACxE,MAAM,OAAO,KAAK,MAAM,QAAQ,IAAI,SAAS;CAC7C,OAAO;EACL,QAAQ,OAAO;EACf,KAAK,QAAQ;EACb,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB;EACA,SAAS,KAAK,EAAE,EAAE,WAAW,WAAW;EACxC,YAAY,KAAK,EAAE,EAAE,cAAc,QAAQ,aAAa;EACxD,YAAY,QAAQ;EACpB,WAAW;EACX,OAAO,QAAQ,SAAS;EACxB,MAAM,OAAO,CAAC,GAAG,OAAO,OAAO,YAAY,KAAA,CAAS,CAAC;CACvD;AACF"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { i as durationMs } from "./version-
|
|
2
|
-
import { a as fetchPage, c as isHeldBack, d as recordOverride, n as HELD_BACK, y as archivedOf } from "./runtime-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { i as durationMs } from "./version-DxUGcHQr.mjs";
|
|
2
|
+
import { a as fetchPage, c as isHeldBack, d as recordOverride, n as HELD_BACK, y as archivedOf } from "./runtime-BVC7iOG4.mjs";
|
|
3
|
+
import { decodeBody } from "./text.mjs";
|
|
4
|
+
import { extractPage, typesOf } from "./html.mjs";
|
|
5
|
+
import { c as runtimeOf, r as deadlineOf } from "./recipe-BO3V_1Kr.mjs";
|
|
5
6
|
import { DAYS, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText } from "./hours.mjs";
|
|
6
7
|
// src/recipe-venue.ts
|
|
7
8
|
/**
|
|
@@ -909,4 +910,4 @@ const readProduct = async (target, url, options = {}) => {
|
|
|
909
910
|
};
|
|
910
911
|
export { readAmount as a, locationMatches as c, readVenue as d, venueReadingsOf as f, productOf as i, namesVenue as l, pickProduct as n, readProduct as o, pickVariant as r, VENUE_LIMITS as s, PRODUCT_LIMITS as t, rankHoursLinks as u };
|
|
911
912
|
|
|
912
|
-
//# sourceMappingURL=recipe-product-
|
|
913
|
+
//# sourceMappingURL=recipe-product-BOQMCTGh.mjs.map
|