@relyon/kit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
package/dist/kit.js ADDED
@@ -0,0 +1,1309 @@
1
+ import { publicUrlFromEnv } from "./kit-environment.js";
2
+ import { CHANNEL_PATH, LEGACY_WEBHOOK_SIGNATURE_HEADER, PAYMENT_SESSIONS_PATH, WEBHOOK_SIGNATURE_HEADER } from "./wire-names.js";
3
+ import { DEVELOPER_HINT, WAITING_STATUS, WAITING_STATUS_HEADER, WAITING_TEXT_MARKER, setupError, waitingResponse, withWaitingXmlMarker } from "./waiting.js";
4
+ import { placeholderApiKey, usableApiKey, usableTestKey } from "./api-key.js";
5
+ import { TEST_CHECKOUT_PATH, handleTestCheckout } from "./test-checkout.js";
6
+ import { orderConfirmation, orderRefusal, renderOrderConfirmation, renderOrderRefusal } from "./confirmation.js";
7
+ import { describeError } from "./relyon-cart-tokens.js";
8
+ import { decide, identifyAgent, verifiedAgentSignal } from "./identify.js";
9
+ import { AgentSignatureVerifier } from "./signatures.js";
10
+ import { WebMcpCheckouts, refusalFor } from "./webmcp.js";
11
+ import { CatalogHolder, syncCatalog } from "./catalog.js";
12
+ import { StoreCatalogReads } from "./catalog-reads.js";
13
+ import { StoreFeedReads } from "./feeds.js";
14
+ import { mergeAiRobots } from "./robots.js";
15
+ import { SealedCartTokens } from "./cart-tokens.js";
16
+ import { AgentRefusedError, CHANNEL_FOR, PAY_CHARGE_NEUTRAL_NOTE, PaymentOutcomeUnknownError, PaymentUnavailableError, chargeNeutralGateMessage, paymentIdempotencyKey, createCardFields, createPayment, isPaymentSession, landing, } from "./checkout.js";
17
+ import { DEFAULT_PATHS } from "./context.js";
18
+ import { DiscoveryReads, feedLabel, jsonLdScript, llmsTxt, productJsonLd, productListJsonLd, productSitemap } from "./discovery.js";
19
+ import { agentCard } from "./agent-card.js";
20
+ import { publicUrlOrigin, requestUrl } from "./public-origin.js";
21
+ import { isLoopbackHostname, isPreviewHostname, isUnspecifiedHostname, TEST_PREVIEW_HEADER, testHostnames } from "./preview-hosts.js";
22
+ import { AgentEventQueue, requestFacts } from "./events.js";
23
+ import { McpEndpoint, mcpCheckoutCall, mcpRefusal } from "./mcp.js";
24
+ import { reportFulfillment } from "./orders.js";
25
+ import { ensureDomain, readStorePolicies, replaceStorePolicies, verifyDomain, } from "./setup.js";
26
+ import { checkoutSessionPath, routeAcp, routeUcp, inputParsers } from "./protocol-inputs.js";
27
+ import { refusal, mcpErrorBody, paymentOutcomeUnknown } from "./refusals.js";
28
+ import { markHandoffOrderPending, orderPendingFor, relayStep } from "./relay.js";
29
+ import { handoffPaymentKey, noteStorePaymentCharging, orderReferencePaymentKey, rememberStorePayment, rememberStorePaymentUnlessStronger, storePaymentRecord, storePaymentStanding, } from "./store-payments.js";
30
+ import { withoutNothingChargedClaims } from "./charge-claims.js";
31
+ import { orderPendingCheckout, orderPendingError, ORDER_PENDING_RETRY_AFTER, PAY_ORDER_PENDING_EARLIER_MESSAGE, PAY_ORDER_PENDING_MESSAGE } from "./order-pending.js";
32
+ import { RelyonGateway, RelyonUnavailableError, liveModeFor } from "./relyon.js";
33
+ import { assertLiveStoreUrls } from "./live.js";
34
+ import { isLoopbackPolicyUrl, normalizeStorePolicies, planStorePolicySync, policyReplacement } from "./policies.js";
35
+ import { AgentRulesCache, DOCTOR_ACKNOWLEDGEMENT_HEADER } from "./rules.js";
36
+ import { MemoryCheckoutStateStore } from "./state.js";
37
+ import { consoleLogger } from "./types.js";
38
+ import { isRecord, jsonResponse, randomId, textResponse, tryParseJson } from "./util.js";
39
+ import { randomBytes } from "node:crypto";
40
+ import { CART_TRANSFER_PARAM, TransferTokens, cartTransferState, catalogProducts, handleCartTransfer, transferLanding } from "./cart-transfer.js";
41
+ import { UCP_2026_04_08, UCP_2026_04_08_PROFILE_PATH, UCP_2026_04_08_SEGMENT, UCP_CURRENT_VERSION, currentProfile, profile20260408 } from "./ucp-versions.js";
42
+ /** Printed once at startup when `paymentCartFormat: "server-legacy"` is configured. */
43
+ export const SERVER_LEGACY_WARNING = "paymentCartFormat \"server-legacy\" is deprecated: Relyon accepts the contract Cart on payments. Remove paymentCartFormat from createStoreKit (the default \"contract\" is right), then restart.";
44
+ /** How long an unfinished order claim holds by default (see `orderClaimLeaseMs`). */
45
+ export const DEFAULT_ORDER_CLAIM_LEASE_MS = 2 * 60 * 1000;
46
+ /**
47
+ * The store kit: everything an agent or shopper reaches on the store's own
48
+ * domain that involves Relyon. The store supplies `priceCart` and
49
+ * `createOrder`; the kit does the rest.
50
+ */
51
+ export class StoreKit {
52
+ options;
53
+ gateway;
54
+ events;
55
+ rules;
56
+ catalog;
57
+ paths;
58
+ cartTokens;
59
+ /** Whether UCP cart transfer runs (see `StoreKitOptions.cartTransfer`). */
60
+ cartTransfer;
61
+ transferTokens;
62
+ maxBodyBytes;
63
+ /** The local agent-signature verifier; null when `agents.verify` is false. */
64
+ verifier;
65
+ /** WebMCP checkouts for the store's checkout page. */
66
+ webmcp;
67
+ identities = new WeakMap();
68
+ ctx;
69
+ discovery;
70
+ catalogReads;
71
+ feeds;
72
+ mcp;
73
+ hostnames;
74
+ /** The origin of `store.publicUrl`, when set. */
75
+ configuredOrigin;
76
+ chatgptChannel;
77
+ /** The validated `policies` option. */
78
+ policies;
79
+ logger;
80
+ now;
81
+ started;
82
+ /** The usable rly_test_ key in Test (signs test-checkout proofs); undefined in Live or without one. */
83
+ testKey;
84
+ testCheckoutNonces = new Map();
85
+ testCheckoutRuns = new Map();
86
+ /**
87
+ * True when this kit runs in Live mode: the explicit `relyon.live: true`
88
+ * opt-in with a Live key. Never inferred from the key prefix alone.
89
+ */
90
+ get livemode() {
91
+ return this.gateway.livemode;
92
+ }
93
+ /** Show this on the checkout page. Restart with real server configuration to activate; no rebuild needed. */
94
+ get checkoutStatus() {
95
+ return this.gateway.waitingForSandboxKey ? "waiting for sandbox key" : "ready";
96
+ }
97
+ constructor(options) {
98
+ this.options = options;
99
+ if (!options.store?.hostnames?.length)
100
+ throw setupError("store.hostnames needs the store's public hostname.");
101
+ if (typeof options.priceCart !== "function" || typeof options.createOrder !== "function") {
102
+ throw setupError("The store kit needs the store's priceCart and createOrder.");
103
+ }
104
+ const configured = options.store.hostnames.map((hostname) => hostname.toLowerCase());
105
+ const unspecified = configured.find((hostname) => isUnspecifiedHostname(hostname));
106
+ if (unspecified !== undefined) {
107
+ throw new TypeError(`store.hostnames can't include ${unspecified}: that is the address a server listens on, not one a browser or agent can open. List the store's own hostnames (STORE_HOSTNAMES), such as shop.example.com.`);
108
+ }
109
+ const previewHosts = options.store.previewHosts;
110
+ if (Array.isArray(previewHosts) && previewHosts.some((host) => typeof host !== "string" || !isPreviewHostname(host.toLowerCase()))) {
111
+ throw new TypeError("store.previewHosts lists hostnames only (such as app-name.example-preview.dev), with no scheme, port or path.");
112
+ }
113
+ // An empty, placeholder or malformed key counts as no key (Test waits for a sandbox key).
114
+ const relyon = { ...options.relyon, apiKey: usableApiKey(options.relyon?.apiKey) };
115
+ if (options.relyon?.live === true && !relyon.apiKey)
116
+ throw setupError("The configured key is missing or not a Live secret key: Live mode needs the store's Live secret key (rly_live_…). Keyless build mode is Test only.");
117
+ // Test only: the app's preview addresses too. Live never adds them.
118
+ this.hostnames = !liveModeFor(relyon) && previewHosts !== false
119
+ ? testHostnames(configured, undefined, Array.isArray(previewHosts) ? previewHosts : [])
120
+ : configured;
121
+ this.now = options.now ?? Date.now;
122
+ this.logger = options.logger ?? consoleLogger;
123
+ this.maxBodyBytes = options.maxBodyBytes ?? 1024 * 1024;
124
+ this.paths = { ...DEFAULT_PATHS, ...options.paths };
125
+ this.policies = normalizeStorePolicies(options.policies, { live: liveModeFor(relyon) });
126
+ // Live needs the explicit opt-in (checked by the gateway) and a public https store.
127
+ if (liveModeFor(relyon))
128
+ assertLiveStoreUrls(this.hostnames, options.store.publicUrl);
129
+ this.configuredOrigin = publicUrlOrigin(options.store.publicUrl, this.hostnames);
130
+ // Brief 87b: every Relyon call names the project space (its host, and its
131
+ // ID when configured), so an unbound workspace key resolves this space's
132
+ // own catalog, doctor run and events instead of the workspace's default
133
+ // space. A call that already names its space (the doctor does) keeps it.
134
+ const storeHostname = this.configuredOrigin
135
+ ? new URL(this.configuredOrigin).hostname
136
+ : this.hostnames[0] && !isLoopbackHostname(this.hostnames[0]) ? this.hostnames[0] : undefined;
137
+ this.gateway = new RelyonGateway({ ...options.relyon, ...(storeHostname ? { storeHostname } : {}) });
138
+ this.testKey = this.gateway.livemode ? undefined : usableTestKey(options.relyon?.apiKey);
139
+ if (placeholderApiKey(options.relyon?.apiKey)) {
140
+ // Never the value itself: it may be a mistyped real key.
141
+ this.logger.warn("RELYON_API_KEY is set but is not a Relyon secret key (a placeholder or malformed value), so checkout waits for a sandbox key. Run npx @relyon/store-kit init to set one up.");
142
+ }
143
+ this.events = new AgentEventQueue(this.gateway, options.events ?? {}, this.now, this.logger);
144
+ this.rules = new AgentRulesCache(this.gateway, {
145
+ ...options.rules,
146
+ // Only without an explicit secret: the receiver recovers the webhook
147
+ // signing secret at runtime by replaying its own deterministic
148
+ // registration with the store's key (failures cool down with backoff).
149
+ // The sandbox fallback key (RELYON_API_KEY=sandbox) has no webhook
150
+ // authority, so recovery stays gated on the store's own key inside
151
+ // AgentRulesCache.
152
+ ...(this.configuredOrigin ? { recoverSecretForUrl: `${this.configuredOrigin}${this.paths.webhook}` } : {}),
153
+ }, this.now, this.logger);
154
+ this.catalog = new CatalogHolder(options.catalog?.persistence);
155
+ if (options.catalog?.initial)
156
+ this.catalog.replace(options.catalog.initial);
157
+ this.catalogReads = options.catalog?.source
158
+ ? new StoreCatalogReads(options.catalog.source, this.hostnames, diagnostic => this.logger.warn("catalog discovery omitted a product", diagnostic))
159
+ : undefined;
160
+ if (options.feeds && !this.catalogReads)
161
+ throw new TypeError("Store-hosted feeds require catalog.source; index mirrors are not feed sources.");
162
+ this.feeds = options.feeds && this.catalogReads ? new StoreFeedReads(this.catalogReads, {
163
+ name: options.store.name, url: `${this.configuredOrigin ?? `https://${this.hostnames[0]}`}/`, hostnames: this.hostnames,
164
+ }, {
165
+ ...options.feeds,
166
+ onDiagnostic: diagnostic => {
167
+ this.logger.warn("store feed omitted a product or attribute", diagnostic);
168
+ options.feeds?.onDiagnostic?.(diagnostic);
169
+ },
170
+ }, this.now, {
171
+ chatgpt: async () => ({
172
+ connected: await this.chatgptConnected(),
173
+ ...(this.policies?.privacyUrl ? { privacyUrl: this.policies.privacyUrl } : {}),
174
+ ...(this.policies?.termsUrl ? { termsUrl: this.policies.termsUrl } : {}),
175
+ }),
176
+ }) : undefined;
177
+ const tokens = options.cartTokens;
178
+ this.cartTokens = tokens && "resolve" in tokens
179
+ ? tokens
180
+ : new SealedCartTokens(tokens?.secret ?? (relyon.apiKey ? `api-key:${relyon.apiKey}` : randomBytes(32).toString("hex")), this.now, tokens && "ttlSeconds" in tokens ? tokens.ttlSeconds : undefined);
181
+ this.cartTransfer = cartTransferState(options.cartTransfer, this.gateway.livemode, process.env, this.logger);
182
+ this.transferTokens = this.cartTransfer.enabled
183
+ // Never keyed from the caller key: Google holds that one and could seal its own links.
184
+ ? new TransferTokens(tokens && !("resolve" in tokens) ? tokens.secret
185
+ : relyon.apiKey ? `api-key:${relyon.apiKey}` : randomBytes(32).toString("hex"), this.now, this.cartTransfer.ttlSeconds)
186
+ : null;
187
+ this.discovery = new DiscoveryReads(this.gateway, this.now);
188
+ const { verify, failClosed, ...verification } = options.agents ?? {};
189
+ this.verifier = verify === false ? null : new AgentSignatureVerifier(verification, this.now);
190
+ const state = options.state ?? new MemoryCheckoutStateStore();
191
+ if (this.gateway.livemode && typeof state.claimHandoffToken !== "function") {
192
+ this.logger.warn("The checkout state store has no claimHandoffToken: a Live hand-off link lands attributed at most once per process, not across servers or restarts. Implement claimHandoffToken in a shared store for single use everywhere.");
193
+ }
194
+ const orderClaimLeaseMs = options.orderClaimLeaseMs ?? DEFAULT_ORDER_CLAIM_LEASE_MS;
195
+ const logger = this.logger;
196
+ this.ctx = {
197
+ gateway: this.gateway, hooks: {
198
+ priceCart: options.priceCart, createOrder: options.createOrder,
199
+ ...(typeof options.findOrderByPaymentId === "function" ? { findOrderByPaymentId: options.findOrderByPaymentId } : {}),
200
+ }, state,
201
+ events: this.events, rules: this.rules, catalog: this.catalog, logger, now: this.now, paths: this.paths,
202
+ ...(this.catalogReads ? { catalogReads: this.catalogReads } : {}),
203
+ paymentCartFormat: options.paymentCartFormat ?? "contract",
204
+ ...(this.policies ? { policies: this.policies } : {}),
205
+ hostnames: this.hostnames,
206
+ liveSigningKeys: async (hostname, { refresh }) => {
207
+ const read = refresh ? await this.discovery.profiles.reload(hostname) : await this.discovery.profiles.read(hostname);
208
+ // Verification never relies on an expired copy served while Relyon is unreachable.
209
+ if (read.stale)
210
+ throw new RelyonUnavailableError("unreachable", "Only a stale copy of the store's UCP profile is available.");
211
+ return Array.isArray(read.value.keys) ? read.value.keys : [];
212
+ },
213
+ failClosed: failClosed !== false,
214
+ identify: (request, mcpClientName) => this.identifyAgent(request, mcpClientName !== undefined ? { mcpClientName } : {}),
215
+ publicHost: (request) => this.publicHost(request),
216
+ publicUrl: (request) => this.publicUrl(request),
217
+ publicOrigin: (request) => this.publicOrigin(request),
218
+ createOrderOnce: async (cart, payment) => {
219
+ const claimId = randomId("oc_");
220
+ if (!(await state.claimOrder(payment.id, { claimId, now: this.now(), leaseMs: orderClaimLeaseMs }))) {
221
+ // Created already, or another request is creating it. A store without
222
+ // `orderClaimStatus` can't say which: that counts as in progress.
223
+ const status = typeof state.orderClaimStatus === "function" ? await state.orderClaimStatus(payment.id, this.now()) : "creating";
224
+ return { created: false, status: status === "created" ? "already_created" : "in_progress" };
225
+ }
226
+ let order;
227
+ try {
228
+ order = await options.createOrder(cart, payment);
229
+ }
230
+ catch (error) {
231
+ logger.error("createOrder failed for a succeeded payment", { payment: payment.id, error: describeError(error, true) });
232
+ try {
233
+ await state.releaseOrder(payment.id, claimId);
234
+ }
235
+ catch (releaseError) {
236
+ // The claim's lease still lets a later request try again.
237
+ logger.error("The checkout state store failed to release an order claim", { payment: payment.id, error: describeError(releaseError) });
238
+ }
239
+ return { created: false, status: "failed", error };
240
+ }
241
+ try {
242
+ await state.completeOrder?.(payment.id, claimId);
243
+ }
244
+ catch (error) {
245
+ // The order exists. Once the claim's lease passes, a resend may call
246
+ // createOrder again, which is why createOrder should be idempotent on the payment id.
247
+ logger.error("The checkout state store failed to mark an order created", { payment: payment.id, error: describeError(error) });
248
+ }
249
+ return { created: true, status: "created", order };
250
+ },
251
+ };
252
+ if (options.paymentCartFormat === "server-legacy") {
253
+ logger.warn(SERVER_LEGACY_WARNING);
254
+ }
255
+ this.mcp = new McpEndpoint(this.ctx, options.store, { checkoutRefusal: () => this.pausedRefusal("mcp") });
256
+ this.webmcp = new WebMcpCheckouts(this.ctx, {
257
+ cardFields: (input) => this.cardFields(input),
258
+ createPayment: (input, payOptions) => createPayment(this.ctx, input, payOptions),
259
+ identify: (request) => this.ctx.identify(request),
260
+ }, options.webmcp);
261
+ }
262
+ /** Restores the saved catalog, starts the event timer and reads the agent rules. Idempotent. */
263
+ start() {
264
+ this.started ??= (async () => {
265
+ await this.catalog.restore(this.options.catalog?.initial);
266
+ if (this.gateway.waitingForSandboxKey)
267
+ return;
268
+ await this.events.start();
269
+ void this.rules.refresh();
270
+ })();
271
+ return this.started;
272
+ }
273
+ /** Stops the timers and sends what's queued (best effort). */
274
+ async stop() {
275
+ this.rules.stop();
276
+ this.events.stop();
277
+ await this.events.flush({ force: true }).catch(() => undefined);
278
+ }
279
+ /**
280
+ * The configured hostname this request was addressed to; the primary one if
281
+ * it names none of them. Behind a proxy, a loopback URL host is the internal
282
+ * side: a forwarded store hostname (including a Test loopback name from a
283
+ * local dev proxy) wins over it. Used for this request's own checkout
284
+ * addressing (agent signatures, hand-offs, status URLs), never for links in
285
+ * shared documents; those use `publicOrigin(request)`.
286
+ */
287
+ publicHost(request) {
288
+ const urlHost = this.requestUrl(request).hostname;
289
+ const forwarded = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim().split(":")[0];
290
+ const candidates = isLoopbackHostname(urlHost) ? [forwarded, urlHost] : [urlHost, forwarded];
291
+ for (const candidate of candidates) {
292
+ if (candidate && this.hostnames.includes(candidate.toLowerCase()))
293
+ return candidate.toLowerCase();
294
+ }
295
+ return this.hostnames[0];
296
+ }
297
+ /**
298
+ * The hostname for links in shared, cacheable documents. Like `publicHost`,
299
+ * except a forwarded host never selects a loopback origin: a proxy
300
+ * presenting a public request does not name loopback, so such a value may
301
+ * be a client's own header passed through, and it must not reach links a
302
+ * cache could serve to others. A request that came through a proxy (it
303
+ * names a forwarded host) never gets the backend's loopback origin either:
304
+ * an unusable forwarded host falls back to the primary.
305
+ */
306
+ linkHost(request) {
307
+ const urlHost = this.requestUrl(request).hostname;
308
+ const named = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim().split(":")[0];
309
+ const forwarded = named && !isLoopbackHostname(named) ? named : undefined;
310
+ const proxied = request.headers.has("x-forwarded-host");
311
+ const candidates = isLoopbackHostname(urlHost) ? (proxied ? [forwarded] : [urlHost]) : [urlHost, forwarded];
312
+ for (const candidate of candidates) {
313
+ if (candidate && this.hostnames.includes(candidate.toLowerCase()))
314
+ return candidate.toLowerCase();
315
+ }
316
+ return this.hostnames[0];
317
+ }
318
+ /** The request's own URL on the known host it arrived on (used to check agent signatures). */
319
+ publicUrl(request) {
320
+ const url = this.requestUrl(request);
321
+ return `${this.requestOrigin(request)}${url.pathname}${url.search}`;
322
+ }
323
+ /**
324
+ * The store's public address for agent-facing links on this request:
325
+ * `store.publicUrl` (STORE_PUBLIC_URL) when set; otherwise the known
326
+ * hostname the request arrived on (an unknown Host header falls back to
327
+ * the primary hostname; see `linkHost` for forwarded loopback hosts). Every
328
+ * link in llms.txt, the sitemaps, feeds, the UCP profile, MCP results, the
329
+ * agent card and the structured-data helpers is built on it.
330
+ */
331
+ publicOrigin(request) {
332
+ if (this.configuredOrigin)
333
+ return this.configuredOrigin;
334
+ const host = this.linkHost(request);
335
+ if (!this.gateway.livemode && isLoopbackHostname(host)) {
336
+ const url = this.requestUrl(request);
337
+ if (url.hostname.toLowerCase() === host)
338
+ return `${url.protocol}//${url.host.toLowerCase()}`;
339
+ }
340
+ return `https://${host}`;
341
+ }
342
+ /** The hostname of `publicOrigin(request)`. */
343
+ publicOriginHost(request) {
344
+ return this.configuredOrigin ? new URL(this.configuredOrigin).hostname : this.linkHost(request);
345
+ }
346
+ /**
347
+ * The store's origin as this request reached it, for this request's own
348
+ * checkout addressing: `https://<host>`, except a Test loopback store, which
349
+ * keeps the request's own scheme and port (plain http on localhost with a
350
+ * port), or the forwarded loopback host and port a local dev proxy names.
351
+ */
352
+ requestOrigin(request) {
353
+ const host = this.publicHost(request);
354
+ if (!this.gateway.livemode && isLoopbackHostname(host)) {
355
+ const url = this.requestUrl(request);
356
+ if (url.hostname.toLowerCase() === host)
357
+ return `${url.protocol}//${url.host.toLowerCase()}`;
358
+ const forwarded = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim().toLowerCase();
359
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
360
+ if (forwarded && /^[a-z0-9.[\]:-]+$/.test(forwarded)) {
361
+ try {
362
+ const origin = new URL(`${proto === "http" ? "http" : url.protocol.replace(/:$/, "")}://${forwarded}`);
363
+ if (origin.hostname === host)
364
+ return origin.origin;
365
+ }
366
+ catch { /* falls through */ }
367
+ }
368
+ }
369
+ return `https://${host}`;
370
+ }
371
+ /** The request's URL, with an unspecified bind address replaced by a validated Host (Test only; see `requestUrl`). */
372
+ requestUrl(request) {
373
+ return requestUrl(request, this.hostnames, !this.gateway.livemode);
374
+ }
375
+ /**
376
+ * A `303 See Other` to `path` on this store, for the app's own routes (a
377
+ * cart form, "Buy now", after a POST). The Location is `path` on the
378
+ * request's validated origin: the store hostname the request arrived on
379
+ * (in Test a loopback address keeps its scheme and port, and a dev server
380
+ * bound to `0.0.0.0` or `[::]` uses the Host header the browser sent); an
381
+ * unknown Host falls back to the primary hostname. Never build a redirect
382
+ * from `request.url`: on a server bound to every interface it names
383
+ * `0.0.0.0`, which no browser can open.
384
+ *
385
+ * `path` must start with a single `/` (such as `/checkout?product=mug`);
386
+ * a full URL, `//host`, or anything that leaves the store's origin throws
387
+ * a TypeError. `init.headers` (such as Set-Cookie) are added to the answer.
388
+ */
389
+ redirect(request, path, init = {}) {
390
+ const refuse = () => {
391
+ throw new TypeError("kit.redirect takes a path on the store's own site that starts with /, such as /checkout?product=mug; never a full URL or another site.");
392
+ };
393
+ if (typeof path !== "string" || path.length > 4096 || !path.startsWith("/") || path.startsWith("//")
394
+ || /[\\\s\u0000-\u001f\u007f]/u.test(path))
395
+ refuse();
396
+ const origin = this.requestOrigin(request);
397
+ let target;
398
+ try {
399
+ target = new URL(path, `${origin}/`);
400
+ }
401
+ catch {
402
+ return refuse();
403
+ }
404
+ if (target.origin !== origin)
405
+ refuse();
406
+ const headers = new Headers(init.headers);
407
+ headers.set("location", target.href);
408
+ headers.set("cache-control", "no-store");
409
+ return new Response(null, { status: 303, headers });
410
+ }
411
+ /** True when the kit serves the agent card. */
412
+ get servesAgentCard() {
413
+ return this.options.agentCard !== false;
414
+ }
415
+ /** True when the kit serves the root sitemap at /sitemap.xml. */
416
+ get servesSitemapIndex() {
417
+ return this.options.sitemapIndex !== false && this.paths.sitemap !== "/sitemap.xml";
418
+ }
419
+ /** True for a path the kit answers (any method). Adapters use it to read bodies only for the kit's routes. */
420
+ matches(pathname) {
421
+ const paths = this.paths;
422
+ return pathname === "/.well-known/relyon-verification" || pathname === "/.well-known/ucp" || pathname === UCP_2026_04_08_PROFILE_PATH || pathname === paths.webhook
423
+ || pathname === paths.llmsTxt || pathname === paths.sitemap || pathname === paths.mcp
424
+ || (pathname === "/sitemap.xml" && this.servesSitemapIndex)
425
+ || (pathname === "/.well-known/agent-card.json" && this.servesAgentCard)
426
+ || this.feeds?.format(pathname) !== undefined || (this.options.robots !== false && pathname === "/robots.txt")
427
+ || pathname === paths.ucp || pathname.startsWith(`${paths.ucp}/`) || pathname === paths.acp || pathname.startsWith(`${paths.acp}/`)
428
+ || pathname === `${paths.webmcp}.js` || pathname.startsWith(`${paths.webmcp}/checkouts/`)
429
+ || pathname === TEST_CHECKOUT_PATH;
430
+ }
431
+ /**
432
+ * Answers a request the kit serves, or returns null so the store's own
433
+ * routes handle it. Never throws for a bad request.
434
+ */
435
+ async handle(request, info = {}) {
436
+ const path = new URL(request.url).pathname;
437
+ const method = request.method.toUpperCase();
438
+ const paths = this.paths;
439
+ const read = method === "GET" || method === "HEAD";
440
+ try {
441
+ if (this.gateway.waitingForSandboxKey && (path === "/.well-known/ucp" || path === UCP_2026_04_08_PROFILE_PATH || path === "/.well-known/relyon-verification"
442
+ || (path === "/.well-known/agent-card.json" && this.servesAgentCard)
443
+ || path === paths.webhook || path === paths.ucp || path.startsWith(`${paths.ucp}/`)
444
+ || path === paths.acp || path.startsWith(`${paths.acp}/`) || path.startsWith(`${paths.webmcp}/checkouts/`)
445
+ || (path === TEST_CHECKOUT_PATH && !this.gateway.livemode))) {
446
+ // Checkout-bearing routes: the kit's own answer, never the app's fallback page,
447
+ // advertising no checkout capability and revealing no configuration.
448
+ const response = waitingResponse();
449
+ return read && method === "HEAD" ? new Response(null, { status: response.status, headers: response.headers }) : response;
450
+ }
451
+ if (path === "/.well-known/relyon-verification" && read) {
452
+ const response = await this.discovery.verification(this.publicHost(request));
453
+ // Test with no Relyon domain on this address: the kit labels its own 404 so the
454
+ // doctor can tell a Test preview store from an app's fallback page.
455
+ if (!this.gateway.livemode && response.status === 404)
456
+ response.headers.set(TEST_PREVIEW_HEADER, "no-domain");
457
+ return response;
458
+ }
459
+ if (path === paths.webhook && method === "POST")
460
+ return await this.webhook(request);
461
+ if (path === TEST_CHECKOUT_PATH)
462
+ return await this.testCheckout(request);
463
+ if (path === "/.well-known/ucp" && read) {
464
+ // The profile for the store's public address, with its endpoints on that address.
465
+ const host = this.publicOriginHost(request);
466
+ const origin = this.publicOrigin(request);
467
+ return await this.discoveryRead(request, info, "profile_read", "ucp", async () => this.servedProfile(await this.discovery.ucpProfile(host, origin), origin, false));
468
+ }
469
+ if (path === UCP_2026_04_08_PROFILE_PATH && read) {
470
+ // The derived UCP 2026-04-08 profile (see ucp-versions.ts).
471
+ const host = this.publicOriginHost(request);
472
+ const origin = this.publicOrigin(request);
473
+ return await this.discoveryRead(request, info, "profile_read", "ucp", async () => this.servedProfile(await this.discovery.ucpProfile(host, origin), origin, true));
474
+ }
475
+ if (path === "/.well-known/agent-card.json" && read && this.servesAgentCard) {
476
+ const origin = this.publicOrigin(request);
477
+ return await this.discoveryRead(request, info, "profile_read", "plain", async () => jsonResponse(200, agentCard({
478
+ store: this.options.store, origin, paths, livemode: this.gateway.livemode, feedUrls: this.feeds?.urls(origin) ?? [],
479
+ }), { "cache-control": "public, max-age=300", "access-control-allow-origin": "*" }));
480
+ }
481
+ const feedFormat = this.feeds?.format(path);
482
+ if (feedFormat && this.feeds) {
483
+ return await this.discoveryRead(request, info, "feed_read", "plain", () => this.feeds.response(request, feedFormat, this.publicOrigin(request), this.gateway.waitingForSandboxKey));
484
+ }
485
+ if (path === "/robots.txt" && this.options.robots !== false && read) {
486
+ const robots = this.options.robots;
487
+ let result;
488
+ try {
489
+ result = mergeAiRobots(robots ? await robots.existing() : "", {
490
+ origin: this.publicOrigin(request), sitemapPath: paths.sitemap, llmsPath: paths.llmsTxt,
491
+ ...(this.servesSitemapIndex ? { sitemapIndexPath: "/sitemap.xml" } : {}),
492
+ });
493
+ }
494
+ catch (error) {
495
+ // The default file on an origin the helpers don't serve (plain http beyond loopback): the app answers.
496
+ if (!robots && error instanceof TypeError)
497
+ return null;
498
+ throw error;
499
+ }
500
+ if (this.gateway.waitingForSandboxKey)
501
+ result.content = `${WAITING_TEXT_MARKER}\n${result.content}`;
502
+ if (result.conflicts.length) {
503
+ if (robots)
504
+ robots.onConflict?.(result.conflicts);
505
+ this.logger.warn("robots integration needs merchant resolution", { conflicts: result.conflicts });
506
+ return new Response(request.method === "HEAD" ? null : result.content, {
507
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "x-relyon-robots-conflicts": String(result.conflicts.length), ...this.waitingHeaders() },
508
+ });
509
+ }
510
+ return new Response(request.method === "HEAD" ? null : result.content, { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...this.waitingHeaders() } });
511
+ }
512
+ if (path === paths.llmsTxt && read) {
513
+ const origin = this.publicOrigin(request);
514
+ return await this.discoveryRead(request, info, "llms_txt_read", "plain", async () => textResponse(200, llmsTxt(this.options.store, origin, await this.discoveryCatalog(), paths, this.feeds?.urls(origin), this.policies, {
515
+ rebase: { hostnames: this.hostnames }, acp: paths.acp, agentCard: this.servesAgentCard,
516
+ waitingForSandboxKey: this.gateway.waitingForSandboxKey,
517
+ }), "text/plain; charset=utf-8", { "cache-control": this.catalogReads ? "no-cache" : "public, max-age=300" }));
518
+ }
519
+ // The product sitemap and the root /sitemap.xml list the same product pages.
520
+ if ((path === paths.sitemap || (path === "/sitemap.xml" && this.servesSitemapIndex)) && read) {
521
+ const origin = this.publicOrigin(request);
522
+ return await this.discoveryRead(request, info, "feed_read", "plain", async () => textResponse(200, withWaitingXmlMarker(productSitemap(await this.discoveryCatalog(), { origin, hostnames: this.hostnames }), this.gateway.waitingForSandboxKey), "application/xml; charset=utf-8", { "cache-control": this.catalogReads ? "no-cache" : "public, max-age=300" }));
523
+ }
524
+ if (path === paths.mcp)
525
+ return await this.mcpRequest(request, info);
526
+ if (path === paths.ucp || path.startsWith(`${paths.ucp}/`)) {
527
+ // `<ucp prefix>/2026-04-08/...` is the same REST service at UCP 2026-04-08
528
+ // (Relyon negotiates the version from the platform's profile).
529
+ let rest = path.slice(paths.ucp.length);
530
+ let version = UCP_CURRENT_VERSION;
531
+ if (rest === UCP_2026_04_08_SEGMENT || rest.startsWith(`${UCP_2026_04_08_SEGMENT}/`)) {
532
+ version = UCP_2026_04_08;
533
+ rest = rest.slice(UCP_2026_04_08_SEGMENT.length);
534
+ }
535
+ if (rest === "/carts" || rest === "/carts/")
536
+ return await this.cartTransferRequest(request, version);
537
+ if (rest.startsWith("/carts/")) {
538
+ return refusal("ucp", "not_found", { status: 404, message: "Reading, updating or cancelling a cart is not supported; create a new cart with POST to /carts." });
539
+ }
540
+ return await this.checkoutRequest(request, info, "ucp", rest, version === UCP_2026_04_08 ? `${paths.ucp}${UCP_2026_04_08_SEGMENT}` : paths.ucp);
541
+ }
542
+ if (path === paths.acp || path.startsWith(`${paths.acp}/`))
543
+ return await this.checkoutRequest(request, info, "acp", path.slice(paths.acp.length));
544
+ if (path === `${paths.webmcp}.js` || path.startsWith(`${paths.webmcp}/checkouts/`))
545
+ return await this.webmcp.handle(request, info, path);
546
+ return null;
547
+ }
548
+ catch (error) {
549
+ if (error instanceof BodyTooLargeError)
550
+ return refusal("plain", "invalid_request", { status: 413, message: "The request body is too large." });
551
+ this.logger.error("the store kit could not answer a request", { path, error: describeError(error, true) });
552
+ return refusal("plain", "internal_error");
553
+ }
554
+ }
555
+ /** Reports a crawler or agent visit to a page the store serves itself (a product page, say). */
556
+ recordCrawlerVisit(request, status, info = {}) {
557
+ const facts = requestFacts(request, this.publicUrl(request), info);
558
+ if (facts)
559
+ this.events.record({ type: "crawler_visit", request: facts, status });
560
+ }
561
+ async readBody(request) {
562
+ if (request.method === "GET" || request.method === "HEAD" || !request.body)
563
+ return "";
564
+ const declared = Number(request.headers.get("content-length") ?? "0");
565
+ if (declared > this.maxBodyBytes)
566
+ throw new BodyTooLargeError();
567
+ const bytes = new Uint8Array(await request.arrayBuffer());
568
+ if (bytes.byteLength > this.maxBodyBytes)
569
+ throw new BodyTooLargeError();
570
+ return new TextDecoder().decode(bytes);
571
+ }
572
+ /** Refuses a blocked agent at the edge (claimed or verified); never fails closed (discovery and relays). */
573
+ async edgeBlock(request, mcpClientName) {
574
+ if (this.gateway.waitingForSandboxKey)
575
+ return false; // Public, store-owned discovery only.
576
+ const identity = await this.ctx.identify(request, mcpClientName);
577
+ if (!identity.identified)
578
+ return false;
579
+ const rules = await this.rules.get();
580
+ return decide(identity, rules, { failClosed: false }).outcome === "refuse";
581
+ }
582
+ async pausedRefusal(protocol) {
583
+ if (this.gateway.waitingForSandboxKey)
584
+ return { code: "sandbox_key_pending", message: "Checkout is waiting for sandbox key." };
585
+ const rules = await this.rules.get();
586
+ if (!rules)
587
+ return null;
588
+ if (rules.paused || rules.paused_channels.includes(CHANNEL_FOR[protocol]) || rules.paused_channels.includes("agent")) {
589
+ return { code: "channel_paused" };
590
+ }
591
+ return null;
592
+ }
593
+ report(type, request, info, status) {
594
+ const facts = requestFacts(request, this.publicUrl(request), info);
595
+ if (facts)
596
+ this.events.record({ type, request: facts, status });
597
+ }
598
+ async discoveryRead(request, info, type, protocol, answer) {
599
+ if (await this.edgeBlock(request)) {
600
+ this.report(type, request, info, 403);
601
+ const response = refusal(protocol, "agent_refused");
602
+ return request.method.toUpperCase() === "HEAD" ? new Response(null, { status: response.status, headers: response.headers }) : response;
603
+ }
604
+ let response;
605
+ try {
606
+ response = await answer();
607
+ }
608
+ catch (error) {
609
+ this.logger.error("store discovery read failed", { error: describeError(error, true) });
610
+ response = textResponse(503, "Store discovery is temporarily unavailable.\n", "text/plain; charset=utf-8", { "cache-control": "no-store", "retry-after": "5" });
611
+ }
612
+ this.report(type, request, info, response.status);
613
+ for (const [name, value] of Object.entries(this.waitingHeaders()))
614
+ response.headers.set(name, value);
615
+ if (request.method.toUpperCase() === "HEAD")
616
+ return new Response(null, { status: response.status, headers: response.headers });
617
+ return response;
618
+ }
619
+ /** While the kit waits for a sandbox key, every discovery answer says so (no configuration). */
620
+ waitingHeaders() {
621
+ return this.gateway.waitingForSandboxKey ? { [WAITING_STATUS_HEADER]: WAITING_STATUS } : {};
622
+ }
623
+ async discoveryCatalog() {
624
+ if (!this.catalogReads)
625
+ return this.catalog;
626
+ const holder = new CatalogHolder();
627
+ holder.replace(await this.catalogReads.all());
628
+ return holder;
629
+ }
630
+ /** True when the kit can answer cart transfer at the profile's advertised REST endpoint. */
631
+ get cartTransferCallable() {
632
+ return this.cartTransfer.enabled && !this.gateway.waitingForSandboxKey;
633
+ }
634
+ /**
635
+ * The UCP profile the store serves: Relyon's 2026-08-25 body plus the cart
636
+ * capability and `supported_versions` (or, for `leaf`, the derived
637
+ * 2026-04-08 profile). Refusals and the cache headers pass through.
638
+ */
639
+ async servedProfile(response, origin, leaf) {
640
+ if (response.status !== 200)
641
+ return response;
642
+ const body = tryParseJson(await response.text());
643
+ const additions = { origin, ucpPath: this.paths.ucp, cart: this.cartTransferCallable };
644
+ const value = leaf ? profile20260408(body, additions) : currentProfile(body, additions);
645
+ if (leaf && !value)
646
+ return refusal("ucp", "not_found", { status: 404, message: "This store has no UCP 2026-04-08 profile." });
647
+ return new Response(JSON.stringify(value), { status: 200, headers: response.headers });
648
+ }
649
+ /** `POST <ucp prefix>/carts`: answered by the kit alone (see cart-transfer.ts). */
650
+ async cartTransferRequest(request, version) {
651
+ const rawBody = await this.readBody(request);
652
+ const origin = this.publicOrigin(request);
653
+ return handleCartTransfer({
654
+ state: this.cartTransfer, tokens: this.transferTokens, products: catalogProducts(this.catalogReads, this.catalog),
655
+ priceCart: this.options.priceCart, logger: this.logger, now: this.now,
656
+ }, request, rawBody, version, (token) => `${origin}${this.paths.checkout}?${CART_TRANSFER_PARAM}=${encodeURIComponent(token)}`);
657
+ }
658
+ async checkoutRequest(request, info, protocol, rest, mount = this.paths[protocol]) {
659
+ const method = request.method.toUpperCase();
660
+ const step = protocol === "ucp" ? routeUcp(method, rest) : routeAcp(method, rest);
661
+ if (!step) {
662
+ const response = refusal(protocol, "not_found", { status: 404, message: "No such checkout endpoint." });
663
+ this.report("crawler_visit", request, info, response.status);
664
+ return response;
665
+ }
666
+ const sessionId = step.operation === "create" ? null : step.sessionId;
667
+ const statusUrl = `${this.requestOrigin(request)}${mount}${checkoutSessionPath(protocol, step.sessionId ?? "")}`;
668
+ /**
669
+ * The kit's own refusal. On a step that names an existing checkout it is
670
+ * never "nothing was charged": an order-pending checkout (paid, order not
671
+ * created) answers order pending; any other existing checkout gets
672
+ * charge-neutral wording. Only `create` keeps "nothing was charged".
673
+ */
674
+ const refuse = async (code, status, message) => {
675
+ let response;
676
+ if (sessionId && await orderPendingFor(this.ctx, protocol, sessionId)) {
677
+ this.logger.warn("a refused step names an order-pending checkout; the agent is told the order is pending", { protocol, operation: step.operation, code });
678
+ response = orderPendingError(protocol, { statusUrl });
679
+ }
680
+ else {
681
+ response = refusal(protocol, code, { ...(status ? { status } : {}), ...(message ? { message } : {}), existingCheckout: sessionId !== null });
682
+ }
683
+ this.report("crawler_visit", request, info, response.status);
684
+ return response;
685
+ };
686
+ try {
687
+ if (await this.edgeBlock(request))
688
+ return await refuse("agent_refused");
689
+ const paused = await this.pausedRefusal(protocol);
690
+ if (paused)
691
+ return await refuse(paused.code);
692
+ const rawBody = await this.readBody(request);
693
+ let patch = null;
694
+ if (step.operation === "create" || step.operation === "update") {
695
+ const parsed = tryParseJson(rawBody);
696
+ if (!isRecord(parsed))
697
+ return await refuse("invalid_request", 400, "The request body must be a JSON object.");
698
+ // Cart-to-checkout conversion is not supported: refused, never ignored.
699
+ if (protocol === "ucp" && step.operation === "create" && parsed.cart_id !== undefined) {
700
+ return await refuse("cart_id_unsupported", 400, "Creating a checkout from a cart (cart_id) is not supported. Send the cart's line_items to create the checkout.");
701
+ }
702
+ patch = inputParsers[protocol](parsed);
703
+ }
704
+ const outcome = await relayStep(this.ctx, { protocol, operation: step.operation, sessionId: step.sessionId, request, rawBody, patch });
705
+ if (outcome.kind === "relayed")
706
+ return outcome.response;
707
+ // Relyon recorded this step, so the kit doesn't report it.
708
+ if (outcome.kind === "order_pending")
709
+ return orderPendingCheckout(protocol, outcome.result, outcome.sessionId);
710
+ if (outcome.kind === "outcome_unknown") {
711
+ // An order-pending checkout's payment is known to have succeeded: a
712
+ // resend replays it, so its order is pending, not its outcome unknown.
713
+ if (sessionId && await orderPendingFor(this.ctx, protocol, sessionId))
714
+ return await refuse("internal_error");
715
+ // Points at the store's own checkout read, never at a Relyon hostname.
716
+ const response = paymentOutcomeUnknown(protocol, { paymentStatus: outcome.paymentStatus, statusUrl });
717
+ this.report("crawler_visit", request, info, response.status);
718
+ return response;
719
+ }
720
+ return await refuse(outcome.code, outcome.status, outcome.message);
721
+ }
722
+ catch (error) {
723
+ if (error instanceof BodyTooLargeError)
724
+ throw error;
725
+ // An unexpected failure (the checkout state store throwing, say): a
726
+ // protocol-shaped 500 (or order pending), never the plain-text generic error.
727
+ this.logger.error("the store kit could not answer an agent checkout step", {
728
+ protocol, operation: step.operation, error: describeError(error, true),
729
+ });
730
+ return await refuse("internal_error", 500);
731
+ }
732
+ }
733
+ async mcpRequest(request, info) {
734
+ const rawBody = await this.readBody(request);
735
+ const client = this.mcp.clientFor(request);
736
+ if (await this.edgeBlock(request, client?.name)) {
737
+ const message = tryParseJson(rawBody);
738
+ const id = isRecord(message) ? message.id : null;
739
+ const facts = requestFacts(request, this.publicUrl(request), info);
740
+ if (facts) {
741
+ const tool = isRecord(message) && message.method === "tools/call" && isRecord(message.params) && typeof message.params.name === "string" ? message.params.name : undefined;
742
+ this.events.record({
743
+ type: tool ? "mcp_tool_call" : "crawler_visit", request: facts, status: 200,
744
+ ...(tool ? { mcp_tool: tool.slice(0, 100) } : {}), ...(tool && client ? { mcp_client: client } : {}),
745
+ });
746
+ }
747
+ // A checkout call naming an order-pending checkout hears order pending.
748
+ const call = mcpCheckoutCall(message);
749
+ if (call?.sessionId)
750
+ return mcpRefusal(this.ctx, id, call.sessionId, "agent_refused", "This store does not accept requests from this agent.");
751
+ return jsonResponse(200, mcpErrorBody(id, "agent_refused", "This store does not accept requests from this agent."));
752
+ }
753
+ try {
754
+ return await this.mcp.handle(request, rawBody, info);
755
+ }
756
+ catch (error) {
757
+ // An unexpected failure: an in-band JSON-RPC error (order pending or
758
+ // charge-neutral for a checkout call), never the plain-text generic error.
759
+ this.logger.error("the store kit could not answer an MCP request", { error: describeError(error, true) });
760
+ const message = tryParseJson(rawBody);
761
+ const call = mcpCheckoutCall(message);
762
+ return mcpRefusal(this.ctx, isRecord(message) ? message.id ?? null : null, call?.sessionId ?? null, "internal_error", call && !call.sessionId ? undefined : "This request could not be answered. Call get_checkout for a checkout's status before trying again; don't start a new checkout.");
763
+ }
764
+ }
765
+ async webhook(request) {
766
+ const raw = await this.readBody(request);
767
+ const header = request.headers.get(WEBHOOK_SIGNATURE_HEADER) ?? request.headers.get(LEGACY_WEBHOOK_SIGNATURE_HEADER);
768
+ // An empty header is absent, not malformed: the request is unsigned.
769
+ const signature = header || null;
770
+ const result = await this.rules.handleWebhook(raw, signature);
771
+ return jsonResponse(result.status, result.status === 200 ? { received: true } : { error: result.error ?? "invalid_signature" }, result.acknowledgement ? { [DOCTOR_ACKNOWLEDGEMENT_HEADER]: result.acknowledgement, "cache-control": "no-store" } : {});
772
+ }
773
+ // ---- Store-side helpers ---------------------------------------------------
774
+ /**
775
+ * Who is at this request: verified from an allowlisted agent signature, or
776
+ * as it claims (user agent, Signature-Agent, UCP-Agent, MCP client), with
777
+ * behaviour hints recorded as claims only. Cached per Request object.
778
+ */
779
+ identifyAgent(request, options = {}) {
780
+ const key = `${options.mcpClientName ?? ""}\u0000${(options.hints ?? []).join(",")}`;
781
+ let byKey = this.identities.get(request);
782
+ if (!byKey) {
783
+ byKey = new Map();
784
+ this.identities.set(request, byKey);
785
+ }
786
+ let found = byKey.get(key);
787
+ if (!found) {
788
+ found = identifyAgent(request, this.verifier, {
789
+ authorities: this.hostnames,
790
+ ...(options.mcpClientName !== undefined ? { mcpClientName: options.mcpClientName } : {}),
791
+ ...(options.hints ? { hints: options.hints } : {}),
792
+ });
793
+ byKey.set(key, found);
794
+ }
795
+ return found;
796
+ }
797
+ /**
798
+ * The edge answer for a checkout step or payment: allow, refuse by a named
799
+ * Relyon rule, or (for an identified agent, when the rules can't be read)
800
+ * unavailable. Never a challenge or a blanket block.
801
+ */
802
+ async agentDecision(request, options = {}) {
803
+ const identity = await this.identifyAgent(request, options);
804
+ const rules = identity.identified ? await this.rules.get() : null;
805
+ return decide(identity, rules, { failClosed: this.ctx.failClosed });
806
+ }
807
+ /**
808
+ * The verified-agent signal for the store's own bot protection: skip a
809
+ * CAPTCHA or WAF challenge only when `skipChallenge` is true (a verified
810
+ * signature Relyon's rules allow). See the README's bot-protection guidance.
811
+ */
812
+ async verifiedAgent(request) {
813
+ return verifiedAgentSignal(await this.agentDecision(request));
814
+ }
815
+ /** Starts a WebMCP checkout for the store's checkout page. */
816
+ createWebMcpCheckout(input) {
817
+ return this.webmcp.create(input);
818
+ }
819
+ /** The machine-readable order confirmation for a paid cart. */
820
+ orderConfirmation(cart, orderReference, result) {
821
+ return orderConfirmation({ cart, orderReference, payment: result.payment, agent: result.agent ?? null, now: this.now });
822
+ }
823
+ /**
824
+ * For the store's own pay endpoint: runs `createPayment` and answers JSON
825
+ * with the order confirmation (200), the decline (402), the refusal
826
+ * naming the Relyon rule (403/503, or Relyon's own status), an unknown
827
+ * outcome (202, `payment_outcome: "unknown"`), or order pending (202,
828
+ * `payment_outcome: "succeeded"`, `order_status: "pending"`: the payment
829
+ * went through and `createOrder` failed or is still running elsewhere).
830
+ * After either 202, retry by calling this again with the SAME input (order
831
+ * reference, attempt and the original `paymentMethod`); never re-read the
832
+ * card. The retry replays the payment (no new charge) and creates the
833
+ * order once. When the pending payment belongs to an earlier attempt of
834
+ * the order reference, or to another order reference for the same agent
835
+ * checkout, the 202 names it (`paid_order_reference`, `paid_attempt`):
836
+ * resend that request instead.
837
+ *
838
+ * Once the key, its order reference or its agent checkout may have been
839
+ * charged, no answer says nothing was charged: every refusal (the kit's
840
+ * own gate, or Relyon's) and every unexpected error answers order pending
841
+ * when the kit remembers a pending order, otherwise charge-neutrally.
842
+ * Unexpected errors are answered (500, `internal_error`), not thrown.
843
+ */
844
+ async payAndConfirm(input) {
845
+ if (this.gateway.waitingForSandboxKey)
846
+ return { response: jsonResponse(503, { code: "sandbox_key_pending", message: "Checkout is waiting for sandbox key. Check existing order status before retrying a payment.", developer_hint: DEVELOPER_HINT }) };
847
+ if (!input.orderReference)
848
+ throw new TypeError("payAndConfirm needs the store's orderReference.");
849
+ let result;
850
+ const attempt = input.attempt ?? 0;
851
+ const key = paymentIdempotencyKey(input.orderReference, attempt);
852
+ /** Every attempt of this order reference, and every payment for this agent checkout, shares one record. */
853
+ const shared = [orderReferencePaymentKey(input.orderReference), ...(input.agentCheckoutId ? [handoffPaymentKey(input.agentCheckoutId)] : [])];
854
+ const tag = { orderReference: input.orderReference, attempt };
855
+ /** What each key said before this request recorded `charging`; undefined until the request is about to be sent. */
856
+ let before;
857
+ const rememberAll = async (state, paymentId) => {
858
+ const record = { state, paymentId, updatedAt: this.now(), ...tag };
859
+ await rememberStorePayment(this.ctx, key, { state, paymentId, updatedAt: record.updatedAt });
860
+ for (const k of shared)
861
+ await rememberStorePaymentUnlessStronger(this.ctx, k, record);
862
+ };
863
+ try {
864
+ // Recorded before the charge and again before createOrder runs, so a
865
+ // concurrent retry the agent rules refuse never hears "nothing was
866
+ // charged" while this request is still charging or creating the order.
867
+ result = await createPayment(this.ctx, input, {
868
+ beforeCharge: async () => {
869
+ const own = await noteStorePaymentCharging(this.ctx, key);
870
+ const others = [];
871
+ for (const k of shared) {
872
+ others.push(await storePaymentRecord(this.ctx, k));
873
+ await rememberStorePaymentUnlessStronger(this.ctx, k, { state: "charging", paymentId: null, updatedAt: this.now(), ...tag });
874
+ }
875
+ before = [own, ...others];
876
+ },
877
+ beforeOrder: async (payment) => {
878
+ await rememberAll("order_pending", payment.id);
879
+ if (input.agentCheckoutId)
880
+ await markHandoffOrderPending(this.ctx, input.agentCheckoutId, payment.id, true);
881
+ },
882
+ });
883
+ }
884
+ catch (error) {
885
+ if (error instanceof PaymentOutcomeUnknownError)
886
+ return this.payOutcomeUnknown(input.orderReference, error);
887
+ return await this.payRefusal(input, key, shared, error, before);
888
+ }
889
+ if (result.payment.status !== "succeeded") {
890
+ await rememberAll("declined", result.payment.id);
891
+ const refusal = orderRefusal(input.orderReference, String(result.payment.failure_code ?? "card_declined"), String(result.payment.failure_message ?? "The card was declined. Nothing was charged."), null, result.payment.id);
892
+ return { response: jsonResponse(402, { order_refusal: refusal }, { "cache-control": "no-store" }), refusal, result };
893
+ }
894
+ const pending = this.orderIsPending(result);
895
+ // Remembered so a retry the agent rules now refuse still hears the truth.
896
+ await rememberAll(pending ? "order_pending" : "order_created", result.payment.id);
897
+ if (input.agentCheckoutId)
898
+ await markHandoffOrderPending(this.ctx, input.agentCheckoutId, result.payment.id, pending);
899
+ if (pending)
900
+ return { response: this.payOrderPending(input.orderReference, result.payment.id), result, orderPending: true };
901
+ const confirmation = this.orderConfirmation(input.cart, input.orderReference, result);
902
+ return { response: jsonResponse(200, { order_confirmation: confirmation }, { "cache-control": "no-store" }), confirmation, result };
903
+ }
904
+ /** `payAndConfirm`'s 202 unknown-outcome answer. */
905
+ payOutcomeUnknown(orderReference, error) {
906
+ return {
907
+ response: jsonResponse(202, {
908
+ payment_outcome: "unknown", order_reference: orderReference,
909
+ message: "The payment outcome is unknown: the charge may have gone through. Check the order status before doing anything else; a retry must resend the original payment request (same order reference and card payload), never a new card entry.",
910
+ }, { "cache-control": "no-store" }),
911
+ outcomeUnknown: error,
912
+ };
913
+ }
914
+ /**
915
+ * `payAndConfirm`'s answer to a refusal or an unexpected error. A pending
916
+ * order the kit remembers (this key, an earlier attempt of the order
917
+ * reference, or another payment for the agent checkout) answers 202 order
918
+ * pending. Otherwise, when anything may have been charged, the refusal is
919
+ * charge-neutral; Relyon's refusal of a request it never charged, or a
920
+ * gate refusal of an established-unpaid key, keeps its own wording.
921
+ */
922
+ async payRefusal(input, key, shared, error, before) {
923
+ const refused = refusalFor(input.orderReference, error);
924
+ if (!refused) {
925
+ this.logger.error("payAndConfirm failed unexpectedly", { error: describeError(error, true) });
926
+ }
927
+ for (const k of [key, ...shared]) {
928
+ const standing = await storePaymentStanding(this.ctx, k);
929
+ if (standing.kind !== "order_pending")
930
+ continue;
931
+ this.logger.warn("a refused store payment's order reference or agent checkout was already charged with its order pending; answering order pending", {
932
+ payment: standing.paymentId, code: refused?.body.code ?? "internal_error",
933
+ });
934
+ return { response: this.payOrderPending(input.orderReference, standing.paymentId, k === key ? undefined : standing.record, input.attempt ?? 0), orderPending: true };
935
+ }
936
+ if (!refused) {
937
+ // Sent and then failed in a way the kit doesn't know: the charge may have gone through.
938
+ if (before)
939
+ return this.payOutcomeUnknown(input.orderReference, new PaymentOutcomeUnknownError(input.orderReference, key, "pending"));
940
+ const body = orderRefusal(input.orderReference, "internal_error", `This payment could not be processed. ${PAY_CHARGE_NEUTRAL_NOTE}`);
941
+ return { response: jsonResponse(500, { order_refusal: body }, { "cache-control": "no-store" }), refusal: body };
942
+ }
943
+ const maybeCharged = async () => {
944
+ if (before) {
945
+ // Relyon answered: it replays a key it charged before any refusal, so
946
+ // only what the kit knew before this request (this key, another
947
+ // attempt, the agent checkout) can make its "nothing was charged" untrue.
948
+ return before.some((record) => record !== null && record.state !== "declined");
949
+ }
950
+ // The kit's own gate refused before Relyon replayed anything: a missing
951
+ // record is never proof of no charge.
952
+ if ((await storePaymentStanding(this.ctx, key)).kind !== "none")
953
+ return true;
954
+ for (const k of shared) {
955
+ const record = await storePaymentRecord(this.ctx, k);
956
+ if (record && record.state !== "declined")
957
+ return true;
958
+ }
959
+ return false;
960
+ };
961
+ if (!(await maybeCharged())) {
962
+ return { response: jsonResponse(refused.status, { order_refusal: refused.body }, { "cache-control": "no-store" }), refusal: refused.body };
963
+ }
964
+ const message = error instanceof AgentRefusedError || error instanceof PaymentUnavailableError
965
+ ? chargeNeutralGateMessage(error)
966
+ : `${withoutNothingChargedClaims(refused.body.message) || "This payment was refused."} ${PAY_CHARGE_NEUTRAL_NOTE}`;
967
+ // The rule's label quotes Relyon's message: never its "nothing was charged" either.
968
+ const rule = refused.body.rule === null ? null : withoutNothingChargedClaims(refused.body.rule) || "Relyon agent rule";
969
+ const body = { ...refused.body, message, rule };
970
+ return { response: jsonResponse(refused.status, { order_refusal: body }, { "cache-control": "no-store" }), refusal: body };
971
+ }
972
+ /** `payAndConfirm`'s 202 order-pending answer; `paid` names an earlier attempt or order reference that paid. */
973
+ payOrderPending(orderReference, paymentId, paid, attempt = 0) {
974
+ const other = paid?.orderReference !== undefined
975
+ && (paid.orderReference !== orderReference || (paid.attempt ?? attempt) !== attempt);
976
+ return jsonResponse(202, {
977
+ payment_outcome: "succeeded", order_status: "pending", order_reference: orderReference, payment_id: paymentId,
978
+ ...(other ? { paid_order_reference: paid.orderReference, ...(paid.attempt !== undefined ? { paid_attempt: paid.attempt } : {}) } : {}),
979
+ message: other ? PAY_ORDER_PENDING_EARLIER_MESSAGE : PAY_ORDER_PENDING_MESSAGE,
980
+ }, { "cache-control": "no-store", "retry-after": String(ORDER_PENDING_RETRY_AFTER) });
981
+ }
982
+ /**
983
+ * True when a succeeded payment's order isn't created: `createOrder` threw,
984
+ * or another request holds the claim on a store that can report claim
985
+ * status. Without `orderClaimStatus` an in-progress claim can't be told
986
+ * from a created order, so it confirms (as before) and logs a warning.
987
+ */
988
+ orderIsPending(result) {
989
+ if (result.orderStatus === "failed")
990
+ return true;
991
+ if (result.orderStatus !== "in_progress")
992
+ return false;
993
+ if (typeof this.ctx.state.orderClaimStatus === "function")
994
+ return true;
995
+ this.logger.warn("The checkout state store has no orderClaimStatus, so the kit can't tell whether the order exists; the payment is confirmed", {
996
+ payment: result.payment.id,
997
+ });
998
+ return false;
999
+ }
1000
+ /** The confirmation page fragment: JSON-LD plus the `#relyon-order-confirmation` element. */
1001
+ renderOrderConfirmation(confirmation) {
1002
+ return renderOrderConfirmation(confirmation);
1003
+ }
1004
+ /** What the confirmation page shows for a refused or declined payment. */
1005
+ renderOrderRefusal(refusal) {
1006
+ return renderOrderRefusal(refusal);
1007
+ }
1008
+ /**
1009
+ * Upserts the store's catalog into Relyon and keeps it as the last good
1010
+ * catalog for discovery. Relyon's index takes full URLs only, so each
1011
+ * product's `url` and `images` that are the store's own (a path such as
1012
+ * `/products/mug`, or a URL on one of the store's hostnames or loopback)
1013
+ * are sent on the store's public address: `store.publicUrl`
1014
+ * (STORE_PUBLIC_URL) when set, else `https://` + the primary hostname, the
1015
+ * same default the feeds use. The kit's own catalog keeps the links as
1016
+ * given. When a path can't be made a full URL (no STORE_PUBLIC_URL and a
1017
+ * loopback primary hostname, whose port the kit can't know) the sync
1018
+ * throws a CatalogSyncError naming the product and the fix before anything
1019
+ * is sent.
1020
+ */
1021
+ syncCatalog(products, options = {}) {
1022
+ const origin = this.syncOrigin();
1023
+ return syncCatalog(this.gateway, this.catalog, products, options.mode ?? "upsert", this.now(), {
1024
+ origin, hostnames: this.hostnames,
1025
+ }).then((result) => {
1026
+ // Brief 87b: the sync result line names the store Relyon wrote to, so a
1027
+ // workspace with several stores shows each sync landing in its own.
1028
+ if (result.storeName) {
1029
+ const host = origin ? new URL(origin).hostname : this.hostnames[0];
1030
+ this.logger.info?.(`Synced ${result.results.length} products to ${result.storeName}${host ? ` (${host})` : ""}.`);
1031
+ }
1032
+ return result;
1033
+ });
1034
+ }
1035
+ /** `POST /relyon/test-checkout`: one Test purchase for `npx @relyon/store-kit test-checkout` (see test-checkout.ts). */
1036
+ testCheckout(request) {
1037
+ return handleTestCheckout(request, {
1038
+ livemode: this.gateway.livemode, testKey: this.testKey, now: this.now,
1039
+ products: async () => this.catalogReads ? await this.catalogReads.all() : this.catalog.all(),
1040
+ priceCart: (...args) => this.ctx.hooks.priceCart(...args),
1041
+ openSession: async (input) => (await this.gateway.call((client) => client.POST(PAYMENT_SESSIONS_PATH, {
1042
+ params: { header: { "Idempotency-Key": input.idempotencyKey } },
1043
+ body: { amount: input.amount, currency: input.currency.toUpperCase(), order_reference: input.orderReference },
1044
+ }), isPaymentSession)).data,
1045
+ payAndConfirm: (input) => this.payAndConfirm(input),
1046
+ checkoutUrl: `${this.publicOrigin(request)}${this.paths.checkout}`,
1047
+ nonces: this.testCheckoutNonces, inflight: this.testCheckoutRuns,
1048
+ });
1049
+ }
1050
+ /** The origin synced product links go on; undefined when no usable one is known. */
1051
+ syncOrigin() {
1052
+ if (this.configuredOrigin)
1053
+ return this.configuredOrigin;
1054
+ const primary = this.hostnames[0];
1055
+ return isLoopbackHostname(primary) ? undefined : `https://${primary}`;
1056
+ }
1057
+ /** Creates a payment session and renders `<relyon-card-fields>` for the checkout page. */
1058
+ cardFields(input) {
1059
+ return createCardFields(this.ctx, input, this.options.cardFieldsScriptUrl);
1060
+ }
1061
+ /** Charges the cart through `createPayment`; creates the store's order once on success. */
1062
+ createPayment(input) {
1063
+ return createPayment(this.ctx, input);
1064
+ }
1065
+ /**
1066
+ * Reads a landing on the store's checkout page: an agent hand-off
1067
+ * (`relyon_cart`) or a UCP cart transfer (`relyon_transfer`). Pass the
1068
+ * page's Request, or (for a Next.js server component) its URL or its
1069
+ * awaited `searchParams`.
1070
+ */
1071
+ landing(request, info = {}) {
1072
+ const page = this.landingRequest(request);
1073
+ // A UCP cart transfer's link: the transferred lines priced again, never attributed.
1074
+ const transfer = new URL(page.url).searchParams.get(CART_TRANSFER_PARAM);
1075
+ if (transfer && !new URL(page.url).searchParams.has("relyon_cart")) {
1076
+ return transferLanding(this.transferTokens, this.options.priceCart, transfer, this.logger, catalogProducts(this.catalogReads, this.catalog));
1077
+ }
1078
+ return landing(this.ctx, this.cartTokens, page, info);
1079
+ }
1080
+ /** The checkout page request for `landing()`: a URL, a path or search params land on the store's checkout path. */
1081
+ landingRequest(input) {
1082
+ if (input instanceof Request)
1083
+ return input;
1084
+ const primary = this.hostnames[0];
1085
+ const base = this.configuredOrigin ?? `${isLoopbackHostname(primary) ? "http" : "https"}://${primary}`;
1086
+ if (input instanceof URL)
1087
+ return new Request(input);
1088
+ if (typeof input === "string")
1089
+ return new Request(new URL(input, `${base}${this.paths.checkout}`));
1090
+ const params = new URLSearchParams();
1091
+ const entries = input instanceof URLSearchParams ? [...input.entries()] : Object.entries(input);
1092
+ for (const [name, value] of entries) {
1093
+ const first = Array.isArray(value) ? value[0] : value;
1094
+ if (typeof first === "string")
1095
+ params.set(name, first);
1096
+ }
1097
+ const query = params.toString();
1098
+ return new Request(`${base}${this.paths.checkout}${query ? `?${query}` : ""}`);
1099
+ }
1100
+ /**
1101
+ * The store checkout URL that hands an agent's cart to a shopper, with a
1102
+ * `relyon_cart` token for the agent checkout. null when the kit doesn't know it.
1103
+ */
1104
+ async handoffUrl(protocol, sessionId, hostname) {
1105
+ const record = await this.ctx.state.get(protocol, sessionId);
1106
+ if (!record)
1107
+ return null;
1108
+ const token = await this.cartTokens.mint({ agentCheckoutId: record.agentCheckoutId ?? sessionId, protocol, inputs: record.inputs });
1109
+ const origin = hostname && this.hostnames.includes(hostname.toLowerCase())
1110
+ ? `https://${hostname.toLowerCase()}`
1111
+ : this.configuredOrigin ?? `https://${this.hostnames[0]}`;
1112
+ return `${origin}${this.paths.checkout}?relyon_cart=${encodeURIComponent(token)}`;
1113
+ }
1114
+ /** Reports a shipped, delivered or canceled order. */
1115
+ reportFulfillment(orderId, update) {
1116
+ return reportFulfillment(this.gateway, orderId, update);
1117
+ }
1118
+ /**
1119
+ * Adds the store's hostname (default: the primary one) as a Relyon domain,
1120
+ * unless Relyon has it already, and returns it. Only the store's own
1121
+ * configured hostnames are accepted.
1122
+ */
1123
+ async ensureDomain(hostname) {
1124
+ const { domain, created } = await ensureDomain(this.gateway, this.ownHostname(hostname));
1125
+ // The verification file must list the new domain right away, not after the cache expires.
1126
+ if (created)
1127
+ this.discovery.domainsChanged();
1128
+ return domain;
1129
+ }
1130
+ /**
1131
+ * Adds the hostname if needed, then asks Relyon to verify it. Relyon reads
1132
+ * `/.well-known/relyon-verification` from this store (or the DNS TXT record)
1133
+ * while the call runs, so the kit must already be serving the hostname.
1134
+ * A verified domain is returned as it is; a pending or failed one is
1135
+ * checked again. Resolves with the domain after the check: look at
1136
+ * `status` and `failure_reason`.
1137
+ */
1138
+ async verifyDomain(hostname) {
1139
+ const domain = await this.ensureDomain(hostname);
1140
+ if (domain.status === "verified")
1141
+ return domain;
1142
+ this.discovery.domainsChanged();
1143
+ try {
1144
+ return await verifyDomain(this.gateway, domain.id);
1145
+ }
1146
+ finally {
1147
+ this.discovery.domainsChanged();
1148
+ }
1149
+ }
1150
+ /** The store's return, support and consumer-notice policies, with `complete` and `missing`. */
1151
+ storePolicies() {
1152
+ return readStorePolicies(this.gateway);
1153
+ }
1154
+ /** Replaces every store policy field (an omitted field is cleared). Incomplete policies are stored and reported. */
1155
+ replaceStorePolicies(input) {
1156
+ return replaceStorePolicies(this.gateway, policyReplacement(input, this.policies));
1157
+ }
1158
+ /**
1159
+ * Keeps Relyon's store policies in step with the store's own policy pages
1160
+ * (the `policies` option). Without `confirm: true` it only reads and
1161
+ * returns the plan: every field it would change (`changes`) and what the
1162
+ * merchant must still supply (`needs`). Show the changes to the merchant;
1163
+ * once they confirm, call again with `confirm: true` to replace the
1164
+ * policies. A return cost comes only from `returns` here or a cost already
1165
+ * stored in Relyon: the kit never infers free returns or a return cost.
1166
+ */
1167
+ async syncStorePolicies(options = {}) {
1168
+ const current = await readStorePolicies(this.gateway);
1169
+ const { confirm, ...confirmed } = options;
1170
+ const plan = planStorePolicySync(current, this.policiesForRelyon(), confirmed);
1171
+ if (confirm !== true || plan.changes.length === 0)
1172
+ return { ...plan, applied: false, policies: current };
1173
+ const policies = await replaceStorePolicies(this.gateway, plan.input);
1174
+ return { ...plan, applied: true, policies };
1175
+ }
1176
+ /**
1177
+ * The policy pages as Relyon stores them: Relyon keeps only public https
1178
+ * pages, so a Test store's local http policy URL (localhost, 127.0.0.1,
1179
+ * [::1]) is sent on the store's https public address (STORE_PUBLIC_URL), or
1180
+ * refused with the fix when the kit doesn't know one. Nothing is sent then.
1181
+ */
1182
+ policiesForRelyon() {
1183
+ const policies = this.policies;
1184
+ if (!policies)
1185
+ return policies;
1186
+ const local = [...["shippingUrl", "privacyUrl", "termsUrl", "contactUrl"].map((field) => [field, policies[field]]),
1187
+ ["returns.policyUrl", policies.returns?.policyUrl]].filter(([, url]) => url !== undefined && isLoopbackPolicyUrl(url));
1188
+ if (!local.length)
1189
+ return policies;
1190
+ const origin = this.configuredOrigin;
1191
+ if (!origin || !origin.startsWith("https://")) {
1192
+ throw new TypeError(`policies.${local[0][0]} is a local http address, and Relyon stores only public https policy pages. `
1193
+ + "Set STORE_PUBLIC_URL (store.publicUrl) to the store's https address so the kit sends the same page path there, or use the page's https URL. Nothing was sent.");
1194
+ }
1195
+ const move = (url) => url !== undefined && isLoopbackPolicyUrl(url)
1196
+ ? new URL(`${new URL(url).pathname}${new URL(url).search}`, origin).href : url;
1197
+ const out = {};
1198
+ for (const field of ["shippingUrl", "privacyUrl", "termsUrl", "contactUrl"]) {
1199
+ const url = move(policies[field]);
1200
+ if (url !== undefined)
1201
+ out[field] = url;
1202
+ }
1203
+ if (policies.returns) {
1204
+ const policyUrl = move(policies.returns.policyUrl);
1205
+ out.returns = { ...policies.returns, ...(policyUrl !== undefined ? { policyUrl } : {}) };
1206
+ }
1207
+ return out;
1208
+ }
1209
+ ownHostname(hostname) {
1210
+ if (hostname === undefined)
1211
+ return this.hostnames[0];
1212
+ const wanted = hostname.toLowerCase();
1213
+ if (!this.hostnames.includes(wanted))
1214
+ throw new TypeError(`${hostname} is not one of the store's hostnames (store.hostnames).`);
1215
+ return wanted;
1216
+ }
1217
+ /**
1218
+ * schema.org `Product` JSON-LD for a product page. With the page's
1219
+ * `request`, links on the store's own hostnames (and dev addresses) are
1220
+ * moved onto `publicOrigin(request)`.
1221
+ */
1222
+ productJsonLd(product, request) {
1223
+ return productJsonLd(product, this.policies, request ? { origin: this.publicOrigin(request), hostnames: this.hostnames } : undefined);
1224
+ }
1225
+ renderProductJsonLd(product, request) {
1226
+ return jsonLdScript(this.productJsonLd(product, request));
1227
+ }
1228
+ /**
1229
+ * schema.org `ItemList` JSON-LD for the homepage product list: each entry
1230
+ * carries the product's name, price, currency, availability, brand and
1231
+ * `sku` (`gtin` / `mpn` only when supplied). At most 100 products.
1232
+ */
1233
+ productListJsonLd(products, request) {
1234
+ return productListJsonLd(products, this.policies, request ? { origin: this.publicOrigin(request), hostnames: this.hostnames } : undefined);
1235
+ }
1236
+ renderProductListJsonLd(products, request) {
1237
+ return jsonLdScript(this.productListJsonLd(products, request));
1238
+ }
1239
+ /**
1240
+ * Where agents find the store, for the homepage `<head>`: llms.txt, the
1241
+ * UCP profile, the MCP server, the ACP checkout endpoint, the agent card,
1242
+ * the product sitemap and every feed the store serves, all on
1243
+ * `publicOrigin(request)`.
1244
+ */
1245
+ discoveryLinks(request) {
1246
+ const origin = this.publicOrigin(request), paths = this.paths;
1247
+ return [
1248
+ { rel: "alternate", href: `${origin}${paths.llmsTxt}`, type: "text/plain", title: "llms.txt" },
1249
+ { rel: "alternate", href: `${origin}/.well-known/ucp`, type: "application/json", title: "UCP business profile" },
1250
+ { rel: "alternate", href: `${origin}${paths.mcp}`, type: "application/json", title: "MCP server" },
1251
+ // No checkout endpoint is advertised while checkout waits for a sandbox key.
1252
+ ...(this.gateway.waitingForSandboxKey ? [] : [{ rel: "alternate", href: `${origin}${paths.acp}/checkout_sessions`, type: "application/json", title: "ACP checkout (Agentic Commerce Protocol)" }]),
1253
+ ...(this.servesAgentCard ? [{ rel: "alternate", href: `${origin}/.well-known/agent-card.json`, type: "application/json", title: "Agent card" }] : []),
1254
+ { rel: "sitemap", href: `${origin}${paths.sitemap}`, type: "application/xml", title: "Product sitemap" },
1255
+ ...(this.feeds?.urls(origin) ?? []).map((href) => ({
1256
+ rel: "alternate", href, type: href.endsWith(".gz") ? "application/gzip" : href.endsWith(".jsonl") ? "application/x-ndjson" : "application/rss+xml", title: feedLabel(href),
1257
+ })),
1258
+ ];
1259
+ }
1260
+ /** `discoveryLinks(request)` as `<link>` tags for the homepage `<head>`. */
1261
+ renderDiscoveryLinks(request) {
1262
+ const attr = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1263
+ return this.discoveryLinks(request)
1264
+ .map((link) => `<link rel="${attr(link.rel)}" type="${attr(link.type)}" title="${attr(link.title)}" href="${attr(link.href)}">`)
1265
+ .join("\n");
1266
+ }
1267
+ /**
1268
+ * Whether Relyon reports this store's ChatGPT channel approved and
1269
+ * connected (`GET /v1/channels/chatgpt` status `connected`, same mode).
1270
+ * Read at most once a minute; a failed read counts as not connected.
1271
+ */
1272
+ async chatgptConnected() {
1273
+ if (this.gateway.waitingForSandboxKey)
1274
+ return false;
1275
+ if (this.chatgptChannel && this.now() - this.chatgptChannel.at < 60_000)
1276
+ return this.chatgptChannel.connected;
1277
+ let connected = false;
1278
+ try {
1279
+ const { data } = await this.gateway.call((client) => client.GET(CHANNEL_PATH, { params: { path: { name: "chatgpt" } } }), (value) => isRecord(value) && typeof value.status === "string" && typeof value.livemode === "boolean");
1280
+ connected = data.status === "connected" && data.livemode === this.gateway.livemode;
1281
+ }
1282
+ catch (error) {
1283
+ this.logger.warn("could not read the ChatGPT channel; ChatGPT feed items stay not checkout-eligible", { error: describeError(error) });
1284
+ }
1285
+ this.chatgptChannel = { at: this.now(), connected };
1286
+ return connected;
1287
+ }
1288
+ }
1289
+ export class BodyTooLargeError extends Error {
1290
+ constructor() {
1291
+ super("The request body is too large.");
1292
+ this.name = "BodyTooLargeError";
1293
+ }
1294
+ }
1295
+ export function createStoreKit(options) {
1296
+ return new StoreKit(options);
1297
+ }
1298
+ /** Creates the kit from project-space options (or the store kit's, unchanged). */
1299
+ export function createKit(options) {
1300
+ if ("store" in options && options.store)
1301
+ return new StoreKit(options);
1302
+ const { projectSpace, ...rest } = options;
1303
+ if (!projectSpace || typeof projectSpace !== "object")
1304
+ throw new TypeError("createKit needs projectSpace (its hostnames and name).");
1305
+ const { id, ...store } = projectSpace;
1306
+ const publicUrl = store.publicUrl ?? publicUrlFromEnv();
1307
+ const relyon = id ? { ...rest.relyon, projectSpace: id } : rest.relyon;
1308
+ return new StoreKit({ ...rest, relyon, store: { ...store, ...(publicUrl ? { publicUrl } : {}) } });
1309
+ }