@rebilder/render-md 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/money.ts","../src/internal/validate.ts","../src/jsonld.ts","../src/internal/budget.ts","../src/markdown.ts","../src/documents/facts.ts","../src/documents/markdown.ts","../src/documents/jsonld.ts","../src/compatibility.ts"],"names":[],"mappings":";;;AAMA,IAAM,YAAA,uBAAmB,GAAA,CAAI;AAAA,EAC3B,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGD,IAAM,aAAA,mBAAgB,IAAI,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAK,CAAC,CAAA;AAO/E,IAAM,OAAA,GAAkC;AAAA,EACtC,GAAA,EAAK,GAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,MAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAEA,SAAS,gBAAgB,IAAA,EAAsB;AAC7C,EAAA,IAAI,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA,EAAG,OAAO,CAAA;AACnC,EAAA,IAAI,aAAA,CAAc,GAAA,CAAI,IAAI,CAAA,EAAG,OAAO,CAAA;AACpC,EAAA,OAAO,CAAA;AACT;AAEA,SAAS,YAAY,CAAA,EAAyD;AAC5E,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,CAAA,CAAE,MAAM,CAAA,EAAG;AA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,OAAO,QAAA;AAChC,IAAA,MAAA,GAAS,CAAA;AAAA,EAA2B,QAAA,CAAS,GAAA,CAAI,CAAC,IAAA,KAAS,KAAK,IAAA,CAAK,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC;;AAAA,CAAA;AAAA,EAC5G;AACA,EAAA,MAAM,SAAS,MAAA,GAAS,QAAA;AACxB,EAAA,MAAM,QAAQ,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,MAAM,CAAA,CAAE,UAAA;AAC/C,EAAA,IAAI,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,MAAM,EAAE,UAAA,GAAa,IAAA,IAAQ,KAAA,IAAS,OAAA,CAAQ,QAAA,IAAY,IAAA,CAAA;AACrF,IAAA,OAAO,QAAA;AACT,EAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAQ,OAAA,EAAQ;AACrC","file":"index.cjs","sourcesContent":["import type { Money } from './types'\n\n/**\n * ISO 4217 currencies with no minor unit — `Money.amount` is already whole\n * currency units for these (e.g. JPY 4900 = ¥4,900).\n */\nconst ZERO_DECIMAL = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n])\n\n/** ISO 4217 currencies with three-digit minor units. */\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\n/**\n * Unambiguous symbol prefixes. Deliberately conservative: currencies whose\n * common symbol is shared across currencies (e.g. \"$\" for CAD/AUD) fall back\n * to the explicit \"CODE 49.00\" form instead of guessing.\n */\nconst SYMBOLS: Record<string, string> = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n}\n\nfunction minorUnitDigits(code: string): number {\n if (ZERO_DECIMAL.has(code)) return 0\n if (THREE_DECIMAL.has(code)) return 3\n return 2\n}\n\nfunction splitAmount(m: Money): { sign: string; major: string; frac: string } {\n if (!Number.isInteger(m.amount)) {\n // Fail closed: silently rounding would alter a price (source validation).\n throw new TypeError(\n `Money.amount must be an integer number of minor units, got: ${String(m.amount)}`,\n )\n }\n const digits = minorUnitDigits(m.currency.toUpperCase())\n const sign = m.amount < 0 ? '-' : ''\n const abs = Math.abs(m.amount)\n const factor = 10 ** digits\n const major = Math.floor(abs / factor).toString()\n const frac = digits === 0 ? '' : `.${(abs % factor).toString().padStart(digits, '0')}`\n return { sign, major, frac }\n}\n\n/**\n * Decimal string for machine consumption (JSON-LD `price`): \"89.00\", \"4900\"\n * (zero-decimal), \"49.123\" (three-decimal). No grouping, no symbol.\n */\nexport function toDecimalString(m: Money): string {\n const { sign, major, frac } = splitAmount(m)\n return `${sign}${major}${frac}`\n}\n\n/**\n * Human-readable, deterministic money formatting: \"$49.00\", \"€49.00\",\n * \"¥4,900\", \"-£5.50\". Unknown/ambiguous currencies render as \"CAD 49.00\".\n * Pure function — no Intl, no locale, same input → same output everywhere.\n */\nexport function formatMoney(m: Money): string {\n const { sign, major, frac } = splitAmount(m)\n const code = m.currency.toUpperCase()\n const grouped = major.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n const symbol = SYMBOLS[code]\n return symbol !== undefined\n ? `${sign}${symbol}${grouped}${frac}`\n : `${sign}${code} ${grouped}${frac}`\n}\n","/**\n * Value-shape validators shared by the commerce and document renderers.\n *\n * `isIsoDate` was moved here verbatim from `documents/facts.ts` when the\n * commerce renderers gained `updated`. Same reasoning as `internal/budget.ts`:\n * a date the document renderer accepts and the product renderer rejects is two\n * validation behaviours that will drift, and the two now serve the same field\n * name on two source types. `documents/facts.ts` re-exports it so its existing\n * importers are unchanged.\n *\n * Every validator here is a **gate, not a transform**. A value that passes is\n * emitted byte-for-byte as the merchant supplied it; a value that fails is\n * dropped, never corrected, normalised, or re-cased. Correcting a malformed\n * value would make this package originate one (source validation), and re-casing a\n * language tag would mean the JSON-LD disagreed with the merchant's own page.\n *\n * Package-internal. Nothing here is part of the public contract.\n */\n\n/** ISO 8601 date or datetime. Structure first, then real-calendar check. */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?(Z|[+-]\\d{2}:\\d{2})?)?$/\n\n/**\n * `Date.parse` alone does NOT implement the real-calendar half this function\n * has always claimed. It rejects a month above 12 and a day above 31, but a\n * day that overflows its own month rolls silently forward:\n *\n * Date.parse('2026-02-31') → March 3 (not NaN)\n * Date.parse('2026-02-29') → March 1 (2026 is not a leap year)\n * Date.parse('2026-04-31') → May 1 (April has 30 days)\n *\n * So the pre-existing check passed three dates that do not exist, and the\n * renderers emitted them verbatim. Harmless-looking in a markdown line; not\n * harmless as `dateModified` in a product feed, where a date is a fact a\n * caller may act on. Round-tripping the calendar portion is what actually\n * enforces the docstring: build the date from its parts and require that the\n * parts survive.\n *\n * `setUTCFullYear` rather than `Date.UTC` because the latter maps years 0–99\n * onto 1900–1999, which would false-reject a four-digit year like `0026`.\n */\nfunction isRealCalendarDate(value: string): boolean {\n const [year, month, day] = value.slice(0, 10).split('-').map(Number) as [number, number, number]\n const probe = new Date(0)\n probe.setUTCFullYear(year, month - 1, day)\n return (\n probe.getUTCFullYear() === year &&\n probe.getUTCMonth() === month - 1 &&\n probe.getUTCDate() === day\n )\n}\n\nexport function isIsoDate(value: string): boolean {\n return ISO_DATE.test(value) && !Number.isNaN(Date.parse(value)) && isRealCalendarDate(value)\n}\n\n/**\n * BCP 47 language tag, restricted to the forms that actually appear on\n * commerce and content pages: language, optional script, optional region.\n *\n * `en` · `en-US` · `pt-BR` · `zh-Hant` · `zh-Hant-TW` · `es-419`\n *\n * Deliberately NOT the full grammar (RFC 5646 admits extensions, private-use\n * subtags and grandfathered tags). A tag this regex rejects is dropped rather\n * than guessed at, and the page simply declares no language — which is the\n * status quo for every page served before this field existed. Widening the\n * grammar later is additive; emitting a malformed `inLanguage` into a product\n * feed is not something a later release can retract.\n *\n * Case is validated leniently and preserved exactly: BCP 47 is\n * case-insensitive, so `EN-us` is a valid tag and rejecting it would punish a\n * merchant for a spelling the standard allows.\n */\nconst BCP_47 = /^[A-Za-z]{2,3}(-[A-Za-z]{4})?(-(?:[A-Za-z]{2}|\\d{3}))?$/\n\nexport function isLanguageTag(value: string): boolean {\n return BCP_47.test(value)\n}\n","import type { Availability, Money, ProductSource } from './types'\nimport { toDecimalString } from './money'\nimport { isIsoDate, isLanguageTag } from './internal/validate'\n\n/** Availability enum → schema.org ItemAvailability URL. */\nconst SCHEMA_AVAILABILITY: Record<Availability, string> = {\n in_stock: 'https://schema.org/InStock',\n out_of_stock: 'https://schema.org/OutOfStock',\n preorder: 'https://schema.org/PreOrder',\n backorder: 'https://schema.org/BackOrder',\n}\n\nfunction offer(\n price: Money,\n availability: Availability,\n extra: { url?: string; sku?: string; name?: string },\n): Record<string, unknown> {\n const o: Record<string, unknown> = {\n '@type': 'Offer',\n price: toDecimalString(price),\n priceCurrency: price.currency,\n availability: SCHEMA_AVAILABILITY[availability],\n }\n if (extra.url !== undefined) o.url = extra.url\n if (extra.sku !== undefined) o.sku = extra.sku\n if (extra.name !== undefined) o.name = extra.name\n return o\n}\n\n/**\n * Render a schema.org Product JSON-LD object from the product source.\n * Injection-only: every value comes from `p`; only fields present in the\n * source appear in the output. Key order is fixed for snapshot stability.\n *\n * `inLanguage` and `dateModified` are emitted only when the source value\n * passes its shape check. A malformed value is dropped rather than repaired or\n * reformatted: this renderer feeds `/acp/v0/feed` and the MCP product tool as\n * well as the canonical page, and a date this package invented would be a\n * substantive value it originated (source validation) — in a product feed, where it\n * would read as authoritative.\n */\nexport function renderProductJsonLd(p: ProductSource): Record<string, unknown> {\n const out: Record<string, unknown> = {\n '@context': 'https://schema.org',\n '@type': 'Product',\n name: p.title,\n url: p.url,\n }\n if (p.brand !== undefined) out.brand = { '@type': 'Brand', name: p.brand }\n if (p.description !== undefined && p.description.length > 0) out.description = p.description\n if (p.images !== undefined && p.images.length > 0) out.image = p.images.map((img) => img.url)\n if (p.language !== undefined && isLanguageTag(p.language)) out.inLanguage = p.language\n out.offers =\n p.variants !== undefined && p.variants.length > 0\n ? p.variants.map((v) => offer(v.price, v.availability, { sku: v.sku, name: v.title }))\n : offer(p.price, p.availability, { url: p.url })\n // After `offers` deliberately: the buying facts stay in the same position\n // they have always occupied, so a diff of two feed records shows the new\n // freshness key appended rather than every offer key shifted down one line.\n if (p.updated !== undefined && isIsoDate(p.updated)) out.dateModified = p.updated\n return out\n}\n","/**\n * Byte-budget, heading, and markdown-escaping primitives shared by every\n * renderer in this package.\n *\n * These helpers were extracted from `src/markdown.ts` verbatim when the\n * universal document renderers were added. The extraction is not cosmetic:\n * the commerce renderers and the document renderers must truncate by exactly\n * the same rule, and two copies of a truncation loop is two truncation\n * behaviours that will drift the first time one of them is \"improved\". The\n * code below is byte-for-byte the code that shipped inside `src/markdown.ts`;\n * `tests/commerce-frozen.test.ts` pins the commerce renderers' output with\n * inline string literals and is the proof that the move changed nothing.\n *\n * Package-internal. Nothing here is re-exported from `src/index.ts` — these\n * are implementation primitives, not part of the public contract.\n */\n\n/** Default output size budget in UTF-8 bytes, shared by every renderer. */\nexport const DEFAULT_MAX_BYTES = 5120\n\n/**\n * Fixed meta note appended when output is truncated to fit the size budget.\n * Pure rendering metadata — contains no prices, claims, or policy text.\n */\nexport const TRUNCATION_NOTE = '*Truncated to fit size budget; remaining content omitted.*'\n\nconst encoder = new TextEncoder()\n\nexport function byteLength(s: string): number {\n return encoder.encode(s).length\n}\n\nexport function clampHeadingLevel(level: number): number {\n return Math.min(Math.max(Math.trunc(level), 1), 6)\n}\n\nexport function heading(level: number, text: string): string {\n return `${'#'.repeat(clampHeadingLevel(level))} ${text}`\n}\n\n/**\n * Keep verbatim source text on a single markdown line (inline contexts only:\n * fact lines, table cells). Collapses newlines to spaces; block contexts\n * (description, policy bodies) stay byte-for-byte verbatim.\n */\nexport function inline(text: string): string {\n return text.replace(/\\s*\\r?\\n\\s*/g, ' ')\n}\n\n/** Escape characters that would break a markdown table cell. Otherwise verbatim. */\nexport function cell(text: string): string {\n return inline(text).replace(/\\|/g, '\\\\|')\n}\n\n/**\n * The URL schemes a rendered link may carry. A `javascript:`/`data:`/`vbscript:`\n * link handed to an agent (or a downstream HTML renderer) is a\n * scheme-smuggling / phishing primitive, so any other scheme is dropped. This\n * matches the document renderer's `isAllowedUrl` (documents/facts.ts) — the\n * commerce renderers must not be the weaker path.\n */\nconst ALLOWED_LINK_SCHEMES: readonly string[] = ['https:', 'http:', 'mailto:', 'tel:']\n\n/** True when `url` parses and carries an allowed scheme. */\nexport function isSafeUrl(url: string): boolean {\n try {\n return ALLOWED_LINK_SCHEMES.includes(new URL(url).protocol)\n } catch {\n return false\n }\n}\n\n/**\n * Escape the characters that let link TEXT break out of `[label](url)` and\n * forge a different target: `]` (which closes the label early) and `[`. `inline`\n * first, so a newline cannot smuggle structure either.\n *\n * Parentheses are deliberately NOT escaped here. They are harmless inside a\n * label — the label is delimited by brackets — and product titles legitimately\n * contain them (\"Wool Socks (3-pack)\"). Escaping them would put backslashes in\n * front of a large fraction of real catalogs, which is visible damage to every\n * honest row to defend against nothing. The URL side is handled by `safeUrl`.\n */\nexport function linkText(text: string): string {\n return inline(text).replace(/[[\\]]/g, (c) => `\\\\${c}`)\n}\n\n/**\n * The URL as it may appear inside `](...)`. A URL carrying `)` would close the\n * link early and leave the remainder as live markdown — `https://x.example/)\n * [click](https://evil.example` renders as TWO links, the second one the\n * attacker's. Percent-encoding the delimiters keeps the URL working and the\n * structure ours. (Angle-bracket link syntax would be the alternative; encoding\n * keeps the output diff-stable for every URL that does not contain them.)\n */\nfunction safeUrl(url: string): string {\n // NOT `encodeURIComponent`: it leaves `(` and `)` untouched (they are in its\n // unreserved set), which is exactly the pair that closes a markdown link —\n // so using it here would look like a fix and do nothing. Percent-encode the\n // delimiters explicitly.\n return url.replace(\n /[()<>\\s]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`,\n )\n}\n\n/**\n * Link text inside a table cell: both escapes, not either. `cell` alone leaves\n * `](` free to forge a link; `linkText` alone leaves `|` free to forge a\n * column. A catalog row is the one place both matter.\n */\nexport function cellLinkText(text: string): string {\n return linkText(text).replace(/\\|/g, '\\\\|')\n}\n\n/**\n * A markdown link with the label escaped and the URL scheme-checked. When the\n * URL is not a safe scheme the label renders as plain (escaped) text rather\n * than a clickable link — the substance is kept, the smuggled scheme is not.\n * `labelEscaper` lets a table cell escape `|` as well.\n */\nexport function safeLink(\n label: string,\n url: string,\n labelEscaper: (text: string) => string = linkText,\n): string {\n const text = labelEscaper(label)\n return isSafeUrl(url) ? `[${text}](${safeUrl(url)})` : text\n}\n\n/** A bottom-of-page section that may be truncated (whole lines only). */\nexport interface TailSection {\n headingLine: string\n items: string[]\n}\n\nfunction tailText(t: TailSection): string {\n return `${t.headingLine}\\n\\n${t.items.join('\\n')}`\n}\n\n/**\n * Join required blocks + tail sections, enforcing the byte budget.\n *\n * Truncation is strictly from the bottom: required blocks (the front-loaded\n * buying facts and the variants table) are never dropped, tail sections are\n * re-added top-down until the budget (minus the truncation note) is exhausted,\n * and a cut always ends the document — nothing renders after it. Items are\n * whole lines; nothing is ever cut mid-fact.\n *\n * If the required blocks alone exceed the budget, they are emitted anyway\n * (facts are never sacrificed to the byte budget) followed by the note.\n */\nexport function assembleWithBudget(\n requiredBlocks: string[],\n tail: TailSection[],\n maxBytes: number,\n): string {\n const full = [...requiredBlocks, ...tail.map(tailText)].join('\\n\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = requiredBlocks.join('\\n\\n')\n for (const section of tail) {\n const whole = `${out}\\n\\n${tailText(section)}`\n if (byteLength(whole) <= budget) {\n out = whole\n continue\n }\n // Section does not fit whole: add as many complete lines as fit.\n let partial = `${out}\\n\\n${section.headingLine}`\n let added = 0\n for (const item of section.items) {\n const next = `${partial}${added === 0 ? '\\n\\n' : '\\n'}${item}`\n if (byteLength(next) > budget) break\n partial = next\n added += 1\n }\n if (added > 0) out = partial\n break // truncate strictly from the bottom — nothing may appear after the cut\n }\n return `${out}${noteSuffix}`\n}\n","import type {\n Availability,\n CatalogItemSource,\n PolicySource,\n ProductSource,\n ProductVariantSource,\n RenderOptions,\n} from './types'\nimport { formatMoney } from './money'\nimport type { TailSection } from './internal/budget'\nimport {\n assembleWithBudget,\n byteLength,\n cell,\n cellLinkText,\n clampHeadingLevel,\n DEFAULT_MAX_BYTES,\n heading,\n inline,\n isSafeUrl,\n safeLink,\n TRUNCATION_NOTE,\n} from './internal/budget'\nimport { isIsoDate } from './internal/validate'\n\n/** Deterministic human labels for the availability enum (format mapping, not content). */\nconst AVAILABILITY_LABELS: Record<Availability, string> = {\n in_stock: 'In stock',\n out_of_stock: 'Out of stock',\n preorder: 'Preorder',\n backorder: 'Backorder',\n}\n\nfunction etaText(eta: [number, number]): string {\n const [min, max] = eta\n return min === max ? `${min} days` : `${min}-${max} days`\n}\n\nfunction variantsTable(variants: ProductVariantSource[], level: number): string {\n const lines = [\n heading(level, 'Variants'),\n '',\n '| ID | Title | Options | Price | Availability |',\n '| --- | --- | --- | --- | --- |',\n ]\n for (const v of variants) {\n const options =\n v.options !== undefined\n ? Object.entries(v.options)\n .map(([key, value]) => `${cell(key)}: ${cell(value)}`)\n .join('; ')\n : ''\n lines.push(\n `| ${cell(v.id)} | ${cell(v.title)} | ${options} | ${formatMoney(v.price)} | ${AVAILABILITY_LABELS[v.availability]} |`,\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * Render a product detail page as clean markdown. Buying facts come first:\n * title, price, availability, shipping, and returns all land in the opening\n * lines so an agent reading top-down never misses them. Every substantive\n * value is injected from `p` — nothing is invented or reworded.\n */\nexport function renderProductMarkdown(p: ProductSource, opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n const sub = clampHeadingLevel(level + 1)\n\n const facts: string[] = [heading(level, safeLink(p.title, p.url)), '']\n if (p.brand !== undefined) facts.push(`- **Brand:** ${inline(p.brand)}`)\n const price = formatMoney(p.price)\n facts.push(\n p.compareAtPrice !== undefined\n ? `- **Price:** ~~${formatMoney(p.compareAtPrice)}~~ ${price}`\n : `- **Price:** ${price}`,\n )\n facts.push(`- **Availability:** ${AVAILABILITY_LABELS[p.availability]}`)\n if (p.shipping !== undefined) {\n facts.push(`- **Shipping:** ${inline(p.shipping.summary)}`)\n if (p.shipping.freeThreshold !== undefined) {\n facts.push(` - Free shipping threshold: ${formatMoney(p.shipping.freeThreshold)}`)\n }\n if (p.shipping.regions !== undefined && p.shipping.regions.length > 0) {\n facts.push(` - Ships to: ${p.shipping.regions.map(inline).join(', ')}`)\n }\n if (p.shipping.etaDays !== undefined) {\n facts.push(` - Delivery estimate: ${etaText(p.shipping.etaDays)}`)\n }\n }\n if (p.returns !== undefined) {\n facts.push(`- **Returns:** ${inline(p.returns.summary)}`)\n if (p.returns.windowDays !== undefined) {\n facts.push(` - Return window: ${p.returns.windowDays} days`)\n }\n if (p.returns.url !== undefined && isSafeUrl(p.returns.url)) {\n facts.push(` - Policy: ${p.returns.url}`)\n }\n }\n // Last in the fact block, not first: `updated` is metadata about the facts\n // rather than one of the buying facts, and every line inserted above\n // `- **Availability:**` pushes a core fact further from the top of the\n // document (ARS D4 scores that byte offset). The label matches the document\n // renderer's `UPDATED_LABEL`; `tests/jsonld.test.ts` pins the two together.\n if (p.updated !== undefined && isIsoDate(p.updated)) {\n facts.push(`- **Updated:** ${inline(p.updated)}`)\n }\n\n const requiredBlocks: string[] = [facts.join('\\n')]\n if (p.variants !== undefined && p.variants.length > 0) {\n requiredBlocks.push(variantsTable(p.variants, sub))\n }\n\n const tail: TailSection[] = []\n if (p.description !== undefined && p.description.length > 0) {\n tail.push({ headingLine: heading(sub, 'Description'), items: p.description.split('\\n') })\n }\n if (p.attributes !== undefined) {\n const items = Object.entries(p.attributes).map(\n ([key, value]) => `- **${inline(key)}:** ${inline(value)}`,\n )\n if (items.length > 0) tail.push({ headingLine: heading(sub, 'Details'), items })\n }\n if (p.images !== undefined && p.images.length > 0) {\n const items = p.images.map((img) => {\n const label = img.alt !== undefined && img.alt.length > 0 ? img.alt : img.url\n return `- ${safeLink(label, img.url)}`\n })\n tail.push({ headingLine: heading(sub, 'Images'), items })\n }\n\n return assembleWithBudget(requiredBlocks, tail, maxBytes)\n}\n\n/**\n * Render store policies as markdown. Each policy is a linked heading followed\n * by its body byte-for-byte verbatim. Under the byte budget, whole policies\n * are kept in order; a policy whose body does not fit degrades to its linked\n * title (policy text is never partially rendered), and the document ends with\n * the truncation note.\n */\nexport function renderPolicyMarkdown(policies: PolicySource[], opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const titleLineFor = (pol: PolicySource): string => heading(level, safeLink(pol.title, pol.url))\n const blocks = policies.map((pol) => `${titleLineFor(pol)}\\n\\n${pol.body}`)\n const full = blocks.join('\\n\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = ''\n for (const pol of policies) {\n const titleLine = titleLineFor(pol)\n const block = `${titleLine}\\n\\n${pol.body}`\n const withBlock = out === '' ? block : `${out}\\n\\n${block}`\n if (byteLength(withBlock) <= budget) {\n out = withBlock\n continue\n }\n const withTitle = out === '' ? titleLine : `${out}\\n\\n${titleLine}`\n if (byteLength(withTitle) <= budget) out = withTitle\n break // truncate strictly from the bottom\n }\n return out === '' ? TRUNCATION_NOTE : `${out}${noteSuffix}`\n}\n\n/**\n * Render a catalog listing as a markdown table (title → link, price,\n * availability). Under the byte budget, whole rows are dropped from the\n * bottom and the truncation note is appended.\n */\nexport function renderCatalogMarkdown(items: CatalogItemSource[], opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const head = [\n heading(level, 'Catalog'),\n '',\n '| Title | Price | Availability |',\n '| --- | --- | --- |',\n ].join('\\n')\n const rows = items.map(\n (item) =>\n `| ${safeLink(item.title, item.url, cellLinkText)} | ${formatMoney(item.price)} | ${AVAILABILITY_LABELS[item.availability]} |`,\n )\n const full = [head, ...rows].join('\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = head\n for (const row of rows) {\n const next = `${out}\\n${row}`\n if (byteLength(next) > budget) break\n out = next\n }\n return `${out}${noteSuffix}`\n}\n","/**\n * Fact rendering: the deterministic `FactValue` → markdown mapping, the fixed\n * label maps, the URL scheme allowlist, and the escaping rules.\n *\n * This file is where the injection-only guarantee is actually enforced for the\n * universal path. Every rule below is mechanical rather than advisory, because\n * an advisory rule in a renderer is a rule that holds until the first hurried\n * patch:\n *\n * - Every renderer-authored string in this package is a named constant here.\n * The whitelist in README.md is the list of these constants, and\n * `tests/documents-integrity.test.ts` re-states that list as literals (not\n * by importing these constants) so that adding scaffolding cannot silently\n * whitelist itself.\n * - A malformed value is DROPPED, never repaired. Repairing a fact invents a\n * value the merchant never stated (source validation); dropping it only loses\n * information, which the agent can still get from the canonical page.\n * - URLs are checked against a scheme allowlist. The commerce path only ever\n * emitted merchant-controlled product/policy URLs; the universal path emits\n * arbitrary merchant-supplied link targets, and `[Click here](javascript:…)`\n * handed to an agent under our formatting authority is a phishing primitive.\n * - Money throws rather than rounds or guesses, matching `formatMoney`. A\n * thrown render is caught by the gateway and falls through to HTML; a\n * silently wrong price is served forever.\n */\n\nimport { formatMoney } from '../money'\nimport { cell, heading, inline } from '../internal/budget'\nimport { isIsoDate } from '../internal/validate'\nimport type {\n BillingPeriod,\n DocumentAccess,\n Fact,\n FactValue,\n HoursException,\n HoursInterval,\n HoursSpec,\n Weekday,\n} from './types'\n\n/* ------------------------------------------------------------------ *\n * Fixed label maps — the only renderer-authored vocabulary.\n * ------------------------------------------------------------------ */\n\n/** Fixed suffix per billing period. Format mapping of a closed enum, not content. */\nexport const PERIOD_SUFFIX: Record<BillingPeriod, string> = {\n one_time: 'one-time',\n hour: 'per hour',\n day: 'per day',\n week: 'per week',\n month: 'per month',\n quarter: 'per quarter',\n year: 'per year',\n}\n\n/** Fixed label map for booleans. */\nexport const BOOLEAN_LABELS: Record<'true' | 'false', string> = {\n true: 'Yes',\n false: 'No',\n}\n\n/** Fixed weekday labels. English only and deliberately not localised: the\n * output is a machine-readable format transformation, and a locale would make\n * the same source render differently for different requesters (consistent source content). */\nexport const WEEKDAY_LABELS: Record<Weekday, string> = {\n monday: 'Monday',\n tuesday: 'Tuesday',\n wednesday: 'Wednesday',\n thursday: 'Thursday',\n friday: 'Friday',\n saturday: 'Saturday',\n sunday: 'Sunday',\n}\n\n/** Fixed weekday order. Every one of the seven renders, always. */\nexport const WEEKDAY_ORDER: readonly Weekday[] = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n]\n\n/** `intervals: []` — the merchant stated the day and stated it is closed. */\nexport const CLOSED_LABEL = 'Closed'\n\n/** Weekday absent from `weekly` — a different fact from `Closed`. */\nexport const NOT_STATED_LABEL = 'Not stated'\n\n/** An `hours` fact is not a valid table cell; the row links out instead. */\nexport const SEE_PAGE_LABEL = 'See page'\n\n/** Fixed labels used for structural bullets and table headers. */\nexport const UPDATED_LABEL = 'Updated'\nexport const PHONE_LABEL = 'Phone'\nexport const EMAIL_LABEL = 'Email'\nexport const ADDRESS_LABEL = 'Address'\nexport const DAY_LABEL = 'Day'\nexport const DATE_LABEL = 'Date'\nexport const HOURS_LABEL = 'Hours'\nexport const NOTE_LABEL = 'Note'\nexport const TITLE_LABEL = 'Title'\n\n/** Fixed headings. */\nexport const EXCEPTIONS_HEADING = 'Exceptions'\nexport const CONTACT_HEADING = 'Contact'\nexport const ACTIONS_HEADING = 'Actions'\nexport const RELATED_HEADING = 'Related'\nexport const CONTENTS_HEADING = 'Contents'\n\n/** Fixed access-level words used inside the single access notice sentence. */\nexport const ACCESS_LABELS: Record<DocumentAccess, string> = {\n free: 'free',\n registered: 'registration required',\n metered: 'metered',\n subscriber: 'subscription required',\n}\n\n/**\n * The fixed access notice. Emitted in place of `sections` whenever access is\n * not 'free'. It states only that the prose was not served and at what access\n * level — it never paraphrases the withheld text.\n */\nexport function accessNotice(access: DocumentAccess): string {\n return `*Full text is not served to agents at this URL (access: ${ACCESS_LABELS[access]}).*`\n}\n\n/** The fixed timezone sentence rendered above every hours table. */\nexport function timeZoneSentence(timeZone: string): string {\n return `All times are local to ${inline(timeZone)}.`\n}\n\n/* ------------------------------------------------------------------ *\n * URL scheme allowlist and escaping.\n * ------------------------------------------------------------------ */\n\n/** The only schemes this package will put behind a markdown link. */\nexport const ALLOWED_URL_SCHEMES: readonly string[] = ['https:', 'http:', 'mailto:', 'tel:']\n\n/**\n * True when `raw` is an absolute URL with an allowlisted scheme. Relative URLs\n * are rejected: this package has no base URL to resolve them against, and\n * guessing one would emit a link the merchant never wrote.\n */\nexport function isAllowedUrl(raw: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(raw)\n } catch {\n return false\n }\n return ALLOWED_URL_SCHEMES.includes(parsed.protocol)\n}\n\n/**\n * Escape a markdown link label. `]`, `(`, and `)` would otherwise let source\n * text break out of the label and forge a link target.\n */\nexport function linkLabel(text: string): string {\n return inline(text).replace(/[\\]()]/g, (c) => `\\\\${c}`)\n}\n\n/** `[label](url)` with the label escaped. Callers must allowlist `url` first. */\nexport function markdownLink(label: string, url: string): string {\n return `[${linkLabel(label)}](${url})`\n}\n\n/**\n * A markdown link safe to drop into a table cell. `cell()` cannot be used on a\n * finished link — it would escape nothing useful and `linkLabel` has already\n * run — so the `|` guard is applied on top instead.\n */\nexport function cellLink(label: string, url: string): string {\n return markdownLink(label, url).replace(/\\|/g, '\\\\|')\n}\n\n/* ------------------------------------------------------------------ *\n * Value validation.\n * ------------------------------------------------------------------ */\n\n/**\n * ISO 8601 date or datetime. Lives in `internal/validate.ts` since the\n * commerce renderers began accepting `updated` on the same terms; re-exported\n * here so this file stays the one place the document path imports value\n * validation from. (`export { … } from` would not bind the name locally, and\n * `factText` below calls it — hence the import plus re-export.)\n */\nexport { isIsoDate }\n\n/** 'YYYY-MM-DD' only — the form `HoursException.date` is specified in. */\nexport function isIsoDay(value: string): boolean {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n}\n\nconst HH_MM = /^([01]\\d|2[0-3]):[0-5]\\d$/\n\n/**\n * A single interval is valid only if both ends are 'HH:MM' and it does not\n * wrap. Overnight spans are expressed as two intervals on two days; accepting\n * `22:00`–`02:00` here would make the same string mean two different things.\n */\nfunction isValidInterval(i: HoursInterval): boolean {\n return HH_MM.test(i.opens) && HH_MM.test(i.closes) && i.closes > i.opens\n}\n\nfunction intervalsText(intervals: HoursInterval[]): string {\n return intervals.map((i) => `${i.opens}-${i.closes}`).join(', ')\n}\n\n/* ------------------------------------------------------------------ *\n * FactValue → text.\n * ------------------------------------------------------------------ */\n\nfunction numberText(value: number, unit?: string): string | null {\n if (!Number.isFinite(value)) return null\n const text = String(value)\n // Exponential form (\"1e+21\") is a number an agent will misparse and a human\n // never wrote. Drop rather than reformat: reformatting invents digits.\n if (text.includes('e') || text.includes('E')) return null\n return unit !== undefined ? `${text} ${inline(unit)}` : text\n}\n\nfunction moneyText(v: Extract<FactValue, { type: 'money' }>): string {\n let text = formatMoney(v.value)\n if (v.maxValue !== undefined) {\n if (v.maxValue.currency.toUpperCase() !== v.value.currency.toUpperCase()) {\n throw new TypeError(\n `Money range currencies must match, got: ${v.value.currency} and ${v.maxValue.currency}`,\n )\n }\n if (v.maxValue.amount < v.value.amount) {\n throw new TypeError(\n `Money range maxValue must not be below value, got: ${String(v.value.amount)} and ${String(v.maxValue.amount)}`,\n )\n }\n text = `${text}-${formatMoney(v.maxValue)}`\n }\n if (v.period !== undefined) text = `${text} ${PERIOD_SUFFIX[v.period]}`\n if (v.per !== undefined) text = `${text} ${inline(v.per)}`\n return text\n}\n\n/**\n * Render a scalar fact value to its single-line inline form, or `null` when\n * the value is malformed (dropped) or is an `hours` value (rendered as its own\n * block, not as a fact line).\n *\n * Throws only for money ranges that are internally contradictory — see the\n * file header.\n */\nexport function factValueText(value: FactValue): string | null {\n switch (value.type) {\n case 'text':\n return inline(value.value)\n case 'list':\n return value.value.length > 0 ? value.value.map(inline).join(', ') : null\n case 'number':\n return numberText(value.value, value.unit)\n case 'boolean':\n return BOOLEAN_LABELS[value.value ? 'true' : 'false']\n case 'money':\n return moneyText(value)\n case 'date':\n return isIsoDate(value.value) ? value.value : null\n case 'url':\n if (!isAllowedUrl(value.value)) return null\n return value.label !== undefined ? markdownLink(value.label, value.value) : value.value\n case 'hours':\n return null\n }\n}\n\n/**\n * Render one fact as `- **Label:** value`, plus an indented note line when the\n * fact carries one. Returns `null` when the value is dropped or is an `hours`\n * value.\n */\nexport function renderFactLine(fact: Fact): string | null {\n const text = factValueText(fact.value)\n if (text === null) return null\n const line = `- **${inline(fact.label)}:** ${text}`\n return fact.note !== undefined ? `${line}\\n - ${inline(fact.note)}` : line\n}\n\n/**\n * Render a fact value as a table cell. Two differences from a fact line: every\n * cell is `|`-escaped, and an `hours` value degrades to a link to the item's\n * own page rather than trying to flatten a table into a cell.\n */\nexport function factCellText(value: FactValue, itemUrl: string): string | null {\n if (value.type === 'hours') {\n return isAllowedUrl(itemUrl) ? cellLink(SEE_PAGE_LABEL, itemUrl) : SEE_PAGE_LABEL\n }\n if (value.type === 'url') {\n if (!isAllowedUrl(value.value)) return null\n // Already an escaped link; only the `|` guard still applies.\n return value.label !== undefined\n ? cellLink(value.label, value.value)\n : value.value.replace(/\\|/g, '\\\\|')\n }\n const text = factValueText(value)\n return text === null ? null : cell(text)\n}\n\n/* ------------------------------------------------------------------ *\n * Hours block.\n * ------------------------------------------------------------------ */\n\nfunction exceptionRow(e: HoursException): string | null {\n if (!isIsoDay(e.date)) return null\n let hours: string\n if (e.closed === true) {\n hours = CLOSED_LABEL\n } else if (e.intervals !== undefined && e.intervals.length > 0) {\n if (!e.intervals.every(isValidInterval)) return null\n hours = intervalsText(e.intervals)\n } else if (e.intervals !== undefined) {\n hours = CLOSED_LABEL\n } else {\n hours = NOT_STATED_LABEL\n }\n const note = e.note !== undefined ? cell(e.note) : ''\n return `| ${e.date} | ${hours} | ${note} |`\n}\n\n/**\n * Render one `hours` fact as its own block, headed by the fact's own label.\n *\n * The heading is `Fact.label`, not a fixed \"Hours\": a clinic with \"Office\n * hours\" and \"Lab hours\" must not emit two identically-titled tables that an\n * agent cannot tell apart.\n *\n * All seven weekdays always render. An absent weekday is `Not stated` and a\n * present-but-empty one is `Closed`; collapsing those two into one label would\n * assert a closure the merchant never stated. Nothing here computes whether\n * the place is open now — that requires a clock and a timezone database, and a\n * wrong answer to \"are they open\" is worse than no answer.\n *\n * Returns `null` when the spec is malformed (missing timezone, or any invalid\n * interval anywhere in `weekly`). Partial hours are dropped whole: a table\n * missing the one day that was malformed reads as authoritative and is not.\n */\nexport function renderHoursBlock(\n label: string,\n spec: HoursSpec,\n level: number,\n subLevel: number,\n): string | null {\n if (typeof spec.timeZone !== 'string' || spec.timeZone.trim() === '') return null\n\n const byDay = new Map<Weekday, HoursInterval[]>()\n for (const rule of spec.weekly) {\n if (!rule.intervals.every(isValidInterval)) return null\n byDay.set(rule.day, rule.intervals)\n }\n\n const lines: string[] = [\n heading(level, inline(label)),\n '',\n timeZoneSentence(spec.timeZone),\n '',\n `| ${DAY_LABEL} | ${HOURS_LABEL} |`,\n '| --- | --- |',\n ]\n for (const day of WEEKDAY_ORDER) {\n const intervals = byDay.get(day)\n const text =\n intervals === undefined\n ? NOT_STATED_LABEL\n : intervals.length === 0\n ? CLOSED_LABEL\n : intervalsText(intervals)\n lines.push(`| ${WEEKDAY_LABELS[day]} | ${text} |`)\n }\n\n if (spec.note !== undefined) {\n lines.push('', `- **${NOTE_LABEL}:** ${inline(spec.note)}`)\n }\n\n const exceptionRows = (spec.exceptions ?? [])\n .map(exceptionRow)\n .filter((row): row is string => row !== null)\n if (exceptionRows.length > 0) {\n lines.push(\n '',\n heading(subLevel, EXCEPTIONS_HEADING),\n '',\n `| ${DATE_LABEL} | ${HOURS_LABEL} | ${NOTE_LABEL} |`,\n '| --- | --- | --- |',\n ...exceptionRows,\n )\n }\n\n return lines.join('\\n')\n}\n","/**\n * The universal renderers: any page that is not a product, a policy set, or a\n * catalog. Same signature shape and the same `RenderOptions` as the three\n * commerce renderers, and the same guarantee — pure, deterministic, no clock,\n * no locale, no network, and every substantive value injected from the source\n * object.\n *\n * Block order and truncation are stated once, here and in README.md, and\n * nowhere else:\n *\n * 1. `# [title](url)` required\n * 2. `> summary` required\n * 3. `- **Updated:**` + scalar fact lines required\n * 4. `## <fact label>` hours table, one per hours fact required\n * 5. `## Contact` required\n * 6. `## Actions` required\n * 7. `## <section heading>` prose (only when free) truncatable\n * 8. `## Related` truncatable, first to go\n *\n * `assembleWithBudget` truncates strictly from the bottom, so putting\n * `related` last in the tail is what makes prose survive a tight budget and\n * cross-links drop. The order of that array is load-bearing, not cosmetic.\n *\n * Two ceilings, not one. `maxBytes` governs the truncatable tail as it does\n * for commerce. A second, absolute ceiling at `4 × maxBytes` governs the\n * required blocks, because \"facts are never sacrificed\" is a safe promise for\n * a PDP with a dozen fields and an unbounded one for a government service page\n * with six twenty-item lists — without the hard ceiling a merchant's own data\n * shape decides our response size.\n */\n\nimport type { RenderOptions } from '../types'\nimport type { TailSection } from '../internal/budget'\nimport {\n assembleWithBudget,\n byteLength,\n cell,\n clampHeadingLevel,\n DEFAULT_MAX_BYTES,\n heading,\n inline,\n TRUNCATION_NOTE,\n} from '../internal/budget'\nimport type {\n CollectionItemSource,\n CollectionSource,\n DocumentSectionSource,\n DocumentSource,\n} from './types'\nimport {\n ACTIONS_HEADING,\n ADDRESS_LABEL,\n CONTACT_HEADING,\n CONTENTS_HEADING,\n EMAIL_LABEL,\n NOTE_LABEL,\n PHONE_LABEL,\n RELATED_HEADING,\n TITLE_LABEL,\n UPDATED_LABEL,\n accessNotice,\n cellLink,\n factCellText,\n isAllowedUrl,\n isIsoDate,\n linkLabel,\n markdownLink,\n renderFactLine,\n renderHoursBlock,\n} from './facts'\n\n/** Hard ceilings. Merchant data shape must not decide our response size. */\nconst MAX_FACTS = 60\nconst MAX_ACTIONS = 20\n/**\n * Exported so `documents/jsonld.ts` truncates the same listing at the same\n * row. Two ceilings would let the ItemList and the markdown table disagree\n * about how long the collection is, at one URL, for the same requester.\n */\nexport const MAX_COLLECTION_ROWS = 500\nconst MAX_COLLECTION_COLUMNS = 12\nconst HARD_CEILING_MULTIPLE = 4\n\n/**\n * Absolute output cap. `assembleWithBudget` deliberately emits required blocks\n * even when they alone exceed `maxBytes`; this bounds that escape hatch. Cuts\n * are on whole lines, and the truncation note always ends the document.\n */\nfunction applyHardCeiling(out: string, maxBytes: number): string {\n const ceiling = maxBytes * HARD_CEILING_MULTIPLE\n if (byteLength(out) <= ceiling) return out\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = ceiling - byteLength(noteSuffix)\n let kept = ''\n for (const line of out.split('\\n')) {\n const next = kept === '' ? line : `${kept}\\n${line}`\n if (byteLength(next) > budget) break\n kept = next\n }\n return kept === '' ? TRUNCATION_NOTE : `${kept}${noteSuffix}`\n}\n\n/** `> ` prefix on every line; blank lines stay blank inside the quote. */\nfunction blockquote(text: string): string[] {\n return text.split('\\n').map((line) => (line.length > 0 ? `> ${line}` : '>'))\n}\n\n/**\n * A prose section as a truncatable tail block.\n *\n * `assembleWithBudget` renders a tail block as `headingLine` + blank line +\n * items. A section with a heading maps onto that exactly. A section without\n * one has no heading to put there, so its first body line takes that slot and\n * the blank line the assembler inserts consumes the body's own paragraph\n * break. For prose — where paragraphs are already blank-line separated — this\n * is byte-for-byte verbatim; for a body with no blank line after its first\n * line it inserts one paragraph break. No characters are ever added, removed,\n * or reordered either way.\n */\nfunction sectionTail(section: DocumentSectionSource, level: number): TailSection {\n const lines = section.body.split('\\n')\n if (section.heading !== undefined && section.heading.length > 0) {\n return { headingLine: heading(level, inline(section.heading)), items: lines }\n }\n const rest = lines.slice(1)\n if (rest[0] === '') rest.shift()\n return { headingLine: lines[0] ?? '', items: rest }\n}\n\n/**\n * Render any non-commerce page as clean markdown. Facts come first: an agent\n * reading top-down gets the whole machine-readable payload before any prose,\n * and prose is the only thing the byte budget can take away.\n */\nexport function renderDocumentMarkdown(doc: DocumentSource, opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n const sub = clampHeadingLevel(level + 1)\n const subSub = clampHeadingLevel(sub + 1)\n const access = doc.access ?? 'free'\n\n // A document whose own canonical URL is not allowlisted still renders — an\n // agent losing the self-link is better than losing the facts — but it never\n // renders as a link.\n const titleText = isAllowedUrl(doc.url)\n ? markdownLink(doc.title, doc.url)\n : linkLabel(doc.title)\n\n const updated = doc.updated !== undefined && isIsoDate(doc.updated) ? doc.updated : undefined\n const facts = (doc.facts ?? []).slice(0, MAX_FACTS)\n\n const factLines: string[] = []\n if (updated !== undefined) factLines.push(`- **${UPDATED_LABEL}:** ${updated}`)\n for (const fact of facts) {\n // Dedup: a top-level `updated` wins over a fact that repeats it. Two\n // \"Updated\" lines disagreeing is worse than one that might be stale.\n if (updated !== undefined && fact.label.trim().toLowerCase() === UPDATED_LABEL.toLowerCase()) {\n continue\n }\n const line = renderFactLine(fact)\n if (line !== null) factLines.push(line)\n }\n\n const head: string[] = [heading(level, titleText)]\n if (doc.summary !== undefined && doc.summary.length > 0) {\n head.push('', ...blockquote(doc.summary))\n }\n if (factLines.length > 0) head.push('', ...factLines)\n\n const requiredBlocks: string[] = [head.join('\\n')]\n\n for (const fact of facts) {\n if (fact.value.type !== 'hours') continue\n const block = renderHoursBlock(fact.label, fact.value.value, sub, subSub)\n if (block !== null) requiredBlocks.push(block)\n }\n\n const contactLines: string[] = []\n const contact = doc.contact\n if (contact !== undefined) {\n if (contact.phone !== undefined) contactLines.push(`- **${PHONE_LABEL}:** ${inline(contact.phone)}`)\n if (contact.email !== undefined) contactLines.push(`- **${EMAIL_LABEL}:** ${inline(contact.email)}`)\n if (contact.address !== undefined && contact.address.length > 0) {\n contactLines.push(`- **${ADDRESS_LABEL}:** ${contact.address.map(inline).join(', ')}`)\n }\n // No label: there is no whitelisted word for \"the contact URL\", and\n // inventing one would put renderer prose in the output.\n if (contact.url !== undefined && isAllowedUrl(contact.url)) contactLines.push(`- ${contact.url}`)\n }\n if (contactLines.length > 0) {\n requiredBlocks.push([heading(sub, CONTACT_HEADING), '', ...contactLines].join('\\n'))\n }\n\n const actionLines: string[] = []\n for (const action of (doc.actions ?? []).slice(0, MAX_ACTIONS)) {\n if (!isAllowedUrl(action.url)) continue\n actionLines.push(`- ${markdownLink(action.label, action.url)}`)\n if (action.note !== undefined) actionLines.push(` - ${inline(action.note)}`)\n }\n if (actionLines.length > 0) {\n requiredBlocks.push([heading(sub, ACTIONS_HEADING), '', ...actionLines].join('\\n'))\n }\n\n if (access !== 'free') requiredBlocks.push(accessNotice(access))\n\n const tail: TailSection[] = []\n // Mechanical, not a prose rule: `sections` is only ever read on this branch,\n // so no renderer bug below can leak a paywalled body.\n if (access === 'free') {\n for (const section of doc.sections ?? []) tail.push(sectionTail(section, sub))\n }\n\n const relatedItems: string[] = []\n for (const link of doc.related ?? []) {\n if (!isAllowedUrl(link.url)) continue\n relatedItems.push(`- ${markdownLink(link.title, link.url)}`)\n if (link.note !== undefined) relatedItems.push(` - ${inline(link.note)}`)\n }\n if (relatedItems.length > 0) {\n tail.push({ headingLine: heading(sub, RELATED_HEADING), items: relatedItems })\n }\n\n return applyHardCeiling(assembleWithBudget(requiredBlocks, tail, maxBytes), maxBytes)\n}\n\n/* ------------------------------------------------------------------ *\n * Collections.\n * ------------------------------------------------------------------ */\n\n/**\n * Exact byte length of `| a | b | c |` given the byte lengths of the cells:\n * two spaces around each cell, one pipe between each pair, one at each end.\n */\nfunction rowBytes(cellByteSum: number, columnCount: number): number {\n return cellByteSum + 3 * columnCount + 1\n}\n\nfunction tableRow(cells: string[]): string {\n return `| ${cells.join(' | ')} |`\n}\n\n/** One item's cells, in the order their columns should first appear. */\nfunction itemCells(item: CollectionItemSource): { label: string; text: string }[] {\n const cells: { label: string; text: string }[] = []\n if (item.summary !== undefined && item.summary.length > 0) {\n cells.push({ label: NOTE_LABEL, text: cell(item.summary) })\n }\n for (const fact of item.facts ?? []) {\n const text = factCellText(fact.value, item.url)\n if (text === null) continue\n cells.push({ label: cell(fact.label), text })\n }\n return cells\n}\n\nfunction titleCell(item: CollectionItemSource): string {\n return isAllowedUrl(item.url) ? cellLink(item.title, item.url) : cell(item.title)\n}\n\n/**\n * Render a listing page. Two deterministic modes and no third: if no item\n * carries facts the output is a link list, otherwise it is a table.\n *\n * The table's columns are the ordered union of fact labels by first\n * appearance, accumulated in the SAME streaming pass that spends the byte\n * budget. That is the whole point: compute the union first and the header can\n * advertise columns belonging only to rows the budget then drops, which is a\n * table of empty cells describing data we did not send. Byte accounting is\n * exact rather than estimated (see `rowBytes`), so the pass never has to\n * re-render to find out whether it overshot.\n *\n * An item `summary` occupies a `Note` column, positioned by the same\n * first-appearance rule. A merchant fact literally labelled `Note` on an item\n * that also has a summary collides; the summary wins, because it was written\n * for the listing.\n */\nexport function renderCollectionMarkdown(\n collection: CollectionSource,\n opts?: RenderOptions,\n): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const title = collection.title !== undefined ? collection.title : CONTENTS_HEADING\n const titleText = isAllowedUrl(collection.url)\n ? markdownLink(title, collection.url)\n : linkLabel(title)\n const head = heading(level, titleText)\n\n const items = collection.items\n if (items.length === 0) return head\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n const anyFacts = items.some((item) => (item.facts ?? []).length > 0)\n\n if (!anyFacts) return linkList(head, items, budget)\n\n // Streaming pass: columns and rows grow together, bounded by `budget`.\n const columns: string[] = []\n const rows: Map<string, string>[] = []\n let headerCellBytes = byteLength(TITLE_LABEL)\n let bodyCellBytes = 0\n let truncated = false\n\n // head + '\\n\\n' + headerRow + '\\n' + separatorRow + ('\\n' + row) per row.\n // Separator cells are always '---', i.e. 3 bytes each.\n const base = byteLength(head) + 2\n const totalBytes = (columnCount: number, rowCount: number): number =>\n base +\n rowBytes(headerCellBytes, columnCount) +\n 1 +\n rowBytes(3 * columnCount, columnCount) +\n bodyCellBytes +\n rowCount * (3 * columnCount + 2)\n\n for (const item of items) {\n if (rows.length >= MAX_COLLECTION_ROWS) {\n truncated = true\n break\n }\n\n const cells = itemCells(item)\n const values = new Map<string, string>()\n const newColumns: string[] = []\n for (const { label, text } of cells) {\n if (values.has(label)) continue // first write wins within a row\n if (!columns.includes(label) && !newColumns.includes(label)) {\n if (columns.length + newColumns.length >= MAX_COLLECTION_COLUMNS) continue\n newColumns.push(label)\n }\n values.set(label, text)\n }\n values.set(TITLE_LABEL, titleCell(item))\n\n const nextColumnCount = 1 + columns.length + newColumns.length\n const addedHeaderBytes = newColumns.reduce((sum, label) => sum + byteLength(label), 0)\n const addedBodyBytes = [...values.values()].reduce((sum, text) => sum + byteLength(text), 0)\n\n const savedHeader = headerCellBytes\n const savedBody = bodyCellBytes\n headerCellBytes += addedHeaderBytes\n bodyCellBytes += addedBodyBytes\n if (totalBytes(nextColumnCount, rows.length + 1) > budget) {\n headerCellBytes = savedHeader\n bodyCellBytes = savedBody\n truncated = true\n break\n }\n\n columns.push(...newColumns)\n rows.push(values)\n }\n\n // No row fit. A bare header advertises columns nothing fills — exactly what\n // the streaming pass exists to prevent — so emit no table at all.\n if (rows.length === 0) return `${head}${noteSuffix}`\n\n const header = [TITLE_LABEL, ...columns]\n const lines = [\n head,\n '',\n tableRow(header),\n tableRow(header.map(() => '---')),\n ...rows.map((values) => tableRow(header.map((label) => values.get(label) ?? ''))),\n ]\n const out = lines.join('\\n')\n return truncated ? `${out}${noteSuffix}` : out\n}\n\n/** Link-list mode: whole entries only, dropped from the bottom. */\nfunction linkList(head: string, items: CollectionItemSource[], budget: number): string {\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n let out = head\n let truncated = false\n let rendered = 0\n\n for (const item of items) {\n if (rendered >= MAX_COLLECTION_ROWS) {\n truncated = true\n break\n }\n const link = isAllowedUrl(item.url)\n ? markdownLink(item.title, item.url)\n : inline(item.title)\n const entry: string[] = [`- ${link}`]\n if (item.summary !== undefined && item.summary.length > 0) {\n entry.push(` - ${inline(item.summary)}`)\n }\n const next = `${out}${rendered === 0 ? '\\n\\n' : '\\n'}${entry.join('\\n')}`\n if (byteLength(next) > budget) {\n truncated = true\n break\n }\n out = next\n rendered += 1\n }\n\n return truncated ? `${out}${noteSuffix}` : out\n}\n","/**\n * `CollectionSource` → schema.org `ItemList` JSON-LD.\n *\n * The listing counterpart to `src/jsonld.ts`'s `Product`. Before this existed,\n * a collection served through the universal gateway carried a markdown table\n * and no structured data at all, so a caller that reads JSON-LD first — and a\n * scorer looking for a recognised type — found nothing on a page whose entire\n * purpose is enumerating things.\n *\n * Injection-only, on the same terms as every other renderer here:\n *\n * - `name` is emitted ONLY when the source supplies a title. The markdown\n * renderer falls back to the fixed `Contents` heading because a document\n * needs a heading for structure; JSON-LD does not, and emitting the fallback\n * would make this package assert a name the merchant never wrote.\n * - URLs pass the same scheme allowlist the markdown path uses. A `ListItem`\n * whose URL is rejected still renders with its name — the item exists, we\n * just decline to publish a link to it. Skipping this check would make the\n * JSON-LD a `javascript:` sink that the markdown renderer already blocks.\n * - `numberOfItems` counts the elements ACTUALLY EMITTED, not `items.length`.\n * A 900-item listing truncates to `MAX_COLLECTION_ROWS`, and a document that\n * announced 900 while listing 500 would be internally inconsistent — an\n * agent trusting the count would page for items that are not there.\n * - Item facts are not projected into the list. `ListItem` has no honest slot\n * for an arbitrary labelled fact, and inventing property names for merchant\n * labels is exactly the inference this package does not do. The facts are in\n * the markdown table, which is where the renderer's contract puts them.\n */\n\nimport type { CollectionItemSource, CollectionSource } from './types'\nimport { isAllowedUrl } from './facts'\nimport { MAX_COLLECTION_ROWS } from './markdown'\nimport { isIsoDate, isLanguageTag } from '../internal/validate'\n\nfunction listItem(item: CollectionItemSource, position: number): Record<string, unknown> {\n const out: Record<string, unknown> = { '@type': 'ListItem', position }\n if (isAllowedUrl(item.url)) out.url = item.url\n out.name = item.title\n return out\n}\n\n/**\n * Render a schema.org ItemList from a collection source. Pure, deterministic,\n * and fixed in key order for snapshot stability — same contract as\n * `renderProductJsonLd`.\n */\nexport function renderCollectionJsonLd(collection: CollectionSource): Record<string, unknown> {\n const out: Record<string, unknown> = {\n '@context': 'https://schema.org',\n '@type': 'ItemList',\n }\n if (isAllowedUrl(collection.url)) out.url = collection.url\n if (collection.title !== undefined) out.name = collection.title\n if (collection.language !== undefined && isLanguageTag(collection.language)) {\n out.inLanguage = collection.language\n }\n\n const elements = collection.items\n .slice(0, MAX_COLLECTION_ROWS)\n .map((item, index) => listItem(item, index + 1))\n\n out.numberOfItems = elements.length\n out.itemListElement = elements\n if (collection.updated !== undefined && isIsoDate(collection.updated)) {\n out.dateModified = collection.updated\n }\n return out\n}\n","/** Conservative, compiled-in presentation strategies. No remote code or prose. */\nexport interface CompatibilityProfile {\n id: 'baseline' | 'source-envelope' | 'section-index'\n version: 1\n}\n\nexport const BASELINE_PROFILE: Readonly<CompatibilityProfile> = Object.freeze({\n id: 'baseline',\n version: 1,\n})\nexport const COMPATIBILITY_RUNTIME_VERSION = 1\n\nexport function validateCompatibilityProfile(value: unknown): CompatibilityProfile | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const profile = value as Record<string, unknown>\n if (Object.keys(profile).some((key) => key !== 'id' && key !== 'version')) return null\n if (\n profile.version !== 1 ||\n typeof profile.id !== 'string' ||\n !['baseline', 'source-envelope', 'section-index'].includes(profile.id)\n )\n return null\n return { id: profile.id as CompatibilityProfile['id'], version: 1 }\n}\n\nexport interface CompatibilityRendering {\n markdown: string\n /** Actual presentation served, including budget/invalid-selection fallback. */\n profile: CompatibilityProfile\n}\n\n/**\n * Baseline markdown stays a contiguous, byte-identical substring. Candidates\n * add orientation only; they cannot rewrite, remove or reorder any source fact\n * or qualification. Existing renderer truncation still applies. If additions\n * do not fit the caller's budget, use the baseline and report that honestly.\n */\nexport function applyCompatibilityProfile(\n markdown: string,\n selected: unknown,\n options: { canonicalUrl: string; maxBytes?: number },\n): CompatibilityRendering {\n const profile = validateCompatibilityProfile(selected) ?? BASELINE_PROFILE\n const baseline = { markdown, profile: { ...BASELINE_PROFILE } }\n if (profile.id === 'baseline') return baseline\n let prefix = ''\n if (profile.id === 'source-envelope') {\n let canonical: URL\n try {\n canonical = new URL(options.canonicalUrl)\n } catch {\n return baseline\n }\n if (\n !['https:', 'http:'].includes(canonical.protocol) ||\n canonical.username ||\n canonical.password\n )\n return baseline\n // JSON encoding makes line breaks and markdown delimiters inert metadata.\n prefix = `Source: ${JSON.stringify(canonical.href)}\\n\\n`\n } else {\n // Navigation duplicates only existing headings; merchant text remains intact.\n const headings = markdown\n .split('\\n')\n .filter((line) => /^#{1,6} /.test(line))\n .slice(0, 12)\n if (headings.length < 2) return baseline\n prefix = `Sections on this page:\\n${headings.map((line) => `- ${line.replace(/^#{1,6} /, '')}`).join('\\n')}\\n\\n`\n }\n const output = prefix + markdown\n const bytes = new TextEncoder().encode(output).byteLength\n if (new TextEncoder().encode(prefix).byteLength > 1024 || bytes > (options.maxBytes ?? 5120))\n return baseline\n return { markdown: output, profile }\n}\n"]}
1
+ {"version":3,"sources":["../src/money.ts","../src/internal/validate.ts","../src/jsonld.ts","../src/internal/budget.ts","../src/markdown.ts","../src/documents/facts.ts","../src/documents/markdown.ts","../src/documents/jsonld.ts","../src/compatibility.ts","../src/frontmatter.ts"],"names":["text","block"],"mappings":";;;AAMA,IAAM,YAAA,uBAAmB,GAAA,CAAI;AAAA,EAC3B,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGD,IAAM,aAAA,mBAAgB,IAAI,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,KAAK,CAAC,CAAA;AAO/E,IAAM,OAAA,GAAkC;AAAA,EACtC,GAAA,EAAK,GAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,MAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAEA,SAAS,gBAAgB,IAAA,EAAsB;AAC7C,EAAA,IAAI,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA,EAAG,OAAO,CAAA;AACnC,EAAA,IAAI,aAAA,CAAc,GAAA,CAAI,IAAI,CAAA,EAAG,OAAO,CAAA;AACpC,EAAA,OAAO,CAAA;AACT;AAEA,SAAS,YAAY,CAAA,EAAyD;AAC5E,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,CAAA,CAAE,MAAM,CAAA,EAAG;AAE/B,IAAA,MAAM,IAAI,SAAA;AAAA,MACR,CAAA,4DAAA,EAA+D,MAAA,CAAO,CAAA,CAAE,MAAM,CAAC,CAAA;AAAA,KACjF;AAAA,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,IAAK,qBAAA,EAAuB,OAAO,IAAA;AACtD,EAAA,MAAM,QAAQ,KAAA,CAAM;AAAA,IAClB,CAAC,SAAS,KAAK,CAAA;AAAA,IACf,CAAC,iBAAiB,SAAS,CAAA;AAAA,IAC3B,CAAC,gBAAgB,OAAO;AAAA,GACzB,CAAA;AACD,EAAA,OAAO,UAAA,CAAW,KAAK,CAAA,IAAK,qBAAA,GAAwB,KAAA,GAAQ,EAAA;AAC9D","file":"index.cjs","sourcesContent":["import type { Money } from './types'\n\n/**\n * ISO 4217 currencies with no minor unit — `Money.amount` is already whole\n * currency units for these (e.g. JPY 4900 = ¥4,900).\n */\nconst ZERO_DECIMAL = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n])\n\n/** ISO 4217 currencies with three-digit minor units. */\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\n/**\n * Unambiguous symbol prefixes. Deliberately conservative: currencies whose\n * common symbol is shared across currencies (e.g. \"$\" for CAD/AUD) fall back\n * to the explicit \"CODE 49.00\" form instead of guessing.\n */\nconst SYMBOLS: Record<string, string> = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n}\n\nfunction minorUnitDigits(code: string): number {\n if (ZERO_DECIMAL.has(code)) return 0\n if (THREE_DECIMAL.has(code)) return 3\n return 2\n}\n\nfunction splitAmount(m: Money): { sign: string; major: string; frac: string } {\n if (!Number.isInteger(m.amount)) {\n // Fail closed: silently rounding would alter a price (source validation).\n throw new TypeError(\n `Money.amount must be an integer number of minor units, got: ${String(m.amount)}`,\n )\n }\n const digits = minorUnitDigits(m.currency.toUpperCase())\n const sign = m.amount < 0 ? '-' : ''\n const abs = Math.abs(m.amount)\n const factor = 10 ** digits\n const major = Math.floor(abs / factor).toString()\n const frac = digits === 0 ? '' : `.${(abs % factor).toString().padStart(digits, '0')}`\n return { sign, major, frac }\n}\n\n/**\n * Decimal string for machine consumption (JSON-LD `price`): \"89.00\", \"4900\"\n * (zero-decimal), \"49.123\" (three-decimal). No grouping, no symbol.\n */\nexport function toDecimalString(m: Money): string {\n const { sign, major, frac } = splitAmount(m)\n return `${sign}${major}${frac}`\n}\n\n/**\n * Human-readable, deterministic money formatting: \"$49.00\", \"€49.00\",\n * \"¥4,900\", \"-£5.50\". Unknown/ambiguous currencies render as \"CAD 49.00\".\n * Pure function — no Intl, no locale, same input → same output everywhere.\n */\nexport function formatMoney(m: Money): string {\n const { sign, major, frac } = splitAmount(m)\n const code = m.currency.toUpperCase()\n const grouped = major.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n const symbol = SYMBOLS[code]\n return symbol !== undefined\n ? `${sign}${symbol}${grouped}${frac}`\n : `${sign}${code} ${grouped}${frac}`\n}\n","/**\n * Value-shape validators shared by the commerce and document renderers.\n *\n * `isIsoDate` was moved here verbatim from `documents/facts.ts` when the\n * commerce renderers gained `updated`. Same reasoning as `internal/budget.ts`:\n * a date the document renderer accepts and the product renderer rejects is two\n * validation behaviours that will drift, and the two now serve the same field\n * name on two source types. `documents/facts.ts` re-exports it so its existing\n * importers are unchanged.\n *\n * Every validator here is a **gate, not a transform**. A value that passes is\n * emitted byte-for-byte as the merchant supplied it; a value that fails is\n * dropped, never corrected, normalised, or re-cased. Correcting a malformed\n * value would make this package originate one (source validation), and re-casing a\n * language tag would mean the JSON-LD disagreed with the merchant's own page.\n *\n * Package-internal. Nothing here is part of the public contract.\n */\n\n/** ISO 8601 date or datetime. Structure first, then real-calendar check. */\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?(Z|[+-]\\d{2}:\\d{2})?)?$/\n\n/**\n * `Date.parse` alone does NOT implement the real-calendar half this function\n * has always claimed. It rejects a month above 12 and a day above 31, but a\n * day that overflows its own month rolls silently forward:\n *\n * Date.parse('2026-02-31') → March 3 (not NaN)\n * Date.parse('2026-02-29') → March 1 (2026 is not a leap year)\n * Date.parse('2026-04-31') → May 1 (April has 30 days)\n *\n * So the pre-existing check passed three dates that do not exist, and the\n * renderers emitted them verbatim. Harmless-looking in a markdown line; not\n * harmless as `dateModified` in a product feed, where a date is a fact a\n * caller may act on. Round-tripping the calendar portion is what actually\n * enforces the docstring: build the date from its parts and require that the\n * parts survive.\n *\n * `setUTCFullYear` rather than `Date.UTC` because the latter maps years 0–99\n * onto 1900–1999, which would false-reject a four-digit year like `0026`.\n */\nfunction isRealCalendarDate(value: string): boolean {\n const [year, month, day] = value.slice(0, 10).split('-').map(Number) as [number, number, number]\n const probe = new Date(0)\n probe.setUTCFullYear(year, month - 1, day)\n return (\n probe.getUTCFullYear() === year &&\n probe.getUTCMonth() === month - 1 &&\n probe.getUTCDate() === day\n )\n}\n\nexport function isIsoDate(value: string): boolean {\n return ISO_DATE.test(value) && !Number.isNaN(Date.parse(value)) && isRealCalendarDate(value)\n}\n\n/**\n * BCP 47 language tag, restricted to the forms that actually appear on\n * commerce and content pages: language, optional script, optional region.\n *\n * `en` · `en-US` · `pt-BR` · `zh-Hant` · `zh-Hant-TW` · `es-419`\n *\n * Deliberately NOT the full grammar (RFC 5646 admits extensions, private-use\n * subtags and grandfathered tags). A tag this regex rejects is dropped rather\n * than guessed at, and the page simply declares no language — which is the\n * status quo for every page served before this field existed. Widening the\n * grammar later is additive; emitting a malformed `inLanguage` into a product\n * feed is not something a later release can retract.\n *\n * Case is validated leniently and preserved exactly: BCP 47 is\n * case-insensitive, so `EN-us` is a valid tag and rejecting it would punish a\n * merchant for a spelling the standard allows.\n */\nconst BCP_47 = /^[A-Za-z]{2,3}(-[A-Za-z]{4})?(-(?:[A-Za-z]{2}|\\d{3}))?$/\n\nexport function isLanguageTag(value: string): boolean {\n return BCP_47.test(value)\n}\n","import type { Availability, Money, ProductSource } from './types'\nimport { toDecimalString } from './money'\nimport { isIsoDate, isLanguageTag } from './internal/validate'\n\n/** Availability enum → schema.org ItemAvailability URL. */\nconst SCHEMA_AVAILABILITY: Record<Availability, string> = {\n in_stock: 'https://schema.org/InStock',\n out_of_stock: 'https://schema.org/OutOfStock',\n preorder: 'https://schema.org/PreOrder',\n backorder: 'https://schema.org/BackOrder',\n}\n\nfunction offer(\n price: Money,\n availability: Availability,\n extra: { url?: string; sku?: string; name?: string },\n): Record<string, unknown> {\n const o: Record<string, unknown> = {\n '@type': 'Offer',\n price: toDecimalString(price),\n priceCurrency: price.currency,\n availability: SCHEMA_AVAILABILITY[availability],\n }\n if (extra.url !== undefined) o.url = extra.url\n if (extra.sku !== undefined) o.sku = extra.sku\n if (extra.name !== undefined) o.name = extra.name\n return o\n}\n\n/**\n * Render a schema.org Product JSON-LD object from the product source.\n * Injection-only: every value comes from `p`; only fields present in the\n * source appear in the output. Key order is fixed for snapshot stability.\n *\n * `inLanguage` and `dateModified` are emitted only when the source value\n * passes its shape check. A malformed value is dropped rather than repaired or\n * reformatted: this renderer feeds `/acp/v0/feed` and the MCP product tool as\n * well as the canonical page, and a date this package invented would be a\n * substantive value it originated (source validation) — in a product feed, where it\n * would read as authoritative.\n */\nexport function renderProductJsonLd(p: ProductSource): Record<string, unknown> {\n const out: Record<string, unknown> = {\n '@context': 'https://schema.org',\n '@type': 'Product',\n name: p.title,\n url: p.url,\n }\n if (p.brand !== undefined) out.brand = { '@type': 'Brand', name: p.brand }\n if (p.description !== undefined && p.description.length > 0) out.description = p.description\n if (p.images !== undefined && p.images.length > 0) out.image = p.images.map((img) => img.url)\n if (p.language !== undefined && isLanguageTag(p.language)) out.inLanguage = p.language\n out.offers =\n p.variants !== undefined && p.variants.length > 0\n ? p.variants.map((v) => offer(v.price, v.availability, { sku: v.sku, name: v.title }))\n : offer(p.price, p.availability, { url: p.url })\n // After `offers` deliberately: the buying facts stay in the same position\n // they have always occupied, so a diff of two feed records shows the new\n // freshness key appended rather than every offer key shifted down one line.\n if (p.updated !== undefined && isIsoDate(p.updated)) out.dateModified = p.updated\n return out\n}\n","/**\n * Byte-budget, heading, and markdown-escaping primitives shared by every\n * renderer in this package.\n *\n * These helpers were extracted from `src/markdown.ts` verbatim when the\n * universal document renderers were added. The extraction is not cosmetic:\n * the commerce renderers and the document renderers must truncate by exactly\n * the same rule, and two copies of a truncation loop is two truncation\n * behaviours that will drift the first time one of them is \"improved\". The\n * code below is byte-for-byte the code that shipped inside `src/markdown.ts`;\n * `tests/commerce-frozen.test.ts` pins the commerce renderers' output with\n * inline string literals and is the proof that the move changed nothing.\n *\n * Package-internal. Nothing here is re-exported from `src/index.ts` — these\n * are implementation primitives, not part of the public contract.\n */\n\n/** Default output size budget in UTF-8 bytes, shared by every renderer. */\nexport const DEFAULT_MAX_BYTES = 5120\n\n/**\n * Fixed meta note appended when output is truncated to fit the size budget.\n * Pure rendering metadata — contains no prices, claims, or policy text.\n */\nexport const TRUNCATION_NOTE = '*Truncated to fit size budget; remaining content omitted.*'\n\nconst encoder = new TextEncoder()\n\nexport function byteLength(s: string): number {\n return encoder.encode(s).length\n}\n\nexport function clampHeadingLevel(level: number): number {\n return Math.min(Math.max(Math.trunc(level), 1), 6)\n}\n\nexport function heading(level: number, text: string): string {\n return `${'#'.repeat(clampHeadingLevel(level))} ${text}`\n}\n\n/**\n * Keep verbatim source text on a single markdown line (inline contexts only:\n * fact lines, table cells). Collapses newlines to spaces; block contexts\n * (description, policy bodies) stay byte-for-byte verbatim.\n */\nexport function inline(text: string): string {\n return text.replace(/\\s*\\r?\\n\\s*/g, ' ')\n}\n\n/** Escape characters that would break a markdown table cell. Otherwise verbatim. */\nexport function cell(text: string): string {\n return inline(text).replace(/\\|/g, '\\\\|')\n}\n\n/**\n * The URL schemes a rendered link may carry. A `javascript:`/`data:`/`vbscript:`\n * link handed to an agent (or a downstream HTML renderer) is a\n * scheme-smuggling / phishing primitive, so any other scheme is dropped. This\n * matches the document renderer's `isAllowedUrl` (documents/facts.ts) — the\n * commerce renderers must not be the weaker path.\n */\nconst ALLOWED_LINK_SCHEMES: readonly string[] = ['https:', 'http:', 'mailto:', 'tel:']\n\n/** True when `url` parses and carries an allowed scheme. */\nexport function isSafeUrl(url: string): boolean {\n try {\n return ALLOWED_LINK_SCHEMES.includes(new URL(url).protocol)\n } catch {\n return false\n }\n}\n\n/**\n * Escape the characters that let link TEXT break out of `[label](url)` and\n * forge a different target: `]` (which closes the label early) and `[`. `inline`\n * first, so a newline cannot smuggle structure either.\n *\n * Parentheses are deliberately NOT escaped here. They are harmless inside a\n * label — the label is delimited by brackets — and product titles legitimately\n * contain them (\"Wool Socks (3-pack)\"). Escaping them would put backslashes in\n * front of a large fraction of real catalogs, which is visible damage to every\n * honest row to defend against nothing. The URL side is handled by `safeUrl`.\n */\nexport function linkText(text: string): string {\n return inline(text).replace(/[[\\]]/g, (c) => `\\\\${c}`)\n}\n\n/**\n * The URL as it may appear inside `](...)`. A URL carrying `)` would close the\n * link early and leave the remainder as live markdown — `https://x.example/)\n * [click](https://evil.example` renders as TWO links, the second one the\n * attacker's. Percent-encoding the delimiters keeps the URL working and the\n * structure ours. (Angle-bracket link syntax would be the alternative; encoding\n * keeps the output diff-stable for every URL that does not contain them.)\n */\nfunction safeUrl(url: string): string {\n // NOT `encodeURIComponent`: it leaves `(` and `)` untouched (they are in its\n // unreserved set), which is exactly the pair that closes a markdown link —\n // so using it here would look like a fix and do nothing. Percent-encode the\n // delimiters explicitly.\n return url.replace(\n /[()<>\\s]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`,\n )\n}\n\n/**\n * Link text inside a table cell: both escapes, not either. `cell` alone leaves\n * `](` free to forge a link; `linkText` alone leaves `|` free to forge a\n * column. A catalog row is the one place both matter.\n */\nexport function cellLinkText(text: string): string {\n return linkText(text).replace(/\\|/g, '\\\\|')\n}\n\n/**\n * A markdown link with the label escaped and the URL scheme-checked. When the\n * URL is not a safe scheme the label renders as plain (escaped) text rather\n * than a clickable link — the substance is kept, the smuggled scheme is not.\n * `labelEscaper` lets a table cell escape `|` as well.\n */\nexport function safeLink(\n label: string,\n url: string,\n labelEscaper: (text: string) => string = linkText,\n): string {\n const text = labelEscaper(label)\n return isSafeUrl(url) ? `[${text}](${safeUrl(url)})` : text\n}\n\n/** A bottom-of-page section that may be truncated (whole lines only). */\nexport interface TailSection {\n headingLine: string\n items: string[]\n}\n\nfunction tailText(t: TailSection): string {\n return `${t.headingLine}\\n\\n${t.items.join('\\n')}`\n}\n\n/**\n * Join required blocks + tail sections, enforcing the byte budget.\n *\n * Truncation is strictly from the bottom: required blocks (the front-loaded\n * buying facts and the variants table) are never dropped, tail sections are\n * re-added top-down until the budget (minus the truncation note) is exhausted,\n * and a cut always ends the document — nothing renders after it. Items are\n * whole lines; nothing is ever cut mid-fact.\n *\n * If the required blocks alone exceed the budget, they are emitted anyway\n * (facts are never sacrificed to the byte budget) followed by the note.\n */\nexport function assembleWithBudget(\n requiredBlocks: string[],\n tail: TailSection[],\n maxBytes: number,\n): string {\n const full = [...requiredBlocks, ...tail.map(tailText)].join('\\n\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = requiredBlocks.join('\\n\\n')\n for (const section of tail) {\n const whole = `${out}\\n\\n${tailText(section)}`\n if (byteLength(whole) <= budget) {\n out = whole\n continue\n }\n // Section does not fit whole: add as many complete lines as fit.\n let partial = `${out}\\n\\n${section.headingLine}`\n let added = 0\n for (const item of section.items) {\n const next = `${partial}${added === 0 ? '\\n\\n' : '\\n'}${item}`\n if (byteLength(next) > budget) break\n partial = next\n added += 1\n }\n if (added > 0) out = partial\n break // truncate strictly from the bottom — nothing may appear after the cut\n }\n return `${out}${noteSuffix}`\n}\n","import type {\n Availability,\n CatalogItemSource,\n PolicySource,\n ProductSource,\n ProductVariantSource,\n RenderOptions,\n} from './types'\nimport { formatMoney } from './money'\nimport type { TailSection } from './internal/budget'\nimport {\n assembleWithBudget,\n byteLength,\n cell,\n cellLinkText,\n clampHeadingLevel,\n DEFAULT_MAX_BYTES,\n heading,\n inline,\n isSafeUrl,\n safeLink,\n TRUNCATION_NOTE,\n} from './internal/budget'\nimport { isIsoDate } from './internal/validate'\n\n/** Deterministic human labels for the availability enum (format mapping, not content). */\nconst AVAILABILITY_LABELS: Record<Availability, string> = {\n in_stock: 'In stock',\n out_of_stock: 'Out of stock',\n preorder: 'Preorder',\n backorder: 'Backorder',\n}\n\nfunction etaText(eta: [number, number]): string {\n const [min, max] = eta\n return min === max ? `${min} days` : `${min}-${max} days`\n}\n\nfunction variantsTable(variants: ProductVariantSource[], level: number): string {\n const lines = [\n heading(level, 'Variants'),\n '',\n '| ID | Title | Options | Price | Availability |',\n '| --- | --- | --- | --- | --- |',\n ]\n for (const v of variants) {\n const options =\n v.options !== undefined\n ? Object.entries(v.options)\n .map(([key, value]) => `${cell(key)}: ${cell(value)}`)\n .join('; ')\n : ''\n lines.push(\n `| ${cell(v.id)} | ${cell(v.title)} | ${options} | ${formatMoney(v.price)} | ${AVAILABILITY_LABELS[v.availability]} |`,\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * Render a product detail page as clean markdown. Buying facts come first:\n * title, price, availability, shipping, and returns all land in the opening\n * lines so an agent reading top-down never misses them. Every substantive\n * value is injected from `p` — nothing is invented or reworded.\n */\nexport function renderProductMarkdown(p: ProductSource, opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n const sub = clampHeadingLevel(level + 1)\n\n const facts: string[] = [heading(level, safeLink(p.title, p.url)), '']\n if (p.brand !== undefined) facts.push(`- **Brand:** ${inline(p.brand)}`)\n const price = formatMoney(p.price)\n facts.push(\n p.compareAtPrice !== undefined\n ? `- **Price:** ~~${formatMoney(p.compareAtPrice)}~~ ${price}`\n : `- **Price:** ${price}`,\n )\n facts.push(`- **Availability:** ${AVAILABILITY_LABELS[p.availability]}`)\n if (p.shipping !== undefined) {\n facts.push(`- **Shipping:** ${inline(p.shipping.summary)}`)\n if (p.shipping.freeThreshold !== undefined) {\n facts.push(` - Free shipping threshold: ${formatMoney(p.shipping.freeThreshold)}`)\n }\n if (p.shipping.regions !== undefined && p.shipping.regions.length > 0) {\n facts.push(` - Ships to: ${p.shipping.regions.map(inline).join(', ')}`)\n }\n if (p.shipping.etaDays !== undefined) {\n facts.push(` - Delivery estimate: ${etaText(p.shipping.etaDays)}`)\n }\n }\n if (p.returns !== undefined) {\n facts.push(`- **Returns:** ${inline(p.returns.summary)}`)\n if (p.returns.windowDays !== undefined) {\n facts.push(` - Return window: ${p.returns.windowDays} days`)\n }\n if (p.returns.url !== undefined && isSafeUrl(p.returns.url)) {\n facts.push(` - Policy: ${p.returns.url}`)\n }\n }\n // Last in the fact block, not first: `updated` is metadata about the facts\n // rather than one of the buying facts, and every line inserted above\n // `- **Availability:**` pushes a core fact further from the top of the\n // document (ARS D4 scores that byte offset). The label matches the document\n // renderer's `UPDATED_LABEL`; `tests/jsonld.test.ts` pins the two together.\n if (p.updated !== undefined && isIsoDate(p.updated)) {\n facts.push(`- **Updated:** ${inline(p.updated)}`)\n }\n\n const requiredBlocks: string[] = [facts.join('\\n')]\n if (p.variants !== undefined && p.variants.length > 0) {\n requiredBlocks.push(variantsTable(p.variants, sub))\n }\n\n const tail: TailSection[] = []\n if (p.description !== undefined && p.description.length > 0) {\n tail.push({ headingLine: heading(sub, 'Description'), items: p.description.split('\\n') })\n }\n if (p.attributes !== undefined) {\n const items = Object.entries(p.attributes).map(\n ([key, value]) => `- **${inline(key)}:** ${inline(value)}`,\n )\n if (items.length > 0) tail.push({ headingLine: heading(sub, 'Details'), items })\n }\n if (p.images !== undefined && p.images.length > 0) {\n const items = p.images.map((img) => {\n const label = img.alt !== undefined && img.alt.length > 0 ? img.alt : img.url\n return `- ${safeLink(label, img.url)}`\n })\n tail.push({ headingLine: heading(sub, 'Images'), items })\n }\n\n return assembleWithBudget(requiredBlocks, tail, maxBytes)\n}\n\n/**\n * Render store policies as markdown. Each policy is a linked heading followed\n * by its body byte-for-byte verbatim. Under the byte budget, whole policies\n * are kept in order; a policy whose body does not fit degrades to its linked\n * title (policy text is never partially rendered), and the document ends with\n * the truncation note.\n */\nexport function renderPolicyMarkdown(policies: PolicySource[], opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const titleLineFor = (pol: PolicySource): string => heading(level, safeLink(pol.title, pol.url))\n const blocks = policies.map((pol) => `${titleLineFor(pol)}\\n\\n${pol.body}`)\n const full = blocks.join('\\n\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = ''\n for (const pol of policies) {\n const titleLine = titleLineFor(pol)\n const block = `${titleLine}\\n\\n${pol.body}`\n const withBlock = out === '' ? block : `${out}\\n\\n${block}`\n if (byteLength(withBlock) <= budget) {\n out = withBlock\n continue\n }\n const withTitle = out === '' ? titleLine : `${out}\\n\\n${titleLine}`\n if (byteLength(withTitle) <= budget) out = withTitle\n break // truncate strictly from the bottom\n }\n return out === '' ? TRUNCATION_NOTE : `${out}${noteSuffix}`\n}\n\n/**\n * Render a catalog listing as a markdown table (title → link, price,\n * availability). Under the byte budget, whole rows are dropped from the\n * bottom and the truncation note is appended.\n */\nexport function renderCatalogMarkdown(items: CatalogItemSource[], opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const head = [\n heading(level, 'Catalog'),\n '',\n '| Title | Price | Availability |',\n '| --- | --- | --- |',\n ].join('\\n')\n const rows = items.map(\n (item) =>\n `| ${safeLink(item.title, item.url, cellLinkText)} | ${formatMoney(item.price)} | ${AVAILABILITY_LABELS[item.availability]} |`,\n )\n const full = [head, ...rows].join('\\n')\n if (byteLength(full) <= maxBytes) return full\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n let out = head\n for (const row of rows) {\n const next = `${out}\\n${row}`\n if (byteLength(next) > budget) break\n out = next\n }\n return `${out}${noteSuffix}`\n}\n","/**\n * Fact rendering: the deterministic `FactValue` → markdown mapping, the fixed\n * label maps, the URL scheme allowlist, and the escaping rules.\n *\n * This file is where the injection-only guarantee is actually enforced for the\n * universal path. Every rule below is mechanical rather than advisory, because\n * an advisory rule in a renderer is a rule that holds until the first hurried\n * patch:\n *\n * - Every renderer-authored string in this package is a named constant here.\n * The whitelist in README.md is the list of these constants, and\n * `tests/documents-integrity.test.ts` re-states that list as literals (not\n * by importing these constants) so that adding scaffolding cannot silently\n * whitelist itself.\n * - A malformed value is DROPPED, never repaired. Repairing a fact invents a\n * value the merchant never stated (source validation); dropping it only loses\n * information, which the agent can still get from the canonical page.\n * - URLs are checked against a scheme allowlist. The commerce path only ever\n * emitted merchant-controlled product/policy URLs; the universal path emits\n * arbitrary merchant-supplied link targets, and `[Click here](javascript:…)`\n * handed to an agent under our formatting authority is a phishing primitive.\n * - Money throws rather than rounds or guesses, matching `formatMoney`. A\n * thrown render is caught by the gateway and falls through to HTML; a\n * silently wrong price is served forever.\n */\n\nimport { formatMoney } from '../money'\nimport { cell, heading, inline } from '../internal/budget'\nimport { isIsoDate } from '../internal/validate'\nimport type {\n BillingPeriod,\n DocumentAccess,\n Fact,\n FactValue,\n HoursException,\n HoursInterval,\n HoursSpec,\n Weekday,\n} from './types'\n\n/* ------------------------------------------------------------------ *\n * Fixed label maps — the only renderer-authored vocabulary.\n * ------------------------------------------------------------------ */\n\n/** Fixed suffix per billing period. Format mapping of a closed enum, not content. */\nexport const PERIOD_SUFFIX: Record<BillingPeriod, string> = {\n one_time: 'one-time',\n hour: 'per hour',\n day: 'per day',\n week: 'per week',\n month: 'per month',\n quarter: 'per quarter',\n year: 'per year',\n}\n\n/** Fixed label map for booleans. */\nexport const BOOLEAN_LABELS: Record<'true' | 'false', string> = {\n true: 'Yes',\n false: 'No',\n}\n\n/** Fixed weekday labels. English only and deliberately not localised: the\n * output is a machine-readable format transformation, and a locale would make\n * the same source render differently for different requesters (consistent source content). */\nexport const WEEKDAY_LABELS: Record<Weekday, string> = {\n monday: 'Monday',\n tuesday: 'Tuesday',\n wednesday: 'Wednesday',\n thursday: 'Thursday',\n friday: 'Friday',\n saturday: 'Saturday',\n sunday: 'Sunday',\n}\n\n/** Fixed weekday order. Every one of the seven renders, always. */\nexport const WEEKDAY_ORDER: readonly Weekday[] = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n]\n\n/** `intervals: []` — the merchant stated the day and stated it is closed. */\nexport const CLOSED_LABEL = 'Closed'\n\n/** Weekday absent from `weekly` — a different fact from `Closed`. */\nexport const NOT_STATED_LABEL = 'Not stated'\n\n/** An `hours` fact is not a valid table cell; the row links out instead. */\nexport const SEE_PAGE_LABEL = 'See page'\n\n/** Fixed labels used for structural bullets and table headers. */\nexport const UPDATED_LABEL = 'Updated'\nexport const PHONE_LABEL = 'Phone'\nexport const EMAIL_LABEL = 'Email'\nexport const ADDRESS_LABEL = 'Address'\nexport const DAY_LABEL = 'Day'\nexport const DATE_LABEL = 'Date'\nexport const HOURS_LABEL = 'Hours'\nexport const NOTE_LABEL = 'Note'\nexport const TITLE_LABEL = 'Title'\n\n/** Fixed headings. */\nexport const EXCEPTIONS_HEADING = 'Exceptions'\nexport const CONTACT_HEADING = 'Contact'\nexport const ACTIONS_HEADING = 'Actions'\nexport const RELATED_HEADING = 'Related'\nexport const CONTENTS_HEADING = 'Contents'\n\n/** Fixed access-level words used inside the single access notice sentence. */\nexport const ACCESS_LABELS: Record<DocumentAccess, string> = {\n free: 'free',\n registered: 'registration required',\n metered: 'metered',\n subscriber: 'subscription required',\n}\n\n/**\n * The fixed access notice. Emitted in place of `sections` whenever access is\n * not 'free'. It states only that the prose was not served and at what access\n * level — it never paraphrases the withheld text.\n */\nexport function accessNotice(access: DocumentAccess): string {\n return `*Full text is not served to agents at this URL (access: ${ACCESS_LABELS[access]}).*`\n}\n\n/** The fixed timezone sentence rendered above every hours table. */\nexport function timeZoneSentence(timeZone: string): string {\n return `All times are local to ${inline(timeZone)}.`\n}\n\n/* ------------------------------------------------------------------ *\n * URL scheme allowlist and escaping.\n * ------------------------------------------------------------------ */\n\n/** The only schemes this package will put behind a markdown link. */\nexport const ALLOWED_URL_SCHEMES: readonly string[] = ['https:', 'http:', 'mailto:', 'tel:']\n\n/**\n * True when `raw` is an absolute URL with an allowlisted scheme. Relative URLs\n * are rejected: this package has no base URL to resolve them against, and\n * guessing one would emit a link the merchant never wrote.\n */\nexport function isAllowedUrl(raw: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(raw)\n } catch {\n return false\n }\n return ALLOWED_URL_SCHEMES.includes(parsed.protocol)\n}\n\n/**\n * Escape a markdown link label. `]`, `(`, and `)` would otherwise let source\n * text break out of the label and forge a link target.\n */\nexport function linkLabel(text: string): string {\n return inline(text).replace(/[\\]()]/g, (c) => `\\\\${c}`)\n}\n\n/** `[label](url)` with the label escaped. Callers must allowlist `url` first. */\nexport function markdownLink(label: string, url: string): string {\n return `[${linkLabel(label)}](${url})`\n}\n\n/**\n * A markdown link safe to drop into a table cell. `cell()` cannot be used on a\n * finished link — it would escape nothing useful and `linkLabel` has already\n * run — so the `|` guard is applied on top instead.\n */\nexport function cellLink(label: string, url: string): string {\n return markdownLink(label, url).replace(/\\|/g, '\\\\|')\n}\n\n/* ------------------------------------------------------------------ *\n * Value validation.\n * ------------------------------------------------------------------ */\n\n/**\n * ISO 8601 date or datetime. Lives in `internal/validate.ts` since the\n * commerce renderers began accepting `updated` on the same terms; re-exported\n * here so this file stays the one place the document path imports value\n * validation from. (`export { … } from` would not bind the name locally, and\n * `factText` below calls it — hence the import plus re-export.)\n */\nexport { isIsoDate }\n\n/** 'YYYY-MM-DD' only — the form `HoursException.date` is specified in. */\nexport function isIsoDay(value: string): boolean {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n}\n\nconst HH_MM = /^([01]\\d|2[0-3]):[0-5]\\d$/\n\n/**\n * A single interval is valid only if both ends are 'HH:MM' and it does not\n * wrap. Overnight spans are expressed as two intervals on two days; accepting\n * `22:00`–`02:00` here would make the same string mean two different things.\n */\nfunction isValidInterval(i: HoursInterval): boolean {\n return HH_MM.test(i.opens) && HH_MM.test(i.closes) && i.closes > i.opens\n}\n\nfunction intervalsText(intervals: HoursInterval[]): string {\n return intervals.map((i) => `${i.opens}-${i.closes}`).join(', ')\n}\n\n/* ------------------------------------------------------------------ *\n * FactValue → text.\n * ------------------------------------------------------------------ */\n\nfunction numberText(value: number, unit?: string): string | null {\n if (!Number.isFinite(value)) return null\n const text = String(value)\n // Exponential form (\"1e+21\") is a number an agent will misparse and a human\n // never wrote. Drop rather than reformat: reformatting invents digits.\n if (text.includes('e') || text.includes('E')) return null\n return unit !== undefined ? `${text} ${inline(unit)}` : text\n}\n\nfunction moneyText(v: Extract<FactValue, { type: 'money' }>): string {\n let text = formatMoney(v.value)\n if (v.maxValue !== undefined) {\n if (v.maxValue.currency.toUpperCase() !== v.value.currency.toUpperCase()) {\n throw new TypeError(\n `Money range currencies must match, got: ${v.value.currency} and ${v.maxValue.currency}`,\n )\n }\n if (v.maxValue.amount < v.value.amount) {\n throw new TypeError(\n `Money range maxValue must not be below value, got: ${String(v.value.amount)} and ${String(v.maxValue.amount)}`,\n )\n }\n text = `${text}-${formatMoney(v.maxValue)}`\n }\n if (v.period !== undefined) text = `${text} ${PERIOD_SUFFIX[v.period]}`\n if (v.per !== undefined) text = `${text} ${inline(v.per)}`\n return text\n}\n\n/**\n * Render a scalar fact value to its single-line inline form, or `null` when\n * the value is malformed (dropped) or is an `hours` value (rendered as its own\n * block, not as a fact line).\n *\n * Throws only for money ranges that are internally contradictory — see the\n * file header.\n */\nexport function factValueText(value: FactValue): string | null {\n switch (value.type) {\n case 'text':\n return inline(value.value)\n case 'list':\n return value.value.length > 0 ? value.value.map(inline).join(', ') : null\n case 'number':\n return numberText(value.value, value.unit)\n case 'boolean':\n return BOOLEAN_LABELS[value.value ? 'true' : 'false']\n case 'money':\n return moneyText(value)\n case 'date':\n return isIsoDate(value.value) ? value.value : null\n case 'url':\n if (!isAllowedUrl(value.value)) return null\n return value.label !== undefined ? markdownLink(value.label, value.value) : value.value\n case 'hours':\n return null\n }\n}\n\n/**\n * Render one fact as `- **Label:** value`, plus an indented note line when the\n * fact carries one. Returns `null` when the value is dropped or is an `hours`\n * value.\n */\nexport function renderFactLine(fact: Fact): string | null {\n const text = factValueText(fact.value)\n if (text === null) return null\n const line = `- **${inline(fact.label)}:** ${text}`\n return fact.note !== undefined ? `${line}\\n - ${inline(fact.note)}` : line\n}\n\n/**\n * Render a fact value as a table cell. Two differences from a fact line: every\n * cell is `|`-escaped, and an `hours` value degrades to a link to the item's\n * own page rather than trying to flatten a table into a cell.\n */\nexport function factCellText(value: FactValue, itemUrl: string): string | null {\n if (value.type === 'hours') {\n return isAllowedUrl(itemUrl) ? cellLink(SEE_PAGE_LABEL, itemUrl) : SEE_PAGE_LABEL\n }\n if (value.type === 'url') {\n if (!isAllowedUrl(value.value)) return null\n // Already an escaped link; only the `|` guard still applies.\n return value.label !== undefined\n ? cellLink(value.label, value.value)\n : value.value.replace(/\\|/g, '\\\\|')\n }\n const text = factValueText(value)\n return text === null ? null : cell(text)\n}\n\n/* ------------------------------------------------------------------ *\n * Hours block.\n * ------------------------------------------------------------------ */\n\nfunction exceptionRow(e: HoursException): string | null {\n if (!isIsoDay(e.date)) return null\n let hours: string\n if (e.closed === true) {\n hours = CLOSED_LABEL\n } else if (e.intervals !== undefined && e.intervals.length > 0) {\n if (!e.intervals.every(isValidInterval)) return null\n hours = intervalsText(e.intervals)\n } else if (e.intervals !== undefined) {\n hours = CLOSED_LABEL\n } else {\n hours = NOT_STATED_LABEL\n }\n const note = e.note !== undefined ? cell(e.note) : ''\n return `| ${e.date} | ${hours} | ${note} |`\n}\n\n/**\n * Render one `hours` fact as its own block, headed by the fact's own label.\n *\n * The heading is `Fact.label`, not a fixed \"Hours\": a clinic with \"Office\n * hours\" and \"Lab hours\" must not emit two identically-titled tables that an\n * agent cannot tell apart.\n *\n * All seven weekdays always render. An absent weekday is `Not stated` and a\n * present-but-empty one is `Closed`; collapsing those two into one label would\n * assert a closure the merchant never stated. Nothing here computes whether\n * the place is open now — that requires a clock and a timezone database, and a\n * wrong answer to \"are they open\" is worse than no answer.\n *\n * Returns `null` when the spec is malformed (missing timezone, or any invalid\n * interval anywhere in `weekly`). Partial hours are dropped whole: a table\n * missing the one day that was malformed reads as authoritative and is not.\n */\nexport function renderHoursBlock(\n label: string,\n spec: HoursSpec,\n level: number,\n subLevel: number,\n): string | null {\n if (typeof spec.timeZone !== 'string' || spec.timeZone.trim() === '') return null\n\n const byDay = new Map<Weekday, HoursInterval[]>()\n for (const rule of spec.weekly) {\n if (!rule.intervals.every(isValidInterval)) return null\n byDay.set(rule.day, rule.intervals)\n }\n\n const lines: string[] = [\n heading(level, inline(label)),\n '',\n timeZoneSentence(spec.timeZone),\n '',\n `| ${DAY_LABEL} | ${HOURS_LABEL} |`,\n '| --- | --- |',\n ]\n for (const day of WEEKDAY_ORDER) {\n const intervals = byDay.get(day)\n const text =\n intervals === undefined\n ? NOT_STATED_LABEL\n : intervals.length === 0\n ? CLOSED_LABEL\n : intervalsText(intervals)\n lines.push(`| ${WEEKDAY_LABELS[day]} | ${text} |`)\n }\n\n if (spec.note !== undefined) {\n lines.push('', `- **${NOTE_LABEL}:** ${inline(spec.note)}`)\n }\n\n const exceptionRows = (spec.exceptions ?? [])\n .map(exceptionRow)\n .filter((row): row is string => row !== null)\n if (exceptionRows.length > 0) {\n lines.push(\n '',\n heading(subLevel, EXCEPTIONS_HEADING),\n '',\n `| ${DATE_LABEL} | ${HOURS_LABEL} | ${NOTE_LABEL} |`,\n '| --- | --- | --- |',\n ...exceptionRows,\n )\n }\n\n return lines.join('\\n')\n}\n","/**\n * The universal renderers: any page that is not a product, a policy set, or a\n * catalog. Same signature shape and the same `RenderOptions` as the three\n * commerce renderers, and the same guarantee — pure, deterministic, no clock,\n * no locale, no network, and every substantive value injected from the source\n * object.\n *\n * Block order and truncation are stated once, here and in README.md, and\n * nowhere else:\n *\n * 1. `# [title](url)` required\n * 2. `> summary` required\n * 3. `- **Updated:**` + scalar fact lines required\n * 4. `## <fact label>` hours table, one per hours fact required\n * 5. `## Contact` required\n * 6. `## Actions` required\n * 7. `## <section heading>` prose (only when free) truncatable\n * 8. `## Related` truncatable, first to go\n *\n * `assembleWithBudget` truncates strictly from the bottom, so putting\n * `related` last in the tail is what makes prose survive a tight budget and\n * cross-links drop. The order of that array is load-bearing, not cosmetic.\n *\n * Two ceilings, not one. `maxBytes` governs the truncatable tail as it does\n * for commerce. A second, absolute ceiling at `4 × maxBytes` governs the\n * required blocks, because \"facts are never sacrificed\" is a safe promise for\n * a PDP with a dozen fields and an unbounded one for a government service page\n * with six twenty-item lists — without the hard ceiling a merchant's own data\n * shape decides our response size.\n */\n\nimport type { RenderOptions } from '../types'\nimport type { TailSection } from '../internal/budget'\nimport {\n assembleWithBudget,\n byteLength,\n cell,\n clampHeadingLevel,\n DEFAULT_MAX_BYTES,\n heading,\n inline,\n TRUNCATION_NOTE,\n} from '../internal/budget'\nimport type {\n CollectionItemSource,\n CollectionSource,\n DocumentSectionSource,\n DocumentSource,\n} from './types'\nimport {\n ACTIONS_HEADING,\n ADDRESS_LABEL,\n CONTACT_HEADING,\n CONTENTS_HEADING,\n EMAIL_LABEL,\n NOTE_LABEL,\n PHONE_LABEL,\n RELATED_HEADING,\n TITLE_LABEL,\n UPDATED_LABEL,\n accessNotice,\n cellLink,\n factCellText,\n isAllowedUrl,\n isIsoDate,\n linkLabel,\n markdownLink,\n renderFactLine,\n renderHoursBlock,\n} from './facts'\n\n/** Hard ceilings. Merchant data shape must not decide our response size. */\nconst MAX_FACTS = 60\nconst MAX_ACTIONS = 20\n/**\n * Exported so `documents/jsonld.ts` truncates the same listing at the same\n * row. Two ceilings would let the ItemList and the markdown table disagree\n * about how long the collection is, at one URL, for the same requester.\n */\nexport const MAX_COLLECTION_ROWS = 500\nconst MAX_COLLECTION_COLUMNS = 12\nconst HARD_CEILING_MULTIPLE = 4\n\n/**\n * Absolute output cap. `assembleWithBudget` deliberately emits required blocks\n * even when they alone exceed `maxBytes`; this bounds that escape hatch. Cuts\n * are on whole lines, and the truncation note always ends the document.\n */\nfunction applyHardCeiling(out: string, maxBytes: number): string {\n const ceiling = maxBytes * HARD_CEILING_MULTIPLE\n if (byteLength(out) <= ceiling) return out\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = ceiling - byteLength(noteSuffix)\n let kept = ''\n for (const line of out.split('\\n')) {\n const next = kept === '' ? line : `${kept}\\n${line}`\n if (byteLength(next) > budget) break\n kept = next\n }\n return kept === '' ? TRUNCATION_NOTE : `${kept}${noteSuffix}`\n}\n\n/** `> ` prefix on every line; blank lines stay blank inside the quote. */\nfunction blockquote(text: string): string[] {\n return text.split('\\n').map((line) => (line.length > 0 ? `> ${line}` : '>'))\n}\n\n/**\n * A prose section as a truncatable tail block.\n *\n * `assembleWithBudget` renders a tail block as `headingLine` + blank line +\n * items. A section with a heading maps onto that exactly. A section without\n * one has no heading to put there, so its first body line takes that slot and\n * the blank line the assembler inserts consumes the body's own paragraph\n * break. For prose — where paragraphs are already blank-line separated — this\n * is byte-for-byte verbatim; for a body with no blank line after its first\n * line it inserts one paragraph break. No characters are ever added, removed,\n * or reordered either way.\n */\nfunction sectionTail(section: DocumentSectionSource, level: number): TailSection {\n const lines = section.body.split('\\n')\n if (section.heading !== undefined && section.heading.length > 0) {\n return { headingLine: heading(level, inline(section.heading)), items: lines }\n }\n const rest = lines.slice(1)\n if (rest[0] === '') rest.shift()\n return { headingLine: lines[0] ?? '', items: rest }\n}\n\n/**\n * Render any non-commerce page as clean markdown. Facts come first: an agent\n * reading top-down gets the whole machine-readable payload before any prose,\n * and prose is the only thing the byte budget can take away.\n */\nexport function renderDocumentMarkdown(doc: DocumentSource, opts?: RenderOptions): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n const sub = clampHeadingLevel(level + 1)\n const subSub = clampHeadingLevel(sub + 1)\n const access = doc.access ?? 'free'\n\n // A document whose own canonical URL is not allowlisted still renders — an\n // agent losing the self-link is better than losing the facts — but it never\n // renders as a link.\n const titleText = isAllowedUrl(doc.url)\n ? markdownLink(doc.title, doc.url)\n : linkLabel(doc.title)\n\n const updated = doc.updated !== undefined && isIsoDate(doc.updated) ? doc.updated : undefined\n const facts = (doc.facts ?? []).slice(0, MAX_FACTS)\n\n const factLines: string[] = []\n if (updated !== undefined) factLines.push(`- **${UPDATED_LABEL}:** ${updated}`)\n for (const fact of facts) {\n // Dedup: a top-level `updated` wins over a fact that repeats it. Two\n // \"Updated\" lines disagreeing is worse than one that might be stale.\n if (updated !== undefined && fact.label.trim().toLowerCase() === UPDATED_LABEL.toLowerCase()) {\n continue\n }\n const line = renderFactLine(fact)\n if (line !== null) factLines.push(line)\n }\n\n const head: string[] = [heading(level, titleText)]\n if (doc.summary !== undefined && doc.summary.length > 0) {\n head.push('', ...blockquote(doc.summary))\n }\n if (factLines.length > 0) head.push('', ...factLines)\n\n const requiredBlocks: string[] = [head.join('\\n')]\n\n for (const fact of facts) {\n if (fact.value.type !== 'hours') continue\n const block = renderHoursBlock(fact.label, fact.value.value, sub, subSub)\n if (block !== null) requiredBlocks.push(block)\n }\n\n const contactLines: string[] = []\n const contact = doc.contact\n if (contact !== undefined) {\n if (contact.phone !== undefined) contactLines.push(`- **${PHONE_LABEL}:** ${inline(contact.phone)}`)\n if (contact.email !== undefined) contactLines.push(`- **${EMAIL_LABEL}:** ${inline(contact.email)}`)\n if (contact.address !== undefined && contact.address.length > 0) {\n contactLines.push(`- **${ADDRESS_LABEL}:** ${contact.address.map(inline).join(', ')}`)\n }\n // No label: there is no whitelisted word for \"the contact URL\", and\n // inventing one would put renderer prose in the output.\n if (contact.url !== undefined && isAllowedUrl(contact.url)) contactLines.push(`- ${contact.url}`)\n }\n if (contactLines.length > 0) {\n requiredBlocks.push([heading(sub, CONTACT_HEADING), '', ...contactLines].join('\\n'))\n }\n\n const actionLines: string[] = []\n for (const action of (doc.actions ?? []).slice(0, MAX_ACTIONS)) {\n if (!isAllowedUrl(action.url)) continue\n actionLines.push(`- ${markdownLink(action.label, action.url)}`)\n if (action.note !== undefined) actionLines.push(` - ${inline(action.note)}`)\n }\n if (actionLines.length > 0) {\n requiredBlocks.push([heading(sub, ACTIONS_HEADING), '', ...actionLines].join('\\n'))\n }\n\n if (access !== 'free') requiredBlocks.push(accessNotice(access))\n\n const tail: TailSection[] = []\n // Mechanical, not a prose rule: `sections` is only ever read on this branch,\n // so no renderer bug below can leak a paywalled body.\n if (access === 'free') {\n for (const section of doc.sections ?? []) tail.push(sectionTail(section, sub))\n }\n\n const relatedItems: string[] = []\n for (const link of doc.related ?? []) {\n if (!isAllowedUrl(link.url)) continue\n relatedItems.push(`- ${markdownLink(link.title, link.url)}`)\n if (link.note !== undefined) relatedItems.push(` - ${inline(link.note)}`)\n }\n if (relatedItems.length > 0) {\n tail.push({ headingLine: heading(sub, RELATED_HEADING), items: relatedItems })\n }\n\n return applyHardCeiling(assembleWithBudget(requiredBlocks, tail, maxBytes), maxBytes)\n}\n\n/* ------------------------------------------------------------------ *\n * Collections.\n * ------------------------------------------------------------------ */\n\n/**\n * Exact byte length of `| a | b | c |` given the byte lengths of the cells:\n * two spaces around each cell, one pipe between each pair, one at each end.\n */\nfunction rowBytes(cellByteSum: number, columnCount: number): number {\n return cellByteSum + 3 * columnCount + 1\n}\n\nfunction tableRow(cells: string[]): string {\n return `| ${cells.join(' | ')} |`\n}\n\n/** One item's cells, in the order their columns should first appear. */\nfunction itemCells(item: CollectionItemSource): { label: string; text: string }[] {\n const cells: { label: string; text: string }[] = []\n if (item.summary !== undefined && item.summary.length > 0) {\n cells.push({ label: NOTE_LABEL, text: cell(item.summary) })\n }\n for (const fact of item.facts ?? []) {\n const text = factCellText(fact.value, item.url)\n if (text === null) continue\n cells.push({ label: cell(fact.label), text })\n }\n return cells\n}\n\nfunction titleCell(item: CollectionItemSource): string {\n return isAllowedUrl(item.url) ? cellLink(item.title, item.url) : cell(item.title)\n}\n\n/**\n * Render a listing page. Two deterministic modes and no third: if no item\n * carries facts the output is a link list, otherwise it is a table.\n *\n * The table's columns are the ordered union of fact labels by first\n * appearance, accumulated in the SAME streaming pass that spends the byte\n * budget. That is the whole point: compute the union first and the header can\n * advertise columns belonging only to rows the budget then drops, which is a\n * table of empty cells describing data we did not send. Byte accounting is\n * exact rather than estimated (see `rowBytes`), so the pass never has to\n * re-render to find out whether it overshot.\n *\n * An item `summary` occupies a `Note` column, positioned by the same\n * first-appearance rule. A merchant fact literally labelled `Note` on an item\n * that also has a summary collides; the summary wins, because it was written\n * for the listing.\n */\nexport function renderCollectionMarkdown(\n collection: CollectionSource,\n opts?: RenderOptions,\n): string {\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES\n const level = clampHeadingLevel(opts?.headingLevel ?? 1)\n\n const title = collection.title !== undefined ? collection.title : CONTENTS_HEADING\n const titleText = isAllowedUrl(collection.url)\n ? markdownLink(title, collection.url)\n : linkLabel(title)\n const head = heading(level, titleText)\n\n const items = collection.items\n if (items.length === 0) return head\n\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n const budget = maxBytes - byteLength(noteSuffix)\n const anyFacts = items.some((item) => (item.facts ?? []).length > 0)\n\n if (!anyFacts) return linkList(head, items, budget)\n\n // Streaming pass: columns and rows grow together, bounded by `budget`.\n const columns: string[] = []\n const rows: Map<string, string>[] = []\n let headerCellBytes = byteLength(TITLE_LABEL)\n let bodyCellBytes = 0\n let truncated = false\n\n // head + '\\n\\n' + headerRow + '\\n' + separatorRow + ('\\n' + row) per row.\n // Separator cells are always '---', i.e. 3 bytes each.\n const base = byteLength(head) + 2\n const totalBytes = (columnCount: number, rowCount: number): number =>\n base +\n rowBytes(headerCellBytes, columnCount) +\n 1 +\n rowBytes(3 * columnCount, columnCount) +\n bodyCellBytes +\n rowCount * (3 * columnCount + 2)\n\n for (const item of items) {\n if (rows.length >= MAX_COLLECTION_ROWS) {\n truncated = true\n break\n }\n\n const cells = itemCells(item)\n const values = new Map<string, string>()\n const newColumns: string[] = []\n for (const { label, text } of cells) {\n if (values.has(label)) continue // first write wins within a row\n if (!columns.includes(label) && !newColumns.includes(label)) {\n if (columns.length + newColumns.length >= MAX_COLLECTION_COLUMNS) continue\n newColumns.push(label)\n }\n values.set(label, text)\n }\n values.set(TITLE_LABEL, titleCell(item))\n\n const nextColumnCount = 1 + columns.length + newColumns.length\n const addedHeaderBytes = newColumns.reduce((sum, label) => sum + byteLength(label), 0)\n const addedBodyBytes = [...values.values()].reduce((sum, text) => sum + byteLength(text), 0)\n\n const savedHeader = headerCellBytes\n const savedBody = bodyCellBytes\n headerCellBytes += addedHeaderBytes\n bodyCellBytes += addedBodyBytes\n if (totalBytes(nextColumnCount, rows.length + 1) > budget) {\n headerCellBytes = savedHeader\n bodyCellBytes = savedBody\n truncated = true\n break\n }\n\n columns.push(...newColumns)\n rows.push(values)\n }\n\n // No row fit. A bare header advertises columns nothing fills — exactly what\n // the streaming pass exists to prevent — so emit no table at all.\n if (rows.length === 0) return `${head}${noteSuffix}`\n\n const header = [TITLE_LABEL, ...columns]\n const lines = [\n head,\n '',\n tableRow(header),\n tableRow(header.map(() => '---')),\n ...rows.map((values) => tableRow(header.map((label) => values.get(label) ?? ''))),\n ]\n const out = lines.join('\\n')\n return truncated ? `${out}${noteSuffix}` : out\n}\n\n/** Link-list mode: whole entries only, dropped from the bottom. */\nfunction linkList(head: string, items: CollectionItemSource[], budget: number): string {\n const noteSuffix = `\\n\\n${TRUNCATION_NOTE}`\n let out = head\n let truncated = false\n let rendered = 0\n\n for (const item of items) {\n if (rendered >= MAX_COLLECTION_ROWS) {\n truncated = true\n break\n }\n const link = isAllowedUrl(item.url)\n ? markdownLink(item.title, item.url)\n : inline(item.title)\n const entry: string[] = [`- ${link}`]\n if (item.summary !== undefined && item.summary.length > 0) {\n entry.push(` - ${inline(item.summary)}`)\n }\n const next = `${out}${rendered === 0 ? '\\n\\n' : '\\n'}${entry.join('\\n')}`\n if (byteLength(next) > budget) {\n truncated = true\n break\n }\n out = next\n rendered += 1\n }\n\n return truncated ? `${out}${noteSuffix}` : out\n}\n","/**\n * `CollectionSource` → schema.org `ItemList` JSON-LD.\n *\n * The listing counterpart to `src/jsonld.ts`'s `Product`. Before this existed,\n * a collection served through the universal gateway carried a markdown table\n * and no structured data at all, so a caller that reads JSON-LD first — and a\n * scorer looking for a recognised type — found nothing on a page whose entire\n * purpose is enumerating things.\n *\n * Injection-only, on the same terms as every other renderer here:\n *\n * - `name` is emitted ONLY when the source supplies a title. The markdown\n * renderer falls back to the fixed `Contents` heading because a document\n * needs a heading for structure; JSON-LD does not, and emitting the fallback\n * would make this package assert a name the merchant never wrote.\n * - URLs pass the same scheme allowlist the markdown path uses. A `ListItem`\n * whose URL is rejected still renders with its name — the item exists, we\n * just decline to publish a link to it. Skipping this check would make the\n * JSON-LD a `javascript:` sink that the markdown renderer already blocks.\n * - `numberOfItems` counts the elements ACTUALLY EMITTED, not `items.length`.\n * A 900-item listing truncates to `MAX_COLLECTION_ROWS`, and a document that\n * announced 900 while listing 500 would be internally inconsistent — an\n * agent trusting the count would page for items that are not there.\n * - Item facts are not projected into the list. `ListItem` has no honest slot\n * for an arbitrary labelled fact, and inventing property names for merchant\n * labels is exactly the inference this package does not do. The facts are in\n * the markdown table, which is where the renderer's contract puts them.\n */\n\nimport type { CollectionItemSource, CollectionSource } from './types'\nimport { isAllowedUrl } from './facts'\nimport { MAX_COLLECTION_ROWS } from './markdown'\nimport { isIsoDate, isLanguageTag } from '../internal/validate'\n\nfunction listItem(item: CollectionItemSource, position: number): Record<string, unknown> {\n const out: Record<string, unknown> = { '@type': 'ListItem', position }\n if (isAllowedUrl(item.url)) out.url = item.url\n out.name = item.title\n return out\n}\n\n/**\n * Render a schema.org ItemList from a collection source. Pure, deterministic,\n * and fixed in key order for snapshot stability — same contract as\n * `renderProductJsonLd`.\n */\nexport function renderCollectionJsonLd(collection: CollectionSource): Record<string, unknown> {\n const out: Record<string, unknown> = {\n '@context': 'https://schema.org',\n '@type': 'ItemList',\n }\n if (isAllowedUrl(collection.url)) out.url = collection.url\n if (collection.title !== undefined) out.name = collection.title\n if (collection.language !== undefined && isLanguageTag(collection.language)) {\n out.inLanguage = collection.language\n }\n\n const elements = collection.items\n .slice(0, MAX_COLLECTION_ROWS)\n .map((item, index) => listItem(item, index + 1))\n\n out.numberOfItems = elements.length\n out.itemListElement = elements\n if (collection.updated !== undefined && isIsoDate(collection.updated)) {\n out.dateModified = collection.updated\n }\n return out\n}\n","/** Conservative, compiled-in presentation strategies. No remote code or prose. */\nexport interface CompatibilityProfile {\n id: 'baseline' | 'source-envelope' | 'section-index'\n version: 1\n}\n\nexport const BASELINE_PROFILE: Readonly<CompatibilityProfile> = Object.freeze({\n id: 'baseline',\n version: 1,\n})\nexport const COMPATIBILITY_RUNTIME_VERSION = 1\n\nexport function validateCompatibilityProfile(value: unknown): CompatibilityProfile | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const profile = value as Record<string, unknown>\n if (Object.keys(profile).some((key) => key !== 'id' && key !== 'version')) return null\n if (\n profile.version !== 1 ||\n typeof profile.id !== 'string' ||\n !['baseline', 'source-envelope', 'section-index'].includes(profile.id)\n )\n return null\n return { id: profile.id as CompatibilityProfile['id'], version: 1 }\n}\n\nexport interface CompatibilityRendering {\n markdown: string\n /** Actual presentation served, including budget/invalid-selection fallback. */\n profile: CompatibilityProfile\n}\n\n/**\n * Baseline markdown stays a contiguous, byte-identical substring. Candidates\n * add orientation only; they cannot rewrite, remove or reorder any source fact\n * or qualification. Existing renderer truncation still applies. If additions\n * do not fit the caller's budget, use the baseline and report that honestly.\n */\nexport function applyCompatibilityProfile(\n markdown: string,\n selected: unknown,\n options: { canonicalUrl: string; maxBytes?: number },\n): CompatibilityRendering {\n const profile = validateCompatibilityProfile(selected) ?? BASELINE_PROFILE\n const baseline = { markdown, profile: { ...BASELINE_PROFILE } }\n if (profile.id === 'baseline') return baseline\n let prefix = ''\n if (profile.id === 'source-envelope') {\n let canonical: URL\n try {\n canonical = new URL(options.canonicalUrl)\n } catch {\n return baseline\n }\n if (\n !['https:', 'http:'].includes(canonical.protocol) ||\n canonical.username ||\n canonical.password\n )\n return baseline\n // JSON encoding makes line breaks and markdown delimiters inert metadata.\n prefix = `Source: ${JSON.stringify(canonical.href)}\\n\\n`\n } else {\n // Navigation duplicates only existing headings; merchant text remains intact.\n const headings = markdown\n .split('\\n')\n .filter((line) => /^#{1,6} /.test(line))\n .slice(0, 12)\n if (headings.length < 2) return baseline\n prefix = `Sections on this page:\\n${headings.map((line) => `- ${line.replace(/^#{1,6} /, '')}`).join('\\n')}\\n\\n`\n }\n const output = prefix + markdown\n const bytes = new TextEncoder().encode(output).byteLength\n if (new TextEncoder().encode(prefix).byteLength > 1024 || bytes > (options.maxBytes ?? 5120))\n return baseline\n return { markdown: output, profile }\n}\n","/**\n * YAML frontmatter for a markdown document: the page's title, description,\n * canonical URL and last-updated date, as a block a caller can put in front of\n * any rendered markdown.\n *\n * OPT-IN. No renderer in this package calls it, so every existing output stays\n * byte-for-byte what it was. `@rebilder/gateway` prepends it only when a\n * merchant sets `frontmatter: true`.\n *\n * Same contract as the renderers:\n *\n * - Every value is injected verbatim from the caller's fields. Nothing is\n * generated: no default title, no summary written from the body, no date\n * from a clock. A field the caller does not have is absent from the block.\n * - Values are gated, never repaired. `canonicalUrl` must be an absolute\n * `http:` or `https:` URL and `lastUpdated` a real ISO 8601 date or datetime;\n * anything else is dropped.\n * - The four keys and the `---` fences are the only text this function adds.\n *\n * Scalars: a value is written bare when YAML reads it back as exactly that\n * string: one line, starting with a letter or digit, with no `: ` or ` #`, and\n * not a word or number YAML would turn into a boolean, null, number or date.\n * Everything else is double-quoted with JSON string escapes, which YAML\n * accepts. Bare where possible, because a bare value is byte-for-byte the\n * source text, so anything reading `description: …` as a labelled line sees\n * the same sentence the page states elsewhere rather than a quoted copy of it.\n * A newline, quote or `---` inside a value always lands inside quotes on one\n * line, so source text can never close the block early or add a key of its own.\n *\n * Bounded: a block over {@link FRONTMATTER_MAX_BYTES} drops `description`, the\n * one long free-text field; if it is still over, no frontmatter is returned.\n * The markdown body is never cut to make room.\n */\n\nimport { byteLength } from './internal/budget'\nimport { isIsoDate } from './internal/validate'\n\nexport interface FrontmatterFields {\n /** Page title, verbatim. Emitted as `title`. */\n title?: string\n /** Short description of the page, verbatim. Emitted as `description`. */\n description?: string\n /**\n * Absolute `http:` or `https:` URL of the canonical HTML page this markdown\n * represents. Emitted as `canonical_url`.\n */\n canonicalUrl?: string\n /** ISO 8601 date or datetime. Emitted as `last_updated`. */\n lastUpdated?: string\n}\n\n/** Largest frontmatter block, fences included, in UTF-8 bytes. */\nexport const FRONTMATTER_MAX_BYTES = 2048\n\n/** A string with visible content, or null. Untyped input that is not a string is dropped. */\nfunction text(value: unknown): string | null {\n return typeof value === 'string' && value.trim() !== '' ? value : null\n}\n\nfunction httpUrl(value: unknown): string | null {\n const raw = text(value)\n if (raw === null) return null\n try {\n const parsed = new URL(raw)\n return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? raw : null\n } catch {\n return null\n }\n}\n\nfunction isoDate(value: unknown): string | null {\n const raw = text(value)\n return raw !== null && isIsoDate(raw) ? raw : null\n}\n\n/**\n * A double-quoted YAML scalar, for any value that cannot be bare. JSON escapes\n * are a subset of YAML's, and\n * U+2028/U+2029 are escaped as well because some YAML 1.1 parsers read them\n * as line breaks. The two characters are built from code points so no\n * editor or tool can turn the pattern into a literal line break.\n */\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\nfunction quoted(value: string): string {\n return JSON.stringify(value)\n .split(LINE_SEPARATOR)\n .join('\\\\u2028')\n .split(PARAGRAPH_SEPARATOR)\n .join('\\\\u2029')\n}\n\n/** Words YAML 1.1 or 1.2 would read as a boolean or null. */\nconst TYPED_WORD = /^(?:true|false|yes|no|on|off|y|n|null|~)$/i\n/** Anything YAML could read as a number (including hex, octal, sexagesimal) or a date. */\nconst NUMBER_LIKE = /^[0-9][0-9a-fA-FxXoO_.:+-]*$/\nconst DATE_LIKE = /^\\d{4}-\\d{1,2}-\\d{1,2}/\n\n/** Control characters, C1 controls, line/paragraph separators and the BOM. */\nfunction hasUnprintable(value: string): boolean {\n for (let i = 0; i < value.length; i += 1) {\n const code = value.charCodeAt(i)\n if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) return true\n if (code === 0x2028 || code === 0x2029 || code === 0xfeff) return true\n }\n return false\n}\n\n/** True when YAML reads the bare value back as exactly this string. */\nfunction isPlainSafe(value: string): boolean {\n if (value !== value.trim() || hasUnprintable(value)) return false\n if (!/^[\\p{L}\\p{N}]/u.test(value)) return false\n if (value.includes(': ') || value.includes(' #') || value.endsWith(':')) return false\n return !TYPED_WORD.test(value) && !NUMBER_LIKE.test(value) && !DATE_LIKE.test(value)\n}\n\nfunction scalar(value: string): string {\n return isPlainSafe(value) ? value : quoted(value)\n}\n\nfunction block(entries: [string, string | null][]): string {\n const lines = entries\n .filter((entry): entry is [string, string] => entry[1] !== null)\n .map(([key, value]) => `${key}: ${scalar(value)}`)\n return lines.length === 0 ? '' : `---\\n${lines.join('\\n')}\\n---\\n`\n}\n\n/**\n * Render the frontmatter block, ending in a newline, or `''` when no field\n * survives validation. Put it first in the document: `block + '\\n' + markdown`.\n */\nexport function renderFrontmatter(fields: FrontmatterFields): string {\n const title = text(fields.title)\n const canonical = httpUrl(fields.canonicalUrl)\n const updated = isoDate(fields.lastUpdated)\n const full = block([\n ['title', title],\n ['description', text(fields.description)],\n ['canonical_url', canonical],\n ['last_updated', updated],\n ])\n if (byteLength(full) <= FRONTMATTER_MAX_BYTES) return full\n const short = block([\n ['title', title],\n ['canonical_url', canonical],\n ['last_updated', updated],\n ])\n return byteLength(short) <= FRONTMATTER_MAX_BYTES ? short : ''\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -145,8 +145,8 @@ declare function renderCatalogMarkdown(items: CatalogItemSource[], opts?: Render
145
145
  *
146
146
  * The same guarantee as the commerce types applies to every field here: it is
147
147
  * authoritative merchant data, and the renderers only transform format. They
148
- * never invent, estimate, or reword a value found on these types (CLAUDE.md
149
- * source validation).
148
+ * never invent, estimate, or reword a value found on these types (project
149
+ * convention: source validation).
150
150
  *
151
151
  * Why two types (document + collection) and not one per vertical: see the
152
152
  * promotion bar in README.md. Every vertical evaluated so far reduces to
@@ -509,4 +509,58 @@ declare function applyCompatibilityProfile(markdown: string, selected: unknown,
509
509
  maxBytes?: number;
510
510
  }): CompatibilityRendering;
511
511
 
512
- export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BASELINE_PROFILE, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, type CatalogItemSource, type CollectionItemSource, type CollectionSource, type CompatibilityProfile, type CompatibilityRendering, type ContactSource, type DocumentAccess, type DocumentKind, type DocumentSectionSource, type DocumentSource, type Fact, type FactValue, type HoursException, type HoursInterval, type HoursRule, type HoursSpec, type LinkSource, type Money, NOT_STATED_LABEL, PERIOD_SUFFIX, type PolicySource, type ProductSource, type ProductVariantSource, type RenderOptions, type ReturnsSource, SEE_PAGE_LABEL, type ShippingSource, WEEKDAY_LABELS, WEEKDAY_ORDER, type Weekday, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };
512
+ /**
513
+ * YAML frontmatter for a markdown document: the page's title, description,
514
+ * canonical URL and last-updated date, as a block a caller can put in front of
515
+ * any rendered markdown.
516
+ *
517
+ * OPT-IN. No renderer in this package calls it, so every existing output stays
518
+ * byte-for-byte what it was. `@rebilder/gateway` prepends it only when a
519
+ * merchant sets `frontmatter: true`.
520
+ *
521
+ * Same contract as the renderers:
522
+ *
523
+ * - Every value is injected verbatim from the caller's fields. Nothing is
524
+ * generated: no default title, no summary written from the body, no date
525
+ * from a clock. A field the caller does not have is absent from the block.
526
+ * - Values are gated, never repaired. `canonicalUrl` must be an absolute
527
+ * `http:` or `https:` URL and `lastUpdated` a real ISO 8601 date or datetime;
528
+ * anything else is dropped.
529
+ * - The four keys and the `---` fences are the only text this function adds.
530
+ *
531
+ * Scalars: a value is written bare when YAML reads it back as exactly that
532
+ * string: one line, starting with a letter or digit, with no `: ` or ` #`, and
533
+ * not a word or number YAML would turn into a boolean, null, number or date.
534
+ * Everything else is double-quoted with JSON string escapes, which YAML
535
+ * accepts. Bare where possible, because a bare value is byte-for-byte the
536
+ * source text, so anything reading `description: …` as a labelled line sees
537
+ * the same sentence the page states elsewhere rather than a quoted copy of it.
538
+ * A newline, quote or `---` inside a value always lands inside quotes on one
539
+ * line, so source text can never close the block early or add a key of its own.
540
+ *
541
+ * Bounded: a block over {@link FRONTMATTER_MAX_BYTES} drops `description`, the
542
+ * one long free-text field; if it is still over, no frontmatter is returned.
543
+ * The markdown body is never cut to make room.
544
+ */
545
+ interface FrontmatterFields {
546
+ /** Page title, verbatim. Emitted as `title`. */
547
+ title?: string;
548
+ /** Short description of the page, verbatim. Emitted as `description`. */
549
+ description?: string;
550
+ /**
551
+ * Absolute `http:` or `https:` URL of the canonical HTML page this markdown
552
+ * represents. Emitted as `canonical_url`.
553
+ */
554
+ canonicalUrl?: string;
555
+ /** ISO 8601 date or datetime. Emitted as `last_updated`. */
556
+ lastUpdated?: string;
557
+ }
558
+ /** Largest frontmatter block, fences included, in UTF-8 bytes. */
559
+ declare const FRONTMATTER_MAX_BYTES = 2048;
560
+ /**
561
+ * Render the frontmatter block, ending in a newline, or `''` when no field
562
+ * survives validation. Put it first in the document: `block + '\n' + markdown`.
563
+ */
564
+ declare function renderFrontmatter(fields: FrontmatterFields): string;
565
+
566
+ export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BASELINE_PROFILE, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, type CatalogItemSource, type CollectionItemSource, type CollectionSource, type CompatibilityProfile, type CompatibilityRendering, type ContactSource, type DocumentAccess, type DocumentKind, type DocumentSectionSource, type DocumentSource, FRONTMATTER_MAX_BYTES, type Fact, type FactValue, type FrontmatterFields, type HoursException, type HoursInterval, type HoursRule, type HoursSpec, type LinkSource, type Money, NOT_STATED_LABEL, PERIOD_SUFFIX, type PolicySource, type ProductSource, type ProductVariantSource, type RenderOptions, type ReturnsSource, SEE_PAGE_LABEL, type ShippingSource, WEEKDAY_LABELS, WEEKDAY_ORDER, type Weekday, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderFrontmatter, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };