polite-crawler 0.7.11 → 0.7.12
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 +22 -0
- package/build/api.d.mts +32 -1
- package/build/api.mjs +47 -1
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-CX276Rtz.mjs → cli-daemon-CfJaQ_vG.mjs} +2 -2
- package/build/{cli-daemon-CX276Rtz.mjs.map → cli-daemon-CfJaQ_vG.mjs.map} +1 -1
- package/build/{cli-recipes-DBZzjwDF.mjs → cli-recipes-Bp_LMzOR.mjs} +2 -2
- package/build/{cli-recipes-DBZzjwDF.mjs.map → cli-recipes-Bp_LMzOR.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-Ds_tQTbe.mjs → daemon-B7SbxQS2.mjs} +3 -3
- package/build/{daemon-Ds_tQTbe.mjs.map → daemon-B7SbxQS2.mjs.map} +1 -1
- package/build/{diff-CedQOqWF.mjs → diff-D0fCuqm-.mjs} +2 -2
- package/build/{diff-CedQOqWF.mjs.map → diff-D0fCuqm-.mjs.map} +1 -1
- package/build/{extract-BaYDYK4l.mjs → extract-BQLuBe6Z.mjs} +2 -2
- package/build/{extract-BaYDYK4l.mjs.map → extract-BQLuBe6Z.mjs.map} +1 -1
- package/build/index.d.mts +1 -1
- package/build/index.mjs +10 -10
- package/build/{open-B-VbHm5U.mjs → open-D5ET6_f4.mjs} +6 -6
- package/build/{open-B-VbHm5U.mjs.map → open-D5ET6_f4.mjs.map} +1 -1
- package/build/{recipe-BbavaUG2.mjs → recipe-DglmR882.mjs} +3 -3
- package/build/{recipe-BbavaUG2.mjs.map → recipe-DglmR882.mjs.map} +1 -1
- package/build/{recipe-product-CpQl83YU.mjs → recipe-product-H05CkiNF.mjs} +4 -4
- package/build/{recipe-product-CpQl83YU.mjs.map → recipe-product-H05CkiNF.mjs.map} +1 -1
- package/build/{runtime-tMl2now7.mjs → runtime-B6bhQ0zb.mjs} +2 -2
- package/build/{runtime-tMl2now7.mjs.map → runtime-B6bhQ0zb.mjs.map} +1 -1
- package/build/{version-B1sAEHHw.mjs → version-C_fke4iU.mjs} +2 -2
- package/build/{version-B1sAEHHw.mjs.map → version-C_fke4iU.mjs.map} +1 -1
- package/build/{wacz-ZXgVsmzT.mjs → wacz-D2Klun_5.mjs} +3 -3
- package/build/{wacz-ZXgVsmzT.mjs.map → wacz-D2Klun_5.mjs.map} +1 -1
- package/build/{warc-6l_5qZF-.mjs → warc-Co_sZew8.mjs} +2 -2
- package/build/{warc-6l_5qZF-.mjs.map → warc-Co_sZew8.mjs.map} +1 -1
- package/package.json +1 -1
package/build/api.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.mjs","names":[],"sources":["../src/api-error.ts","../src/quota.ts","../src/kept.ts","../src/kept-seal.ts","../src/api.ts"],"sourcesContent":["/**\n * The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import\n * it and do not import each other.\n */\n\n/**\n * An error of the send or of the token. The `redact` function of the send examined its message.\n *\n * @beta\n */\nexport class ApiError extends Error {\n override readonly name: string = \"ApiError\";\n}\n\n/**\n * The names of `ApiError` and of each class that extends it. A new class of error adds its name here,\n * and the test of the guards fails when it does not.\n */\nconst NAMES: ReadonlySet<string> = new Set([\"ApiError\", \"QuotaError\"]);\n\n/**\n * This function tells if a value is an error of `polite-crawler/api`: an `ApiError`, or a\n * `QuotaError`, which extends it. The error can come from this copy of the package or from another\n * copy, of this version or of an earlier one. `instanceof` is false across two copies, so the\n * function also accepts an `Error` with one of their names. Thus it also accepts an error of a\n * different library with one of these names. Use it on the errors of a call through\n * `polite-crawler/api`.\n *\n * @beta\n */\nexport const isApiError = (value: unknown): value is ApiError =>\n value instanceof ApiError || (value instanceof Error && NAMES.has(value.name));\n","/**\n * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day\n * or month in a time zone, or a rolling window. The gate counts each call before it starts, and it\n * refuses a call over the quota before the provider does. `withQuota` puts a gate on any async\n * function: a `fetch`, a transport or a different client.\n *\n * The count is not lower than the count of the provider. A rolling window puts each call in a time\n * bucket, and a bucket counts until all of it is out of the window. The answer of the provider can\n * make the count larger, but not smaller.\n *\n * The count of a window comes from the keyed quota of `@mark1russell7/service/limiter`, and a list\n * of gates takes its units with `takeQuotas` of that module. The module imports no Node.js module,\n * so a browser can use it. Each export is beta.\n */\nimport type {\n QuotaChange,\n QuotaPart,\n QuotaRefused,\n QuotaSpec,\n QuotaState as LimiterState,\n QuotaStore as LimiterStore,\n QuotaVerdict,\n} from \"@mark1russell7/service/limiter\";\nimport { keyedQuota, quotaProblems, takeQuotas } from \"@mark1russell7/service/limiter\";\nimport { ApiError } from \"./api-error.ts\";\nimport { parseRetryAfter } from \"./classify.ts\";\nimport type { QuotaRecord, QuotaStore } from \"./politeness.ts\";\n\n/**\n * The window of a quota.\n *\n * - `rolling`: the units of the last `ms` milliseconds. Use it when the provider does not tell when\n * its count starts again. It is stricter than each fixed window of the same length or shorter.\n * - `calendar`: the units of a day or a month in the IANA time zone `timeZone`. A window starts at\n * the hour `hour` (default 0) of the first day, in that zone. When the clock jumps over that hour,\n * the window starts at the jump.\n *\n * @beta\n */\nexport type QuotaWindow =\n | {\n readonly kind: \"rolling\";\n readonly ms: number;\n /** The window has this count of time buckets. The default is 60. Each call counts until all of its bucket is out of the window. */\n readonly buckets?: number | undefined;\n }\n | {\n readonly kind: \"calendar\";\n readonly unit: \"day\" | \"month\";\n /** This value is an IANA time zone, for example `America/Chicago` or `UTC`. */\n readonly timeZone: string;\n /** This value is the hour of the start of a window, from 0 to 23. The default is 0. */\n readonly hour?: number | undefined;\n };\n\n/**\n * A quota of one API key: at most `limit` units in each window.\n *\n * @beta\n */\nexport interface Quota {\n /**\n * This value names the quota in a message, for example `Example API requests`. A store keeps a\n * record for each name and key, so give each quota of a key a different name.\n */\n readonly name: string;\n /** This value is the count of units that the provider gives in one window. */\n readonly limit: number;\n /** The gate keeps this count of units unused. The default is 0. */\n readonly reserve?: number | undefined;\n readonly window: QuotaWindow;\n}\n\n/**\n * What an answer of the provider tells of its count.\n *\n * @beta\n */\nexport interface QuotaReading {\n /** This value is the count of units that the provider gives before its next reset. */\n readonly remaining?: number | undefined;\n /**\n * This value is the time of the next reset of the provider, in milliseconds since the epoch. When\n * `remaining` is 0 or is not there, the gate refuses each call until this time.\n */\n readonly resetAt?: number | undefined;\n}\n\n/**\n * The state of a quota at one time.\n *\n * @beta\n */\nexport interface QuotaState {\n /** This value is the count of units in the window. */\n readonly used: number;\n /**\n * This value is the count of units that the gate gives: the limit, less the reserve and `used`.\n * It is 0 while the provider refuses the key.\n */\n readonly left: number;\n /** The units come back from this time, in milliseconds since the epoch. With no unit in the window, it is not there. */\n readonly resetAt?: number | undefined;\n /** The provider refused the key until this time, in milliseconds since the epoch. */\n readonly blockedUntil?: number | undefined;\n /**\n * This value is the time of the state, in milliseconds since the epoch. For the state that `take`\n * gives, it is the time of the units of the call, which `giveBack` needs.\n */\n readonly at?: number | undefined;\n}\n\n/**\n * The refusal of a call over its quota. The gate refused the call before the call started.\n *\n * @beta\n */\nexport class QuotaError extends ApiError {\n override readonly name: string = \"QuotaError\";\n /** This value is the key of the quota. */\n readonly key: string;\n /** The gate gives units again from this time, in milliseconds since the epoch. */\n readonly resetAt: number;\n\n constructor(message: string, key: string, resetAt: number) {\n super(message);\n this.key = key;\n this.resetAt = resetAt;\n }\n}\n\n/**\n * This function tells if a value is a `QuotaError`. The error can come from this copy of the package\n * or from another copy, of this version or of an earlier one. `instanceof` is false across two copies.\n * So the function also accepts an `Error` named `QuotaError`, with a string `key` and a finite number\n * `resetAt`. A package that gets a transport of `withQuota` uses it to tell a refusal of the quota from\n * another failure. That package needs no dependency on this package.\n *\n * @beta\n */\nexport const isQuotaError = (value: unknown): value is QuotaError =>\n value instanceof QuotaError ||\n (value instanceof Error &&\n value.name === \"QuotaError\" &&\n typeof (value as { readonly key?: unknown }).key === \"string\" &&\n Number.isFinite((value as { readonly resetAt?: unknown }).resetAt));\n\nconst DEFAULT_BUCKETS = 60;\n/** The largest time of a `Date`, in milliseconds from the epoch. */\nconst MAX_TIME = 8.64e15;\n\nconst iso = (t: number): string => new Date(t).toISOString();\n\nconst isTime = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;\n\n/** This function refuses a cost that is not a finite number of 0 or more. */\nconst checkCost = (cost: number, of: string): void => {\n if (!Number.isFinite(cost) || cost < 0) {\n throw new ApiError(`The cost of ${of} is not a number of 0 or more: ${String(cost)}.`);\n }\n};\n\n/**\n * This function gives the spec of the limiter for a quota. Without `maxBlockMs`, a block ends at the\n * latest when the bucket of its reading stops counting: one window.\n */\nconst specOf = (quota: Quota, maxBlockMs: number | undefined): QuotaSpec => {\n const { window } = quota;\n return {\n limit: { value: quota.limit, unit: \"count\" },\n reserve: { value: quota.reserve ?? 0, unit: \"count\" },\n window:\n window.kind === \"rolling\"\n ? {\n kind: \"rolling\",\n span: { value: window.ms, unit: \"ms\" },\n buckets: { value: window.buckets ?? DEFAULT_BUCKETS, unit: \"count\" },\n }\n : {\n kind: \"calendar\",\n unit: window.unit,\n zone: window.timeZone,\n start: { value: window.hour ?? 0, unit: \"h\" },\n },\n maxBlock: maxBlockMs === undefined ? \"window\" : { value: maxBlockMs, unit: \"ms\" },\n };\n};\n\n/**\n * This function gives a store of the limiter over a store of this package. The two stores keep one\n * form of record, so a record of an earlier version stays valid.\n */\nconst limiterStore = (store: QuotaStore): LimiterStore<true> => ({\n sync: true,\n change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): T {\n let result: { readonly value: T } | undefined;\n store.changeQuota(quota, key, (stored) => {\n const next = step(stored);\n result = { value: next.result };\n return next.record;\n });\n if (result === undefined) {\n throw new ApiError(`The store did not change the record of the quota ${quota} of ${key}.`);\n }\n return result.value;\n },\n});\n\n/**\n * The gate of one key. It counts the units of the calls, and it refuses a call over the quota.\n *\n * @beta\n */\nexport interface QuotaGate {\n readonly quota: Quota;\n readonly key: string;\n /**\n * This method counts `cost` units (default 1) for a call that starts at this time, and gives the\n * state. A cost of 0 counts nothing and refuses nothing.\n *\n * @throws QuotaError when the units are more than `left`, or when the provider refused the key.\n * The gate then counts nothing. Its `resetAt` is the end of the refusal of the provider, or a later\n * time when the window has the units of the call.\n * @throws ApiError when the cost is negative or not finite, or when it is more than the quota\n * gives in one window.\n */\n take(cost?: number): QuotaState;\n /** This method adds what an answer of the provider tells. The count can only become larger. */\n note(reading: QuotaReading): QuotaState;\n /** This method gives the state at this time, and changes nothing. */\n state(): QuotaState;\n /**\n * This method gives back `cost` units that `take` counted at the time `at` (the `at` of its\n * state), for a call that did not start. `withQuota` uses it for a list of gates. When the gate\n * read the count of the provider at the time `at` or later, the method changes nothing. That\n * reading can include the units. So the count does not become lower than the count of the provider\n * at any time. A gate made by `quotaGate` has this method.\n *\n * @throws ApiError when the cost is negative or not finite, or when `at` is not a time.\n */\n giveBack?(cost: number, at: number): QuotaState;\n}\n\n/**\n * The options of `quotaGate`.\n *\n * @beta\n */\nexport interface QuotaGateOptions {\n /**\n * This value names the key, for example `example:account-1`. A store keeps it as text, so do not\n * give the secret of the key. Give one name to each account that the provider counts.\n */\n readonly key: string;\n /** This store keeps the records. The default is a new `memoryQuotaStore`. */\n readonly store?: QuotaStore | undefined;\n /** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */\n readonly now?: (() => number) | undefined;\n /**\n * This value is the longest block that a reset of the provider can set, in milliseconds. A reading\n * with a later reset blocks the key until the time of the reading plus this value. The default is\n * one window. Then the block ends at the latest when the units of a call at the time of the\n * reading go free. Thus a reset header in a wrong form cannot stop a key for much longer than the\n * window of the quota.\n */\n readonly maxBlockMs?: number | undefined;\n}\n\n/**\n * This function makes the gate of one key.\n *\n * @throws ApiError when the quota, its window or `maxBlockMs` is not valid. The message gives each\n * problem.\n * @beta\n */\nexport function quotaGate(quota: Quota, options: QuotaGateOptions): QuotaGate {\n const { limit, name } = quota;\n const reserve = quota.reserve ?? 0;\n const { key, maxBlockMs } = options;\n const spec = specOf(quota, maxBlockMs);\n const problems = quotaProblems(name, spec);\n if (problems.length > 0) {\n throw new ApiError(`The quota ${name} is not valid: ${problems.join(\"; \")}.`);\n }\n // the record of the quota and the key, so two quotas of one key in one store count apart\n const limiter = keyedQuota(name, spec, limiterStore(options.store ?? memoryQuotaStore()), {\n time: \"wall\",\n now: options.now ?? Date.now,\n });\n /** This function gives the error of a refused call. */\n const refusal = (verdict: QuotaRefused, cost: number): ApiError => {\n if (verdict.cause === \"capacity\") {\n return new ApiError(\n `A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(verdict.capacity)}.`,\n );\n }\n const { resetAt, state } = verdict;\n const { blockedUntil } = state;\n if (verdict.cause === \"provider\" && blockedUntil !== undefined) {\n return new QuotaError(\n `The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` +\n (resetAt > blockedUntil\n ? ` The window has the units of the call at ${iso(resetAt)}.`\n : \"\"),\n key,\n resetAt,\n );\n }\n return new QuotaError(\n `The quota ${name} of ${key} refused a call of ${String(cost)} units: ` +\n `${String(state.used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. ` +\n `It gives units again at ${iso(resetAt)}.`,\n key,\n resetAt,\n );\n };\n return {\n quota,\n key,\n take(cost = 1) {\n checkCost(cost, \"a call\");\n // a call of cost 0 is a call that the provider does not count, for example a read of a receipt\n const verdict = limiter.take(key, cost);\n if (!verdict.allowed) throw refusal(verdict, cost);\n return verdict.state;\n },\n note: (reading) => limiter.note(key, reading),\n state: () => limiter.state(key),\n giveBack(cost, at) {\n checkCost(cost, \"a give-back\");\n if (!isTime(at)) throw new ApiError(`The time of a give-back is not a time: ${String(at)}.`);\n return limiter.giveBack(key, cost, at);\n },\n };\n}\n\n/**\n * This function makes a store of records in memory. Each gate of one process can share it.\n *\n * @beta\n */\nexport function memoryQuotaStore(): QuotaStore {\n const records = new Map<string, Map<string, QuotaRecord>>();\n return {\n changeQuota(quota, key, step) {\n let keys = records.get(quota);\n if (keys === undefined) {\n keys = new Map();\n records.set(quota, keys);\n }\n const next = step(keys.get(key));\n keys.set(key, next);\n return next;\n },\n };\n}\n\n/**\n * The options of `withQuota`.\n *\n * @beta\n */\nexport interface WithQuotaOptions<A extends readonly unknown[], R> {\n /**\n * This value is the count of units of a call, or a function of the arguments that gives it. The\n * default is 1. Give 0 for a call that the provider does not count: the gate then does not refuse it.\n */\n readonly cost?: number | ((...args: A) => number) | undefined;\n /**\n * This function reads what the result of a call tells of the count of the provider, for example\n * with `readQuotaHeaders`. With a list of gates, it reads once for each gate. A provider often\n * tells the count of one quota only: then give its reading for that gate, and undefined for the\n * other gates.\n */\n readonly read?: ((result: R, gate: QuotaGate) => QuotaReading | undefined) | undefined;\n /**\n * This function gets an error of `read` or of the store after the call. The call went out, so\n * `withQuota` gives its result. It does not throw, because a retry after a throw sends the call\n * again. It also gets an error of a give-back of a list, and the caller still gets the refusal.\n * With no function, the error is lost. An error that this function throws is lost too.\n */\n readonly onError?: ((error: unknown) => void) | undefined;\n}\n\nconst isGateList = (gate: QuotaGate | readonly QuotaGate[]): gate is readonly QuotaGate[] =>\n Array.isArray(gate);\n\n/** This function checks the gates of `withQuota`: a list has gates that can give back units. */\nconst gateList = (gate: QuotaGate | readonly QuotaGate[]): readonly QuotaGate[] => {\n if (!isGateList(gate)) return [gate];\n if (gate.length === 0) throw new ApiError(\"The list of gates of withQuota is empty.\");\n const seen = new Set<string>();\n for (const each of gate) {\n const named = `the quota ${each.quota.name} of ${each.key}`;\n if (gate.length > 1 && each.giveBack === undefined) {\n throw new ApiError(`The gate of ${named} cannot give back units, so it cannot be in a list.`);\n }\n // a store keeps one record for each name and key, so two such gates count each call twice;\n // a gate does not show its store, so two gates of one name and key on two stores are refused too\n const id = JSON.stringify([each.quota.name, each.key]);\n if (seen.has(id)) {\n throw new ApiError(`Two gates of the list have ${named}. Give each quota a different name.`);\n }\n seen.add(id);\n }\n return [...gate];\n};\n\n/**\n * This function gives an error to `onError`. An error that `onError` throws is lost. Thus the other\n * give-backs still occur, and the caller gets the refusal or the result of the call.\n */\nconst report = (onError: ((error: unknown) => void) | undefined, error: unknown): void => {\n try {\n onError?.(error);\n } catch {\n // the refusal or the result of the call is more important than an error of the report\n }\n};\n\n/** This function gives a state of a gate in the form of the limiter. A state with no time gets the time NaN. */\nconst limiterState = (state: QuotaState): LimiterState => ({\n ...state,\n at: state.at ?? Number.NaN,\n});\n\n/**\n * This function gives a gate of a list as a part of `takeQuotas`. The part keeps the `QuotaError` of\n * its refusal in `refusals`, because the caller gets that error. A `QuotaError` has no state, so a\n * refused part reads the state of its gate. A give-back of units with no time fails, and `onError`\n * gets its error.\n */\nconst partOf = (\n gate: QuotaGate,\n units: number,\n index: number,\n refusals: Map<number, QuotaError>,\n): QuotaPart<true> => ({\n key: gate.key,\n units,\n quota: {\n sync: true,\n take: (_key, cost = 1): QuotaVerdict => {\n try {\n return { allowed: true, state: limiterState(gate.take(cost)) };\n } catch (error) {\n if (!isQuotaError(error)) throw error;\n refusals.set(index, error);\n const state = limiterState(gate.state());\n const wait = Number.isNaN(state.at) ? 0 : Math.max(0, error.resetAt - state.at);\n return {\n allowed: false,\n cause: state.blockedUntil === undefined ? \"limit\" : \"provider\",\n resetAt: error.resetAt,\n retryAfter: { value: wait, unit: \"ms\" },\n state,\n };\n }\n },\n giveBack: (_key, cost, at) => {\n if (Number.isNaN(at)) {\n throw new ApiError(\n `The gate of the quota ${gate.quota.name} of ${gate.key} gave no time for its units, so it cannot give them back.`,\n );\n }\n return limiterState(gate.giveBack?.(cost, at) ?? gate.state());\n },\n },\n});\n\n/**\n * This function counts `cost` units in each gate, or in none. One gate gives its refusal as it is. A\n * list takes with `takeQuotas`: when a gate refuses, the gates that counted give back the units,\n * because the call did not start. The next gates still answer, so the `QuotaError` has the latest\n * time of a reset.\n */\nconst takeAll = (\n gates: readonly QuotaGate[],\n cost: number,\n onError: ((error: unknown) => void) | undefined,\n): void => {\n const [only] = gates;\n if (gates.length === 1 && only !== undefined) {\n only.take(cost);\n return;\n }\n const refusals = new Map<number, QuotaError>();\n const verdict = takeQuotas(\n gates.map((gate, index) => partOf(gate, cost, index, refusals)),\n { onGiveBackError: (error) => report(onError, error) },\n );\n if (!verdict.allowed) {\n throw (\n refusals.get(verdict.index) ??\n new ApiError(\"A gate of the list refused the call, but it gave no QuotaError.\")\n );\n }\n};\n\n/**\n * This function puts a gate, or a list of gates, on an async function, and keeps the type of the\n * function. Each call counts its units first. A call over the quota throws `QuotaError`, and the\n * function does not start.\n *\n * Give the result to a client that takes a function of this type. For example, `withQuota(gate,\n * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`.\n *\n * For two quotas of one key, give a list: `withQuota([perMinute, perDay], fetch)`. The list counts\n * the call in each gate or in none. Do not put one gate in the function of another. The outer gate\n * cannot know if a request went out before the inner gate refused (`send` retries). So it keeps\n * the units of the call.\n *\n * @throws ApiError when the list is empty, or when a gate of a list of two or more has no\n * `giveBack`. Also when two gates of the list have one quota name and key.\n * @beta\n */\nexport function withQuota<A extends readonly unknown[], R>(\n gate: QuotaGate | readonly QuotaGate[],\n call: (...args: A) => Promise<R>,\n options: WithQuotaOptions<A, R> = {},\n): (...args: A) => Promise<R> {\n const gates = gateList(gate);\n const { cost, read, onError } = options;\n return async (...args: A): Promise<R> => {\n takeAll(gates, typeof cost === \"function\" ? cost(...args) : (cost ?? 1), onError);\n const result = await call(...args);\n for (const each of gates) {\n try {\n const reading = read?.(result, each);\n if (reading !== undefined) each.note(reading);\n } catch (error) {\n report(onError, error);\n }\n }\n return result;\n };\n}\n\n/**\n * The names of the headers of an answer that tell the count of a provider. Each name is optional.\n *\n * @beta\n */\nexport interface QuotaHeaders {\n /** This header has the count of units that the provider gives before its reset, for example `x-ratelimit-remaining`. */\n readonly remaining?: string | undefined;\n /**\n * This header has the time of the reset, for example `x-ratelimit-reset`. The function reads its\n * form from its size. A value under 10^9 is the seconds until the reset, as `RateLimit-Reset` of\n * the IETF draft gives them. A value from 10^9 to under 10^11 is seconds since the epoch. A value\n * from 10^11 is milliseconds since the epoch.\n */\n readonly resetAt?: string | undefined;\n /**\n * This header has the seconds until the reset, or the HTTP date of the reset, as `retry-after`\n * gives them. When it has a value that the function can read, the function does not read `resetAt`.\n */\n readonly resetAfter?: string | undefined;\n}\n\nconst COUNT = /^\\d{1,15}$/;\nconst SECONDS = /^\\d{1,12}(?:\\.\\d{1,3})?$/;\nconst RESET = /^\\d{1,15}(?:\\.\\d{1,3})?$/;\n\n/**\n * A reset value under this bound is a count of seconds until the reset. As seconds since the epoch,\n * it is a time before 2001-09-09T01:46:40Z, and no reset of a provider is that early.\n */\nexport const SECONDS_SINCE_EPOCH_FROM = 1e9;\n/**\n * A reset value from this bound is in milliseconds since the epoch. As seconds since the epoch, it\n * is a time in the year 5138, and as milliseconds it is a time in 1973.\n */\nexport const MILLISECONDS_SINCE_EPOCH_FROM = 1e11;\n\n/**\n * This function gives the time of a reset, in milliseconds since the epoch, from the number of a\n * reset header. The three forms of the header do not overlap:\n *\n * - under `SECONDS_SINCE_EPOCH_FROM` (10^9): seconds until the reset, from `now`\n * - from 10^9 to under `MILLISECONDS_SINCE_EPOCH_FROM` (10^11): seconds since the epoch\n * - from 10^11: milliseconds since the epoch\n */\nexport const resetTimeOf = (value: number, now: number): number =>\n value < SECONDS_SINCE_EPOCH_FROM\n ? now + value * 1000\n : value < MILLISECONDS_SINCE_EPOCH_FROM\n ? value * 1000\n : value;\n\n/**\n * This function reads the count of a provider from the headers of an answer. `get` gives the value\n * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or\n * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of\n * `resetAfter` can also be an HTTP date, as in `Retry-After`. The value of `resetAt` can be in each\n * of three forms, which the function tells apart by their size.\n *\n * A reset with no count tells that the provider refuses the key until that time. The answer can\n * have a reset header, and no `remaining` header with a number. Then the gate stops the key until\n * the reset, also after a successful answer.\n *\n * @returns the reading, or undefined when no header has a value.\n * @beta\n */\nexport function readQuotaHeaders(\n get: (name: string) => string | null | undefined,\n names: QuotaHeaders,\n now: number,\n): QuotaReading | undefined {\n const text = (name: string | undefined): string | undefined =>\n name === undefined ? undefined : get(name.toLowerCase())?.trim();\n const value = (name: string | undefined, form: RegExp): number | undefined => {\n const found = text(name);\n return found !== undefined && form.test(found) ? Number(found) : undefined;\n };\n const remaining = value(names.remaining, COUNT);\n const at = value(names.resetAt, RESET);\n // seconds with a fraction, as some providers give, and then the two forms of Retry-After\n const afterText = text(names.resetAfter);\n const after =\n afterText === undefined\n ? undefined\n : SECONDS.test(afterText)\n ? Number(afterText) * 1000\n : parseRetryAfter(afterText, now);\n const resetAt =\n after !== undefined ? now + after : at === undefined ? undefined : resetTimeOf(at, now);\n if (remaining === undefined && resetAt === undefined) return undefined;\n return {\n ...(remaining === undefined ? {} : { remaining }),\n ...(resetAt === undefined ? {} : { resetAt }),\n };\n}\n","/**\n * Kept answers. A client keeps the last full answer of a GET with its validators. The next GET of\n * the same key is then a conditional request (RFC 9110 §13.1). An answer 304 then gives the kept\n * answer with the fields of the 304 (RFC 9111 §4.3.4). Some APIs with a rate limit do not count a\n * 304, for example the REST API of GitHub. The store is data, so a client can keep it between two\n * runs. The server examines each validator, so a kept answer goes to the client only after the\n * server tells that it is current. The module imports no Node.js module.\n */\n\n/**\n * The kept answer of one key.\n *\n * @beta\n */\nexport interface Kept {\n /** This value is the `ETag` header of the answer, when it had one. */\n readonly etag?: string | undefined;\n /** This value is the `Last-Modified` header of the answer, when it had one. */\n readonly lastModified?: string | undefined;\n /** This value is the status of the answer: 200, 203 or 204 (`KEPT_STATUSES`). */\n readonly status: number;\n /** These values are the headers that the store keeps, by name in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the answer, as text. */\n readonly body: string;\n}\n\n/**\n * A store of kept answers, by key. A `Map` is a store in memory. `keptStore` also records the\n * entries that a run uses.\n *\n * @beta\n */\nexport interface KeptStore {\n /** This function gives the kept answer of the key, or undefined when the store has none. */\n get(key: string): Kept | undefined;\n /** This function keeps the answer under the key, in place of an earlier one. */\n set(key: string, kept: Kept): void;\n}\n\n/**\n * An answer as a client reads it: its status, its headers by name in lowercase, and its body.\n *\n * @beta\n */\nexport interface KeptAnswer {\n /** The status of the answer. After a 304, it is the status of the kept answer. */\n readonly status: number;\n /** The headers of the answer, by name in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** The body of the answer as text. After a 304, it is the kept body. */\n readonly body: string;\n /** This value is true when the server answered 304 and the answer is the kept answer. */\n readonly notModified: boolean;\n}\n\n/**\n * The options of `keepAnswer`.\n *\n * @beta\n */\nexport interface KeepOptions {\n /** These names are the headers that a kept answer keeps. The default is `KEPT_HEADERS`. */\n readonly headers?: readonly string[] | undefined;\n /**\n * This value is the largest body that the store keeps, in UTF-16 code units. The default is\n * `KEPT_BODY_MAX`.\n */\n readonly maxBody?: number | undefined;\n}\n\n/**\n * The headers that a kept answer keeps when the options give no list. `link` keeps the next page\n * of a list.\n *\n * @beta\n */\nexport const KEPT_HEADERS: readonly string[] = [\"content-type\", \"etag\", \"last-modified\", \"link\"];\n\n/**\n * The largest body that a store keeps when the options give no limit: 1,048,576 UTF-16 code units.\n *\n * @beta\n */\nexport const KEPT_BODY_MAX: number = 1_048_576;\n\n/**\n * The statuses that a store keeps. The body of each is the full answer. A 206 has only a part of\n * the body, so a store does not keep it.\n *\n * @beta\n */\nexport const KEPT_STATUSES: readonly number[] = [200, 203, 204];\n\n/** These fields of a 304 tell of its empty body, so they do not go into the kept answer. */\nconst BODY_FIELDS: ReadonlySet<string> = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n/** A body of one of these media types is text, so a store can keep it as text. */\nconst TEXT_TYPE = /^\\s*(?:text\\/[\\w.+-]+|application\\/(?:[\\w.-]+\\+)?(?:json|xml))\\s*(?:;|$)/i;\n\n/** This pattern finds the charset parameter of a media type. */\nconst CHARSET = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i;\n\n/** This function gives the headers with each name in lowercase. */\nconst lower = (headers: Readonly<Record<string, string>>): Record<string, string> => {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) out[name.toLowerCase()] = value;\n return out;\n};\n\n/**\n * This function tells if the headers of a request make it conditional or partial on their own:\n * `If-None-Match`, `If-Modified-Since`, `If-Match`, `If-Unmodified-Since`, `If-Range` or\n * `Range`. The client of such a request reads the answer itself, so a store does not answer for\n * it.\n *\n * @beta\n */\nexport function hasValidator(headers: Readonly<Record<string, string>>): boolean {\n return Object.keys(headers).some((name) => {\n const n = name.toLowerCase();\n return n === \"range\" || n.startsWith(\"if-\");\n });\n}\n\n/**\n * This function tells if a body of a media type is text in UTF-8. That is a text, JSON or XML type\n * with no charset or with the charset UTF-8. A store keeps only such a body, because `text()` of\n * `fetch` reads a body as UTF-8.\n *\n * @beta\n */\nexport function isTextType(contentType: string | undefined): boolean {\n const type = contentType ?? \"\";\n if (!TEXT_TYPE.test(type)) return false;\n const charset = CHARSET.exec(type)?.[1];\n return charset === undefined || /^utf-?8$/i.test(charset);\n}\n\n/**\n * This function gives the key of a request in a store: its `accept` header and its URL. A\n * different `accept` header can give a different body, so it gets a different key.\n *\n * @beta\n */\nexport function keptKey(url: string, headers: Readonly<Record<string, string>>): string {\n return `${lower(headers)[\"accept\"] ?? \"\"} ${url}`;\n}\n\n/**\n * This function gives the headers of a conditional request: the headers of the request, and the\n * validators of the kept answer. `If-None-Match` sends its ETag, and `If-Modified-Since` sends its\n * date. The function adds no header to a request that has a validator of its own.\n *\n * @beta\n */\nexport function keptRequestHeaders(\n kept: Kept | undefined,\n headers: Readonly<Record<string, string>>,\n): Record<string, string> {\n const out: Record<string, string> = { ...headers };\n if (kept === undefined || hasValidator(headers)) return out;\n if (kept.etag !== undefined) out[\"if-none-match\"] = kept.etag;\n if (kept.lastModified !== undefined) out[\"if-modified-since\"] = kept.lastModified;\n return out;\n}\n\n/**\n * This function gives the answer that a client reads, and changes the store.\n *\n * - A 304 for a key with a kept answer gives the kept answer. Its headers get the fields of the\n * 304, as RFC 9111 §4.3.4 tells, and the store keeps the new values of its kept headers.\n * - An answer with a status of `KEPT_STATUSES` and an ETag or a date goes into the store. It needs\n * a text type in UTF-8 and a body in the limit.\n * - Each other answer is as it is, and the store does not change.\n *\n * @beta\n */\nexport function keepAnswer(\n store: KeptStore,\n key: string,\n answer: {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n },\n options: KeepOptions = {},\n): KeptAnswer {\n const names = new Set((options.headers ?? KEPT_HEADERS).map((name) => name.toLowerCase()));\n const headers = lower(answer.headers);\n const kept = store.get(key);\n if (answer.status === 304 && kept !== undefined) {\n const read: Record<string, string> = { ...kept.headers };\n const keep: Record<string, string> = { ...kept.headers };\n for (const [name, value] of Object.entries(headers)) {\n if (BODY_FIELDS.has(name)) continue;\n read[name] = value;\n if (names.has(name)) keep[name] = value;\n }\n store.set(key, {\n ...kept,\n etag: headers[\"etag\"] ?? kept.etag,\n lastModified: headers[\"last-modified\"] ?? kept.lastModified,\n headers: keep,\n });\n return { status: kept.status, headers: read, body: kept.body, notModified: true };\n }\n const etag = headers[\"etag\"];\n const lastModified = headers[\"last-modified\"];\n if (\n KEPT_STATUSES.includes(answer.status) &&\n (etag !== undefined || lastModified !== undefined) &&\n isTextType(headers[\"content-type\"]) &&\n answer.body.length <= (options.maxBody ?? KEPT_BODY_MAX)\n ) {\n const keep: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) if (names.has(name)) keep[name] = value;\n store.set(key, { etag, lastModified, status: answer.status, headers: keep, body: answer.body });\n }\n return { status: answer.status, headers, body: answer.body, notModified: false };\n}\n\n/**\n * A store of kept answers in memory that records which entries a run uses.\n *\n * @beta\n */\nexport interface KeptMemory extends KeptStore {\n /**\n * This function gives each entry that a `get` found or a `set` wrote, in the order of the first\n * use. A client that saves only these entries keeps no answer that it does not ask for again.\n */\n used(): [string, Kept][];\n}\n\n/**\n * This function makes a store of kept answers in memory, with the entries of an earlier run.\n *\n * @beta\n */\nexport function keptStore(entries: Iterable<readonly [string, Kept]> = []): KeptMemory {\n const all = new Map<string, Kept>(entries);\n const used = new Set<string>();\n return {\n get(key) {\n const kept = all.get(key);\n if (kept !== undefined) used.add(key);\n return kept;\n },\n set(key, kept) {\n all.set(key, kept);\n used.add(key);\n },\n used: () =>\n [...used].flatMap((key): [string, Kept][] => {\n const kept = all.get(key);\n return kept === undefined ? [] : [[key, kept]];\n }),\n };\n}\n\n/** This function gives a kept answer from data, or null when the data does not have its shape. */\nconst keptOf = (value: unknown): Kept | null => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n const { etag, lastModified, status, headers, body } = value as Record<string, unknown>;\n if (typeof status !== \"number\" || !KEPT_STATUSES.includes(status)) return null;\n if (typeof body !== \"string\") return null;\n if (etag !== undefined && typeof etag !== \"string\") return null;\n if (lastModified !== undefined && typeof lastModified !== \"string\") return null;\n if (etag === undefined && lastModified === undefined) return null;\n if (typeof headers !== \"object\" || headers === null || Array.isArray(headers)) return null;\n const read: Record<string, string> = {};\n for (const [name, field] of Object.entries(headers)) {\n if (typeof field !== \"string\") return null;\n read[name.toLowerCase()] = field;\n }\n return {\n etag: typeof etag === \"string\" ? etag : undefined,\n lastModified: typeof lastModified === \"string\" ? lastModified : undefined,\n status,\n headers: read,\n body,\n };\n};\n\n/**\n * This function reads the entries of a store from data, for example from the JSON of the `used`\n * entries of an earlier run. It keeps each entry with a correct shape and drops each other entry.\n * Thus damaged data gives fewer kept answers and no error.\n *\n * @beta\n */\nexport function readKept(data: unknown): [string, Kept][] {\n if (!Array.isArray(data)) return [];\n const out: [string, Kept][] = [];\n for (const entry of data) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== \"string\") continue;\n const kept = keptOf(entry[1]);\n if (kept !== null) out.push([entry[0], kept]);\n }\n return out;\n}\n","/**\n * The sealed form of a store of kept answers. Use it for a place that other people can read, for\n * example the cache of a public repository in GitHub Actions. A kept answer of a private resource\n * holds its body as text. Thus a client that saves its store in such a place seals it first.\n *\n * `sealKept` encrypts the entries with AES-256-GCM. The key comes from a secret by HKDF-SHA-256\n * (RFC 5869). Each seal has a new random salt, and the label of the use is the info. Thus two labels\n * give two keys from one secret. The format name is the first line of the bytes. It is also the\n * associated data of the cipher, so a change of the format cannot go unseen.\n *\n * Each entry is compressed alone (gzip) before the encryption. A compression of all entries together\n * puts the text of one answer in the window of another answer. Then the size of the sealed bytes can\n * tell something of a private answer to a person who controls a public answer. With one compression\n * for each entry, the text of an answer meets only its own text.\n *\n * The functions use only Web APIs (`crypto.subtle`, `CompressionStream`). Thus they operate in\n * Node.js and in a browser.\n */\nimport { readKept, type Kept } from \"./kept.ts\";\n\n/**\n * The name and the version of the sealed format. It is the first line of the sealed bytes.\n *\n * @beta\n */\nexport const KEPT_SEAL_FORMAT = \"polite-crawler-kept-sealed/1\";\n\n/**\n * The smallest secret that `sealKept` and `openKept` take, in bytes. HKDF does not slow a guess, so\n * the secret must be a random key, not a password.\n *\n * @beta\n */\nexport const KEPT_SEAL_SECRET_MIN = 16;\n\n/**\n * The options of `sealKept` and `openKept`.\n *\n * @beta\n */\nexport interface SealOptions {\n /**\n * This value is the label of the use, for example the name of the client. A store opens only with\n * the label that sealed it. Give a label when the secret has a second use. The default is \"\".\n */\n readonly label?: string | undefined;\n}\n\n/**\n * The result of `openKept`.\n *\n * @beta\n */\nexport interface OpenedKept {\n /** These values are the entries of the store. They are empty when the store does not open. */\n readonly entries: [string, Kept][];\n /** This value tells why the store gave fewer entries or none, when that occurs. */\n readonly note?: string | undefined;\n}\n\nconst SALT_BYTES = 16;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\nconst HEADER = encoder.encode(`${KEPT_SEAL_FORMAT}\\n`);\n\n/** This function gives the bytes of the secret, or throws when the secret is too short. */\nconst secretBytes = (secret: string | Uint8Array): Uint8Array<ArrayBuffer> => {\n const bytes = typeof secret === \"string\" ? encoder.encode(secret) : new Uint8Array(secret);\n if (bytes.length < KEPT_SEAL_SECRET_MIN) {\n throw new RangeError(\n `The secret of a sealed store needs ${KEPT_SEAL_SECRET_MIN} bytes or more, and it has ${bytes.length}. Give a random key.`,\n );\n }\n return bytes;\n};\n\n/** This function gives the AES-GCM key of a seal from the secret, the salt and the label. */\nconst keyOf = async (\n secret: Uint8Array<ArrayBuffer>,\n salt: Uint8Array<ArrayBuffer>,\n label: string,\n use: \"encrypt\" | \"decrypt\",\n) => {\n const base = await crypto.subtle.importKey(\"raw\", secret, \"HKDF\", false, [\"deriveKey\"]);\n const info = encoder.encode(`${KEPT_SEAL_FORMAT}\\n${label}`);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [use],\n );\n};\n\n/** This function sends the bytes through a compression stream or a decompression stream. */\nconst through = async (\n bytes: Uint8Array<ArrayBuffer>,\n stream: CompressionStream | DecompressionStream,\n): Promise<Uint8Array<ArrayBuffer>> =>\n new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());\n\n/** This function joins the parts into one array of bytes. */\nconst join = (parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {\n const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n};\n\n/**\n * This function seals the entries of a store of kept answers, for example the `used` entries of a\n * run. It compresses each entry alone, and it encrypts all of them with a key from the secret. It\n * throws a `RangeError` when the secret has fewer than `KEPT_SEAL_SECRET_MIN` bytes.\n *\n * @beta\n */\nexport async function sealKept(\n entries: Iterable<readonly [string, Kept]>,\n secret: string | Uint8Array,\n options: SealOptions = {},\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = secretBytes(secret);\n const parts: Uint8Array[] = [];\n for (const entry of entries) {\n const packed = await through(\n encoder.encode(JSON.stringify(entry)),\n new CompressionStream(\"gzip\"),\n );\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, packed.length);\n parts.push(length, packed);\n }\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const cipherKey = await keyOf(key, salt, options.label ?? \"\", \"encrypt\");\n const sealed = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: HEADER },\n cipherKey,\n join(parts),\n );\n return join([HEADER, salt, iv, new Uint8Array(sealed)]);\n}\n\n/**\n * This function opens a store that `sealKept` sealed, and gives its entries. Data that does not open\n * (another format, another secret, another label, damaged bytes) gives no entries and a note, and no\n * error, so a client goes on with an empty store. It throws a `RangeError` when the secret has fewer\n * than `KEPT_SEAL_SECRET_MIN` bytes, as `sealKept` does. As `readKept` does, it drops each entry that\n * does not have the shape of a kept answer.\n *\n * @beta\n */\nexport async function openKept(\n sealed: Uint8Array,\n secret: string | Uint8Array,\n options: SealOptions = {},\n): Promise<OpenedKept> {\n const key = secretBytes(secret);\n const bytes = new Uint8Array(sealed);\n if (bytes.length < HEADER.length || HEADER.some((byte, index) => bytes[index] !== byte)) {\n return {\n entries: [],\n note: `The data is not a sealed store of the format ${KEPT_SEAL_FORMAT}.`,\n };\n }\n const start = HEADER.length;\n if (bytes.length < start + SALT_BYTES + IV_BYTES + TAG_BYTES) {\n return { entries: [], note: \"The sealed store is too short, so it is damaged.\" };\n }\n const salt = bytes.slice(start, start + SALT_BYTES);\n const iv = bytes.slice(start + SALT_BYTES, start + SALT_BYTES + IV_BYTES);\n let plain: Uint8Array<ArrayBuffer>;\n try {\n const cipherKey = await keyOf(key, salt, options.label ?? \"\", \"decrypt\");\n const opened = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv, additionalData: HEADER },\n cipherKey,\n bytes.slice(start + SALT_BYTES + IV_BYTES),\n );\n plain = new Uint8Array(opened);\n } catch {\n return {\n entries: [],\n note: \"The sealed store does not open: another secret, another label, or damaged bytes.\",\n };\n }\n const read: unknown[] = [];\n const view = new DataView(plain.buffer);\n let at = 0;\n try {\n while (at < plain.length) {\n if (at + 4 > plain.length) throw new Error(\"a length is cut\");\n const length = view.getUint32(at);\n at += 4;\n if (at + length > plain.length) throw new Error(\"an entry is cut\");\n read.push(\n JSON.parse(\n decoder.decode(\n await through(plain.slice(at, at + length), new DecompressionStream(\"gzip\")),\n ),\n ),\n );\n at += length;\n }\n } catch {\n return {\n entries: readKept(read),\n note: \"An entry of the sealed store does not read, so the store gives only the entries before it.\",\n };\n }\n return { entries: readKept(read) };\n}\n","/**\n * The polite send of a documented API. It keeps the pace of each host with the scheduler of the\n * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each\n * answer. The send stores no page, because the terms of some APIs forbid a store.\n *\n * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.\n * The module imports no Node.js module, and it uses no type of a platform except the signal.\n *\n * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,\n * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent\n * and a time limit. `poll` sends conditional requests. `freshUntil` gives the end of the freshness\n * of an answer (RFC 9111), so a client that keeps answers knows when to ask again. `keptFetch` and\n * `keepAnswer` keep the last full answer of a GET with its body, so a 304 gives the kept answer. The\n * client decides where the store is: a store is data. Each export is beta: a minor version can\n * change it.\n */\nimport { ApiError } from \"./api-error.ts\";\nimport type { Classified } from \"./classify.ts\";\nimport { classify } from \"./classify.ts\";\nimport type { HostStateStore, Paced, PolicyOptions, ValidatorAnswer } from \"./politeness.ts\";\nimport { policyFor, restAfter, validatorsToSend } from \"./politeness.ts\";\nimport type { OutcomeFacts } from \"./reaction.ts\";\nimport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\nimport { isQuotaError } from \"./quota.ts\";\nimport type { KeepOptions, KeptStore } from \"./kept.ts\";\nimport {\n hasValidator,\n isTextType,\n keepAnswer,\n KEPT_STATUSES,\n keptKey,\n keptRequestHeaders,\n} from \"./kept.ts\";\n\nexport { ApiError, isApiError } from \"./api-error.ts\";\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport { freshUntil } from \"./freshness.ts\";\nexport type { KeepOptions, Kept, KeptAnswer, KeptMemory, KeptStore } from \"./kept.ts\";\nexport {\n hasValidator,\n isTextType,\n keepAnswer,\n KEPT_BODY_MAX,\n KEPT_HEADERS,\n KEPT_STATUSES,\n keptKey,\n keptRequestHeaders,\n keptStore,\n readKept,\n} from \"./kept.ts\";\nexport type { OpenedKept, SealOptions } from \"./kept-seal.ts\";\nexport { KEPT_SEAL_FORMAT, KEPT_SEAL_SECRET_MIN, openKept, sealKept } from \"./kept-seal.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n QuotaRecord,\n QuotaStore,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\nexport type {\n Quota,\n QuotaGate,\n QuotaGateOptions,\n QuotaHeaders,\n QuotaReading,\n QuotaState,\n QuotaWindow,\n WithQuotaOptions,\n} from \"./quota.ts\";\nexport {\n isQuotaError,\n memoryQuotaStore,\n QuotaError,\n quotaGate,\n readQuotaHeaders,\n withQuota,\n} from \"./quota.ts\";\n\n/**\n * One request of a client to an API.\n *\n * @beta\n */\nexport interface Exchange {\n /** This value is the method of the request, for example `GET` or `POST`. */\n readonly method: string;\n readonly url: string;\n /** These are the headers of the request. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the request, or null. */\n readonly body: string | null;\n /**\n * This value tells how the transport reads the body of the answer. The default `text` gives the\n * body as text. With `bytes`, the reply has the body in `bytes`, and its `body` is empty.\n */\n readonly read?: \"text\" | \"bytes\" | undefined;\n}\n\n/**\n * The answer of an API to one exchange.\n *\n * @beta\n */\nexport interface Reply {\n readonly status: number;\n /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */\n readonly statusText: string;\n /** These are the headers of the answer. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body as text. It is empty when the exchange reads `bytes`. */\n readonly body: string;\n /** This value is the body as bytes, when the exchange reads `bytes`. */\n readonly bytes?: Uint8Array | undefined;\n}\n\n/**\n * The part of a signal that the send reads. An `AbortSignal` has it.\n *\n * @beta\n */\nexport interface Signal {\n readonly aborted: boolean;\n}\n\n/**\n * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an\n * error when the API gives no answer, and when the signal stops the request.\n *\n * @beta\n */\nexport type Transport<S extends Signal = AbortSignal> = (\n exchange: Exchange,\n signal: S | undefined,\n) => Promise<Reply>;\n\n/**\n * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.\n *\n * @beta\n */\nexport interface ApiScheduler<S extends Signal = AbortSignal> {\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;\n /**\n * This store keeps the counts and the stops of each host. When it has the validator memo\n * (`validators` and `noteValidators`), `poll` uses it as the crawler does. The two members are optional, as in\n * `HostStateStore`, so a store of `record` and `stop` is sufficient.\n */\n readonly store: Pick<HostStateStore, \"record\" | \"stop\" | \"validators\" | \"noteValidators\">;\n}\n\n/**\n * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.\n *\n * @beta\n */\nexport interface Pace<S extends Signal = AbortSignal> {\n /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */\n readonly scheduler: ApiScheduler<S>;\n /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */\n readonly now: () => number;\n /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */\n readonly policy?: PolicyOptions | undefined;\n /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * This function removes each secret from the text of an error. `secrets` holds the secrets of the\n * exchange: its keys and its token.\n *\n * @beta\n */\nexport type Redact = (text: string, secrets: readonly string[]) => string;\n\n/**\n * One exchange of a client, and its context for the pace and the messages.\n *\n * @beta\n */\nexport interface Send {\n /** This value is the name of the API in a message, for example `Example API`. */\n readonly source: string;\n /** This value is the host of the URL. The scheduler keeps one pace for each host. */\n readonly host: string;\n /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */\n readonly minIntervalMs?: number | undefined;\n /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */\n readonly what: string;\n readonly exchange: Exchange;\n /** These are the secrets of the exchange. The send gives them to `redact`. */\n readonly secrets?: readonly string[] | undefined;\n /**\n * This function removes the secrets from the text of each error. The default changes nothing.\n * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.\n */\n readonly redact?: Redact | undefined;\n /** With true, a 401 does not stop the host. The client then gets a new token one time. */\n readonly tokenRetry?: boolean | undefined;\n}\n\n/**\n * An answer, and what it means for the host.\n *\n * @beta\n */\nexport interface Answer {\n readonly reply: Reply;\n readonly classified: Classified;\n}\n\nconst unchanged: Redact = (text) => text;\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function gives the status line of an answer for a message, with no control character.\n *\n * @beta\n */\nexport function statusLine(reply: Reply): string {\n const reason = reply.statusText\n .replace(/\\p{Cc}/gu, \" \")\n .trim()\n .slice(0, 80);\n return reason === \"\" ? String(reply.status) : `${String(reply.status)} ${reason}`;\n}\n\n/**\n * This function sends one exchange at the pace of its host. The scheduler waits the rest of the\n * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for\n * the `Crawler`:\n *\n * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.\n * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.\n * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.\n * - A `QuotaError` of the transport (`withQuota`) does not change the host.\n * - An `ApiError` of the transport is a refusal of the client, for example a `FetchLike` with no\n * `arrayBuffer` for an exchange that reads bytes. The host gets only its rest, and its counts do not change.\n *\n * The function gives each answer, with each status. The caller reads the status.\n *\n * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.\n * @throws QuotaError of the transport, as it is, when a quota refuses the exchange.\n * @throws the ApiError of the transport, as it is, when the transport refuses the exchange.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function send<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n input: Send,\n signal?: S,\n): Promise<Answer> {\n const { scheduler } = pace;\n const { host } = input;\n const policy = policyFor(pace.policy, host);\n const random = pace.random ?? Math.random;\n const redact = (text: string): string => (input.redact ?? unchanged)(text, input.secrets ?? []);\n const spare = input.tokenRetry === true ? [401] : undefined;\n // the reaction of the host, inside the slot of the request, as the crawler does it\n const settle = (facts: OutcomeFacts, elapsedMs: number): number => {\n const now = pace.now();\n const restMs = restAfter(policy, {\n kind: \"api\",\n elapsedMs,\n minIntervalMs: input.minIntervalMs,\n }).ms;\n const counts = scheduler.store.record(host, outcomeResult(facts));\n const reaction = reactToOutcome(facts, counts, { policy, now, restMs, random });\n if (reaction.stop !== undefined)\n scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);\n return reaction.restMs;\n };\n let attempt: Answer | { readonly error: unknown };\n try {\n attempt = await scheduler.run<Answer | { readonly error: unknown }>(\n host,\n async () => {\n const started = pace.now();\n let reply: Reply;\n try {\n reply = await transport(input.exchange, signal);\n } catch (error) {\n // a quota refused the exchange before it started, so the host keeps its state and its pace.\n // The guard accepts a refusal of another copy of the package too.\n if (isQuotaError(error)) return { value: { error }, delayMs: 0 };\n // a request that the caller stopped is no fault of the host, and neither is a refusal of the\n // client. Only an ApiError of this copy is a refusal: an error of a different library can have its name.\n const neutral = signal?.aborted === true || error instanceof ApiError;\n const facts: OutcomeFacts = {\n outcome: \"error\",\n status: 0,\n ...(neutral ? { result: \"neutral\" as const } : {}),\n };\n return { value: { error }, delayMs: settle(facts, pace.now() - started) };\n }\n const classified = classify(\n reply.status,\n (name) => reply.headers[name.toLowerCase()],\n pace.now(),\n );\n const facts: OutcomeFacts = {\n outcome: classified.outcome,\n status: reply.status,\n retryAfterMs: classified.retryAfterMs,\n spare,\n };\n return { value: { reply, classified }, delayMs: settle(facts, pace.now() - started) };\n },\n signal,\n );\n } catch (error) {\n if (signal?.aborted === true) throw error;\n throw new ApiError(\n redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`),\n );\n }\n if (\"error\" in attempt) {\n const { error } = attempt;\n if (signal?.aborted === true || isQuotaError(error) || error instanceof ApiError) throw error;\n throw new ApiError(\n redact(`${input.source} gave no answer to ${input.what}: ${messageOf(error)}`),\n );\n }\n return attempt;\n}\n\n/**\n * The token of a client credentials grant, and the time when the client stops its use.\n *\n * @beta\n */\nexport interface Grant {\n readonly token: string;\n /** The client uses the token before this time, in milliseconds since the epoch. */\n readonly until: number;\n}\n\n/**\n * A client stops the use of a token this time before its end.\n *\n * @beta\n */\nexport const TOKEN_MARGIN_MS: number = 60_000;\n\n/** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */\nconst TOKEN = /^[!-~]{8,4096}$/;\n\nconst fieldOf = (value: unknown, key: string): unknown =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)\n ? (value as Record<string, unknown>)[key]\n : undefined;\n\n/**\n * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant\n * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or\n * for half of a short life.\n *\n * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The\n * message has no part of the body, and `redact` examined it.\n * @beta\n */\nexport function readGrant(\n reply: Reply,\n source: string,\n issuedAt: number,\n secrets: readonly string[] = [],\n redact: Redact = unchanged,\n): Grant {\n if (reply.status < 200 || reply.status > 299) {\n throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));\n }\n let body: unknown;\n try {\n body = JSON.parse(reply.body);\n } catch {\n throw new ApiError(`The token answer of ${source} is not JSON.`);\n }\n const token = fieldOf(body, \"access_token\");\n const expiresIn = fieldOf(body, \"expires_in\");\n if (typeof token !== \"string\" || !TOKEN.test(token)) {\n throw new ApiError(`The token answer of ${source} has no valid access_token.`);\n }\n if (typeof expiresIn !== \"number\" || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new ApiError(`The token answer of ${source} has no valid expires_in.`);\n }\n const lifeMs = expiresIn * 1000;\n return {\n token,\n until: issuedAt + (lifeMs > 2 * TOKEN_MARGIN_MS ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2),\n };\n}\n\n/**\n * A store of one token. The exchanges that wait for a token at one time share one grant.\n *\n * @beta\n */\nexport interface Tokens<S extends Signal = AbortSignal> {\n /** This method gives a token that the client can use. With no such token, it gets a new token. */\n get(signal?: S): Promise<string>;\n /**\n * This method forgets the token after an answer 401. With a token, it forgets only that token,\n * so a second 401 of an old token does not drop a newer token.\n */\n drop(token?: string): void;\n}\n\n/**\n * This function makes a store of one token. The store gets a new token from `grant` when the token\n * ends. `now` gives the time in milliseconds since the epoch.\n *\n * @beta\n */\nexport function tokenStore<S extends Signal = AbortSignal>(\n grant: (signal: S | undefined) => Promise<Grant>,\n now: () => number,\n): Tokens<S> {\n let held: Grant | undefined;\n let pending: Promise<Grant> | undefined;\n return {\n async get(signal) {\n if (held !== undefined && now() < held.until) return held.token;\n pending ??= grant(signal).finally(() => {\n pending = undefined;\n });\n const next = await pending;\n held = next;\n return next.token;\n },\n drop(token) {\n if (token === undefined || held?.token === token) held = undefined;\n },\n };\n}\n\n/**\n * This function sends an exchange with a token. `headers` gives the headers of the token, for\n * example `authorization`. After an answer 401, the function forgets the token, gets a new token,\n * and sends the exchange one more time. A second 401 stops the host. The token goes into the\n * secrets of the messages.\n *\n * @throws ApiError as `send` does, and the error of the grant.\n * @beta\n */\nexport async function sendWithToken<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n tokens: Tokens<S>,\n input: Send,\n headers: (token: string) => Readonly<Record<string, string>>,\n signal?: S,\n): Promise<Answer> {\n const once = async (tokenRetry: boolean): Promise<{ answer: Answer; token: string }> => {\n const token = await tokens.get(signal);\n const exchange = {\n ...input.exchange,\n headers: { ...input.exchange.headers, ...headers(token) },\n };\n const secrets = [...(input.secrets ?? []), token];\n const answer = await send(pace, transport, { ...input, exchange, secrets, tokenRetry }, signal);\n return { answer, token };\n };\n const first = await once(true);\n if (first.answer.reply.status !== 401) return first.answer;\n tokens.drop(first.token);\n return (await once(false)).answer;\n}\n\n/**\n * The part of a `fetch` function that `fetchTransport` uses. The `fetch` of Node.js and of a\n * browser has it.\n *\n * @beta\n */\nexport type FetchLike = (\n url: string,\n init: {\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body?: string;\n readonly redirect: \"manual\";\n readonly signal: AbortSignal;\n },\n) => Promise<{\n readonly status: number;\n readonly statusText: string;\n readonly headers: { forEach(callback: (value: string, name: string) => void): void };\n text(): Promise<string>;\n /** The transport uses this member only for an exchange that reads `bytes`. */\n arrayBuffer?(): Promise<ArrayBuffer>;\n}>;\n\n/**\n * The default time limit of `fetchTransport`: 30 seconds for the request and its body.\n *\n * @beta\n */\nexport const API_TIMEOUT_MS: number = 30_000;\n\n/**\n * The options of `fetchTransport`.\n *\n * @beta\n */\nexport interface FetchTransportOptions {\n /**\n * This value names the client and a contact, for example `example-app/1.0 (ops@example.com)`.\n * Each request sends it, except a request with its own `user-agent` header. Some APIs, for\n * example `api.weather.gov`, refuse a request with no User-Agent.\n */\n readonly userAgent: string;\n /** This value is the time limit of one request and its body, in milliseconds. The default is `API_TIMEOUT_MS`. */\n readonly timeoutMs?: number | undefined;\n /** This function sends the request. The default is the global `fetch`. */\n readonly fetch?: FetchLike | undefined;\n}\n\n/** A User-Agent is printable ASCII, from 1 to 512 characters, with no space at an end. */\nconst USER_AGENT = /^[!-~](?:[ -~]{0,510}[!-~])?$/;\n\n/**\n * This function makes a transport over `fetch`. The transport sends the User-Agent, does not\n * follow a redirect, and stops a request after the time limit. A request that the time limit\n * stopped throws an error, and `send` counts it as a failure of the host. A request that the\n * signal stopped throws the reason of the signal. For an exchange that reads `bytes`, the\n * transport reads the body with `arrayBuffer`.\n *\n * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.\n * @beta\n */\nexport function fetchTransport(options: FetchTransportOptions): Transport {\n const { userAgent } = options;\n if (!USER_AGENT.test(userAgent)) {\n throw new ApiError(\n \"The transport needs a User-Agent of 1 to 512 printable ASCII characters, with no space at an end.\",\n );\n }\n const timeoutMs = options.timeoutMs ?? API_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new ApiError(\n `The time limit of the transport is not a positive number: ${String(timeoutMs)}.`,\n );\n }\n const fetchOf: FetchLike = options.fetch ?? ((url, init) => globalThis.fetch(url, init));\n return async (exchange, signal) => {\n const timeout = AbortSignal.timeout(timeoutMs);\n const both = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);\n const headers: Record<string, string> = { \"user-agent\": userAgent, ...exchange.headers };\n try {\n const response = await fetchOf(exchange.url, {\n method: exchange.method,\n headers,\n ...(exchange.body === null ? {} : { body: exchange.body }),\n redirect: \"manual\",\n signal: both,\n });\n const replyHeaders: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n replyHeaders[name.toLowerCase()] = value;\n });\n const head = {\n status: response.status,\n statusText: response.statusText,\n headers: replyHeaders,\n };\n // the time limit also stops a body that does not end\n if (exchange.read !== \"bytes\") return { ...head, body: await response.text() };\n if (response.arrayBuffer === undefined) {\n // with undici, a body that nobody reads keeps its socket until garbage collection\n await response.text().catch(() => \"\");\n throw new ApiError(\n \"The fetch function gives no arrayBuffer, so the transport cannot read bytes.\",\n );\n }\n return { ...head, body: \"\", bytes: new Uint8Array(await response.arrayBuffer()) };\n } catch (error) {\n if (timeout.aborted && signal?.aborted !== true) {\n throw new Error(`no answer in ${String(Math.ceil(timeoutMs / 1000))} s`, { cause: error });\n }\n throw error;\n }\n };\n}\n\n/**\n * This function makes a `fetch` with kept answers, for example for `fetchTransport`. A GET with no\n * body and no conditional or range header of its own (`hasValidator`) sends the validators of its\n * kept answer. The key of the answer is `keptKey`. A 304 then gives the kept answer, as\n * `keepAnswer` tells, and a full answer with a text body in UTF-8 goes into the store. The function does not read a body\n * of a different media type, so an exchange that reads `bytes` gets the bytes. Each other request\n * goes to `fetch` as it is. The key does not hold the `authorization` header: the server examines\n * the access of each request before it answers 304.\n *\n * @beta\n */\nexport function keptFetch(\n fetch: FetchLike,\n store: KeptStore,\n options: KeepOptions = {},\n): FetchLike {\n return async (url, init) => {\n const plain = init.method.toUpperCase() === \"GET\" && init.body === undefined;\n if (!plain || hasValidator(init.headers)) return fetch(url, init);\n const key = keptKey(url, init.headers);\n const kept = store.get(key);\n const response = await fetch(url, { ...init, headers: keptRequestHeaders(kept, init.headers) });\n const headers: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const unchanged = response.status === 304 && kept !== undefined;\n const full = KEPT_STATUSES.includes(response.status) && isTextType(headers[\"content-type\"]);\n if (!unchanged && !full) return response;\n const body = response.status === 304 ? \"\" : await response.text();\n const answer = keepAnswer(store, key, { status: response.status, headers, body }, options);\n return {\n status: answer.status,\n statusText: answer.notModified ? \"\" : response.statusText,\n headers: {\n forEach(callback: (value: string, name: string) => void): void {\n for (const [name, value] of Object.entries(answer.headers)) callback(value, name);\n },\n },\n text: () => Promise.resolve(answer.body),\n arrayBuffer: () => Promise.resolve(new TextEncoder().encode(answer.body).slice().buffer),\n };\n };\n}\n\n/**\n * What a poll keeps of the last answer 2xx of one URL.\n *\n * @beta\n */\nexport interface Condition {\n /** This value is the `ETag` header of the answer, when it had one. */\n readonly etag?: string | undefined;\n /** This value is the `Last-Modified` header of the answer, when it had one. */\n readonly lastModified?: string | undefined;\n /** This value is the SHA-256 of the body, in hexadecimal. */\n readonly digest: string;\n}\n\n/**\n * A store of the conditions of a poll, one for each URL. A `Map` is a store in memory. One store\n * goes with one set of request headers: give a second store to a second `accept` header.\n *\n * @beta\n */\nexport interface Conditions {\n get(url: string): Condition | undefined;\n set(url: string, condition: Condition): void;\n}\n\n/**\n * An answer of a poll.\n *\n * @beta\n */\nexport interface Polled extends Answer {\n /**\n * This value is true for an answer 2xx with a body that is not the body of the last answer 2xx\n * of the URL. It is false for a 304, for the same body, and for each other status.\n */\n readonly changed: boolean;\n}\n\nconst HEX = \"0123456789abcdef\";\n\n/** This function gives the SHA-256 of a text or of bytes, in hexadecimal. */\nconst digestOf = async (body: string | Uint8Array): Promise<string> => {\n const data = typeof body === \"string\" ? new TextEncoder().encode(body) : body;\n const bytes = new Uint8Array(await globalThis.crypto.subtle.digest(\"SHA-256\", data));\n let hex = \"\";\n for (const byte of bytes) hex += (HEX[byte >> 4] ?? \"\") + (HEX[byte & 15] ?? \"\");\n return hex;\n};\n\n/**\n * This function sends one conditional GET at the pace of its host, as `send` does. It sends the\n * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and\n * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then\n * the function sends only the date to a host whose ETags do not match, as the crawler does.\n *\n * A 304 gives no body: the caller keeps the result of the last changed body. A server that does\n * not answer 304 can send the same body again. The function then gives `changed: false` too.\n *\n * @throws ApiError as `send` does, and when the method is not GET.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function poll<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n conditions: Conditions,\n input: Send,\n signal?: S,\n): Promise<Polled> {\n const { exchange, host } = input;\n if (exchange.method.toUpperCase() !== \"GET\") {\n throw new ApiError(`A poll sends only GET, not ${exchange.method}.`);\n }\n const { store } = pace.scheduler;\n const last = conditions.get(exchange.url);\n const which = validatorsToSend(\n store.validators?.(host),\n { etag: last?.etag !== undefined, lastModified: last?.lastModified !== undefined },\n pace.now(),\n );\n const headers: Record<string, string> = { ...exchange.headers };\n if (which.etag && last?.etag !== undefined) headers[\"if-none-match\"] = last.etag;\n if (which.lastModified && last?.lastModified !== undefined)\n headers[\"if-modified-since\"] = last.lastModified;\n const answer = await send(\n pace,\n transport,\n { ...input, exchange: { ...exchange, headers } },\n signal,\n );\n const { reply } = answer;\n let verdict: ValidatorAnswer | undefined;\n let changed = false;\n if (reply.status === 304) verdict = \"not-modified\";\n else if (reply.status >= 200 && reply.status <= 299) {\n const digest = await digestOf(reply.bytes ?? reply.body);\n changed = last?.digest !== digest;\n verdict = changed ? \"changed\" : \"same\";\n conditions.set(exchange.url, {\n etag: reply.headers[\"etag\"],\n lastModified: reply.headers[\"last-modified\"],\n digest,\n });\n }\n const report = {\n etag: headers[\"if-none-match\"] !== undefined,\n lastModified: headers[\"if-modified-since\"] !== undefined,\n };\n if (verdict !== undefined && (report.etag || report.lastModified))\n store.noteValidators?.(host, { ...report, answer: verdict }, pace.now());\n return { ...answer, changed };\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,IAAa,WAAb,cAA8B,MAAM;CAChB,OAAe;AACnC;;;;;AAMA,MAAM,wBAA6B,IAAI,IAAI,CAAC,YAAY,YAAY,CAAC;;;;;;;;;;;AAYrE,MAAa,cAAc,UACzB,iBAAiB,YAAa,iBAAiB,SAAS,MAAM,IAAI,MAAM,IAAI;;;;;;;ACsF9E,IAAa,aAAb,cAAgC,SAAS;CACrB,OAAe;;CAExB;;CAEA;CAET,YAAY,SAAiB,KAAa,SAAiB;EACzD,MAAM,OAAO;EACb,KAAK,MAAM;EACX,KAAK,UAAU;CACjB;AACF;;;;;;;;;;AAWA,MAAa,gBAAgB,UAC3B,iBAAiB,cAChB,iBAAiB,SAChB,MAAM,SAAS,gBACf,OAAQ,MAAqC,QAAQ,YACrD,OAA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;EAAE,GAAG;EAAQ,QAAQ;CAAQ,GAAG,KAAK,IAAI,CAAC;CACzE,OAAO;EAAE,GAAG;EAAQ;CAAQ;AAC9B"}
|
|
1
|
+
{"version":3,"file":"api.mjs","names":[],"sources":["../src/api-error.ts","../src/quota.ts","../src/kept.ts","../src/kept-replies.ts","../src/kept-seal.ts","../src/api.ts"],"sourcesContent":["/**\n * The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import\n * it and do not import each other.\n */\n\n/**\n * An error of the send or of the token. The `redact` function of the send examined its message.\n *\n * @beta\n */\nexport class ApiError extends Error {\n override readonly name: string = \"ApiError\";\n}\n\n/**\n * The names of `ApiError` and of each class that extends it. A new class of error adds its name here,\n * and the test of the guards fails when it does not.\n */\nconst NAMES: ReadonlySet<string> = new Set([\"ApiError\", \"QuotaError\"]);\n\n/**\n * This function tells if a value is an error of `polite-crawler/api`: an `ApiError`, or a\n * `QuotaError`, which extends it. The error can come from this copy of the package or from another\n * copy, of this version or of an earlier one. `instanceof` is false across two copies, so the\n * function also accepts an `Error` with one of their names. Thus it also accepts an error of a\n * different library with one of these names. Use it on the errors of a call through\n * `polite-crawler/api`.\n *\n * @beta\n */\nexport const isApiError = (value: unknown): value is ApiError =>\n value instanceof ApiError || (value instanceof Error && NAMES.has(value.name));\n","/**\n * The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day\n * or month in a time zone, or a rolling window. The gate counts each call before it starts, and it\n * refuses a call over the quota before the provider does. `withQuota` puts a gate on any async\n * function: a `fetch`, a transport or a different client.\n *\n * The count is not lower than the count of the provider. A rolling window puts each call in a time\n * bucket, and a bucket counts until all of it is out of the window. The answer of the provider can\n * make the count larger, but not smaller.\n *\n * The count of a window comes from the keyed quota of `@mark1russell7/service/limiter`, and a list\n * of gates takes its units with `takeQuotas` of that module. The module imports no Node.js module,\n * so a browser can use it. Each export is beta.\n */\nimport type {\n QuotaChange,\n QuotaPart,\n QuotaRefused,\n QuotaSpec,\n QuotaState as LimiterState,\n QuotaStore as LimiterStore,\n QuotaVerdict,\n} from \"@mark1russell7/service/limiter\";\nimport { keyedQuota, quotaProblems, takeQuotas } from \"@mark1russell7/service/limiter\";\nimport { ApiError } from \"./api-error.ts\";\nimport { parseRetryAfter } from \"./classify.ts\";\nimport type { QuotaRecord, QuotaStore } from \"./politeness.ts\";\n\n/**\n * The window of a quota.\n *\n * - `rolling`: the units of the last `ms` milliseconds. Use it when the provider does not tell when\n * its count starts again. It is stricter than each fixed window of the same length or shorter.\n * - `calendar`: the units of a day or a month in the IANA time zone `timeZone`. A window starts at\n * the hour `hour` (default 0) of the first day, in that zone. When the clock jumps over that hour,\n * the window starts at the jump.\n *\n * @beta\n */\nexport type QuotaWindow =\n | {\n readonly kind: \"rolling\";\n readonly ms: number;\n /** The window has this count of time buckets. The default is 60. Each call counts until all of its bucket is out of the window. */\n readonly buckets?: number | undefined;\n }\n | {\n readonly kind: \"calendar\";\n readonly unit: \"day\" | \"month\";\n /** This value is an IANA time zone, for example `America/Chicago` or `UTC`. */\n readonly timeZone: string;\n /** This value is the hour of the start of a window, from 0 to 23. The default is 0. */\n readonly hour?: number | undefined;\n };\n\n/**\n * A quota of one API key: at most `limit` units in each window.\n *\n * @beta\n */\nexport interface Quota {\n /**\n * This value names the quota in a message, for example `Example API requests`. A store keeps a\n * record for each name and key, so give each quota of a key a different name.\n */\n readonly name: string;\n /** This value is the count of units that the provider gives in one window. */\n readonly limit: number;\n /** The gate keeps this count of units unused. The default is 0. */\n readonly reserve?: number | undefined;\n readonly window: QuotaWindow;\n}\n\n/**\n * What an answer of the provider tells of its count.\n *\n * @beta\n */\nexport interface QuotaReading {\n /** This value is the count of units that the provider gives before its next reset. */\n readonly remaining?: number | undefined;\n /**\n * This value is the time of the next reset of the provider, in milliseconds since the epoch. When\n * `remaining` is 0 or is not there, the gate refuses each call until this time.\n */\n readonly resetAt?: number | undefined;\n}\n\n/**\n * The state of a quota at one time.\n *\n * @beta\n */\nexport interface QuotaState {\n /** This value is the count of units in the window. */\n readonly used: number;\n /**\n * This value is the count of units that the gate gives: the limit, less the reserve and `used`.\n * It is 0 while the provider refuses the key.\n */\n readonly left: number;\n /** The units come back from this time, in milliseconds since the epoch. With no unit in the window, it is not there. */\n readonly resetAt?: number | undefined;\n /** The provider refused the key until this time, in milliseconds since the epoch. */\n readonly blockedUntil?: number | undefined;\n /**\n * This value is the time of the state, in milliseconds since the epoch. For the state that `take`\n * gives, it is the time of the units of the call, which `giveBack` needs.\n */\n readonly at?: number | undefined;\n}\n\n/**\n * The refusal of a call over its quota. The gate refused the call before the call started.\n *\n * @beta\n */\nexport class QuotaError extends ApiError {\n override readonly name: string = \"QuotaError\";\n /** This value is the key of the quota. */\n readonly key: string;\n /** The gate gives units again from this time, in milliseconds since the epoch. */\n readonly resetAt: number;\n\n constructor(message: string, key: string, resetAt: number) {\n super(message);\n this.key = key;\n this.resetAt = resetAt;\n }\n}\n\n/**\n * This function tells if a value is a `QuotaError`. The error can come from this copy of the package\n * or from another copy, of this version or of an earlier one. `instanceof` is false across two copies.\n * So the function also accepts an `Error` named `QuotaError`, with a string `key` and a finite number\n * `resetAt`. A package that gets a transport of `withQuota` uses it to tell a refusal of the quota from\n * another failure. That package needs no dependency on this package.\n *\n * @beta\n */\nexport const isQuotaError = (value: unknown): value is QuotaError =>\n value instanceof QuotaError ||\n (value instanceof Error &&\n value.name === \"QuotaError\" &&\n typeof (value as { readonly key?: unknown }).key === \"string\" &&\n Number.isFinite((value as { readonly resetAt?: unknown }).resetAt));\n\nconst DEFAULT_BUCKETS = 60;\n/** The largest time of a `Date`, in milliseconds from the epoch. */\nconst MAX_TIME = 8.64e15;\n\nconst iso = (t: number): string => new Date(t).toISOString();\n\nconst isTime = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;\n\n/** This function refuses a cost that is not a finite number of 0 or more. */\nconst checkCost = (cost: number, of: string): void => {\n if (!Number.isFinite(cost) || cost < 0) {\n throw new ApiError(`The cost of ${of} is not a number of 0 or more: ${String(cost)}.`);\n }\n};\n\n/**\n * This function gives the spec of the limiter for a quota. Without `maxBlockMs`, a block ends at the\n * latest when the bucket of its reading stops counting: one window.\n */\nconst specOf = (quota: Quota, maxBlockMs: number | undefined): QuotaSpec => {\n const { window } = quota;\n return {\n limit: { value: quota.limit, unit: \"count\" },\n reserve: { value: quota.reserve ?? 0, unit: \"count\" },\n window:\n window.kind === \"rolling\"\n ? {\n kind: \"rolling\",\n span: { value: window.ms, unit: \"ms\" },\n buckets: { value: window.buckets ?? DEFAULT_BUCKETS, unit: \"count\" },\n }\n : {\n kind: \"calendar\",\n unit: window.unit,\n zone: window.timeZone,\n start: { value: window.hour ?? 0, unit: \"h\" },\n },\n maxBlock: maxBlockMs === undefined ? \"window\" : { value: maxBlockMs, unit: \"ms\" },\n };\n};\n\n/**\n * This function gives a store of the limiter over a store of this package. The two stores keep one\n * form of record, so a record of an earlier version stays valid.\n */\nconst limiterStore = (store: QuotaStore): LimiterStore<true> => ({\n sync: true,\n change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): T {\n let result: { readonly value: T } | undefined;\n store.changeQuota(quota, key, (stored) => {\n const next = step(stored);\n result = { value: next.result };\n return next.record;\n });\n if (result === undefined) {\n throw new ApiError(`The store did not change the record of the quota ${quota} of ${key}.`);\n }\n return result.value;\n },\n});\n\n/**\n * The gate of one key. It counts the units of the calls, and it refuses a call over the quota.\n *\n * @beta\n */\nexport interface QuotaGate {\n readonly quota: Quota;\n readonly key: string;\n /**\n * This method counts `cost` units (default 1) for a call that starts at this time, and gives the\n * state. A cost of 0 counts nothing and refuses nothing.\n *\n * @throws QuotaError when the units are more than `left`, or when the provider refused the key.\n * The gate then counts nothing. Its `resetAt` is the end of the refusal of the provider, or a later\n * time when the window has the units of the call.\n * @throws ApiError when the cost is negative or not finite, or when it is more than the quota\n * gives in one window.\n */\n take(cost?: number): QuotaState;\n /** This method adds what an answer of the provider tells. The count can only become larger. */\n note(reading: QuotaReading): QuotaState;\n /** This method gives the state at this time, and changes nothing. */\n state(): QuotaState;\n /**\n * This method gives back `cost` units that `take` counted at the time `at` (the `at` of its\n * state), for a call that did not start. `withQuota` uses it for a list of gates. When the gate\n * read the count of the provider at the time `at` or later, the method changes nothing. That\n * reading can include the units. So the count does not become lower than the count of the provider\n * at any time. A gate made by `quotaGate` has this method.\n *\n * @throws ApiError when the cost is negative or not finite, or when `at` is not a time.\n */\n giveBack?(cost: number, at: number): QuotaState;\n}\n\n/**\n * The options of `quotaGate`.\n *\n * @beta\n */\nexport interface QuotaGateOptions {\n /**\n * This value names the key, for example `example:account-1`. A store keeps it as text, so do not\n * give the secret of the key. Give one name to each account that the provider counts.\n */\n readonly key: string;\n /** This store keeps the records. The default is a new `memoryQuotaStore`. */\n readonly store?: QuotaStore | undefined;\n /** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */\n readonly now?: (() => number) | undefined;\n /**\n * This value is the longest block that a reset of the provider can set, in milliseconds. A reading\n * with a later reset blocks the key until the time of the reading plus this value. The default is\n * one window. Then the block ends at the latest when the units of a call at the time of the\n * reading go free. Thus a reset header in a wrong form cannot stop a key for much longer than the\n * window of the quota.\n */\n readonly maxBlockMs?: number | undefined;\n}\n\n/**\n * This function makes the gate of one key.\n *\n * @throws ApiError when the quota, its window or `maxBlockMs` is not valid. The message gives each\n * problem.\n * @beta\n */\nexport function quotaGate(quota: Quota, options: QuotaGateOptions): QuotaGate {\n const { limit, name } = quota;\n const reserve = quota.reserve ?? 0;\n const { key, maxBlockMs } = options;\n const spec = specOf(quota, maxBlockMs);\n const problems = quotaProblems(name, spec);\n if (problems.length > 0) {\n throw new ApiError(`The quota ${name} is not valid: ${problems.join(\"; \")}.`);\n }\n // the record of the quota and the key, so two quotas of one key in one store count apart\n const limiter = keyedQuota(name, spec, limiterStore(options.store ?? memoryQuotaStore()), {\n time: \"wall\",\n now: options.now ?? Date.now,\n });\n /** This function gives the error of a refused call. */\n const refusal = (verdict: QuotaRefused, cost: number): ApiError => {\n if (verdict.cause === \"capacity\") {\n return new ApiError(\n `A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(verdict.capacity)}.`,\n );\n }\n const { resetAt, state } = verdict;\n const { blockedUntil } = state;\n if (verdict.cause === \"provider\" && blockedUntil !== undefined) {\n return new QuotaError(\n `The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` +\n (resetAt > blockedUntil\n ? ` The window has the units of the call at ${iso(resetAt)}.`\n : \"\"),\n key,\n resetAt,\n );\n }\n return new QuotaError(\n `The quota ${name} of ${key} refused a call of ${String(cost)} units: ` +\n `${String(state.used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. ` +\n `It gives units again at ${iso(resetAt)}.`,\n key,\n resetAt,\n );\n };\n return {\n quota,\n key,\n take(cost = 1) {\n checkCost(cost, \"a call\");\n // a call of cost 0 is a call that the provider does not count, for example a read of a receipt\n const verdict = limiter.take(key, cost);\n if (!verdict.allowed) throw refusal(verdict, cost);\n return verdict.state;\n },\n note: (reading) => limiter.note(key, reading),\n state: () => limiter.state(key),\n giveBack(cost, at) {\n checkCost(cost, \"a give-back\");\n if (!isTime(at)) throw new ApiError(`The time of a give-back is not a time: ${String(at)}.`);\n return limiter.giveBack(key, cost, at);\n },\n };\n}\n\n/**\n * This function makes a store of records in memory. Each gate of one process can share it.\n *\n * @beta\n */\nexport function memoryQuotaStore(): QuotaStore {\n const records = new Map<string, Map<string, QuotaRecord>>();\n return {\n changeQuota(quota, key, step) {\n let keys = records.get(quota);\n if (keys === undefined) {\n keys = new Map();\n records.set(quota, keys);\n }\n const next = step(keys.get(key));\n keys.set(key, next);\n return next;\n },\n };\n}\n\n/**\n * The options of `withQuota`.\n *\n * @beta\n */\nexport interface WithQuotaOptions<A extends readonly unknown[], R> {\n /**\n * This value is the count of units of a call, or a function of the arguments that gives it. The\n * default is 1. Give 0 for a call that the provider does not count: the gate then does not refuse it.\n */\n readonly cost?: number | ((...args: A) => number) | undefined;\n /**\n * This function reads what the result of a call tells of the count of the provider, for example\n * with `readQuotaHeaders`. With a list of gates, it reads once for each gate. A provider often\n * tells the count of one quota only: then give its reading for that gate, and undefined for the\n * other gates.\n */\n readonly read?: ((result: R, gate: QuotaGate) => QuotaReading | undefined) | undefined;\n /**\n * This function gets an error of `read` or of the store after the call. The call went out, so\n * `withQuota` gives its result. It does not throw, because a retry after a throw sends the call\n * again. It also gets an error of a give-back of a list, and the caller still gets the refusal.\n * With no function, the error is lost. An error that this function throws is lost too.\n */\n readonly onError?: ((error: unknown) => void) | undefined;\n}\n\nconst isGateList = (gate: QuotaGate | readonly QuotaGate[]): gate is readonly QuotaGate[] =>\n Array.isArray(gate);\n\n/** This function checks the gates of `withQuota`: a list has gates that can give back units. */\nconst gateList = (gate: QuotaGate | readonly QuotaGate[]): readonly QuotaGate[] => {\n if (!isGateList(gate)) return [gate];\n if (gate.length === 0) throw new ApiError(\"The list of gates of withQuota is empty.\");\n const seen = new Set<string>();\n for (const each of gate) {\n const named = `the quota ${each.quota.name} of ${each.key}`;\n if (gate.length > 1 && each.giveBack === undefined) {\n throw new ApiError(`The gate of ${named} cannot give back units, so it cannot be in a list.`);\n }\n // a store keeps one record for each name and key, so two such gates count each call twice;\n // a gate does not show its store, so two gates of one name and key on two stores are refused too\n const id = JSON.stringify([each.quota.name, each.key]);\n if (seen.has(id)) {\n throw new ApiError(`Two gates of the list have ${named}. Give each quota a different name.`);\n }\n seen.add(id);\n }\n return [...gate];\n};\n\n/**\n * This function gives an error to `onError`. An error that `onError` throws is lost. Thus the other\n * give-backs still occur, and the caller gets the refusal or the result of the call.\n */\nconst report = (onError: ((error: unknown) => void) | undefined, error: unknown): void => {\n try {\n onError?.(error);\n } catch {\n // the refusal or the result of the call is more important than an error of the report\n }\n};\n\n/** This function gives a state of a gate in the form of the limiter. A state with no time gets the time NaN. */\nconst limiterState = (state: QuotaState): LimiterState => ({\n ...state,\n at: state.at ?? Number.NaN,\n});\n\n/**\n * This function gives a gate of a list as a part of `takeQuotas`. The part keeps the `QuotaError` of\n * its refusal in `refusals`, because the caller gets that error. A `QuotaError` has no state, so a\n * refused part reads the state of its gate. A give-back of units with no time fails, and `onError`\n * gets its error.\n */\nconst partOf = (\n gate: QuotaGate,\n units: number,\n index: number,\n refusals: Map<number, QuotaError>,\n): QuotaPart<true> => ({\n key: gate.key,\n units,\n quota: {\n sync: true,\n take: (_key, cost = 1): QuotaVerdict => {\n try {\n return { allowed: true, state: limiterState(gate.take(cost)) };\n } catch (error) {\n if (!isQuotaError(error)) throw error;\n refusals.set(index, error);\n const state = limiterState(gate.state());\n const wait = Number.isNaN(state.at) ? 0 : Math.max(0, error.resetAt - state.at);\n return {\n allowed: false,\n cause: state.blockedUntil === undefined ? \"limit\" : \"provider\",\n resetAt: error.resetAt,\n retryAfter: { value: wait, unit: \"ms\" },\n state,\n };\n }\n },\n giveBack: (_key, cost, at) => {\n if (Number.isNaN(at)) {\n throw new ApiError(\n `The gate of the quota ${gate.quota.name} of ${gate.key} gave no time for its units, so it cannot give them back.`,\n );\n }\n return limiterState(gate.giveBack?.(cost, at) ?? gate.state());\n },\n },\n});\n\n/**\n * This function counts `cost` units in each gate, or in none. One gate gives its refusal as it is. A\n * list takes with `takeQuotas`: when a gate refuses, the gates that counted give back the units,\n * because the call did not start. The next gates still answer, so the `QuotaError` has the latest\n * time of a reset.\n */\nconst takeAll = (\n gates: readonly QuotaGate[],\n cost: number,\n onError: ((error: unknown) => void) | undefined,\n): void => {\n const [only] = gates;\n if (gates.length === 1 && only !== undefined) {\n only.take(cost);\n return;\n }\n const refusals = new Map<number, QuotaError>();\n const verdict = takeQuotas(\n gates.map((gate, index) => partOf(gate, cost, index, refusals)),\n { onGiveBackError: (error) => report(onError, error) },\n );\n if (!verdict.allowed) {\n throw (\n refusals.get(verdict.index) ??\n new ApiError(\"A gate of the list refused the call, but it gave no QuotaError.\")\n );\n }\n};\n\n/**\n * This function puts a gate, or a list of gates, on an async function, and keeps the type of the\n * function. Each call counts its units first. A call over the quota throws `QuotaError`, and the\n * function does not start.\n *\n * Give the result to a client that takes a function of this type. For example, `withQuota(gate,\n * fetch)` is a `fetch`, and `withQuota(gate, transport)` is a transport of `send` and `poll`.\n *\n * For two quotas of one key, give a list: `withQuota([perMinute, perDay], fetch)`. The list counts\n * the call in each gate or in none. Do not put one gate in the function of another. The outer gate\n * cannot know if a request went out before the inner gate refused (`send` retries). So it keeps\n * the units of the call.\n *\n * @throws ApiError when the list is empty, or when a gate of a list of two or more has no\n * `giveBack`. Also when two gates of the list have one quota name and key.\n * @beta\n */\nexport function withQuota<A extends readonly unknown[], R>(\n gate: QuotaGate | readonly QuotaGate[],\n call: (...args: A) => Promise<R>,\n options: WithQuotaOptions<A, R> = {},\n): (...args: A) => Promise<R> {\n const gates = gateList(gate);\n const { cost, read, onError } = options;\n return async (...args: A): Promise<R> => {\n takeAll(gates, typeof cost === \"function\" ? cost(...args) : (cost ?? 1), onError);\n const result = await call(...args);\n for (const each of gates) {\n try {\n const reading = read?.(result, each);\n if (reading !== undefined) each.note(reading);\n } catch (error) {\n report(onError, error);\n }\n }\n return result;\n };\n}\n\n/**\n * The names of the headers of an answer that tell the count of a provider. Each name is optional.\n *\n * @beta\n */\nexport interface QuotaHeaders {\n /** This header has the count of units that the provider gives before its reset, for example `x-ratelimit-remaining`. */\n readonly remaining?: string | undefined;\n /**\n * This header has the time of the reset, for example `x-ratelimit-reset`. The function reads its\n * form from its size. A value under 10^9 is the seconds until the reset, as `RateLimit-Reset` of\n * the IETF draft gives them. A value from 10^9 to under 10^11 is seconds since the epoch. A value\n * from 10^11 is milliseconds since the epoch.\n */\n readonly resetAt?: string | undefined;\n /**\n * This header has the seconds until the reset, or the HTTP date of the reset, as `retry-after`\n * gives them. When it has a value that the function can read, the function does not read `resetAt`.\n */\n readonly resetAfter?: string | undefined;\n}\n\nconst COUNT = /^\\d{1,15}$/;\nconst SECONDS = /^\\d{1,12}(?:\\.\\d{1,3})?$/;\nconst RESET = /^\\d{1,15}(?:\\.\\d{1,3})?$/;\n\n/**\n * A reset value under this bound is a count of seconds until the reset. As seconds since the epoch,\n * it is a time before 2001-09-09T01:46:40Z, and no reset of a provider is that early.\n */\nexport const SECONDS_SINCE_EPOCH_FROM = 1e9;\n/**\n * A reset value from this bound is in milliseconds since the epoch. As seconds since the epoch, it\n * is a time in the year 5138, and as milliseconds it is a time in 1973.\n */\nexport const MILLISECONDS_SINCE_EPOCH_FROM = 1e11;\n\n/**\n * This function gives the time of a reset, in milliseconds since the epoch, from the number of a\n * reset header. The three forms of the header do not overlap:\n *\n * - under `SECONDS_SINCE_EPOCH_FROM` (10^9): seconds until the reset, from `now`\n * - from 10^9 to under `MILLISECONDS_SINCE_EPOCH_FROM` (10^11): seconds since the epoch\n * - from 10^11: milliseconds since the epoch\n */\nexport const resetTimeOf = (value: number, now: number): number =>\n value < SECONDS_SINCE_EPOCH_FROM\n ? now + value * 1000\n : value < MILLISECONDS_SINCE_EPOCH_FROM\n ? value * 1000\n : value;\n\n/**\n * This function reads the count of a provider from the headers of an answer. `get` gives the value\n * of one header, for example `(name) => response.headers.get(name)` for a `fetch` answer, or\n * `(name) => reply.headers[name]` for a `Reply`. A value that is not a number is not read. A value of\n * `resetAfter` can also be an HTTP date, as in `Retry-After`. The value of `resetAt` can be in each\n * of three forms, which the function tells apart by their size.\n *\n * A reset with no count tells that the provider refuses the key until that time. The answer can\n * have a reset header, and no `remaining` header with a number. Then the gate stops the key until\n * the reset, also after a successful answer.\n *\n * @returns the reading, or undefined when no header has a value.\n * @beta\n */\nexport function readQuotaHeaders(\n get: (name: string) => string | null | undefined,\n names: QuotaHeaders,\n now: number,\n): QuotaReading | undefined {\n const text = (name: string | undefined): string | undefined =>\n name === undefined ? undefined : get(name.toLowerCase())?.trim();\n const value = (name: string | undefined, form: RegExp): number | undefined => {\n const found = text(name);\n return found !== undefined && form.test(found) ? Number(found) : undefined;\n };\n const remaining = value(names.remaining, COUNT);\n const at = value(names.resetAt, RESET);\n // seconds with a fraction, as some providers give, and then the two forms of Retry-After\n const afterText = text(names.resetAfter);\n const after =\n afterText === undefined\n ? undefined\n : SECONDS.test(afterText)\n ? Number(afterText) * 1000\n : parseRetryAfter(afterText, now);\n const resetAt =\n after !== undefined ? now + after : at === undefined ? undefined : resetTimeOf(at, now);\n if (remaining === undefined && resetAt === undefined) return undefined;\n return {\n ...(remaining === undefined ? {} : { remaining }),\n ...(resetAt === undefined ? {} : { resetAt }),\n };\n}\n","/**\n * Kept answers. A client keeps the last full answer of a GET with its validators. The next GET of\n * the same key is then a conditional request (RFC 9110 §13.1). An answer 304 then gives the kept\n * answer with the fields of the 304 (RFC 9111 §4.3.4). Some APIs with a rate limit do not count a\n * 304, for example the REST API of GitHub. The store is data, so a client can keep it between two\n * runs. The server examines each validator, so a kept answer goes to the client only after the\n * server tells that it is current. The module imports no Node.js module.\n */\n\n/**\n * The kept answer of one key.\n *\n * @beta\n */\nexport interface Kept {\n /** This value is the `ETag` header of the answer, when it had one. */\n readonly etag?: string | undefined;\n /** This value is the `Last-Modified` header of the answer, when it had one. */\n readonly lastModified?: string | undefined;\n /** This value is the status of the answer: 200, 203 or 204 (`KEPT_STATUSES`). */\n readonly status: number;\n /** These values are the headers that the store keeps, by name in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the answer, as text. */\n readonly body: string;\n}\n\n/**\n * A store of kept answers, by key. A `Map` is a store in memory. `keptStore` also records the\n * entries that a run uses.\n *\n * @beta\n */\nexport interface KeptStore {\n /** This function gives the kept answer of the key, or undefined when the store has none. */\n get(key: string): Kept | undefined;\n /** This function keeps the answer under the key, in place of an earlier one. */\n set(key: string, kept: Kept): void;\n}\n\n/**\n * An answer as a client reads it: its status, its headers by name in lowercase, and its body.\n *\n * @beta\n */\nexport interface KeptAnswer {\n /** The status of the answer. After a 304, it is the status of the kept answer. */\n readonly status: number;\n /** The headers of the answer, by name in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** The body of the answer as text. After a 304, it is the kept body. */\n readonly body: string;\n /** This value is true when the server answered 304 and the answer is the kept answer. */\n readonly notModified: boolean;\n}\n\n/**\n * The options of `keepAnswer`.\n *\n * @beta\n */\nexport interface KeepOptions {\n /** These names are the headers that a kept answer keeps. The default is `KEPT_HEADERS`. */\n readonly headers?: readonly string[] | undefined;\n /**\n * This value is the largest body that the store keeps, in UTF-16 code units. The default is\n * `KEPT_BODY_MAX`.\n */\n readonly maxBody?: number | undefined;\n}\n\n/**\n * The headers that a kept answer keeps when the options give no list. `link` keeps the next page\n * of a list.\n *\n * @beta\n */\nexport const KEPT_HEADERS: readonly string[] = [\"content-type\", \"etag\", \"last-modified\", \"link\"];\n\n/**\n * The largest body that a store keeps when the options give no limit: 1,048,576 UTF-16 code units.\n *\n * @beta\n */\nexport const KEPT_BODY_MAX: number = 1_048_576;\n\n/**\n * The statuses that a store keeps. The body of each is the full answer. A 206 has only a part of\n * the body, so a store does not keep it.\n *\n * @beta\n */\nexport const KEPT_STATUSES: readonly number[] = [200, 203, 204];\n\n/** These fields of a 304 tell of its empty body, so they do not go into the kept answer. */\nconst BODY_FIELDS: ReadonlySet<string> = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n/** A body of one of these media types is text, so a store can keep it as text. */\nconst TEXT_TYPE = /^\\s*(?:text\\/[\\w.+-]+|application\\/(?:[\\w.-]+\\+)?(?:json|xml))\\s*(?:;|$)/i;\n\n/** This pattern finds the charset parameter of a media type. */\nconst CHARSET = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i;\n\n/** This function gives the headers with each name in lowercase. */\nconst lower = (headers: Readonly<Record<string, string>>): Record<string, string> => {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) out[name.toLowerCase()] = value;\n return out;\n};\n\n/**\n * This function tells if the headers of a request make it conditional or partial on their own:\n * `If-None-Match`, `If-Modified-Since`, `If-Match`, `If-Unmodified-Since`, `If-Range` or\n * `Range`. The client of such a request reads the answer itself, so a store does not answer for\n * it.\n *\n * @beta\n */\nexport function hasValidator(headers: Readonly<Record<string, string>>): boolean {\n return Object.keys(headers).some((name) => {\n const n = name.toLowerCase();\n return n === \"range\" || n.startsWith(\"if-\");\n });\n}\n\n/**\n * This function tells if a body of a media type is text in UTF-8. That is a text, JSON or XML type\n * with no charset or with the charset UTF-8. A store keeps only such a body, because `text()` of\n * `fetch` reads a body as UTF-8.\n *\n * @beta\n */\nexport function isTextType(contentType: string | undefined): boolean {\n const type = contentType ?? \"\";\n if (!TEXT_TYPE.test(type)) return false;\n const charset = CHARSET.exec(type)?.[1];\n return charset === undefined || /^utf-?8$/i.test(charset);\n}\n\n/**\n * This function gives the key of a request in a store: its `accept` header and its URL. A\n * different `accept` header can give a different body, so it gets a different key.\n *\n * @beta\n */\nexport function keptKey(url: string, headers: Readonly<Record<string, string>>): string {\n return `${lower(headers)[\"accept\"] ?? \"\"} ${url}`;\n}\n\n/**\n * This function gives the headers of a conditional request: the headers of the request, and the\n * validators of the kept answer. `If-None-Match` sends its ETag, and `If-Modified-Since` sends its\n * date. The function adds no header to a request that has a validator of its own.\n *\n * @beta\n */\nexport function keptRequestHeaders(\n kept: Kept | undefined,\n headers: Readonly<Record<string, string>>,\n): Record<string, string> {\n const out: Record<string, string> = { ...headers };\n if (kept === undefined || hasValidator(headers)) return out;\n if (kept.etag !== undefined) out[\"if-none-match\"] = kept.etag;\n if (kept.lastModified !== undefined) out[\"if-modified-since\"] = kept.lastModified;\n return out;\n}\n\n/**\n * This function gives the answer that a client reads, and changes the store.\n *\n * - A 304 for a key with a kept answer gives the kept answer. Its headers get the fields of the\n * 304, as RFC 9111 §4.3.4 tells, and the store keeps the new values of its kept headers.\n * - An answer with a status of `KEPT_STATUSES` and an ETag or a date goes into the store. It needs\n * a text type in UTF-8 and a body in the limit.\n * - Each other answer is as it is, and the store does not change.\n *\n * @beta\n */\nexport function keepAnswer(\n store: KeptStore,\n key: string,\n answer: {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n },\n options: KeepOptions = {},\n): KeptAnswer {\n const names = new Set((options.headers ?? KEPT_HEADERS).map((name) => name.toLowerCase()));\n const headers = lower(answer.headers);\n const kept = store.get(key);\n if (answer.status === 304 && kept !== undefined) {\n const read: Record<string, string> = { ...kept.headers };\n const keep: Record<string, string> = { ...kept.headers };\n for (const [name, value] of Object.entries(headers)) {\n if (BODY_FIELDS.has(name)) continue;\n read[name] = value;\n if (names.has(name)) keep[name] = value;\n }\n store.set(key, {\n ...kept,\n etag: headers[\"etag\"] ?? kept.etag,\n lastModified: headers[\"last-modified\"] ?? kept.lastModified,\n headers: keep,\n });\n return { status: kept.status, headers: read, body: kept.body, notModified: true };\n }\n const etag = headers[\"etag\"];\n const lastModified = headers[\"last-modified\"];\n if (\n KEPT_STATUSES.includes(answer.status) &&\n (etag !== undefined || lastModified !== undefined) &&\n isTextType(headers[\"content-type\"]) &&\n answer.body.length <= (options.maxBody ?? KEPT_BODY_MAX)\n ) {\n const keep: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) if (names.has(name)) keep[name] = value;\n store.set(key, { etag, lastModified, status: answer.status, headers: keep, body: answer.body });\n }\n return { status: answer.status, headers, body: answer.body, notModified: false };\n}\n\n/**\n * A store of kept answers in memory that records which entries a run uses.\n *\n * @beta\n */\nexport interface KeptMemory extends KeptStore {\n /**\n * This function gives each entry that a `get` found or a `set` wrote, in the order of the first\n * use. A client that saves only these entries keeps no answer that it does not ask for again.\n */\n used(): [string, Kept][];\n}\n\n/**\n * This function makes a store of kept answers in memory, with the entries of an earlier run.\n *\n * @beta\n */\nexport function keptStore(entries: Iterable<readonly [string, Kept]> = []): KeptMemory {\n const all = new Map<string, Kept>(entries);\n const used = new Set<string>();\n return {\n get(key) {\n const kept = all.get(key);\n if (kept !== undefined) used.add(key);\n return kept;\n },\n set(key, kept) {\n all.set(key, kept);\n used.add(key);\n },\n used: () =>\n [...used].flatMap((key): [string, Kept][] => {\n const kept = all.get(key);\n return kept === undefined ? [] : [[key, kept]];\n }),\n };\n}\n\n/** This function gives a kept answer from data, or null when the data does not have its shape. */\nconst keptOf = (value: unknown): Kept | null => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n const { etag, lastModified, status, headers, body } = value as Record<string, unknown>;\n if (typeof status !== \"number\" || !KEPT_STATUSES.includes(status)) return null;\n if (typeof body !== \"string\") return null;\n if (etag !== undefined && typeof etag !== \"string\") return null;\n if (lastModified !== undefined && typeof lastModified !== \"string\") return null;\n if (etag === undefined && lastModified === undefined) return null;\n if (typeof headers !== \"object\" || headers === null || Array.isArray(headers)) return null;\n const read: Record<string, string> = {};\n for (const [name, field] of Object.entries(headers)) {\n if (typeof field !== \"string\") return null;\n read[name.toLowerCase()] = field;\n }\n return {\n etag: typeof etag === \"string\" ? etag : undefined,\n lastModified: typeof lastModified === \"string\" ? lastModified : undefined,\n status,\n headers: read,\n body,\n };\n};\n\n/**\n * This function reads the entries of a store from data, for example from the JSON of the `used`\n * entries of an earlier run. It keeps each entry with a correct shape and drops each other entry.\n * Thus damaged data gives fewer kept answers and no error.\n *\n * @beta\n */\nexport function readKept(data: unknown): [string, Kept][] {\n if (!Array.isArray(data)) return [];\n const out: [string, Kept][] = [];\n for (const entry of data) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== \"string\") continue;\n const kept = keptOf(entry[1]);\n if (kept !== null) out.push([entry[0], kept]);\n }\n return out;\n}\n","/**\n * Kept replies of a poll. A 304 answer of `poll` has no body: the caller keeps the result of the\n * last full answer. A caller that reads each full answer into many values keeps those values until\n * the next full answer. Thus its memory grows with the data of the feed. `keptReplies` keeps the\n * last full reply of each URL with its body as compressed bytes. At a 304, the caller reads the\n * reply again and gets the same values.\n *\n * - The compression is the Web stream `CompressionStream` with the format `deflate-raw`. Node.js\n * and the browser have it. In Node.js, the stream operates in the thread pool of `zlib`, thus it\n * does not block the event loop.\n * - The store keeps a value of the caller with each reply, for example the time of the fetch and\n * its latency. Thus a new read gives the same result.\n * - A reply with `bytes` keeps its bytes as they are. Only the text body gets the compression.\n * - A failed compression or expansion rejects the `get` of the URL. The caller then has no earlier\n * full answer.\n *\n * `keptFetch` and `keptStore` keep the answers of a `fetch` as text, for the clients that save\n * them between two runs. `keptReplies` keeps the replies of `poll` in memory for one run.\n */\nimport type { Reply } from \"./api.ts\";\n\n/** This function gives the compressed bytes of a text. */\nconst deflate = async (text: string): Promise<Uint8Array<ArrayBuffer>> => {\n const stream = new Blob([text]).stream().pipeThrough(new CompressionStream(\"deflate-raw\"));\n return new Uint8Array(await new Response(stream).arrayBuffer());\n};\n\n/** This function gives the text of compressed bytes. */\nconst inflate = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> =>\n new Response(\n new Blob([bytes]).stream().pipeThrough(new DecompressionStream(\"deflate-raw\")),\n ).text();\n\n/**\n * One reply of a store of kept replies, with the value that the caller kept with it.\n *\n * @beta\n */\nexport interface KeptReply<Extra> {\n /** This value is the reply, with its body. */\n readonly reply: Reply;\n /** This value is the value that the caller kept with the reply. */\n readonly extra: Extra;\n}\n\n/**\n * A store of the last full reply of each URL.\n *\n * @beta\n */\nexport interface KeptReplies<Extra> {\n /** This method keeps the full reply of a URL in place of the last one. */\n keep(url: string, reply: Reply, extra: Extra): void;\n /** This method gives the last full reply of a URL, or `undefined` when the store has none. */\n get(url: string): Promise<KeptReply<Extra> | undefined>;\n /** This method removes the reply of a URL. */\n delete(url: string): void;\n}\n\n/** One reply in the store. The compression is a promise, thus a 304 that comes first waits for it. */\ninterface Entry<Extra> {\n readonly reply: Omit<Reply, \"body\">;\n readonly body: Promise<Uint8Array<ArrayBuffer>>;\n readonly extra: Extra;\n}\n\n/**\n * This function makes a store of the last full reply of each URL of a poll, with each text body\n * as compressed bytes. The store is in memory.\n *\n * @beta\n */\nexport function keptReplies<Extra>(): KeptReplies<Extra> {\n const entries = new Map<string, Entry<Extra>>();\n return {\n keep(url, reply, extra) {\n const { body, ...rest } = reply;\n const entry: Entry<Extra> = { reply: rest, body: deflate(body), extra };\n // A failed compression rejects only the next `get` of the URL. This handler stops an unhandled rejection before it.\n entry.body.catch(() => undefined);\n entries.set(url, entry);\n },\n async get(url) {\n const entry = entries.get(url);\n if (entry === undefined) return undefined;\n const body = await inflate(await entry.body);\n return { reply: { ...entry.reply, body }, extra: entry.extra };\n },\n delete(url) {\n entries.delete(url);\n },\n };\n}\n","/**\n * The sealed form of a store of kept answers. Use it for a place that other people can read, for\n * example the cache of a public repository in GitHub Actions. A kept answer of a private resource\n * holds its body as text. Thus a client that saves its store in such a place seals it first.\n *\n * `sealKept` encrypts the entries with AES-256-GCM. The key comes from a secret by HKDF-SHA-256\n * (RFC 5869). Each seal has a new random salt, and the label of the use is the info. Thus two labels\n * give two keys from one secret. The format name is the first line of the bytes. It is also the\n * associated data of the cipher, so a change of the format cannot go unseen.\n *\n * Each entry is compressed alone (gzip) before the encryption. A compression of all entries together\n * puts the text of one answer in the window of another answer. Then the size of the sealed bytes can\n * tell something of a private answer to a person who controls a public answer. With one compression\n * for each entry, the text of an answer meets only its own text.\n *\n * The functions use only Web APIs (`crypto.subtle`, `CompressionStream`). Thus they operate in\n * Node.js and in a browser.\n */\nimport { readKept, type Kept } from \"./kept.ts\";\n\n/**\n * The name and the version of the sealed format. It is the first line of the sealed bytes.\n *\n * @beta\n */\nexport const KEPT_SEAL_FORMAT = \"polite-crawler-kept-sealed/1\";\n\n/**\n * The smallest secret that `sealKept` and `openKept` take, in bytes. HKDF does not slow a guess, so\n * the secret must be a random key, not a password.\n *\n * @beta\n */\nexport const KEPT_SEAL_SECRET_MIN = 16;\n\n/**\n * The options of `sealKept` and `openKept`.\n *\n * @beta\n */\nexport interface SealOptions {\n /**\n * This value is the label of the use, for example the name of the client. A store opens only with\n * the label that sealed it. Give a label when the secret has a second use. The default is \"\".\n */\n readonly label?: string | undefined;\n}\n\n/**\n * The result of `openKept`.\n *\n * @beta\n */\nexport interface OpenedKept {\n /** These values are the entries of the store. They are empty when the store does not open. */\n readonly entries: [string, Kept][];\n /** This value tells why the store gave fewer entries or none, when that occurs. */\n readonly note?: string | undefined;\n}\n\nconst SALT_BYTES = 16;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\nconst HEADER = encoder.encode(`${KEPT_SEAL_FORMAT}\\n`);\n\n/** This function gives the bytes of the secret, or throws when the secret is too short. */\nconst secretBytes = (secret: string | Uint8Array): Uint8Array<ArrayBuffer> => {\n const bytes = typeof secret === \"string\" ? encoder.encode(secret) : new Uint8Array(secret);\n if (bytes.length < KEPT_SEAL_SECRET_MIN) {\n throw new RangeError(\n `The secret of a sealed store needs ${KEPT_SEAL_SECRET_MIN} bytes or more, and it has ${bytes.length}. Give a random key.`,\n );\n }\n return bytes;\n};\n\n/** This function gives the AES-GCM key of a seal from the secret, the salt and the label. */\nconst keyOf = async (\n secret: Uint8Array<ArrayBuffer>,\n salt: Uint8Array<ArrayBuffer>,\n label: string,\n use: \"encrypt\" | \"decrypt\",\n) => {\n const base = await crypto.subtle.importKey(\"raw\", secret, \"HKDF\", false, [\"deriveKey\"]);\n const info = encoder.encode(`${KEPT_SEAL_FORMAT}\\n${label}`);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [use],\n );\n};\n\n/** This function sends the bytes through a compression stream or a decompression stream. */\nconst through = async (\n bytes: Uint8Array<ArrayBuffer>,\n stream: CompressionStream | DecompressionStream,\n): Promise<Uint8Array<ArrayBuffer>> =>\n new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());\n\n/** This function joins the parts into one array of bytes. */\nconst join = (parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {\n const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n};\n\n/**\n * This function seals the entries of a store of kept answers, for example the `used` entries of a\n * run. It compresses each entry alone, and it encrypts all of them with a key from the secret. It\n * throws a `RangeError` when the secret has fewer than `KEPT_SEAL_SECRET_MIN` bytes.\n *\n * @beta\n */\nexport async function sealKept(\n entries: Iterable<readonly [string, Kept]>,\n secret: string | Uint8Array,\n options: SealOptions = {},\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = secretBytes(secret);\n const parts: Uint8Array[] = [];\n for (const entry of entries) {\n const packed = await through(\n encoder.encode(JSON.stringify(entry)),\n new CompressionStream(\"gzip\"),\n );\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, packed.length);\n parts.push(length, packed);\n }\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const cipherKey = await keyOf(key, salt, options.label ?? \"\", \"encrypt\");\n const sealed = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: HEADER },\n cipherKey,\n join(parts),\n );\n return join([HEADER, salt, iv, new Uint8Array(sealed)]);\n}\n\n/**\n * This function opens a store that `sealKept` sealed, and gives its entries. Data that does not open\n * (another format, another secret, another label, damaged bytes) gives no entries and a note, and no\n * error, so a client goes on with an empty store. It throws a `RangeError` when the secret has fewer\n * than `KEPT_SEAL_SECRET_MIN` bytes, as `sealKept` does. As `readKept` does, it drops each entry that\n * does not have the shape of a kept answer.\n *\n * @beta\n */\nexport async function openKept(\n sealed: Uint8Array,\n secret: string | Uint8Array,\n options: SealOptions = {},\n): Promise<OpenedKept> {\n const key = secretBytes(secret);\n const bytes = new Uint8Array(sealed);\n if (bytes.length < HEADER.length || HEADER.some((byte, index) => bytes[index] !== byte)) {\n return {\n entries: [],\n note: `The data is not a sealed store of the format ${KEPT_SEAL_FORMAT}.`,\n };\n }\n const start = HEADER.length;\n if (bytes.length < start + SALT_BYTES + IV_BYTES + TAG_BYTES) {\n return { entries: [], note: \"The sealed store is too short, so it is damaged.\" };\n }\n const salt = bytes.slice(start, start + SALT_BYTES);\n const iv = bytes.slice(start + SALT_BYTES, start + SALT_BYTES + IV_BYTES);\n let plain: Uint8Array<ArrayBuffer>;\n try {\n const cipherKey = await keyOf(key, salt, options.label ?? \"\", \"decrypt\");\n const opened = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv, additionalData: HEADER },\n cipherKey,\n bytes.slice(start + SALT_BYTES + IV_BYTES),\n );\n plain = new Uint8Array(opened);\n } catch {\n return {\n entries: [],\n note: \"The sealed store does not open: another secret, another label, or damaged bytes.\",\n };\n }\n const read: unknown[] = [];\n const view = new DataView(plain.buffer);\n let at = 0;\n try {\n while (at < plain.length) {\n if (at + 4 > plain.length) throw new Error(\"a length is cut\");\n const length = view.getUint32(at);\n at += 4;\n if (at + length > plain.length) throw new Error(\"an entry is cut\");\n read.push(\n JSON.parse(\n decoder.decode(\n await through(plain.slice(at, at + length), new DecompressionStream(\"gzip\")),\n ),\n ),\n );\n at += length;\n }\n } catch {\n return {\n entries: readKept(read),\n note: \"An entry of the sealed store does not read, so the store gives only the entries before it.\",\n };\n }\n return { entries: readKept(read) };\n}\n","/**\n * The polite send of a documented API. It keeps the pace of each host with the scheduler of the\n * crawler (`HostScheduler`). As for the `Crawler`, `reactToOutcome` gives its reaction to each\n * answer. The send stores no page, because the terms of some APIs forbid a store.\n *\n * The transport is a port: a host gives `fetch` or a different HTTP client, and a test gives a fake.\n * The module imports no Node.js module, and it uses no type of a platform except the signal.\n *\n * The module also has the OAuth 2.0 client credentials grant (RFC 6749, section 4.4): `readGrant`,\n * `tokenStore` and `sendWithToken`. `fetchTransport` is a transport over `fetch` with a User-Agent\n * and a time limit. `poll` sends conditional requests. `freshUntil` gives the end of the freshness\n * of an answer (RFC 9111), so a client that keeps answers knows when to ask again. `keptFetch` and\n * `keepAnswer` keep the last full answer of a GET with its body, so a 304 gives the kept answer. The\n * client decides where the store is: a store is data. Each export is beta: a minor version can\n * change it.\n *\n * `keptReplies` keeps the last full reply of each URL of a poll, with the body compressed.\n */\nimport { ApiError } from \"./api-error.ts\";\nimport type { Classified } from \"./classify.ts\";\nimport { classify } from \"./classify.ts\";\nimport type { HostStateStore, Paced, PolicyOptions, ValidatorAnswer } from \"./politeness.ts\";\nimport { policyFor, restAfter, validatorsToSend } from \"./politeness.ts\";\nimport type { OutcomeFacts } from \"./reaction.ts\";\nimport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\nimport { isQuotaError } from \"./quota.ts\";\nimport type { KeepOptions, KeptStore } from \"./kept.ts\";\nimport {\n hasValidator,\n isTextType,\n keepAnswer,\n KEPT_STATUSES,\n keptKey,\n keptRequestHeaders,\n} from \"./kept.ts\";\n\nexport { ApiError, isApiError } from \"./api-error.ts\";\nexport type { Classified, Outcome } from \"./classify.ts\";\nexport { freshUntil } from \"./freshness.ts\";\nexport type { KeepOptions, Kept, KeptAnswer, KeptMemory, KeptStore } from \"./kept.ts\";\nexport {\n hasValidator,\n isTextType,\n keepAnswer,\n KEPT_BODY_MAX,\n KEPT_HEADERS,\n KEPT_STATUSES,\n keptKey,\n keptRequestHeaders,\n keptStore,\n readKept,\n} from \"./kept.ts\";\nexport type { KeptReplies, KeptReply } from \"./kept-replies.ts\";\nexport { keptReplies } from \"./kept-replies.ts\";\nexport type { OpenedKept, SealOptions } from \"./kept-seal.ts\";\nexport { KEPT_SEAL_FORMAT, KEPT_SEAL_SECRET_MIN, openKept, sealKept } from \"./kept-seal.ts\";\nexport type {\n HostCounts,\n HostResult,\n HostStateStore,\n HostStop,\n Paced,\n PolicyOptions,\n PolitenessPolicy,\n QuotaRecord,\n QuotaStore,\n ValidatorAnswer,\n ValidatorMemo,\n ValidatorReport,\n ValidatorVerdict,\n} from \"./politeness.ts\";\nexport type { HostReaction, OutcomeFacts, ReactionContext } from \"./reaction.ts\";\nexport { outcomeResult, reactToOutcome } from \"./reaction.ts\";\nexport type {\n Quota,\n QuotaGate,\n QuotaGateOptions,\n QuotaHeaders,\n QuotaReading,\n QuotaState,\n QuotaWindow,\n WithQuotaOptions,\n} from \"./quota.ts\";\nexport {\n isQuotaError,\n memoryQuotaStore,\n QuotaError,\n quotaGate,\n readQuotaHeaders,\n withQuota,\n} from \"./quota.ts\";\n\n/**\n * One request of a client to an API.\n *\n * @beta\n */\nexport interface Exchange {\n /** This value is the method of the request, for example `GET` or `POST`. */\n readonly method: string;\n readonly url: string;\n /** These are the headers of the request. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body of the request, or null. */\n readonly body: string | null;\n /**\n * This value tells how the transport reads the body of the answer. The default `text` gives the\n * body as text. With `bytes`, the reply has the body in `bytes`, and its `body` is empty.\n */\n readonly read?: \"text\" | \"bytes\" | undefined;\n}\n\n/**\n * The answer of an API to one exchange.\n *\n * @beta\n */\nexport interface Reply {\n readonly status: number;\n /** This value is the reason phrase of the status line. HTTP/2 has no reason phrase, so it can be empty. */\n readonly statusText: string;\n /** These are the headers of the answer. Each name is in lowercase. */\n readonly headers: Readonly<Record<string, string>>;\n /** This value is the body as text. It is empty when the exchange reads `bytes`. */\n readonly body: string;\n /** This value is the body as bytes, when the exchange reads `bytes`. */\n readonly bytes?: Uint8Array | undefined;\n}\n\n/**\n * The part of a signal that the send reads. An `AbortSignal` has it.\n *\n * @beta\n */\nexport interface Signal {\n readonly aborted: boolean;\n}\n\n/**\n * A transport sends one exchange and gives the answer. It does not follow a redirect. It throws an\n * error when the API gives no answer, and when the signal stops the request.\n *\n * @beta\n */\nexport type Transport<S extends Signal = AbortSignal> = (\n exchange: Exchange,\n signal: S | undefined,\n) => Promise<Reply>;\n\n/**\n * The part of a `HostScheduler` that the send uses. A `HostScheduler` has each member.\n *\n * @beta\n */\nexport interface ApiScheduler<S extends Signal = AbortSignal> {\n run<T>(host: string, task: () => Promise<Paced<T>>, signal?: S): Promise<T>;\n /**\n * This store keeps the counts and the stops of each host. When it has the validator memo\n * (`validators` and `noteValidators`), `poll` uses it as the crawler does. The two members are optional, as in\n * `HostStateStore`, so a store of `record` and `stop` is sufficient.\n */\n readonly store: Pick<HostStateStore, \"record\" | \"stop\" | \"validators\" | \"noteValidators\">;\n}\n\n/**\n * The pace of the API clients of one process. Give one pace to each client, so each host keeps one pace.\n *\n * @beta\n */\nexport interface Pace<S extends Signal = AbortSignal> {\n /** This scheduler keeps one request in progress for each host. Give the scheduler of the crawler to share its pace. */\n readonly scheduler: ApiScheduler<S>;\n /** This function gives the time in milliseconds since the epoch. Give the clock of the scheduler. */\n readonly now: () => number;\n /** This value is the politeness policy. The default is `DEFAULT_POLICY`. */\n readonly policy?: PolicyOptions | undefined;\n /** This function gives a number in [0, 1) for the jitter of a backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * This function removes each secret from the text of an error. `secrets` holds the secrets of the\n * exchange: its keys and its token.\n *\n * @beta\n */\nexport type Redact = (text: string, secrets: readonly string[]) => string;\n\n/**\n * One exchange of a client, and its context for the pace and the messages.\n *\n * @beta\n */\nexport interface Send {\n /** This value is the name of the API in a message, for example `Example API`. */\n readonly source: string;\n /** This value is the host of the URL. The scheduler keeps one pace for each host. */\n readonly host: string;\n /** This value is the documented pace of the API: the shortest time between two requests. The default is `apiIntervalMs` of the policy. */\n readonly minIntervalMs?: number | undefined;\n /** This value tells what the exchange asks for, in a message, for example `the product P-1`. */\n readonly what: string;\n readonly exchange: Exchange;\n /** These are the secrets of the exchange. The send gives them to `redact`. */\n readonly secrets?: readonly string[] | undefined;\n /**\n * This function removes the secrets from the text of each error. The default changes nothing.\n * Give a function that removes each form of a secret, for example `redactSecrets` of `@mark1russell7/text`.\n */\n readonly redact?: Redact | undefined;\n /** With true, a 401 does not stop the host. The client then gets a new token one time. */\n readonly tokenRetry?: boolean | undefined;\n}\n\n/**\n * An answer, and what it means for the host.\n *\n * @beta\n */\nexport interface Answer {\n readonly reply: Reply;\n readonly classified: Classified;\n}\n\nconst unchanged: Redact = (text) => text;\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function gives the status line of an answer for a message, with no control character.\n *\n * @beta\n */\nexport function statusLine(reply: Reply): string {\n const reason = reply.statusText\n .replace(/\\p{Cc}/gu, \" \")\n .trim()\n .slice(0, 80);\n return reason === \"\" ? String(reply.status) : `${String(reply.status)} ${reason}`;\n}\n\n/**\n * This function sends one exchange at the pace of its host. The scheduler waits the rest of the\n * host first. After the answer, `reactToOutcome` sets the rest of the host and its stops, as for\n * the `Crawler`:\n *\n * - A 429, 502, 503 or 504 parks the host for its `Retry-After`, or for a backoff with jitter.\n * - A 401 or a 403 stops the host for 1 hour. A 402 and a bot challenge stop it for 24 hours.\n * - An error 5xx and an exchange with no answer are failures. After 5 failures in sequence, the host stops.\n * - A `QuotaError` of the transport (`withQuota`) does not change the host.\n * - An `ApiError` of the transport is a refusal of the client, for example a `FetchLike` with no\n * `arrayBuffer` for an exchange that reads bytes. The host gets only its rest, and its counts do not change.\n *\n * The function gives each answer, with each status. The caller reads the status.\n *\n * @throws ApiError when the API gives no answer, or when the host is stopped. `redact` examined the message.\n * @throws QuotaError of the transport, as it is, when a quota refuses the exchange.\n * @throws the ApiError of the transport, as it is, when the transport refuses the exchange.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function send<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n input: Send,\n signal?: S,\n): Promise<Answer> {\n const { scheduler } = pace;\n const { host } = input;\n const policy = policyFor(pace.policy, host);\n const random = pace.random ?? Math.random;\n const redact = (text: string): string => (input.redact ?? unchanged)(text, input.secrets ?? []);\n const spare = input.tokenRetry === true ? [401] : undefined;\n // the reaction of the host, inside the slot of the request, as the crawler does it\n const settle = (facts: OutcomeFacts, elapsedMs: number): number => {\n const now = pace.now();\n const restMs = restAfter(policy, {\n kind: \"api\",\n elapsedMs,\n minIntervalMs: input.minIntervalMs,\n }).ms;\n const counts = scheduler.store.record(host, outcomeResult(facts));\n const reaction = reactToOutcome(facts, counts, { policy, now, restMs, random });\n if (reaction.stop !== undefined)\n scheduler.store.stop(host, reaction.stop.until, reaction.stop.reason);\n return reaction.restMs;\n };\n let attempt: Answer | { readonly error: unknown };\n try {\n attempt = await scheduler.run<Answer | { readonly error: unknown }>(\n host,\n async () => {\n const started = pace.now();\n let reply: Reply;\n try {\n reply = await transport(input.exchange, signal);\n } catch (error) {\n // a quota refused the exchange before it started, so the host keeps its state and its pace.\n // The guard accepts a refusal of another copy of the package too.\n if (isQuotaError(error)) return { value: { error }, delayMs: 0 };\n // a request that the caller stopped is no fault of the host, and neither is a refusal of the\n // client. Only an ApiError of this copy is a refusal: an error of a different library can have its name.\n const neutral = signal?.aborted === true || error instanceof ApiError;\n const facts: OutcomeFacts = {\n outcome: \"error\",\n status: 0,\n ...(neutral ? { result: \"neutral\" as const } : {}),\n };\n return { value: { error }, delayMs: settle(facts, pace.now() - started) };\n }\n const classified = classify(\n reply.status,\n (name) => reply.headers[name.toLowerCase()],\n pace.now(),\n );\n const facts: OutcomeFacts = {\n outcome: classified.outcome,\n status: reply.status,\n retryAfterMs: classified.retryAfterMs,\n spare,\n };\n return { value: { reply, classified }, delayMs: settle(facts, pace.now() - started) };\n },\n signal,\n );\n } catch (error) {\n if (signal?.aborted === true) throw error;\n throw new ApiError(\n redact(`The client of ${input.source} did not send ${input.what}: ${messageOf(error)}`),\n );\n }\n if (\"error\" in attempt) {\n const { error } = attempt;\n if (signal?.aborted === true || isQuotaError(error) || error instanceof ApiError) throw error;\n throw new ApiError(\n redact(`${input.source} gave no answer to ${input.what}: ${messageOf(error)}`),\n );\n }\n return attempt;\n}\n\n/**\n * The token of a client credentials grant, and the time when the client stops its use.\n *\n * @beta\n */\nexport interface Grant {\n readonly token: string;\n /** The client uses the token before this time, in milliseconds since the epoch. */\n readonly until: number;\n}\n\n/**\n * A client stops the use of a token this time before its end.\n *\n * @beta\n */\nexport const TOKEN_MARGIN_MS: number = 60_000;\n\n/** A token is printable ASCII with no space, from 8 to 4096 characters, so it goes into a header. */\nconst TOKEN = /^[!-~]{8,4096}$/;\n\nconst fieldOf = (value: unknown, key: string): unknown =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)\n ? (value as Record<string, unknown>)[key]\n : undefined;\n\n/**\n * This function reads the answer of a token endpoint of the OAuth 2.0 client credentials grant\n * (RFC 6749, section 4.4). The client uses the token until `TOKEN_MARGIN_MS` before its end, or\n * for half of a short life.\n *\n * @throws ApiError when the answer is not a 2xx with an `access_token` and an `expires_in`. The\n * message has no part of the body, and `redact` examined it.\n * @beta\n */\nexport function readGrant(\n reply: Reply,\n source: string,\n issuedAt: number,\n secrets: readonly string[] = [],\n redact: Redact = unchanged,\n): Grant {\n if (reply.status < 200 || reply.status > 299) {\n throw new ApiError(redact(`${source} refused the token: ${statusLine(reply)}.`, secrets));\n }\n let body: unknown;\n try {\n body = JSON.parse(reply.body);\n } catch {\n throw new ApiError(`The token answer of ${source} is not JSON.`);\n }\n const token = fieldOf(body, \"access_token\");\n const expiresIn = fieldOf(body, \"expires_in\");\n if (typeof token !== \"string\" || !TOKEN.test(token)) {\n throw new ApiError(`The token answer of ${source} has no valid access_token.`);\n }\n if (typeof expiresIn !== \"number\" || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new ApiError(`The token answer of ${source} has no valid expires_in.`);\n }\n const lifeMs = expiresIn * 1000;\n return {\n token,\n until: issuedAt + (lifeMs > 2 * TOKEN_MARGIN_MS ? lifeMs - TOKEN_MARGIN_MS : lifeMs / 2),\n };\n}\n\n/**\n * A store of one token. The exchanges that wait for a token at one time share one grant.\n *\n * @beta\n */\nexport interface Tokens<S extends Signal = AbortSignal> {\n /** This method gives a token that the client can use. With no such token, it gets a new token. */\n get(signal?: S): Promise<string>;\n /**\n * This method forgets the token after an answer 401. With a token, it forgets only that token,\n * so a second 401 of an old token does not drop a newer token.\n */\n drop(token?: string): void;\n}\n\n/**\n * This function makes a store of one token. The store gets a new token from `grant` when the token\n * ends. `now` gives the time in milliseconds since the epoch.\n *\n * @beta\n */\nexport function tokenStore<S extends Signal = AbortSignal>(\n grant: (signal: S | undefined) => Promise<Grant>,\n now: () => number,\n): Tokens<S> {\n let held: Grant | undefined;\n let pending: Promise<Grant> | undefined;\n return {\n async get(signal) {\n if (held !== undefined && now() < held.until) return held.token;\n pending ??= grant(signal).finally(() => {\n pending = undefined;\n });\n const next = await pending;\n held = next;\n return next.token;\n },\n drop(token) {\n if (token === undefined || held?.token === token) held = undefined;\n },\n };\n}\n\n/**\n * This function sends an exchange with a token. `headers` gives the headers of the token, for\n * example `authorization`. After an answer 401, the function forgets the token, gets a new token,\n * and sends the exchange one more time. A second 401 stops the host. The token goes into the\n * secrets of the messages.\n *\n * @throws ApiError as `send` does, and the error of the grant.\n * @beta\n */\nexport async function sendWithToken<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n tokens: Tokens<S>,\n input: Send,\n headers: (token: string) => Readonly<Record<string, string>>,\n signal?: S,\n): Promise<Answer> {\n const once = async (tokenRetry: boolean): Promise<{ answer: Answer; token: string }> => {\n const token = await tokens.get(signal);\n const exchange = {\n ...input.exchange,\n headers: { ...input.exchange.headers, ...headers(token) },\n };\n const secrets = [...(input.secrets ?? []), token];\n const answer = await send(pace, transport, { ...input, exchange, secrets, tokenRetry }, signal);\n return { answer, token };\n };\n const first = await once(true);\n if (first.answer.reply.status !== 401) return first.answer;\n tokens.drop(first.token);\n return (await once(false)).answer;\n}\n\n/**\n * The part of a `fetch` function that `fetchTransport` uses. The `fetch` of Node.js and of a\n * browser has it.\n *\n * @beta\n */\nexport type FetchLike = (\n url: string,\n init: {\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body?: string;\n readonly redirect: \"manual\";\n readonly signal: AbortSignal;\n },\n) => Promise<{\n readonly status: number;\n readonly statusText: string;\n readonly headers: { forEach(callback: (value: string, name: string) => void): void };\n text(): Promise<string>;\n /** The transport uses this member only for an exchange that reads `bytes`. */\n arrayBuffer?(): Promise<ArrayBuffer>;\n}>;\n\n/**\n * The default time limit of `fetchTransport`: 30 seconds for the request and its body.\n *\n * @beta\n */\nexport const API_TIMEOUT_MS: number = 30_000;\n\n/**\n * The options of `fetchTransport`.\n *\n * @beta\n */\nexport interface FetchTransportOptions {\n /**\n * This value names the client and a contact, for example `example-app/1.0 (ops@example.com)`.\n * Each request sends it, except a request with its own `user-agent` header. Some APIs, for\n * example `api.weather.gov`, refuse a request with no User-Agent.\n */\n readonly userAgent: string;\n /** This value is the time limit of one request and its body, in milliseconds. The default is `API_TIMEOUT_MS`. */\n readonly timeoutMs?: number | undefined;\n /** This function sends the request. The default is the global `fetch`. */\n readonly fetch?: FetchLike | undefined;\n}\n\n/** A User-Agent is printable ASCII, from 1 to 512 characters, with no space at an end. */\nconst USER_AGENT = /^[!-~](?:[ -~]{0,510}[!-~])?$/;\n\n/**\n * This function makes a transport over `fetch`. The transport sends the User-Agent, does not\n * follow a redirect, and stops a request after the time limit. A request that the time limit\n * stopped throws an error, and `send` counts it as a failure of the host. A request that the\n * signal stopped throws the reason of the signal. For an exchange that reads `bytes`, the\n * transport reads the body with `arrayBuffer`.\n *\n * @throws ApiError when the User-Agent is not printable ASCII, or when the time limit is not a positive number.\n * @beta\n */\nexport function fetchTransport(options: FetchTransportOptions): Transport {\n const { userAgent } = options;\n if (!USER_AGENT.test(userAgent)) {\n throw new ApiError(\n \"The transport needs a User-Agent of 1 to 512 printable ASCII characters, with no space at an end.\",\n );\n }\n const timeoutMs = options.timeoutMs ?? API_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new ApiError(\n `The time limit of the transport is not a positive number: ${String(timeoutMs)}.`,\n );\n }\n const fetchOf: FetchLike = options.fetch ?? ((url, init) => globalThis.fetch(url, init));\n return async (exchange, signal) => {\n const timeout = AbortSignal.timeout(timeoutMs);\n const both = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);\n const headers: Record<string, string> = { \"user-agent\": userAgent, ...exchange.headers };\n try {\n const response = await fetchOf(exchange.url, {\n method: exchange.method,\n headers,\n ...(exchange.body === null ? {} : { body: exchange.body }),\n redirect: \"manual\",\n signal: both,\n });\n const replyHeaders: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n replyHeaders[name.toLowerCase()] = value;\n });\n const head = {\n status: response.status,\n statusText: response.statusText,\n headers: replyHeaders,\n };\n // the time limit also stops a body that does not end\n if (exchange.read !== \"bytes\") return { ...head, body: await response.text() };\n if (response.arrayBuffer === undefined) {\n // with undici, a body that nobody reads keeps its socket until garbage collection\n await response.text().catch(() => \"\");\n throw new ApiError(\n \"The fetch function gives no arrayBuffer, so the transport cannot read bytes.\",\n );\n }\n return { ...head, body: \"\", bytes: new Uint8Array(await response.arrayBuffer()) };\n } catch (error) {\n if (timeout.aborted && signal?.aborted !== true) {\n throw new Error(`no answer in ${String(Math.ceil(timeoutMs / 1000))} s`, { cause: error });\n }\n throw error;\n }\n };\n}\n\n/**\n * This function makes a `fetch` with kept answers, for example for `fetchTransport`. A GET with no\n * body and no conditional or range header of its own (`hasValidator`) sends the validators of its\n * kept answer. The key of the answer is `keptKey`. A 304 then gives the kept answer, as\n * `keepAnswer` tells, and a full answer with a text body in UTF-8 goes into the store. The function does not read a body\n * of a different media type, so an exchange that reads `bytes` gets the bytes. Each other request\n * goes to `fetch` as it is. The key does not hold the `authorization` header: the server examines\n * the access of each request before it answers 304.\n *\n * @beta\n */\nexport function keptFetch(\n fetch: FetchLike,\n store: KeptStore,\n options: KeepOptions = {},\n): FetchLike {\n return async (url, init) => {\n const plain = init.method.toUpperCase() === \"GET\" && init.body === undefined;\n if (!plain || hasValidator(init.headers)) return fetch(url, init);\n const key = keptKey(url, init.headers);\n const kept = store.get(key);\n const response = await fetch(url, { ...init, headers: keptRequestHeaders(kept, init.headers) });\n const headers: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const unchanged = response.status === 304 && kept !== undefined;\n const full = KEPT_STATUSES.includes(response.status) && isTextType(headers[\"content-type\"]);\n if (!unchanged && !full) return response;\n const body = response.status === 304 ? \"\" : await response.text();\n const answer = keepAnswer(store, key, { status: response.status, headers, body }, options);\n return {\n status: answer.status,\n statusText: answer.notModified ? \"\" : response.statusText,\n headers: {\n forEach(callback: (value: string, name: string) => void): void {\n for (const [name, value] of Object.entries(answer.headers)) callback(value, name);\n },\n },\n text: () => Promise.resolve(answer.body),\n arrayBuffer: () => Promise.resolve(new TextEncoder().encode(answer.body).slice().buffer),\n };\n };\n}\n\n/**\n * What a poll keeps of the last answer 2xx of one URL.\n *\n * @beta\n */\nexport interface Condition {\n /** This value is the `ETag` header of the answer, when it had one. */\n readonly etag?: string | undefined;\n /** This value is the `Last-Modified` header of the answer, when it had one. */\n readonly lastModified?: string | undefined;\n /** This value is the SHA-256 of the body, in hexadecimal. */\n readonly digest: string;\n}\n\n/**\n * A store of the conditions of a poll, one for each URL. A `Map` is a store in memory. One store\n * goes with one set of request headers: give a second store to a second `accept` header.\n *\n * @beta\n */\nexport interface Conditions {\n get(url: string): Condition | undefined;\n set(url: string, condition: Condition): void;\n}\n\n/**\n * An answer of a poll.\n *\n * @beta\n */\nexport interface Polled extends Answer {\n /**\n * This value is true for an answer 2xx with a body that is not the body of the last answer 2xx\n * of the URL. It is false for a 304, for the same body, and for each other status.\n */\n readonly changed: boolean;\n}\n\nconst HEX = \"0123456789abcdef\";\n\n/** This function gives the SHA-256 of a text or of bytes, in hexadecimal. */\nconst digestOf = async (body: string | Uint8Array): Promise<string> => {\n const data = typeof body === \"string\" ? new TextEncoder().encode(body) : body;\n const bytes = new Uint8Array(await globalThis.crypto.subtle.digest(\"SHA-256\", data));\n let hex = \"\";\n for (const byte of bytes) hex += (HEX[byte >> 4] ?? \"\") + (HEX[byte & 15] ?? \"\");\n return hex;\n};\n\n/**\n * This function sends one conditional GET at the pace of its host, as `send` does. It sends the\n * validators of the last answer 2xx of the URL: `If-None-Match` with its ETag and\n * `If-Modified-Since` with its date. The store of the scheduler can have a validator memo. Then\n * the function sends only the date to a host whose ETags do not match, as the crawler does.\n *\n * A 304 gives no body: the caller keeps the result of the last changed body. A server that does\n * not answer 304 can send the same body again. The function then gives `changed: false` too.\n *\n * @throws ApiError as `send` does, and when the method is not GET.\n * @throws the reason of the signal, when the signal stops the exchange.\n * @beta\n */\nexport async function poll<S extends Signal = AbortSignal>(\n pace: Pace<S>,\n transport: Transport<S>,\n conditions: Conditions,\n input: Send,\n signal?: S,\n): Promise<Polled> {\n const { exchange, host } = input;\n if (exchange.method.toUpperCase() !== \"GET\") {\n throw new ApiError(`A poll sends only GET, not ${exchange.method}.`);\n }\n const { store } = pace.scheduler;\n const last = conditions.get(exchange.url);\n const which = validatorsToSend(\n store.validators?.(host),\n { etag: last?.etag !== undefined, lastModified: last?.lastModified !== undefined },\n pace.now(),\n );\n const headers: Record<string, string> = { ...exchange.headers };\n if (which.etag && last?.etag !== undefined) headers[\"if-none-match\"] = last.etag;\n if (which.lastModified && last?.lastModified !== undefined)\n headers[\"if-modified-since\"] = last.lastModified;\n const answer = await send(\n pace,\n transport,\n { ...input, exchange: { ...exchange, headers } },\n signal,\n );\n const { reply } = answer;\n let verdict: ValidatorAnswer | undefined;\n let changed = false;\n if (reply.status === 304) verdict = \"not-modified\";\n else if (reply.status >= 200 && reply.status <= 299) {\n const digest = await digestOf(reply.bytes ?? reply.body);\n changed = last?.digest !== digest;\n verdict = changed ? \"changed\" : \"same\";\n conditions.set(exchange.url, {\n etag: reply.headers[\"etag\"],\n lastModified: reply.headers[\"last-modified\"],\n digest,\n });\n }\n const report = {\n etag: headers[\"if-none-match\"] !== undefined,\n lastModified: headers[\"if-modified-since\"] !== undefined,\n };\n if (verdict !== undefined && (report.etag || report.lastModified))\n store.noteValidators?.(host, { ...report, answer: verdict }, pace.now());\n return { ...answer, changed };\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,IAAa,WAAb,cAA8B,MAAM;CAChB,OAAe;AACnC;;;;;AAMA,MAAM,wBAA6B,IAAI,IAAI,CAAC,YAAY,YAAY,C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cAAc,QAAQ,yBAAyB,KAAA;CACjD;CACA,IAAI,YAAY,KAAA,MAAc,OAAO,QAAQ,OAAO,eAClD,MAAM,iBAAiB,MAAM;EAAE,GAAG;EAAQ,QAAQ;CAAQ,GAAG,KAAK,IAAI,CAAC;CACzE,OAAO;EAAE,GAAG;EAAQ;CAAQ;AAC9B"}
|
|
@@ -6,7 +6,7 @@ import { n as describeDaemonStatus } from "./cli.mjs";
|
|
|
6
6
|
* error at start rejects, so the command exits with 1.
|
|
7
7
|
*/
|
|
8
8
|
const daemonCommand = async (line, options, io) => {
|
|
9
|
-
const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-
|
|
9
|
+
const { changeCommand, readDaemonState, startDaemon } = await import("./daemon-B7SbxQS2.mjs").then((n) => n.a);
|
|
10
10
|
if (line.action === "status") {
|
|
11
11
|
const state = readDaemonState(options.dir);
|
|
12
12
|
io.out(io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir));
|
|
@@ -34,4 +34,4 @@ const daemonCommand = async (line, options, io) => {
|
|
|
34
34
|
};
|
|
35
35
|
export { daemonCommand };
|
|
36
36
|
|
|
37
|
-
//# sourceMappingURL=cli-daemon-
|
|
37
|
+
//# sourceMappingURL=cli-daemon-CfJaQ_vG.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-daemon-
|
|
1
|
+
{"version":3,"file":"cli-daemon-CfJaQ_vG.mjs","names":[],"sources":["../src/cli-daemon.ts"],"sourcesContent":["/*\n * The command `daemon` of the command line: `daemon` runs the daemon until `SIGINT` or `SIGTERM`, and\n * `daemon status` prints the state file. `cli.ts` loads this file only for the command `daemon`.\n */\nimport type { DaemonLine } from \"./cli-line.ts\";\nimport { describeDaemonStatus } from \"./cli-line.ts\";\nimport type { OpenOptions } from \"./open.ts\";\n\n/** These are the parts of the command line that the command `daemon` uses. */\nexport interface DaemonIo {\n /** The value true lets `user_provided` work when the MCP client cannot ask the user. */\n readonly allowUserProvided: boolean;\n /** The value true prints the status as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n}\n\n/**\n * This function does the command `daemon`, and gives the exit code. `daemon status` gives 0 when a\n * daemon operates on the store, and 1 when none operates. `daemon` gives 0 after a clean stop. An\n * error at start rejects, so the command exits with 1.\n */\nexport const daemonCommand = async (\n line: DaemonLine,\n options: OpenOptions,\n io: DaemonIo,\n): Promise<number> => {\n const { changeCommand, readDaemonState, startDaemon } = await import(\"./daemon.ts\");\n if (line.action === \"status\") {\n const state = readDaemonState(options.dir);\n io.out(\n io.json ? JSON.stringify(state ?? null, null, 2) : describeDaemonStatus(state, options.dir),\n );\n return state?.alive === true ? 0 : 1;\n }\n const daemon = await startDaemon({\n ...options,\n tick: line.tickMs,\n jitter: line.jitterMs,\n budget: line.budgetMs,\n maxPages: line.maxPages,\n grace: line.graceMs,\n events: line.events,\n onChange: line.onChange === undefined ? undefined : changeCommand(line.onChange),\n mcp:\n line.mcp === undefined\n ? undefined\n : {\n port: line.mcp.port,\n host: line.mcp.host,\n allowRemote: line.mcp.allowRemote,\n tokenFile: line.mcp.tokenFile,\n allowUserProvided: io.allowUserProvided,\n },\n signals: true,\n });\n await daemon.done;\n return 0;\n};\n"],"mappings":";;;;;;;AAuBA,MAAa,gBAAgB,OAC3B,MACA,SACA,OACoB;CACpB,MAAM,EAAE,eAAe,iBAAiB,gBAAgB,MAAM,OAAO,wBAAc,CAAA,MAAA,MAAA,EAAA,CAAA;CACnF,IAAI,KAAK,WAAW,UAAU;EAC5B,MAAM,QAAQ,gBAAgB,QAAQ,GAAG;EACzC,GAAG,IACD,GAAG,OAAO,KAAK,UAAU,SAAS,MAAM,MAAM,CAAC,IAAI,qBAAqB,OAAO,QAAQ,GAAG,CAC5F;EACA,OAAO,OAAO,UAAU,OAAO,IAAI;CACrC;CAsBA,OAAM,MArBe,YAAY;EAC/B,GAAG;EACH,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,UAAU,KAAK,aAAa,KAAA,IAAY,KAAA,IAAY,cAAc,KAAK,QAAQ;EAC/E,KACE,KAAK,QAAQ,KAAA,IACT,KAAA,IACA;GACE,MAAM,KAAK,IAAI;GACf,MAAM,KAAK,IAAI;GACf,aAAa,KAAK,IAAI;GACtB,WAAW,KAAK,IAAI;GACpB,mBAAmB,GAAG;EACxB;EACN,SAAS;CACX,CAAC,EAAA,CACY;CACb,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as keptWeekOf, i as describeVenue, o as productCode, r as describeProduct, s as venueCode, t as UsageError } from "./cli.mjs";
|
|
2
2
|
import { compareHours, fromCompact } from "./hours.mjs";
|
|
3
|
-
import { f as readVenue, o as readProduct } from "./recipe-product-
|
|
3
|
+
import { f as readVenue, o as readProduct } from "./recipe-product-H05CkiNF.mjs";
|
|
4
4
|
// src/cli-recipes.ts
|
|
5
5
|
/**
|
|
6
6
|
* This function checks the parts of `venue` that need a file or a reader, before the store opens.
|
|
@@ -55,4 +55,4 @@ const productCommand = async (target, line, io) => {
|
|
|
55
55
|
};
|
|
56
56
|
export { prepareRecipe, productCommand, venueCommand };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=cli-recipes-
|
|
58
|
+
//# sourceMappingURL=cli-recipes-Bp_LMzOR.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-recipes-
|
|
1
|
+
{"version":3,"file":"cli-recipes-Bp_LMzOR.mjs","names":[],"sources":["../src/cli-recipes.ts"],"sourcesContent":["/*\n * The commands `venue` and `product` of the command line. They read a venue or a product page with\n * the recipes of the package (`readVenue` and `readProduct`). `cli.ts` loads this file only for these\n * two commands, so the other commands do not load the recipes.\n */\nimport type { KeptWeek, RecipeLine, VenueCompare } from \"./cli-line.ts\";\nimport {\n UsageError,\n describeProduct,\n describeVenue,\n keptWeekOf,\n productCode,\n venueCode,\n} from \"./cli-line.ts\";\nimport { compareHours, fromCompact } from \"./hours.ts\";\nimport type { RecipeTarget } from \"./recipe.ts\";\nimport type { ProductOptions } from \"./recipe-product.ts\";\nimport { readProduct } from \"./recipe-product.ts\";\nimport type { VenueOptions } from \"./recipe-venue.ts\";\nimport { readVenue } from \"./recipe-venue.ts\";\n\n/** These are the parts of the command line that `venue` and `product` use. */\nexport interface RecipeIo {\n /** The value true prints the result as JSON. */\n readonly json: boolean;\n /** This function prints a line on the standard output. */\n readonly out: (text: string) => void;\n /** This text tells why rendering is off, when the computer has no browser. */\n readonly renderOff?: string | undefined;\n}\n\n/** These are the inputs of `venue` that the command reads before the store opens. */\nexport interface RecipeInput {\n /** This value is the kept week of `--compare`, or undefined with no `--compare`. */\n readonly kept: KeptWeek | undefined;\n}\n\n/**\n * This function checks the parts of `venue` that need a file or a reader, before the store opens.\n * They are the kept week of `--compare` and the value of `--osm`. An error is a usage error.\n */\nexport const prepareRecipe = (line: RecipeLine): RecipeInput => {\n if (line.osm !== undefined && fromCompact(line.osm, \"osm\") === undefined) {\n throw new UsageError(\n `--osm: the hours reader cannot read \"${line.osm}\". Write an opening_hours value, such as \"Mo-Fr 08:00-18:00; Sa 09:00-13:00\"`,\n );\n }\n return { kept: line.compare === undefined ? undefined : keptWeekOf(line.compare) };\n};\n\n/** This function gives the options of the recipe that `venue` and `product` share. */\nconst sharedOptions = (line: RecipeLine): ProductOptions => ({\n render: line.render,\n maxAge: line.maxAge,\n budget: line.budget,\n onBehalfOf: line.onBehalfOf,\n userProvided: line.userProvided,\n fallback: line.fallback,\n archiveDespiteRobots: line.archiveDespiteRobots,\n});\n\n/**\n * This function does the command `venue`, and gives the exit code. It reads the hours of the venue\n * with `readVenue`. With `--compare`, it compares the week of the site (`from_site`) with the kept\n * week through `compareHours`.\n */\nexport const venueCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n input: RecipeInput,\n io: RecipeIo,\n): Promise<number> => {\n const options: VenueOptions = {\n ...sharedOptions(line),\n name: line.name,\n requireName: line.requireName,\n location: line.location,\n osm: line.osm,\n pages: line.pages,\n };\n const result = await readVenue(target, line.url, options);\n const site = result.from_site;\n const compare: VenueCompare | undefined =\n input.kept === undefined\n ? undefined\n : {\n file: input.kept.file,\n kept: input.kept.week,\n comparison: site === null ? null : compareHours(input.kept.week, site.week),\n };\n io.out(\n io.json\n ? JSON.stringify(compare === undefined ? result : { ...result, compare }, null, 2)\n : describeVenue(result, compare, io.renderOff).join(\"\\n\"),\n );\n return venueCode(result);\n};\n\n/** This function does the command `product`, and gives the exit code. It reads the page with `readProduct`. */\nexport const productCommand = async (\n target: RecipeTarget,\n line: RecipeLine,\n io: RecipeIo,\n): Promise<number> => {\n const result = await readProduct(target, line.url, sharedOptions(line));\n io.out(\n io.json ? JSON.stringify(result, null, 2) : describeProduct(result, io.renderOff).join(\"\\n\"),\n );\n return productCode(result);\n};\n"],"mappings":";;;;;;;;AAyCA,MAAa,iBAAiB,SAAkC;CAC9D,IAAI,KAAK,QAAQ,KAAA,KAAa,YAAY,KAAK,KAAK,KAAK,MAAM,KAAA,GAC7D,MAAM,IAAI,WACR,wCAAwC,KAAK,IAAI,6EACnD;CAEF,OAAO,EAAE,MAAM,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,WAAW,KAAK,OAAO,EAAE;AACnF;;AAGA,MAAM,iBAAiB,UAAsC;CAC3D,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,QAAQ,KAAK;CACb,YAAY,KAAK;CACjB,cAAc,KAAK;CACnB,UAAU,KAAK;CACf,sBAAsB,KAAK;AAC7B;;;;;;AAOA,MAAa,eAAe,OAC1B,QACA,MACA,OACA,OACoB;CACpB,MAAM,UAAwB;EAC5B,GAAG,cAAc,IAAI;EACrB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,UAAU,KAAK;EACf,KAAK,KAAK;EACV,OAAO,KAAK;CACd;CACA,MAAM,SAAS,MAAM,UAAU,QAAQ,KAAK,KAA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