@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,104 @@
1
+ import { withMerchantProductId } from "./catalog.js";
2
+ import { publicUrl } from "./feed-values.js";
3
+ import { isStoreOwnUrl } from "./public-origin.js";
4
+ /** The values `ageGroup` accepts. */
5
+ export const STORE_AGE_GROUPS = ["newborn", "infant", "toddler", "kids", "adult"];
6
+ /** The values `gender` accepts. */
7
+ export const STORE_GENDERS = ["male", "female", "unisex"];
8
+ /** What an apparel item without `ageGroup` / `gender` gets in the Google and Microsoft feeds (with a diagnostic). */
9
+ export const APPAREL_DEFAULTS = { ageGroup: "adult", gender: "unisex" };
10
+ /**
11
+ * Whether a product `category` is Google's "Apparel & Accessories" (the rule
12
+ * for apparel defaults): the category path's first level is "Apparel &
13
+ * Accessories" (any case, "&" or "&"), or it is that category's Google ID
14
+ * 166 (alone or as "166 > ..."). Numeric IDs of subcategories aren't
15
+ * recognized; give the full path. Nothing else (titles, brands, other
16
+ * category names) makes an item apparel.
17
+ */
18
+ export function isApparelCategory(category) {
19
+ if (typeof category !== "string")
20
+ return false;
21
+ const first = category.split(">")[0].trim().replace(/\s+/g, " ").toLowerCase();
22
+ return first === "apparel & accessories" || first === "apparel & accessories" || first === "166";
23
+ }
24
+ export function storeDomainUrl(value, hostnames) {
25
+ const parsed = publicUrl(value);
26
+ if (!parsed)
27
+ return;
28
+ const url = new URL(parsed);
29
+ if (url.protocol !== "https:" || url.port || url.hash
30
+ || /(^|\.)(getrelyon\.com|relyon\.com)$/i.test(url.hostname)
31
+ || !hostnames.some(host => host.toLowerCase() === url.hostname.toLowerCase()))
32
+ return;
33
+ return url.href;
34
+ }
35
+ /** One visibility and store-domain boundary for all callback-backed discovery. No index calls. */
36
+ export class StoreCatalogReads {
37
+ source;
38
+ hostnames;
39
+ diagnose;
40
+ constructor(source, hostnames, diagnose = () => undefined) {
41
+ this.source = source;
42
+ this.hostnames = hostnames;
43
+ this.diagnose = diagnose;
44
+ if (typeof source.listProducts !== "function" || typeof source.getProduct !== "function") {
45
+ throw new TypeError("catalog.source needs both listProducts and getProduct.");
46
+ }
47
+ }
48
+ visible(product) {
49
+ // New callback mode requires an affirmative visibility assertion. Legacy mirror mode is unchanged.
50
+ if (product?.agent?.visible !== true)
51
+ return false;
52
+ const id = product.merchant_product_id;
53
+ if (typeof id !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(id)) {
54
+ this.diagnose({ productId: typeof id === "string" ? id : "", code: "invalid_product_id" });
55
+ return false;
56
+ }
57
+ // A page on one of the store's own addresses (or a root-relative path);
58
+ // readers move it onto the store's public address.
59
+ if (!isStoreOwnUrl(product.url, this.hostnames)) {
60
+ this.diagnose({ productId: id, code: "invalid_or_off_store_product_url" });
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+ async all(query) {
66
+ const products = [];
67
+ const cursors = new Set(), ids = new Set();
68
+ let cursor;
69
+ for (let page = 0; page < 100; page++) {
70
+ const result = await this.source.listProducts({ limit: 500, ...(cursor ? { cursor } : {}), ...(query !== undefined ? { query } : {}) });
71
+ if (!result || !Array.isArray(result.products) || result.products.length > 500
72
+ || !(result.nextCursor === null || (typeof result.nextCursor === "string" && result.nextCursor.length > 0 && result.nextCursor.length <= 4096))) {
73
+ throw new Error("Invalid catalog page: return at most 500 products and an explicit nextCursor (null when complete).");
74
+ }
75
+ for (const listed of result.products) {
76
+ const product = withMerchantProductId(listed);
77
+ if (product && ids.has(product.merchant_product_id))
78
+ throw new Error("Duplicate catalog product ID across pages.");
79
+ if (product)
80
+ ids.add(product.merchant_product_id);
81
+ if (product && this.visible(product))
82
+ products.push(product);
83
+ }
84
+ if (result.nextCursor === null)
85
+ return products.sort((a, b) => a.merchant_product_id.localeCompare(b.merchant_product_id, "en"));
86
+ if (cursors.has(result.nextCursor))
87
+ throw new Error("Catalog pagination cursor repeated.");
88
+ cursors.add(result.nextCursor);
89
+ cursor = result.nextCursor;
90
+ }
91
+ throw new Error("Catalog pagination exceeded 100 pages; no partial discovery is served.");
92
+ }
93
+ async get(id) {
94
+ const product = withMerchantProductId(await this.source.getProduct(id));
95
+ return product && product.merchant_product_id === id && this.visible(product) ? product : undefined;
96
+ }
97
+ async search(query, limit) {
98
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
99
+ return (await this.all(query)).filter(product => {
100
+ const text = [product.title, product.description, product.brand, product.category].filter(Boolean).join(" ").toLowerCase();
101
+ return words.every(word => text.includes(word));
102
+ }).slice(0, limit);
103
+ }
104
+ }
@@ -0,0 +1,78 @@
1
+ import { type RelyonGateway } from "./relyon.js";
2
+ import type { StoreProduct } from "./types.js";
3
+ /** Keeps the store's last good catalog for discovery (llms.txt, sitemap, MCP browse). */
4
+ export interface CatalogPersistence {
5
+ load(): Promise<StoreProduct[] | null> | StoreProduct[] | null;
6
+ save(products: StoreProduct[]): Promise<void> | void;
7
+ }
8
+ export declare class CatalogHolder {
9
+ private readonly persistence?;
10
+ private products;
11
+ private byId;
12
+ syncedAt: number | null;
13
+ constructor(persistence?: CatalogPersistence | undefined);
14
+ restore(initial?: StoreProduct[]): Promise<void>;
15
+ replace(products: StoreProduct[]): void;
16
+ commit(products: StoreProduct[], at: number): Promise<void>;
17
+ /**
18
+ * Applies one accepted batch: `published` products are added or replaced,
19
+ * `removed` IDs (products Relyon rejected) leave discovery, and every other
20
+ * product the kit already serves stays, as it does in Relyon's index.
21
+ */
22
+ merge(published: StoreProduct[], removed: string[], at: number): Promise<void>;
23
+ all(): readonly StoreProduct[];
24
+ get(id: string): StoreProduct | undefined;
25
+ /** Simple case-insensitive search over title, description, brand and category; every word must match. */
26
+ search(query: string, limit: number): StoreProduct[];
27
+ }
28
+ export interface CatalogSyncResult {
29
+ object: "catalog_sync";
30
+ results: Array<{
31
+ id: string;
32
+ status: string;
33
+ issues?: unknown[];
34
+ }>;
35
+ deleted?: string[];
36
+ /** The name of the store Relyon wrote the sync to (response header, not contract body). */
37
+ storeName?: string;
38
+ }
39
+ export declare class CatalogSyncError extends Error {
40
+ readonly cause?: unknown | undefined;
41
+ /** The field at fault, as `products[<index in the list passed to syncCatalog>].<field>`, when known. */
42
+ readonly param?: string | undefined;
43
+ constructor(message: string, cause?: unknown | undefined,
44
+ /** The field at fault, as `products[<index in the list passed to syncCatalog>].<field>`, when known. */
45
+ param?: string | undefined);
46
+ }
47
+ /**
48
+ * Where synced product links go: Relyon's index takes full http(s) URLs only,
49
+ * so product `url` and `images` that are the store's own (a path such as
50
+ * `/products/mug`, or a URL on one of the store's hostnames or loopback) are
51
+ * sent on `origin`, the same public address the feeds use.
52
+ */
53
+ export interface CatalogSyncAddress {
54
+ /** The store's public origin, or undefined when the kit can't know it (see `fix`). */
55
+ origin: string | undefined;
56
+ /** The store's own hostnames (configured, preview and loopback in Test). */
57
+ hostnames: readonly string[];
58
+ }
59
+ /**
60
+ * Upserts the store's products into Relyon's index with `upsertProductsBatch`,
61
+ * 500 at a time, each batch with an Idempotency-Key derived from its content.
62
+ * Discovery (llms.txt, sitemap, MCP browse) only ever shows products Relyon
63
+ * published:
64
+ * - A product Relyon rejects leaves discovery.
65
+ * - `upsert` merges each accepted batch into the catalog the kit serves, the
66
+ * same as Relyon's index keeps earlier products.
67
+ * - `full` replaces it with the batch's published products.
68
+ * - A batch Relyon doesn't accept changes nothing; batches before it stay
69
+ * applied, as they are in Relyon.
70
+ */
71
+ /**
72
+ * A product with `merchant_product_id` filled from its `id` (or `sku`) when
73
+ * it is missing: the store's own product ID is the index ID. The `id` and
74
+ * `sku` keys are not product fields, so they are dropped once used. A product
75
+ * with neither is returned unchanged (and refused where an ID is required).
76
+ */
77
+ export declare function withMerchantProductId<T>(product: T): T;
78
+ export declare function syncCatalog(gateway: RelyonGateway, holder: CatalogHolder, products: StoreProduct[], mode: "upsert" | "full", now: number, address?: CatalogSyncAddress): Promise<CatalogSyncResult>;
@@ -0,0 +1,288 @@
1
+ import { CATALOG_SYNC_OBJECT, PRODUCTS_BATCH_PATH, PROJECT_SPACE_NAME_HEADER } from "./wire-names.js";
2
+ import { RelyonProblemError } from "./relyon.js";
3
+ import { bindAddressOf, rebaseStoreUrl } from "./public-origin.js";
4
+ import { canonicalJson, isRecord, sha256 } from "./util.js";
5
+ import { categoryGuidance, withOptionAttributes } from "./catalog-enrichment.js";
6
+ import { readStorePolicies } from "./setup.js";
7
+ export class CatalogHolder {
8
+ persistence;
9
+ products = [];
10
+ byId = new Map();
11
+ syncedAt = null;
12
+ constructor(persistence) {
13
+ this.persistence = persistence;
14
+ }
15
+ async restore(initial) {
16
+ const saved = this.persistence ? await this.persistence.load() : null;
17
+ const products = saved ?? initial;
18
+ if (products)
19
+ this.replace(products);
20
+ }
21
+ replace(products) {
22
+ products = products.map((product) => withMerchantProductId(product));
23
+ this.products = [...products];
24
+ this.byId = new Map(products.map((product) => [product.merchant_product_id, product]));
25
+ }
26
+ async commit(products, at) {
27
+ this.replace(products);
28
+ this.syncedAt = at;
29
+ if (this.persistence)
30
+ await this.persistence.save(products);
31
+ }
32
+ /**
33
+ * Applies one accepted batch: `published` products are added or replaced,
34
+ * `removed` IDs (products Relyon rejected) leave discovery, and every other
35
+ * product the kit already serves stays, as it does in Relyon's index.
36
+ */
37
+ async merge(published, removed, at) {
38
+ const next = new Map(this.byId);
39
+ for (const id of removed)
40
+ next.delete(id);
41
+ for (const product of published)
42
+ next.set(product.merchant_product_id, product);
43
+ await this.commit([...next.values()], at);
44
+ }
45
+ all() {
46
+ return this.products;
47
+ }
48
+ get(id) {
49
+ return this.byId.get(id);
50
+ }
51
+ /** Simple case-insensitive search over title, description, brand and category; every word must match. */
52
+ search(query, limit) {
53
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
54
+ const matches = this.products.filter((product) => {
55
+ const text = [product.title, product.description, product.brand, product.category].filter(Boolean).join(" ").toLowerCase();
56
+ return words.every((word) => text.includes(word));
57
+ });
58
+ return matches.slice(0, limit);
59
+ }
60
+ }
61
+ export class CatalogSyncError extends Error {
62
+ cause;
63
+ param;
64
+ constructor(message, cause,
65
+ /** The field at fault, as `products[<index in the list passed to syncCatalog>].<field>`, when known. */
66
+ param) {
67
+ super(message);
68
+ this.cause = cause;
69
+ this.param = param;
70
+ this.name = "CatalogSyncError";
71
+ }
72
+ }
73
+ const ADDRESS_FIX = "Set STORE_PUBLIC_URL (store.publicUrl) to the address the store is opened at (https://shop.example.com, "
74
+ + "or for a local store plain http on localhost with its port), or set STORE_HOSTNAMES so its first hostname is the store's public one.";
75
+ const shown = (value) => JSON.stringify(value.length > 120 ? `${value.slice(0, 117)}...` : value);
76
+ /** True for a string that parses as a URL on its own (it has a scheme). */
77
+ function absolute(value) {
78
+ try {
79
+ new URL(value);
80
+ return true;
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /**
87
+ * The product as it is sent to Relyon: its `url` and `images` that are the
88
+ * store's own moved onto `address.origin`; other sites' URLs unchanged
89
+ * (Relyon checks them). Throws a CatalogSyncError, naming the product and
90
+ * the fix, for a relative link that can't be made a full URL.
91
+ */
92
+ function outgoingProduct(product, index, address) {
93
+ const link = (value, field) => {
94
+ if (typeof value !== "string")
95
+ return value;
96
+ const param = `products[${index}].${field}`;
97
+ const where = `Product ${JSON.stringify(product.merchant_product_id)} (${param})`;
98
+ if (absolute(value)) {
99
+ const rebased = address.origin ? rebaseStoreUrl(value, address.origin, address.hostnames) : undefined;
100
+ if (rebased)
101
+ return rebased;
102
+ const host = bindAddressOf(value);
103
+ if (!host)
104
+ return value;
105
+ // Never sent, even when it can't be moved: no browser or agent can open a dev server's bind address.
106
+ throw new CatalogSyncError(`${where} is on ${host}, the address a dev server listens on, which no browser or agent can open. `
107
+ + (address.origin
108
+ ? `Use a path such as /products/mug (the kit puts it on ${address.origin}) or the store's public URL. Nothing was sent.`
109
+ : `The kit doesn't know the store's public address to put it on. ${ADDRESS_FIX} Nothing was sent.`), undefined, param);
110
+ }
111
+ if (!address.origin) {
112
+ throw new CatalogSyncError(`${where} is the path ${shown(value)}, and Relyon needs a full URL, but the kit doesn't know the store's public address to put it on. ${ADDRESS_FIX} Nothing was sent.`, undefined, param);
113
+ }
114
+ const rebased = rebaseStoreUrl(value, address.origin, address.hostnames);
115
+ if (rebased)
116
+ return rebased;
117
+ throw new CatalogSyncError(`${where} is ${shown(value)}, which is neither a full http(s) URL nor a path starting with a single "/". `
118
+ + "Use a path such as /products/mug or a full https URL. Nothing was sent.", undefined, param);
119
+ };
120
+ // Project onto the contract, not the richer catalog-source object. Keep the
121
+ // original (including feed metadata) in the local catalog after acceptance.
122
+ const fields = [
123
+ "merchant_product_id", "group_id", "title", "description", "url", "brand", "images",
124
+ "from_price", "availability", "configurable", "options", "gtin", "mpn", "category",
125
+ "attributes", "dimensions", "weight", "shipping", "returns", "agent", "metadata",
126
+ "subscription", "personalized", "age_restricted",
127
+ ];
128
+ const sent = Object.fromEntries(fields.filter(field => product[field] !== undefined)
129
+ .map(field => [field, product[field]]));
130
+ if (product.url !== undefined)
131
+ sent.url = link(product.url, "url");
132
+ if (Array.isArray(product.images))
133
+ sent.images = product.images.map((image, at) => link(image, `images[${at}]`));
134
+ return sent;
135
+ }
136
+ /** A plain fix for a field Relyon refused. */
137
+ function fixFor(param) {
138
+ if (param && /\.(url|images(\[\d+\])?)$/.test(param)) {
139
+ return "Product links must be full http(s) URLs: use a path such as /products/mug (the kit puts it on the store's public address) "
140
+ + `or a full https URL. ${ADDRESS_FIX}`;
141
+ }
142
+ return param ? "Correct that field in the product data and sync again." : "Correct the product data and sync again.";
143
+ }
144
+ /** A sync failure as the merchant reads it: the product and field at fault, and what to do. */
145
+ function syncFailure(error, start, chunk) {
146
+ if (error instanceof RelyonProblemError && error.status >= 400 && error.status < 500) {
147
+ const match = error.param ? /^products\[(\d+)\](.*)$/.exec(error.param) : null;
148
+ const index = match ? start + Number(match[1]) : undefined;
149
+ const param = match ? `products[${index}]${match[2]}` : error.param;
150
+ const product = match ? chunk[Number(match[1])] : undefined;
151
+ const subject = product ? `product ${JSON.stringify(product.merchant_product_id)} (${param})` : param ? `${param}` : `the batch starting at products[${start}]`;
152
+ return new CatalogSyncError(`Catalog sync failed: Relyon refused ${subject} with ${error.code} (HTTP ${error.status}): ${error.message} ${fixFor(param)}`, error, param);
153
+ }
154
+ return new CatalogSyncError(`Catalog sync failed at product ${start}: ${error?.message ?? error}`, error);
155
+ }
156
+ const BATCH = 500;
157
+ /**
158
+ * Upserts the store's products into Relyon's index with `upsertProductsBatch`,
159
+ * 500 at a time, each batch with an Idempotency-Key derived from its content.
160
+ * Discovery (llms.txt, sitemap, MCP browse) only ever shows products Relyon
161
+ * published:
162
+ * - A product Relyon rejects leaves discovery.
163
+ * - `upsert` merges each accepted batch into the catalog the kit serves, the
164
+ * same as Relyon's index keeps earlier products.
165
+ * - `full` replaces it with the batch's published products.
166
+ * - A batch Relyon doesn't accept changes nothing; batches before it stay
167
+ * applied, as they are in Relyon.
168
+ */
169
+ /**
170
+ * A product with `merchant_product_id` filled from its `id` (or `sku`) when
171
+ * it is missing: the store's own product ID is the index ID. The `id` and
172
+ * `sku` keys are not product fields, so they are dropped once used. A product
173
+ * with neither is returned unchanged (and refused where an ID is required).
174
+ */
175
+ export function withMerchantProductId(product) {
176
+ if (!isRecord(product))
177
+ return product;
178
+ if (typeof product.merchant_product_id === "string" && product.merchant_product_id)
179
+ return product;
180
+ const fromValue = (value) => typeof value === "string" && value.trim() ? value.trim()
181
+ : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? String(value) : undefined;
182
+ const id = fromValue(product.id) ?? fromValue(product.sku);
183
+ if (id === undefined)
184
+ return product;
185
+ const { id: _id, sku: _sku, ...rest } = product;
186
+ return { ...rest, merchant_product_id: id };
187
+ }
188
+ export async function syncCatalog(gateway, holder, products, mode, now, address = { origin: undefined, hostnames: [] }) {
189
+ // A missing merchant_product_id comes from the product's id (or sku); uniqueness is still checked.
190
+ products = products.map((product) => withMerchantProductId(product));
191
+ const seen = new Set();
192
+ for (const [index, product] of products.entries()) {
193
+ if (!isRecord(product) || typeof product.merchant_product_id !== "string" || !product.merchant_product_id) {
194
+ throw new CatalogSyncError(`products[${index}] needs a merchant_product_id (or an id or sku the kit can use as one).`);
195
+ }
196
+ if (seen.has(product.merchant_product_id))
197
+ throw new CatalogSyncError(`merchant_product_id ${product.merchant_product_id} appears more than once.`);
198
+ seen.add(product.merchant_product_id);
199
+ }
200
+ if (products.length === 0)
201
+ throw new CatalogSyncError("A catalog sync needs at least one product.");
202
+ if (mode === "full" && products.length > BATCH) {
203
+ throw new CatalogSyncError(`A full sync replaces the whole index in one batch, so it takes at most ${BATCH} products; use mode "upsert" for larger catalogs.`);
204
+ }
205
+ try {
206
+ products = products.map(withOptionAttributes);
207
+ }
208
+ catch (error) {
209
+ throw new CatalogSyncError(error.message, error);
210
+ }
211
+ // Every link is checked (and made full) before anything is sent.
212
+ const outgoing = products.map((product, index) => outgoingProduct(product, index, address));
213
+ if (outgoing.some(product => product.returns === undefined)) {
214
+ // No cache: a policy saved immediately before sync must be observed. A
215
+ // failed/unauthorized read is not the same as an unanswered owner question.
216
+ let policies;
217
+ try {
218
+ policies = await readStorePolicies(gateway);
219
+ }
220
+ catch (error) {
221
+ throw new CatalogSyncError(`Catalog sync could not read the store's return policy: ${error.message}. Nothing was sent.`, error);
222
+ }
223
+ if (policies.livemode !== gateway.livemode)
224
+ throw new CatalogSyncError("Catalog sync received a return policy for the wrong Test/Live mode. Nothing was sent.");
225
+ const returns = policies.returns;
226
+ if (returns !== undefined && !policies.missing.some(field => field === "returns" || field === "returns.policy_url")) {
227
+ if (!Number.isInteger(returns.window_days) || returns.window_days < 0 || returns.window_days > 365
228
+ || typeof returns.policy_url !== "string" || !returns.policy_url.trim()) {
229
+ throw new CatalogSyncError("The saved return policy needs a valid window_days and policy_url before catalog sync. Nothing was sent.");
230
+ }
231
+ for (const product of outgoing)
232
+ if (product.returns === undefined) {
233
+ product.returns = { days: returns.window_days, policy_url: returns.policy_url };
234
+ }
235
+ }
236
+ }
237
+ const combined = { object: "catalog_sync", results: [] };
238
+ for (let start = 0; start < products.length; start += BATCH) {
239
+ // The kit keeps the merchant's own links; Relyon gets the full ones, keyed on what is sent.
240
+ const chunk = products.slice(start, start + BATCH);
241
+ const sent = outgoing.slice(start, start + BATCH);
242
+ const key = `sk-cat-${sha256(`${mode}\n${canonicalJson(sent)}`)}`;
243
+ let answer;
244
+ try {
245
+ answer = await gateway.call((client) => client.POST(PRODUCTS_BATCH_PATH, {
246
+ params: { header: { "Idempotency-Key": key } },
247
+ body: { products: sent, mode },
248
+ }), isSyncResult);
249
+ }
250
+ catch (error) {
251
+ throw syncFailure(error, start, chunk);
252
+ }
253
+ combined.results.push(...answer.data.results.map(row => {
254
+ const product = chunk.find(product => product.merchant_product_id === row.id);
255
+ if (!product || product.category?.trim())
256
+ return row;
257
+ return { ...row, issues: [
258
+ ...(row.issues ?? []).filter(issue => !isRecord(issue) || issue.field !== "category"),
259
+ { field: "category", code: "recommended_field_missing", severity: "warning", message: categoryGuidance(product) },
260
+ ] };
261
+ }));
262
+ if (answer.data.deleted)
263
+ combined.deleted = [...(combined.deleted ?? []), ...answer.data.deleted];
264
+ // Brief 87b: the store Relyon resolved for this sync, for the result line.
265
+ const storeName = answer.response.headers.get(PROJECT_SPACE_NAME_HEADER);
266
+ if (storeName) {
267
+ try {
268
+ combined.storeName = decodeURIComponent(storeName);
269
+ }
270
+ catch {
271
+ combined.storeName = storeName;
272
+ }
273
+ }
274
+ const status = new Map(answer.data.results.map((row) => [row.id, row.status]));
275
+ const published = chunk.filter((product) => status.get(product.merchant_product_id) === "published");
276
+ if (mode === "full")
277
+ await holder.commit(published, now);
278
+ else {
279
+ const removed = chunk.filter((product) => status.get(product.merchant_product_id) !== "published").map((product) => product.merchant_product_id);
280
+ await holder.merge(published, removed, now);
281
+ }
282
+ }
283
+ return combined;
284
+ }
285
+ function isSyncResult(data) {
286
+ return isRecord(data) && data.object === CATALOG_SYNC_OBJECT && Array.isArray(data.results)
287
+ && data.results.every((row) => isRecord(row) && typeof row.id === "string" && typeof row.status === "string");
288
+ }
@@ -0,0 +1,11 @@
1
+ /** A claim that nothing was charged (see above). */
2
+ export declare const NOTHING_CHARGED_CLAIM: RegExp;
3
+ /** True when `text` claims that nothing was charged. */
4
+ export declare function claimsNothingCharged(text: string): boolean;
5
+ /**
6
+ * `text` without every sentence that claims nothing was charged. Whitespace
7
+ * is collapsed; sentences end at `.`, `!` or `?` followed by whitespace (so
8
+ * "$12.50" never splits). Returns "" when nothing else is left, or when a
9
+ * claim would survive the split (the caller then uses its own wording).
10
+ */
11
+ export declare function withoutNothingChargedClaims(text: string): string;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Claims that nothing was charged. Once a checkout or an order reference may
3
+ * have been charged, no answer the kit gives may carry one, in any phrasing a
4
+ * store's `StoreRefusal`, a rule text or Relyon uses. Matching is
5
+ * case-insensitive, accepts straight and curly apostrophes, and treats any
6
+ * run of whitespace (spaces, newlines, non-breaking spaces) as one space.
7
+ * "this request charged nothing more" (an existing charge stands) is not a claim.
8
+ *
9
+ * The API server keeps the same list (a shared test set pins the two).
10
+ */
11
+ const S = "\\s+";
12
+ const APOSTROPHE = "['\u2019\u2018`]";
13
+ const CLAIMS = [
14
+ // nothing was / is / has been / will be / gets charged; a bare "nothing charged"
15
+ `\\bnothing${S}(?:(?:was|is|has${S}been|have${S}been|had${S}been|will${S}be|would${S}be|shall${S}be|got|gets|has|will|was${S}ever)${S})?charged\\b`,
16
+ // charged nothing (but not "charged nothing more")
17
+ `\\bcharged${S}nothing\\b(?!${S}more)`,
18
+ // wasn't / weren't / hasn't been / haven't been / won't be / isn't charged
19
+ `\\b\\w+n${APOSTROPHE}t${S}(?:(?:yet|ever)${S})?(?:been${S}|be${S})?charged\\b`,
20
+ `\\b(?:wasnt|werent|isnt|arent|hasnt|havent|hadnt|wont|wouldnt)${S}(?:been${S}|be${S})?charged\\b`,
21
+ // was not / has not been / not been / not yet been / will not be charged
22
+ `\\bnot${S}(?:(?:yet|ever)${S})?(?:been${S}|be${S})?charged\\b`,
23
+ // didn't / did not charge; never charged
24
+ `\\b(?:didn${APOSTROPHE}?t|did${S}not)${S}charge\\b`,
25
+ `\\bnever${S}(?:been${S})?charged\\b`,
26
+ // no charge(s) / payment(s) / money ... made / taken / collected / captured / processed
27
+ `\\bno${S}(?:charges?|payments?|money|funds)${S}(?:\\w+${S}){0,2}(?:made|taken|collected|captured|charged|processed|debited)\\b`,
28
+ ];
29
+ /** A claim that nothing was charged (see above). */
30
+ export const NOTHING_CHARGED_CLAIM = new RegExp(CLAIMS.join("|"), "i");
31
+ /** True when `text` claims that nothing was charged. */
32
+ export function claimsNothingCharged(text) {
33
+ return NOTHING_CHARGED_CLAIM.test(text);
34
+ }
35
+ /**
36
+ * `text` without every sentence that claims nothing was charged. Whitespace
37
+ * is collapsed; sentences end at `.`, `!` or `?` followed by whitespace (so
38
+ * "$12.50" never splits). Returns "" when nothing else is left, or when a
39
+ * claim would survive the split (the caller then uses its own wording).
40
+ */
41
+ export function withoutNothingChargedClaims(text) {
42
+ if (!claimsNothingCharged(text))
43
+ return text;
44
+ const flat = text.replace(/\s+/g, " ").trim();
45
+ const kept = flat.split(/(?<=[.!?])\s+(?=\S)/).filter((sentence) => !claimsNothingCharged(sentence)).join(" ").trim();
46
+ return claimsNothingCharged(kept) ? "" : kept;
47
+ }
@@ -0,0 +1,44 @@
1
+ import { type FetchLike } from "./relyon.js";
2
+ export declare const CHECK_STEPS: readonly ["Test key", "Payment session", "Mock Test charge", "Webhook signature"];
3
+ export type CheckStepName = typeof CHECK_STEPS[number];
4
+ export type CheckStatus = "PASS" | "FAIL" | "NOT RUN";
5
+ export interface CheckStep {
6
+ name: CheckStepName;
7
+ status: CheckStatus;
8
+ detail: string;
9
+ /** What to do about a FAIL or NOT RUN. */
10
+ fix?: string;
11
+ }
12
+ export interface CheckOptions {
13
+ /** RELYON_API_KEY as given (may be a placeholder, a Live key or absent). */
14
+ envKey?: string | undefined;
15
+ /** The saved Test key (init's private folder or .env); read by the caller only when not Live. */
16
+ savedKey?: string | undefined;
17
+ live?: boolean | undefined;
18
+ baseUrl?: string | undefined;
19
+ /** Send a saved key to a base URL other than Relyon's official API. */
20
+ allowSavedKeyToBaseUrl?: boolean | undefined;
21
+ /** RELYON_WEBHOOK_SECRET, when set: step 4 verifies with it. Otherwise a throwaway secret proves the verifier. */
22
+ webhookSecret?: string | undefined;
23
+ currency?: string | undefined;
24
+ /** RELYON_PROJECT_SPACE, when set: sent as the Relyon-Project-Space header (needed when the workspace has several project spaces). */
25
+ projectSpace?: string | undefined;
26
+ fetch?: FetchLike | undefined;
27
+ timeoutMs?: number | undefined;
28
+ }
29
+ export interface CheckResult {
30
+ exitCode: 0 | 1 | 2;
31
+ steps: CheckStep[];
32
+ lines: string[];
33
+ /** The Test payment step 3 created, when it ran. */
34
+ paymentId?: string;
35
+ }
36
+ export declare const CHECK_REFUSED_LIVE = "check is Test mode only: it never runs with RELYON_LIVE=true or a Live key, and never makes a Live charge.";
37
+ /** The amount of the mock Test charge, in minor units. */
38
+ export declare const CHECK_AMOUNT = 100;
39
+ /** The verdict, then one line per step (with its fix), redacted. */
40
+ export declare function formatCheck(steps: readonly CheckStep[]): string[];
41
+ /** Step 4 on its own: a signed body verifies, and a tampered or unsigned one doesn't. */
42
+ export declare function webhookSelfTest(secret: string, nowSeconds?: number): boolean;
43
+ /** Runs the four steps. Never throws; every line is terminal-safe and redacted. */
44
+ export declare function runCheck(options: CheckOptions): Promise<CheckResult>;