@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
@@ -0,0 +1,387 @@
1
+ import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { expandFeedVariants } from "./feeds.js";
3
+ import { describeError } from "./relyon-cart-tokens.js";
4
+ import { StoreRefusal } from "./types.js";
5
+ import { CART_CAPABILITY } from "./ucp-versions.js";
6
+ import { isRecord, jsonResponse, tryParseJson } from "./util.js";
7
+ import { resolveFeedItem } from "./variants.js";
8
+ export const CART_TRANSFER_KEY_ENV = "RELYON_CART_TRANSFER_KEY";
9
+ export const CART_TRANSFER_KEY_HEADER = "x-api-key";
10
+ export const CART_TRANSFER_PARAM = "relyon_transfer";
11
+ const MIN_KEY_LENGTH = 16;
12
+ const DEFAULT_TTL_SECONDS = 24 * 60 * 60;
13
+ const MAX_LINES = 100;
14
+ const MAX_QUANTITY = 999;
15
+ const ITEM_ID = /^[A-Za-z0-9._:-]{1,128}$/;
16
+ /**
17
+ * Whether cart transfer runs, and with which caller key. Test: on by
18
+ * default, open without a key. Live: on only with a key. A key that is too
19
+ * short never opens the endpoint: cart transfer is off and a warning logged.
20
+ */
21
+ export function cartTransferState(option, livemode, env, logger) {
22
+ if (option === false)
23
+ return { enabled: false, reason: "switched_off" };
24
+ const configured = option?.apiKey ?? env[CART_TRANSFER_KEY_ENV];
25
+ const apiKey = typeof configured === "string" && configured.trim() ? configured.trim() : null;
26
+ if (apiKey !== null && apiKey.length < MIN_KEY_LENGTH) {
27
+ logger.warn(`cart transfer is off: its caller key must be at least ${MIN_KEY_LENGTH} characters`);
28
+ return { enabled: false, reason: "invalid_key" };
29
+ }
30
+ if (livemode && apiKey === null)
31
+ return { enabled: false, reason: "live_without_key" };
32
+ const ttl = option?.ttlSeconds;
33
+ return { enabled: true, apiKey, ttlSeconds: Number.isInteger(ttl) && ttl > 0 ? ttl : DEFAULT_TTL_SECONDS };
34
+ }
35
+ /** Compares the caller's key in constant time (hashes first, so lengths never leak). */
36
+ export function callerKeyMatches(expected, given) {
37
+ const a = createHash("sha256").update(expected, "utf8").digest();
38
+ const b = createHash("sha256").update(given, "utf8").digest();
39
+ return timingSafeEqual(a, b);
40
+ }
41
+ const TOKEN_PREFIX = "ct1_";
42
+ const TOKEN_MAX_LENGTH = 4000;
43
+ /** A transferred line's options as sealed in the token: string values only. */
44
+ function sealedOptions(value) {
45
+ if (value === undefined)
46
+ return undefined;
47
+ if (!isRecord(value))
48
+ return null;
49
+ const entries = Object.entries(value);
50
+ if (entries.length > 50 || entries.some(([, option]) => typeof option !== "string"))
51
+ return null;
52
+ return Object.fromEntries(entries);
53
+ }
54
+ /**
55
+ * The `relyon_transfer` token in a transferred cart's `continue_url`:
56
+ * AES-256-GCM sealed `{lines, expiry}`, its own key (HKDF info
57
+ * "relyon_transfer v1") and associated data, so it can never be read as a
58
+ * `relyon_cart` hand-off token or the other way round. Version 2 (kit
59
+ * 0.1.11) carries each line's options; version 1 tokens (kit 0.1.10, IDs and
60
+ * quantities only) are still read.
61
+ */
62
+ export class TransferTokens {
63
+ now;
64
+ ttlSeconds;
65
+ key;
66
+ constructor(secret, now, ttlSeconds) {
67
+ this.now = now;
68
+ this.ttlSeconds = ttlSeconds;
69
+ this.key = Buffer.from(hkdfSync("sha256", secret, "relyon-store-kit", "relyon_transfer v1", 32));
70
+ }
71
+ /** Whether a link for these lines fits in a token (the size depends only on the lines). */
72
+ fits(lines) {
73
+ const payload = Buffer.byteLength(TransferTokens.payload(lines, Math.floor(this.now() / 1000) + this.ttlSeconds), "utf8");
74
+ return TOKEN_PREFIX.length + Math.ceil(((12 + 16 + payload) * 4) / 3) <= TOKEN_MAX_LENGTH;
75
+ }
76
+ static payload(lines, expiresAt) {
77
+ return JSON.stringify({
78
+ v: 2,
79
+ l: lines.map((line) => line.options && Object.keys(line.options).length ? [line.product_id, line.quantity, line.options] : [line.product_id, line.quantity]),
80
+ exp: expiresAt,
81
+ });
82
+ }
83
+ mint(lines) {
84
+ const expiresAt = Math.floor(this.now() / 1000) + this.ttlSeconds;
85
+ return { token: this.seal(TransferTokens.payload(lines, expiresAt)), expiresAt };
86
+ }
87
+ /** Seals a raw payload (also how tests make a kit 0.1.10 token). */
88
+ seal(payload) {
89
+ const iv = randomBytes(12);
90
+ const cipher = createCipheriv("aes-256-gcm", this.key, iv);
91
+ cipher.setAAD(Buffer.from(TOKEN_PREFIX));
92
+ const sealed = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
93
+ const token = TOKEN_PREFIX + Buffer.concat([iv, cipher.getAuthTag(), sealed]).toString("base64url");
94
+ if (token.length > TOKEN_MAX_LENGTH)
95
+ throw new RangeError("This cart is too large for a transfer link.");
96
+ return token;
97
+ }
98
+ /**
99
+ * The token's lines and version, or null for a tampered, expired or foreign
100
+ * token. Never throws.
101
+ */
102
+ read(token) {
103
+ if (typeof token !== "string" || !token.startsWith(TOKEN_PREFIX) || token.length > TOKEN_MAX_LENGTH)
104
+ return null;
105
+ try {
106
+ const raw = Buffer.from(token.slice(TOKEN_PREFIX.length), "base64url");
107
+ if (raw.length < 29)
108
+ return null;
109
+ const decipher = createDecipheriv("aes-256-gcm", this.key, raw.subarray(0, 12));
110
+ decipher.setAAD(Buffer.from(TOKEN_PREFIX));
111
+ decipher.setAuthTag(raw.subarray(12, 28));
112
+ const payload = JSON.parse(Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8"));
113
+ if (!isRecord(payload) || (payload.v !== 1 && payload.v !== 2) || !Array.isArray(payload.l) || !payload.l.length)
114
+ return null;
115
+ if (typeof payload.exp !== "number" || payload.exp <= Math.floor(this.now() / 1000))
116
+ return null;
117
+ const lines = [];
118
+ for (const entry of payload.l) {
119
+ if (!Array.isArray(entry) || typeof entry[0] !== "string" || !Number.isInteger(entry[1]))
120
+ return null;
121
+ const options = payload.v === 2 ? sealedOptions(entry[2]) : undefined;
122
+ if (options === null)
123
+ return null;
124
+ lines.push({ product_id: entry[0], quantity: entry[1], ...(options ? { options } : {}) });
125
+ }
126
+ return { version: payload.v, lines };
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ /** The lines, or null for a tampered, expired or foreign token. Never throws. */
133
+ resolve(token) {
134
+ return this.read(token)?.lines ?? null;
135
+ }
136
+ }
137
+ /** A UCP protocol error (`{code, content}`) with its HTTP status. */
138
+ function protocolError(status, code, content, headers = {}) {
139
+ return jsonResponse(status, { code, content }, headers);
140
+ }
141
+ /** The catalog entries cart transfer can sell, by feed ID: variants win over a product with the same ID. */
142
+ export function transferableItems(products) {
143
+ const byId = new Map();
144
+ for (const entry of expandFeedVariants(products)) {
145
+ const existing = byId.get(entry.merchant_product_id);
146
+ if (existing && existing.feed?.variant && !entry.feed?.variant)
147
+ continue;
148
+ byId.set(entry.merchant_product_id, entry);
149
+ }
150
+ return byId;
151
+ }
152
+ /** Why one catalog entry can't be transferred, or null when it can. */
153
+ function unusable(entry) {
154
+ if (!entry || entry.agent?.visible !== true)
155
+ return { code: "item_not_found", content: "This store has no item with this ID for agents." };
156
+ const agent = entry.agent;
157
+ if (agent.purchasable === false || agent.restrictions || (Array.isArray(agent.must_ask) && agent.must_ask.length)) {
158
+ return { code: "item_unavailable", content: "This item can't be bought through an agent; the shopper can buy it on the store's site." };
159
+ }
160
+ if (entry.configurable === true)
161
+ return { code: "item_unavailable", content: "This product has options; send the feed ID of one variant." };
162
+ if (entry.availability === "out_of_stock")
163
+ return { code: "out_of_stock", content: "This item is out of stock." };
164
+ return null;
165
+ }
166
+ /** The create-cart request's line items, or a description of what is wrong with it. */
167
+ function readRequest(body) {
168
+ if (!isRecord(body))
169
+ return "The request body must be a JSON object.";
170
+ if ("id" in body)
171
+ return "Send a new cart without an id.";
172
+ const items = body.line_items;
173
+ if (!Array.isArray(items) || !items.length)
174
+ return "line_items must be a non-empty array.";
175
+ if (items.length > MAX_LINES)
176
+ return `A cart holds at most ${MAX_LINES} line items.`;
177
+ const lines = [];
178
+ for (const [index, line] of items.entries()) {
179
+ const item = isRecord(line) ? line.item : undefined;
180
+ const id = isRecord(item) ? item.id : undefined;
181
+ const quantity = isRecord(line) ? line.quantity : undefined;
182
+ if (typeof id !== "string" || !id)
183
+ return `line_items[${index}].item.id must be a non-empty string.`;
184
+ if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_QUANTITY) {
185
+ return `line_items[${index}].quantity must be an integer from 1 to ${MAX_QUANTITY}.`;
186
+ }
187
+ lines.push({ itemId: id, quantity: quantity, index });
188
+ }
189
+ return lines;
190
+ }
191
+ /** A UCP error response (no cart was created): `ucp.status` "error" and the messages, no `id`. */
192
+ function errorResponse(version, messages) {
193
+ return jsonResponse(200, { ucp: { version, status: "error", capabilities: { [CART_CAPABILITY]: [{ version }] } }, messages });
194
+ }
195
+ /**
196
+ * The store's priced cart, checked against the lines asked for; null when it
197
+ * doesn't add up. A priced line may name the product or the feed ID (a
198
+ * variant's ID) the caller sent.
199
+ */
200
+ function checkedCart(cart, lines, feedIds = []) {
201
+ if (!isRecord(cart) || !Array.isArray(cart.lines) || cart.lines.length !== lines.length || !isRecord(cart.totals))
202
+ return null;
203
+ if (typeof cart.currency !== "string" || !/^[A-Za-z]{3}$/.test(cart.currency))
204
+ return null;
205
+ const totals = cart.totals;
206
+ const amounts = [totals.subtotal, totals.discount, totals.shipping, totals.tax, totals.total];
207
+ if (!amounts.every((amount) => Number.isSafeInteger(amount) && amount >= 0))
208
+ return null;
209
+ let sum = 0;
210
+ for (const [index, line] of cart.lines.entries()) {
211
+ const named = isRecord(line) ? line.merchant_product_id : undefined;
212
+ if (!isRecord(line) || (named !== lines[index].product_id && named !== feedIds[index]) || line.quantity !== lines[index].quantity)
213
+ return null;
214
+ if (!Number.isSafeInteger(line.amount) || line.amount < 0 || typeof line.title !== "string" || !line.title)
215
+ return null;
216
+ if (line.unit_amount !== undefined && (!Number.isSafeInteger(line.unit_amount) || line.unit_amount < 0))
217
+ return null;
218
+ if (line.discount !== undefined && (!Number.isSafeInteger(line.discount) || line.discount < 0))
219
+ return null;
220
+ sum += line.amount;
221
+ }
222
+ if (sum !== totals.subtotal || totals.total !== totals.subtotal - totals.discount + totals.shipping + totals.tax)
223
+ return null;
224
+ return cart;
225
+ }
226
+ /**
227
+ * Answers `POST <ucp prefix>/carts` at `version`. `continueUrl` builds the
228
+ * store checkout link for a token. Never throws.
229
+ */
230
+ export async function handleCartTransfer(deps, request, rawBody, version, continueUrl) {
231
+ const state = deps.state;
232
+ if (!state.enabled || !deps.tokens)
233
+ return protocolError(404, "not_found", "Cart transfer is not available on this store.");
234
+ if (request.method.toUpperCase() !== "POST")
235
+ return protocolError(405, "method_not_allowed", "Create a cart with POST.", { allow: "POST" });
236
+ if (state.apiKey !== null) {
237
+ const given = request.headers.get(CART_TRANSFER_KEY_HEADER);
238
+ if (!given)
239
+ return protocolError(401, "unauthorized", "This store requires its cart-transfer key in the X-API-Key header.");
240
+ if (!callerKeyMatches(state.apiKey, given))
241
+ return protocolError(403, "forbidden", "The X-API-Key is not this store's cart-transfer key.");
242
+ }
243
+ const requested = readRequest(tryParseJson(rawBody));
244
+ if (typeof requested === "string")
245
+ return protocolError(400, "invalid_request", requested);
246
+ let catalog;
247
+ let products;
248
+ try {
249
+ products = await deps.products();
250
+ catalog = transferableItems(products);
251
+ }
252
+ catch (error) {
253
+ deps.logger.error("cart transfer could not read the catalog", { error: describeError(error) });
254
+ return protocolError(503, "service_unavailable", "The store's catalog is temporarily unavailable; try again shortly.", { "retry-after": "30" });
255
+ }
256
+ const groups = new Set();
257
+ for (const entry of catalog.values())
258
+ if (entry.agent?.visible === true && entry.feed?.variant)
259
+ groups.add(entry.feed.variant.groupId);
260
+ const messages = [];
261
+ const usable = [];
262
+ for (const line of requested) {
263
+ const entry = ITEM_ID.test(line.itemId) ? catalog.get(line.itemId) : undefined;
264
+ // A product's own ID when only its variants are sold: name the fix.
265
+ const why = !entry && ITEM_ID.test(line.itemId) && groups.has(line.itemId)
266
+ ? { code: "item_unavailable", content: "This product has options; send the feed ID of one variant." }
267
+ : unusable(entry);
268
+ if (why)
269
+ messages.push({ type: "error", code: why.code, path: `$.line_items[${line.index}]`, content: `${why.content} (item ${JSON.stringify(line.itemId.slice(0, 128))})`, severity: "recoverable" });
270
+ else
271
+ usable.push(line);
272
+ }
273
+ if (!usable.length)
274
+ return errorResponse(version, messages);
275
+ // A variant's feed ID goes to priceCart as its product plus the variant's
276
+ // options (opaque to the kit, exactly as the store listed them).
277
+ const inputs = usable.map((line) => {
278
+ const resolved = resolveFeedItem(products, line.itemId);
279
+ return resolved && resolved.options
280
+ ? { product_id: resolved.product_id, quantity: line.quantity, options: { ...resolved.options } }
281
+ : { product_id: line.itemId, quantity: line.quantity };
282
+ });
283
+ const feedIds = usable.map((line) => line.itemId);
284
+ // The continue_url carries the lines sealed; refuse before pricing when they can't fit.
285
+ if (!deps.tokens.fits(inputs)) {
286
+ return protocolError(400, "invalid_request", "This cart is too large to transfer: send fewer line items or shorter item IDs (the store's checkout link holds about 2,900 characters of items).");
287
+ }
288
+ let cart;
289
+ try {
290
+ cart = checkedCart(await deps.priceCart(inputs, null, [], { protocol: "ucp", operation: "cart_transfer", shippingOptionId: null, agentCheckoutId: null }), inputs, feedIds);
291
+ }
292
+ catch (error) {
293
+ if (error instanceof StoreRefusal) {
294
+ return errorResponse(version, [...messages, { type: "error", code: error.code, content: error.message, severity: "recoverable" }]);
295
+ }
296
+ deps.logger.error("cart transfer: the store's priceCart threw", { error: describeError(error) });
297
+ return protocolError(500, "internal_error", "The store could not price this cart; try again.");
298
+ }
299
+ if (!cart) {
300
+ deps.logger.error("cart transfer: the store's priceCart returned a cart that doesn't match the items or doesn't add up");
301
+ return protocolError(500, "internal_error", "The store could not price this cart; try again.");
302
+ }
303
+ let minted;
304
+ try {
305
+ minted = deps.tokens.mint(inputs);
306
+ }
307
+ catch (error) {
308
+ deps.logger.error("cart transfer could not seal the checkout link", { error: describeError(error) });
309
+ return protocolError(400, "invalid_request", "This cart is too large to transfer: send fewer line items or shorter item IDs.");
310
+ }
311
+ const { token, expiresAt } = minted;
312
+ const currency = cart.currency.toUpperCase();
313
+ const totals = [{ type: "subtotal", amount: cart.totals.subtotal }];
314
+ // UCP discount entries are negative amounts.
315
+ if (cart.totals.discount > 0)
316
+ totals.push({ type: "discount", amount: -cart.totals.discount });
317
+ if (cart.totals.shipping > 0)
318
+ totals.push({ type: "fulfillment", amount: cart.totals.shipping });
319
+ if (cart.totals.tax > 0)
320
+ totals.push({ type: "tax", amount: cart.totals.tax });
321
+ totals.push({ type: "total", amount: cart.totals.total });
322
+ return jsonResponse(201, {
323
+ ucp: { version, status: "success", capabilities: { [CART_CAPABILITY]: [{ version }] } },
324
+ id: `cart_${randomUUID().replace(/-/g, "")}`,
325
+ line_items: cart.lines.map((line, index) => {
326
+ const before = line.amount + (line.discount ?? 0);
327
+ return {
328
+ id: `li_${index + 1}`,
329
+ // The caller's own item ID (a variant's feed ID), whichever ID the store priced the line under.
330
+ item: { id: feedIds[index], title: line.title, price: line.unit_amount ?? Math.round(before / line.quantity) },
331
+ quantity: line.quantity,
332
+ totals: [
333
+ { type: "subtotal", amount: before },
334
+ ...(line.discount ? [{ type: "items_discount", amount: -line.discount }] : []),
335
+ { type: "total", amount: line.amount },
336
+ ],
337
+ };
338
+ }),
339
+ currency,
340
+ totals,
341
+ ...(messages.length ? { messages } : {}),
342
+ continue_url: continueUrl(token),
343
+ expires_at: new Date(expiresAt * 1000).toISOString().replace(/\.\d{3}Z$/, "Z"),
344
+ });
345
+ }
346
+ /**
347
+ * A shopper landing on the store's checkout with a `relyon_transfer` token:
348
+ * the transferred lines priced again by the store now. Never attributed to an
349
+ * agent checkout and never a payment authority. A bad, expired or tampered
350
+ * token is a normal, unattributed landing.
351
+ */
352
+ export async function transferLanding(tokens, priceCart, token, logger, products) {
353
+ const read = tokens?.read(token) ?? null;
354
+ const plain = { attributed: false, agentCheckoutId: null, protocol: null, channel: "web", cart: null, inputs: null, transferred: false };
355
+ if (!read)
356
+ return plain;
357
+ let lines = read.lines;
358
+ // A kit 0.1.10 link holds feed IDs without options: a variant's ID becomes
359
+ // its product plus that variant's options, as a 0.1.11 link carries them.
360
+ if (read.version === 1 && products) {
361
+ try {
362
+ const catalog = await products();
363
+ lines = lines.map((line) => {
364
+ const resolved = resolveFeedItem(catalog, line.product_id);
365
+ return resolved?.options ? { product_id: resolved.product_id, quantity: line.quantity, options: { ...resolved.options } } : line;
366
+ });
367
+ }
368
+ catch (error) {
369
+ logger.warn("a transferred cart's items could not be matched to the catalog on landing", { error: describeError(error) });
370
+ }
371
+ }
372
+ const inputs = { lines, address: null, coupons: [], shipping_option_id: null };
373
+ try {
374
+ const cart = await priceCart(lines, null, [], { protocol: "web", operation: "landing", shippingOptionId: null, agentCheckoutId: null });
375
+ return { ...plain, cart, inputs, transferred: true };
376
+ }
377
+ catch (error) {
378
+ if (error instanceof StoreRefusal)
379
+ return { ...plain, inputs, transferred: true, refusal: error };
380
+ logger.warn("a transferred cart could not be priced on landing", { error: describeError(error) });
381
+ return { ...plain, inputs, transferred: true };
382
+ }
383
+ }
384
+ /** The kit's catalog read for cart transfer. */
385
+ export function catalogProducts(reads, mirror) {
386
+ return async () => reads ? await reads.all() : mirror.all();
387
+ }
@@ -0,0 +1,6 @@
1
+ import type { StoreProduct } from "./types.js";
2
+ /** Derive descriptive attributes only; options and variant selection remain opaque and unchanged. */
3
+ export declare function withOptionAttributes(product: StoreProduct): StoreProduct;
4
+ export declare function categoryGuidance(product: Pick<StoreProduct, "title" | "merchant_product_id">): string;
5
+ /** Plain terminal output, including unexpected issue shapes instead of hiding them. */
6
+ export declare function formatCatalogIssue(product: string, issue: unknown): string;
@@ -0,0 +1,71 @@
1
+ import { firstOptionValues, productVariants } from "./variants.js";
2
+ import { isRecord } from "./util.js";
3
+ const keys = new Set(["color", "size", "material", "gender", "age_group"]);
4
+ const enums = {
5
+ gender: ["male", "female", "unisex"],
6
+ age_group: ["newborn", "infant", "toddler", "kids", "adult"],
7
+ };
8
+ /** Derive descriptive attributes only; options and variant selection remain opaque and unchanged. */
9
+ export function withOptionAttributes(product) {
10
+ if (product.attributes && Object.keys(product.attributes).length)
11
+ return product;
12
+ const collected = new Map();
13
+ const add = (name, value) => {
14
+ const key = name.trim().toLowerCase().replace(/^colour$/, "color").replace(/[ -]/g, "_");
15
+ if (!keys.has(key))
16
+ return;
17
+ if (Array.isArray(value)) {
18
+ for (const entry of value)
19
+ add(name, isRecord(entry) ? entry.value ?? entry.name ?? entry.label : entry);
20
+ return;
21
+ }
22
+ if (isRecord(value)) {
23
+ add(name, value.values ?? value.choices ?? value.default ?? value.value);
24
+ return;
25
+ }
26
+ const read = firstOptionValues({ [name]: value })?.[name]?.trim();
27
+ if (!read)
28
+ return;
29
+ const normalized = enums[key] ? read.toLowerCase() : read;
30
+ const values = collected.get(key) ?? [];
31
+ if (!values.some(existing => existing.toLowerCase() === normalized.toLowerCase()))
32
+ values.push(normalized);
33
+ collected.set(key, values);
34
+ };
35
+ if (isRecord(product.options)) {
36
+ for (const [name, value] of Object.entries(product.options)) {
37
+ if (Array.isArray(value) && value.length && value.every(entry => isRecord(entry) && typeof entry.name === "string")) {
38
+ for (const group of value)
39
+ add(group.name, group.values ?? group.choices ?? group.options);
40
+ }
41
+ else
42
+ add(name, value);
43
+ }
44
+ }
45
+ for (const variant of productVariants(product)) {
46
+ for (const [name, value] of Object.entries(variant.options))
47
+ add(name, value);
48
+ }
49
+ const attributes = {};
50
+ for (const [key, values] of collected) {
51
+ const allowed = enums[key];
52
+ const value = values.join(", ");
53
+ if (allowed && (values.length !== 1 || !allowed.includes(values[0]))) {
54
+ throw new Error(`Product ${JSON.stringify(product.merchant_product_id)}: attributes.${key} cannot represent options ${JSON.stringify(values)}. Set one merchant-confirmed value (${allowed.join(", ")}), then sync again.`);
55
+ }
56
+ if (value.length > 100) {
57
+ throw new Error(`Product ${JSON.stringify(product.merchant_product_id)}: attributes.${key} exceeds 100 characters. Set a concise merchant-confirmed attribute, then sync again.`);
58
+ }
59
+ attributes[key] = value;
60
+ }
61
+ return Object.keys(attributes).length ? { ...product, attributes } : product;
62
+ }
63
+ export function categoryGuidance(product) {
64
+ return `Add a category to ${product.title || product.merchant_product_id} (a product type path such as Home & Garden > Kitchen & Dining > Tableware > Drinkware > Mugs), then sync again.`;
65
+ }
66
+ /** Plain terminal output, including unexpected issue shapes instead of hiding them. */
67
+ export function formatCatalogIssue(product, issue) {
68
+ if (!isRecord(issue))
69
+ return `${product}: unknown field: ${JSON.stringify(issue)}`;
70
+ return `${product}: ${typeof issue.field === "string" ? issue.field : "unknown field"}: ${typeof issue.message === "string" ? issue.message : JSON.stringify(issue)}`;
71
+ }
@@ -0,0 +1,126 @@
1
+ import type { StoreProduct } from "./types.js";
2
+ /** One sellable variant of a configurable product, for the feeds. */
3
+ export interface StoreFeedVariant {
4
+ /** The variant's own ID (unique in the catalog), such as "tee-classic-2xl". */
5
+ id: string;
6
+ /** Its options, such as { size: "2XL", color: "Black" }. */
7
+ options: Readonly<Record<string, string>>;
8
+ /** Its exact price in minor units. */
9
+ exactPrice: {
10
+ amount: number;
11
+ currency: string;
12
+ };
13
+ /** Defaults to the product's availability. */
14
+ availability?: StoreProduct["availability"];
15
+ gtin?: string;
16
+ mpn?: string;
17
+ }
18
+ export interface StoreFeedFacts {
19
+ /** Actual item/selected variant price in minor units. Never a display minimum. */
20
+ exactPrice?: {
21
+ amount: number;
22
+ currency: string;
23
+ };
24
+ condition?: "new" | "used" | "refurbished";
25
+ variant?: {
26
+ groupId: string;
27
+ options: Readonly<Record<string, string>>;
28
+ };
29
+ /**
30
+ * A product with options (`configurable: true`) lists each variant it sells,
31
+ * with its own ID, options and exact price. Each variant becomes its own feed
32
+ * row (grouped under this product's ID), so a size that costs more shows its
33
+ * own price. Example: a tee at 2500 for S–XL and 3000 for 2XL/3XL.
34
+ */
35
+ variants?: ReadonlyArray<StoreFeedVariant>;
36
+ /** Explicit eligibility from the store's channel policy, not agent visibility. */
37
+ googleCheckout?: {
38
+ eligible: boolean;
39
+ channelStatus: "connected" | "paused" | "disconnected";
40
+ };
41
+ /**
42
+ * The store attests it owns the product's brand (its own label, such as
43
+ * print-on-demand goods sold under the store's brand) and that the
44
+ * product's `mpn` is the store's own SKU for it. Google and Microsoft then
45
+ * get the product's `brand` + `mpn`. Both must be set on the product: the
46
+ * kit never fills the brand from the store name or the MPN from an ID.
47
+ */
48
+ ownBrand?: boolean;
49
+ /**
50
+ * The store attests the product is custom or made to order and has no GTIN
51
+ * or MPN. Only this emits `identifier_exists=false` (Google and Microsoft).
52
+ * Contradicted by a `gtin`, an `mpn` or `ownBrand`.
53
+ */
54
+ customGoods?: boolean;
55
+ /**
56
+ * Google's `age_group`: "newborn", "infant", "toddler", "kids" or "adult".
57
+ * Emitted in the Google and Microsoft feeds (never the ChatGPT feed). Any
58
+ * other value is omitted with an `invalid_age_group_omitted` diagnostic and
59
+ * never guessed. An apparel item (see `isApparelCategory`: a Google
60
+ * "Apparel & Accessories" category) without one gets the documented default
61
+ * "adult" and an `age_group_defaulted` diagnostic.
62
+ */
63
+ ageGroup?: StoreAgeGroup;
64
+ /**
65
+ * Google's `gender`: "male", "female" or "unisex". Emitted in the Google and
66
+ * Microsoft feeds (never the ChatGPT feed). Any other value is omitted with
67
+ * an `invalid_gender_omitted` diagnostic and never guessed. An apparel item
68
+ * without one gets the documented default "unisex" and a `gender_defaulted`
69
+ * diagnostic.
70
+ */
71
+ gender?: StoreGender;
72
+ }
73
+ export type StoreAgeGroup = "newborn" | "infant" | "toddler" | "kids" | "adult";
74
+ export type StoreGender = "male" | "female" | "unisex";
75
+ /** The values `ageGroup` accepts. */
76
+ export declare const STORE_AGE_GROUPS: readonly StoreAgeGroup[];
77
+ /** The values `gender` accepts. */
78
+ export declare const STORE_GENDERS: readonly StoreGender[];
79
+ /** What an apparel item without `ageGroup` / `gender` gets in the Google and Microsoft feeds (with a diagnostic). */
80
+ export declare const APPAREL_DEFAULTS: Readonly<{
81
+ ageGroup: StoreAgeGroup;
82
+ gender: StoreGender;
83
+ }>;
84
+ /**
85
+ * Whether a product `category` is Google's "Apparel & Accessories" (the rule
86
+ * for apparel defaults): the category path's first level is "Apparel &
87
+ * Accessories" (any case, "&" or "&amp;"), or it is that category's Google ID
88
+ * 166 (alone or as "166 > ..."). Numeric IDs of subcategories aren't
89
+ * recognized; give the full path. Nothing else (titles, brands, other
90
+ * category names) makes an item apparel.
91
+ */
92
+ export declare function isApparelCategory(category: unknown): boolean;
93
+ export type StoreCatalogProduct = StoreProduct & {
94
+ feed?: StoreFeedFacts;
95
+ };
96
+ export interface StoreCatalogQuery {
97
+ /** Opaque continuation returned by the previous call; absent on the first page. */
98
+ cursor?: string;
99
+ limit: number;
100
+ query?: string;
101
+ }
102
+ export interface StoreCatalogPage {
103
+ products: readonly StoreCatalogProduct[];
104
+ /** null means complete. A nonempty, nonrepeating cursor means another page. */
105
+ nextCursor: string | null;
106
+ }
107
+ export interface StoreCatalogSource {
108
+ listProducts(query: StoreCatalogQuery): StoreCatalogPage | Promise<StoreCatalogPage>;
109
+ getProduct(id: string): StoreCatalogProduct | null | Promise<StoreCatalogProduct | null>;
110
+ }
111
+ export type CatalogReadDiagnostic = {
112
+ productId: string;
113
+ code: string;
114
+ };
115
+ export declare function storeDomainUrl(value: unknown, hostnames: readonly string[]): string | undefined;
116
+ /** One visibility and store-domain boundary for all callback-backed discovery. No index calls. */
117
+ export declare class StoreCatalogReads {
118
+ private readonly source;
119
+ private readonly hostnames;
120
+ private readonly diagnose;
121
+ constructor(source: StoreCatalogSource, hostnames: readonly string[], diagnose?: (diagnostic: CatalogReadDiagnostic) => void);
122
+ private visible;
123
+ all(query?: string): Promise<StoreCatalogProduct[]>;
124
+ get(id: string): Promise<StoreCatalogProduct | undefined>;
125
+ search(query: string, limit: number): Promise<StoreCatalogProduct[]>;
126
+ }