polite-crawler 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +22 -0
  2. package/build/{cli-daemon--cTmq0Z5.mjs → cli-daemon-ZYRdy6EW.mjs} +3 -3
  3. package/build/{cli-daemon--cTmq0Z5.mjs.map → cli-daemon-ZYRdy6EW.mjs.map} +1 -1
  4. package/build/cli-recipes-Bci6HREA.mjs +59 -0
  5. package/build/cli-recipes-Bci6HREA.mjs.map +1 -0
  6. package/build/cli.mjs +397 -18
  7. package/build/cli.mjs.map +1 -1
  8. package/build/{daemon-fZTE24P5.mjs → daemon-DK6U51_v.mjs} +3 -3
  9. package/build/{daemon-fZTE24P5.mjs.map → daemon-DK6U51_v.mjs.map} +1 -1
  10. package/build/{daemon-DP4EqjFL.d.mts → daemon-wwIWsUmU.d.mts} +7 -2
  11. package/build/{diff-NQcQqKe9.mjs → diff-BUM91Rev.mjs} +2 -2
  12. package/build/{diff-NQcQqKe9.mjs.map → diff-BUM91Rev.mjs.map} +1 -1
  13. package/build/{extract-ByFfc8Zk.mjs → extract-CefB5Vfn.mjs} +2 -2
  14. package/build/{extract-ByFfc8Zk.mjs.map → extract-CefB5Vfn.mjs.map} +1 -1
  15. package/build/index.d.mts +2 -2
  16. package/build/index.mjs +10 -894
  17. package/build/mcp.d.mts +1 -1
  18. package/build/mcp.mjs +4 -4
  19. package/build/{open-C4fhXJgD.mjs → open-CbpSCEZc.mjs} +12 -284
  20. package/build/open-CbpSCEZc.mjs.map +1 -0
  21. package/build/recipe-GiFQojmo.mjs +279 -0
  22. package/build/recipe-GiFQojmo.mjs.map +1 -0
  23. package/build/recipe-product-Dellqudu.mjs +892 -0
  24. package/build/recipe-product-Dellqudu.mjs.map +1 -0
  25. package/build/{runtime-JToRO63o.mjs → runtime-D_r2SYge.mjs} +2 -2
  26. package/build/{runtime-JToRO63o.mjs.map → runtime-D_r2SYge.mjs.map} +1 -1
  27. package/build/{version-ntbY-6wh.mjs → version-BPem-XZd.mjs} +2 -2
  28. package/build/{version-ntbY-6wh.mjs.map → version-BPem-XZd.mjs.map} +1 -1
  29. package/build/{wacz-BFNG42Kt.mjs → wacz-QyzLp4mC.mjs} +3 -3
  30. package/build/{wacz-BFNG42Kt.mjs.map → wacz-QyzLp4mC.mjs.map} +1 -1
  31. package/build/{warc-CVS0t1fW.mjs → warc-BHcaRKHw.mjs} +2 -2
  32. package/build/{warc-CVS0t1fW.mjs.map → warc-BHcaRKHw.mjs.map} +1 -1
  33. package/build/webbotauth-CjJdTAfE.mjs.map +1 -1
  34. package/package.json +1 -1
  35. package/build/index.mjs.map +0 -1
  36. package/build/open-C4fhXJgD.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"webbotauth-CjJdTAfE.mjs","names":["signBytes","verifyBytes"],"sources":["../src/webbotauth.ts"],"sourcesContent":["import type { JsonWebKey, KeyObject } from \"node:crypto\";\nimport {\n createHash,\n createPrivateKey,\n createPublicKey,\n randomBytes,\n sign as signBytes,\n verify as verifyBytes,\n} from \"node:crypto\";\n\n/**\n * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells\n * (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that\n * a request comes from the holder of a key that the operator publishes.\n *\n * - Each request gets three headers: `Signature-Agent`, `Signature-Input` and `Signature`.\n * - `Signature-Agent` is a dictionary. Its member names the key directory of the operator.\n * - The signature covers `@authority` and that member of `Signature-Agent`.\n * - The parameters are `created`, `keyid` (the JWK thumbprint of the key), `alg=\"ed25519\"`,\n * `expires`, a random `nonce` and `tag=\"web-bot-auth\"`.\n * - The key is an Ed25519 key, and `node:crypto` signs. The package adds no dependency.\n *\n * A signature adds an identity. It does not replace the `User-Agent` header, which stays honest.\n */\n\n/** The path of the key directory on the host of the operator (the well-known URI of the draft). */\nexport const KEY_DIRECTORY_PATH = \"/.well-known/http-message-signatures-directory\";\n\n/** The media type of the key directory. The host of the directory sends it as `Content-Type`. */\nexport const KEY_DIRECTORY_TYPE = \"application/http-message-signatures-directory+json\";\n\n/** The value of the `tag` parameter of a Web Bot Auth signature. */\nexport const WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n\n/**\n * This value tells how a site finds the keys from the URL of `Signature-Agent`:\n *\n * - `directory` (the default): the URL is an origin, and the keys are at `KEY_DIRECTORY_PATH` on it.\n * - `jwks_uri`: the URL is the address of a JSON Web Key Set, on any path.\n */\nexport type SignatureAgentType = \"directory\" | \"jwks_uri\";\n\n/** A key in one of the forms that `node:crypto` reads: a `KeyObject`, PEM text, DER bytes (PKCS#8 or SPKI) or a JWK. */\nexport type KeyInput = KeyObject | string | Uint8Array | JsonWebKey;\n\n/** These options make a signer for Web Bot Auth. */\nexport interface WebBotAuthOptions {\n /** This key signs. It is an Ed25519 private key: a `KeyObject`, PKCS#8 (PEM text or DER bytes) or a JWK with `d`. */\n readonly privateKey: KeyInput;\n /**\n * This text is the `keyid` of each signature: the JWK thumbprint of the key (RFC 8037). The signer\n * calculates it. A value that is not the thumbprint of the key throws an error.\n */\n readonly keyId?: string | undefined;\n /**\n * This URL tells a site where the keys are. For the type `directory`, it is an https origin, for\n * example `https://bot.example.com`. For `jwks_uri`, it is the https URL of a JSON Web Key Set.\n */\n readonly signatureAgent: string;\n /** This value tells how a site finds the keys from `signatureAgent`. The default is `directory`. */\n readonly agentType?: SignatureAgentType | undefined;\n /** This value is the time that a signature stays valid, in milliseconds. The default is 5 minutes, and the maximum is 24 hours. */\n readonly lifetimeMs?: number | undefined;\n /** This text is the label of the signature, and the key of the member of `Signature-Agent`. The default is `sig1`. */\n readonly label?: string | undefined;\n}\n\n/**\n * A request signer gives the signature headers of one request. The crawler uses it for each\n * request, robots.txt too. `createWebBotAuthSigner` makes one. A signer of your own can sign with a\n * key in a hardware module, for example.\n */\nexport interface RequestSigner {\n /** This text is the `keyid` of the signatures. */\n readonly keyId: string;\n /** This URL is the value of the member of `Signature-Agent`: where a site finds the keys. */\n readonly signatureAgent: string;\n /** This method gives the headers that sign a request to `url` at the time `now` (milliseconds since the epoch). */\n sign(url: URL, now: number): Readonly<Record<string, string>>;\n}\n\n/** The signer that `createWebBotAuthSigner` makes. It also gives its public key for the key directory. */\nexport interface WebBotAuthSigner extends RequestSigner {\n /** This JWK is the public key of the signer, with no private part. Give it to `keyDirectory`. */\n readonly publicKey: JsonWebKey;\n}\n\n/** One key of a key directory: an Ed25519 public key as a JWK, with its thumbprint as `kid`. */\nexport interface DirectoryKey {\n readonly kty: \"OKP\";\n readonly crv: \"Ed25519\";\n readonly kid: string;\n readonly x: string;\n readonly use: \"sig\";\n}\n\n/** A key directory: a JSON Web Key Set. The operator serves it as JSON at `KEY_DIRECTORY_PATH`, with the type `KEY_DIRECTORY_TYPE`. */\nexport interface KeyDirectory {\n readonly keys: readonly DirectoryKey[];\n}\n\n/** The parts of a request that `verifySignature` reads. */\nexport interface SignedRequest {\n readonly url: string;\n /** The default is `GET`. */\n readonly method?: string | undefined;\n /** These are the headers of the request. A name can be in any case, and a header can have more than one line. */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n}\n\n/** The result of `verifySignature`. */\nexport interface SignatureCheck {\n /** This value is true when a Web Bot Auth signature of the request verifies with a key of the directory. */\n readonly verified: boolean;\n /** This text is the label of the signature that the check examined last, or null. */\n readonly label: string | null;\n readonly keyId: string | null;\n /** This URL is the member of `Signature-Agent` that the signature covers, or null. */\n readonly agent: string | null;\n /** This text tells why the request does not verify. It is null when it verifies. */\n readonly reason: string | null;\n}\n\n// ── structured fields (RFC 9651): the parts that the signature headers use ──\n\n/** A token of a structured field, for example `ed25519` in `alg=ed25519`. */\nclass Token {\n constructor(readonly value: string) {}\n}\n\ntype BareItem = string | number | boolean | Uint8Array | Token;\ntype Params = ReadonlyArray<readonly [string, BareItem]>;\n\ninterface Item {\n readonly value: BareItem;\n readonly params: Params;\n}\n\ninterface InnerList {\n readonly items: readonly Item[];\n readonly params: Params;\n}\n\ntype Member = Item | InnerList;\n\nconst isInnerList = (member: Member): member is InnerList => \"items\" in member;\n\n/** This error tells that a structured field does not parse. */\nclass FieldError extends Error {}\n\nconst KEY_START = /[a-z*]/;\nconst KEY_CHAR = /[a-z0-9_\\-.*]/;\nconst TOKEN_START = /[A-Za-z*]/;\nconst TOKEN_CHAR = /[!#$%&'*+\\-.^_`|~0-9A-Za-z:/]/;\nconst BASE64 = /^[A-Za-z0-9+/=]*$/;\n\n/** This class reads one structured field from its text. */\nclass FieldParser {\n private at = 0;\n constructor(private readonly text: string) {}\n\n private peek(): string {\n return this.text[this.at] ?? \"\";\n }\n\n private spaces(): void {\n while (this.peek() === \" \") this.at += 1;\n }\n\n private ows(): void {\n while (this.peek() === \" \" || this.peek() === \"\\t\") this.at += 1;\n }\n\n dictionary(): Map<string, Member> {\n const out = new Map<string, Member>();\n this.spaces();\n while (this.at < this.text.length) {\n const key = this.key();\n let member: Member;\n if (this.peek() === \"=\") {\n this.at += 1;\n member = this.peek() === \"(\" ? this.innerList() : this.item();\n } else {\n member = { value: true, params: this.params() };\n }\n out.set(key, member);\n this.ows();\n if (this.at >= this.text.length) break;\n if (this.peek() !== \",\") throw new FieldError(`a \",\" is necessary at ${String(this.at)}`);\n this.at += 1;\n this.ows();\n if (this.at >= this.text.length) throw new FieldError(\"the field ends with a comma\");\n }\n return out;\n }\n\n /** This method reads one item and checks that the field has nothing after it. */\n wholeItem(): Item {\n this.spaces();\n const item = this.item();\n this.spaces();\n if (this.at < this.text.length) throw new FieldError(\"text after the item\");\n return item;\n }\n\n private key(): string {\n if (!KEY_START.test(this.peek())) throw new FieldError(`no key at ${String(this.at)}`);\n const start = this.at;\n while (KEY_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return this.text.slice(start, this.at);\n }\n\n private innerList(): InnerList {\n this.at += 1;\n const items: Item[] = [];\n for (;;) {\n this.spaces();\n if (this.peek() === \")\") {\n this.at += 1;\n return { items, params: this.params() };\n }\n if (this.at >= this.text.length) throw new FieldError(\"an inner list has no end\");\n items.push(this.item());\n if (this.peek() !== \" \" && this.peek() !== \")\")\n throw new FieldError(`a space or \")\" is necessary at ${String(this.at)}`);\n }\n }\n\n private item(): Item {\n const value = this.bare();\n return { value, params: this.params() };\n }\n\n private params(): Params {\n const out: Array<readonly [string, BareItem]> = [];\n while (this.peek() === \";\") {\n this.at += 1;\n this.spaces();\n const key = this.key();\n let value: BareItem = true;\n if (this.peek() === \"=\") {\n this.at += 1;\n value = this.bare();\n }\n const known = out.findIndex(([name]) => name === key);\n if (known === -1) out.push([key, value]);\n else out[known] = [key, value];\n }\n return out;\n }\n\n private bare(): BareItem {\n const char = this.peek();\n if (char === \"-\" || /[0-9]/.test(char)) return this.number();\n if (char === '\"') return this.string();\n if (char === \":\") return this.bytes();\n if (char === \"?\") return this.boolean();\n if (TOKEN_START.test(char)) return this.token();\n throw new FieldError(`no item at ${String(this.at)}`);\n }\n\n private number(): number {\n const match = /^-?(\\d{1,15})(\\.\\d{1,3})?/.exec(this.text.slice(this.at));\n if (match === null || (match[2] !== undefined && match[1]!.length > 12))\n throw new FieldError(`not a number at ${String(this.at)}`);\n this.at += match[0].length;\n return Number(match[0]);\n }\n\n private string(): string {\n this.at += 1;\n let out = \"\";\n for (;;) {\n const char = this.peek();\n if (char === \"\") throw new FieldError(\"a string has no end\");\n this.at += 1;\n if (char === \"\\\\\") {\n const next = this.peek();\n if (next !== '\"' && next !== \"\\\\\") throw new FieldError(\"a bad escape in a string\");\n out += next;\n this.at += 1;\n } else if (char === '\"') {\n return out;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code > 0x7e)\n throw new FieldError(\"a string holds a character that is not printable ASCII\");\n out += char;\n }\n }\n }\n\n private bytes(): Uint8Array {\n this.at += 1;\n const end = this.text.indexOf(\":\", this.at);\n if (end === -1) throw new FieldError(\"a byte sequence has no end\");\n const text = this.text.slice(this.at, end);\n if (!BASE64.test(text)) throw new FieldError(\"a byte sequence is not base64\");\n this.at = end + 1;\n return new Uint8Array(Buffer.from(text, \"base64\"));\n }\n\n private boolean(): boolean {\n const value = this.text.slice(this.at, this.at + 2);\n if (value !== \"?1\" && value !== \"?0\") throw new FieldError(\"not a boolean\");\n this.at += 2;\n return value === \"?1\";\n }\n\n private token(): Token {\n const start = this.at;\n this.at += 1;\n while (TOKEN_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return new Token(this.text.slice(start, this.at));\n }\n}\n\nconst serializeBare = (value: BareItem): string => {\n if (value instanceof Token) return value.value;\n if (value instanceof Uint8Array) return `:${Buffer.from(value).toString(\"base64\")}:`;\n if (typeof value === \"boolean\") return value ? \"?1\" : \"?0\";\n if (typeof value === \"number\")\n return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);\n return `\"${value.replace(/[\"\\\\]/g, (char) => `\\\\${char}`)}\"`;\n};\n\nconst serializeParams = (params: Params): string =>\n params\n .map(([key, value]) => (value === true ? `;${key}` : `;${key}=${serializeBare(value)}`))\n .join(\"\");\n\nconst serializeItem = (item: Item): string =>\n `${serializeBare(item.value)}${serializeParams(item.params)}`;\n\nconst serializeMember = (member: Member): string =>\n isInnerList(member)\n ? `(${member.items.map(serializeItem).join(\" \")})${serializeParams(member.params)}`\n : serializeItem(member);\n\n/** This function tells if a text is a key of a structured field: a label of a signature, for example. */\nconst isKey = (text: string): boolean => /^[a-z*][a-z0-9_\\-.*]*$/.test(text);\n\n// ── keys ──\n\nconst base64url = (bytes: Uint8Array): string => Buffer.from(bytes).toString(\"base64url\");\n\nconst isKeyObject = (key: KeyInput): key is KeyObject =>\n typeof key === \"object\" && key !== null && \"asymmetricKeyType\" in key && \"export\" in key;\n\n/** This function reads a private key. Its errors do not hold the key. */\nconst privateKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPrivateKey({ key: JSON.parse(input) as JsonWebKey, format: \"jwk\" })\n : createPrivateKey(input);\n else if (input instanceof Uint8Array)\n key = createPrivateKey({ key: Buffer.from(input), format: \"der\", type: \"pkcs8\" });\n else key = createPrivateKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\n \"the private key of the signer does not parse: give an Ed25519 key as PKCS#8 (PEM or DER) or as a JWK\",\n { cause },\n );\n }\n if (key.type !== \"private\")\n throw new Error(\"the key of the signer is not a private key: give the Ed25519 private key\");\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `the key of the signer is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519: Web Bot Auth here uses Ed25519 keys`,\n );\n return key;\n};\n\n/** This function reads a public key, or the public part of a private key. Its errors do not hold the key. */\nconst publicKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input.type === \"private\" ? createPublicKey(input) : input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPublicKey({ key: JSON.parse(input) as JsonWebKey, format: \"jwk\" })\n : createPublicKey(input);\n else if (input instanceof Uint8Array) {\n const bytes = Buffer.from(input);\n try {\n key = createPublicKey({ key: bytes, format: \"der\", type: \"spki\" });\n } catch {\n key = createPublicKey(createPrivateKey({ key: bytes, format: \"der\", type: \"pkcs8\" }));\n }\n } else key = createPublicKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\"a key of the directory does not parse: give an Ed25519 key\", { cause });\n }\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `a key of the directory is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519`,\n );\n return key;\n};\n\n/** This function gives the JWK thumbprint of an Ed25519 public key (RFC 7638, RFC 8037 appendix A.3). */\nconst thumbprintOf = (x: string): string =>\n base64url(\n createHash(\"sha256\")\n .update(JSON.stringify({ crv: \"Ed25519\", kty: \"OKP\", x }), \"utf8\")\n .digest(),\n );\n\nconst directoryKeyOf = (key: KeyObject): DirectoryKey => {\n const jwk = key.export({ format: \"jwk\" });\n const x = typeof jwk.x === \"string\" ? jwk.x : \"\";\n return { kty: \"OKP\", crv: \"Ed25519\", kid: thumbprintOf(x), x, use: \"sig\" };\n};\n\n/**\n * This function makes the key directory for the operator to host: a JSON Web Key Set with each\n * public key and its thumbprint as `kid`. It takes public keys, or private keys, and it writes only\n * their public parts. Serve the JSON at `KEY_DIRECTORY_PATH` with the type `KEY_DIRECTORY_TYPE`.\n */\nexport const keyDirectory = (publicKeys: readonly KeyInput[]): KeyDirectory => {\n const keys = new Map<string, DirectoryKey>();\n for (const input of publicKeys) {\n const key = directoryKeyOf(publicKeyOf(input));\n keys.set(key.kid, key);\n }\n return { keys: [...keys.values()] };\n};\n\n// ── signing ──\n\n/** The parts of one signature. The signer and the tests use this function. */\nexport interface SignatureParts {\n /** The value of `@authority`: the host and a port that is not the default port, in lowercase. */\n readonly authority: string;\n readonly label: string;\n /** The key of the member of `Signature-Agent`. The draft uses the label of the signature. */\n readonly agentKey: string;\n /** The serialized value of the member: a string, and its parameters. */\n readonly agentValue: string;\n readonly keyId: string;\n readonly created: number;\n readonly expires: number;\n readonly nonce?: string | undefined;\n}\n\n/** This function gives the `@signature-params` value: the covered components and the parameters, in the order of the draft. */\nconst signatureParams = (parts: SignatureParts): string =>\n `(\"@authority\" \"signature-agent\";key=${serializeBare(parts.agentKey)});created=${String(parts.created)};keyid=${serializeBare(parts.keyId)};alg=\"ed25519\";expires=${String(parts.expires)}${parts.nonce === undefined ? \"\" : `;nonce=${serializeBare(parts.nonce)}`};tag=\"${WEB_BOT_AUTH_TAG}\"`;\n\n/** This function gives the signature base of RFC 9421, section 2.5, for the components of Web Bot Auth. */\nexport const signatureBase = (parts: SignatureParts): string =>\n [\n `\"@authority\": ${parts.authority}`,\n `\"signature-agent\";key=${serializeBare(parts.agentKey)}: ${parts.agentValue}`,\n `\"@signature-params\": ${signatureParams(parts)}`,\n ].join(\"\\n\");\n\n/** This function signs the parts with an Ed25519 key, and gives the three headers. */\nexport const signParts = (\n parts: SignatureParts,\n key: KeyObject,\n): {\n readonly \"signature-agent\": string;\n readonly \"signature-input\": string;\n readonly signature: string;\n} => {\n const signature = signBytes(null, Buffer.from(signatureBase(parts), \"utf8\"), key);\n return {\n \"signature-agent\": `${parts.agentKey}=${parts.agentValue}`,\n \"signature-input\": `${parts.label}=${signatureParams(parts)}`,\n signature: `${parts.label}=:${signature.toString(\"base64\")}:`,\n };\n};\n\nconst DEFAULT_LIFETIME_MS = 5 * 60_000;\nconst MAX_LIFETIME_MS = 24 * 60 * 60_000;\n\n/** This function checks the URL of `Signature-Agent`, and gives the URL and the serialized value of the member. */\nconst agentOf = (\n url: string,\n type: SignatureAgentType,\n): { readonly url: string; readonly value: string } => {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new Error(\n `signatureAgent \"${url}\" is not a URL: give the https URL of the key directory`,\n );\n }\n if (target.protocol !== \"https:\")\n throw new Error(`signatureAgent \"${url}\" is not an https URL: the draft permits only https`);\n if (target.username !== \"\" || target.password !== \"\" || target.hash !== \"\")\n throw new Error(`signatureAgent \"${url}\" has a user name, a password or a fragment`);\n if (type === \"directory\") {\n if (target.pathname !== \"/\" || target.search !== \"\")\n throw new Error(\n `signatureAgent \"${url}\" is not an origin: the type directory takes only an origin, such as https://bot.example.com. For a key set on a path, set agentType to jwks_uri`,\n );\n return { url: target.origin, value: serializeBare(target.origin) };\n }\n return { url: target.href, value: `${serializeBare(target.href)};type=${type}` };\n};\n\n/**\n * This function makes a signer for Web Bot Auth with an Ed25519 key. Each signature covers\n * `@authority` and the member of `Signature-Agent`. It has a new random nonce, and it expires after\n * `lifetimeMs`. The signer keeps the private key in a closure: no property of the signer holds it.\n */\nexport const createWebBotAuthSigner = (options: WebBotAuthOptions): WebBotAuthSigner => {\n const key = privateKeyOf(options.privateKey);\n const publicKey = directoryKeyOf(createPublicKey(key));\n if (options.keyId !== undefined && options.keyId !== publicKey.kid)\n throw new Error(\n `keyId \"${options.keyId}\" is not the JWK thumbprint of the key (${publicKey.kid}): Web Bot Auth uses the thumbprint as keyid`,\n );\n const agent = agentOf(options.signatureAgent, options.agentType ?? \"directory\");\n const label = options.label ?? \"sig1\";\n if (!isKey(label))\n throw new Error(\n `label \"${label}\" is not a key of a structured field: use lowercase letters, digits, \"_\", \"-\", \".\" and \"*\"`,\n );\n const lifetimeMs = options.lifetimeMs ?? DEFAULT_LIFETIME_MS;\n if (!Number.isFinite(lifetimeMs) || lifetimeMs < 1000 || lifetimeMs > MAX_LIFETIME_MS)\n throw new RangeError(\n `lifetimeMs must be from 1000 (1 second) to ${String(MAX_LIFETIME_MS)} (24 hours), not ${String(lifetimeMs)}`,\n );\n const { kty, crv, x } = publicKey;\n return {\n keyId: publicKey.kid,\n signatureAgent: agent.url,\n publicKey: { kty, crv, x },\n sign(url, now) {\n const created = Math.floor(now / 1000);\n return signParts(\n {\n authority: url.host.toLowerCase(),\n label,\n agentKey: label,\n agentValue: agent.value,\n keyId: publicKey.kid,\n created,\n expires: created + Math.ceil(lifetimeMs / 1000),\n nonce: randomBytes(32).toString(\"base64\"),\n },\n key,\n );\n },\n };\n};\n\n/** This function tells if a value is a request signer, not the options of one. */\nexport const isRequestSigner = (value: RequestSigner | WebBotAuthOptions): value is RequestSigner =>\n typeof (value as Partial<RequestSigner>).sign === \"function\";\n\n/** This function gives a request signer: the signer itself, or a new signer from its options. */\nexport const signerOf = (\n value: RequestSigner | WebBotAuthOptions | undefined,\n): RequestSigner | undefined =>\n value === undefined ? undefined : isRequestSigner(value) ? value : createWebBotAuthSigner(value);\n\n// ── verification ──\n\n/** A signature can start this long before the clock of the verifier, for a small difference of the clocks. */\nconst CLOCK_SKEW_S = 60;\n\nconst headerLines = (\n headers: SignedRequest[\"headers\"],\n name: string,\n): readonly string[] | undefined => {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== name || value === undefined) continue;\n return typeof value === \"string\" ? [value] : value;\n }\n return undefined;\n};\n\n/** This function gives the value of a header as RFC 9421 section 2.1 combines it: each line without its outer spaces, with \", \" between. */\nconst fieldValue = (headers: SignedRequest[\"headers\"], name: string): string | undefined =>\n headerLines(headers, name)\n ?.map((line) => line.replace(/\\r?\\n[ \\t]+/g, \" \").trim())\n .join(\", \");\n\n/** This function gives the value of one component of a request, or an error text. */\nconst componentValue = (\n component: Item,\n request: SignedRequest,\n target: URL,\n): { readonly value: string } | { readonly error: string } => {\n const name = component.value;\n if (typeof name !== \"string\") return { error: \"a component is not a string\" };\n const params = new Map(component.params);\n if (name.startsWith(\"@\")) {\n if (params.size > 0) return { error: `the parameters of ${name} are not supported` };\n switch (name) {\n case \"@method\":\n return { value: (request.method ?? \"GET\").toUpperCase() };\n case \"@authority\":\n return { value: target.host.toLowerCase() };\n case \"@scheme\":\n return { value: target.protocol.slice(0, -1).toLowerCase() };\n case \"@target-uri\":\n return { value: target.href };\n case \"@path\":\n return { value: target.pathname === \"\" ? \"/\" : target.pathname };\n case \"@query\":\n return { value: target.search === \"\" ? \"?\" : target.search };\n case \"@request-target\":\n return { value: `${target.pathname}${target.search}` };\n default:\n return { error: `the component ${name} is not supported` };\n }\n }\n const value = fieldValue(request.headers, name);\n if (value === undefined) return { error: `the request has no ${name} header` };\n if ([...params.keys()].some((param) => param !== \"key\"))\n return { error: `the parameters of ${name} are not supported` };\n const key = params.get(\"key\");\n if (key === undefined) return { value };\n if (typeof key !== \"string\") return { error: `the key of ${name} is not a string` };\n let member: Member | undefined;\n try {\n member = new FieldParser(value).dictionary().get(key);\n } catch (error) {\n return { error: `the ${name} header is not a dictionary: ${(error as Error).message}` };\n }\n if (member === undefined) return { error: `the ${name} header has no member ${key}` };\n return { value: serializeMember(member) };\n};\n\nconst failed = (\n reason: string,\n facts: { label?: string | null; keyId?: string | null; agent?: string | null } = {},\n): SignatureCheck => ({\n verified: false,\n label: facts.label ?? null,\n keyId: facts.keyId ?? null,\n agent: facts.agent ?? null,\n reason,\n});\n\n/**\n * This function verifies the Web Bot Auth signatures of a request with the keys of a directory. It\n * applies RFC 9421 section 3.2 and the profile of the draft. The profile asks for the tag\n * `web-bot-auth`, `created`, `expires` and `@authority`. It also asks for the member of\n * `Signature-Agent`, and a key with the thumbprint of `keyid`. The tests use it, and an operator can check a setup with it. It sends no request.\n */\nexport const verifySignature = (\n request: SignedRequest,\n directory: KeyDirectory,\n options: { readonly now?: number | undefined } = {},\n): SignatureCheck => {\n let target: URL;\n try {\n target = new URL(request.url);\n } catch {\n return failed(\"the URL of the request is not a URL\");\n }\n const inputText = fieldValue(request.headers, \"signature-input\");\n const signatureText = fieldValue(request.headers, \"signature\");\n if (inputText === undefined || signatureText === undefined)\n return failed(\"the request has no Signature-Input or no Signature header\");\n let inputs: Map<string, Member>;\n let signatures: Map<string, Member>;\n try {\n inputs = new FieldParser(inputText).dictionary();\n signatures = new FieldParser(signatureText).dictionary();\n } catch (error) {\n return failed(`a signature header does not parse: ${(error as Error).message}`);\n }\n const now = Math.floor((options.now ?? Date.now()) / 1000);\n const keys = new Map<string, KeyObject>();\n for (const entry of directory.keys) {\n try {\n const key = createPublicKey({\n key: { kty: entry.kty, crv: entry.crv, x: entry.x },\n format: \"jwk\",\n });\n keys.set(thumbprintOf(entry.x), key);\n } catch {\n // a key that does not parse verifies nothing\n }\n }\n let last: SignatureCheck = failed(\"the request has no Web Bot Auth signature\");\n for (const [label, input] of inputs) {\n if (!isInnerList(input)) continue;\n const params = new Map(input.params);\n if (params.get(\"tag\") !== WEB_BOT_AUTH_TAG) continue;\n const keyId = typeof params.get(\"keyid\") === \"string\" ? (params.get(\"keyid\") as string) : null;\n const covered = input.items;\n const names = covered.map((item) => serializeItem(item));\n const agentItem = covered.find((item) => item.value === \"signature-agent\");\n let agent: string | null = null;\n if (agentItem !== undefined) {\n const value = componentValue(agentItem, request, target);\n if (\"value\" in value) {\n try {\n const member = new FieldParser(value.value).wholeItem().value;\n agent = typeof member === \"string\" ? member : null;\n } catch {\n agent = null;\n }\n }\n }\n const facts = { label, keyId, agent };\n if (new Set(names).size !== names.length) {\n last = failed(\"a component is covered two times\", facts);\n continue;\n }\n if (!names.includes('\"@authority\"') && !names.includes('\"@target-uri\"')) {\n last = failed(\"the signature does not cover @authority or @target-uri\", facts);\n continue;\n }\n if (agentItem === undefined) {\n last = failed(\"the signature does not cover Signature-Agent\", facts);\n continue;\n }\n const created = params.get(\"created\");\n const expires = params.get(\"expires\");\n if (typeof created !== \"number\" || typeof expires !== \"number\") {\n last = failed(\"the signature has no created or no expires\", facts);\n continue;\n }\n if (expires <= now) {\n last = failed(\"the signature expired\", facts);\n continue;\n }\n if (created > now + CLOCK_SKEW_S) {\n last = failed(\"the signature was created in the future\", facts);\n continue;\n }\n const alg = params.get(\"alg\");\n if (alg !== undefined && alg !== \"ed25519\") {\n last = failed(`the algorithm ${serializeBare(alg)} is not ed25519`, facts);\n continue;\n }\n const key = keyId === null ? undefined : keys.get(keyId);\n if (key === undefined) {\n last = failed(\"no key of the directory has the thumbprint of keyid\", facts);\n continue;\n }\n const lines: string[] = [];\n let error: string | undefined;\n for (const item of covered) {\n const value = componentValue(item, request, target);\n if (\"error\" in value) {\n error = value.error;\n break;\n }\n lines.push(`${serializeItem(item)}: ${value.value}`);\n }\n if (error !== undefined) {\n last = failed(error, facts);\n continue;\n }\n lines.push(`\"@signature-params\": ${serializeMember(input)}`);\n const signature = signatures.get(label);\n if (\n signature === undefined ||\n isInnerList(signature) ||\n !(signature.value instanceof Uint8Array)\n ) {\n last = failed(`the Signature header has no byte sequence for ${label}`, facts);\n continue;\n }\n const good = verifyBytes(null, Buffer.from(lines.join(\"\\n\"), \"utf8\"), key, signature.value);\n if (good) return { verified: true, label, keyId, agent, reason: null };\n last = failed(\"the signature does not match the signature base\", facts);\n }\n return last;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,mBAAmB;;AA8FhC,IAAM,QAAN,MAAY;CACW;CAArB,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ACE,cAAc,KAAA,KACd,YAAY,SAAS,KACrB,EAAE,UAAU,iBAAiB,aAC7B;GACA,OAAO,OAAO,iDAAiD,SAAS,KAAK;GAC7E;EACF;EAEA,IADaC,OAAY,MAAM,OAAO,KAAK,MAAM,KAAK,IAAI,GAAG,MAAM,GAAG,KAAK,UAAU,KAC9E,GAAG,OAAO;GAAE,UAAU;GAAM;GAAO;GAAO;GAAO,QAAQ;EAAK;EACrE,OAAO,OAAO,mDAAmD,KAAK;CACxE;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"webbotauth-CjJdTAfE.mjs","names":["signBytes","verifyBytes"],"sources":["../src/webbotauth.ts"],"sourcesContent":["import type { JsonWebKeyInput, KeyObject } from \"node:crypto\";\nimport {\n createHash,\n createPrivateKey,\n createPublicKey,\n randomBytes,\n sign as signBytes,\n verify as verifyBytes,\n} from \"node:crypto\";\n\n/**\n * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells\n * (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that\n * a request comes from the holder of a key that the operator publishes.\n *\n * - Each request gets three headers: `Signature-Agent`, `Signature-Input` and `Signature`.\n * - `Signature-Agent` is a dictionary. Its member names the key directory of the operator.\n * - The signature covers `@authority` and that member of `Signature-Agent`.\n * - The parameters are `created`, `keyid` (the JWK thumbprint of the key), `alg=\"ed25519\"`,\n * `expires`, a random `nonce` and `tag=\"web-bot-auth\"`.\n * - The key is an Ed25519 key, and `node:crypto` signs. The package adds no dependency.\n *\n * A signature adds an identity. It does not replace the `User-Agent` header, which stays honest.\n */\n\n/** The path of the key directory on the host of the operator (the well-known URI of the draft). */\nexport const KEY_DIRECTORY_PATH = \"/.well-known/http-message-signatures-directory\";\n\n/** The media type of the key directory. The host of the directory sends it as `Content-Type`. */\nexport const KEY_DIRECTORY_TYPE = \"application/http-message-signatures-directory+json\";\n\n/** The value of the `tag` parameter of a Web Bot Auth signature. */\nexport const WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n\n/**\n * This value tells how a site finds the keys from the URL of `Signature-Agent`:\n *\n * - `directory` (the default): the URL is an origin, and the keys are at `KEY_DIRECTORY_PATH` on it.\n * - `jwks_uri`: the URL is the address of a JSON Web Key Set, on any path.\n */\nexport type SignatureAgentType = \"directory\" | \"jwks_uri\";\n\n/** A key in one of the forms that `node:crypto` reads: a `KeyObject`, PEM text, DER bytes (PKCS#8 or SPKI) or a JWK. */\n/**\n * This type is a JSON Web Key, as `createPrivateKey` of `node:crypto` reads it. The type comes from `JsonWebKeyInput`, which\n * `@types/node` 22 and 26 both have: version 26 has no `JsonWebKey` export in `node:crypto`.\n */\ntype JsonWebKey = JsonWebKeyInput[\"key\"];\n\nexport type KeyInput = KeyObject | string | Uint8Array | JsonWebKey;\n\n/** These options make a signer for Web Bot Auth. */\nexport interface WebBotAuthOptions {\n /** This key signs. It is an Ed25519 private key: a `KeyObject`, PKCS#8 (PEM text or DER bytes) or a JWK with `d`. */\n readonly privateKey: KeyInput;\n /**\n * This text is the `keyid` of each signature: the JWK thumbprint of the key (RFC 8037). The signer\n * calculates it. A value that is not the thumbprint of the key throws an error.\n */\n readonly keyId?: string | undefined;\n /**\n * This URL tells a site where the keys are. For the type `directory`, it is an https origin, for\n * example `https://bot.example.com`. For `jwks_uri`, it is the https URL of a JSON Web Key Set.\n */\n readonly signatureAgent: string;\n /** This value tells how a site finds the keys from `signatureAgent`. The default is `directory`. */\n readonly agentType?: SignatureAgentType | undefined;\n /** This value is the time that a signature stays valid, in milliseconds. The default is 5 minutes, and the maximum is 24 hours. */\n readonly lifetimeMs?: number | undefined;\n /** This text is the label of the signature, and the key of the member of `Signature-Agent`. The default is `sig1`. */\n readonly label?: string | undefined;\n}\n\n/**\n * A request signer gives the signature headers of one request. The crawler uses it for each\n * request, robots.txt too. `createWebBotAuthSigner` makes one. A signer of your own can sign with a\n * key in a hardware module, for example.\n */\nexport interface RequestSigner {\n /** This text is the `keyid` of the signatures. */\n readonly keyId: string;\n /** This URL is the value of the member of `Signature-Agent`: where a site finds the keys. */\n readonly signatureAgent: string;\n /** This method gives the headers that sign a request to `url` at the time `now` (milliseconds since the epoch). */\n sign(url: URL, now: number): Readonly<Record<string, string>>;\n}\n\n/** The signer that `createWebBotAuthSigner` makes. It also gives its public key for the key directory. */\nexport interface WebBotAuthSigner extends RequestSigner {\n /** This JWK is the public key of the signer, with no private part. Give it to `keyDirectory`. */\n readonly publicKey: JsonWebKey;\n}\n\n/** One key of a key directory: an Ed25519 public key as a JWK, with its thumbprint as `kid`. */\nexport interface DirectoryKey {\n readonly kty: \"OKP\";\n readonly crv: \"Ed25519\";\n readonly kid: string;\n readonly x: string;\n readonly use: \"sig\";\n}\n\n/** A key directory: a JSON Web Key Set. The operator serves it as JSON at `KEY_DIRECTORY_PATH`, with the type `KEY_DIRECTORY_TYPE`. */\nexport interface KeyDirectory {\n readonly keys: readonly DirectoryKey[];\n}\n\n/** The parts of a request that `verifySignature` reads. */\nexport interface SignedRequest {\n readonly url: string;\n /** The default is `GET`. */\n readonly method?: string | undefined;\n /** These are the headers of the request. A name can be in any case, and a header can have more than one line. */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n}\n\n/** The result of `verifySignature`. */\nexport interface SignatureCheck {\n /** This value is true when a Web Bot Auth signature of the request verifies with a key of the directory. */\n readonly verified: boolean;\n /** This text is the label of the signature that the check examined last, or null. */\n readonly label: string | null;\n readonly keyId: string | null;\n /** This URL is the member of `Signature-Agent` that the signature covers, or null. */\n readonly agent: string | null;\n /** This text tells why the request does not verify. It is null when it verifies. */\n readonly reason: string | null;\n}\n\n// ── structured fields (RFC 9651): the parts that the signature headers use ──\n\n/** A token of a structured field, for example `ed25519` in `alg=ed25519`. */\nclass Token {\n constructor(readonly value: string) {}\n}\n\ntype BareItem = string | number | boolean | Uint8Array | Token;\ntype Params = ReadonlyArray<readonly [string, BareItem]>;\n\ninterface Item {\n readonly value: BareItem;\n readonly params: Params;\n}\n\ninterface InnerList {\n readonly items: readonly Item[];\n readonly params: Params;\n}\n\ntype Member = Item | InnerList;\n\nconst isInnerList = (member: Member): member is InnerList => \"items\" in member;\n\n/** This error tells that a structured field does not parse. */\nclass FieldError extends Error {}\n\nconst KEY_START = /[a-z*]/;\nconst KEY_CHAR = /[a-z0-9_\\-.*]/;\nconst TOKEN_START = /[A-Za-z*]/;\nconst TOKEN_CHAR = /[!#$%&'*+\\-.^_`|~0-9A-Za-z:/]/;\nconst BASE64 = /^[A-Za-z0-9+/=]*$/;\n\n/** This class reads one structured field from its text. */\nclass FieldParser {\n private at = 0;\n constructor(private readonly text: string) {}\n\n private peek(): string {\n return this.text[this.at] ?? \"\";\n }\n\n private spaces(): void {\n while (this.peek() === \" \") this.at += 1;\n }\n\n private ows(): void {\n while (this.peek() === \" \" || this.peek() === \"\\t\") this.at += 1;\n }\n\n dictionary(): Map<string, Member> {\n const out = new Map<string, Member>();\n this.spaces();\n while (this.at < this.text.length) {\n const key = this.key();\n let member: Member;\n if (this.peek() === \"=\") {\n this.at += 1;\n member = this.peek() === \"(\" ? this.innerList() : this.item();\n } else {\n member = { value: true, params: this.params() };\n }\n out.set(key, member);\n this.ows();\n if (this.at >= this.text.length) break;\n if (this.peek() !== \",\") throw new FieldError(`a \",\" is necessary at ${String(this.at)}`);\n this.at += 1;\n this.ows();\n if (this.at >= this.text.length) throw new FieldError(\"the field ends with a comma\");\n }\n return out;\n }\n\n /** This method reads one item and checks that the field has nothing after it. */\n wholeItem(): Item {\n this.spaces();\n const item = this.item();\n this.spaces();\n if (this.at < this.text.length) throw new FieldError(\"text after the item\");\n return item;\n }\n\n private key(): string {\n if (!KEY_START.test(this.peek())) throw new FieldError(`no key at ${String(this.at)}`);\n const start = this.at;\n while (KEY_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return this.text.slice(start, this.at);\n }\n\n private innerList(): InnerList {\n this.at += 1;\n const items: Item[] = [];\n for (;;) {\n this.spaces();\n if (this.peek() === \")\") {\n this.at += 1;\n return { items, params: this.params() };\n }\n if (this.at >= this.text.length) throw new FieldError(\"an inner list has no end\");\n items.push(this.item());\n if (this.peek() !== \" \" && this.peek() !== \")\")\n throw new FieldError(`a space or \")\" is necessary at ${String(this.at)}`);\n }\n }\n\n private item(): Item {\n const value = this.bare();\n return { value, params: this.params() };\n }\n\n private params(): Params {\n const out: Array<readonly [string, BareItem]> = [];\n while (this.peek() === \";\") {\n this.at += 1;\n this.spaces();\n const key = this.key();\n let value: BareItem = true;\n if (this.peek() === \"=\") {\n this.at += 1;\n value = this.bare();\n }\n const known = out.findIndex(([name]) => name === key);\n if (known === -1) out.push([key, value]);\n else out[known] = [key, value];\n }\n return out;\n }\n\n private bare(): BareItem {\n const char = this.peek();\n if (char === \"-\" || /[0-9]/.test(char)) return this.number();\n if (char === '\"') return this.string();\n if (char === \":\") return this.bytes();\n if (char === \"?\") return this.boolean();\n if (TOKEN_START.test(char)) return this.token();\n throw new FieldError(`no item at ${String(this.at)}`);\n }\n\n private number(): number {\n const match = /^-?(\\d{1,15})(\\.\\d{1,3})?/.exec(this.text.slice(this.at));\n if (match === null || (match[2] !== undefined && match[1]!.length > 12))\n throw new FieldError(`not a number at ${String(this.at)}`);\n this.at += match[0].length;\n return Number(match[0]);\n }\n\n private string(): string {\n this.at += 1;\n let out = \"\";\n for (;;) {\n const char = this.peek();\n if (char === \"\") throw new FieldError(\"a string has no end\");\n this.at += 1;\n if (char === \"\\\\\") {\n const next = this.peek();\n if (next !== '\"' && next !== \"\\\\\") throw new FieldError(\"a bad escape in a string\");\n out += next;\n this.at += 1;\n } else if (char === '\"') {\n return out;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code > 0x7e)\n throw new FieldError(\"a string holds a character that is not printable ASCII\");\n out += char;\n }\n }\n }\n\n private bytes(): Uint8Array {\n this.at += 1;\n const end = this.text.indexOf(\":\", this.at);\n if (end === -1) throw new FieldError(\"a byte sequence has no end\");\n const text = this.text.slice(this.at, end);\n if (!BASE64.test(text)) throw new FieldError(\"a byte sequence is not base64\");\n this.at = end + 1;\n return new Uint8Array(Buffer.from(text, \"base64\"));\n }\n\n private boolean(): boolean {\n const value = this.text.slice(this.at, this.at + 2);\n if (value !== \"?1\" && value !== \"?0\") throw new FieldError(\"not a boolean\");\n this.at += 2;\n return value === \"?1\";\n }\n\n private token(): Token {\n const start = this.at;\n this.at += 1;\n while (TOKEN_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return new Token(this.text.slice(start, this.at));\n }\n}\n\nconst serializeBare = (value: BareItem): string => {\n if (value instanceof Token) return value.value;\n if (value instanceof Uint8Array) return `:${Buffer.from(value).toString(\"base64\")}:`;\n if (typeof value === \"boolean\") return value ? \"?1\" : \"?0\";\n if (typeof value === \"number\")\n return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);\n return `\"${value.replace(/[\"\\\\]/g, (char) => `\\\\${char}`)}\"`;\n};\n\nconst serializeParams = (params: Params): string =>\n params\n .map(([key, value]) => (value === true ? `;${key}` : `;${key}=${serializeBare(value)}`))\n .join(\"\");\n\nconst serializeItem = (item: Item): string =>\n `${serializeBare(item.value)}${serializeParams(item.params)}`;\n\nconst serializeMember = (member: Member): string =>\n isInnerList(member)\n ? `(${member.items.map(serializeItem).join(\" \")})${serializeParams(member.params)}`\n : serializeItem(member);\n\n/** This function tells if a text is a key of a structured field: a label of a signature, for example. */\nconst isKey = (text: string): boolean => /^[a-z*][a-z0-9_\\-.*]*$/.test(text);\n\n// ── keys ──\n\nconst base64url = (bytes: Uint8Array): string => Buffer.from(bytes).toString(\"base64url\");\n\nconst isKeyObject = (key: KeyInput): key is KeyObject =>\n typeof key === \"object\" && key !== null && \"asymmetricKeyType\" in key && \"export\" in key;\n\n/** This function reads a private key. Its errors do not hold the key. */\nconst privateKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPrivateKey({ key: JSON.parse(input) as JsonWebKey, format: \"jwk\" })\n : createPrivateKey(input);\n else if (input instanceof Uint8Array)\n key = createPrivateKey({ key: Buffer.from(input), format: \"der\", type: \"pkcs8\" });\n else key = createPrivateKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\n \"the private key of the signer does not parse: give an Ed25519 key as PKCS#8 (PEM or DER) or as a JWK\",\n { cause },\n );\n }\n if (key.type !== \"private\")\n throw new Error(\"the key of the signer is not a private key: give the Ed25519 private key\");\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `the key of the signer is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519: Web Bot Auth here uses Ed25519 keys`,\n );\n return key;\n};\n\n/** This function reads a public key, or the public part of a private key. Its errors do not hold the key. */\nconst publicKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input.type === \"private\" ? createPublicKey(input) : input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPublicKey({ key: JSON.parse(input) as JsonWebKey, format: \"jwk\" })\n : createPublicKey(input);\n else if (input instanceof Uint8Array) {\n const bytes = Buffer.from(input);\n try {\n key = createPublicKey({ key: bytes, format: \"der\", type: \"spki\" });\n } catch {\n key = createPublicKey(createPrivateKey({ key: bytes, format: \"der\", type: \"pkcs8\" }));\n }\n } else key = createPublicKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\"a key of the directory does not parse: give an Ed25519 key\", { cause });\n }\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `a key of the directory is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519`,\n );\n return key;\n};\n\n/** This function gives the JWK thumbprint of an Ed25519 public key (RFC 7638, RFC 8037 appendix A.3). */\nconst thumbprintOf = (x: string): string =>\n base64url(\n createHash(\"sha256\")\n .update(JSON.stringify({ crv: \"Ed25519\", kty: \"OKP\", x }), \"utf8\")\n .digest(),\n );\n\nconst directoryKeyOf = (key: KeyObject): DirectoryKey => {\n const jwk = key.export({ format: \"jwk\" });\n const x = typeof jwk.x === \"string\" ? jwk.x : \"\";\n return { kty: \"OKP\", crv: \"Ed25519\", kid: thumbprintOf(x), x, use: \"sig\" };\n};\n\n/**\n * This function makes the key directory for the operator to host: a JSON Web Key Set with each\n * public key and its thumbprint as `kid`. It takes public keys, or private keys, and it writes only\n * their public parts. Serve the JSON at `KEY_DIRECTORY_PATH` with the type `KEY_DIRECTORY_TYPE`.\n */\nexport const keyDirectory = (publicKeys: readonly KeyInput[]): KeyDirectory => {\n const keys = new Map<string, DirectoryKey>();\n for (const input of publicKeys) {\n const key = directoryKeyOf(publicKeyOf(input));\n keys.set(key.kid, key);\n }\n return { keys: [...keys.values()] };\n};\n\n// ── signing ──\n\n/** The parts of one signature. The signer and the tests use this function. */\nexport interface SignatureParts {\n /** The value of `@authority`: the host and a port that is not the default port, in lowercase. */\n readonly authority: string;\n readonly label: string;\n /** The key of the member of `Signature-Agent`. The draft uses the label of the signature. */\n readonly agentKey: string;\n /** The serialized value of the member: a string, and its parameters. */\n readonly agentValue: string;\n readonly keyId: string;\n readonly created: number;\n readonly expires: number;\n readonly nonce?: string | undefined;\n}\n\n/** This function gives the `@signature-params` value: the covered components and the parameters, in the order of the draft. */\nconst signatureParams = (parts: SignatureParts): string =>\n `(\"@authority\" \"signature-agent\";key=${serializeBare(parts.agentKey)});created=${String(parts.created)};keyid=${serializeBare(parts.keyId)};alg=\"ed25519\";expires=${String(parts.expires)}${parts.nonce === undefined ? \"\" : `;nonce=${serializeBare(parts.nonce)}`};tag=\"${WEB_BOT_AUTH_TAG}\"`;\n\n/** This function gives the signature base of RFC 9421, section 2.5, for the components of Web Bot Auth. */\nexport const signatureBase = (parts: SignatureParts): string =>\n [\n `\"@authority\": ${parts.authority}`,\n `\"signature-agent\";key=${serializeBare(parts.agentKey)}: ${parts.agentValue}`,\n `\"@signature-params\": ${signatureParams(parts)}`,\n ].join(\"\\n\");\n\n/** This function signs the parts with an Ed25519 key, and gives the three headers. */\nexport const signParts = (\n parts: SignatureParts,\n key: KeyObject,\n): {\n readonly \"signature-agent\": string;\n readonly \"signature-input\": string;\n readonly signature: string;\n} => {\n const signature = signBytes(null, Buffer.from(signatureBase(parts), \"utf8\"), key);\n return {\n \"signature-agent\": `${parts.agentKey}=${parts.agentValue}`,\n \"signature-input\": `${parts.label}=${signatureParams(parts)}`,\n signature: `${parts.label}=:${signature.toString(\"base64\")}:`,\n };\n};\n\nconst DEFAULT_LIFETIME_MS = 5 * 60_000;\nconst MAX_LIFETIME_MS = 24 * 60 * 60_000;\n\n/** This function checks the URL of `Signature-Agent`, and gives the URL and the serialized value of the member. */\nconst agentOf = (\n url: string,\n type: SignatureAgentType,\n): { readonly url: string; readonly value: string } => {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new Error(\n `signatureAgent \"${url}\" is not a URL: give the https URL of the key directory`,\n );\n }\n if (target.protocol !== \"https:\")\n throw new Error(`signatureAgent \"${url}\" is not an https URL: the draft permits only https`);\n if (target.username !== \"\" || target.password !== \"\" || target.hash !== \"\")\n throw new Error(`signatureAgent \"${url}\" has a user name, a password or a fragment`);\n if (type === \"directory\") {\n if (target.pathname !== \"/\" || target.search !== \"\")\n throw new Error(\n `signatureAgent \"${url}\" is not an origin: the type directory takes only an origin, such as https://bot.example.com. For a key set on a path, set agentType to jwks_uri`,\n );\n return { url: target.origin, value: serializeBare(target.origin) };\n }\n return { url: target.href, value: `${serializeBare(target.href)};type=${type}` };\n};\n\n/**\n * This function makes a signer for Web Bot Auth with an Ed25519 key. Each signature covers\n * `@authority` and the member of `Signature-Agent`. It has a new random nonce, and it expires after\n * `lifetimeMs`. The signer keeps the private key in a closure: no property of the signer holds it.\n */\nexport const createWebBotAuthSigner = (options: WebBotAuthOptions): WebBotAuthSigner => {\n const key = privateKeyOf(options.privateKey);\n const publicKey = directoryKeyOf(createPublicKey(key));\n if (options.keyId !== undefined && options.keyId !== publicKey.kid)\n throw new Error(\n `keyId \"${options.keyId}\" is not the JWK thumbprint of the key (${publicKey.kid}): Web Bot Auth uses the thumbprint as keyid`,\n );\n const agent = agentOf(options.signatureAgent, options.agentType ?? \"directory\");\n const label = options.label ?? \"sig1\";\n if (!isKey(label))\n throw new Error(\n `label \"${label}\" is not a key of a structured field: use lowercase letters, digits, \"_\", \"-\", \".\" and \"*\"`,\n );\n const lifetimeMs = options.lifetimeMs ?? DEFAULT_LIFETIME_MS;\n if (!Number.isFinite(lifetimeMs) || lifetimeMs < 1000 || lifetimeMs > MAX_LIFETIME_MS)\n throw new RangeError(\n `lifetimeMs must be from 1000 (1 second) to ${String(MAX_LIFETIME_MS)} (24 hours), not ${String(lifetimeMs)}`,\n );\n const { kty, crv, x } = publicKey;\n return {\n keyId: publicKey.kid,\n signatureAgent: agent.url,\n publicKey: { kty, crv, x },\n sign(url, now) {\n const created = Math.floor(now / 1000);\n return signParts(\n {\n authority: url.host.toLowerCase(),\n label,\n agentKey: label,\n agentValue: agent.value,\n keyId: publicKey.kid,\n created,\n expires: created + Math.ceil(lifetimeMs / 1000),\n nonce: randomBytes(32).toString(\"base64\"),\n },\n key,\n );\n },\n };\n};\n\n/** This function tells if a value is a request signer, not the options of one. */\nexport const isRequestSigner = (value: RequestSigner | WebBotAuthOptions): value is RequestSigner =>\n typeof (value as Partial<RequestSigner>).sign === \"function\";\n\n/** This function gives a request signer: the signer itself, or a new signer from its options. */\nexport const signerOf = (\n value: RequestSigner | WebBotAuthOptions | undefined,\n): RequestSigner | undefined =>\n value === undefined ? undefined : isRequestSigner(value) ? value : createWebBotAuthSigner(value);\n\n// ── verification ──\n\n/** A signature can start this long before the clock of the verifier, for a small difference of the clocks. */\nconst CLOCK_SKEW_S = 60;\n\nconst headerLines = (\n headers: SignedRequest[\"headers\"],\n name: string,\n): readonly string[] | undefined => {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== name || value === undefined) continue;\n return typeof value === \"string\" ? [value] : value;\n }\n return undefined;\n};\n\n/** This function gives the value of a header as RFC 9421 section 2.1 combines it: each line without its outer spaces, with \", \" between. */\nconst fieldValue = (headers: SignedRequest[\"headers\"], name: string): string | undefined =>\n headerLines(headers, name)\n ?.map((line) => line.replace(/\\r?\\n[ \\t]+/g, \" \").trim())\n .join(\", \");\n\n/** This function gives the value of one component of a request, or an error text. */\nconst componentValue = (\n component: Item,\n request: SignedRequest,\n target: URL,\n): { readonly value: string } | { readonly error: string } => {\n const name = component.value;\n if (typeof name !== \"string\") return { error: \"a component is not a string\" };\n const params = new Map(component.params);\n if (name.startsWith(\"@\")) {\n if (params.size > 0) return { error: `the parameters of ${name} are not supported` };\n switch (name) {\n case \"@method\":\n return { value: (request.method ?? \"GET\").toUpperCase() };\n case \"@authority\":\n return { value: target.host.toLowerCase() };\n case \"@scheme\":\n return { value: target.protocol.slice(0, -1).toLowerCase() };\n case \"@target-uri\":\n return { value: target.href };\n case \"@path\":\n return { value: target.pathname === \"\" ? \"/\" : target.pathname };\n case \"@query\":\n return { value: target.search === \"\" ? \"?\" : target.search };\n case \"@request-target\":\n return { value: `${target.pathname}${target.search}` };\n default:\n return { error: `the component ${name} is not supported` };\n }\n }\n const value = fieldValue(request.headers, name);\n if (value === undefined) return { error: `the request has no ${name} header` };\n if ([...params.keys()].some((param) => param !== \"key\"))\n return { error: `the parameters of ${name} are not supported` };\n const key = params.get(\"key\");\n if (key === undefined) return { value };\n if (typeof key !== \"string\") return { error: `the key of ${name} is not a string` };\n let member: Member | undefined;\n try {\n member = new FieldParser(value).dictionary().get(key);\n } catch (error) {\n return { error: `the ${name} header is not a dictionary: ${(error as Error).message}` };\n }\n if (member === undefined) return { error: `the ${name} header has no member ${key}` };\n return { value: serializeMember(member) };\n};\n\nconst failed = (\n reason: string,\n facts: { label?: string | null; keyId?: string | null; agent?: string | null } = {},\n): SignatureCheck => ({\n verified: false,\n label: facts.label ?? null,\n keyId: facts.keyId ?? null,\n agent: facts.agent ?? null,\n reason,\n});\n\n/**\n * This function verifies the Web Bot Auth signatures of a request with the keys of a directory. It\n * applies RFC 9421 section 3.2 and the profile of the draft. The profile asks for the tag\n * `web-bot-auth`, `created`, `expires` and `@authority`. It also asks for the member of\n * `Signature-Agent`, and a key with the thumbprint of `keyid`. The tests use it, and an operator can check a setup with it. It sends no request.\n */\nexport const verifySignature = (\n request: SignedRequest,\n directory: KeyDirectory,\n options: { readonly now?: number | undefined } = {},\n): SignatureCheck => {\n let target: URL;\n try {\n target = new URL(request.url);\n } catch {\n return failed(\"the URL of the request is not a URL\");\n }\n const inputText = fieldValue(request.headers, \"signature-input\");\n const signatureText = fieldValue(request.headers, \"signature\");\n if (inputText === undefined || signatureText === undefined)\n return failed(\"the request has no Signature-Input or no Signature header\");\n let inputs: Map<string, Member>;\n let signatures: Map<string, Member>;\n try {\n inputs = new FieldParser(inputText).dictionary();\n signatures = new FieldParser(signatureText).dictionary();\n } catch (error) {\n return failed(`a signature header does not parse: ${(error as Error).message}`);\n }\n const now = Math.floor((options.now ?? Date.now()) / 1000);\n const keys = new Map<string, KeyObject>();\n for (const entry of directory.keys) {\n try {\n const key = createPublicKey({\n key: { kty: entry.kty, crv: entry.crv, x: entry.x },\n format: \"jwk\",\n });\n keys.set(thumbprintOf(entry.x), key);\n } catch {\n // a key that does not parse verifies nothing\n }\n }\n let last: SignatureCheck = failed(\"the request has no Web Bot Auth signature\");\n for (const [label, input] of inputs) {\n if (!isInnerList(input)) continue;\n const params = new Map(input.params);\n if (params.get(\"tag\") !== WEB_BOT_AUTH_TAG) continue;\n const keyId = typeof params.get(\"keyid\") === \"string\" ? (params.get(\"keyid\") as string) : null;\n const covered = input.items;\n const names = covered.map((item) => serializeItem(item));\n const agentItem = covered.find((item) => item.value === \"signature-agent\");\n let agent: string | null = null;\n if (agentItem !== undefined) {\n const value = componentValue(agentItem, request, target);\n if (\"value\" in value) {\n try {\n const member = new FieldParser(value.value).wholeItem().value;\n agent = typeof member === \"string\" ? member : null;\n } catch {\n agent = null;\n }\n }\n }\n const facts = { label, keyId, agent };\n if (new Set(names).size !== names.length) {\n last = failed(\"a component is covered two times\", facts);\n continue;\n }\n if (!names.includes('\"@authority\"') && !names.includes('\"@target-uri\"')) {\n last = failed(\"the signature does not cover @authority or @target-uri\", facts);\n continue;\n }\n if (agentItem === undefined) {\n last = failed(\"the signature does not cover Signature-Agent\", facts);\n continue;\n }\n const created = params.get(\"created\");\n const expires = params.get(\"expires\");\n if (typeof created !== \"number\" || typeof expires !== \"number\") {\n last = failed(\"the signature has no created or no expires\", facts);\n continue;\n }\n if (expires <= now) {\n last = failed(\"the signature expired\", facts);\n continue;\n }\n if (created > now + CLOCK_SKEW_S) {\n last = failed(\"the signature was created in the future\", facts);\n continue;\n }\n const alg = params.get(\"alg\");\n if (alg !== undefined && alg !== \"ed25519\") {\n last = failed(`the algorithm ${serializeBare(alg)} is not ed25519`, facts);\n continue;\n }\n const key = keyId === null ? undefined : keys.get(keyId);\n if (key === undefined) {\n last = failed(\"no key of the directory has the thumbprint of keyid\", facts);\n continue;\n }\n const lines: string[] = [];\n let error: string | undefined;\n for (const item of covered) {\n const value = componentValue(item, request, target);\n if (\"error\" in value) {\n error = value.error;\n break;\n }\n lines.push(`${serializeItem(item)}: ${value.value}`);\n }\n if (error !== undefined) {\n last = failed(error, facts);\n continue;\n }\n lines.push(`\"@signature-params\": ${serializeMember(input)}`);\n const signature = signatures.get(label);\n if (\n signature === undefined ||\n isInnerList(signature) ||\n !(signature.value instanceof Uint8Array)\n ) {\n last = failed(`the Signature header has no byte sequence for ${label}`, facts);\n continue;\n }\n const good = verifyBytes(null, Buffer.from(lines.join(\"\\n\"), \"utf8\"), key, signature.value);\n if (good) return { verified: true, label, keyId, agent, reason: null };\n last = failed(\"the signature does not match the signature base\", facts);\n }\n return last;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,mBAAmB;;AAoGhC,IAAM,QAAN,MAAY;C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K;EACtC,IACE,cAAc,KAAA,KACd,YAAY,SAAS,KACrB,EAAE,UAAU,iBAAiB,aAC7B;GACA,OAAO,OAAO,iDAAiD,SAAS,KAAK;GAC7E;EACF;EAEA,IADaC,OAAY,MAAM,OAAO,KAAK,MAAM,KAAK,IAAI,GAAG,MAAM,GAAG,KAAK,UAAU,KAC9E,GAAG,OAAO;GAAE,UAAU;GAAM;GAAO;GAAO;GAAO,QAAQ;EAAK;EACrE,OAAO,OAAO,mDAAmD,KAAK;CACxE;CACA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "polite-crawler",
4
- "version": "0.1.3",
4
+ "version": "0.1.4",
5
5
  "mcpName": "io.github.mark1russell7/polite-crawler",
6
6
  "description": "A polite web crawler for research and AI agents. It fetches a source once, keeps it, and reads it many times: robots.txt obeyed, one request per site, full-text search, an MCP server.",
7
7
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["answered"],"sources":["../src/recipe-venue.ts","../src/recipe-product.ts"],"sourcesContent":["/*\n * The venue recipe reads the opening hours of a venue (a restaurant, a shop, a museum) from its own\n * site. It reads the cheap sources first:\n *\n * 1. The home page: its JSON-LD (`openingHoursSpecification` and `openingHours`) and its text.\n * 2. The few pages of the site that most likely hold hours or a menu, by the words of their links.\n * 3. An OpenStreetMap `opening_hours` value, when the caller gives one. The recipe sends no\n * request to OpenStreetMap.\n *\n * Each reading names the page, the document and the capture that it came from. The recipe gives\n * readings only. To compare them with the hours that an application keeps is the work of the\n * application, and `compareHours` is the pure helper for it.\n */\nimport type { Doc } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedOf } from \"./fallback.ts\";\nimport type { Day, Hours, Week } from \"./hours.ts\";\nimport {\n DAYS,\n describeWeek,\n disagreements,\n fromCompact,\n fromSchemaOrg,\n fromText,\n} from \"./hours.ts\";\nimport type { PageLink } from \"./html.ts\";\nimport { typesOf } from \"./html.ts\";\nimport type { RecipeTarget } from \"./recipe.ts\";\nimport { deadlineOf, runtimeOf } from \"./recipe.ts\";\nimport type { PageOptions, PageResult } from \"./runtime.ts\";\nimport { HELD_BACK, fetchPage, isHeldBack, recordOverride } from \"./runtime.ts\";\n\n/** These are the limits of the venue recipe. */\nexport const VENUE_LIMITS: {\n /** The pages of the site that a read fetches after the home page, by default. */\n readonly pages: number;\n /** The most pages after the home page. */\n readonly maxPages: number;\n /** The most menu links of a result. */\n readonly menus: number;\n /** The most readings of one page. A page with more is a list of something else. */\n readonly readingsPerPage: number;\n /** The most links of one page that the recipe ranks. */\n readonly links: number;\n /** The distance in metres within which a JSON-LD location is the venue. */\n readonly nearMetres: number;\n} = { pages: 3, maxPages: 8, menus: 8, readingsPerPage: 20, links: 200, nearMetres: 150 };\n\n// ── words ───────────────────────────────────────────────────────────────────\n\nconst STOP_WORDS: ReadonlySet<string> = new Set([\"the\", \"a\", \"an\", \"and\", \"of\", \"at\"]);\n\n/** This function gives the words of a text in one form: lower case, no accents, and `&` as `and`. */\nconst wordsOf = (text: string): string[] =>\n text\n .toLowerCase()\n .normalize(\"NFKD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/&/g, \" and \")\n .replace(/[^\\p{L}\\p{N} ]/gu, \" \")\n .split(/\\s+/)\n .filter((word) => word.length > 0 && !STOP_WORDS.has(word));\n\n/**\n * This function tells if a page names a venue: the page has the first word of the name and 60\n * percent of its words. A domain that a venue let go can show a different business. It gives\n * undefined for a name with no word.\n */\nexport const namesVenue = (\n name: string,\n page: { readonly title: string; readonly text: string },\n): boolean | undefined => {\n const words = wordsOf(name);\n if (words.length === 0) return undefined;\n const onPage = new Set(wordsOf(`${page.title} ${page.text}`));\n const named = new Set(words);\n const found = [...named].filter((word) => onPage.has(word)).length;\n return onPage.has(words[0]!) && found / named.size >= 0.6;\n};\n\n// ── the links of the site ───────────────────────────────────────────────────\n\n/** The words of a link that tell what its page holds, with their weights. */\nconst LINK_WORDS: ReadonlyArray<readonly [RegExp, number]> = [\n [/hours|horario|horaires|opening/, 6],\n [/menu|food|drink|wine|cocktail/, 4],\n [/contact|location|visit|find.?us|directions/, 3],\n [/about|info/, 2],\n [/lunch|dinner|brunch|breakfast/, 2],\n];\n\n/** The hosts of review and social sites: a menu there is a different page about the venue. */\nconst SOCIAL =\n /(?:^|\\.)(?:yelp|tripadvisor|facebook|instagram|twitter|x|tiktok|google|apple|spotify)\\.[a-z.]+$/i;\n\n/** The files that hold no hours as text. */\nconst FILE = /\\.(?:pdf|jpe?g|png|gif|webp|svg|mp4)(?:[?#]|$)/i;\n\nconst hostOf = (url: string): string | undefined => {\n try {\n return new URL(url).hostname.toLowerCase().replace(/^www\\./, \"\");\n } catch {\n return undefined;\n }\n};\n\nconst withoutHash = (url: string): string => url.replace(/#.*$/s, \"\").replace(/\\/$/, \"\");\n\n/**\n * This function ranks the links of a page by the words of their text and path. The links to\n * the hours or a menu come first. It keeps only the links on the site of `home`,\n * and it leaves out the files (a PDF, an image) and the home page itself.\n */\nexport const rankHoursLinks = (links: readonly PageLink[], home: string): PageLink[] => {\n const site = hostOf(home);\n const self = withoutHash(home);\n const seen = new Set<string>();\n const scored: Array<{ readonly link: PageLink; readonly score: number }> = [];\n for (const link of links.slice(0, VENUE_LIMITS.links)) {\n if (typeof link?.href !== \"string\" || hostOf(link.href) !== site || FILE.test(link.href))\n continue;\n const key = withoutHash(link.href);\n if (key === self || seen.has(key)) continue;\n let path = \"\";\n try {\n path = new URL(link.href).pathname;\n } catch {\n continue;\n }\n const words = `${typeof link.text === \"string\" ? link.text : \"\"} ${path}`.toLowerCase();\n const score = LINK_WORDS.reduce(\n (sum, [pattern, weight]) => sum + (pattern.test(words) ? weight : 0),\n 0,\n );\n if (score <= 0) continue;\n seen.add(key);\n scored.push({ link, score });\n }\n // a stable sort: links of equal score keep the order of the page\n return scored.sort((a, b) => b.score - a.score).map((entry) => entry.link);\n};\n\n/** A link to a menu. */\nexport interface VenueLink {\n readonly url: string;\n readonly text: string;\n}\n\n// ── the location of a venue ─────────────────────────────────────────────────\n\n/** The place of a venue, to choose its hours on a page that lists more than one location. */\nexport interface VenueLocation {\n /** This text is the street address, for example `12 Via Esempio`. The number and the street count. */\n readonly address?: string | undefined;\n readonly lat?: number | undefined;\n readonly lon?: number | undefined;\n}\n\ninterface Point {\n readonly lat: number;\n readonly lon: number;\n}\n\nconst EARTH_METRES = 6_371_000;\n\n/** This function gives the distance in metres between two points on the earth (the haversine formula). */\nconst metresBetween = (a: Point, b: Point): number => {\n const rad = Math.PI / 180;\n const dLat = (b.lat - a.lat) * rad;\n const dLon = (b.lon - a.lon) * rad;\n const h =\n Math.sin(dLat / 2) ** 2 +\n Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;\n return 2 * EARTH_METRES * Math.asin(Math.min(1, Math.sqrt(h)));\n};\n\nconst pointOf = (lat: unknown, lon: unknown): Point | undefined => {\n const la = typeof lat === \"string\" ? Number.parseFloat(lat) : lat;\n const lo = typeof lon === \"string\" ? Number.parseFloat(lon) : lon;\n return typeof la === \"number\" &&\n typeof lo === \"number\" &&\n Number.isFinite(la) &&\n Number.isFinite(lo) &&\n Math.abs(la) <= 90 &&\n Math.abs(lo) <= 180\n ? { lat: la, lon: lo }\n : undefined;\n};\n\n/** The words of a street that tell nothing about which street: directions and kinds of road. */\nconst STREET_NOISE: ReadonlySet<string> = new Set([\n \"n\",\n \"s\",\n \"e\",\n \"w\",\n \"north\",\n \"south\",\n \"east\",\n \"west\",\n \"st\",\n \"street\",\n \"ave\",\n \"avenue\",\n \"rd\",\n \"road\",\n \"blvd\",\n \"boulevard\",\n \"dr\",\n \"drive\",\n \"ln\",\n \"lane\",\n \"ct\",\n \"court\",\n \"pl\",\n \"place\",\n \"sq\",\n \"square\",\n \"hwy\",\n \"highway\",\n \"pkwy\",\n \"parkway\",\n \"way\",\n \"ter\",\n \"terrace\",\n \"suite\",\n \"ste\",\n \"unit\",\n]);\n\n/** This function gives the number of a street address and the words that name its street. */\nconst streetOf = (\n address: string,\n): { readonly number: string; readonly words: ReadonlySet<string> } | undefined => {\n const words = wordsOf((address.split(\",\")[0] ?? address).slice(0, 200));\n const number = words.find((word) => /^\\d+[a-z]?$/.test(word));\n if (number === undefined) return undefined;\n return {\n number,\n words: new Set(words.filter((word) => !/^\\d/.test(word) && !STREET_NOISE.has(word))),\n };\n};\n\nconst addressText = (value: unknown): string | undefined => {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return addressText(value[0]);\n if (typeof value === \"object\" && value !== null) {\n const street = (value as Record<string, unknown>)[\"streetAddress\"];\n return typeof street === \"string\" ? street : undefined;\n }\n return undefined;\n};\n\n/**\n * This function tells if a JSON-LD location record is the venue. The record must have the same\n * number on a street that shares a word, or a position near the venue (`VENUE_LIMITS.nearMetres`).\n */\nexport const locationMatches = (\n record: Readonly<Record<string, unknown>>,\n location: VenueLocation,\n): boolean => {\n const geo = record[\"geo\"];\n const at =\n typeof geo === \"object\" && geo !== null\n ? pointOf(\n (geo as Record<string, unknown>)[\"latitude\"],\n (geo as Record<string, unknown>)[\"longitude\"],\n )\n : undefined;\n const ours = pointOf(location.lat, location.lon);\n if (at !== undefined && ours !== undefined && metresBetween(at, ours) <= VENUE_LIMITS.nearMetres)\n return true;\n const theirs = addressText(record[\"address\"]);\n if (theirs === undefined || location.address === undefined) return false;\n const a = streetOf(theirs);\n const b = streetOf(location.address);\n return (\n a !== undefined &&\n b !== undefined &&\n a.number === b.number &&\n [...a.words].some((word) => b.words.has(word))\n );\n};\n\nconst located = (record: Readonly<Record<string, unknown>>): boolean =>\n record[\"address\"] !== undefined || record[\"geo\"] !== undefined;\n\n// ── the readings ────────────────────────────────────────────────────────────\n\n/** One reading of the hours, with the source that it came from. */\nexport interface VenueReading {\n /** The value `jsonld` is the structured data of a page, `text` the text of a page, and `osm` the value of the caller. */\n readonly from: \"jsonld\" | \"osm\" | \"text\";\n /**\n * This value orders the readings, 0 first. JSON-LD is 0, a text under an hours heading is 1 and\n * OpenStreetMap is 2. A text with no label of a different schedule is 3. A different schedule is\n * 4, for example a brunch, a kitchen, a happy hour or an office.\n */\n readonly rank: number;\n /** The value `opening` is the opening hours of the venue (a rank of 3 or less). Else it is `other`. */\n readonly schedule: \"opening\" | \"other\";\n /** This text is the line above a reading of the text, for example `Hours` or `Happy hour`. */\n readonly label: string | null;\n /** This text is the week as words, from `describeWeek`. */\n readonly hours: string;\n readonly week: Week;\n /** This value is true when the reader guessed an am or a pm. */\n readonly inferred: boolean;\n /** This value is true when the reader left out a rule or a line (a holiday, a date). */\n readonly partial: boolean;\n /** This text names the season or the dates of the hours. */\n readonly season: string | null;\n /** This text is the words that the hours came from. A reading of the text can be a quote for `verify`. */\n readonly raw: string;\n /** This path names the JSON-LD record of the reading in the metadata of the document, for example `jsonld[2]`. */\n readonly path: string | null;\n /** This URL is the page of the reading. */\n readonly url: string | null;\n readonly doc: string | null;\n /** This id is the capture of the text that the reading came from. A citation names it. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n /** This value tells that the page is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n}\n\n/** A stored document, or a version of one: what `venueReadingsOf` reads. */\nexport interface VenueSource {\n readonly doc?: string | null | undefined;\n readonly url: string | null;\n readonly text: string;\n readonly meta: Readonly<Record<string, unknown>>;\n readonly capture?: string | null | undefined;\n readonly fetched_at?: string | null | undefined;\n}\n\n/** The result of `venueReadingsOf`: what one document says. */\nexport interface VenueRead {\n readonly readings: readonly VenueReading[];\n /** This value is the first `telephone` of the JSON-LD records of the venue. */\n readonly phone: string | null;\n readonly menus: readonly VenueLink[];\n readonly notes: readonly string[];\n /** This value counts the work of the reader. The tests use it, because it does not change with the computer. */\n readonly steps: number;\n}\n\n/** The types of JSON-LD records that have the hours of a venue. */\nconst HOURS_TYPES =\n /Restaurant|LocalBusiness|FoodEstablishment|BarOrPub|CafeOrCoffeeShop|Bakery|Store|Place|Winery|Brewery|NightClub|Museum|TouristAttraction|Library|EntertainmentBusiness/;\n\n/**\n * A label that names a schedule that is not the opening hours. The line above a schedule is often a\n * different thing, for example a phone number, and such a line tells nothing.\n */\nconst OTHER_SCHEDULE =\n /brunch|lunch|dinner|breakfast|happy|kitchen|\bbar\b|deliver|take.?out|pick.?up|patio|holiday|season|summer|winter|special|late|menu/i;\n\n/**\n * A label of a service beside the opening hours, or of an office. Its hours are a different\n * schedule, also when the label says \"hours\" (\"Happy hour\", \"Kitchen hours\", \"Office hours\").\n */\nconst SERVICE =\n /happy|kitchen|deliver|take.?out|pick.?up|brunch|holiday|special|patio|\bbar\b|late.?night|office/i;\n\nconst rankOf = (from: VenueReading[\"from\"], label: string | null): number => {\n if (from === \"jsonld\") return 0;\n if (from === \"osm\") return 2;\n const text = label ?? \"\";\n if (SERVICE.test(text)) return 4;\n if (/hour|open/i.test(text)) return 1;\n return OTHER_SCHEDULE.test(text) ? 4 : 3;\n};\n\nconst reading = (\n from: VenueReading[\"from\"],\n hours: Hours,\n label: string | null,\n source: {\n readonly url: string | null;\n readonly doc: string | null;\n readonly capture: string | null;\n readonly fetched_at: string | null;\n readonly path: string | null;\n readonly archived?: Archived | undefined;\n },\n): VenueReading => {\n const rank = rankOf(from, label);\n return {\n from,\n rank,\n schedule: rank <= 3 ? \"opening\" : \"other\",\n label,\n hours: describeWeek(hours.week),\n week: hours.week,\n inferred: hours.inferred,\n partial: hours.partial === true,\n season: hours.season ?? null,\n raw: hours.raw,\n path: source.path,\n url: source.url,\n doc: source.doc,\n capture: source.capture,\n fetched_at: source.fetched_at,\n ...(source.archived === undefined ? {} : { archived: source.archived }),\n };\n};\n\nconst recordsOf = (meta: Readonly<Record<string, unknown>>): Record<string, unknown>[] => {\n const jsonld = meta[\"jsonld\"];\n return Array.isArray(jsonld)\n ? jsonld.filter(\n (record): record is Record<string, unknown> =>\n record !== null && typeof record === \"object\" && !Array.isArray(record),\n )\n : [];\n};\n\nconst linksOf = (meta: Readonly<Record<string, unknown>>): PageLink[] => {\n const links = meta[\"links\"];\n return Array.isArray(links)\n ? links.filter(\n (link): link is PageLink =>\n link !== null && typeof link === \"object\" && typeof (link as PageLink).href === \"string\",\n )\n : [];\n};\n\n/**\n * This function reads the hours of one stored document, or of one version of it. It is pure, and\n * it sends no request. Thus it also reads a version at a time (`versionAtTime`) or an archived copy.\n *\n * - It reads each JSON-LD record of a venue type with `fromSchemaOrg`, and the text with `fromText`.\n * - On a page that lists more than one location, it reads only the location that matches\n * `location`. With no `location`, it reads none of them, and a note says so.\n * - It gives the first `telephone` and the menu links that are not on a review or social site.\n */\nexport const venueReadingsOf = (\n source: VenueSource,\n options: { readonly location?: VenueLocation | undefined } = {},\n): VenueRead => {\n let steps = 0;\n const notes: string[] = [];\n const archived = archivedOf(source.meta);\n const where = {\n url: archived?.original ?? source.url,\n doc: source.doc ?? null,\n capture: source.capture ?? null,\n fetched_at: source.fetched_at ?? null,\n ...(archived === undefined ? {} : { archived }),\n };\n const all = recordsOf(source.meta);\n steps += all.length;\n const venues = all\n .map((record, index) => ({ record, index }))\n .filter(({ record }) => typesOf(record).some((type) => HOURS_TYPES.test(type)));\n // a page of a group lists each of its locations: only the hours of this venue are its hours\n let usable = venues;\n const placed = venues.filter(({ record }) => located(record));\n if (placed.length > 1) {\n const location = options.location;\n const ours =\n location === undefined\n ? []\n : placed.filter(({ record }) => locationMatches(record, location));\n if (ours.length === 0) {\n notes.push(\n location === undefined\n ? `${where.url ?? \"the page\"} lists ${String(placed.length)} locations: give location to read the hours of one`\n : `${where.url ?? \"the page\"} lists ${String(placed.length)} locations, and none matched the location: their hours were not read`,\n );\n }\n usable = [...ours, ...venues.filter(({ record }) => !located(record))];\n }\n const readings: VenueReading[] = [];\n let phone: string | null = null;\n for (const { record, index } of usable) {\n steps += 1;\n const hours = fromSchemaOrg(record);\n if (hours !== undefined && readings.length < VENUE_LIMITS.readingsPerPage) {\n readings.push(reading(\"jsonld\", hours, null, { ...where, path: `jsonld[${String(index)}]` }));\n }\n const telephone = record[\"telephone\"];\n if (phone === null && typeof telephone === \"string\" && telephone.trim().length > 0)\n phone = telephone.trim().slice(0, 100);\n }\n steps += source.text.length;\n for (const hours of fromText(source.text)) {\n if (readings.length >= VENUE_LIMITS.readingsPerPage) {\n notes.push(\n `${where.url ?? \"the page\"} gives more than ${String(VENUE_LIMITS.readingsPerPage)} readings: the rest were not read`,\n );\n break;\n }\n readings.push(reading(\"text\", hours, hours.label, { ...where, path: null }));\n }\n const menus: VenueLink[] = [];\n for (const link of linksOf(source.meta).slice(0, VENUE_LIMITS.links)) {\n steps += 1;\n if (menus.length >= VENUE_LIMITS.menus) break;\n const text = typeof link.text === \"string\" ? link.text.slice(0, 200) : \"\";\n const host = hostOf(link.href);\n if (host === undefined || SOCIAL.test(host) || !/menu/i.test(`${text} ${link.href}`)) continue;\n if (menus.some((menu) => menu.url === link.href)) continue;\n menus.push({ url: link.href, text });\n }\n return { readings, phone, menus, notes, steps };\n};\n\n// ── the recipe ──────────────────────────────────────────────────────────────\n\n/** An OpenStreetMap `opening_hours` value, with where the caller got it. */\nexport interface VenueOsm {\n /** This text is the value of the tag, for example `Mo-Fr 08:00-18:00; Sa 09:00-13:00`. */\n readonly value: string;\n readonly url?: string | null | undefined;\n readonly doc?: string | null | undefined;\n readonly capture?: string | null | undefined;\n readonly fetched_at?: string | null | undefined;\n}\n\n/** These options control `readVenue`. */\nexport interface VenueOptions {\n /** This value is the number of pages after the home page, from 0 to `VENUE_LIMITS.maxPages`. The default is 3. */\n readonly pages?: number | undefined;\n /** This text is the name of the venue. The result tells if the home page names it (`names_venue`). */\n readonly name?: string | undefined;\n /** With true, a home page that does not name the venue gives no reading, and the recipe fetches no more pages. */\n readonly requireName?: boolean | undefined;\n /** This value is the place of the venue, for a page that lists more than one location. */\n readonly location?: VenueLocation | undefined;\n /** This value is an OpenStreetMap `opening_hours` value. The recipe reads it, and sends no request for it. */\n readonly osm?: string | VenueOsm | undefined;\n /** The value `auto` renders a page only when it shows almost nothing without JavaScript. */\n readonly render?: \"auto\" | \"never\" | \"always\" | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for example `Claude-User`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n readonly signal?: AbortSignal | undefined;\n /** No request starts after this time from the start of the read, for example `\"2m\"`. */\n readonly budget?: Duration | undefined;\n readonly scope?: string | undefined;\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** This name connects the captures to the job that asked for them. The default is `venue`. */\n readonly job?: string | undefined;\n /** This value is true when a person gave this URL directly. It is the only way to read a held-back page. The crawler logs it. */\n readonly userProvided?: boolean | undefined;\n /** The value `archive` reads an archived copy of a page that the site refuses, or when the site is down. */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** One page that the venue recipe fetched. */\nexport interface VenuePage {\n readonly url: string;\n readonly doc: string | null;\n readonly outcome: string;\n readonly status: number;\n readonly rendered: boolean;\n readonly capture: string | null;\n readonly fetched_at: string | null;\n readonly from_cache: boolean;\n readonly held_back: boolean;\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\n/** The result of `readVenue`. */\nexport interface VenueResult {\n /** This URL is the site that the caller gave. */\n readonly url: string;\n /** This URL is where the home page landed, after the redirects. */\n readonly home: string | null;\n /** This URL is the new site, when the home page landed on a different host. */\n readonly moved: string | null;\n /** This value tells if the home page names the venue. It is null with no `name`. */\n readonly names_venue: boolean | null;\n readonly pages: readonly VenuePage[];\n /** These are the readings, one for each source, label and week: the best first. */\n readonly readings: readonly VenueReading[];\n /** This reading is the best reading of the opening hours, from any source. */\n readonly best: VenueReading | null;\n /** This reading is the best reading of the site itself (not OpenStreetMap) with no guess. A check for a change compares it. */\n readonly from_site: VenueReading | null;\n /** These days are the days where two readings of the whole schedule (a rank of 2 or less) disagree. */\n readonly disagree: readonly Day[];\n readonly menus: readonly VenueLink[];\n readonly phone: string | null;\n /** These ids are the captures of the pages that the recipe read. */\n readonly captures: readonly string[];\n /** This value is true when a page asked not to be AI input, so the recipe read nothing from it. */\n readonly held_back: boolean;\n readonly note: string | null;\n}\n\nconst answered = (page: PageResult): boolean =>\n page.outcome === \"ok\" || page.outcome === \"not-modified\" || page.archived !== undefined;\n\n/**\n * This function reads the hours of a venue from its site. It fetches the home page and the pages\n * that most likely hold hours or a menu. Each one is a fetch of the crawler. Thus robots.txt, the\n * pace, the stops, the capture log and the rule for a held-back page apply. It renders a page only\n * when the page needs JavaScript, as `fetch` does.\n *\n * It gives each reading with its source, the best reading, and the days where the readings\n * disagree. It writes nothing but the capture log. To choose the true hours is the decision of\n * the application.\n */\nexport const readVenue = async (\n target: RecipeTarget,\n url: string,\n options: VenueOptions = {},\n): Promise<VenueResult> => {\n const runtime = runtimeOf(target);\n const extra = options.pages ?? VENUE_LIMITS.pages;\n if (!Number.isInteger(extra) || extra < 0 || extra > VENUE_LIMITS.maxPages) {\n throw new RangeError(\n `pages must be a whole number from 0 to ${String(VENUE_LIMITS.maxPages)}, not ${String(extra)}`,\n );\n }\n let site: URL;\n try {\n site = new URL(url);\n } catch {\n throw new TypeError(`readVenue needs the URL of a site, not ${JSON.stringify(url)}`);\n }\n if (site.protocol !== \"http:\" && site.protocol !== \"https:\")\n throw new TypeError(`readVenue needs an http or https URL, not ${url}`);\n const maxAge = options.maxAge ?? \"24h\";\n const job = options.job ?? \"venue\";\n const userProvided = options.userProvided ?? false;\n const pageOptions: PageOptions = {\n render: options.render ?? \"auto\",\n maxAgeMs: maxAge === \"auto\" ? \"auto\" : durationMs(maxAge),\n onBehalfOf: options.onBehalfOf,\n job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline: deadlineOf(runtime, options.budget),\n fallback: options.fallback,\n archiveDespiteRobots: options.archiveDespiteRobots,\n };\n const notes: string[] = [];\n const readings: VenueReading[] = [];\n const pages: VenuePage[] = [];\n const menus: VenueLink[] = [];\n const captures = new Set<string>();\n let phone: string | null = null;\n let heldBack = false;\n\n if (options.osm !== undefined) {\n const osm: VenueOsm = typeof options.osm === \"string\" ? { value: options.osm } : options.osm;\n const hours = typeof osm.value === \"string\" ? fromCompact(osm.value, \"osm\") : undefined;\n if (hours === undefined) {\n notes.push(\n `the OpenStreetMap hours cannot be read: ${JSON.stringify(String(osm.value).slice(0, 200))}`,\n );\n } else {\n readings.push(\n reading(\"osm\", hours, null, {\n url: osm.url ?? null,\n doc: osm.doc ?? null,\n capture: osm.capture ?? null,\n fetched_at: osm.fetched_at ?? null,\n path: null,\n }),\n );\n if (typeof osm.capture === \"string\") captures.add(osm.capture);\n }\n }\n\n /** This function fetches one page, and gives its document when the recipe can read it. */\n const readPage = async (pageUrl: string): Promise<Doc | undefined> => {\n const page = await fetchPage(runtime, pageUrl, pageOptions);\n const doc = page.doc === null ? undefined : runtime.index.get(page.doc);\n const held = doc !== undefined && isHeldBack(doc, userProvided);\n pages.push({\n url: pageUrl,\n doc: page.doc,\n outcome: page.outcome,\n status: page.status,\n rendered: page.rendered,\n capture: page.capture,\n fetched_at: page.fetched_at,\n from_cache: page.from_cache,\n held_back: held,\n ...(page.archived === undefined ? {} : { archived: page.archived }),\n note: page.note,\n });\n if (!answered(page)) {\n notes.push(`${pageUrl}: ${page.outcome}${page.note === null ? \"\" : ` (${page.note})`}`);\n }\n if (doc === undefined) return undefined;\n if (held) {\n heldBack = true;\n return undefined;\n }\n if (doc.ai_input === \"no\") await recordOverride(runtime, doc, job);\n captures.add(doc.capture);\n return doc;\n };\n\n const readDoc = (doc: Doc): void => {\n const read = venueReadingsOf(doc, { location: options.location });\n readings.push(...read.readings);\n notes.push(...read.notes);\n phone ??= read.phone;\n for (const menu of read.menus) {\n if (menus.length < VENUE_LIMITS.menus && !menus.some((known) => known.url === menu.url))\n menus.push(menu);\n }\n };\n\n let homeUrl: string | null = null;\n let namesVenueResult: boolean | null = null;\n const home = await readPage(site.href);\n if (home !== undefined) {\n homeUrl = archivedOf(home.meta)?.original ?? home.url ?? site.href;\n if (options.name !== undefined) {\n namesVenueResult = namesVenue(options.name, home) ?? null;\n if (namesVenueResult === false) {\n notes.push(\n `${homeUrl} does not name ${options.name}: the domain can belong to a different business now`,\n );\n }\n }\n if (namesVenueResult === false && options.requireName === true) {\n notes.push(\"requireName: the recipe read no hours from a site that does not name the venue\");\n } else {\n readDoc(home);\n for (const link of rankHoursLinks(linksOf(home.meta), homeUrl).slice(0, extra)) {\n if (options.signal?.aborted === true) break;\n const doc = await readPage(link.href);\n if (doc !== undefined) readDoc(doc);\n }\n }\n }\n const moved = homeUrl !== null && hostOf(homeUrl) !== hostOf(site.href) ? homeUrl : null;\n if (moved !== null) notes.push(`${site.href} now goes to ${moved}`);\n if (heldBack) notes.push(HELD_BACK);\n\n // one reading for each source, label and week: a site that repeats its JSON-LD on each page said it once\n const firstOf = new Map<string, VenueReading>();\n for (const one of readings) {\n const key = `${one.from}|${one.label ?? \"\"}|${one.hours}|${one.season ?? \"\"}`;\n if (!firstOf.has(key)) firstOf.set(key, one);\n }\n // the best first; of two equal readings, the reading as written before a guess\n const unique = [...firstOf.values()].sort(\n (a, b) => a.rank - b.rank || Number(a.inferred) - Number(b.inferred),\n );\n const disagree = new Set<Day>();\n const whole = unique.filter((one) => one.rank <= 2);\n for (let i = 0; i < whole.length; i += 1) {\n for (let j = i + 1; j < whole.length; j += 1) {\n for (const day of disagreements(whole[i]!.week, whole[j]!.week)) disagree.add(day);\n }\n }\n const best = unique.find((one) => one.schedule === \"opening\") ?? null;\n const fromSite =\n unique.find((one) => one.from !== \"osm\" && one.schedule === \"opening\" && !one.inferred) ?? null;\n return {\n url: site.href,\n home: homeUrl,\n moved,\n names_venue: namesVenueResult,\n pages,\n readings: unique,\n best,\n from_site: fromSite,\n disagree: DAYS.filter((day) => disagree.has(day)),\n menus,\n phone,\n captures: [...captures],\n held_back: heldBack,\n note: notes.length > 0 ? notes.join(\"; \") : null,\n };\n};\n","/*\n * The product recipe reads a product page: its schema.org Product data. Most shop systems write\n * this data on each product page. The recipe gives the name, the brand, the codes (SKU and GTIN),\n * the price as an amount and a currency, a range of prices across the variants, the availability,\n * the seller, the image, and the variant that the URL names.\n *\n * A shop that refuses the crawler is a clean stop: the result says `wall`, with a note, and the\n * crawler does not try a different identity.\n */\nimport type { Doc } from \"./docs.ts\";\nimport type { Duration } from \"./duration.ts\";\nimport { durationMs } from \"./duration.ts\";\nimport type { Archived } from \"./fallback.ts\";\nimport { archivedOf } from \"./fallback.ts\";\nimport { extractPage, typesOf } from \"./html.ts\";\nimport type { RecipeTarget } from \"./recipe.ts\";\nimport { deadlineOf, runtimeOf } from \"./recipe.ts\";\nimport type { CrawlRuntime, PageOptions, PageResult } from \"./runtime.ts\";\nimport { HELD_BACK, fetchPage, isHeldBack, recordOverride } from \"./runtime.ts\";\nimport { decodeBody } from \"./text.ts\";\n\ntype Json = Readonly<Record<string, unknown>>;\n\n/** These are the limits of the product reader. A page with more is hostile or broken, and the reader stops there. */\nexport const PRODUCT_LIMITS: {\n /** The most JSON-LD records that the reader examines. */\n readonly records: number;\n /** The most offers of one product or variant. */\n readonly offers: number;\n /** The most variants of one product. */\n readonly variants: number;\n /** The levels of `hasVariant` and of nested offers that the reader follows. */\n readonly depth: number;\n /** The longest text of a price. */\n readonly priceChars: number;\n} = { records: 500, offers: 200, variants: 200, depth: 2, priceChars: 64 };\n\n/** An amount of money, as schema.org Product data gives it. */\nexport interface Money {\n /** This value is the amount in the unit of the currency, for example 12.5. */\n readonly amount: number;\n /** This value is the ISO 4217 code of the currency, for example `EUR`. */\n readonly currency: string;\n /** This text is the price as the page wrote it, for a check with `extract`. */\n readonly raw: string;\n}\n\n/** The variant of a product that the URL names. */\nexport interface ProductVariant {\n readonly name: string | null;\n readonly sku: string | null;\n readonly price: Money | null;\n readonly availability: string | null;\n}\n\n/** The result of `productOf`: what the Product data of a page says. */\nexport interface ProductRead {\n /** This value is true when the page has a Product record. */\n readonly found: boolean;\n readonly name: string | null;\n readonly brand: string | null;\n readonly sku: string | null;\n readonly gtin: string | null;\n /** This value is the lowest price of the offers, in the first currency of the page. */\n readonly price: Money | null;\n /** This value is the highest price, when the offers give a range (sizes, colors, variants). */\n readonly price_to: Money | null;\n /**\n * This value is the schema.org name of the availability, for example `InStock`. When the offers\n * do not agree, it is `InStock` if one offer is in stock, and `availabilities` gives each value.\n */\n readonly availability: string | null;\n readonly availabilities: readonly string[];\n /** This value is the variant that the URL names (`?variant=`, `sku` or `gtin`), read alone. */\n readonly variant: ProductVariant | null;\n readonly seller: string | null;\n readonly image: string | null;\n readonly notes: readonly string[];\n /** This value counts the work of the reader. The tests use it, because it does not change with the computer. */\n readonly steps: number;\n}\n\nconst PRODUCT_TYPES = /^(?:Product|ProductGroup|IndividualProduct|ProductModel|SomeProducts)$/;\n\n/** A list price or a struck-through price is the old price, not the price. */\nconst WAS_PRICE = /ListPrice|StrikethroughPrice|MSRP|SRP/i;\n\nconst GTIN_KEYS = [\"gtin13\", \"gtin12\", \"gtin14\", \"gtin8\", \"gtin\"] as const;\n\n/** Two symbols that name one currency only. The other symbols (`$`, `¥`) name more than one. */\nconst SYMBOLS: Readonly<Record<string, string>> = { \"€\": \"EUR\", \"£\": \"GBP\" };\n\nlet knownCurrencies: ReadonlySet<string> | undefined;\n/** This function tells if a code is an ISO 4217 currency that the runtime knows. */\nconst isCurrency = (code: string): boolean => {\n if (!/^[A-Z]{3}$/.test(code)) return false;\n if (knownCurrencies === undefined) {\n try {\n knownCurrencies = new Set(Intl.supportedValuesOf(\"currency\"));\n } catch {\n // a runtime with no list: each code of three capital letters counts\n knownCurrencies = new Set();\n }\n }\n return knownCurrencies.size === 0 || knownCurrencies.has(code);\n};\n\n/** This function gives the number of digits after the decimal point of a currency: 2 for EUR, 0 for JPY. */\nconst fractionDigits = (currency: string | undefined): number | undefined => {\n if (currency === undefined) return undefined;\n try {\n return new Intl.NumberFormat(\"en\", { style: \"currency\", currency }).resolvedOptions()\n .maximumFractionDigits;\n } catch {\n return undefined;\n }\n};\n\n/**\n * This function reads an amount as a shop writes it: `19.99`, `1,299.00`, `1.299,00`, `$19.99` or\n * the number 19.99. The last separator is the decimal point, with one exception. One kind of\n * separator, each followed by three digits, separates thousands: `1.299` is 1299. For a\n * currency with three decimal digits, one point with three digits is the decimal point. A text\n * with two numbers (a range), a negative amount or zero gives undefined.\n */\nexport const readAmount = (value: unknown, currency?: string): number | undefined => {\n if (typeof value === \"number\") return Number.isFinite(value) && value > 0 ? value : undefined;\n if (typeof value !== \"string\" || value.length > PRODUCT_LIMITS.priceChars) return undefined;\n // one number, with the currency and the spaces around it\n const match = /^[^\\d-]*?(\\d(?:[\\d.,'   ]*\\d)?)[^\\d]*$/.exec(value.trim());\n if (match === null) return undefined;\n let digits = match[1]!.replace(/['   ]/g, \"\");\n const last = Math.max(digits.lastIndexOf(\".\"), digits.lastIndexOf(\",\"));\n if (last !== -1) {\n const kinds = new Set(digits.match(/[.,]/g));\n const groups = kinds.size === 1 && /^[1-9]\\d{0,2}(?:[.,]\\d{3})+$/.test(digits);\n const decimalThree = groups && fractionDigits(currency) === 3 && /^\\d+\\.\\d{3}$/.test(digits);\n digits =\n groups && !decimalThree\n ? digits.replace(/[.,]/g, \"\")\n : `${digits.slice(0, last).replace(/[.,]/g, \"\")}.${digits.slice(last + 1)}`;\n }\n const amount = Number(digits);\n return Number.isFinite(amount) && amount > 0 ? amount : undefined;\n};\n\nconst list = (value: unknown, limit: number): unknown[] =>\n (Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]).slice(\n 0,\n limit,\n );\n\nconst objects = (value: unknown, limit: number): Json[] =>\n list(value, limit).filter(\n (item): item is Json => typeof item === \"object\" && item !== null && !Array.isArray(item),\n );\n\n/** This function gives a name, written as a text or as an object that has one. */\nconst nameOf = (value: unknown): string | null => {\n for (const item of list(value, 20)) {\n if (typeof item === \"string\" && item.trim().length > 0) return item.trim().slice(0, 500);\n if (typeof item === \"object\" && item !== null) {\n const named = (item as Json)[\"name\"];\n if (typeof named === \"string\" && named.trim().length > 0) return named.trim().slice(0, 500);\n }\n }\n return null;\n};\n\nconst textOf = (value: unknown): string | null =>\n typeof value === \"string\" && value.trim().length > 0\n ? value.trim().slice(0, 200)\n : typeof value === \"number\" && Number.isFinite(value)\n ? String(value)\n : null;\n\nconst imageOf = (value: unknown): string | null => {\n for (const item of list(value, 20)) {\n if (typeof item === \"string\" && /^https?:/i.test(item)) return item;\n const url = typeof item === \"object\" && item !== null ? (item as Json)[\"url\"] : undefined;\n if (typeof url === \"string\" && /^https?:/i.test(url)) return url;\n }\n return null;\n};\n\ninterface Offers {\n readonly prices: Money[];\n readonly unknownCurrencies: Set<string>;\n readonly availability: Set<string>;\n readonly sellers: Set<string>;\n /** An amount with no currency, which is not a price. */\n unstated: boolean;\n steps: number;\n}\n\nconst emptyOffers = (): Offers => ({\n prices: [],\n unknownCurrencies: new Set(),\n availability: new Set(),\n sellers: new Set(),\n unstated: false,\n steps: 0,\n});\n\n/** This function reads the offers of a product into `read`, and the offers of its variants to `depth` levels. */\nconst readOffers = (product: Json, read: Offers, depth: number): void => {\n const money = (value: unknown, currency: unknown): void => {\n const written = typeof currency === \"string\" ? currency.trim() : \"\";\n const code = SYMBOLS[written] ?? written.toUpperCase();\n const amount = readAmount(value, code.length > 0 ? code : undefined);\n if (amount === undefined) return;\n if (code.length === 0) {\n read.unstated = true;\n return;\n }\n if (!isCurrency(code)) {\n read.unknownCurrencies.add(written.slice(0, 20));\n return;\n }\n read.prices.push({\n amount,\n currency: code,\n raw: String(value).slice(0, PRODUCT_LIMITS.priceChars),\n });\n };\n const offer = (o: Json, level: number): void => {\n read.steps += 1;\n const spec = objects(o[\"priceSpecification\"], PRODUCT_LIMITS.offers).find((entry) => {\n const kind = entry[\"priceType\"];\n return !(typeof kind === \"string\" && WAS_PRICE.test(kind));\n });\n const currency = o[\"priceCurrency\"] ?? spec?.[\"priceCurrency\"];\n money(o[\"price\"] ?? spec?.[\"price\"], currency);\n money(o[\"lowPrice\"], currency);\n money(o[\"highPrice\"], currency);\n const availability =\n typeof o[\"availability\"] === \"string\"\n ? o[\"availability\"]\n .trim()\n .replace(/^.*[/#:]/, \"\")\n .slice(0, 60)\n : undefined;\n if (availability !== undefined && availability.length > 0) read.availability.add(availability);\n const seller = nameOf(o[\"seller\"]);\n if (seller !== null) read.sellers.add(seller);\n // an AggregateOffer can list its offers\n if (level < PRODUCT_LIMITS.depth) {\n for (const inner of objects(o[\"offers\"], PRODUCT_LIMITS.offers)) offer(inner, level + 1);\n }\n };\n for (const o of objects(product[\"offers\"], PRODUCT_LIMITS.offers)) offer(o, 0);\n if (depth <= 0) return;\n for (const variant of objects(product[\"hasVariant\"], PRODUCT_LIMITS.variants)) {\n read.steps += 1;\n readOffers(variant, read, depth - 1);\n }\n};\n\nconst availabilityOf = (read: Offers): string | null =>\n read.availability.size === 0\n ? null\n : read.availability.size === 1 || !read.availability.has(\"InStock\")\n ? [...read.availability][0]!\n : \"InStock\";\n\nconst pathKey = (value: string, page: string): string | undefined => {\n // \"#product\" names a part of this page: a related product can have such an id too\n if (value.startsWith(\"#\")) return undefined;\n try {\n const url = new URL(value, page);\n return `${url.hostname.toLowerCase().replace(/^www\\./, \"\")}${url.pathname.replace(/\\/$/, \"\")}`;\n } catch {\n return undefined;\n }\n};\n\n/** This function gives the size of a record as JSON, or 0 for a record that JSON cannot write (a nesting too deep). */\nconst sizeOf = (record: Json): number => {\n try {\n return JSON.stringify(record).length;\n } catch {\n return 0;\n }\n};\n\n/**\n * This function picks the product of a page from its JSON-LD records. A page often has more\n * records of products: the related products, the products that others bought. It picks:\n *\n * 1. The product whose `url` or `@id` is the page (the path, with no query).\n * 2. Else the largest product with offers or variants.\n * 3. Else the largest product.\n *\n * It also reads the `mainEntity` of a record (a `WebPage` or an `ItemPage` that names its product).\n */\nexport const pickProduct = (\n records: readonly Json[],\n page: string,\n): { readonly product: Json | undefined; readonly steps: number } => {\n let steps = 0;\n const products: Json[] = [];\n for (const record of records.slice(0, PRODUCT_LIMITS.records)) {\n steps += 1;\n if (typesOf(record as Record<string, unknown>).some((type) => PRODUCT_TYPES.test(type)))\n products.push(record);\n for (const inner of objects(record[\"mainEntity\"], 20)) {\n steps += 1;\n if (typesOf(inner as Record<string, unknown>).some((type) => PRODUCT_TYPES.test(type)))\n products.push(inner);\n }\n }\n const here = pathKey(page, page);\n const own = products.find((product) =>\n [product[\"url\"], product[\"@id\"]].some(\n (value) => typeof value === \"string\" && here !== undefined && pathKey(value, page) === here,\n ),\n );\n if (own !== undefined) return { product: own, steps };\n const selling = products.filter(\n (product) => list(product[\"offers\"], 1).length > 0 || list(product[\"hasVariant\"], 1).length > 0,\n );\n const pool = selling.length > 0 ? selling : products;\n let best: Json | undefined;\n let size = -1;\n for (const product of pool) {\n const length = sizeOf(product);\n steps += length;\n if (length > size) {\n best = product;\n size = length;\n }\n }\n return { product: best, steps };\n};\n\n/** This function gives the variant that a URL names: the `variant` parameter of Shopify, or a `sku` or `gtin` parameter. */\nexport const pickVariant = (product: Json, page: string): Json | undefined => {\n let params: URLSearchParams;\n try {\n params = new URL(page).searchParams;\n } catch {\n return undefined;\n }\n const variantId = params.get(\"variant\");\n const code = params.get(\"sku\") ?? params.get(\"gtin\");\n if (variantId === null && code === null) return undefined;\n const names = (value: unknown): boolean => {\n if (typeof value !== \"string\" || variantId === null) return false;\n try {\n return (\n new URL(value, page).searchParams.get(\"variant\") === variantId ||\n value.endsWith(`/${variantId}`)\n );\n } catch {\n return false;\n }\n };\n return objects(product[\"hasVariant\"], PRODUCT_LIMITS.variants).find((variant) => {\n const offers = objects(variant[\"offers\"], PRODUCT_LIMITS.offers);\n const codes = [\n variant[\"sku\"],\n variant[\"gtin\"],\n variant[\"gtin13\"],\n variant[\"gtin12\"],\n variant[\"productID\"],\n ]\n .map(textOf)\n .filter((one): one is string => one !== null);\n return (\n (code !== null && codes.includes(code)) ||\n [variant[\"@id\"], variant[\"url\"], ...offers.map((offer) => offer[\"url\"])].some(names) ||\n (variantId !== null && codes.includes(variantId))\n );\n });\n};\n\nconst byAmount = (a: Money, b: Money): number => a.amount - b.amount;\n\n/**\n * This function reads the Product data of a page from its JSON-LD records. It is pure, and it sends\n * no request. Thus it also reads a version at a time, or the stored JSON-LD of a document.\n *\n * - The prices are in the first currency of the offers. A price with no currency is not a price.\n * - A list price or a struck-through price is not the price.\n * - A currency must be an ISO 4217 code (`€` and `£` count too). The notes name each other one.\n */\nexport const productOf = (records: readonly Json[], page: string): ProductRead => {\n const picked = pickProduct(records, page);\n const product = picked.product;\n if (product === undefined) {\n return {\n found: false,\n name: null,\n brand: null,\n sku: null,\n gtin: null,\n price: null,\n price_to: null,\n availability: null,\n availabilities: [],\n variant: null,\n seller: null,\n image: null,\n notes: [\n \"no schema.org Product data on the page: a list of products, or a shop that does not publish it\",\n ],\n steps: picked.steps,\n };\n }\n const read = emptyOffers();\n readOffers(product, read, PRODUCT_LIMITS.depth);\n const currency = read.prices[0]?.currency;\n const sorted = read.prices.filter((price) => price.currency === currency).sort(byAmount);\n const low = sorted[0] ?? null;\n const high = sorted.at(-1) ?? null;\n const gtin = GTIN_KEYS.map((key) => textOf(product[key])).find((value) => value !== null);\n const chosen = pickVariant(product, page);\n let variant: ProductVariant | null = null;\n let steps = picked.steps + read.steps;\n if (chosen !== undefined) {\n const own = emptyOffers();\n readOffers(chosen, own, 0);\n steps += own.steps;\n const prices = own.prices.filter((price) => price.currency === currency).sort(byAmount);\n variant = {\n name: nameOf(chosen[\"name\"]),\n sku: textOf(chosen[\"sku\"]),\n price: prices[0] ?? null,\n availability: availabilityOf(own),\n };\n }\n const notes = [\n read.unknownCurrencies.size > 0\n ? `a currency that is not an ISO 4217 code: ${[...read.unknownCurrencies].join(\", \")}`\n : null,\n read.unstated && sorted.length === 0\n ? \"the page gives a price with no currency, so the price is not read as money\"\n : sorted.length === 0\n ? \"the page names the product and gives no price\"\n : null,\n new Set(read.prices.map((price) => price.currency)).size > 1\n ? `the offers have more than one currency: the prices are in ${currency ?? \"\"}`\n : null,\n /[?&](?:variant|sku|gtin)=/.test(page) && chosen === undefined\n ? \"the URL names a variant that the Product data does not list: the price is the whole range\"\n : null,\n ].filter((note): note is string => note !== null);\n return {\n found: true,\n name: nameOf(product[\"name\"]),\n brand: nameOf(product[\"brand\"]),\n sku: textOf(product[\"sku\"]),\n gtin: gtin ?? null,\n price: low,\n price_to: high !== null && low !== null && high.amount > low.amount ? high : null,\n availability: availabilityOf(read),\n availabilities: [...read.availability],\n variant,\n seller: read.sellers.size === 0 ? null : [...read.sellers].join(\", \"),\n image: imageOf(product[\"image\"]),\n notes,\n steps,\n };\n};\n\n// ── the recipe ──────────────────────────────────────────────────────────────\n\n/** These options control `readProduct`. */\nexport interface ProductOptions {\n /** The value `auto` (the default) renders once more when the plain page has no Product data. `never` does not render. */\n readonly render?: \"auto\" | \"never\" | \"always\" | undefined;\n /** A stored copy younger than this age answers with no request. The default is `24h`. */\n readonly maxAge?: Duration | undefined;\n /** These agents get their robots.txt rules applied too, for example `Claude-User`. */\n readonly onBehalfOf?: readonly string[] | undefined;\n readonly signal?: AbortSignal | undefined;\n /** No request starts after this time from the start of the read, for example `\"1m\"`. */\n readonly budget?: Duration | undefined;\n readonly scope?: string | undefined;\n readonly labels?: Readonly<Record<string, string>> | undefined;\n /** This name connects the captures to the job that asked for them. The default is `product`. */\n readonly job?: string | undefined;\n /** This value is true when a person gave this URL directly. It is the only way to read a held-back page. The crawler logs it. */\n readonly userProvided?: boolean | undefined;\n /** The value `archive` reads an archived copy of a page that the shop refuses. Its prices are of the date of the copy. */\n readonly fallback?: \"archive\" | \"none\" | undefined;\n readonly archiveDespiteRobots?: boolean | undefined;\n}\n\n/** The result of `readProduct`. */\nexport interface ProductResult extends Omit<ProductRead, \"steps\" | \"notes\"> {\n readonly url: string;\n /** This value is true when the page says what it sells, in structured data: the Product has a name. */\n readonly verified: boolean;\n /**\n * This value is true when the site refused the crawler. The causes are a 401, a 402 or a 403, a\n * challenge, a bot check, a stop of the host or robots.txt. The recipe stops there, and the note\n * says why. With `fallback: \"archive\"`, it stays true when an archived copy answers.\n */\n readonly wall: boolean;\n readonly outcome: string;\n readonly status: number;\n readonly rendered: boolean;\n readonly doc: string | null;\n /** This id is the capture of the text that the recipe read. A citation names it. */\n readonly capture: string | null;\n readonly fetched_at: string | null;\n readonly captures: readonly string[];\n readonly from_cache: boolean;\n /** This value is true when the page asked not to be AI input, so the recipe read nothing from it. */\n readonly held_back: boolean;\n /** This value tells that the page is an archived copy, with the archive and the date of the copy. */\n readonly archived?: Archived | undefined;\n readonly note: string | null;\n}\n\nconst WALLS: ReadonlySet<string> = new Set([\"blocked\", \"challenge\", \"payment-required\"]);\n\n/** This function tells if the site refused the crawler. */\nconst wallOf = (page: PageResult): boolean =>\n WALLS.has(page.outcome) ||\n (page.outcome === \"skipped\" && /^(?:robots\\.txt disallows|host stopped)/.test(page.note ?? \"\")) ||\n (page.doc === null && /\\bbot check\\b/.test(page.note ?? \"\"));\n\nconst answered = (page: PageResult): boolean =>\n page.doc !== null &&\n (page.outcome === \"ok\" || page.outcome === \"not-modified\" || page.archived !== undefined);\n\n/**\n * This function gives the JSON-LD records of a document from its stored body. The index keeps a\n * part of the JSON-LD of a large page only, and a product with many variants can be larger. An\n * archived copy gives the JSON-LD that the index keeps.\n */\nconst recordsOfDoc = async (runtime: CrawlRuntime, doc: Doc): Promise<readonly Json[]> => {\n const kept = Array.isArray(doc.meta[\"jsonld\"]) ? (doc.meta[\"jsonld\"] as Json[]) : [];\n if (doc.blob === null || archivedOf(doc.meta) !== undefined) return kept;\n const body = await runtime.blobs.get(doc.blob);\n if (body === undefined) return kept;\n const at = doc.url ?? \"\";\n const type = doc.rendered\n ? \"text/html; charset=utf-8\"\n : (runtime.index.latest(at, \"plain\")?.content_type ?? null);\n try {\n return extractPage(decodeBody(body, type), at).jsonld;\n } catch {\n return kept;\n }\n};\n\n/**\n * This function reads a product page. It fetches the page through the crawler: robots.txt, the\n * pace, the stops, the capture log and the rule for a held-back page apply. When the plain page has\n * no Product data, it renders the page once, because some shops write that data with JavaScript.\n *\n * A shop that refuses the crawler gives `wall: true` and a note. The recipe writes nothing but the\n * capture log. `extract` can check each value against the stored page.\n */\nexport const readProduct = async (\n target: RecipeTarget,\n url: string,\n options: ProductOptions = {},\n): Promise<ProductResult> => {\n const runtime = runtimeOf(target);\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new TypeError(url);\n } catch {\n throw new TypeError(`readProduct needs an http or https URL, not ${JSON.stringify(url)}`);\n }\n const maxAge = options.maxAge ?? \"24h\";\n const job = options.job ?? \"product\";\n const userProvided = options.userProvided ?? false;\n const render = options.render ?? \"auto\";\n const deadline = deadlineOf(runtime, options.budget);\n const pageOptions = (mode: \"auto\" | \"never\" | \"always\"): PageOptions => ({\n render: mode,\n maxAgeMs: maxAge === \"auto\" ? \"auto\" : durationMs(maxAge),\n onBehalfOf: options.onBehalfOf,\n job,\n signal: options.signal,\n scope: options.scope,\n labels: options.labels,\n deadline,\n fallback: options.fallback,\n archiveDespiteRobots: options.archiveDespiteRobots,\n });\n let page = await fetchPage(runtime, url, pageOptions(render));\n const notes: string[] = [];\n const result = (\n from: PageResult,\n read: Omit<ProductRead, \"steps\"> | undefined,\n more: { readonly held_back?: boolean } = {},\n ): ProductResult => {\n const all = [from.note, ...notes, ...(read?.notes ?? [])].filter(\n (part): part is string => part !== null && part !== undefined && part.length > 0,\n );\n return {\n url,\n found: read?.found ?? false,\n verified: read?.found === true && read.name !== null,\n name: read?.name ?? null,\n brand: read?.brand ?? null,\n sku: read?.sku ?? null,\n gtin: read?.gtin ?? null,\n price: read?.price ?? null,\n price_to: read?.price_to ?? null,\n availability: read?.availability ?? null,\n availabilities: read?.availabilities ?? [],\n variant: read?.variant ?? null,\n seller: read?.seller ?? null,\n image: read?.image ?? null,\n wall: wallOf(from),\n outcome: from.outcome,\n status: from.status,\n rendered: from.rendered,\n doc: from.doc,\n capture: from.capture,\n fetched_at: from.fetched_at,\n captures: [...from.captures],\n from_cache: from.from_cache,\n held_back: more.held_back ?? false,\n ...(from.archived === undefined ? {} : { archived: from.archived }),\n note: all.length > 0 ? [...new Set(all)].join(\"; \") : null,\n };\n };\n if (!answered(page)) {\n const wall = wallOf(page);\n notes.push(\n wall\n ? `the shop refused the crawler (${page.outcome}): the recipe read nothing, and it does not try a different identity`\n : `the page gave no document (${page.outcome})`,\n );\n return result(page, undefined);\n }\n const held = (from: PageResult): Doc | undefined => {\n const doc = from.doc === null ? undefined : runtime.index.get(from.doc);\n return doc !== undefined && isHeldBack(doc, userProvided) ? doc : undefined;\n };\n if (held(page) !== undefined) {\n notes.push(HELD_BACK);\n return result(page, undefined, { held_back: true });\n }\n const docOf = (from: PageResult): Doc | undefined =>\n from.doc === null ? undefined : runtime.index.get(from.doc);\n let doc = docOf(page);\n let read = doc === undefined ? undefined : productOf(await recordsOfDoc(runtime, doc), url);\n // some shops write their Product data with JavaScript: one render before the recipe says that the page has none\n if (read?.found !== true && !page.rendered && render === \"auto\" && page.archived === undefined) {\n const rendered = await fetchPage(runtime, url, pageOptions(\"always\"));\n const shown = docOf(rendered);\n if (\n rendered.rendered &&\n answered(rendered) &&\n shown !== undefined &&\n held(rendered) === undefined\n ) {\n page = rendered;\n doc = shown;\n read = productOf(await recordsOfDoc(runtime, shown), url);\n } else if (rendered.note !== null && !rendered.rendered) {\n notes.push(`the render gave nothing more: ${rendered.note}`);\n }\n }\n if (userProvided && doc?.ai_input === \"no\") await recordOverride(runtime, doc, job);\n return result(page, read);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,eAaT;CAAE,OAAO;CAAG,UAAU;CAAG,OAAO;CAAG,iBAAiB;CAAI,OAAO;CAAK,YAAY;AAAI;AAIxF,MAAM,6BAAkC,IAAI,IAAI;CAAC;CAAO;CAAK;CAAM;CAAO;CAAM;AAAI,CAAC;;AAGrF,MAAM,WAAW,SACf,K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