@simpleapps-com/augur-server 2026.11.5 → 2026.11.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EXPORTS.md +26 -1
- package/README.md +33 -2
- package/dist/actions/action-rules.d.ts +99 -0
- package/dist/actions/action-rules.d.ts.map +1 -0
- package/dist/actions/agr-site.d.ts +7 -15
- package/dist/actions/agr-site.d.ts.map +1 -1
- package/dist/actions/commerce.d.ts.map +1 -1
- package/dist/actions/customers.d.ts +12 -15
- package/dist/actions/customers.d.ts.map +1 -1
- package/dist/actions/favorites.d.ts +9 -12
- package/dist/actions/favorites.d.ts.map +1 -1
- package/dist/actions/gregorovich.d.ts +7 -15
- package/dist/actions/gregorovich.d.ts.map +1 -1
- package/dist/actions/items.d.ts +8 -20
- package/dist/actions/items.d.ts.map +1 -1
- package/dist/actions/joomla.d.ts +8 -14
- package/dist/actions/joomla.d.ts.map +1 -1
- package/dist/actions/legacy.d.ts +10 -20
- package/dist/actions/legacy.d.ts.map +1 -1
- package/dist/actions/orders.d.ts +7 -14
- package/dist/actions/orders.d.ts.map +1 -1
- package/dist/actions/read-specs.d.ts +119 -0
- package/dist/actions/read-specs.d.ts.map +1 -0
- package/dist/actions/site.d.ts.map +1 -1
- package/dist/actions/vmi.d.ts +10 -16
- package/dist/actions/vmi.d.ts.map +1 -1
- package/dist/actions/wishlists.d.ts +11 -13
- package/dist/actions/wishlists.d.ts.map +1 -1
- package/dist/api-handler.d.ts.map +1 -1
- package/dist/api.js +3 -2
- package/dist/api.js.map +1 -1
- package/dist/auth.js +3 -2
- package/dist/cache/redis-client.d.ts.map +1 -1
- package/dist/cache/redis-rules.d.ts +21 -0
- package/dist/cache/redis-rules.d.ts.map +1 -0
- package/dist/cache/spec-read.d.ts +39 -0
- package/dist/cache/spec-read.d.ts.map +1 -0
- package/dist/cache/with-cache.d.ts +2 -2
- package/dist/cache/with-cache.d.ts.map +1 -1
- package/dist/{chunk-KSGH4DXD.js → chunk-4JPJQHT6.js} +2 -2
- package/dist/{chunk-FIM6LDMD.js → chunk-GJHQPBK7.js} +5 -3
- package/dist/chunk-GJHQPBK7.js.map +1 -0
- package/dist/chunk-JIYVQWXK.js +10 -0
- package/dist/chunk-JIYVQWXK.js.map +1 -0
- package/dist/{chunk-U54IM6FL.js → chunk-SFXO74RC.js} +874 -719
- package/dist/chunk-SFXO74RC.js.map +1 -0
- package/dist/chunk-V76GZZF3.js +66 -0
- package/dist/chunk-V76GZZF3.js.map +1 -0
- package/dist/{chunk-6GPKXGPG.js → chunk-Z53NEFEQ.js} +8 -16
- package/dist/chunk-Z53NEFEQ.js.map +1 -0
- package/dist/hooks.d.ts +2 -2
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js +5 -3
- package/dist/hooks.js.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/query-action.d.ts +11 -4
- package/dist/query-action.d.ts.map +1 -1
- package/dist/query-action.js +3 -2
- package/dist/read-rules.d.ts +45 -0
- package/dist/read-rules.d.ts.map +1 -0
- package/dist/server-site-registry.d.ts.map +1 -1
- package/dist/server-site.d.ts.map +1 -1
- package/dist/site.js +24 -14
- package/dist/site.js.map +1 -1
- package/dist/sitemap-rules.d.ts +154 -0
- package/dist/sitemap-rules.d.ts.map +1 -0
- package/dist/sitemap.d.ts +80 -0
- package/dist/sitemap.d.ts.map +1 -0
- package/dist/sitemap.js +242 -0
- package/dist/sitemap.js.map +1 -0
- package/dist/testing.js +4 -2
- package/dist/testing.js.map +1 -1
- package/dist/utils/read-all-pages.d.ts +17 -0
- package/dist/utils/read-all-pages.d.ts.map +1 -0
- package/llms.txt +44 -1
- package/package.json +9 -5
- package/dist/chunk-6GPKXGPG.js.map +0 -1
- package/dist/chunk-FIM6LDMD.js.map +0 -1
- package/dist/chunk-U54IM6FL.js.map +0 -1
- /package/dist/{chunk-KSGH4DXD.js.map → chunk-4JPJQHT6.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../utils/src/replace.ts","../../utils/src/xml.ts","../../utils/src/sitemap.ts","../src/sitemap-rules.ts","../src/sitemap.ts"],"sourcesContent":["//@ backend dafny\nimport { codeAt, indexOfFrom } from \"./strings\";\n\n/* Whole-string rewrites, verified with LemmaScript → Dafny (model: models/Utils.dfy \"text\n replacement\"; link: models/links/utils-replace.dfy). Each has a recursive spec (for\n proofs and tests) and a loop proved to build exactly it (for callers: its depth doesn't\n grow with the input). The `\\result === spec(s)` clause of each loop is a hand `ensures`\n in replace.dfy, as utils `escapeHtml`'s is: lsc would put it in every importer's axiom,\n where this file's own spec isn't emitted. */\n\n// --- One substitution rule (model `Utils.Substituted`, 2026-11-03): each code unit found in a\n// table is replaced by its text, every other kept. replaceCode, pointerToken, escapeHtml and\n// the generator's look-alike fold are this rule, each with its own table.\n\n/**\n * The first index ≥ `i` holding `c` in `codes`, or -1.\n *\n * @ensures result = -1 ∨ (i ≤ result < |codes| ∧ codes[result] = c) — the model's CodeIndex\n */\nexport function codeIndex(codes: number[], c: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i <= codes.length\n //@ decreases codes.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result < codes.length && codes[\\result] === c)\n // `===`, not `>=`: past the end codes[i] is undefined, never c, so `>=` vs `>` is equivalent\n if (i === codes.length) return -1;\n return (codes[i] as number) === c ? i : codeIndex(codes, c, i + 1);\n}\n\n/** `s` with each code unit in `codes` replaced by its text, recursively: the spec `substitute` builds. */\nexport function substitutedText(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ decreases s.length\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n if (s.length === 0) return \"\";\n const k = codeIndex(codes, s.charCodeAt(0), 0);\n const head = k >= 0 && k < texts.length ? (texts[k] as string) : s.slice(0, 1);\n return head + substitutedText(s.slice(1), codes, texts);\n}\n\n/**\n * `s` with each code unit in `codes` replaced by the text at its first index there, every\n * other kept. A loop, so its depth doesn't grow with the input.\n *\n * @ensures result = substitutedText(s, codes, texts) — the model's Substituted (a hand\n * ensures in replace.dfy: importers can't resolve substitutedText)\n * @ensures |s| = 0 ⟹ result = \"\" ∧ |codes| = 0 ⟹ result = s — no table, no change\n */\nexport function substitute(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n let out = \"\";\n // `!==`, not `<`: one step past the end reads NaN and adds \"\", so `<=` would be equivalent\n for (let i = 0; i !== s.length; i++) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + substitutedText(s.slice(i), codes, texts) === substitutedText(s, codes, texts)\n //@ decreases s.length - i\n const k = codeIndex(codes, s.charCodeAt(i), 0);\n out = k >= 0 && k < texts.length ? out + (texts[k] as string) : out + s.slice(i, i + 1);\n }\n return out;\n}\n\n/**\n * `s` with every `from` code unit replaced by `to`, recursively: the one-entry table.\n *\n * @ensures no `from` survives when `to` holds none — exactly the model's ReplaceCode in the link\n */\nexport function replacedCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitutedText(s, [from], [to]);\n}\n\n/**\n * `s` with every `from` code unit replaced by `to` (`replaceAll` of one character).\n *\n * @ensures no `from` survives when `to` holds none (ReplaceCodeRemoves) — = replacedCode(s,\n * from, to), the model's ReplaceCode, as a hand ensures in replace.dfy\n */\nexport function replaceCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitute(s, [from], [to]);\n}\n\n/**\n * `s` with its first `find` replaced by `put`; no match leaves it: JS `s.replace(find, put)` for\n * a string `find`, when `put` holds no `$` (JS reads `$&`, `$1` there as a pattern).\n *\n * @ensures exactly the model's ReplaceFirst\n */\nexport function replaceFirst(s: string, find: string, put: string): string {\n //@ verify\n //@ ensures \\result === (indexOfFrom(s, find, 0) < 0 ? s : s.slice(0, indexOfFrom(s, find, 0)) + put + s.slice(indexOfFrom(s, find, 0) + find.length))\n const i = indexOfFrom(s, find, 0);\n if (i < 0) return s;\n return s.slice(0, i) + put + s.slice(i + find.length);\n}\n\n/**\n * `s` with every `find` replaced by `put`, left to right without overlaps: JS\n * `s.split(find).join(put)` for a non-empty `find` (tests pin the two). Recursive, with no\n * loop twin: its callers fill short templates (the SDK's registry paths), so the depth stays\n * small; a long-input caller would need one.\n *\n * @requires |find| > 0 — split(\"\") splits into characters, a different rule\n * @ensures text shorter than `find` is unchanged, and so is any text when `put` = `find` —\n * exactly the model's ReplaceText in the link\n */\nexport function replaceText(s: string, find: string, put: string): string {\n //@ verify\n //@ requires find.length > 0\n //@ decreases s.length\n //@ ensures s.length < find.length ==> \\result === s\n //@ ensures put === find ==> \\result === s\n if (s.length < find.length) return s;\n if (s.slice(0, find.length) === find) {\n return put + replaceText(s.slice(find.length), find, put);\n }\n return s.slice(0, 1) + replaceText(s.slice(1), find, put);\n}\n\n/**\n * A JSON Pointer token of `s`, recursively: `~` → `~0`, `/` → `~1`.\n *\n * @ensures never holds \"/\" — exactly the model's PointerToken in the link\n */\nexport function pointerTokenOf(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitutedText(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * `s` as a JSON Pointer reference token (RFC 6901 §3): `~` as `~0`, `/` as `~1`.\n *\n * @ensures never holds \"/\" (PointerTokenHasNoSlash) — = pointerTokenOf(s), the model's\n * PointerToken, as a hand ensures in replace.dfy\n */\nexport function pointerToken(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitute(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * The escape of `s`, recursively: each `&` `<` `>` `\"` `'` as its entity.\n *\n * @ensures no `<` `>` `\"` `'` in result — exactly the model's EscapeHtml in the link\n */\nexport function escapedText(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitutedText(s, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * Escape text for an HTML body or a double-quoted attribute.\n *\n * @ensures result = escapedText(value) — exactly the model's EscapeHtml (a hand ensures in\n * replace.dfy, since importers can't see escapedText)\n * @ensures ∀ k < |result|. result[k] ∉ {\"<\", \">\", \"\\\"\", \"'\"} — nothing in the output can\n * open a tag or close the attribute; \"&\" appears only as the start of an entity\n */\nexport function escapeHtml(value: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitute(value, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * The code units a JSON string escapes: `\"`, `\\`, then the control characters with short\n * escapes (\\b \\t \\n \\f \\r), then the other code units below 0x20.\n *\n * @ensures exactly the model's JsonCodes\n */\nexport function jsonCodes(): number[] {\n //@ verify\n //@ ensures \\result === [34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]\n return [\n 34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n ];\n}\n\n/**\n * Each `jsonCodes` entry's escape (ECMA-262 QuoteJSONString; lowercase hex, as JSON.stringify).\n *\n * @ensures exactly the model's JsonTexts\n */\nexport function jsonTexts(): string[] {\n //@ verify\n //@ ensures \\result === [\"\\\\\\\"\", \"\\\\\\\\\", \"\\\\b\", \"\\\\t\", \"\\\\n\", \"\\\\f\", \"\\\\r\", \"\\\\u0000\", \"\\\\u0001\", \"\\\\u0002\", \"\\\\u0003\", \"\\\\u0004\", \"\\\\u0005\", \"\\\\u0006\", \"\\\\u0007\", \"\\\\u000b\", \"\\\\u000e\", \"\\\\u000f\", \"\\\\u0010\", \"\\\\u0011\", \"\\\\u0012\", \"\\\\u0013\", \"\\\\u0014\", \"\\\\u0015\", \"\\\\u0016\", \"\\\\u0017\", \"\\\\u0018\", \"\\\\u0019\", \"\\\\u001a\", \"\\\\u001b\", \"\\\\u001c\", \"\\\\u001d\", \"\\\\u001e\", \"\\\\u001f\"]\n return [\n '\\\\\"',\n \"\\\\\\\\\",\n \"\\\\b\",\n \"\\\\t\",\n \"\\\\n\",\n \"\\\\f\",\n \"\\\\r\",\n \"\\\\u0000\",\n \"\\\\u0001\",\n \"\\\\u0002\",\n \"\\\\u0003\",\n \"\\\\u0004\",\n \"\\\\u0005\",\n \"\\\\u0006\",\n \"\\\\u0007\",\n \"\\\\u000b\",\n \"\\\\u000e\",\n \"\\\\u000f\",\n \"\\\\u0010\",\n \"\\\\u0011\",\n \"\\\\u0012\",\n \"\\\\u0013\",\n \"\\\\u0014\",\n \"\\\\u0015\",\n \"\\\\u0016\",\n \"\\\\u0017\",\n \"\\\\u0018\",\n \"\\\\u0019\",\n \"\\\\u001a\",\n \"\\\\u001b\",\n \"\\\\u001c\",\n \"\\\\u001d\",\n \"\\\\u001e\",\n \"\\\\u001f\",\n ];\n}\n\n/**\n * A string as JSON text, as `JSON.stringify(s)` writes it for well-formed text: quoted, `\"`\n * and `\\` backslashed, control characters escaped. A lone surrogate is kept as it is\n * (JSON.stringify writes `\\udxxx`); callers pass well-formed text. Built by the `substitute`\n * loop, so its depth doesn't grow with the text (an FAQ answer can be long; Fable review\n * 2026-11-06); importers still see a function (its contract as an axiom), so their premise\n * `jsonString(s) == Utils.JsonString(s)` stands.\n *\n * @ensures result = `\"` + substitutedText(s, jsonCodes(), jsonTexts()) + `\"` — a hand ensures in\n * replace.dfy; the model's JsonString (proved in links/utils-replace.dfy)\n * @ensures result starts and ends with `\"`\n */\nexport function jsonString(s: string): string {\n //@ verify\n //@ ensures \\result.length >= 2 && \\result.charCodeAt(0) === 34 && \\result.charCodeAt(\\result.length - 1) === 34\n return '\"' + substitute(s, jsonCodes(), jsonTexts()) + '\"';\n}\n\n/**\n * `s` with every `*` `/` pair written `* /`, recursively: the spec `commentSafe` builds.\n *\n * @ensures no \"*\" \"/\" pair in result — exactly the model's CommentSafe in the link\n */\nexport function commentSafeOf(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n if (s.length === 0) return \"\";\n if (codeAt(s, 0) === 42 && codeAt(s, 1) === 47) {\n return \"* /\" + commentSafeOf(s.slice(2));\n }\n return s.slice(0, 1) + commentSafeOf(s.slice(1));\n}\n\n/**\n * Text safe inside a `/* … *\\/` comment: every `*` `/` pair written `* /`.\n *\n * @ensures no \"*\" \"/\" pair in result: nothing can close the comment — = commentSafeOf(s), the\n * model's CommentSafe, as a hand ensures in replace.dfy\n */\nexport function commentSafe(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + commentSafeOf(s.slice(i)) === commentSafeOf(s)\n //@ decreases s.length - i\n if (codeAt(s, i) === 42 && codeAt(s, i + 1) === 47) {\n out = out + \"* /\";\n i = i + 2;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n","//@ backend dafny\n\n/* XML text escaping, verified with LemmaScript → Dafny (model: models/Sitemap.dfy XmlEscape;\n link: models/links/utils-xml.dfy). The sitemap protocol's list, exactly (sitemaps.org\n \"Entity escaping\", atlas#101): `&` `'` `\"` `>` `<` as `&` `'` `"` `>` `<`.\n Recursive, so proved text builders (utils `sitemap`) can call it inside an expression; its\n depth is the text's length (a URL, at most 2,048 characters by the protocol). */\n\n/**\n * The entity the sitemap protocol writes for code unit `c`, or \"\" when `c` is written as itself.\n *\n * @ensures exactly the model's XmlEntity\n */\nexport function xmlEntity(c: number): string {\n //@ verify\n //@ ensures \\result === (c === 38 ? \"&\" : c === 60 ? \"<\" : c === 62 ? \">\" : c === 34 ? \""\" : c === 39 ? \"'\" : \"\")\n if (c === 38) return \"&\";\n if (c === 60) return \"<\";\n if (c === 62) return \">\";\n if (c === 34) return \""\";\n if (c === 39) return \"'\";\n return \"\";\n}\n\n/**\n * `s` escaped for XML text or a quoted attribute: each of `&` `<` `>` `\"` `'` as its entity,\n * every other code unit kept.\n *\n * @ensures ∀ k < |result|. result[k] ∉ {\"<\", \">\", \"\\\"\", \"'\"} — nothing can end an element or a\n * quoted value; exactly the model's XmlEscape in the link (a recursive contract can't be\n * imported, models/LSC-GAPS.md)\n */\nexport function xmlEscaped(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n if (s.length === 0) return \"\";\n const entity = xmlEntity(s.charCodeAt(0));\n return (entity === \"\" ? s.slice(0, 1) : entity) + xmlEscaped(s.slice(1));\n}\n","//@ backend dafny\nimport { lineFeed } from \"./strings\";\nimport { xmlEscaped } from \"./xml\";\n\n/* The sitemap protocol's XML (sitemaps.org; atlas#101), built once for every site, verified with\n LemmaScript → Dafny (model: models/Sitemap.dfy; link: models/links/utils-sitemap.dfy). A\n caller writes a head, its blocks and the tail: a `<urlset>` of `urlBlock`s, or a\n `<sitemapindex>` of `sitemapBlock`s. Each element sits on its own line, indented two spaces per\n level (owner 2026-11-10: \"properly formatted\"), and each value is escaped with `xmlEscaped`.\n\n The contracts here are true but not exact: an exact one names `xmlEscaped` or `lineFeed`, which\n an importer that doesn't call them itself can't resolve (models/LSC-GAPS.md). The link proves\n each function is the model's, and importers' links take that as a premise. */\n\n/**\n * A `<urlset>` file's opening: the XML declaration, then the root element.\n *\n * @ensures starts with the XML declaration — exactly the model's UrlsetHead in the link\n */\nexport function urlsetHead(): string {\n //@ verify\n //@ ensures \\result.length > 38 && \\result.slice(0, 38) === '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n return (\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' +\n lineFeed() +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">' +\n lineFeed()\n );\n}\n\n/**\n * A `<urlset>` file's closing tag and final line feed.\n *\n * @ensures |result| = 10 ∧ starts with \"</urlset>\" — exactly the model's UrlsetTail in the link\n */\nexport function urlsetTail(): string {\n //@ verify\n //@ ensures \\result.length === 10 && \\result.slice(0, 9) === \"</urlset>\"\n return \"</urlset>\" + lineFeed();\n}\n\n/**\n * A `<sitemapindex>` file's opening: the XML declaration, then the root element.\n *\n * @ensures starts with the XML declaration — exactly the model's IndexHead in the link\n */\nexport function sitemapIndexHead(): string {\n //@ verify\n //@ ensures \\result.length > 38 && \\result.slice(0, 38) === '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n return (\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' +\n lineFeed() +\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">' +\n lineFeed()\n );\n}\n\n/**\n * A `<sitemapindex>` file's closing tag and final line feed.\n *\n * @ensures |result| = 16 ∧ starts with \"</sitemapindex>\" — exactly the model's IndexTail in the link\n */\nexport function sitemapIndexTail(): string {\n //@ verify\n //@ ensures \\result.length === 16 && \\result.slice(0, 15) === \"</sitemapindex>\"\n return \"</sitemapindex>\" + lineFeed();\n}\n\n/**\n * One page of a `<urlset>`: its `<loc>`, and its `<lastmod>` only when known (\"\" leaves it out),\n * each escaped and on its own line.\n *\n * @ensures starts with \" <url>\" — exactly the model's UrlBlock in the link\n */\nexport function urlBlock(loc: string, lastmod: string): string {\n //@ verify\n //@ ensures \\result.length > 7 && \\result.slice(0, 7) === \" <url>\"\n const date =\n lastmod === \"\" ? \"\" : \" <lastmod>\" + xmlEscaped(lastmod) + \"</lastmod>\" + lineFeed();\n return (\n \" <url>\" +\n lineFeed() +\n \" <loc>\" +\n xmlEscaped(loc) +\n \"</loc>\" +\n lineFeed() +\n date +\n \" </url>\" +\n lineFeed()\n );\n}\n\n/**\n * One child sitemap of a `<sitemapindex>`: its `<loc>`, escaped, on its own line.\n *\n * @ensures starts with \" <sitemap>\" — exactly the model's SitemapBlock in the link\n */\nexport function sitemapBlock(loc: string): string {\n //@ verify\n //@ ensures \\result.length > 11 && \\result.slice(0, 11) === \" <sitemap>\"\n return (\n \" <sitemap>\" +\n lineFeed() +\n \" <loc>\" +\n xmlEscaped(loc) +\n \"</loc>\" +\n lineFeed() +\n \" </sitemap>\" +\n lineFeed()\n );\n}\n","//@ backend dafny\nimport { decimal } from \"@atlas/foundation/decimal\";\nimport { substitutedText } from \"@atlas/utils/replace\";\nimport {\n sitemapBlock,\n sitemapIndexHead,\n sitemapIndexTail,\n urlBlock,\n urlsetHead,\n urlsetTail,\n} from \"@atlas/utils/sitemap\";\nimport {\n canonicalNatValue,\n endsWith,\n isCanonicalNat,\n rStripCode,\n startsWithAt,\n} from \"@atlas/utils/strings\";\n\n/* The item sitemaps' decisions (atlas#101), verified with LemmaScript → Dafny and linked to\n models/AugurServerSitemap.dfy (models/links/augur-server-sitemap-rules.dfy). `sitemap.ts` only\n awaits the SDK and maps these answers to a Response.\n\n Layout (owner 2026-11-10): the item index at `{base}sitemap.xml` and page n at\n `{base}sitemap-{n}.xml`, all in the items' own folder `base` (default \"/items/\"), so by the\n sitemap protocol's location rule they may list the item pages there. */\n\n/** One item for a `<urlset>`: its page URL and, when known, its last change (\"\" leaves it out). */\nexport interface SitemapRow {\n loc: string;\n lastmod: string;\n}\n\n/** What a sitemap request comes to: served, not a sitemap (404), or Augur failed (503). */\nexport type SitemapOutcome = \"ok\" | \"not-found\" | \"unavailable\";\n\n// ---------------------------------------------------------------- pages\n\n/**\n * The SDK's `total` as a count: itself when a whole number ≥ 0, else 0 (no item sitemaps rather\n * than a guess).\n *\n * @ensures exactly the model's UsableTotal\n */\nexport function usableTotal(isWhole: boolean, n: number): number {\n //@ verify\n //@ ensures \\result === (isWhole && n >= 0 ? n : 0)\n return isWhole && n >= 0 ? n : 0;\n}\n\n/**\n * How many 5,000-item sitemaps cover `total` items (the endpoint fixes a page at 5,000).\n *\n * @requires total ≥ 0\n * @ensures result = ⌈total / 5000⌉ — exactly the model's ItemSitemapCount\n */\nexport function itemSitemapCount(total: number): number {\n //@ verify\n //@ type total nat\n //@ requires total >= 0\n //@ ensures \\result === Math.floor((total + 4999) / 5000)\n return Math.floor((total + 4999) / 5000);\n}\n\n/**\n * The page a request names (the rewrite's bare `:page`): its value when it is a canonical\n * natural number, else 0, \"not a page\" (`0`, `01`, `1e3`, ` 1`, `-1` and text never name one).\n *\n * @ensures result = canonicalNatValue(page) for canonical text, else 0 — exactly the model's\n * ItemSitemapPage (the test is spelled out: canonicalNatValue's contract names\n * isCanonicalNat, which this file must call to resolve, models/LSC-GAPS.md)\n */\nexport function parseItemSitemapPage(page: string): number {\n //@ verify\n //@ ensures \\result === (isCanonicalNat(page) ? canonicalNatValue(page) : 0)\n return isCanonicalNat(page) ? canonicalNatValue(page) : 0;\n}\n\n// ---------------------------------------------------------------- outcomes\n\n/**\n * An item page's outcome: not a page, or an empty page past the first, is \"not-found\"; a failed\n * fetch is \"unavailable\"; anything else is served. `rows` counts what the endpoint returned,\n * before the scope filter.\n *\n * @ensures exactly the model's ItemOutcome\n */\nexport function itemSitemapOutcome(page: number, fetched: boolean, rows: number): SitemapOutcome {\n //@ verify\n //@ ensures page === 0 ==> \\result === \"not-found\"\n //@ ensures page !== 0 && !fetched ==> \\result === \"unavailable\"\n //@ ensures page !== 0 && fetched && rows === 0 && page > 1 ==> \\result === \"not-found\"\n //@ ensures page !== 0 && fetched && !(rows === 0 && page > 1) ==> \\result === \"ok\"\n if (page === 0) return \"not-found\";\n if (!fetched) return \"unavailable\";\n if (rows === 0 && page > 1) return \"not-found\";\n return \"ok\";\n}\n\n/**\n * The item index's outcome: served when the count was read, else \"unavailable\" (a 200 with no\n * sitemaps would tell a crawler the site has none).\n *\n * @ensures exactly the model's IndexOutcome\n */\nexport function sitemapIndexOutcome(fetched: boolean): SitemapOutcome {\n //@ verify\n //@ ensures \\result === (fetched ? \"ok\" : \"unavailable\")\n return fetched ? \"ok\" : \"unavailable\";\n}\n\n/**\n * The HTTP status of an outcome.\n *\n * @ensures exactly the model's StatusOf\n */\nexport function sitemapStatus(o: SitemapOutcome): number {\n //@ verify\n //@ ensures \\result === (o === \"ok\" ? 200 : o === \"not-found\" ? 404 : 503)\n if (o === \"ok\") return 200;\n return o === \"not-found\" ? 404 : 503;\n}\n\n/**\n * An outcome's `Cache-Control`: a served sitemap for a day at the CDN and an hour in browsers\n * (rebuilt at most daily); a 404 or a 503 never.\n *\n * @ensures exactly the model's CacheControlOf\n */\nexport function sitemapCacheControl(o: SitemapOutcome): string {\n //@ verify\n //@ ensures \\result === (o === \"ok\" ? \"public, max-age=3600, s-maxage=86400\" : \"no-store\")\n return o === \"ok\" ? \"public, max-age=3600, s-maxage=86400\" : \"no-store\";\n}\n\n/**\n * An outcome's `Retry-After` in seconds: an hour for a 503, else \"\" (no header).\n *\n * @ensures exactly the model's RetryAfterOf\n */\nexport function sitemapRetryAfter(o: SitemapOutcome): string {\n //@ verify\n //@ ensures \\result === (o === \"unavailable\" ? \"3600\" : \"\")\n return o === \"unavailable\" ? \"3600\" : \"\";\n}\n\n/**\n * Whether a request's page is worth asking Augur for: only a page (≥ 1); \"not a page\" is\n * answered without a call.\n *\n * @ensures exactly the model's FetchesPage\n */\nexport function fetchesPage(page: number): boolean {\n //@ verify\n //@ ensures \\result === (page >= 1)\n return page >= 1;\n}\n\n/**\n * A response's body: the XML when served, else a short plain-text reason.\n *\n * @ensures exactly the model's BodyOf\n */\nexport function sitemapBody(o: SitemapOutcome, xml: string): string {\n //@ verify\n //@ ensures \\result === (o === \"ok\" ? xml : o === \"not-found\" ? \"Not Found\" : \"Sitemap temporarily unavailable\")\n if (o === \"ok\") return xml;\n return o === \"not-found\" ? \"Not Found\" : \"Sitemap temporarily unavailable\";\n}\n\n/** One response header. */\nexport interface SitemapHeader {\n name: string;\n value: string;\n}\n\n/**\n * A response's headers: its type, its cache rule, and `Retry-After` on a 503 only.\n *\n * @ensures exactly the model's HeadersOf\n */\nexport function sitemapHeaders(o: SitemapOutcome): SitemapHeader[] {\n //@ verify\n //@ ensures \\result.length === (o === \"unavailable\" ? 3 : 2)\n const type: SitemapHeader = {\n name: \"Content-Type\",\n value: o === \"ok\" ? \"application/xml; charset=utf-8\" : \"text/plain; charset=utf-8\",\n };\n const cache: SitemapHeader = { name: \"Cache-Control\", value: sitemapCacheControl(o) };\n const retry: SitemapHeader = { name: \"Retry-After\", value: sitemapRetryAfter(o) };\n return o === \"unavailable\" ? [type, cache, retry] : [type, cache];\n}\n\n// ---------------------------------------------------------------- URLs\n\n/**\n * The items' folder as a path, with one leading and one trailing \"/\" (\"items\" → \"/items/\").\n *\n * @ensures exactly the model's SitemapBase\n */\nexport function sitemapBase(base: string): string {\n //@ verify\n //@ ensures \\result.length >= 1 && \\result.charCodeAt(0) === 47 && \\result.charCodeAt(\\result.length - 1) === 47\n const lead = base.length > 0 && base.charCodeAt(0) === 47 ? base : \"/\" + base;\n return lead.charCodeAt(lead.length - 1) === 47 ? lead : lead + \"/\";\n}\n\n/**\n * The folder every item sitemap, and every item it lists, sits in: the site's origin with no\n * trailing \"/\", then the base.\n *\n * @ensures result = rStripCode(siteUrl, \"/\") + sitemapBase(base) — exactly the model's ItemsPrefix\n */\nexport function itemsPrefix(siteUrl: string, base: string): string {\n //@ verify\n //@ ensures \\result === rStripCode(siteUrl, 47) + sitemapBase(base)\n return rStripCode(siteUrl, 47) + sitemapBase(base);\n}\n\n/**\n * Item sitemap n's URL: `{siteUrl}{base}sitemap-{n}.xml`.\n *\n * @ensures exactly the model's ItemSitemapUrl\n */\nexport function itemSitemapUrl(siteUrl: string, base: string, n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === itemsPrefix(siteUrl, base) + \"sitemap-\" + decimal(n) + \".xml\"\n return itemsPrefix(siteUrl, base) + \"sitemap-\" + decimal(n) + \".xml\";\n}\n\n/**\n * Whether a link is under the items' folder (the location rule); an empty link never is.\n *\n * @ensures exactly the model's InScope\n */\nexport function inScope(prefix: string, loc: string): boolean {\n //@ verify\n //@ ensures \\result <==> (prefix.length <= loc.length && loc.slice(0, prefix.length) === prefix)\n return startsWithAt(loc, prefix, 0);\n}\n\n// ---------------------------------------------------------------- the two files\n\n/**\n * The index's `<sitemap>` blocks for pages lo+1 … hi, built by halves (depth log n).\n *\n * @ensures nothing for an empty range — exactly the model's blocks of ItemSitemapUrlsFrom in the link\n */\nfunction indexBlocksRange(siteUrl: string, base: string, lo: number, hi: number): string {\n //@ verify\n //@ type lo nat\n //@ type hi nat\n //@ requires 0 <= lo && lo <= hi\n //@ decreases hi - lo\n //@ ensures lo === hi ==> \\result === \"\"\n if (hi - lo === 0) return \"\";\n if (hi - lo === 1) return sitemapBlock(itemSitemapUrl(siteUrl, base, lo + 1));\n const mid = lo + Math.floor((hi - lo) / 2);\n return indexBlocksRange(siteUrl, base, lo, mid) + indexBlocksRange(siteUrl, base, mid, hi);\n}\n\n/**\n * The item index: a `<sitemapindex>` of `{base}sitemap-1.xml` … `{base}sitemap-{count}.xml`.\n *\n * @ensures exactly the model's ItemIndex\n */\nexport function buildSitemapIndexXml(siteUrl: string, base: string, count: number): string {\n //@ verify\n //@ type count nat\n //@ requires count >= 0\n //@ ensures \\result === sitemapIndexHead() + indexBlocksRange(siteUrl, base, 0, count) + sitemapIndexTail()\n return sitemapIndexHead() + indexBlocksRange(siteUrl, base, 0, count) + sitemapIndexTail();\n}\n\n/**\n * The `<url>` blocks for rows[lo..hi) under `prefix`, others left out, built by halves.\n *\n * @ensures nothing for an empty range — exactly the model's blocks of ScopedEntries in the link\n */\nfunction urlBlocksRange(rows: SitemapRow[], prefix: string, lo: number, hi: number): string {\n //@ verify\n //@ type lo nat\n //@ type hi nat\n //@ requires 0 <= lo && lo <= hi && hi <= rows.length\n //@ decreases hi - lo\n //@ ensures lo === hi ==> \\result === \"\"\n if (hi - lo === 0) return \"\";\n if (hi - lo === 1) {\n const row = rows[lo] as SitemapRow;\n return inScope(prefix, row.loc) ? urlBlock(row.loc, row.lastmod) : \"\";\n }\n const mid = lo + Math.floor((hi - lo) / 2);\n return urlBlocksRange(rows, prefix, lo, mid) + urlBlocksRange(rows, prefix, mid, hi);\n}\n\n/**\n * An item page: a `<urlset>` of the rows under the items' folder, in order.\n *\n * @ensures exactly the model's ItemUrlset\n */\nexport function buildUrlsetXml(rows: SitemapRow[], siteUrl: string, base: string): string {\n //@ verify\n //@ ensures \\result === urlsetHead() + urlBlocksRange(rows, itemsPrefix(siteUrl, base), 0, rows.length) + urlsetTail()\n return (\n urlsetHead() + urlBlocksRange(rows, itemsPrefix(siteUrl, base), 0, rows.length) + urlsetTail()\n );\n}\n\n// ---------------------------------------------------------------- Next.js and robots.txt\n\n/**\n * The Next.js rewrite `source` for the page files, `{base}sitemap-:page.xml`, with every\n * character Next reads as pattern syntax (`( ) { } [ ] | \\ ^ . : * + - ? $`) escaped by a \"\\\".\n *\n * @ensures exactly the model's RewriteSource\n */\nexport function rewriteSource(base: string): string {\n //@ verify\n //@ ensures \\result === substitutedText(sitemapBase(base), [40, 41, 123, 125, 91, 93, 124, 92, 94, 46, 58, 42, 43, 45, 63, 36], [\"\\\\(\", \"\\\\)\", \"\\\\{\", \"\\\\}\", \"\\\\[\", \"\\\\]\", \"\\\\|\", \"\\\\\\\\\", \"\\\\^\", \"\\\\.\", \"\\\\:\", \"\\\\*\", \"\\\\+\", \"\\\\-\", \"\\\\?\", \"\\\\$\"]) + \"sitemap\\\\-:page\\\\.xml\"\n return (\n substitutedText(\n sitemapBase(base),\n [40, 41, 123, 125, 91, 93, 124, 92, 94, 46, 58, 42, 43, 45, 63, 36],\n [\n \"\\\\(\",\n \"\\\\)\",\n \"\\\\{\",\n \"\\\\}\",\n \"\\\\[\",\n \"\\\\]\",\n \"\\\\|\",\n \"\\\\\\\\\",\n \"\\\\^\",\n \"\\\\.\",\n \"\\\\:\",\n \"\\\\*\",\n \"\\\\+\",\n \"\\\\-\",\n \"\\\\?\",\n \"\\\\$\",\n ],\n ) + \"sitemap\\\\-:page\\\\.xml\"\n );\n}\n\n/**\n * The rewrite's destination, the page handler's route `{base}sitemap.xml/:page`\n * (`app/<base>/sitemap.xml/[page]/route.ts`).\n *\n * @ensures exactly the model's RewriteDestination\n */\nexport function rewriteDestination(base: string): string {\n //@ verify\n //@ ensures \\result === sitemapBase(base) + \"sitemap.xml/:page\"\n return sitemapBase(base) + \"sitemap.xml/:page\";\n}\n\n/**\n * Whether a path is one of the item sitemaps (the index or a page file), which a site's proxy\n * MUST pass through before any item-URL redirect (the proxy runs before rewrites).\n *\n * @ensures exactly the model's IsSitemapPath\n */\nexport function isSitemapPath(pathname: string, base: string): boolean {\n //@ verify\n //@ ensures \\result === (startsWithAt(pathname, sitemapBase(base) + \"sitemap\", 0) && endsWith(pathname, \".xml\"))\n return startsWithAt(pathname, sitemapBase(base) + \"sitemap\", 0) && endsWith(pathname, \".xml\");\n}\n\n/**\n * robots.txt's sitemaps: the site's own root `/sitemap.xml` and the item index. Two lines, since\n * the specs name no index inside an index.\n *\n * @ensures exactly the model's RobotsSitemaps\n */\nexport function robotsSitemaps(siteUrl: string, base: string): string[] {\n //@ verify\n //@ ensures \\result.length === 2\n //@ ensures \\result[0] === rStripCode(siteUrl, 47) + \"/sitemap.xml\"\n //@ ensures \\result[1] === itemsPrefix(siteUrl, base) + \"sitemap.xml\"\n return [rStripCode(siteUrl, 47) + \"/sitemap.xml\", itemsPrefix(siteUrl, base) + \"sitemap.xml\"];\n}\n","/**\n * Item sitemaps for a Next.js site, built at request time from the Augur SDK's\n * `googMc.sitemaps.items.list` (atlas#101), so the number of files follows the catalog without a\n * deploy, whatever its size.\n *\n * Layout: the item index at `{base}sitemap.xml` and page n (5,000 items) at\n * `{base}sitemap-{n}.xml`, in the items' own folder (`base`, default \"/items/\"), so by the\n * sitemap protocol's location rule they may list the item pages there. The site's root\n * `/sitemap.xml` stays its own; robots.txt names both (`robotsSitemaps`).\n *\n * Every decision is a proved rule in `sitemap-rules.ts`; this file only awaits the SDK and maps\n * the rules' answers to a Response.\n */\n\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport {\n buildSitemapIndexXml,\n buildUrlsetXml,\n fetchesPage,\n itemSitemapCount,\n itemSitemapOutcome,\n parseItemSitemapPage,\n rewriteDestination,\n rewriteSource,\n sitemapBody,\n sitemapHeaders,\n sitemapIndexOutcome,\n sitemapStatus,\n usableTotal,\n type SitemapOutcome,\n type SitemapRow,\n} from \"./sitemap-rules\";\n\nexport {\n buildSitemapIndexXml,\n buildUrlsetXml,\n inScope,\n isSitemapPath,\n itemSitemapCount,\n itemSitemapUrl,\n parseItemSitemapPage,\n robotsSitemaps,\n sitemapBase,\n type SitemapOutcome,\n type SitemapRow,\n} from \"./sitemap-rules\";\n\n/** The items' folder when a site names none. */\nexport const DEFAULT_SITEMAP_BASE = \"/items/\";\n\n/**\n * How long one Augur call may take, in milliseconds: crawlers wait longer than page visitors, and\n * a call past it is a 503 the crawler retries.\n */\nexport const DEFAULT_SITEMAP_DEADLINE = 10_000;\n\n/** What the handlers need of a server site: its SDK client (`createServerSite`'s result fits). */\nexport interface SitemapSite {\n client: Pick<AugurAPI, \"withRequest\" | \"googMc\">;\n}\n\n/** Where the site lives and where its item sitemaps sit. */\nexport interface SitemapOptions {\n /** The site's origin, e.g. \"https://www.example.com\" (a trailing \"/\" is dropped). */\n siteUrl: string;\n /** The items' folder, matching the item links Augur returns; default \"/items/\". */\n base?: string;\n /** Milliseconds one Augur call may take; default 10,000. */\n deadline?: number;\n}\n\n/** A Next.js rewrite, as `next.config` `rewrites()` takes it. */\nexport interface SitemapRewrite {\n source: string;\n destination: string;\n}\n\n/** The Augur edge cache the reads ask for, in hours: a day's sitemap stays close to the catalog. */\nconst EDGE_CACHE_HOURS = 1;\n\nfunction respond(outcome: SitemapOutcome, xml: string): Response {\n const headers = new Headers(\n sitemapHeaders(outcome).map((h): [string, string] => [h.name, h.value]),\n );\n return new Response(sitemapBody(outcome, xml), { status: sitemapStatus(outcome), headers });\n}\n\n/** The catalog's total from a one-row read, or undefined when Augur failed. */\nasync function readTotal(site: SitemapSite, deadline: number): Promise<number | undefined> {\n try {\n const response = await site.client\n .withRequest({ deadline })\n .googMc.sitemaps.items.list({ limit: 1, edgeCache: EDGE_CACHE_HOURS });\n return usableTotal(Number.isInteger(response.total), response.total);\n } catch {\n return undefined;\n }\n}\n\n/** One page's rows, as the rules take them, or undefined when Augur failed. */\nasync function readPage(\n site: SitemapSite,\n page: number,\n deadline: number,\n): Promise<SitemapRow[] | undefined> {\n try {\n const response = await site.client\n .withRequest({ deadline })\n .googMc.sitemaps.items.list({ page, edgeCache: EDGE_CACHE_HOURS });\n return (response.data ?? []).map((row) => ({\n loc: row.link ?? \"\",\n lastmod: row.lastModified ?? \"\",\n }));\n } catch {\n return undefined;\n }\n}\n\n/**\n * The item index's Route Handler, for `app/items/sitemap.xml/route.ts` (or the folder `base`\n * names): a `<sitemapindex>` of every item page file, or a 503 when Augur can't be read.\n *\n * @example\n * ```ts\n * export const dynamic = \"force-dynamic\";\n * export const GET = createSitemapIndexHandler(site, { siteUrl: \"https://www.example.com\" });\n * ```\n */\nexport function createSitemapIndexHandler(site: SitemapSite, options: SitemapOptions) {\n const { siteUrl, base = DEFAULT_SITEMAP_BASE, deadline = DEFAULT_SITEMAP_DEADLINE } = options;\n return async (): Promise<Response> => {\n const total = await readTotal(site, deadline);\n const count = itemSitemapCount(total ?? 0);\n return respond(\n sitemapIndexOutcome(total !== undefined),\n buildSitemapIndexXml(siteUrl, base, count),\n );\n };\n}\n\n/**\n * An item page's Route Handler, for `app/items/sitemap.xml/[page]/route.ts`, which\n * `sitemapRewrite` maps `{base}sitemap-{n}.xml` onto: a `<urlset>` of page n's items under\n * `base`, a 404 for no such page, or a 503 when Augur can't be read.\n *\n * @example\n * ```ts\n * export const dynamic = \"force-dynamic\";\n * export const GET = createItemSitemapHandler(site, { siteUrl: \"https://www.example.com\" });\n * ```\n */\nexport function createItemSitemapHandler(site: SitemapSite, options: SitemapOptions) {\n const { siteUrl, base = DEFAULT_SITEMAP_BASE, deadline = DEFAULT_SITEMAP_DEADLINE } = options;\n return async (\n _request: Request,\n context: { params: Promise<{ page: string }> },\n ): Promise<Response> => {\n const page = parseItemSitemapPage((await context.params).page);\n const rows = fetchesPage(page) ? await readPage(site, page, deadline) : [];\n const outcome = itemSitemapOutcome(page, rows !== undefined, rows?.length ?? 0);\n return respond(outcome, buildUrlsetXml(rows ?? [], siteUrl, base));\n };\n}\n\n/**\n * The Next.js rewrite from `{base}sitemap-{n}.xml` to the item page handler's route; spread it\n * into `next.config`'s `rewrites()`.\n *\n * @example\n * ```ts\n * async rewrites() {\n * return [sitemapRewrite()];\n * }\n * ```\n */\nexport function sitemapRewrite(base: string = DEFAULT_SITEMAP_BASE): SitemapRewrite {\n return { source: rewriteSource(base), destination: rewriteDestination(base) };\n}\n"],"mappings":";;;;;;;;;;;;;AAmBO,SAAS,UAAU,OAAiB,GAAW,GAAmB;AAOvE,MAAI,MAAM,MAAM,OAAQ,QAAO;AAC/B,SAAQ,MAAM,CAAC,MAAiB,IAAI,IAAI,UAAU,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AQ,CAAC,GAAG,SAAS,IAAI,CAAC;AAAA,EACnE;AACF;AAaO,SAAS,eAAe,OAAe,sBAAsC;AAClF,SAAO,EAAE,QAAQ,cAAc,IAAI,GAAG,aAAa,mBAAmB,IAAI,EAAE;AAC9E;","names":[]}
|
package/dist/testing.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
clearSiteActions
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-SFXO74RC.js";
|
|
4
|
+
import "./chunk-JIYVQWXK.js";
|
|
5
|
+
import "./chunk-Z53NEFEQ.js";
|
|
6
|
+
import "./chunk-V76GZZF3.js";
|
|
5
7
|
|
|
6
8
|
// src/testing.ts
|
|
7
9
|
import { createMockClient } from "@simpleapps-com/augur-core/testing";
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["export { createMockClient } from \"@simpleapps-com/augur-core/testing\";\nexport { clearSiteActions } from \"./server-site-registry\";\nexport type { DeepMockClient, MockClientResult } from \"@simpleapps-com/augur-core/testing\";\n\nimport type { SiteActions } from \"./actions/site\";\n\n/**\n * A mock function type compatible with both Vitest and Jest.\n * Supports `.mockResolvedValue()`, `.mockRejectedValue()`, and call tracking.\n */\nexport interface MockFn {\n (...args: unknown[]): unknown;\n mockResolvedValue: (value: unknown) => MockFn;\n mockRejectedValue: (value: unknown) => MockFn;\n mockReturnValue: (value: unknown) => MockFn;\n mockImplementation: (fn: (...args: unknown[]) => unknown) => MockFn;\n mock: { calls: unknown[][] };\n}\n\n/** Mirror of SiteActions where every method is a MockFn. */\nexport type MockSiteActions = {\n [K in keyof SiteActions]: {\n [M in keyof SiteActions[K]]: MockFn;\n };\n};\n\n/** Return type of createMockSiteActions. */\nexport interface MockSiteActionsResult {\n /** Typed as SiteActions — pass this to your components/server actions. */\n actions: SiteActions;\n /** Same object typed with MockFn — use for assertions and mock setup. */\n mocks: MockSiteActions;\n}\n\n/** Shape definition: service name → method names. */\nconst SERVICE_METHODS: Record<string, string[]> = {\n pricing: [\"getItemPrice\", \"batchGetItemPrices\", \"getTaxEstimate\"],\n items: [\n \"itemCategoryLookup\",\n \"getItemCategory\",\n \"getCategoryItems\",\n \"getCategoryItemsInfinite\",\n \"getItemAttributes\",\n \"getInvMast\",\n \"getInvMastDoc\",\n \"getStock\",\n \"getStockCompanySummary\",\n \"getItemFaqs\",\n \"getItemSubstitutes\",\n \"getItemAccessories\",\n \"getSimilarItems\",\n \"batchGetInvMastDocs\",\n \"batchGetStockData\",\n ],\n commerce: [\n \"cartHdrLookup\",\n \"getCartLines\",\n \"addToCart\",\n \"updateCartLines\",\n \"deleteCartItems\",\n \"getCartAlsoBought\",\n \"checkoutOrder\",\n ],\n search: [\"getSearchAttributes\", \"getSearchSuggestions\", \"itemSearch\", \"itemSearchInfinite\"],\n orders: [\"getOrderDoc\"],\n shipping: [\"getShippingRates\"],\n joomla: [\n \"getJoomlaContent\",\n \"getJoomlaContentList\",\n \"getJoomlaMenu\",\n \"getJoomlaMenuDoc\",\n \"getUserProfile\",\n \"verifyPassword\",\n ],\n legacy: [\"getItemWebDesc\", \"getAlsoBoughtItems\", \"getItemTags\", \"getStates\"],\n customers: [\n \"customerLookup\",\n \"getCustomerDoc\",\n \"getCustomerOrders\",\n \"getCustomerOrderDetail\",\n \"getCustomerInvoices\",\n \"getCustomerInvoiceDetail\",\n \"getCustomerQuotes\",\n \"getCustomerQuoteDetail\",\n \"getShipToAddresses\",\n ],\n smartyStreets: [\"validateAddress\"],\n p21Pim: [\"getInvMastExt\", \"listInvMastExt\"],\n agrSite: [\"getSettings\", \"getRobots\"],\n avalara: [\"calculateTax\"],\n payments: [\n \"transactionSetup\",\n \"accountQuery\",\n \"getSurcharge\",\n \"cardInfo\",\n \"billingUpdate\",\n \"validatePayment\",\n ],\n logistics: [\"getFreightRates\", \"getShipVia\"],\n vmi: [\n \"getWarehouses\",\n \"getWarehouseAvailability\",\n \"getDistributors\",\n \"getProducts\",\n \"getInventoryProfiles\",\n \"getRestockHeaders\",\n \"getSections\",\n ],\n p21Core: [\n \"getAddresses\",\n \"getCompanies\",\n \"getCompany\",\n \"getLocations\",\n \"getPaymentTypes\",\n \"getCashDrawers\",\n \"getCodeP21\",\n ],\n p21Apis: [\"refreshContacts\", \"refreshCustomers\"],\n p21Sism: [\"getRecentImports\", \"getImport\", \"getScheduledImports\"],\n agrWork: [\"healthCheck\", \"ping\"],\n agrInfo: [\"getContext\", \"getRubrics\", \"getMicroservices\", \"generateAkasha\", \"generateJoomla\"],\n basecamp2: [\n \"getTodos\",\n \"getTodo\",\n \"getTodosSummary\",\n \"getComments\",\n \"getPeople\",\n \"getProjects\",\n \"getEvents\",\n \"getMetrics\",\n \"getTodolists\",\n ],\n brandFolder: [\"getCategories\", \"getCategory\", \"createFocus\"],\n gregorovich: [\"getDocuments\"],\n favorites: [\"getFavorites\", \"addFavorite\", \"removeFavorite\"],\n wishlists: [\n \"getWishlists\",\n \"createWishlist\",\n \"getWishlistDetail\",\n \"deleteWishlist\",\n \"addWishlistItems\",\n \"removeWishlistItem\",\n ],\n};\n\nfunction createStubFn(): MockFn {\n const calls: unknown[][] = [];\n\n const fn = ((...args: unknown[]) => {\n calls.push(args);\n const impl = (fn as MockFnInternal)._impl;\n return impl ? impl(...args) : undefined;\n }) as MockFn & MockFnInternal;\n\n fn._impl = undefined;\n fn.mock = { calls };\n\n fn.mockResolvedValue = (value: unknown) => {\n fn._impl = () => Promise.resolve(value);\n return fn;\n };\n\n fn.mockRejectedValue = (value: unknown) => {\n fn._impl = () => Promise.reject(value);\n return fn;\n };\n\n fn.mockReturnValue = (value: unknown) => {\n fn._impl = () => value;\n return fn;\n };\n\n fn.mockImplementation = (impl: (...args: unknown[]) => unknown) => {\n fn._impl = impl;\n return fn;\n };\n\n return fn;\n}\n\ninterface MockFnInternal {\n _impl: ((...args: unknown[]) => unknown) | undefined;\n}\n\n/**\n * Creates a fully-mocked SiteActions object for testing.\n *\n * Every method on every service is a stub function with call tracking\n * and `.mockResolvedValue()` / `.mockReturnValue()` support.\n * Works with both Vitest and Jest — no framework dependency.\n *\n * @example\n * ```ts\n * import { createMockSiteActions } from \"@simpleapps-com/augur-server/testing\";\n *\n * const { actions, mocks } = createMockSiteActions();\n *\n * // Setup return values\n * mocks.pricing.getItemPrice.mockResolvedValue({ price: 9.99 });\n *\n * // Pass actions to your component/server action\n * const price = await actions.pricing.getItemPrice(\"ITEM-1\");\n *\n * // Assert calls\n * expect(mocks.pricing.getItemPrice.mock.calls[0]).toEqual([\"ITEM-1\"]);\n * ```\n */\nexport function createMockSiteActions(): MockSiteActionsResult {\n const result: Record<string, Record<string, MockFn>> = {};\n\n for (const [service, methods] of Object.entries(SERVICE_METHODS)) {\n const serviceMock: Record<string, MockFn> = {};\n for (const method of methods) {\n serviceMock[method] = createStubFn();\n }\n result[service] = serviceMock;\n }\n\n return {\n actions: result as unknown as SiteActions,\n mocks: result as unknown as MockSiteActions,\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["export { createMockClient } from \"@simpleapps-com/augur-core/testing\";\nexport { clearSiteActions } from \"./server-site-registry\";\nexport type { DeepMockClient, MockClientResult } from \"@simpleapps-com/augur-core/testing\";\n\nimport type { SiteActions } from \"./actions/site\";\n\n/**\n * A mock function type compatible with both Vitest and Jest.\n * Supports `.mockResolvedValue()`, `.mockRejectedValue()`, and call tracking.\n */\nexport interface MockFn {\n (...args: unknown[]): unknown;\n mockResolvedValue: (value: unknown) => MockFn;\n mockRejectedValue: (value: unknown) => MockFn;\n mockReturnValue: (value: unknown) => MockFn;\n mockImplementation: (fn: (...args: unknown[]) => unknown) => MockFn;\n mock: { calls: unknown[][] };\n}\n\n/** Mirror of SiteActions where every method is a MockFn. */\nexport type MockSiteActions = {\n [K in keyof SiteActions]: {\n [M in keyof SiteActions[K]]: MockFn;\n };\n};\n\n/** Return type of createMockSiteActions. */\nexport interface MockSiteActionsResult {\n /** Typed as SiteActions — pass this to your components/server actions. */\n actions: SiteActions;\n /** Same object typed with MockFn — use for assertions and mock setup. */\n mocks: MockSiteActions;\n}\n\n/** Shape definition: service name → method names. */\nconst SERVICE_METHODS: Record<string, string[]> = {\n pricing: [\"getItemPrice\", \"batchGetItemPrices\", \"getTaxEstimate\"],\n items: [\n \"itemCategoryLookup\",\n \"getItemCategory\",\n \"getCategoryItems\",\n \"getCategoryItemsInfinite\",\n \"getItemAttributes\",\n \"getInvMast\",\n \"getInvMastDoc\",\n \"getStock\",\n \"getStockCompanySummary\",\n \"getItemFaqs\",\n \"getItemSubstitutes\",\n \"getItemAccessories\",\n \"getSimilarItems\",\n \"batchGetInvMastDocs\",\n \"batchGetStockData\",\n ],\n commerce: [\n \"cartHdrLookup\",\n \"getCartLines\",\n \"addToCart\",\n \"updateCartLines\",\n \"deleteCartItems\",\n \"getCartAlsoBought\",\n \"checkoutOrder\",\n ],\n search: [\"getSearchAttributes\", \"getSearchSuggestions\", \"itemSearch\", \"itemSearchInfinite\"],\n orders: [\"getOrderDoc\"],\n shipping: [\"getShippingRates\"],\n joomla: [\n \"getJoomlaContent\",\n \"getJoomlaContentList\",\n \"getJoomlaMenu\",\n \"getJoomlaMenuDoc\",\n \"getUserProfile\",\n \"verifyPassword\",\n ],\n legacy: [\"getItemWebDesc\", \"getAlsoBoughtItems\", \"getItemTags\", \"getStates\"],\n customers: [\n \"customerLookup\",\n \"getCustomerDoc\",\n \"getCustomerOrders\",\n \"getCustomerOrderDetail\",\n \"getCustomerInvoices\",\n \"getCustomerInvoiceDetail\",\n \"getCustomerQuotes\",\n \"getCustomerQuoteDetail\",\n \"getShipToAddresses\",\n ],\n smartyStreets: [\"validateAddress\"],\n p21Pim: [\"getInvMastExt\", \"listInvMastExt\"],\n agrSite: [\"getSettings\", \"getRobots\"],\n avalara: [\"calculateTax\"],\n payments: [\n \"transactionSetup\",\n \"accountQuery\",\n \"getSurcharge\",\n \"cardInfo\",\n \"billingUpdate\",\n \"validatePayment\",\n ],\n logistics: [\"getFreightRates\", \"getShipVia\"],\n vmi: [\n \"getWarehouses\",\n \"getWarehouseAvailability\",\n \"getDistributors\",\n \"getProducts\",\n \"getInventoryProfiles\",\n \"getRestockHeaders\",\n \"getSections\",\n ],\n p21Core: [\n \"getAddresses\",\n \"getCompanies\",\n \"getCompany\",\n \"getLocations\",\n \"getPaymentTypes\",\n \"getCashDrawers\",\n \"getCodeP21\",\n ],\n p21Apis: [\"refreshContacts\", \"refreshCustomers\"],\n p21Sism: [\"getRecentImports\", \"getImport\", \"getScheduledImports\"],\n agrWork: [\"healthCheck\", \"ping\"],\n agrInfo: [\"getContext\", \"getRubrics\", \"getMicroservices\", \"generateAkasha\", \"generateJoomla\"],\n basecamp2: [\n \"getTodos\",\n \"getTodo\",\n \"getTodosSummary\",\n \"getComments\",\n \"getPeople\",\n \"getProjects\",\n \"getEvents\",\n \"getMetrics\",\n \"getTodolists\",\n ],\n brandFolder: [\"getCategories\", \"getCategory\", \"createFocus\"],\n gregorovich: [\"getDocuments\"],\n favorites: [\"getFavorites\", \"addFavorite\", \"removeFavorite\"],\n wishlists: [\n \"getWishlists\",\n \"createWishlist\",\n \"getWishlistDetail\",\n \"deleteWishlist\",\n \"addWishlistItems\",\n \"removeWishlistItem\",\n ],\n};\n\nfunction createStubFn(): MockFn {\n const calls: unknown[][] = [];\n\n const fn = ((...args: unknown[]) => {\n calls.push(args);\n const impl = (fn as MockFnInternal)._impl;\n return impl ? impl(...args) : undefined;\n }) as MockFn & MockFnInternal;\n\n fn._impl = undefined;\n fn.mock = { calls };\n\n fn.mockResolvedValue = (value: unknown) => {\n fn._impl = () => Promise.resolve(value);\n return fn;\n };\n\n fn.mockRejectedValue = (value: unknown) => {\n fn._impl = () => Promise.reject(value);\n return fn;\n };\n\n fn.mockReturnValue = (value: unknown) => {\n fn._impl = () => value;\n return fn;\n };\n\n fn.mockImplementation = (impl: (...args: unknown[]) => unknown) => {\n fn._impl = impl;\n return fn;\n };\n\n return fn;\n}\n\ninterface MockFnInternal {\n _impl: ((...args: unknown[]) => unknown) | undefined;\n}\n\n/**\n * Creates a fully-mocked SiteActions object for testing.\n *\n * Every method on every service is a stub function with call tracking\n * and `.mockResolvedValue()` / `.mockReturnValue()` support.\n * Works with both Vitest and Jest — no framework dependency.\n *\n * @example\n * ```ts\n * import { createMockSiteActions } from \"@simpleapps-com/augur-server/testing\";\n *\n * const { actions, mocks } = createMockSiteActions();\n *\n * // Setup return values\n * mocks.pricing.getItemPrice.mockResolvedValue({ price: 9.99 });\n *\n * // Pass actions to your component/server action\n * const price = await actions.pricing.getItemPrice(\"ITEM-1\");\n *\n * // Assert calls\n * expect(mocks.pricing.getItemPrice.mock.calls[0]).toEqual([\"ITEM-1\"]);\n * ```\n */\nexport function createMockSiteActions(): MockSiteActionsResult {\n const result: Record<string, Record<string, MockFn>> = {};\n\n for (const [service, methods] of Object.entries(SERVICE_METHODS)) {\n const serviceMock: Record<string, MockFn> = {};\n for (const method of methods) {\n serviceMock[method] = createStubFn();\n }\n result[service] = serviceMock;\n }\n\n return {\n actions: result as unknown as SiteActions,\n mocks: result as unknown as MockSiteActions,\n };\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,wBAAwB;AAmCjC,IAAM,kBAA4C;AAAA,EAChD,SAAS,CAAC,gBAAgB,sBAAsB,gBAAgB;AAAA,EAChE,OAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAQ,CAAC,uBAAuB,wBAAwB,cAAc,oBAAoB;AAAA,E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AAgB,eAAe,gBAAgB;AAAA,EAC3D,WAAW;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,SAAS,eAAuB;AAC9B,QAAM,QAAqB,CAAC;AAE5B,QAAM,MAAM,IAAI,SAAoB;AAClC,UAAM,KAAK,IAAI;AACf,UAAM,OAAQ,GAAsB;AACpC,WAAO,OAAO,KAAK,GAAG,IAAI,IAAI;AAAA,EAChC;AAEA,KAAG,QAAQ;AACX,KAAG,OAAO,EAAE,MAAM;AAElB,KAAG,oBAAoB,CAAC,UAAmB;AACzC,OAAG,QAAQ,MAAM,QAAQ,QAAQ,KAAK;AACtC,WAAO;AAAA,EACT;AAEA,KAAG,oBAAoB,CAAC,UAAmB;AACzC,OAAG,QAAQ,MAAM,QAAQ,OAAO,KAAK;AACrC,WAAO;AAAA,EACT;AAEA,KAAG,kBAAkB,CAAC,UAAmB;AACvC,OAAG,QAAQ,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,KAAG,qBAAqB,CAAC,SAA0C;AACjE,OAAG,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AA6BO,SAAS,wBAA+C;AAC7D,QAAM,SAAiD,CAAC;AAExD,aAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,eAAe,GAAG;AAChE,UAAM,cAAsC,CAAC;AAC7C,eAAW,UAAU,SAAS;AAC5B,kBAAY,MAAM,IAAI,aAAa;AAAA,IACrC;AACA,WAAO,OAAO,IAAI;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,OAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Every row a list route holds, and whether the read stopped on the page cap. */
|
|
2
|
+
export interface AllPages<T> {
|
|
3
|
+
rows: T[];
|
|
4
|
+
/** True when the last allowed call still returned rows: the list may be incomplete. */
|
|
5
|
+
capReached: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Reads every row of a list route (atlas#102): pages of `size` until an empty page, at most `cap`
|
|
9
|
+
* calls, each next offset past the rows actually read. The decisions are the proved
|
|
10
|
+
* `read-rules.ts` (`continues`, `nextOffset`, `capReached`); this only awaits and gathers, as the
|
|
11
|
+
* model's `ReadLoop` (models/AugurServerReads.dfy) states: every row when the rows fit the cap's
|
|
12
|
+
* pages, never more than `cap` calls, never silently short.
|
|
13
|
+
*
|
|
14
|
+
* @param fetchPage One call to the route at `offset` asking for `limit` rows; resolves to its rows.
|
|
15
|
+
*/
|
|
16
|
+
export declare function readAllPages<T>(fetchPage: (offset: number, limit: number) => Promise<T[]>, size?: number, cap?: number): Promise<AllPages<T>>;
|
|
17
|
+
//# sourceMappingURL=read-all-pages.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-all-pages.d.ts","sourceRoot":"","sources":["../../src/utils/read-all-pages.ts"],"names":[],"mappings":"AAEA,kFAAkF;AAClF,MAAM,WAAW,QAAQ,CAAC,CAAC;IACzB,IAAI,EAAE,CAAC,EAAE,CAAC;IACV,uFAAuF;IACvF,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAClC,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,EAC1D,IAAI,GAAE,MAAmB,EACzB,GAAG,GAAE,MAAkB,GACtB,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAatB"}
|
package/llms.txt
CHANGED
|
@@ -45,7 +45,7 @@ The docs are at https://augur.build/docs/packages (the API reference lists every
|
|
|
45
45
|
- value: unwrap
|
|
46
46
|
- value: unwrapOr
|
|
47
47
|
- function: verifyRecaptcha - Server-side Google reCAPTCHA v3 verification. Used by API routes that accept public form submissions.
|
|
48
|
-
-
|
|
48
|
+
- const: withServerCache - Caches an action's shaped value.
|
|
49
49
|
- type: ActionResult
|
|
50
50
|
- type: EdgeCacheValue
|
|
51
51
|
- type: PaginatedResult
|
|
@@ -242,5 +242,48 @@ const handler = createAugurApiHandler();
|
|
|
242
242
|
export const POST = handler;
|
|
243
243
|
```
|
|
244
244
|
|
|
245
|
+
## @simpleapps-com/augur-server/sitemap
|
|
246
|
+
|
|
247
|
+
- function: buildSitemapIndexXml - The item index: a `<sitemapindex>` of `{base}sitemap-1.xml` … `{base}sitemap-{count}.xml`.
|
|
248
|
+
- function: buildUrlsetXml - An item page: a `<urlset>` of the rows under the items' folder, in order.
|
|
249
|
+
- function: createItemSitemapHandler - An item page's Route Handler, for `app/items/sitemap.xml/[page]/route.ts`, which `sitemapRewrite` maps `{base}sitemap-{n}.xml` onto: a `<urlset>` of page n's items under `base`, a 404 for no such page, or a 503 when Augur can't be read.
|
|
250
|
+
- function: createSitemapIndexHandler - The item index's Route Handler, for `app/items/sitemap.xml/route.ts` (or the folder `base` names): a `<sitemapindex>` of every item page file, or a 503 when Augur can't be read.
|
|
251
|
+
- const: DEFAULT_SITEMAP_BASE - The items' folder when a site names none.
|
|
252
|
+
- const: DEFAULT_SITEMAP_DEADLINE - How long one Augur call may take, in milliseconds: crawlers wait longer than page visitors, and a call past it is a 503 the crawler retries.
|
|
253
|
+
- function: inScope - Whether a link is under the items' folder (the location rule); an empty link never is.
|
|
254
|
+
- function: isSitemapPath - Whether a path is one of the item sitemaps (the index or a page file), which a site's proxy MUST pass through before any item-URL redirect (the proxy runs before rewrites).
|
|
255
|
+
- function: itemSitemapCount - How many 5,000-item sitemaps cover `total` items (the endpoint fixes a page at 5,000).
|
|
256
|
+
- function: itemSitemapUrl - Item sitemap n's URL: `{siteUrl}{base}sitemap-{n}.xml`.
|
|
257
|
+
- function: parseItemSitemapPage - The page a request names (the rewrite's bare `:page`): its value when it is a canonical natural number, else 0, "not a page" (`0`, `01`, `1e3`, ` 1`, `-1` and text never name one).
|
|
258
|
+
- function: robotsSitemaps - robots.txt's sitemaps: the site's own root `/sitemap.xml` and the item index. Two lines, since the specs name no index inside an index.
|
|
259
|
+
- function: sitemapBase - The items' folder as a path, with one leading and one trailing "/" ("items" → "/items/").
|
|
260
|
+
- function: sitemapRewrite - The Next.js rewrite from `{base}sitemap-{n}.xml` to the item page handler's route; spread it into `next.config`'s `rewrites()`.
|
|
261
|
+
- type: SitemapOptions
|
|
262
|
+
- type: SitemapOutcome
|
|
263
|
+
- type: SitemapRewrite
|
|
264
|
+
- type: SitemapRow
|
|
265
|
+
- type: SitemapSite
|
|
266
|
+
|
|
267
|
+
### Examples
|
|
268
|
+
|
|
269
|
+
createItemSitemapHandler:
|
|
270
|
+
```ts
|
|
271
|
+
export const dynamic = "force-dynamic";
|
|
272
|
+
export const GET = createItemSitemapHandler(site, { siteUrl: "https://www.example.com" });
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
createSitemapIndexHandler:
|
|
276
|
+
```ts
|
|
277
|
+
export const dynamic = "force-dynamic";
|
|
278
|
+
export const GET = createSitemapIndexHandler(site, { siteUrl: "https://www.example.com" });
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
sitemapRewrite:
|
|
282
|
+
```ts
|
|
283
|
+
async rewrites() {
|
|
284
|
+
return [sitemapRewrite()];
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
245
288
|
## @simpleapps-com/augur-server/next-auth
|
|
246
289
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simpleapps-com/augur-server",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.7",
|
|
4
4
|
"description": "Server-side utilities for Augur ecommerce sites (Redis caching, SDK helpers, auth)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"types": "./dist/api.d.ts",
|
|
47
47
|
"import": "./dist/api.js"
|
|
48
48
|
},
|
|
49
|
+
"./sitemap": {
|
|
50
|
+
"types": "./dist/sitemap.d.ts",
|
|
51
|
+
"import": "./dist/sitemap.js"
|
|
52
|
+
},
|
|
49
53
|
"./next-auth": {
|
|
50
54
|
"types": "./next-auth.d.ts"
|
|
51
55
|
}
|
|
@@ -58,8 +62,8 @@
|
|
|
58
62
|
"llms.txt"
|
|
59
63
|
],
|
|
60
64
|
"dependencies": {
|
|
61
|
-
"@simpleapps-com/augur-core": "^2026.11.
|
|
62
|
-
"@simpleapps-com/augur-hooks": "^2026.11.
|
|
65
|
+
"@simpleapps-com/augur-core": "^2026.11.5",
|
|
66
|
+
"@simpleapps-com/augur-hooks": "^2026.11.4",
|
|
63
67
|
"@simpleapps-com/augur-utils": "^2026.11.3"
|
|
64
68
|
},
|
|
65
69
|
"peerDependencies": {
|
|
@@ -98,10 +102,10 @@
|
|
|
98
102
|
"@atlas/eslint-config": "0.0.0",
|
|
99
103
|
"@atlas/tsconfig": "0.0.0",
|
|
100
104
|
"@atlas/tsup-config": "0.0.0",
|
|
101
|
-
"@atlas/utils": "0.0.0",
|
|
102
105
|
"@atlas/foundation": "0.0.0",
|
|
106
|
+
"@atlas/utils": "0.0.0",
|
|
103
107
|
"@atlas/vitest-config": "0.0.0",
|
|
104
|
-
"@simpleapps-com/augur-api": "2026.11.
|
|
108
|
+
"@simpleapps-com/augur-api": "2026.11.5"
|
|
105
109
|
},
|
|
106
110
|
"engines": {
|
|
107
111
|
"node": ">=22.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../foundation/src/duration.ts","../../utils/src/strings.ts","../../utils/src/includes.ts","../src/rules.ts","../src/scoped-client-key.ts","../src/sdk-client-store.ts"],"sourcesContent":["//@ backend dafny\n\n/* Seconds and milliseconds as two types (2026-11-08). Verified with LemmaScript → Dafny\n (`pnpm proofs`; model: models/Durations.dfy, where they are two datatypes; link:\n models/links/foundation-duration.dfy).\n\n Both are branded: a plain `number` is neither, and a `Seconds` is not a `Millis`, so a TTL in\n seconds can't be passed where milliseconds are meant (augur-core's `staleTime` vs\n `redisTtl`), and a JWT `exp` can't be compared with `Date.now()` unconverted. Write a\n duration in the unit people think in (`minutes(15)`) and convert with `toMillis`; read a\n clock or a millisecond count back with `floorSeconds`. Values enter through the guards\n `secondsOf` / `millisOf` (an env value, a JSON `expires_in`); the clock is `millis(Date.now())`\n (the platform's time value is a whole, non-negative number of milliseconds).\n lsc writes both aliases as `nat` (no refinement, models/LSC-GAPS.md). */\n\n/** A whole number of seconds, made only by the builders and guards below. */\n//@ type nat\nexport type Seconds = number & { readonly __seconds: true };\n\n/** A whole number of milliseconds, made only by the builders and guards below. */\n//@ type nat\nexport type Millis = number & { readonly __millis: true };\n\n/**\n * `n` seconds.\n *\n * @ensures exactly the model's Seconds(n)\n */\nexport function seconds(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Seconds;\n}\n\n/**\n * `n` minutes, in seconds.\n *\n * @ensures exactly the model's Minutes\n */\nexport function minutes(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 60\n return (n * 60) as Seconds;\n}\n\n/**\n * `n` hours, in seconds.\n *\n * @ensures exactly the model's Hours\n */\nexport function hours(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 3600\n return (n * 3600) as Seconds;\n}\n\n/**\n * `n` days, in seconds.\n *\n * @ensures exactly the model's Days\n */\nexport function days(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 86400\n return (n * 86400) as Seconds;\n}\n\n/**\n * `n` milliseconds: for a duration under a second (a retry backoff, a debounce).\n *\n * @ensures exactly the model's Millis(n)\n */\nexport function millis(n: number): Millis {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Millis;\n}\n\n/**\n * Seconds as milliseconds, exactly.\n *\n * @ensures exactly the model's ToMillis\n */\nexport function toMillis(d: Seconds): Millis {\n //@ verify\n //@ requires d >= 0\n //@ ensures \\result === d * 1000\n return (d * 1000) as Millis;\n}\n\n/**\n * Milliseconds as whole seconds, rounded down (a JWT `exp` or `iat` from a clock).\n *\n * @ensures exactly the model's FloorSeconds\n */\nexport function floorSeconds(m: Millis): Seconds {\n //@ verify\n //@ type m nat\n //@ requires m >= 0\n //@ ensures \\result === Math.floor(m / 1000)\n return Math.floor(m / 1000) as Seconds;\n}\n\n/**\n * A clock reading plus a duration, both `Millis`: when something expires (`addMillis(now,\n * toMillis(minutes(15)))`).\n *\n * @ensures exactly the model's AddMillis\n */\nexport function addMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === a + b\n return (a + b) as Millis;\n}\n\n/**\n * A reading less a duration, never below 0 (a token used until a minute before it expires). An\n * expiry clamped to 0 is no more live than the negative one it stands for (the model's\n * MinusMillisKeepsLiveness).\n *\n * @ensures exactly the model's MinusMillis\n */\nexport function minusMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === (a >= b ? a - b : 0)\n return a >= b ? ((a - b) as Millis) : millis(0);\n}\n\n/**\n * `n` as `Seconds`, or null when it is not a safe integer at least 0: a fraction, NaN, a\n * negative, an infinity, or past `Number.MAX_SAFE_INTEGER`. Where a number of seconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function secondsOf(n: number): Seconds | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Seconds) : null;\n}\n\n/**\n * An outside count of seconds (a token's `expires_in`, a JWT's `exp`) as `Seconds`: rounded\n * down, and 0 when it is then no safe integer at least 0 (a negative, NaN, an infinity), so a\n * bad lifetime is no lifetime and a bad expiry is already past.\n *\n * @ensures exactly the model's WholeSeconds (the proof reads a number as an integer)\n */\nexport function wholeSeconds(n: number): Seconds {\n //@ verify\n //@ ensures (n >= 0 && n <= 9007199254740991) ==> \\result === n\n //@ ensures !(n >= 0 && n <= 9007199254740991) ==> \\result === 0\n const whole = secondsOf(Math.floor(n));\n return whole === null ? seconds(0) : whole;\n}\n\n/**\n * `n` as `Millis`, or null when it is not a safe integer at least 0 (the same rule as\n * `secondsOf`). Where a number of milliseconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function millisOf(n: number): Millis | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Millis) : null;\n}\n","//@ backend dafny\nimport {\n isAlnumChar,\n isBase64UrlChar,\n isDigit,\n isHexChar,\n isJsSpace,\n isLineTerminator,\n isLowerHexChar,\n isSnakeChar,\n isWordChar,\n lowerCode,\n} from \"@atlas/foundation/chars\";\n\n/* String scans and slices, verified with LemmaScript → Dafny (hand lemmas in strings.dfy;\n model: models/Utils.dfy; link: models/links/utils-strings.dfy). Recursive and\n expression-bodied so specs can use them, and each contract pins the result exactly, so\n an importer (which sees only the contract) knows what it returns. Two of them stand in\n for constructs lsc mistranslates: `prefix` for an unclamped `slice`, and the code-unit\n scans for \"\\r\" / \"\\n\" literals. */\n\n/**\n * The code unit at `i`, or -1 when `i` is outside `s`. JS `charCodeAt` gives NaN there,\n * which no code equals, so a scan's own bounds test would change no result and no test\n * could tell it from none (an equivalent mutant); with the bound here once, the boundary is\n * observable (tests pin -1) and the scans that use it carry no bound of their own. A code\n * unit is never negative, so -1 matches no `code` a caller passes (`requires code >= 0`).\n *\n * @ensures 0 ≤ i < |s| ⟹ result = s[i]; otherwise result = -1\n */\nexport function codeAt(s: string, i: number): number {\n //@ verify\n //@ ensures (i >= 0 && i < s.length) ==> \\result === s.charCodeAt(i)\n //@ ensures !(i >= 0 && i < s.length) ==> \\result === -1\n return i >= 0 && i < s.length ? s.charCodeAt(i) : -1;\n}\n\n/**\n * Every character of `s` from index `i` on is base64url.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isBase64UrlChar(s[k])\n */\nexport function base64UrlFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isBase64UrlChar(s.charCodeAt(k)))\n return i >= s.length || (isBase64UrlChar(s.charCodeAt(i)) && base64UrlFrom(s, i + 1));\n}\n\n/**\n * The base64url digit for `v` (RFC 4648 §5): A-Z a-z 0-9 - _.\n *\n * @ensures exactly the model's Base64UrlDigit\n */\nexport function base64UrlDigit(v: number): string {\n //@ verify\n //@ type v nat\n //@ requires v >= 0 && v < 64\n //@ ensures \\result === \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1)\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1);\n}\n\n/**\n * Bytes from `i` on as unpadded base64url: each three as four digits, a last one or two as two or\n * three (JS `btoa` with `+/` as `-_` and the `=` dropped). One frame per three bytes: a JWT part\n * is a few hundred.\n *\n * @ensures exactly the model's Base64UrlFrom (links/utils-strings.dfy)\n */\nexport function encodeBase64UrlFrom(b: number[], i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && forall(k: nat, k < b.length ==> (b[k] >= 0 && b[k] < 256))\n //@ decreases b.length - i\n //@ ensures i >= b.length ==> \\result === \"\"\n if (i >= b.length) return \"\";\n const x = b[i] as number;\n const first = base64UrlDigit(Math.floor(x / 4));\n if (i + 1 === b.length) return first + base64UrlDigit((x % 4) * 16);\n const y = b[i + 1] as number;\n const second = base64UrlDigit((x % 4) * 16 + Math.floor(y / 16));\n if (i + 2 === b.length) return first + second + base64UrlDigit((y % 16) * 4);\n const z = b[i + 2] as number;\n return (\n first +\n second +\n base64UrlDigit((y % 16) * 4 + Math.floor(z / 64)) +\n base64UrlDigit(z % 64) +\n encodeBase64UrlFrom(b, i + 3)\n );\n}\n\n/**\n * Every character of `s` from index `i` on is lowercase hex.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isLowerHexChar(s[k])\n */\nexport function lowerHexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isLowerHexChar(s.charCodeAt(k)))\n return i >= s.length || (isLowerHexChar(s.charCodeAt(i)) && lowerHexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is hex, either case.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isHexChar(s[k])\n */\nexport function hexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isHexChar(s.charCodeAt(k)))\n return i >= s.length || (isHexChar(s.charCodeAt(i)) && hexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII digit (`\\d` without the `u` flag).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isDigit(s[k])\n */\nexport function digitsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isDigit(s.charCodeAt(k)))\n return i >= s.length || (isDigit(s.charCodeAt(i)) && digitsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a word character (`\\w`: `[A-Za-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isWordChar(s[k])\n */\nexport function wordCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isWordChar(s.charCodeAt(k)))\n return i >= s.length || (isWordChar(s.charCodeAt(i)) && wordCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a snake_case character (`[a-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isSnakeChar(s[k])\n */\nexport function snakeCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isSnakeChar(s.charCodeAt(k)))\n return i >= s.length || (isSnakeChar(s.charCodeAt(i)) && snakeCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter or digit (`[A-Za-z0-9]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k])\n */\nexport function alnumFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isAlnumChar(s.charCodeAt(k)))\n return i >= s.length || (isAlnumChar(s.charCodeAt(i)) && alnumFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter, digit or `-` (`[A-Za-z0-9-]`):\n * a domain label's tail, a service name's tail.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k]) ∨ s[k] = \"-\" — the model's AlnumDashFrom\n */\nexport function alnumDashFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> (isAlnumChar(s.charCodeAt(k)) || s.charCodeAt(k) === 45))\n if (i >= s.length) return true;\n const c = s.charCodeAt(i);\n return (isAlnumChar(c) || c === 45) && alnumDashFrom(s, i + 1);\n}\n\n/**\n * The last index before `end` holding `code`, or -1 (JS `s.lastIndexOf(c)` at end = |s|).\n *\n * @ensures result = -1 ∨ (0 ≤ result < end ∧ s[result] = code ∧ no `code` in (result, end))\n */\nexport function lastIndexOfCode(s: string, code: number, end: number): number {\n //@ verify\n //@ type end nat\n //@ requires 0 <= end && end <= s.length\n //@ decreases end\n //@ ensures \\result === -1 || (0 <= \\result && \\result < end)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < end) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, k < end ==> s.charCodeAt(k) !== code)\n if (end === 0) return -1;\n if (s.charCodeAt(end - 1) === code) return end - 1;\n return lastIndexOfCode(s, code, end - 1);\n}\n\n/**\n * No character of `s` from index `i` on is `code`.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). s[k] ≠ code\n */\nexport function lacksCode(s: string, code: number, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n // `===`, not `>=`: past the end a read is NaN !== code, so `>=` vs `>` would be equivalent\n return i === s.length || (s.charCodeAt(i) !== code && lacksCode(s, code, i + 1));\n}\n\n/**\n * The end of the run of `code` starting at `i`: the first index ≥ i that isn't `code`\n * (skip spaces: `codeRunEnd(header, 32, i)`).\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] = code ∧ (result < |s| ⟹ s[result] ≠ code)\n * — exactly the run's end\n */\nexport function codeRunEnd(s: string, code: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires code >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> s.charCodeAt(k) === code)\n //@ ensures \\result < s.length ==> s.charCodeAt(\\result) !== code\n return codeAt(s, i) === code ? codeRunEnd(s, code, i + 1) : i;\n}\n\n/**\n * The first index ≥ `from` holding `code`, or -1 (`indexOf` for one code unit, so \"\\n\" is\n * passed as 10, never as a literal).\n *\n * @ensures result = -1 ∨ (from ≤ result < |s| ∧ s[result] = code), with no `code` in\n * [from, result) — the first one; result = -1 ⟹ none from `from` on\n */\nexport function indexOfCode(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ decreases s.length - from\n //@ ensures \\result === -1 || (from <= \\result && \\result < s.length)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (from <= k && k < \\result) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, (from <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n const c = codeAt(s, from);\n if (c === code) return from;\n if (c === -1) return -1;\n return indexOfCode(s, code, from + 1);\n}\n\n/**\n * The first index ≥ `i` holding `a` or `b`, or |s| (a run either code ends: a path segment's\n * run to \"/\" or \"?\"). One scan: the lesser of two `indexOfCode` ends is the same index, but\n * its two sides are equal only when both are |s|, a boundary no test can observe.\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] ∉ {a, b} ∧ (result < |s| ⟹ s[result] ∈ {a, b})\n * — exactly the first such index\n */\nexport function eitherCodeEnd(s: string, a: number, b: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires a >= 0 && b >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) !== a && s.charCodeAt(k) !== b))\n //@ ensures \\result < s.length ==> (s.charCodeAt(\\result) === a || s.charCodeAt(\\result) === b)\n const c = codeAt(s, i);\n if (c === -1 || c === a || c === b) return i;\n return eitherCodeEnd(s, a, b, i + 1);\n}\n\n/**\n * `s` without one trailing `code` (\"\\r\" before a \"\\n\", say); unchanged otherwise.\n *\n * @ensures s ends with code ⟹ result = s[0, |s| − 1)\n * @ensures otherwise result = s\n */\nexport function dropLast(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures (s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s.slice(0, s.length - 1)\n //@ ensures !(s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s\n return codeAt(s, s.length - 1) === code ? s.slice(0, s.length - 1) : s;\n}\n\n/**\n * `s` without its leading `code` units (every one of them).\n *\n * @ensures exactly the model's LStripCode\n */\nexport function lStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, 0) === code) return lStripCode(s.slice(1), code);\n return s;\n}\n\n/**\n * `s` without its trailing `code` units (every one of them).\n *\n * @ensures exactly the model's RStripCode\n */\nexport function rStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, s.length - 1) === code) {\n return rStripCode(s.slice(0, s.length - 1), code);\n }\n return s;\n}\n\n/**\n * `s` without its leading and trailing `code` units, the middle kept (`/a/b/` with `/` →\n * `a/b`).\n *\n * @ensures exactly the model's StripCode — neither end is `code` (StripCodeTrims)\n */\nexport function stripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === rStripCode(lStripCode(s, code), code)\n return rStripCode(lStripCode(s, code), code);\n}\n\n/**\n * JS `s.startsWith(x, pos)`, which lsc mistranslates (it drops `pos`). Like JS, a `pos`\n * past the end counts as the end, so the empty string matches anywhere.\n *\n * @ensures pos ≤ |s| ⟹ (result ⟺ pos + |x| ≤ |s| ∧ s[pos, pos + |x|) = x) — so a true\n * result also gives the bounds for slicing after the match\n * @ensures pos > |s| ⟹ (result ⟺ x = \"\")\n */\nexport function startsWithAt(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures pos <= s.length ==> (\\result <==> (pos + x.length <= s.length && s.slice(pos, pos + x.length) === x))\n //@ ensures pos > s.length ==> (\\result <==> x.length === 0)\n // Math.min, not a ternary: at pos = |s| both branches agree, so `<` vs `<=` is equivalent\n const at = Math.min(pos, s.length);\n // The slice is clamped to the end, so a too-long x differs by length: no separate fit test\n // (JS slice clamps too, which made one unobservable)\n return s.slice(at, Math.min(at + x.length, s.length)) === x;\n}\n\n/**\n * `s` with A-Z lowercased and every other character kept: what lsc's proofs take\n * `toLowerCase()` to be. JS's `toLowerCase()` also maps non-ASCII letters, some onto ASCII\n * (the Kelvin sign K, U+212A, becomes \"k\") or onto two characters (İ, U+0130), so a proved\n * function that lowercases MUST use this, or the runtime does what the proof says it\n * doesn't.\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ A-Z ? s[k] + 32 : s[k]) — A-Z\n * lowered, every other code unit unchanged; true in JS (a contract `=== s.toLowerCase()` held\n * only in lsc's ASCII model of the built-in, Fable review 2026-11-06). Helper-free, since an\n * importer is given only the helpers its own body calls; exactly the model's LowerAscii in\n * the link\n */\nexport function lowerAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 65 && s.charCodeAt(k) <= 90) ? s.charCodeAt(k) + 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(0, 1);\n return head + lowerAscii(s.slice(1));\n}\n\n/**\n * `lowerAscii` as a loop: a constant stack depth (and linear time) on long text, where the\n * recursive spec takes a frame and a slice per character.\n *\n * @ensures result = lowerAscii(s)\n */\nexport function lowerAsciiText(s: string): string {\n //@ verify\n //@ ensures \\result === lowerAscii(s)\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + lowerAscii(s.slice(i)) === lowerAscii(s)\n //@ decreases s.length - i\n const c = s.charCodeAt(i);\n out =\n out +\n (c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(i, i + 1));\n i = i + 1;\n }\n return out;\n}\n\n/**\n * Whether `x` from index `k` matches `s` from `pos + k`, code by code, ASCII-lowered. A code\n * past the end of `s` is -1 (`codeAt`), which no code of `x` is, so there is no bound to\n * check (a `pos + |x| ≤ |s|` guard before a slice never changed the answer at runtime, where\n * `slice` clamps: an equivalent mutant, 2026-11-02).\n *\n * @ensures exactly the model's CaselessFrom\n */\nexport function caselessFrom(s: string, x: string, pos: number, k: number): boolean {\n //@ verify\n //@ type pos nat\n //@ type k nat\n //@ requires pos >= 0 && k >= 0 && k <= x.length\n //@ decreases x.length - k\n //@ ensures k === x.length ==> \\result\n if (k === x.length) return true;\n return lowerCode(codeAt(s, pos + k)) === x.charCodeAt(k) && caselessFrom(s, x, pos, k + 1);\n}\n\n/**\n * Whether the text of `s` at `pos`, ASCII-lowered, is `x` (`x` given lowercase): a case-free\n * `startsWith`; callers carry no length guard of their own. Only `pos ≤ |s|` is checked: it\n * decides an empty `x` past the end, the one case the code-by-code test can't see.\n *\n * @ensures result ⟺ pos + |x| ≤ |s| ∧ ∀ j < |x|. lowered(s[pos + j]) = x[j] — the text at pos,\n * ASCII-lowered (A-Z + 32), is x; helper-free; exactly the model's StartsWithCaseless in the link\n */\nexport function startsWithCaseless(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures \\result <==> (pos + x.length <= s.length && forall(j: nat, j < x.length ==> ((s.charCodeAt(pos + j) >= 65 && s.charCodeAt(pos + j) <= 90) ? s.charCodeAt(pos + j) + 32 : s.charCodeAt(pos + j)) === x.charCodeAt(j)))\n return pos <= s.length && caselessFrom(s, x, pos, 0);\n}\n\n/**\n * Whether `s` ends with `suffix` (JS one-argument `endsWith`, which lsc reads as its\n * two-argument form; moved from the augur-api generator 2026-11-01).\n *\n * @ensures result ⟺ |s| ≥ |suffix| ∧ s[|s| − |suffix|, |s|) = suffix — exactly the model's EndsWith\n */\nexport function endsWith(s: string, suffix: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s.length >= suffix.length && s.slice(s.length - suffix.length) === suffix)\n // No length test: from max(|s| − |suffix|, 0), a too-long suffix compares unequal by length\n return s.slice(Math.max(s.length - suffix.length, 0)) === suffix;\n}\n\n/**\n * The order of `a` and `b` by UTF-16 code unit from index `i`, as a recursive spec: -1, 0\n * or 1 (JS `<` on strings; a proper prefix comes first). Locale-free, unlike `localeCompare`.\n *\n * @ensures result ∈ {-1, 0, 1} — exactly the model's CompareFrom\n */\nexport function compareFrom(a: string, b: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases a.length - i\n //@ ensures \\result === -1 || \\result === 0 || \\result === 1\n if (i >= a.length) return i >= b.length ? 0 : -1;\n if (i >= b.length) return 1;\n const x = a.charCodeAt(i);\n const y = b.charCodeAt(i);\n if (x < y) return -1;\n if (x > y) return 1;\n return compareFrom(a, b, i + 1);\n}\n\n/**\n * The order of two strings by UTF-16 code unit, for `sort` (what the default `sort` uses on\n * strings), so sorted output never depends on locale.\n *\n * @ensures result = compareFrom(a, b, 0)\n */\nexport function compareCodeUnits(a: string, b: string): number {\n //@ verify\n //@ ensures \\result === compareFrom(a, b, 0)\n return compareFrom(a, b, 0);\n}\n\n/**\n * JS `s.slice(0, n)`: at most `n` characters, clamped to the length. lsc reads a bare\n * `slice(0, n)` without JS's clamp, so use this instead.\n *\n * @ensures result = s[0, min(n, |s|))\n */\nexport function prefix(s: string, n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures n < s.length ==> \\result === s.slice(0, n)\n //@ ensures n >= s.length ==> \\result === s\n // Math.min, not a ternary: JS slice already clamps, so a ternary's branch is unobservable\n return s.slice(0, Math.min(n, s.length));\n}\n\n/**\n * The end of the JS-whitespace (`\\s`) run starting at `i`: the first index ≥ i that is not\n * whitespace, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all whitespace ∧ (result = |s| ∨ ¬space(s[result]))\n */\nexport function spaceRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> isJsSpace(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> !isJsSpace(s.charCodeAt(\\result))\n // codeAt is -1 at the end, which is no space: the bound needs no test of its own here\n if (!isJsSpace(codeAt(s, i))) return i;\n return spaceRunEnd(s, i + 1);\n}\n\n/**\n * The end of the ASCII-digit run starting at `i` (a regex's `\\d+`, from `i`): the first index\n * ≥ i that is not 0-9, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all digits ∧ (result = |s| ∨ ¬digit(s[result])) —\n * exactly the model's DigitRunEnd\n */\nexport function digitRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ ensures \\result < s.length ==> !(s.charCodeAt(\\result) >= 48 && s.charCodeAt(\\result) <= 57)\n // codeAt is -1 at the end, which is no digit\n if (!isDigit(codeAt(s, i))) return i;\n return digitRunEnd(s, i + 1);\n}\n\n/**\n * A natural number written canonically (`^(0|[1-9][0-9]*)$`): the keys JS objects move\n * first, ahead of their source order.\n *\n * @ensures exactly the model's CanonicalNat, stated over the codes themselves so an importer\n * can use it (a contract naming `digitsFrom` can't be resolved there, models/LSC-GAPS.md)\n */\nexport function isCanonicalNat(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s === \"0\" || (s.length > 0 && s.charCodeAt(0) >= 49 && s.charCodeAt(0) <= 57 && forall(k: nat, (1 <= k && k < s.length) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))))\n if (s === \"0\") return true;\n const first = codeAt(s, 0);\n return first >= 49 && first <= 57 && digitsFrom(s, 1);\n}\n\n/**\n * The value of a run of decimal digits, most significant first (\"\" is 0).\n *\n * @requires ∀ k ∈ [0, |s|). isDigit(s[k])\n * @ensures exactly the model's DigitsValue (proved in links/utils-strings.dfy)\n */\nexport function digitsValue(s: string): number {\n //@ verify\n //@ requires forall(k: nat, k < s.length ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ decreases s.length\n //@ ensures \\result >= 0\n if (s.length === 0) return 0;\n return digitsValue(s.slice(0, s.length - 1)) * 10 + (s.charCodeAt(s.length - 1) - 48);\n}\n\n/**\n * What a number from the environment means (owner 2026-11-04: a bad one fails at start):\n * \"default\" when unset (\"\": the wrapper reads a missing variable as \"\"), \"value\" when it is\n * a canonical natural number at least `min` (its value is `digitsValue(raw)`), and \"bad\"\n * otherwise: a sign, a space, a fraction, an exponent, hex, text, or below `min`.\n *\n * @ensures exactly the model's EnvNumberOf (proved in links/utils-strings.dfy)\n */\nexport function envNumberKind(raw: string, min: number): string {\n //@ verify\n //@ type min nat\n //@ ensures raw === \"\" ==> \\result === \"default\"\n //@ ensures (raw !== \"\" && !isCanonicalNat(raw)) ==> \\result === \"bad\"\n if (raw === \"\") return \"default\";\n if (!isCanonicalNat(raw)) return \"bad\";\n return digitsValue(raw) < min ? \"bad\" : \"value\";\n}\n\n/**\n * A canonical natural number's value, 0 for any other text (a count written as JSON).\n *\n * @ensures exactly the model's CanonicalNatValue (in the link: `digitsValue` needs the digits\n * isCanonicalNat's contract gives, which a contract can't call for); 0 for other text\n */\nexport function canonicalNatValue(s: string): number {\n //@ verify\n //@ ensures \\result >= 0\n //@ ensures !isCanonicalNat(s) ==> \\result === 0\n if (!isCanonicalNat(s)) return 0;\n return digitsValue(s);\n}\n\n/**\n * The first index ≥ `i` holding a line terminator, or |s|: where a regex `.+` started at `i`\n * stops.\n *\n * @ensures i ≤ result ≤ |s| ∧ no terminator in s[i, result) ∧ (result = |s| ∨ terminator at result)\n */\nexport function lineEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> !isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> isLineTerminator(s.charCodeAt(\\result))\n if (i === s.length || isLineTerminator(s.charCodeAt(i))) return i;\n return lineEnd(s, i + 1);\n}\n\n/**\n * The largest p with lo ≤ p < hi whose character is not a line terminator, or -1: where a\n * backtracking regex `.` can start.\n *\n * @ensures result = -1 ∨ (lo ≤ result < hi ∧ ¬terminator(s[result]) ∧ only terminators in (result, hi))\n */\nexport function lastLineCharBelow(s: string, hi: number, lo: number): number {\n //@ verify\n //@ type hi nat\n //@ type lo nat\n //@ requires 0 <= lo && 0 <= hi && hi <= s.length\n //@ decreases hi\n //@ ensures \\result === -1 || (lo <= \\result && \\result < hi)\n //@ ensures \\result >= 0 ==> !isLineTerminator(s.charCodeAt(\\result))\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result === -1 ==> forall(k: nat, (lo <= k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n if (hi <= lo) return -1;\n if (!isLineTerminator(s.charCodeAt(hi - 1))) return hi - 1;\n return lastLineCharBelow(s, hi - 1, lo);\n}\n\n/**\n * Nothing but JS whitespace (`s.trim() === \"\"`).\n *\n * @ensures exactly the model's Blank\n */\nexport function isBlank(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> s.trim() === \"\"\n return s.trim() === \"\";\n}\n\n/**\n * The first index ≥ `i` where `x` occurs in `s`, or -1 (JS `s.indexOf(x, i)` for i ≤ |s|).\n *\n * @ensures result = -1 ∨ (i ≤ result ∧ s[result, result + |x|) = x) — and the first such\n * index: links/utils-strings.dfy proves it is exactly the model's IndexOfFrom (lsc can't\n * give the \"no earlier match\" quantifier a trigger)\n */\nexport function indexOfFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result + x.length <= s.length)\n //@ ensures \\result >= 0 ==> s.slice(\\result, \\result + x.length) === x\n // A match here, else the end, else the next index: stopping at `i === |s|` (not \"x no\n // longer fits\") leaves no bound whose slip a later, harmless step would hide\n if (startsWithAt(s, x, i)) return i;\n if (i === s.length) return -1;\n return indexOfFrom(s, x, i + 1);\n}\n\n/**\n * `indexOfFrom` as a loop: the same answer at a constant stack depth, for text long enough that\n * one frame per character would overflow the stack (a rendered page, 50–60 KB with its inlined\n * stylesheet). Specs and links use `indexOfFrom`; runtime scans over long text use this.\n *\n * @ensures result = indexOfFrom(s, x, i)\n */\nexport function findFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ ensures \\result === indexOfFrom(s, x, i)\n let k = i;\n while (k !== s.length) {\n //@ invariant i <= k && k <= s.length\n //@ invariant indexOfFrom(s, x, k) === indexOfFrom(s, x, i)\n //@ decreases s.length - k\n if (startsWithAt(s, x, k)) return k;\n k = k + 1;\n }\n return startsWithAt(s, x, k) ? k : -1;\n}\n\n/**\n * `indexOfCode` as a loop: the same answer at a constant stack depth (see `findFrom`).\n *\n * @ensures result = indexOfCode(s, code, from)\n */\nexport function findCodeFrom(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ ensures \\result === indexOfCode(s, code, from)\n let k = from;\n while (k < s.length) {\n //@ invariant from <= k\n //@ invariant indexOfCode(s, code, k) === indexOfCode(s, code, from)\n //@ decreases s.length - k\n if (s.charCodeAt(k) === code) return k;\n k = k + 1;\n }\n return -1;\n}\n\n/**\n * How many times `x` occurs in `s` from `i` on, left to right without overlaps (repeated JS\n * `s.indexOf(x, at + x.length)`).\n *\n * @requires |x| > 0\n * @ensures result ≥ 0 — exactly the model's CountFrom (links/utils-strings.dfy)\n */\nexport function countFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires x.length > 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result >= 0\n const at = indexOfFrom(s, x, i);\n if (at === -1) return 0;\n return 1 + countFrom(s, x, at + x.length);\n}\n\n/**\n * `countFrom(s, x, 0)` as a loop: a constant stack depth on long text (see `findFrom`).\n *\n * @requires |x| > 0\n * @ensures result = countFrom(s, x, 0)\n */\nexport function countOf(s: string, x: string): number {\n //@ verify\n //@ requires x.length > 0\n //@ ensures \\result === countFrom(s, x, 0)\n let n = 0;\n let i = 0;\n let at = findFrom(s, x, 0);\n while (at !== -1) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant at === indexOfFrom(s, x, i)\n //@ invariant n + countFrom(s, x, i) === countFrom(s, x, 0)\n //@ decreases s.length - i\n n = n + 1;\n i = at + x.length;\n at = findFrom(s, x, i);\n }\n return n;\n}\n\n/**\n * The text before the first `code`, or all of it when there is none (JS `s.split(c)[0]`).\n *\n * @ensures result = s[0, first code) when s holds one, else s — the model's UntilCode\n */\nexport function untilCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === (indexOfCode(s, code, 0) >= 0 && indexOfCode(s, code, 0) <= s.length ? s.slice(0, indexOfCode(s, code, 0)) : s)\n const k = indexOfCode(s, code, 0);\n return k >= 0 ? s.slice(0, k) : s;\n}\n\n/**\n * `s` from `i` on split at every `code` (JS `s.split(c)` at i = 0, for a one-character\n * separator): always at least one part.\n *\n * @ensures |result| ≥ 1 — exactly the model's SplitCodeFrom (links/utils-strings.dfy)\n */\nexport function splitCodeFrom(s: string, code: number, i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires code >= 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length > 0\n const k = indexOfCode(s, code, i);\n if (k === -1) return [s.slice(i)];\n return [s.slice(i, k), ...splitCodeFrom(s, code, k + 1)];\n}\n\n/**\n * Every run of JS whitespace in `s` from `i` on as one space (JS `s.replace(/\\s+/g, \" \")` at\n * i = 0).\n *\n * @ensures |result| ≤ |s| − i — exactly the model's CollapseSpacesFrom (links/utils-strings.dfy)\n */\nexport function collapseSpacesFrom(s: string, i: number): string {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length <= s.length - i\n if (i === s.length) return \"\";\n if (isJsSpace(s.charCodeAt(i))) return \" \" + collapseSpacesFrom(s, spaceRunEnd(s, i));\n return s.slice(i, i + 1) + collapseSpacesFrom(s, i + 1);\n}\n\n/**\n * `collapseSpacesFrom(s, 0)` at a constant stack depth (a page's text is tens of KB).\n *\n * @ensures result = collapseSpacesFrom(s, 0)\n */\nexport function collapseSpaces(s: string): string {\n //@ verify\n //@ ensures \\result === collapseSpacesFrom(s, 0)\n let out = \"\";\n let i = 0;\n while (i < s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + collapseSpacesFrom(s, i) === collapseSpacesFrom(s, 0)\n //@ decreases s.length - i\n if (isJsSpace(s.charCodeAt(i))) {\n out = out + \" \";\n // the run's end as a loop too: spaceRunEnd takes a frame per space (Fable review 2026-11-06)\n let e = i + 1;\n while (e !== s.length && isJsSpace(s.charCodeAt(e))) {\n //@ invariant i < e && e <= s.length\n //@ invariant forall(k: nat, (i <= k && k < e) ==> isJsSpace(s.charCodeAt(k)))\n //@ decreases s.length - e\n e = e + 1;\n }\n i = e;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n\n/**\n * `n` spaces.\n *\n * @ensures result = \" \" repeated n times — the model's Spaces\n */\nexport function spaces(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length === n\n //@ ensures forall(k: nat, k < n ==> \\result.charCodeAt(k) === 32)\n // `<= 0`, not `=== 0`: the same for a nat, and a fraction a caller slips in (outside the\n // contract) ends instead of recursing forever (Fable review 2026-11-06: spaces(0.5))\n if (n <= 0) return \"\";\n return \" \" + spaces(n - 1);\n}\n\n/**\n * A line feed, `\"\\n\"`, for proved text that spans lines: lsc emits a `\"\\n\"` escape raw, which\n * Dafny cannot parse (models/LSC-GAPS.md), so the contract pins it by code unit and the body is\n * a template literal holding the line break itself.\n *\n * @ensures result = \"\\n\" — one code unit, 10\n */\nexport function lineFeed(): string {\n //@ verify\n //@ ensures \\result.length === 1 && \\result.charCodeAt(0) === 10\n return `\n`;\n}\n\n/**\n * `s` padded on the left with spaces to `width` (JS `s.padStart(width)`).\n *\n * @ensures result = Spaces(width − |s|) + s when width > |s|, else s\n */\nexport function padLeft(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ spaces(width − |s|) + s: a hand ensures in strings.dfy, so importers'\n // axioms name no helper (models/LSC-GAPS.md). Math.max, not a ternary: at width = |s|\n // both branches agree (spaces(0) is \"\"), so `>` vs `>=` would be equivalent.\n return spaces(Math.max(width - s.length, 0)) + s;\n}\n\n/**\n * `s` padded on the right with spaces to `width` (JS `s.padEnd(width)`).\n *\n * @ensures result = s + Spaces(width − |s|) when width > |s|, else s\n */\nexport function padRight(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ s + spaces(width − |s|): a hand ensures in strings.dfy, as padLeft's.\n return s + spaces(Math.max(width - s.length, 0));\n}\n\n/**\n * An optional part of a key: `tag` then `text`, or nothing when `text` is empty, so an absent\n * part never leaves a bare tag.\n *\n * @ensures result = \"\" when text = \"\", else tag + text — exactly the model's KeyPart\n */\nexport function keyPart(tag: string, text: string): string {\n //@ verify\n //@ ensures \\result === (text === \"\" ? \"\" : tag + text)\n return text === \"\" ? \"\" : tag + text;\n}\n\n/**\n * Two texts joined by one space: the one rule behind a loader key's `<column> <direction>`, a\n * sync line's `METHOD /path` and a field's description then note.\n *\n * @ensures result = a + \" \" + b — exactly the model's SpaceJoined\n */\nexport function spaceJoined(a: string, b: string): string {\n //@ verify\n //@ ensures \\result === a + \" \" + b\n return a + \" \" + b;\n}\n\n/**\n * The first code point of `w` as text: a surrogate pair whole, else the first code unit, or \"\"\n * (Fable review 2026-11-06: an astral initial was a lone surrogate).\n *\n * @ensures exactly the model's FirstChar\n */\nexport function firstCodePoint(w: string): string {\n //@ verify\n //@ ensures \\result === ((w.length >= 2 && w.charCodeAt(0) >= 55296 && w.charCodeAt(0) <= 56319 && w.charCodeAt(1) >= 56320 && w.charCodeAt(1) <= 57343) ? w.slice(0, 2) : (w.length > 0 ? w.slice(0, 1) : \"\"))\n if (w.length >= 2) {\n const hi = w.charCodeAt(0);\n const lo = w.charCodeAt(1);\n if (hi >= 55296 && hi <= 56319 && lo >= 56320 && lo <= 57343) return w.slice(0, 2);\n }\n return w.length > 0 ? w.slice(0, 1) : \"\";\n}\n\n/**\n * An ASCII letter (A-Z, a-z) somewhere in `w` from `i` on (moved from readability.ts\n * 2026-11-06, so `readableWords`' contract can name it and importers resolve it).\n *\n * @ensures result ⟺ ∃ k ∈ [i, |w|). w[k] ∈ A-Z ∪ a-z — at i = 0 exactly the model's HasAsciiLetter\n */\nexport function hasAsciiLetterFrom(w: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases w.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < w.length && ((w.charCodeAt(k) >= 65 && w.charCodeAt(k) <= 90) || (w.charCodeAt(k) >= 97 && w.charCodeAt(k) <= 122)))\n if (i >= w.length) return false;\n const c = w.charCodeAt(i);\n if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) return true;\n return hasAsciiLetterFrom(w, i + 1);\n}\n\n/**\n * `s` with a-z uppercased and every other character kept, the mirror of `lowerAscii`: JS's\n * `toUpperCase()` also maps non-ASCII letters (ß becomes \"SS\").\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ a-z ? s[k] − 32 : s[k]) — a-z\n * raised, every other code unit unchanged; exactly the model's UpperAscii in the link\n */\nexport function upperAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 97 && s.charCodeAt(k) <= 122) ? s.charCodeAt(k) - 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 97 && c <= 122 ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".slice(c - 97, c - 96) : s.slice(0, 1);\n return head + upperAscii(s.slice(1));\n}\n","//@ backend dafny\nimport { startsWithAt } from \"./strings\";\n\n/* Substring search from an index, verified with LemmaScript → Dafny (model: models/Utils.dfy\n IncludesFrom; link: models/links/utils-includes.dfy). Its own file (moved out of strings.ts,\n 2026-11-06) so its contract can name `startsWithAt`: lsc gives an importer a helper from\n another file with that helper's contract, never one from the same file (models/LSC-GAPS.md). */\n\n/**\n * Whether `x` occurs in `s` at some index ≥ `i` (JS `s.includes(x, i)`). `i` MUST be at most\n * |s|: past the end JS clamps it to |s| (Fable review 2026-11-06), so a start there is the end.\n *\n * A loop, so its depth doesn't grow with `s` (agr-entity-graphql runs it on a whole schema's JSON).\n *\n * @requires i ≤ |s|\n * @ensures result ⟺ ∃ k. i ≤ k ≤ |s| ∧ startsWithAt(s, x, k) — exactly the model's IncludesFrom\n */\nexport function includesFrom(s: string, x: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ ensures \\result <==> exists(k: nat, i <= k && k <= s.length && startsWithAt(s, x, k))\n for (let k = i; k !== s.length + 1; k++) {\n //@ invariant i <= k && k <= s.length + 1\n //@ invariant forall(j: nat, (i <= j && j < k) ==> !startsWithAt(s, x, j))\n //@ decreases s.length + 1 - k\n if (startsWithAt(s, x, k)) return true;\n }\n return false;\n}\n","//@ backend dafny\nimport { addMillis, hours, millis, minutes, seconds, toMillis } from \"@atlas/foundation/duration\";\nimport { includesFrom } from \"@atlas/utils/includes\";\nimport { indexOfCode } from \"@atlas/utils/strings\";\nimport type { Millis, Seconds } from \"./duration\";\n\n/* The server's decisions, as pure functions verified with LemmaScript → Dafny (model:\n models/AugurServer.dfy; link: models/links/augur-server-rules.dfy). Cookies, JWT decoding,\n fetch, Redis and process.env stay in the callers, which hand over plain values. */\n\n/**\n * The siteId of a bearer's client_id claim (`<n>|<siteId>`): the text after the first \"|\", when\n * there is one and it is non-empty. The prefix is not checked.\n *\n * @ensures exactly the model's ClientIdSiteId on a string claim\n */\nexport function clientIdSiteIdOf(clientId: string): string | null {\n //@ verify\n //@ ensures indexOfCode(clientId, 124, 0) < 0 ==> \\result === null\n //@ ensures indexOfCode(clientId, 124, 0) >= 0 && indexOfCode(clientId, 124, 0) + 1 >= clientId.length ==> \\result === null\n //@ ensures indexOfCode(clientId, 124, 0) >= 0 && indexOfCode(clientId, 124, 0) + 1 < clientId.length ==> \\result === clientId.slice(indexOfCode(clientId, 124, 0) + 1)\n const k = indexOfCode(clientId, 124, 0);\n if (k < 0) return null;\n if (k + 1 >= clientId.length) return null;\n return clientId.slice(k + 1);\n}\n\n/** A session's siteId and bearer token, as minted, or refused. */\nexport type Mint = { kind: \"minted\"; siteId: string; token: string } | { kind: \"refused\" };\n\n/**\n * getSessionCredentials' mint, once the secret and the decoded session are in hand: a valid\n * siteId (augur-api's `isSiteId`, checked by the caller), a non-empty token, and the bearer's\n * client_id siteId (`\"\"` for none: `clientIdSiteIdOf` never gives `\"\"`) equal to it.\n *\n * @ensures exactly the model's MintCredentials with a secret and a decoded session\n */\nexport function mintedCredentials(\n siteIdOk: boolean,\n targetSiteId: string,\n token: string,\n bearerSiteId: string,\n): Mint {\n //@ verify\n //@ ensures siteIdOk && token !== \"\" && bearerSiteId !== \"\" && bearerSiteId === targetSiteId ==> \\result.kind === \"minted\" && \\result.siteId === targetSiteId && \\result.token === token\n //@ ensures !(siteIdOk && token !== \"\" && bearerSiteId !== \"\" && bearerSiteId === targetSiteId) ==> \\result.kind === \"refused\"\n if (!siteIdOk || token === \"\" || bearerSiteId === \"\" || bearerSiteId !== targetSiteId) {\n return { kind: \"refused\" };\n }\n return { kind: \"minted\", siteId: targetSiteId, token };\n}\n\n/**\n * Whether there is another page: from the total when one is given, else a full page.\n *\n * @ensures exactly the model's HasMore\n */\nexport function hasMoreOf(\n page: number,\n limit: number,\n total: number | undefined,\n itemCount: number,\n): boolean {\n //@ verify\n //@ ensures total !== undefined ==> \\result === ((page + 1) * limit < total)\n //@ ensures total === undefined ==> \\result === (itemCount === limit)\n if (total !== undefined) return (page + 1) * limit < total;\n return itemCount === limit;\n}\n\n/**\n * The next page's cursor: page + 1 while there is more.\n *\n * @ensures exactly the model's NextCursor given HasMore\n */\nexport function nextCursorOf(hasMore: boolean, page: number): number | undefined {\n //@ verify\n //@ ensures hasMore ==> \\result === page + 1\n //@ ensures !hasMore ==> \\result === undefined\n if (hasMore) return page + 1;\n return undefined;\n}\n\n/** The deployment environment. */\nexport type Env = \"development\" | \"staging\" | \"production\";\n\n/**\n * DEPLOYMENT_ENV first; then the server's NODE_ENV; then the browser's host (substring). A missing\n * variable is \"\".\n *\n * @ensures exactly the model's EnvOf\n */\nexport function envOf(\n deploymentEnv: string,\n isServer: boolean,\n nodeEnv: string,\n host: string,\n): Env {\n //@ verify\n //@ ensures deploymentEnv === \"dev\" ==> \\result === \"staging\"\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv === \"live\" ==> \\result === \"production\"\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv !== \"live\" && isServer ==> \\result === serverEnvOf(nodeEnv)\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv !== \"live\" && !isServer ==> \\result === hostEnvOf(host)\n if (deploymentEnv === \"dev\") return \"staging\";\n if (deploymentEnv === \"live\") return \"production\";\n if (isServer) return serverEnvOf(nodeEnv);\n return hostEnvOf(host);\n}\n\n/**\n * On the server: development only for NODE_ENV \"development\".\n *\n * @ensures result = development ⟺ nodeEnv = \"development\", else production\n */\nexport function serverEnvOf(nodeEnv: string): Env {\n //@ verify\n //@ ensures nodeEnv === \"development\" ==> \\result === \"development\"\n //@ ensures nodeEnv !== \"development\" ==> \\result === \"production\"\n return nodeEnv === \"development\" ? \"development\" : \"production\";\n}\n\n/**\n * In the browser: localhost or 127.0.0.1 anywhere in the host is development, agr-hosting.dev\n * staging, anything else production.\n *\n * @ensures exactly the model's host rule\n */\nexport function hostEnvOf(host: string): Env {\n //@ verify\n //@ ensures (includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) ==> \\result === \"development\"\n //@ ensures !(includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) && includesFrom(host, \"agr-hosting.dev\", 0) ==> \\result === \"staging\"\n //@ ensures !(includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) && !includesFrom(host, \"agr-hosting.dev\", 0) ==> \\result === \"production\"\n if (includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0))\n return \"development\";\n if (includesFrom(host, \"agr-hosting.dev\", 0)) return \"staging\";\n return \"production\";\n}\n\n/**\n * The API route's outcome for a request: \"run\" answers queryAction's data, \"run-full\"\n * queryActionRaw's full response (atlas#107).\n */\nexport type ApiOutcome =\n \"forbidden\" | \"bad-json\" | \"bad-method-path\" | \"bad-args\" | \"run\" | \"run-full\";\n\n/**\n * A present, non-empty Sec-Fetch-Site other than same-origin is refused (a missing one, `\"\"`\n * from the caller, passes).\n *\n * @ensures result ⟺ fetchSite ∉ {\"\", \"same-origin\"}\n */\nexport function isCrossOrigin(fetchSite: string): boolean {\n //@ verify\n //@ ensures \\result === (fetchSite !== \"\" && fetchSite !== \"same-origin\")\n return fetchSite !== \"\" && fetchSite !== \"same-origin\";\n}\n\n/**\n * The body's outcome: JSON, then a non-empty methodPath string, then an args array; a valid\n * body with `raw: true` (`full`) runs for the full response, any other for its data.\n *\n * @ensures exactly the model's ApiOutcomeOf past the origin check\n */\nexport function bodyOutcomeOf(\n jsonOk: boolean,\n methodPathOk: boolean,\n argsIsArray: boolean,\n full: boolean,\n): ApiOutcome {\n //@ verify\n //@ ensures !jsonOk ==> \\result === \"bad-json\"\n //@ ensures jsonOk && !methodPathOk ==> \\result === \"bad-method-path\"\n //@ ensures jsonOk && methodPathOk && !argsIsArray ==> \\result === \"bad-args\"\n //@ ensures jsonOk && methodPathOk && argsIsArray && full ==> \\result === \"run-full\"\n //@ ensures jsonOk && methodPathOk && argsIsArray && !full ==> \\result === \"run\"\n if (!jsonOk) return \"bad-json\";\n if (!methodPathOk) return \"bad-method-path\";\n if (!argsIsArray) return \"bad-args\";\n if (full) return \"run-full\";\n return \"run\";\n}\n\n/**\n * The route runs the call: either view; any other outcome is a refusal.\n *\n * @ensures exactly the model's Runs\n */\nexport function runsOf(o: ApiOutcome): boolean {\n //@ verify\n //@ ensures \\result === (o === \"run\" || o === \"run-full\")\n return o === \"run\" || o === \"run-full\";\n}\n\n/**\n * The route answers the full response (queryActionRaw), not its data.\n *\n * @ensures exactly the model's AnswersFull\n */\nexport function answersFullOf(o: ApiOutcome): boolean {\n //@ verify\n //@ ensures \\result === (o === \"run-full\")\n return o === \"run-full\";\n}\n\n/**\n * An outcome's HTTP status: 403, 400 for a bad body, 200 to run.\n *\n * @ensures exactly the model's ApiStatus\n */\nexport function apiStatusOf(o: ApiOutcome): number {\n //@ verify\n //@ ensures o === \"forbidden\" ==> \\result === 403\n //@ ensures (o === \"bad-json\" || o === \"bad-method-path\" || o === \"bad-args\") ==> \\result === 400\n //@ ensures (o === \"run\" || o === \"run-full\") ==> \\result === 200\n if (o === \"forbidden\") return 403;\n if (o === \"run\" || o === \"run-full\") return 200;\n return 400;\n}\n\n/**\n * A refusal's response text (\"\" to run).\n *\n * @ensures each refusal has its fixed text\n */\nexport function apiMessageOf(o: ApiOutcome): string {\n //@ verify\n //@ ensures o === \"forbidden\" ==> \\result === \"Forbidden: cross-origin requests not allowed\"\n //@ ensures o === \"bad-json\" ==> \\result === \"Invalid JSON body\"\n //@ ensures o === \"bad-method-path\" ==> \\result === \"Missing or invalid methodPath\"\n //@ ensures o === \"bad-args\" ==> \\result === \"Missing or invalid args array\"\n //@ ensures (o === \"run\" || o === \"run-full\") ==> \\result === \"\"\n if (o === \"forbidden\") return \"Forbidden: cross-origin requests not allowed\";\n if (o === \"bad-json\") return \"Invalid JSON body\";\n if (o === \"bad-method-path\") return \"Missing or invalid methodPath\";\n if (o === \"bad-args\") return \"Missing or invalid args array\";\n return \"\";\n}\n\n/**\n * The Redis TTL for a cache tier: none for staleTime 0, the long TTL from an hour up, else the\n * standard one. `staleTime` is React Query's `Millis`, the TTLs Redis's `Seconds`; the hour is\n * compared in milliseconds.\n *\n * @ensures exactly the model's TtlFor\n */\nexport function ttlFor(\n staleTime: Millis,\n redisTtl: Seconds,\n longRedisTtl: Seconds,\n): Seconds | null {\n //@ verify\n //@ ensures staleTime === 0 ==> \\result === null\n //@ ensures staleTime !== 0 && staleTime >= 3600000 ==> \\result === longRedisTtl\n //@ ensures staleTime !== 0 && staleTime < 3600000 ==> \\result === redisTtl\n if (staleTime === 0) return null;\n if (staleTime >= toMillis(hours(1))) return longRedisTtl;\n return redisTtl;\n}\n\n/** The Redis circuit breaker's state: consecutive failures, and when it closes (0 = closed). */\nexport interface Circuit {\n failures: number;\n openUntil: Millis;\n}\n\n/** The circuit's answer at a time: whether it is open, and its state after the check. */\nexport interface CircuitAnswer {\n open: boolean;\n next: Circuit;\n}\n\n/**\n * isCircuitOpen at `now`: closed at openUntil 0; past it, reset and closed; else open.\n *\n * @ensures exactly the model's CircuitCheck\n */\nexport function circuitCheck(c: Circuit, now: Millis): CircuitAnswer {\n //@ verify\n //@ ensures c.openUntil === 0 ==> !\\result.open && \\result.next === c\n //@ ensures c.openUntil !== 0 && now >= c.openUntil ==> !\\result.open && \\result.next.failures === 0 && \\result.next.openUntil === 0\n //@ ensures c.openUntil !== 0 && now < c.openUntil ==> \\result.open && \\result.next === c\n if (c.openUntil === 0) return { open: false, next: c };\n if (now >= c.openUntil) return { open: false, next: { failures: 0, openUntil: millis(0) } };\n return { open: true, next: c };\n}\n\n/**\n * Whether a failure count opens the circuit: five in a row.\n *\n * @ensures result ⟺ failures ≥ 5\n */\nexport function opensAt(failures: number): boolean {\n //@ verify\n //@ ensures \\result === (failures >= 5)\n return failures >= 5;\n}\n\n/**\n * A failure counts; from the threshold on the circuit opens for a minute from now.\n *\n * @ensures exactly the model's RecordFailure\n */\nexport function recordFailureOf(c: Circuit, now: Millis): Circuit {\n //@ verify\n //@ ensures \\result.failures === c.failures + 1\n //@ ensures opensAt(c.failures + 1) ==> \\result.openUntil === now + 60000\n //@ ensures !opensAt(c.failures + 1) ==> \\result.openUntil === c.openUntil\n const failures = c.failures + 1;\n if (opensAt(failures)) return { failures, openUntil: addMillis(now, toMillis(minutes(1))) };\n return { failures, openUntil: c.openUntil };\n}\n\n/**\n * A success clears the failure count and leaves openUntil.\n *\n * @ensures exactly the model's RecordSuccess\n */\nexport function recordSuccessOf(c: Circuit): Circuit {\n //@ verify\n //@ ensures \\result.failures === 0 && \\result.openUntil === c.openUntil\n return { failures: 0, openUntil: c.openUntil };\n}\n\n/**\n * authorize's verified flag: exactly the text \"true\".\n *\n * @ensures result ⟺ s = \"true\"\n */\nexport function verifiedFlag(s: string): boolean {\n //@ verify\n //@ ensures \\result === (s === \"true\")\n return s === \"true\";\n}\n\n/**\n * reCAPTCHA passes only with a secret, an ok response and the reply's optional `success` exactly\n * true (the score is not read).\n *\n * @ensures exactly the model's RecaptchaOk, success read as `=== true`\n */\nexport function recaptchaOk(\n hasSecret: boolean,\n httpOk: boolean,\n success: boolean | undefined,\n): boolean {\n //@ verify\n //@ ensures \\result === (hasSecret && httpOk && success === true)\n return hasSecret && httpOk && success === true;\n}\n\n/**\n * A customer id is used only above 0; anything else (NaN included, at the caller) is 0.\n *\n * @ensures result = n when n > 0, else 0\n */\nexport function positiveOrZero(n: number): number {\n //@ verify\n //@ ensures n > 0 ==> \\result === n\n //@ ensures n <= 0 ==> \\result === 0\n return n > 0 ? n : 0;\n}\n\n/**\n * The category page size: 24 when none (or 0) is given.\n *\n * @ensures exactly the model's ItemsLimit, a missing limit as 0\n */\nexport function itemsLimitOf(limit: number | undefined): number {\n //@ verify\n //@ ensures (limit === undefined || limit === 0) ==> \\result === 24\n //@ ensures limit !== undefined && limit !== 0 ==> \\result === limit\n if (limit === undefined) return 24;\n if (limit === 0) return 24;\n return limit;\n}\n\n/**\n * The cross-site opt-in as configured (`auth.crossSite`): on only when set to true, so a site\n * that says nothing stays off (atlas#105).\n *\n * @ensures exactly the model's CrossSiteOf\n */\nexport function crossSiteOf(flag: boolean | undefined): boolean {\n //@ verify\n //@ ensures \\result === (flag === true)\n return flag === true;\n}\n\n/**\n * Whether queryAction looks for a cross-site session (imports next/headers and reads the\n * cookie): only on a site that opted in and has a secret. Every other site never reads cookies\n * here, so its pages can render statically (atlas#105).\n *\n * @ensures exactly the model's ReadsSession\n */\nexport function readsSession(crossSite: boolean, hasSecret: boolean): boolean {\n //@ verify\n //@ ensures \\result === (crossSite && hasSecret)\n return crossSite && hasSecret;\n}\n\n/**\n * The target siteId authorize writes into the session: the sign-in's `siteId` only on an\n * opted-in site, and only when it is not empty (atlas#105).\n *\n * @ensures exactly the model's SignInTarget\n */\nexport function signInTarget(crossSite: boolean, siteId: string | undefined): string | undefined {\n //@ verify\n //@ ensures !crossSite ==> \\result === undefined\n //@ ensures crossSite && siteId === undefined ==> \\result === undefined\n //@ ensures crossSite && siteId !== undefined && siteId === \"\" ==> \\result === undefined\n //@ ensures crossSite && siteId !== undefined && siteId !== \"\" ==> \\result === siteId\n if (!crossSite) return undefined;\n if (siteId === undefined) return undefined;\n if (siteId === \"\") return undefined;\n return siteId;\n}\n\n/** How queryAction resolves its client. */\nexport type Resolution = \"scoped\" | \"global\" | \"uninit\";\n\n/**\n * resolveClient: scoped when credentials minted and a scoped client was made; else the global\n * client when one is registered (also for a valid session without a factory); else none.\n *\n * @ensures exactly the model's ResolveClient\n */\nexport function resolutionOf(minted: boolean, scopedMade: boolean, hasGlobal: boolean): Resolution {\n //@ verify\n //@ ensures minted && scopedMade ==> \\result === \"scoped\"\n //@ ensures !(minted && scopedMade) && hasGlobal ==> \\result === \"global\"\n //@ ensures !(minted && scopedMade) && !hasGlobal ==> \\result === \"uninit\"\n if (minted && scopedMade) return \"scoped\";\n return hasGlobal ? \"global\" : \"uninit\";\n}\n\n/** The scoped-client slot's decision. */\nexport type SlotDecision = \"hit\" | \"mint\" | \"no-client\";\n\n/**\n * getOrCreateScopedClient's single slot: a hit when it holds this key; else a new client when a\n * factory is registered; else none. An empty slot is \"\" at the caller, which no key equals (a\n * key holds a NUL).\n *\n * @ensures exactly the model's SlotDecisionOf\n */\nexport function slotDecisionOf(slotKey: string, key: string, hasFactory: boolean): SlotDecision {\n //@ verify\n //@ ensures slotKey === key ==> \\result === \"hit\"\n //@ ensures slotKey !== key && hasFactory ==> \\result === \"mint\"\n //@ ensures slotKey !== key && !hasFactory ==> \\result === \"no-client\"\n if (slotKey === key) return \"hit\";\n return hasFactory ? \"mint\" : \"no-client\";\n}\n\n/**\n * parseMethodPath: a non-empty path, in the allowlist when one is registered (permissive by\n * default); `listed` is the caller's Set lookup.\n *\n * @ensures exactly the model's ApprovePath\n */\nexport function approvePath(path: string, hasAllowlist: boolean, listed: boolean): boolean {\n //@ verify\n //@ ensures \\result === (path !== \"\" && (!hasAllowlist || listed))\n return path !== \"\" && (!hasAllowlist || listed);\n}\n\n/**\n * queryAction caches a call only through a wrapper, and only for a read leaf (augur-core's\n * `isReadMethod`, checked by the caller).\n *\n * @ensures exactly the model's UsesCache\n */\nexport function usesCache(hasWrapper: boolean, isRead: boolean): boolean {\n //@ verify\n //@ ensures \\result === (hasWrapper && isRead)\n return hasWrapper && isRead;\n}\n\n/**\n * The Auth.js session cookie decodeSessionJwt reads, and the salt it decodes with: the HTTPS\n * cookie when the request has one, else the plain one.\n *\n * @ensures exactly the model's SessionCookieName\n */\nexport function sessionCookieName(hasSecure: boolean): string {\n //@ verify\n //@ ensures hasSecure ==> \\result === \"__Secure-authjs.session-token\"\n //@ ensures !hasSecure ==> \\result === \"authjs.session-token\"\n return hasSecure ? \"__Secure-authjs.session-token\" : \"authjs.session-token\";\n}\n\n/** Which client a bounded call runs on (atlas#106). */\nexport type ClientChoice = \"client\" | \"view\" | \"refuse\";\n\n/**\n * queryActionWith's client: today's client with no options; else the client's `withRequest`\n * view, refused when the client has none (a call asked to be bounded never runs unbounded).\n *\n * @ensures exactly the model's ClientFor\n */\nexport function clientFor(hasOptions: boolean, hasWithRequest: boolean): ClientChoice {\n //@ verify\n //@ ensures !hasOptions ==> \\result === \"client\"\n //@ ensures hasOptions && hasWithRequest ==> \\result === \"view\"\n //@ ensures hasOptions && !hasWithRequest ==> \\result === \"refuse\"\n if (!hasOptions) return \"client\";\n return hasWithRequest ? \"view\" : \"refuse\";\n}\n\n/**\n * The scoped cache prefix: the session's siteId and \":\".\n *\n * @ensures exactly the model's ScopedPrefix\n */\nexport function scopedPrefix(siteId: string): string {\n //@ verify\n //@ ensures \\result === siteId + \":\"\n return siteId + \":\";\n}\n\n/**\n * withServerCache caches when the TTL is not 0 (missing or NaN is 0 at the caller; a `Seconds`\n * is never negative).\n *\n * @ensures exactly the model's ShouldCache\n */\nexport function shouldCache(ttl: Seconds): boolean {\n //@ verify\n //@ ensures \\result === (ttl !== 0)\n return ttl !== 0;\n}\n\n/**\n * The TTL a server cache call uses: a missing one (undefined or NaN, which the caller reads) is 0,\n * as `!redisTtl` had it.\n *\n * @ensures exactly the model's CacheTtl\n */\nexport function cacheTtlOf(missing: boolean, ttl: Seconds): Seconds {\n //@ verify\n //@ ensures \\result === (missing ? 0 : ttl)\n return missing ? seconds(0) : ttl;\n}\n\n/**\n * getInvMastDoc's positional uid: kept above 0, else none.\n *\n * @ensures result = uid when uid > 0, else undefined\n */\nexport function docUidOf(uid: number): number | undefined {\n //@ verify\n //@ ensures uid > 0 ==> \\result === uid\n //@ ensures uid <= 0 ==> \\result === undefined\n if (uid > 0) return uid;\n return undefined;\n}\n\n/**\n * The positional itemId is used only at uid 0 and when non-empty (\"\" for none, at the caller).\n *\n * @ensures result ⟺ uid = 0 ∧ itemId ≠ \"\"\n */\nexport function takesItemId(uid: number, itemId: string): boolean {\n //@ verify\n //@ ensures \\result === (uid === 0 && itemId !== \"\")\n return uid === 0 && itemId !== \"\";\n}\n\n/**\n * A doc call needs a uid (truthy at the caller) or a non-empty itemId.\n *\n * @ensures result ⟺ uidSet ∨ itemId ≠ \"\"\n */\nexport function hasDocKey(uidSet: boolean, itemId: string): boolean {\n //@ verify\n //@ ensures \\result === (uidSet || itemId !== \"\")\n return uidSet || itemId !== \"\";\n}\n\n/**\n * The configured payments mode, \"live\" by default.\n *\n * @ensures result = configured ?? \"live\"\n */\nexport function configuredModeOf(configured: string | undefined): string {\n //@ verify\n //@ ensures configured === undefined ==> \\result === \"live\"\n //@ ensures configured !== undefined ==> \\result === configured\n if (configured === undefined) return \"live\";\n return configured;\n}\n","//@ backend dafny\n\n/* Cache key for the per-request scoped SDK client (`sdk-client-store.ts`\n `getOrCreateScopedClient`). Verified with LemmaScript → Dafny (`pnpm proofs`; model:\n models/AugurServer.dfy `ScopedClientKey`, whose `ScopedClientKeyInjective` proves that for two\n siteIds with no NUL character, equal keys mean equal siteIds AND equal tokens, so two\n credential pairs never share a cached client; link:\n models/links/augur-server-scoped-client-key.dfy). Only the siteId needs to be NUL-free; the\n token may contain anything. Not proved: that every siteId reaching this function is NUL-free.\n That rests on `getSessionCredentials` (query-action.ts), the only mint point, refusing any\n siteId that fails augur-api's `isSiteId` (`[a-z0-9_-]+`, proved in augur-api), which is\n tested. */\n\n/** Character code of the separator; no siteId contains it. */\nconst SEPARATOR_CODE = 0;\n\n/** `siteId` has no NUL character, so the first NUL in a key marks where the siteId ends. */\nfunction hasNoSeparator(siteId: string): boolean {\n //@ verify\n //@ ensures \\result === !siteId.includes(String.fromCharCode(0))\n return !siteId.includes(String.fromCharCode(SEPARATOR_CODE));\n}\n\n/** The key `siteId + \"\\0\" + token`, or null (the refusal) when the siteId has a NUL. */\nfunction scopedClientKeyOf(siteId: string, token: string): string | null {\n //@ verify\n //@ ensures hasNoSeparator(siteId) ==> \\result === siteId + String.fromCharCode(0) + token\n //@ ensures !hasNoSeparator(siteId) ==> \\result === null\n if (!hasNoSeparator(siteId)) return null;\n return siteId + String.fromCharCode(SEPARATOR_CODE) + token;\n}\n\n/**\n * The key `siteId + \"\\0\" + token`. Callers MUST pass a siteId with no NUL character\n * (`getSessionCredentials` enforces `isSiteId`); with that, distinct pairs give distinct keys.\n * A siteId with a NUL throws instead of returning a key that could collide.\n *\n * @throws TypeError when `siteId` contains a NUL character\n */\nexport function scopedClientKey(siteId: string, token: string): string {\n const key = scopedClientKeyOf(siteId, token);\n if (key === null) {\n throw new TypeError(\"scopedClientKey: siteId must not contain a NUL character\");\n }\n return key;\n}\n","/**\n * Lightweight getter/setter for the raw SDK client instance, cache wrapper,\n * auth secret, client factory, and scoped client cache.\n *\n * queryAction resolves method paths on the SDK client directly (not on\n * SiteActions). This ensures the proxy pattern works end-to-end: the\n * proxy generates SDK namespace paths (e.g. \"pricing.priceEngine.get\")\n * which match the SDK client structure.\n *\n * The cache wrapper is a function registered by createServerSite() that\n * wraps SDK calls with Redis caching. It captures withServerCache + config\n * in its closure, so queryAction can use it without importing heavy deps.\n *\n * The auth secret, client factory, and scoped cache wrapper support\n * per-request session credentials for multi-tenant apps. queryAction\n * decodes the JWT from request cookies and creates scoped SDK clients\n * when the session contains a targetSiteId + token.\n *\n * This module has ZERO imports from actions/site, cache/, or any factory.\n * Same isolation constraints as site-actions-store.ts.\n */\n\nimport { approvePath, slotDecisionOf } from \"./rules\";\nimport { scopedClientKey } from \"./scoped-client-key\";\n\n/** Function that wraps an SDK call with server-side caching. */\nexport type SdkCallWrapper = (\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that wraps an SDK call with server-side caching using a specific prefix. */\nexport type ScopedCacheWrapper = (\n prefix: string,\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that creates a scoped SDK client with different credentials. */\nexport type ClientFactory = (siteId: string, bearerToken: string) => unknown;\n\ndeclare const SessionSiteIdBrand: unique symbol;\ndeclare const SessionBearerTokenBrand: unique symbol;\ndeclare const SessionCredentialsBrand: unique symbol;\ndeclare const ApprovedMethodPathBrand: unique symbol;\n\n/**\n * Site identifier extracted from a validated Auth.js session JWT cookie.\n *\n * Intended to be minted only by `getSessionCredentials` in query-action.ts.\n *\n * Brand strength: code-review signal, not type-system enforcement. TypeScript\n * allows `value as SessionSiteId` casts, so audit `as SessionSiteId` usages\n * to catch unintended mints — there should be exactly one, at the JWT mint\n * point.\n */\nexport type SessionSiteId = string & { readonly [SessionSiteIdBrand]: true };\n\n/**\n * Bearer token extracted from a validated Auth.js session JWT cookie.\n * Same intended-mint and brand-strength caveat as {@link SessionSiteId}.\n */\nexport type SessionBearerToken = string & { readonly [SessionBearerTokenBrand]: true };\n\n/**\n * Paired session credentials. Bundles `siteId` and `token` from the same\n * validated session into one value so downstream functions can accept the\n * pair as a unit, instead of two separate parameters that callers might\n * accidentally mix across sessions.\n *\n * Intended to be minted only by `getSessionCredentials` in query-action.ts,\n * which performs the cross-check that the bearer's `client_id` siteId\n * matches `targetSiteId`. Anything that holds a `SessionCredentials` *was*\n * cross-checked at mint time — provided the value came through that mint\n * and not via a cast.\n *\n * Brand strength: same code-review signal as the field brands. `value as\n * SessionCredentials` compiles. Audit `as SessionCredentials` usages — there\n * should be exactly one, in `getSessionCredentials`.\n */\nexport type SessionCredentials = {\n readonly siteId: SessionSiteId;\n readonly token: SessionBearerToken;\n readonly [SessionCredentialsBrand]: true;\n};\n\n/**\n * SDK method path validated against the registered allowlist.\n *\n * Intended to be minted only by `parseMethodPath` below. Functions that walk\n * the path into the SDK client (notably `resolveMethod`) demand this type\n * so that an unvalidated string flowing into the walker is a compile error\n * for code that respects the convention.\n *\n * Brand strength: code-review signal. `value as ApprovedMethodPath` compiles.\n * Audit `as ApprovedMethodPath` usages — there should be one, in\n * `parseMethodPath`.\n *\n * Scope of validation: this is a *site-level surface restriction*, not a\n * security boundary. augur-api is the auth authority; the allowlist limits\n * what the application's proxy will forward to the SDK, not what tokens are\n * permitted to do. Useful for narrowing same-origin attack surface (XSS,\n * malicious bundled deps); not a substitute for API-level authorization.\n */\nexport type ApprovedMethodPath = string & { readonly [ApprovedMethodPathBrand]: true };\n\nconst g = globalThis as unknown as {\n __augur_sdk_client?: unknown;\n __augur_sdk_call_wrapper?: SdkCallWrapper;\n __augur_auth_secret?: string;\n __augur_cross_site?: boolean;\n __augur_client_factory?: ClientFactory;\n __augur_scoped_cache_wrapper?: ScopedCacheWrapper;\n __augur_allowed_method_paths?: Set<string>;\n};\n\nlet _cachedClient: unknown = null;\nlet _cachedWrapper: SdkCallWrapper | null = null;\nlet _cachedAuthSecret: string | null = null;\nlet _cachedCrossSite = false;\nlet _cachedClientFactory: ClientFactory | null = null;\nlet _cachedScopedCacheWrapper: ScopedCacheWrapper | null = null;\nlet _scopedClient: { key: string; client: unknown } | null = null;\nlet _allowedMethodPaths: Set<string> | null = null;\n\n/** Register the raw SDK client instance. Called by createServerSite(). */\nexport function registerSdkClient(client: unknown): void {\n _cachedClient = client;\n g.__augur_sdk_client = client;\n}\n\n/** Returns the registered SDK client, or null if not yet registered. */\nexport function getSdkClientOrNull(): unknown {\n const client = g.__augur_sdk_client ?? _cachedClient;\n if (client) {\n if (!g.__augur_sdk_client) {\n g.__augur_sdk_client = client;\n }\n return client;\n }\n return null;\n}\n\n/**\n * Register a cache wrapper for SDK calls. Called by createServerSite().\n * The wrapper captures withServerCache + config in its closure so that\n * queryAction can use Redis caching without importing heavy deps.\n */\nexport function registerSdkCallWrapper(wrapper: SdkCallWrapper): void {\n _cachedWrapper = wrapper;\n g.__augur_sdk_call_wrapper = wrapper;\n}\n\n/** Returns the registered cache wrapper, or null if not registered. */\nexport function getSdkCallWrapper(): SdkCallWrapper | null {\n return g.__augur_sdk_call_wrapper ?? _cachedWrapper ?? null;\n}\n\n/** Register the auth secret for JWT decoding. Called by createServerSite(). */\nexport function registerAuthSecret(secret: string): void {\n _cachedAuthSecret = secret;\n g.__augur_auth_secret = secret;\n}\n\n/** Returns the registered auth secret, or null if not registered. */\nexport function getAuthSecret(): string | null {\n return g.__augur_auth_secret ?? _cachedAuthSecret ?? null;\n}\n\n/**\n * Register the cross-site opt-in (`auth.crossSite`, through rules.crossSiteOf). Called by\n * createServerSite(). The ONE source both queryAction's session read and authorize's sign-in\n * target read (models/AugurServer.dfy, \"the cross-site opt-in\", atlas#105).\n */\nexport function registerCrossSite(on: boolean): void {\n _cachedCrossSite = on;\n g.__augur_cross_site = on;\n}\n\n/** Whether this site opted in to cross-site sessions; false unless registered. */\nexport function getCrossSite(): boolean {\n return g.__augur_cross_site ?? _cachedCrossSite;\n}\n\n/** Register a factory that creates scoped SDK clients. Called by createServerSite(). */\nexport function registerClientFactory(factory: ClientFactory): void {\n _cachedClientFactory = factory;\n g.__augur_client_factory = factory;\n}\n\n/** Returns the registered client factory, or null if not registered. */\nexport function getClientFactory(): ClientFactory | null {\n return g.__augur_client_factory ?? _cachedClientFactory ?? null;\n}\n\n/** Register a scoped cache wrapper that accepts a prefix. Called by createServerSite(). */\nexport function registerScopedCacheWrapper(wrapper: ScopedCacheWrapper): void {\n _cachedScopedCacheWrapper = wrapper;\n g.__augur_scoped_cache_wrapper = wrapper;\n}\n\n/** Returns the registered scoped cache wrapper, or null if not registered. */\nexport function getScopedCacheWrapper(): ScopedCacheWrapper | null {\n return g.__augur_scoped_cache_wrapper ?? _cachedScopedCacheWrapper ?? null;\n}\n\n/**\n * Returns a cached scoped client for the given credentials, or creates one\n * via the registered factory. Caches the last credential pair so that\n * multiple queryAction calls in the same request reuse the same client.\n *\n * Accepts `SessionCredentials` (a branded paired type) rather than two raw\n * strings: well-behaved callers pass the pair as a unit, eliminating the\n * \"siteId from session A combined with token from session B\" mistake at\n * the type level — see {@link SessionCredentials} brand-strength caveat.\n * The factory itself still receives strings (its signature is user-facing API).\n *\n * ## Trust\n *\n * @trusted credentials // the SessionCredentials brand carries the\n * // bearer/session siteId cross-check discharged at\n * // mint time by `getSessionCredentials`. This\n * // function does NOT re-validate; if a non-mint\n * // path produces a SessionCredentials value (via\n * // `as` cast), this function will materialise a\n * // client for whatever siteId + token are present\n * // in the value. Audit `as SessionCredentials`\n * // usages — there should be exactly one, in\n * // getSessionCredentials.\n *\n * ## Decision (Property)\n *\n * let key = `${credentials.siteId}\\0${credentials.token}` in\n * result(credentials) =\n * _scopedClient.client when _scopedClient?.key = key // cache hit\n * factory(siteId, token) when factory ≠ null // mint + cache\n * null when factory = null // uninitialised\n *\n * Three outcomes. Throws only if `credentials.siteId` contains a NUL\n * (`scopedClientKey`), which the mint point rules out by `isSiteId`, so it\n * is reachable only through an `as SessionCredentials` cast. Side effect on\n * the mint path only:\n * `_scopedClient` is replaced with `{key, client}` so the next call with\n * the same credentials hits the cached branch. Minting implicitly evicts\n * the previous `_scopedClient` value (single-slot semantics — see invariant).\n *\n * ## Invariant — null-byte key separator (machine-checked)\n *\n * The key is `scopedClientKey(siteId, token)` = `siteId + \"\\0\" + token`\n * (`scoped-client-key.ts`). Dafny proves (`ScopedClientKeyInjective`) that\n * for two NUL-free siteIds, equal keys mean equal siteIds and equal tokens,\n * so the cache cannot hand one credential pair another pair's client. Only\n * the siteId has to be NUL-free; the token may contain anything.\n *\n * The precondition is enforced, not assumed: `getSessionCredentials`, the\n * only mint point, refuses any `targetSiteId` that fails augur-api's\n * `isSiteId` (`[a-z0-9_-]+`, machine-checked in augur-api), and\n * `scopedClientKey` throws on a NUL rather than return a key that could\n * collide. What is NOT proved: that no other code path casts a value to\n * `SessionCredentials` (see the Trust note above).\n *\n * Do NOT change the separator to a character that could appear in a\n * siteId; the proof is stated for NUL and would have to be redone.\n *\n * ## Invariant — single-slot cache (eviction is implicit)\n *\n * `_scopedClient` holds at most one entry. Minting a client for\n * credentials A AFTER credentials B were cached evicts B unrecoverably;\n * a later request with credentials B will call the factory again rather\n * than retrieving the previously-minted client.\n *\n * This is intentional. Scoped clients are per-request shortcuts; the\n * cache exists to let multiple queryAction calls within a single request\n * share an SDK client without re-running the factory. Cross-request\n * caching is NOT a goal — Next.js may or may not preserve module state\n * across invocations, so any retention beyond the single slot is\n * best-effort and MUST NOT be relied upon for correctness.\n *\n * A future refactor to multi-slot LRU would change this contract:\n * per-credential client identity becomes ambiguous across requests, and\n * eviction policy becomes security-relevant (e.g. oldest-out could re-mint\n * a client immediately after a credential rotation, surfacing stale\n * permissions to the next caller). Do not multi-slot this without\n * re-deriving the contract — particularly the relationship to credential\n * rotation and bearer-token revocation in augur-api.\n *\n * ## Postcondition — identity, not transformation\n *\n * result ≠ null ⟹ result is referentially identical to the value the\n * factory returned for the matching credentials.\n *\n * The cache stores and serves the factory's exact return value. It does\n * not wrap, transform, proxy, or copy the client. Consumers that mutate\n * the returned client (e.g. setting per-request properties on a singleton\n * field) will observe the mutation on subsequent cache hits within the\n * same request — by design.\n */\nexport function getOrCreateScopedClient(credentials: SessionCredentials): unknown {\n const { siteId, token } = credentials;\n const key = scopedClientKey(siteId, token);\n const factory = g.__augur_client_factory ?? _cachedClientFactory;\n const decision = slotDecisionOf(_scopedClient?.key ?? \"\", key, !!factory);\n if (decision === \"hit\") return _scopedClient!.client;\n if (decision === \"no-client\") return null;\n\n const client = factory!(siteId, token);\n _scopedClient = { key, client };\n return client;\n}\n\n/**\n * Register one or more SDK method paths the application is permitted to call\n * through `queryAction`. Subsequent calls accumulate (idempotent on repeats).\n *\n * This is *site-level surface restriction*, not security. augur-api remains\n * the auth authority; this primitive lets a site narrow its proxy's surface\n * to the methods its UI actually wires up. Useful as defense-in-depth against\n * same-origin XSS or compromised bundled deps POSTing arbitrary methodPaths\n * to `/api/augur` — those calls will hit augur-api with the user's bearer\n * (which augur-api will allow if the bearer is authorized), but the allowlist\n * stops them from leaving the proxy in the first place.\n *\n * Permissive default: if `registerAllowedMethodPaths` is never called, all\n * non-empty paths pass — the proxy behaves as a transparent forwarder, which\n * is the package's design intent. Sites that want surface restriction opt in\n * by calling this function.\n */\nexport function registerAllowedMethodPaths(paths: readonly string[]): void {\n if (_allowedMethodPaths === null) {\n _allowedMethodPaths = new Set();\n g.__augur_allowed_method_paths = _allowedMethodPaths;\n }\n for (const p of paths) _allowedMethodPaths.add(p);\n}\n\n/**\n * Returns true if the application has registered an allowlist via\n * {@link registerAllowedMethodPaths}. When false, `parseMethodPath` operates\n * in permissive mode (any non-empty string passes).\n */\nexport function isMethodPathAllowlistRegistered(): boolean {\n return (g.__augur_allowed_method_paths ?? _allowedMethodPaths) !== null;\n}\n\n/**\n * Validate a candidate method path against the registered allowlist.\n *\n * - Returns the branded value if the path is a non-empty string AND\n * (no allowlist is registered OR the path is in the allowlist).\n * - Returns null if the path is not a non-empty string, or if an allowlist\n * has been registered and the path is not in it.\n *\n * The brand on the return type is the only way internal code can produce an\n * `ApprovedMethodPath`. Functions that walk the path into the SDK should\n * accept `ApprovedMethodPath`, forcing the caller to discharge the validation.\n */\nexport function parseMethodPath(candidate: unknown): ApprovedMethodPath | null {\n if (typeof candidate !== \"string\") return null;\n const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;\n const listed = allowed !== null && allowed.has(candidate);\n if (!approvePath(candidate, allowed !== null, listed)) return null;\n return candidate as ApprovedMethodPath;\n}\n\n/** Clears the registered SDK client, wrapper, and session stores. Used in tests only. @internal */\nexport function clearSdkClient(): void {\n _cachedClient = null;\n _cachedWrapper = null;\n _cachedAuthSecret = null;\n _cachedCrossSite = false;\n _cachedClientFactory = null;\n _cachedScopedCacheWrapper = null;\n _scopedClient = null;\n _allowedMethodPaths = null;\n g.__augur_sdk_client = undefined;\n g.__augur_sdk_call_wrapper = undefined;\n g.__augur_auth_secret = undefined;\n g.__augur_cross_site = undefined;\n g.__augur_client_factory = undefined;\n g.__augur_scoped_cache_wrapper = undefined;\n g.__augur_allowed_method_paths = undefined;\n}\n"],"mappings":";AA4BO,SAAS,QAAQ,GAAoB;AAK1C,SAAO;AACT;AAOO,SAAS,QAAQ,GAAoB;AAK1C,SAAQ,IAAI;AACd;AAOO,SAAS,MAAM,GAAoB;AAKxC,SAAQ,IAAI;AACd;AAoBO,SAAS,OAAO,GAAmB;AAKxC,SAAO;AACT;AAOO,SAAS,SAAS,GAAoB;AAI3C,SAAQ,IAAI;AACd;AAqBO,SAAS,UAAU,GAAW,GAAmB;AAItD,SAAQ,IAAI;AACd;;;AC9FO,SAAS,OAAO,GAAW,GAAmB;AAInD,SAAO,KAAK,KAAK,IAAI,EAAE,SAAS,EAAE,WAAW,CAAC,IAAI;AACpD;AA6NO,SAAS,YAAY,GAAW,MAAc,MAAsB;AASzE,QAAM,IAAI,OAAO,GAAG,IAAI;AACxB,MAAI,MAAM,KAAM,QAAO;AACvB,MAAI,MAAM,GAAI,QAAO;AACrB,SAAO,YAAY,GAAG,MAAM,OAAO,CAAC;AACtC;AA0FO,SAAS,aAAa,GAAW,GAAW,KAAsB;AAOvE,QAAM,KAAK,KAAK,IAAI,KAAK,EAAE,MAAM;AAGjC,SAAO,EAAE,MAAM,IAAI,KAAK,IAAI,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM;AAC5D;;;ACjWO,SAAS,aAAa,GAAW,GAAW,GAAoB;AAKrE,WAAS,IAAI,GAAG,MAAM,EAAE,SAAS,GAAG,KAAK;AAIvC,QAAI,aAAa,GA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