@rebilder/agent-readability 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/probe/ssrf.ts","../../src/profiles.ts","../../src/ruleset.ts","../../src/html.ts","../../src/extract.ts","../../src/robots-policy.ts","../../src/probe/headers.ts","../../src/score.ts","../../src/probe/limiter.ts","../../src/probe/index.ts","../../src/probe/local.ts"],"names":["dnsPromises","deepFreeze","a","b"],"mappings":";;;;;AAgEO,IAAM,mBAAA,0BAA4C,wCAAwC,CAAA;AAK1F,IAAM,kBAAA,GAAqB,CAAC,MAAA,KAAgC,MAAA,KAAW,mBAAA;AAa9E,IAAM,YAA8B,EAAE,MAAA,EAAQ,MAAM,QAAA,EAAU,KAAA,EAAO,OAAO,UAAA,EAAW;AAEvF,IAAM,UAAA,GAAa,sBAAA;AAGZ,SAAS,UAAU,IAAA,EAAuD;AAC/E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC5B,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,IAAI,GAAG,OAAO,IAAA;AACnC,IAAA,MAAM,KAAA,GAAQ,OAAO,IAAI,CAAA;AACzB,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,KAAA,GAAQ,KAAK,OAAO,IAAA;AACpD,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,EACnB;AACA,EAAA,MAAM,CAAC,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA,GAAI,MAAA;AACrB,EAAA,IAAI,CAAA,KAAM,UAAa,CAAA,KAAM,MAAA,IAA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MACR,qEAAqE,kBAAkB,CAAA,uQAAA;AAAA,KAIzF;AAAA,EACF;AACF;AAEA,uBAAA,EAAwB;AAQjB,SAAS,WAAA,CAAY,OAAA,EAAkB,OAAA,GAAsB,eAAA,EAA8B;AAChG,EAAA,OAAO,EAAE,GAAG,YAAA,CAAa,SAAS,OAAO,CAAA,EAAG,WAAW,IAAA,EAAK;AAC9D;AAWO,SAAS,UAAA,CACd,MAAA,EACA,MAAA,EACA,OAAA,GAAwB,EAAC,EACF;AACvB,EAAA,OAAO,mBAAA,CAAoB,MAAA,EAAQ,MAAA,EAAQ,mBAAA,EAAqB;AAAA,IAC9D,GAAG,OAAA;AAAA,IACH,OAAA,EAAS,QAAQ,OAAA,IAAW;AAAA,GAC7B,CAAA;AACH","file":"local.js","sourcesContent":["/**\n * probe/ssrf.ts — the network-side host policy for `@rebilder/agent-readability`.\n *\n * WHAT CHANGED, AND WHY IT HAD TO. The ancestor of this file (the Console\n * preview's URL guard) described itself as *\"Pure parse +\n * reject (no DNS resolution in v1)\"*. That sentence is deliberately not repeated\n * here, because it is a description of a hole. A parse-only guard rejects IP\n * literals; it does not reject `https://attacker.example/` whose A record is\n * `169.254.169.254`, `10.0.0.5` or `127.0.0.1`, and DNS rebinding beats it by\n * construction — resolve public, pass the guard, resolve private, connect.\n * Behind a Console login that was defensible. On a public endpoint it is not,\n * and this module is the one the public scanner, the CLI and the MCP server all\n * go through. So (design §5.2):\n *\n * 1. WE RESOLVE THE HOSTNAME OURSELVES and reject if **any** returned A/AAAA\n * is private or reserved. Not \"the first one\" — a hostname with one public\n * and one private answer is an attack, not a multi-homed service.\n * 2. WE CONNECT PINNED TO THE VALIDATED IP, with `Host` and SNI still carrying\n * the hostname. This closes the rebinding window: the address the guard\n * approved is the address the socket uses, because the resolver the socket\n * would have called is replaced by a function that returns the approved set\n * and nothing else.\n * 3. EVERY REDIRECT HOP RE-RESOLVES AND RE-PINS. Re-parsing the `Location`\n * URL is not enough; hop 2 is a fresh connection to a fresh name.\n * 4. THE RESERVED SET IS THE FULL ONE — CGNAT (`100.64/10`, which is also\n * where Alibaba keeps its metadata service at `100.100.100.200`), IETF\n * protocol assignments, benchmarking, multicast, the whole of `240/4`,\n * the broadcast address, and the IPv6 equivalents including IPv4-mapped\n * and NAT64/6to4 forms, where a reserved v4 address hides inside a v6 one.\n *\n * WHAT THIS MODULE STILL CANNOT DO. It cannot stop a target whose *public* IP\n * fronts an internal service (a cloud load balancer with a private backend), and\n * it cannot stop a captive network from answering for someone else. Design §5.2\n * requires the belt to the braces: scanner egress runs on a network with no route\n * to cloud metadata or any internal subnet. This file assumes that and does not\n * replace it.\n *\n * NOT AN ENTRY POINT. `package.json#exports` publishes `.`, `./probe` and\n * `./probe/local` only, so `ALLOW_PRIVATE_HOSTS` below is unreachable from\n * outside the package at runtime, and the package-graph check fails any deep\n * import that tries. That is what makes the symbol an unforgeable capability\n * rather than a naming convention.\n */\n\nimport { promises as dnsPromises } from 'node:dns'\nimport * as http from 'node:http'\nimport * as https from 'node:https'\nimport type { LookupFunction } from 'node:net'\n\n/* ── the host policy capability ───────────────────────────────────────────── */\n\n/**\n * The capability that unlocks private/loopback targets. Held by `./probe/local`\n * and by nothing else.\n *\n * WHY A SYMBOL AND NOT A BOOLEAN. `ProbePolicy` (see `./index`) has no\n * `allowPrivateHosts` field on purpose. A boolean on a shared config object will\n * eventually be passed as `true` by a hosted endpoint — not maliciously, just by\n * someone wiring a new route who copies a working config. The concrete failure:\n * an MCP server on a developer's machine, driven by a model whose context\n * contains untrusted web text, asked to \"check http://169.254.169.254/\". A symbol\n * that only a separate, import-time-gated entry point can obtain cannot be turned\n * on by a config file, an env var, or a copied object literal.\n */\nexport const ALLOW_PRIVATE_HOSTS: unique symbol = Symbol('rebilder.ars.probe.allow-private-hosts')\n\n/** `'public-only'` everywhere except the `./probe/local` entry point. */\nexport type HostPolicy = 'public-only' | typeof ALLOW_PRIVATE_HOSTS\n\nexport const allowsPrivateHosts = (policy: HostPolicy): boolean => policy === ALLOW_PRIVATE_HOSTS\n\n/* ── IP classification ────────────────────────────────────────────────────── */\n\nexport interface IpClassification {\n /** `null` when the text is not an IP literal at all (i.e. it is a hostname). */\n readonly family: 4 | 6 | null\n /** True for anything that is not a globally routable unicast address. */\n readonly reserved: boolean\n /** Human-readable reason, printed in guard messages and probe details. */\n readonly label: string\n}\n\nconst NOT_AN_IP: IpClassification = { family: null, reserved: false, label: 'hostname' }\n\nconst IPV4_OCTET = /^(?:0|[1-9]\\d{0,2})$/\n\n/** Strict dotted-quad. Leading zeros are rejected: `010.0.0.1` is ambiguous octal. */\nexport function parseIpv4(text: string): [number, number, number, number] | null {\n const parts = text.split('.')\n if (parts.length !== 4) return null\n const octets: number[] = []\n for (const part of parts) {\n if (!IPV4_OCTET.test(part)) return null\n const value = Number(part)\n if (!Number.isInteger(value) || value > 255) return null\n octets.push(value)\n }\n const [a, b, c, d] = octets\n if (a === undefined || b === undefined || c === undefined || d === undefined) return null\n return [a, b, c, d]\n}\n\n/**\n * IPv4 reserved ranges. The first six shipped in the Console guard; the rest are\n * the §5.2 expansion. `255.255.255.255` is inside `240/4` and is listed anyway\n * because the design lists it and a reader should not have to do the arithmetic.\n */\nfunction classifyIpv4Octets(octets: readonly [number, number, number, number]): IpClassification {\n const [a, b] = octets\n const v4 = (label: string, reserved: boolean): IpClassification => ({\n family: 4,\n reserved,\n label,\n })\n\n if (a === 0) return v4('this-network (0.0.0.0/8)', true)\n if (a === 10) return v4('private (10.0.0.0/8)', true)\n if (a === 100 && b >= 64 && b <= 127) return v4('carrier-grade NAT (100.64.0.0/10)', true)\n if (a === 127) return v4('loopback (127.0.0.0/8)', true)\n if (a === 169 && b === 254) return v4('link-local / cloud metadata (169.254.0.0/16)', true)\n if (a === 172 && b >= 16 && b <= 31) return v4('private (172.16.0.0/12)', true)\n if (a === 192 && b === 0 && octets[2] === 0)\n return v4('IETF protocol assignments (192.0.0.0/24)', true)\n if (a === 192 && b === 168) return v4('private (192.168.0.0/16)', true)\n if (a === 198 && (b === 18 || b === 19)) return v4('benchmarking (198.18.0.0/15)', true)\n if (a >= 224 && a <= 239) return v4('multicast (224.0.0.0/4)', true)\n if (a >= 240) return v4('reserved / broadcast (240.0.0.0/4)', true)\n return v4('public', false)\n}\n\n/**\n * IPv6 to eight 16-bit groups. Handles `::` compression, a zone id, and the\n * trailing-IPv4 forms (`::ffff:169.254.169.254`, `64:ff9b::10.0.0.5`) that are\n * the whole reason IPv6 belongs in an SSRF guard at all.\n */\nexport function parseIpv6(input: string): number[] | null {\n let text = input.trim()\n if (text.startsWith('[') && text.endsWith(']')) text = text.slice(1, -1)\n const zone = text.indexOf('%')\n if (zone !== -1) text = text.slice(0, zone)\n if (text.length === 0 || !text.includes(':')) return null\n\n // A trailing dotted quad is the last two groups. Rewriting it as hex up front\n // means the rest of the parser only ever sees hex groups and `::` — the\n // alternative (splicing groups back on afterwards) is where the separator\n // colon gets miscounted and `64:ff9b::10.0.0.5` silently fails to parse.\n const lastColon = text.lastIndexOf(':')\n const maybeV4 = text.slice(lastColon + 1)\n if (maybeV4.includes('.')) {\n const quad = parseIpv4(maybeV4)\n if (quad === null) return null\n const hi = ((quad[0] << 8) | quad[1]).toString(16)\n const lo = ((quad[2] << 8) | quad[3]).toString(16)\n text = `${text.slice(0, lastColon + 1)}${hi}:${lo}`\n }\n\n const doubleColon = text.indexOf('::')\n if (doubleColon !== text.lastIndexOf('::')) return null\n\n const toGroups = (segment: string): number[] | null => {\n if (segment.length === 0) return []\n const out: number[] = []\n for (const piece of segment.split(':')) {\n if (piece.length === 0 || piece.length > 4 || !/^[0-9a-fA-F]+$/.test(piece)) return null\n out.push(Number.parseInt(piece, 16))\n }\n return out\n }\n\n if (doubleColon === -1) {\n const only = toGroups(text)\n return only !== null && only.length === 8 ? only : null\n }\n const head = toGroups(text.slice(0, doubleColon))\n const rest = toGroups(text.slice(doubleColon + 2))\n if (head === null || rest === null) return null\n const explicit = head.length + rest.length\n if (explicit > 7) return null\n const zeros = new Array<number>(8 - explicit).fill(0)\n return [...head, ...zeros, ...rest]\n}\n\nfunction classifyIpv6Groups(groups: readonly number[]): IpClassification {\n const v6 = (label: string, reserved: boolean): IpClassification => ({\n family: 6,\n reserved,\n label,\n })\n const g = (index: number): number => groups[index] ?? 0\n const embeddedV4 = (hi: number, lo: number): [number, number, number, number] => [\n (hi >> 8) & 0xff,\n hi & 0xff,\n (lo >> 8) & 0xff,\n lo & 0xff,\n ]\n\n const allZeroThrough = (upTo: number): boolean => groups.slice(0, upTo).every((x) => x === 0)\n\n if (groups.every((x) => x === 0)) return v6('unspecified (::)', true)\n if (allZeroThrough(7) && g(7) === 1) return v6('loopback (::1)', true)\n\n // IPv4-mapped ::ffff:a.b.c.d and the deprecated IPv4-compatible ::a.b.c.d.\n if (allZeroThrough(5) && g(5) === 0xffff) {\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`IPv4-mapped → ${inner.label}`, inner.reserved)\n }\n if (allZeroThrough(6)) {\n // IPv4-compatible ::a.b.c.d is deprecated (RFC 4291 §2.5.5.1) and reserved\n // regardless of what the embedded address would be on its own.\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`IPv4-compatible → ${inner.label}`, true)\n }\n // NAT64 well-known prefix 64:ff9b::/96 — the v4 address rides in the last 32 bits.\n if (g(0) === 0x0064 && g(1) === 0xff9b && g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`NAT64 64:ff9b::/96 → ${inner.label}`, inner.reserved)\n }\n // 6to4 2002::/16 — the v4 address rides in groups 1 and 2.\n if (g(0) === 0x2002) {\n const inner = classifyIpv4Octets(embeddedV4(g(1), g(2)))\n return v6(`6to4 2002::/16 → ${inner.label}`, inner.reserved)\n }\n if (g(0) === 0x0100 && g(1) === 0 && g(2) === 0 && g(3) === 0)\n return v6('discard-only (100::/64)', true)\n if (g(0) === 0x2001 && g(1) === 0x0db8) return v6('documentation (2001:db8::/32)', true)\n if ((g(0) & 0xfe00) === 0xfc00) return v6('unique local (fc00::/7)', true)\n if ((g(0) & 0xffc0) === 0xfe80) return v6('link-local (fe80::/10)', true)\n if ((g(0) & 0xff00) === 0xff00) return v6('multicast (ff00::/8)', true)\n return v6('public', false)\n}\n\n/**\n * Classifies an IP literal. `family: null` means the text is not an IP at all.\n * Fails closed: anything that looks like an IP but does not parse is reserved.\n */\nexport function classifyIp(text: string): IpClassification {\n const trimmed = text.trim()\n const bare = trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed\n\n const quad = parseIpv4(bare)\n if (quad !== null) return classifyIpv4Octets(quad)\n\n if (bare.includes(':')) {\n const groups = parseIpv6(bare)\n if (groups === null) return { family: 6, reserved: true, label: 'unparseable IPv6 literal' }\n return classifyIpv6Groups(groups)\n }\n // Looks numeric but is not a valid dotted quad — treat as unusable, not as a name.\n if (/^[0-9.]+$/.test(bare))\n return { family: 4, reserved: true, label: 'unparseable IPv4 literal' }\n return NOT_AN_IP\n}\n\n/* ── URL syntax guard ─────────────────────────────────────────────────────── */\n\nexport type UrlGuardResult = { ok: true; url: URL } | { ok: false; reason: string }\n\nexport interface UrlGuardPolicy {\n /** `false` in every hosted path. `true` only under `./probe/local`. */\n readonly allowHttp: boolean\n readonly hostPolicy: HostPolicy\n}\n\n/** Hostname suffixes that never name a public host. */\nconst PRIVATE_SUFFIXES = ['.localhost', '.local', '.internal'] as const\n\n/**\n * Parse + reject, with no I/O. This is the FIRST of two gates, not the only one:\n * `resolveAndValidate` is the second and is the one that closes the DNS hole.\n * Splitting them keeps the syntactic policy testable without a resolver and keeps\n * the resolver from being the place a reviewer has to look for \"is http allowed\".\n */\nexport function guardUrl(input: string, policy: UrlGuardPolicy): UrlGuardResult {\n let url: URL\n try {\n url = new URL(input.trim())\n } catch {\n return { ok: false, reason: 'That does not look like a valid URL.' }\n }\n\n const httpsOnly = !policy.allowHttp\n if (httpsOnly && url.protocol !== 'https:') {\n return { ok: false, reason: 'Only https:// URLs can be fetched.' }\n }\n if (!httpsOnly && url.protocol !== 'https:' && url.protocol !== 'http:') {\n return { ok: false, reason: 'Only https:// and http:// URLs can be fetched.' }\n }\n const defaultPort = url.protocol === 'https:' ? '443' : '80'\n if (url.port !== '' && url.port !== defaultPort && !allowsPrivateHosts(policy.hostPolicy)) {\n return {\n ok: false,\n reason: `Non-standard ports cannot be fetched (${url.protocol}// on ${defaultPort} only).`,\n }\n }\n if (url.username !== '' || url.password !== '') {\n return { ok: false, reason: 'URLs with embedded credentials cannot be fetched.' }\n }\n\n let hostname = url.hostname.toLowerCase()\n // A trailing dot is the DNS root and resolves identically; strip it so that\n // `169.254.169.254.` and `internal.` cannot walk past the suffix checks.\n if (hostname.endsWith('.') && hostname.length > 1) hostname = hostname.slice(0, -1)\n\n const permissive = allowsPrivateHosts(policy.hostPolicy)\n\n if (!permissive && (hostname === 'localhost' || hostname.endsWith('.localhost'))) {\n return { ok: false, reason: 'localhost cannot be fetched.' }\n }\n\n const classification = classifyIp(hostname)\n if (classification.family === 6) {\n // IPv6 literals in a submitted URL stay rejected even when they are public:\n // a store lives on a name, and the useful IPv6 case (an AAAA record) is\n // handled — and classified in full — by `resolveAndValidate`.\n if (!permissive) {\n return { ok: false, reason: 'IPv6 literal addresses cannot be fetched — use a hostname.' }\n }\n }\n if (classification.family !== null && classification.reserved && !permissive) {\n return {\n ok: false,\n reason: `Private or reserved IP addresses cannot be fetched (${classification.label}).`,\n }\n }\n if (classification.family === null && !permissive) {\n if (PRIVATE_SUFFIXES.some((suffix) => hostname.endsWith(suffix))) {\n return {\n ok: false,\n reason: 'Internal hostnames (.local, .internal, .localhost) cannot be fetched.',\n }\n }\n if (!hostname.includes('.')) {\n return {\n ok: false,\n reason: 'Single-label hostnames cannot be fetched — they resolve on the local network.',\n }\n }\n }\n\n return { ok: true, url }\n}\n\n/**\n * The strict public policy, and the name the Console preview has always used.\n * Kept as a named export because the Console preview and its shipped tests are\n * written against it.\n */\nexport function guardPreviewUrl(input: string): UrlGuardResult {\n return guardUrl(input, { allowHttp: false, hostPolicy: 'public-only' })\n}\n\n/* ── DNS resolution + validation ──────────────────────────────────────────── */\n\nexport interface PinnedAddress {\n readonly address: string\n readonly family: 4 | 6\n}\n\nexport interface HostResolver {\n resolve(hostname: string): Promise<readonly PinnedAddress[]>\n}\n\nexport type ResolveOutcome =\n | { ok: true; addresses: readonly PinnedAddress[] }\n | { ok: false; kind: 'unreachable' | 'policy-rejected'; reason: string }\n\n/** Real DNS. The only resolver a hosted path ever uses. */\nexport function createDnsResolver(): HostResolver {\n return {\n async resolve(hostname: string): Promise<readonly PinnedAddress[]> {\n const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true })\n return records.map((record) => ({\n address: record.address,\n family: record.family === 6 ? 6 : 4,\n }))\n },\n }\n}\n\n/**\n * Resolves and validates. Rejects if ANY answer is reserved — not \"if the first\n * one is\". A name that answers with one public and one private address is the\n * shape of the attack, and picking the public one and connecting anyway is how\n * a guard that looks correct fails.\n */\nexport async function resolveAndValidate(\n hostname: string,\n resolver: HostResolver,\n hostPolicy: HostPolicy,\n): Promise<ResolveOutcome> {\n // An IP literal needs no resolution; it was already classified by `guardUrl`.\n const literal = classifyIp(hostname)\n if (literal.family !== null) {\n if (literal.reserved && !allowsPrivateHosts(hostPolicy)) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `target is a reserved address (${literal.label})`,\n }\n }\n return {\n ok: true,\n addresses: [{ address: hostname.replace(/^\\[|\\]$/g, ''), family: literal.family }],\n }\n }\n\n let addresses: readonly PinnedAddress[]\n try {\n addresses = await resolver.resolve(hostname)\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n return {\n ok: false,\n kind: 'unreachable',\n reason: `DNS lookup failed for ${hostname}: ${detail}`,\n }\n }\n if (addresses.length === 0) {\n return { ok: false, kind: 'unreachable', reason: `DNS returned no addresses for ${hostname}` }\n }\n if (allowsPrivateHosts(hostPolicy)) return { ok: true, addresses }\n\n for (const record of addresses) {\n const classification = classifyIp(record.address)\n if (classification.family === null) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `DNS returned an unparseable address (${record.address})`,\n }\n }\n if (classification.reserved) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `${hostname} resolves to a private or reserved address (${record.address}: ${classification.label})`,\n }\n }\n }\n return { ok: true, addresses }\n}\n\n/* ── the transport ────────────────────────────────────────────────────────── */\n\nexport interface ProbeRequestInit {\n readonly headers: Readonly<Record<string, string>>\n /** Always `'manual'`: hops are our decision, because each one must re-resolve. */\n readonly redirect: 'manual'\n readonly signal: AbortSignal\n /**\n * The addresses `resolveAndValidate` approved for this exact URL's hostname.\n * The transport MUST connect to one of these and MUST NOT consult a resolver\n * of its own; that is the whole anti-rebinding mechanism.\n */\n readonly pinnedAddresses: readonly PinnedAddress[]\n}\n\n/**\n * A response, reduced to the three things ARS evidence needs.\n *\n * `headers` is `name → all values`, not `name → value`. `Link` is routinely sent\n * more than once and is scored twice over (D2.2 declared alternates, D6.5\n * machine endpoints); a transport that joins them is losing scored evidence.\n */\nexport interface ProbeHttpResponse {\n readonly status: number\n readonly headers: Record<string, string[]>\n readonly body: ReadableStream<Uint8Array> | null\n}\n\nexport type ProbeTransport = (url: string, init: ProbeRequestInit) => Promise<ProbeHttpResponse>\n\n/** Adapts a WHATWG `Response` — the shape tests and fixtures find easiest to build. */\nexport function fromWebResponse(response: Response): ProbeHttpResponse {\n const headers: Record<string, string[]> = {}\n response.headers.forEach((value, name) => {\n const key = name.toLowerCase()\n if (key === 'set-cookie') return\n const existing = headers[key]\n if (existing) existing.push(value)\n else headers[key] = [value]\n })\n const setCookie =\n typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []\n if (setCookie.length > 0) headers['set-cookie'] = [...setCookie]\n return { status: response.status, headers, body: response.body }\n}\n\n/** Returns the pinned addresses and refuses to look anything up. */\nfunction pinnedLookup(addresses: readonly PinnedAddress[]): LookupFunction {\n return (_hostname, options, callback) => {\n if (addresses.length === 0) {\n callback(new Error('rebilder-ars: no pinned address for this connection'), '', 4)\n return\n }\n // Node ≥20 enables `autoSelectFamily`, which calls `lookup` with `all: true`.\n if (typeof options === 'object' && options !== null && options.all === true) {\n callback(\n null,\n addresses.map((record) => ({ address: record.address, family: record.family })),\n )\n return\n }\n const first = addresses[0]\n if (first === undefined) {\n callback(new Error('rebilder-ars: no pinned address for this connection'), '', 4)\n return\n }\n callback(null, first.address, first.family)\n }\n}\n\n/**\n * The production transport: `node:https`/`node:http` with a `lookup` that can\n * only return the validated addresses.\n *\n * WHY NOT `fetch` + an undici `Agent`. Design §5.2 names undici's `Agent` with a\n * custom `lookup`, which is the same mechanism; `undici` is not reachable as a\n * built-in module and this package's contract is zero runtime dependencies, so\n * the identical property is obtained from `node:https`, whose options flow\n * through to `net.connect`. `servername` keeps SNI on the hostname and Node's\n * default `setHost` keeps the `Host` header on the hostname, so the origin sees\n * a normal request and only the socket's destination is fixed.\n *\n * No `Accept-Encoding` is sent, so nothing arrives compressed and the decoded\n * byte count is the transferred byte count. §3.3 drops `transferBytes` for\n * exactly this reason: a hashed field that is platform-dependent is worse than\n * no field.\n */\nexport function createPinnedTransport(): ProbeTransport {\n return (url, init) =>\n new Promise<ProbeHttpResponse>((resolve, reject) => {\n let target: URL\n try {\n target = new URL(url)\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)))\n return\n }\n const secure = target.protocol === 'https:'\n const client = secure ? https : http\n const headers: Record<string, string> = { ...init.headers, host: target.host }\n\n const request = client.request(\n {\n protocol: target.protocol,\n hostname: target.hostname,\n port: target.port === '' ? (secure ? 443 : 80) : Number(target.port),\n path: `${target.pathname}${target.search}`,\n method: 'GET',\n headers,\n servername: secure ? target.hostname : undefined,\n lookup: pinnedLookup(init.pinnedAddresses),\n agent: false,\n signal: init.signal,\n },\n (response) => {\n const collected: Record<string, string[]> = {}\n const raw = response.rawHeaders\n for (let i = 0; i + 1 < raw.length; i += 2) {\n const name = (raw[i] ?? '').toLowerCase()\n const value = raw[i + 1] ?? ''\n const existing = collected[name]\n if (existing) existing.push(value)\n else collected[name] = [value]\n }\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n response.on('data', (chunk: Buffer) => {\n // Copy: `chunk` may be a view onto Node's shared read pool.\n controller.enqueue(new Uint8Array(chunk))\n if ((controller.desiredSize ?? 1) <= 0) response.pause()\n })\n response.on('end', () => {\n try {\n controller.close()\n } catch {\n /* already closed by a cancel() */\n }\n })\n response.on('error', (error) => {\n try {\n controller.error(error)\n } catch {\n /* already errored */\n }\n })\n },\n pull() {\n response.resume()\n },\n cancel() {\n // The byte cap fires here: stop reading and drop the socket.\n response.destroy()\n request.destroy()\n },\n })\n\n resolve({ status: response.statusCode ?? 0, headers: collected, body })\n },\n )\n\n request.on('error', (error) => reject(error))\n request.end()\n })\n}\n","/**\n * profiles.ts — the eight page-kind fact profiles. Design §3.5, table verbatim.\n *\n * THE ONE IDEA IN THIS FILE. ARS uses fixed weights for every page kind. What\n * varies is *what counts as a fact* and *what a page of that kind reasonably\n * costs*:\n *\n * > ARS does not measure how much you say. It measures whether the facts a\n * > caller needs **for this kind of page** are present, findable, and cheap\n * > **relative to what that kind of page costs**.\n *\n * Per-vertical *weights* would be the wrong design — it makes an 88 mean\n * different things on different pages and invites site-type shopping. A\n * per-vertical *fact set* and *byte reference* are not weights: an article that\n * spends 38 KB saying something is not penalised against a 40 KB reference,\n * while a product page that spends 38 KB to state four facts is. The byte\n * reference is specifically what stops long-form content being structurally\n * capped around C, which every source design that used absolute byte bands did.\n *\n * The set is CLOSED at eight, and every kind has a complete profile — there is\n * no \"no profile\" path. Conformance fixture `058-profiles-total-and-typed`\n * asserts both halves of that: the mapping is total over `ArsPageKind`, and\n * every fact name is a member of `ArsFactKind`. `PROFILE_BY_KIND` is typed as a\n * total `Record`, so the first half is also a compile error.\n *\n * `unknown` is deliberately not an easy exit. It carries the smallest core set,\n * but it still scores D5.2 against \"any recognised schema.org type present\",\n * which requires having a type at all. Hiding your page kind costs up to 7\n * points and gains nothing on coverage.\n *\n * ── Definitions of the fact terms the source designs left undefined (§3.5) ──\n *\n * `primary-action-url` — a same-origin-or-declared URL reachable from an\n * `<a href>`, a `<form action>`, or JSON-LD `potentialAction.target`, whose\n * anchor text or `name` matches the ruleset's action lexicon (`book`, `apply`,\n * `contact`, `buy`, `subscribe`, `start`, `request`, `download`, `sign up`,\n * `get a quote` and their pinned synonyms). The lexicon is pinned in\n * `DEFAULT_RULESET.actionLexicon`, not inferred per page.\n *\n * `authority` — an organisation or person named as the publisher of the content,\n * extracted from JSON-LD `publisher`/`author`, `<meta name=\"author\">`, or a\n * `rel=\"publisher\"` link.\n *\n * `org-name` — JSON-LD `Organization.name` / `LocalBusiness.name`,\n * `og:site_name`, or `<meta itemprop=\"name\">` on an org-typed scope.\n *\n * `item-count` / `item-link` — for `collection`: the number of distinct item\n * links inside the largest repeated-structure block, and whether those links\n * resolve to same-origin URLs. Counted from the largest repeated block\n * specifically so that a nav menu is not mistaken for a product grid.\n *\n * `question-answer` — a `FAQPage`/`Question` JSON-LD pair, or a `<dt>/<dd>`, a\n * `<details><summary>`, or a heading-followed-by-paragraph pair. Counted ONCE\n * as present, not per item: a page with 40 questions is not four times better\n * than a page with 10.\n *\n * `price` is satisfied by an explicit \"no published price\" signal as well as by\n * a number. We score honesty, not disclosure — a service page that says\n * \"pricing on request\" has told the agent what it needs to know.\n */\n\nimport type { ArsFactProfile, ArsPageKind } from './types'\n\n/**\n * The §3.5 table, one entry per `ArsPageKind`. Core facts score at full weight,\n * extended facts at ¼ credit (the single definition — the source designs used\n * ¼, ½ and \"half credit\" in three different places). Byte references are the\n * D3.2 denominator, in bytes.\n */\nexport const PROFILE_BY_KIND = {\n product: {\n pageKind: 'product',\n core: ['title', 'price', 'currency', 'availability'],\n extended: ['brand', 'sku', 'shipping', 'returns', 'description'],\n byteReference: 8 * 1024,\n },\n collection: {\n pageKind: 'collection',\n core: ['title', 'item-count', 'item-link'],\n extended: ['price', 'availability', 'description'],\n byteReference: 16 * 1024,\n },\n article: {\n pageKind: 'article',\n core: ['title', 'author', 'published'],\n extended: ['updated', 'section', 'description'],\n byteReference: 40 * 1024,\n },\n place: {\n pageKind: 'place',\n core: ['org-name', 'address', 'hours', 'phone'],\n extended: ['email', 'service-area', 'primary-action-url', 'description'],\n byteReference: 8 * 1024,\n },\n service: {\n pageKind: 'service',\n core: ['title', 'price', 'primary-action-url'],\n extended: ['duration', 'eligibility', 'service-area', 'description', 'updated'],\n byteReference: 8 * 1024,\n },\n faq: {\n pageKind: 'faq',\n core: ['title', 'question-answer'],\n extended: ['updated', 'description'],\n byteReference: 16 * 1024,\n },\n document: {\n pageKind: 'document',\n core: ['title', 'updated', 'authority'],\n extended: ['description', 'primary-action-url', 'section'],\n byteReference: 24 * 1024,\n },\n unknown: {\n pageKind: 'unknown',\n core: ['title', 'description', 'primary-action-url'],\n extended: ['updated', 'org-name'],\n byteReference: 16 * 1024,\n },\n} as const satisfies Record<ArsPageKind, ArsFactProfile>\n\n/**\n * The same eight profiles as the array `ArsRuleset.profiles` expects, in\n * declaration order (which is the order they appear in the §3.5 table, and is\n * therefore the order the spec renders them in).\n *\n * Runtime immutability: `as const` above makes every profile deeply readonly to\n * TypeScript, and `DEFAULT_RULESET` deep-freezes these exact objects at module\n * load, so a consumer cannot mutate a shared profile and silently change every\n * subsequent score.\n */\nexport const PROFILES: readonly ArsFactProfile[] = Object.freeze(Object.values(PROFILE_BY_KIND))\n\n/** Total by construction — `PROFILE_BY_KIND` is typed as a total Record. */\nexport function profileFor(pageKind: ArsPageKind): ArsFactProfile {\n return PROFILE_BY_KIND[pageKind]\n}\n","/**\n * ruleset.ts — `DEFAULT_RULESET`, the frozen ARS 0.3 ruleset.\n *\n * WHAT THIS FILE IS. Every number a second implementation needs in order to\n * reproduce a score, and nothing that varies between runs. `rulesetHash()` is\n * the SHA-256 of the RFC 8785 canonical JSON of this object, it is printed on\n * every result, and the determinism guarantee is stated in terms of it: a\n * number without `rulesetHash`, `corpusHash` and `evidenceHash` is not an ARS\n * score. That makes this file a published artifact, not configuration.\n *\n * CONSEQUENCE: editing a number here is a spec version change, not a code\n * change. Per §3.1, any edit that moves a conformance `expected.json` is at\n * minimum a MINOR — and MINOR means scores stop being comparable and every\n * published surface re-scores in a batch. The CI gate on PATCH releases exists\n * precisely so that \"just tweaking a threshold\" cannot happen quietly.\n *\n * WHY THE BODY CAP, REDIRECT LIMIT AND TIMEOUT LIVE HERE rather than in the\n * probe: two implementations with different caps produce different scores. A\n * 3 MiB cap turns a `truncated-evidence` non-grade into an F, and a 10s timeout\n * scores pages a 5s timeout reports as unreachable. They are inputs to the\n * score, so they are inputs to the hash.\n *\n * SHAPE. Everything is `as const satisfies <contract>`: the `satisfies` clause\n * proves the object matches the published type (and, for the tables keyed by\n * `ArsCheckId` / `ArsPageKind`, that it is TOTAL), while `as const` keeps the\n * literal types so callers get `number`, not `number | undefined`, from a known\n * key. `deepFreeze` then makes it immutable at runtime as well — a mutated\n * shared ruleset would corrupt every subsequent score in the process, silently.\n */\n\nimport { PROFILES } from './profiles'\nimport type {\n ArsBand,\n ArsBasis,\n ArsCheckId,\n ArsDimensionId,\n ArsPageKind,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// Deep freeze\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively freezes a plain data structure. Used once, on `DEFAULT_RULESET`.\n * `as const` is a compile-time guarantee only; this is the runtime half.\n */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Check weights — the §3.4 table, row for row\n// ---------------------------------------------------------------------------\n\n/**\n * Check id → points. Sums to exactly 100 across 22 checks.\n *\n * NO CONDITIONAL WEIGHTS. NO REDISTRIBUTION. NO HEURISTIC GATES OVER MEASURED\n * POINTS. Redistribution is a gaming vector (make the dimension you are bad at\n * inapplicable and the rest inflate), and a heuristic that can zero measured\n * points makes those points heuristic. So D2.4 and D5.3 are scored checks, not\n * gates: a parity failure loses its own 3 points and raises a `warn`, and does\n * not touch D2's other measured points. That is what makes \"measured 63 /\n * heuristic 37\" an honest figure rather than a presentational one, and fixture\n * `053` re-derives the heuristic-*controlled* weight to prove it.\n *\n * `satisfies Record<ArsCheckId, number>` makes the table total: a check id\n * added to the union without a weight here is a compile error.\n */\nconst WEIGHTS = {\n // D1 Retrievability — 28\n 'retrievability.reachable': 11,\n 'retrievability.robots-policy': 10,\n 'retrievability.render-independence': 7,\n // D2 Machine representation — 18\n 'machine-representation.negotiated-response': 9,\n 'machine-representation.declared-alternates': 3,\n 'machine-representation.vary-accept': 3,\n 'machine-representation.substance-parity': 3,\n // D3 Fact coverage — 20\n 'fact-coverage.core-facts': 14,\n 'fact-coverage.context-cost': 6,\n // D4 Fact position — 10\n 'fact-position.first-core-fact-offset': 5,\n 'fact-position.front-window': 5,\n // D5 Structured data — 6\n 'structured-data.present': 2,\n 'structured-data.required-properties': 3,\n 'structured-data.text-agreement': 1,\n // D6 Contract & discovery — 10\n 'contract-discovery.canonical': 4,\n 'contract-discovery.cache-validators': 2,\n 'contract-discovery.llms-txt': 1,\n 'contract-discovery.sitemap': 1,\n 'contract-discovery.machine-endpoint': 2,\n // D7 Evidence density — 8\n 'evidence-density.quantities': 4,\n 'evidence-density.definitions': 2,\n 'evidence-density.comparisons': 2,\n} as const satisfies Record<ArsCheckId, number>\n\n/** Descriptive metadata per check: which dimension it belongs to, its published label, its basis. */\nexport interface ArsCheckMeta {\n dimension: ArsDimensionId\n label: string\n basis: ArsBasis\n}\n\n/**\n * The published catalogue of checks. `dimension` is redundant with the check id\n * prefix by construction — the id shape `<dimension>.<check>` is normative — and\n * is spelled out anyway so consumers never parse an id string to group results.\n *\n * `basis` is spec data (it appears in every `expected.json` and is printed next\n * to every check in the UI) but it is not part of `ArsRuleset` in §3.9, so it is\n * exported here rather than folded into the hashed object. A second\n * implementation reads it from the published §3.4 table.\n */\nexport const CHECK_META = {\n 'retrievability.reachable': {\n dimension: 'retrievability',\n label: 'Reachable on the agent path',\n basis: 'measured',\n },\n 'retrievability.robots-policy': {\n dimension: 'retrievability',\n label: 'Robots policy for assistants',\n basis: 'measured',\n },\n 'retrievability.render-independence': {\n dimension: 'retrievability',\n label: 'Core facts present without JavaScript',\n basis: 'heuristic',\n },\n 'machine-representation.negotiated-response': {\n dimension: 'machine-representation',\n label: 'Machine representation on Accept negotiation',\n basis: 'measured',\n },\n 'machine-representation.declared-alternates': {\n dimension: 'machine-representation',\n label: 'Declared alternate representations',\n basis: 'measured',\n },\n 'machine-representation.vary-accept': {\n dimension: 'machine-representation',\n label: 'Vary: Accept declared correctly',\n basis: 'measured',\n },\n 'machine-representation.substance-parity': {\n dimension: 'machine-representation',\n label: 'Same substance across representations',\n basis: 'heuristic',\n },\n 'fact-coverage.core-facts': {\n dimension: 'fact-coverage',\n label: 'Core facts for this page kind',\n basis: 'heuristic',\n },\n 'fact-coverage.context-cost': {\n dimension: 'fact-coverage',\n label: 'Context cost relative to this page kind',\n basis: 'measured',\n },\n 'fact-position.first-core-fact-offset': {\n dimension: 'fact-position',\n label: 'Byte offset of the first core fact',\n basis: 'heuristic',\n },\n 'fact-position.front-window': {\n dimension: 'fact-position',\n label: 'Core facts inside the front window',\n basis: 'heuristic',\n },\n 'structured-data.present': {\n dimension: 'structured-data',\n label: 'Structured data present and parsing',\n basis: 'measured',\n },\n 'structured-data.required-properties': {\n dimension: 'structured-data',\n label: 'Recognised type with its required properties',\n basis: 'measured',\n },\n 'structured-data.text-agreement': {\n dimension: 'structured-data',\n label: 'Structured data agrees with visible text',\n basis: 'heuristic',\n },\n 'contract-discovery.canonical': {\n dimension: 'contract-discovery',\n label: 'Canonical URL present and self-consistent',\n basis: 'measured',\n },\n 'contract-discovery.cache-validators': {\n dimension: 'contract-discovery',\n label: 'Cache validators',\n basis: 'measured',\n },\n 'contract-discovery.llms-txt': {\n dimension: 'contract-discovery',\n label: 'llms.txt present and spec-shaped',\n basis: 'measured',\n },\n 'contract-discovery.sitemap': {\n dimension: 'contract-discovery',\n label: 'Sitemap declared in robots.txt',\n basis: 'measured',\n },\n 'contract-discovery.machine-endpoint': {\n dimension: 'contract-discovery',\n label: 'Declared machine endpoint',\n basis: 'measured',\n },\n 'evidence-density.quantities': {\n dimension: 'evidence-density',\n label: 'Quantities an answer can quote',\n basis: 'measured',\n },\n 'evidence-density.definitions': {\n dimension: 'evidence-density',\n label: 'Labelled term and value pairs',\n basis: 'heuristic',\n },\n 'evidence-density.comparisons': {\n dimension: 'evidence-density',\n label: 'Comparable rows',\n basis: 'measured',\n },\n} as const satisfies Record<ArsCheckId, ArsCheckMeta>\n\n/**\n * The six dimensions and their frozen weights (§3.4): 20 · 20 · 20 · 10 · 15 ·\n * 15 = 100, identical for every page kind. Each weight is the sum of its\n * checks' weights in `WEIGHTS`; both are written out because both are published,\n * and conformance fixture `052` asserts they agree and that the total is 100.\n */\nexport const DIMENSION_META = {\n retrievability: { label: 'Retrievability', weight: 28 },\n 'machine-representation': { label: 'Machine representation', weight: 18 },\n 'fact-coverage': { label: 'Fact coverage', weight: 20 },\n 'fact-position': { label: 'Fact position', weight: 10 },\n 'structured-data': { label: 'Structured data', weight: 6 },\n 'contract-discovery': { label: 'Contract & discovery', weight: 10 },\n 'evidence-density': { label: 'Evidence density', weight: 8 },\n} as const satisfies Record<ArsDimensionId, { label: string; weight: number }>\n\n/**\n * Published totals (§3.4). Heuristic weight has a spec ceiling of 40; fixture\n * `053` enforces it, and the ceiling is what shaped D7's basis split rather\n * than the other way round. Labelling `definitions` measured would have bought\n * three points of headroom and made \"measured 63\" a presentational number\n * instead of an honest one, which is the exact failure the ceiling exists to\n * prevent.\n */\nexport const ARS_MEASURED_WEIGHT = 63\nexport const ARS_HEURISTIC_WEIGHT = 37\nexport const ARS_HEURISTIC_WEIGHT_CEILING = 40\n\n// ---------------------------------------------------------------------------\n// Thresholds — the §3.6 scoring tables, as integer pairs\n// ---------------------------------------------------------------------------\n\n/**\n * All numeric bands from §3.6, encoded as flat `[threshold, value]` pairs so a\n * second implementation reads one shape rather than five. Integer arithmetic\n * only: no floating point anywhere in the scoring path, because cross-language\n * conformance is impossible with float rounding drift. All values are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator` in integer division.\n *\n * Two encodings, each stated per key:\n * AT-LEAST — descending pairs; the first pair whose `threshold <= input` wins.\n * AT-MOST — ascending pairs; the first pair whose `input <= threshold` wins;\n * no match scores 0.\n */\nconst THRESHOLDS = {\n /**\n * D3.1 fact weighting, in quarter-units (§3.6), as\n * `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:\n * coreUnits = 4 × corroborated core + 2 × uncorroborated core\n * extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended\n * \"Extended = ¼ credit\" is the single definition of extended credit.\n */\n 'fact-coverage.fact-units': [4, 2, 1, 0],\n /**\n * D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit\n * is every core fact corroborated. `coveragePct` is then\n * `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.\n */\n 'fact-coverage.core-denominator-multiplier': [4],\n /**\n * D3.1 density band. AT-LEAST over\n * `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.\n * The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n * which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so\n * that keyword stuffing is pointless — fixtures `031` and `032` must score\n * identically.\n * Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.\n */\n 'fact-coverage.density': [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],\n /**\n * D3.2 context cost, 6 pts. AT-MOST over\n * `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.\n */\n 'fact-coverage.context-cost': [100, 6, 200, 5, 500, 3, 1500, 1],\n /**\n * D7.1 quantities, 4 pts. AT-LEAST over the count of DISTINCT quantity tokens\n * in the agent's counted text: a currency amount, a percentage, a number\n * carrying a unit, or an ISO date. Distinct, because a price repeated in a\n * header, a buy box and a footer is one fact stated three times, and counting\n * it three times would reward the repetition this score exists to discourage.\n * Saturates at 12 so a specification table cannot outscore a page that simply\n * states its facts.\n */\n 'evidence-density.quantities': [12, 4, 6, 3, 3, 2, 1, 1],\n /**\n * D7.2 definitions, 2 pts. AT-LEAST over the count of `term: value` pairs the\n * agent can read as a labelled fact, counting markdown bold-label lines,\n * list items with a leading label, and HTML definition lists.\n */\n 'evidence-density.definitions': [6, 2, 2, 1],\n /**\n * D7.3 comparisons, 2 pts. AT-LEAST over the number of comparable ROWS: a\n * table with at least two data columns contributes its data-row count, minus\n * the header. One row is not a comparison, so the band starts at two; three\n * options laid side by side is a full comparison and pays out. Calibrated\n * against fixture `060`, where a three-row size table is exactly the shape\n * this check exists to reward, and `063`, where one row is not.\n */\n 'evidence-density.comparisons': [3, 2, 2, 1],\n /** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */\n 'fact-position.first-core-fact-offset': [512, 5, 2048, 4, 8192, 2, 32768, 1],\n /**\n * D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose\n * offset falls inside the window; below the last threshold, 0.\n */\n 'fact-position.front-window': [90, 5, 70, 4, 50, 3, 25, 1],\n /**\n * D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE\n * expression, integer division — the `0.2 × bytes` form is deleted, because\n * two implementations rounding a float disagree at the boundary.\n */\n 'fact-position.front-window-size': [2048, 5],\n /**\n * Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8\n * bytes are the normative measurement and approximate tokens are always\n * rendered with `≈` and an \"est.\" chip. chars/4 is not a token count and the\n * spec says so.\n */\n 'cost.approx-bytes-per-token': [4],\n} as const satisfies Readonly<Record<string, readonly number[]>>\n\n// ---------------------------------------------------------------------------\n// Crawler audiences (§3.7)\n// ---------------------------------------------------------------------------\n\n/**\n * Robots `User-agent:` product tokens per audience, in their published casing.\n * Matching is case-insensitive (RFC 9309 §2.2.1) — the casing here is for the\n * rendered spec table.\n *\n * The `training` list exists so it can be treated NEUTRALLY. Blocking training\n * crawlers while allowing assistants scores identically to a fully open site,\n * and fixtures `021`/`022` exist solely to prove it, because it is the first\n * thing a hostile reviewer tests. `search` is reported only, and feeds the\n * `robots-contradiction` input; it never scores.\n *\n * This list is versioned data, not a heuristic: adding a token changes scores\n * for sites that named it, so additions land as a MINOR.\n */\nconst AUDIENCE_TOKENS = {\n /** User-triggered assistant fetches. THE audience ARS scores. */\n assistant: [\n 'ChatGPT-User',\n 'Claude-User',\n 'Claude-SearchBot',\n 'DuckAssistBot',\n 'Meta-ExternalFetcher',\n 'MistralAI-User',\n 'OAI-SearchBot',\n 'Perplexity-User',\n ],\n /** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */\n training: [\n 'AI2Bot',\n 'Applebot-Extended',\n 'Bytespider',\n 'CCBot',\n 'ClaudeBot',\n 'Diffbot',\n 'FacebookBot',\n 'Google-Extended',\n 'GPTBot',\n 'Meta-ExternalAgent',\n 'PanguBot',\n 'Timpibot',\n 'anthropic-ai',\n 'cohere-ai',\n 'omgili',\n ],\n /** Classic search indexers. Reported only. */\n search: ['Applebot', 'Baiduspider', 'Bingbot', 'DuckDuckBot', 'Googlebot', 'Slurp', 'YandexBot'],\n} as const satisfies Record<'assistant' | 'training' | 'search', readonly string[]>\n\n// ---------------------------------------------------------------------------\n// D5.2 required properties (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The hand-curated required-property table, per page kind.\n *\n * PROVENANCE, stated because D5.2 is 7 points and merchants will ask where the\n * list came from: it is NOT \"schema.org validity\" — schema.org defines no\n * required properties at all — and it is NOT Google's rich-results guidelines by\n * reference, which change without a version and would make ARS scores move\n * without an ARS release. It is the CORE FACT SET of each page kind (see\n * `./profiles`) expressed in schema.org vocabulary, plus the properties without\n * which those facts are not actionable — a price with no `priceCurrency` cannot\n * be used by a buying agent, so `product` and `service` require both. The table\n * is bounded because it covers 8 kinds, not the full vocabulary, and it is\n * published in the spec next to this rationale.\n *\n * NOTATION: a dot is a property path from the top-level node; traversal enters\n * array members (`offers.price` matches `offers[0].price`). Alias handling\n * (`openingHours` vs `openingHoursSpecification`, `Article.headline` vs `name`)\n * belongs to the extractor, not to this table.\n *\n * `unknown` requires only `name`, deliberately: §3.5 scores `unknown` against\n * \"any recognised schema.org type present\", which requires having a type but\n * cannot require properties of a kind we did not identify.\n */\nconst REQUIRED_PROPERTIES = {\n product: ['name', 'offers.price', 'offers.priceCurrency', 'offers.availability'],\n collection: ['name', 'numberOfItems', 'itemListElement'],\n article: ['headline', 'author', 'datePublished'],\n place: ['name', 'address', 'openingHours', 'telephone'],\n service: ['name', 'offers.price', 'offers.priceCurrency', 'potentialAction.target'],\n faq: ['name', 'mainEntity', 'mainEntity.acceptedAnswer'],\n document: ['name', 'dateModified', 'publisher'],\n unknown: ['name'],\n} as const satisfies Record<ArsPageKind, readonly string[]>\n\n// ---------------------------------------------------------------------------\n// Action lexicon (§3.5)\n// ---------------------------------------------------------------------------\n\n/**\n * Phrases that qualify a link, form or `potentialAction` as the page's\n * `primary-action-url`. Matched case-insensitively against normalised anchor\n * text / `name`, whitespace collapsed.\n *\n * ARS 0.3 ADDED THE COMMON ONES 0.2 MISSED. A shop whose button read \"Shop\n * now\", software whose button read \"Install\" or \"Try it free\", and a local\n * business whose button read \"Get directions\" were all told their main action\n * link was missing. The additions are the labels those pages actually use, each\n * still a whole phrase or a word-bounded prefix (`matchesLexicon`), so \"shop\"\n * matches \"Shop now\" and never \"Workshop\".\n *\n * PINNED, not inferred. §3.5 names ten stems — `book`, `apply`, `contact`,\n * `buy`, `subscribe`, `start`, `request`, `download`, `sign up`, `get a quote` —\n * \"and their pinned synonyms\"; this is that list. A lexicon that grew per page\n * (or per LLM call) would make `primary-action-url` non-deterministic, and\n * `primary-action-url` is a core fact for `service` and `unknown`, so it would\n * take the whole score with it. Sorted for readability; order is not\n * significant.\n */\nconst ACTION_LEXICON = [\n 'add to bag',\n 'add to basket',\n 'add to cart',\n 'apply',\n 'apply now',\n 'book',\n 'book now',\n 'buy',\n 'buy now',\n 'call',\n 'call now',\n 'check availability',\n 'check out',\n 'checkout',\n 'contact',\n 'contact us',\n 'create account',\n 'create an account',\n 'donate',\n 'download',\n 'email us',\n 'enquire',\n 'enrol',\n 'enroll',\n 'free trial',\n 'get a demo',\n 'get a quote',\n 'get directions',\n 'get in touch',\n 'get quote',\n 'get started',\n 'get the app',\n 'get tickets',\n 'hire',\n 'inquire',\n 'install',\n 'join',\n 'make an appointment',\n 'message us',\n 'order',\n 'order now',\n 'order online',\n 'pre-order',\n 'preorder',\n 'purchase',\n 'register',\n 'rent',\n 'request',\n 'request a demo',\n 'request a quote',\n 'reserve',\n 'schedule',\n 'shop',\n 'shop now',\n 'sign up',\n 'signup',\n 'start',\n 'start free trial',\n 'subscribe',\n 'talk to sales',\n 'talk to us',\n 'text us',\n 'try',\n 'upgrade',\n] as const satisfies readonly string[]\n\n// ---------------------------------------------------------------------------\n// Bands (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.3 integer grade bands (unchanged from 0.2). Meanings describe retrieved response structure;\n * they do not predict third-party output or certify business facts. Interfaces\n * can link the measurement methodology rather than repeat fixed boilerplate.\n */\nconst BANDS = [\n {\n grade: 'A',\n min: 90,\n max: 100,\n label: 'Agent-native',\n meaning:\n 'Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch.',\n },\n {\n grade: 'B',\n min: 75,\n max: 89,\n label: 'Agent-friendly',\n meaning:\n 'All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing.',\n },\n {\n grade: 'C',\n min: 60,\n max: 74,\n label: 'Readable with effort',\n meaning: 'Core facts are extractable from HTML, at high cost.',\n },\n {\n grade: 'D',\n min: 40,\n max: 59,\n label: 'Partial',\n meaning: 'Some core facts for this page kind were not found in the fetched response.',\n },\n {\n grade: 'F',\n min: 0,\n max: 39,\n label: 'Not extractable',\n meaning: 'Few or no core facts for this page kind were found in the fetched response.',\n },\n] as const satisfies readonly ArsBand[]\n\n// ---------------------------------------------------------------------------\n// The ruleset\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.3's frozen ruleset. Weights and bands are 0.2's; the action lexicon grew.\n *\n * DESIGNED CEILINGS, printed in the spec (§8) as intentional rather than\n * discovered, and stated here in 0.2's numbers: no content negotiation loses\n * D2.1 (9) + D2.3 (3, gated on D2.1) + D2.4 (3, nothing comparable) → max 85,\n * capped at B. No valid structured data loses all of D5 (6) → max 94, so an A is\n * still reachable. Reaching an A therefore requires a machine representation and\n * NO LONGER requires structured data — 0.1 required both, and 0.2 does not.\n * Provable from these numbers alone, which is why the whole ruleset is published\n * rather than described.\n */\nexport const DEFAULT_RULESET = deepFreeze({\n version: '0.3.0',\n weights: WEIGHTS,\n thresholds: THRESHOLDS,\n audienceTokens: AUDIENCE_TOKENS,\n requiredProperties: REQUIRED_PROPERTIES,\n actionLexicon: ACTION_LEXICON,\n /** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */\n maxBodyBytes: 2 * 1024 * 1024,\n /** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */\n maxRedirects: 3,\n /** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */\n timeoutMs: 5_000,\n profiles: PROFILES,\n bands: BANDS,\n} as const satisfies ArsRuleset)\n","/**\n * html.ts — a tolerant, NON-EXECUTING HTML tokenizer, hand-rolled.\n *\n * WHY NOT parse5, cheerio, jsdom, or htmlparser2 (design §3.2, stated as a\n * normative reason rather than a preference): **a third-party parser version is\n * an unversioned input to a deterministic score.** ARS publishes the guarantee\n * that for a given `evidenceHash`, `rulesetHash` and `corpusHash`, `score()`\n * returns a byte-identical result in any conformant implementation, in any\n * language. A dependency that changes how a malformed `<div` is recovered\n * changes scores on a `pnpm update`, with no ARS version bump, no conformance\n * diff, and nothing in the release notes. It would also put a transitive\n * dependency tree into a package whose whole claim is that it has none.\n *\n * The second reason is the same one that rules out a cascade engine: this\n * tokenizer's recovery rules ARE the spec. They are written here, in ~600 lines,\n * where a second implementation in Go can read them.\n *\n * NON-EXECUTING is literal and load-bearing. `<script>` and `<style>` contents\n * are captured as opaque raw text and never evaluated, never fed to a JS engine,\n * never resolved. The probe fetches attacker-controlled bytes from arbitrary\n * origins; the only safe posture is that those bytes are data all the way down.\n *\n * WHAT IT EXTRACTS\n * - every start/end tag, with attributes (lowercased names, entity-decoded values)\n * - every text node, with its **UTF-8 byte offset** into the source\n * - `<script type=\"application/ld+json\">` contents, verbatim\n * - `<meta>` tags (name / property / http-equiv / itemprop / charset / content)\n * - `<link>` tags, including the multi-value `rel` token list\n *\n * BYTE OFFSETS ARE LOAD-BEARING. D4 scores the byte offset of the first core\n * fact (`≤512B → 5 · ≤2KiB → 4 · ≤8KiB → 2 · ≤32KiB → 1`) and the fraction of\n * core facts inside a `max(2048, bytes / 5)` front window. `ArsHttpCapture.bytes`\n * is defined as the *decoded UTF-8 byte length*, so offsets here are UTF-8 byte\n * offsets, NOT JavaScript string indices. On a page with any multibyte character\n * before the price — a `€`, a `—`, a CJK product name — those two numbers differ,\n * and a Go implementation counting real bytes would disagree with us. See\n * `Utf8Cursor`.\n *\n * TEXT EXTRACTION (normative, §3.6). Counted text is every text node except:\n * `<script>`, `<style>`, `<template>`, elements carrying the `hidden`\n * attribute, and elements carrying inline `style=\"display:none\"`.\n * **No CSS resolution** — a cascade engine would not be deterministic across\n * implementations, so a class that hides an element in a stylesheet does not\n * hide it here, and the spec says so rather than pretending otherwise.\n *\n * ONE READING DECISION, FLAGGED. §3.6 writes the rule as \"except `<script>`\n * (excluding `application/ld+json`)\", which can be read either way. We implement:\n * **JSON-LD script contents are NOT counted text**; they are surfaced separately\n * as `HtmlDocument.jsonLd`. The other reading breaks two mechanisms that the rest\n * of the spec depends on — D5.3 checks that structured data agrees with *visible*\n * text, and \"corroborated\" means observed in ≥2 sources (e.g. JSON-LD *and*\n * visible text). If JSON-LD were visible text, both would be satisfied by a\n * single JSON-LD block, trivially and always. Every text node reports\n * `excludedBy`, so the distinction is visible to callers rather than baked in.\n *\n * TOLERANCE CONTRACT: `tokenizeHtml` never throws, for any input string —\n * unterminated tags, unterminated comments, stray `<`, lone surrogates, 100k\n * nested `<div>`s, binary noise. Conformance fixture `057-tokenizer-fuzz` and\n * `tests/html.test.ts` both assert it. A scanner that can be crashed by the page\n * it is scanning is a denial-of-service endpoint.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why a text node is not counted text. `null` means it is counted. */\nexport type HtmlExclusionReason =\n | 'script'\n | 'script-ld-json'\n | 'style'\n | 'template'\n | 'hidden-attribute'\n | 'inline-display-none'\n\nexport interface HtmlElement {\n /** Index into `HtmlDocument.elements`; ascending in source order. */\n index: number\n /** Lowercased tag name. */\n tag: string\n /** Lowercased attribute names → entity-decoded values. First occurrence wins (HTML5). */\n attrs: Readonly<Record<string, string>>\n /** UTF-8 byte offset of the `<` that opens this tag. */\n offset: number\n /** Index of the enclosing open element, or -1 at document level. */\n parent: number\n /** Nesting depth; 0 at document level. */\n depth: number\n /**\n * Effective exclusion for text inside this element — its own reason, or the\n * nearest ancestor's. `null` when text inside it counts.\n */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlText {\n /** Entity-decoded text (raw, undecoded inside `<script>`/`<style>`). */\n text: string\n /** UTF-8 byte offset of the first character of the RAW source text. */\n offset: number\n /** UTF-8 byte length of the RAW source text. */\n bytes: number\n /** Index of the innermost enclosing element, or -1 at document level. */\n parent: number\n /** `null` when this node is counted text; otherwise why it is not. */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlJsonLd {\n /** Script contents, verbatim. Not entity-decoded: `<script>` is a raw-text element. */\n text: string\n /** UTF-8 byte offset of the first character of the contents. */\n offset: number\n /** Index of the `<script>` element in `HtmlDocument.elements`. */\n element: number\n}\n\nexport interface HtmlMeta {\n /** Lowercased `name`, or null. */\n name: string | null\n /** Lowercased `property` (Open Graph), or null. */\n property: string | null\n /** Lowercased `http-equiv`, or null. */\n httpEquiv: string | null\n /** Lowercased `itemprop`, or null. */\n itemprop: string | null\n /** Lowercased `charset`, or null. */\n charset: string | null\n /** `content`, decoded, case preserved. */\n content: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlLink {\n /**\n * `rel` as a token list, lowercased, source order, duplicates removed.\n * `rel=\"alternate canonical\"` is one link declaring two relations, and D2.2\n * (declared alternates) and D6.1 (canonical) both read it — collapsing it to a\n * string would lose one of them.\n */\n rel: readonly string[]\n href: string | null\n /** Lowercased `type`, or null. */\n type: string | null\n /** Lowercased `hreflang`, or null. */\n hreflang: string | null\n title: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlDocument {\n readonly elements: readonly HtmlElement[]\n readonly texts: readonly HtmlText[]\n readonly jsonLd: readonly HtmlJsonLd[]\n readonly metas: readonly HtmlMeta[]\n readonly links: readonly HtmlLink[]\n /** Total UTF-8 byte length of the source. */\n readonly bytes: number\n}\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * Maps JavaScript string indices to UTF-8 byte offsets in one forward pass.\n *\n * The tokenizer advances monotonically, so `at()` is amortised O(1); a\n * non-monotonic call restarts from zero rather than returning a wrong number,\n * because a silently wrong offset is a silently wrong D4 score.\n *\n * Surrogate handling matches `TextEncoder`: a well-formed pair costs 4 bytes,\n * and a LONE surrogate costs 3 — WHATWG encoding replaces it with U+FFFD, so\n * that is what its byte cost actually is on the wire.\n */\nclass Utf8Cursor {\n private charIndex = 0\n private byteIndex = 0\n\n constructor(private readonly source: string) {}\n\n at(target: number): number {\n if (target < this.charIndex) {\n this.charIndex = 0\n this.byteIndex = 0\n }\n const limit = Math.min(target, this.source.length)\n while (this.charIndex < limit) {\n const code = this.source.charCodeAt(this.charIndex)\n if (code < 0x80) {\n this.byteIndex += 1\n this.charIndex += 1\n } else if (code < 0x800) {\n this.byteIndex += 2\n this.charIndex += 1\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const next =\n this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff && this.charIndex + 1 < limit) {\n this.byteIndex += 4\n this.charIndex += 2\n } else {\n // Lone high surrogate, or a pair straddling `limit`: 3 bytes for U+FFFD.\n this.byteIndex += 3\n this.charIndex += 1\n }\n } else {\n this.byteIndex += 3\n this.charIndex += 1\n }\n }\n return this.byteIndex\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned named character references.\n *\n * The full HTML5 named-reference table is ~2 200 entries. This is the subset\n * that appears in the parts of a page ARS reads — money symbols, typography,\n * and the five XML entities — and it is PINNED per spec version for the same\n * reason the tokenizer is hand-rolled: growing the table changes extracted text,\n * which changes facts, which changes scores. Additions land as a MINOR.\n *\n * A named reference outside this table is left verbatim, which is also the only\n * safe failure: `&hearts;` surviving as literal text costs nothing, whereas\n * guessing would be non-deterministic.\n */\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00a0',\n ensp: '\\u2002',\n emsp: '\\u2003',\n thinsp: '\\u2009',\n shy: '\\u00ad',\n zwnj: '\\u200c',\n zwj: '\\u200d',\n // Currency\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n // Typography\n ndash: '–',\n mdash: '—',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n sbquo: '‚',\n ldquo: '“',\n rdquo: '”',\n bdquo: '„',\n laquo: '«',\n raquo: '»',\n lsaquo: '‹',\n rsaquo: '›',\n bull: '•',\n middot: '·',\n dagger: '†',\n Dagger: '‡',\n prime: '′',\n Prime: '″',\n // Marks and math\n copy: '©',\n reg: '®',\n trade: '™',\n sect: '§',\n para: '¶',\n deg: '°',\n plusmn: '±',\n times: '×',\n divide: '÷',\n minus: '−',\n permil: '‰',\n frac12: '½',\n frac14: '¼',\n frac34: '¾',\n sup2: '²',\n sup3: '³',\n le: '≤',\n ge: '≥',\n ne: '≠',\n // Directionality (invisible, but they do occupy bytes)\n lrm: '\\u200e',\n rlm: '\\u200f',\n}\n\n/**\n * The HTML spec's windows-1252 override for numeric references in 0x80–0x9F.\n * `&#146;` is a right single quote on real pages, not a C1 control, and\n * decoding it as one would corrupt product titles.\n */\nconst C1_REPLACEMENTS: Readonly<Record<number, number>> = {\n 0x80: 0x20ac,\n 0x82: 0x201a,\n 0x83: 0x0192,\n 0x84: 0x201e,\n 0x85: 0x2026,\n 0x86: 0x2020,\n 0x87: 0x2021,\n 0x88: 0x02c6,\n 0x89: 0x2030,\n 0x8a: 0x0160,\n 0x8b: 0x2039,\n 0x8c: 0x0152,\n 0x8e: 0x017d,\n 0x91: 0x2018,\n 0x92: 0x2019,\n 0x93: 0x201c,\n 0x94: 0x201d,\n 0x95: 0x2022,\n 0x96: 0x2013,\n 0x97: 0x2014,\n 0x98: 0x02dc,\n 0x99: 0x2122,\n 0x9a: 0x0161,\n 0x9b: 0x203a,\n 0x9c: 0x0153,\n 0x9e: 0x017e,\n 0x9f: 0x0178,\n}\n\n/**\n * A trailing `;` is REQUIRED. HTML's legacy semicolon-less forms\n * (`&copy` inside `?a=1&copy=2`) are exactly the cases where decoding mangles a\n * URL, and every reference that matters on a page ARS reads is written properly.\n * Bounded name length keeps the match linear.\n */\nconst ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g\n\nfunction codePointToString(raw: number): string {\n const mapped = C1_REPLACEMENTS[raw]\n const code = mapped ?? raw\n // Null, surrogates and out-of-range all become U+FFFD, per the HTML spec.\n if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\\ufffd'\n return String.fromCodePoint(code)\n}\n\n/** Decodes the pinned named references plus numeric references. Never throws. */\nexport function decodeEntities(text: string): string {\n if (!text.includes('&')) return text\n return text.replace(ENTITY_RE, (match, body: string) => {\n if (body.startsWith('#')) {\n const isHex = body[1] === 'x' || body[1] === 'X'\n const digits = isHex ? body.slice(2) : body.slice(1)\n const value = Number.parseInt(digits, isHex ? 16 : 10)\n return Number.isNaN(value) ? match : codePointToString(value)\n }\n return NAMED_ENTITIES[body] ?? match\n })\n}\n\n// ---------------------------------------------------------------------------\n// Element tables\n// ---------------------------------------------------------------------------\n\n/** Void elements: no contents, never pushed onto the open-element stack. */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n])\n\n/** Raw-text elements: contents are opaque, entities are NOT decoded. */\nconst RAW_TEXT_ELEMENTS = new Set(['script', 'style'])\n\n/** RCDATA elements: contents are text, entities ARE decoded, tags are not. */\nconst RCDATA_ELEMENTS = new Set(['textarea', 'title'])\n\n/**\n * Optional-end-tag recovery, in the small form that matters here. A start tag\n * listed as a key implicitly closes any open element in its value set. Without\n * this, `<li>a<li>b` nests forever and `<dt>q<dd>a` puts the answer inside the\n * question — and `<dt>/<dd>` pairs are one of the recognised `question-answer`\n * shapes for the `faq` page kind, so getting it wrong costs real points.\n */\nconst IMPLIED_END_TAGS: Readonly<Record<string, readonly string[]>> = {\n li: ['li'],\n dt: ['dt', 'dd'],\n dd: ['dt', 'dd'],\n option: ['option'],\n optgroup: ['option', 'optgroup'],\n tr: ['td', 'th', 'tr'],\n td: ['td', 'th'],\n th: ['td', 'th'],\n tbody: ['td', 'th', 'tr', 'thead', 'tbody'],\n tfoot: ['td', 'th', 'tr', 'thead', 'tbody'],\n}\n\n/** Block-level start tags that implicitly close an open `<p>`. */\nconst CLOSES_OPEN_P = new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'details',\n 'div',\n 'dl',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'main',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'ul',\n])\n\n/**\n * Cap on open-element depth. Beyond it, elements are still recorded but not\n * pushed, so a page with 200 000 nested `<div>`s costs memory proportional to\n * its bytes and nothing more. Real documents do not approach this.\n */\nconst MAX_DEPTH = 256\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunction isAsciiAlpha(ch: string | undefined): boolean {\n if (ch === undefined) return false\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\nfunction isHtmlSpace(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f'\n}\n\n/**\n * Inline `display:none`, with whitespace stripped first so the test itself is a\n * plain substring match rather than a regex with a backtracking profile. Only\n * the element's own `style` attribute is consulted: NO CSS RESOLUTION (§3.6).\n */\nconst DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/\n\nfunction hasInlineDisplayNone(style: string | undefined): boolean {\n if (style === undefined) return false\n return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\\s+/g, ''))\n}\n\n/** Reads an attribute, or null. Attribute names are lowercased by the tokenizer. */\nexport function attr(element: HtmlElement, name: string): string | null {\n return element.attrs[name] ?? null\n}\n\n// ---------------------------------------------------------------------------\n// Tag parsing\n// ---------------------------------------------------------------------------\n\ninterface ParsedTag {\n tag: string\n attrs: Record<string, string>\n selfClosing: boolean\n /** Index just past the closing `>` (or past the end of input if unterminated). */\n end: number\n}\n\n/**\n * Parses a start tag beginning at `start` (the `<`). Tolerant: an unterminated\n * tag consumes to end of input and returns what it read.\n */\nfunction parseStartTag(html: string, start: number): ParsedTag {\n let i = start + 1\n const nameStart = i\n while (i < html.length) {\n const ch = html[i] ?? ''\n if (isHtmlSpace(ch) || ch === '/' || ch === '>') break\n i++\n }\n const tag = html.slice(nameStart, i).toLowerCase()\n const attrs: Record<string, string> = {}\n let selfClosing = false\n\n while (i < html.length) {\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (i >= html.length) break\n const ch = html[i] ?? ''\n if (ch === '>') {\n i++\n return { tag, attrs, selfClosing, end: i }\n }\n if (ch === '/') {\n selfClosing = true\n i++\n continue\n }\n // Attribute name.\n const attrNameStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '=' || c === '>' || c === '/') break\n i++\n }\n if (i === attrNameStart) {\n // Nothing consumed (e.g. a stray '='): skip a character so we always advance.\n i++\n continue\n }\n const attrName = html.slice(attrNameStart, i).toLowerCase()\n let value = ''\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (html[i] === '=') {\n i++\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n const quote = html[i]\n if (quote === '\"' || quote === \"'\") {\n i++\n const valueStart = i\n const close = html.indexOf(quote, i)\n if (close === -1) {\n value = html.slice(valueStart)\n i = html.length\n } else {\n value = html.slice(valueStart, close)\n i = close + 1\n }\n } else {\n const valueStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '>') break\n i++\n }\n value = html.slice(valueStart, i)\n }\n }\n // First occurrence wins, per the HTML parsing spec.\n if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value)\n }\n return { tag, attrs, selfClosing, end: i }\n}\n\n/** Locates the matching `</tag` for a raw-text or RCDATA element, case-insensitively. */\nfunction findRawTextEnd(html: string, from: number, tag: string): number {\n const needle = `</${tag}`\n const lower = html.toLowerCase()\n const at = lower.indexOf(needle, from)\n return at === -1 ? -1 : at\n}\n\n// ---------------------------------------------------------------------------\n// tokenizeHtml\n// ---------------------------------------------------------------------------\n\n/** The element's own exclusion reason, ignoring ancestors. */\nfunction ownExclusion(\n tag: string,\n attrs: Readonly<Record<string, string>>,\n): HtmlExclusionReason | null {\n if (tag === 'script') {\n const type = (attrs['type'] ?? '').toLowerCase().split(';')[0]?.trim() ?? ''\n return type === 'application/ld+json' ? 'script-ld-json' : 'script'\n }\n if (tag === 'style') return 'style'\n if (tag === 'template') return 'template'\n // `hidden` is a boolean attribute: its presence hides, whatever the value\n // (including `hidden=\"until-found\"`, which is still hidden until found).\n if ('hidden' in attrs) return 'hidden-attribute'\n if (hasInlineDisplayNone(attrs['style'])) return 'inline-display-none'\n return null\n}\n\n/**\n * Tokenizes `html` into the flat, offset-annotated structure ARS scores against.\n * Never throws. `html` is the DECODED response body; offsets are UTF-8 byte\n * offsets into that decoded body, matching `ArsHttpCapture.bytes`.\n */\nexport function tokenizeHtml(html: string): HtmlDocument {\n const elements: HtmlElement[] = []\n const texts: HtmlText[] = []\n const jsonLd: HtmlJsonLd[] = []\n const metas: HtmlMeta[] = []\n const links: HtmlLink[] = []\n const stack: number[] = []\n const cursor = new Utf8Cursor(html)\n\n const topIndex = (): number => stack[stack.length - 1] ?? -1\n const exclusionAt = (elementIndex: number): HtmlExclusionReason | null =>\n elementIndex >= 0 ? (elements[elementIndex]?.excludedBy ?? null) : null\n\n const emitText = (\n from: number,\n to: number,\n decode: boolean,\n override?: HtmlExclusionReason,\n ): void => {\n if (to <= from) return\n const raw = html.slice(from, to)\n const parent = topIndex()\n const offset = cursor.at(from)\n texts.push({\n text: decode ? decodeEntities(raw) : raw,\n offset,\n bytes: cursor.at(to) - offset,\n parent,\n excludedBy: override ?? exclusionAt(parent),\n })\n }\n\n const popTo = (tag: string): void => {\n for (let depth = stack.length - 1; depth >= 0; depth--) {\n const candidate = stack[depth]\n if (candidate === undefined) continue\n if (elements[candidate]?.tag === tag) {\n stack.length = depth\n return\n }\n }\n // No matching open element: a stray end tag. Ignore it, as browsers do.\n }\n\n const applyImpliedEndTags = (tag: string): void => {\n const closes = IMPLIED_END_TAGS[tag]\n if (closes !== undefined) {\n while (stack.length > 0) {\n const top = stack[stack.length - 1]\n const openTag = top === undefined ? undefined : elements[top]?.tag\n if (openTag === undefined || !closes.includes(openTag)) break\n stack.pop()\n }\n }\n if (CLOSES_OPEN_P.has(tag)) {\n const top = stack[stack.length - 1]\n if (top !== undefined && elements[top]?.tag === 'p') stack.pop()\n }\n }\n\n // `textStart` trails `i`: a `<` that turns out NOT to open markup stays inside\n // the current text run rather than splitting it. `a < b` is one text node, not\n // three — and since `countedText` joins nodes with a space, splitting it would\n // silently rewrite the page's own text before any fact is extracted from it.\n let i = 0\n let textStart = 0\n while (i < html.length) {\n const lt = html.indexOf('<', i)\n if (lt === -1) break\n\n const next = html[lt + 1]\n // A `<` opens markup only before `!`, `/`, or an ASCII letter. Anything else\n // — `3<4`, a stray `<` at end of input — is text.\n if (next !== '!' && next !== '/' && !isAsciiAlpha(next)) {\n i = lt + 1\n continue\n }\n emitText(textStart, lt, true)\n\n // --- Comments, doctypes, CDATA, bogus comments ---\n if (next === '!') {\n if (html.startsWith('<!--', lt)) {\n const close = html.indexOf('-->', lt + 4)\n i = close === -1 ? html.length : close + 3\n } else {\n const close = html.indexOf('>', lt + 2)\n i = close === -1 ? html.length : close + 1\n }\n textStart = i\n continue\n }\n\n // --- End tags ---\n if (next === '/') {\n const close = html.indexOf('>', lt + 2)\n const end = close === -1 ? html.length : close + 1\n const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim()\n const tag = rawName.toLowerCase()\n if (tag.length > 0) popTo(tag)\n i = end\n textStart = i\n continue\n }\n\n // --- Start tags ---\n const parsed = parseStartTag(html, lt)\n applyImpliedEndTags(parsed.tag)\n\n const parent = topIndex()\n const own = ownExclusion(parsed.tag, parsed.attrs)\n const element: HtmlElement = {\n index: elements.length,\n tag: parsed.tag,\n attrs: parsed.attrs,\n offset: cursor.at(lt),\n parent,\n depth: stack.length,\n excludedBy: exclusionAt(parent) ?? own,\n }\n elements.push(element)\n collectMetaOrLink(element, metas, links)\n i = parsed.end\n\n const isVoid = VOID_ELEMENTS.has(parsed.tag)\n const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag)\n const isRcdata = RCDATA_ELEMENTS.has(parsed.tag)\n\n if (isRawText || isRcdata) {\n // Contents are opaque: no nested tags, no stack push. Entities are decoded\n // for RCDATA (`<title>`, `<textarea>`) and NOT for raw text (`<script>`,\n // `<style>`) — a JSON-LD block must survive byte-for-byte.\n const contentStart = i\n const close = findRawTextEnd(html, contentStart, parsed.tag)\n const contentEnd = close === -1 ? html.length : close\n if (contentEnd > contentStart) {\n const wasTop = stack.length\n stack.push(element.index)\n emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? undefined)\n stack.length = wasTop\n if (own === 'script-ld-json') {\n jsonLd.push({\n text: html.slice(contentStart, contentEnd),\n offset: cursor.at(contentStart),\n element: element.index,\n })\n }\n }\n if (close === -1) {\n i = html.length\n } else {\n const gt = html.indexOf('>', close)\n i = gt === -1 ? html.length : gt + 1\n }\n textStart = i\n continue\n }\n\n if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index)\n textStart = i\n }\n emitText(textStart, html.length, true)\n\n return {\n elements,\n texts,\n jsonLd,\n metas,\n links,\n bytes: cursor.at(html.length),\n }\n}\n\n/** Records `<meta>` and `<link>` elements into their typed side-tables. */\nfunction collectMetaOrLink(element: HtmlElement, metas: HtmlMeta[], links: HtmlLink[]): void {\n const lower = (value: string | undefined): string | null =>\n value === undefined ? null : value.toLowerCase()\n\n if (element.tag === 'meta') {\n metas.push({\n name: lower(element.attrs['name']),\n property: lower(element.attrs['property']),\n httpEquiv: lower(element.attrs['http-equiv']),\n itemprop: lower(element.attrs['itemprop']),\n charset: lower(element.attrs['charset']),\n content: element.attrs['content'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n return\n }\n\n if (element.tag === 'link') {\n const rawRel = element.attrs['rel'] ?? ''\n const rel: string[] = []\n for (const token of rawRel.toLowerCase().split(/\\s+/)) {\n if (token.length > 0 && !rel.includes(token)) rel.push(token)\n }\n links.push({\n rel,\n href: element.attrs['href'] ?? null,\n type: lower(element.attrs['type']),\n hreflang: lower(element.attrs['hreflang']),\n title: element.attrs['title'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text views\n// ---------------------------------------------------------------------------\n\n/**\n * Joins text nodes with a single space and collapses whitespace runs.\n *\n * A single space rather than an empty string: `<b>Blue</b><i>Shirt</i>` renders\n * as two words to a reader, and \"BlueShirt\" is not a title. Joining always,\n * rather than only across block boundaries, avoids needing a display-model —\n * which is the same reason there is no CSS resolution anywhere in this file.\n */\nfunction joinText(parts: readonly string[]): string {\n return parts.join(' ').replace(/\\s+/g, ' ').trim()\n}\n\n/** All counted text in the document, per the §3.6 normative extraction rule. */\nexport function countedText(doc: HtmlDocument): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy === null) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/**\n * Counted text inside one element's subtree — anchor text for\n * `primary-action-url`, a `<summary>`'s question, a heading. `includeExcluded`\n * opts into hidden subtrees, which the extractor needs for exactly one thing:\n * reporting hidden facts as evidence (fixture `037-hidden-text-facts`) without\n * letting them score.\n */\nexport function elementText(\n doc: HtmlDocument,\n elementIndex: number,\n includeExcluded = false,\n): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (!includeExcluded && node.excludedBy !== null) continue\n if (isSelfOrDescendant(doc, node.parent, elementIndex)) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/** Walks `parent` links upward. Bounded by MAX_DEPTH + 1 so a cycle cannot hang. */\nfunction isSelfOrDescendant(doc: HtmlDocument, from: number, ancestor: number): boolean {\n let current = from\n for (let hops = 0; hops <= MAX_DEPTH + 1 && current >= 0; hops++) {\n if (current === ancestor) return true\n current = doc.elements[current]?.parent ?? -1\n }\n return false\n}\n","/**\n * extract.ts — pass 2 of the ARS pipeline: turn one fetched representation into\n * a set of normalised fact observations, scored against the resolved page-kind\n * profile (design §3.5, §3.6).\n *\n * WHAT A \"REPRESENTATION\" IS. The probe returns two captures that differ only in\n * their `Accept` header (§3.3). Each one is turned into an `ArsRepresentation`:\n * a decoded body, its byte length as the probe measured it, the tokenized\n * document when the bytes are HTML, the JSON-LD blocks, and the counted text.\n * Everything downstream reads a representation, never a raw capture, so the\n * markdown path and the HTML path go through the same scoring code.\n *\n * WHICH REPRESENTATION SCORES WHAT — the decision that makes the golden pair\n * (`001-pdp-gateway-md` vs `002-pdp-raw-html`) mean anything:\n *\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. A merchant whose markdown omits\n * `availability` loses coverage even though the HTML declares it — the agent\n * never saw it.\n *\n * D1.3 (render independence) and D5 (structured data) score the HTML\n * representation, because those checks are about the document a caller that\n * only reads HTML gets. JSON-LD does not live in markdown, and \"would this\n * page work without JavaScript\" is a question about HTML.\n *\n * CORROBORATION CROSSES THE TWO. §3.6 defines corroborated as \"observed in ≥2\n * sources (e.g. JSON-LD and visible text)\". A price stated in the negotiated\n * markdown *and* in the HTML's JSON-LD is observed in two sources and is\n * corroborated; that is the only reason a correctly installed gateway can reach\n * an A. But a fact observed ONLY in the HTML does not enter the scored fact set\n * at all — corroboration strengthens a fact the agent received, it never\n * conjures one it did not. See `mergeFacts`.\n *\n * VALUE FACTS vs PRESENCE FACTS. Some facts are compared by value (a price, a\n * title, a phone number); others are only ever \"declared or not\" (shipping,\n * returns, opening hours, question/answer shape). Presence facts normalise to\n * the literal string `declared` from EVERY source, deliberately: two sources\n * that describe the same shipping policy in different words must still\n * corroborate each other, and a free-text comparison would make that\n * non-deterministic. The split is pinned in `PRESENCE_FACTS` below and printed\n * in the spec, because it is the difference between \"we compared the values\" and\n * \"we compared whether you said anything\".\n *\n * EVERYTHING HERE IS PINNED DATA, NOT INFERENCE. The label lexicon, the\n * availability vocabulary, the no-published-price phrases, the schema.org\n * property aliases: all tables, all versioned. An extractor that guessed would\n * make `score()` non-reproducible in a second implementation, which is the one\n * property the whole package exists to provide.\n */\n\nimport { attr, countedText, elementText, tokenizeHtml } from './html'\nimport type { HtmlDocument } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type {\n ArsAudience,\n ArsAudienceDecision,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsHttpCapture,\n ArsPolicyReport,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * UTF-8 byte length of a JavaScript string, counting a lone surrogate as 3\n * bytes — the width WHATWG encoding gives U+FFFD, which is what a lone\n * surrogate actually costs on the wire. Matches `Utf8Cursor` in `./html`, which\n * is why offsets from the two files are in the same address space.\n */\nexport function utf8Length(text: string): number {\n let bytes = 0\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code <= 0xdbff) {\n const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4\n i++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD\n// ---------------------------------------------------------------------------\n\n/** A flattened JSON-LD node: one object with an `@type`, wherever it was nested. */\nexport interface JsonLdNode {\n /** `@type` values with any `http(s)://schema.org/` prefix stripped. Always ≥1 entry. */\n readonly types: readonly string[]\n readonly value: Readonly<Record<string, unknown>>\n /** UTF-8 byte offset of the block the node came from. */\n readonly offset: number\n}\n\n/** What `parseJsonLd` observed, including the blocks that failed — D5.1 scores both. */\nexport interface JsonLdReport {\n readonly nodes: readonly JsonLdNode[]\n readonly blocks: number\n readonly parsed: number\n}\n\nconst SCHEMA_PREFIX = /^https?:\\/\\/schema\\.org\\//\n\nfunction stripSchemaPrefix(type: string): string {\n return type.replace(SCHEMA_PREFIX, '')\n}\n\n/** Types from a node's `@type`, which may be a string or an array of strings. */\nfunction typesOf(value: Record<string, unknown>): string[] {\n const raw = value['@type']\n if (typeof raw === 'string') return [stripSchemaPrefix(raw)]\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) if (typeof entry === 'string') out.push(stripSchemaPrefix(entry))\n return out\n }\n return []\n}\n\n/** Depth cap on JSON-LD traversal. Deeper than any real graph; stops a hostile nesting bomb. */\nconst JSON_LD_MAX_DEPTH = 12\n\nfunction collectNodes(\n value: unknown,\n offset: number,\n depth: number,\n out: JsonLdNode[],\n seen: Set<object>,\n): void {\n if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== 'object') return\n if (seen.has(value)) return\n seen.add(value)\n\n if (Array.isArray(value)) {\n for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen)\n return\n }\n\n const record = value as Record<string, unknown>\n const types = typesOf(record)\n if (types.length > 0) out.push({ types, value: record, offset })\n\n for (const [key, child] of Object.entries(record)) {\n if (key === '@context') continue\n collectNodes(child, offset, depth + 1, out, seen)\n }\n}\n\n/**\n * Parses every JSON-LD block. A block that does not parse is counted and\n * dropped: D5.1 scores \"present **and parses**\", so fixture `033-invalid-jsonld`\n * needs the block count and the parsed count to differ.\n */\nexport function parseJsonLd(blocks: readonly { text: string; offset: number }[]): JsonLdReport {\n const nodes: JsonLdNode[] = []\n let parsed = 0\n for (const block of blocks) {\n let value: unknown\n try {\n value = JSON.parse(block.text) as unknown\n } catch {\n continue\n }\n parsed++\n collectNodes(value, block.offset, 0, nodes, new Set<object>())\n }\n return { nodes, blocks: blocks.length, parsed }\n}\n\n/**\n * Reads a dotted property path off a node, entering array members: `offers.price`\n * matches `offers[0].price`. Returns the first non-empty scalar found, or null.\n * The notation is the one `DEFAULT_RULESET.requiredProperties` is written in.\n */\nexport function readPath(node: JsonLdNode, path: string): string | null {\n const segments = path.split('.')\n let frontier: unknown[] = [node.value]\n for (const segment of segments) {\n const next: unknown[] = []\n for (const current of frontier) {\n if (current === null || typeof current !== 'object') continue\n if (Array.isArray(current)) {\n for (const entry of current) {\n if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {\n const child = (entry as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n }\n continue\n }\n const child = (current as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n frontier = next\n if (frontier.length === 0) return null\n }\n for (const found of frontier) {\n const scalar = scalarOf(found)\n if (scalar !== null) return scalar\n }\n return null\n}\n\n/**\n * A scalar reading of a JSON-LD value. Objects yield their `name`, `@id` or\n * `value` — `brand: {\"@type\":\"Brand\",\"name\":\"X\"}` is the common real shape and\n * refusing to read it would cost merchants points for correct markup.\n */\nfunction scalarOf(value: unknown): string | null {\n if (typeof value === 'string') return value.trim().length > 0 ? value.trim() : null\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) {\n for (const entry of value) {\n const scalar = scalarOf(entry)\n if (scalar !== null) return scalar\n }\n return null\n }\n if (value !== null && typeof value === 'object') {\n const record = value as Record<string, unknown>\n for (const key of ['name', 'value', '@id', 'url', 'headline']) {\n const scalar = scalarOf(record[key])\n if (scalar !== null) return scalar\n }\n }\n return null\n}\n\n/** True when the path resolves to anything at all — what D5.2 counts. */\nexport function hasPath(node: JsonLdNode, path: string): boolean {\n return readPath(node, path) !== null\n}\n\n// ---------------------------------------------------------------------------\n// Representations\n// ---------------------------------------------------------------------------\n\nexport type ArsRepresentationKind = 'html' | 'markdown' | 'text' | 'json' | 'other'\n\nexport interface ArsRepresentation {\n /** Classified from the `Content-Type` header alone. See `looksLikeHtml` for the body's opinion. */\n readonly kind: ArsRepresentationKind\n /** Lowercased media type without parameters, or null when the header is absent. */\n readonly contentType: string | null\n /** The decoded body. */\n readonly body: string\n /** Byte length AS THE PROBE MEASURED IT (`ArsHttpCapture.bytes`), not recomputed. */\n readonly bytes: number\n /** Tokenized document, present whenever the bytes are HTML however they are labelled. */\n readonly doc: HtmlDocument | null\n readonly jsonLd: JsonLdReport\n /** Counted text (§3.6) for HTML; the body itself for every other kind. */\n readonly text: string\n /** The body's own opinion, independent of the header. D2.1 scores the disagreement. */\n readonly looksLikeHtml: boolean\n readonly truncated: boolean\n readonly finalUrl: string\n readonly headers: Readonly<Record<string, readonly string[]>>\n}\n\n/** First value of a header, or null. Header names are lowercased by the probe. */\nexport function header(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): string | null {\n const values = headers[name]\n return values !== undefined && values.length > 0 ? (values[0] ?? null) : null\n}\n\n/** All values of a header, in order. `Link` is routinely repeated and is scored twice over. */\nexport function headerAll(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): readonly string[] {\n return headers[name] ?? []\n}\n\n/** Media type without parameters, lowercased. */\nexport function mediaType(contentType: string | null): string | null {\n if (contentType === null) return null\n const semi = contentType.indexOf(';')\n const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()\n return value.length > 0 ? value : null\n}\n\nfunction classifyMediaType(type: string | null): ArsRepresentationKind {\n if (type === null) return 'other'\n if (type === 'text/html' || type === 'application/xhtml+xml') return 'html'\n if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'\n if (type === 'text/plain') return 'text'\n if (type === 'application/json' || type === 'application/ld+json' || type.endsWith('+json')) {\n return 'json'\n }\n return 'other'\n}\n\n/**\n * Does the body look like HTML regardless of what the header claims? Bounded to\n * the first 1 KiB so the test is O(1) on a 2 MiB body. Fixture\n * `036-negotiation-wrong-content-type` is exactly the case where the header and\n * this function disagree, and D2.1 pays for it.\n */\nfunction bodyLooksLikeHtml(body: string): boolean {\n const head = body.slice(0, 1024).trimStart().toLowerCase()\n return head.startsWith('<!doctype html') || head.startsWith('<html') || head.startsWith('<?xml')\n ? true\n : head.includes('<html') || head.includes('<head>') || head.includes('<body')\n}\n\n/**\n * Builds a representation from a capture. Returns null when the body is absent:\n * `ArsHttpCapture.body` is optional because a PUBLISHED evidence bundle carries\n * the hash and not the bytes (§3.9), and a bundle without bytes cannot be\n * re-scored — `score()` reports `unscored / evidence-incomplete` rather than\n * inventing a zero.\n */\nexport function buildRepresentation(capture: ArsHttpCapture): ArsRepresentation | null {\n if (typeof capture.body !== 'string') return null\n const contentType = mediaType(header(capture.headers, 'content-type'))\n const declared = classifyMediaType(contentType)\n const looksLikeHtml = bodyLooksLikeHtml(capture.body)\n\n // Tokenize whenever the BYTES are HTML, whatever the header says. A merchant\n // with a mislabelled content type already loses 10 points on D2.1; taking\n // their fact coverage as well would charge them twice for one mistake.\n const doc = declared === 'html' || looksLikeHtml ? tokenizeHtml(capture.body) : null\n\n const jsonLd =\n doc !== null\n ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset })))\n : declared === 'json'\n ? parseJsonLd([{ text: capture.body, offset: 0 }])\n : { nodes: [], blocks: 0, parsed: 0 }\n\n return {\n kind: declared,\n contentType,\n body: capture.body,\n bytes: capture.bytes,\n doc,\n jsonLd,\n text: doc !== null ? countedText(doc) : capture.body,\n looksLikeHtml,\n truncated: capture.truncated,\n finalUrl: capture.finalUrl,\n headers: capture.headers,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Facts — the internal shape\n// ---------------------------------------------------------------------------\n\nexport type ArsFactSource = ArsFactObservation['source']\n\n/**\n * One observation before merging. `qualified` and `element` are internal:\n * `ArsFactObservation` (§3.9) carries neither, and this file exists to keep the\n * published shape exactly as the design wrote it.\n */\nexport interface ExtractedFact {\n readonly kind: ArsFactKind\n readonly normalized: string\n readonly source: ArsFactSource\n readonly offset: number\n /** True for ranges and qualifiers. Excluded from the D2.4 parity comparison (§3.11). */\n readonly qualified: boolean\n}\n\n/** A merged fact: the published observation plus what merging learned. */\nexport interface MergedFact extends ArsFactObservation {\n readonly qualified: boolean\n /** Distinct sources that reported THIS value. `corroborated` is `length >= 2`. */\n readonly sources: readonly ArsFactSource[]\n}\n\n/**\n * Source precedence, used only to break an offset tie. Declaration order is the\n * order of the union in §3.9, so a second implementation reads it off the\n * published type rather than out of this file.\n */\nconst SOURCE_ORDER: readonly ArsFactSource[] = [\n 'json-ld',\n 'microdata',\n 'meta',\n 'html-text',\n 'negotiated',\n]\n\n/**\n * Facts that are only ever \"declared or not\". Every source normalises them to\n * the literal `declared`, so two sources that word the same shipping policy\n * differently still corroborate one another. See the file header.\n */\nconst PRESENCE_FACTS: ReadonlySet<ArsFactKind> = new Set<ArsFactKind>([\n 'shipping',\n 'returns',\n 'hours',\n 'service-area',\n 'eligibility',\n 'question-answer',\n 'item-link',\n])\n\nconst DECLARED = 'declared'\n\n/**\n * Merges observations into the published fact set.\n *\n * `primary` is the representation the agent received; `corroborating` is the\n * other one. A fact appears in the output only if the AGENT saw it. The\n * representative observation is the one with the lowest byte offset (ties broken\n * by `SOURCE_ORDER`, then lexicographically by value) — lowest offset, because\n * D4.1 scores the byte offset at which a fact first becomes available.\n * `corroborated` counts the distinct sources, across BOTH representations, that\n * reported the representative's exact normalised value; a source reporting a\n * different value corroborates nothing, which is what makes fixture\n * `034-jsonld-price-mismatch` fail to corroborate rather than agree.\n */\nexport function mergeFacts(\n primary: readonly ExtractedFact[],\n corroborating: readonly ExtractedFact[],\n): MergedFact[] {\n const byKind = new Map<ArsFactKind, ExtractedFact[]>()\n for (const fact of primary) {\n const list = byKind.get(fact.kind)\n if (list === undefined) byKind.set(fact.kind, [fact])\n else list.push(fact)\n }\n\n const merged: MergedFact[] = []\n for (const [kind, observations] of byKind) {\n const representative = observations.reduce((best, candidate) =>\n betterObservation(best, candidate),\n )\n const sources: ArsFactSource[] = []\n for (const fact of [...observations, ...corroborating]) {\n if (fact.kind !== kind) continue\n if (fact.normalized !== representative.normalized) continue\n if (!sources.includes(fact.source)) sources.push(fact.source)\n }\n merged.push({\n kind,\n normalized: representative.normalized,\n source: representative.source,\n offset: representative.offset,\n corroborated: sources.length >= 2,\n qualified: representative.qualified,\n sources,\n })\n }\n\n merged.sort((a, b) => (a.offset === b.offset ? cmp(a.kind, b.kind) : a.offset - b.offset))\n return merged\n}\n\nfunction betterObservation(a: ExtractedFact, b: ExtractedFact): ExtractedFact {\n if (a.offset !== b.offset) return a.offset < b.offset ? a : b\n const rank = SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source)\n if (rank !== 0) return rank < 0 ? a : b\n return cmp(a.normalized, b.normalized) <= 0 ? a : b\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n// ---------------------------------------------------------------------------\n// Normalisation\n// ---------------------------------------------------------------------------\n\nconst TITLE_SEPARATORS = [' | ', ' — ', ' – ', ' · ', ' :: ', ' » ']\n\n/**\n * Collapse whitespace, cut at the first pinned separator, lowercase.\n *\n * The cut is what lets `<title>Alpine Trail Pack 28L — 420D Ripstop | Basecamp\n * Supply Co</title>` corroborate a JSON-LD `name` of `Alpine Trail Pack 28L`.\n * Without it, essentially no real page would ever have a corroborated title,\n * and `title` is a core fact for seven of the eight page kinds.\n */\nexport function normalizeTitle(text: string): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim()\n let cut = collapsed\n for (const separator of TITLE_SEPARATORS) {\n const at = cut.indexOf(separator)\n if (at > 0) cut = cut.slice(0, at)\n }\n return cut.trim().toLowerCase()\n}\n\n/** Collapse whitespace + lowercase, capped so one long description cannot bloat a result. */\nconst MAX_NORMALIZED_TEXT = 200\n\nexport function normalizeText(text: string): string {\n return text.replace(/\\s+/g, ' ').trim().toLowerCase().slice(0, MAX_NORMALIZED_TEXT)\n}\n\n/**\n * Money → `<ISO> <minor units>`, e.g. `USD 14800`. Currency travels with the\n * amount so the D2.4 parity comparison cannot match 14800 JPY against 14800 USD,\n * and `currency` is still reported separately because it is its own core fact.\n */\nfunction normalizeMoney(amount: number, currency: string): string {\n return `${currency} ${amount}`\n}\n\n/** ISO 8601 date, day precision. Anything that is not a recognisable date is not a fact. */\nexport function normalizeDate(text: string): string | null {\n const trimmed = text.trim()\n const iso = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(trimmed)\n if (iso !== null) return `${iso[1]}-${iso[2]}-${iso[3]}`\n const slashes = /^(\\d{4})\\/(\\d{2})\\/(\\d{2})/.exec(trimmed)\n if (slashes !== null) return `${slashes[1]}-${slashes[2]}-${slashes[3]}`\n const named = /^(\\d{1,2}) ([A-Za-z]{3,9}) (\\d{4})$/.exec(trimmed)\n if (named !== null) {\n const month = MONTHS.indexOf((named[2] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${named[3]}-${pad2(month + 1)}-${pad2(Number(named[1]))}`\n }\n const american = /^([A-Za-z]{3,9}) (\\d{1,2}), (\\d{4})$/.exec(trimmed)\n if (american !== null) {\n const month = MONTHS.indexOf((american[1] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${american[3]}-${pad2(month + 1)}-${pad2(Number(american[2]))}`\n }\n return null\n}\n\nconst MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\nfunction pad2(value: number): string {\n return value < 10 ? `0${value}` : String(value)\n}\n\n/**\n * The availability vocabulary, pinned. schema.org URLs, the bare enum names and\n * the visible-text phrases all collapse to one of six tokens, because \"In stock\"\n * on the page and `https://schema.org/InStock` in the JSON-LD are the same fact\n * and must corroborate.\n */\nconst AVAILABILITY_TOKENS: readonly (readonly [string, string])[] = [\n ['limitedavailability', 'limited'],\n ['onlineonly', 'instock'],\n ['instoreonly', 'instock'],\n ['presale', 'preorder'],\n ['preorder', 'preorder'],\n ['backorder', 'backorder'],\n ['discontinued', 'discontinued'],\n ['soldout', 'outofstock'],\n ['outofstock', 'outofstock'],\n ['instock', 'instock'],\n]\n\n/** Visible-text phrases, matched against normalised text. Longest first. */\nconst AVAILABILITY_PHRASES: readonly (readonly [string, string])[] = [\n ['limited availability', 'limited'],\n ['limited stock', 'limited'],\n ['currently unavailable', 'outofstock'],\n ['temporarily unavailable', 'outofstock'],\n ['out of stock', 'outofstock'],\n ['discontinued', 'discontinued'],\n ['back order', 'backorder'],\n ['backorder', 'backorder'],\n ['pre-order', 'preorder'],\n ['preorder', 'preorder'],\n ['sold out', 'outofstock'],\n ['in stock', 'instock'],\n ['available now', 'instock'],\n]\n\nexport function normalizeAvailability(value: string): string | null {\n const squashed = value.toLowerCase().replace(/[^a-z]/g, '')\n for (const [needle, token] of AVAILABILITY_TOKENS) {\n if (squashed.endsWith(needle) || squashed === needle) return token\n }\n return null\n}\n\n/**\n * \"We score honesty, not disclosure\" (§3.5): an explicit statement that there is\n * no published price satisfies the `price` core fact. The list is pinned and\n * deliberately short — it contains only phrases that state the absence of a\n * price, never phrases that merely fail to state one.\n */\nconst NO_PUBLISHED_PRICE: readonly string[] = [\n 'price on request',\n 'pricing on request',\n 'price on application',\n 'contact us for pricing',\n 'contact for pricing',\n 'contact us for a quote',\n 'no published price',\n 'pricing available on request',\n]\n\nconst UNPRICED = 'unpriced'\n\n/** Phone → `+` and digits. `(415) 555-0142` and `+1 415 555 0142` are one fact. */\nexport function normalizePhone(value: string): string | null {\n const trimmed = value.trim()\n const plus = trimmed.startsWith('+') || trimmed.startsWith('tel:+')\n const digits = trimmed.replace(/\\D/g, '')\n if (digits.length < 7 || digits.length > 15) return null\n return plus ? `+${digits}` : digits\n}\n\n// ---------------------------------------------------------------------------\n// Money tokens in free text\n// ---------------------------------------------------------------------------\n\n/**\n * Single-character currency symbols that may START a money span. Multi-character\n * markers (`R$`, `kr`, `CHF`) are reached through the ISO-code branch instead: a\n * scanner that treated `R` or `k` as a currency start would open a span on every\n * capital R on the page and hand `parseMoneyText` garbage to reject.\n */\nconst CURRENCY_SYMBOLS = '$€£¥₹₩₪₫₴₦₱฿₺'\nconst DIGITS = '0123456789'\n/** Comma, period, both apostrophes, plain space, NBSP, NARROW NBSP. */\nconst MONEY_SEPARATORS = \".,'’   \"\nconst MONEY_PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as low as',\n 'starts at',\n 'from',\n]\nconst RANGE_JOINERS = ['—', '–', '-', ' to ']\n\n/**\n * Finds money-shaped substrings and hands each to `parseMoneyText`.\n *\n * Written as a scanner rather than a regex on purpose: the pattern that would\n * express this correctly needs nested quantifiers over overlapping character\n * classes, which is both a backtracking hazard on attacker-supplied bytes and\n * much harder to reimplement in another language than twenty lines of loop.\n *\n * The window handed to the parser includes an immediately preceding qualifier\n * (`From $9`) and a following range operand (`$148 – $198`), because\n * `parseMoneyText` resolves both to the lower bound with `qualified: true`, and a\n * qualified price is excluded from D2.4 parity (§3.11). Slicing the bare token\n * would silently turn a range into an exact price.\n */\nexport function findMoneyPhrases(text: string): { phrase: string; index: number }[] {\n const found: { phrase: string; index: number }[] = []\n const limit = Math.min(text.length, MAX_SCAN_CHARS)\n let i = 0\n while (i < limit) {\n const spanEnd = readMoneySpan(text, i, limit)\n if (spanEnd === null) {\n i++\n continue\n }\n let start = i\n let end = spanEnd\n\n // Leading qualifier.\n const before = text.slice(Math.max(0, start - 20), start).toLowerCase()\n for (const qualifier of MONEY_PREFIX_QUALIFIERS) {\n if (before.trimEnd().endsWith(qualifier)) {\n start = Math.max(0, start - (before.length - before.trimEnd().length) - qualifier.length)\n break\n }\n }\n\n // Trailing range operand.\n for (const joiner of RANGE_JOINERS) {\n const after = text.slice(end, end + joiner.length + 2)\n const at = after.indexOf(joiner)\n if (at === -1 || at > 1) continue\n const secondStart = end + at + joiner.length\n const secondEnd = readMoneySpan(text, skipSpaces(text, secondStart, limit), limit)\n if (secondEnd !== null) end = secondEnd\n break\n }\n\n found.push({ phrase: text.slice(start, end), index: start })\n i = end\n }\n return found\n}\n\n/** Bounded scan window. A 2 MiB body is data, not a budget. */\nconst MAX_SCAN_CHARS = 400_000\n\nfunction skipSpaces(text: string, from: number, limit: number): number {\n let i = from\n while (i < limit && text.charAt(i) === ' ') i++\n return i\n}\n\n/**\n * Reads one money-shaped span starting at `from`, or null. A span is a currency\n * marker adjacent to a digit run, in either order; the marker is a symbol from\n * the pinned set or an uppercase three-letter token.\n */\nfunction readMoneySpan(text: string, from: number, limit: number): number | null {\n const char = text.charAt(from)\n if (CURRENCY_SYMBOLS.includes(char) && char !== '') {\n let i = from + 1\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n if (DIGITS.includes(char)) {\n // Only start a span at the beginning of a number run.\n const previous = from > 0 ? text.charAt(from - 1) : ''\n if (DIGITS.includes(previous) || MONEY_SEPARATORS.includes(previous)) return null\n const end = readNumberRun(text, from, limit)\n let i = end\n if (text.charAt(i) === ' ') i++\n const symbol = text.charAt(i)\n if (CURRENCY_SYMBOLS.includes(symbol) && symbol !== '') return i + 1\n const code = text.slice(i, i + 3)\n if (/^[A-Z]{3}$/.test(code) && !/[A-Za-z]/.test(text.charAt(i + 3))) return i + 3\n return null\n }\n if (/[A-Z]/.test(char) && from + 3 <= limit) {\n const code = text.slice(from, from + 3)\n if (!/^[A-Z]{3}$/.test(code)) return null\n if (from > 0 && /[A-Za-z]/.test(text.charAt(from - 1))) return null\n let i = from + 3\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n return null\n}\n\nfunction readNumberRun(text: string, from: number, limit: number): number {\n let i = from\n let end = from\n while (i < limit) {\n const char = text.charAt(i)\n if (DIGITS.includes(char)) {\n i++\n end = i\n continue\n }\n if (MONEY_SEPARATORS.includes(char) && char !== '') {\n i++\n continue\n }\n break\n }\n return end\n}\n\n// ---------------------------------------------------------------------------\n// Label lexicon — the key/value shape of markdown and of `<dt>`-style HTML\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned label → fact mapping. This is how facts are read out of the negotiated\n * markdown representation, whose shape is `- **Price:** $148.00` (see\n * `@rebilder/render-md`), and out of definition-list HTML.\n *\n * Pinned rather than fuzzy-matched for the usual reason: a lexicon that grew per\n * page would make the same bytes score differently in two implementations.\n * Additions land as a MINOR.\n */\nconst LABEL_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['price', 'price'],\n ['cost', 'price'],\n ['currency', 'currency'],\n ['availability', 'availability'],\n ['stock', 'availability'],\n ['brand', 'brand'],\n ['manufacturer', 'brand'],\n ['sku', 'sku'],\n ['item number', 'sku'],\n ['product code', 'sku'],\n ['mpn', 'sku'],\n ['shipping', 'shipping'],\n ['delivery', 'shipping'],\n ['returns', 'returns'],\n ['return policy', 'returns'],\n ['refunds', 'returns'],\n ['description', 'description'],\n ['summary', 'description'],\n ['updated', 'updated'],\n ['last updated', 'updated'],\n ['modified', 'updated'],\n ['published', 'published'],\n ['date published', 'published'],\n ['author', 'author'],\n ['written by', 'author'],\n ['publisher', 'authority'],\n ['organization', 'org-name'],\n ['organisation', 'org-name'],\n ['company', 'org-name'],\n ['business', 'org-name'],\n ['address', 'address'],\n ['location', 'address'],\n ['phone', 'phone'],\n ['telephone', 'phone'],\n ['tel', 'phone'],\n ['email', 'email'],\n ['e-mail', 'email'],\n ['hours', 'hours'],\n ['opening hours', 'hours'],\n ['duration', 'duration'],\n ['length', 'duration'],\n ['eligibility', 'eligibility'],\n ['requirements', 'eligibility'],\n ['section', 'section'],\n ['category', 'section'],\n ['topic', 'section'],\n ['service area', 'service-area'],\n ['areas served', 'service-area'],\n ['items', 'item-count'],\n ['item count', 'item-count'],\n]\n\n/** Strips markdown list bullets, emphasis and heading marks from a label. */\nfunction normalizeLabel(raw: string): string {\n return raw\n .replace(/^[\\s>*\\-+#]+/, '')\n .replace(/[*_`]/g, '')\n .trim()\n .toLowerCase()\n}\n\ninterface LabelledValue {\n kind: ArsFactKind\n value: string\n index: number\n}\n\n/**\n * Reads `Label: value` lines. Handles the markdown emphasis form\n * (`- **Price:** $148.00`), the plain form (`Price: $148.00`) and nothing else —\n * a colon inside prose is not a label, which is why the label must be the first\n * thing on the line and no longer than `MAX_LABEL_CHARS`.\n */\nfunction readLabelledLines(text: string): LabelledValue[] {\n const out: LabelledValue[] = []\n let cursor = 0\n for (const line of text.split('\\n')) {\n const lineStart = cursor\n cursor += line.length + 1\n const colon = line.indexOf(':')\n if (colon === -1 || colon > MAX_LABEL_CHARS) continue\n const label = normalizeLabel(line.slice(0, colon))\n if (label.length === 0) continue\n const value = line\n .slice(colon + 1)\n .replace(/^[\\s*_`]+/, '')\n .trim()\n if (value.length === 0) continue\n for (const [needle, kind] of LABEL_LEXICON) {\n if (label !== needle) continue\n out.push({ kind, value, index: lineStart + colon + 1 })\n break\n }\n }\n return out\n}\n\nconst MAX_LABEL_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Extraction context\n// ---------------------------------------------------------------------------\n\nexport interface ExtractContext {\n readonly profile: ArsFactProfile\n readonly ruleset: ArsRuleset\n /** Absolute URL the capture resolved to, used as the base for relative links. */\n readonly baseUrl: string\n /** Origin of the target, for the same-origin test on `item-link`. */\n readonly origin: string\n /** ISO code from structured data, if any. Disambiguates `$` and a bare `1.500`. */\n readonly currencyHint: string | undefined\n}\n\n/** Facts the caller wants: the profile's core plus extended set, as one lookup. */\nfunction wanted(profile: ArsFactProfile): ReadonlySet<ArsFactKind> {\n return new Set<ArsFactKind>([...profile.core, ...profile.extended])\n}\n\n/**\n * Pass 2 (§3.5): extract against the RESOLVED profile. Only facts the profile\n * names are extracted, which is the mechanism that caps coverage at the profile\n * size and makes fixtures `031-keyword-stuffed` and `032-density-baseline` score\n * identically — a page can invent a hundred extra facts and none of them counts.\n */\nexport function extractFacts(\n representation: ArsRepresentation,\n context: ExtractContext,\n): ExtractedFact[] {\n const facts: ExtractedFact[] = []\n const want = wanted(context.profile)\n const push = (fact: ExtractedFact): void => {\n if (want.has(fact.kind)) facts.push(fact)\n }\n\n for (const node of representation.jsonLd.nodes) extractFromJsonLd(node, context, push)\n\n if (representation.doc !== null) {\n extractFromHtml(representation.doc, context, push)\n } else {\n extractFromPlainText(representation, context, push)\n }\n\n return facts\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Property aliases per fact, in precedence order. Written as paths so\n * `offers.price` reaches into an `Offer` and `offers.lowPrice` reaches into an\n * `AggregateOffer` — the shape Shopify actually emits.\n */\nconst JSON_LD_PATHS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['title', ['name', 'headline']],\n ['description', ['description', 'abstract']],\n ['price', ['offers.price', 'offers.lowPrice', 'offers.priceSpecification.price', 'price']],\n ['currency', ['offers.priceCurrency', 'offers.priceSpecification.priceCurrency', 'priceCurrency']],\n ['availability', ['offers.availability', 'availability']],\n ['brand', ['brand']],\n ['sku', ['sku', 'mpn', 'gtin13', 'gtin']],\n ['shipping', ['offers.shippingDetails', 'shippingDetails']],\n ['returns', ['offers.hasMerchantReturnPolicy', 'hasMerchantReturnPolicy']],\n ['org-name', ['name']],\n ['address', ['address']],\n ['hours', ['openingHours', 'openingHoursSpecification']],\n ['phone', ['telephone', 'contactPoint.telephone']],\n ['email', ['email', 'contactPoint.email']],\n ['service-area', ['areaServed', 'serviceArea']],\n ['author', ['author']],\n ['authority', ['publisher', 'author']],\n ['section', ['articleSection', 'genre']],\n ['published', ['datePublished', 'dateCreated']],\n ['updated', ['dateModified']],\n ['duration', ['duration', 'timeRequired']],\n ['eligibility', ['eligibleCustomerType', 'audience']],\n ['primary-action-url', ['potentialAction.target', 'potentialAction.url']],\n ['question-answer', ['mainEntity.acceptedAnswer']],\n ['item-count', ['numberOfItems']],\n ['item-link', ['itemListElement.url', 'itemListElement.item']],\n]\n\n/** Types whose `name` is an organisation name rather than a page title. */\nconst ORG_TYPES = new Set([\n 'Organization',\n 'LocalBusiness',\n 'Store',\n 'Restaurant',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'MedicalBusiness',\n 'ProfessionalService',\n 'FoodEstablishment',\n 'LodgingBusiness',\n 'AutomotiveBusiness',\n 'HealthAndBeautyBusiness',\n 'SportsActivityLocation',\n 'Place',\n])\n\nfunction extractFromJsonLd(\n node: JsonLdNode,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const isOrg = node.types.some((type) => ORG_TYPES.has(type))\n for (const [kind, paths] of JSON_LD_PATHS) {\n // `name` means two different things depending on the node's type; reading it\n // as both would let one string corroborate itself across two fact kinds.\n if (kind === 'title' && isOrg) continue\n if (kind === 'org-name' && !isOrg) continue\n\n for (const path of paths) {\n const raw = readPath(node, path)\n if (raw === null) continue\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized === null) continue\n push({ kind, normalized: normalized.value, source: 'json-ld', offset: node.offset, qualified: normalized.qualified })\n break\n }\n }\n}\n\ninterface NormalizedValue {\n value: string\n qualified: boolean\n}\n\n/** One normaliser, shared by every source, so the same fact from two places matches. */\nfunction normalizeFactValue(\n kind: ArsFactKind,\n raw: string,\n context: ExtractContext,\n): NormalizedValue | null {\n if (PRESENCE_FACTS.has(kind)) return { value: DECLARED, qualified: false }\n\n switch (kind) {\n case 'title':\n return raw.trim().length === 0 ? null : { value: normalizeTitle(raw), qualified: false }\n case 'price': {\n const lowered = raw.trim().toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n return { value: UNPRICED, qualified: false }\n }\n const money = parseMoneyText(raw, { currency: context.currencyHint })\n return money === null\n ? null\n : { value: normalizeMoney(money.amount, money.currency), qualified: money.qualified }\n }\n case 'currency': {\n const code = raw.trim().toUpperCase()\n return /^[A-Z]{3}$/.test(code) ? { value: code, qualified: false } : null\n }\n case 'availability': {\n const token = normalizeAvailability(raw)\n return token === null ? null : { value: token, qualified: false }\n }\n case 'phone': {\n const phone = normalizePhone(raw)\n return phone === null ? null : { value: phone, qualified: false }\n }\n case 'email': {\n const email = raw.trim().replace(/^mailto:/i, '').toLowerCase()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { value: email, qualified: false } : null\n }\n case 'published':\n case 'updated': {\n const date = normalizeDate(raw)\n return date === null ? null : { value: date, qualified: false }\n }\n case 'duration': {\n const minutes = normalizeDuration(raw)\n return minutes === null ? null : { value: minutes, qualified: false }\n }\n case 'item-count': {\n const count = Number.parseInt(raw.replace(/[^0-9]/g, ''), 10)\n return Number.isFinite(count) && count > 0 ? { value: String(count), qualified: false } : null\n }\n case 'primary-action-url': {\n const absolute = absoluteUrl(raw, context.baseUrl)\n return absolute === null ? null : { value: absolute, qualified: false }\n }\n default:\n return raw.trim().length === 0 ? null : { value: normalizeText(raw), qualified: false }\n }\n}\n\n/** ISO 8601 durations and the two visible forms, normalised to whole minutes. */\nexport function normalizeDuration(raw: string): string | null {\n // LINEAR, verified.\n // safe-regex flags `\\d+` nested inside a quantified group structurally. It is\n // not ambiguous here: every `\\d+` is followed by a REQUIRED distinct literal\n // (D, H, M), so each group matches exactly one way or none, and the outer\n // quantifiers are `?` (max one repetition), not `*`/`+`. Catastrophic\n // backtracking needs many ways to split the same input; there are none.\n // Measured: 200k chars in <1 ms, growth linear. Input is also capped at\n // MAX_NORMALIZED_TEXT (200) upstream.\n // eslint-disable-next-line security/detect-unsafe-regex\n const iso = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?)?$/.exec(raw.trim().toUpperCase())\n if (iso !== null && (iso[1] ?? iso[2] ?? iso[3]) !== undefined) {\n const minutes = Number(iso[1] ?? 0) * 1440 + Number(iso[2] ?? 0) * 60 + Number(iso[3] ?? 0)\n return minutes > 0 ? String(minutes) : null\n }\n const spoken = /^(\\d{1,4})\\s?(min|mins|minute|minutes|h|hr|hrs|hour|hours)\\b/i.exec(raw.trim())\n if (spoken !== null) {\n const amount = Number(spoken[1])\n const unit = (spoken[2] ?? '').toLowerCase()\n const minutes = unit.startsWith('h') ? amount * 60 : amount\n return minutes > 0 ? String(minutes) : null\n }\n return null\n}\n\n/** Resolves a possibly relative URL. Returns null rather than throwing on garbage. */\nexport function absoluteUrl(href: string, base: string): string | null {\n try {\n return new URL(href, base).toString()\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// HTML extraction\n// ---------------------------------------------------------------------------\n\n/** `<meta>` name/property → fact. Pinned; `og:` and the Twitter card are the whole set. */\nconst META_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['og:title', 'title'],\n ['twitter:title', 'title'],\n ['description', 'description'],\n ['og:description', 'description'],\n ['twitter:description', 'description'],\n ['og:price:amount', 'price'],\n ['product:price:amount', 'price'],\n ['og:price:currency', 'currency'],\n ['product:price:currency', 'currency'],\n ['og:availability', 'availability'],\n ['product:availability', 'availability'],\n ['product:brand', 'brand'],\n ['og:site_name', 'org-name'],\n ['author', 'author'],\n ['article:author', 'author'],\n ['article:published_time', 'published'],\n ['article:modified_time', 'updated'],\n ['article:section', 'section'],\n]\n\n/** `itemprop` → fact, for microdata. The same vocabulary as JSON-LD, one level flat. */\nconst ITEMPROP_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['name', 'title'],\n ['price', 'price'],\n ['pricecurrency', 'currency'],\n ['availability', 'availability'],\n ['brand', 'brand'],\n ['sku', 'sku'],\n ['description', 'description'],\n ['telephone', 'phone'],\n ['email', 'email'],\n ['address', 'address'],\n ['openinghours', 'hours'],\n ['author', 'author'],\n ['datepublished', 'published'],\n ['datemodified', 'updated'],\n ['articlesection', 'section'],\n]\n\nfunction extractFromHtml(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n // <title> and the first <h1>.\n for (const element of doc.elements) {\n if (element.tag !== 'title') continue\n const text = elementText(doc, element.index)\n const normalized = normalizeFactValue('title', text, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n for (const element of doc.elements) {\n if (element.tag !== 'h1' || element.excludedBy !== null) continue\n const normalized = normalizeFactValue('title', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n\n // <meta>.\n for (const meta of doc.metas) {\n if (meta.content === null) continue\n const key = meta.property ?? meta.name\n if (key === null) continue\n for (const [needle, kind] of META_LEXICON) {\n if (key !== needle) continue\n const normalized = normalizeFactValue(kind, meta.content, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'meta', offset: meta.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Microdata: itemprop, with content= preferred over text (schema.org's own advice).\n for (const element of doc.elements) {\n const itemprop = attr(element, 'itemprop')\n if (itemprop === null) continue\n const key = itemprop.toLowerCase()\n for (const [needle, kind] of ITEMPROP_LEXICON) {\n if (key !== needle) continue\n const raw =\n attr(element, 'content') ??\n attr(element, 'datetime') ??\n attr(element, 'href') ??\n elementText(doc, element.index)\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'microdata', offset: element.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Visible text: money, availability phrases, the no-published-price signal.\n extractVisibleText(doc, context, push)\n\n // Links and forms.\n extractLinks(doc, context, push)\n\n // Structural shapes: question/answer, opening hours, definition lists.\n extractStructures(doc, context, push)\n}\n\n/**\n * Facts read out of counted text. Every text node is visited individually so the\n * fact's offset is the offset of the node it was found in — a measured offset of\n * a heuristic fact, which is exactly how §3.9 describes `ArsFactObservation`.\n *\n * Hidden nodes (`hidden`, inline `display:none`, `<template>`) are skipped:\n * fixture `037-hidden-text-facts` asserts that facts stuffed into a hidden\n * element do not score.\n */\nfunction extractVisibleText(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n const text = node.text\n if (text.trim().length === 0) continue\n\n for (const money of findMoneyPhrases(text)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({\n kind: 'price',\n normalized: normalizeMoney(parsed.amount, parsed.currency),\n source: 'html-text',\n offset: node.offset,\n qualified: parsed.qualified,\n })\n push({\n kind: 'currency',\n normalized: parsed.currency,\n source: 'html-text',\n offset: node.offset,\n qualified: false,\n })\n }\n\n const lowered = text.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'html-text', offset: node.offset, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n if (!lowered.includes(phrase)) continue\n push({ kind: 'availability', normalized: token, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n for (const [kind, marker] of TEXT_PRESENCE_MARKERS) {\n if (!marker.some((phrase) => lowered.includes(phrase))) continue\n push({ kind, normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n }\n const sku = /\\bsku[:\\s]+([A-Za-z0-9][A-Za-z0-9._-]{2,31})\\b/i.exec(text)\n if (sku !== null && sku[1] !== undefined) {\n push({ kind: 'sku', normalized: normalizeText(sku[1]), source: 'html-text', offset: node.offset, qualified: false })\n }\n }\n\n // Labelled lines inside HTML (`<dt>Price</dt><dd>$148</dd>` collapses to\n // \"Price $148\" in counted text, so this reads the whole document's text once).\n for (const labelled of readLabelledLines(countedText(doc))) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({\n kind: labelled.kind,\n normalized: normalized.value,\n source: 'html-text',\n offset: firstTextOffset(doc),\n qualified: normalized.qualified,\n })\n }\n}\n\n/** Presence facts detectable from prose, with their pinned phrase lists. */\nconst TEXT_PRESENCE_MARKERS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['shipping', ['free shipping', 'shipping', 'ships in', 'delivery', 'ships free']],\n ['returns', ['return policy', 'returns', 'money-back', 'money back', 'refund']],\n ['service-area', ['areas served', 'service area', 'we serve', 'serving']],\n ['eligibility', ['eligibility', 'who can apply', 'you must be', 'requirements']],\n]\n\nfunction firstTextOffset(doc: HtmlDocument): number {\n for (const node of doc.texts) {\n if (node.excludedBy === null && node.text.trim().length > 0) return node.offset\n }\n return 0\n}\n\nconst ACTION_MAX_TEXT_CHARS = 64\n\nfunction extractLinks(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const lexicon = context.ruleset.actionLexicon\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href === null) continue\n if (href.toLowerCase().startsWith('tel:')) {\n const phone = normalizePhone(href.slice(4))\n if (phone !== null) {\n push({ kind: 'phone', normalized: phone, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n if (href.toLowerCase().startsWith('mailto:')) {\n const normalized = normalizeFactValue('email', href, context)\n if (normalized !== null) {\n push({ kind: 'email', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n continue\n }\n\n if (element.tag === 'form') {\n const action = attr(element, 'action')\n if (action === null) continue\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(action, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n\n const items = largestRepeatedLinkBlock(doc, context.origin)\n if (items.count > 0) {\n push({ kind: 'item-count', normalized: String(items.count), source: 'html-text', offset: items.offset, qualified: false })\n if (items.sameOrigin) {\n push({ kind: 'item-link', normalized: DECLARED, source: 'html-text', offset: items.offset, qualified: false })\n }\n }\n}\n\n/** Anchor text matches the action lexicon exactly, or begins with a lexicon phrase. */\nfunction matchesLexicon(text: string, lexicon: readonly string[]): boolean {\n const normalized = text.replace(/\\s+/g, ' ').trim().toLowerCase()\n if (normalized.length === 0) return false\n for (const phrase of lexicon) {\n if (normalized === phrase) return true\n if (normalized.startsWith(`${phrase} `)) return true\n }\n return false\n}\n\n/**\n * `item-count` / `item-link` for `collection` (§3.5): \"the number of distinct\n * item links inside the largest repeated-structure block, and whether those\n * links resolve to same-origin URLs.\"\n *\n * Made deterministic as: group every anchor by its GRANDPARENT element (the\n * container of the repeated item, e.g. `<ul>` for `<li><a>`), drop groups whose\n * container is inside `<nav>`, `<header>` or `<footer>`, and take the group with\n * the most distinct hrefs. The nav exclusion is the whole reason for the\n * \"largest repeated block\" phrasing — a site-wide menu is a repeated block of\n * links and is not a product grid.\n */\nfunction largestRepeatedLinkBlock(\n doc: HtmlDocument,\n origin: string,\n): { count: number; offset: number; sameOrigin: boolean } {\n const groups = new Map<number, { hrefs: Set<string>; sameOrigin: number; offset: number }>()\n for (const element of doc.elements) {\n if (element.tag !== 'a' || element.excludedBy !== null) continue\n const href = attr(element, 'href')\n if (href === null || href.startsWith('#')) continue\n const parent = element.parent >= 0 ? doc.elements[element.parent] : undefined\n const container = parent !== undefined && parent.parent >= 0 ? parent.parent : element.parent\n if (container < 0) continue\n if (isInsideChrome(doc, container)) continue\n\n const absolute = absoluteUrl(href, origin)\n if (absolute === null) continue\n const group = groups.get(container) ?? {\n hrefs: new Set<string>(),\n sameOrigin: 0,\n offset: doc.elements[container]?.offset ?? 0,\n }\n if (!group.hrefs.has(absolute)) {\n group.hrefs.add(absolute)\n if (absolute.startsWith(origin)) group.sameOrigin++\n }\n groups.set(container, group)\n }\n\n let best = { count: 0, offset: 0, sameOrigin: false }\n for (const [, group] of groups) {\n if (group.hrefs.size <= best.count) continue\n best = {\n count: group.hrefs.size,\n offset: group.offset,\n sameOrigin: group.sameOrigin * 2 >= group.hrefs.size,\n }\n }\n return best.count >= MIN_REPEATED_ITEMS ? best : { count: 0, offset: 0, sameOrigin: false }\n}\n\n/** Below this, a group of links is a paragraph with citations, not a listing. */\nconst MIN_REPEATED_ITEMS = 3\n\nconst CHROME_TAGS = new Set(['nav', 'header', 'footer'])\n\nfunction isInsideChrome(doc: HtmlDocument, from: number): boolean {\n let current = from\n for (let hops = 0; hops < 64 && current >= 0; hops++) {\n const element = doc.elements[current]\n if (element === undefined) return false\n if (CHROME_TAGS.has(element.tag)) return true\n if (element.attrs['role'] === 'navigation' || element.attrs['role'] === 'banner') return true\n current = element.parent\n }\n return false\n}\n\nconst DAY_NAMES = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n 'mon',\n 'tue',\n 'wed',\n 'thu',\n 'fri',\n 'sat',\n 'sun',\n]\n\n/**\n * Day-name / `HH:MM` adjacency, the §3.5 pass-1 signal, reused here as the\n * visible-text source for `hours`. \"Adjacent\" is: a day name and a clock time\n * within 40 characters of each other in the same text node.\n */\nexport function hasOpeningHoursShape(text: string): boolean {\n const lowered = text.toLowerCase()\n for (const day of DAY_NAMES) {\n let at = lowered.indexOf(day)\n while (at !== -1) {\n const window = lowered.slice(at, at + 40)\n if (/\\d{1,2}[:.]\\d{2}/.test(window) || /\\d{1,2}\\s?(am|pm)/.test(window)) return true\n at = lowered.indexOf(day, at + day.length)\n }\n }\n return false\n}\n\nfunction extractStructures(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (!hasOpeningHoursShape(node.text)) continue\n push({ kind: 'hours', normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'address') {\n const normalized = normalizeFactValue('address', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'address', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n }\n\n const qa = firstQuestionAnswer(doc)\n if (qa !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'html-text', offset: qa, qualified: false })\n }\n}\n\nconst HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n/**\n * The §3.5 `question-answer` shapes: a `<dt>`/`<dd>` pair, a\n * `<details><summary>`, or a heading ending in `?` followed by a paragraph.\n * Counted ONCE as present, not per item — a page with 40 questions is not four\n * times better than a page with 10, and the offset returned is the first shape's.\n */\nfunction firstQuestionAnswer(doc: HtmlDocument): number | null {\n let sawDt = false\n let pendingQuestionHeading = false\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'dt') {\n sawDt = true\n continue\n }\n if (element.tag === 'dd' && sawDt) return element.offset\n if (element.tag === 'details') {\n for (const child of doc.elements) {\n if (child.parent === element.index && child.tag === 'summary') return element.offset\n }\n continue\n }\n if (HEADING_TAGS.has(element.tag)) {\n pendingQuestionHeading = elementText(doc, element.index).trim().endsWith('?')\n continue\n }\n if (element.tag === 'p' && pendingQuestionHeading) return element.offset\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Plain-text / markdown extraction\n// ---------------------------------------------------------------------------\n\nconst MARKDOWN_LINK_RE = /\\[([^\\]\\n]{1,120})\\]\\(([^)\\s]{1,500})\\)/g\n\n/**\n * Extraction from a NEGOTIATED representation — markdown or plain text. Offsets\n * are UTF-8 byte offsets into the body, computed once per hit rather than by\n * scanning the whole body, so a 2 MiB markdown file does not become quadratic.\n *\n * The source is recorded as `negotiated` for everything found here, which is\n * what lets a fact stated in markdown corroborate the same fact in the HTML's\n * JSON-LD: two distinct sources, one value.\n */\nfunction extractFromPlainText(\n representation: ArsRepresentation,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const body = representation.body\n const offsetOf = (index: number): number => utf8Length(body.slice(0, index))\n\n // Title: the first ATX heading, with a wrapping markdown link unwrapped —\n // `render-md` emits `# [Alpine Trail Pack 28L](https://…)`.\n const heading = /^#{1,6}[ \\t]+(.+)$/m.exec(body)\n if (heading !== null && heading[1] !== undefined) {\n const linked = /^\\[([^\\]]+)\\]\\([^)]*\\)\\s*$/.exec(heading[1].trim())\n const raw = linked !== null && linked[1] !== undefined ? linked[1] : heading[1]\n const normalized = normalizeFactValue('title', raw, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'negotiated', offset: offsetOf(heading.index), qualified: false })\n }\n }\n\n for (const labelled of readLabelledLines(body)) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({ kind: labelled.kind, normalized: normalized.value, source: 'negotiated', offset: offsetOf(labelled.index), qualified: normalized.qualified })\n // A labelled price also states its currency.\n if (labelled.kind === 'price' && normalized.value !== UNPRICED) {\n const code = normalized.value.slice(0, 3)\n push({ kind: 'currency', normalized: code, source: 'negotiated', offset: offsetOf(labelled.index), qualified: false })\n }\n }\n\n for (const money of findMoneyPhrases(body)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({ kind: 'price', normalized: normalizeMoney(parsed.amount, parsed.currency), source: 'negotiated', offset: offsetOf(money.index), qualified: parsed.qualified })\n push({ kind: 'currency', normalized: parsed.currency, source: 'negotiated', offset: offsetOf(money.index), qualified: false })\n }\n\n const lowered = body.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'negotiated', offset: 0, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind: 'availability', normalized: token, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n for (const [kind, markers] of TEXT_PRESENCE_MARKERS) {\n for (const phrase of markers) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind, normalized: DECLARED, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n }\n if (hasOpeningHoursShape(body)) {\n push({ kind: 'hours', normalized: DECLARED, source: 'negotiated', offset: 0, qualified: false })\n }\n\n // Markdown links: the primary action, and the repeated-item block.\n const itemLinks = new Set<string>()\n let firstItemOffset = 0\n let match: RegExpExecArray | null\n MARKDOWN_LINK_RE.lastIndex = 0\n while ((match = MARKDOWN_LINK_RE.exec(body)) !== null) {\n const text = match[1] ?? ''\n const href = match[2] ?? ''\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n if (matchesLexicon(text, context.ruleset.actionLexicon)) {\n push({ kind: 'primary-action-url', normalized: absolute, source: 'negotiated', offset: offsetOf(match.index), qualified: false })\n }\n if (absolute.startsWith(context.origin) && !itemLinks.has(absolute)) {\n if (itemLinks.size === 0) firstItemOffset = offsetOf(match.index)\n itemLinks.add(absolute)\n }\n }\n if (itemLinks.size >= MIN_REPEATED_ITEMS) {\n push({ kind: 'item-count', normalized: String(itemLinks.size), source: 'negotiated', offset: firstItemOffset, qualified: false })\n push({ kind: 'item-link', normalized: DECLARED, source: 'negotiated', offset: firstItemOffset, qualified: false })\n }\n\n // A question/answer shape in markdown: a heading that ends in `?`.\n const question = /^#{1,6}[ \\t]+.*\\?[ \\t]*$/m.exec(body)\n if (question !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'negotiated', offset: offsetOf(question.index), qualified: false })\n }\n}\n\n// ---------------------------------------------------------------------------\n// robots.txt\n// ---------------------------------------------------------------------------\n\nexport interface RobotsGroup {\n /** Lowercased user-agent tokens this group applies to. */\n readonly agents: readonly string[]\n readonly allow: readonly string[]\n readonly disallow: readonly string[]\n}\n\nexport interface RobotsFile {\n readonly groups: readonly RobotsGroup[]\n readonly sitemaps: readonly string[]\n /** Lines that are neither blank, a comment, nor a `field: value` pair. */\n readonly malformedLines: number\n /** Directives that appeared before any `User-agent:` line — the classic authoring bug. */\n readonly orphanRules: number\n}\n\n/**\n * RFC 9309 robots.txt, in the subset ARS reads. Deliberately small: we consume\n * `User-agent`, `Allow`, `Disallow` and `Sitemap`, count what we could not\n * parse, and ignore everything else. `Crawl-delay` is honoured by the PROBE, not\n * by the score — waiting longer is not worse markup.\n */\nexport function parseRobots(text: string): RobotsFile {\n /** Mutable while parsing; the exported shape is the readonly one. */\n interface MutableGroup {\n agents: string[]\n allow: string[]\n disallow: string[]\n }\n\n const groups: MutableGroup[] = []\n const sitemaps: string[] = []\n let malformedLines = 0\n let orphanRules = 0\n\n let current: MutableGroup | null = null\n /**\n * True while consecutive `User-agent:` lines are still accumulating into one\n * group. RFC 9309 §2.2.1: adjacent user-agent lines share the rules that\n * follow them; the first rule line closes the group to further agents.\n */\n let openingGroup = false\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const withoutComment = rawLine.split('#')[0] ?? ''\n const line = withoutComment.trim()\n if (line.length === 0) continue\n const colon = line.indexOf(':')\n if (colon <= 0) {\n malformedLines++\n continue\n }\n const field = line.slice(0, colon).trim().toLowerCase()\n const value = line.slice(colon + 1).trim()\n\n if (field === 'user-agent') {\n if (current === null || !openingGroup) {\n current = { agents: [], allow: [], disallow: [] }\n groups.push(current)\n openingGroup = true\n }\n current.agents.push(value.toLowerCase())\n continue\n }\n if (field === 'sitemap') {\n sitemaps.push(value)\n continue\n }\n if (field === 'allow' || field === 'disallow') {\n if (current === null) {\n orphanRules++\n continue\n }\n openingGroup = false\n if (field === 'allow') current.allow.push(value)\n else current.disallow.push(value)\n continue\n }\n if (field === 'crawl-delay' || field === 'host' || field === 'clean-param') continue\n malformedLines++\n }\n\n return { groups, sitemaps, malformedLines, orphanRules }\n}\n\n/**\n * RFC 9309 group selection: the most specific matching `User-agent` wins, `*` is\n * the fallback, and matching is case-insensitive. Returns the decision plus the\n * group and rule that produced it, because `ArsAudienceDecision` publishes both —\n * a merchant who disagrees with an `opt-out` verdict gets to see the line.\n */\nexport function decideRobots(\n robots: RobotsFile,\n tokens: readonly string[],\n path: string,\n): ArsAudienceDecision {\n let bestGroup: RobotsGroup | null = null\n let bestAgent: string | null = null\n let bestSpecificity = -1\n\n for (const group of robots.groups) {\n for (const agent of group.agents) {\n const specificity = agent === '*' ? 0 : matchesToken(agent, tokens) ? agent.length : -1\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity\n bestGroup = group\n bestAgent = agent\n }\n }\n }\n\n if (bestGroup === null || bestAgent === null) {\n return { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n }\n\n // Longest-match wins between Allow and Disallow; a tie goes to Allow (RFC 9309 §2.2.2).\n let bestRule: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of bestGroup.allow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'allow', value }\n }\n }\n for (const value of bestGroup.disallow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'disallow', value }\n }\n }\n\n if (bestRule === null) {\n return { decision: 'allow', matchedGroup: bestAgent, matchedRule: null }\n }\n return {\n decision: bestRule.field === 'allow' ? 'allow' : 'disallow',\n matchedGroup: bestAgent,\n matchedRule: `${bestRule.field === 'allow' ? 'Allow' : 'Disallow'}: ${bestRule.value}`,\n }\n}\n\nfunction matchesToken(agent: string, tokens: readonly string[]): boolean {\n const lowered = agent.toLowerCase()\n return tokens.some((token) => token.toLowerCase() === lowered)\n}\n\n/**\n * Path matching with `*` and `$`, done as a bounded scan rather than a compiled\n * regex: a robots.txt is attacker-controlled input and\n * `new RegExp(pathFromTheInternet)` is a denial-of-service primitive.\n */\nexport function pathMatches(pattern: string, path: string): boolean {\n if (pattern === '') return false\n const anchored = pattern.endsWith('$')\n const body = anchored ? pattern.slice(0, -1) : pattern\n const segments = body.split('*')\n\n let cursor = 0\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i] ?? ''\n if (i === 0) {\n if (!path.startsWith(segment)) return false\n cursor = segment.length\n continue\n }\n if (segment === '') continue\n const at = path.indexOf(segment, cursor)\n if (at === -1) return false\n cursor = at + segment.length\n }\n if (anchored) {\n const last = segments[segments.length - 1] ?? ''\n return segments.length === 1 ? path === body : path.endsWith(last)\n }\n return true\n}\n\n/** Every audience decision plus the derived policy flags. Pure over a parsed robots file. */\nexport function buildPolicyReport(\n robots: RobotsFile | null,\n status: ArsPolicyReport['robotsTxtStatus'],\n ruleset: ArsRuleset,\n path: string,\n): ArsPolicyReport {\n const empty: ArsAudienceDecision = { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n const audiences: Record<ArsAudience, ArsAudienceDecision> = {\n assistant: empty,\n training: empty,\n search: empty,\n }\n if (robots !== null) {\n for (const audience of ['assistant', 'training', 'search'] as const) {\n audiences[audience] = decideRobots(robots, ruleset.audienceTokens[audience], path)\n }\n }\n\n return {\n robotsTxtStatus: status,\n audiences,\n // A deliberate opt-out requires a group that NAMES an assistant token.\n // Consent has to be specific: a blanket `User-agent: *` disallow is the\n // accidental case (§3.7) and is scored, not excused.\n deliberateOptOut:\n robots !== null &&\n audiences.assistant.decision === 'disallow' &&\n audiences.assistant.matchedGroup !== '*' &&\n robots.malformedLines === 0 &&\n robots.orphanRules === 0,\n trainingOptOut: audiences.training.decision === 'disallow',\n sitemapDeclared: robots !== null && robots.sitemaps.length > 0,\n }\n}\n","/**\n * robots-policy.ts — the refusal token and the one function that decides\n * whether a site has refused us.\n *\n * WHY THIS IS ITS OWN MODULE RATHER THAN A PRIVATE FUNCTION IN `./probe`.\n *\n * There is now more than one probe. The Node probe fetches over the network; a\n * browser extension probes from inside a page the user is already looking at,\n * and cannot import `./probe` at all (that module carries a connection limiter\n * and DNS-level SSRF guards that have no meaning and no implementation in a\n * browser). Both must answer \"has this origin refused us?\" identically, because\n * a refusal honoured by one scanner and ignored by another is not a policy, it\n * is a coin flip — and the one being ignored is always the one a site operator\n * actually wrote down.\n *\n * So the decision lives here, at the bottom of the import graph, beside the\n * token it matches on. Pure, no clock, no network, safe under this package's\n * purity rule (`eslint.config.mjs`) and therefore usable from any runtime.\n */\nimport { parseRobots, pathMatches } from './extract'\n\n/**\n * The robots.txt token this scanner answers to. Matched case-insensitively.\n *\n * IT IS NOT VERSIONED, DELIBERATELY. A site that disallowed us under ARS 0.1 is\n * still refusing us under 0.2. Versioning the refusal token would let a spec\n * bump quietly re-open sites that already said no.\n */\nexport const ARS_ROBOTS_TOKEN = 'rebilder-ars'\n\n/**\n * Has this origin refused this path, by name? Returns the matching rule as a\n * human-readable string, or `null` when it has not.\n *\n * ONLY A GROUP THAT NAMES THE TOKEN COUNTS. A blanket `User-agent: *` disallow\n * is not a decision about us — it is the accidental case, which §3.7 scores with\n * a `robots-contradiction` flag rather than treating as consent or as refusal.\n * Reading a generic bot block as a refusal would also make the honest thing\n * (asking first) indistinguishable from the useless thing (refusing to look at\n * most of the web), and a scanner nobody can run is not a safer scanner.\n *\n * Rule selection uses `pathMatches`, the same matcher the scorer uses, so the\n * fetch gate and the published audience decision can never disagree about what\n * a pattern means. Longest match wins, `allow` beating `disallow` at equal\n * length by virtue of being tested first.\n */\nexport function robotsDisallowsScanner(robotsBody: string, path: string): string | null {\n const robots = parseRobots(robotsBody)\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent.toLowerCase() === ARS_ROBOTS_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${ARS_ROBOTS_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n","/**\n * The two request identities the standard is defined in terms of, in a leaf\n * module so a browser can import them without pulling in the Node probe.\n *\n * D2.4 IS THE REASON THESE ARE NORMATIVE. It compares what an origin serves an\n * agent against what it serves a browser, and the comparison is only meaningful\n * because the two requests differ in exactly one header. A probe that invents\n * its own `Accept` strings is measuring a different thing and reporting it under\n * the same name — which is worse than not measuring it, because the number still\n * looks like an ARS number.\n */\nexport const AGENT_ACCEPT = 'text/markdown;q=1.0, text/html;q=0.8, text/plain;q=0.5, */*;q=0.1'\nexport const BROWSER_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'\nexport const ASSET_ACCEPT = 'text/plain,*/*;q=0.5'\n","/**\n * score.ts — the ARS 0.3 scoring engine. The whole pure half comes together here.\n *\n * THE CONTRACT. `score(evidence, ruleset)` is a pure function: same evidence,\n * same ruleset, same `ArsResult`, byte for byte, in any conformant\n * implementation in any language. No network, no clock, no randomness, no LLM.\n * The ESLint rule in `eslint.config.mjs` enforces the first three at build time;\n * the fourth has nowhere to hide, because there is no model call anywhere in this\n * package.\n *\n * INTEGER ARITHMETIC ONLY (§3.6). Every number below is produced by `idiv` /\n * `divRoundHalfUp`, never by `/` on values that do not divide, and never by\n * `Math.round`. Cross-language conformance is impossible with float rounding\n * drift, and publishing a standard whose scores differ in the third\n * implementation would be worse than publishing nothing. All inputs are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator`.\n *\n * FIXED WEIGHTS. 100 points for every page, whatever its kind. What varies by\n * page kind is the fact set and the byte reference (`./profiles`) — never a\n * weight. Redistribution would be a gaming vector: make the dimension you are bad\n * at inapplicable and everything else inflates.\n *\n * TWO GATES EXIST, AND THEY POINT THE SAFE WAY. D2.3 (`Vary: Accept`) and D2.4\n * (substance parity) are gated on D2.1 (a machine representation was served),\n * which is a MEASURED check gating others. That direction is fine and is what\n * makes the published ceiling provable: no content negotiation loses D2.1 (9) +\n * D2.3 (3) + D2.4 (3) → max 85 → capped at B. The forbidden direction — a\n * heuristic that can zero measured points — appears nowhere. In particular D2.4\n * and D5.3 are SCORED CHECKS, NOT GATES: a parity failure loses its own 3 points\n * and raises a `warn`, and leaves D2's other 15 measured points alone. That is\n * the whole reason \"measured 63 / heuristic 37\" is an honest split rather than a\n * presentational one.\n *\n * EVIDENCE IS WRITTEN FOR THE SITE OWNER. Labels, values, remedies and flag\n * messages are printed on the public scan page, so they use plain words and name\n * a header or file only where a developer needs it to act. \"Content\n * negotiation\" in particular is written as what it means to a merchant: the\n * page sends AI assistants a Markdown copy when they ask for one. None of this\n * text is in the conformance projection, so rewording it is a PATCH.\n *\n * WHICH REPRESENTATION SCORES WHAT (the decision `./extract` states in its own\n * header, repeated here because it is the reason the golden pair means anything):\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. D1.3 (render independence) and D5\n * (structured data) score the representation that carries a document, because\n * those checks are about the HTML a caller that only reads HTML gets.\n *\n * MEASURED CHECKS NEVER AWARD POINTS FOR AN OBSERVATION WE DID NOT MAKE. When\n * the browser probe is missing, the sub-conditions that compare the two probes\n * (D1.1's \"no Accept-conditional redirect\", D6.1's \"self-consistent\") score 0 and\n * say so in their evidence. Awarding them by default would make a measured check\n * heuristic; deducting them silently would be unexplained. The evidence line is\n * the difference.\n *\n * WHAT LIVES IN THE RULESET AND WHAT LIVES HERE. `DEFAULT_RULESET.thresholds`\n * holds exactly the §3.6 numeric tables (density, context cost, offsets, front\n * window). The remaining checks are conjunctions of named conditions rather than\n * bands, and their point splits are `SUBPOINTS` below: published, frozen, and —\n * like the classification tables in `./classify` — NOT covered by `rulesetHash`,\n * because §3.9's `ArsRuleset` has no field for them. That gap is recorded in the\n * package README as a known limitation of 0.1 rather than papered over.\n */\n\nimport { classify, isRecognisedType, nodeForKind, pass1Signals } from './classify'\nimport type { ArsClassification } from './classify'\nimport {\n buildPolicyReport,\n buildRepresentation,\n extractFacts,\n hasPath,\n header,\n headerAll,\n mergeFacts,\n parseRobots,\n pathMatches,\n readPath,\n} from './extract'\nimport type {\n ArsRepresentation,\n ExtractedFact,\n JsonLdNode,\n MergedFact,\n RobotsFile,\n} from './extract'\nimport { attr, elementText } from './html'\nimport { profileFor } from './profiles'\nimport { recommend } from './recommend'\nimport { CHECK_META, DEFAULT_RULESET, DIMENSION_META } from './ruleset'\nimport type {\n ArsAudience,\n ArsBand,\n ArsBasis,\n ArsCheck,\n ArsCheckEvidence,\n ArsCheckId,\n ArsCostReport,\n ArsDimension,\n ArsDimensionId,\n ArsEvidence,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsFlag,\n ArsFlagId,\n ArsGrade,\n ArsHttpCapture,\n ArsOutcome,\n ArsPolicyReport,\n ArsProbeRecord,\n ArsResult,\n ArsRuleset,\n ArsUnscoredReason,\n} from './types'\nimport { ARS_SPEC_VERSION } from './types'\n\n// ---------------------------------------------------------------------------\n// Integer arithmetic (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * Exact integer division for non-negative safe integers. `%` is exact, the\n * subtraction is exact, and dividing by an exact multiple is exact, so this\n * never rounds — unlike `Math.floor(a / b)`, whose intermediate quotient is an\n * IEEE-754 double that can land on the wrong side of an integer boundary. A\n * scoring path that is \"almost always\" the same in two languages is not a\n * standard.\n */\nfunction idiv(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return (numerator - (numerator % denominator)) / denominator\n}\n\n/** §3.6's half-up rounding, `(numerator + denominator / 2) / denominator`, in integers. */\nfunction divRoundHalfUp(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return idiv(numerator + idiv(denominator, 2), denominator)\n}\n\n/**\n * AT-LEAST table lookup: flat `[threshold, value]` pairs in DESCENDING threshold\n * order; the first pair whose `threshold <= input` wins. No match scores 0, which\n * can only happen if a ruleset omits the table — a malformed ruleset must not\n * silently invent points.\n */\nfunction atLeast(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input >= threshold) return value\n }\n return 0\n}\n\n/**\n * AT-MOST table lookup: flat `[threshold, value]` pairs in ASCENDING threshold\n * order; the first pair whose `input <= threshold` wins; no match scores 0.\n */\nfunction atMost(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input <= threshold) return value\n }\n return 0\n}\n\n/** Recursively freezes a plain data structure. Used on `SUBPOINTS`. */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Sub-point splits\n// ---------------------------------------------------------------------------\n\n/**\n * The point split inside each check that scores a CONJUNCTION of named\n * conditions rather than a numeric band. §3.4 states the conditions (\"D1.1 2xx on\n * the agent path, ≤3 hops, no Accept-conditional redirect\"); this is how the\n * check's points are divided between them, and every split sums to the check's\n * weight in `DEFAULT_RULESET.weights`.\n *\n * Published here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has\n * no field for them. The consequence is stated rather than hidden: these numbers\n * are NOT covered by `rulesetHash`, exactly like the classification tables in\n * `./classify`. Editing one moves conformance `expected.json` files and is\n * therefore a MINOR, and the corpus is what actually pins them.\n */\n/**\n * The per-check point splits.\n *\n * THESE MUST SUM TO `WEIGHTS`, and until ARS 0.2 nothing said so. The ruleset\n * carried the same numbers twice, here and in `WEIGHTS`, with fixture `052`\n * checking only that `DIMENSION_META` agreed with `WEIGHTS`. Rebalancing for\n * 0.2 changed `WEIGHTS` alone and every check kept emitting 0.1's points, so\n * the corpus re-scored with dimensions claiming 28 while their checks could\n * only pay 20. `subpointTotals()` below closes that, and `score.test.ts`\n * asserts the two tables agree check by check.\n */\nexport const SUBPOINTS = deepFreeze({\n /** D1.1, 11 = 5 + 3 + 3. */\n reachable: { status2xx: 5, withinRedirectLimit: 3, noAcceptConditionalRedirect: 3 },\n /** D1.2, 10 = 6 + 2 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */\n robotsPolicy: { assistantAllowed: 6, parsesClean: 2, noOrphanRules: 1, sitemapDeclared: 1 },\n /**\n * D1.3, 7. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus\n * the `<noscript>` floor: a page whose facts are all client-rendered but which\n * ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8\n * says that earns partial credit.\n */\n renderIndependence: {\n band: [100, 7, 75, 5, 50, 3, 25, 1] as readonly number[],\n noscriptFloor: 1,\n },\n /**\n * D2.1, 9 for a machine copy served at the page's own address on `Accept`\n * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6\n * when the page does not negotiate but the Markdown copy it declares as an\n * alternate was fetched and is real. Less than full because only agents that\n * look for the link reach it, and they pay a second request to do so.\n */\n negotiatedResponse: { full: 9, linkedCopy: 6 },\n /** D2.2, 3. All-or-nothing. */\n declaredAlternates: { full: 3 },\n /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */\n varyAccept: { full: 3 },\n /** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */\n substanceParity: { full: 3 },\n /** D5.1, 2. Structured data present AND parsing; a partly-broken graph scores 1. */\n structuredDataPresent: { clean: 2, partial: 1 },\n /** D5.2, 3 = 1 (a recognised type) + 2 (required-property completeness, scaled). */\n requiredProperties: { recognisedType: 1, completeness: 2 },\n /** D5.3, 1. All-or-nothing. */\n textAgreement: { full: 1 },\n /** D6.1, 4 = 2 + 1 + 1. */\n canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },\n /** D6.2, 2 = 1 + 1. */\n cacheValidators: { saneCacheControl: 1, validator: 1 },\n /**\n * D6.3, 1. `specShaped` — an H1 and at least one Markdown link — is the whole\n * point. `present` is 0 in 0.2: at two points 0.1 could pay one for the file\n * existing and one for it being usable, but at one point that split would make\n * \"exists\" and \"usable\" score identically, which is a distinction the standard\n * would then be printing a remedy for and paying nothing to fix.\n */\n llmsTxt: { present: 0, specShaped: 1 },\n /** D6.4, 1. All-or-nothing. */\n sitemap: { full: 1 },\n /** D6.5, 2. All-or-nothing over any ONE declared machine endpoint. */\n machineEndpoint: { full: 2 },\n})\n\n/**\n * The maximum each SUBPOINTS entry can pay, for the agreement assertion. A band\n * pays its highest value; `structuredDataPresent` and `llmsTxt` are graded, so\n * the best branch is the max, not the sum.\n */\nexport function subpointTotals(): Record<string, number> {\n const s = SUBPOINTS\n return {\n 'retrievability.reachable':\n s.reachable.status2xx + s.reachable.withinRedirectLimit + s.reachable.noAcceptConditionalRedirect,\n 'retrievability.robots-policy':\n s.robotsPolicy.assistantAllowed +\n s.robotsPolicy.parsesClean +\n s.robotsPolicy.noOrphanRules +\n s.robotsPolicy.sitemapDeclared,\n 'retrievability.render-independence': s.renderIndependence.band[1] ?? 0,\n 'machine-representation.negotiated-response': s.negotiatedResponse.full,\n 'machine-representation.declared-alternates': s.declaredAlternates.full,\n 'machine-representation.vary-accept': s.varyAccept.full,\n 'machine-representation.substance-parity': s.substanceParity.full,\n 'structured-data.present': s.structuredDataPresent.clean,\n 'structured-data.required-properties':\n s.requiredProperties.recognisedType + s.requiredProperties.completeness,\n 'structured-data.text-agreement': s.textAgreement.full,\n 'contract-discovery.canonical':\n s.canonical.present + s.canonical.absolute + s.canonical.consistentAcrossProbes,\n 'contract-discovery.cache-validators': s.cacheValidators.saneCacheControl + s.cacheValidators.validator,\n 'contract-discovery.llms-txt': s.llmsTxt.specShaped,\n 'contract-discovery.sitemap': s.sitemap.full,\n 'contract-discovery.machine-endpoint': s.machineEndpoint.full,\n }\n}\n\n// ---------------------------------------------------------------------------\n// SHA-256 and RFC 8785 canonical JSON\n// ---------------------------------------------------------------------------\n\n/**\n * WHY A HAND-ROLLED SHA-256 LIVES IN THE PURE HALF. `ArsResult` carries three\n * hashes and the determinism guarantee is stated in terms of them, so `score()`\n * has to compute two of them. `node:crypto` would make this package Node-only,\n * and browser and edge callers import the root entry point; `crypto.subtle` is async\n * and `score()` is not. A dependency is out — the package's contract is zero\n * runtime dependencies, and a third-party hash version would be an unversioned\n * input to a hashed artifact, which is the same argument that made the tokenizer\n * hand-rolled. So: ~80 lines of FIPS 180-4, checked against the published test\n * vectors in `tests/score.test.ts`.\n */\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]\n\nfunction rotr(value: number, bits: number): number {\n return ((value >>> bits) | (value << (32 - bits))) >>> 0\n}\n\n/** SHA-256 of a UTF-8 string, lowercase hex. FIPS 180-4. */\nexport function sha256Hex(message: string): string {\n const bytes = new TextEncoder().encode(message)\n const bitLength = bytes.length * 8\n // Padded length: message + 0x80 + zeros + 8 length bytes, to a 64-byte multiple.\n const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64)\n padded.set(bytes)\n padded[bytes.length] = 0x80\n // Length as a 64-bit big-endian bit count. Bodies are capped at 2 MiB, so the\n // high word is always zero; it is written anyway so the routine is correct for\n // any input a caller hands it.\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 8, idiv(bitLength, 0x100000000), false)\n view.setUint32(padded.length - 4, bitLength >>> 0, false)\n\n const h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]\n const w = new Uint32Array(64)\n\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false)\n for (let i = 16; i < 64; i++) {\n const a = w[i - 15] ?? 0\n const b = w[i - 2] ?? 0\n const s0 = (rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3)) >>> 0\n const s1 = (rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10)) >>> 0\n w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0\n }\n\n let [a, b, c, d, e, f, g, hh] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ]\n for (let i = 0; i < 64; i++) {\n const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0\n const ch = ((e & f) ^ (~e & g)) >>> 0\n const temp1 = (hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0)) >>> 0\n const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0\n const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0\n const temp2 = (s0 + maj) >>> 0\n hh = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n const next = [a, b, c, d, e, f, g, hh]\n for (let i = 0; i < 8; i++) h[i] = ((h[i] ?? 0) + (next[i] ?? 0)) >>> 0\n }\n\n let hex = ''\n for (const word of h) hex += word.toString(16).padStart(8, '0')\n return hex\n}\n\n/**\n * RFC 8785 (JCS) canonical JSON, over the value shapes ARS actually hashes:\n * objects, arrays, strings, booleans, null and JSON numbers.\n *\n * Two details make this RFC-conformant rather than merely deterministic:\n * object keys are sorted by UTF-16 code unit (JCS §3.2.3, which is what\n * JavaScript's default string comparison already does), and numbers are\n * serialised with `JSON.stringify`, whose output is the ECMAScript\n * `Number::toString` shortest round-trip form that JCS §3.2.2.3 mandates.\n * `undefined` and functions cannot appear in the data we hash and are dropped.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null'\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined)\n keys.sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\n/** SHA-256 of the RFC 8785 canonical JSON of the frozen ruleset (§3.1). */\nexport function rulesetHash(ruleset: ArsRuleset): string {\n return sha256Hex(canonicalJson(ruleset))\n}\n\n/**\n * Headers excluded from `evidenceHash` (§3.3). Without this exclusion the hash\n * changes on every scan of every real site — `date` alone guarantees it — and the\n * replay story, which is the only reason the hash is published, dies.\n */\nconst VOLATILE_HEADERS: ReadonlySet<string> = new Set([\n 'date',\n 'age',\n 'set-cookie',\n 'x-request-id',\n 'cf-ray',\n 'report-to',\n])\n\nfunction stableHeaders(\n headers: Readonly<Record<string, readonly string[]>>,\n): Record<string, readonly string[]> {\n const out: Record<string, readonly string[]> = {}\n for (const [name, values] of Object.entries(headers)) {\n if (VOLATILE_HEADERS.has(name.toLowerCase())) continue\n out[name.toLowerCase()] = values\n }\n return out\n}\n\n/**\n * SHA-256 over the evidence bundle with the volatile fields removed: the header\n * denylist above, and `capturedAt`, which is wall-clock time and is never an\n * input to scoring. Bodies ARE hashed — `bodySha256` is already in the capture,\n * but hashing the body itself means a bundle whose body was edited without\n * updating its digest does not silently keep its identity.\n */\nexport function evidenceHash(evidence: ArsEvidence): string {\n const redactProbe = (probe: ArsProbeRecord | null): unknown => {\n if (probe === null) return null\n if (!probe.result.ok) return { requestHeaders: probe.requestHeaders, result: probe.result }\n const capture = probe.result.capture\n return {\n requestHeaders: probe.requestHeaders,\n result: {\n ok: true,\n capture: { ...capture, headers: stableHeaders(capture.headers) },\n },\n }\n }\n return sha256Hex(\n canonicalJson({\n evidenceVersion: evidence.evidenceVersion,\n target: evidence.target,\n vantage: evidence.vantage,\n probes: {\n agent: redactProbe(evidence.probes.agent),\n browser: redactProbe(evidence.probes.browser),\n parityConfirm: redactProbe(evidence.probes.parityConfirm),\n robotsTxt: redactProbe(evidence.probes.robotsTxt),\n llmsTxt: redactProbe(evidence.probes.llmsTxt),\n wellKnownUcp: redactProbe(evidence.probes.wellKnownUcp),\n // ARS 0.3, and only when present, so a 0.2 bundle hashes as it did.\n ...(evidence.probes.markdownAlternate === undefined\n ? {}\n : { markdownAlternate: redactProbe(evidence.probes.markdownAlternate) }),\n },\n }),\n )\n}\n\n/**\n * Version marker for the ARS 0.3 corpus (spec §2.4.3).\n * This is the hash of the versioned marker string, not of fixture contents.\n * A corpus-content digest replaces it at corpus freeze in a MINOR release.\n */\nexport const ARS_CORPUS_HASH = sha256Hex('ars-0.3-corpus-unfrozen')\n\n// ---------------------------------------------------------------------------\n// Header helpers\n// ---------------------------------------------------------------------------\n\n/** One entry of a `Link` header: the target IRI plus the parameters ARS reads. */\ninterface ParsedLink {\n readonly url: string\n readonly rel: readonly string[]\n readonly type: string | null\n}\n\n/**\n * Parses `Link` header values (RFC 8288) in the subset ARS scores: the target\n * IRI, `rel` as a token list, and `type`.\n *\n * Written as a scanner because the separator is a comma and target IRIs contain\n * commas — `<https://x/a,b>; rel=\"alternate\"` is one link, not two. Splitting on\n * `,` would silently drop half of the alternates a merchant declared and cost\n * them 4 points on D2.2.\n */\nexport function parseLinkHeaders(values: readonly string[]): ParsedLink[] {\n const out: ParsedLink[] = []\n for (const value of values) {\n for (const entry of splitLinkEntries(value)) {\n const open = entry.indexOf('<')\n const close = entry.indexOf('>', open + 1)\n if (open === -1 || close === -1) continue\n const url = entry.slice(open + 1, close).trim()\n if (url.length === 0) continue\n let rel: string[] = []\n let type: string | null = null\n for (const param of entry.slice(close + 1).split(';')) {\n const equals = param.indexOf('=')\n if (equals === -1) continue\n const name = param.slice(0, equals).trim().toLowerCase()\n const raw = param.slice(equals + 1).trim()\n const unquoted = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw\n if (name === 'rel')\n rel = unquoted\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n else if (name === 'type') type = unquoted.trim().toLowerCase()\n }\n out.push({ url, rel, type })\n }\n }\n return out\n}\n\n/** Splits on commas that are outside `<…>` and outside a quoted string. */\nfunction splitLinkEntries(value: string): string[] {\n const entries: string[] = []\n let depth = 0\n let quoted = false\n let start = 0\n for (let i = 0; i < value.length; i++) {\n const char = value.charAt(i)\n if (quoted) {\n if (char === '\"') quoted = false\n continue\n }\n if (char === '\"') quoted = true\n else if (char === '<') depth++\n else if (char === '>') depth = depth > 0 ? depth - 1 : 0\n else if (char === ',' && depth === 0) {\n entries.push(value.slice(start, i))\n start = i + 1\n }\n }\n entries.push(value.slice(start))\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0)\n}\n\n/** Comma/space-separated header token list, lowercased. */\nfunction headerTokens(value: string | null): string[] {\n if (value === null) return []\n return value\n .toLowerCase()\n .split(/[,\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Scoring context\n// ---------------------------------------------------------------------------\n\n/** Everything the 22 checks read, computed exactly once. */\n/** The Markdown copy a page links to, as the probe found it (ARS 0.3). */\ninterface LinkedCopy {\n /** The declared URL the probe should have fetched. */\n readonly url: string\n /** `checked`: fetched and real. `broken`: fetched and not Markdown. `unchecked`: not in the bundle. */\n readonly status: 'checked' | 'broken' | 'unchecked'\n readonly representation: ArsRepresentation | null\n /** Why a broken copy failed, in plain words. */\n readonly reason: string | null\n}\n\ninterface ScoreContext {\n readonly evidence: ArsEvidence\n readonly ruleset: ArsRuleset\n readonly agentCapture: ArsHttpCapture\n readonly browserCapture: ArsHttpCapture | null\n readonly agent: ArsRepresentation\n readonly browser: ArsRepresentation | null\n /** The representation that carries a tokenized document, if either does. */\n readonly structural: ArsRepresentation | null\n readonly classification: ArsClassification\n readonly profile: ArsFactProfile\n readonly facts: readonly MergedFact[]\n readonly agentFacts: readonly ExtractedFact[]\n readonly browserFacts: readonly ExtractedFact[]\n readonly structuralFacts: readonly ExtractedFact[]\n readonly policy: ArsPolicyReport\n readonly robots: RobotsFile | null\n readonly flags: ArsFlag[]\n /** True when the agent probe itself received a machine copy (negotiation). */\n readonly negotiated: boolean\n /** The declared Markdown copy, when the page links to one and does not negotiate. */\n readonly linkedCopy: LinkedCopy | null\n}\n\ninterface CheckOutcome {\n readonly earned: number\n readonly evidence: ArsCheckEvidence[]\n readonly remedy?: string\n}\n\nconst YES = 'yes'\nconst NO = 'no'\nconst yesNo = (value: boolean): string => (value ? YES : NO)\n\nfunction measured(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'measured' }\n}\n\nfunction heuristic(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'heuristic' }\n}\n\n/**\n * Plain names for fact kinds, for evidence and remedies a site owner reads. The\n * kind ids stay the published vocabulary; this is only how they are printed.\n */\nconst FACT_NAMES: Readonly<Record<ArsFactKind, string>> = {\n title: 'name or title',\n description: 'description',\n updated: 'last-updated date',\n published: 'publish date',\n price: 'price',\n currency: 'currency',\n availability: 'availability',\n brand: 'brand',\n sku: 'SKU',\n shipping: 'shipping details',\n returns: 'returns policy',\n 'org-name': 'business name',\n address: 'address',\n hours: 'opening hours',\n phone: 'phone number',\n email: 'email address',\n 'service-area': 'service area',\n author: 'author',\n section: 'section',\n authority: 'publisher',\n 'primary-action-url': 'main action link (such as Buy, Book, Contact or Install)',\n eligibility: 'eligibility',\n duration: 'duration',\n 'question-answer': 'questions and answers',\n 'item-count': 'number of items',\n 'item-link': 'links to the items',\n}\n\nfunction factName(kind: ArsFactKind): string {\n return FACT_NAMES[kind] ?? kind\n}\n\nfunction factList(kinds: readonly ArsFactKind[]): string {\n return kinds.map(factName).join(', ')\n}\n\n/**\n * Bytes as a reader says them. Integer arithmetic only, so the string is the\n * same in every implementation: under 1 KB prints bytes, above it prints whole\n * kilobytes (1 KB = 1024 bytes), rounded half-up.\n */\nfunction plainBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} bytes`\n return `${divRoundHalfUp(bytes, 1024)} KB`\n}\n\n/** Plain words for a robots.txt status. */\nconst ROBOTS_STATUS: Readonly<Record<ArsPolicyReport['robotsTxtStatus'], string>> = {\n ok: 'found',\n missing: 'not found (nothing is blocked)',\n error: 'the server returned an error',\n unparseable: 'found, but it could not be read',\n}\n\n/** The gated D2 checks' evidence while no Markdown copy is served. */\nconst COUNTS_ONCE_COPY = 'only once the page sends AI assistants a Markdown copy, so 0 for now'\n\n// ---------------------------------------------------------------------------\n// D1 — Retrievability\n// ---------------------------------------------------------------------------\n\nfunction checkReachable(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, ruleset } = context\n const split = SUBPOINTS.reachable\n const status2xx = agentCapture.status >= 200 && agentCapture.status < 300\n const hops = agentCapture.redirects.length\n const withinLimit = hops <= ruleset.maxRedirects\n const sameFinalUrl = browserCapture !== null && browserCapture.finalUrl === agentCapture.finalUrl\n\n const earned =\n (status2xx ? split.status2xx : 0) +\n (withinLimit ? split.withinRedirectLimit : 0) +\n (sameFinalUrl ? split.noAcceptConditionalRedirect : 0)\n\n const evidence = [\n measured('Status code AI assistants got', String(agentCapture.status)),\n measured('Redirects on the way', `${hops} (up to ${ruleset.maxRedirects} allowed)`),\n measured(\n 'Same address for AI assistants and browsers',\n browserCapture === null\n ? 'not checked, because this scan has no browser request to compare'\n : yesNo(sameFinalUrl),\n ),\n ]\n return sameFinalUrl\n ? { earned, evidence }\n : {\n earned,\n evidence,\n remedy:\n 'Send AI assistants and browsers to the same address. A redirect that depends on the Accept header sends assistants to a page browsers never see.',\n }\n}\n\nfunction checkRobotsPolicy(context: ScoreContext): CheckOutcome {\n const { policy, robots } = context\n const split = SUBPOINTS.robotsPolicy\n const decision = policy.audiences.assistant\n const parsesClean = robots === null || robots.malformedLines === 0\n const noOrphanRules = robots === null || robots.orphanRules === 0\n\n const rule =\n decision.matchedGroup === null\n ? ''\n : ` (User-agent: ${decision.matchedGroup}${\n decision.matchedRule === null ? '' : `, ${decision.matchedRule}`\n })`\n const evidence = [\n measured('robots.txt', ROBOTS_STATUS[policy.robotsTxtStatus]),\n measured(\n 'AI assistants allowed',\n decision.decision === 'disallow'\n ? `no${rule}`\n : decision.matchedGroup === null\n ? 'yes, no rule mentions them'\n : `yes${rule}`,\n ),\n measured('Lines that could not be read', robots === null ? 'none' : String(robots.malformedLines)),\n measured(\n 'Rules outside a User-agent group',\n robots === null ? 'none' : String(robots.orphanRules),\n ),\n measured('Sitemap listed', yesNo(policy.sitemapDeclared)),\n measured(\n 'AI training crawlers',\n policy.trainingOptOut ? 'blocked, which does not affect this score' : 'allowed',\n ),\n ]\n\n // §3.7: an accidental or ambiguous assistant disallow — a blanket group, a\n // malformed file — is SCORED, with D1.2 at zero and a `robots-contradiction`\n // warning. It is not an opt-out, because consent has to be specific.\n if (decision.decision === 'disallow') {\n context.flags.push({\n id: 'robots-contradiction',\n severity: 'warn',\n basis: 'measured',\n message:\n 'Your robots.txt blocks AI assistants with a rule written for all crawlers. That looks accidental, and it keeps assistants out.',\n evidence: [evidence[1] ?? measured('AI assistants allowed', 'no')],\n })\n return {\n earned: 0,\n evidence,\n remedy:\n 'Your robots.txt blocks AI assistants with a rule meant for all crawlers. If you want assistants to read your pages, give them their own group that allows them, such as ChatGPT-User and Claude-User.',\n }\n }\n\n const earned =\n split.assistantAllowed +\n (parsesClean ? split.parsesClean : 0) +\n (noOrphanRules ? split.noOrphanRules : 0) +\n (policy.sitemapDeclared ? split.sitemapDeclared : 0)\n\n return {\n earned,\n evidence,\n remedy: policy.sitemapDeclared\n ? undefined\n : 'Add a `Sitemap:` line to robots.txt so assistants can find the rest of your pages.',\n }\n}\n\nfunction checkRenderIndependence(context: ScoreContext): CheckOutcome {\n const { structural, structuralFacts, profile } = context\n const split = SUBPOINTS.renderIndependence\n const coreSize = profile.core.length\n\n if (structural === null || structural.doc === null) {\n return {\n earned: 0,\n evidence: [heuristic('HTML page', 'not checked, because no HTML was returned')],\n }\n }\n\n const found = new Set<ArsFactKind>()\n for (const fact of structuralFacts) if (profile.core.includes(fact.kind)) found.add(fact.kind)\n const ratio = coreSize === 0 ? 0 : idiv(100 * found.size, coreSize)\n\n let noscriptText = ''\n for (const element of structural.doc.elements) {\n if (element.tag !== 'noscript') continue\n noscriptText = elementText(structural.doc, element.index).trim()\n if (noscriptText.length > 0) break\n }\n const hasNoscript = noscriptText.length > 0\n\n const banded = atLeast(split.band, ratio)\n const earned = Math.max(banded, hasNoscript ? split.noscriptFloor : 0)\n const full = atLeast(split.band, 100)\n\n if (ratio < 50) {\n context.flags.push({\n id: 'render-dependent',\n severity: 'info',\n basis: 'heuristic',\n message: `${found.size} of ${coreSize} key facts for this kind of page were in the HTML before any JavaScript ran. An assistant that does not run scripts sees the rest as missing.`,\n evidence: [heuristic('Key facts in the HTML', `${found.size} of ${coreSize}`)],\n })\n }\n\n return {\n earned,\n evidence: [\n heuristic('Key facts in the HTML before JavaScript runs', `${found.size} of ${coreSize}`),\n heuristic('Fallback text for visitors without JavaScript', yesNo(hasNoscript)),\n heuristic(\n 'How we checked',\n 'we read the HTML your server sends and do not run JavaScript, so facts added by scripts count as missing',\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Put the key facts in the HTML your server sends. Most AI assistants do not run JavaScript, so facts added by scripts are invisible to them.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D2 — Machine representation\n// ---------------------------------------------------------------------------\n\n/** Media types that count as a machine representation for D2.1 (§3.4). */\nconst MACHINE_KINDS: ReadonlySet<ArsRepresentation['kind']> = new Set(['markdown', 'text', 'json'])\n\n/** Whether a capture is a machine copy: a machine media type and a body that is not HTML. */\nexport function isMachineCopy(capture: ArsHttpCapture): boolean {\n const representation = buildRepresentation(capture)\n return (\n representation !== null &&\n MACHINE_KINDS.has(representation.kind) &&\n !representation.looksLikeHtml\n )\n}\n\nconst MARKDOWN_MEDIA: ReadonlySet<string> = new Set(['text/markdown', 'text/x-markdown'])\n\nfunction isMarkdownType(type: string | null): boolean {\n return type !== null && MARKDOWN_MEDIA.has((type.split(';')[0] ?? '').trim().toLowerCase())\n}\n\n/**\n * The Markdown copies a page declares as alternates, as absolute URLs without a\n * fragment, deduplicated, in a fixed order: `Link` headers on each capture, then\n * `<link rel=\"alternate\" type=\"text/markdown\">` in each capture's HTML.\n */\nexport function declaredMarkdownAlternates(captures: readonly (ArsHttpCapture | null)[]): string[] {\n const out: string[] = []\n const add = (raw: string, base: string): void => {\n try {\n const url = new URL(raw, base)\n url.hash = ''\n const href = url.toString()\n if (!out.includes(href)) out.push(href)\n } catch {\n // An unparseable href declares nothing.\n }\n }\n for (const capture of captures) {\n if (capture === null) continue\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('alternate') && isMarkdownType(link.type)) add(link.url, capture.finalUrl)\n }\n }\n for (const capture of captures) {\n if (capture === null) continue\n const representation = buildRepresentation(capture)\n if (representation === null || representation.doc === null) continue\n for (const link of representation.doc.links) {\n if (!link.rel.includes('alternate') || link.href === null) continue\n if (isMarkdownType(link.type)) add(link.href, capture.finalUrl)\n }\n }\n return out\n}\n\n/**\n * THE ONE MARKDOWN ALTERNATE ARS FETCHES (§3.3, ARS 0.3), shared by the probe and\n * the scorer so the two cannot disagree about which URL was meant. The first\n * declared Markdown copy that is on the target's origin and is not the page's\n * own address; null when the agent probe already received a machine copy, when\n * it did not get a 2xx, or when nothing qualifies. One extra request at most.\n */\nexport function markdownAlternateTarget(\n agent: ArsHttpCapture | null,\n browser: ArsHttpCapture | null,\n origin: string,\n): string | null {\n if (agent === null || agent.status < 200 || agent.status >= 300) return null\n if (isMachineCopy(agent)) return null\n const own = new Set([agent.finalUrl, agent.requestedUrl])\n for (const href of declaredMarkdownAlternates([browser, agent])) {\n let sameOrigin = false\n try {\n sameOrigin = new URL(href).origin === origin\n } catch {\n sameOrigin = false\n }\n if (sameOrigin && !own.has(href)) return href\n }\n return null\n}\n\n/** What the bundle says about the linked Markdown copy, checked against the declaration. */\nfunction linkedCopyOf(\n evidence: ArsEvidence,\n agent: ArsHttpCapture,\n browser: ArsHttpCapture | null,\n): LinkedCopy | null {\n const url = markdownAlternateTarget(agent, browser, evidence.target.origin)\n if (url === null) return null\n const record = evidence.probes.markdownAlternate ?? null\n if (record === null) return { url, status: 'unchecked', representation: null, reason: null }\n if (!record.result.ok) {\n // A refusal is not an observation. robots.txt telling rebilder-ars to stay\n // off the file, or our own safety policy, means we never saw it, and a\n // measured check never deducts for what we did not see.\n if (record.result.error === 'policy-rejected') {\n return { url, status: 'unchecked', representation: null, reason: null }\n }\n return { url, status: 'broken', representation: null, reason: record.result.error }\n }\n const capture = record.result.capture\n // A record for some other URL is not evidence about this declaration.\n if (capture.requestedUrl !== url) {\n return { url, status: 'unchecked', representation: null, reason: null }\n }\n if (capture.status < 200 || capture.status >= 300) {\n return { url, status: 'broken', representation: null, reason: `HTTP ${capture.status}` }\n }\n if (!isMachineCopy(capture)) {\n return { url, status: 'broken', representation: null, reason: 'it returned HTML, not Markdown' }\n }\n return { url, status: 'checked', representation: buildRepresentation(capture), reason: null }\n}\n\n/** Plain names for the media types the probe asks for, in the order it asks. */\nconst MEDIA_NAMES: Readonly<Record<string, string>> = {\n 'text/markdown': 'Markdown',\n 'text/x-markdown': 'Markdown',\n 'text/html': 'HTML',\n 'text/plain': 'plain text',\n 'application/json': 'JSON',\n '*/*': 'anything else',\n}\n\n/** `text/markdown;q=1.0, text/html;q=0.8` → `Markdown first, then HTML`. */\nfunction acceptSummary(accept: string): string {\n const names: string[] = []\n for (const entry of accept.split(',')) {\n const type = (entry.split(';')[0] ?? '').trim().toLowerCase()\n if (type === '') continue\n const name = MEDIA_NAMES[type] ?? type\n if (!names.includes(name)) names.push(name)\n }\n const [first, ...rest] = names\n if (first === undefined) return accept\n return rest.length === 0 ? first : `${first} first, then ${rest.join(', ')}`\n}\n\nfunction checkNegotiatedResponse(context: ScoreContext): CheckOutcome {\n const { agent, linkedCopy } = context\n const typeIsMachine = MACHINE_KINDS.has(agent.kind)\n const bodyIsHtml = agent.looksLikeHtml\n const linkedWorks = linkedCopy !== null && linkedCopy.status === 'checked'\n const earned = context.negotiated\n ? SUBPOINTS.negotiatedResponse.full\n : linkedWorks\n ? SUBPOINTS.negotiatedResponse.linkedCopy\n : 0\n\n const asked =\n context.evidence.probes.agent.requestHeaders['accept'] ??\n context.evidence.probes.agent.requestHeaders['Accept'] ??\n null\n return {\n earned,\n evidence: [\n measured('We asked for', asked === null ? 'not recorded' : acceptSummary(asked)),\n measured('Format we got', agent.contentType ?? 'not stated'),\n measured('Content was HTML', yesNo(bodyIsHtml)),\n ...(linkedCopy === null ? [] : [measured('Linked Markdown copy', linkedCopyLine(linkedCopy))]),\n ],\n remedy: context.negotiated\n ? undefined\n : linkedWorks\n ? 'Your linked Markdown copy works. For full credit, also send it from the page address when an AI assistant asks for Markdown, so assistants get it without a second request.'\n : typeIsMachine\n ? 'Your server labels this response as Markdown, text or JSON but sends HTML. Send the format the Content-Type header names.'\n : 'When an AI assistant asks for Markdown, answer from the same address with a Markdown copy of the page and `Content-Type: text/markdown`. Assistants get your facts without the menus, scripts and styling, which are usually most of the page.',\n }\n}\n\nfunction linkedCopyLine(copy: LinkedCopy): string {\n if (copy.status === 'checked') {\n return `loaded as Markdown from ${copy.url} (${plainBytes(copy.representation?.bytes ?? 0)})`\n }\n if (copy.status === 'broken') return `did not load as Markdown from ${copy.url} (${copy.reason ?? 'error'})`\n return `linked at ${copy.url}, not checked in this scan`\n}\n\nfunction checkDeclaredAlternates(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, structural } = context\n const links = parseLinkHeaders([\n ...headerAll(agentCapture.headers, 'link'),\n ...(browserCapture === null ? [] : headerAll(browserCapture.headers, 'link')),\n ])\n // An alternate with no `type` is a language variant (`hreflang`), not a second\n // representation. Every international site declares those, and paying 4 points\n // for them would make the check meaningless.\n const headerAlternates = links.filter(\n (link) => link.rel.includes('alternate') && link.type !== null,\n )\n\n const documentAlternates: string[] = []\n if (structural !== null && structural.doc !== null) {\n for (const link of structural.doc.links) {\n if (!link.rel.includes('alternate')) continue\n if (link.type === null || link.href === null) continue\n documentAlternates.push(`${link.type} at ${link.href}`)\n }\n }\n\n const total = headerAlternates.length + documentAlternates.length\n const broken = context.linkedCopy !== null && context.linkedCopy.status === 'broken'\n if (broken && context.linkedCopy !== null) {\n return {\n earned: 0,\n evidence: [measured('Linked Markdown copy', linkedCopyLine(context.linkedCopy))],\n remedy: `The Markdown copy this page links to did not load (${context.linkedCopy.reason ?? 'error'}). Fix the file or the link.`,\n }\n }\n return {\n earned: total > 0 ? SUBPOINTS.declaredAlternates.full : 0,\n evidence: [\n measured(\n 'Link header pointing to the Markdown copy',\n headerAlternates.length === 0\n ? 'none'\n : headerAlternates.map((link) => `${link.type ?? '?'} at ${link.url}`).join(', '),\n ),\n measured(\n 'Link tag in the page pointing to the Markdown copy',\n documentAlternates.length === 0 ? 'none' : documentAlternates.join(', '),\n ),\n ],\n remedy:\n total > 0\n ? undefined\n : 'Tell assistants where the Markdown copy is. Add `<link rel=\"alternate\" type=\"text/markdown\" href=\"…\">` to the page, or send the same thing as a `Link` header.',\n }\n}\n\nfunction checkVaryAccept(context: ScoreContext): CheckOutcome {\n const negotiated = context.negotiated\n const { agentCapture, browserCapture } = context\n const agentVary = headerTokens(header(agentCapture.headers, 'vary'))\n const browserVary =\n browserCapture === null ? [] : headerTokens(header(browserCapture.headers, 'vary'))\n const declared = agentVary.includes('accept') || browserVary.includes('accept')\n\n const evidence = [\n measured('Vary header sent to AI assistants', header(agentCapture.headers, 'vary') ?? 'not sent'),\n measured(\n 'Vary header sent to browsers',\n browserCapture === null\n ? 'not checked'\n : (header(browserCapture.headers, 'vary') ?? 'not sent'),\n ),\n ]\n\n // Gated on D2.1: `Vary: Accept` on a response that does not vary by Accept is\n // a claim about caching that is not true. Fixture 035 pins it.\n if (!negotiated) {\n return {\n earned: 0,\n evidence: [\n ...evidence,\n measured(\n 'Counts',\n context.linkedCopy?.status === 'checked'\n ? 'only when the page address itself sends the Markdown copy, so 0 for now'\n : COUNTS_ONCE_COPY,\n ),\n ],\n }\n }\n\n if (!declared) {\n context.flags.push({\n id: 'vary-missing',\n severity: 'warn',\n basis: 'measured',\n message:\n 'This address sends the Markdown copy or the HTML depending on what is asked for, but does not send `Vary: Accept`. A shared cache can hand the Markdown to a shopper, or the HTML to an assistant.',\n evidence,\n })\n }\n\n return {\n earned: declared ? SUBPOINTS.varyAccept.full : 0,\n evidence,\n remedy: declared\n ? undefined\n : 'Send `Vary: Accept` on every response from an address that serves a Markdown copy, so caches keep the two versions apart.',\n }\n}\n\n/**\n * The kinds D2.4 compares. Explicitly four, and never description or free text\n * (§3.8): a prose difference between a Markdown summary and an HTML page is a\n * rendering difference, and calling it a substance divergence would be an\n * accusation we cannot support.\n */\nconst PARITY_KINDS: readonly ArsFactKind[] = ['price', 'currency', 'availability', 'title']\n\n/**\n * Two readings of one side's facts: the value it would PUBLISH for each kind\n * (the unqualified observation with the lowest byte offset, ties broken\n * lexicographically — the same choice `mergeFacts` makes for the published fact\n * set), and EVERY unqualified value it stated.\n *\n * Qualified values — ranges, \"from $9\" — never enter either map (§3.11).\n */\ninterface FactView {\n readonly representative: Map<ArsFactKind, string>\n readonly observed: Map<ArsFactKind, Set<string>>\n}\n\n/** The facts in a linked Markdown copy, read with the page's own profile and currency. */\nfunction linkedCopyFacts(context: ScoreContext, copy: LinkedCopy): readonly ExtractedFact[] {\n if (copy.representation === null) return []\n return extractFacts(copy.representation, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: copy.representation.finalUrl,\n origin: context.evidence.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n}\n\nfunction factView(facts: readonly ExtractedFact[]): FactView {\n const best = new Map<ArsFactKind, ExtractedFact>()\n const observed = new Map<ArsFactKind, Set<string>>()\n for (const fact of facts) {\n if (fact.qualified) continue\n const seen = observed.get(fact.kind)\n if (seen === undefined) observed.set(fact.kind, new Set([fact.normalized]))\n else seen.add(fact.normalized)\n\n const current = best.get(fact.kind)\n if (current === undefined) {\n best.set(fact.kind, fact)\n continue\n }\n if (fact.offset < current.offset) best.set(fact.kind, fact)\n else if (fact.offset === current.offset && fact.normalized < current.normalized)\n best.set(fact.kind, fact)\n }\n const representative = new Map<ArsFactKind, string>()\n for (const [kind, fact] of best) representative.set(kind, fact.normalized)\n return { representative, observed }\n}\n\n/**\n * The comparison rule for D2.4 and D5.3, and it is ASYMMETRIC on purpose:\n * **the value the left side would publish must appear somewhere among the values\n * the right side stated.**\n *\n * Both symmetric rules are wrong, and each is wrong in a way that matters:\n *\n * - Requiring the two REPRESENTATIVES to be equal produces false accusations on\n * ordinary pages. The demo product page in fixtures 001/002 names a backordered\n * variant above the line that says the product is in stock; its JSON-LD says\n * `InStock`, and both statements are true. Flagging that as a\n * structured-data divergence would be an accusation the evidence does not\n * support, and ARS reports observations rather than charges (§3.8).\n * - Accepting ANY shared value lets a real divergence hide behind an incidental\n * match: \"Free shipping over $50\" appears in both representations, so a page\n * whose headline price differs would still certify clean.\n *\n * The asymmetric rule catches the second and not the first, which is the\n * conservative direction: a missed divergence costs a merchant nothing, and a\n * false one is published on a scanner page next to their name.\n */\nfunction divergentKinds(\n left: FactView,\n right: FactView,\n kinds: readonly ArsFactKind[],\n): { compared: ArsFactKind[]; divergent: { kind: ArsFactKind; left: string; right: string }[] } {\n const compared: ArsFactKind[] = []\n const divergent: { kind: ArsFactKind; left: string; right: string }[] = []\n for (const kind of kinds) {\n const claim = left.representative.get(kind)\n const stated = right.observed.get(kind)\n if (claim === undefined || stated === undefined || stated.size === 0) continue\n compared.push(kind)\n if (!stated.has(claim)) {\n divergent.push({ kind, left: claim, right: [...stated].sort().join(' | ') })\n }\n }\n return { compared, divergent }\n}\n\nfunction checkSubstanceParity(context: ScoreContext): CheckOutcome {\n const { agentFacts, browserFacts, browser, evidence: bundle } = context\n // ARS 0.3: a linked Markdown copy that loaded is compared the same way as a\n // negotiated one. It has no confirming probe, so a difference costs the\n // points and raises no flag, the conservative branch below.\n const linked =\n !context.negotiated && context.linkedCopy?.status === 'checked' ? context.linkedCopy : null\n const htmlFacts = browser !== null ? browserFacts : agentFacts\n\n if ((!context.negotiated && linked === null) || (linked === null && browser === null)) {\n return {\n earned: 0,\n evidence: [\n heuristic(\n 'Counts',\n !context.negotiated\n ? COUNTS_ONCE_COPY\n : 'not checked, because this scan has no browser request to compare',\n ),\n ],\n }\n }\n\n const agentValues = factView(linked === null ? agentFacts : linkedCopyFacts(context, linked))\n const browserValues = factView(linked === null ? browserFacts : htmlFacts)\n const { compared, divergent } = divergentKinds(agentValues, browserValues, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Facts compared',\n compared.length === 0\n ? 'none appear in both the Markdown copy and the page'\n : factList(compared),\n ),\n ...(compared.length === 0\n ? []\n : [\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'match'\n : divergent\n .map(\n (entry) =>\n `${factName(entry.kind)}: Markdown copy ${entry.left}, page ${entry.right}`,\n )\n .join('; '),\n ),\n ]),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'State the same key facts, such as name and price, in the Markdown copy and in the page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length === 0)\n return { earned: SUBPOINTS.substanceParity.full, evidence: evidenceLines }\n\n // §3.8: divergence must REPRODUCE on a third confirming probe taken ≥30s later\n // before the flag is set. Inventory and price genuinely change between two\n // sequential requests, and a one-shot difference is not evidence of anything.\n // A linked copy never has one, so it always takes the unflagged branch.\n const confirm = linked === null ? bundle.probes.parityConfirm : null\n const confirmCapture = confirm !== null && confirm.result.ok ? confirm.result.capture : null\n const confirmRep = confirmCapture === null ? null : buildRepresentation(confirmCapture)\n if (confirmRep === null) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic('Second look', 'not taken, so this difference was seen once and is not flagged'),\n ],\n remedy:\n 'The Markdown copy and the page showed different values for a key fact. That can happen when a price or stock level changes between requests. If it repeats, build both from the same source.',\n }\n }\n\n const confirmFacts = extractFacts(confirmRep, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: confirmRep.finalUrl,\n origin: bundle.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n const confirmValues = factView(confirmFacts)\n const reproduced = divergentKinds(\n confirmValues,\n browserValues,\n divergent.map((entry) => entry.kind),\n )\n\n if (reproduced.divergent.length === 0) {\n return {\n earned: SUBPOINTS.substanceParity.full,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Second look',\n 'the difference was gone, so we treat it as a value that changed between requests',\n ),\n ],\n }\n }\n\n context.flags.push({\n id: 'substance-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: reproduced.divergent\n .map(\n (entry) =>\n `The Markdown copy showed ${factName(entry.kind)} ${entry.left}; the HTML page showed ${entry.right}. We saw the same difference on two requests taken apart.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Second look', 'the difference was still there')],\n remedy:\n 'Show the same values in the Markdown copy and the page, ideally by building both from one source. We report what each version said and do not judge which is right.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D3 — Fact coverage\n// ---------------------------------------------------------------------------\n\ninterface CoverageMath {\n readonly coreFound: number\n readonly extendedFound: number\n readonly coveragePct: number\n readonly densityPct: number\n readonly factsPerKiB100: number\n}\n\n/** §3.6's fact weighting, verbatim, in quarter-units. */\nfunction coverageMath(context: ScoreContext): CoverageMath {\n const { facts, profile, ruleset, agent } = context\n const units = ruleset.thresholds['fact-coverage.fact-units'] ?? []\n const coreCorroboratedUnit = units[0] ?? 0\n const coreUnit = units[1] ?? 0\n const extendedCorroboratedUnit = units[2] ?? 0\n const extendedUnit = units[3] ?? 0\n const denominatorMultiplier =\n ruleset.thresholds['fact-coverage.core-denominator-multiplier']?.[0] ?? 0\n\n let coreUnits = 0\n let extendedUnits = 0\n let coreFound = 0\n let extendedFound = 0\n for (const fact of facts) {\n if (profile.core.includes(fact.kind)) {\n coreFound++\n coreUnits += fact.corroborated ? coreCorroboratedUnit : coreUnit\n } else if (profile.extended.includes(fact.kind)) {\n extendedFound++\n extendedUnits += fact.corroborated ? extendedCorroboratedUnit : extendedUnit\n }\n }\n\n const denominator = denominatorMultiplier * profile.core.length\n const coveragePct =\n denominator === 0\n ? 0\n : Math.min(100, divRoundHalfUp(100 * (coreUnits + extendedUnits), denominator))\n\n // The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n // which let a 200-byte stub top the density band.\n const factsPerKiB100 = idiv(\n (coreFound * 100 + extendedFound * 25) * 1024,\n Math.max(1, agent.bytes),\n )\n const densityPct = atLeast(ruleset.thresholds['fact-coverage.density'], factsPerKiB100)\n\n return { coreFound, extendedFound, coveragePct, densityPct, factsPerKiB100 }\n}\n\nfunction checkCoreFacts(context: ScoreContext, math: CoverageMath): CheckOutcome {\n const weight = weightOf(context.ruleset, 'fact-coverage.core-facts')\n const earned = idiv(weight * math.coveragePct * math.densityPct + 5000, 10000)\n const missing = context.profile.core.filter(\n (kind) => !context.facts.some((fact) => fact.kind === kind),\n )\n\n return {\n earned,\n evidence: [\n heuristic('Key facts for this kind of page', factList(context.profile.core)),\n heuristic('Found', `${math.coreFound} of ${context.profile.core.length}`),\n heuristic('Missing', missing.length === 0 ? 'none' : factList(missing)),\n heuristic(\n 'Extra facts found',\n `${math.extendedFound} of ${context.profile.extended.length}`,\n ),\n heuristic(\n 'Credit for the facts',\n `${math.coveragePct}% (a fact stated in both the text and structured data counts in full)`,\n ),\n heuristic(\n 'Credit kept for length',\n `${math.densityPct}% (${math.coreFound + math.extendedFound} facts in ${plainBytes(context.agent.bytes)}; the more text around each fact, the less is kept)`,\n ),\n ],\n remedy:\n missing.length > 0\n ? `Add the ${factList(missing)} to what AI assistants receive. An assistant can only repeat what the page states.${\n missing.includes('primary-action-url')\n ? ' For the main action link, use a label that starts with a common action word, such as Buy, Book, Order, Contact, Sign up, Get started or Request a quote.'\n : ''\n }`\n : earned === weight\n ? undefined\n : math.coveragePct < 100\n ? 'Repeat the key facts in both the visible text and the structured data. A fact stated once gets half credit.'\n : 'Your key facts are all there, but there is a lot of page around them, so this keeps only part of its credit. A Markdown copy for AI assistants that leads with the facts is the simplest fix; trimming the page also helps.',\n }\n}\n\nfunction checkContextCost(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['fact-coverage.context-cost']\n const reference = context.profile.byteReference\n const ratio = reference === 0 ? 0 : idiv(100 * context.agent.bytes, reference)\n const earned = atMost(table, ratio)\n const full = atMost(table, 0)\n\n return {\n earned,\n evidence: [\n measured(\n 'Size AI assistants had to read',\n `${plainBytes(context.agent.bytes)}${context.agent.truncated ? ' or more (cut off at the limit)' : ''}`,\n ),\n measured(\n `Typical size for a ${context.profile.pageKind === 'unknown' ? 'general' : context.profile.pageKind} page`,\n plainBytes(reference),\n ),\n measured(\n 'Compared with typical',\n ratio <= 100 ? 'at or under typical' : `about ${divRoundHalfUp(ratio, 100)} times typical`,\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Send AI assistants a Markdown copy, which carries the facts without the page code, or make the page lighter. Scripts, inline styles and repeated menus are usually most of the size.',\n }\n}\n\n\n// ---------------------------------------------------------------------------\n// D7 — Evidence density\n// ---------------------------------------------------------------------------\n\n/**\n * WHY THIS DIMENSION EXISTS (ARS 0.2). The controlled work on what an assistant\n * actually lifts into an answer, rather than what it merely cites, finds the\n * effect concentrated in extractable evidence units: quantities, definitions\n * and comparisons carry large influence uplift, while conversational Q&A\n * phrasing carries none. D1-D6 grade whether an agent can REACH and PARSE a\n * page. Nothing before this graded whether, having parsed it, there was\n * anything quotable on it.\n *\n * ALL THREE ARE COUNTS OVER THE AGENT'S OWN COUNTED TEXT. No model, no\n * randomness, no clock. `quantities` and `comparisons` are `measured` because\n * they observe the artifact directly, a token shape and a markup structure;\n * `definitions` is `heuristic` because calling a `label: value` line a\n * definition is a judgement about intent, and the basis field says so.\n */\n\n/** Currency amount, percentage, number carrying a unit, or an ISO date. */\nconst QUANTITY = new RegExp(\n [\n String.raw`[$£€¥]\\s?\\d[\\d,]*(?:\\.\\d+)?`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?%`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?(?:kg|g|lb|lbs|oz|mm|cm|m|km|mi|in|ft|ml|l|kb|mb|gb|tb|hz|w|kw|v|°c|°f|hours?|hrs?|minutes?|mins?|seconds?|secs?|days?|weeks?|months?|years?)\\b`,\n String.raw`\\d{4}-\\d{2}-\\d{2}`,\n ].join('|'),\n 'giu',\n)\n\n/** `**Label:** value`, `- Label: value`, and `<dt>` rows once tokenized to text. */\nconst DEFINITION_LINE = /^\\s*(?:[-*+]\\s+)?(?:\\*\\*)?[A-Za-z][A-Za-z0-9 /&'()-]{1,40}(?:\\*\\*)?\\s*:\\s*\\S/\n\n/**\n * Block elements that hold ONE labelled fact when a page states them in markup\n * rather than in Markdown. Pinned, like every other table in this standard.\n *\n * WHY THIS SET EXISTS AT ALL. `countedText` joins every text node with a single\n * space and collapses whitespace runs, so an HTML document's counted text is one\n * line — deliberately, because a line model would need a display model and there\n * is no CSS resolution anywhere in this package. Splitting D7.2 on `\\n` would\n * therefore score EVERY HTML page at zero and pay only representations that\n * arrive already line-structured, which in practice means pages behind a\n * Markdown gateway. A check that only the editors' own product can satisfy is\n * exactly the self-serving design this standard must not contain, so D7.2\n * segments an HTML document structurally instead: each counted text node is\n * attributed to its nearest ancestor in this set, and each such element's own\n * text is one candidate line. Innermost wins by construction, so a `<p>` inside\n * an `<li>` is counted once and not twice.\n */\nconst LABELLED_BLOCK_TAGS = new Set(['li', 'dt', 'dd', 'p', 'td', 'th', 'div'])\n\nfunction checkQuantities(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.quantities']\n // DISTINCT, normalized on case and inner whitespace: a price stated in a\n // header, a buy box and a footer is one fact said three times, and paying\n // for the repetition would reward exactly the padding this score exists to\n // discourage.\n const seen = new Set<string>()\n for (const match of context.agent.text.matchAll(QUANTITY)) {\n seen.add(match[0].toLowerCase().replace(/\\s+/g, ''))\n }\n const count = seen.size\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [\n measured('Different numbers an answer could quote', `${count} (prices, sizes, percentages, dates)`),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Write the numbers people ask about in the page text: prices, sizes, hours, fees and dates. Assistants quote numbers they can read.',\n }\n}\n\n/**\n * The candidate lines of a representation: one per labelled block element when\n * there is a document, and the text's own lines when there is not. Order is\n * document order in both cases, so two runs over one bundle agree.\n */\nfunction labelledSegments(context: ScoreContext): string[] {\n const doc = context.agent.doc\n if (doc === null) return context.agent.text.split('\\n')\n\n // One pass over counted text nodes, each attributed to its nearest ancestor\n // in LABELLED_BLOCK_TAGS. `Map` preserves insertion order, which is the order\n // the first text node of each element appeared.\n const byElement = new Map<number, string[]>()\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (node.text.trim().length === 0) continue\n let at = node.parent\n // Bounded by the tokenizer's own depth limit; a cycle cannot hang this.\n for (let hops = 0; at >= 0 && hops <= MAX_ANCESTOR_HOPS; hops += 1) {\n const element = doc.elements[at]\n if (element === undefined) break\n if (LABELLED_BLOCK_TAGS.has(element.tag)) {\n const parts = byElement.get(at)\n if (parts === undefined) byElement.set(at, [node.text])\n else parts.push(node.text)\n break\n }\n at = element.parent\n }\n }\n\n const segments: string[] = []\n for (const parts of byElement.values()) {\n segments.push(parts.join(' ').replace(/\\s+/g, ' ').trim())\n }\n return segments\n}\n\n/** Deep enough for any real document; the tokenizer caps nesting well below it. */\nconst MAX_ANCESTOR_HOPS = 256\n\nfunction checkDefinitions(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.definitions']\n let count = 0\n for (const line of labelledSegments(context)) {\n if (DEFINITION_LINE.test(line)) count += 1\n }\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [heuristic('Labelled facts, like \"Returns: 60 days\"', `${count}`)],\n remedy:\n earned === full\n ? undefined\n : 'Label your facts. A line like \"Returns: 60 days\" can be quoted as it is. The same fact inside a paragraph has to be worked out.',\n }\n}\n\n/**\n * Comparable ROWS, not tables. A table with one data row states a fact; two or\n * more let an assistant contrast options, which is the shape the absorption\n * work found doing the work. Counted from the tokenized document so it is a\n * structural observation, and from the markdown pipe form when there is no\n * document, so a markdown-only representation is not silently scored zero.\n */\nfunction checkComparisons(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.comparisons']\n let rows = 0\n\n const doc = context.agent.doc\n if (doc !== null) {\n // Cells per row, by walking children back to their parent `tr`. The\n // tokenizer records `parent` as an index into `elements`, so this is one\n // pass and no tree is built.\n const cellsByRow = new Map<number, number>()\n for (const element of doc.elements) {\n if (element.tag !== 'td' && element.tag !== 'th') continue\n const row = doc.elements[element.parent]\n if (row === undefined || row.tag !== 'tr') continue\n cellsByRow.set(element.parent, (cellsByRow.get(element.parent) ?? 0) + 1)\n }\n for (const cells of cellsByRow.values()) if (cells >= 2) rows += 1\n // A header row is not a comparison.\n rows = Math.max(0, rows - 1)\n } else {\n let pipeRows = 0\n for (const line of context.agent.text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) continue\n if (/^\\|[\\s:|-]+\\|$/.test(trimmed)) continue // the alignment rule\n if (trimmed.split('|').length - 2 >= 2) pipeRows += 1\n }\n rows = Math.max(0, pipeRows - 1)\n }\n\n const earned = atLeast(table, rows)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [measured('Table rows that compare options', `${rows}`)],\n remedy:\n earned === full\n ? undefined\n : 'Put options side by side in a table, one row each. Assistants answering \"which one?\" use rows they can line up.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D4 — Fact position\n// ---------------------------------------------------------------------------\n\nfunction coreOffsets(context: ScoreContext): number[] {\n const offsets: number[] = []\n for (const fact of context.facts)\n if (context.profile.core.includes(fact.kind)) offsets.push(fact.offset)\n return offsets.sort((a, b) => a - b)\n}\n\nfunction checkFirstCoreFactOffset(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const first = offsets[0]\n if (first === undefined) {\n return {\n earned: 0,\n evidence: [heuristic('First key fact', 'none found, so there is nothing to place')],\n }\n }\n const firstKind = context.facts.find((fact) => fact.offset === first)?.kind\n return {\n earned: atMost(context.ruleset.thresholds['fact-position.first-core-fact-offset'], first),\n evidence: [\n measured('First key fact appears', first === 0 ? 'at the very start' : `after ${plainBytes(first)}`),\n heuristic('Which fact', firstKind === undefined ? 'unknown' : factName(firstKind)),\n ],\n remedy:\n first <= 512\n ? undefined\n : 'Put the key facts near the top of what AI assistants receive. Assistants often read only the start.',\n }\n}\n\nfunction checkFrontWindow(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const windowRule = context.ruleset.thresholds['fact-position.front-window-size'] ?? []\n const floor = windowRule[0] ?? 0\n const divisor = windowRule[1] ?? 1\n const size = Math.max(floor, idiv(context.agent.bytes, divisor))\n\n if (offsets.length === 0) {\n return {\n earned: 0,\n evidence: [\n measured('Opening section', `the first ${plainBytes(size)}`),\n heuristic('Key facts in it', 'none found, so there is nothing to place'),\n ],\n }\n }\n\n const inside = offsets.filter((offset) => offset < size).length\n // The denominator is the core facts that are PRESENT, not the profile size:\n // absence is D3.1's job, and charging the same absence twice would make the\n // 100 points non-orthogonal. The evidence prints both numbers so a reader can\n // see which question was asked.\n const pct = idiv(100 * inside, offsets.length)\n\n return {\n earned: atLeast(context.ruleset.thresholds['fact-position.front-window'], pct),\n evidence: [\n measured(\n 'Opening section',\n `the first ${plainBytes(size)} (a ${divisor === 5 ? 'fifth' : `1/${divisor}`} of the page, at least ${plainBytes(floor)})`,\n ),\n heuristic('Key facts in it', `${inside} of the ${offsets.length} found (${pct}%)`),\n ],\n remedy:\n pct >= 90\n ? undefined\n : 'Move the key facts into the first part of the page. Facts further down cost an assistant a full read.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D5 — Structured data\n// ---------------------------------------------------------------------------\n\nfunction checkStructuredDataPresent(context: ScoreContext): CheckOutcome {\n const { structural } = context\n const split = SUBPOINTS.structuredDataPresent\n if (structural === null) {\n return {\n earned: 0,\n evidence: [measured('HTML page', 'not checked, because no HTML was returned')],\n }\n }\n\n const { blocks, parsed } = structural.jsonLd\n let microdata = 0\n let rdfa = 0\n if (structural.doc !== null) {\n for (const element of structural.doc.elements) {\n if (attr(element, 'itemtype') !== null) microdata++\n if (attr(element, 'typeof') !== null) rdfa++\n }\n }\n\n const jsonLdScore =\n blocks === 0 ? null : parsed === blocks ? split.clean : parsed > 0 ? split.partial : 0\n const otherScore = microdata > 0 || rdfa > 0 ? split.clean : null\n const earned = Math.max(jsonLdScore ?? 0, otherScore ?? 0)\n\n return {\n earned,\n evidence: [\n measured('JSON-LD blocks that could be read', `${parsed} of ${blocks}`),\n measured('Microdata items', String(microdata)),\n measured('RDFa items', String(rdfa)),\n ],\n remedy:\n earned === split.clean\n ? undefined\n : blocks > parsed\n ? 'At least one JSON-LD block has a syntax error, so it cannot be read. Check it with a JSON validator.'\n : 'Add a JSON-LD block describing this page, such as a schema.org Product with its price. Search engines and some AI assistants read it.',\n }\n}\n\n/**\n * The JSON-LD node D5.2 scores against: the node whose `@type` decided the page\n * kind, then any node with a recognised type. Scoring the first node in the\n * document would mark a page incomplete because its `BreadcrumbList` has no\n * `offers.price` (§ `nodeForKind` in ./classify).\n */\nfunction scoredNode(context: ScoreContext): JsonLdNode | null {\n const nodes = context.structural?.jsonLd.nodes ?? []\n const forKind = nodeForKind(nodes, context.profile.pageKind)\n if (forKind !== null) return forKind\n for (const node of nodes) if (node.types.some(isRecognisedType)) return node\n return null\n}\n\nfunction checkRequiredProperties(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.requiredProperties\n const required = context.ruleset.requiredProperties[context.profile.pageKind] ?? []\n const node = scoredNode(context)\n\n if (node === null) {\n return {\n earned: 0,\n evidence: [\n measured('Schema.org type', 'none found'),\n measured('Properties we look for', required.join(', ') || 'none'),\n measured('Where we look', 'JSON-LD. Microdata counts toward the check above, not this one.'),\n ],\n remedy:\n 'Give the JSON-LD a schema.org type that matches the page, such as Product, LocalBusiness or Article, with the properties listed.',\n }\n }\n\n const satisfied = required.filter((path) => hasPath(node, path))\n const missing = required.filter((path) => !hasPath(node, path))\n const completeness =\n required.length === 0\n ? split.completeness\n : divRoundHalfUp(split.completeness * satisfied.length, required.length)\n\n return {\n earned: split.recognisedType + completeness,\n evidence: [\n measured('Schema.org type', node.types.join(', ')),\n measured('Properties present', `${satisfied.length} of ${required.length}`),\n measured('Missing', missing.length === 0 ? 'none' : missing.join(', ')),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `Add ${missing.join(', ')} to the ${node.types[0] ?? 'main'} item in your JSON-LD.`,\n }\n}\n\nfunction checkTextAgreement(context: ScoreContext): CheckOutcome {\n const { structuralFacts } = context\n const fromJsonLd = factView(structuralFacts.filter((fact) => fact.source === 'json-ld'))\n const fromPage = factView(structuralFacts.filter((fact) => fact.source !== 'json-ld'))\n const { compared, divergent } = divergentKinds(fromJsonLd, fromPage, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Facts compared',\n compared.length === 0\n ? 'none appear in both the structured data and the page text'\n : factList(compared),\n ),\n ...(compared.length === 0\n ? []\n : [\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'match'\n : divergent\n .map(\n (entry) =>\n `${factName(entry.kind)}: structured data ${entry.left}, page ${entry.right}`,\n )\n .join('; '),\n ),\n ]),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'State the key facts, such as name and price, in both the structured data and the visible page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length > 0) {\n context.flags.push({\n id: 'structured-data-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: divergent\n .map(\n (entry) =>\n `The structured data says ${factName(entry.kind)} ${entry.left}; the visible page says ${entry.right}.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'Build the structured data from the same source as the visible page, so the two cannot disagree.',\n }\n }\n\n return { earned: SUBPOINTS.textAgreement.full, evidence: evidenceLines }\n}\n\n// ---------------------------------------------------------------------------\n// D6 — Contract & discovery\n// ---------------------------------------------------------------------------\n\nfunction canonicalOf(\n capture: ArsHttpCapture | null,\n representation: ArsRepresentation | null,\n): string | null {\n if (capture !== null) {\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('canonical')) return link.url\n }\n }\n if (representation !== null && representation.doc !== null) {\n for (const link of representation.doc.links) {\n if (link.rel.includes('canonical') && link.href !== null) return link.href\n }\n }\n return null\n}\n\nfunction checkCanonical(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.canonical\n const htmlCanonical =\n canonicalOf(context.browserCapture, context.browser) ??\n canonicalOf(context.agentCapture, context.agent)\n const agentCanonical = canonicalOf(context.agentCapture, context.agent)\n\n const present = htmlCanonical !== null\n const absolute = htmlCanonical !== null && /^https?:\\/\\//i.test(htmlCanonical)\n const consistent =\n htmlCanonical !== null && agentCanonical !== null && agentCanonical === htmlCanonical\n\n if (htmlCanonical !== null && agentCanonical !== null && agentCanonical !== htmlCanonical) {\n context.flags.push({\n id: 'canonical-mismatch',\n severity: 'warn',\n basis: 'measured',\n message: `The Markdown copy and the HTML page name different main addresses: ${agentCanonical} and ${htmlCanonical}.`,\n evidence: [\n measured('Main address given to AI assistants', agentCanonical),\n measured('Main address in the HTML', htmlCanonical),\n ],\n })\n }\n\n return {\n earned:\n (present ? split.present : 0) +\n (absolute ? split.absolute : 0) +\n (consistent ? split.consistentAcrossProbes : 0),\n evidence: [\n measured('Canonical address in the HTML', htmlCanonical ?? 'none'),\n measured('Canonical address AI assistants got', agentCanonical ?? 'none'),\n measured('Full address with https://', yesNo(absolute)),\n measured('Same for AI assistants and browsers', yesNo(consistent)),\n ],\n remedy:\n consistent && absolute\n ? undefined\n : htmlCanonical === null\n ? 'Add `<link rel=\"canonical\" href=\"https://…\">` with the full address of the page, so assistants know which address to cite.'\n : agentCanonical === null\n ? 'Your Markdown copy has no canonical address. Send `Link: <https://…>; rel=\"canonical\"` with it, pointing at the page.'\n : !consistent\n ? 'Use one canonical address, written in full, for the page and its Markdown copy.'\n : 'Write the canonical address in full, starting with https://.',\n }\n}\n\nfunction checkCacheValidators(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.cacheValidators\n const cacheControl = header(context.agentCapture.headers, 'cache-control')\n const directives = headerTokens(cacheControl)\n const noStore = directives.includes('no-store')\n const maxAge = directives.some((token) => {\n const match = /^(?:max-age|s-maxage)=(\\d{1,10})$/.exec(token)\n return match !== null && Number(match[1]) > 0\n })\n const noCache = directives.includes('no-cache') || directives.includes('must-revalidate')\n const etag = header(context.agentCapture.headers, 'etag')\n const lastModified = header(context.agentCapture.headers, 'last-modified')\n const validator = etag !== null || lastModified !== null\n\n // \"Sane\" is: the response says how long it may be reused, or says to\n // revalidate — and revalidation only means anything with a validator.\n const sane = cacheControl !== null && !noStore && (maxAge || (noCache && validator))\n\n return {\n earned: (sane ? split.saneCacheControl : 0) + (validator ? split.validator : 0),\n evidence: [\n measured('Cache-Control header', cacheControl ?? 'not sent'),\n measured('ETag header', etag ?? 'not sent'),\n measured('Last-Modified header', lastModified ?? 'not sent'),\n ],\n remedy:\n sane && validator\n ? undefined\n : 'Send a `Cache-Control` header with a lifetime, plus an `ETag` or `Last-Modified` header, so repeat visits can skip unchanged pages.',\n }\n}\n\nfunction bodyOf(probe: ArsProbeRecord | null): string | null {\n if (probe === null || !probe.result.ok) return null\n const capture = probe.result.capture\n if (capture.status < 200 || capture.status >= 300) return null\n return typeof capture.body === 'string' ? capture.body : null\n}\n\nconst MARKDOWN_LINK = /\\[[^\\]\\n]{1,200}\\]\\(([^)\\s]{1,500})\\)/g\n\nfunction checkLlmsTxt(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.llmsTxt\n const body = bodyOf(context.evidence.probes.llmsTxt)\n if (body === null || body.trim().length === 0) {\n return {\n earned: 0,\n evidence: [measured('/llms.txt', body === null ? 'not found' : 'empty')],\n remedy:\n 'Publish /llms.txt with a `#` title, a short summary and links to your main pages.',\n }\n }\n // The llms.txt convention: an H1 title, then Markdown links. Both halves are\n // checked because a file with a title and no links tells an agent nothing.\n const hasTitle = /^#\\s+\\S/m.test(body)\n MARKDOWN_LINK.lastIndex = 0\n const hasLinks = MARKDOWN_LINK.test(body)\n const specShaped = hasTitle && hasLinks\n\n return {\n earned: specShaped ? split.specShaped : split.present,\n evidence: [\n measured('/llms.txt', `found, ${body.length} characters`),\n measured('Has a # title', yesNo(hasTitle)),\n measured('Has links', yesNo(hasLinks)),\n ],\n remedy: specShaped\n ? undefined\n : 'Start /llms.txt with a `#` title and add at least one link written as `[name](url)`.',\n }\n}\n\nfunction checkSitemap(context: ScoreContext): CheckOutcome {\n return {\n earned: context.policy.sitemapDeclared ? SUBPOINTS.sitemap.full : 0,\n evidence: [\n measured('Sitemap listed in robots.txt', yesNo(context.policy.sitemapDeclared)),\n measured(\n 'Sitemaps',\n context.robots === null ? 'none' : context.robots.sitemaps.join(', ') || 'none',\n ),\n ],\n remedy: context.policy.sitemapDeclared\n ? undefined\n : 'Add a line like `Sitemap: https://example.com/sitemap.xml` to robots.txt.',\n }\n}\n\n/**\n * Media types and URL shapes that count as a declared machine endpoint (§3.4\n * D6.5: UCP/ACP/MCP/OpenAPI/GraphQL/RSS/Atom/ICS/JSON feed).\n *\n * Credit comes from DECLARATION. ARS probes `/robots.txt`, `/llms.txt` and\n * `/.well-known/ucp` and nothing else — no guessing at `/sitemap.xml`, `/mcp` or\n * `/acp` — because an endpoint an agent cannot find is an endpoint that does not\n * exist. The three probed paths are the disclosed exception: they are published\n * conventions with published locations.\n */\nconst ENDPOINT_TYPES: readonly string[] = [\n 'application/rss+xml',\n 'application/atom+xml',\n 'application/feed+json',\n 'application/json',\n 'application/ld+json',\n 'application/vnd.api+json',\n 'application/schema+json',\n 'application/graphql',\n 'application/openapi+json',\n 'application/yaml',\n 'text/calendar',\n]\nconst ENDPOINT_RELS: readonly string[] = [\n 'service-desc',\n 'service-doc',\n 'api',\n 'describedby',\n 'ucp',\n 'mcp',\n]\nconst ENDPOINT_PATH_MARKERS: readonly string[] = [\n '/api',\n '/mcp',\n '/graphql',\n '/openapi',\n '/.well-known/',\n '.json',\n '.ics',\n '.rss',\n '.atom',\n]\n\nfunction checkMachineEndpoint(context: ScoreContext): CheckOutcome {\n const declarations: string[] = []\n\n const links = parseLinkHeaders([\n ...headerAll(context.agentCapture.headers, 'link'),\n ...(context.browserCapture === null ? [] : headerAll(context.browserCapture.headers, 'link')),\n ])\n for (const link of links) {\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`Link header (${link.rel.join(' ')}) at ${link.url}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`Link header (${link.type}) at ${link.url}`)\n }\n\n if (context.structural !== null && context.structural.doc !== null) {\n for (const link of context.structural.doc.links) {\n if (link.href === null) continue\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`link tag (${link.rel.join(' ')}) at ${link.href}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`link tag (${link.type}) at ${link.href}`)\n }\n }\n\n const llms = bodyOf(context.evidence.probes.llmsTxt)\n if (llms !== null) {\n MARKDOWN_LINK.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = MARKDOWN_LINK.exec(llms)) !== null) {\n const url = (match[1] ?? '').toLowerCase()\n if (ENDPOINT_PATH_MARKERS.some((marker) => url.includes(marker)))\n declarations.push(`llms.txt link to ${match?.[1] ?? url}`)\n }\n }\n\n const ucp = bodyOf(context.evidence.probes.wellKnownUcp)\n if (ucp !== null && ucp.trim().length > 0) declarations.push('/.well-known/ucp')\n // Both probes usually carry the same `Link` header; list each once.\n const unique = [...new Set(declarations)]\n\n return {\n earned: declarations.length > 0 ? SUBPOINTS.machineEndpoint.full : 0,\n evidence: [\n measured('Feeds or APIs we found', unique.length === 0 ? 'none' : unique.join('; ')),\n measured('Where we looked', 'link tags, Link headers, /llms.txt and /.well-known/ucp'),\n ],\n remedy:\n declarations.length > 0\n ? undefined\n : 'Point to a product feed, API or calendar from the page with a `<link>` tag or a `Link` header. We only count ones the page names.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assembly\n// ---------------------------------------------------------------------------\n\nfunction weightOf(ruleset: ArsRuleset, id: ArsCheckId): number {\n return ruleset.weights[id] ?? 0\n}\n\nfunction buildCheck(ruleset: ArsRuleset, id: ArsCheckId, outcome: CheckOutcome): ArsCheck {\n const meta = CHECK_META[id]\n const weight = weightOf(ruleset, id)\n // Structural guarantee: `earned` is an integer in `[0, weight]`. Every branch\n // above already produces one; the clamp is what makes it impossible for a\n // future check to publish a number outside its own weight. Fixture 052 asserts\n // the property over the whole corpus.\n const earned = Math.max(0, Math.min(weight, outcome.earned))\n const check: ArsCheck = {\n id,\n label: meta.label,\n basis: meta.basis,\n weight,\n earned,\n evidence: outcome.evidence,\n }\n return outcome.remedy === undefined || earned === weight\n ? check\n : { ...check, remedy: outcome.remedy }\n}\n\n/**\n * Publication order. HAND-MAINTAINED AND THEREFORE DANGEROUS: a dimension\n * missing here is silently dropped from `dimensions`, and its checks' points\n * vanish from the total. ARS 0.2 shipped D7 without it for one commit and the\n * corpus re-scored against a maximum of 92. `score.test.ts` now asserts this\n * list covers `DIMENSION_META` exactly.\n */\nconst DIMENSION_ORDER: readonly ArsDimensionId[] = [\n 'retrievability',\n 'machine-representation',\n 'fact-coverage',\n 'fact-position',\n 'structured-data',\n 'contract-discovery',\n 'evidence-density',\n]\n\nfunction buildDimensions(checks: readonly ArsCheck[]): ArsDimension[] {\n return DIMENSION_ORDER.map((id) => {\n const own = checks.filter((check) => CHECK_META[check.id].dimension === id)\n return {\n id,\n label: DIMENSION_META[id].label,\n weight: DIMENSION_META[id].weight,\n earned: own.reduce((sum, check) => sum + check.earned, 0),\n basis: own.some((check) => check.basis === 'heuristic')\n ? ('heuristic' as ArsBasis)\n : ('measured' as ArsBasis),\n checks: own,\n }\n })\n}\n\n/** Pinned flag order, so two runs over the same evidence emit the same array. */\nconst FLAG_ORDER: readonly ArsFlagId[] = [\n 'substance-divergence',\n 'structured-data-divergence',\n 'robots-contradiction',\n 'paywalled',\n 'render-dependent',\n 'scanner-blocked',\n 'training-opt-out',\n 'assistant-opt-out',\n 'vary-missing',\n 'canonical-mismatch',\n 'body-truncated',\n 'vantage-variance',\n]\n\nfunction sortFlags(flags: readonly ArsFlag[]): ArsFlag[] {\n return [...flags].sort((a, b) => FLAG_ORDER.indexOf(a.id) - FLAG_ORDER.indexOf(b.id))\n}\n\n/** The band a score falls in. Bands headline; the integer is secondary (§3.6). */\nexport function bandFor(score: number, ruleset: ArsRuleset = DEFAULT_RULESET): ArsBand | null {\n for (const band of ruleset.bands) if (score >= band.min && score <= band.max) return band\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Evidence plumbing\n// ---------------------------------------------------------------------------\n\nfunction captureOf(probe: ArsProbeRecord | null): ArsHttpCapture | null {\n return probe !== null && probe.result.ok ? probe.result.capture : null\n}\n\n/**\n * The currency the page prices in, read from structured data and Open Graph.\n * The SAME hint is used for both representations, deliberately: a hint is a\n * property of the page, and letting the two representations resolve `$` to\n * different currencies would manufacture a substance divergence out of nothing.\n */\nfunction currencyHintOf(\n structural: ArsRepresentation | null,\n agent: ArsRepresentation,\n): string | undefined {\n for (const representation of [structural, agent]) {\n if (representation === null) continue\n for (const node of representation.jsonLd.nodes) {\n for (const path of ['offers.priceCurrency', 'priceCurrency']) {\n const raw = readPath(node, path)\n if (raw !== null && /^[A-Za-z]{3}$/.test(raw.trim())) return raw.trim().toUpperCase()\n }\n }\n if (representation.doc === null) continue\n for (const meta of representation.doc.metas) {\n const key = meta.property ?? meta.name\n if (key !== 'og:price:currency' && key !== 'product:price:currency') continue\n const value = meta.content\n if (value !== null && /^[A-Za-z]{3}$/.test(value.trim())) return value.trim().toUpperCase()\n }\n }\n return undefined\n}\n\nfunction pathOf(url: string, fallback: string): string {\n try {\n return new URL(url).pathname\n } catch {\n return fallback\n }\n}\n\n/** robots.txt status and parse, from the probe record alone. */\nfunction readRobots(probe: ArsProbeRecord | null): {\n status: ArsPolicyReport['robotsTxtStatus']\n robots: RobotsFile | null\n} {\n if (probe === null) return { status: 'missing', robots: null }\n if (!probe.result.ok) return { status: 'error', robots: null }\n const capture = probe.result.capture\n if (capture.status >= 500) return { status: 'error', robots: null }\n if (capture.status >= 400) return { status: 'missing', robots: null }\n const body = typeof capture.body === 'string' ? capture.body : null\n if (body === null) return { status: 'missing', robots: null }\n const robots = parseRobots(body)\n const empty = robots.groups.length === 0 && robots.sitemaps.length === 0\n return { status: empty && robots.malformedLines > 0 ? 'unparseable' : 'ok', robots }\n}\n\n/** Declared paywalls only (§3.8). Undeclared soft paywalls need impersonation, which we refuse. */\nfunction detectPaywall(context: {\n structural: ArsRepresentation | null\n agentCapture: ArsHttpCapture\n}): string | null {\n if (context.agentCapture.status === 402) return 'HTTP 402'\n if (header(context.agentCapture.headers, 'www-authenticate') !== null) return 'WWW-Authenticate'\n for (const node of context.structural?.jsonLd.nodes ?? []) {\n const value = node.value['isAccessibleForFree']\n if (value === false || value === 'False' || value === 'false')\n return 'isAccessibleForFree: false'\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Non-grades\n// ---------------------------------------------------------------------------\n\n/**\n * The result shape for the three non-grades (§3.6). `score` is null and there is\n * no letter — an opt-out is a choice and an unscored target is a missing\n * observation, and neither is an F.\n *\n * The six dimensions are still present with their weights, because §3.9 says\n * `dimensions` always has 6 entries summing to 100, but every check reports\n * `earned: 0` with an evidence line naming the reason. A non-grade is a\n * statement that we did not score; publishing sub-scores next to it would be\n * scoring by another name.\n */\nfunction nonGrade(\n evidence: ArsEvidence,\n ruleset: ArsRuleset,\n outcome: ArsOutcome,\n reason: string,\n policy: ArsPolicyReport,\n flags: readonly ArsFlag[],\n): ArsResult {\n const agentCapture = captureOf(evidence.probes.agent)\n const browserCapture = captureOf(evidence.probes.browser)\n const checks = (Object.keys(CHECK_META) as ArsCheckId[]).map((id) =>\n buildCheck(ruleset, id, {\n earned: 0,\n evidence: [{ label: 'Not evaluated', value: reason, basis: CHECK_META[id].basis }],\n }),\n )\n const htmlBytes = browserCapture?.bytes ?? agentCapture?.bytes ?? 0\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture?.finalUrl ?? evidence.target.url,\n origin: evidence.target.origin,\n },\n outcome,\n score: null,\n grade: null,\n bandLabel: null,\n pageKind: 'unknown',\n pageKindBasis: 'heuristic',\n pageKindConfidence: 'low',\n factProfile: profileFor('unknown'),\n facts: [],\n dimensions: buildDimensions(checks),\n flags: sortFlags(flags),\n policy,\n cost: {\n htmlBytes,\n negotiatedBytes: null,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: null,\n reductionRatio: null,\n firstCoreFactOffset: null,\n truncated: (agentCapture?.truncated ?? false) || (browserCapture?.truncated ?? false),\n },\n recommendations: [],\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\nfunction measuredWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'measured') total += weightOf(ruleset, id)\n }\n return total\n}\n\nfunction heuristicWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'heuristic') total += weightOf(ruleset, id)\n }\n return total\n}\n\n/** Probe error → the reason ARS publishes. `detail` carries the probe's own word for it. */\nfunction unscoredReasonFor(error: string): { reason: ArsUnscoredReason; detail?: string } {\n switch (error) {\n case 'challenge':\n return { reason: 'blocked-at-edge', detail: 'challenge' }\n case 'non-2xx':\n return { reason: 'non-2xx' }\n case 'too-many-redirects':\n return { reason: 'too-many-redirects' }\n case 'timeout':\n return { reason: 'unreachable', detail: 'timeout' }\n case 'blocked-redirect':\n return { reason: 'unreachable', detail: 'blocked-redirect' }\n case 'policy-rejected':\n return { reason: 'unreachable', detail: 'policy-rejected' }\n default:\n return { reason: 'unreachable' }\n }\n}\n\n// ---------------------------------------------------------------------------\n// score()\n// ---------------------------------------------------------------------------\n\n/**\n * The entire pure surface. No network. No clock. No randomness. No LLM.\n *\n * GATE ORDER, and why it is this order:\n * 1. `robots-disallow-scanner` — a statement about OUR conduct. If we were not\n * allowed to fetch, nothing else about the evidence should be reported.\n * Only `vantage: 'public'` is gated; an owner can consent for their own\n * origin (§3.7), and a merchant scanning their own store getting `unscored`\n * because they block unknown tokens is a product regression dressed as rigour.\n * 2. `robots-unavailable` — a persistent 5xx means we could not learn the policy.\n * 3. `opt-out` — the site's own decision, reported before any failure of ours,\n * because it is a choice and not a failure.\n * 4. Fetch failures, then a bundle with no body, then a truncated body.\n */\nexport function score(evidence: ArsEvidence, ruleset: ArsRuleset = DEFAULT_RULESET): ArsResult {\n const flags: ArsFlag[] = []\n const targetPath = pathOf(evidence.target.url, '/')\n const { status: robotsStatus, robots } = readRobots(evidence.probes.robotsTxt)\n const policy = buildPolicyReport(robots, robotsStatus, ruleset, targetPath)\n\n if (policy.trainingOptOut) {\n flags.push({\n id: 'training-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site blocks AI training crawlers but lets AI assistants in. That does not affect the score.',\n evidence: [\n measured('Training audience', policy.audiences.training.matchedRule ?? 'disallowed'),\n measured('Effect on this score', 'none'),\n ],\n })\n }\n\n // 1 — we obey our own token, and say so.\n if (evidence.vantage === 'public' && robots !== null) {\n const scannerDecision = decideScannerToken(robots, targetPath)\n if (scannerDecision) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'info',\n basis: 'measured',\n message:\n 'robots.txt asks Rebilder’s scanner not to read this site, so we did not score the page.',\n evidence: [measured('Matched rule', scannerDecision)],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-disallow-scanner' },\n 'robots.txt disallows the rebilder-ars token',\n policy,\n flags,\n )\n }\n }\n\n // 2 — a policy we could not read is not a policy we may assume.\n if (robotsStatus === 'error') {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-unavailable' },\n 'robots.txt returned a persistent error',\n policy,\n flags,\n )\n }\n\n // 3 — a deliberate, well-formed opt-out. Not a failure, not ranked, no letter.\n if (policy.deliberateOptOut) {\n flags.push({\n id: 'assistant-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site’s robots.txt blocks AI assistants by name. We respect that choice and do not grade the page.',\n evidence: [\n measured('Matched group', policy.audiences.assistant.matchedGroup ?? '(named group)'),\n measured('Matched rule', policy.audiences.assistant.matchedRule ?? 'Disallow'),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'opt-out', audience: 'assistant' satisfies ArsAudience, wellFormed: true },\n 'the site opted out of assistant crawling',\n policy,\n flags,\n )\n }\n\n // 4 — fetch failures.\n const agentProbe = evidence.probes.agent\n if (!agentProbe.result.ok) {\n const { reason, detail } = unscoredReasonFor(agentProbe.result.error)\n if (reason === 'blocked-at-edge') {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The site answered our scanner with a bot check or a block, so we did not grade the page. AI assistants may be blocked the same way.',\n evidence: [measured('Probe error', agentProbe.result.error)],\n })\n }\n const outcome: ArsOutcome =\n detail === undefined ? { kind: 'unscored', reason } : { kind: 'unscored', reason, detail }\n return nonGrade(\n evidence,\n ruleset,\n outcome,\n `the agent probe failed: ${agentProbe.result.error}`,\n policy,\n flags,\n )\n }\n\n const agentCapture = agentProbe.result.capture\n if (agentCapture.status === 403 || agentCapture.status === 401 || agentCapture.status === 429) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message: `The site answered our scanner with HTTP ${agentCapture.status}, so we did not grade the page. AI assistants may be blocked the same way.`,\n evidence: [measured('HTTP status', String(agentCapture.status))],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'blocked-at-edge', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.status < 200 || agentCapture.status >= 300) {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'non-2xx', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.redirects.length > ruleset.maxRedirects) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'too-many-redirects',\n detail: `${agentCapture.redirects.length} hops`,\n },\n `the agent path took ${agentCapture.redirects.length} redirect hops`,\n policy,\n flags,\n )\n }\n\n const browserCapture = captureOf(evidence.probes.browser)\n if (agentCapture.truncated || (browserCapture?.truncated ?? false)) {\n flags.push({\n id: 'body-truncated',\n severity: 'warn',\n basis: 'measured',\n message: `The page is larger than our ${plainBytes(ruleset.maxBodyBytes)} reading limit, so we did not score it. The facts and sizes would both be incomplete.`,\n evidence: [\n measured('Body cap', `${ruleset.maxBodyBytes} bytes`),\n measured('Bytes read', `≥ ${agentCapture.bytes}`),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'truncated-evidence' },\n 'the response exceeded the body cap and was truncated',\n policy,\n flags,\n )\n }\n\n const agent = buildRepresentation(agentCapture)\n if (agent === null) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'evidence-incomplete',\n detail: 'the bundle carries no response body',\n },\n 'the evidence bundle carries hashes but no body, so it cannot be re-scored',\n policy,\n flags,\n )\n }\n const browser = browserCapture === null ? null : buildRepresentation(browserCapture)\n const structural =\n browser !== null && browser.doc !== null ? browser : agent.doc !== null ? agent : browser\n\n // ── classification (pass 1) ──────────────────────────────────────────────\n const classification = classify(pass1Signals(structural ?? agent, evidence.target.url))\n const profile = profileFor(classification.pageKind)\n\n // ── extraction (pass 2) ──────────────────────────────────────────────────\n const currencyHint = currencyHintOf(structural, agent)\n const extractContext = {\n profile,\n ruleset,\n baseUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n currencyHint,\n }\n const agentFacts = extractFacts(agent, extractContext)\n const browserFacts =\n browser === null || browser === agent\n ? []\n : extractFacts(browser, { ...extractContext, baseUrl: browser.finalUrl })\n const structuralFacts =\n structural === agent ? agentFacts : structural === browser ? browserFacts : []\n const facts = mergeFacts(agentFacts, structuralFacts)\n\n const negotiated = isMachineCopy(agentCapture)\n const context: ScoreContext = {\n negotiated,\n linkedCopy: negotiated ? null : linkedCopyOf(evidence, agentCapture, browserCapture),\n evidence,\n ruleset,\n agentCapture,\n browserCapture,\n agent,\n browser,\n structural,\n classification,\n profile,\n facts,\n agentFacts,\n browserFacts,\n structuralFacts,\n policy,\n robots,\n flags,\n }\n\n const paywall = detectPaywall(context)\n if (paywall !== null) {\n flags.push({\n id: 'paywalled',\n severity: 'info',\n basis: 'measured',\n message: `This page says it is behind a paywall (${paywall}). We scored the part we were shown.`,\n evidence: [measured('Paywall signal', paywall)],\n })\n }\n\n // ── the 22 checks ────────────────────────────────────────────────────────\n const math = coverageMath(context)\n const offsets = coreOffsets(context)\n const negotiatedResponse = checkNegotiatedResponse(context)\n\n const checks: ArsCheck[] = [\n buildCheck(ruleset, 'retrievability.reachable', checkReachable(context)),\n buildCheck(ruleset, 'retrievability.robots-policy', checkRobotsPolicy(context)),\n buildCheck(ruleset, 'retrievability.render-independence', checkRenderIndependence(context)),\n buildCheck(ruleset, 'machine-representation.negotiated-response', negotiatedResponse),\n buildCheck(\n ruleset,\n 'machine-representation.declared-alternates',\n checkDeclaredAlternates(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.vary-accept',\n checkVaryAccept(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.substance-parity',\n checkSubstanceParity(context),\n ),\n buildCheck(ruleset, 'fact-coverage.core-facts', checkCoreFacts(context, math)),\n buildCheck(ruleset, 'fact-coverage.context-cost', checkContextCost(context)),\n buildCheck(\n ruleset,\n 'fact-position.first-core-fact-offset',\n checkFirstCoreFactOffset(context, offsets),\n ),\n buildCheck(ruleset, 'fact-position.front-window', checkFrontWindow(context, offsets)),\n buildCheck(ruleset, 'structured-data.present', checkStructuredDataPresent(context)),\n buildCheck(ruleset, 'structured-data.required-properties', checkRequiredProperties(context)),\n buildCheck(ruleset, 'structured-data.text-agreement', checkTextAgreement(context)),\n buildCheck(ruleset, 'contract-discovery.canonical', checkCanonical(context)),\n buildCheck(ruleset, 'contract-discovery.cache-validators', checkCacheValidators(context)),\n buildCheck(ruleset, 'contract-discovery.llms-txt', checkLlmsTxt(context)),\n buildCheck(ruleset, 'contract-discovery.sitemap', checkSitemap(context)),\n buildCheck(ruleset, 'contract-discovery.machine-endpoint', checkMachineEndpoint(context)),\n buildCheck(ruleset, 'evidence-density.quantities', checkQuantities(context)),\n buildCheck(ruleset, 'evidence-density.definitions', checkDefinitions(context)),\n buildCheck(ruleset, 'evidence-density.comparisons', checkComparisons(context)),\n ]\n\n const dimensions = buildDimensions(checks)\n const total = dimensions.reduce((sum, dimension) => sum + dimension.earned, 0)\n const band = bandFor(total, ruleset)\n const grade: ArsGrade = band?.grade ?? 'F'\n\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n const htmlBytes = structural?.bytes ?? agent.bytes\n const negotiatedBytes = negotiated ? agent.bytes : null\n const cost: ArsCostReport = {\n htmlBytes,\n negotiatedBytes,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: negotiatedBytes === null ? null : idiv(negotiatedBytes, perToken),\n // Integer PERCENT of HTML bytes the machine representation eliminates:\n // 94 means \"94% fewer bytes\". §3.9 types this as a number and does not fix\n // its unit; a multiple (`4.2×`) would be a float, and this is the same\n // information with no rounding for two implementations to disagree about.\n reductionRatio:\n negotiatedBytes === null || htmlBytes === 0\n ? null\n : Math.max(0, 100 - idiv(100 * negotiatedBytes, htmlBytes)),\n firstCoreFactOffset: offsets[0] ?? null,\n truncated: agent.truncated || (browser?.truncated ?? false),\n }\n\n const published: ArsFactObservation[] = facts.map((fact) => ({\n kind: fact.kind,\n normalized: fact.normalized,\n source: fact.source,\n offset: fact.offset,\n corroborated: fact.corroborated,\n }))\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n },\n outcome: { kind: 'scored', grade, score: total },\n score: total,\n grade,\n bandLabel: band?.label ?? null,\n pageKind: classification.pageKind,\n pageKindBasis: 'heuristic',\n pageKindConfidence: classification.confidence,\n factProfile: profile,\n facts: published,\n dimensions,\n flags: sortFlags(flags),\n policy,\n cost,\n recommendations: recommend({ dimensions, score: total }),\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\n/**\n * The product token the probe sends (§3.3). This is the ONLY place in the scorer\n * where our own identity is an input to a decision, and the decision it drives is\n * to score nothing.\n */\nconst SCANNER_TOKEN = 'rebilder-ars'\n\n/**\n * Does robots.txt disallow the ARS scanner itself? Returns the matched rule when\n * it does, so the result can print the line rather than assert a verdict.\n *\n * Only a group that NAMES `rebilder-ars` counts. A blanket `User-agent: *`\n * disallow is not a decision about us: it is the accidental case (§3.7), which is\n * scored with `robots-contradiction`, not silently exempted. Rule selection is\n * RFC 9309 longest-match with ties to Allow, via `./extract`'s `pathMatches` —\n * the same matcher `decideRobots` uses, so the scanner gate and the audience\n * decision can never disagree about what a pattern means.\n */\nfunction decideScannerToken(robots: RobotsFile, path: string): string | null {\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent === SCANNER_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${SCANNER_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n","/**\n * probe/limiter.ts — politeness, as a thing you have to hold rather than a thing\n * you have to remember.\n *\n * WHY IT LIVES IN THE PACKAGE. Every consumer of `./probe` — the hosted scanner,\n * the CLI, the MCP server on a stranger's laptop — puts OUR user agent on OUR\n * domain in front of somebody else's origin. A limiter that each consumer is\n * asked to remember to install is a limiter that one of them ships without.\n * `ProbePolicy.limiter` is therefore required, not optional: there is no code\n * path through `probeStrict` that does not take a lease first.\n *\n * WHY IT IS INJECTED AND NEVER MODULE-GLOBAL. Module state is exactly right in a\n * CLI process — one run, one budget, exit — and exactly wrong in a warm\n * serverless instance, where a module-level counter is shared by every request\n * the container ever serves. A 20-probe soft cap implemented as a module global\n * would work perfectly in testing and then, on the twenty-first scan of an\n * instance's life, start refusing unrelated users with no signal that anything\n * had changed. So the limiter is constructed by the caller, scoped to whatever\n * the caller means by \"a run\", and passed in.\n *\n * DEFAULTS (design §5.2): 1 concurrent probe per host, 2 globally, ≥1s between\n * probes to the same host, ~20 probes per run and then an explicit override.\n * \"Probe\" here means one HTTP request, which is the unit an origin experiences.\n * A cold single-URL scan is 5 requests (§3.3: robots, agent, browser, llms.txt,\n * .well-known/ucp), so the default budget is about four cold URLs — a deliberate\n * floor that a multi-URL CLI run raises on purpose by passing `maxProbesPerRun`.\n *\n * NOTHING HERE IS PURE, and it does not have to be: the ESLint purity rule\n * exempts `src/probe/**`. `now` and `sleep` are injectable so the tests do not\n * spend real seconds proving that a one-second gap is a one-second gap.\n */\n\nexport interface LimiterLease {\n /** Idempotent. Releases the host and global slots and starts the host's cooldown. */\n release(): void\n}\n\nexport interface Limiter {\n /** Resolves when it is polite to send. Rejects with `ProbeBudgetExceededError`. */\n acquire(host: string): Promise<LimiterLease>\n /** Requests started in this run, including ones still in flight. */\n readonly used: number\n /** The soft cap this limiter was constructed with. */\n readonly budget: number\n}\n\n/**\n * Thrown by `acquire` when the run budget is spent. A distinct type because the\n * caller has to be able to tell \"we chose not to send this\" from \"the origin\n * did not answer\" — the CLI maps them to different exit codes (4 vs 3) and\n * confusing the two deletes a CI check within a week (design §5.6).\n */\nexport class ProbeBudgetExceededError extends Error {\n readonly budget: number\n\n constructor(budget: number) {\n super(\n `rebilder-ars: probe budget exhausted (${budget} requests this run). ` +\n 'Raise it explicitly with createLimiter({ maxProbesPerRun }) — it is a soft cap, not a hard one, ' +\n 'and raising it should be a decision someone made on purpose.',\n )\n this.name = 'ProbeBudgetExceededError'\n this.budget = budget\n }\n}\n\nexport interface LimiterOptions {\n /** Default 1. Two concurrent requests to one origin is not a probe, it is a load test. */\n maxConcurrentPerHost?: number\n /** Default 2. */\n maxConcurrentGlobal?: number\n /** Default 1000ms, measured from the release of the previous lease for that host. */\n minIntervalPerHostMs?: number\n /** Default 20 requests. The explicit override is passing a different number here. */\n maxProbesPerRun?: number\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n}\n\nconst DEFAULTS = {\n maxConcurrentPerHost: 1,\n maxConcurrentGlobal: 2,\n minIntervalPerHostMs: 1_000,\n maxProbesPerRun: 20,\n} as const\n\ninterface Semaphore {\n acquire(): Promise<void>\n release(): void\n}\n\n/**\n * Slot-transferring semaphore. `release` hands the slot straight to the next\n * waiter instead of decrementing and letting a fresh caller race in through the\n * fast path — the classic way a \"limit 1\" semaphore lets two through.\n */\nfunction semaphore(limit: number): Semaphore {\n let active = 0\n const waiting: (() => void)[] = []\n return {\n acquire(): Promise<void> {\n if (active < limit) {\n active += 1\n return Promise.resolve()\n }\n return new Promise<void>((resolve) => waiting.push(resolve))\n },\n release(): void {\n const next = waiting.shift()\n if (next) next()\n else active = Math.max(0, active - 1)\n },\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> =>\n ms <= 0 ? Promise.resolve() : new Promise<void>((resolve) => setTimeout(resolve, ms))\n\n/**\n * Builds a limiter scoped to one \"run\" — one CLI invocation, one MCP session,\n * one scan job. Acquisition order is global-then-host in every path, so two\n * hosts can never deadlock each other.\n */\nexport function createLimiter(options: LimiterOptions = {}): Limiter {\n const maxConcurrentPerHost = options.maxConcurrentPerHost ?? DEFAULTS.maxConcurrentPerHost\n const maxConcurrentGlobal = options.maxConcurrentGlobal ?? DEFAULTS.maxConcurrentGlobal\n const minIntervalPerHostMs = options.minIntervalPerHostMs ?? DEFAULTS.minIntervalPerHostMs\n const budget = options.maxProbesPerRun ?? DEFAULTS.maxProbesPerRun\n const now = options.now ?? (() => Date.now())\n const sleep = options.sleep ?? defaultSleep\n\n const global = semaphore(Math.max(1, maxConcurrentGlobal))\n const perHost = new Map<string, Semaphore>()\n const nextAllowedAt = new Map<string, number>()\n let used = 0\n\n const hostSemaphore = (host: string): Semaphore => {\n const existing = perHost.get(host)\n if (existing) return existing\n const created = semaphore(Math.max(1, maxConcurrentPerHost))\n perHost.set(host, created)\n return created\n }\n\n return {\n get used() {\n return used\n },\n get budget() {\n return budget\n },\n async acquire(host: string): Promise<LimiterLease> {\n if (used >= budget) throw new ProbeBudgetExceededError(budget)\n used += 1\n\n const key = host.toLowerCase()\n const host$ = hostSemaphore(key)\n await global.acquire()\n try {\n await host$.acquire()\n } catch (error) {\n global.release()\n throw error\n }\n\n const wait = (nextAllowedAt.get(key) ?? 0) - now()\n if (wait > 0) await sleep(wait)\n\n let released = false\n return {\n release(): void {\n if (released) return\n released = true\n nextAllowedAt.set(key, now() + minIntervalPerHostMs)\n host$.release()\n global.release()\n },\n }\n },\n }\n}\n","/**\n * probe/index.ts — `\"./probe\"`. The server-only, deliberately impure half.\n *\n * The pure half (`.`) consumes exactly one thing: an `ArsEvidence` bundle. This\n * file is the only sanctioned way to produce one from a live origin. Everything\n * non-deterministic in ARS is here — sockets, DNS, the clock, sleeping — and\n * nothing here influences a score except through the bundle it returns. The\n * ESLint purity rule in `eslint.config.mjs` exempts `src/probe/**`, and only\n * `src/probe/**`; nothing that needs a clock or a socket may move up a directory.\n *\n * THE REQUEST SET IS CLOSED (§3.3). Per URL: an **agent probe** and a **browser\n * control** that differ in the `Accept` header AND IN NOTHING ELSE — same User\n * Agent, same everything. That is what makes the D2.4 parity check meaningful and\n * what stops a correctly installed gateway, which negotiates on `Accept` and not\n * on UA, from being scored as a cloaker. ARS 0.3 adds one conditional request:\n * when the agent probe got HTML and the page declares a Markdown copy at another\n * same-origin address, that one address is fetched with the agent's headers\n * (`markdownAlternateTarget` in `../score` decides which, for the probe and the\n * scorer alike). Per origin: `/robots.txt` (first), `/llms.txt`,\n * `/.well-known/ucp`. Nothing else. No guessing `/sitemap.xml`,\n * `/mcp`, `/acp` — credit for an endpoint comes from *declaring* it, because an\n * endpoint an agent cannot find is an endpoint that does not exist. The three\n * probed paths are the disclosed exception: published conventions at published\n * locations.\n *\n * WE IMITATE AGENT INTENT, NEVER AGENT IDENTITY. `assertIdentities` refuses a\n * User-Agent that names somebody else's crawler and refuses an agent/browser\n * pair whose UAs differ. The printed consequence, which belongs next to the\n * parity check and not in a footnote: ARS cannot detect UA-targeted cloaking,\n * including cloaking aimed at `rebilder-ars` itself.\n *\n * THE TWO DEFECTS THIS FILE EXISTS TO CLOSE (design §5.2):\n * - **DNS.** The ancestor guard rejected IP literals and resolved nothing. See\n * `./ssrf`: we resolve, we reject if any answer is reserved, we connect\n * pinned to the validated address, and we re-resolve and re-pin on every hop.\n * - **Byte cap.** The ancestor called `await response.text()` with no limit.\n * Bodies are streamed through `getReader()`, decoded bytes are counted, the\n * read is aborted at the ruleset's 2 MiB and `truncated: true` is recorded.\n * Silently scoring a truncated body would make the heaviest pages score best\n * on D3.2 — the one number the product is built on.\n *\n * WHAT THIS FILE DOES NOT DO. It does not take the §3.8 parity-confirm probe\n * (`probes.parityConfirm` is always `null` here): that one is taken ≥30s after a\n * divergence is detected, which is a scan-orchestration decision, not something\n * to hide inside a call with a 5s budget. It does not cache; caching is the\n * caller's, because the cache key is the caller's. And it does not decide what a\n * result means — `score()` does, from the bundle alone.\n */\n\nimport type {\n ArsEvidence,\n ArsHttpCapture,\n ArsProbeError,\n ArsProbeRecord,\n ArsRuleset,\n ArsVantage,\n} from '../types'\nimport { DEFAULT_RULESET } from '../ruleset'\nimport { utf8Length } from '../extract'\nimport { ARS_ROBOTS_TOKEN, robotsDisallowsScanner } from '../robots-policy'\nimport { AGENT_ACCEPT, ASSET_ACCEPT, BROWSER_ACCEPT } from './headers'\nimport { markdownAlternateTarget, sha256Hex } from '../score'\nimport {\n createDnsResolver,\n createPinnedTransport,\n guardUrl,\n resolveAndValidate,\n type HostPolicy,\n type HostResolver,\n type ProbeHttpResponse,\n type ProbeTransport,\n} from './ssrf'\nimport { createLimiter, ProbeBudgetExceededError, type Limiter, type LimiterLease } from './limiter'\n\n/* ── re-exports: everything a consumer of \"./probe\" legitimately needs ─────── */\n\nexport {\n classifyIp,\n createDnsResolver,\n createPinnedTransport,\n fromWebResponse,\n guardPreviewUrl,\n guardUrl,\n parseIpv4,\n parseIpv6,\n resolveAndValidate,\n} from './ssrf'\nexport type {\n HostResolver,\n IpClassification,\n PinnedAddress,\n ProbeHttpResponse,\n ProbeRequestInit,\n ProbeTransport,\n ResolveOutcome,\n UrlGuardPolicy,\n UrlGuardResult,\n} from './ssrf'\nexport { createLimiter, ProbeBudgetExceededError } from './limiter'\nexport type { Limiter, LimiterLease, LimiterOptions } from './limiter'\n\n/* ── identities (§3.3) ────────────────────────────────────────────────────── */\n\nexport type ProbeRole = 'agent' | 'browser' | 'asset'\n\nexport interface ProbeIdentity {\n readonly role: ProbeRole\n readonly userAgent: string\n readonly accept: string\n}\n\n/**\n * Honest, contactable, and never anybody else's. The number tracks the spec\n * version, so a server log tells its operator which ruleset scored them.\n *\n * IT IS NOT THE REFUSAL TOKEN. A site that disallowed us under 0.1 is still\n * refusing us under 0.2, because robots.txt is matched on `ARS_ROBOTS_TOKEN`\n * below and that string never moves. Versioning the refusal token would let a\n * spec bump quietly re-open sites that already said no.\n */\nexport const ARS_USER_AGENT = 'rebilder-ars/0.3 (+https://rebilder.com/bots)'\n\n/**\n * Re-exported, not defined here: the token and the refusal decision moved to\n * `../robots-policy` when a second probe (the browser extension) needed to\n * honour the same refusals without importing this module. See the note there.\n */\nexport { ARS_ROBOTS_TOKEN }\n\nexport { AGENT_ACCEPT, ASSET_ACCEPT, BROWSER_ACCEPT } from './headers'\n\nconst AGENT_IDENTITY: ProbeIdentity = {\n role: 'agent',\n userAgent: ARS_USER_AGENT,\n accept: AGENT_ACCEPT,\n}\nconst BROWSER_IDENTITY: ProbeIdentity = {\n role: 'browser',\n userAgent: ARS_USER_AGENT,\n accept: BROWSER_ACCEPT,\n}\nconst ASSET_IDENTITY: ProbeIdentity = {\n role: 'asset',\n userAgent: ARS_USER_AGENT,\n accept: ASSET_ACCEPT,\n}\n\nexport const DEFAULT_IDENTITIES: readonly ProbeIdentity[] = Object.freeze([\n AGENT_IDENTITY,\n BROWSER_IDENTITY,\n ASSET_IDENTITY,\n])\n\n/**\n * Crawler names we refuse to wear. Not a completeness claim — it is a tripwire\n * for the specific mistake of \"just set the UA to Googlebot and see what they\n * serve\", which is the one request this package must never make on anyone's\n * behalf.\n */\nconst IMPERSONATION_TOKENS = [\n 'googlebot',\n 'bingbot',\n 'applebot',\n 'baiduspider',\n 'yandexbot',\n 'duckduckbot',\n 'slurp',\n 'gptbot',\n 'chatgpt',\n 'oai-searchbot',\n 'claudebot',\n 'claude-user',\n 'claude-searchbot',\n 'anthropic-ai',\n 'perplexitybot',\n 'perplexity-user',\n 'facebookexternalhit',\n 'meta-external',\n] as const\n\nfunction assertIdentities(identities: readonly ProbeIdentity[]): string | null {\n const byRole = new Map<ProbeRole, ProbeIdentity>()\n for (const identity of identities) byRole.set(identity.role, identity)\n const agent = byRole.get('agent')\n const browser = byRole.get('browser')\n if (agent === undefined || browser === undefined) {\n return 'the identity set must contain an \"agent\" and a \"browser\" entry (§3.3)'\n }\n if (agent.userAgent !== browser.userAgent) {\n return 'the agent and browser probes must send the SAME User-Agent and differ only in Accept (§3.3) — a UA difference makes the parity check measure our own request instead of the page'\n }\n for (const identity of identities) {\n const ua = identity.userAgent.toLowerCase()\n for (const token of IMPERSONATION_TOKENS) {\n if (ua.includes(token)) {\n return `the User-Agent names another operator's crawler (\"${token}\"). ARS imitates agent intent, never agent identity (§3.3)`\n }\n }\n }\n return null\n}\n\n/* ── policy ───────────────────────────────────────────────────────────────── */\n\n/**\n * Policy as a type rather than a pile of booleans — and note what is NOT here:\n * there is no `allowPrivateHosts`. Private/loopback targets are unlocked by\n * importing a different entry point (`./probe/local`), which throws at import\n * time without a per-invocation opt-in, not by flipping a field on a config\n * object that somebody will one day copy into a hosted route.\n */\nexport interface ProbePolicy {\n /** Default false. True only under `./probe/local`. */\n allowHttp: boolean\n /** 2 MiB, from the ruleset. Normative: two caps produce two different scores. */\n maxBodyBytes: number\n /** 3, from the ruleset. */\n maxRedirects: number\n /** 5 000ms, from the ruleset. */\n timeoutMs: number\n /** Injected, never module-global. See `./limiter` for why that matters. */\n limiter: Limiter\n identities: readonly ProbeIdentity[]\n}\n\n/**\n * The hosted policy: https only, ruleset caps, default identities. The limiter\n * is a required argument because \"who owns this run's budget\" is a question the\n * caller has to answer, and a default would answer it wrongly in a warm\n * serverless instance.\n */\nexport function strictPolicy(limiter: Limiter, ruleset: ArsRuleset = DEFAULT_RULESET): ProbePolicy {\n return {\n allowHttp: false,\n maxBodyBytes: ruleset.maxBodyBytes,\n maxRedirects: ruleset.maxRedirects,\n timeoutMs: ruleset.timeoutMs,\n limiter,\n identities: DEFAULT_IDENTITIES,\n }\n}\n\n/* ── options and outcome ──────────────────────────────────────────────────── */\n\nexport interface ProbeOptions {\n /** Default `'public'`. Only `'public'` is gated on the `rebilder-ars` token. */\n vantage?: ArsVantage\n /** Default: DNS-pinned `node:https`. Injected in tests; never bypasses the guard. */\n transport?: ProbeTransport\n /** Default: real DNS. Validation runs whatever transport is in use. */\n resolver?: HostResolver\n /** Default: wall clock. Feeds `ArsEvidence.capturedAt`, which is excluded from the hash. */\n now?: () => Date\n sleep?: (ms: number) => Promise<void>\n /** §3.3: one retry after 5s before a 5xx robots.txt becomes `robots-unavailable`. */\n robotsRetryDelayMs?: number\n}\n\n/**\n * Why `rejection` is not an `ArsUnscoredReason`: these are the cases where no\n * evidence bundle exists at all, so there is nothing for `score()` to judge.\n * Everything the origin actually said — a 404, a 500, a timeout, a redirect loop\n * — comes back as `{ ok: true }` with the failure recorded inside the bundle,\n * because that IS the observation.\n */\nexport type ProbeRejection = 'invalid-url' | 'policy-rejected' | 'budget-exceeded'\n\nexport type ProbeOutcome =\n | { ok: true; evidence: ArsEvidence }\n | { ok: false; rejection: ProbeRejection; detail: string }\n\n/* ── body reading: streamed, counted, capped ──────────────────────────────── */\n\ninterface DecodedBody {\n text: string\n /** UTF-8 byte length of `text` — the normative measurement (§3.3). */\n bytes: number\n truncated: boolean\n}\n\n/** `charset` from Content-Type, defaulting to UTF-8 (§3.3). */\nfunction charsetOf(headers: Record<string, string[]>): string {\n const value = headers['content-type']?.[0]\n if (value === undefined) return 'utf-8'\n const match = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i.exec(value)\n return match?.[1]?.toLowerCase() ?? 'utf-8'\n}\n\nfunction createDecoder(charset: string): TextDecoder {\n try {\n return new TextDecoder(charset, { fatal: false })\n } catch {\n return new TextDecoder('utf-8', { fatal: false })\n }\n}\n\n/** Largest prefix of `chunk` whose UTF-8 length fits in `budget`, split on code points. */\nfunction fitPrefix(chunk: string, budget: number): string {\n let out = ''\n let used = 0\n for (const codePoint of chunk) {\n const size = utf8Length(codePoint)\n if (used + size > budget) break\n out += codePoint\n used += size\n }\n return out\n}\n\n/**\n * Streams the body, counting decoded UTF-8 bytes, and cancels the read the\n * moment the cap is reached. `await response.text()` is forbidden by §3.3 and is\n * the live defect this replaces: `BODY_PREVIEW_CHARS` in the Console preview\n * truncated only what was *stored*, so a 4 GB response was still fully buffered\n * into the server's heap before anything was trimmed.\n *\n * The NORMATIVE cap is on decoded UTF-8 bytes (§3.3), because that is the number\n * D3.2 scores and two implementations counting different things produce\n * different scores. Wire bytes carry a separate, much looser ceiling whose only\n * job is to bound the read for a charset that SHRINKS on decode — UTF-16 halves,\n * so without it a 2 MiB decoded cap would let 4 MiB off the socket. It is set\n * well above any real ratio on purpose: making it tight would mark a perfectly\n * complete UTF-16 page as `truncated`, and a false truncation flag is a lie\n * about the evidence.\n */\nasync function readCappedBody(\n body: ReadableStream<Uint8Array> | null,\n charset: string,\n maxBytes: number,\n): Promise<DecodedBody> {\n if (body === null) return { text: '', bytes: 0, truncated: false }\n\n const decoder = createDecoder(charset)\n const reader = body.getReader()\n const parts: string[] = []\n /** Backstop only; see the note above. No real charset shrinks by 4×. */\n const rawCeiling = maxBytes * 4\n let bytes = 0\n let rawBytes = 0\n let truncated = false\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value === undefined) continue\n rawBytes += value.byteLength\n\n const chunk = decoder.decode(value, { stream: true })\n const chunkBytes = utf8Length(chunk)\n if (bytes + chunkBytes > maxBytes) {\n const prefix = fitPrefix(chunk, maxBytes - bytes)\n if (prefix.length > 0) parts.push(prefix)\n bytes += utf8Length(prefix)\n truncated = true\n break\n }\n parts.push(chunk)\n bytes += chunkBytes\n\n if (rawBytes >= rawCeiling) {\n truncated = true\n break\n }\n }\n if (!truncated) {\n const tail = decoder.decode()\n if (tail.length > 0) {\n const tailBytes = utf8Length(tail)\n if (bytes + tailBytes > maxBytes) {\n const prefix = fitPrefix(tail, maxBytes - bytes)\n parts.push(prefix)\n bytes += utf8Length(prefix)\n truncated = true\n } else {\n parts.push(tail)\n bytes += tailBytes\n }\n }\n }\n } finally {\n // Cancelling is what actually stops the socket; without it the cap only\n // limits what we keep, not what the origin sends us.\n await reader.cancel().catch(() => undefined)\n }\n\n return { text: parts.join(''), bytes, truncated }\n}\n\n/* ── one request, with the full guard on every hop ────────────────────────── */\n\ninterface FetchContext {\n readonly policy: ProbePolicy\n readonly hostPolicy: HostPolicy\n readonly transport: ProbeTransport\n readonly resolver: HostResolver\n}\n\ntype FetchResult = ArsProbeRecord['result']\n\nfunction failed(error: ArsProbeError, detail: string): FetchResult {\n return { ok: false, error, detail }\n}\n\nfunction classifyTransportError(error: unknown, signal: AbortSignal): ArsProbeError {\n const reason: unknown = signal.aborted ? signal.reason : undefined\n if (reason instanceof Error && reason.name === 'TimeoutError') return 'timeout'\n if (error instanceof Error && error.name === 'TimeoutError') return 'timeout'\n if (signal.aborted) return 'timeout'\n return 'unreachable'\n}\n\nasync function fetchWithPolicy(\n startUrl: string,\n headers: Readonly<Record<string, string>>,\n context: FetchContext,\n): Promise<FetchResult> {\n const { policy, hostPolicy, transport, resolver } = context\n const redirects: { status: number; location: string }[] = []\n let current = startUrl\n\n // `hop < maxRedirects`, not `<=`. The shipped Console loop used `<=` and\n // therefore allowed four requests where the ruleset says three (§3.3).\n for (let hop = 0; hop < policy.maxRedirects; hop++) {\n const blocked: ArsProbeError = hop === 0 ? 'policy-rejected' : 'blocked-redirect'\n\n const guard = guardUrl(current, { allowHttp: policy.allowHttp, hostPolicy })\n if (!guard.ok) return failed(blocked, guard.reason)\n\n // Re-resolve and re-pin on EVERY hop. Re-parsing the Location URL is not\n // enough: hop 2 is a new connection to a new name.\n const resolved = await resolveAndValidate(guard.url.hostname, resolver, hostPolicy)\n if (!resolved.ok) {\n return failed(resolved.kind === 'unreachable' ? 'unreachable' : blocked, resolved.reason)\n }\n\n // Politeness before the socket, not after. A `ProbeBudgetExceededError` is\n // deliberately allowed to propagate: half a bundle is not evidence, so the\n // whole probe reports `budget-exceeded` rather than a partial observation.\n const lease: LimiterLease = await policy.limiter.acquire(guard.url.hostname)\n\n const signal = AbortSignal.timeout(policy.timeoutMs)\n let response: ProbeHttpResponse\n try {\n response = await transport(guard.url.toString(), {\n headers,\n redirect: 'manual',\n signal,\n pinnedAddresses: resolved.addresses,\n })\n } catch (error) {\n lease.release()\n const kind = classifyTransportError(error, signal)\n return failed(\n kind,\n kind === 'timeout'\n ? `No response within ${policy.timeoutMs}ms.`\n : `The URL could not be reached: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers['location']?.[0]\n // Drain and drop: a redirect body is not evidence, and leaving the stream\n // open leaves the socket open.\n if (response.body !== null) await response.body.cancel().catch(() => undefined)\n lease.release()\n if (location === undefined || location.trim() === '') {\n return failed('non-2xx', `Redirect (${response.status}) without a Location header.`)\n }\n let next: string\n try {\n next = new URL(location, guard.url).toString()\n } catch {\n return failed('blocked-redirect', `Redirect to an unparseable Location: ${location}`)\n }\n redirects.push({ status: response.status, location: next })\n current = next\n continue\n }\n\n let decoded: DecodedBody\n try {\n decoded = await readCappedBody(\n response.body,\n charsetOf(response.headers),\n policy.maxBodyBytes,\n )\n } catch (error) {\n const kind = classifyTransportError(error, signal)\n return failed(\n kind,\n `The response body could not be read: ${error instanceof Error ? error.message : String(error)}`,\n )\n } finally {\n lease.release()\n }\n\n const capture: ArsHttpCapture = {\n requestedUrl: startUrl,\n finalUrl: guard.url.toString(),\n redirects,\n status: response.status,\n headers: response.headers,\n bytes: decoded.bytes,\n bodySha256: sha256Hex(decoded.text),\n body: decoded.text,\n truncated: decoded.truncated,\n }\n return { ok: true, capture }\n }\n\n return failed('too-many-redirects', `More than ${policy.maxRedirects - 1} redirects.`)\n}\n\n/* ── robots ───────────────────────────────────────────────────────────────── */\n\n/* ── the probe ────────────────────────────────────────────────────────────── */\n\nfunction headersFor(identity: ProbeIdentity): Record<string, string> {\n return { accept: identity.accept, 'user-agent': identity.userAgent }\n}\n\nfunction identityFor(policy: ProbePolicy, role: ProbeRole): ProbeIdentity {\n const found = policy.identities.find((identity) => identity.role === role)\n // `assertIdentities` guarantees agent/browser; `asset` falls back to agent.\n return found ?? policy.identities.find((identity) => identity.role === 'agent') ?? AGENT_IDENTITY\n}\n\nfunction skipped(headers: Record<string, string>, detail: string): ArsProbeRecord {\n return { requestHeaders: headers, result: { ok: false, error: 'policy-rejected', detail } }\n}\n\n/**\n * `hostPolicy` is a capability, not a flag: the only value other than\n * `'public-only'` is a symbol exported from a non-entry-point module, so a\n * consumer of `\"./probe\"` cannot construct one. Exported because\n * `\"./probe/local\"` has to call it; harmless because calling it without the\n * symbol is exactly `probeStrict`.\n */\nexport async function probeWithHostPolicy(\n target: string,\n policy: ProbePolicy,\n hostPolicy: HostPolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n const identityProblem = assertIdentities(policy.identities)\n if (identityProblem !== null) {\n return { ok: false, rejection: 'policy-rejected', detail: identityProblem }\n }\n\n // \"Unparseable\" and \"parseable but refused\" are different answers to the\n // caller — the CLI exit-code contract splits them (2 = usage, 4 = policy) —\n // so they are distinguished by re-parsing rather than by matching on the\n // guard's message text.\n let parseable = true\n try {\n void new URL(target.trim())\n } catch {\n parseable = false\n }\n\n const guard = guardUrl(target, { allowHttp: policy.allowHttp, hostPolicy })\n if (!guard.ok) {\n return {\n ok: false,\n rejection: parseable ? 'policy-rejected' : 'invalid-url',\n detail: guard.reason,\n }\n }\n\n const context: FetchContext = {\n policy,\n hostPolicy,\n transport: options.transport ?? createPinnedTransport(),\n resolver: options.resolver ?? createDnsResolver(),\n }\n const vantage = options.vantage ?? 'public'\n const now = options.now ?? (() => new Date())\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))\n const robotsRetryDelayMs = options.robotsRetryDelayMs ?? 5_000\n\n const url = guard.url\n const origin = url.origin\n const assetHeaders = headersFor(identityFor(policy, 'asset'))\n const agentHeaders = headersFor(identityFor(policy, 'agent'))\n const browserHeaders = headersFor(identityFor(policy, 'browser'))\n\n const run = async (href: string, headers: Record<string, string>): Promise<ArsProbeRecord> => {\n try {\n return { requestHeaders: headers, result: await fetchWithPolicy(href, headers, context) }\n } catch (error) {\n if (error instanceof ProbeBudgetExceededError) throw error\n return {\n requestHeaders: headers,\n result: {\n ok: false,\n error: 'unreachable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n\n const evidenceOf = (probes: ArsEvidence['probes']): ProbeOutcome => ({\n ok: true,\n evidence: {\n evidenceVersion: '0.1.0',\n target: { url: url.toString(), origin },\n probes,\n vantage,\n capturedAt: now().toISOString(),\n },\n })\n\n try {\n // 1 — robots.txt, first, always. §3.3.\n let robotsTxt = await run(`${origin}/robots.txt`, assetHeaders)\n const robotsUnavailable = (record: ArsProbeRecord): boolean =>\n !record.result.ok || record.result.capture.status >= 500\n // Retry a transport hiccup or a 5xx. NEVER retry a refusal: a target we\n // declined on policy grounds will be declined identically in five seconds,\n // and sleeping first only makes the caller wait for the same answer.\n const worthRetrying = (record: ArsProbeRecord): boolean =>\n record.result.ok\n ? record.result.capture.status >= 500\n : record.result.error === 'unreachable' || record.result.error === 'timeout'\n if (worthRetrying(robotsTxt)) {\n // A single hiccup does not un-score a domain; a persistent 5xx does.\n await sleep(robotsRetryDelayMs)\n robotsTxt = await run(`${origin}/robots.txt`, assetHeaders)\n }\n if (robotsUnavailable(robotsTxt)) {\n const detail =\n 'robots.txt returned a persistent error; a policy we could not read is not a policy we may assume'\n return evidenceOf({\n agent: skipped(agentHeaders, detail),\n browser: skipped(browserHeaders, detail),\n parityConfirm: null,\n robotsTxt,\n llmsTxt: null,\n wellKnownUcp: null,\n })\n }\n\n const robotsBody = robotsTxt.result.ok ? (robotsTxt.result.capture.body ?? '') : ''\n const robotsUsable = robotsTxt.result.ok && robotsTxt.result.capture.status < 400\n const disallowedFor = (path: string): string | null =>\n vantage === 'public' && robotsUsable ? robotsDisallowsScanner(robotsBody, path) : null\n\n // 2 — we obey our own token, and we do not fetch what it forbids.\n const pageRule = disallowedFor(url.pathname)\n if (pageRule !== null) {\n const detail = `robots.txt disallows the ${ARS_ROBOTS_TOKEN} token (${pageRule})`\n return evidenceOf({\n agent: skipped(agentHeaders, detail),\n browser: skipped(browserHeaders, detail),\n parityConfirm: null,\n robotsTxt,\n llmsTxt: null,\n wellKnownUcp: null,\n })\n }\n\n // 3 — agent, then browser control. Sequential: two quick hits are gentler on\n // an origin than a simultaneous pair, and the limiter spaces them anyway.\n const agent = await run(url.toString(), agentHeaders)\n const browser = await run(url.toString(), browserHeaders)\n\n // 3b — the Markdown copy the page links to, when it did not send one (ARS 0.3).\n const linked = markdownAlternateTarget(\n agent.result.ok ? agent.result.capture : null,\n browser.result.ok ? browser.result.capture : null,\n origin,\n )\n let markdownAlternate: ArsProbeRecord | null = null\n if (linked !== null) {\n const rule = disallowedFor(new URL(linked).pathname)\n markdownAlternate =\n rule !== null\n ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`)\n : await run(linked, agentHeaders)\n }\n\n // 4 — the two origin-level conventions, and nothing else.\n const fetchAsset = async (path: string): Promise<ArsProbeRecord | null> => {\n const rule = disallowedFor(path)\n if (rule !== null)\n return skipped(assetHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${path}`)\n return run(`${origin}${path}`, assetHeaders)\n }\n const llmsTxt = await fetchAsset('/llms.txt')\n const wellKnownUcp = await fetchAsset('/.well-known/ucp')\n\n return evidenceOf({\n agent,\n browser,\n parityConfirm: null,\n // Omitted when not taken, so a page with no linked copy produces exactly\n // the bundle (and the evidence hash) it produced under 0.2.\n ...(markdownAlternate === null ? {} : { markdownAlternate }),\n robotsTxt,\n llmsTxt,\n wellKnownUcp,\n })\n } catch (error) {\n if (error instanceof ProbeBudgetExceededError) {\n return { ok: false, rejection: 'budget-exceeded', detail: error.message }\n }\n throw error\n }\n}\n\n/**\n * The hosted probe. https only, public hosts only, DNS-validated and pinned,\n * 2 MiB streamed cap, robots-gated, limiter-gated.\n *\n * There is deliberately no argument that relaxes any of that. `probeLocal` lives\n * at `\"./probe/local\"`, throws at import time without a per-invocation opt-in,\n * and is imported by the CLI and by nothing that can be reached over HTTP.\n */\nexport function probeStrict(\n target: string,\n policy: ProbePolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n return probeWithHostPolicy(target, policy, 'public-only', options)\n}\n\n/** Convenience for one-off callers: a fresh run-scoped limiter and the strict policy. */\nexport function strictPolicyForRun(overrides: Partial<ProbePolicy> = {}): ProbePolicy {\n return { ...strictPolicy(createLimiter()), ...overrides }\n}\n\n/**\n * The type is exported so `probeWithHostPolicy`'s signature is nameable. The\n * *value* — the `ALLOW_PRIVATE_HOSTS` symbol — is deliberately NOT re-exported\n * here: it lives in `./ssrf`, which `package.json#exports` does not publish, so\n * the only way to hold it is to be inside this package. Re-exporting it from\n * `\"./probe\"` would turn the capability straight back into the boolean it was\n * designed to replace.\n */\nexport type { HostPolicy }\n","/**\n * probe/local.ts — `\"./probe/local\"`. Private hosts and plain http, and NOTHING\n * that can be reached over HTTP.\n *\n * WHY THIS IS A SEPARATE ENTRY POINT THAT THROWS ON IMPORT, RATHER THAN A FLAG.\n *\n * The obvious design is `probe(url, { allowPrivateHosts: true })`. It is wrong,\n * and the reason is worth writing down because the wrong version looks fine in\n * review. `ProbePolicy` is a plain object that gets built once and reused. A\n * boolean on it is a boolean somebody will set to `true` — not maliciously, but\n * because they are wiring a new route, the local config already works, and\n * copying it is the obvious move. The moment that happens, an SSRF guard exists\n * in the codebase and is switched off in production, and nothing about the diff\n * looks like a security change.\n *\n * The concrete failure this prevents: `@rebilder/mcp-server` runs on a\n * developer's machine, inside their network, driven by a model whose context\n * contains web pages we did not write. \"Check http://169.254.169.254/ for me\"\n * arriving as text inside a scraped page is not a hypothetical — it is the\n * standard prompt-injection payload, and a company whose entire product is *what\n * agents read* cannot ship the tool that fetches it on request.\n *\n * So the permission is a capability, held three ways at once:\n * 1. It is a DIFFERENT MODULE. `probeStrict` cannot reach it; nothing that\n * imports `\"./probe\"` gets it transitively.\n * 2. It THROWS AT IMPORT TIME unless the process was started with\n * `--allow-private`. A process argument is not configuration: a serverless\n * handler's argv is set by the platform, not by our env file or our JSON,\n * so there is no way to switch this on from a dashboard or a `.env`.\n * 3. It REFUSES OUTRIGHT in a serverless/edge runtime, flag or no flag. If we\n * are running inside a request handler, the answer is no, and there is no\n * argument to be had about it.\n *\n * The permission is per invocation. `rebilder check --allow-private\n * http://staging.internal.corp` is a thing a developer chose to type on their own\n * machine. It is never a default, never an env var, and never inherited.\n *\n * NOTE ON THE PAIR OF GUARANTEES: the CLI and MCP server ship zero telemetry\n * (a project convention). That is not decoration next to this file — a probe\n * that reaches internal hostnames and a binary that uploads what it found are\n * only safe together as long as the second half stays false.\n */\n\nimport { ALLOW_PRIVATE_HOSTS } from './ssrf'\nimport {\n probeWithHostPolicy,\n strictPolicy,\n type ProbeOptions,\n type ProbeOutcome,\n type ProbePolicy,\n} from './index'\nimport { type Limiter } from './limiter'\nimport type { ArsRuleset } from '../types'\nimport { DEFAULT_RULESET } from '../ruleset'\n\n/** The one accepted opt-in. A CLI flag, on purpose: argv is not configuration. */\nexport const ALLOW_PRIVATE_FLAG = '--allow-private'\n\n/**\n * Environment markers that mean \"this process is serving HTTP requests\". Any of\n * them present is a hard refusal: local mode exists for a human at a terminal.\n */\nconst HOSTED_RUNTIME_MARKERS = [\n 'VERCEL',\n 'NEXT_RUNTIME',\n 'AWS_LAMBDA_FUNCTION_NAME',\n 'AWS_EXECUTION_ENV',\n 'FUNCTIONS_WORKER_RUNTIME',\n 'K_SERVICE',\n 'CF_PAGES',\n] as const\n\nfunction hostedRuntimeMarker(): string | null {\n for (const key of HOSTED_RUNTIME_MARKERS) {\n const value = process.env[key]\n if (typeof value === 'string' && value.length > 0) return key\n }\n return null\n}\n\n/**\n * The import-time gate. Runs on module evaluation — before anything can call\n * `probeLocal`, and before a bundler can tree-shake the check away from the\n * function it protects.\n */\nfunction assertLocalModeUnlocked(): void {\n const hosted = hostedRuntimeMarker()\n if (hosted !== null) {\n throw new Error(\n `@rebilder/agent-readability/probe/local: refusing to load in a hosted runtime (${hosted} is set). ` +\n 'Local mode allows private and loopback targets and must never be reachable from an HTTP transport. ' +\n 'Use probeStrict() from \"@rebilder/agent-readability/probe\".',\n )\n }\n if (!process.argv.includes(ALLOW_PRIVATE_FLAG)) {\n throw new Error(\n `@rebilder/agent-readability/probe/local: refusing to load without ${ALLOW_PRIVATE_FLAG}. ` +\n 'Private hosts, loopback, link-local and cloud-metadata addresses are reachable through this entry point, ' +\n 'so the permission is per invocation and comes from the command line — not from a config object, ' +\n 'not from an environment variable, and never by default.',\n )\n }\n}\n\nassertLocalModeUnlocked()\n\n/**\n * The local policy: http allowed, non-standard ports allowed, private hosts\n * allowed. Everything else — the streamed byte cap, the redirect limit, the\n * timeout, the politeness limiter, the robots gate — is unchanged, because none\n * of those exist to protect us from ourselves.\n */\nexport function localPolicy(limiter: Limiter, ruleset: ArsRuleset = DEFAULT_RULESET): ProbePolicy {\n return { ...strictPolicy(limiter, ruleset), allowHttp: true }\n}\n\n/**\n * Probes a target that may be private, loopback, or plain http.\n *\n * `vantage` defaults to `'self'` rather than `'public'`: someone running this\n * against their own staging host is the operator of that host, and §3.7 says the\n * owner can consent for their own origin. It also means the `rebilder-ars`\n * robots gate does not apply, which is correct — you do not need your own\n * permission to read your own site.\n */\nexport function probeLocal(\n target: string,\n policy: ProbePolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n return probeWithHostPolicy(target, policy, ALLOW_PRIVATE_HOSTS, {\n ...options,\n vantage: options.vantage ?? 'self',\n })\n}\n"]}
1
+ {"version":3,"sources":["../../src/probe/ssrf.ts","../../src/profiles.ts","../../src/ruleset.ts","../../src/html.ts","../../src/extract.ts","../../src/robots-policy.ts","../../src/probe/headers.ts","../../src/score.ts","../../src/site-signals.ts","../../src/probe/limiter.ts","../../src/probe/index.ts","../../src/probe/local.ts"],"names":["dnsPromises","deepFreeze","a","b"],"mappings":";;;;;AAgEO,IAAM,mBAAA,0BAA4C,wCAAwC,CAAA;AAK1F,IAAM,kBAAA,GAAqB,CAAC,MAAA,KAAgC,MAAA,KAAW,mBAAA;AAa9E,IAAM,YAA8B,EAAE,MAAA,EAAQ,MAAM,QAAA,EAAU,KAAA,EAAO,OAAO,UAAA,EAAW;AAEvF,IAAM,UAAA,GAAa,sBAAA;AAGZ,SAAS,UAAU,IAAA,EAAuD;AAC/E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC5B,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,IAAI,GAAG,OAAO,IAAA;AACnC,IAAA,MAAM,KAAA,GAAQ,OAAO,IAAI,CAAA;AACzB,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,KAAA,GAAQ,KAAK,OAAO,IAAA;AACpD,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,EACnB;AACA,EAAA,MAAM,CAAC,CAAA,EAAG,CAAA,EAAG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AAA,EAA8B;AAChG,EAAA,OAAO,EAAE,GAAG,YAAA,CAAa,SAAS,OAAO,CAAA,EAAG,WAAW,IAAA,EAAK;AAC9D;AAWO,SAAS,UAAA,CACd,MAAA,EACA,MAAA,EACA,OAAA,GAAwB,EAAC,EACF;AACvB,EAAA,OAAO,mBAAA,CAAoB,MAAA,EAAQ,MAAA,EAAQ,mBAAA,EAAqB;AAAA,IAC9D,GAAG,OAAA;AAAA,IACH,OAAA,EAAS,QAAQ,OAAA,IAAW;AAAA,GAC7B,CAAA;AACH","file":"local.js","sourcesContent":["/**\n * probe/ssrf.ts — the network-side host policy for `@rebilder/agent-readability`.\n *\n * WHAT CHANGED, AND WHY IT HAD TO. The ancestor of this file (the Console\n * preview's URL guard) described itself as *\"Pure parse +\n * reject (no DNS resolution in v1)\"*. That sentence is deliberately not repeated\n * here, because it is a description of a hole. A parse-only guard rejects IP\n * literals; it does not reject `https://attacker.example/` whose A record is\n * `169.254.169.254`, `10.0.0.5` or `127.0.0.1`, and DNS rebinding beats it by\n * construction — resolve public, pass the guard, resolve private, connect.\n * Behind a Console login that was defensible. On a public endpoint it is not,\n * and this module is the one the public scanner, the CLI and the MCP server all\n * go through. So (design §5.2):\n *\n * 1. WE RESOLVE THE HOSTNAME OURSELVES and reject if **any** returned A/AAAA\n * is private or reserved. Not \"the first one\" — a hostname with one public\n * and one private answer is an attack, not a multi-homed service.\n * 2. WE CONNECT PINNED TO THE VALIDATED IP, with `Host` and SNI still carrying\n * the hostname. This closes the rebinding window: the address the guard\n * approved is the address the socket uses, because the resolver the socket\n * would have called is replaced by a function that returns the approved set\n * and nothing else.\n * 3. EVERY REDIRECT HOP RE-RESOLVES AND RE-PINS. Re-parsing the `Location`\n * URL is not enough; hop 2 is a fresh connection to a fresh name.\n * 4. THE RESERVED SET IS THE FULL ONE — CGNAT (`100.64/10`, which is also\n * where Alibaba keeps its metadata service at `100.100.100.200`), IETF\n * protocol assignments, benchmarking, multicast, the whole of `240/4`,\n * the broadcast address, and the IPv6 equivalents including IPv4-mapped\n * and NAT64/6to4 forms, where a reserved v4 address hides inside a v6 one.\n *\n * WHAT THIS MODULE STILL CANNOT DO. It cannot stop a target whose *public* IP\n * fronts an internal service (a cloud load balancer with a private backend), and\n * it cannot stop a captive network from answering for someone else. Design §5.2\n * requires the belt to the braces: scanner egress runs on a network with no route\n * to cloud metadata or any internal subnet. This file assumes that and does not\n * replace it.\n *\n * NOT AN ENTRY POINT. `package.json#exports` publishes `.`, `./probe` and\n * `./probe/local` only, so `ALLOW_PRIVATE_HOSTS` below is unreachable from\n * outside the package at runtime, and the package-graph check fails any deep\n * import that tries. That is what makes the symbol an unforgeable capability\n * rather than a naming convention.\n */\n\nimport { promises as dnsPromises } from 'node:dns'\nimport * as http from 'node:http'\nimport * as https from 'node:https'\nimport type { LookupFunction } from 'node:net'\n\n/* ── the host policy capability ───────────────────────────────────────────── */\n\n/**\n * The capability that unlocks private/loopback targets. Held by `./probe/local`\n * and by nothing else.\n *\n * WHY A SYMBOL AND NOT A BOOLEAN. `ProbePolicy` (see `./index`) has no\n * `allowPrivateHosts` field on purpose. A boolean on a shared config object will\n * eventually be passed as `true` by a hosted endpoint — not maliciously, just by\n * someone wiring a new route who copies a working config. The concrete failure:\n * an MCP server on a developer's machine, driven by a model whose context\n * contains untrusted web text, asked to \"check http://169.254.169.254/\". A symbol\n * that only a separate, import-time-gated entry point can obtain cannot be turned\n * on by a config file, an env var, or a copied object literal.\n */\nexport const ALLOW_PRIVATE_HOSTS: unique symbol = Symbol('rebilder.ars.probe.allow-private-hosts')\n\n/** `'public-only'` everywhere except the `./probe/local` entry point. */\nexport type HostPolicy = 'public-only' | typeof ALLOW_PRIVATE_HOSTS\n\nexport const allowsPrivateHosts = (policy: HostPolicy): boolean => policy === ALLOW_PRIVATE_HOSTS\n\n/* ── IP classification ────────────────────────────────────────────────────── */\n\nexport interface IpClassification {\n /** `null` when the text is not an IP literal at all (i.e. it is a hostname). */\n readonly family: 4 | 6 | null\n /** True for anything that is not a globally routable unicast address. */\n readonly reserved: boolean\n /** Human-readable reason, printed in guard messages and probe details. */\n readonly label: string\n}\n\nconst NOT_AN_IP: IpClassification = { family: null, reserved: false, label: 'hostname' }\n\nconst IPV4_OCTET = /^(?:0|[1-9]\\d{0,2})$/\n\n/** Strict dotted-quad. Leading zeros are rejected: `010.0.0.1` is ambiguous octal. */\nexport function parseIpv4(text: string): [number, number, number, number] | null {\n const parts = text.split('.')\n if (parts.length !== 4) return null\n const octets: number[] = []\n for (const part of parts) {\n if (!IPV4_OCTET.test(part)) return null\n const value = Number(part)\n if (!Number.isInteger(value) || value > 255) return null\n octets.push(value)\n }\n const [a, b, c, d] = octets\n if (a === undefined || b === undefined || c === undefined || d === undefined) return null\n return [a, b, c, d]\n}\n\n/**\n * IPv4 reserved ranges. The first six shipped in the Console guard; the rest are\n * the §5.2 expansion. `255.255.255.255` is inside `240/4` and is listed anyway\n * because the design lists it and a reader should not have to do the arithmetic.\n */\nfunction classifyIpv4Octets(octets: readonly [number, number, number, number]): IpClassification {\n const [a, b] = octets\n const v4 = (label: string, reserved: boolean): IpClassification => ({\n family: 4,\n reserved,\n label,\n })\n\n if (a === 0) return v4('this-network (0.0.0.0/8)', true)\n if (a === 10) return v4('private (10.0.0.0/8)', true)\n if (a === 100 && b >= 64 && b <= 127) return v4('carrier-grade NAT (100.64.0.0/10)', true)\n if (a === 127) return v4('loopback (127.0.0.0/8)', true)\n if (a === 169 && b === 254) return v4('link-local / cloud metadata (169.254.0.0/16)', true)\n if (a === 172 && b >= 16 && b <= 31) return v4('private (172.16.0.0/12)', true)\n if (a === 192 && b === 0 && octets[2] === 0)\n return v4('IETF protocol assignments (192.0.0.0/24)', true)\n if (a === 192 && b === 168) return v4('private (192.168.0.0/16)', true)\n if (a === 198 && (b === 18 || b === 19)) return v4('benchmarking (198.18.0.0/15)', true)\n if (a >= 224 && a <= 239) return v4('multicast (224.0.0.0/4)', true)\n if (a >= 240) return v4('reserved / broadcast (240.0.0.0/4)', true)\n return v4('public', false)\n}\n\n/**\n * IPv6 to eight 16-bit groups. Handles `::` compression, a zone id, and the\n * trailing-IPv4 forms (`::ffff:169.254.169.254`, `64:ff9b::10.0.0.5`) that are\n * the whole reason IPv6 belongs in an SSRF guard at all.\n */\nexport function parseIpv6(input: string): number[] | null {\n let text = input.trim()\n if (text.startsWith('[') && text.endsWith(']')) text = text.slice(1, -1)\n const zone = text.indexOf('%')\n if (zone !== -1) text = text.slice(0, zone)\n if (text.length === 0 || !text.includes(':')) return null\n\n // A trailing dotted quad is the last two groups. Rewriting it as hex up front\n // means the rest of the parser only ever sees hex groups and `::` — the\n // alternative (splicing groups back on afterwards) is where the separator\n // colon gets miscounted and `64:ff9b::10.0.0.5` silently fails to parse.\n const lastColon = text.lastIndexOf(':')\n const maybeV4 = text.slice(lastColon + 1)\n if (maybeV4.includes('.')) {\n const quad = parseIpv4(maybeV4)\n if (quad === null) return null\n const hi = ((quad[0] << 8) | quad[1]).toString(16)\n const lo = ((quad[2] << 8) | quad[3]).toString(16)\n text = `${text.slice(0, lastColon + 1)}${hi}:${lo}`\n }\n\n const doubleColon = text.indexOf('::')\n if (doubleColon !== text.lastIndexOf('::')) return null\n\n const toGroups = (segment: string): number[] | null => {\n if (segment.length === 0) return []\n const out: number[] = []\n for (const piece of segment.split(':')) {\n if (piece.length === 0 || piece.length > 4 || !/^[0-9a-fA-F]+$/.test(piece)) return null\n out.push(Number.parseInt(piece, 16))\n }\n return out\n }\n\n if (doubleColon === -1) {\n const only = toGroups(text)\n return only !== null && only.length === 8 ? only : null\n }\n const head = toGroups(text.slice(0, doubleColon))\n const rest = toGroups(text.slice(doubleColon + 2))\n if (head === null || rest === null) return null\n const explicit = head.length + rest.length\n if (explicit > 7) return null\n const zeros = new Array<number>(8 - explicit).fill(0)\n return [...head, ...zeros, ...rest]\n}\n\nfunction classifyIpv6Groups(groups: readonly number[]): IpClassification {\n const v6 = (label: string, reserved: boolean): IpClassification => ({\n family: 6,\n reserved,\n label,\n })\n const g = (index: number): number => groups[index] ?? 0\n const embeddedV4 = (hi: number, lo: number): [number, number, number, number] => [\n (hi >> 8) & 0xff,\n hi & 0xff,\n (lo >> 8) & 0xff,\n lo & 0xff,\n ]\n\n const allZeroThrough = (upTo: number): boolean => groups.slice(0, upTo).every((x) => x === 0)\n\n if (groups.every((x) => x === 0)) return v6('unspecified (::)', true)\n if (allZeroThrough(7) && g(7) === 1) return v6('loopback (::1)', true)\n\n // IPv4-translated ::ffff:0:0:0/96 (RFC 2765) — reserved, not globally reachable.\n if (allZeroThrough(4) && g(4) === 0xffff && g(5) === 0) {\n return v6('IPv4-translated (::ffff:0:0:0/96)', true)\n }\n // IPv4-mapped ::ffff:a.b.c.d and the deprecated IPv4-compatible ::a.b.c.d.\n if (allZeroThrough(5) && g(5) === 0xffff) {\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`IPv4-mapped → ${inner.label}`, inner.reserved)\n }\n if (allZeroThrough(6)) {\n // IPv4-compatible ::a.b.c.d is deprecated (RFC 4291 §2.5.5.1) and reserved\n // regardless of what the embedded address would be on its own.\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`IPv4-compatible → ${inner.label}`, true)\n }\n // NAT64 local-use prefix 64:ff9b:1::/48 (RFC 8215).\n if (g(0) === 0x0064 && g(1) === 0xff9b && g(2) === 0x0001) {\n return v6('NAT64 local-use (64:ff9b:1::/48)', true)\n }\n // NAT64 well-known prefix 64:ff9b::/96 — the v4 address rides in the last 32 bits.\n if (g(0) === 0x0064 && g(1) === 0xff9b && g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {\n const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)))\n return v6(`NAT64 64:ff9b::/96 → ${inner.label}`, inner.reserved)\n }\n // Teredo tunneling 2001::/32 (RFC 4380).\n if (g(0) === 0x2001 && g(1) === 0x0000) {\n return v6('Teredo (2001::/32)', true)\n }\n // 6to4 2002::/16 — the v4 address rides in groups 1 and 2.\n if (g(0) === 0x2002) {\n const inner = classifyIpv4Octets(embeddedV4(g(1), g(2)))\n return v6(`6to4 2002::/16 → ${inner.label}`, inner.reserved)\n }\n if (g(0) === 0x0100 && g(1) === 0 && g(2) === 0 && g(3) === 0)\n return v6('discard-only (100::/64)', true)\n if (g(0) === 0x2001 && g(1) === 0x0db8) return v6('documentation (2001:db8::/32)', true)\n if ((g(0) & 0xfe00) === 0xfc00) return v6('unique local (fc00::/7)', true)\n if ((g(0) & 0xffc0) === 0xfe80) return v6('link-local (fe80::/10)', true)\n if ((g(0) & 0xffc0) === 0xfec0) return v6('site-local (fec0::/10)', true)\n if ((g(0) & 0xff00) === 0xff00) return v6('multicast (ff00::/8)', true)\n return v6('public', false)\n}\n\n/**\n * Classifies an IP literal. `family: null` means the text is not an IP at all.\n * Fails closed: anything that looks like an IP but does not parse is reserved.\n */\nexport function classifyIp(text: string): IpClassification {\n const trimmed = text.trim()\n const bare = trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed\n\n const quad = parseIpv4(bare)\n if (quad !== null) return classifyIpv4Octets(quad)\n\n if (bare.includes(':')) {\n const groups = parseIpv6(bare)\n if (groups === null) return { family: 6, reserved: true, label: 'unparseable IPv6 literal' }\n return classifyIpv6Groups(groups)\n }\n // Looks numeric but is not a valid dotted quad — treat as unusable, not as a name.\n if (/^[0-9.]+$/.test(bare))\n return { family: 4, reserved: true, label: 'unparseable IPv4 literal' }\n return NOT_AN_IP\n}\n\n/* ── URL syntax guard ─────────────────────────────────────────────────────── */\n\nexport type UrlGuardResult = { ok: true; url: URL } | { ok: false; reason: string }\n\nexport interface UrlGuardPolicy {\n /** `false` in every hosted path. `true` only under `./probe/local`. */\n readonly allowHttp: boolean\n readonly hostPolicy: HostPolicy\n}\n\n/** Hostname suffixes that never name a public host. */\nconst PRIVATE_SUFFIXES = ['.localhost', '.local', '.internal'] as const\n\n/**\n * Parse + reject, with no I/O. This is the FIRST of two gates, not the only one:\n * `resolveAndValidate` is the second and is the one that closes the DNS hole.\n * Splitting them keeps the syntactic policy testable without a resolver and keeps\n * the resolver from being the place a reviewer has to look for \"is http allowed\".\n */\nexport function guardUrl(input: string, policy: UrlGuardPolicy): UrlGuardResult {\n let url: URL\n try {\n url = new URL(input.trim())\n } catch {\n return { ok: false, reason: 'That does not look like a valid URL.' }\n }\n\n const httpsOnly = !policy.allowHttp\n if (httpsOnly && url.protocol !== 'https:') {\n return { ok: false, reason: 'Only https:// URLs can be fetched.' }\n }\n if (!httpsOnly && url.protocol !== 'https:' && url.protocol !== 'http:') {\n return { ok: false, reason: 'Only https:// and http:// URLs can be fetched.' }\n }\n const defaultPort = url.protocol === 'https:' ? '443' : '80'\n if (url.port !== '' && url.port !== defaultPort && !allowsPrivateHosts(policy.hostPolicy)) {\n return {\n ok: false,\n reason: `Non-standard ports cannot be fetched (${url.protocol}// on ${defaultPort} only).`,\n }\n }\n if (url.username !== '' || url.password !== '') {\n return { ok: false, reason: 'URLs with embedded credentials cannot be fetched.' }\n }\n\n // Trailing dots are stripped so `169.254.169.254.` or `db.internal..` cannot walk past suffix checks.\n const hostname = url.hostname.toLowerCase().replace(/\\.+$/, '')\n if (hostname === '') {\n return { ok: false, reason: 'That URL has no hostname.' }\n }\n\n const permissive = allowsPrivateHosts(policy.hostPolicy)\n\n if (!permissive && (hostname === 'localhost' || hostname.endsWith('.localhost'))) {\n return { ok: false, reason: 'localhost cannot be fetched.' }\n }\n\n const classification = classifyIp(hostname)\n if (classification.family === 6) {\n // IPv6 literals in a submitted URL stay rejected even when they are public:\n // a store lives on a name, and the useful IPv6 case (an AAAA record) is\n // handled — and classified in full — by `resolveAndValidate`.\n if (!permissive) {\n return { ok: false, reason: 'IPv6 literal addresses cannot be fetched — use a hostname.' }\n }\n }\n if (classification.family !== null && classification.reserved && !permissive) {\n return {\n ok: false,\n reason: `Private or reserved IP addresses cannot be fetched (${classification.label}).`,\n }\n }\n if (classification.family === null && !permissive) {\n if (PRIVATE_SUFFIXES.some((suffix) => hostname.endsWith(suffix))) {\n return {\n ok: false,\n reason: 'Internal hostnames (.local, .internal, .localhost) cannot be fetched.',\n }\n }\n if (!hostname.includes('.')) {\n return {\n ok: false,\n reason: 'Single-label hostnames cannot be fetched — they resolve on the local network.',\n }\n }\n }\n\n return { ok: true, url }\n}\n\n/**\n * The strict public policy, and the name the Console preview has always used.\n * Kept as a named export because the Console preview and its shipped tests are\n * written against it.\n */\nexport function guardPreviewUrl(input: string): UrlGuardResult {\n return guardUrl(input, { allowHttp: false, hostPolicy: 'public-only' })\n}\n\n/* ── DNS resolution + validation ──────────────────────────────────────────── */\n\nexport interface PinnedAddress {\n readonly address: string\n readonly family: 4 | 6\n}\n\nexport interface HostResolver {\n resolve(hostname: string): Promise<readonly PinnedAddress[]>\n}\n\nexport type ResolveOutcome =\n | { ok: true; addresses: readonly PinnedAddress[] }\n | { ok: false; kind: 'unreachable' | 'policy-rejected'; reason: string }\n\n/** Real DNS. The only resolver a hosted path ever uses. */\nexport function createDnsResolver(): HostResolver {\n return {\n async resolve(hostname: string): Promise<readonly PinnedAddress[]> {\n const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true })\n return records.map((record) => ({\n address: record.address,\n family: record.family === 6 ? 6 : 4,\n }))\n },\n }\n}\n\n/**\n * Resolves and validates. Rejects if ANY answer is reserved — not \"if the first\n * one is\". A name that answers with one public and one private address is the\n * shape of the attack, and picking the public one and connecting anyway is how\n * a guard that looks correct fails.\n */\nexport async function resolveAndValidate(\n hostname: string,\n resolver: HostResolver,\n hostPolicy: HostPolicy,\n): Promise<ResolveOutcome> {\n // An IP literal needs no resolution; it was already classified by `guardUrl`.\n const literal = classifyIp(hostname)\n if (literal.family !== null) {\n if (literal.reserved && !allowsPrivateHosts(hostPolicy)) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `target is a reserved address (${literal.label})`,\n }\n }\n return {\n ok: true,\n addresses: [{ address: hostname.replace(/^\\[|\\]$/g, ''), family: literal.family }],\n }\n }\n\n let addresses: readonly PinnedAddress[]\n try {\n addresses = await resolver.resolve(hostname)\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n return {\n ok: false,\n kind: 'unreachable',\n reason: `DNS lookup failed for ${hostname}: ${detail}`,\n }\n }\n if (addresses.length === 0) {\n return { ok: false, kind: 'unreachable', reason: `DNS returned no addresses for ${hostname}` }\n }\n if (allowsPrivateHosts(hostPolicy)) return { ok: true, addresses }\n\n for (const record of addresses) {\n const classification = classifyIp(record.address)\n if (classification.family === null) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `DNS returned an unparseable address (${record.address})`,\n }\n }\n if (classification.reserved) {\n return {\n ok: false,\n kind: 'policy-rejected',\n reason: `${hostname} resolves to a private or reserved address (${record.address}: ${classification.label})`,\n }\n }\n }\n return { ok: true, addresses }\n}\n\n/* ── the transport ────────────────────────────────────────────────────────── */\n\nexport interface ProbeRequestInit {\n readonly headers: Readonly<Record<string, string>>\n /** Always `'manual'`: hops are our decision, because each one must re-resolve. */\n readonly redirect: 'manual'\n readonly signal: AbortSignal\n /**\n * The addresses `resolveAndValidate` approved for this exact URL's hostname.\n * The transport MUST connect to one of these and MUST NOT consult a resolver\n * of its own; that is the whole anti-rebinding mechanism.\n */\n readonly pinnedAddresses: readonly PinnedAddress[]\n}\n\n/**\n * A response, reduced to the three things ARS evidence needs.\n *\n * `headers` is `name → all values`, not `name → value`. `Link` is routinely sent\n * more than once and is scored twice over (D2.2 declared alternates, D6.5\n * machine endpoints); a transport that joins them is losing scored evidence.\n */\nexport interface ProbeHttpResponse {\n readonly status: number\n readonly headers: Record<string, string[]>\n readonly body: ReadableStream<Uint8Array> | null\n}\n\nexport type ProbeTransport = (url: string, init: ProbeRequestInit) => Promise<ProbeHttpResponse>\n\n/** Adapts a WHATWG `Response` — the shape tests and fixtures find easiest to build. */\nexport function fromWebResponse(response: Response): ProbeHttpResponse {\n const headers: Record<string, string[]> = {}\n response.headers.forEach((value, name) => {\n const key = name.toLowerCase()\n if (key === 'set-cookie') return\n const existing = headers[key]\n if (existing) existing.push(value)\n else headers[key] = [value]\n })\n const setCookie =\n typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []\n if (setCookie.length > 0) headers['set-cookie'] = [...setCookie]\n return { status: response.status, headers, body: response.body }\n}\n\n/** Returns the pinned addresses and refuses to look anything up. */\nfunction pinnedLookup(addresses: readonly PinnedAddress[]): LookupFunction {\n return (_hostname, options, callback) => {\n if (addresses.length === 0) {\n callback(new Error('rebilder-ars: no pinned address for this connection'), '', 4)\n return\n }\n // Node ≥20 enables `autoSelectFamily`, which calls `lookup` with `all: true`.\n if (typeof options === 'object' && options !== null && options.all === true) {\n callback(\n null,\n addresses.map((record) => ({ address: record.address, family: record.family })),\n )\n return\n }\n const first = addresses[0]\n if (first === undefined) {\n callback(new Error('rebilder-ars: no pinned address for this connection'), '', 4)\n return\n }\n callback(null, first.address, first.family)\n }\n}\n\n/**\n * The production transport: `node:https`/`node:http` with a `lookup` that can\n * only return the validated addresses.\n *\n * WHY NOT `fetch` + an undici `Agent`. Design §5.2 names undici's `Agent` with a\n * custom `lookup`, which is the same mechanism; `undici` is not reachable as a\n * built-in module and this package's contract is zero runtime dependencies, so\n * the identical property is obtained from `node:https`, whose options flow\n * through to `net.connect`. `servername` keeps SNI on the hostname and Node's\n * default `setHost` keeps the `Host` header on the hostname, so the origin sees\n * a normal request and only the socket's destination is fixed.\n *\n * No `Accept-Encoding` is sent, so nothing arrives compressed and the decoded\n * byte count is the transferred byte count. §3.3 drops `transferBytes` for\n * exactly this reason: a hashed field that is platform-dependent is worse than\n * no field.\n */\nexport function createPinnedTransport(): ProbeTransport {\n return (url, init) =>\n new Promise<ProbeHttpResponse>((resolve, reject) => {\n let target: URL\n try {\n target = new URL(url)\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)))\n return\n }\n const secure = target.protocol === 'https:'\n const client = secure ? https : http\n const headers: Record<string, string> = { ...init.headers, host: target.host }\n\n const request = client.request(\n {\n protocol: target.protocol,\n hostname: target.hostname,\n port: target.port === '' ? (secure ? 443 : 80) : Number(target.port),\n path: `${target.pathname}${target.search}`,\n method: 'GET',\n headers,\n servername: secure ? target.hostname : undefined,\n lookup: pinnedLookup(init.pinnedAddresses),\n agent: false,\n signal: init.signal,\n },\n (response) => {\n const collected: Record<string, string[]> = {}\n const raw = response.rawHeaders\n for (let i = 0; i + 1 < raw.length; i += 2) {\n const name = (raw[i] ?? '').toLowerCase()\n const value = raw[i + 1] ?? ''\n const existing = collected[name]\n if (existing) existing.push(value)\n else collected[name] = [value]\n }\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n response.on('data', (chunk: Buffer) => {\n // Copy: `chunk` may be a view onto Node's shared read pool.\n controller.enqueue(new Uint8Array(chunk))\n if ((controller.desiredSize ?? 1) <= 0) response.pause()\n })\n response.on('end', () => {\n try {\n controller.close()\n } catch {\n /* already closed by a cancel() */\n }\n })\n response.on('error', (error) => {\n try {\n controller.error(error)\n } catch {\n /* already errored */\n }\n })\n },\n pull() {\n response.resume()\n },\n cancel() {\n // The byte cap fires here: stop reading and drop the socket.\n response.destroy()\n request.destroy()\n },\n })\n\n resolve({ status: response.statusCode ?? 0, headers: collected, body })\n },\n )\n\n request.on('error', (error) => reject(error))\n request.end()\n })\n}\n","/**\n * profiles.ts — the eight page-kind fact profiles. Design §3.5, table verbatim.\n *\n * THE ONE IDEA IN THIS FILE. ARS uses fixed weights for every page kind. What\n * varies is *what counts as a fact* and *what a page of that kind reasonably\n * costs*:\n *\n * > ARS does not measure how much you say. It measures whether the facts a\n * > caller needs **for this kind of page** are present, findable, and cheap\n * > **relative to what that kind of page costs**.\n *\n * Per-vertical *weights* would be the wrong design — it makes an 88 mean\n * different things on different pages and invites site-type shopping. A\n * per-vertical *fact set* and *byte reference* are not weights: an article that\n * spends 38 KB saying something is not penalised against a 40 KB reference,\n * while a product page that spends 38 KB to state four facts is. The byte\n * reference is specifically what stops long-form content being structurally\n * capped around C, which every source design that used absolute byte bands did.\n *\n * The set is CLOSED at eight, and every kind has a complete profile — there is\n * no \"no profile\" path. Conformance fixture `058-profiles-total-and-typed`\n * asserts both halves of that: the mapping is total over `ArsPageKind`, and\n * every fact name is a member of `ArsFactKind`. `PROFILE_BY_KIND` is typed as a\n * total `Record`, so the first half is also a compile error.\n *\n * `unknown` is deliberately not an easy exit. It carries the smallest core set,\n * but it still scores D5.2 against \"any recognised schema.org type present\",\n * which requires having a type at all. Hiding your page kind costs up to 7\n * points and gains nothing on coverage.\n *\n * ── Definitions of the fact terms the source designs left undefined (§3.5) ──\n *\n * `primary-action-url` — a same-origin-or-declared URL reachable from an\n * `<a href>`, a `<form action>`, or JSON-LD `potentialAction.target`, whose\n * anchor text or `name` matches the ruleset's action lexicon (`book`, `apply`,\n * `contact`, `buy`, `subscribe`, `start`, `request`, `download`, `sign up`,\n * `get a quote` and their pinned synonyms). The lexicon is pinned in\n * `DEFAULT_RULESET.actionLexicon`, not inferred per page.\n *\n * `authority` — an organisation or person named as the publisher of the content,\n * extracted from JSON-LD `publisher`/`author`, `<meta name=\"author\">`, or a\n * `rel=\"publisher\"` link.\n *\n * `org-name` — JSON-LD `Organization.name` / `LocalBusiness.name`,\n * `og:site_name`, or `<meta itemprop=\"name\">` on an org-typed scope.\n *\n * `item-count` / `item-link` — for `collection`: the number of distinct item\n * links inside the largest repeated-structure block, and whether those links\n * resolve to same-origin URLs. Counted from the largest repeated block\n * specifically so that a nav menu is not mistaken for a product grid.\n *\n * `question-answer` — a `FAQPage`/`Question` JSON-LD pair, or a `<dt>/<dd>`, a\n * `<details><summary>`, or a heading-followed-by-paragraph pair. Counted ONCE\n * as present, not per item: a page with 40 questions is not four times better\n * than a page with 10.\n *\n * `price` is satisfied by an explicit \"no published price\" signal as well as by\n * a number. We score honesty, not disclosure — a service page that says\n * \"pricing on request\" has told the agent what it needs to know.\n */\n\nimport type { ArsFactProfile, ArsPageKind } from './types'\n\n/**\n * The §3.5 table, one entry per `ArsPageKind`. Core facts score at full weight,\n * extended facts at ¼ credit (the single definition — the source designs used\n * ¼, ½ and \"half credit\" in three different places). Byte references are the\n * D3.2 denominator, in bytes.\n */\nexport const PROFILE_BY_KIND = {\n product: {\n pageKind: 'product',\n core: ['title', 'price', 'currency', 'availability'],\n extended: ['brand', 'sku', 'shipping', 'returns', 'description'],\n byteReference: 8 * 1024,\n },\n collection: {\n pageKind: 'collection',\n core: ['title', 'item-count', 'item-link'],\n extended: ['price', 'availability', 'description'],\n byteReference: 16 * 1024,\n },\n article: {\n pageKind: 'article',\n core: ['title', 'author', 'published'],\n extended: ['updated', 'section', 'description'],\n byteReference: 40 * 1024,\n },\n place: {\n pageKind: 'place',\n core: ['org-name', 'address', 'hours', 'phone'],\n extended: ['email', 'service-area', 'primary-action-url', 'description'],\n byteReference: 8 * 1024,\n },\n service: {\n pageKind: 'service',\n core: ['title', 'price', 'primary-action-url'],\n extended: ['duration', 'eligibility', 'service-area', 'description', 'updated'],\n byteReference: 8 * 1024,\n },\n faq: {\n pageKind: 'faq',\n core: ['title', 'question-answer'],\n extended: ['updated', 'description'],\n byteReference: 16 * 1024,\n },\n document: {\n pageKind: 'document',\n core: ['title', 'updated', 'authority'],\n extended: ['description', 'primary-action-url', 'section'],\n byteReference: 24 * 1024,\n },\n unknown: {\n pageKind: 'unknown',\n core: ['title', 'description', 'primary-action-url'],\n extended: ['updated', 'org-name'],\n byteReference: 16 * 1024,\n },\n} as const satisfies Record<ArsPageKind, ArsFactProfile>\n\n/**\n * The same eight profiles as the array `ArsRuleset.profiles` expects, in\n * declaration order (which is the order they appear in the §3.5 table, and is\n * therefore the order the spec renders them in).\n *\n * Runtime immutability: `as const` above makes every profile deeply readonly to\n * TypeScript, and `DEFAULT_RULESET` deep-freezes these exact objects at module\n * load, so a consumer cannot mutate a shared profile and silently change every\n * subsequent score.\n */\nexport const PROFILES: readonly ArsFactProfile[] = Object.freeze(Object.values(PROFILE_BY_KIND))\n\n/** Total by construction — `PROFILE_BY_KIND` is typed as a total Record. */\nexport function profileFor(pageKind: ArsPageKind): ArsFactProfile {\n return PROFILE_BY_KIND[pageKind]\n}\n","/**\n * ruleset.ts — `DEFAULT_RULESET`, the frozen ARS 0.3 ruleset.\n *\n * WHAT THIS FILE IS. Every number a second implementation needs in order to\n * reproduce a score, and nothing that varies between runs. `rulesetHash()` is\n * the SHA-256 of the RFC 8785 canonical JSON of this object, it is printed on\n * every result, and the determinism guarantee is stated in terms of it: a\n * number without `rulesetHash`, `corpusHash` and `evidenceHash` is not an ARS\n * score. That makes this file a published artifact, not configuration.\n *\n * CONSEQUENCE: editing a number here is a spec version change, not a code\n * change. Per §3.1, any edit that moves a conformance `expected.json` is at\n * minimum a MINOR — and MINOR means scores stop being comparable and every\n * published surface re-scores in a batch. The CI gate on PATCH releases exists\n * precisely so that \"just tweaking a threshold\" cannot happen quietly.\n *\n * WHY THE BODY CAP, REDIRECT LIMIT AND TIMEOUT LIVE HERE rather than in the\n * probe: two implementations with different caps produce different scores. A\n * 3 MiB cap turns a `truncated-evidence` non-grade into an F, and a 10s timeout\n * scores pages a 5s timeout reports as unreachable. They are inputs to the\n * score, so they are inputs to the hash.\n *\n * SHAPE. Everything is `as const satisfies <contract>`: the `satisfies` clause\n * proves the object matches the published type (and, for the tables keyed by\n * `ArsCheckId` / `ArsPageKind`, that it is TOTAL), while `as const` keeps the\n * literal types so callers get `number`, not `number | undefined`, from a known\n * key. `deepFreeze` then makes it immutable at runtime as well — a mutated\n * shared ruleset would corrupt every subsequent score in the process, silently.\n */\n\nimport { PROFILES } from './profiles'\nimport type {\n ArsBand,\n ArsBasis,\n ArsCheckId,\n ArsDimensionId,\n ArsPageKind,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// Deep freeze\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively freezes a plain data structure. Used once, on `DEFAULT_RULESET`.\n * `as const` is a compile-time guarantee only; this is the runtime half.\n */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Check weights — the §3.4 table, row for row\n// ---------------------------------------------------------------------------\n\n/**\n * Check id → points. Sums to exactly 100 across 22 checks.\n *\n * NO CONDITIONAL WEIGHTS. NO REDISTRIBUTION. NO HEURISTIC GATES OVER MEASURED\n * POINTS. Redistribution is a gaming vector (make the dimension you are bad at\n * inapplicable and the rest inflate), and a heuristic that can zero measured\n * points makes those points heuristic. So D2.4 and D5.3 are scored checks, not\n * gates: a parity failure loses its own 3 points and raises a `warn`, and does\n * not touch D2's other measured points. That is what makes \"measured 63 /\n * heuristic 37\" an honest figure rather than a presentational one, and fixture\n * `053` re-derives the heuristic-*controlled* weight to prove it.\n *\n * `satisfies Record<ArsCheckId, number>` makes the table total: a check id\n * added to the union without a weight here is a compile error.\n */\nconst WEIGHTS = {\n // D1 Retrievability — 28\n 'retrievability.reachable': 11,\n 'retrievability.robots-policy': 10,\n 'retrievability.render-independence': 7,\n // D2 Machine representation — 18\n 'machine-representation.negotiated-response': 9,\n 'machine-representation.declared-alternates': 3,\n 'machine-representation.vary-accept': 3,\n 'machine-representation.substance-parity': 3,\n // D3 Fact coverage — 20\n 'fact-coverage.core-facts': 14,\n 'fact-coverage.context-cost': 6,\n // D4 Fact position — 10\n 'fact-position.first-core-fact-offset': 5,\n 'fact-position.front-window': 5,\n // D5 Structured data — 6\n 'structured-data.present': 2,\n 'structured-data.required-properties': 3,\n 'structured-data.text-agreement': 1,\n // D6 Contract & discovery — 10\n 'contract-discovery.canonical': 4,\n 'contract-discovery.cache-validators': 2,\n 'contract-discovery.llms-txt': 1,\n 'contract-discovery.sitemap': 1,\n 'contract-discovery.machine-endpoint': 2,\n // D7 Evidence density — 8\n 'evidence-density.quantities': 4,\n 'evidence-density.definitions': 2,\n 'evidence-density.comparisons': 2,\n} as const satisfies Record<ArsCheckId, number>\n\n/** Descriptive metadata per check: which dimension it belongs to, its published label, its basis. */\nexport interface ArsCheckMeta {\n dimension: ArsDimensionId\n label: string\n basis: ArsBasis\n}\n\n/**\n * The published catalogue of checks. `dimension` is redundant with the check id\n * prefix by construction — the id shape `<dimension>.<check>` is normative — and\n * is spelled out anyway so consumers never parse an id string to group results.\n *\n * `basis` is spec data (it appears in every `expected.json` and is printed next\n * to every check in the UI) but it is not part of `ArsRuleset` in §3.9, so it is\n * exported here rather than folded into the hashed object. A second\n * implementation reads it from the published §3.4 table.\n */\nexport const CHECK_META = {\n 'retrievability.reachable': {\n dimension: 'retrievability',\n label: 'Reachable on the agent path',\n basis: 'measured',\n },\n 'retrievability.robots-policy': {\n dimension: 'retrievability',\n label: 'Robots policy for assistants',\n basis: 'measured',\n },\n 'retrievability.render-independence': {\n dimension: 'retrievability',\n label: 'Core facts present without JavaScript',\n basis: 'heuristic',\n },\n 'machine-representation.negotiated-response': {\n dimension: 'machine-representation',\n label: 'Machine representation on Accept negotiation',\n basis: 'measured',\n },\n 'machine-representation.declared-alternates': {\n dimension: 'machine-representation',\n label: 'Declared alternate representations',\n basis: 'measured',\n },\n 'machine-representation.vary-accept': {\n dimension: 'machine-representation',\n label: 'Vary: Accept declared correctly',\n basis: 'measured',\n },\n 'machine-representation.substance-parity': {\n dimension: 'machine-representation',\n label: 'Same substance across representations',\n basis: 'heuristic',\n },\n 'fact-coverage.core-facts': {\n dimension: 'fact-coverage',\n label: 'Core facts for this page kind',\n basis: 'heuristic',\n },\n 'fact-coverage.context-cost': {\n dimension: 'fact-coverage',\n label: 'Context cost relative to this page kind',\n basis: 'measured',\n },\n 'fact-position.first-core-fact-offset': {\n dimension: 'fact-position',\n label: 'Byte offset of the first core fact',\n basis: 'heuristic',\n },\n 'fact-position.front-window': {\n dimension: 'fact-position',\n label: 'Core facts inside the front window',\n basis: 'heuristic',\n },\n 'structured-data.present': {\n dimension: 'structured-data',\n label: 'Structured data present and parsing',\n basis: 'measured',\n },\n 'structured-data.required-properties': {\n dimension: 'structured-data',\n label: 'Recognised type with its required properties',\n basis: 'measured',\n },\n 'structured-data.text-agreement': {\n dimension: 'structured-data',\n label: 'Structured data agrees with visible text',\n basis: 'heuristic',\n },\n 'contract-discovery.canonical': {\n dimension: 'contract-discovery',\n label: 'Canonical URL present and self-consistent',\n basis: 'measured',\n },\n 'contract-discovery.cache-validators': {\n dimension: 'contract-discovery',\n label: 'Cache validators',\n basis: 'measured',\n },\n 'contract-discovery.llms-txt': {\n dimension: 'contract-discovery',\n label: 'llms.txt present and spec-shaped',\n basis: 'measured',\n },\n 'contract-discovery.sitemap': {\n dimension: 'contract-discovery',\n label: 'Sitemap declared in robots.txt',\n basis: 'measured',\n },\n 'contract-discovery.machine-endpoint': {\n dimension: 'contract-discovery',\n label: 'Declared machine endpoint',\n basis: 'measured',\n },\n 'evidence-density.quantities': {\n dimension: 'evidence-density',\n label: 'Quantities an answer can quote',\n basis: 'measured',\n },\n 'evidence-density.definitions': {\n dimension: 'evidence-density',\n label: 'Labelled term and value pairs',\n basis: 'heuristic',\n },\n 'evidence-density.comparisons': {\n dimension: 'evidence-density',\n label: 'Comparable rows',\n basis: 'measured',\n },\n} as const satisfies Record<ArsCheckId, ArsCheckMeta>\n\n/**\n * The six dimensions and their frozen weights (§3.4): 20 · 20 · 20 · 10 · 15 ·\n * 15 = 100, identical for every page kind. Each weight is the sum of its\n * checks' weights in `WEIGHTS`; both are written out because both are published,\n * and conformance fixture `052` asserts they agree and that the total is 100.\n */\nexport const DIMENSION_META = {\n retrievability: { label: 'Retrievability', weight: 28 },\n 'machine-representation': { label: 'Machine representation', weight: 18 },\n 'fact-coverage': { label: 'Fact coverage', weight: 20 },\n 'fact-position': { label: 'Fact position', weight: 10 },\n 'structured-data': { label: 'Structured data', weight: 6 },\n 'contract-discovery': { label: 'Contract & discovery', weight: 10 },\n 'evidence-density': { label: 'Evidence density', weight: 8 },\n} as const satisfies Record<ArsDimensionId, { label: string; weight: number }>\n\n/**\n * Published totals (§3.4). Heuristic weight has a spec ceiling of 40; fixture\n * `053` enforces it, and the ceiling is what shaped D7's basis split rather\n * than the other way round. Labelling `definitions` measured would have bought\n * three points of headroom and made \"measured 63\" a presentational number\n * instead of an honest one, which is the exact failure the ceiling exists to\n * prevent.\n */\nexport const ARS_MEASURED_WEIGHT = 63\nexport const ARS_HEURISTIC_WEIGHT = 37\nexport const ARS_HEURISTIC_WEIGHT_CEILING = 40\n\n// ---------------------------------------------------------------------------\n// Thresholds — the §3.6 scoring tables, as integer pairs\n// ---------------------------------------------------------------------------\n\n/**\n * All numeric bands from §3.6, encoded as flat `[threshold, value]` pairs so a\n * second implementation reads one shape rather than five. Integer arithmetic\n * only: no floating point anywhere in the scoring path, because cross-language\n * conformance is impossible with float rounding drift. All values are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator` in integer division.\n *\n * Two encodings, each stated per key:\n * AT-LEAST — descending pairs; the first pair whose `threshold <= input` wins.\n * AT-MOST — ascending pairs; the first pair whose `input <= threshold` wins;\n * no match scores 0.\n */\nconst THRESHOLDS = {\n /**\n * D3.1 fact weighting, in quarter-units (§3.6), as\n * `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:\n * coreUnits = 4 × corroborated core + 2 × uncorroborated core\n * extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended\n * \"Extended = ¼ credit\" is the single definition of extended credit.\n */\n 'fact-coverage.fact-units': [4, 2, 1, 0],\n /**\n * D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit\n * is every core fact corroborated. `coveragePct` is then\n * `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.\n */\n 'fact-coverage.core-denominator-multiplier': [4],\n /**\n * D3.1 density band. AT-LEAST over\n * `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.\n * The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n * which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so\n * that keyword stuffing is pointless — fixtures `031` and `032` must score\n * identically.\n * Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.\n */\n 'fact-coverage.density': [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],\n /**\n * D3.2 context cost, 6 pts. AT-MOST over\n * `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.\n */\n 'fact-coverage.context-cost': [100, 6, 200, 5, 500, 3, 1500, 1],\n /**\n * D7.1 quantities, 4 pts. AT-LEAST over the count of DISTINCT quantity tokens\n * in the agent's counted text: a currency amount, a percentage, a number\n * carrying a unit, or an ISO date. Distinct, because a price repeated in a\n * header, a buy box and a footer is one fact stated three times, and counting\n * it three times would reward the repetition this score exists to discourage.\n * Saturates at 12 so a specification table cannot outscore a page that simply\n * states its facts.\n */\n 'evidence-density.quantities': [12, 4, 6, 3, 3, 2, 1, 1],\n /**\n * D7.2 definitions, 2 pts. AT-LEAST over the count of `term: value` pairs the\n * agent can read as a labelled fact, counting markdown bold-label lines,\n * list items with a leading label, and HTML definition lists.\n */\n 'evidence-density.definitions': [6, 2, 2, 1],\n /**\n * D7.3 comparisons, 2 pts. AT-LEAST over the number of comparable ROWS: a\n * table with at least two data columns contributes its data-row count, minus\n * the header. One row is not a comparison, so the band starts at two; three\n * options laid side by side is a full comparison and pays out. Calibrated\n * against fixture `060`, where a three-row size table is exactly the shape\n * this check exists to reward, and `063`, where one row is not.\n */\n 'evidence-density.comparisons': [3, 2, 2, 1],\n /** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */\n 'fact-position.first-core-fact-offset': [512, 5, 2048, 4, 8192, 2, 32768, 1],\n /**\n * D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose\n * offset falls inside the window; below the last threshold, 0.\n */\n 'fact-position.front-window': [90, 5, 70, 4, 50, 3, 25, 1],\n /**\n * D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE\n * expression, integer division — the `0.2 × bytes` form is deleted, because\n * two implementations rounding a float disagree at the boundary.\n */\n 'fact-position.front-window-size': [2048, 5],\n /**\n * Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8\n * bytes are the normative measurement and approximate tokens are always\n * rendered with `≈` and an \"est.\" chip. chars/4 is not a token count and the\n * spec says so.\n */\n 'cost.approx-bytes-per-token': [4],\n} as const satisfies Readonly<Record<string, readonly number[]>>\n\n// ---------------------------------------------------------------------------\n// Crawler audiences (§3.7)\n// ---------------------------------------------------------------------------\n\n/**\n * Robots `User-agent:` product tokens per audience, in their published casing.\n * Matching is case-insensitive (RFC 9309 §2.2.1) — the casing here is for the\n * rendered spec table.\n *\n * The `training` list exists so it can be treated NEUTRALLY. Blocking training\n * crawlers while allowing assistants scores identically to a fully open site,\n * and fixtures `021`/`022` exist solely to prove it, because it is the first\n * thing a hostile reviewer tests. `search` is reported only, and feeds the\n * `robots-contradiction` input; it never scores.\n *\n * This list is versioned data, not a heuristic: adding a token changes scores\n * for sites that named it, so additions land as a MINOR.\n */\nconst AUDIENCE_TOKENS = {\n /** User-triggered assistant fetches. THE audience ARS scores. */\n assistant: [\n 'ChatGPT-User',\n 'Claude-User',\n 'Claude-SearchBot',\n 'DuckAssistBot',\n 'Meta-ExternalFetcher',\n 'MistralAI-User',\n 'OAI-SearchBot',\n 'Perplexity-User',\n ],\n /** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */\n training: [\n 'AI2Bot',\n 'Applebot-Extended',\n 'Bytespider',\n 'CCBot',\n 'ClaudeBot',\n 'Diffbot',\n 'FacebookBot',\n 'Google-Extended',\n 'GPTBot',\n 'Meta-ExternalAgent',\n 'PanguBot',\n 'Timpibot',\n 'anthropic-ai',\n 'cohere-ai',\n 'omgili',\n ],\n /** Classic search indexers. Reported only. */\n search: ['Applebot', 'Baiduspider', 'Bingbot', 'DuckDuckBot', 'Googlebot', 'Slurp', 'YandexBot'],\n} as const satisfies Record<'assistant' | 'training' | 'search', readonly string[]>\n\n// ---------------------------------------------------------------------------\n// D5.2 required properties (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The hand-curated required-property table, per page kind.\n *\n * PROVENANCE, stated because D5.2 is 7 points and merchants will ask where the\n * list came from: it is NOT \"schema.org validity\" — schema.org defines no\n * required properties at all — and it is NOT Google's rich-results guidelines by\n * reference, which change without a version and would make ARS scores move\n * without an ARS release. It is the CORE FACT SET of each page kind (see\n * `./profiles`) expressed in schema.org vocabulary, plus the properties without\n * which those facts are not actionable — a price with no `priceCurrency` cannot\n * be used by a buying agent, so `product` and `service` require both. The table\n * is bounded because it covers 8 kinds, not the full vocabulary, and it is\n * published in the spec next to this rationale.\n *\n * NOTATION: a dot is a property path from the top-level node; traversal enters\n * array members (`offers.price` matches `offers[0].price`). Alias handling\n * (`openingHours` vs `openingHoursSpecification`, `Article.headline` vs `name`)\n * belongs to the extractor, not to this table.\n *\n * `unknown` requires only `name`, deliberately: §3.5 scores `unknown` against\n * \"any recognised schema.org type present\", which requires having a type but\n * cannot require properties of a kind we did not identify.\n */\nconst REQUIRED_PROPERTIES = {\n product: ['name', 'offers.price', 'offers.priceCurrency', 'offers.availability'],\n collection: ['name', 'numberOfItems', 'itemListElement'],\n article: ['headline', 'author', 'datePublished'],\n place: ['name', 'address', 'openingHours', 'telephone'],\n service: ['name', 'offers.price', 'offers.priceCurrency', 'potentialAction.target'],\n faq: ['name', 'mainEntity', 'mainEntity.acceptedAnswer'],\n document: ['name', 'dateModified', 'publisher'],\n unknown: ['name'],\n} as const satisfies Record<ArsPageKind, readonly string[]>\n\n// ---------------------------------------------------------------------------\n// Action lexicon (§3.5)\n// ---------------------------------------------------------------------------\n\n/**\n * Phrases that qualify a link, form or `potentialAction` as the page's\n * `primary-action-url`. Matched case-insensitively against normalised anchor\n * text / `name`, whitespace collapsed.\n *\n * ARS 0.3 ADDED THE COMMON ONES 0.2 MISSED. A shop whose button read \"Shop\n * now\", software whose button read \"Install\" or \"Try it free\", and a local\n * business whose button read \"Get directions\" were all told their main action\n * link was missing. The additions are the labels those pages actually use, each\n * still a whole phrase or a word-bounded prefix (`matchesLexicon`), so \"shop\"\n * matches \"Shop now\" and never \"Workshop\".\n *\n * PINNED, not inferred. §3.5 names ten stems — `book`, `apply`, `contact`,\n * `buy`, `subscribe`, `start`, `request`, `download`, `sign up`, `get a quote` —\n * \"and their pinned synonyms\"; this is that list. A lexicon that grew per page\n * (or per LLM call) would make `primary-action-url` non-deterministic, and\n * `primary-action-url` is a core fact for `service` and `unknown`, so it would\n * take the whole score with it. Sorted for readability; order is not\n * significant.\n */\nconst ACTION_LEXICON = [\n 'add to bag',\n 'add to basket',\n 'add to cart',\n 'apply',\n 'apply now',\n 'book',\n 'book now',\n 'buy',\n 'buy now',\n 'call',\n 'call now',\n 'check availability',\n 'check out',\n 'checkout',\n 'contact',\n 'contact us',\n 'create account',\n 'create an account',\n 'donate',\n 'download',\n 'email us',\n 'enquire',\n 'enrol',\n 'enroll',\n 'free trial',\n 'get a demo',\n 'get a quote',\n 'get directions',\n 'get in touch',\n 'get quote',\n 'get started',\n 'get the app',\n 'get tickets',\n 'hire',\n 'inquire',\n 'install',\n 'join',\n 'make an appointment',\n 'message us',\n 'order',\n 'order now',\n 'order online',\n 'pre-order',\n 'preorder',\n 'purchase',\n 'register',\n 'rent',\n 'request',\n 'request a demo',\n 'request a quote',\n 'reserve',\n 'schedule',\n 'shop',\n 'shop now',\n 'sign up',\n 'signup',\n 'start',\n 'start free trial',\n 'subscribe',\n 'talk to sales',\n 'talk to us',\n 'text us',\n 'try',\n 'upgrade',\n] as const satisfies readonly string[]\n\n// ---------------------------------------------------------------------------\n// Bands (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.3 integer grade bands (unchanged from 0.2). Meanings describe retrieved response structure;\n * they do not predict third-party output or certify business facts. Interfaces\n * can link the measurement methodology rather than repeat fixed boilerplate.\n */\nconst BANDS = [\n {\n grade: 'A',\n min: 90,\n max: 100,\n label: 'Agent-native',\n meaning:\n 'Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch.',\n },\n {\n grade: 'B',\n min: 75,\n max: 89,\n label: 'Agent-friendly',\n meaning:\n 'All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing.',\n },\n {\n grade: 'C',\n min: 60,\n max: 74,\n label: 'Readable with effort',\n meaning: 'Core facts are extractable from HTML, at high cost.',\n },\n {\n grade: 'D',\n min: 40,\n max: 59,\n label: 'Partial',\n meaning: 'Some core facts for this page kind were not found in the fetched response.',\n },\n {\n grade: 'F',\n min: 0,\n max: 39,\n label: 'Not extractable',\n meaning: 'Few or no core facts for this page kind were found in the fetched response.',\n },\n] as const satisfies readonly ArsBand[]\n\n// ---------------------------------------------------------------------------\n// The ruleset\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.3's frozen ruleset. Weights and bands are 0.2's; the action lexicon grew.\n *\n * DESIGNED CEILINGS, printed in the spec (§8) as intentional rather than\n * discovered, and stated here in 0.2's numbers: no content negotiation loses\n * D2.1 (9) + D2.3 (3, gated on D2.1) + D2.4 (3, nothing comparable) → max 85,\n * capped at B. No valid structured data loses all of D5 (6) → max 94, so an A is\n * still reachable. Reaching an A therefore requires a machine representation and\n * NO LONGER requires structured data — 0.1 required both, and 0.2 does not.\n * Provable from these numbers alone, which is why the whole ruleset is published\n * rather than described.\n */\nexport const DEFAULT_RULESET = deepFreeze({\n version: '0.3.0',\n weights: WEIGHTS,\n thresholds: THRESHOLDS,\n audienceTokens: AUDIENCE_TOKENS,\n requiredProperties: REQUIRED_PROPERTIES,\n actionLexicon: ACTION_LEXICON,\n /** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */\n maxBodyBytes: 2 * 1024 * 1024,\n /** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */\n maxRedirects: 3,\n /** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */\n timeoutMs: 5_000,\n profiles: PROFILES,\n bands: BANDS,\n} as const satisfies ArsRuleset)\n","/**\n * html.ts — a tolerant, NON-EXECUTING HTML tokenizer, hand-rolled.\n *\n * WHY NOT parse5, cheerio, jsdom, or htmlparser2 (design §3.2, stated as a\n * normative reason rather than a preference): **a third-party parser version is\n * an unversioned input to a deterministic score.** ARS publishes the guarantee\n * that for a given `evidenceHash`, `rulesetHash` and `corpusHash`, `score()`\n * returns a byte-identical result in any conformant implementation, in any\n * language. A dependency that changes how a malformed `<div` is recovered\n * changes scores on a `pnpm update`, with no ARS version bump, no conformance\n * diff, and nothing in the release notes. It would also put a transitive\n * dependency tree into a package whose whole claim is that it has none.\n *\n * The second reason is the same one that rules out a cascade engine: this\n * tokenizer's recovery rules ARE the spec. They are written here, in ~600 lines,\n * where a second implementation in Go can read them.\n *\n * NON-EXECUTING is literal and load-bearing. `<script>` and `<style>` contents\n * are captured as opaque raw text and never evaluated, never fed to a JS engine,\n * never resolved. The probe fetches attacker-controlled bytes from arbitrary\n * origins; the only safe posture is that those bytes are data all the way down.\n *\n * WHAT IT EXTRACTS\n * - every start/end tag, with attributes (lowercased names, entity-decoded values)\n * - every text node, with its **UTF-8 byte offset** into the source\n * - `<script type=\"application/ld+json\">` contents, verbatim\n * - `<meta>` tags (name / property / http-equiv / itemprop / charset / content)\n * - `<link>` tags, including the multi-value `rel` token list\n *\n * BYTE OFFSETS ARE LOAD-BEARING. D4 scores the byte offset of the first core\n * fact (`≤512B → 5 · ≤2KiB → 4 · ≤8KiB → 2 · ≤32KiB → 1`) and the fraction of\n * core facts inside a `max(2048, bytes / 5)` front window. `ArsHttpCapture.bytes`\n * is defined as the *decoded UTF-8 byte length*, so offsets here are UTF-8 byte\n * offsets, NOT JavaScript string indices. On a page with any multibyte character\n * before the price — a `€`, a `—`, a CJK product name — those two numbers differ,\n * and a Go implementation counting real bytes would disagree with us. See\n * `Utf8Cursor`.\n *\n * TEXT EXTRACTION (normative, §3.6). Counted text is every text node except:\n * `<script>`, `<style>`, `<template>`, elements carrying the `hidden`\n * attribute, and elements carrying inline `style=\"display:none\"`.\n * **No CSS resolution** — a cascade engine would not be deterministic across\n * implementations, so a class that hides an element in a stylesheet does not\n * hide it here, and the spec says so rather than pretending otherwise.\n *\n * ONE READING DECISION, FLAGGED. §3.6 writes the rule as \"except `<script>`\n * (excluding `application/ld+json`)\", which can be read either way. We implement:\n * **JSON-LD script contents are NOT counted text**; they are surfaced separately\n * as `HtmlDocument.jsonLd`. The other reading breaks two mechanisms that the rest\n * of the spec depends on — D5.3 checks that structured data agrees with *visible*\n * text, and \"corroborated\" means observed in ≥2 sources (e.g. JSON-LD *and*\n * visible text). If JSON-LD were visible text, both would be satisfied by a\n * single JSON-LD block, trivially and always. Every text node reports\n * `excludedBy`, so the distinction is visible to callers rather than baked in.\n *\n * TOLERANCE CONTRACT: `tokenizeHtml` never throws, for any input string —\n * unterminated tags, unterminated comments, stray `<`, lone surrogates, 100k\n * nested `<div>`s, binary noise. Conformance fixture `057-tokenizer-fuzz` and\n * `tests/html.test.ts` both assert it. A scanner that can be crashed by the page\n * it is scanning is a denial-of-service endpoint.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why a text node is not counted text. `null` means it is counted. */\nexport type HtmlExclusionReason =\n | 'script'\n | 'script-ld-json'\n | 'style'\n | 'template'\n | 'hidden-attribute'\n | 'inline-display-none'\n\nexport interface HtmlElement {\n /** Index into `HtmlDocument.elements`; ascending in source order. */\n index: number\n /** Lowercased tag name. */\n tag: string\n /** Lowercased attribute names → entity-decoded values. First occurrence wins (HTML5). */\n attrs: Readonly<Record<string, string>>\n /** UTF-8 byte offset of the `<` that opens this tag. */\n offset: number\n /** Index of the enclosing open element, or -1 at document level. */\n parent: number\n /** Nesting depth; 0 at document level. */\n depth: number\n /**\n * Effective exclusion for text inside this element — its own reason, or the\n * nearest ancestor's. `null` when text inside it counts.\n */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlText {\n /** Entity-decoded text (raw, undecoded inside `<script>`/`<style>`). */\n text: string\n /** UTF-8 byte offset of the first character of the RAW source text. */\n offset: number\n /** UTF-8 byte length of the RAW source text. */\n bytes: number\n /** Index of the innermost enclosing element, or -1 at document level. */\n parent: number\n /** `null` when this node is counted text; otherwise why it is not. */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlJsonLd {\n /** Script contents, verbatim. Not entity-decoded: `<script>` is a raw-text element. */\n text: string\n /** UTF-8 byte offset of the first character of the contents. */\n offset: number\n /** Index of the `<script>` element in `HtmlDocument.elements`. */\n element: number\n}\n\nexport interface HtmlMeta {\n /** Lowercased `name`, or null. */\n name: string | null\n /** Lowercased `property` (Open Graph), or null. */\n property: string | null\n /** Lowercased `http-equiv`, or null. */\n httpEquiv: string | null\n /** Lowercased `itemprop`, or null. */\n itemprop: string | null\n /** Lowercased `charset`, or null. */\n charset: string | null\n /** `content`, decoded, case preserved. */\n content: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlLink {\n /**\n * `rel` as a token list, lowercased, source order, duplicates removed.\n * `rel=\"alternate canonical\"` is one link declaring two relations, and D2.2\n * (declared alternates) and D6.1 (canonical) both read it — collapsing it to a\n * string would lose one of them.\n */\n rel: readonly string[]\n href: string | null\n /** Lowercased `type`, or null. */\n type: string | null\n /** Lowercased `hreflang`, or null. */\n hreflang: string | null\n title: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlDocument {\n readonly elements: readonly HtmlElement[]\n readonly texts: readonly HtmlText[]\n readonly jsonLd: readonly HtmlJsonLd[]\n readonly metas: readonly HtmlMeta[]\n readonly links: readonly HtmlLink[]\n /** Total UTF-8 byte length of the source. */\n readonly bytes: number\n}\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * Maps JavaScript string indices to UTF-8 byte offsets in one forward pass.\n *\n * The tokenizer advances monotonically, so `at()` is amortised O(1); a\n * non-monotonic call restarts from zero rather than returning a wrong number,\n * because a silently wrong offset is a silently wrong D4 score.\n *\n * Surrogate handling matches `TextEncoder`: a well-formed pair costs 4 bytes,\n * and a LONE surrogate costs 3 — WHATWG encoding replaces it with U+FFFD, so\n * that is what its byte cost actually is on the wire.\n */\nclass Utf8Cursor {\n private charIndex = 0\n private byteIndex = 0\n\n constructor(private readonly source: string) {}\n\n at(target: number): number {\n if (target < this.charIndex) {\n this.charIndex = 0\n this.byteIndex = 0\n }\n const limit = Math.min(target, this.source.length)\n while (this.charIndex < limit) {\n const code = this.source.charCodeAt(this.charIndex)\n if (code < 0x80) {\n this.byteIndex += 1\n this.charIndex += 1\n } else if (code < 0x800) {\n this.byteIndex += 2\n this.charIndex += 1\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const next =\n this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff && this.charIndex + 1 < limit) {\n this.byteIndex += 4\n this.charIndex += 2\n } else {\n // Lone high surrogate, or a pair straddling `limit`: 3 bytes for U+FFFD.\n this.byteIndex += 3\n this.charIndex += 1\n }\n } else {\n this.byteIndex += 3\n this.charIndex += 1\n }\n }\n return this.byteIndex\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned named character references.\n *\n * The full HTML5 named-reference table is ~2 200 entries. This is the subset\n * that appears in the parts of a page ARS reads — money symbols, typography,\n * and the five XML entities — and it is PINNED per spec version for the same\n * reason the tokenizer is hand-rolled: growing the table changes extracted text,\n * which changes facts, which changes scores. Additions land as a MINOR.\n *\n * A named reference outside this table is left verbatim, which is also the only\n * safe failure: `&hearts;` surviving as literal text costs nothing, whereas\n * guessing would be non-deterministic.\n */\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00a0',\n ensp: '\\u2002',\n emsp: '\\u2003',\n thinsp: '\\u2009',\n shy: '\\u00ad',\n zwnj: '\\u200c',\n zwj: '\\u200d',\n // Currency\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n // Typography\n ndash: '–',\n mdash: '—',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n sbquo: '‚',\n ldquo: '“',\n rdquo: '”',\n bdquo: '„',\n laquo: '«',\n raquo: '»',\n lsaquo: '‹',\n rsaquo: '›',\n bull: '•',\n middot: '·',\n dagger: '†',\n Dagger: '‡',\n prime: '′',\n Prime: '″',\n // Marks and math\n copy: '©',\n reg: '®',\n trade: '™',\n sect: '§',\n para: '¶',\n deg: '°',\n plusmn: '±',\n times: '×',\n divide: '÷',\n minus: '−',\n permil: '‰',\n frac12: '½',\n frac14: '¼',\n frac34: '¾',\n sup2: '²',\n sup3: '³',\n le: '≤',\n ge: '≥',\n ne: '≠',\n // Directionality (invisible, but they do occupy bytes)\n lrm: '\\u200e',\n rlm: '\\u200f',\n}\n\n/**\n * The HTML spec's windows-1252 override for numeric references in 0x80–0x9F.\n * `&#146;` is a right single quote on real pages, not a C1 control, and\n * decoding it as one would corrupt product titles.\n */\nconst C1_REPLACEMENTS: Readonly<Record<number, number>> = {\n 0x80: 0x20ac,\n 0x82: 0x201a,\n 0x83: 0x0192,\n 0x84: 0x201e,\n 0x85: 0x2026,\n 0x86: 0x2020,\n 0x87: 0x2021,\n 0x88: 0x02c6,\n 0x89: 0x2030,\n 0x8a: 0x0160,\n 0x8b: 0x2039,\n 0x8c: 0x0152,\n 0x8e: 0x017d,\n 0x91: 0x2018,\n 0x92: 0x2019,\n 0x93: 0x201c,\n 0x94: 0x201d,\n 0x95: 0x2022,\n 0x96: 0x2013,\n 0x97: 0x2014,\n 0x98: 0x02dc,\n 0x99: 0x2122,\n 0x9a: 0x0161,\n 0x9b: 0x203a,\n 0x9c: 0x0153,\n 0x9e: 0x017e,\n 0x9f: 0x0178,\n}\n\n/**\n * A trailing `;` is REQUIRED. HTML's legacy semicolon-less forms\n * (`&copy` inside `?a=1&copy=2`) are exactly the cases where decoding mangles a\n * URL, and every reference that matters on a page ARS reads is written properly.\n * Bounded name length keeps the match linear.\n */\nconst ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g\n\nfunction codePointToString(raw: number): string {\n const mapped = C1_REPLACEMENTS[raw]\n const code = mapped ?? raw\n // Null, surrogates and out-of-range all become U+FFFD, per the HTML spec.\n if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\\ufffd'\n return String.fromCodePoint(code)\n}\n\n/** Decodes the pinned named references plus numeric references. Never throws. */\nexport function decodeEntities(text: string): string {\n if (!text.includes('&')) return text\n return text.replace(ENTITY_RE, (match, body: string) => {\n if (body.startsWith('#')) {\n const isHex = body[1] === 'x' || body[1] === 'X'\n const digits = isHex ? body.slice(2) : body.slice(1)\n const value = Number.parseInt(digits, isHex ? 16 : 10)\n return Number.isNaN(value) ? match : codePointToString(value)\n }\n return NAMED_ENTITIES[body] ?? match\n })\n}\n\n// ---------------------------------------------------------------------------\n// Element tables\n// ---------------------------------------------------------------------------\n\n/** Void elements: no contents, never pushed onto the open-element stack. */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n])\n\n/** Raw-text elements: contents are opaque, entities are NOT decoded. */\nconst RAW_TEXT_ELEMENTS = new Set(['script', 'style'])\n\n/** RCDATA elements: contents are text, entities ARE decoded, tags are not. */\nconst RCDATA_ELEMENTS = new Set(['textarea', 'title'])\n\n/**\n * Optional-end-tag recovery, in the small form that matters here. A start tag\n * listed as a key implicitly closes any open element in its value set. Without\n * this, `<li>a<li>b` nests forever and `<dt>q<dd>a` puts the answer inside the\n * question — and `<dt>/<dd>` pairs are one of the recognised `question-answer`\n * shapes for the `faq` page kind, so getting it wrong costs real points.\n */\nconst IMPLIED_END_TAGS: Readonly<Record<string, readonly string[]>> = {\n li: ['li'],\n dt: ['dt', 'dd'],\n dd: ['dt', 'dd'],\n option: ['option'],\n optgroup: ['option', 'optgroup'],\n tr: ['td', 'th', 'tr'],\n td: ['td', 'th'],\n th: ['td', 'th'],\n tbody: ['td', 'th', 'tr', 'thead', 'tbody'],\n tfoot: ['td', 'th', 'tr', 'thead', 'tbody'],\n}\n\n/** Block-level start tags that implicitly close an open `<p>`. */\nconst CLOSES_OPEN_P = new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'details',\n 'div',\n 'dl',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'main',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'ul',\n])\n\n/**\n * Cap on open-element depth. Beyond it, elements are still recorded but not\n * pushed, so a page with 200 000 nested `<div>`s costs memory proportional to\n * its bytes and nothing more. Real documents do not approach this.\n */\nconst MAX_DEPTH = 256\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunction isAsciiAlpha(ch: string | undefined): boolean {\n if (ch === undefined) return false\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\nfunction isHtmlSpace(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f'\n}\n\n/**\n * Inline `display:none`, with whitespace stripped first so the test itself is a\n * plain substring match rather than a regex with a backtracking profile. Only\n * the element's own `style` attribute is consulted: NO CSS RESOLUTION (§3.6).\n */\nconst DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/\n\nfunction hasInlineDisplayNone(style: string | undefined): boolean {\n if (style === undefined) return false\n return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\\s+/g, ''))\n}\n\n/** Reads an attribute, or null. Attribute names are lowercased by the tokenizer. */\nexport function attr(element: HtmlElement, name: string): string | null {\n return element.attrs[name] ?? null\n}\n\n// ---------------------------------------------------------------------------\n// Tag parsing\n// ---------------------------------------------------------------------------\n\ninterface ParsedTag {\n tag: string\n attrs: Record<string, string>\n selfClosing: boolean\n /** Index just past the closing `>` (or past the end of input if unterminated). */\n end: number\n}\n\n/**\n * Parses a start tag beginning at `start` (the `<`). Tolerant: an unterminated\n * tag consumes to end of input and returns what it read.\n */\nfunction parseStartTag(html: string, start: number): ParsedTag {\n let i = start + 1\n const nameStart = i\n while (i < html.length) {\n const ch = html[i] ?? ''\n if (isHtmlSpace(ch) || ch === '/' || ch === '>') break\n i++\n }\n const tag = html.slice(nameStart, i).toLowerCase()\n const attrs: Record<string, string> = {}\n let selfClosing = false\n\n while (i < html.length) {\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (i >= html.length) break\n const ch = html[i] ?? ''\n if (ch === '>') {\n i++\n return { tag, attrs, selfClosing, end: i }\n }\n if (ch === '/') {\n selfClosing = true\n i++\n continue\n }\n // Attribute name.\n const attrNameStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '=' || c === '>' || c === '/') break\n i++\n }\n if (i === attrNameStart) {\n // Nothing consumed (e.g. a stray '='): skip a character so we always advance.\n i++\n continue\n }\n const attrName = html.slice(attrNameStart, i).toLowerCase()\n let value = ''\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (html[i] === '=') {\n i++\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n const quote = html[i]\n if (quote === '\"' || quote === \"'\") {\n i++\n const valueStart = i\n const close = html.indexOf(quote, i)\n if (close === -1) {\n value = html.slice(valueStart)\n i = html.length\n } else {\n value = html.slice(valueStart, close)\n i = close + 1\n }\n } else {\n const valueStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '>') break\n i++\n }\n value = html.slice(valueStart, i)\n }\n }\n // First occurrence wins, per the HTML parsing spec.\n if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value)\n }\n return { tag, attrs, selfClosing, end: i }\n}\n\n/** Locates the matching `</tag` for a raw-text or RCDATA element, case-insensitively. */\nfunction findRawTextEnd(lowerHtml: string, from: number, tag: string): number {\n const needle = `</${tag}`\n const at = lowerHtml.indexOf(needle, from)\n return at === -1 ? -1 : at\n}\n\n// ---------------------------------------------------------------------------\n// tokenizeHtml\n// ---------------------------------------------------------------------------\n\n/** The element's own exclusion reason, ignoring ancestors. */\nfunction ownExclusion(\n tag: string,\n attrs: Readonly<Record<string, string>>,\n): HtmlExclusionReason | null {\n if (tag === 'script') {\n const type = (attrs['type'] ?? '').toLowerCase().split(';')[0]?.trim() ?? ''\n return type === 'application/ld+json' ? 'script-ld-json' : 'script'\n }\n if (tag === 'style') return 'style'\n if (tag === 'template') return 'template'\n // `hidden` is a boolean attribute: its presence hides, whatever the value\n // (including `hidden=\"until-found\"`, which is still hidden until found).\n if ('hidden' in attrs) return 'hidden-attribute'\n if (hasInlineDisplayNone(attrs['style'])) return 'inline-display-none'\n return null\n}\n\n/**\n * Tokenizes `html` into the flat, offset-annotated structure ARS scores against.\n * Never throws. `html` is the DECODED response body; offsets are UTF-8 byte\n * offsets into that decoded body, matching `ArsHttpCapture.bytes`.\n */\nexport function tokenizeHtml(html: string): HtmlDocument {\n const elements: HtmlElement[] = []\n const texts: HtmlText[] = []\n const jsonLd: HtmlJsonLd[] = []\n const metas: HtmlMeta[] = []\n const links: HtmlLink[] = []\n const stack: number[] = []\n const cursor = new Utf8Cursor(html)\n\n const topIndex = (): number => stack[stack.length - 1] ?? -1\n const exclusionAt = (elementIndex: number): HtmlExclusionReason | null =>\n elementIndex >= 0 ? (elements[elementIndex]?.excludedBy ?? null) : null\n\n const emitText = (\n from: number,\n to: number,\n decode: boolean,\n override?: HtmlExclusionReason,\n ): void => {\n if (to <= from) return\n const raw = html.slice(from, to)\n const parent = topIndex()\n const offset = cursor.at(from)\n texts.push({\n text: decode ? decodeEntities(raw) : raw,\n offset,\n bytes: cursor.at(to) - offset,\n parent,\n excludedBy: override ?? exclusionAt(parent),\n })\n }\n\n const popTo = (tag: string): void => {\n for (let depth = stack.length - 1; depth >= 0; depth--) {\n const candidate = stack[depth]\n if (candidate === undefined) continue\n if (elements[candidate]?.tag === tag) {\n stack.length = depth\n return\n }\n }\n // No matching open element: a stray end tag. Ignore it, as browsers do.\n }\n\n const applyImpliedEndTags = (tag: string): void => {\n const closes = IMPLIED_END_TAGS[tag]\n if (closes !== undefined) {\n while (stack.length > 0) {\n const top = stack[stack.length - 1]\n const openTag = top === undefined ? undefined : elements[top]?.tag\n if (openTag === undefined || !closes.includes(openTag)) break\n stack.pop()\n }\n }\n if (CLOSES_OPEN_P.has(tag)) {\n const top = stack[stack.length - 1]\n if (top !== undefined && elements[top]?.tag === 'p') stack.pop()\n }\n }\n\n // `textStart` trails `i`: a `<` that turns out NOT to open markup stays inside\n // the current text run rather than splitting it. `a < b` is one text node, not\n // three — and since `countedText` joins nodes with a space, splitting it would\n // silently rewrite the page's own text before any fact is extracted from it.\n let i = 0\n let textStart = 0\n let lowerHtml: string | null = null\n while (i < html.length) {\n const lt = html.indexOf('<', i)\n if (lt === -1) break\n\n const next = html[lt + 1]\n // A `<` opens markup only before `!`, `/`, or an ASCII letter. Anything else\n // — `3<4`, a stray `<` at end of input — is text.\n if (next !== '!' && next !== '/' && !isAsciiAlpha(next)) {\n i = lt + 1\n continue\n }\n emitText(textStart, lt, true)\n\n // --- Comments, doctypes, CDATA, bogus comments ---\n if (next === '!') {\n if (html.startsWith('<!--', lt)) {\n const close = html.indexOf('-->', lt + 4)\n i = close === -1 ? html.length : close + 3\n } else {\n const close = html.indexOf('>', lt + 2)\n i = close === -1 ? html.length : close + 1\n }\n textStart = i\n continue\n }\n\n // --- End tags ---\n if (next === '/') {\n const close = html.indexOf('>', lt + 2)\n const end = close === -1 ? html.length : close + 1\n const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim()\n const tag = rawName.toLowerCase()\n if (tag.length > 0) popTo(tag)\n i = end\n textStart = i\n continue\n }\n\n // --- Start tags ---\n const parsed = parseStartTag(html, lt)\n applyImpliedEndTags(parsed.tag)\n\n const parent = topIndex()\n const own = ownExclusion(parsed.tag, parsed.attrs)\n const element: HtmlElement = {\n index: elements.length,\n tag: parsed.tag,\n attrs: parsed.attrs,\n offset: cursor.at(lt),\n parent,\n depth: stack.length,\n excludedBy: exclusionAt(parent) ?? own,\n }\n elements.push(element)\n collectMetaOrLink(element, metas, links)\n i = parsed.end\n\n const isVoid = VOID_ELEMENTS.has(parsed.tag)\n const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag)\n const isRcdata = RCDATA_ELEMENTS.has(parsed.tag)\n\n if (isRawText || isRcdata) {\n // Contents are opaque: no nested tags, no stack push. Entities are decoded\n // for RCDATA (`<title>`, `<textarea>`) and NOT for raw text (`<script>`,\n // `<style>`) — a JSON-LD block must survive byte-for-byte.\n const contentStart = i\n lowerHtml ??= html.toLowerCase()\n const close = findRawTextEnd(lowerHtml, contentStart, parsed.tag)\n const contentEnd = close === -1 ? html.length : close\n if (contentEnd > contentStart) {\n const wasTop = stack.length\n stack.push(element.index)\n emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? undefined)\n stack.length = wasTop\n if (own === 'script-ld-json') {\n jsonLd.push({\n text: html.slice(contentStart, contentEnd),\n offset: cursor.at(contentStart),\n element: element.index,\n })\n }\n }\n if (close === -1) {\n i = html.length\n } else {\n const gt = html.indexOf('>', close)\n i = gt === -1 ? html.length : gt + 1\n }\n textStart = i\n continue\n }\n\n if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index)\n textStart = i\n }\n emitText(textStart, html.length, true)\n\n return {\n elements,\n texts,\n jsonLd,\n metas,\n links,\n bytes: cursor.at(html.length),\n }\n}\n\n/** Records `<meta>` and `<link>` elements into their typed side-tables. */\nfunction collectMetaOrLink(element: HtmlElement, metas: HtmlMeta[], links: HtmlLink[]): void {\n const lower = (value: string | undefined): string | null =>\n value === undefined ? null : value.toLowerCase()\n\n if (element.tag === 'meta') {\n metas.push({\n name: lower(element.attrs['name']),\n property: lower(element.attrs['property']),\n httpEquiv: lower(element.attrs['http-equiv']),\n itemprop: lower(element.attrs['itemprop']),\n charset: lower(element.attrs['charset']),\n content: element.attrs['content'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n return\n }\n\n if (element.tag === 'link') {\n const rawRel = element.attrs['rel'] ?? ''\n const rel: string[] = []\n for (const token of rawRel.toLowerCase().split(/\\s+/)) {\n if (token.length > 0 && !rel.includes(token)) rel.push(token)\n }\n links.push({\n rel,\n href: element.attrs['href'] ?? null,\n type: lower(element.attrs['type']),\n hreflang: lower(element.attrs['hreflang']),\n title: element.attrs['title'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text views\n// ---------------------------------------------------------------------------\n\n/**\n * Joins text nodes with a single space and collapses whitespace runs.\n *\n * A single space rather than an empty string: `<b>Blue</b><i>Shirt</i>` renders\n * as two words to a reader, and \"BlueShirt\" is not a title. Joining always,\n * rather than only across block boundaries, avoids needing a display-model —\n * which is the same reason there is no CSS resolution anywhere in this file.\n */\nfunction joinText(parts: readonly string[]): string {\n return parts.join(' ').replace(/\\s+/g, ' ').trim()\n}\n\n/** All counted text in the document, per the §3.6 normative extraction rule. */\nexport function countedText(doc: HtmlDocument): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy === null) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/**\n * Counted text inside one element's subtree — anchor text for\n * `primary-action-url`, a `<summary>`'s question, a heading. `includeExcluded`\n * opts into hidden subtrees, which the extractor needs for exactly one thing:\n * reporting hidden facts as evidence (fixture `037-hidden-text-facts`) without\n * letting them score.\n */\nexport function elementText(\n doc: HtmlDocument,\n elementIndex: number,\n includeExcluded = false,\n): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (!includeExcluded && node.excludedBy !== null) continue\n if (isSelfOrDescendant(doc, node.parent, elementIndex)) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/** Walks `parent` links upward. Bounded by MAX_DEPTH + 1 so a cycle cannot hang. */\nfunction isSelfOrDescendant(doc: HtmlDocument, from: number, ancestor: number): boolean {\n let current = from\n for (let hops = 0; hops <= MAX_DEPTH + 1 && current >= 0; hops++) {\n if (current === ancestor) return true\n current = doc.elements[current]?.parent ?? -1\n }\n return false\n}\n","/**\n * extract.ts — pass 2 of the ARS pipeline: turn one fetched representation into\n * a set of normalised fact observations, scored against the resolved page-kind\n * profile (design §3.5, §3.6).\n *\n * WHAT A \"REPRESENTATION\" IS. The probe returns two captures that differ only in\n * their `Accept` header (§3.3). Each one is turned into an `ArsRepresentation`:\n * a decoded body, its byte length as the probe measured it, the tokenized\n * document when the bytes are HTML, the JSON-LD blocks, and the counted text.\n * Everything downstream reads a representation, never a raw capture, so the\n * markdown path and the HTML path go through the same scoring code.\n *\n * WHICH REPRESENTATION SCORES WHAT — the decision that makes the golden pair\n * (`001-pdp-gateway-md` vs `002-pdp-raw-html`) mean anything:\n *\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. A merchant whose markdown omits\n * `availability` loses coverage even though the HTML declares it — the agent\n * never saw it.\n *\n * D1.3 (render independence) and D5 (structured data) score the HTML\n * representation, because those checks are about the document a caller that\n * only reads HTML gets. JSON-LD does not live in markdown, and \"would this\n * page work without JavaScript\" is a question about HTML.\n *\n * CORROBORATION CROSSES THE TWO. §3.6 defines corroborated as \"observed in ≥2\n * sources (e.g. JSON-LD and visible text)\". A price stated in the negotiated\n * markdown *and* in the HTML's JSON-LD is observed in two sources and is\n * corroborated; that is the only reason a correctly installed gateway can reach\n * an A. But a fact observed ONLY in the HTML does not enter the scored fact set\n * at all — corroboration strengthens a fact the agent received, it never\n * conjures one it did not. See `mergeFacts`.\n *\n * VALUE FACTS vs PRESENCE FACTS. Some facts are compared by value (a price, a\n * title, a phone number); others are only ever \"declared or not\" (shipping,\n * returns, opening hours, question/answer shape). Presence facts normalise to\n * the literal string `declared` from EVERY source, deliberately: two sources\n * that describe the same shipping policy in different words must still\n * corroborate each other, and a free-text comparison would make that\n * non-deterministic. The split is pinned in `PRESENCE_FACTS` below and printed\n * in the spec, because it is the difference between \"we compared the values\" and\n * \"we compared whether you said anything\".\n *\n * EVERYTHING HERE IS PINNED DATA, NOT INFERENCE. The label lexicon, the\n * availability vocabulary, the no-published-price phrases, the schema.org\n * property aliases: all tables, all versioned. An extractor that guessed would\n * make `score()` non-reproducible in a second implementation, which is the one\n * property the whole package exists to provide.\n */\n\nimport { attr, countedText, elementText, tokenizeHtml } from './html'\nimport type { HtmlDocument } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type {\n ArsAudience,\n ArsAudienceDecision,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsHttpCapture,\n ArsPolicyReport,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * UTF-8 byte length of a JavaScript string, counting a lone surrogate as 3\n * bytes — the width WHATWG encoding gives U+FFFD, which is what a lone\n * surrogate actually costs on the wire. Matches `Utf8Cursor` in `./html`, which\n * is why offsets from the two files are in the same address space.\n */\nexport function utf8Length(text: string): number {\n let bytes = 0\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code <= 0xdbff) {\n const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4\n i++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD\n// ---------------------------------------------------------------------------\n\n/** A flattened JSON-LD node: one object with an `@type`, wherever it was nested. */\nexport interface JsonLdNode {\n /** `@type` values with any `http(s)://schema.org/` prefix stripped. Always ≥1 entry. */\n readonly types: readonly string[]\n readonly value: Readonly<Record<string, unknown>>\n /** UTF-8 byte offset of the block the node came from. */\n readonly offset: number\n}\n\n/** What `parseJsonLd` observed, including the blocks that failed — D5.1 scores both. */\nexport interface JsonLdReport {\n readonly nodes: readonly JsonLdNode[]\n readonly blocks: number\n readonly parsed: number\n}\n\nconst SCHEMA_PREFIX = /^https?:\\/\\/schema\\.org\\//\n\nfunction stripSchemaPrefix(type: string): string {\n return type.replace(SCHEMA_PREFIX, '')\n}\n\n/** Types from a node's `@type`, which may be a string or an array of strings. */\nfunction typesOf(value: Record<string, unknown>): string[] {\n const raw = value['@type']\n if (typeof raw === 'string') return [stripSchemaPrefix(raw)]\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) if (typeof entry === 'string') out.push(stripSchemaPrefix(entry))\n return out\n }\n return []\n}\n\n/** Depth cap on JSON-LD traversal. Deeper than any real graph; stops a hostile nesting bomb. */\nconst JSON_LD_MAX_DEPTH = 12\n\nfunction collectNodes(\n value: unknown,\n offset: number,\n depth: number,\n out: JsonLdNode[],\n seen: Set<object>,\n): void {\n if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== 'object') return\n if (seen.has(value)) return\n seen.add(value)\n\n if (Array.isArray(value)) {\n for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen)\n return\n }\n\n const record = value as Record<string, unknown>\n const types = typesOf(record)\n if (types.length > 0) out.push({ types, value: record, offset })\n\n for (const [key, child] of Object.entries(record)) {\n if (key === '@context') continue\n collectNodes(child, offset, depth + 1, out, seen)\n }\n}\n\n/**\n * Parses every JSON-LD block. A block that does not parse is counted and\n * dropped: D5.1 scores \"present **and parses**\", so fixture `033-invalid-jsonld`\n * needs the block count and the parsed count to differ.\n */\nexport function parseJsonLd(blocks: readonly { text: string; offset: number }[]): JsonLdReport {\n const nodes: JsonLdNode[] = []\n let parsed = 0\n for (const block of blocks) {\n let value: unknown\n try {\n value = JSON.parse(block.text) as unknown\n } catch {\n continue\n }\n parsed++\n collectNodes(value, block.offset, 0, nodes, new Set<object>())\n }\n return { nodes, blocks: blocks.length, parsed }\n}\n\n/**\n * Reads a dotted property path off a node, entering array members: `offers.price`\n * matches `offers[0].price`. Returns the first non-empty scalar found, or null.\n * The notation is the one `DEFAULT_RULESET.requiredProperties` is written in.\n */\nexport function readPath(node: JsonLdNode, path: string): string | null {\n const segments = path.split('.')\n let frontier: unknown[] = [node.value]\n for (const segment of segments) {\n const next: unknown[] = []\n for (const current of frontier) {\n if (current === null || typeof current !== 'object') continue\n if (Array.isArray(current)) {\n for (const entry of current) {\n if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {\n const child = (entry as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n }\n continue\n }\n const child = (current as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n frontier = next\n if (frontier.length === 0) return null\n }\n for (const found of frontier) {\n const scalar = scalarOf(found)\n if (scalar !== null) return scalar\n }\n return null\n}\n\n/**\n * A scalar reading of a JSON-LD value. Objects yield their `name`, `@id` or\n * `value` — `brand: {\"@type\":\"Brand\",\"name\":\"X\"}` is the common real shape and\n * refusing to read it would cost merchants points for correct markup.\n */\nfunction scalarOf(value: unknown): string | null {\n if (typeof value === 'string') return value.trim().length > 0 ? value.trim() : null\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) {\n for (const entry of value) {\n const scalar = scalarOf(entry)\n if (scalar !== null) return scalar\n }\n return null\n }\n if (value !== null && typeof value === 'object') {\n const record = value as Record<string, unknown>\n for (const key of ['name', 'value', '@id', 'url', 'headline']) {\n const scalar = scalarOf(record[key])\n if (scalar !== null) return scalar\n }\n }\n return null\n}\n\n/** True when the path resolves to anything at all — what D5.2 counts. */\nexport function hasPath(node: JsonLdNode, path: string): boolean {\n return readPath(node, path) !== null\n}\n\n// ---------------------------------------------------------------------------\n// Representations\n// ---------------------------------------------------------------------------\n\nexport type ArsRepresentationKind = 'html' | 'markdown' | 'text' | 'json' | 'other'\n\nexport interface ArsRepresentation {\n /** Classified from the `Content-Type` header alone. See `looksLikeHtml` for the body's opinion. */\n readonly kind: ArsRepresentationKind\n /** Lowercased media type without parameters, or null when the header is absent. */\n readonly contentType: string | null\n /** The decoded body. */\n readonly body: string\n /** Byte length AS THE PROBE MEASURED IT (`ArsHttpCapture.bytes`), not recomputed. */\n readonly bytes: number\n /** Tokenized document, present whenever the bytes are HTML however they are labelled. */\n readonly doc: HtmlDocument | null\n readonly jsonLd: JsonLdReport\n /** Counted text (§3.6) for HTML; the body itself for every other kind. */\n readonly text: string\n /** The body's own opinion, independent of the header. D2.1 scores the disagreement. */\n readonly looksLikeHtml: boolean\n readonly truncated: boolean\n readonly finalUrl: string\n readonly headers: Readonly<Record<string, readonly string[]>>\n}\n\n/** First value of a header, or null. Header names are lowercased by the probe. */\nexport function header(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): string | null {\n const values = headers[name]\n return values !== undefined && values.length > 0 ? (values[0] ?? null) : null\n}\n\n/** All values of a header, in order. `Link` is routinely repeated and is scored twice over. */\nexport function headerAll(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): readonly string[] {\n return headers[name] ?? []\n}\n\n/** Media type without parameters, lowercased. */\nexport function mediaType(contentType: string | null): string | null {\n if (contentType === null) return null\n const semi = contentType.indexOf(';')\n const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()\n return value.length > 0 ? value : null\n}\n\nfunction classifyMediaType(type: string | null): ArsRepresentationKind {\n if (type === null) return 'other'\n if (type === 'text/html' || type === 'application/xhtml+xml') return 'html'\n if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'\n if (type === 'text/plain') return 'text'\n if (type === 'application/json' || type === 'application/ld+json' || type.endsWith('+json')) {\n return 'json'\n }\n return 'other'\n}\n\n/**\n * Does the body look like HTML regardless of what the header claims? Bounded to\n * the first 1 KiB so the test is O(1) on a 2 MiB body. Fixture\n * `036-negotiation-wrong-content-type` is exactly the case where the header and\n * this function disagree, and D2.1 pays for it.\n */\nfunction bodyLooksLikeHtml(body: string): boolean {\n const head = body.slice(0, 1024).trimStart().toLowerCase()\n return head.startsWith('<!doctype html') || head.startsWith('<html') || head.startsWith('<?xml')\n ? true\n : head.includes('<html') || head.includes('<head>') || head.includes('<body')\n}\n\n/**\n * Builds a representation from a capture. Returns null when the body is absent:\n * `ArsHttpCapture.body` is optional because a PUBLISHED evidence bundle carries\n * the hash and not the bytes (§3.9), and a bundle without bytes cannot be\n * re-scored — `score()` reports `unscored / evidence-incomplete` rather than\n * inventing a zero.\n */\nexport function buildRepresentation(capture: ArsHttpCapture): ArsRepresentation | null {\n if (typeof capture.body !== 'string') return null\n const contentType = mediaType(header(capture.headers, 'content-type'))\n const declared = classifyMediaType(contentType)\n const looksLikeHtml = bodyLooksLikeHtml(capture.body)\n\n // Tokenize whenever the BYTES are HTML, whatever the header says. A merchant\n // with a mislabelled content type already loses 10 points on D2.1; taking\n // their fact coverage as well would charge them twice for one mistake.\n const doc = declared === 'html' || looksLikeHtml ? tokenizeHtml(capture.body) : null\n\n const jsonLd =\n doc !== null\n ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset })))\n : declared === 'json'\n ? parseJsonLd([{ text: capture.body, offset: 0 }])\n : { nodes: [], blocks: 0, parsed: 0 }\n\n return {\n kind: declared,\n contentType,\n body: capture.body,\n bytes: capture.bytes,\n doc,\n jsonLd,\n text: doc !== null ? countedText(doc) : capture.body,\n looksLikeHtml,\n truncated: capture.truncated,\n finalUrl: capture.finalUrl,\n headers: capture.headers,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Facts — the internal shape\n// ---------------------------------------------------------------------------\n\nexport type ArsFactSource = ArsFactObservation['source']\n\n/**\n * One observation before merging. `qualified` and `element` are internal:\n * `ArsFactObservation` (§3.9) carries neither, and this file exists to keep the\n * published shape exactly as the design wrote it.\n */\nexport interface ExtractedFact {\n readonly kind: ArsFactKind\n readonly normalized: string\n readonly source: ArsFactSource\n readonly offset: number\n /** True for ranges and qualifiers. Excluded from the D2.4 parity comparison (§3.11). */\n readonly qualified: boolean\n}\n\n/** A merged fact: the published observation plus what merging learned. */\nexport interface MergedFact extends ArsFactObservation {\n readonly qualified: boolean\n /** Distinct sources that reported THIS value. `corroborated` is `length >= 2`. */\n readonly sources: readonly ArsFactSource[]\n}\n\n/**\n * Source precedence, used only to break an offset tie. Declaration order is the\n * order of the union in §3.9, so a second implementation reads it off the\n * published type rather than out of this file.\n */\nconst SOURCE_ORDER: readonly ArsFactSource[] = [\n 'json-ld',\n 'microdata',\n 'meta',\n 'html-text',\n 'negotiated',\n]\n\n/**\n * Facts that are only ever \"declared or not\". Every source normalises them to\n * the literal `declared`, so two sources that word the same shipping policy\n * differently still corroborate one another. See the file header.\n */\nconst PRESENCE_FACTS: ReadonlySet<ArsFactKind> = new Set<ArsFactKind>([\n 'shipping',\n 'returns',\n 'hours',\n 'service-area',\n 'eligibility',\n 'question-answer',\n 'item-link',\n])\n\nconst DECLARED = 'declared'\n\n/**\n * Merges observations into the published fact set.\n *\n * `primary` is the representation the agent received; `corroborating` is the\n * other one. A fact appears in the output only if the AGENT saw it. The\n * representative observation is the one with the lowest byte offset (ties broken\n * by `SOURCE_ORDER`, then lexicographically by value) — lowest offset, because\n * D4.1 scores the byte offset at which a fact first becomes available.\n * `corroborated` counts the distinct sources, across BOTH representations, that\n * reported the representative's exact normalised value; a source reporting a\n * different value corroborates nothing, which is what makes fixture\n * `034-jsonld-price-mismatch` fail to corroborate rather than agree.\n */\nexport function mergeFacts(\n primary: readonly ExtractedFact[],\n corroborating: readonly ExtractedFact[],\n): MergedFact[] {\n const byKind = new Map<ArsFactKind, ExtractedFact[]>()\n for (const fact of primary) {\n const list = byKind.get(fact.kind)\n if (list === undefined) byKind.set(fact.kind, [fact])\n else list.push(fact)\n }\n\n const merged: MergedFact[] = []\n for (const [kind, observations] of byKind) {\n const representative = observations.reduce((best, candidate) =>\n betterObservation(best, candidate),\n )\n const sources: ArsFactSource[] = []\n for (const fact of [...observations, ...corroborating]) {\n if (fact.kind !== kind) continue\n if (fact.normalized !== representative.normalized) continue\n if (!sources.includes(fact.source)) sources.push(fact.source)\n }\n merged.push({\n kind,\n normalized: representative.normalized,\n source: representative.source,\n offset: representative.offset,\n corroborated: sources.length >= 2,\n qualified: representative.qualified,\n sources,\n })\n }\n\n merged.sort((a, b) => (a.offset === b.offset ? cmp(a.kind, b.kind) : a.offset - b.offset))\n return merged\n}\n\nfunction betterObservation(a: ExtractedFact, b: ExtractedFact): ExtractedFact {\n if (a.offset !== b.offset) return a.offset < b.offset ? a : b\n const rank = SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source)\n if (rank !== 0) return rank < 0 ? a : b\n return cmp(a.normalized, b.normalized) <= 0 ? a : b\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n// ---------------------------------------------------------------------------\n// Normalisation\n// ---------------------------------------------------------------------------\n\nconst TITLE_SEPARATORS = [' | ', ' — ', ' – ', ' · ', ' :: ', ' » ']\n\n/**\n * Collapse whitespace, cut at the first pinned separator, lowercase.\n *\n * The cut is what lets `<title>Alpine Trail Pack 28L — 420D Ripstop | Basecamp\n * Supply Co</title>` corroborate a JSON-LD `name` of `Alpine Trail Pack 28L`.\n * Without it, essentially no real page would ever have a corroborated title,\n * and `title` is a core fact for seven of the eight page kinds.\n */\nexport function normalizeTitle(text: string): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim()\n let cut = collapsed\n for (const separator of TITLE_SEPARATORS) {\n const at = cut.indexOf(separator)\n if (at > 0) cut = cut.slice(0, at)\n }\n return cut.trim().toLowerCase()\n}\n\n/** Collapse whitespace + lowercase, capped so one long description cannot bloat a result. */\nconst MAX_NORMALIZED_TEXT = 200\n\nexport function normalizeText(text: string): string {\n return text.replace(/\\s+/g, ' ').trim().toLowerCase().slice(0, MAX_NORMALIZED_TEXT)\n}\n\n/**\n * Money → `<ISO> <minor units>`, e.g. `USD 14800`. Currency travels with the\n * amount so the D2.4 parity comparison cannot match 14800 JPY against 14800 USD,\n * and `currency` is still reported separately because it is its own core fact.\n */\nfunction normalizeMoney(amount: number, currency: string): string {\n return `${currency} ${amount}`\n}\n\n/** ISO 8601 date, day precision. Anything that is not a recognisable date is not a fact. */\nexport function normalizeDate(text: string): string | null {\n const trimmed = text.trim()\n const iso = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(trimmed)\n if (iso !== null) return `${iso[1]}-${iso[2]}-${iso[3]}`\n const slashes = /^(\\d{4})\\/(\\d{2})\\/(\\d{2})/.exec(trimmed)\n if (slashes !== null) return `${slashes[1]}-${slashes[2]}-${slashes[3]}`\n const named = /^(\\d{1,2}) ([A-Za-z]{3,9}) (\\d{4})$/.exec(trimmed)\n if (named !== null) {\n const month = MONTHS.indexOf((named[2] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${named[3]}-${pad2(month + 1)}-${pad2(Number(named[1]))}`\n }\n const american = /^([A-Za-z]{3,9}) (\\d{1,2}), (\\d{4})$/.exec(trimmed)\n if (american !== null) {\n const month = MONTHS.indexOf((american[1] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${american[3]}-${pad2(month + 1)}-${pad2(Number(american[2]))}`\n }\n return null\n}\n\nconst MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\nfunction pad2(value: number): string {\n return value < 10 ? `0${value}` : String(value)\n}\n\n/**\n * The availability vocabulary, pinned. schema.org URLs, the bare enum names and\n * the visible-text phrases all collapse to one of six tokens, because \"In stock\"\n * on the page and `https://schema.org/InStock` in the JSON-LD are the same fact\n * and must corroborate.\n */\nconst AVAILABILITY_TOKENS: readonly (readonly [string, string])[] = [\n ['limitedavailability', 'limited'],\n ['onlineonly', 'instock'],\n ['instoreonly', 'instock'],\n ['presale', 'preorder'],\n ['preorder', 'preorder'],\n ['backorder', 'backorder'],\n ['discontinued', 'discontinued'],\n ['soldout', 'outofstock'],\n ['outofstock', 'outofstock'],\n ['instock', 'instock'],\n]\n\n/** Visible-text phrases, matched against normalised text. Longest first. */\nconst AVAILABILITY_PHRASES: readonly (readonly [string, string])[] = [\n ['limited availability', 'limited'],\n ['limited stock', 'limited'],\n ['currently unavailable', 'outofstock'],\n ['temporarily unavailable', 'outofstock'],\n ['out of stock', 'outofstock'],\n ['discontinued', 'discontinued'],\n ['back order', 'backorder'],\n ['backorder', 'backorder'],\n ['pre-order', 'preorder'],\n ['preorder', 'preorder'],\n ['sold out', 'outofstock'],\n ['in stock', 'instock'],\n ['available now', 'instock'],\n]\n\nexport function normalizeAvailability(value: string): string | null {\n const squashed = value.toLowerCase().replace(/[^a-z]/g, '')\n for (const [needle, token] of AVAILABILITY_TOKENS) {\n if (squashed.endsWith(needle) || squashed === needle) return token\n }\n return null\n}\n\n/**\n * \"We score honesty, not disclosure\" (§3.5): an explicit statement that there is\n * no published price satisfies the `price` core fact. The list is pinned and\n * deliberately short — it contains only phrases that state the absence of a\n * price, never phrases that merely fail to state one.\n */\nconst NO_PUBLISHED_PRICE: readonly string[] = [\n 'price on request',\n 'pricing on request',\n 'price on application',\n 'contact us for pricing',\n 'contact for pricing',\n 'contact us for a quote',\n 'no published price',\n 'pricing available on request',\n]\n\nconst UNPRICED = 'unpriced'\n\n/** Phone → `+` and digits. `(415) 555-0142` and `+1 415 555 0142` are one fact. */\nexport function normalizePhone(value: string): string | null {\n const trimmed = value.trim()\n const plus = trimmed.startsWith('+') || trimmed.startsWith('tel:+')\n const digits = trimmed.replace(/\\D/g, '')\n if (digits.length < 7 || digits.length > 15) return null\n return plus ? `+${digits}` : digits\n}\n\n// ---------------------------------------------------------------------------\n// Money tokens in free text\n// ---------------------------------------------------------------------------\n\n/**\n * Single-character currency symbols that may START a money span. Multi-character\n * markers (`R$`, `kr`, `CHF`) are reached through the ISO-code branch instead: a\n * scanner that treated `R` or `k` as a currency start would open a span on every\n * capital R on the page and hand `parseMoneyText` garbage to reject.\n */\nconst CURRENCY_SYMBOLS = '$€£¥₹₩₪₫₴₦₱฿₺'\nconst DIGITS = '0123456789'\n/** Comma, period, both apostrophes, plain space, NBSP, NARROW NBSP. */\nconst MONEY_SEPARATORS = \".,'’   \"\nconst MONEY_PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as low as',\n 'starts at',\n 'from',\n]\nconst RANGE_JOINERS = ['—', '–', '-', ' to ']\n\n/**\n * Finds money-shaped substrings and hands each to `parseMoneyText`.\n *\n * Written as a scanner rather than a regex on purpose: the pattern that would\n * express this correctly needs nested quantifiers over overlapping character\n * classes, which is both a backtracking hazard on attacker-supplied bytes and\n * much harder to reimplement in another language than twenty lines of loop.\n *\n * The window handed to the parser includes an immediately preceding qualifier\n * (`From $9`) and a following range operand (`$148 – $198`), because\n * `parseMoneyText` resolves both to the lower bound with `qualified: true`, and a\n * qualified price is excluded from D2.4 parity (§3.11). Slicing the bare token\n * would silently turn a range into an exact price.\n */\nexport function findMoneyPhrases(text: string): { phrase: string; index: number }[] {\n const found: { phrase: string; index: number }[] = []\n const limit = Math.min(text.length, MAX_SCAN_CHARS)\n let i = 0\n while (i < limit) {\n const spanEnd = readMoneySpan(text, i, limit)\n if (spanEnd === null) {\n i++\n continue\n }\n let start = i\n let end = spanEnd\n\n // Leading qualifier.\n const before = text.slice(Math.max(0, start - 20), start).toLowerCase()\n for (const qualifier of MONEY_PREFIX_QUALIFIERS) {\n if (before.trimEnd().endsWith(qualifier)) {\n start = Math.max(0, start - (before.length - before.trimEnd().length) - qualifier.length)\n break\n }\n }\n\n // Trailing range operand.\n for (const joiner of RANGE_JOINERS) {\n const after = text.slice(end, end + joiner.length + 2)\n const at = after.indexOf(joiner)\n if (at === -1 || at > 1) continue\n const secondStart = end + at + joiner.length\n const secondEnd = readMoneySpan(text, skipSpaces(text, secondStart, limit), limit)\n if (secondEnd !== null) end = secondEnd\n break\n }\n\n found.push({ phrase: text.slice(start, end), index: start })\n i = end\n }\n return found\n}\n\n/** Bounded scan window. A 2 MiB body is data, not a budget. */\nconst MAX_SCAN_CHARS = 400_000\n\nfunction skipSpaces(text: string, from: number, limit: number): number {\n let i = from\n while (i < limit && text.charAt(i) === ' ') i++\n return i\n}\n\n/**\n * Reads one money-shaped span starting at `from`, or null. A span is a currency\n * marker adjacent to a digit run, in either order; the marker is a symbol from\n * the pinned set or an uppercase three-letter token.\n */\nfunction readMoneySpan(text: string, from: number, limit: number): number | null {\n const char = text.charAt(from)\n if (CURRENCY_SYMBOLS.includes(char) && char !== '') {\n let i = from + 1\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n if (DIGITS.includes(char)) {\n // Only start a span at the beginning of a number run.\n const previous = from > 0 ? text.charAt(from - 1) : ''\n if (DIGITS.includes(previous) || MONEY_SEPARATORS.includes(previous)) return null\n const end = readNumberRun(text, from, limit)\n let i = end\n if (text.charAt(i) === ' ') i++\n const symbol = text.charAt(i)\n if (CURRENCY_SYMBOLS.includes(symbol) && symbol !== '') return i + 1\n const code = text.slice(i, i + 3)\n if (/^[A-Z]{3}$/.test(code) && !/[A-Za-z]/.test(text.charAt(i + 3))) return i + 3\n return null\n }\n if (/[A-Z]/.test(char) && from + 3 <= limit) {\n const code = text.slice(from, from + 3)\n if (!/^[A-Z]{3}$/.test(code)) return null\n if (from > 0 && /[A-Za-z]/.test(text.charAt(from - 1))) return null\n let i = from + 3\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n return null\n}\n\nfunction readNumberRun(text: string, from: number, limit: number): number {\n let i = from\n let end = from\n while (i < limit) {\n const char = text.charAt(i)\n if (DIGITS.includes(char)) {\n i++\n end = i\n continue\n }\n if (MONEY_SEPARATORS.includes(char) && char !== '') {\n i++\n continue\n }\n break\n }\n return end\n}\n\n// ---------------------------------------------------------------------------\n// Label lexicon — the key/value shape of markdown and of `<dt>`-style HTML\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned label → fact mapping. This is how facts are read out of the negotiated\n * markdown representation, whose shape is `- **Price:** $148.00` (see\n * `@rebilder/render-md`), and out of definition-list HTML.\n *\n * Pinned rather than fuzzy-matched for the usual reason: a lexicon that grew per\n * page would make the same bytes score differently in two implementations.\n * Additions land as a MINOR.\n */\nconst LABEL_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['price', 'price'],\n ['cost', 'price'],\n ['currency', 'currency'],\n ['availability', 'availability'],\n ['stock', 'availability'],\n ['brand', 'brand'],\n ['manufacturer', 'brand'],\n ['sku', 'sku'],\n ['item number', 'sku'],\n ['product code', 'sku'],\n ['mpn', 'sku'],\n ['shipping', 'shipping'],\n ['delivery', 'shipping'],\n ['returns', 'returns'],\n ['return policy', 'returns'],\n ['refunds', 'returns'],\n ['description', 'description'],\n ['summary', 'description'],\n ['updated', 'updated'],\n ['last updated', 'updated'],\n ['modified', 'updated'],\n ['published', 'published'],\n ['date published', 'published'],\n ['author', 'author'],\n ['written by', 'author'],\n ['publisher', 'authority'],\n ['organization', 'org-name'],\n ['organisation', 'org-name'],\n ['company', 'org-name'],\n ['business', 'org-name'],\n ['address', 'address'],\n ['location', 'address'],\n ['phone', 'phone'],\n ['telephone', 'phone'],\n ['tel', 'phone'],\n ['email', 'email'],\n ['e-mail', 'email'],\n ['hours', 'hours'],\n ['opening hours', 'hours'],\n ['duration', 'duration'],\n ['length', 'duration'],\n ['eligibility', 'eligibility'],\n ['requirements', 'eligibility'],\n ['section', 'section'],\n ['category', 'section'],\n ['topic', 'section'],\n ['service area', 'service-area'],\n ['areas served', 'service-area'],\n ['items', 'item-count'],\n ['item count', 'item-count'],\n]\n\n/** Strips markdown list bullets, emphasis and heading marks from a label. */\nfunction normalizeLabel(raw: string): string {\n return raw\n .replace(/^[\\s>*\\-+#]+/, '')\n .replace(/[*_`]/g, '')\n .trim()\n .toLowerCase()\n}\n\ninterface LabelledValue {\n kind: ArsFactKind\n value: string\n index: number\n}\n\n/**\n * Reads `Label: value` lines. Handles the markdown emphasis form\n * (`- **Price:** $148.00`), the plain form (`Price: $148.00`) and nothing else —\n * a colon inside prose is not a label, which is why the label must be the first\n * thing on the line and no longer than `MAX_LABEL_CHARS`.\n */\nfunction readLabelledLines(text: string): LabelledValue[] {\n const out: LabelledValue[] = []\n let cursor = 0\n for (const line of text.split('\\n')) {\n const lineStart = cursor\n cursor += line.length + 1\n const colon = line.indexOf(':')\n if (colon === -1 || colon > MAX_LABEL_CHARS) continue\n const label = normalizeLabel(line.slice(0, colon))\n if (label.length === 0) continue\n const value = line\n .slice(colon + 1)\n .replace(/^[\\s*_`]+/, '')\n .trim()\n if (value.length === 0) continue\n for (const [needle, kind] of LABEL_LEXICON) {\n if (label !== needle) continue\n out.push({ kind, value, index: lineStart + colon + 1 })\n break\n }\n }\n return out\n}\n\nconst MAX_LABEL_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Extraction context\n// ---------------------------------------------------------------------------\n\nexport interface ExtractContext {\n readonly profile: ArsFactProfile\n readonly ruleset: ArsRuleset\n /** Absolute URL the capture resolved to, used as the base for relative links. */\n readonly baseUrl: string\n /** Origin of the target, for the same-origin test on `item-link`. */\n readonly origin: string\n /** ISO code from structured data, if any. Disambiguates `$` and a bare `1.500`. */\n readonly currencyHint: string | undefined\n}\n\n/** Facts the caller wants: the profile's core plus extended set, as one lookup. */\nfunction wanted(profile: ArsFactProfile): ReadonlySet<ArsFactKind> {\n return new Set<ArsFactKind>([...profile.core, ...profile.extended])\n}\n\n/**\n * Pass 2 (§3.5): extract against the RESOLVED profile. Only facts the profile\n * names are extracted, which is the mechanism that caps coverage at the profile\n * size and makes fixtures `031-keyword-stuffed` and `032-density-baseline` score\n * identically — a page can invent a hundred extra facts and none of them counts.\n */\nexport function extractFacts(\n representation: ArsRepresentation,\n context: ExtractContext,\n): ExtractedFact[] {\n const facts: ExtractedFact[] = []\n const want = wanted(context.profile)\n const push = (fact: ExtractedFact): void => {\n if (want.has(fact.kind)) facts.push(fact)\n }\n\n for (const node of representation.jsonLd.nodes) extractFromJsonLd(node, context, push)\n\n if (representation.doc !== null) {\n extractFromHtml(representation.doc, context, push)\n } else {\n extractFromPlainText(representation, context, push)\n }\n\n return facts\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Property aliases per fact, in precedence order. Written as paths so\n * `offers.price` reaches into an `Offer` and `offers.lowPrice` reaches into an\n * `AggregateOffer` — the shape Shopify actually emits.\n */\nconst JSON_LD_PATHS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['title', ['name', 'headline']],\n ['description', ['description', 'abstract']],\n ['price', ['offers.price', 'offers.lowPrice', 'offers.priceSpecification.price', 'price']],\n ['currency', ['offers.priceCurrency', 'offers.priceSpecification.priceCurrency', 'priceCurrency']],\n ['availability', ['offers.availability', 'availability']],\n ['brand', ['brand']],\n ['sku', ['sku', 'mpn', 'gtin13', 'gtin']],\n ['shipping', ['offers.shippingDetails', 'shippingDetails']],\n ['returns', ['offers.hasMerchantReturnPolicy', 'hasMerchantReturnPolicy']],\n ['org-name', ['name']],\n ['address', ['address']],\n ['hours', ['openingHours', 'openingHoursSpecification']],\n ['phone', ['telephone', 'contactPoint.telephone']],\n ['email', ['email', 'contactPoint.email']],\n ['service-area', ['areaServed', 'serviceArea']],\n ['author', ['author']],\n ['authority', ['publisher', 'author']],\n ['section', ['articleSection', 'genre']],\n ['published', ['datePublished', 'dateCreated']],\n ['updated', ['dateModified']],\n ['duration', ['duration', 'timeRequired']],\n ['eligibility', ['eligibleCustomerType', 'audience']],\n ['primary-action-url', ['potentialAction.target', 'potentialAction.url']],\n ['question-answer', ['mainEntity.acceptedAnswer']],\n ['item-count', ['numberOfItems']],\n ['item-link', ['itemListElement.url', 'itemListElement.item']],\n]\n\n/** Types whose `name` is an organisation name rather than a page title. */\nconst ORG_TYPES = new Set([\n 'Organization',\n 'LocalBusiness',\n 'Store',\n 'Restaurant',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'MedicalBusiness',\n 'ProfessionalService',\n 'FoodEstablishment',\n 'LodgingBusiness',\n 'AutomotiveBusiness',\n 'HealthAndBeautyBusiness',\n 'SportsActivityLocation',\n 'Place',\n])\n\nfunction extractFromJsonLd(\n node: JsonLdNode,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const isOrg = node.types.some((type) => ORG_TYPES.has(type))\n for (const [kind, paths] of JSON_LD_PATHS) {\n // `name` means two different things depending on the node's type; reading it\n // as both would let one string corroborate itself across two fact kinds.\n if (kind === 'title' && isOrg) continue\n if (kind === 'org-name' && !isOrg) continue\n\n for (const path of paths) {\n const raw = readPath(node, path)\n if (raw === null) continue\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized === null) continue\n push({ kind, normalized: normalized.value, source: 'json-ld', offset: node.offset, qualified: normalized.qualified })\n break\n }\n }\n}\n\ninterface NormalizedValue {\n value: string\n qualified: boolean\n}\n\n/** One normaliser, shared by every source, so the same fact from two places matches. */\nfunction normalizeFactValue(\n kind: ArsFactKind,\n raw: string,\n context: ExtractContext,\n): NormalizedValue | null {\n if (PRESENCE_FACTS.has(kind)) return { value: DECLARED, qualified: false }\n\n switch (kind) {\n case 'title':\n return raw.trim().length === 0 ? null : { value: normalizeTitle(raw), qualified: false }\n case 'price': {\n const lowered = raw.trim().toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n return { value: UNPRICED, qualified: false }\n }\n const money = parseMoneyText(raw, { currency: context.currencyHint })\n return money === null\n ? null\n : { value: normalizeMoney(money.amount, money.currency), qualified: money.qualified }\n }\n case 'currency': {\n const code = raw.trim().toUpperCase()\n return /^[A-Z]{3}$/.test(code) ? { value: code, qualified: false } : null\n }\n case 'availability': {\n const token = normalizeAvailability(raw)\n return token === null ? null : { value: token, qualified: false }\n }\n case 'phone': {\n const phone = normalizePhone(raw)\n return phone === null ? null : { value: phone, qualified: false }\n }\n case 'email': {\n const email = raw.trim().replace(/^mailto:/i, '').toLowerCase()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { value: email, qualified: false } : null\n }\n case 'published':\n case 'updated': {\n const date = normalizeDate(raw)\n return date === null ? null : { value: date, qualified: false }\n }\n case 'duration': {\n const minutes = normalizeDuration(raw)\n return minutes === null ? null : { value: minutes, qualified: false }\n }\n case 'item-count': {\n const count = Number.parseInt(raw.replace(/[^0-9]/g, ''), 10)\n return Number.isFinite(count) && count > 0 ? { value: String(count), qualified: false } : null\n }\n case 'primary-action-url': {\n const absolute = absoluteUrl(raw, context.baseUrl)\n return absolute === null ? null : { value: absolute, qualified: false }\n }\n default:\n return raw.trim().length === 0 ? null : { value: normalizeText(raw), qualified: false }\n }\n}\n\n/** ISO 8601 durations and the two visible forms, normalised to whole minutes. */\nexport function normalizeDuration(raw: string): string | null {\n // LINEAR, verified.\n // safe-regex flags `\\d+` nested inside a quantified group structurally. It is\n // not ambiguous here: every `\\d+` is followed by a REQUIRED distinct literal\n // (D, H, M), so each group matches exactly one way or none, and the outer\n // quantifiers are `?` (max one repetition), not `*`/`+`. Catastrophic\n // backtracking needs many ways to split the same input; there are none.\n // Measured: 200k chars in <1 ms, growth linear. Input is also capped at\n // MAX_NORMALIZED_TEXT (200) upstream.\n // eslint-disable-next-line security/detect-unsafe-regex\n const iso = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?)?$/.exec(raw.trim().toUpperCase())\n if (iso !== null && (iso[1] ?? iso[2] ?? iso[3]) !== undefined) {\n const minutes = Number(iso[1] ?? 0) * 1440 + Number(iso[2] ?? 0) * 60 + Number(iso[3] ?? 0)\n return minutes > 0 ? String(minutes) : null\n }\n const spoken = /^(\\d{1,4})\\s?(min|mins|minute|minutes|h|hr|hrs|hour|hours)\\b/i.exec(raw.trim())\n if (spoken !== null) {\n const amount = Number(spoken[1])\n const unit = (spoken[2] ?? '').toLowerCase()\n const minutes = unit.startsWith('h') ? amount * 60 : amount\n return minutes > 0 ? String(minutes) : null\n }\n return null\n}\n\n/** Resolves a possibly relative URL. Returns null rather than throwing on garbage. */\nexport function absoluteUrl(href: string, base: string): string | null {\n try {\n return new URL(href, base).toString()\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// HTML extraction\n// ---------------------------------------------------------------------------\n\n/** `<meta>` name/property → fact. Pinned; `og:` and the Twitter card are the whole set. */\nconst META_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['og:title', 'title'],\n ['twitter:title', 'title'],\n ['description', 'description'],\n ['og:description', 'description'],\n ['twitter:description', 'description'],\n ['og:price:amount', 'price'],\n ['product:price:amount', 'price'],\n ['og:price:currency', 'currency'],\n ['product:price:currency', 'currency'],\n ['og:availability', 'availability'],\n ['product:availability', 'availability'],\n ['product:brand', 'brand'],\n ['og:site_name', 'org-name'],\n ['author', 'author'],\n ['article:author', 'author'],\n ['article:published_time', 'published'],\n ['article:modified_time', 'updated'],\n ['article:section', 'section'],\n]\n\n/** `itemprop` → fact, for microdata. The same vocabulary as JSON-LD, one level flat. */\nconst ITEMPROP_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['name', 'title'],\n ['price', 'price'],\n ['pricecurrency', 'currency'],\n ['availability', 'availability'],\n ['brand', 'brand'],\n ['sku', 'sku'],\n ['description', 'description'],\n ['telephone', 'phone'],\n ['email', 'email'],\n ['address', 'address'],\n ['openinghours', 'hours'],\n ['author', 'author'],\n ['datepublished', 'published'],\n ['datemodified', 'updated'],\n ['articlesection', 'section'],\n]\n\nfunction extractFromHtml(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n // <title> and the first <h1>.\n for (const element of doc.elements) {\n if (element.tag !== 'title') continue\n const text = elementText(doc, element.index)\n const normalized = normalizeFactValue('title', text, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n for (const element of doc.elements) {\n if (element.tag !== 'h1' || element.excludedBy !== null) continue\n const normalized = normalizeFactValue('title', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n\n // <meta>.\n for (const meta of doc.metas) {\n if (meta.content === null) continue\n const key = meta.property ?? meta.name\n if (key === null) continue\n for (const [needle, kind] of META_LEXICON) {\n if (key !== needle) continue\n const normalized = normalizeFactValue(kind, meta.content, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'meta', offset: meta.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Microdata: itemprop, with content= preferred over text (schema.org's own advice).\n for (const element of doc.elements) {\n const itemprop = attr(element, 'itemprop')\n if (itemprop === null) continue\n const key = itemprop.toLowerCase()\n for (const [needle, kind] of ITEMPROP_LEXICON) {\n if (key !== needle) continue\n const raw =\n attr(element, 'content') ??\n attr(element, 'datetime') ??\n attr(element, 'href') ??\n elementText(doc, element.index)\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'microdata', offset: element.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Visible text: money, availability phrases, the no-published-price signal.\n extractVisibleText(doc, context, push)\n\n // Links and forms.\n extractLinks(doc, context, push)\n\n // Structural shapes: question/answer, opening hours, definition lists.\n extractStructures(doc, context, push)\n}\n\n/**\n * Facts read out of counted text. Every text node is visited individually so the\n * fact's offset is the offset of the node it was found in — a measured offset of\n * a heuristic fact, which is exactly how §3.9 describes `ArsFactObservation`.\n *\n * Hidden nodes (`hidden`, inline `display:none`, `<template>`) are skipped:\n * fixture `037-hidden-text-facts` asserts that facts stuffed into a hidden\n * element do not score.\n */\nfunction extractVisibleText(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n const text = node.text\n if (text.trim().length === 0) continue\n\n for (const money of findMoneyPhrases(text)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({\n kind: 'price',\n normalized: normalizeMoney(parsed.amount, parsed.currency),\n source: 'html-text',\n offset: node.offset,\n qualified: parsed.qualified,\n })\n push({\n kind: 'currency',\n normalized: parsed.currency,\n source: 'html-text',\n offset: node.offset,\n qualified: false,\n })\n }\n\n const lowered = text.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'html-text', offset: node.offset, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n if (!lowered.includes(phrase)) continue\n push({ kind: 'availability', normalized: token, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n for (const [kind, marker] of TEXT_PRESENCE_MARKERS) {\n if (!marker.some((phrase) => lowered.includes(phrase))) continue\n push({ kind, normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n }\n const sku = /\\bsku[:\\s]+([A-Za-z0-9][A-Za-z0-9._-]{2,31})\\b/i.exec(text)\n if (sku !== null && sku[1] !== undefined) {\n push({ kind: 'sku', normalized: normalizeText(sku[1]), source: 'html-text', offset: node.offset, qualified: false })\n }\n }\n\n // Labelled lines inside HTML (`<dt>Price</dt><dd>$148</dd>` collapses to\n // \"Price $148\" in counted text, so this reads the whole document's text once).\n for (const labelled of readLabelledLines(countedText(doc))) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({\n kind: labelled.kind,\n normalized: normalized.value,\n source: 'html-text',\n offset: firstTextOffset(doc),\n qualified: normalized.qualified,\n })\n }\n}\n\n/** Presence facts detectable from prose, with their pinned phrase lists. */\nconst TEXT_PRESENCE_MARKERS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['shipping', ['free shipping', 'shipping', 'ships in', 'delivery', 'ships free']],\n ['returns', ['return policy', 'returns', 'money-back', 'money back', 'refund']],\n ['service-area', ['areas served', 'service area', 'we serve', 'serving']],\n ['eligibility', ['eligibility', 'who can apply', 'you must be', 'requirements']],\n]\n\nfunction firstTextOffset(doc: HtmlDocument): number {\n for (const node of doc.texts) {\n if (node.excludedBy === null && node.text.trim().length > 0) return node.offset\n }\n return 0\n}\n\nconst ACTION_MAX_TEXT_CHARS = 64\n\nfunction extractLinks(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const lexicon = context.ruleset.actionLexicon\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href === null) continue\n if (href.toLowerCase().startsWith('tel:')) {\n const phone = normalizePhone(href.slice(4))\n if (phone !== null) {\n push({ kind: 'phone', normalized: phone, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n if (href.toLowerCase().startsWith('mailto:')) {\n const normalized = normalizeFactValue('email', href, context)\n if (normalized !== null) {\n push({ kind: 'email', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n continue\n }\n\n if (element.tag === 'form') {\n const action = attr(element, 'action')\n if (action === null) continue\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(action, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n\n const items = largestRepeatedLinkBlock(doc, context.origin)\n if (items.count > 0) {\n push({ kind: 'item-count', normalized: String(items.count), source: 'html-text', offset: items.offset, qualified: false })\n if (items.sameOrigin) {\n push({ kind: 'item-link', normalized: DECLARED, source: 'html-text', offset: items.offset, qualified: false })\n }\n }\n}\n\n/** Anchor text matches the action lexicon exactly, or begins with a lexicon phrase. */\nfunction matchesLexicon(text: string, lexicon: readonly string[]): boolean {\n const normalized = text.replace(/\\s+/g, ' ').trim().toLowerCase()\n if (normalized.length === 0) return false\n for (const phrase of lexicon) {\n if (normalized === phrase) return true\n if (normalized.startsWith(`${phrase} `)) return true\n }\n return false\n}\n\n/**\n * `item-count` / `item-link` for `collection` (§3.5): \"the number of distinct\n * item links inside the largest repeated-structure block, and whether those\n * links resolve to same-origin URLs.\"\n *\n * Made deterministic as: group every anchor by its GRANDPARENT element (the\n * container of the repeated item, e.g. `<ul>` for `<li><a>`), drop groups whose\n * container is inside `<nav>`, `<header>` or `<footer>`, and take the group with\n * the most distinct hrefs. The nav exclusion is the whole reason for the\n * \"largest repeated block\" phrasing — a site-wide menu is a repeated block of\n * links and is not a product grid.\n */\nfunction largestRepeatedLinkBlock(\n doc: HtmlDocument,\n origin: string,\n): { count: number; offset: number; sameOrigin: boolean } {\n const groups = new Map<number, { hrefs: Set<string>; sameOrigin: number; offset: number }>()\n for (const element of doc.elements) {\n if (element.tag !== 'a' || element.excludedBy !== null) continue\n const href = attr(element, 'href')\n if (href === null || href.startsWith('#')) continue\n const parent = element.parent >= 0 ? doc.elements[element.parent] : undefined\n const container = parent !== undefined && parent.parent >= 0 ? parent.parent : element.parent\n if (container < 0) continue\n if (isInsideChrome(doc, container)) continue\n\n const absolute = absoluteUrl(href, origin)\n if (absolute === null) continue\n const group = groups.get(container) ?? {\n hrefs: new Set<string>(),\n sameOrigin: 0,\n offset: doc.elements[container]?.offset ?? 0,\n }\n if (!group.hrefs.has(absolute)) {\n group.hrefs.add(absolute)\n if (absolute.startsWith(origin)) group.sameOrigin++\n }\n groups.set(container, group)\n }\n\n let best = { count: 0, offset: 0, sameOrigin: false }\n for (const [, group] of groups) {\n if (group.hrefs.size <= best.count) continue\n best = {\n count: group.hrefs.size,\n offset: group.offset,\n sameOrigin: group.sameOrigin * 2 >= group.hrefs.size,\n }\n }\n return best.count >= MIN_REPEATED_ITEMS ? best : { count: 0, offset: 0, sameOrigin: false }\n}\n\n/** Below this, a group of links is a paragraph with citations, not a listing. */\nconst MIN_REPEATED_ITEMS = 3\n\nconst CHROME_TAGS = new Set(['nav', 'header', 'footer'])\n\nfunction isInsideChrome(doc: HtmlDocument, from: number): boolean {\n let current = from\n for (let hops = 0; hops < 64 && current >= 0; hops++) {\n const element = doc.elements[current]\n if (element === undefined) return false\n if (CHROME_TAGS.has(element.tag)) return true\n if (element.attrs['role'] === 'navigation' || element.attrs['role'] === 'banner') return true\n current = element.parent\n }\n return false\n}\n\nconst DAY_NAMES = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n 'mon',\n 'tue',\n 'wed',\n 'thu',\n 'fri',\n 'sat',\n 'sun',\n]\n\n/**\n * Day-name / `HH:MM` adjacency, the §3.5 pass-1 signal, reused here as the\n * visible-text source for `hours`. \"Adjacent\" is: a day name and a clock time\n * within 40 characters of each other in the same text node.\n */\nexport function hasOpeningHoursShape(text: string): boolean {\n const lowered = text.toLowerCase()\n for (const day of DAY_NAMES) {\n let at = lowered.indexOf(day)\n while (at !== -1) {\n const window = lowered.slice(at, at + 40)\n if (/\\d{1,2}[:.]\\d{2}/.test(window) || /\\d{1,2}\\s?(am|pm)/.test(window)) return true\n at = lowered.indexOf(day, at + day.length)\n }\n }\n return false\n}\n\nfunction extractStructures(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (!hasOpeningHoursShape(node.text)) continue\n push({ kind: 'hours', normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'address') {\n const normalized = normalizeFactValue('address', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'address', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n }\n\n const qa = firstQuestionAnswer(doc)\n if (qa !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'html-text', offset: qa, qualified: false })\n }\n}\n\nconst HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n/**\n * The §3.5 `question-answer` shapes: a `<dt>`/`<dd>` pair, a\n * `<details><summary>`, or a heading ending in `?` followed by a paragraph.\n * Counted ONCE as present, not per item — a page with 40 questions is not four\n * times better than a page with 10, and the offset returned is the first shape's.\n */\nfunction firstQuestionAnswer(doc: HtmlDocument): number | null {\n let sawDt = false\n let pendingQuestionHeading = false\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'dt') {\n sawDt = true\n continue\n }\n if (element.tag === 'dd' && sawDt) return element.offset\n if (element.tag === 'details') {\n for (const child of doc.elements) {\n if (child.parent === element.index && child.tag === 'summary') return element.offset\n }\n continue\n }\n if (HEADING_TAGS.has(element.tag)) {\n pendingQuestionHeading = elementText(doc, element.index).trim().endsWith('?')\n continue\n }\n if (element.tag === 'p' && pendingQuestionHeading) return element.offset\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Plain-text / markdown extraction\n// ---------------------------------------------------------------------------\n\nconst MARKDOWN_LINK_RE = /\\[([^\\]\\n]{1,120})\\]\\(([^)\\s]{1,500})\\)/g\n\n/**\n * Extraction from a NEGOTIATED representation — markdown or plain text. Offsets\n * are UTF-8 byte offsets into the body, computed once per hit rather than by\n * scanning the whole body, so a 2 MiB markdown file does not become quadratic.\n *\n * The source is recorded as `negotiated` for everything found here, which is\n * what lets a fact stated in markdown corroborate the same fact in the HTML's\n * JSON-LD: two distinct sources, one value.\n */\nfunction extractFromPlainText(\n representation: ArsRepresentation,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const body = representation.body\n const offsetOf = (index: number): number => utf8Length(body.slice(0, index))\n\n // Title: the first ATX heading, with a wrapping markdown link unwrapped —\n // `render-md` emits `# [Alpine Trail Pack 28L](https://…)`.\n const heading = /^#{1,6}[ \\t]+(.+)$/m.exec(body)\n if (heading !== null && heading[1] !== undefined) {\n const linked = /^\\[([^\\]]+)\\]\\([^)]*\\)\\s*$/.exec(heading[1].trim())\n const raw = linked !== null && linked[1] !== undefined ? linked[1] : heading[1]\n const normalized = normalizeFactValue('title', raw, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'negotiated', offset: offsetOf(heading.index), qualified: false })\n }\n }\n\n for (const labelled of readLabelledLines(body)) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({ kind: labelled.kind, normalized: normalized.value, source: 'negotiated', offset: offsetOf(labelled.index), qualified: normalized.qualified })\n // A labelled price also states its currency.\n if (labelled.kind === 'price' && normalized.value !== UNPRICED) {\n const code = normalized.value.slice(0, 3)\n push({ kind: 'currency', normalized: code, source: 'negotiated', offset: offsetOf(labelled.index), qualified: false })\n }\n }\n\n for (const money of findMoneyPhrases(body)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({ kind: 'price', normalized: normalizeMoney(parsed.amount, parsed.currency), source: 'negotiated', offset: offsetOf(money.index), qualified: parsed.qualified })\n push({ kind: 'currency', normalized: parsed.currency, source: 'negotiated', offset: offsetOf(money.index), qualified: false })\n }\n\n const lowered = body.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'negotiated', offset: 0, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind: 'availability', normalized: token, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n for (const [kind, markers] of TEXT_PRESENCE_MARKERS) {\n for (const phrase of markers) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind, normalized: DECLARED, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n }\n if (hasOpeningHoursShape(body)) {\n push({ kind: 'hours', normalized: DECLARED, source: 'negotiated', offset: 0, qualified: false })\n }\n\n // Markdown links: the primary action, and the repeated-item block.\n const itemLinks = new Set<string>()\n let firstItemOffset = 0\n let match: RegExpExecArray | null\n MARKDOWN_LINK_RE.lastIndex = 0\n while ((match = MARKDOWN_LINK_RE.exec(body)) !== null) {\n const text = match[1] ?? ''\n const href = match[2] ?? ''\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n if (matchesLexicon(text, context.ruleset.actionLexicon)) {\n push({ kind: 'primary-action-url', normalized: absolute, source: 'negotiated', offset: offsetOf(match.index), qualified: false })\n }\n if (absolute.startsWith(context.origin) && !itemLinks.has(absolute)) {\n if (itemLinks.size === 0) firstItemOffset = offsetOf(match.index)\n itemLinks.add(absolute)\n }\n }\n if (itemLinks.size >= MIN_REPEATED_ITEMS) {\n push({ kind: 'item-count', normalized: String(itemLinks.size), source: 'negotiated', offset: firstItemOffset, qualified: false })\n push({ kind: 'item-link', normalized: DECLARED, source: 'negotiated', offset: firstItemOffset, qualified: false })\n }\n\n // A question/answer shape in markdown: a heading that ends in `?`.\n const question = /^#{1,6}[ \\t]+.*\\?[ \\t]*$/m.exec(body)\n if (question !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'negotiated', offset: offsetOf(question.index), qualified: false })\n }\n}\n\n// ---------------------------------------------------------------------------\n// robots.txt\n// ---------------------------------------------------------------------------\n\nexport interface RobotsGroup {\n /** Lowercased user-agent tokens this group applies to. */\n readonly agents: readonly string[]\n readonly allow: readonly string[]\n readonly disallow: readonly string[]\n}\n\nexport interface RobotsFile {\n readonly groups: readonly RobotsGroup[]\n readonly sitemaps: readonly string[]\n /** Lines that are neither blank, a comment, nor a `field: value` pair. */\n readonly malformedLines: number\n /** Directives that appeared before any `User-agent:` line — the classic authoring bug. */\n readonly orphanRules: number\n}\n\n/**\n * RFC 9309 robots.txt, in the subset ARS reads. Deliberately small: we consume\n * `User-agent`, `Allow`, `Disallow` and `Sitemap`, count what we could not\n * parse, and ignore everything else. `Crawl-delay` is honoured by the PROBE, not\n * by the score — waiting longer is not worse markup.\n */\nexport function parseRobots(text: string): RobotsFile {\n /** Mutable while parsing; the exported shape is the readonly one. */\n interface MutableGroup {\n agents: string[]\n allow: string[]\n disallow: string[]\n }\n\n const groups: MutableGroup[] = []\n const sitemaps: string[] = []\n let malformedLines = 0\n let orphanRules = 0\n\n let current: MutableGroup | null = null\n /**\n * True while consecutive `User-agent:` lines are still accumulating into one\n * group. RFC 9309 §2.2.1: adjacent user-agent lines share the rules that\n * follow them; the first rule line closes the group to further agents.\n */\n let openingGroup = false\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const withoutComment = rawLine.split('#')[0] ?? ''\n const line = withoutComment.trim()\n if (line.length === 0) continue\n const colon = line.indexOf(':')\n if (colon <= 0) {\n malformedLines++\n continue\n }\n const field = line.slice(0, colon).trim().toLowerCase()\n const value = line.slice(colon + 1).trim()\n\n if (field === 'user-agent') {\n if (current === null || !openingGroup) {\n current = { agents: [], allow: [], disallow: [] }\n groups.push(current)\n openingGroup = true\n }\n current.agents.push(value.toLowerCase())\n continue\n }\n if (field === 'sitemap') {\n sitemaps.push(value)\n continue\n }\n if (field === 'allow' || field === 'disallow') {\n if (current === null) {\n orphanRules++\n continue\n }\n openingGroup = false\n if (field === 'allow') current.allow.push(value)\n else current.disallow.push(value)\n continue\n }\n if (\n field === 'crawl-delay' ||\n field === 'host' ||\n field === 'clean-param' ||\n field === 'content-signal'\n ) {\n if (field === 'content-signal' && current !== null) openingGroup = false\n continue\n }\n malformedLines++\n }\n\n return { groups, sitemaps, malformedLines, orphanRules }\n}\n\n/**\n * RFC 9309 group selection: the most specific matching `User-agent` wins, `*` is\n * the fallback, and matching is case-insensitive. Returns the decision plus the\n * group and rule that produced it, because `ArsAudienceDecision` publishes both —\n * a merchant who disagrees with an `opt-out` verdict gets to see the line.\n */\nexport function decideRobots(\n robots: RobotsFile,\n tokens: readonly string[],\n path: string,\n): ArsAudienceDecision {\n let bestGroup: RobotsGroup | null = null\n let bestAgent: string | null = null\n let bestSpecificity = -1\n\n for (const group of robots.groups) {\n for (const agent of group.agents) {\n const specificity = agent === '*' ? 0 : matchesToken(agent, tokens) ? agent.length : -1\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity\n bestGroup = group\n bestAgent = agent\n }\n }\n }\n\n if (bestGroup === null || bestAgent === null) {\n return { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n }\n\n // Longest-match wins between Allow and Disallow; a tie goes to Allow (RFC 9309 §2.2.2).\n let bestRule: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of bestGroup.allow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'allow', value }\n }\n }\n for (const value of bestGroup.disallow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'disallow', value }\n }\n }\n\n if (bestRule === null) {\n return { decision: 'allow', matchedGroup: bestAgent, matchedRule: null }\n }\n return {\n decision: bestRule.field === 'allow' ? 'allow' : 'disallow',\n matchedGroup: bestAgent,\n matchedRule: `${bestRule.field === 'allow' ? 'Allow' : 'Disallow'}: ${bestRule.value}`,\n }\n}\n\nfunction matchesToken(agent: string, tokens: readonly string[]): boolean {\n const lowered = agent.toLowerCase()\n return tokens.some((token) => token.toLowerCase() === lowered)\n}\n\n/**\n * Path matching with `*` and `$`, done as a bounded scan rather than a compiled\n * regex: a robots.txt is attacker-controlled input and\n * `new RegExp(pathFromTheInternet)` is a denial-of-service primitive.\n */\nexport function pathMatches(pattern: string, path: string): boolean {\n if (pattern === '') return false\n const anchored = pattern.endsWith('$')\n const body = anchored ? pattern.slice(0, -1) : pattern\n const segments = body.split('*')\n\n let cursor = 0\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i] ?? ''\n if (i === 0) {\n if (!path.startsWith(segment)) return false\n cursor = segment.length\n continue\n }\n if (segment === '') continue\n const at = path.indexOf(segment, cursor)\n if (at === -1) return false\n cursor = at + segment.length\n }\n if (anchored) {\n const last = segments[segments.length - 1] ?? ''\n return segments.length === 1 ? path === body : path.endsWith(last)\n }\n return true\n}\n\n/** Every audience decision plus the derived policy flags. Pure over a parsed robots file. */\nexport function buildPolicyReport(\n robots: RobotsFile | null,\n status: ArsPolicyReport['robotsTxtStatus'],\n ruleset: ArsRuleset,\n path: string,\n): ArsPolicyReport {\n const empty: ArsAudienceDecision = { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n const audiences: Record<ArsAudience, ArsAudienceDecision> = {\n assistant: empty,\n training: empty,\n search: empty,\n }\n if (robots !== null) {\n for (const audience of ['assistant', 'training', 'search'] as const) {\n audiences[audience] = decideRobots(robots, ruleset.audienceTokens[audience], path)\n }\n }\n\n return {\n robotsTxtStatus: status,\n audiences,\n // A deliberate opt-out requires a group that NAMES an assistant token.\n // Consent has to be specific: a blanket `User-agent: *` disallow is the\n // accidental case (§3.7) and is scored, not excused.\n deliberateOptOut:\n robots !== null &&\n audiences.assistant.decision === 'disallow' &&\n audiences.assistant.matchedGroup !== '*' &&\n robots.malformedLines === 0 &&\n robots.orphanRules === 0,\n trainingOptOut: audiences.training.decision === 'disallow',\n sitemapDeclared: robots !== null && robots.sitemaps.length > 0,\n }\n}\n","/**\n * robots-policy.ts — the refusal token and the one function that decides\n * whether a site has refused us.\n *\n * WHY THIS IS ITS OWN MODULE RATHER THAN A PRIVATE FUNCTION IN `./probe`.\n *\n * There is now more than one probe. The Node probe fetches over the network; a\n * browser extension probes from inside a page the user is already looking at,\n * and cannot import `./probe` at all (that module carries a connection limiter\n * and DNS-level SSRF guards that have no meaning and no implementation in a\n * browser). Both must answer \"has this origin refused us?\" identically, because\n * a refusal honoured by one scanner and ignored by another is not a policy, it\n * is a coin flip — and the one being ignored is always the one a site operator\n * actually wrote down.\n *\n * So the decision lives here, at the bottom of the import graph, beside the\n * token it matches on. Pure, no clock, no network, safe under this package's\n * purity rule (`eslint.config.mjs`) and therefore usable from any runtime.\n */\nimport { parseRobots, pathMatches } from './extract'\n\n/**\n * The robots.txt token this scanner answers to. Matched case-insensitively.\n *\n * IT IS NOT VERSIONED, DELIBERATELY. A site that disallowed us under ARS 0.1 is\n * still refusing us under 0.2. Versioning the refusal token would let a spec\n * bump quietly re-open sites that already said no.\n */\nexport const ARS_ROBOTS_TOKEN = 'rebilder-ars'\n\n/**\n * Has this origin refused this path, by name? Returns the matching rule as a\n * human-readable string, or `null` when it has not.\n *\n * ONLY A GROUP THAT NAMES THE TOKEN COUNTS. A blanket `User-agent: *` disallow\n * is not a decision about us — it is the accidental case, which §3.7 scores with\n * a `robots-contradiction` flag rather than treating as consent or as refusal.\n * Reading a generic bot block as a refusal would also make the honest thing\n * (asking first) indistinguishable from the useless thing (refusing to look at\n * most of the web), and a scanner nobody can run is not a safer scanner.\n *\n * Rule selection uses `pathMatches`, the same matcher the scorer uses, so the\n * fetch gate and the published audience decision can never disagree about what\n * a pattern means. Longest match wins, `allow` beating `disallow` at equal\n * length by virtue of being tested first.\n */\nexport function robotsDisallowsScanner(robotsBody: string, path: string): string | null {\n const robots = parseRobots(robotsBody)\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent.toLowerCase() === ARS_ROBOTS_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${ARS_ROBOTS_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n","/**\n * The two request identities the standard is defined in terms of, in a leaf\n * module so a browser can import them without pulling in the Node probe.\n *\n * D2.4 IS THE REASON THESE ARE NORMATIVE. It compares what an origin serves an\n * agent against what it serves a browser, and the comparison is only meaningful\n * because the two requests differ in exactly one header. A probe that invents\n * its own `Accept` strings is measuring a different thing and reporting it under\n * the same name — which is worse than not measuring it, because the number still\n * looks like an ARS number.\n */\nexport const AGENT_ACCEPT = 'text/markdown;q=1.0, text/html;q=0.8, text/plain;q=0.5, */*;q=0.1'\nexport const BROWSER_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'\nexport const ASSET_ACCEPT = 'text/plain,*/*;q=0.5'\n","/**\n * score.ts — the ARS 0.3 scoring engine. The whole pure half comes together here.\n *\n * THE CONTRACT. `score(evidence, ruleset)` is a pure function: same evidence,\n * same ruleset, same `ArsResult`, byte for byte, in any conformant\n * implementation in any language. No network, no clock, no randomness, no LLM.\n * The ESLint rule in `eslint.config.mjs` enforces the first three at build time;\n * the fourth has nowhere to hide, because there is no model call anywhere in this\n * package.\n *\n * INTEGER ARITHMETIC ONLY (§3.6). Every number below is produced by `idiv` /\n * `divRoundHalfUp`, never by `/` on values that do not divide, and never by\n * `Math.round`. Cross-language conformance is impossible with float rounding\n * drift, and publishing a standard whose scores differ in the third\n * implementation would be worse than publishing nothing. All inputs are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator`.\n *\n * FIXED WEIGHTS. 100 points for every page, whatever its kind. What varies by\n * page kind is the fact set and the byte reference (`./profiles`) — never a\n * weight. Redistribution would be a gaming vector: make the dimension you are bad\n * at inapplicable and everything else inflates.\n *\n * TWO GATES EXIST, AND THEY POINT THE SAFE WAY. D2.3 (`Vary: Accept`) and D2.4\n * (substance parity) are gated on D2.1 (a machine representation was served),\n * which is a MEASURED check gating others. That direction is fine and is what\n * makes the published ceiling provable: no content negotiation loses D2.1 (9) +\n * D2.3 (3) + D2.4 (3) → max 85 → capped at B. The forbidden direction — a\n * heuristic that can zero measured points — appears nowhere. In particular D2.4\n * and D5.3 are SCORED CHECKS, NOT GATES: a parity failure loses its own 3 points\n * and raises a `warn`, and leaves D2's other 15 measured points alone. That is\n * the whole reason \"measured 63 / heuristic 37\" is an honest split rather than a\n * presentational one.\n *\n * EVIDENCE IS WRITTEN FOR THE SITE OWNER. Labels, values, remedies and flag\n * messages are printed on the public scan page, so they use plain words and name\n * a header or file only where a developer needs it to act. \"Content\n * negotiation\" in particular is written as what it means to a merchant: the\n * page sends AI assistants a Markdown copy when they ask for one. None of this\n * text is in the conformance projection, so rewording it is a PATCH.\n *\n * WHICH REPRESENTATION SCORES WHAT (the decision `./extract` states in its own\n * header, repeated here because it is the reason the golden pair means anything):\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. D1.3 (render independence) and D5\n * (structured data) score the representation that carries a document, because\n * those checks are about the HTML a caller that only reads HTML gets.\n *\n * MEASURED CHECKS NEVER AWARD POINTS FOR AN OBSERVATION WE DID NOT MAKE. When\n * the browser probe is missing, the sub-conditions that compare the two probes\n * (D1.1's \"no Accept-conditional redirect\", D6.1's \"self-consistent\") score 0 and\n * say so in their evidence. Awarding them by default would make a measured check\n * heuristic; deducting them silently would be unexplained. The evidence line is\n * the difference.\n *\n * WHAT LIVES IN THE RULESET AND WHAT LIVES HERE. `DEFAULT_RULESET.thresholds`\n * holds exactly the §3.6 numeric tables (density, context cost, offsets, front\n * window). The remaining checks are conjunctions of named conditions rather than\n * bands, and their point splits are `SUBPOINTS` below: published, frozen, and —\n * like the classification tables in `./classify` — NOT covered by `rulesetHash`,\n * because §3.9's `ArsRuleset` has no field for them. That gap is recorded in the\n * package README as a known limitation of 0.1 rather than papered over.\n */\n\nimport { classify, isRecognisedType, nodeForKind, pass1Signals } from './classify'\nimport type { ArsClassification } from './classify'\nimport {\n buildPolicyReport,\n buildRepresentation,\n extractFacts,\n hasPath,\n header,\n headerAll,\n mergeFacts,\n parseRobots,\n pathMatches,\n readPath,\n} from './extract'\nimport type {\n ArsRepresentation,\n ExtractedFact,\n JsonLdNode,\n MergedFact,\n RobotsFile,\n} from './extract'\nimport { attr, elementText } from './html'\nimport { profileFor } from './profiles'\nimport { recommend } from './recommend'\nimport { CHECK_META, DEFAULT_RULESET, DIMENSION_META } from './ruleset'\nimport type {\n ArsAudience,\n ArsBand,\n ArsBasis,\n ArsCheck,\n ArsCheckEvidence,\n ArsCheckId,\n ArsCostReport,\n ArsDimension,\n ArsDimensionId,\n ArsEvidence,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsFlag,\n ArsFlagId,\n ArsGrade,\n ArsHttpCapture,\n ArsOutcome,\n ArsPolicyReport,\n ArsProbeRecord,\n ArsResult,\n ArsRuleset,\n ArsUnscoredReason,\n} from './types'\nimport { ARS_SPEC_VERSION } from './types'\n\n// ---------------------------------------------------------------------------\n// Integer arithmetic (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * Exact integer division for non-negative safe integers. `%` is exact, the\n * subtraction is exact, and dividing by an exact multiple is exact, so this\n * never rounds — unlike `Math.floor(a / b)`, whose intermediate quotient is an\n * IEEE-754 double that can land on the wrong side of an integer boundary. A\n * scoring path that is \"almost always\" the same in two languages is not a\n * standard.\n */\nfunction idiv(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return (numerator - (numerator % denominator)) / denominator\n}\n\n/** §3.6's half-up rounding, `(numerator + denominator / 2) / denominator`, in integers. */\nfunction divRoundHalfUp(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return idiv(numerator + idiv(denominator, 2), denominator)\n}\n\n/**\n * AT-LEAST table lookup: flat `[threshold, value]` pairs in DESCENDING threshold\n * order; the first pair whose `threshold <= input` wins. No match scores 0, which\n * can only happen if a ruleset omits the table — a malformed ruleset must not\n * silently invent points.\n */\nfunction atLeast(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input >= threshold) return value\n }\n return 0\n}\n\n/**\n * AT-MOST table lookup: flat `[threshold, value]` pairs in ASCENDING threshold\n * order; the first pair whose `input <= threshold` wins; no match scores 0.\n */\nfunction atMost(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input <= threshold) return value\n }\n return 0\n}\n\n/** Recursively freezes a plain data structure. Used on `SUBPOINTS`. */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Sub-point splits\n// ---------------------------------------------------------------------------\n\n/**\n * The point split inside each check that scores a CONJUNCTION of named\n * conditions rather than a numeric band. §3.4 states the conditions (\"D1.1 2xx on\n * the agent path, ≤3 hops, no Accept-conditional redirect\"); this is how the\n * check's points are divided between them, and every split sums to the check's\n * weight in `DEFAULT_RULESET.weights`.\n *\n * Published here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has\n * no field for them. The consequence is stated rather than hidden: these numbers\n * are NOT covered by `rulesetHash`, exactly like the classification tables in\n * `./classify`. Editing one moves conformance `expected.json` files and is\n * therefore a MINOR, and the corpus is what actually pins them.\n */\n/**\n * The per-check point splits.\n *\n * THESE MUST SUM TO `WEIGHTS`, and until ARS 0.2 nothing said so. The ruleset\n * carried the same numbers twice, here and in `WEIGHTS`, with fixture `052`\n * checking only that `DIMENSION_META` agreed with `WEIGHTS`. Rebalancing for\n * 0.2 changed `WEIGHTS` alone and every check kept emitting 0.1's points, so\n * the corpus re-scored with dimensions claiming 28 while their checks could\n * only pay 20. `subpointTotals()` below closes that, and `score.test.ts`\n * asserts the two tables agree check by check.\n */\nexport const SUBPOINTS = deepFreeze({\n /** D1.1, 11 = 5 + 3 + 3. */\n reachable: { status2xx: 5, withinRedirectLimit: 3, noAcceptConditionalRedirect: 3 },\n /** D1.2, 10 = 6 + 2 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */\n robotsPolicy: { assistantAllowed: 6, parsesClean: 2, noOrphanRules: 1, sitemapDeclared: 1 },\n /**\n * D1.3, 7. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus\n * the `<noscript>` floor: a page whose facts are all client-rendered but which\n * ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8\n * says that earns partial credit.\n */\n renderIndependence: {\n band: [100, 7, 75, 5, 50, 3, 25, 1] as readonly number[],\n noscriptFloor: 1,\n },\n /**\n * D2.1, 9 for a machine copy served at the page's own address on `Accept`\n * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6\n * when the page does not negotiate but the Markdown copy it declares as an\n * alternate was fetched and is real. Less than full because only agents that\n * look for the link reach it, and they pay a second request to do so.\n */\n negotiatedResponse: { full: 9, linkedCopy: 6 },\n /** D2.2, 3. All-or-nothing. */\n declaredAlternates: { full: 3 },\n /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */\n varyAccept: { full: 3 },\n /** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */\n substanceParity: { full: 3 },\n /** D5.1, 2. Structured data present AND parsing; a partly-broken graph scores 1. */\n structuredDataPresent: { clean: 2, partial: 1 },\n /** D5.2, 3 = 1 (a recognised type) + 2 (required-property completeness, scaled). */\n requiredProperties: { recognisedType: 1, completeness: 2 },\n /** D5.3, 1. All-or-nothing. */\n textAgreement: { full: 1 },\n /** D6.1, 4 = 2 + 1 + 1. */\n canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },\n /** D6.2, 2 = 1 + 1. */\n cacheValidators: { saneCacheControl: 1, validator: 1 },\n /**\n * D6.3, 1. `specShaped` — an H1 and at least one Markdown link — is the whole\n * point. `present` is 0 in 0.2: at two points 0.1 could pay one for the file\n * existing and one for it being usable, but at one point that split would make\n * \"exists\" and \"usable\" score identically, which is a distinction the standard\n * would then be printing a remedy for and paying nothing to fix.\n */\n llmsTxt: { present: 0, specShaped: 1 },\n /** D6.4, 1. All-or-nothing. */\n sitemap: { full: 1 },\n /** D6.5, 2. All-or-nothing over any ONE declared machine endpoint. */\n machineEndpoint: { full: 2 },\n})\n\n/**\n * The maximum each SUBPOINTS entry can pay, for the agreement assertion. A band\n * pays its highest value; `structuredDataPresent` and `llmsTxt` are graded, so\n * the best branch is the max, not the sum.\n */\nexport function subpointTotals(): Record<string, number> {\n const s = SUBPOINTS\n return {\n 'retrievability.reachable':\n s.reachable.status2xx + s.reachable.withinRedirectLimit + s.reachable.noAcceptConditionalRedirect,\n 'retrievability.robots-policy':\n s.robotsPolicy.assistantAllowed +\n s.robotsPolicy.parsesClean +\n s.robotsPolicy.noOrphanRules +\n s.robotsPolicy.sitemapDeclared,\n 'retrievability.render-independence': s.renderIndependence.band[1] ?? 0,\n 'machine-representation.negotiated-response': s.negotiatedResponse.full,\n 'machine-representation.declared-alternates': s.declaredAlternates.full,\n 'machine-representation.vary-accept': s.varyAccept.full,\n 'machine-representation.substance-parity': s.substanceParity.full,\n 'structured-data.present': s.structuredDataPresent.clean,\n 'structured-data.required-properties':\n s.requiredProperties.recognisedType + s.requiredProperties.completeness,\n 'structured-data.text-agreement': s.textAgreement.full,\n 'contract-discovery.canonical':\n s.canonical.present + s.canonical.absolute + s.canonical.consistentAcrossProbes,\n 'contract-discovery.cache-validators': s.cacheValidators.saneCacheControl + s.cacheValidators.validator,\n 'contract-discovery.llms-txt': s.llmsTxt.specShaped,\n 'contract-discovery.sitemap': s.sitemap.full,\n 'contract-discovery.machine-endpoint': s.machineEndpoint.full,\n }\n}\n\n// ---------------------------------------------------------------------------\n// SHA-256 and RFC 8785 canonical JSON\n// ---------------------------------------------------------------------------\n\n/**\n * WHY A HAND-ROLLED SHA-256 LIVES IN THE PURE HALF. `ArsResult` carries three\n * hashes and the determinism guarantee is stated in terms of them, so `score()`\n * has to compute two of them. `node:crypto` would make this package Node-only,\n * and browser and edge callers import the root entry point; `crypto.subtle` is async\n * and `score()` is not. A dependency is out — the package's contract is zero\n * runtime dependencies, and a third-party hash version would be an unversioned\n * input to a hashed artifact, which is the same argument that made the tokenizer\n * hand-rolled. So: ~80 lines of FIPS 180-4, checked against the published test\n * vectors in `tests/score.test.ts`.\n */\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]\n\nfunction rotr(value: number, bits: number): number {\n return ((value >>> bits) | (value << (32 - bits))) >>> 0\n}\n\n/** SHA-256 of a UTF-8 string, lowercase hex. FIPS 180-4. */\nexport function sha256Hex(message: string): string {\n const bytes = new TextEncoder().encode(message)\n const bitLength = bytes.length * 8\n // Padded length: message + 0x80 + zeros + 8 length bytes, to a 64-byte multiple.\n const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64)\n padded.set(bytes)\n padded[bytes.length] = 0x80\n // Length as a 64-bit big-endian bit count. Bodies are capped at 2 MiB, so the\n // high word is always zero; it is written anyway so the routine is correct for\n // any input a caller hands it.\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 8, idiv(bitLength, 0x100000000), false)\n view.setUint32(padded.length - 4, bitLength >>> 0, false)\n\n const h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]\n const w = new Uint32Array(64)\n\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false)\n for (let i = 16; i < 64; i++) {\n const a = w[i - 15] ?? 0\n const b = w[i - 2] ?? 0\n const s0 = (rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3)) >>> 0\n const s1 = (rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10)) >>> 0\n w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0\n }\n\n let [a, b, c, d, e, f, g, hh] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ]\n for (let i = 0; i < 64; i++) {\n const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0\n const ch = ((e & f) ^ (~e & g)) >>> 0\n const temp1 = (hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0)) >>> 0\n const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0\n const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0\n const temp2 = (s0 + maj) >>> 0\n hh = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n const next = [a, b, c, d, e, f, g, hh]\n for (let i = 0; i < 8; i++) h[i] = ((h[i] ?? 0) + (next[i] ?? 0)) >>> 0\n }\n\n let hex = ''\n for (const word of h) hex += word.toString(16).padStart(8, '0')\n return hex\n}\n\n/**\n * RFC 8785 (JCS) canonical JSON, over the value shapes ARS actually hashes:\n * objects, arrays, strings, booleans, null and JSON numbers.\n *\n * Two details make this RFC-conformant rather than merely deterministic:\n * object keys are sorted by UTF-16 code unit (JCS §3.2.3, which is what\n * JavaScript's default string comparison already does), and numbers are\n * serialised with `JSON.stringify`, whose output is the ECMAScript\n * `Number::toString` shortest round-trip form that JCS §3.2.2.3 mandates.\n * `undefined` and functions cannot appear in the data we hash and are dropped.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null'\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined)\n keys.sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\n/** SHA-256 of the RFC 8785 canonical JSON of the frozen ruleset (§3.1). */\nexport function rulesetHash(ruleset: ArsRuleset): string {\n return sha256Hex(canonicalJson(ruleset))\n}\n\n/**\n * Headers excluded from `evidenceHash` (§3.3). Without this exclusion the hash\n * changes on every scan of every real site — `date` alone guarantees it — and the\n * replay story, which is the only reason the hash is published, dies.\n */\nconst VOLATILE_HEADERS: ReadonlySet<string> = new Set([\n 'date',\n 'age',\n 'set-cookie',\n 'x-request-id',\n 'cf-ray',\n 'report-to',\n])\n\nfunction stableHeaders(\n headers: Readonly<Record<string, readonly string[]>>,\n): Record<string, readonly string[]> {\n const out: Record<string, readonly string[]> = {}\n for (const [name, values] of Object.entries(headers)) {\n if (VOLATILE_HEADERS.has(name.toLowerCase())) continue\n out[name.toLowerCase()] = values\n }\n return out\n}\n\n/**\n * SHA-256 over the evidence bundle with the volatile fields removed: the header\n * denylist above, and `capturedAt`, which is wall-clock time and is never an\n * input to scoring. Bodies ARE hashed — `bodySha256` is already in the capture,\n * but hashing the body itself means a bundle whose body was edited without\n * updating its digest does not silently keep its identity.\n */\nexport function evidenceHash(evidence: ArsEvidence): string {\n const redactProbe = (probe: ArsProbeRecord | null): unknown => {\n if (probe === null) return null\n if (!probe.result.ok) return { requestHeaders: probe.requestHeaders, result: probe.result }\n const capture = probe.result.capture\n return {\n requestHeaders: probe.requestHeaders,\n result: {\n ok: true,\n capture: { ...capture, headers: stableHeaders(capture.headers) },\n },\n }\n }\n return sha256Hex(\n canonicalJson({\n evidenceVersion: evidence.evidenceVersion,\n target: evidence.target,\n vantage: evidence.vantage,\n probes: {\n agent: redactProbe(evidence.probes.agent),\n browser: redactProbe(evidence.probes.browser),\n parityConfirm: redactProbe(evidence.probes.parityConfirm),\n robotsTxt: redactProbe(evidence.probes.robotsTxt),\n llmsTxt: redactProbe(evidence.probes.llmsTxt),\n wellKnownUcp: redactProbe(evidence.probes.wellKnownUcp),\n // ARS 0.3, and only when present, so a 0.2 bundle hashes as it did.\n ...(evidence.probes.markdownAlternate === undefined\n ? {}\n : { markdownAlternate: redactProbe(evidence.probes.markdownAlternate) }),\n },\n }),\n )\n}\n\n/**\n * Version marker for the ARS 0.3 corpus (spec §2.4.3).\n * This is the hash of the versioned marker string, not of fixture contents.\n * A corpus-content digest replaces it at corpus freeze in a MINOR release.\n */\nexport const ARS_CORPUS_HASH = sha256Hex('ars-0.3-corpus-unfrozen')\n\n// ---------------------------------------------------------------------------\n// Header helpers\n// ---------------------------------------------------------------------------\n\n/** One entry of a `Link` header: the target IRI plus the parameters ARS reads. */\ninterface ParsedLink {\n readonly url: string\n readonly rel: readonly string[]\n readonly type: string | null\n}\n\n/**\n * Parses `Link` header values (RFC 8288) in the subset ARS scores: the target\n * IRI, `rel` as a token list, and `type`.\n *\n * Written as a scanner because the separator is a comma and target IRIs contain\n * commas — `<https://x/a,b>; rel=\"alternate\"` is one link, not two. Splitting on\n * `,` would silently drop half of the alternates a merchant declared and cost\n * them 4 points on D2.2.\n */\nexport function parseLinkHeaders(values: readonly string[]): ParsedLink[] {\n const out: ParsedLink[] = []\n for (const value of values) {\n for (const entry of splitLinkEntries(value)) {\n const open = entry.indexOf('<')\n const close = entry.indexOf('>', open + 1)\n if (open === -1 || close === -1) continue\n const url = entry.slice(open + 1, close).trim()\n if (url.length === 0) continue\n let rel: string[] = []\n let type: string | null = null\n for (const param of entry.slice(close + 1).split(';')) {\n const equals = param.indexOf('=')\n if (equals === -1) continue\n const name = param.slice(0, equals).trim().toLowerCase()\n const raw = param.slice(equals + 1).trim()\n const unquoted = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw\n if (name === 'rel')\n rel = unquoted\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n else if (name === 'type') type = unquoted.trim().toLowerCase()\n }\n out.push({ url, rel, type })\n }\n }\n return out\n}\n\n/** Splits on commas that are outside `<…>` and outside a quoted string. */\nfunction splitLinkEntries(value: string): string[] {\n const entries: string[] = []\n let depth = 0\n let quoted = false\n let start = 0\n for (let i = 0; i < value.length; i++) {\n const char = value.charAt(i)\n if (quoted) {\n if (char === '\"') quoted = false\n continue\n }\n if (char === '\"') quoted = true\n else if (char === '<') depth++\n else if (char === '>') depth = depth > 0 ? depth - 1 : 0\n else if (char === ',' && depth === 0) {\n entries.push(value.slice(start, i))\n start = i + 1\n }\n }\n entries.push(value.slice(start))\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0)\n}\n\n/** Comma/space-separated header token list, lowercased. */\nfunction headerTokens(value: string | null): string[] {\n if (value === null) return []\n return value\n .toLowerCase()\n .split(/[,\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Scoring context\n// ---------------------------------------------------------------------------\n\n/** Everything the 22 checks read, computed exactly once. */\n/** The Markdown copy a page links to, as the probe found it (ARS 0.3). */\ninterface LinkedCopy {\n /** The declared URL the probe should have fetched. */\n readonly url: string\n /** `checked`: fetched and real. `broken`: fetched and not Markdown. `unchecked`: not in the bundle. */\n readonly status: 'checked' | 'broken' | 'unchecked'\n readonly representation: ArsRepresentation | null\n /** Why a broken copy failed, in plain words. */\n readonly reason: string | null\n}\n\ninterface ScoreContext {\n readonly evidence: ArsEvidence\n readonly ruleset: ArsRuleset\n readonly agentCapture: ArsHttpCapture\n readonly browserCapture: ArsHttpCapture | null\n readonly agent: ArsRepresentation\n readonly browser: ArsRepresentation | null\n /** The representation that carries a tokenized document, if either does. */\n readonly structural: ArsRepresentation | null\n readonly classification: ArsClassification\n readonly profile: ArsFactProfile\n readonly facts: readonly MergedFact[]\n readonly agentFacts: readonly ExtractedFact[]\n readonly browserFacts: readonly ExtractedFact[]\n readonly structuralFacts: readonly ExtractedFact[]\n readonly policy: ArsPolicyReport\n readonly robots: RobotsFile | null\n readonly flags: ArsFlag[]\n /** True when the agent probe itself received a machine copy (negotiation). */\n readonly negotiated: boolean\n /** The declared Markdown copy, when the page links to one and does not negotiate. */\n readonly linkedCopy: LinkedCopy | null\n}\n\ninterface CheckOutcome {\n readonly earned: number\n readonly evidence: ArsCheckEvidence[]\n readonly remedy?: string\n}\n\nconst YES = 'yes'\nconst NO = 'no'\nconst yesNo = (value: boolean): string => (value ? YES : NO)\n\nfunction measured(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'measured' }\n}\n\nfunction heuristic(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'heuristic' }\n}\n\n/**\n * Plain names for fact kinds, for evidence and remedies a site owner reads. The\n * kind ids stay the published vocabulary; this is only how they are printed.\n */\nconst FACT_NAMES: Readonly<Record<ArsFactKind, string>> = {\n title: 'name or title',\n description: 'description',\n updated: 'last-updated date',\n published: 'publish date',\n price: 'price',\n currency: 'currency',\n availability: 'availability',\n brand: 'brand',\n sku: 'SKU',\n shipping: 'shipping details',\n returns: 'returns policy',\n 'org-name': 'business name',\n address: 'address',\n hours: 'opening hours',\n phone: 'phone number',\n email: 'email address',\n 'service-area': 'service area',\n author: 'author',\n section: 'section',\n authority: 'publisher',\n 'primary-action-url': 'main action link (such as Buy, Book, Contact or Install)',\n eligibility: 'eligibility',\n duration: 'duration',\n 'question-answer': 'questions and answers',\n 'item-count': 'number of items',\n 'item-link': 'links to the items',\n}\n\nfunction factName(kind: ArsFactKind): string {\n return FACT_NAMES[kind] ?? kind\n}\n\nfunction factList(kinds: readonly ArsFactKind[]): string {\n return kinds.map(factName).join(', ')\n}\n\n/**\n * Bytes as a reader says them. Integer arithmetic only, so the string is the\n * same in every implementation: under 1 KB prints bytes, above it prints whole\n * kilobytes (1 KB = 1024 bytes), rounded half-up.\n */\nfunction plainBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} bytes`\n return `${divRoundHalfUp(bytes, 1024)} KB`\n}\n\n/** Plain words for a robots.txt status. */\nconst ROBOTS_STATUS: Readonly<Record<ArsPolicyReport['robotsTxtStatus'], string>> = {\n ok: 'found',\n missing: 'not found (nothing is blocked)',\n error: 'the server returned an error',\n unparseable: 'found, but it could not be read',\n}\n\n/** The gated D2 checks' evidence while no Markdown copy is served. */\nconst COUNTS_ONCE_COPY = 'only once the page sends AI assistants a Markdown copy, so 0 for now'\n\n// ---------------------------------------------------------------------------\n// D1 — Retrievability\n// ---------------------------------------------------------------------------\n\nfunction checkReachable(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, ruleset } = context\n const split = SUBPOINTS.reachable\n const status2xx = agentCapture.status >= 200 && agentCapture.status < 300\n const hops = agentCapture.redirects.length\n const withinLimit = hops <= ruleset.maxRedirects\n const sameFinalUrl = browserCapture !== null && browserCapture.finalUrl === agentCapture.finalUrl\n\n const earned =\n (status2xx ? split.status2xx : 0) +\n (withinLimit ? split.withinRedirectLimit : 0) +\n (sameFinalUrl ? split.noAcceptConditionalRedirect : 0)\n\n const evidence = [\n measured('Status code AI assistants got', String(agentCapture.status)),\n measured('Redirects on the way', `${hops} (up to ${ruleset.maxRedirects} allowed)`),\n measured(\n 'Same address for AI assistants and browsers',\n browserCapture === null\n ? 'not checked, because this scan has no browser request to compare'\n : yesNo(sameFinalUrl),\n ),\n ]\n return sameFinalUrl\n ? { earned, evidence }\n : {\n earned,\n evidence,\n remedy:\n 'Send AI assistants and browsers to the same address. A redirect that depends on the Accept header sends assistants to a page browsers never see.',\n }\n}\n\nfunction checkRobotsPolicy(context: ScoreContext): CheckOutcome {\n const { policy, robots } = context\n const split = SUBPOINTS.robotsPolicy\n const decision = policy.audiences.assistant\n const parsesClean = robots === null || robots.malformedLines === 0\n const noOrphanRules = robots === null || robots.orphanRules === 0\n\n const rule =\n decision.matchedGroup === null\n ? ''\n : ` (User-agent: ${decision.matchedGroup}${\n decision.matchedRule === null ? '' : `, ${decision.matchedRule}`\n })`\n const evidence = [\n measured('robots.txt', ROBOTS_STATUS[policy.robotsTxtStatus]),\n measured(\n 'AI assistants allowed',\n decision.decision === 'disallow'\n ? `no${rule}`\n : decision.matchedGroup === null\n ? 'yes, no rule mentions them'\n : `yes${rule}`,\n ),\n measured('Lines that could not be read', robots === null ? 'none' : String(robots.malformedLines)),\n measured(\n 'Rules outside a User-agent group',\n robots === null ? 'none' : String(robots.orphanRules),\n ),\n measured('Sitemap listed', yesNo(policy.sitemapDeclared)),\n measured(\n 'AI training crawlers',\n policy.trainingOptOut ? 'blocked, which does not affect this score' : 'allowed',\n ),\n ]\n\n // §3.7: an accidental or ambiguous assistant disallow — a blanket group, a\n // malformed file — is SCORED, with D1.2 at zero and a `robots-contradiction`\n // warning. It is not an opt-out, because consent has to be specific.\n if (decision.decision === 'disallow') {\n context.flags.push({\n id: 'robots-contradiction',\n severity: 'warn',\n basis: 'measured',\n message:\n 'Your robots.txt blocks AI assistants with a rule written for all crawlers. That looks accidental, and it keeps assistants out.',\n evidence: [evidence[1] ?? measured('AI assistants allowed', 'no')],\n })\n return {\n earned: 0,\n evidence,\n remedy:\n 'Your robots.txt blocks AI assistants with a rule meant for all crawlers. If you want assistants to read your pages, give them their own group that allows them, such as ChatGPT-User and Claude-User.',\n }\n }\n\n const earned =\n split.assistantAllowed +\n (parsesClean ? split.parsesClean : 0) +\n (noOrphanRules ? split.noOrphanRules : 0) +\n (policy.sitemapDeclared ? split.sitemapDeclared : 0)\n\n return {\n earned,\n evidence,\n remedy: policy.sitemapDeclared\n ? undefined\n : 'Add a `Sitemap:` line to robots.txt so assistants can find the rest of your pages.',\n }\n}\n\nfunction checkRenderIndependence(context: ScoreContext): CheckOutcome {\n const { structural, structuralFacts, profile } = context\n const split = SUBPOINTS.renderIndependence\n const coreSize = profile.core.length\n\n if (structural === null || structural.doc === null) {\n return {\n earned: 0,\n evidence: [heuristic('HTML page', 'not checked, because no HTML was returned')],\n }\n }\n\n const found = new Set<ArsFactKind>()\n for (const fact of structuralFacts) if (profile.core.includes(fact.kind)) found.add(fact.kind)\n const ratio = coreSize === 0 ? 0 : idiv(100 * found.size, coreSize)\n\n let noscriptText = ''\n for (const element of structural.doc.elements) {\n if (element.tag !== 'noscript') continue\n noscriptText = elementText(structural.doc, element.index).trim()\n if (noscriptText.length > 0) break\n }\n const hasNoscript = noscriptText.length > 0\n\n const banded = atLeast(split.band, ratio)\n const earned = Math.max(banded, hasNoscript ? split.noscriptFloor : 0)\n const full = atLeast(split.band, 100)\n\n if (ratio < 50) {\n context.flags.push({\n id: 'render-dependent',\n severity: 'info',\n basis: 'heuristic',\n message: `${found.size} of ${coreSize} key facts for this kind of page were in the HTML before any JavaScript ran. An assistant that does not run scripts sees the rest as missing.`,\n evidence: [heuristic('Key facts in the HTML', `${found.size} of ${coreSize}`)],\n })\n }\n\n return {\n earned,\n evidence: [\n heuristic('Key facts in the HTML before JavaScript runs', `${found.size} of ${coreSize}`),\n heuristic('Fallback text for visitors without JavaScript', yesNo(hasNoscript)),\n heuristic(\n 'How we checked',\n 'we read the HTML your server sends and do not run JavaScript, so facts added by scripts count as missing',\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Put the key facts in the HTML your server sends. Most AI assistants do not run JavaScript, so facts added by scripts are invisible to them.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D2 — Machine representation\n// ---------------------------------------------------------------------------\n\n/** Media types that count as a machine representation for D2.1 (§3.4). */\nconst MACHINE_KINDS: ReadonlySet<ArsRepresentation['kind']> = new Set(['markdown', 'text', 'json'])\n\n/** Whether a capture is a machine copy: a machine media type and a body that is not HTML. */\nexport function isMachineCopy(capture: ArsHttpCapture): boolean {\n const representation = buildRepresentation(capture)\n return (\n representation !== null &&\n MACHINE_KINDS.has(representation.kind) &&\n !representation.looksLikeHtml\n )\n}\n\nconst MARKDOWN_MEDIA: ReadonlySet<string> = new Set(['text/markdown', 'text/x-markdown'])\n\nfunction isMarkdownType(type: string | null): boolean {\n return type !== null && MARKDOWN_MEDIA.has((type.split(';')[0] ?? '').trim().toLowerCase())\n}\n\n/**\n * The Markdown copies a page declares as alternates, as absolute URLs without a\n * fragment, deduplicated, in a fixed order: `Link` headers on each capture, then\n * `<link rel=\"alternate\" type=\"text/markdown\">` in each capture's HTML.\n */\nexport function declaredMarkdownAlternates(captures: readonly (ArsHttpCapture | null)[]): string[] {\n const out: string[] = []\n const add = (raw: string, base: string): void => {\n try {\n const url = new URL(raw, base)\n url.hash = ''\n const href = url.toString()\n if (!out.includes(href)) out.push(href)\n } catch {\n // An unparseable href declares nothing.\n }\n }\n for (const capture of captures) {\n if (capture === null) continue\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('alternate') && isMarkdownType(link.type)) add(link.url, capture.finalUrl)\n }\n }\n for (const capture of captures) {\n if (capture === null) continue\n const representation = buildRepresentation(capture)\n if (representation === null || representation.doc === null) continue\n for (const link of representation.doc.links) {\n if (!link.rel.includes('alternate') || link.href === null) continue\n if (isMarkdownType(link.type)) add(link.href, capture.finalUrl)\n }\n }\n return out\n}\n\n/**\n * THE ONE MARKDOWN ALTERNATE ARS FETCHES (§3.3, ARS 0.3), shared by the probe and\n * the scorer so the two cannot disagree about which URL was meant. The first\n * declared Markdown copy that is on the target's origin and is not the page's\n * own address; null when the agent probe already received a machine copy, when\n * it did not get a 2xx, or when nothing qualifies. One extra request at most.\n */\nexport function markdownAlternateTarget(\n agent: ArsHttpCapture | null,\n browser: ArsHttpCapture | null,\n origin: string,\n): string | null {\n if (agent === null || agent.status < 200 || agent.status >= 300) return null\n if (isMachineCopy(agent)) return null\n const own = new Set([agent.finalUrl, agent.requestedUrl])\n for (const href of declaredMarkdownAlternates([browser, agent])) {\n let sameOrigin = false\n try {\n sameOrigin = new URL(href).origin === origin\n } catch {\n sameOrigin = false\n }\n if (sameOrigin && !own.has(href)) return href\n }\n return null\n}\n\n/** What the bundle says about the linked Markdown copy, checked against the declaration. */\nfunction linkedCopyOf(\n evidence: ArsEvidence,\n agent: ArsHttpCapture,\n browser: ArsHttpCapture | null,\n): LinkedCopy | null {\n const url = markdownAlternateTarget(agent, browser, evidence.target.origin)\n if (url === null) return null\n const record = evidence.probes.markdownAlternate ?? null\n if (record === null) return { url, status: 'unchecked', representation: null, reason: null }\n if (!record.result.ok) {\n // A refusal is not an observation. robots.txt telling rebilder-ars to stay\n // off the file, or our own safety policy, means we never saw it, and a\n // measured check never deducts for what we did not see.\n if (record.result.error === 'policy-rejected') {\n return { url, status: 'unchecked', representation: null, reason: null }\n }\n return { url, status: 'broken', representation: null, reason: record.result.error }\n }\n const capture = record.result.capture\n // A record for some other URL is not evidence about this declaration.\n if (capture.requestedUrl !== url) {\n return { url, status: 'unchecked', representation: null, reason: null }\n }\n if (capture.status < 200 || capture.status >= 300) {\n return { url, status: 'broken', representation: null, reason: `HTTP ${capture.status}` }\n }\n if (!isMachineCopy(capture)) {\n return { url, status: 'broken', representation: null, reason: 'it returned HTML, not Markdown' }\n }\n return { url, status: 'checked', representation: buildRepresentation(capture), reason: null }\n}\n\n/** Plain names for the media types the probe asks for, in the order it asks. */\nconst MEDIA_NAMES: Readonly<Record<string, string>> = {\n 'text/markdown': 'Markdown',\n 'text/x-markdown': 'Markdown',\n 'text/html': 'HTML',\n 'text/plain': 'plain text',\n 'application/json': 'JSON',\n '*/*': 'anything else',\n}\n\n/** `text/markdown;q=1.0, text/html;q=0.8` → `Markdown first, then HTML`. */\nfunction acceptSummary(accept: string): string {\n const names: string[] = []\n for (const entry of accept.split(',')) {\n const type = (entry.split(';')[0] ?? '').trim().toLowerCase()\n if (type === '') continue\n const name = MEDIA_NAMES[type] ?? type\n if (!names.includes(name)) names.push(name)\n }\n const [first, ...rest] = names\n if (first === undefined) return accept\n return rest.length === 0 ? first : `${first} first, then ${rest.join(', ')}`\n}\n\nfunction checkNegotiatedResponse(context: ScoreContext): CheckOutcome {\n const { agent, linkedCopy } = context\n const typeIsMachine = MACHINE_KINDS.has(agent.kind)\n const bodyIsHtml = agent.looksLikeHtml\n const linkedWorks = linkedCopy !== null && linkedCopy.status === 'checked'\n const earned = context.negotiated\n ? SUBPOINTS.negotiatedResponse.full\n : linkedWorks\n ? SUBPOINTS.negotiatedResponse.linkedCopy\n : 0\n\n const asked =\n context.evidence.probes.agent.requestHeaders['accept'] ??\n context.evidence.probes.agent.requestHeaders['Accept'] ??\n null\n return {\n earned,\n evidence: [\n measured('We asked for', asked === null ? 'not recorded' : acceptSummary(asked)),\n measured('Format we got', agent.contentType ?? 'not stated'),\n measured('Content was HTML', yesNo(bodyIsHtml)),\n ...(linkedCopy === null ? [] : [measured('Linked Markdown copy', linkedCopyLine(linkedCopy))]),\n ],\n remedy: context.negotiated\n ? undefined\n : linkedWorks\n ? 'Your linked Markdown copy works. For full credit, also send it from the page address when an AI assistant asks for Markdown, so assistants get it without a second request.'\n : typeIsMachine\n ? 'Your server labels this response as Markdown, text or JSON but sends HTML. Send the format the Content-Type header names.'\n : 'When an AI assistant asks for Markdown, answer from the same address with a Markdown copy of the page and `Content-Type: text/markdown`. Assistants get your facts without the menus, scripts and styling, which are usually most of the page.',\n }\n}\n\nfunction linkedCopyLine(copy: LinkedCopy): string {\n if (copy.status === 'checked') {\n return `loaded as Markdown from ${copy.url} (${plainBytes(copy.representation?.bytes ?? 0)})`\n }\n if (copy.status === 'broken') return `did not load as Markdown from ${copy.url} (${copy.reason ?? 'error'})`\n return `linked at ${copy.url}, not checked in this scan`\n}\n\nfunction checkDeclaredAlternates(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, structural } = context\n const links = parseLinkHeaders([\n ...headerAll(agentCapture.headers, 'link'),\n ...(browserCapture === null ? [] : headerAll(browserCapture.headers, 'link')),\n ])\n // An alternate with no `type` is a language variant (`hreflang`), not a second\n // representation. Every international site declares those, and paying 4 points\n // for them would make the check meaningless.\n const headerAlternates = links.filter(\n (link) => link.rel.includes('alternate') && link.type !== null,\n )\n\n const documentAlternates: string[] = []\n if (structural !== null && structural.doc !== null) {\n for (const link of structural.doc.links) {\n if (!link.rel.includes('alternate')) continue\n if (link.type === null || link.href === null) continue\n documentAlternates.push(`${link.type} at ${link.href}`)\n }\n }\n\n const total = headerAlternates.length + documentAlternates.length\n const broken = context.linkedCopy !== null && context.linkedCopy.status === 'broken'\n if (broken && context.linkedCopy !== null) {\n return {\n earned: 0,\n evidence: [measured('Linked Markdown copy', linkedCopyLine(context.linkedCopy))],\n remedy: `The Markdown copy this page links to did not load (${context.linkedCopy.reason ?? 'error'}). Fix the file or the link.`,\n }\n }\n return {\n earned: total > 0 ? SUBPOINTS.declaredAlternates.full : 0,\n evidence: [\n measured(\n 'Link header pointing to the Markdown copy',\n headerAlternates.length === 0\n ? 'none'\n : headerAlternates.map((link) => `${link.type ?? '?'} at ${link.url}`).join(', '),\n ),\n measured(\n 'Link tag in the page pointing to the Markdown copy',\n documentAlternates.length === 0 ? 'none' : documentAlternates.join(', '),\n ),\n ],\n remedy:\n total > 0\n ? undefined\n : 'Tell assistants where the Markdown copy is. Add `<link rel=\"alternate\" type=\"text/markdown\" href=\"…\">` to the page, or send the same thing as a `Link` header.',\n }\n}\n\nfunction checkVaryAccept(context: ScoreContext): CheckOutcome {\n const negotiated = context.negotiated\n const { agentCapture, browserCapture } = context\n const agentVary = headerTokens(header(agentCapture.headers, 'vary'))\n const browserVary =\n browserCapture === null ? [] : headerTokens(header(browserCapture.headers, 'vary'))\n const declared = agentVary.includes('accept') || browserVary.includes('accept')\n\n const evidence = [\n measured('Vary header sent to AI assistants', header(agentCapture.headers, 'vary') ?? 'not sent'),\n measured(\n 'Vary header sent to browsers',\n browserCapture === null\n ? 'not checked'\n : (header(browserCapture.headers, 'vary') ?? 'not sent'),\n ),\n ]\n\n // Gated on D2.1: `Vary: Accept` on a response that does not vary by Accept is\n // a claim about caching that is not true. Fixture 035 pins it.\n if (!negotiated) {\n return {\n earned: 0,\n evidence: [\n ...evidence,\n measured(\n 'Counts',\n context.linkedCopy?.status === 'checked'\n ? 'only when the page address itself sends the Markdown copy, so 0 for now'\n : COUNTS_ONCE_COPY,\n ),\n ],\n }\n }\n\n if (!declared) {\n context.flags.push({\n id: 'vary-missing',\n severity: 'warn',\n basis: 'measured',\n message:\n 'This address sends the Markdown copy or the HTML depending on what is asked for, but does not send `Vary: Accept`. A shared cache can hand the Markdown to a shopper, or the HTML to an assistant.',\n evidence,\n })\n }\n\n return {\n earned: declared ? SUBPOINTS.varyAccept.full : 0,\n evidence,\n remedy: declared\n ? undefined\n : 'Send `Vary: Accept` on every response from an address that serves a Markdown copy, so caches keep the two versions apart.',\n }\n}\n\n/**\n * The kinds D2.4 compares. Explicitly four, and never description or free text\n * (§3.8): a prose difference between a Markdown summary and an HTML page is a\n * rendering difference, and calling it a substance divergence would be an\n * accusation we cannot support.\n */\nconst PARITY_KINDS: readonly ArsFactKind[] = ['price', 'currency', 'availability', 'title']\n\n/**\n * Two readings of one side's facts: the value it would PUBLISH for each kind\n * (the unqualified observation with the lowest byte offset, ties broken\n * lexicographically — the same choice `mergeFacts` makes for the published fact\n * set), and EVERY unqualified value it stated.\n *\n * Qualified values — ranges, \"from $9\" — never enter either map (§3.11).\n */\ninterface FactView {\n readonly representative: Map<ArsFactKind, string>\n readonly observed: Map<ArsFactKind, Set<string>>\n}\n\n/** The facts in a linked Markdown copy, read with the page's own profile and currency. */\nfunction linkedCopyFacts(context: ScoreContext, copy: LinkedCopy): readonly ExtractedFact[] {\n if (copy.representation === null) return []\n return extractFacts(copy.representation, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: copy.representation.finalUrl,\n origin: context.evidence.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n}\n\nfunction factView(facts: readonly ExtractedFact[]): FactView {\n const best = new Map<ArsFactKind, ExtractedFact>()\n const observed = new Map<ArsFactKind, Set<string>>()\n for (const fact of facts) {\n if (fact.qualified) continue\n const seen = observed.get(fact.kind)\n if (seen === undefined) observed.set(fact.kind, new Set([fact.normalized]))\n else seen.add(fact.normalized)\n\n const current = best.get(fact.kind)\n if (current === undefined) {\n best.set(fact.kind, fact)\n continue\n }\n if (fact.offset < current.offset) best.set(fact.kind, fact)\n else if (fact.offset === current.offset && fact.normalized < current.normalized)\n best.set(fact.kind, fact)\n }\n const representative = new Map<ArsFactKind, string>()\n for (const [kind, fact] of best) representative.set(kind, fact.normalized)\n return { representative, observed }\n}\n\n/**\n * The comparison rule for D2.4 and D5.3, and it is ASYMMETRIC on purpose:\n * **the value the left side would publish must appear somewhere among the values\n * the right side stated.**\n *\n * Both symmetric rules are wrong, and each is wrong in a way that matters:\n *\n * - Requiring the two REPRESENTATIVES to be equal produces false accusations on\n * ordinary pages. The demo product page in fixtures 001/002 names a backordered\n * variant above the line that says the product is in stock; its JSON-LD says\n * `InStock`, and both statements are true. Flagging that as a\n * structured-data divergence would be an accusation the evidence does not\n * support, and ARS reports observations rather than charges (§3.8).\n * - Accepting ANY shared value lets a real divergence hide behind an incidental\n * match: \"Free shipping over $50\" appears in both representations, so a page\n * whose headline price differs would still certify clean.\n *\n * The asymmetric rule catches the second and not the first, which is the\n * conservative direction: a missed divergence costs a merchant nothing, and a\n * false one is published on a scanner page next to their name.\n */\nfunction divergentKinds(\n left: FactView,\n right: FactView,\n kinds: readonly ArsFactKind[],\n): { compared: ArsFactKind[]; divergent: { kind: ArsFactKind; left: string; right: string }[] } {\n const compared: ArsFactKind[] = []\n const divergent: { kind: ArsFactKind; left: string; right: string }[] = []\n for (const kind of kinds) {\n const claim = left.representative.get(kind)\n const stated = right.observed.get(kind)\n if (claim === undefined || stated === undefined || stated.size === 0) continue\n compared.push(kind)\n if (!stated.has(claim)) {\n divergent.push({ kind, left: claim, right: [...stated].sort().join(' | ') })\n }\n }\n return { compared, divergent }\n}\n\nfunction checkSubstanceParity(context: ScoreContext): CheckOutcome {\n const { agentFacts, browserFacts, browser, evidence: bundle } = context\n // ARS 0.3: a linked Markdown copy that loaded is compared the same way as a\n // negotiated one. It has no confirming probe, so a difference costs the\n // points and raises no flag, the conservative branch below.\n const linked =\n !context.negotiated && context.linkedCopy?.status === 'checked' ? context.linkedCopy : null\n const htmlFacts = browser !== null ? browserFacts : agentFacts\n\n if ((!context.negotiated && linked === null) || (linked === null && browser === null)) {\n return {\n earned: 0,\n evidence: [\n heuristic(\n 'Counts',\n !context.negotiated\n ? COUNTS_ONCE_COPY\n : 'not checked, because this scan has no browser request to compare',\n ),\n ],\n }\n }\n\n const agentValues = factView(linked === null ? agentFacts : linkedCopyFacts(context, linked))\n const browserValues = factView(linked === null ? browserFacts : htmlFacts)\n const { compared, divergent } = divergentKinds(agentValues, browserValues, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Facts compared',\n compared.length === 0\n ? 'none appear in both the Markdown copy and the page'\n : factList(compared),\n ),\n ...(compared.length === 0\n ? []\n : [\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'match'\n : divergent\n .map(\n (entry) =>\n `${factName(entry.kind)}: Markdown copy ${entry.left}, page ${entry.right}`,\n )\n .join('; '),\n ),\n ]),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'State the same key facts, such as name and price, in the Markdown copy and in the page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length === 0)\n return { earned: SUBPOINTS.substanceParity.full, evidence: evidenceLines }\n\n // §3.8: divergence must REPRODUCE on a third confirming probe taken ≥30s later\n // before the flag is set. Inventory and price genuinely change between two\n // sequential requests, and a one-shot difference is not evidence of anything.\n // A linked copy never has one, so it always takes the unflagged branch.\n const confirm = linked === null ? bundle.probes.parityConfirm : null\n const confirmCapture = confirm !== null && confirm.result.ok ? confirm.result.capture : null\n const confirmRep = confirmCapture === null ? null : buildRepresentation(confirmCapture)\n if (confirmRep === null) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic('Second look', 'not taken, so this difference was seen once and is not flagged'),\n ],\n remedy:\n 'The Markdown copy and the page showed different values for a key fact. That can happen when a price or stock level changes between requests. If it repeats, build both from the same source.',\n }\n }\n\n const confirmFacts = extractFacts(confirmRep, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: confirmRep.finalUrl,\n origin: bundle.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n const confirmValues = factView(confirmFacts)\n const reproduced = divergentKinds(\n confirmValues,\n browserValues,\n divergent.map((entry) => entry.kind),\n )\n\n if (reproduced.divergent.length === 0) {\n return {\n earned: SUBPOINTS.substanceParity.full,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Second look',\n 'the difference was gone, so we treat it as a value that changed between requests',\n ),\n ],\n }\n }\n\n context.flags.push({\n id: 'substance-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: reproduced.divergent\n .map(\n (entry) =>\n `The Markdown copy showed ${factName(entry.kind)} ${entry.left}; the HTML page showed ${entry.right}. We saw the same difference on two requests taken apart.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Second look', 'the difference was still there')],\n remedy:\n 'Show the same values in the Markdown copy and the page, ideally by building both from one source. We report what each version said and do not judge which is right.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D3 — Fact coverage\n// ---------------------------------------------------------------------------\n\ninterface CoverageMath {\n readonly coreFound: number\n readonly extendedFound: number\n readonly coveragePct: number\n readonly densityPct: number\n readonly factsPerKiB100: number\n}\n\n/** §3.6's fact weighting, verbatim, in quarter-units. */\nfunction coverageMath(context: ScoreContext): CoverageMath {\n const { facts, profile, ruleset, agent } = context\n const units = ruleset.thresholds['fact-coverage.fact-units'] ?? []\n const coreCorroboratedUnit = units[0] ?? 0\n const coreUnit = units[1] ?? 0\n const extendedCorroboratedUnit = units[2] ?? 0\n const extendedUnit = units[3] ?? 0\n const denominatorMultiplier =\n ruleset.thresholds['fact-coverage.core-denominator-multiplier']?.[0] ?? 0\n\n let coreUnits = 0\n let extendedUnits = 0\n let coreFound = 0\n let extendedFound = 0\n for (const fact of facts) {\n if (profile.core.includes(fact.kind)) {\n coreFound++\n coreUnits += fact.corroborated ? coreCorroboratedUnit : coreUnit\n } else if (profile.extended.includes(fact.kind)) {\n extendedFound++\n extendedUnits += fact.corroborated ? extendedCorroboratedUnit : extendedUnit\n }\n }\n\n const denominator = denominatorMultiplier * profile.core.length\n const coveragePct =\n denominator === 0\n ? 0\n : Math.min(100, divRoundHalfUp(100 * (coreUnits + extendedUnits), denominator))\n\n // The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n // which let a 200-byte stub top the density band.\n const factsPerKiB100 = idiv(\n (coreFound * 100 + extendedFound * 25) * 1024,\n Math.max(1, agent.bytes),\n )\n const densityPct = atLeast(ruleset.thresholds['fact-coverage.density'], factsPerKiB100)\n\n return { coreFound, extendedFound, coveragePct, densityPct, factsPerKiB100 }\n}\n\nfunction checkCoreFacts(context: ScoreContext, math: CoverageMath): CheckOutcome {\n const weight = weightOf(context.ruleset, 'fact-coverage.core-facts')\n const earned = idiv(weight * math.coveragePct * math.densityPct + 5000, 10000)\n const missing = context.profile.core.filter(\n (kind) => !context.facts.some((fact) => fact.kind === kind),\n )\n\n return {\n earned,\n evidence: [\n heuristic('Key facts for this kind of page', factList(context.profile.core)),\n heuristic('Found', `${math.coreFound} of ${context.profile.core.length}`),\n heuristic('Missing', missing.length === 0 ? 'none' : factList(missing)),\n heuristic(\n 'Extra facts found',\n `${math.extendedFound} of ${context.profile.extended.length}`,\n ),\n heuristic(\n 'Credit for the facts',\n `${math.coveragePct}% (a fact stated in both the text and structured data counts in full)`,\n ),\n heuristic(\n 'Credit kept for length',\n `${math.densityPct}% (${math.coreFound + math.extendedFound} facts in ${plainBytes(context.agent.bytes)}; the more text around each fact, the less is kept)`,\n ),\n ],\n remedy:\n missing.length > 0\n ? `Add the ${factList(missing)} to what AI assistants receive. An assistant can only repeat what the page states.${\n missing.includes('primary-action-url')\n ? ' For the main action link, use a label that starts with a common action word, such as Buy, Book, Order, Contact, Sign up, Get started or Request a quote.'\n : ''\n }`\n : earned === weight\n ? undefined\n : math.coveragePct < 100\n ? 'Repeat the key facts in both the visible text and the structured data. A fact stated once gets half credit.'\n : 'Your key facts are all there, but there is a lot of page around them, so this keeps only part of its credit. A Markdown copy for AI assistants that leads with the facts is the simplest fix; trimming the page also helps.',\n }\n}\n\nfunction checkContextCost(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['fact-coverage.context-cost']\n const reference = context.profile.byteReference\n const ratio = reference === 0 ? 0 : idiv(100 * context.agent.bytes, reference)\n const earned = atMost(table, ratio)\n const full = atMost(table, 0)\n\n return {\n earned,\n evidence: [\n measured(\n 'Size AI assistants had to read',\n `${plainBytes(context.agent.bytes)}${context.agent.truncated ? ' or more (cut off at the limit)' : ''}`,\n ),\n measured(\n `Typical size for a ${context.profile.pageKind === 'unknown' ? 'general' : context.profile.pageKind} page`,\n plainBytes(reference),\n ),\n measured(\n 'Compared with typical',\n ratio <= 100 ? 'at or under typical' : `about ${divRoundHalfUp(ratio, 100)} times typical`,\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Send AI assistants a Markdown copy, which carries the facts without the page code, or make the page lighter. Scripts, inline styles and repeated menus are usually most of the size.',\n }\n}\n\n\n// ---------------------------------------------------------------------------\n// D7 — Evidence density\n// ---------------------------------------------------------------------------\n\n/**\n * WHY THIS DIMENSION EXISTS (ARS 0.2). The controlled work on what an assistant\n * actually lifts into an answer, rather than what it merely cites, finds the\n * effect concentrated in extractable evidence units: quantities, definitions\n * and comparisons carry large influence uplift, while conversational Q&A\n * phrasing carries none. D1-D6 grade whether an agent can REACH and PARSE a\n * page. Nothing before this graded whether, having parsed it, there was\n * anything quotable on it.\n *\n * ALL THREE ARE COUNTS OVER THE AGENT'S OWN COUNTED TEXT. No model, no\n * randomness, no clock. `quantities` and `comparisons` are `measured` because\n * they observe the artifact directly, a token shape and a markup structure;\n * `definitions` is `heuristic` because calling a `label: value` line a\n * definition is a judgement about intent, and the basis field says so.\n */\n\n/** Currency amount, percentage, number carrying a unit, or an ISO date. */\nconst QUANTITY = new RegExp(\n [\n String.raw`[$£€¥]\\s?\\d[\\d,]*(?:\\.\\d+)?`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?%`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?(?:kg|g|lb|lbs|oz|mm|cm|m|km|mi|in|ft|ml|l|kb|mb|gb|tb|hz|w|kw|v|°c|°f|hours?|hrs?|minutes?|mins?|seconds?|secs?|days?|weeks?|months?|years?)\\b`,\n String.raw`\\d{4}-\\d{2}-\\d{2}`,\n ].join('|'),\n 'giu',\n)\n\n/** `**Label:** value`, `- Label: value`, and `<dt>` rows once tokenized to text. */\nconst DEFINITION_LINE = /^\\s*(?:[-*+]\\s+)?(?:\\*\\*)?[A-Za-z][A-Za-z0-9 /&'()-]{1,40}(?:\\*\\*)?\\s*:\\s*\\S/\n\n/**\n * Block elements that hold ONE labelled fact when a page states them in markup\n * rather than in Markdown. Pinned, like every other table in this standard.\n *\n * WHY THIS SET EXISTS AT ALL. `countedText` joins every text node with a single\n * space and collapses whitespace runs, so an HTML document's counted text is one\n * line — deliberately, because a line model would need a display model and there\n * is no CSS resolution anywhere in this package. Splitting D7.2 on `\\n` would\n * therefore score EVERY HTML page at zero and pay only representations that\n * arrive already line-structured, which in practice means pages behind a\n * Markdown gateway. A check that only the editors' own product can satisfy is\n * exactly the self-serving design this standard must not contain, so D7.2\n * segments an HTML document structurally instead: each counted text node is\n * attributed to its nearest ancestor in this set, and each such element's own\n * text is one candidate line. Innermost wins by construction, so a `<p>` inside\n * an `<li>` is counted once and not twice.\n */\nconst LABELLED_BLOCK_TAGS = new Set(['li', 'dt', 'dd', 'p', 'td', 'th', 'div'])\n\nfunction checkQuantities(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.quantities']\n // DISTINCT, normalized on case and inner whitespace: a price stated in a\n // header, a buy box and a footer is one fact said three times, and paying\n // for the repetition would reward exactly the padding this score exists to\n // discourage.\n const seen = new Set<string>()\n for (const match of context.agent.text.matchAll(QUANTITY)) {\n seen.add(match[0].toLowerCase().replace(/\\s+/g, ''))\n }\n const count = seen.size\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [\n measured('Different numbers an answer could quote', `${count} (prices, sizes, percentages, dates)`),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Write the numbers people ask about in the page text: prices, sizes, hours, fees and dates. Assistants quote numbers they can read.',\n }\n}\n\n/**\n * The candidate lines of a representation: one per labelled block element when\n * there is a document, and the text's own lines when there is not. Order is\n * document order in both cases, so two runs over one bundle agree.\n */\nfunction labelledSegments(context: ScoreContext): string[] {\n const doc = context.agent.doc\n if (doc === null) return context.agent.text.split('\\n')\n\n // One pass over counted text nodes, each attributed to its nearest ancestor\n // in LABELLED_BLOCK_TAGS. `Map` preserves insertion order, which is the order\n // the first text node of each element appeared.\n const byElement = new Map<number, string[]>()\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (node.text.trim().length === 0) continue\n let at = node.parent\n // Bounded by the tokenizer's own depth limit; a cycle cannot hang this.\n for (let hops = 0; at >= 0 && hops <= MAX_ANCESTOR_HOPS; hops += 1) {\n const element = doc.elements[at]\n if (element === undefined) break\n if (LABELLED_BLOCK_TAGS.has(element.tag)) {\n const parts = byElement.get(at)\n if (parts === undefined) byElement.set(at, [node.text])\n else parts.push(node.text)\n break\n }\n at = element.parent\n }\n }\n\n const segments: string[] = []\n for (const parts of byElement.values()) {\n segments.push(parts.join(' ').replace(/\\s+/g, ' ').trim())\n }\n return segments\n}\n\n/** Deep enough for any real document; the tokenizer caps nesting well below it. */\nconst MAX_ANCESTOR_HOPS = 256\n\nfunction checkDefinitions(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.definitions']\n let count = 0\n for (const line of labelledSegments(context)) {\n if (DEFINITION_LINE.test(line)) count += 1\n }\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [heuristic('Labelled facts, like \"Returns: 60 days\"', `${count}`)],\n remedy:\n earned === full\n ? undefined\n : 'Label your facts. A line like \"Returns: 60 days\" can be quoted as it is. The same fact inside a paragraph has to be worked out.',\n }\n}\n\n/**\n * Comparable ROWS, not tables. A table with one data row states a fact; two or\n * more let an assistant contrast options, which is the shape the absorption\n * work found doing the work. Counted from the tokenized document so it is a\n * structural observation, and from the markdown pipe form when there is no\n * document, so a markdown-only representation is not silently scored zero.\n */\nfunction checkComparisons(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.comparisons']\n let rows = 0\n\n const doc = context.agent.doc\n if (doc !== null) {\n // Cells per row, by walking children back to their parent `tr`. The\n // tokenizer records `parent` as an index into `elements`, so this is one\n // pass and no tree is built.\n const cellsByRow = new Map<number, number>()\n for (const element of doc.elements) {\n if (element.tag !== 'td' && element.tag !== 'th') continue\n const row = doc.elements[element.parent]\n if (row === undefined || row.tag !== 'tr') continue\n cellsByRow.set(element.parent, (cellsByRow.get(element.parent) ?? 0) + 1)\n }\n for (const cells of cellsByRow.values()) if (cells >= 2) rows += 1\n // A header row is not a comparison.\n rows = Math.max(0, rows - 1)\n } else {\n let pipeRows = 0\n for (const line of context.agent.text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) continue\n if (/^\\|[\\s:|-]+\\|$/.test(trimmed)) continue // the alignment rule\n if (trimmed.split('|').length - 2 >= 2) pipeRows += 1\n }\n rows = Math.max(0, pipeRows - 1)\n }\n\n const earned = atLeast(table, rows)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [measured('Table rows that compare options', `${rows}`)],\n remedy:\n earned === full\n ? undefined\n : 'Put options side by side in a table, one row each. Assistants answering \"which one?\" use rows they can line up.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D4 — Fact position\n// ---------------------------------------------------------------------------\n\nfunction coreOffsets(context: ScoreContext): number[] {\n const offsets: number[] = []\n for (const fact of context.facts)\n if (context.profile.core.includes(fact.kind)) offsets.push(fact.offset)\n return offsets.sort((a, b) => a - b)\n}\n\nfunction checkFirstCoreFactOffset(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const first = offsets[0]\n if (first === undefined) {\n return {\n earned: 0,\n evidence: [heuristic('First key fact', 'none found, so there is nothing to place')],\n }\n }\n const firstKind = context.facts.find((fact) => fact.offset === first)?.kind\n return {\n earned: atMost(context.ruleset.thresholds['fact-position.first-core-fact-offset'], first),\n evidence: [\n measured('First key fact appears', first === 0 ? 'at the very start' : `after ${plainBytes(first)}`),\n heuristic('Which fact', firstKind === undefined ? 'unknown' : factName(firstKind)),\n ],\n remedy:\n first <= 512\n ? undefined\n : 'Put the key facts near the top of what AI assistants receive. Assistants often read only the start.',\n }\n}\n\nfunction checkFrontWindow(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const windowRule = context.ruleset.thresholds['fact-position.front-window-size'] ?? []\n const floor = windowRule[0] ?? 0\n const divisor = windowRule[1] ?? 1\n const size = Math.max(floor, idiv(context.agent.bytes, divisor))\n\n if (offsets.length === 0) {\n return {\n earned: 0,\n evidence: [\n measured('Opening section', `the first ${plainBytes(size)}`),\n heuristic('Key facts in it', 'none found, so there is nothing to place'),\n ],\n }\n }\n\n const inside = offsets.filter((offset) => offset < size).length\n // The denominator is the core facts that are PRESENT, not the profile size:\n // absence is D3.1's job, and charging the same absence twice would make the\n // 100 points non-orthogonal. The evidence prints both numbers so a reader can\n // see which question was asked.\n const pct = idiv(100 * inside, offsets.length)\n\n return {\n earned: atLeast(context.ruleset.thresholds['fact-position.front-window'], pct),\n evidence: [\n measured(\n 'Opening section',\n `the first ${plainBytes(size)} (a ${divisor === 5 ? 'fifth' : `1/${divisor}`} of the page, at least ${plainBytes(floor)})`,\n ),\n heuristic('Key facts in it', `${inside} of the ${offsets.length} found (${pct}%)`),\n ],\n remedy:\n pct >= 90\n ? undefined\n : 'Move the key facts into the first part of the page. Facts further down cost an assistant a full read.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D5 — Structured data\n// ---------------------------------------------------------------------------\n\nfunction checkStructuredDataPresent(context: ScoreContext): CheckOutcome {\n const { structural } = context\n const split = SUBPOINTS.structuredDataPresent\n if (structural === null) {\n return {\n earned: 0,\n evidence: [measured('HTML page', 'not checked, because no HTML was returned')],\n }\n }\n\n const { blocks, parsed } = structural.jsonLd\n let microdata = 0\n let rdfa = 0\n if (structural.doc !== null) {\n for (const element of structural.doc.elements) {\n if (attr(element, 'itemtype') !== null) microdata++\n if (attr(element, 'typeof') !== null) rdfa++\n }\n }\n\n const jsonLdScore =\n blocks === 0 ? null : parsed === blocks ? split.clean : parsed > 0 ? split.partial : 0\n const otherScore = microdata > 0 || rdfa > 0 ? split.clean : null\n const earned = Math.max(jsonLdScore ?? 0, otherScore ?? 0)\n\n return {\n earned,\n evidence: [\n measured('JSON-LD blocks that could be read', `${parsed} of ${blocks}`),\n measured('Microdata items', String(microdata)),\n measured('RDFa items', String(rdfa)),\n ],\n remedy:\n earned === split.clean\n ? undefined\n : blocks > parsed\n ? 'At least one JSON-LD block has a syntax error, so it cannot be read. Check it with a JSON validator.'\n : 'Add a JSON-LD block describing this page, such as a schema.org Product with its price. Search engines and some AI assistants read it.',\n }\n}\n\n/**\n * The JSON-LD node D5.2 scores against: the node whose `@type` decided the page\n * kind, then any node with a recognised type. Scoring the first node in the\n * document would mark a page incomplete because its `BreadcrumbList` has no\n * `offers.price` (§ `nodeForKind` in ./classify).\n */\nfunction scoredNode(context: ScoreContext): JsonLdNode | null {\n const nodes = context.structural?.jsonLd.nodes ?? []\n const forKind = nodeForKind(nodes, context.profile.pageKind)\n if (forKind !== null) return forKind\n for (const node of nodes) if (node.types.some(isRecognisedType)) return node\n return null\n}\n\nfunction checkRequiredProperties(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.requiredProperties\n const required = context.ruleset.requiredProperties[context.profile.pageKind] ?? []\n const node = scoredNode(context)\n\n if (node === null) {\n return {\n earned: 0,\n evidence: [\n measured('Schema.org type', 'none found'),\n measured('Properties we look for', required.join(', ') || 'none'),\n measured('Where we look', 'JSON-LD. Microdata counts toward the check above, not this one.'),\n ],\n remedy:\n 'Give the JSON-LD a schema.org type that matches the page, such as Product, LocalBusiness or Article, with the properties listed.',\n }\n }\n\n const satisfied = required.filter((path) => hasPath(node, path))\n const missing = required.filter((path) => !hasPath(node, path))\n const completeness =\n required.length === 0\n ? split.completeness\n : divRoundHalfUp(split.completeness * satisfied.length, required.length)\n\n return {\n earned: split.recognisedType + completeness,\n evidence: [\n measured('Schema.org type', node.types.join(', ')),\n measured('Properties present', `${satisfied.length} of ${required.length}`),\n measured('Missing', missing.length === 0 ? 'none' : missing.join(', ')),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `Add ${missing.join(', ')} to the ${node.types[0] ?? 'main'} item in your JSON-LD.`,\n }\n}\n\nfunction checkTextAgreement(context: ScoreContext): CheckOutcome {\n const { structuralFacts } = context\n const fromJsonLd = factView(structuralFacts.filter((fact) => fact.source === 'json-ld'))\n const fromPage = factView(structuralFacts.filter((fact) => fact.source !== 'json-ld'))\n const { compared, divergent } = divergentKinds(fromJsonLd, fromPage, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Facts compared',\n compared.length === 0\n ? 'none appear in both the structured data and the page text'\n : factList(compared),\n ),\n ...(compared.length === 0\n ? []\n : [\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'match'\n : divergent\n .map(\n (entry) =>\n `${factName(entry.kind)}: structured data ${entry.left}, page ${entry.right}`,\n )\n .join('; '),\n ),\n ]),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'State the key facts, such as name and price, in both the structured data and the visible page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length > 0) {\n context.flags.push({\n id: 'structured-data-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: divergent\n .map(\n (entry) =>\n `The structured data says ${factName(entry.kind)} ${entry.left}; the visible page says ${entry.right}.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'Build the structured data from the same source as the visible page, so the two cannot disagree.',\n }\n }\n\n return { earned: SUBPOINTS.textAgreement.full, evidence: evidenceLines }\n}\n\n// ---------------------------------------------------------------------------\n// D6 — Contract & discovery\n// ---------------------------------------------------------------------------\n\nfunction canonicalOf(\n capture: ArsHttpCapture | null,\n representation: ArsRepresentation | null,\n): string | null {\n if (capture !== null) {\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('canonical')) return link.url\n }\n }\n if (representation !== null && representation.doc !== null) {\n for (const link of representation.doc.links) {\n if (link.rel.includes('canonical') && link.href !== null) return link.href\n }\n }\n return null\n}\n\nfunction checkCanonical(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.canonical\n const htmlCanonical =\n canonicalOf(context.browserCapture, context.browser) ??\n canonicalOf(context.agentCapture, context.agent)\n const agentCanonical = canonicalOf(context.agentCapture, context.agent)\n\n const present = htmlCanonical !== null\n const absolute = htmlCanonical !== null && /^https?:\\/\\//i.test(htmlCanonical)\n const consistent =\n htmlCanonical !== null && agentCanonical !== null && agentCanonical === htmlCanonical\n\n if (htmlCanonical !== null && agentCanonical !== null && agentCanonical !== htmlCanonical) {\n context.flags.push({\n id: 'canonical-mismatch',\n severity: 'warn',\n basis: 'measured',\n message: `The Markdown copy and the HTML page name different main addresses: ${agentCanonical} and ${htmlCanonical}.`,\n evidence: [\n measured('Main address given to AI assistants', agentCanonical),\n measured('Main address in the HTML', htmlCanonical),\n ],\n })\n }\n\n return {\n earned:\n (present ? split.present : 0) +\n (absolute ? split.absolute : 0) +\n (consistent ? split.consistentAcrossProbes : 0),\n evidence: [\n measured('Canonical address in the HTML', htmlCanonical ?? 'none'),\n measured('Canonical address AI assistants got', agentCanonical ?? 'none'),\n measured('Full address with https://', yesNo(absolute)),\n measured('Same for AI assistants and browsers', yesNo(consistent)),\n ],\n remedy:\n consistent && absolute\n ? undefined\n : htmlCanonical === null\n ? 'Add `<link rel=\"canonical\" href=\"https://…\">` with the full address of the page, so assistants know which address to cite.'\n : agentCanonical === null\n ? 'Your Markdown copy has no canonical address. Send `Link: <https://…>; rel=\"canonical\"` with it, pointing at the page.'\n : !consistent\n ? 'Use one canonical address, written in full, for the page and its Markdown copy.'\n : 'Write the canonical address in full, starting with https://.',\n }\n}\n\nfunction checkCacheValidators(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.cacheValidators\n const cacheControl = header(context.agentCapture.headers, 'cache-control')\n const directives = headerTokens(cacheControl)\n const noStore = directives.includes('no-store')\n const maxAge = directives.some((token) => {\n const match = /^(?:max-age|s-maxage)=(\\d{1,10})$/.exec(token)\n return match !== null && Number(match[1]) > 0\n })\n const noCache = directives.includes('no-cache') || directives.includes('must-revalidate')\n const etag = header(context.agentCapture.headers, 'etag')\n const lastModified = header(context.agentCapture.headers, 'last-modified')\n const validator = etag !== null || lastModified !== null\n\n // \"Sane\" is: the response says how long it may be reused, or says to\n // revalidate — and revalidation only means anything with a validator.\n const sane = cacheControl !== null && !noStore && (maxAge || (noCache && validator))\n\n return {\n earned: (sane ? split.saneCacheControl : 0) + (validator ? split.validator : 0),\n evidence: [\n measured('Cache-Control header', cacheControl ?? 'not sent'),\n measured('ETag header', etag ?? 'not sent'),\n measured('Last-Modified header', lastModified ?? 'not sent'),\n ],\n remedy:\n sane && validator\n ? undefined\n : 'Send a `Cache-Control` header with a lifetime, plus an `ETag` or `Last-Modified` header, so repeat visits can skip unchanged pages.',\n }\n}\n\nfunction bodyOf(probe: ArsProbeRecord | null): string | null {\n if (probe === null || !probe.result.ok) return null\n const capture = probe.result.capture\n if (capture.status < 200 || capture.status >= 300) return null\n return typeof capture.body === 'string' ? capture.body : null\n}\n\nconst MARKDOWN_LINK = /\\[[^\\]\\n]{1,200}\\]\\(([^)\\s]{1,500})\\)/g\n\nfunction checkLlmsTxt(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.llmsTxt\n const body = bodyOf(context.evidence.probes.llmsTxt)\n if (body === null || body.trim().length === 0) {\n return {\n earned: 0,\n evidence: [measured('/llms.txt', body === null ? 'not found' : 'empty')],\n remedy:\n 'Publish /llms.txt with a `#` title, a short summary and links to your main pages.',\n }\n }\n // The llms.txt convention: an H1 title, then Markdown links. Both halves are\n // checked because a file with a title and no links tells an agent nothing.\n const hasTitle = /^#\\s+\\S/m.test(body)\n MARKDOWN_LINK.lastIndex = 0\n const hasLinks = MARKDOWN_LINK.test(body)\n const specShaped = hasTitle && hasLinks\n\n return {\n earned: specShaped ? split.specShaped : split.present,\n evidence: [\n measured('/llms.txt', `found, ${body.length} characters`),\n measured('Has a # title', yesNo(hasTitle)),\n measured('Has links', yesNo(hasLinks)),\n ],\n remedy: specShaped\n ? undefined\n : 'Start /llms.txt with a `#` title and add at least one link written as `[name](url)`.',\n }\n}\n\nfunction checkSitemap(context: ScoreContext): CheckOutcome {\n return {\n earned: context.policy.sitemapDeclared ? SUBPOINTS.sitemap.full : 0,\n evidence: [\n measured('Sitemap listed in robots.txt', yesNo(context.policy.sitemapDeclared)),\n measured(\n 'Sitemaps',\n context.robots === null ? 'none' : context.robots.sitemaps.join(', ') || 'none',\n ),\n ],\n remedy: context.policy.sitemapDeclared\n ? undefined\n : 'Add a line like `Sitemap: https://example.com/sitemap.xml` to robots.txt.',\n }\n}\n\n/**\n * Media types and URL shapes that count as a declared machine endpoint (§3.4\n * D6.5: UCP/ACP/MCP/OpenAPI/GraphQL/RSS/Atom/ICS/JSON feed).\n *\n * Credit comes from DECLARATION. ARS probes `/robots.txt`, `/llms.txt` and\n * `/.well-known/ucp` and nothing else — no guessing at `/sitemap.xml`, `/mcp` or\n * `/acp` — because an endpoint an agent cannot find is an endpoint that does not\n * exist. The three probed paths are the disclosed exception: they are published\n * conventions with published locations.\n */\nconst ENDPOINT_TYPES: readonly string[] = [\n 'application/rss+xml',\n 'application/atom+xml',\n 'application/feed+json',\n 'application/json',\n 'application/ld+json',\n 'application/vnd.api+json',\n 'application/schema+json',\n 'application/graphql',\n 'application/openapi+json',\n 'application/yaml',\n 'text/calendar',\n]\nconst ENDPOINT_RELS: readonly string[] = [\n 'service-desc',\n 'service-doc',\n 'api',\n 'describedby',\n 'ucp',\n 'mcp',\n]\nconst ENDPOINT_PATH_MARKERS: readonly string[] = [\n '/api',\n '/mcp',\n '/graphql',\n '/openapi',\n '/.well-known/',\n '.json',\n '.ics',\n '.rss',\n '.atom',\n]\n\nfunction checkMachineEndpoint(context: ScoreContext): CheckOutcome {\n const declarations: string[] = []\n\n const links = parseLinkHeaders([\n ...headerAll(context.agentCapture.headers, 'link'),\n ...(context.browserCapture === null ? [] : headerAll(context.browserCapture.headers, 'link')),\n ])\n for (const link of links) {\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`Link header (${link.rel.join(' ')}) at ${link.url}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`Link header (${link.type}) at ${link.url}`)\n }\n\n if (context.structural !== null && context.structural.doc !== null) {\n for (const link of context.structural.doc.links) {\n if (link.href === null) continue\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`link tag (${link.rel.join(' ')}) at ${link.href}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`link tag (${link.type}) at ${link.href}`)\n }\n }\n\n const llms = bodyOf(context.evidence.probes.llmsTxt)\n if (llms !== null) {\n MARKDOWN_LINK.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = MARKDOWN_LINK.exec(llms)) !== null) {\n const url = (match[1] ?? '').toLowerCase()\n if (ENDPOINT_PATH_MARKERS.some((marker) => url.includes(marker)))\n declarations.push(`llms.txt link to ${match?.[1] ?? url}`)\n }\n }\n\n const ucp = bodyOf(context.evidence.probes.wellKnownUcp)\n if (ucp !== null && ucp.trim().length > 0) declarations.push('/.well-known/ucp')\n // Both probes usually carry the same `Link` header; list each once.\n const unique = [...new Set(declarations)]\n\n return {\n earned: declarations.length > 0 ? SUBPOINTS.machineEndpoint.full : 0,\n evidence: [\n measured('Feeds or APIs we found', unique.length === 0 ? 'none' : unique.join('; ')),\n measured('Where we looked', 'link tags, Link headers, /llms.txt and /.well-known/ucp'),\n ],\n remedy:\n declarations.length > 0\n ? undefined\n : 'Point to a product feed, API or calendar from the page with a `<link>` tag or a `Link` header. We only count ones the page names.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assembly\n// ---------------------------------------------------------------------------\n\nfunction weightOf(ruleset: ArsRuleset, id: ArsCheckId): number {\n return ruleset.weights[id] ?? 0\n}\n\nfunction buildCheck(ruleset: ArsRuleset, id: ArsCheckId, outcome: CheckOutcome): ArsCheck {\n const meta = CHECK_META[id]\n const weight = weightOf(ruleset, id)\n // Structural guarantee: `earned` is an integer in `[0, weight]`. Every branch\n // above already produces one; the clamp is what makes it impossible for a\n // future check to publish a number outside its own weight. Fixture 052 asserts\n // the property over the whole corpus.\n const earned = Math.max(0, Math.min(weight, outcome.earned))\n const check: ArsCheck = {\n id,\n label: meta.label,\n basis: meta.basis,\n weight,\n earned,\n evidence: outcome.evidence,\n }\n return outcome.remedy === undefined || earned === weight\n ? check\n : { ...check, remedy: outcome.remedy }\n}\n\n/**\n * Publication order. HAND-MAINTAINED AND THEREFORE DANGEROUS: a dimension\n * missing here is silently dropped from `dimensions`, and its checks' points\n * vanish from the total. ARS 0.2 shipped D7 without it for one commit and the\n * corpus re-scored against a maximum of 92. `score.test.ts` now asserts this\n * list covers `DIMENSION_META` exactly.\n */\nconst DIMENSION_ORDER: readonly ArsDimensionId[] = [\n 'retrievability',\n 'machine-representation',\n 'fact-coverage',\n 'fact-position',\n 'structured-data',\n 'contract-discovery',\n 'evidence-density',\n]\n\nfunction buildDimensions(checks: readonly ArsCheck[]): ArsDimension[] {\n return DIMENSION_ORDER.map((id) => {\n const own = checks.filter((check) => CHECK_META[check.id].dimension === id)\n return {\n id,\n label: DIMENSION_META[id].label,\n weight: DIMENSION_META[id].weight,\n earned: own.reduce((sum, check) => sum + check.earned, 0),\n basis: own.some((check) => check.basis === 'heuristic')\n ? ('heuristic' as ArsBasis)\n : ('measured' as ArsBasis),\n checks: own,\n }\n })\n}\n\n/** Pinned flag order, so two runs over the same evidence emit the same array. */\nconst FLAG_ORDER: readonly ArsFlagId[] = [\n 'substance-divergence',\n 'structured-data-divergence',\n 'robots-contradiction',\n 'paywalled',\n 'render-dependent',\n 'scanner-blocked',\n 'training-opt-out',\n 'assistant-opt-out',\n 'vary-missing',\n 'canonical-mismatch',\n 'body-truncated',\n 'vantage-variance',\n]\n\nfunction sortFlags(flags: readonly ArsFlag[]): ArsFlag[] {\n return [...flags].sort((a, b) => FLAG_ORDER.indexOf(a.id) - FLAG_ORDER.indexOf(b.id))\n}\n\n/** The band a score falls in. Bands headline; the integer is secondary (§3.6). */\nexport function bandFor(score: number, ruleset: ArsRuleset = DEFAULT_RULESET): ArsBand | null {\n for (const band of ruleset.bands) if (score >= band.min && score <= band.max) return band\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Evidence plumbing\n// ---------------------------------------------------------------------------\n\nfunction captureOf(probe: ArsProbeRecord | null): ArsHttpCapture | null {\n return probe !== null && probe.result.ok ? probe.result.capture : null\n}\n\n/**\n * The currency the page prices in, read from structured data and Open Graph.\n * The SAME hint is used for both representations, deliberately: a hint is a\n * property of the page, and letting the two representations resolve `$` to\n * different currencies would manufacture a substance divergence out of nothing.\n */\nfunction currencyHintOf(\n structural: ArsRepresentation | null,\n agent: ArsRepresentation,\n): string | undefined {\n for (const representation of [structural, agent]) {\n if (representation === null) continue\n for (const node of representation.jsonLd.nodes) {\n for (const path of ['offers.priceCurrency', 'priceCurrency']) {\n const raw = readPath(node, path)\n if (raw !== null && /^[A-Za-z]{3}$/.test(raw.trim())) return raw.trim().toUpperCase()\n }\n }\n if (representation.doc === null) continue\n for (const meta of representation.doc.metas) {\n const key = meta.property ?? meta.name\n if (key !== 'og:price:currency' && key !== 'product:price:currency') continue\n const value = meta.content\n if (value !== null && /^[A-Za-z]{3}$/.test(value.trim())) return value.trim().toUpperCase()\n }\n }\n return undefined\n}\n\nfunction pathOf(url: string, fallback: string): string {\n try {\n return new URL(url).pathname\n } catch {\n return fallback\n }\n}\n\n/** robots.txt status and parse, from the probe record alone. */\nfunction readRobots(probe: ArsProbeRecord | null): {\n status: ArsPolicyReport['robotsTxtStatus']\n robots: RobotsFile | null\n} {\n if (probe === null) return { status: 'missing', robots: null }\n if (!probe.result.ok) return { status: 'error', robots: null }\n const capture = probe.result.capture\n if (capture.status >= 500) return { status: 'error', robots: null }\n if (capture.status >= 400) return { status: 'missing', robots: null }\n const body = typeof capture.body === 'string' ? capture.body : null\n if (body === null) return { status: 'missing', robots: null }\n const robots = parseRobots(body)\n const empty = robots.groups.length === 0 && robots.sitemaps.length === 0\n return { status: empty && robots.malformedLines > 0 ? 'unparseable' : 'ok', robots }\n}\n\n/** Declared paywalls only (§3.8). Undeclared soft paywalls need impersonation, which we refuse. */\nfunction detectPaywall(context: {\n structural: ArsRepresentation | null\n agentCapture: ArsHttpCapture\n}): string | null {\n if (context.agentCapture.status === 402) return 'HTTP 402'\n if (header(context.agentCapture.headers, 'www-authenticate') !== null) return 'WWW-Authenticate'\n for (const node of context.structural?.jsonLd.nodes ?? []) {\n const value = node.value['isAccessibleForFree']\n if (value === false || value === 'False' || value === 'false')\n return 'isAccessibleForFree: false'\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Non-grades\n// ---------------------------------------------------------------------------\n\n/**\n * The result shape for the three non-grades (§3.6). `score` is null and there is\n * no letter — an opt-out is a choice and an unscored target is a missing\n * observation, and neither is an F.\n *\n * The six dimensions are still present with their weights, because §3.9 says\n * `dimensions` always has 6 entries summing to 100, but every check reports\n * `earned: 0` with an evidence line naming the reason. A non-grade is a\n * statement that we did not score; publishing sub-scores next to it would be\n * scoring by another name.\n */\nfunction nonGrade(\n evidence: ArsEvidence,\n ruleset: ArsRuleset,\n outcome: ArsOutcome,\n reason: string,\n policy: ArsPolicyReport,\n flags: readonly ArsFlag[],\n): ArsResult {\n const agentCapture = captureOf(evidence.probes.agent)\n const browserCapture = captureOf(evidence.probes.browser)\n const checks = (Object.keys(CHECK_META) as ArsCheckId[]).map((id) =>\n buildCheck(ruleset, id, {\n earned: 0,\n evidence: [{ label: 'Not evaluated', value: reason, basis: CHECK_META[id].basis }],\n }),\n )\n const htmlBytes = browserCapture?.bytes ?? agentCapture?.bytes ?? 0\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture?.finalUrl ?? evidence.target.url,\n origin: evidence.target.origin,\n },\n outcome,\n score: null,\n grade: null,\n bandLabel: null,\n pageKind: 'unknown',\n pageKindBasis: 'heuristic',\n pageKindConfidence: 'low',\n factProfile: profileFor('unknown'),\n facts: [],\n dimensions: buildDimensions(checks),\n flags: sortFlags(flags),\n policy,\n cost: {\n htmlBytes,\n negotiatedBytes: null,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: null,\n reductionRatio: null,\n firstCoreFactOffset: null,\n truncated: (agentCapture?.truncated ?? false) || (browserCapture?.truncated ?? false),\n },\n recommendations: [],\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\nfunction measuredWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'measured') total += weightOf(ruleset, id)\n }\n return total\n}\n\nfunction heuristicWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'heuristic') total += weightOf(ruleset, id)\n }\n return total\n}\n\n/** Probe error → the reason ARS publishes. `detail` carries the probe's own word for it. */\nfunction unscoredReasonFor(error: string): { reason: ArsUnscoredReason; detail?: string } {\n switch (error) {\n case 'challenge':\n return { reason: 'blocked-at-edge', detail: 'challenge' }\n case 'non-2xx':\n return { reason: 'non-2xx' }\n case 'too-many-redirects':\n return { reason: 'too-many-redirects' }\n case 'timeout':\n return { reason: 'unreachable', detail: 'timeout' }\n case 'blocked-redirect':\n return { reason: 'unreachable', detail: 'blocked-redirect' }\n case 'policy-rejected':\n return { reason: 'unreachable', detail: 'policy-rejected' }\n default:\n return { reason: 'unreachable' }\n }\n}\n\n// ---------------------------------------------------------------------------\n// score()\n// ---------------------------------------------------------------------------\n\n/**\n * The entire pure surface. No network. No clock. No randomness. No LLM.\n *\n * GATE ORDER, and why it is this order:\n * 1. `robots-disallow-scanner` — a statement about OUR conduct. If we were not\n * allowed to fetch, nothing else about the evidence should be reported.\n * Only `vantage: 'public'` is gated; an owner can consent for their own\n * origin (§3.7), and a merchant scanning their own store getting `unscored`\n * because they block unknown tokens is a product regression dressed as rigour.\n * 2. `robots-unavailable` — a persistent 5xx means we could not learn the policy.\n * 3. `opt-out` — the site's own decision, reported before any failure of ours,\n * because it is a choice and not a failure.\n * 4. Fetch failures, then a bundle with no body, then a truncated body.\n */\nexport function score(evidence: ArsEvidence, ruleset: ArsRuleset = DEFAULT_RULESET): ArsResult {\n const flags: ArsFlag[] = []\n const targetPath = pathOf(evidence.target.url, '/')\n const { status: robotsStatus, robots } = readRobots(evidence.probes.robotsTxt)\n const policy = buildPolicyReport(robots, robotsStatus, ruleset, targetPath)\n\n if (policy.trainingOptOut) {\n flags.push({\n id: 'training-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site blocks AI training crawlers but lets AI assistants in. That does not affect the score.',\n evidence: [\n measured('Training audience', policy.audiences.training.matchedRule ?? 'disallowed'),\n measured('Effect on this score', 'none'),\n ],\n })\n }\n\n // 1 — we obey our own token, and say so.\n if (evidence.vantage === 'public' && robots !== null) {\n const scannerDecision = decideScannerToken(robots, targetPath)\n if (scannerDecision) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'info',\n basis: 'measured',\n message:\n 'robots.txt asks Rebilder’s scanner not to read this site, so we did not score the page.',\n evidence: [measured('Matched rule', scannerDecision)],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-disallow-scanner' },\n 'robots.txt disallows the rebilder-ars token',\n policy,\n flags,\n )\n }\n }\n\n // 2 — a policy we could not read is not a policy we may assume.\n if (robotsStatus === 'error') {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-unavailable' },\n 'robots.txt returned a persistent error',\n policy,\n flags,\n )\n }\n\n // 3 — a deliberate, well-formed opt-out. Not a failure, not ranked, no letter.\n if (policy.deliberateOptOut) {\n flags.push({\n id: 'assistant-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site’s robots.txt blocks AI assistants by name. We respect that choice and do not grade the page.',\n evidence: [\n measured('Matched group', policy.audiences.assistant.matchedGroup ?? '(named group)'),\n measured('Matched rule', policy.audiences.assistant.matchedRule ?? 'Disallow'),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'opt-out', audience: 'assistant' satisfies ArsAudience, wellFormed: true },\n 'the site opted out of assistant crawling',\n policy,\n flags,\n )\n }\n\n // 4 — fetch failures.\n const agentProbe = evidence.probes.agent\n if (!agentProbe.result.ok) {\n const { reason, detail } = unscoredReasonFor(agentProbe.result.error)\n if (reason === 'blocked-at-edge') {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The site answered our scanner with a bot check or a block, so we did not grade the page. AI assistants may be blocked the same way.',\n evidence: [measured('Probe error', agentProbe.result.error)],\n })\n }\n const outcome: ArsOutcome =\n detail === undefined ? { kind: 'unscored', reason } : { kind: 'unscored', reason, detail }\n return nonGrade(\n evidence,\n ruleset,\n outcome,\n `the agent probe failed: ${agentProbe.result.error}`,\n policy,\n flags,\n )\n }\n\n const agentCapture = agentProbe.result.capture\n if (agentCapture.status === 403 || agentCapture.status === 401 || agentCapture.status === 429) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message: `The site answered our scanner with HTTP ${agentCapture.status}, so we did not grade the page. AI assistants may be blocked the same way.`,\n evidence: [measured('HTTP status', String(agentCapture.status))],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'blocked-at-edge', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.status < 200 || agentCapture.status >= 300) {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'non-2xx', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.redirects.length > ruleset.maxRedirects) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'too-many-redirects',\n detail: `${agentCapture.redirects.length} hops`,\n },\n `the agent path took ${agentCapture.redirects.length} redirect hops`,\n policy,\n flags,\n )\n }\n\n const browserCapture = captureOf(evidence.probes.browser)\n if (agentCapture.truncated || (browserCapture?.truncated ?? false)) {\n flags.push({\n id: 'body-truncated',\n severity: 'warn',\n basis: 'measured',\n message: `The page is larger than our ${plainBytes(ruleset.maxBodyBytes)} reading limit, so we did not score it. The facts and sizes would both be incomplete.`,\n evidence: [\n measured('Body cap', `${ruleset.maxBodyBytes} bytes`),\n measured('Bytes read', `≥ ${agentCapture.bytes}`),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'truncated-evidence' },\n 'the response exceeded the body cap and was truncated',\n policy,\n flags,\n )\n }\n\n const agent = buildRepresentation(agentCapture)\n if (agent === null) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'evidence-incomplete',\n detail: 'the bundle carries no response body',\n },\n 'the evidence bundle carries hashes but no body, so it cannot be re-scored',\n policy,\n flags,\n )\n }\n const browser = browserCapture === null ? null : buildRepresentation(browserCapture)\n const structural =\n browser !== null && browser.doc !== null ? browser : agent.doc !== null ? agent : browser\n\n // ── classification (pass 1) ──────────────────────────────────────────────\n const classification = classify(pass1Signals(structural ?? agent, evidence.target.url))\n const profile = profileFor(classification.pageKind)\n\n // ── extraction (pass 2) ──────────────────────────────────────────────────\n const currencyHint = currencyHintOf(structural, agent)\n const extractContext = {\n profile,\n ruleset,\n baseUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n currencyHint,\n }\n const agentFacts = extractFacts(agent, extractContext)\n const browserFacts =\n browser === null || browser === agent\n ? []\n : extractFacts(browser, { ...extractContext, baseUrl: browser.finalUrl })\n const structuralFacts =\n structural === agent ? agentFacts : structural === browser ? browserFacts : []\n const facts = mergeFacts(agentFacts, structuralFacts)\n\n const negotiated = isMachineCopy(agentCapture)\n const context: ScoreContext = {\n negotiated,\n linkedCopy: negotiated ? null : linkedCopyOf(evidence, agentCapture, browserCapture),\n evidence,\n ruleset,\n agentCapture,\n browserCapture,\n agent,\n browser,\n structural,\n classification,\n profile,\n facts,\n agentFacts,\n browserFacts,\n structuralFacts,\n policy,\n robots,\n flags,\n }\n\n const paywall = detectPaywall(context)\n if (paywall !== null) {\n flags.push({\n id: 'paywalled',\n severity: 'info',\n basis: 'measured',\n message: `This page says it is behind a paywall (${paywall}). We scored the part we were shown.`,\n evidence: [measured('Paywall signal', paywall)],\n })\n }\n\n // ── the 22 checks ────────────────────────────────────────────────────────\n const math = coverageMath(context)\n const offsets = coreOffsets(context)\n const negotiatedResponse = checkNegotiatedResponse(context)\n\n const checks: ArsCheck[] = [\n buildCheck(ruleset, 'retrievability.reachable', checkReachable(context)),\n buildCheck(ruleset, 'retrievability.robots-policy', checkRobotsPolicy(context)),\n buildCheck(ruleset, 'retrievability.render-independence', checkRenderIndependence(context)),\n buildCheck(ruleset, 'machine-representation.negotiated-response', negotiatedResponse),\n buildCheck(\n ruleset,\n 'machine-representation.declared-alternates',\n checkDeclaredAlternates(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.vary-accept',\n checkVaryAccept(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.substance-parity',\n checkSubstanceParity(context),\n ),\n buildCheck(ruleset, 'fact-coverage.core-facts', checkCoreFacts(context, math)),\n buildCheck(ruleset, 'fact-coverage.context-cost', checkContextCost(context)),\n buildCheck(\n ruleset,\n 'fact-position.first-core-fact-offset',\n checkFirstCoreFactOffset(context, offsets),\n ),\n buildCheck(ruleset, 'fact-position.front-window', checkFrontWindow(context, offsets)),\n buildCheck(ruleset, 'structured-data.present', checkStructuredDataPresent(context)),\n buildCheck(ruleset, 'structured-data.required-properties', checkRequiredProperties(context)),\n buildCheck(ruleset, 'structured-data.text-agreement', checkTextAgreement(context)),\n buildCheck(ruleset, 'contract-discovery.canonical', checkCanonical(context)),\n buildCheck(ruleset, 'contract-discovery.cache-validators', checkCacheValidators(context)),\n buildCheck(ruleset, 'contract-discovery.llms-txt', checkLlmsTxt(context)),\n buildCheck(ruleset, 'contract-discovery.sitemap', checkSitemap(context)),\n buildCheck(ruleset, 'contract-discovery.machine-endpoint', checkMachineEndpoint(context)),\n buildCheck(ruleset, 'evidence-density.quantities', checkQuantities(context)),\n buildCheck(ruleset, 'evidence-density.definitions', checkDefinitions(context)),\n buildCheck(ruleset, 'evidence-density.comparisons', checkComparisons(context)),\n ]\n\n const dimensions = buildDimensions(checks)\n const total = dimensions.reduce((sum, dimension) => sum + dimension.earned, 0)\n const band = bandFor(total, ruleset)\n const grade: ArsGrade = band?.grade ?? 'F'\n\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n const htmlBytes = structural?.bytes ?? agent.bytes\n const negotiatedBytes = negotiated ? agent.bytes : null\n const cost: ArsCostReport = {\n htmlBytes,\n negotiatedBytes,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: negotiatedBytes === null ? null : idiv(negotiatedBytes, perToken),\n // Integer PERCENT of HTML bytes the machine representation eliminates:\n // 94 means \"94% fewer bytes\". §3.9 types this as a number and does not fix\n // its unit; a multiple (`4.2×`) would be a float, and this is the same\n // information with no rounding for two implementations to disagree about.\n reductionRatio:\n negotiatedBytes === null || htmlBytes === 0\n ? null\n : Math.max(0, 100 - idiv(100 * negotiatedBytes, htmlBytes)),\n firstCoreFactOffset: offsets[0] ?? null,\n truncated: agent.truncated || (browser?.truncated ?? false),\n }\n\n const published: ArsFactObservation[] = facts.map((fact) => ({\n kind: fact.kind,\n normalized: fact.normalized,\n source: fact.source,\n offset: fact.offset,\n corroborated: fact.corroborated,\n }))\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n },\n outcome: { kind: 'scored', grade, score: total },\n score: total,\n grade,\n bandLabel: band?.label ?? null,\n pageKind: classification.pageKind,\n pageKindBasis: 'heuristic',\n pageKindConfidence: classification.confidence,\n factProfile: profile,\n facts: published,\n dimensions,\n flags: sortFlags(flags),\n policy,\n cost,\n recommendations: recommend({ dimensions, score: total }),\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\n/**\n * The product token the probe sends (§3.3). This is the ONLY place in the scorer\n * where our own identity is an input to a decision, and the decision it drives is\n * to score nothing.\n */\nconst SCANNER_TOKEN = 'rebilder-ars'\n\n/**\n * Does robots.txt disallow the ARS scanner itself? Returns the matched rule when\n * it does, so the result can print the line rather than assert a verdict.\n *\n * Only a group that NAMES `rebilder-ars` counts. A blanket `User-agent: *`\n * disallow is not a decision about us: it is the accidental case (§3.7), which is\n * scored with `robots-contradiction`, not silently exempted. Rule selection is\n * RFC 9309 longest-match with ties to Allow, via `./extract`'s `pathMatches` —\n * the same matcher `decideRobots` uses, so the scanner gate and the audience\n * decision can never disagree about what a pattern means.\n */\nfunction decideScannerToken(robots: RobotsFile, path: string): string | null {\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent === SCANNER_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${SCANNER_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n","/**\n * site-signals.ts — observations about a page that are NOT part of ARS.\n *\n * Nothing in this file is read by `score()`, and nothing here changes a check,\n * a weight, a flag in `ArsResult`, or the ruleset hash. These are the unscored\n * site-report findings that ride alongside a score: a CDN bot challenge served\n * instead of the page, `noindex` directives, the canonical address a page\n * names. Pure, no clock, no network, so the probe, the API and a second\n * implementation can all read a capture the same way.\n *\n * ── EDGE CHALLENGE FINGERPRINTS ─────────────────────────────────────────────\n * A fingerprint ships only when the vendor's own documentation confirms it.\n * Sources, checked November 2026:\n *\n * - Cloudflare, header. \"cf-mitigated\" present and set to \"challenge\" on every\n * Challenge Page type, any status:\n * https://developers.cloudflare.com/cloudflare-challenges/challenge-types/challenge-pages/detect-response/\n * - Cloudflare, markup. Challenge scripts load from paths starting\n * \"/cdn-cgi/challenge-platform/\":\n * https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/\n * Cloudflare also injects that path into ORDINARY pages (JavaScript\n * Detections), so the markup alone never counts: it needs `server:\n * cloudflare` AND a 403, 429 or 503. A 200 challenge is caught by the\n * header, which Cloudflare sets on all challenge types.\n * - Vercel. A challenged visitor sees the \"Vercel Security Checkpoint\" screen:\n * https://vercel.com/docs/vercel-firewall/firewall-concepts#challenge\n * The page is localised, so the English title is a supplementary signal and\n * needs a non-2xx status and `server: Vercel`. The `x-vercel-mitigated:\n * challenge` header is not in Vercel's reference docs; it is what Vercel's\n * own community forum shows on challenged responses\n * (https://community.vercel.com/t/all-non-browser-requests-challenged-on-hobby-account-ddos-mitigation-false-positive/1000000130).\n * - DataDome. A blocking response carries the status DataDome's API returned\n * plus the mapped `X-DataDome` header:\n * https://docs.datadome.co/reference/validate-request\n * The header alone also appears on allowed responses, so it counts only\n * with a 401 or 403.\n * - HUMAN (PerimeterX). The block page renders a `px-captcha` element and sets\n * `window._pxAppId`:\n * https://docs.humansecurity.com/applications/advanced-blocking-response\n * Both markers are required, with a 403 or 429.\n *\n * NOT SHIPPED, because no vendor documentation confirmed a fingerprint:\n * Akamai Bot Manager (the `sec-cpt`/428 behaviour is described only by third\n * parties) and Imperva (the \"Incapsula incident ID\" page and `x-iinfo` header\n * are described only by third parties and Imperva's community forum). Those\n * still surface as an HTTP 403 block, exactly as before.\n */\nimport type { ArsEvidence, ArsFactKind, ArsFactProfile, ArsHttpCapture } from './types'\nimport {\n absoluteUrl,\n buildRepresentation,\n extractFacts,\n headerAll,\n parseJsonLd,\n utf8Length,\n type ArsFactSource,\n} from './extract'\nimport { elementText, tokenizeHtml, type HtmlDocument, type HtmlElement } from './html'\nimport { parseLinkHeaders } from './score'\nimport { DEFAULT_RULESET } from './ruleset'\n\n/* ── edge challenges ──────────────────────────────────────────────────────── */\n\nexport type EdgeChallengeVendor = 'cloudflare' | 'vercel' | 'datadome' | 'human'\n\nexport const EDGE_CHALLENGE_VENDOR_LABEL: Readonly<Record<EdgeChallengeVendor, string>> = {\n cloudflare: 'Cloudflare',\n vercel: 'Vercel',\n datadome: 'DataDome',\n human: 'HUMAN',\n}\n\nexport interface EdgeChallenge {\n vendor: EdgeChallengeVendor\n /** The observation that matched, e.g. `cf-mitigated: challenge`. */\n signal: string\n status: number\n}\n\n/** The slice of a response the detector reads. `ArsHttpCapture` satisfies it. */\nexport interface ChallengeInput {\n status: number\n headers: Readonly<Record<string, readonly string[]>>\n body?: string | null\n requestedUrl?: string\n finalUrl?: string\n}\n\n/** Markers sit in the first part of every documented challenge page. */\nconst BODY_SCAN_CHARS = 256 * 1024\n\nfunction headerValues(input: ChallengeInput, name: string): string[] {\n const direct = input.headers[name]\n if (direct !== undefined) return direct.map((value) => value.toLowerCase())\n const target = name.toLowerCase()\n const out: string[] = []\n for (const [key, values] of Object.entries(input.headers)) {\n if (key.toLowerCase() === target) {\n for (const value of values) out.push(value.toLowerCase())\n }\n }\n return out\n}\n\nfunction hasToken(values: readonly string[], token: string): boolean {\n return values.some((value) =>\n value\n .split(',')\n .map((part) => part.trim())\n .includes(token),\n )\n}\n\nfunction isRobotsTxtTarget(input: ChallengeInput): boolean {\n for (const raw of [input.requestedUrl, input.finalUrl]) {\n if (typeof raw !== 'string' || raw.length === 0) continue\n try {\n if (new URL(raw).pathname.toLowerCase() === '/robots.txt') return true\n } catch {\n const path = (raw.split('#')[0]?.split('?')[0] ?? '').toLowerCase()\n if (path === '/robots.txt' || path.endsWith('/robots.txt')) return true\n }\n }\n return false\n}\n\n/**\n * The documented challenge fingerprints, most specific first. Returns null for\n * an ordinary response, including an ordinary 403: a block without a\n * recognised challenge stays a block. Also handles `/robots.txt` responses\n * cleanly (case-insensitive headers, never flagging plain-text `Disallow:`\n * lines, and recognising HTML challenge pages served at `/robots.txt`).\n */\nexport function detectEdgeChallenge(input: ChallengeInput): EdgeChallenge | null {\n const status = input.status\n const body = typeof input.body === 'string' ? input.body.slice(0, BODY_SCAN_CHARS) : ''\n const server = headerValues(input, 'server')\n const contentTypes = headerValues(input, 'content-type')\n const isHtmlContent = contentTypes.some(\n (value) => value.includes('text/html') || value.includes('application/xhtml+xml'),\n )\n const lowerBodyHead = body.slice(0, 4096).toLowerCase()\n const isPlainTextWithoutMarkup =\n contentTypes.some((value) => value.includes('text/plain')) &&\n !lowerBodyHead.includes('<html') &&\n !lowerBodyHead.includes('<script') &&\n !lowerBodyHead.includes('<!doctype html')\n const isRobotsHtmlChallenge = isRobotsTxtTarget(input) && isHtmlContent\n\n if (hasToken(headerValues(input, 'cf-mitigated'), 'challenge')) {\n return { vendor: 'cloudflare', signal: 'cf-mitigated: challenge', status }\n }\n if (\n (status === 403 || status === 429 || status === 503 || (isRobotsHtmlChallenge && status === 200)) &&\n !isPlainTextWithoutMarkup &&\n server.some((value) => value.includes('cloudflare')) &&\n body.includes('/cdn-cgi/challenge-platform/')\n ) {\n return { vendor: 'cloudflare', signal: 'Cloudflare challenge page', status }\n }\n\n if (hasToken(headerValues(input, 'x-vercel-mitigated'), 'challenge')) {\n return { vendor: 'vercel', signal: 'x-vercel-mitigated: challenge', status }\n }\n if (\n (status < 200 || status >= 300 || (isRobotsHtmlChallenge && status === 200)) &&\n !isPlainTextWithoutMarkup &&\n server.some((value) => value.includes('vercel')) &&\n body.includes('Vercel Security Checkpoint')\n ) {\n return { vendor: 'vercel', signal: 'Vercel Security Checkpoint page', status }\n }\n\n if ((status === 401 || status === 403) && headerValues(input, 'x-datadome').length > 0) {\n return { vendor: 'datadome', signal: `x-datadome with HTTP ${status}`, status }\n }\n\n if (\n (status === 403 || status === 429 || (isRobotsHtmlChallenge && status === 200)) &&\n !isPlainTextWithoutMarkup &&\n body.includes('px-captcha') &&\n body.includes('_pxAppId')\n ) {\n return { vendor: 'human', signal: 'HUMAN block page', status }\n }\n\n return null\n}\n\nconst DETAIL_PREFIX = 'edge-challenge'\nconst DETAIL_PATTERN = /^edge-challenge; vendor=([a-z]+); status=(\\d{3}); signal=(.{1,120})$/\n\n/**\n * The probe records a challenge as `{ ok: false, error: 'challenge', detail }`.\n * `detail` is this fixed, parseable line, so a consumer can name the vendor\n * without the bundle carrying the challenge page itself.\n */\nexport function challengeDetail(challenge: EdgeChallenge): string {\n return `${DETAIL_PREFIX}; vendor=${challenge.vendor}; status=${challenge.status}; signal=${challenge.signal.slice(0, 120)}`\n}\n\nexport function parseChallengeDetail(detail: unknown): EdgeChallenge | null {\n if (typeof detail !== 'string') return null\n const match = DETAIL_PATTERN.exec(detail)\n if (match === null) return null\n const vendor = match[1] as EdgeChallengeVendor\n if (!(vendor in EDGE_CHALLENGE_VENDOR_LABEL)) return null\n return { vendor, status: Number(match[2]), signal: match[3] ?? '' }\n}\n\n/**\n * The challenge the AGENT probe met, if any. Accepts `unknown` so callers that\n * only hold a structural slice of the bundle (the API's seam types) can ask.\n */\nexport function edgeChallengeOf(evidence: unknown): EdgeChallenge | null {\n if (typeof evidence !== 'object' || evidence === null) return null\n const agent = (evidence as { probes?: { agent?: { result?: unknown } } }).probes?.agent?.result\n if (typeof agent !== 'object' || agent === null) return null\n const result = agent as { ok?: unknown; error?: unknown; detail?: unknown }\n if (result.ok !== false || result.error !== 'challenge') return null\n return parseChallengeDetail(result.detail)\n}\n\n/**\n * The challenge the `/robots.txt` probe met, if any — inspecting either a\n * recorded `challenge` probe error or the captured `/robots.txt` response.\n */\nexport function robotsEdgeChallengeOf(evidence: unknown): EdgeChallenge | null {\n if (typeof evidence !== 'object' || evidence === null) return null\n const robots = (evidence as { probes?: { robotsTxt?: { result?: unknown } | null } }).probes\n ?.robotsTxt?.result\n if (typeof robots !== 'object' || robots === null) return null\n const result = robots as {\n ok?: unknown\n error?: unknown\n detail?: unknown\n capture?: ChallengeInput\n }\n if (result.ok === false && result.error === 'challenge') {\n return parseChallengeDetail(result.detail)\n }\n if (result.ok === true && result.capture !== undefined && typeof result.capture === 'object') {\n return detectEdgeChallenge(result.capture)\n }\n return null\n}\n\n/* ── Cloudflare / robots.txt Content-signal directives ────────────────────── */\n\nexport type ContentSignalValue = 'yes' | 'no' | (string & {})\n\nexport interface ContentSignalRule {\n /** User-agent tokens in the enclosing group (lowercased); empty if global. */\n readonly agents: readonly string[]\n /** Raw trimmed value after `Content-signal:`. */\n readonly raw: string\n /** Parsed lowercased `key=value` pairs (e.g. `{ search: 'yes', 'ai-train': 'no' }`). */\n readonly signals: Readonly<Record<string, ContentSignalValue>>\n}\n\nexport interface ContentSignalsReport {\n /** True when at least one `Content-signal:` directive was found. */\n readonly present: boolean\n /** True when `# BEGIN Cloudflare Managed content` appears in robots.txt. */\n readonly cloudflareManaged: boolean\n /** All parsed `Content-signal:` rules in source order. */\n readonly rules: readonly ContentSignalRule[]\n /** Effective wildcard (`*`) or global summary for the three standard signals. */\n readonly summary: {\n readonly search: ContentSignalValue | null\n readonly aiInput: ContentSignalValue | null\n readonly aiTrain: ContentSignalValue | null\n }\n}\n\nconst CLOUDFLARE_MANAGED_MARKER = '# begin cloudflare managed content'\n\n/**\n * Parses `Content-signal:` directives (e.g. Cloudflare Managed `robots.txt`\n * `Content-signal: search=yes, ai-train=no`) and detects the Cloudflare\n * Managed content block marker. Pure, unscored, never read by `score()`.\n */\nexport function parseContentSignals(robotsTxt: string): ContentSignalsReport {\n let cloudflareManaged = false\n const rules: ContentSignalRule[] = []\n let currentAgents: string[] = []\n let openingGroup = false\n\n for (const rawLine of robotsTxt.split(/\\r?\\n/)) {\n const trimmedRaw = rawLine.trim()\n if (trimmedRaw.toLowerCase().includes(CLOUDFLARE_MANAGED_MARKER)) {\n cloudflareManaged = true\n }\n\n const withoutComment = rawLine.split('#')[0] ?? ''\n const line = withoutComment.trim()\n if (line.length === 0) continue\n\n const colon = line.indexOf(':')\n if (colon <= 0) continue\n\n const field = line.slice(0, colon).trim().toLowerCase()\n const value = line.slice(colon + 1).trim()\n\n if (field === 'user-agent') {\n if (!openingGroup) {\n currentAgents = []\n openingGroup = true\n }\n if (value.length > 0) currentAgents.push(value.toLowerCase())\n continue\n }\n\n if (field === 'allow' || field === 'disallow') {\n openingGroup = false\n continue\n }\n\n if (field === 'content-signal') {\n if (currentAgents.length > 0) openingGroup = false\n const parsed: Record<string, ContentSignalValue> = {}\n for (const part of value.split(',')) {\n const eq = part.indexOf('=')\n if (eq <= 0) continue\n const key = part.slice(0, eq).trim().toLowerCase()\n const val = part.slice(eq + 1).trim().toLowerCase()\n if (key.length > 0 && val.length > 0) {\n parsed[key] = val\n }\n }\n rules.push({\n agents: [...currentAgents],\n raw: value,\n signals: parsed,\n })\n }\n }\n\n let search: ContentSignalValue | null = null\n let aiInput: ContentSignalValue | null = null\n let aiTrain: ContentSignalValue | null = null\n\n const wildcardRules = rules.filter((rule) => rule.agents.includes('*'))\n const summarySource =\n wildcardRules.length > 0\n ? wildcardRules\n : rules.filter((rule) => rule.agents.length === 0)\n\n for (const rule of summarySource) {\n if (rule.signals['search'] !== undefined) search = rule.signals['search']\n if (rule.signals['ai-input'] !== undefined) aiInput = rule.signals['ai-input']\n if (rule.signals['ai-train'] !== undefined) aiTrain = rule.signals['ai-train']\n }\n\n return {\n present: rules.length > 0,\n cloudflareManaged,\n rules,\n summary: { search, aiInput, aiTrain },\n }\n}\n\n/* ── indexability ─────────────────────────────────────────────────────────── */\n\nexport interface NoindexDirective {\n /** `robots` for the generic directive, otherwise the crawler token named. */\n agent: string\n source: 'meta' | 'header'\n value: string\n}\n\nexport type RestrictedRobotsDirectiveKind = 'nosnippet' | 'max-snippet:0' | 'noai' | 'noimageai'\n\nexport interface RobotsRestrictionDirective {\n /** `robots` for the generic directive, otherwise the crawler token named. */\n agent: string\n source: 'meta' | 'header'\n directive: RestrictedRobotsDirectiveKind\n value: string\n}\n\nexport interface CanonicalDeclaration {\n source: 'header' | 'html'\n url: string\n}\n\nexport interface PageIndexSignals {\n status: number\n finalUrl: string\n redirected: boolean\n /** Every `noindex`/`none` directive found, generic and agent-specific. */\n noindex: NoindexDirective[]\n /** Absolute canonical address the page declares, or null. */\n canonical: string | null\n /** Every `nosnippet`, `max-snippet:0`, `noai`, or `noimageai` directive found. */\n restrictions: RobotsRestrictionDirective[]\n /** True when any `nosnippet` directive was found. */\n nosnippet: boolean\n /** True when any `max-snippet:0` directive was found. */\n maxSnippetZero: boolean\n /** True when any `noai` directive was found. */\n noai: boolean\n /** True when any `noimageai` directive was found. */\n noimageai: boolean\n /** Every resolved canonical declaration across HTTP `Link` headers and HTML `<link>` tags. */\n canonicals: CanonicalDeclaration[]\n /** True when more than one HTML `<link rel=\"canonical\">` or HTTP `Link` canonical header was sent. */\n duplicateCanonical: boolean\n /** True when canonical declarations disagree on their resolved URL (HTML vs HTML or HTTP vs HTML). */\n conflictingCanonical: boolean\n /** True when HTTP 402 Payment Required (e.g. Pay-Per-Crawl) was observed. */\n payPerCrawl: boolean\n}\n\n/** Directive names that may carry a colon themselves (`unavailable_after: …`). */\nconst ROBOTS_DIRECTIVES = new Set([\n 'all',\n 'noindex',\n 'nofollow',\n 'none',\n 'noarchive',\n 'nosnippet',\n 'notranslate',\n 'noimageindex',\n 'unavailable_after',\n 'max-snippet',\n 'max-image-preview',\n 'max-video-preview',\n 'indexifembedded',\n 'noai',\n 'noimageai',\n])\n\n/** Crawler names a page may address by meta name: the ruleset's own tokens plus the two search majors. */\nconst AGENT_META_NAMES: ReadonlySet<string> = new Set(\n [\n ...DEFAULT_RULESET.audienceTokens.assistant,\n ...DEFAULT_RULESET.audienceTokens.training,\n ...DEFAULT_RULESET.audienceTokens.search,\n 'googlebot',\n 'bingbot',\n ].map((token) => token.toLowerCase()),\n)\n\nfunction splitRobotTokens(directives: string): string[] {\n return directives\n .toLowerCase()\n .split(',')\n .map((part) => part.trim())\n .filter((part) => part.length > 0)\n}\n\nfunction blocksIndexing(directives: string): boolean {\n return splitRobotTokens(directives).some((part) => part === 'noindex' || part === 'none')\n}\n\nfunction extractRestrictions(directives: string): RestrictedRobotsDirectiveKind[] {\n const found: RestrictedRobotsDirectiveKind[] = []\n for (const part of splitRobotTokens(directives)) {\n if (part === 'nosnippet') found.push('nosnippet')\n else if (/^max-snippet\\s*:\\s*0$/.test(part)) found.push('max-snippet:0')\n else if (part === 'noai') found.push('noai')\n else if (part === 'noimageai') found.push('noimageai')\n }\n return found\n}\n\ninterface ParsedHeaderRobots {\n noindex: NoindexDirective[]\n restrictions: RobotsRestrictionDirective[]\n}\n\n/** `X-Robots-Tag` values → noindex and restriction directives, splitting the optional `agent:` prefix. */\nfunction parseHeaderRobots(values: readonly string[]): ParsedHeaderRobots {\n const noindex: NoindexDirective[] = []\n const restrictions: RobotsRestrictionDirective[] = []\n for (const value of values) {\n const trimmed = value.trim()\n const prefixed = /^\\s*([A-Za-z0-9_.-]+)\\s*:\\s*(.*)$/.exec(value)\n const prefix = prefixed?.[1]?.toLowerCase()\n let agent = 'robots'\n let directiveBody = value\n if (prefixed !== null && prefix !== undefined && !ROBOTS_DIRECTIVES.has(prefix)) {\n agent = prefix\n directiveBody = prefixed[2] ?? ''\n }\n if (blocksIndexing(directiveBody)) {\n noindex.push({ agent, source: 'header', value: trimmed })\n }\n for (const directive of extractRestrictions(directiveBody)) {\n restrictions.push({ agent, source: 'header', directive, value: trimmed })\n }\n }\n return { noindex, restrictions }\n}\n\nfunction summarizeCanonicals(canonicals: readonly CanonicalDeclaration[]): {\n duplicateCanonical: boolean\n conflictingCanonical: boolean\n} {\n let htmlCount = 0\n let headerCount = 0\n const distinct = new Set<string>()\n for (const entry of canonicals) {\n if (entry.source === 'html') htmlCount++\n else headerCount++\n distinct.add(entry.url)\n }\n return {\n duplicateCanonical: htmlCount > 1 || headerCount > 1,\n conflictingCanonical: distinct.size > 1,\n }\n}\n\n/** Index signals of one response. Pure; reads headers and, when present, the HTML. */\nexport function indexSignalsOf(capture: ArsHttpCapture): PageIndexSignals {\n const parsedHeaders = parseHeaderRobots(headerAll(capture.headers, 'x-robots-tag'))\n const noindex = [...parsedHeaders.noindex]\n const restrictions = [...parsedHeaders.restrictions]\n const canonicals: CanonicalDeclaration[] = []\n\n let canonical: string | null = null\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('canonical')) {\n const resolved = absoluteUrl(link.url, capture.finalUrl)\n if (resolved !== null) {\n canonicals.push({ source: 'header', url: resolved })\n if (canonical === null) canonical = resolved\n }\n }\n }\n\n const representation = buildRepresentation(capture)\n const doc = representation?.doc ?? null\n if (doc !== null) {\n for (const meta of doc.metas) {\n const name = meta.name\n if (name === null || meta.content === null) continue\n const targetAgent = name === 'robots' ? 'robots' : AGENT_META_NAMES.has(name) ? name : null\n if (targetAgent === null) continue\n if (blocksIndexing(meta.content)) {\n noindex.push({ agent: targetAgent, source: 'meta', value: meta.content })\n }\n for (const directive of extractRestrictions(meta.content)) {\n restrictions.push({\n agent: targetAgent,\n source: 'meta',\n directive,\n value: meta.content,\n })\n }\n }\n for (const link of doc.links) {\n if (link.rel.includes('canonical') && link.href !== null) {\n const resolved = absoluteUrl(link.href, capture.finalUrl)\n if (resolved !== null) {\n canonicals.push({ source: 'html', url: resolved })\n if (canonical === null) canonical = resolved\n }\n }\n }\n }\n\n const { duplicateCanonical, conflictingCanonical } = summarizeCanonicals(canonicals)\n\n return {\n status: capture.status,\n finalUrl: capture.finalUrl,\n redirected: capture.redirects.length > 0,\n noindex,\n canonical,\n restrictions,\n nosnippet: restrictions.some((r) => r.directive === 'nosnippet'),\n maxSnippetZero: restrictions.some((r) => r.directive === 'max-snippet:0'),\n noai: restrictions.some((r) => r.directive === 'noai'),\n noimageai: restrictions.some((r) => r.directive === 'noimageai'),\n canonicals,\n duplicateCanonical,\n conflictingCanonical,\n payPerCrawl: capture.status === 402,\n }\n}\n\n/**\n * The page's index signals from a probe bundle: the browser control first (it\n * asked for HTML, which is where `<meta name=\"robots\">` lives), the agent probe\n * otherwise. Null when neither probe returned a response.\n */\nexport function pageIndexSignals(evidence: ArsEvidence): PageIndexSignals | null {\n const browser = evidence.probes.browser.result\n const agent = evidence.probes.agent.result\n const capture = browser.ok ? browser.capture : agent.ok ? agent.capture : null\n if (capture === null) return null\n const signals = indexSignalsOf(capture)\n // The HTML probe can miss a header-only directive, canonical, or 402 Pay-Per-Crawl\n // status that the agent probe received.\n if (browser.ok && agent.ok) {\n const agentRobots = parseHeaderRobots(headerAll(agent.capture.headers, 'x-robots-tag'))\n const seenNoindex = new Set(signals.noindex.map((d) => `${d.agent}|${d.source}|${d.value}`))\n for (const directive of agentRobots.noindex) {\n const key = `${directive.agent}|${directive.source}|${directive.value}`\n if (!seenNoindex.has(key)) {\n seenNoindex.add(key)\n signals.noindex.push(directive)\n }\n }\n\n const seenRestrictions = new Set(\n signals.restrictions.map((d) => `${d.agent}|${d.source}|${d.directive}|${d.value}`),\n )\n for (const directive of agentRobots.restrictions) {\n const key = `${directive.agent}|${directive.source}|${directive.directive}|${directive.value}`\n if (!seenRestrictions.has(key)) {\n seenRestrictions.add(key)\n signals.restrictions.push(directive)\n }\n }\n signals.nosnippet = signals.restrictions.some((r) => r.directive === 'nosnippet')\n signals.maxSnippetZero = signals.restrictions.some((r) => r.directive === 'max-snippet:0')\n signals.noai = signals.restrictions.some((r) => r.directive === 'noai')\n signals.noimageai = signals.restrictions.some((r) => r.directive === 'noimageai')\n\n const seenCanonicals = new Set(signals.canonicals.map((c) => `${c.source}|${c.url}`))\n let canonicalsAdded = false\n for (const link of parseLinkHeaders(headerAll(agent.capture.headers, 'link'))) {\n if (!link.rel.includes('canonical')) continue\n const resolved = absoluteUrl(link.url, agent.capture.finalUrl)\n if (resolved === null) continue\n const key = `header|${resolved}`\n if (!seenCanonicals.has(key)) {\n seenCanonicals.add(key)\n signals.canonicals.push({ source: 'header', url: resolved })\n if (signals.canonical === null) signals.canonical = resolved\n canonicalsAdded = true\n }\n }\n if (canonicalsAdded) {\n const summary = summarizeCanonicals(signals.canonicals)\n signals.duplicateCanonical = summary.duplicateCanonical\n signals.conflictingCanonical = summary.conflictingCanonical\n }\n\n if (agent.capture.status === 402) {\n signals.payPerCrawl = true\n }\n }\n return signals\n}\n\n/* ── SPA / JS-dependency static heuristics (unscored) ─────────────────────── */\n\nexport type SpaJsDependencyReason =\n | 'empty-mount-root'\n | 'noscript-js-required'\n | 'unrendered-next-payload'\n | 'low-text-vs-script'\n\nexport interface SpaJsDependencyReport {\n /** True when static HTML heuristics indicate a JS-dependent SPA shell. */\n readonly likelySpaShell: boolean\n /** Specific heuristic signals that fired. */\n readonly reasons: readonly SpaJsDependencyReason[]\n /** Empty SPA mount roots found (e.g. `['#root']`, `['#__next']`). */\n readonly emptyMountRoots: readonly string[]\n /** True when `<noscript>` carries a boilerplate JavaScript-required message. */\n readonly jsRequiredNoscript: boolean\n /** Matched `<noscript>` text snippet, or null. */\n readonly noscriptSnippet: string | null\n /** True when `<script id=\"__NEXT_DATA__\">` is present. */\n readonly hasNextData: boolean\n /** True when Next.js RSC flight chunks (`__next_f`) appear in inline scripts. */\n readonly hasNextFlight: boolean\n /** Combined UTF-8 bytes of Next.js hydration payloads (`__NEXT_DATA__` / `__next_f`). */\n readonly hydrationPayloadBytes: number\n /** True when Next.js hydration payload appears to carry unrendered page content. */\n readonly unrenderedHydrationPayload: boolean\n /** Visible body word count (excluding `<title>`, `<noscript>`, `<script>`, `<style>`, hidden). */\n readonly visibleWordCount: number\n /** UTF-8 byte length of visible body text. */\n readonly visibleTextBytes: number\n /** Total UTF-8 byte length of non-JSON-LD inline `<script>` contents. */\n readonly scriptBytes: number\n /** Number of external `<script src=\"...\">` tags. */\n readonly externalScriptCount: number\n /** Ratio of inline script bytes to visible text bytes, or `null` when visible text is empty and scripts exist. */\n readonly scriptToTextRatio: number | null\n /** True when visible word count is low relative to script payload. */\n readonly lowTextToScriptRatio: boolean\n}\n\nconst SPA_MOUNT_ROOT_IDS = new Set(['root', 'app', '__next', '__nuxt'])\n\nconst NOSCRIPT_JS_PATTERNS: readonly RegExp[] = [\n /\\benable\\s+javascript\\b/i,\n /\\bjavascript\\s+(?:is\\s+required|must\\s+be\\s+enabled|is\\s+disabled)\\b/i,\n /\\brequires?\\s+javascript\\b/i,\n /\\bturn\\s+on\\s+javascript\\b/i,\n /\\bwithout\\s+javascript\\b/i,\n /\\bdoes\\s+not\\s+support\\s+javascript\\b/i,\n /\\bneed\\s+javascript\\b/i,\n]\n\nfunction hasAncestorTag(doc: HtmlDocument, startIndex: number, tags: ReadonlySet<string>): boolean {\n let current = startIndex\n for (let hops = 0; hops < 128 && current >= 0; hops++) {\n const el = doc.elements[current]\n if (el === undefined) break\n if (tags.has(el.tag)) return true\n current = el.parent\n }\n return false\n}\n\nconst NON_BODY_TEXT_TAGS = new Set(['title', 'noscript'])\n\n/**\n * Static HTML heuristics for client-side SPA shells and JS-only rendering:\n * empty `#root`/`#app`/`#__next` mount roots, boilerplate JS-required\n * `<noscript>` notices, Next.js `__NEXT_DATA__`/`__next_f` unrendered payload\n * clues, and low visible word count relative to script bytes. Pure, non-executing,\n * unscored.\n */\nexport function detectSpaJsDependency(html: string): SpaJsDependencyReport {\n const doc = tokenizeHtml(html)\n\n // 1. Empty mount roots\n const emptyMountRoots: string[] = []\n for (const el of doc.elements) {\n const id = el.attrs['id']?.trim().toLowerCase()\n if (id === undefined || !SPA_MOUNT_ROOT_IDS.has(id)) continue\n const text = elementText(doc, el.index)\n if (text.length === 0) {\n const selector = `#${el.attrs['id']?.trim() ?? id}`\n if (!emptyMountRoots.includes(selector)) emptyMountRoots.push(selector)\n }\n }\n\n // 2. Boilerplate JS-required <noscript>\n let jsRequiredNoscript = false\n let noscriptSnippet: string | null = null\n for (const el of doc.elements) {\n if (el.tag !== 'noscript') continue\n const text = elementText(doc, el.index)\n if (text.length === 0) continue\n if (NOSCRIPT_JS_PATTERNS.some((pattern) => pattern.test(text))) {\n jsRequiredNoscript = true\n if (noscriptSnippet === null) noscriptSnippet = text.slice(0, 200)\n }\n }\n\n // 3. Visible body text (excluding <title> and <noscript>)\n const visibleParts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (hasAncestorTag(doc, node.parent, NON_BODY_TEXT_TAGS)) continue\n visibleParts.push(node.text)\n }\n const visibleBodyText = visibleParts.join(' ').replace(/\\s+/g, ' ').trim()\n const visibleWordCount =\n visibleBodyText.length === 0 ? 0 : visibleBodyText.split(/\\s+/).filter(Boolean).length\n const visibleTextBytes = utf8Length(visibleBodyText)\n\n // 4. Inline JS bytes, external scripts, and Next.js hydration payloads\n let scriptBytes = 0\n let externalScriptCount = 0\n let hasNextData = false\n let hasNextFlight = false\n let hydrationPayloadBytes = 0\n\n const nextDataElements = new Set<number>()\n for (const el of doc.elements) {\n if (el.tag !== 'script') continue\n const typeAttr = el.attrs['type']?.trim().toLowerCase() ?? ''\n if (typeAttr === 'application/ld+json') continue\n if (typeof el.attrs['src'] === 'string' && el.attrs['src'].trim().length > 0) {\n externalScriptCount++\n }\n if (el.attrs['id']?.trim().toLowerCase() === '__next_data__') {\n hasNextData = true\n nextDataElements.add(el.index)\n }\n }\n\n for (const node of doc.texts) {\n if (node.excludedBy !== 'script') continue\n scriptBytes += node.bytes\n if (nextDataElements.has(node.parent)) {\n hydrationPayloadBytes += node.bytes\n } else if (node.text.includes('__next_f')) {\n hasNextFlight = true\n hydrationPayloadBytes += node.bytes\n }\n }\n\n const unrenderedHydrationPayload =\n (hasNextData || hasNextFlight) &&\n hydrationPayloadBytes >= 1024 &&\n (visibleWordCount < 50 ||\n (visibleWordCount < 100 && visibleTextBytes > 0 && hydrationPayloadBytes / visibleTextBytes >= 4))\n\n const scriptToTextRatio =\n visibleTextBytes > 0\n ? Number((scriptBytes / visibleTextBytes).toFixed(2))\n : scriptBytes > 0\n ? null\n : 0\n\n const lowTextToScriptRatio =\n (visibleWordCount < 40 && (scriptBytes >= 2048 || externalScriptCount >= 2)) ||\n (visibleWordCount < 80 && visibleTextBytes > 0 && scriptBytes / visibleTextBytes >= 20)\n\n const reasons: SpaJsDependencyReason[] = []\n if (emptyMountRoots.length > 0) reasons.push('empty-mount-root')\n if (jsRequiredNoscript) reasons.push('noscript-js-required')\n if (unrenderedHydrationPayload) reasons.push('unrendered-next-payload')\n if (lowTextToScriptRatio) reasons.push('low-text-vs-script')\n\n const likelySpaShell =\n (emptyMountRoots.length > 0 && visibleWordCount < 50) ||\n (jsRequiredNoscript && visibleWordCount < 80) ||\n unrenderedHydrationPayload ||\n reasons.length >= 2\n\n return {\n likelySpaShell,\n reasons,\n emptyMountRoots,\n jsRequiredNoscript,\n noscriptSnippet,\n hasNextData,\n hasNextFlight,\n hydrationPayloadBytes,\n unrenderedHydrationPayload,\n visibleWordCount,\n visibleTextBytes,\n scriptBytes,\n externalScriptCount,\n scriptToTextRatio,\n lowTextToScriptRatio,\n }\n}\n\n/* ── multi-tier SaaS pricing & feature-limit auditor (unscored) ───────────── */\n\nexport const SAAS_QUOTA_UNITS = [\n 'seats',\n 'users',\n 'projects',\n 'pages',\n 'sites',\n 'requests',\n 'tokens',\n 'credits',\n 'calls',\n 'events',\n 'contacts',\n 'workspaces',\n 'domains',\n 'rows',\n] as const\n\nexport type SaasQuotaUnit = (typeof SAAS_QUOTA_UNITS)[number]\n\nconst QUOTA_UNIT_CANONICAL: Readonly<Record<string, SaasQuotaUnit>> = {\n seat: 'seats',\n seats: 'seats',\n user: 'users',\n users: 'users',\n project: 'projects',\n projects: 'projects',\n page: 'pages',\n pages: 'pages',\n site: 'sites',\n sites: 'sites',\n request: 'requests',\n requests: 'requests',\n token: 'tokens',\n tokens: 'tokens',\n credit: 'credits',\n credits: 'credits',\n call: 'calls',\n calls: 'calls',\n event: 'events',\n events: 'events',\n contact: 'contacts',\n contacts: 'contacts',\n workspace: 'workspaces',\n workspaces: 'workspaces',\n domain: 'domains',\n domains: 'domains',\n row: 'rows',\n rows: 'rows',\n}\n\nexport interface PricingAuditJsonLdNode {\n readonly types: readonly string[]\n readonly value: Readonly<Record<string, unknown>>\n}\n\nexport interface PricingAndLimitsAudit {\n /** Number of schema.org `Offer` nodes found in JSON-LD. */\n readonly jsonLdOfferCount: number\n /** Number of schema.org `Offer` nodes declaring a price or priceSpecification. */\n readonly jsonLdPricedOfferCount: number\n /** Estimated number of visible pricing tiers in server HTML. */\n readonly visibleTierCount: number\n /** Total visible currency price occurrences found in server HTML. */\n readonly visiblePriceCount: number\n /** True when a feature comparison table contains icon-only SVG/empty-text cells. */\n readonly iconOnlyFeatureMatrix: boolean\n /** Count of icon-only / empty-text cells inside comparison tables. */\n readonly iconOnlyCellCount: number\n /** True when server HTML includes a monthly/annual billing toggle hint. */\n readonly hasBillingToggleHint: boolean\n /** True when a billing toggle hint is present but only one billing period appears in server HTML. */\n readonly billingToggleSinglePeriodOnly: boolean\n /** Distinct billing cadences extracted from visible text (e.g. '/mo', '/yr', 'per seat', 'billed annually'). */\n readonly billingCadences: readonly string[]\n /** Total quantified SaaS feature-limit mentions across the 14 canonical quota units. */\n readonly featureLimitCount: number\n /** Per-unit counts for detected SaaS feature-limit quotas. */\n readonly featureLimitUnits: Readonly<Partial<Record<SaasQuotaUnit, number>>>\n /** Distinct canonical quota units detected. */\n readonly detectedQuotaUnits: readonly SaasQuotaUnit[]\n}\n\nconst PRICE_TOKEN_PATTERN = /(?:[$€£¥] ?\\d[\\d,.]*|\\b(?:USD|EUR|GBP|CAD|AUD) \\d[\\d,.]*)/gi\n\nconst TIER_CONTAINER_TAGS = new Set(['article', 'section', 'div', 'li'])\nconst TIER_ATTR_HINT = /(?:^|[-_\\s])(plan|tier|pricing[-_]?card|price[-_]?card|package)(?:$|[-_\\s])/i\nconst TIER_TEXT_HINT = /\\b(?:free|custom pricing|custom|contact sales|enterprise|talk to sales)\\b/i\n\nconst ICON_CLASS_HINT = /(?:icon|check|tick|cross|dash|minus|yes|no|fa-|lucide|heroicon|badge)/i\n\nconst TOGGLE_ELEMENT_TAGS = new Set(['button', 'input', 'label', 'select', 'div', 'span', 'fieldset'])\nconst ANNUAL_PRICE_CONTEXT = /\\b(?:billed (?:annually|yearly)|annual billing|per year|annually|yearly)\\b|\\/(?:yr|year)\\b/i\nconst MONTHLY_PRICE_CONTEXT = /\\b(?:billed monthly|monthly billing|per month|monthly)\\b|\\/(?:mo|month)\\b/i\n\nconst CADENCE_PATTERNS: readonly RegExp[] = [\n /\\/(?:mo|month|yr|year|quarter|week|day|seat|user|member)\\b/gi,\n /\\bper (?:month|mo|year|yr|quarter|week|day|hour|seat|user|member|workspace|project|site|domain|request|call|credit|token|contact|unit)\\b/gi,\n /\\bbilled (?:annually|yearly|monthly|quarterly)\\b/gi,\n /\\bone-time\\b/gi,\n]\n\nconst QUOTA_MODIFIER_WORDS = new Set([\n 'active',\n 'custom',\n 'monthly',\n 'annual',\n 'api',\n 'team',\n 'tracked',\n 'monitored',\n 'included',\n 'free',\n 'extra',\n 'total',\n 'concurrent',\n 'unique',\n])\n\nconst QUOTA_QUANTITY_TOKEN = /^(?:unlimited|\\d[\\d,.]*[kmb]?\\+?)$/i\n\nconst QUOTA_VALUE_CELL = /^(?:unlimited|up to \\d[\\d,.]*[kmb]?|\\d[\\d,.]*[kmb]?\\+?)$/i\n\nfunction isAncestorOf(doc: HtmlDocument, ancestor: number, descendant: number): boolean {\n let current = descendant\n for (let hops = 0; hops < 128 && current >= 0; hops++) {\n if (current === ancestor) return true\n current = doc.elements[current]?.parent ?? -1\n }\n return false\n}\n\nfunction collectOfferRecords(\n nodes: readonly PricingAuditJsonLdNode[],\n): Readonly<Record<string, unknown>>[] {\n const offers: Readonly<Record<string, unknown>>[] = []\n const seen = new Set<object>()\n\n const visit = (obj: unknown, depth: number): void => {\n if (depth > 8 || obj === null || typeof obj !== 'object') return\n if (Array.isArray(obj)) {\n for (const item of obj) visit(item, depth + 1)\n return\n }\n if (seen.has(obj)) return\n seen.add(obj)\n const rec = obj as Record<string, unknown>\n const rawType = rec['@type']\n const types =\n typeof rawType === 'string'\n ? [rawType.replace(/^https?:\\/\\/schema\\.org\\//, '')]\n : Array.isArray(rawType)\n ? rawType\n .filter((t): t is string => typeof t === 'string')\n .map((t) => t.replace(/^https?:\\/\\/schema\\.org\\//, ''))\n : []\n if (types.includes('Offer')) offers.push(rec)\n if (rec['offers'] !== undefined) visit(rec['offers'], depth + 1)\n }\n\n for (const node of nodes) {\n if (!seen.has(node.value)) {\n seen.add(node.value)\n if (node.types.includes('Offer')) offers.push(node.value)\n }\n if (node.value['offers'] !== undefined) visit(node.value['offers'], 1)\n }\n return offers\n}\n\nfunction hasOfferPrice(offer: Readonly<Record<string, unknown>>): boolean {\n if (offer['price'] !== undefined && offer['price'] !== null && String(offer['price']).trim() !== '') {\n return true\n }\n const spec = offer['priceSpecification']\n const specs = Array.isArray(spec) ? spec : spec !== undefined && spec !== null ? [spec] : []\n return specs.some((entry) => {\n if (entry === null || typeof entry !== 'object') return false\n const record = entry as Record<string, unknown>\n return (\n (record['price'] !== undefined && String(record['price']).trim() !== '') ||\n (record['minPrice'] !== undefined && String(record['minPrice']).trim() !== '')\n )\n })\n}\n\nfunction normalizePriceMatch(raw: string): string {\n return raw.replace(/[.,]+$/, '').replace(/\\s+/g, '').toUpperCase()\n}\n\nfunction directChildrenOfTag(doc: HtmlDocument, parentIndex: number, tag: string): HtmlElement[] {\n const out: HtmlElement[] = []\n for (const el of doc.elements) {\n if (el.parent === parentIndex && el.tag === tag) out.push(el)\n }\n return out\n}\n\nfunction descendantsOf(doc: HtmlDocument, ancestorIndex: number): HtmlElement[] {\n const out: HtmlElement[] = []\n for (let i = ancestorIndex + 1; i < doc.elements.length; i++) {\n const el = doc.elements[i]\n if (el === undefined) continue\n if (el.depth <= (doc.elements[ancestorIndex]?.depth ?? 0)) break\n if (isAncestorOf(doc, ancestorIndex, el.index)) out.push(el)\n }\n return out\n}\n\nfunction quotaUnitFromLabel(label: string): SaasQuotaUnit | null {\n const words = label\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ')\n .split(/\\s+/)\n .filter(Boolean)\n for (const word of words) {\n const mapped = QUOTA_UNIT_CANONICAL[word]\n if (mapped !== undefined) return mapped\n }\n return null\n}\n\n/**\n * Multi-tier SaaS pricing & feature-limit auditor over server HTML and JSON-LD.\n * Pure, non-executing, unscored: inspects Offer coverage, visible tiers,\n * icon-only comparison matrix cells, single-period billing toggle hints,\n * billing cadences, and quantified SaaS feature-limit quota units.\n */\nexport function auditPricingAndLimits(\n html: string,\n jsonLdNodes?: readonly PricingAuditJsonLdNode[],\n): PricingAndLimitsAudit {\n const doc = tokenizeHtml(html)\n const nodes: readonly PricingAuditJsonLdNode[] =\n jsonLdNodes !== undefined ? jsonLdNodes : parseJsonLd(doc.jsonLd).nodes\n\n // 1. JSON-LD Offers\n const offerRecords = collectOfferRecords(nodes)\n const jsonLdOfferCount = offerRecords.length\n const jsonLdPricedOfferCount = offerRecords.filter(hasOfferPrice).length\n\n // 2. Visible text & prices\n const visibleParts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (hasAncestorTag(doc, node.parent, NON_BODY_TEXT_TAGS)) continue\n visibleParts.push(node.text)\n }\n const visibleText = visibleParts.join(' ').replace(/\\s+/g, ' ').trim()\n\n const priceMatches: { raw: string; index: number }[] = []\n PRICE_TOKEN_PATTERN.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = PRICE_TOKEN_PATTERN.exec(visibleText)) !== null) {\n priceMatches.push({ raw: match[0], index: match.index })\n }\n const visiblePriceCount = priceMatches.length\n const distinctVisiblePriceCount = new Set(priceMatches.map((m) => normalizePriceMatch(m.raw))).size\n\n // 3. Pricing card containers (leaf-most card elements)\n const candidateCards: HtmlElement[] = []\n for (const el of doc.elements) {\n if (!TIER_CONTAINER_TAGS.has(el.tag) || el.excludedBy !== null) continue\n const hasDataPlan =\n el.attrs['data-plan'] !== undefined ||\n el.attrs['data-tier'] !== undefined ||\n el.attrs['data-pricing-tier'] !== undefined\n const hintStr = `${el.attrs['class'] ?? ''} ${el.attrs['id'] ?? ''}`\n if (!hasDataPlan && !TIER_ATTR_HINT.test(hintStr)) continue\n const text = elementText(doc, el.index)\n if (text.length === 0) continue\n PRICE_TOKEN_PATTERN.lastIndex = 0\n if (PRICE_TOKEN_PATTERN.test(text) || TIER_TEXT_HINT.test(text)) {\n candidateCards.push(el)\n }\n }\n const leafCards = candidateCards.filter(\n (card) => !candidateCards.some((other) => other.index !== card.index && isAncestorOf(doc, card.index, other.index)),\n )\n\n // 4. Tables: icon-only feature matrix cells, pricing table tier columns, and quota rows\n let iconOnlyCellCount = 0\n let pricingTableTierCount = 0\n const unitCounts: Partial<Record<SaasQuotaUnit, number>> = {}\n\n const incrementUnit = (unit: SaasQuotaUnit): void => {\n unitCounts[unit] = (unitCounts[unit] ?? 0) + 1\n }\n\n for (const el of doc.elements) {\n if (el.tag !== 'table' || el.excludedBy !== null) continue\n const tableDescendants = descendantsOf(doc, el.index)\n const rows = tableDescendants.filter((child) => child.tag === 'tr')\n if (rows.length === 0) continue\n\n const tableText = elementText(doc, el.index)\n PRICE_TOKEN_PATTERN.lastIndex = 0\n const tableHasPrices = PRICE_TOKEN_PATTERN.test(tableText)\n\n for (const row of rows) {\n const cells = [\n ...directChildrenOfTag(doc, row.index, 'th'),\n ...directChildrenOfTag(doc, row.index, 'td'),\n ].sort((a, b) => a.index - b.index)\n\n if (cells.length >= 3 && tableHasPrices) {\n const thCount = cells.filter((c) => c.tag === 'th').length\n if (thCount >= 3) {\n pricingTableTierCount = Math.max(pricingTableTierCount, thCount - 1)\n }\n }\n\n // Check row-label quota cells: `<tr><td>Seats</td><td>1</td><td>25</td></tr>`\n const firstCell = cells[0]\n const rowQuotaUnit =\n firstCell !== undefined && cells.length >= 2\n ? quotaUnitFromLabel(elementText(doc, firstCell.index))\n : null\n\n for (let cellIdx = 0; cellIdx < cells.length; cellIdx++) {\n const cell = cells[cellIdx]\n if (cell === undefined || cell.tag !== 'td') continue\n const cellText = elementText(doc, cell.index)\n\n if (cellIdx > 0 && rowQuotaUnit !== null && QUOTA_VALUE_CELL.test(cellText)) {\n incrementUnit(rowQuotaUnit)\n }\n\n if (cells.length >= 2 && cellText.length === 0) {\n const cellDescendants = descendantsOf(doc, cell.index)\n const hasIconOnly = cellDescendants.some((desc) => {\n if (desc.tag === 'svg') return true\n if (desc.tag === 'img' && (desc.attrs['alt'] ?? '').trim().length === 0) return true\n if (\n (desc.tag === 'i' || desc.tag === 'span') &&\n ICON_CLASS_HINT.test(desc.attrs['class'] ?? '')\n ) {\n return true\n }\n return false\n })\n if (hasIconOnly) iconOnlyCellCount++\n }\n }\n }\n }\n\n const visibleTierCount = Math.max(leafCards.length, pricingTableTierCount, distinctVisiblePriceCount)\n const iconOnlyFeatureMatrix = iconOnlyCellCount > 0\n\n // 5. Billing toggle hints & single-period detection\n let hasBillingToggleHint = false\n let sawMonthlyControl = false\n let sawAnnualControl = false\n\n for (const el of doc.elements) {\n if (!TOGGLE_ELEMENT_TAGS.has(el.tag) || el.excludedBy !== null) continue\n const role = el.attrs['role']?.toLowerCase() ?? ''\n const isInteractive =\n el.tag === 'button' ||\n el.tag === 'input' ||\n el.tag === 'label' ||\n el.tag === 'select' ||\n role === 'switch' ||\n role === 'tab' ||\n role === 'tablist' ||\n role === 'radiogroup'\n if (!isInteractive) continue\n\n const labelText = [\n elementText(doc, el.index),\n el.attrs['aria-label'] ?? '',\n el.attrs['name'] ?? '',\n el.attrs['id'] ?? '',\n el.attrs['data-billing'] ?? '',\n el.attrs['data-period'] ?? '',\n ]\n .join(' ')\n .toLowerCase()\n\n const hasMonthly = /\\b(?:monthly|month)\\b/.test(labelText)\n const hasAnnual = /\\b(?:annual(?:ly)?|yearly|year)\\b/.test(labelText)\n if (hasMonthly && hasAnnual) {\n hasBillingToggleHint = true\n break\n }\n if (hasMonthly) sawMonthlyControl = true\n if (hasAnnual) sawAnnualControl = true\n }\n if (sawMonthlyControl && sawAnnualControl) hasBillingToggleHint = true\n\n let monthlyPricePresent = false\n let annualPricePresent = false\n for (let i = 0; i < priceMatches.length; i++) {\n const pm = priceMatches[i]\n if (pm === undefined) continue\n const nextPriceIndex = priceMatches[i + 1]?.index ?? visibleText.length\n const contextEnd = Math.min(nextPriceIndex, pm.index + 48)\n const context = visibleText.slice(pm.index, contextEnd)\n if (ANNUAL_PRICE_CONTEXT.test(context)) {\n annualPricePresent = true\n } else if (MONTHLY_PRICE_CONTEXT.test(context)) {\n monthlyPricePresent = true\n }\n }\n\n const billingToggleSinglePeriodOnly =\n hasBillingToggleHint && monthlyPricePresent !== annualPricePresent\n\n // 6. Billing cadences\n const billingCadences: string[] = []\n const seenCadences = new Set<string>()\n for (const pattern of CADENCE_PATTERNS) {\n pattern.lastIndex = 0\n let cadenceMatch: RegExpExecArray | null\n while ((cadenceMatch = pattern.exec(visibleText)) !== null) {\n const normalized = cadenceMatch[0].replace(/\\s+/g, ' ').trim().toLowerCase()\n if (normalized.length > 0 && !seenCadences.has(normalized)) {\n seenCadences.add(normalized)\n billingCadences.push(normalized)\n }\n }\n }\n\n // 7. Inline quantified SaaS feature-limit quota units (linear token scan)\n const words = visibleText\n .toLowerCase()\n .split(/[^a-z0-9.,+]+/)\n .map((token) => token.replace(/^[.,]+/, '').replace(/[.,]+$/, ''))\n .filter((token) => token.length > 0)\n for (let i = 0; i + 1 < words.length; i++) {\n const qty = words[i]\n if (qty === undefined || !QUOTA_QUANTITY_TOKEN.test(qty)) continue\n const next = words[i + 1]\n if (next === undefined) continue\n const direct = QUOTA_UNIT_CANONICAL[next]\n if (direct !== undefined) {\n incrementUnit(direct)\n i += 1\n continue\n }\n if (QUOTA_MODIFIER_WORDS.has(next)) {\n const after = words[i + 2]\n const modified = after !== undefined ? QUOTA_UNIT_CANONICAL[after] : undefined\n if (modified !== undefined) {\n incrementUnit(modified)\n i += 2\n }\n }\n }\n\n const detectedQuotaUnits = SAAS_QUOTA_UNITS.filter((unit) => (unitCounts[unit] ?? 0) > 0)\n const featureLimitCount = detectedQuotaUnits.reduce((sum, unit) => sum + (unitCounts[unit] ?? 0), 0)\n\n return {\n jsonLdOfferCount,\n jsonLdPricedOfferCount,\n visibleTierCount,\n visiblePriceCount,\n iconOnlyFeatureMatrix,\n iconOnlyCellCount,\n hasBillingToggleHint,\n billingToggleSinglePeriodOnly,\n billingCadences,\n featureLimitCount,\n featureLimitUnits: unitCounts,\n detectedQuotaUnits,\n }\n}\n\n/* ── declared facts, read for the site report ─────────────────────────────── */\n\nexport interface DeclaredPageFacts {\n /** The modified date the page itself states (ISO 8601), or null. */\n updated: string | null\n /** Where each price the page states was found; empty when no price was readable. */\n priceSources: ArsFactSource[]\n}\n\n/**\n * The extractor's own `updated` and `price` facts, read with a profile that asks\n * for exactly those two, whatever kind the page was classified as. `score()`\n * extracts against the page kind's profile (an `unknown` page never yields a\n * price), so these values are taken separately and never feed a score.\n */\nexport function declaredPageFacts(evidence: ArsEvidence): DeclaredPageFacts | null {\n const browser = evidence.probes.browser.result\n const agent = evidence.probes.agent.result\n const capture = browser.ok ? browser.capture : agent.ok ? agent.capture : null\n if (capture === null) return null\n const representation = buildRepresentation(capture)\n if (representation === null) return null\n const extract = (kinds: ArsFactKind[], currencyHint: string | undefined) => {\n const profile: ArsFactProfile = {\n pageKind: 'unknown',\n core: kinds,\n extended: [],\n byteReference: DEFAULT_RULESET.maxBodyBytes,\n }\n return extractFacts(representation, {\n profile,\n ruleset: DEFAULT_RULESET,\n baseUrl: capture.finalUrl,\n origin: evidence.target.origin,\n currencyHint,\n })\n }\n // The currency the page declares disambiguates a bare `29.00`, as in score().\n const currency = extract(['currency'], undefined).find((fact) => fact.kind === 'currency')\n const facts = extract(['updated', 'price'], currency?.normalized)\n let updated: string | null = null\n const priceSources: ArsFactSource[] = []\n for (const fact of facts) {\n if (fact.kind === 'updated' && updated === null) updated = fact.normalized\n if (fact.kind === 'price' && !priceSources.includes(fact.source)) priceSources.push(fact.source)\n }\n return { updated, priceSources }\n}\n","/**\n * probe/limiter.ts — politeness, as a thing you have to hold rather than a thing\n * you have to remember.\n *\n * WHY IT LIVES IN THE PACKAGE. Every consumer of `./probe` — the hosted scanner,\n * the CLI, the MCP server on a stranger's laptop — puts OUR user agent on OUR\n * domain in front of somebody else's origin. A limiter that each consumer is\n * asked to remember to install is a limiter that one of them ships without.\n * `ProbePolicy.limiter` is therefore required, not optional: there is no code\n * path through `probeStrict` that does not take a lease first.\n *\n * WHY IT IS INJECTED AND NEVER MODULE-GLOBAL. Module state is exactly right in a\n * CLI process — one run, one budget, exit — and exactly wrong in a warm\n * serverless instance, where a module-level counter is shared by every request\n * the container ever serves. A 20-probe soft cap implemented as a module global\n * would work perfectly in testing and then, on the twenty-first scan of an\n * instance's life, start refusing unrelated users with no signal that anything\n * had changed. So the limiter is constructed by the caller, scoped to whatever\n * the caller means by \"a run\", and passed in.\n *\n * DEFAULTS (design §5.2): 1 concurrent probe per host, 2 globally, ≥1s between\n * probes to the same host, ~20 probes per run and then an explicit override.\n * \"Probe\" here means one HTTP request, which is the unit an origin experiences.\n * A cold single-URL scan is 5 requests (§3.3: robots, agent, browser, llms.txt,\n * .well-known/ucp), so the default budget is about four cold URLs — a deliberate\n * floor that a multi-URL CLI run raises on purpose by passing `maxProbesPerRun`.\n *\n * NOTHING HERE IS PURE, and it does not have to be: the ESLint purity rule\n * exempts `src/probe/**`. `now` and `sleep` are injectable so the tests do not\n * spend real seconds proving that a one-second gap is a one-second gap.\n */\n\nexport interface LimiterLease {\n /** Idempotent. Releases the host and global slots and starts the host's cooldown. */\n release(): void\n}\n\nexport interface Limiter {\n /** Resolves when it is polite to send. Rejects with `ProbeBudgetExceededError`. */\n acquire(host: string): Promise<LimiterLease>\n /** Requests started in this run, including ones still in flight. */\n readonly used: number\n /** The soft cap this limiter was constructed with. */\n readonly budget: number\n}\n\n/**\n * Thrown by `acquire` when the run budget is spent. A distinct type because the\n * caller has to be able to tell \"we chose not to send this\" from \"the origin\n * did not answer\" — the CLI maps them to different exit codes (4 vs 3) and\n * confusing the two deletes a CI check within a week (design §5.6).\n */\nexport class ProbeBudgetExceededError extends Error {\n readonly budget: number\n\n constructor(budget: number) {\n super(\n `rebilder-ars: probe budget exhausted (${budget} requests this run). ` +\n 'Raise it explicitly with createLimiter({ maxProbesPerRun }) — it is a soft cap, not a hard one, ' +\n 'and raising it should be a decision someone made on purpose.',\n )\n this.name = 'ProbeBudgetExceededError'\n this.budget = budget\n }\n}\n\nexport interface LimiterOptions {\n /** Default 1. Two concurrent requests to one origin is not a probe, it is a load test. */\n maxConcurrentPerHost?: number\n /** Default 2. */\n maxConcurrentGlobal?: number\n /** Default 1000ms, measured from the release of the previous lease for that host. */\n minIntervalPerHostMs?: number\n /** Default 20 requests. The explicit override is passing a different number here. */\n maxProbesPerRun?: number\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n}\n\nconst DEFAULTS = {\n maxConcurrentPerHost: 1,\n maxConcurrentGlobal: 2,\n minIntervalPerHostMs: 1_000,\n maxProbesPerRun: 20,\n} as const\n\ninterface Semaphore {\n acquire(): Promise<void>\n release(): void\n}\n\n/**\n * Slot-transferring semaphore. `release` hands the slot straight to the next\n * waiter instead of decrementing and letting a fresh caller race in through the\n * fast path — the classic way a \"limit 1\" semaphore lets two through.\n */\nfunction semaphore(limit: number): Semaphore {\n let active = 0\n const waiting: (() => void)[] = []\n return {\n acquire(): Promise<void> {\n if (active < limit) {\n active += 1\n return Promise.resolve()\n }\n return new Promise<void>((resolve) => waiting.push(resolve))\n },\n release(): void {\n const next = waiting.shift()\n if (next) next()\n else active = Math.max(0, active - 1)\n },\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> =>\n ms <= 0 ? Promise.resolve() : new Promise<void>((resolve) => setTimeout(resolve, ms))\n\n/**\n * Builds a limiter scoped to one \"run\" — one CLI invocation, one MCP session,\n * one scan job. Acquisition order is global-then-host in every path, so two\n * hosts can never deadlock each other.\n */\nexport function createLimiter(options: LimiterOptions = {}): Limiter {\n const maxConcurrentPerHost = options.maxConcurrentPerHost ?? DEFAULTS.maxConcurrentPerHost\n const maxConcurrentGlobal = options.maxConcurrentGlobal ?? DEFAULTS.maxConcurrentGlobal\n const minIntervalPerHostMs = options.minIntervalPerHostMs ?? DEFAULTS.minIntervalPerHostMs\n const budget = options.maxProbesPerRun ?? DEFAULTS.maxProbesPerRun\n const now = options.now ?? (() => Date.now())\n const sleep = options.sleep ?? defaultSleep\n\n const global = semaphore(Math.max(1, maxConcurrentGlobal))\n const perHost = new Map<string, Semaphore>()\n const nextAllowedAt = new Map<string, number>()\n let used = 0\n\n const hostSemaphore = (host: string): Semaphore => {\n const existing = perHost.get(host)\n if (existing) return existing\n const created = semaphore(Math.max(1, maxConcurrentPerHost))\n perHost.set(host, created)\n return created\n }\n\n return {\n get used() {\n return used\n },\n get budget() {\n return budget\n },\n async acquire(host: string): Promise<LimiterLease> {\n if (used >= budget) throw new ProbeBudgetExceededError(budget)\n used += 1\n\n const key = host.toLowerCase()\n const host$ = hostSemaphore(key)\n await global.acquire()\n try {\n await host$.acquire()\n } catch (error) {\n global.release()\n throw error\n }\n\n const wait = (nextAllowedAt.get(key) ?? 0) - now()\n if (wait > 0) await sleep(wait)\n\n let released = false\n return {\n release(): void {\n if (released) return\n released = true\n nextAllowedAt.set(key, now() + minIntervalPerHostMs)\n host$.release()\n global.release()\n },\n }\n },\n }\n}\n","/**\n * probe/index.ts — `\"./probe\"`. The server-only, deliberately impure half.\n *\n * The pure half (`.`) consumes exactly one thing: an `ArsEvidence` bundle. This\n * file is the only sanctioned way to produce one from a live origin. Everything\n * non-deterministic in ARS is here — sockets, DNS, the clock, sleeping — and\n * nothing here influences a score except through the bundle it returns. The\n * ESLint purity rule in `eslint.config.mjs` exempts `src/probe/**`, and only\n * `src/probe/**`; nothing that needs a clock or a socket may move up a directory.\n *\n * THE REQUEST SET IS CLOSED (§3.3). Per URL: an **agent probe** and a **browser\n * control** that differ in the `Accept` header AND IN NOTHING ELSE — same User\n * Agent, same everything. That is what makes the D2.4 parity check meaningful and\n * what stops a correctly installed gateway, which negotiates on `Accept` and not\n * on UA, from being scored as a cloaker. ARS 0.3 adds one conditional request:\n * when the agent probe got HTML and the page declares a Markdown copy at another\n * same-origin address, that one address is fetched with the agent's headers\n * (`markdownAlternateTarget` in `../score` decides which, for the probe and the\n * scorer alike). Per origin: `/robots.txt` (first), `/llms.txt`,\n * `/.well-known/ucp`. Nothing else. No guessing `/sitemap.xml`,\n * `/mcp`, `/acp` — credit for an endpoint comes from *declaring* it, because an\n * endpoint an agent cannot find is an endpoint that does not exist. The three\n * probed paths are the disclosed exception: published conventions at published\n * locations.\n *\n * WE IMITATE AGENT INTENT, NEVER AGENT IDENTITY. `assertIdentities` refuses a\n * User-Agent that names somebody else's crawler and refuses an agent/browser\n * pair whose UAs differ. The printed consequence, which belongs next to the\n * parity check and not in a footnote: ARS cannot detect UA-targeted cloaking,\n * including cloaking aimed at `rebilder-ars` itself.\n *\n * THE TWO DEFECTS THIS FILE EXISTS TO CLOSE (design §5.2):\n * - **DNS.** The ancestor guard rejected IP literals and resolved nothing. See\n * `./ssrf`: we resolve, we reject if any answer is reserved, we connect\n * pinned to the validated address, and we re-resolve and re-pin on every hop.\n * - **Byte cap.** The ancestor called `await response.text()` with no limit.\n * Bodies are streamed through `getReader()`, decoded bytes are counted, the\n * read is aborted at the ruleset's 2 MiB and `truncated: true` is recorded.\n * Silently scoring a truncated body would make the heaviest pages score best\n * on D3.2 — the one number the product is built on.\n *\n * WHAT THIS FILE DOES NOT DO. It does not take the §3.8 parity-confirm probe\n * (`probes.parityConfirm` is always `null` here): that one is taken ≥30s after a\n * divergence is detected, which is a scan-orchestration decision, not something\n * to hide inside a call with a 5s budget. It does not cache; caching is the\n * caller's, because the cache key is the caller's. And it does not decide what a\n * result means — `score()` does, from the bundle alone.\n */\n\nimport type {\n ArsEvidence,\n ArsHttpCapture,\n ArsProbeError,\n ArsProbeRecord,\n ArsRuleset,\n ArsVantage,\n} from '../types'\nimport { DEFAULT_RULESET } from '../ruleset'\nimport { utf8Length } from '../extract'\nimport { ARS_ROBOTS_TOKEN, robotsDisallowsScanner } from '../robots-policy'\nimport { AGENT_ACCEPT, ASSET_ACCEPT, BROWSER_ACCEPT } from './headers'\nimport { markdownAlternateTarget, sha256Hex } from '../score'\nimport { challengeDetail, detectEdgeChallenge } from '../site-signals'\nimport {\n createDnsResolver,\n createPinnedTransport,\n guardUrl,\n resolveAndValidate,\n type HostPolicy,\n type HostResolver,\n type ProbeHttpResponse,\n type ProbeTransport,\n} from './ssrf'\nimport { createLimiter, ProbeBudgetExceededError, type Limiter, type LimiterLease } from './limiter'\n\n/* ── re-exports: everything a consumer of \"./probe\" legitimately needs ─────── */\n\nexport {\n classifyIp,\n createDnsResolver,\n createPinnedTransport,\n fromWebResponse,\n guardPreviewUrl,\n guardUrl,\n parseIpv4,\n parseIpv6,\n resolveAndValidate,\n} from './ssrf'\nexport type {\n HostResolver,\n IpClassification,\n PinnedAddress,\n ProbeHttpResponse,\n ProbeRequestInit,\n ProbeTransport,\n ResolveOutcome,\n UrlGuardPolicy,\n UrlGuardResult,\n} from './ssrf'\nexport { createLimiter, ProbeBudgetExceededError } from './limiter'\nexport type { Limiter, LimiterLease, LimiterOptions } from './limiter'\n\n/* ── identities (§3.3) ────────────────────────────────────────────────────── */\n\nexport type ProbeRole = 'agent' | 'browser' | 'asset'\n\nexport interface ProbeIdentity {\n readonly role: ProbeRole\n readonly userAgent: string\n readonly accept: string\n}\n\n/**\n * Honest, contactable, and never anybody else's. The number tracks the spec\n * version, so a server log tells its operator which ruleset scored them.\n *\n * IT IS NOT THE REFUSAL TOKEN. A site that disallowed us under 0.1 is still\n * refusing us under 0.2, because robots.txt is matched on `ARS_ROBOTS_TOKEN`\n * below and that string never moves. Versioning the refusal token would let a\n * spec bump quietly re-open sites that already said no.\n */\nexport const ARS_USER_AGENT = 'rebilder-ars/0.3 (+https://rebilder.com/bots)'\n\n/**\n * Re-exported, not defined here: the token and the refusal decision moved to\n * `../robots-policy` when a second probe (the browser extension) needed to\n * honour the same refusals without importing this module. See the note there.\n */\nexport { ARS_ROBOTS_TOKEN }\n\nexport { AGENT_ACCEPT, ASSET_ACCEPT, BROWSER_ACCEPT } from './headers'\n\nconst AGENT_IDENTITY: ProbeIdentity = {\n role: 'agent',\n userAgent: ARS_USER_AGENT,\n accept: AGENT_ACCEPT,\n}\nconst BROWSER_IDENTITY: ProbeIdentity = {\n role: 'browser',\n userAgent: ARS_USER_AGENT,\n accept: BROWSER_ACCEPT,\n}\nconst ASSET_IDENTITY: ProbeIdentity = {\n role: 'asset',\n userAgent: ARS_USER_AGENT,\n accept: ASSET_ACCEPT,\n}\n\nexport const DEFAULT_IDENTITIES: readonly ProbeIdentity[] = Object.freeze([\n AGENT_IDENTITY,\n BROWSER_IDENTITY,\n ASSET_IDENTITY,\n])\n\n/**\n * Crawler names we refuse to wear. Not a completeness claim — it is a tripwire\n * for the specific mistake of \"just set the UA to Googlebot and see what they\n * serve\", which is the one request this package must never make on anyone's\n * behalf.\n */\nconst IMPERSONATION_TOKENS = [\n 'googlebot',\n 'bingbot',\n 'applebot',\n 'baiduspider',\n 'yandexbot',\n 'duckduckbot',\n 'slurp',\n 'gptbot',\n 'chatgpt',\n 'oai-searchbot',\n 'claudebot',\n 'claude-user',\n 'claude-searchbot',\n 'anthropic-ai',\n 'perplexitybot',\n 'perplexity-user',\n 'facebookexternalhit',\n 'meta-external',\n] as const\n\nfunction assertIdentities(identities: readonly ProbeIdentity[]): string | null {\n const byRole = new Map<ProbeRole, ProbeIdentity>()\n for (const identity of identities) byRole.set(identity.role, identity)\n const agent = byRole.get('agent')\n const browser = byRole.get('browser')\n if (agent === undefined || browser === undefined) {\n return 'the identity set must contain an \"agent\" and a \"browser\" entry (§3.3)'\n }\n if (agent.userAgent !== browser.userAgent) {\n return 'the agent and browser probes must send the SAME User-Agent and differ only in Accept (§3.3) — a UA difference makes the parity check measure our own request instead of the page'\n }\n for (const identity of identities) {\n const ua = identity.userAgent.toLowerCase()\n for (const token of IMPERSONATION_TOKENS) {\n if (ua.includes(token)) {\n return `the User-Agent names another operator's crawler (\"${token}\"). ARS imitates agent intent, never agent identity (§3.3)`\n }\n }\n }\n return null\n}\n\n/* ── policy ───────────────────────────────────────────────────────────────── */\n\n/**\n * Policy as a type rather than a pile of booleans — and note what is NOT here:\n * there is no `allowPrivateHosts`. Private/loopback targets are unlocked by\n * importing a different entry point (`./probe/local`), which throws at import\n * time without a per-invocation opt-in, not by flipping a field on a config\n * object that somebody will one day copy into a hosted route.\n */\nexport interface ProbePolicy {\n /** Default false. True only under `./probe/local`. */\n allowHttp: boolean\n /** 2 MiB, from the ruleset. Normative: two caps produce two different scores. */\n maxBodyBytes: number\n /** 3, from the ruleset. */\n maxRedirects: number\n /** 5 000ms, from the ruleset. */\n timeoutMs: number\n /** Injected, never module-global. See `./limiter` for why that matters. */\n limiter: Limiter\n identities: readonly ProbeIdentity[]\n}\n\n/**\n * The hosted policy: https only, ruleset caps, default identities. The limiter\n * is a required argument because \"who owns this run's budget\" is a question the\n * caller has to answer, and a default would answer it wrongly in a warm\n * serverless instance.\n */\nexport function strictPolicy(limiter: Limiter, ruleset: ArsRuleset = DEFAULT_RULESET): ProbePolicy {\n return {\n allowHttp: false,\n maxBodyBytes: ruleset.maxBodyBytes,\n maxRedirects: ruleset.maxRedirects,\n timeoutMs: ruleset.timeoutMs,\n limiter,\n identities: DEFAULT_IDENTITIES,\n }\n}\n\n/* ── options and outcome ──────────────────────────────────────────────────── */\n\nexport interface ProbeOptions {\n /** Default `'public'`. Only `'public'` is gated on the `rebilder-ars` token. */\n vantage?: ArsVantage\n /** Default: DNS-pinned `node:https`. Injected in tests; never bypasses the guard. */\n transport?: ProbeTransport\n /** Default: real DNS. Validation runs whatever transport is in use. */\n resolver?: HostResolver\n /** Default: wall clock. Feeds `ArsEvidence.capturedAt`, which is excluded from the hash. */\n now?: () => Date\n sleep?: (ms: number) => Promise<void>\n /** §3.3: one retry after 5s before a 5xx robots.txt becomes `robots-unavailable`. */\n robotsRetryDelayMs?: number\n}\n\n/**\n * Why `rejection` is not an `ArsUnscoredReason`: these are the cases where no\n * evidence bundle exists at all, so there is nothing for `score()` to judge.\n * Everything the origin actually said — a 404, a 500, a timeout, a redirect loop\n * — comes back as `{ ok: true }` with the failure recorded inside the bundle,\n * because that IS the observation.\n */\nexport type ProbeRejection = 'invalid-url' | 'policy-rejected' | 'budget-exceeded'\n\nexport type ProbeOutcome =\n { ok: true; evidence: ArsEvidence } | { ok: false; rejection: ProbeRejection; detail: string }\n\n/* ── body reading: streamed, counted, capped ──────────────────────────────── */\n\ninterface DecodedBody {\n text: string\n /** UTF-8 byte length of `text` — the normative measurement (§3.3). */\n bytes: number\n truncated: boolean\n}\n\n/** `charset` from Content-Type, defaulting to UTF-8 (§3.3). */\nfunction charsetOf(headers: Record<string, string[]>): string {\n const value = headers['content-type']?.[0]\n if (value === undefined) return 'utf-8'\n const match = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i.exec(value)\n return match?.[1]?.toLowerCase() ?? 'utf-8'\n}\n\nfunction createDecoder(charset: string): TextDecoder {\n try {\n return new TextDecoder(charset, { fatal: false })\n } catch {\n return new TextDecoder('utf-8', { fatal: false })\n }\n}\n\n/** Largest prefix of `chunk` whose UTF-8 length fits in `budget`, split on code points. */\nfunction fitPrefix(chunk: string, budget: number): string {\n let out = ''\n let used = 0\n for (const codePoint of chunk) {\n const size = utf8Length(codePoint)\n if (used + size > budget) break\n out += codePoint\n used += size\n }\n return out\n}\n\n/**\n * Streams the body, counting decoded UTF-8 bytes, and cancels the read the\n * moment the cap is reached. `await response.text()` is forbidden by §3.3 and is\n * the live defect this replaces: `BODY_PREVIEW_CHARS` in the Console preview\n * truncated only what was *stored*, so a 4 GB response was still fully buffered\n * into the server's heap before anything was trimmed.\n *\n * The NORMATIVE cap is on decoded UTF-8 bytes (§3.3), because that is the number\n * D3.2 scores and two implementations counting different things produce\n * different scores. Wire bytes carry a separate, much looser ceiling whose only\n * job is to bound the read for a charset that SHRINKS on decode — UTF-16 halves,\n * so without it a 2 MiB decoded cap would let 4 MiB off the socket. It is set\n * well above any real ratio on purpose: making it tight would mark a perfectly\n * complete UTF-16 page as `truncated`, and a false truncation flag is a lie\n * about the evidence.\n */\nasync function readCappedBody(\n body: ReadableStream<Uint8Array> | null,\n charset: string,\n maxBytes: number,\n): Promise<DecodedBody> {\n if (body === null) return { text: '', bytes: 0, truncated: false }\n\n const decoder = createDecoder(charset)\n const reader = body.getReader()\n const parts: string[] = []\n /** Backstop only; see the note above. No real charset shrinks by 4×. */\n const rawCeiling = maxBytes * 4\n let bytes = 0\n let rawBytes = 0\n let truncated = false\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value === undefined) continue\n rawBytes += value.byteLength\n\n const chunk = decoder.decode(value, { stream: true })\n const chunkBytes = utf8Length(chunk)\n if (bytes + chunkBytes > maxBytes) {\n const prefix = fitPrefix(chunk, maxBytes - bytes)\n if (prefix.length > 0) parts.push(prefix)\n bytes += utf8Length(prefix)\n truncated = true\n break\n }\n parts.push(chunk)\n bytes += chunkBytes\n\n if (rawBytes >= rawCeiling) {\n truncated = true\n break\n }\n }\n if (!truncated) {\n const tail = decoder.decode()\n if (tail.length > 0) {\n const tailBytes = utf8Length(tail)\n if (bytes + tailBytes > maxBytes) {\n const prefix = fitPrefix(tail, maxBytes - bytes)\n parts.push(prefix)\n bytes += utf8Length(prefix)\n truncated = true\n } else {\n parts.push(tail)\n bytes += tailBytes\n }\n }\n }\n } finally {\n // Cancelling is what actually stops the socket; without it the cap only\n // limits what we keep, not what the origin sends us.\n await reader.cancel().catch(() => undefined)\n }\n\n return { text: parts.join(''), bytes, truncated }\n}\n\n/* ── one request, with the full guard on every hop ────────────────────────── */\n\ninterface FetchContext {\n readonly policy: ProbePolicy\n readonly hostPolicy: HostPolicy\n readonly transport: ProbeTransport\n readonly resolver: HostResolver\n}\n\ntype FetchResult = ArsProbeRecord['result']\n\nfunction failed(error: ArsProbeError, detail: string): FetchResult {\n return { ok: false, error, detail }\n}\n\nfunction classifyTransportError(error: unknown, signal: AbortSignal): ArsProbeError {\n const reason: unknown = signal.aborted ? signal.reason : undefined\n if (reason instanceof Error && reason.name === 'TimeoutError') return 'timeout'\n if (error instanceof Error && error.name === 'TimeoutError') return 'timeout'\n if (signal.aborted) return 'timeout'\n return 'unreachable'\n}\n\nasync function fetchWithPolicy(\n startUrl: string,\n headers: Readonly<Record<string, string>>,\n context: FetchContext,\n): Promise<FetchResult> {\n const { policy, hostPolicy, transport, resolver } = context\n const redirects: { status: number; location: string }[] = []\n let current = startUrl\n\n // `hop < maxRedirects`, not `<=`. The shipped Console loop used `<=` and\n // therefore allowed four requests where the ruleset says three (§3.3).\n for (let hop = 0; hop < policy.maxRedirects; hop++) {\n const blocked: ArsProbeError = hop === 0 ? 'policy-rejected' : 'blocked-redirect'\n\n const guard = guardUrl(current, { allowHttp: policy.allowHttp, hostPolicy })\n if (!guard.ok) return failed(blocked, guard.reason)\n\n // Re-resolve and re-pin on EVERY hop. Re-parsing the Location URL is not\n // enough: hop 2 is a new connection to a new name.\n const resolved = await resolveAndValidate(guard.url.hostname, resolver, hostPolicy)\n if (!resolved.ok) {\n return failed(resolved.kind === 'unreachable' ? 'unreachable' : blocked, resolved.reason)\n }\n\n // Politeness before the socket, not after. A `ProbeBudgetExceededError` is\n // deliberately allowed to propagate: half a bundle is not evidence, so the\n // whole probe reports `budget-exceeded` rather than a partial observation.\n const lease: LimiterLease = await policy.limiter.acquire(guard.url.hostname)\n\n const signal = AbortSignal.timeout(policy.timeoutMs)\n let response: ProbeHttpResponse\n try {\n response = await transport(guard.url.toString(), {\n headers,\n redirect: 'manual',\n signal,\n pinnedAddresses: resolved.addresses,\n })\n } catch (error) {\n lease.release()\n const kind = classifyTransportError(error, signal)\n return failed(\n kind,\n kind === 'timeout'\n ? `No response within ${policy.timeoutMs}ms.`\n : `The URL could not be reached: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers['location']?.[0]\n // Drain and drop: a redirect body is not evidence, and leaving the stream\n // open leaves the socket open.\n if (response.body !== null) await response.body.cancel().catch(() => undefined)\n lease.release()\n if (location === undefined || location.trim() === '') {\n return failed('non-2xx', `Redirect (${response.status}) without a Location header.`)\n }\n let next: string\n try {\n next = new URL(location, guard.url).toString()\n } catch {\n return failed('blocked-redirect', `Redirect to an unparseable Location: ${location}`)\n }\n redirects.push({ status: response.status, location: next })\n current = next\n continue\n }\n\n let decoded: DecodedBody\n try {\n decoded = await readCappedBody(\n response.body,\n charsetOf(response.headers),\n policy.maxBodyBytes,\n )\n } catch (error) {\n const kind = classifyTransportError(error, signal)\n return failed(\n kind,\n `The response body could not be read: ${error instanceof Error ? error.message : String(error)}`,\n )\n } finally {\n lease.release()\n }\n\n const capture: ArsHttpCapture = {\n requestedUrl: startUrl,\n finalUrl: guard.url.toString(),\n redirects,\n status: response.status,\n headers: response.headers,\n bytes: decoded.bytes,\n bodySha256: sha256Hex(decoded.text),\n body: decoded.text,\n truncated: decoded.truncated,\n }\n return { ok: true, capture }\n }\n\n return failed('too-many-redirects', `More than ${policy.maxRedirects - 1} redirects.`)\n}\n\n/* ── robots ───────────────────────────────────────────────────────────────── */\n\n/* ── the probe ────────────────────────────────────────────────────────────── */\n\nfunction headersFor(identity: ProbeIdentity): Record<string, string> {\n return { accept: identity.accept, 'user-agent': identity.userAgent }\n}\n\nfunction identityFor(policy: ProbePolicy, role: ProbeRole): ProbeIdentity {\n const found = policy.identities.find((identity) => identity.role === role)\n // `assertIdentities` guarantees agent/browser; `asset` falls back to agent.\n return found ?? policy.identities.find((identity) => identity.role === 'agent') ?? AGENT_IDENTITY\n}\n\nfunction skipped(headers: Record<string, string>, detail: string): ArsProbeRecord {\n return { requestHeaders: headers, result: { ok: false, error: 'policy-rejected', detail } }\n}\n\n/**\n * `hostPolicy` is a capability, not a flag: the only value other than\n * `'public-only'` is a symbol exported from a non-entry-point module, so a\n * consumer of `\"./probe\"` cannot construct one. Exported because\n * `\"./probe/local\"` has to call it; harmless because calling it without the\n * symbol is exactly `probeStrict`.\n */\nexport async function probeWithHostPolicy(\n target: string,\n policy: ProbePolicy,\n hostPolicy: HostPolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n const identityProblem = assertIdentities(policy.identities)\n if (identityProblem !== null) {\n return { ok: false, rejection: 'policy-rejected', detail: identityProblem }\n }\n\n // \"Unparseable\" and \"parseable but refused\" are different answers to the\n // caller — the CLI exit-code contract splits them (2 = usage, 4 = policy) —\n // so they are distinguished by re-parsing rather than by matching on the\n // guard's message text.\n let parseable = true\n try {\n void new URL(target.trim())\n } catch {\n parseable = false\n }\n\n const guard = guardUrl(target, { allowHttp: policy.allowHttp, hostPolicy })\n if (!guard.ok) {\n return {\n ok: false,\n rejection: parseable ? 'policy-rejected' : 'invalid-url',\n detail: guard.reason,\n }\n }\n\n const context: FetchContext = {\n policy,\n hostPolicy,\n transport: options.transport ?? createPinnedTransport(),\n resolver: options.resolver ?? createDnsResolver(),\n }\n const vantage = options.vantage ?? 'public'\n const now = options.now ?? (() => new Date())\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))\n const robotsRetryDelayMs = options.robotsRetryDelayMs ?? 5_000\n\n const url = guard.url\n const origin = url.origin\n const assetHeaders = headersFor(identityFor(policy, 'asset'))\n const agentHeaders = headersFor(identityFor(policy, 'agent'))\n const browserHeaders = headersFor(identityFor(policy, 'browser'))\n\n const run = async (href: string, headers: Record<string, string>): Promise<ArsProbeRecord> => {\n try {\n return { requestHeaders: headers, result: await fetchWithPolicy(href, headers, context) }\n } catch (error) {\n if (error instanceof ProbeBudgetExceededError) throw error\n return {\n requestHeaders: headers,\n result: {\n ok: false,\n error: 'unreachable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n\n /**\n * The page-level requests (agent, browser, linked Markdown copy) recognise a\n * CDN bot challenge served in place of the page and record it as the\n * `challenge` probe error, with the vendor in `detail` (`../site-signals`\n * lists the fingerprints and their sources). Without this a 200 challenge\n * page was scored as a thin page and a 403 one as a generic block. The\n * origin-level assets (robots.txt, llms.txt, /.well-known/ucp) are not\n * inspected: their handling is unchanged.\n */\n const runPage = async (\n href: string,\n headers: Record<string, string>,\n ): Promise<ArsProbeRecord> => {\n const record = await run(href, headers)\n if (!record.result.ok) return record\n const challenge = detectEdgeChallenge(record.result.capture)\n if (challenge === null) return record\n return {\n requestHeaders: headers,\n result: { ok: false, error: 'challenge', detail: challengeDetail(challenge) },\n }\n }\n\n const evidenceOf = (probes: ArsEvidence['probes']): ProbeOutcome => ({\n ok: true,\n evidence: {\n evidenceVersion: '0.1.0',\n target: { url: url.toString(), origin },\n probes,\n vantage,\n capturedAt: now().toISOString(),\n },\n })\n\n try {\n // 1 — robots.txt, first, always. §3.3.\n let robotsTxt = await run(`${origin}/robots.txt`, assetHeaders)\n const robotsUnavailable = (record: ArsProbeRecord): boolean =>\n !record.result.ok || record.result.capture.status >= 500\n // Retry a transport hiccup or a 5xx. NEVER retry a refusal: a target we\n // declined on policy grounds will be declined identically in five seconds,\n // and sleeping first only makes the caller wait for the same answer.\n const worthRetrying = (record: ArsProbeRecord): boolean =>\n record.result.ok\n ? record.result.capture.status >= 500\n : record.result.error === 'unreachable' || record.result.error === 'timeout'\n if (worthRetrying(robotsTxt)) {\n // A single hiccup does not un-score a domain; a persistent 5xx does.\n await sleep(robotsRetryDelayMs)\n robotsTxt = await run(`${origin}/robots.txt`, assetHeaders)\n }\n if (robotsUnavailable(robotsTxt)) {\n const detail =\n 'robots.txt returned a persistent error; a policy we could not read is not a policy we may assume'\n return evidenceOf({\n agent: skipped(agentHeaders, detail),\n browser: skipped(browserHeaders, detail),\n parityConfirm: null,\n robotsTxt,\n llmsTxt: null,\n wellKnownUcp: null,\n })\n }\n\n const robotsBody = robotsTxt.result.ok ? (robotsTxt.result.capture.body ?? '') : ''\n const robotsUsable = robotsTxt.result.ok && robotsTxt.result.capture.status < 400\n const disallowedFor = (path: string): string | null =>\n vantage === 'public' && robotsUsable ? robotsDisallowsScanner(robotsBody, path) : null\n\n // 2 — we obey our own token, and we do not fetch what it forbids.\n const pageRule = disallowedFor(url.pathname)\n if (pageRule !== null) {\n const detail = `robots.txt disallows the ${ARS_ROBOTS_TOKEN} token (${pageRule})`\n return evidenceOf({\n agent: skipped(agentHeaders, detail),\n browser: skipped(browserHeaders, detail),\n parityConfirm: null,\n robotsTxt,\n llmsTxt: null,\n wellKnownUcp: null,\n })\n }\n\n // 3 — agent, then browser control. Sequential: two quick hits are gentler on\n // an origin than a simultaneous pair, and the limiter spaces them anyway.\n const agent = await runPage(url.toString(), agentHeaders)\n const browser = await runPage(url.toString(), browserHeaders)\n\n // 3b — the Markdown copy the page links to, when it did not send one (ARS 0.3).\n const linked = markdownAlternateTarget(\n agent.result.ok ? agent.result.capture : null,\n browser.result.ok ? browser.result.capture : null,\n origin,\n )\n let markdownAlternate: ArsProbeRecord | null = null\n if (linked !== null) {\n const rule = disallowedFor(new URL(linked).pathname)\n markdownAlternate =\n rule !== null\n ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`)\n : await runPage(linked, agentHeaders)\n }\n\n // 4 — the two origin-level conventions, and nothing else.\n const fetchAsset = async (path: string): Promise<ArsProbeRecord | null> => {\n const rule = disallowedFor(path)\n if (rule !== null)\n return skipped(assetHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${path}`)\n return run(`${origin}${path}`, assetHeaders)\n }\n const llmsTxt = await fetchAsset('/llms.txt')\n const wellKnownUcp = await fetchAsset('/.well-known/ucp')\n\n return evidenceOf({\n agent,\n browser,\n parityConfirm: null,\n // Omitted when not taken, so a page with no linked copy produces exactly\n // the bundle (and the evidence hash) it produced under 0.2.\n ...(markdownAlternate === null ? {} : { markdownAlternate }),\n robotsTxt,\n llmsTxt,\n wellKnownUcp,\n })\n } catch (error) {\n if (error instanceof ProbeBudgetExceededError) {\n return { ok: false, rejection: 'budget-exceeded', detail: error.message }\n }\n throw error\n }\n}\n\n/**\n * The hosted probe. https only, public hosts only, DNS-validated and pinned,\n * 2 MiB streamed cap, robots-gated, limiter-gated.\n *\n * There is deliberately no argument that relaxes any of that. `probeLocal` lives\n * at `\"./probe/local\"`, throws at import time without a per-invocation opt-in,\n * and is imported by the CLI and by nothing that can be reached over HTTP.\n */\nexport function probeStrict(\n target: string,\n policy: ProbePolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n return probeWithHostPolicy(target, policy, 'public-only', options)\n}\n\n/** Convenience for one-off callers: a fresh run-scoped limiter and the strict policy. */\nexport function strictPolicyForRun(overrides: Partial<ProbePolicy> = {}): ProbePolicy {\n return { ...strictPolicy(createLimiter()), ...overrides }\n}\n\n/**\n * The type is exported so `probeWithHostPolicy`'s signature is nameable. The\n * *value* — the `ALLOW_PRIVATE_HOSTS` symbol — is deliberately NOT re-exported\n * here: it lives in `./ssrf`, which `package.json#exports` does not publish, so\n * the only way to hold it is to be inside this package. Re-exporting it from\n * `\"./probe\"` would turn the capability straight back into the boolean it was\n * designed to replace.\n */\nexport type { HostPolicy }\n","/**\n * probe/local.ts — `\"./probe/local\"`. Private hosts and plain http, and NOTHING\n * that can be reached over HTTP.\n *\n * WHY THIS IS A SEPARATE ENTRY POINT THAT THROWS ON IMPORT, RATHER THAN A FLAG.\n *\n * The obvious design is `probe(url, { allowPrivateHosts: true })`. It is wrong,\n * and the reason is worth writing down because the wrong version looks fine in\n * review. `ProbePolicy` is a plain object that gets built once and reused. A\n * boolean on it is a boolean somebody will set to `true` — not maliciously, but\n * because they are wiring a new route, the local config already works, and\n * copying it is the obvious move. The moment that happens, an SSRF guard exists\n * in the codebase and is switched off in production, and nothing about the diff\n * looks like a security change.\n *\n * The concrete failure this prevents: `@rebilder/mcp-server` runs on a\n * developer's machine, inside their network, driven by a model whose context\n * contains web pages we did not write. \"Check http://169.254.169.254/ for me\"\n * arriving as text inside a scraped page is not a hypothetical — it is the\n * standard prompt-injection payload, and a company whose entire product is *what\n * agents read* cannot ship the tool that fetches it on request.\n *\n * So the permission is a capability, held three ways at once:\n * 1. It is a DIFFERENT MODULE. `probeStrict` cannot reach it; nothing that\n * imports `\"./probe\"` gets it transitively.\n * 2. It THROWS AT IMPORT TIME unless the process was started with\n * `--allow-private`. A process argument is not configuration: a serverless\n * handler's argv is set by the platform, not by our env file or our JSON,\n * so there is no way to switch this on from a dashboard or a `.env`.\n * 3. It REFUSES OUTRIGHT in a serverless/edge runtime, flag or no flag. If we\n * are running inside a request handler, the answer is no, and there is no\n * argument to be had about it.\n *\n * The permission is per invocation. `rebilder check --allow-private\n * http://staging.internal.corp` is a thing a developer chose to type on their own\n * machine. It is never a default, never an env var, and never inherited.\n *\n * NOTE ON THE PAIR OF GUARANTEES: the CLI and MCP server ship zero telemetry\n * (a project convention). That is not decoration next to this file — a probe\n * that reaches internal hostnames and a binary that uploads what it found are\n * only safe together as long as the second half stays false.\n */\n\nimport { ALLOW_PRIVATE_HOSTS } from './ssrf'\nimport {\n probeWithHostPolicy,\n strictPolicy,\n type ProbeOptions,\n type ProbeOutcome,\n type ProbePolicy,\n} from './index'\nimport { type Limiter } from './limiter'\nimport type { ArsRuleset } from '../types'\nimport { DEFAULT_RULESET } from '../ruleset'\n\n/** The one accepted opt-in. A CLI flag, on purpose: argv is not configuration. */\nexport const ALLOW_PRIVATE_FLAG = '--allow-private'\n\n/**\n * Environment markers that mean \"this process is serving HTTP requests\". Any of\n * them present is a hard refusal: local mode exists for a human at a terminal.\n */\nconst HOSTED_RUNTIME_MARKERS = [\n 'VERCEL',\n 'NEXT_RUNTIME',\n 'AWS_LAMBDA_FUNCTION_NAME',\n 'AWS_EXECUTION_ENV',\n 'FUNCTIONS_WORKER_RUNTIME',\n 'K_SERVICE',\n 'CF_PAGES',\n] as const\n\nfunction hostedRuntimeMarker(): string | null {\n for (const key of HOSTED_RUNTIME_MARKERS) {\n const value = process.env[key]\n if (typeof value === 'string' && value.length > 0) return key\n }\n return null\n}\n\n/**\n * The import-time gate. Runs on module evaluation — before anything can call\n * `probeLocal`, and before a bundler can tree-shake the check away from the\n * function it protects.\n */\nfunction assertLocalModeUnlocked(): void {\n const hosted = hostedRuntimeMarker()\n if (hosted !== null) {\n throw new Error(\n `@rebilder/agent-readability/probe/local: refusing to load in a hosted runtime (${hosted} is set). ` +\n 'Local mode allows private and loopback targets and must never be reachable from an HTTP transport. ' +\n 'Use probeStrict() from \"@rebilder/agent-readability/probe\".',\n )\n }\n if (!process.argv.includes(ALLOW_PRIVATE_FLAG)) {\n throw new Error(\n `@rebilder/agent-readability/probe/local: refusing to load without ${ALLOW_PRIVATE_FLAG}. ` +\n 'Private hosts, loopback, link-local and cloud-metadata addresses are reachable through this entry point, ' +\n 'so the permission is per invocation and comes from the command line — not from a config object, ' +\n 'not from an environment variable, and never by default.',\n )\n }\n}\n\nassertLocalModeUnlocked()\n\n/**\n * The local policy: http allowed, non-standard ports allowed, private hosts\n * allowed. Everything else — the streamed byte cap, the redirect limit, the\n * timeout, the politeness limiter, the robots gate — is unchanged, because none\n * of those exist to protect us from ourselves.\n */\nexport function localPolicy(limiter: Limiter, ruleset: ArsRuleset = DEFAULT_RULESET): ProbePolicy {\n return { ...strictPolicy(limiter, ruleset), allowHttp: true }\n}\n\n/**\n * Probes a target that may be private, loopback, or plain http.\n *\n * `vantage` defaults to `'self'` rather than `'public'`: someone running this\n * against their own staging host is the operator of that host, and §3.7 says the\n * owner can consent for their own origin. It also means the `rebilder-ars`\n * robots gate does not apply, which is correct — you do not need your own\n * permission to read your own site.\n */\nexport function probeLocal(\n target: string,\n policy: ProbePolicy,\n options: ProbeOptions = {},\n): Promise<ProbeOutcome> {\n return probeWithHostPolicy(target, policy, ALLOW_PRIVATE_HOSTS, {\n ...options,\n vantage: options.vantage ?? 'self',\n })\n}\n"]}