@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/relyon.js ADDED
@@ -0,0 +1,238 @@
1
+ import { namesProjectSpace, PROJECT_SPACE_REQUIRED, PROJECT_SPACE_REQUIRED_GUIDANCE, projectSpaceHeaders, projectSpaceProblemCode } from "./wire-names.js";
2
+ import { projectSpaceFromEnv } from "./kit-environment.js";
3
+ import { usableApiKey } from "./api-key.js";
4
+ import { createRelyonClient } from "./sdk/index.js";
5
+ import { isRecord } from "./util.js";
6
+ import { DEVELOPER_HINT, setupError } from "./waiting.js";
7
+ /**
8
+ * Relyon could not give a usable answer: it was unreachable, timed out,
9
+ * answered 5xx, or answered something that doesn't match the contract.
10
+ * Decision calls (checkout steps, payments) are refused when this happens;
11
+ * discovery reads fall back to their last good copy.
12
+ */
13
+ export class RelyonUnavailableError extends Error {
14
+ kind;
15
+ status;
16
+ notSent;
17
+ constructor(kind, message, status,
18
+ /**
19
+ * True only when the request provably never left the store: the
20
+ * connection was refused or the hostname didn't resolve. Anything else
21
+ * (a reset, a timeout, an unknown network error) may have been sent.
22
+ */
23
+ notSent = false) {
24
+ super(message);
25
+ this.kind = kind;
26
+ this.status = status;
27
+ this.notSent = notSent;
28
+ this.name = "RelyonUnavailableError";
29
+ }
30
+ }
31
+ /** Network error codes that mean no request bytes were sent: connection refused, or DNS failure. */
32
+ const NOT_SENT_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EAI_NONAME", "EAI_FAIL"]);
33
+ /**
34
+ * True when a fetch failure provably happened before the request was sent.
35
+ * Follows `cause` chains (Node's fetch wraps the socket error) and requires
36
+ * every attempt of an AggregateError (happy eyeballs) to be pre-send.
37
+ */
38
+ export function failedBeforeSending(error, depth = 0) {
39
+ if (depth > 5 || typeof error !== "object" || error === null)
40
+ return false;
41
+ const { code, cause, errors } = error;
42
+ if (Array.isArray(errors) && errors.length > 0)
43
+ return errors.every((inner) => failedBeforeSending(inner, depth + 1));
44
+ if (typeof code === "string" && NOT_SENT_CODES.has(code))
45
+ return true;
46
+ return cause !== undefined && failedBeforeSending(cause, depth + 1);
47
+ }
48
+ /**
49
+ * The mode a connection runs in. Live needs both a Live key and the explicit
50
+ * `live: true` opt-in; either one alone is refused with a `TypeError`.
51
+ */
52
+ export function liveModeFor(connection) {
53
+ if (connection.live !== undefined && typeof connection.live !== "boolean") {
54
+ throw new TypeError("relyon.live must be true or false.");
55
+ }
56
+ const liveKey = typeof connection.apiKey === "string" && connection.apiKey.startsWith("rly_live_");
57
+ if (connection.live === true && !liveKey) {
58
+ throw new TypeError("relyon.live is true but the key is not a Live secret key (rly_live_…). Use the store's Live key, or remove live: true to run in Test mode.");
59
+ }
60
+ if (liveKey && connection.live !== true) {
61
+ throw new TypeError("This is a Live secret key (rly_live_…). Without relyon.live: true the kit runs in Test mode only. Live mode must be switched on explicitly with relyon.live: true; use a rly_test_ key for Test mode.");
62
+ }
63
+ return connection.live === true;
64
+ }
65
+ /** Relyon refused the store's request with a contract Problem (4xx). */
66
+ export class RelyonProblemError extends Error {
67
+ status;
68
+ code;
69
+ param;
70
+ problem;
71
+ constructor(status, code, message, param,
72
+ /** The whole Problem body Relyon answered with (extra fields included). */
73
+ problem) {
74
+ super(message);
75
+ this.status = status;
76
+ this.code = code;
77
+ this.param = param;
78
+ this.problem = problem;
79
+ this.name = "RelyonProblemError";
80
+ if (KEY_PROBLEM_CODES.has(code))
81
+ this.developer_hint = DEVELOPER_HINT;
82
+ }
83
+ /** For the store's builder when Relyon refused the key itself (never shown to shoppers). */
84
+ developer_hint;
85
+ }
86
+ /** Refusals that mean the store's key is missing or wrong, not the request. */
87
+ const KEY_PROBLEM_CODES = new Set(["invalid_api_key", "authentication_required", "key_environment_mismatch", "sandbox_key_pending"]);
88
+ /**
89
+ * Problems meaning this store's Relyon account can't do this in this mode
90
+ * yet. They are final: retrying (or retrying a charge) can't change the
91
+ * answer until Relyon changes the account.
92
+ */
93
+ export const ACCOUNT_NOT_READY_CODES = ["processor_not_configured", "sandbox_test_only", "live_not_available"];
94
+ const ACCOUNT_NOT_READY_MESSAGES = {
95
+ processor_not_configured: "Payments are not set up for this store in this mode: Relyon has no usable payment processor account for it. Don't retry the payment; Relyon staff must configure the store's processor account first.",
96
+ sandbox_test_only: "This store's Relyon account is a sandbox, which works in Test mode only for now. Don't retry with this key; use the store's Test key, or ask Relyon about moving the account to Live.",
97
+ live_not_available: "Relyon does not offer this in Live mode for this store yet. Don't retry; keep using Test mode until Relyon enables it.",
98
+ };
99
+ /**
100
+ * Relyon refused because the store's account isn't ready for this mode
101
+ * (`processor_not_configured`, `sandbox_test_only`, `live_not_available`).
102
+ * Fail closed: never retried, and a payment refused this way is never resent.
103
+ * `message` is the kit's explanation; `relyonMessage` is Relyon's own.
104
+ */
105
+ export class RelyonAccountNotReadyError extends RelyonProblemError {
106
+ relyonMessage;
107
+ retryable = false;
108
+ constructor(status, code, relyonMessage, param, problem) {
109
+ super(status, code, ACCOUNT_NOT_READY_MESSAGES[code], param, problem);
110
+ this.relyonMessage = relyonMessage;
111
+ this.name = "RelyonAccountNotReadyError";
112
+ }
113
+ }
114
+ export function isAccountNotReadyCode(code) {
115
+ return typeof code === "string" && ACCOUNT_NOT_READY_CODES.includes(code);
116
+ }
117
+ /**
118
+ * The SDK client with a timeout on every call and one strict rule: anything
119
+ * but a well-formed 2xx answer or a well-formed Problem is "unavailable".
120
+ */
121
+ export class RelyonGateway {
122
+ configuredClient;
123
+ waitingForSandboxKey;
124
+ get client() {
125
+ if (!this.configuredClient)
126
+ throw new RelyonProblemError(503, "sandbox_key_pending", "Checkout is waiting for sandbox key. No payment or order was created.");
127
+ return this.configuredClient;
128
+ }
129
+ baseUrl;
130
+ /** The timeout for every call to Relyon, in milliseconds. */
131
+ timeoutMs;
132
+ /** True only when Live was switched on explicitly (`live: true`) with a Live key. */
133
+ livemode;
134
+ constructor(given) {
135
+ // An empty, placeholder or malformed key is no key: the kit waits for a
136
+ // sandbox key (Test only) instead of failing every call with invalid_api_key.
137
+ const connection = { ...given, apiKey: usableApiKey(given.apiKey) };
138
+ if (given.live === true && !connection.apiKey)
139
+ 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.");
140
+ this.livemode = liveModeFor(connection);
141
+ this.waitingForSandboxKey = !connection.apiKey;
142
+ const timeoutMs = connection.timeoutMs ?? 10_000;
143
+ this.timeoutMs = timeoutMs;
144
+ const baseFetch = connection.fetch ?? ((input, init) => fetch(input, init));
145
+ // Every call names the project space (by ID when one is configured, and
146
+ // by hostname) so an unbound workspace key resolves this space; a call
147
+ // that already names it keeps its own headers.
148
+ const spaceHeaders = projectSpaceHeaders({
149
+ id: connection.projectSpace !== undefined ? connection.projectSpace.trim() || undefined : projectSpaceFromEnv(),
150
+ hostname: connection.storeHostname,
151
+ });
152
+ const storeFetch = Object.keys(spaceHeaders).length
153
+ ? (request, init) => {
154
+ if (namesProjectSpace(request.headers))
155
+ return baseFetch(request, init);
156
+ const headers = new Headers(request.headers);
157
+ for (const [name, value] of Object.entries(spaceHeaders))
158
+ headers.set(name, value);
159
+ return baseFetch(new Request(request, { headers }), init);
160
+ }
161
+ : baseFetch;
162
+ this.baseUrl = connection.baseUrl;
163
+ this.configuredClient = connection.apiKey ? createRelyonClient({
164
+ baseUrl: connection.baseUrl,
165
+ apiKey: connection.apiKey,
166
+ ...(connection.version ? { version: connection.version } : {}),
167
+ fetch: (request) => withTimeout(storeFetch, request, timeoutMs),
168
+ }) : undefined;
169
+ }
170
+ /**
171
+ * Runs one SDK call. `valid` checks the 2xx body against the contract shape
172
+ * the kit relies on; a body that fails it is treated as Relyon being down.
173
+ */
174
+ async call(run, valid) {
175
+ if (this.waitingForSandboxKey)
176
+ throw new RelyonProblemError(503, "sandbox_key_pending", "Checkout is waiting for sandbox key.");
177
+ let result;
178
+ try {
179
+ result = await run(this.client);
180
+ }
181
+ catch (error) {
182
+ if (error instanceof RelyonUnavailableError)
183
+ throw error;
184
+ if (error instanceof SyntaxError)
185
+ throw new RelyonUnavailableError("malformed", "Relyon answered with a body that isn't JSON.");
186
+ throw new RelyonUnavailableError("unreachable", `Relyon could not be reached: ${error?.message ?? String(error)}`, undefined, failedBeforeSending(error));
187
+ }
188
+ const { response } = result;
189
+ // 501 with a Problem is a decision (e.g. protocol_not_available), not an outage.
190
+ const deliberate = response.status === 501 && isRecord(result.error) && typeof result.error.code === "string";
191
+ if (response.status >= 500 && !deliberate) {
192
+ throw new RelyonUnavailableError("server_error", `Relyon answered ${response.status}.`, response.status);
193
+ }
194
+ if (response.ok) {
195
+ if (!valid(result.data))
196
+ throw new RelyonUnavailableError("malformed", "Relyon's answer doesn't match the contract.", response.status);
197
+ return { data: result.data, response };
198
+ }
199
+ const problem = result.error;
200
+ if (isRecord(problem) && typeof problem.code === "string") {
201
+ // Relyon's Problem body carries the plain explanation in `detail` (RFC
202
+ // 9457); older kit reads looked only at `message` and so printed the
203
+ // bare code, e.g. "(409 invalid_request): invalid_request".
204
+ // Old "store" codes read as their project-space names.
205
+ const code = projectSpaceProblemCode(problem.code);
206
+ const stated = typeof problem.message === "string" ? problem.message
207
+ : typeof problem.detail === "string" ? problem.detail : code;
208
+ const message = code === PROJECT_SPACE_REQUIRED ? `${stated} ${PROJECT_SPACE_REQUIRED_GUIDANCE}` : stated;
209
+ const param = typeof problem.param === "string" ? problem.param : undefined;
210
+ if (isAccountNotReadyCode(code))
211
+ throw new RelyonAccountNotReadyError(response.status, code, message, param, problem);
212
+ throw new RelyonProblemError(response.status, code, message, param, problem);
213
+ }
214
+ throw new RelyonUnavailableError("malformed", `Relyon answered ${response.status} without a Problem body.`, response.status);
215
+ }
216
+ }
217
+ async function withTimeout(fetchImpl, request, timeoutMs) {
218
+ const controller = new AbortController();
219
+ let timer;
220
+ const timeout = new Promise((_, reject) => {
221
+ timer = setTimeout(() => {
222
+ controller.abort();
223
+ reject(new RelyonUnavailableError("timeout", `Relyon did not answer within ${timeoutMs} ms.`));
224
+ }, timeoutMs);
225
+ });
226
+ try {
227
+ return await Promise.race([fetchImpl(request, { signal: controller.signal }), timeout]);
228
+ }
229
+ finally {
230
+ clearTimeout(timer);
231
+ }
232
+ }
233
+ /** The script URL for `<relyon-card-fields>`, served by Relyon next to its API. */
234
+ export function cardFieldsScriptUrl(baseUrl) {
235
+ const url = new URL(baseUrl);
236
+ const prefix = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "");
237
+ return `${url.origin}${prefix}/public/relyon-card-fields.js`;
238
+ }
@@ -0,0 +1,27 @@
1
+ /** Vendor-verified search/shopping/user-fetch tokens, not training crawlers. */
2
+ export declare const AI_DISCOVERY_CRAWLERS: readonly ["OAI-SearchBot", "ChatGPT-User", "Claude-SearchBot", "Claude-User", "PerplexityBot", "Perplexity-User", "Googlebot", "Storebot-Google", "bingbot"];
3
+ export interface RobotsOptions {
4
+ origin: string;
5
+ sitemapPath?: string;
6
+ /** The store's root sitemap index (the kit serves `/sitemap.xml`), linked with its own `Sitemap:` line. */
7
+ sitemapIndexPath?: string;
8
+ llmsPath?: string;
9
+ }
10
+ export interface RobotsConflict {
11
+ code: "explicit_disallow" | "wildcard_disallow" | "unsupported_directive" | "unfinished_group";
12
+ line: number;
13
+ message: string;
14
+ }
15
+ export interface RobotsMerge {
16
+ content: string;
17
+ changed: boolean;
18
+ conflicts: readonly RobotsConflict[];
19
+ }
20
+ /** Standalone section only. Use mergeAiRobots for an existing file. No checkout disallow is added. */
21
+ export declare function aiRobotsSection(options: RobotsOptions): string;
22
+ /**
23
+ * Append-only and atomic: any conflict returns the original text unchanged.
24
+ * New specific-agent groups inherit EVERY wildcard rule so private paths never
25
+ * become accessible merely because a more specific group was introduced.
26
+ */
27
+ export declare function mergeAiRobots(existing: string, options: RobotsOptions): RobotsMerge;
package/dist/robots.js ADDED
@@ -0,0 +1,127 @@
1
+ import { storeDomainUrl } from "./catalog-reads.js";
2
+ import { isLoopbackHostname } from "./preview-hosts.js";
3
+ /** Vendor-verified search/shopping/user-fetch tokens, not training crawlers. */
4
+ export const AI_DISCOVERY_CRAWLERS = [
5
+ "OAI-SearchBot", "ChatGPT-User", "Claude-SearchBot", "Claude-User",
6
+ "PerplexityBot", "Perplexity-User", "Googlebot", "Storebot-Google", "bingbot",
7
+ ];
8
+ function locations(options) {
9
+ const origin = new URL(options.origin);
10
+ // A Test loopback store (plain http on localhost with a port) is the one http origin allowed.
11
+ const loopback = origin.protocol === "http:" && isLoopbackHostname(origin.hostname);
12
+ if (origin.origin !== options.origin.replace(/\/$/, "") || (!loopback && !storeDomainUrl(origin.href, [origin.hostname]))) {
13
+ throw new TypeError("Robots helpers need an HTTPS store origin.");
14
+ }
15
+ const locate = (path) => {
16
+ if (!path.startsWith("/") || path.startsWith("//") || /[\s#\\]/.test(path))
17
+ throw new TypeError("Robots paths must be local absolute paths.");
18
+ const url = new URL(path, origin);
19
+ if (url.origin !== origin.origin)
20
+ throw new TypeError("Robots paths cannot leave the store.");
21
+ return url.href;
22
+ };
23
+ return {
24
+ sitemap: locate(options.sitemapPath ?? "/sitemap-products.xml"), llms: locate(options.llmsPath ?? "/llms.txt"),
25
+ ...(options.sitemapIndexPath ? { index: locate(options.sitemapIndexPath) } : {}),
26
+ };
27
+ }
28
+ function section(tokens, rules, links) {
29
+ const lines = ["# AI search/shopping discovery. Not payment authorization or a WAF exception."];
30
+ for (const token of tokens) {
31
+ lines.push(`User-agent: ${token}`, "Allow: /", ...rules.map(rule => `${rule.key}: ${rule.value}`), "");
32
+ }
33
+ if (links.index)
34
+ lines.push(`Sitemap: ${links.index}`);
35
+ if (links.sitemap)
36
+ lines.push(`Sitemap: ${links.sitemap}`);
37
+ if (links.llms)
38
+ lines.push(`# llms.txt: ${links.llms}`);
39
+ return lines.join("\n") + "\n";
40
+ }
41
+ /** Standalone section only. Use mergeAiRobots for an existing file. No checkout disallow is added. */
42
+ export function aiRobotsSection(options) {
43
+ return section(AI_DISCOVERY_CRAWLERS, [], locations(options));
44
+ }
45
+ /**
46
+ * Append-only and atomic: any conflict returns the original text unchanged.
47
+ * New specific-agent groups inherit EVERY wildcard rule so private paths never
48
+ * become accessible merely because a more specific group was introduced.
49
+ */
50
+ export function mergeAiRobots(existing, options) {
51
+ const links = locations(options);
52
+ const groups = [], globals = [], conflicts = [];
53
+ let group;
54
+ for (const [index, raw] of existing.split(/\r?\n/).entries()) {
55
+ const line = raw.replace(/#.*$/, "").trim();
56
+ if (!line)
57
+ continue;
58
+ const match = /^([^:]+):\s*(.*)$/.exec(line);
59
+ if (!match) {
60
+ conflicts.push({ code: "unsupported_directive", line: index + 1, message: "Resolve this unrecognized robots line before merging." });
61
+ continue;
62
+ }
63
+ const key = match[1].trim().toLowerCase(), value = match[2].trim();
64
+ if (key === "user-agent") {
65
+ if (!value || !/^[a-z0-9_.*-]+$/i.test(value)) {
66
+ conflicts.push({ code: "unsupported_directive", line: index + 1, message: "Resolve the invalid user-agent token." });
67
+ continue;
68
+ }
69
+ if (!group || group.rules.length) {
70
+ group = { agents: [], rules: [], line: index + 1 };
71
+ groups.push(group);
72
+ }
73
+ group.agents.push(value.toLowerCase());
74
+ }
75
+ else if (key === "sitemap")
76
+ globals.push({ key, value, line: index + 1 });
77
+ else if (group && ["allow", "disallow", "crawl-delay"].includes(key))
78
+ group.rules.push({ key, value, line: index + 1 });
79
+ else
80
+ conflicts.push({ code: "unsupported_directive", line: index + 1, message: `Resolve or manually merge "${key}"; the helper cannot safely interpret it.` });
81
+ }
82
+ for (const current of groups)
83
+ if (!current.rules.length)
84
+ conflicts.push({
85
+ code: "unfinished_group", line: current.line, message: "This user-agent group has no rules; appending could combine it with another group. Finish it explicitly.",
86
+ });
87
+ const wildcards = groups.filter(current => current.agents.includes("*")).flatMap(current => current.rules);
88
+ // A root or public discovery denial needs a deliberate merchant decision.
89
+ const publicPaths = ["/", new URL(links.sitemap).pathname, ...(links.index ? [new URL(links.index).pathname] : []), new URL(links.llms).pathname, "/feeds/openai.jsonl", "/feeds/openai.jsonl.gz", "/feeds/google.xml", "/feeds/microsoft.xml"];
90
+ const deniesDiscovery = (rule) => {
91
+ if (rule.key !== "disallow" || !rule.value)
92
+ return false;
93
+ const escaped = rule.value.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\\\$$/, "$");
94
+ try {
95
+ return publicPaths.some(path => new RegExp(`^${escaped}`).test(path));
96
+ }
97
+ catch {
98
+ return true;
99
+ }
100
+ };
101
+ for (const rule of wildcards.filter(deniesDiscovery))
102
+ conflicts.push({
103
+ code: "wildcard_disallow", line: rule.line, message: `Wildcard rule "${rule.value}" blocks discovery. Keep it or change it explicitly; no override was added.`,
104
+ });
105
+ const additions = [];
106
+ for (const token of AI_DISCOVERY_CRAWLERS) {
107
+ const matched = groups.filter(current => current.agents.some(agent => agent !== "*" && token.toLowerCase().includes(agent)));
108
+ for (const current of matched)
109
+ for (const rule of current.rules) {
110
+ if (rule.key === "disallow" && rule.value && !wildcards.some(wildcard => wildcard.key === rule.key && wildcard.value === rule.value)) {
111
+ conflicts.push({ code: "explicit_disallow", line: rule.line, message: `${token} has an explicit disallow "${rule.value}". Resolve it manually; existing policy was preserved.` });
112
+ }
113
+ }
114
+ if (!matched.length)
115
+ additions.push(token);
116
+ }
117
+ if (conflicts.length)
118
+ return { content: existing, changed: false, conflicts };
119
+ const sitemap = globals.some(rule => rule.value === links.sitemap) ? undefined : links.sitemap;
120
+ const index = links.index && !globals.some(rule => rule.value === links.index) ? links.index : undefined;
121
+ const llms = existing.split(/\r?\n/).some(line => line.trim() === `# llms.txt: ${links.llms}`) ? undefined : links.llms;
122
+ if (!additions.length && !sitemap && !llms && !index)
123
+ return { content: existing, changed: false, conflicts: [] };
124
+ const uniqueRules = [...new Map(wildcards.map(rule => [`${rule.key}:${rule.value}`, rule])).values()];
125
+ const addition = section(additions, uniqueRules, { ...(index ? { index } : {}), ...(sitemap ? { sitemap } : {}), ...(llms ? { llms } : {}) });
126
+ return { content: existing + (existing ? (existing.endsWith("\n") ? "\n" : "\n\n") : "") + addition, changed: true, conflicts: [] };
127
+ }
@@ -0,0 +1,144 @@
1
+ import type { AgentRules, Logger } from "./types.js";
2
+ import { type RelyonGateway } from "./relyon.js";
3
+ /** The response header carrying the doctor challenge acknowledgement. */
4
+ export declare const DOCTOR_ACKNOWLEDGEMENT_HEADER = "relyon-doctor-acknowledgement";
5
+ /**
6
+ * The contract's doctor acknowledgement: lowercase hex HMAC-SHA256, with the
7
+ * webhook endpoint's signing secret, of
8
+ * "relyon.doctor.ack.v1\n<id>\n<challenge>\n<created>" (no trailing newline).
9
+ */
10
+ export declare function doctorAcknowledgement(secret: string, id: string, challenge: string, created: number): string;
11
+ export interface AgentRulesOptions {
12
+ /**
13
+ * The webhook endpoint secret that signs `agent_rules.updated`. When this is
14
+ * unset and the kit has a usable key, the receiver resolves the secret
15
+ * itself at runtime (see `recoverSecretForUrl`). Without either, webhooks
16
+ * are refused.
17
+ */
18
+ webhookSecret?: string;
19
+ /**
20
+ * Runtime secret recovery, wired by the kit: the receiver's own endpoint URL
21
+ * (the store's configured public origin plus its webhook path). The first
22
+ * delivery with no configured secret replays this URL's deterministic
23
+ * registration (`sk-whe-<sha256(url)>`, an existing contract operation) with
24
+ * the store's own key, accepting the answer only when the shape checks pass
25
+ * (livemode matching the kit's mode, a secret of the mode's shape) and it
26
+ * names the newest active endpoint. The secret is cached in memory and
27
+ * never logged. After any resolution failure the receiver backs off (60s,
28
+ * doubling to 15 minutes) and warns at most once per cooldown window, and a
29
+ * bad signature against the cached secret re-resolves at most once per
30
+ * cooldown — a re-resolution returning the same (still stale) secret counts
31
+ * as a failure, so the backoff doubles instead of resetting. A request
32
+ * handler never registers a first endpoint.
33
+ */
34
+ recoverSecretForUrl?: string;
35
+ /** Refresh in the background on a timer as well as on demand. Default true. */
36
+ backgroundRefresh?: boolean;
37
+ }
38
+ /**
39
+ * How long a doctor challenge waits on a cold secret recovery before it
40
+ * answers 503 and lets the shared recovery finish in the background for
41
+ * Relyon's retry (Brief 89c). Comfortably inside the doctor's per-attempt
42
+ * response budget, so the fast answer always beats the probe's abort.
43
+ */
44
+ export declare const CHALLENGE_SECRET_BUDGET_MS = 2500;
45
+ /**
46
+ * The store's merged agent rules, read with `getAgentRules`, used for at most
47
+ * `refresh_seconds` (60 by default) and refreshed early by a signed
48
+ * `agent_rules.updated` webhook. When a refresh fails the last good copy is
49
+ * kept: blocks keep applying while Relyon is away.
50
+ */
51
+ export declare class AgentRulesCache {
52
+ private readonly gateway;
53
+ private readonly options;
54
+ private readonly now;
55
+ private readonly logger;
56
+ private rules;
57
+ private fetchedAt;
58
+ private inflight;
59
+ private timer;
60
+ private stopped;
61
+ private lastAttemptAt;
62
+ /** The secret recovered at runtime; undefined until one resolves. */
63
+ private recoveredSecret;
64
+ private recoveringSecret;
65
+ /** Consecutive resolution failures; drives the backoff. Reset on success. */
66
+ private secretFailures;
67
+ /** Resolution (and bad-signature re-resolution) is refused until this time. */
68
+ private secretBlockedUntil;
69
+ /** The last signature-mismatch warning, throttled to one per cooldown window. */
70
+ private mismatchWarnedAt;
71
+ constructor(gateway: RelyonGateway, options: AgentRulesOptions, now: () => number, logger: Logger);
72
+ get current(): AgentRules | null;
73
+ private get refreshMs();
74
+ /**
75
+ * The rules to apply now. A copy older than `refresh_seconds` is still used
76
+ * while it refreshes in the background, so requests never wait on Relyon
77
+ * once the first copy is in. Before that, the first read waits for Relyon
78
+ * (bounded by the client timeout); while Relyon stays away, further reads
79
+ * retry at most every 5 seconds and get null (no edge rules; Relyon still
80
+ * applies its rules to every checkout step and payment).
81
+ */
82
+ get(): Promise<AgentRules | null>;
83
+ /** Reads the rules from Relyon now. Keeps (and returns) the last good copy when Relyon is unavailable. */
84
+ refresh(): Promise<AgentRules | null>;
85
+ private load;
86
+ private schedule;
87
+ stop(): void;
88
+ /**
89
+ * Handles a Relyon webhook delivery. A valid `agent_rules.updated` refreshes
90
+ * the rules now. Any other validly signed event type is acknowledged (200)
91
+ * and changes nothing; a bad or missing signature is ignored (400).
92
+ */
93
+ handleWebhook(rawBody: string, signature: string | null): Promise<{
94
+ status: number;
95
+ type?: string;
96
+ acknowledgement?: string;
97
+ error?: string;
98
+ }>;
99
+ /**
100
+ * The challenge path's secret wait (Brief 89c). A doctor challenge must be
101
+ * answered fast: a configured or cached secret is used at once, an in-flight
102
+ * recovery is awaited only up to CHALLENGE_SECRET_BUDGET_MS, and a cold
103
+ * recovery is started and awaited under the same bound. When the bound
104
+ * elapses the caller answers 503 while the shared recovery promise keeps
105
+ * running and caches the secret, so Relyon's retry succeeds instead of this
106
+ * request hanging past the doctor's response budget.
107
+ */
108
+ private recoverForChallenge;
109
+ /**
110
+ * Runtime recovery of the webhook signing secret, used only when no
111
+ * `webhookSecret` is configured: find the newest active endpoint for the
112
+ * receiver's own URL and replay its deterministic registration with the
113
+ * store's key. Works in Test and Live with identical semantics: an answer
114
+ * is accepted only when its livemode matches the kit's mode, it names that
115
+ * newest endpoint and it carries a shape-valid secret of the mode. No first
116
+ * endpoint is registered by this receiver. A 409 (a session-owned or legacy
117
+ * registration row, or a Live adoption refusal), an endpoint-id mismatch or
118
+ * a malformed answer fails closed: the webhook is refused as before, with
119
+ * guidance to run the webhook command. No active endpoint for the URL means
120
+ * nothing to replay, so no registration POST ever goes out from a request
121
+ * handler.
122
+ *
123
+ * Every failure starts a cooldown (60s, doubling per consecutive failure up
124
+ * to 15 minutes, reset on success) and warns once per cooldown window, so
125
+ * unsigned-request floods cannot amplify into Relyon calls. With `force`
126
+ * (a bad signature against the cached secret) the same cooldown bounds
127
+ * re-resolution, but a fresh attempt is allowed once the window elapsed —
128
+ * and a forced re-resolution returning the SAME secret the cache already
129
+ * holds counts as a failure (the suspected rotation has not happened), so
130
+ * the backoff doubles instead of resetting.
131
+ */
132
+ /**
133
+ * A secret was loaded (configured or recovered) but the delivery's signature
134
+ * doesn't match it: after `webhook --rotate` the running store still holds
135
+ * the old secret. `attempted` is true only when this delivery ran the
136
+ * bounded re-resolution (or the secret is operator-configured, which never
137
+ * re-resolves): the warning fires once per re-resolution attempt — never
138
+ * per request inside a cooldown window — and the secret's value is never
139
+ * logged.
140
+ */
141
+ private warnSignatureMismatch;
142
+ private resolveWebhookSecret;
143
+ }
144
+ export declare function isAgentRules(data: unknown): data is AgentRules;