@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.
- package/AGENTS.md +75 -0
- package/CHANGELOG.md +1053 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +239 -0
- package/README.md +117 -2
- package/dist/adapters/express.d.ts +39 -0
- package/dist/adapters/express.js +106 -0
- package/dist/adapters/hono.d.ts +16 -0
- package/dist/adapters/hono.js +15 -0
- package/dist/adapters/next.d.ts +29 -0
- package/dist/adapters/next.js +38 -0
- package/dist/agent-card.d.ts +14 -0
- package/dist/agent-card.js +58 -0
- package/dist/agent-docs.d.ts +36 -0
- package/dist/agent-docs.js +78 -0
- package/dist/agent-hooks.d.ts +66 -0
- package/dist/agent-hooks.js +280 -0
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +120 -0
- package/dist/api-key.d.ts +6 -0
- package/dist/api-key.js +33 -0
- package/dist/cache.d.ts +46 -0
- package/dist/cache.js +86 -0
- package/dist/cart-tokens.d.ts +31 -0
- package/dist/cart-tokens.js +58 -0
- package/dist/cart-transfer.d.ts +95 -0
- package/dist/cart-transfer.js +387 -0
- package/dist/catalog-enrichment.d.ts +6 -0
- package/dist/catalog-enrichment.js +71 -0
- package/dist/catalog-reads.d.ts +126 -0
- package/dist/catalog-reads.js +104 -0
- package/dist/catalog.d.ts +78 -0
- package/dist/catalog.js +288 -0
- package/dist/charge-claims.d.ts +11 -0
- package/dist/charge-claims.js +47 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +152 -0
- package/dist/checklist-manifest.d.ts +72 -0
- package/dist/checklist-manifest.js +341 -0
- package/dist/checkout.d.ts +222 -0
- package/dist/checkout.js +353 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +727 -0
- package/dist/confirmation.d.ts +78 -0
- package/dist/confirmation.js +124 -0
- package/dist/context.d.ts +81 -0
- package/dist/context.js +10 -0
- package/dist/discovery.d.ts +151 -0
- package/dist/discovery.js +346 -0
- package/dist/doctor-cart-transfer.d.ts +33 -0
- package/dist/doctor-cart-transfer.js +186 -0
- package/dist/doctor-catalog.d.ts +8 -0
- package/dist/doctor-catalog.js +47 -0
- package/dist/doctor-evidence.d.ts +22 -0
- package/dist/doctor-evidence.js +57 -0
- package/dist/doctor-merchant.d.ts +48 -0
- package/dist/doctor-merchant.js +74 -0
- package/dist/doctor-source.d.ts +5 -0
- package/dist/doctor-source.js +142 -0
- package/dist/doctor-variants.d.ts +70 -0
- package/dist/doctor-variants.js +102 -0
- package/dist/doctor.d.ts +215 -0
- package/dist/doctor.js +1689 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.js +200 -0
- package/dist/feed-mapping.d.ts +114 -0
- package/dist/feed-mapping.js +152 -0
- package/dist/feed-values.d.ts +13 -0
- package/dist/feed-values.js +40 -0
- package/dist/feeds.d.ts +104 -0
- package/dist/feeds.js +366 -0
- package/dist/identify.d.ts +102 -0
- package/dist/identify.js +124 -0
- package/dist/identity.d.ts +37 -0
- package/dist/identity.js +54 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +41 -0
- package/dist/init.d.ts +157 -0
- package/dist/init.js +912 -0
- package/dist/kit-config.d.ts +19 -0
- package/dist/kit-config.js +43 -0
- package/dist/kit-environment.d.ts +20 -0
- package/dist/kit-environment.js +32 -0
- package/dist/kit-updates.d.ts +47 -0
- package/dist/kit-updates.js +77 -0
- package/dist/kit-version-project.d.ts +18 -0
- package/dist/kit-version-project.js +214 -0
- package/dist/kit-version.d.ts +37 -0
- package/dist/kit-version.js +162 -0
- package/dist/kit.d.ts +516 -0
- package/dist/kit.js +1309 -0
- package/dist/layers/pages.d.ts +3 -0
- package/dist/layers/pages.js +5 -0
- package/dist/layers/payments.d.ts +7 -0
- package/dist/layers/payments.js +9 -0
- package/dist/layers/products.d.ts +10 -0
- package/dist/layers/products.js +13 -0
- package/dist/live.d.ts +13 -0
- package/dist/live.js +52 -0
- package/dist/mcp.d.ts +270 -0
- package/dist/mcp.js +312 -0
- package/dist/next-steps.d.ts +101 -0
- package/dist/next-steps.js +257 -0
- package/dist/order-pending.d.ts +57 -0
- package/dist/order-pending.js +127 -0
- package/dist/orders.d.ts +12 -0
- package/dist/orders.js +21 -0
- package/dist/payments-init.d.ts +19 -0
- package/dist/payments-init.js +70 -0
- package/dist/payments-routes.d.ts +54 -0
- package/dist/payments-routes.js +123 -0
- package/dist/payments.d.ts +165 -0
- package/dist/payments.js +192 -0
- package/dist/pnpm-workspace.d.ts +58 -0
- package/dist/pnpm-workspace.js +250 -0
- package/dist/policies.d.ts +111 -0
- package/dist/policies.js +317 -0
- package/dist/preview-hosts.d.ts +64 -0
- package/dist/preview-hosts.js +175 -0
- package/dist/private-config.d.ts +169 -0
- package/dist/private-config.js +820 -0
- package/dist/progress.d.ts +54 -0
- package/dist/progress.js +153 -0
- package/dist/protocol-inputs.d.ts +22 -0
- package/dist/protocol-inputs.js +151 -0
- package/dist/public-origin.d.ts +50 -0
- package/dist/public-origin.js +180 -0
- package/dist/refusals.d.ts +86 -0
- package/dist/refusals.js +157 -0
- package/dist/relay.d.ts +107 -0
- package/dist/relay.js +655 -0
- package/dist/release-notes.d.ts +2 -0
- package/dist/release-notes.js +290 -0
- package/dist/relyon-cart-tokens.d.ts +101 -0
- package/dist/relyon-cart-tokens.js +521 -0
- package/dist/relyon.d.ts +141 -0
- package/dist/relyon.js +238 -0
- package/dist/robots.d.ts +27 -0
- package/dist/robots.js +127 -0
- package/dist/rules.d.ts +144 -0
- package/dist/rules.js +347 -0
- package/dist/sdk/generated/public-api.d.ts +4816 -0
- package/dist/sdk/generated/public-api.js +1 -0
- package/dist/sdk/index.d.ts +24 -0
- package/dist/sdk/index.js +34 -0
- package/dist/sdk/signatures.d.ts +17 -0
- package/dist/sdk/signatures.js +33 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.js +94 -0
- package/dist/signatures.d.ts +112 -0
- package/dist/signatures.js +443 -0
- package/dist/state.d.ts +185 -0
- package/dist/state.js +96 -0
- package/dist/store-payments.d.ts +48 -0
- package/dist/store-payments.js +143 -0
- package/dist/structured-fields.d.ts +26 -0
- package/dist/structured-fields.js +200 -0
- package/dist/templates.d.ts +19 -0
- package/dist/templates.js +193 -0
- package/dist/test-checkout-command.d.ts +32 -0
- package/dist/test-checkout-command.js +161 -0
- package/dist/test-checkout.d.ts +88 -0
- package/dist/test-checkout.js +292 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +18 -0
- package/dist/ucp-versions.d.ts +57 -0
- package/dist/ucp-versions.js +129 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +68 -0
- package/dist/variants.d.ts +67 -0
- package/dist/variants.js +146 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.js +10 -0
- package/dist/waiting.d.ts +43 -0
- package/dist/waiting.js +57 -0
- package/dist/webhook-command.d.ts +48 -0
- package/dist/webhook-command.js +367 -0
- package/dist/webhook-registration.d.ts +47 -0
- package/dist/webhook-registration.js +69 -0
- package/dist/webmcp-schema.d.ts +14 -0
- package/dist/webmcp-schema.js +140 -0
- package/dist/webmcp-script.d.ts +3 -0
- package/dist/webmcp-script.js +176 -0
- package/dist/webmcp-store.d.ts +102 -0
- package/dist/webmcp-store.js +116 -0
- package/dist/webmcp.d.ts +242 -0
- package/dist/webmcp.js +866 -0
- package/dist/wire-names.d.ts +85 -0
- package/dist/wire-names.js +109 -0
- package/package.json +118 -4
- package/release-notes.json +290 -0
- package/scripts/install-notice.cjs +7 -0
- package/skills/relyon-agents/SKILL.md +327 -0
- package/skills/relyon-catalog/SKILL.md +499 -0
- package/skills/relyon-catalog/references/example-store.md +218 -0
- package/skills/relyon-checkout/SKILL.md +603 -0
- package/skills/relyon-checkout/references/checkout-flow.md +257 -0
- package/skills/relyon-checkout/references/checkout-page.md +315 -0
- package/skills/relyon-go-live/SKILL.md +344 -0
- package/skills/relyon-orders/SKILL.md +191 -0
- package/skills/relyon-orders/references/webhook-receiver.md +113 -0
- package/skills/relyon-payments/SKILL.md +117 -0
- package/skills/relyon-setup/SKILL.md +1061 -0
- package/skills/relyon-setup/references/QUICKSTART.md +239 -0
- package/skills/relyon-setup/references/durable-state.md +209 -0
- package/skills/relyon-setup/references/express-server.md +388 -0
- package/skills/relyon-setup/references/next-app-router.md +251 -0
- package/templates/common/STORE-README.md +67 -0
- package/templates/common/gitignore +8 -0
- package/templates/common/scripts/check-pricing.ts +22 -0
- package/templates/common/scripts/serve.mjs +13 -0
- package/templates/common/server/catalog.ts +79 -0
- package/templates/common/server/checkout-flow.d.ts +34 -0
- package/templates/common/server/pages.ts +184 -0
- package/templates/common/server/storage.ts +114 -0
- package/templates/common/server/store.ts +67 -0
- package/templates/express/server/express.ts +20 -0
- package/templates/express/tsconfig.build.json +6 -0
- package/templates/express/tsconfig.json +9 -0
- package/templates/next/app/[[...path]]/route.ts +24 -0
- package/templates/next/next.config.mjs +19 -0
- package/templates/next/tsconfig.json +12 -0
- package/templates/payments/express.ts +39 -0
- package/templates/payments/next.ts +38 -0
- package/templates/payments/node.ts +39 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
# Express server with the store kit
|
|
2
|
+
|
|
3
|
+
A complete Express 5 app: the kit's routes, a homepage with the product list,
|
|
4
|
+
a product page, a real cart page, the policy pages its footer links to, the checkout page on the
|
|
5
|
+
store's domain, and the pay, confirm and order status routes.
|
|
6
|
+
`store.js` is in the `relyon-catalog` skill (`references/example-store.md`),
|
|
7
|
+
`relyon.js` is in this skill's `SKILL.md`, and `checkout-flow.js` (the
|
|
8
|
+
server's checkout records) and `checkout.js` (the browser script) are in the
|
|
9
|
+
`relyon-checkout` skill (`references/checkout-flow.md` and
|
|
10
|
+
`references/checkout-page.md`).
|
|
11
|
+
|
|
12
|
+
The order of middleware matters: the kit is mounted **before** `express.json()`.
|
|
13
|
+
|
|
14
|
+
```js server.js
|
|
15
|
+
import express from "express";
|
|
16
|
+
import { PaymentUnavailableError, StoreRefusal } from "@relyon/store-kit";
|
|
17
|
+
import { storeKitMiddleware } from "@relyon/store-kit/express";
|
|
18
|
+
import { createCheckoutFlow, memoryCheckouts } from "./checkout-flow.js";
|
|
19
|
+
import { catalogSource, findOrderByPayment, getProduct, priceCart } from "./store.js";
|
|
20
|
+
|
|
21
|
+
const escape = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
22
|
+
const money = (amount, currency) =>
|
|
23
|
+
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount / 100);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The Web Request the kit's helpers read, built from an Express request.
|
|
27
|
+
* The kit only trusts its Host when it is one of the store's own or Test
|
|
28
|
+
* preview hostnames; plain http is used for loopback (localhost) only.
|
|
29
|
+
*/
|
|
30
|
+
export function webRequest(req) {
|
|
31
|
+
const headers = new Headers();
|
|
32
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
33
|
+
if (typeof value === "string") headers.set(name, value);
|
|
34
|
+
else if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
35
|
+
}
|
|
36
|
+
const host = req.headers.host ?? "localhost";
|
|
37
|
+
const loopback = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host);
|
|
38
|
+
const scheme = loopback && !req.socket?.encrypted ? "http" : "https";
|
|
39
|
+
return new Request(`${scheme}://${host}${req.originalUrl}`, { method: req.method, headers });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The policy pages the homepage footer links to. Write them from the
|
|
44
|
+
* merchant's own answers (relyon-setup: "Ask before publishing claims").
|
|
45
|
+
* Until the merchant confirms a fact, the page says "to confirm with the merchant" rather than
|
|
46
|
+
* inventing a return window, a return cost, tax handling or a brand claim.
|
|
47
|
+
* Display copy only: never pass POLICY_PAGES to policy sync, kit policies,
|
|
48
|
+
* feeds, structured policy data or API payloads.
|
|
49
|
+
*/
|
|
50
|
+
export const POLICY_PAGES = {
|
|
51
|
+
shipping: { title: "Shipping", text: "Where we ship, delivery times and costs: to confirm with the merchant." },
|
|
52
|
+
returns: { title: "Returns", text: "Return window, which items qualify and who pays return shipping: to confirm with the merchant." },
|
|
53
|
+
privacy: { title: "Privacy", text: "How this store handles your personal data: to confirm with the merchant." },
|
|
54
|
+
terms: { title: "Terms", text: "Terms of sale, including how tax is handled: to confirm with the merchant." },
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** The footer every page shows: links to the four policy pages. */
|
|
58
|
+
const footer = () => `<footer><nav aria-label="Store policies">${Object.entries(POLICY_PAGES)
|
|
59
|
+
.map(([path, page]) => `<a href="/${path}">${escape(page.title)}</a>`).join(" · ")}</nav></footer>`;
|
|
60
|
+
|
|
61
|
+
/** One cookie value from the request, or null. */
|
|
62
|
+
const cookie = (req, name) => {
|
|
63
|
+
for (const part of (req.headers.cookie ?? "").split(";")) {
|
|
64
|
+
const [key, ...value] = part.trim().split("=");
|
|
65
|
+
if (key === name) return decodeURIComponent(value.join("="));
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** The order status page: no card fields, Pay can't be pressed here. */
|
|
71
|
+
function statusPage(view, newCheckoutHref) {
|
|
72
|
+
const { state, order_reference: ref, message, payment_succeeded: paymentSucceeded } = view.body;
|
|
73
|
+
const statusHref = `/checkout/status?order_reference=${encodeURIComponent(ref ?? "")}`;
|
|
74
|
+
return `<!doctype html><meta charset="utf-8"><title>Order status</title>
|
|
75
|
+
<h1>Order status</h1>
|
|
76
|
+
<div id="checkout-status" data-order-reference="${escape(ref ?? "")}" data-state="${escape(state)}" data-payment-succeeded="${paymentSucceeded === true}">
|
|
77
|
+
<p id="status" role="status">${escape(message)}${state === "pending" ? ` <a href="${escape(statusHref)}">Check your order status</a>` : ""}</p>
|
|
78
|
+
<p>Order reference: ${escape(ref ?? "unknown")}</p>
|
|
79
|
+
</div>
|
|
80
|
+
${newCheckoutHref && state !== "pending" ? `<p><a href="${escape(newCheckoutHref)}">Start a new order</a></p>` : ""}
|
|
81
|
+
<script type="module" src="/checkout.js"></script>`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* `checkouts` holds each checkout by order reference (checkout-flow.js in
|
|
86
|
+
* relyon-checkout). Use the app's database in production
|
|
87
|
+
* (`postgresStoreCheckouts` in durable-state.js).
|
|
88
|
+
*/
|
|
89
|
+
export function createApp(kit, { checkouts = memoryCheckouts() } = {}) {
|
|
90
|
+
const flow = createCheckoutFlow(kit, { priceCart, checkouts, findOrder: async (paymentId) => findOrderByPayment(paymentId) });
|
|
91
|
+
const app = express();
|
|
92
|
+
// Run app.locals.reconcile() on a timer: replays payments still being confirmed.
|
|
93
|
+
app.locals.reconcile = (options) => flow.reconcile(options);
|
|
94
|
+
// 1. The kit first: it needs the raw body of its own routes. It serves the
|
|
95
|
+
// discovery files too: /.well-known/ucp, /.well-known/agent-card.json,
|
|
96
|
+
// /llms.txt, /sitemap-products.xml, the selected feeds and the root sitemap
|
|
97
|
+
// /sitemap.xml, a urlset of the product pages (sitemapIndex: false turns
|
|
98
|
+
// that off when the app has its own /sitemap.xml).
|
|
99
|
+
app.use(storeKitMiddleware(kit));
|
|
100
|
+
// 2. Then the app's own parsers, static files and routes.
|
|
101
|
+
app.use(express.json({ limit: "64kb" }));
|
|
102
|
+
app.use(express.static("public")); // serves public/checkout.js
|
|
103
|
+
|
|
104
|
+
// The homepage: the product list with its Product data, the discovery links
|
|
105
|
+
// agents look for in <head> (llms.txt, UCP, MCP, ACP, the agent card, the
|
|
106
|
+
// sitemap and the feeds) and the policy footer. Every link uses the store's
|
|
107
|
+
// public address for this request (kit.publicOrigin), never a dev address.
|
|
108
|
+
app.get("/", async (req, res) => {
|
|
109
|
+
const request = webRequest(req);
|
|
110
|
+
kit.recordCrawlerVisit(request, 200, { ip: req.ip });
|
|
111
|
+
const { products } = await catalogSource.listProducts({ limit: 100 });
|
|
112
|
+
res.type("html").send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Example Candle Co</title>
|
|
113
|
+
${kit.renderDiscoveryLinks(request)}
|
|
114
|
+
${kit.renderProductListJsonLd(products, request)}
|
|
115
|
+
</head><body>
|
|
116
|
+
<h1>Example Candle Co</h1>
|
|
117
|
+
<ul>${products.map((product) => `<li><a href="/products/${encodeURIComponent(product.merchant_product_id)}">${escape(product.title)}</a>
|
|
118
|
+
${money(product.from_price.amount, product.from_price.currency)}${product.availability === "in_stock" ? "" : " (out of stock)"}</li>`).join("")}</ul>
|
|
119
|
+
${footer()}
|
|
120
|
+
</body></html>`);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// A product page the app renders from its own data. Pass the request so the
|
|
124
|
+
// Product data's links and images use the public address.
|
|
125
|
+
app.get("/products/:id", (req, res) => {
|
|
126
|
+
const request = webRequest(req);
|
|
127
|
+
const product = getProduct(req.params.id);
|
|
128
|
+
kit.recordCrawlerVisit(request, product ? 200 : 404, { ip: req.ip });
|
|
129
|
+
if (!product) return res.status(404).send("Not found");
|
|
130
|
+
const image = kit.productJsonLd(product, request).image?.[0];
|
|
131
|
+
res.type("html").send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${escape(product.title)}</title>
|
|
132
|
+
${kit.renderProductJsonLd(product, request)}
|
|
133
|
+
</head><body>
|
|
134
|
+
<h1>${escape(product.title)}</h1>
|
|
135
|
+
${image ? `<img src="${escape(image)}" alt="${escape(product.title)}" width="480">` : ""}
|
|
136
|
+
<p>${escape(product.description)}</p>
|
|
137
|
+
<p>${money(product.from_price.amount, product.from_price.currency)}</p>
|
|
138
|
+
<form method="post" action="/cart"><input type="hidden" name="product" value="${escape(product.merchant_product_id)}">
|
|
139
|
+
<input type="number" name="quantity" value="1" min="1" max="99" aria-label="Quantity"> <button type="submit">Buy now</button></form>
|
|
140
|
+
${footer()}
|
|
141
|
+
</body></html>`);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// Add to cart: the form posts here, and a 303 sends the shopper to /cart.
|
|
145
|
+
// kit.redirect(request, path) builds the Location on this request's validated store
|
|
146
|
+
// address. Never build a Location from req.url or a Web request.url: a dev
|
|
147
|
+
// server bound to 0.0.0.0 can name that bind address, which no browser opens.
|
|
148
|
+
app.post("/cart", express.urlencoded({ extended: false, limit: "8kb" }), (req, res) => {
|
|
149
|
+
const product = getProduct(String(req.body?.product ?? ""));
|
|
150
|
+
if (!product) return res.status(404).send("Not found");
|
|
151
|
+
const quantity = Math.min(99, Math.max(1, Math.trunc(Number(req.body?.quantity) || 1)));
|
|
152
|
+
const query = new URLSearchParams({ product: product.merchant_product_id, quantity: String(quantity) });
|
|
153
|
+
const seeOther = kit.redirect(webRequest(req), `/cart?${query}`);
|
|
154
|
+
res.status(seeOther.status).set("cache-control", "no-store").location(seeOther.headers.get("location")).end();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// This minimal example keeps only product/quantity in the URL, never prices.
|
|
158
|
+
// A deployed store can read its durable shopper cart/session here instead.
|
|
159
|
+
app.get("/cart", async (req, res) => {
|
|
160
|
+
const id = String(req.query.product ?? "");
|
|
161
|
+
if (!id) return res.type("html").send(`<!doctype html><meta charset="utf-8"><title>Cart</title>
|
|
162
|
+
<h1>Cart</h1><p>Your cart is empty.</p><a href="/checkout">Checkout</a>${footer()}`);
|
|
163
|
+
const product = getProduct(id);
|
|
164
|
+
if (!product) return res.status(404).send("Not found");
|
|
165
|
+
const quantity = Math.min(99, Math.max(1, Math.trunc(Number(req.query.quantity) || 1)));
|
|
166
|
+
let cart;
|
|
167
|
+
try {
|
|
168
|
+
cart = await priceCart([{ product_id: product.merchant_product_id, quantity }], null, [],
|
|
169
|
+
{ protocol: "web", operation: "landing", shippingOptionId: "ground" });
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (error instanceof StoreRefusal) return res.status(error.status).send(escape(error.message));
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
const query = new URLSearchParams({ product: product.merchant_product_id, quantity: String(quantity) });
|
|
175
|
+
res.set("cache-control", "no-store").type("html").send(`<!doctype html><meta charset="utf-8"><title>Cart</title>
|
|
176
|
+
<h1>Cart</h1><ul>${cart.lines.map(line => `<li>${escape(line.title)} × ${line.quantity}: ${money(line.amount, cart.currency)}</li>`).join("")}</ul>
|
|
177
|
+
<p><strong>Total ${money(cart.totals.total, cart.currency)}</strong></p>
|
|
178
|
+
<a href="${escape(`/checkout?${query}`)}">Checkout</a>${footer()}`);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// The policy pages the footer links to.
|
|
182
|
+
for (const [path, page] of Object.entries(POLICY_PAGES)) {
|
|
183
|
+
app.get(`/${path}`, (req, res) => {
|
|
184
|
+
res.type("html").send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${escape(page.title)}</title></head><body>
|
|
185
|
+
<h1>${escape(page.title)}</h1><p>${escape(page.text)}</p>
|
|
186
|
+
${footer()}
|
|
187
|
+
</body></html>`);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// The checkout page, on the store's own domain.
|
|
192
|
+
app.get("/checkout", async (req, res) => {
|
|
193
|
+
if (kit.checkoutStatus === "waiting for sandbox key") {
|
|
194
|
+
return res.status(503).type("html").send(`<!doctype html><meta charset="utf-8"><title>Checkout</title>
|
|
195
|
+
<h1>Checkout</h1><p role="status">Checkout is waiting for sandbox key.</p><button disabled>Pay</button>
|
|
196
|
+
<a href="/products/lavender-candle">Continue shopping</a>`);
|
|
197
|
+
}
|
|
198
|
+
const previous = cookie(req, "checkout_ref");
|
|
199
|
+
const startNew = req.query.new === "1";
|
|
200
|
+
const again = new URLSearchParams({ ...req.query, new: "1" });
|
|
201
|
+
// Check saved payment evidence even when there is no usable cart on reload.
|
|
202
|
+
const prior = await flow.status(previous);
|
|
203
|
+
if (prior.body.state === "pending" || (prior.body.state === "paid" && !startNew)) {
|
|
204
|
+
const view = prior.body.state === "pending" ? await flow.confirm(previous) : prior;
|
|
205
|
+
return res.status(view.httpStatus).type("html").send(statusPage(view, `/checkout?${again}`));
|
|
206
|
+
}
|
|
207
|
+
// A shopper an agent handed over arrives with ?relyon_cart=…; anyone else
|
|
208
|
+
// gets the app's own cart. Only an unattributed or invalid link falls back,
|
|
209
|
+
// never a handed-over cart the store refused, a failure pricing that
|
|
210
|
+
// independent cart, or a failure obtaining its payment fields.
|
|
211
|
+
let landing;
|
|
212
|
+
try {
|
|
213
|
+
landing = await kit.landing(webRequest(req), { ip: req.ip });
|
|
214
|
+
} catch {
|
|
215
|
+
landing = null;
|
|
216
|
+
}
|
|
217
|
+
if (landing?.alreadyPaid) {
|
|
218
|
+
return res.status(202).type("html").send(`<!doctype html><meta charset="utf-8"><title>Order status</title>
|
|
219
|
+
<h1>Order status</h1><p role="status">${landing.alreadyPaid.orderPending
|
|
220
|
+
? "Your payment went through. Your order is still being placed"
|
|
221
|
+
: "This order may already have been paid. Check your order status before paying again."}</p>`);
|
|
222
|
+
}
|
|
223
|
+
if (landing?.attributed && landing.refusal) {
|
|
224
|
+
// The store refused the cart the agent handed over: say why, never swap in another cart.
|
|
225
|
+
return res.status(409).type("html").send(`<!doctype html><meta charset="utf-8"><title>Checkout</title>
|
|
226
|
+
<h1>Checkout</h1><p role="alert">${escape(landing.refusal.message)}</p><p><a href="/products/lavender-candle">Start shopping</a></p>`);
|
|
227
|
+
}
|
|
228
|
+
const accepted = landing?.attributed && !landing.refusal
|
|
229
|
+
&& landing.cart?.lines?.length > 0 && landing.inputs?.lines?.length > 0;
|
|
230
|
+
// This example's independent cart source is the product/quantity query.
|
|
231
|
+
// A real store can read a shopper session instead.
|
|
232
|
+
const product = String(req.query.product ?? "");
|
|
233
|
+
const inputs = accepted ? landing.inputs : {
|
|
234
|
+
lines: product ? [{ product_id: product, quantity: Number(req.query.quantity ?? 1) }] : [],
|
|
235
|
+
address: null, coupons: [], shipping_option_id: "ground",
|
|
236
|
+
};
|
|
237
|
+
if (!inputs.lines.length) {
|
|
238
|
+
return res.type("html").send(`<!doctype html><meta charset="utf-8"><title>Checkout</title>
|
|
239
|
+
<h1>Checkout</h1><p>Your cart is empty.</p><p><a href="/products/lavender-candle">Start shopping</a></p>`);
|
|
240
|
+
}
|
|
241
|
+
let opened;
|
|
242
|
+
try {
|
|
243
|
+
opened = await flow.open({
|
|
244
|
+
inputs, cart: accepted ? landing.cart : null,
|
|
245
|
+
channel: accepted ? landing.channel : "web", agentCheckoutId: accepted ? landing.agentCheckoutId : null,
|
|
246
|
+
// A reload while a payment is being confirmed shows its status, never new card fields.
|
|
247
|
+
previous, startNew,
|
|
248
|
+
});
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error instanceof StoreRefusal) return res.status(error.status).send(escape(error.message));
|
|
251
|
+
if (error instanceof PaymentUnavailableError) return res.status(503).send("Payments are unavailable right now. Try again shortly.");
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
const { orderReference } = opened;
|
|
255
|
+
res.cookie("checkout_ref", orderReference, { httpOnly: true, secure: true, sameSite: "lax", path: "/" });
|
|
256
|
+
if (opened.view) {
|
|
257
|
+
return res.status(opened.view.httpStatus).type("html").send(statusPage(opened.view, `/checkout?${again}`));
|
|
258
|
+
}
|
|
259
|
+
const { cart, fields } = opened;
|
|
260
|
+
const t = cart.totals;
|
|
261
|
+
res.type("html").send(`<!doctype html><meta charset="utf-8"><title>Checkout</title>
|
|
262
|
+
<h1>Checkout</h1>
|
|
263
|
+
<ul>${cart.lines.map((line) => `<li>${escape(line.title)} × ${line.quantity}: ${money(line.amount, cart.currency)}</li>`).join("")}</ul>
|
|
264
|
+
<p>Subtotal ${money(t.subtotal, t.currency)} · Discount ${money(t.discount, t.currency)} · Shipping ${money(t.shipping, t.currency)} · Tax ${money(t.tax, t.currency)}</p>
|
|
265
|
+
<p><strong>Total ${money(t.total, t.currency)}</strong></p>
|
|
266
|
+
<form id="pay" data-order-reference="${escape(orderReference)}" data-new-checkout="${escape(`/checkout?${again}`)}">
|
|
267
|
+
<script>
|
|
268
|
+
// Ready latch (relyon-checkout's checkout-page.md): before the card fields, so it never misses "relyon-ready".
|
|
269
|
+
addEventListener("relyon-ready", (event) => { event.target.dataset.relyonReady = "true"; }, true);
|
|
270
|
+
addEventListener("relyon-error", (event) => { delete event.target.dataset.relyonReady; }, true);
|
|
271
|
+
</script>
|
|
272
|
+
${fields.html}
|
|
273
|
+
<button type="submit">Pay ${money(t.total, t.currency)}</button>
|
|
274
|
+
<p id="status" role="status"></p>
|
|
275
|
+
</form>
|
|
276
|
+
<script type="module" src="/checkout.js"></script>`);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
const answer = (res, view) => res.status(view.httpStatus).json(view.body);
|
|
280
|
+
|
|
281
|
+
// The browser sends only the order reference and the tokenized payment method.
|
|
282
|
+
app.post("/checkout/pay", async (req, res) => {
|
|
283
|
+
if (kit.checkoutStatus === "waiting for sandbox key") return res.status(503).json({ code: "sandbox_key_pending", message: "Checkout is waiting for sandbox key." });
|
|
284
|
+
const { orderReference, paymentMethod } = req.body ?? {};
|
|
285
|
+
answer(res, await flow.pay({ orderReference, paymentMethod, request: webRequest(req), info: { ip: req.ip } }));
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
// After a lost answer: replays the attempt already sent, never a new one.
|
|
289
|
+
app.post("/checkout/confirm", async (req, res) => {
|
|
290
|
+
answer(res, await flow.confirm(req.body?.orderReference));
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// The order status page a shopper can come back to.
|
|
294
|
+
app.get("/checkout/status", async (req, res) => {
|
|
295
|
+
const view = await flow.status(String(req.query.order_reference ?? ""));
|
|
296
|
+
res.status(view.httpStatus).type("html").send(statusPage(view, null));
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
return app;
|
|
300
|
+
}
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Start it and stop cleanly. Source-backed discovery and feeds need no sync,
|
|
304
|
+
but Relyon's agent checkout (MCP, UCP and ACP) only buys products it has in
|
|
305
|
+
the store's Relyon catalog, so the starter sends them once a key is set.
|
|
306
|
+
A plain Node/Express server doesn't read `.env` by itself: `loadTestConfig()`
|
|
307
|
+
below loads the Test key init saved (or use `dotenv`). Never cat or print
|
|
308
|
+
`.env`, and never paste the key into a command.
|
|
309
|
+
|
|
310
|
+
```js main.js
|
|
311
|
+
import { createRelyonKit } from "./relyon.js";
|
|
312
|
+
import { createApp } from "./server.js";
|
|
313
|
+
import { loadTestConfig } from "@relyon/store-kit/server-config";
|
|
314
|
+
import { listProducts } from "./store.js";
|
|
315
|
+
|
|
316
|
+
const privateConfig = await loadTestConfig({ project: process.cwd() });
|
|
317
|
+
const kit = createRelyonKit({
|
|
318
|
+
env: { ...process.env, ...(privateConfig.apiKey ? { RELYON_API_KEY: privateConfig.apiKey } : {}),
|
|
319
|
+
...(privateConfig.webhookSecret ? { RELYON_WEBHOOK_SECRET: privateConfig.webhookSecret } : {}) },
|
|
320
|
+
// robots.txt is served by default (AI search and shopping crawlers allowed,
|
|
321
|
+
// both sitemaps named). An app with its own robots.txt passes
|
|
322
|
+
// robots: { existing: () => itsText } so every line is kept; robots: false opts out.
|
|
323
|
+
});
|
|
324
|
+
await kit.start();
|
|
325
|
+
// catalog.source serves discovery and feeds from the store's database. Agent
|
|
326
|
+
// checkout buys only products in the store's Relyon catalog: send them now and
|
|
327
|
+
// again whenever the merchant edits products. A failed sync changes nothing.
|
|
328
|
+
if (kit.checkoutStatus === "ready") {
|
|
329
|
+
await kit.syncCatalog(await listProducts()).catch((error) => console.error("catalog sync failed", error.message));
|
|
330
|
+
}
|
|
331
|
+
const app = createApp(kit);
|
|
332
|
+
const server = app.listen(Number(process.env.PORT ?? 3000), "0.0.0.0");
|
|
333
|
+
// Payments whose outcome wasn't final are replayed (same Idempotency-Key) until it is.
|
|
334
|
+
const reconcile = setInterval(() => {
|
|
335
|
+
app.locals.reconcile().catch((error) => console.error("reconcile failed", error.message));
|
|
336
|
+
}, 60_000);
|
|
337
|
+
process.on("SIGTERM", () => {
|
|
338
|
+
clearInterval(reconcile);
|
|
339
|
+
server.close();
|
|
340
|
+
void kit.stop(); // flushes queued agent events
|
|
341
|
+
});
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
## Sitemaps and robots.txt
|
|
345
|
+
|
|
346
|
+
The kit answers the root `/sitemap.xml` with a urlset of the product pages
|
|
347
|
+
(the same entries as `/sitemap-products.xml`), on the store's public address:
|
|
348
|
+
|
|
349
|
+
```xml
|
|
350
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
351
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
352
|
+
<url><loc>https://shop.example.com/products/lavender-candle</loc></url>
|
|
353
|
+
<url><loc>https://shop.example.com/products/candle-trio</loc></url>
|
|
354
|
+
</urlset>
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
The kit serves `/robots.txt` by default. With `robots: { existing }`
|
|
358
|
+
(`existing()` returns the app's own robots.txt), the merged file keeps every
|
|
359
|
+
original line and adds the AI discovery section. Either way it ends with a
|
|
360
|
+
`Sitemap:` line for the root sitemap and one for the product sitemap:
|
|
361
|
+
|
|
362
|
+
```text
|
|
363
|
+
Sitemap: https://shop.example.com/sitemap.xml
|
|
364
|
+
Sitemap: https://shop.example.com/sitemap-products.xml
|
|
365
|
+
# llms.txt: https://shop.example.com/llms.txt
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
A new store has no robots.txt of its own, so the starter's `main.js` uses the
|
|
369
|
+
default. An Express app with its own robots route mounted after the kit must
|
|
370
|
+
pass `robots: { existing }` or `robots: false`, or the kit's answer shadows it.
|
|
371
|
+
Some hosts and tunnels add
|
|
372
|
+
their own robots.txt rules in front of the app's (blocking AI crawlers by
|
|
373
|
+
default); the kit's explicit `Allow: /` groups for AI search and shopping
|
|
374
|
+
crawlers still apply, but check the host's bot settings too. With
|
|
375
|
+
`robots: false`, add those two `Sitemap:` lines to the app's own robots.txt by
|
|
376
|
+
hand.
|
|
377
|
+
|
|
378
|
+
## On the preview address
|
|
379
|
+
|
|
380
|
+
In Test mode the same server works on the app's preview address, on any
|
|
381
|
+
platform: an https preview URL or tunnel, or `localhost` on its port over
|
|
382
|
+
plain http. The kit adds loopback, the hostnames in `RELYON_PREVIEW_HOSTS`
|
|
383
|
+
(set it in your platform's secrets or environment settings) and the app's own
|
|
384
|
+
address when its platform names it in a well-known variable to
|
|
385
|
+
`store.hostnames` itself, so agents can run a whole Test checkout there, and
|
|
386
|
+
the hand-off link comes back to this same address. A Live key is refused there: publish, add
|
|
387
|
+
and verify the domain, then switch to a Live key only with the merchant's
|
|
388
|
+
approval (`relyon-go-live`).
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
# Next.js App Router (Next.js 15 and 16)
|
|
2
|
+
|
|
3
|
+
The kit runs inside the app's own route handlers. These files build on
|
|
4
|
+
`create-next-app@latest` (Next.js 16, Turbopack, `cacheComponents`) and on
|
|
5
|
+
Next.js 15. `npx @relyon/store-kit init --template next` creates a complete
|
|
6
|
+
starter that already does all of this.
|
|
7
|
+
|
|
8
|
+
## No route segment config
|
|
9
|
+
|
|
10
|
+
Add **no** `export const runtime`, `export const dynamic` or
|
|
11
|
+
`export const revalidate` to the kit's route files. Route handlers run on
|
|
12
|
+
Node.js by default, and they read the request, so they are dynamic on both
|
|
13
|
+
versions. Next.js 16 with `cacheComponents` refuses that segment config and the
|
|
14
|
+
build fails.
|
|
15
|
+
|
|
16
|
+
## One shared kit
|
|
17
|
+
|
|
18
|
+
Create the kit once, on the server only. Next.js loads `.env` itself; the Test
|
|
19
|
+
key init saved privately is read by `loadTestConfig()`. Never cat or print
|
|
20
|
+
`.env`, and never paste the key into a command.
|
|
21
|
+
|
|
22
|
+
```ts lib/relyon.ts
|
|
23
|
+
import "server-only"; // optional: npm install server-only
|
|
24
|
+
import { createStoreKit, type StoreKit } from "@relyon/store-kit";
|
|
25
|
+
import { loadTestConfig } from "@relyon/store-kit/server-config";
|
|
26
|
+
import { priceCart, createOrder, catalogSource } from "./store";
|
|
27
|
+
|
|
28
|
+
// One instance per server process, created on first use (never at build time).
|
|
29
|
+
const shared = globalThis as typeof globalThis & { relyonKit?: Promise<StoreKit> };
|
|
30
|
+
|
|
31
|
+
export function getKit(): Promise<StoreKit> {
|
|
32
|
+
return (shared.relyonKit ??= (async () => {
|
|
33
|
+
const { apiKey } = await loadTestConfig({ project: process.cwd() });
|
|
34
|
+
const hostnames = (process.env.STORE_HOSTNAMES ?? "localhost").split(",").map((h) => h.trim()).filter(Boolean);
|
|
35
|
+
const kit = createStoreKit({
|
|
36
|
+
relyon: { baseUrl: "https://core.getrelyon.com/api", apiKey, waitingForSandboxKey: true },
|
|
37
|
+
store: { name: "Example Store", description: "What the store sells.", hostnames },
|
|
38
|
+
priceCart,
|
|
39
|
+
createOrder,
|
|
40
|
+
catalog: { source: catalogSource },
|
|
41
|
+
feeds: { formats: ["openai", "openaiGzip", "google", "microsoft"] },
|
|
42
|
+
// robots.txt is served by default; robots: false opts out.
|
|
43
|
+
});
|
|
44
|
+
await kit.start();
|
|
45
|
+
return kit;
|
|
46
|
+
})());
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Route files
|
|
51
|
+
|
|
52
|
+
```ts lib/relyon-routes.ts
|
|
53
|
+
import { storeKitRouteHandlers } from "@relyon/store-kit/next";
|
|
54
|
+
import { getKit } from "./relyon";
|
|
55
|
+
|
|
56
|
+
type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
|
|
57
|
+
const route = (method: Method) => async (request: Request) => {
|
|
58
|
+
const handler = storeKitRouteHandlers(await getKit())[method];
|
|
59
|
+
return handler(request);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const GET = route("GET"), POST = route("POST"), PUT = route("PUT"),
|
|
63
|
+
PATCH = route("PATCH"), DELETE = route("DELETE"), HEAD = route("HEAD");
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Each of these files contains only one line,
|
|
67
|
+
`export { GET, POST, PUT, PATCH, DELETE, HEAD } from "@/lib/relyon-routes";`:
|
|
68
|
+
|
|
69
|
+
| File | Kit path |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `app/.well-known/ucp/route.ts` | UCP profile |
|
|
72
|
+
| `app/.well-known/ucp/[...path]/route.ts` | UCP 2026-04-08 profile (`/.well-known/ucp/2026-04-08`, needed for cart transfer) |
|
|
73
|
+
| `app/.well-known/relyon-verification/route.ts` | domain verification |
|
|
74
|
+
| `app/.well-known/agent-card.json/route.ts` | agent card |
|
|
75
|
+
| `app/ucp/[...path]/route.ts`, `app/acp/[...path]/route.ts` | agent checkout; UCP cart transfer (`POST /ucp/carts`) runs under `app/ucp/[...path]` |
|
|
76
|
+
| `app/mcp/route.ts` | store MCP |
|
|
77
|
+
| `app/llms.txt/route.ts`, `app/sitemap-products.xml/route.ts`, `app/sitemap.xml/route.ts` | discovery |
|
|
78
|
+
| `app/feeds/[file]/route.ts` | selected feeds |
|
|
79
|
+
| `app/robots.txt/route.ts` | robots (skip with `robots: false`) |
|
|
80
|
+
| `app/relyon/[...path]/route.ts` | webhooks and the Test checkout |
|
|
81
|
+
|
|
82
|
+
A Next.js `app/robots.ts` or `app/sitemap.ts` metadata file conflicts with the
|
|
83
|
+
kit's route of the same path: keep one. To keep the app's own robots policy,
|
|
84
|
+
pass `robots: { existing: () => itsText }` and delete `app/robots.ts`.
|
|
85
|
+
|
|
86
|
+
## Product pages (Next.js 16)
|
|
87
|
+
|
|
88
|
+
A product page builds on Next.js 16 (`cacheComponents`) when its dynamic
|
|
89
|
+
params come from `generateStaticParams`, the data read sits inside a
|
|
90
|
+
`Suspense` boundary, and the product JSON-LD is rendered on the server.
|
|
91
|
+
`productJsonLd` is a pure function: it needs no kit instance, so nothing talks
|
|
92
|
+
to Relyon at build time.
|
|
93
|
+
|
|
94
|
+
```tsx app/products/[id]/page.tsx
|
|
95
|
+
import { Suspense } from "react";
|
|
96
|
+
import { notFound } from "next/navigation";
|
|
97
|
+
import { productJsonLd } from "@relyon/store-kit";
|
|
98
|
+
import { catalogSource } from "@/lib/store";
|
|
99
|
+
import { AddToCart } from "./add-to-cart";
|
|
100
|
+
|
|
101
|
+
type Params = Promise<{ id: string }>;
|
|
102
|
+
|
|
103
|
+
export async function generateStaticParams() {
|
|
104
|
+
const { products } = await catalogSource.listProducts({ limit: 100 });
|
|
105
|
+
return products.map((product) => ({ id: product.merchant_product_id }));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export default function ProductPage({ params }: { params: Params }) {
|
|
109
|
+
return (
|
|
110
|
+
<Suspense fallback={<p>Loading…</p>}>
|
|
111
|
+
<Product params={params} />
|
|
112
|
+
</Suspense>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function Product({ params }: { params: Params }) {
|
|
117
|
+
const { id } = await params;
|
|
118
|
+
const product = await catalogSource.getProduct(id);
|
|
119
|
+
if (!product) notFound();
|
|
120
|
+
const jsonLd = JSON.stringify(productJsonLd(product)).replace(/</g, "\\u003c");
|
|
121
|
+
return (
|
|
122
|
+
<main>
|
|
123
|
+
<h1>{product.title}</h1>
|
|
124
|
+
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLd }} />
|
|
125
|
+
<AddToCart productId={product.merchant_product_id} />
|
|
126
|
+
</main>
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```tsx app/products/[id]/add-to-cart.tsx
|
|
132
|
+
"use client";
|
|
133
|
+
// A client component: plain props only. Never import @relyon/store-kit here.
|
|
134
|
+
export function AddToCart({ productId }: { productId: string }) {
|
|
135
|
+
return (
|
|
136
|
+
<form method="post" action="/cart/add">
|
|
137
|
+
<input type="hidden" name="product" value={productId} />
|
|
138
|
+
<button type="submit">Add to cart</button>
|
|
139
|
+
</form>
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Keep every `@relyon/store-kit` import (and `lib/relyon.ts`) out of client
|
|
145
|
+
components (`"use client"` files and anything they import): the kit is server
|
|
146
|
+
code that reads the store's keys. Pass plain values to client components as
|
|
147
|
+
props.
|
|
148
|
+
|
|
149
|
+
## A real cart page
|
|
150
|
+
|
|
151
|
+
Next cannot put `page.tsx` and `route.ts` at the same URL. The form above
|
|
152
|
+
therefore posts to `/cart/add`; its handler sends HTTP 303 to the real
|
|
153
|
+
server-rendered `/cart` page. Do not add `app/cart/route.ts` beside the page.
|
|
154
|
+
These examples keep only product and quantity in the URL, never a trusted
|
|
155
|
+
price. A deployed store can use its durable shopper cart/session instead.
|
|
156
|
+
|
|
157
|
+
```ts app/cart/add/route.ts
|
|
158
|
+
import { catalogSource } from "@/lib/store";
|
|
159
|
+
import { getKit } from "@/lib/relyon";
|
|
160
|
+
|
|
161
|
+
export async function POST(request: Request) {
|
|
162
|
+
if (request.headers.get("origin") !== new URL(request.url).origin)
|
|
163
|
+
return new Response("Same-origin form required", { status: 403 });
|
|
164
|
+
const form = await request.formData();
|
|
165
|
+
const product = await catalogSource.getProduct(String(form.get("product") ?? ""));
|
|
166
|
+
if (!product) return new Response("Not found", { status: 404 });
|
|
167
|
+
const quantity = Math.min(99, Math.max(1, Math.trunc(Number(form.get("quantity")) || 1)));
|
|
168
|
+
const query = new URLSearchParams({ product: product.merchant_product_id, quantity: String(quantity) });
|
|
169
|
+
const kit = await getKit();
|
|
170
|
+
return kit.redirect(request, `/cart?${query}`);
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
```tsx app/cart/page.tsx
|
|
175
|
+
import { Suspense } from "react";
|
|
176
|
+
import { notFound } from "next/navigation";
|
|
177
|
+
import { catalogSource, priceCart } from "@/lib/store";
|
|
178
|
+
|
|
179
|
+
type SearchParams = Promise<{ product?: string; quantity?: string }>;
|
|
180
|
+
const money = (amount: number, currency: string) =>
|
|
181
|
+
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount / 100);
|
|
182
|
+
|
|
183
|
+
export default function CartPage({ searchParams }: { searchParams: SearchParams }) {
|
|
184
|
+
return <Suspense fallback={<p>Loading cart…</p>}><Cart searchParams={searchParams} /></Suspense>;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function Cart({ searchParams }: { searchParams: SearchParams }) {
|
|
188
|
+
const params = await searchParams;
|
|
189
|
+
if (!params.product) return <main><h1>Cart</h1><p>Your cart is empty.</p><a href="/checkout">Checkout</a></main>;
|
|
190
|
+
const product = await catalogSource.getProduct(params.product);
|
|
191
|
+
if (!product) notFound();
|
|
192
|
+
const quantity = Math.min(99, Math.max(1, Math.trunc(Number(params.quantity) || 1)));
|
|
193
|
+
const cart = await priceCart([{ product_id: product.merchant_product_id, quantity }], null, [],
|
|
194
|
+
{ protocol: "web", operation: "landing", shippingOptionId: "ground" });
|
|
195
|
+
const query = new URLSearchParams({ product: product.merchant_product_id, quantity: String(quantity) });
|
|
196
|
+
return <main>
|
|
197
|
+
<h1>Cart</h1>
|
|
198
|
+
<ul>{cart.lines.map((line, index) => <li key={line.id ?? index}>{line.title} × {line.quantity}: {money(line.amount, cart.currency)}</li>)}</ul>
|
|
199
|
+
<p>Total {money(cart.totals.total, cart.currency)}</p>
|
|
200
|
+
<a href={`/checkout?${query}`}>Checkout</a>
|
|
201
|
+
</main>;
|
|
202
|
+
}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
The checkout server reads the same `product` and `quantity` search parameters
|
|
206
|
+
into `[{ product_id: product, quantity }]` and re-prices with `priceCart`, just
|
|
207
|
+
as the Express reference does. For an attributed `relyon_cart` hand-off, use
|
|
208
|
+
the accepted `kit.landing()` inputs instead; never replace a refused hand-off
|
|
209
|
+
with this independent cart. All catalog/pricing and kit imports above stay
|
|
210
|
+
in server files; the client form receives only its product ID.
|
|
211
|
+
|
|
212
|
+
For a product with options, list its variants in `feed.variants`
|
|
213
|
+
(relyon-catalog skill) and post the chosen options with the cart form. The
|
|
214
|
+
checkout page shows a landed cart with `kit.landing()`, which also takes the
|
|
215
|
+
page's `searchParams` (see "Transferred carts and hand-offs" in the
|
|
216
|
+
relyon-checkout skill's `references/checkout-page.md`).
|
|
217
|
+
|
|
218
|
+
## Previews on 127.0.0.1
|
|
219
|
+
|
|
220
|
+
`next dev` refuses its development resources to an origin it doesn't know.
|
|
221
|
+
When the preview opens the app on `127.0.0.1` (doctor and test-checkout use
|
|
222
|
+
that address too), add it to `next.config.mjs`:
|
|
223
|
+
|
|
224
|
+
```js next.config.mjs
|
|
225
|
+
const nextConfig = { allowedDevOrigins: ["127.0.0.1"] };
|
|
226
|
+
export default nextConfig;
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
The `--template next` starter sets it.
|
|
230
|
+
|
|
231
|
+
## Imports between server files
|
|
232
|
+
|
|
233
|
+
With `"moduleResolution": "bundler"` (the create-next-app default), import
|
|
234
|
+
server files without an extension (`./store`). If the project's server code
|
|
235
|
+
uses NodeNext-style `.js` imports of `.ts` files, set `"module"` and
|
|
236
|
+
`"moduleResolution"` to `"NodeNext"` in `tsconfig.json` so Turbopack (Next 16)
|
|
237
|
+
resolves them, and keep `"skipLibCheck": true` (Next.js 15's own type files
|
|
238
|
+
don't resolve under NodeNext otherwise). For Next.js 15 (webpack) also add
|
|
239
|
+
`webpack(config) { config.resolve.extensionAlias = { ".js": [".ts", ".tsx", ".js"] }; return config; }`
|
|
240
|
+
and `turbopack: {}` to `next.config.mjs`. The `--template next` starter does
|
|
241
|
+
exactly this.
|
|
242
|
+
|
|
243
|
+
## Check it
|
|
244
|
+
|
|
245
|
+
Start the app (with `STORE_PUBLIC_URL` set to its address), then:
|
|
246
|
+
|
|
247
|
+
```sh
|
|
248
|
+
npx --no-install @relyon/store-kit doctor --url "$STORE_PUBLIC_URL"
|
|
249
|
+
npx --no-install @relyon/store-kit test-checkout --url "$STORE_PUBLIC_URL"
|
|
250
|
+
npx --no-install @relyon/store-kit doctor --url "$STORE_PUBLIC_URL"
|
|
251
|
+
```
|