@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,123 @@
1
+ import { RelyonPayments, PaymentOutcomeUnknown } from "./payments.js";
2
+ import { RelyonProblemError, RelyonUnavailableError } from "./relyon.js";
3
+ import { isRecord } from "./util.js";
4
+ export const DEFAULT_PAYMENT_ROUTES = Object.freeze({
5
+ session: "/relyon/payments/session",
6
+ charge: "/relyon/payments/charge",
7
+ webhook: "/relyon/webhooks",
8
+ });
9
+ const ORDER_REFERENCE = /^[\w.:#/-]{1,200}$/;
10
+ function json(status, body, headers = {}) {
11
+ return new Response(`${JSON.stringify(body)}\n`, { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers } });
12
+ }
13
+ const problem = (status, code, message) => json(status, { error: { code, message } });
14
+ function relyonProblem(error) {
15
+ if (error instanceof PaymentOutcomeUnknown) {
16
+ return json(202, { status: "payment_outcome_unknown", message: error.message }, { "retry-after": "2" });
17
+ }
18
+ if (error instanceof RelyonProblemError) {
19
+ // Relyon's own refusal, passed on by code; the key and Relyon's details stay on the server.
20
+ return problem(error.status >= 500 ? 502 : error.status === 401 || error.status === 403 ? 503 : 400, error.code, error.message);
21
+ }
22
+ if (error instanceof RelyonUnavailableError)
23
+ return problem(503, "payments_unavailable", "Payments are unavailable right now. Try again shortly.");
24
+ if (error instanceof TypeError)
25
+ return problem(400, "invalid_request", error.message);
26
+ throw error;
27
+ }
28
+ /**
29
+ * The payments-only routes as one Fetch handler. Mount it with
30
+ * `paymentsMiddleware` (Express), `paymentsRouteHandlers` (Next.js) or
31
+ * `paymentsNodeHandler` (a plain Node server).
32
+ */
33
+ export class PaymentRoutes {
34
+ payments;
35
+ paths;
36
+ maxBodyBytes;
37
+ options;
38
+ constructor(options) {
39
+ if (typeof options?.orderAmount !== "function")
40
+ throw new TypeError("Payment routes need orderAmount: the order's amount from your own records.");
41
+ this.options = options;
42
+ this.payments = options.payments ?? new RelyonPayments();
43
+ this.paths = Object.freeze({ ...DEFAULT_PAYMENT_ROUTES, ...options.paths });
44
+ this.maxBodyBytes = options.maxBodyBytes ?? 64 * 1024;
45
+ }
46
+ /** True for the three paths this handler answers. */
47
+ matches(pathname) {
48
+ return pathname === this.paths.session || pathname === this.paths.charge || pathname === this.paths.webhook;
49
+ }
50
+ /** The route's answer, or null for any other path. */
51
+ async handle(request, _context = {}) {
52
+ const pathname = new URL(request.url).pathname;
53
+ if (!this.matches(pathname))
54
+ return null;
55
+ if (request.method !== "POST")
56
+ return json(405, { error: { code: "method_not_allowed", message: "Use POST." } }, { allow: "POST" });
57
+ const raw = new Uint8Array(await request.arrayBuffer());
58
+ if (raw.byteLength > this.maxBodyBytes)
59
+ return problem(413, "body_too_large", "The request body is too large.");
60
+ if (pathname === this.paths.webhook)
61
+ return this.webhook(raw, request.headers);
62
+ let body;
63
+ try {
64
+ body = JSON.parse(new TextDecoder().decode(raw));
65
+ }
66
+ catch {
67
+ return problem(400, "invalid_json", "Send a JSON body.");
68
+ }
69
+ if (!isRecord(body) || typeof body.order_reference !== "string" || !ORDER_REFERENCE.test(body.order_reference)) {
70
+ return problem(400, "invalid_order_reference", "Send order_reference: your order's reference (letters, digits and . : # / - _).");
71
+ }
72
+ const orderReference = body.order_reference;
73
+ const order = await this.options.orderAmount(orderReference);
74
+ if (!order)
75
+ return problem(404, "order_not_found", "No order has that reference.");
76
+ try {
77
+ if (pathname === this.paths.session) {
78
+ const session = await this.payments.createSession({ amount: order.amount, currency: order.currency, orderReference });
79
+ return json(200, {
80
+ payment_session: session.id, client_token: session.client_token, script_url: this.payments.cardFieldsScriptUrl,
81
+ amount: session.amount, currency: session.currency,
82
+ });
83
+ }
84
+ if (!isRecord(body.payment_method))
85
+ return problem(400, "invalid_payment_method", "Send payment_method: exactly what the card fields' tokenize() resolved to.");
86
+ const attempt = body.attempt === undefined ? 0 : body.attempt;
87
+ if (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 0 || attempt > 20)
88
+ return problem(400, "invalid_attempt", "attempt must be a whole number from 0 to 20.");
89
+ const payment = await this.payments.charge({
90
+ amount: order.amount, currency: order.currency, orderReference, paymentMethod: body.payment_method, attempt,
91
+ ...(order.description ? { description: order.description } : {}),
92
+ });
93
+ if (payment.status !== "succeeded") {
94
+ return json(402, { status: "failed", payment_id: payment.id, message: "The card was declined. Try another card (send attempt + 1)." });
95
+ }
96
+ await this.options.onPaid?.(payment, orderReference);
97
+ return json(200, { status: "succeeded", payment_id: payment.id, amount: payment.amount, currency: payment.currency });
98
+ }
99
+ catch (error) {
100
+ return relyonProblem(error);
101
+ }
102
+ }
103
+ async webhook(raw, headers) {
104
+ if (!this.payments.verifyWebhook({ rawBody: raw, headers })) {
105
+ return problem(400, "invalid_signature", "The webhook signature did not verify (check RELYON_WEBHOOK_SECRET).");
106
+ }
107
+ let event;
108
+ try {
109
+ event = JSON.parse(new TextDecoder().decode(raw));
110
+ }
111
+ catch {
112
+ return problem(400, "invalid_json", "The webhook body is not JSON.");
113
+ }
114
+ if (!isRecord(event))
115
+ return problem(400, "invalid_event", "The webhook body is not an event.");
116
+ await this.options.onEvent?.(event);
117
+ return json(200, { received: true });
118
+ }
119
+ }
120
+ /** Creates the payments-only routes (layer 1). */
121
+ export function createPaymentRoutes(options) {
122
+ return new PaymentRoutes(options);
123
+ }
@@ -0,0 +1,165 @@
1
+ import { WEBHOOK_SIGNATURE_HEADER } from "./wire-names.js";
2
+ import { RelyonGateway, type FetchLike } from "./relyon.js";
3
+ import type { PaymentSession } from "./types.js";
4
+ /** Relyon's API base URL when none is configured. */
5
+ export declare const DEFAULT_PAYMENTS_BASE_URL = "https://core.getrelyon.com/api";
6
+ export interface PaymentsOptions {
7
+ /** The secret key: a Test key (`rly_test_…`), or a Live key with `live: true`. Default `RELYON_API_KEY`. */
8
+ apiKey?: string | undefined;
9
+ /** Relyon's API base URL. Default `RELYON_BASE_URL`, else Relyon's own. */
10
+ baseUrl?: string | undefined;
11
+ /** Explicit Live opt-in (never from the key prefix alone). Default `RELYON_LIVE=true`, else Test. */
12
+ live?: boolean | undefined;
13
+ /**
14
+ * The project space these payments belong to (`RELYON_PROJECT_SPACE`).
15
+ * Sent as the `Relyon-Project-Space` header (its `prj_…` ID). Optional in a
16
+ * workspace with one project space; with several, Relyon refuses calls
17
+ * without it (`project_space_required`).
18
+ */
19
+ projectSpace?: string | undefined;
20
+ /** The webhook endpoint's signing secret, for `verifyWebhook`. Default `RELYON_WEBHOOK_SECRET`. */
21
+ webhookSecret?: string | undefined;
22
+ /** Timeout for every call to Relyon, in milliseconds. Default 10000. */
23
+ timeoutMs?: number;
24
+ /** Replaces the global fetch, for tests and custom transports. */
25
+ fetch?: FetchLike;
26
+ /** Where unset options are read from. Default `process.env`. */
27
+ env?: NodeJS.ProcessEnv;
28
+ }
29
+ export interface PaymentSessionInput {
30
+ /** The amount the shopper will pay, in minor units (cents). */
31
+ amount: number;
32
+ currency: string;
33
+ /** The app's own order reference; the same one goes to `charge`. */
34
+ orderReference: string;
35
+ metadata?: Record<string, string>;
36
+ /** Default: a fresh key per call (sessions are single use). */
37
+ idempotencyKey?: string;
38
+ }
39
+ export interface PaymentCardFieldsInput extends PaymentSessionInput {
40
+ /** Passed to the element's `field-styles` attribute. */
41
+ fieldStyles?: string;
42
+ /** The element's id attribute. Default `relyon-card-fields`. */
43
+ elementId?: string;
44
+ }
45
+ export interface PaymentCardFields {
46
+ session: PaymentSession;
47
+ /** The `<script>` tag loading the card fields: the only Relyon URL a shopper loads. */
48
+ scriptTag: string;
49
+ /** The `<relyon-card-fields>` element for this session. */
50
+ element: string;
51
+ /** Both, ready to place in the checkout page. */
52
+ html: string;
53
+ }
54
+ /** What `<relyon-card-fields>`'s `tokenize()` resolves to, passed through unchanged. */
55
+ export interface HostedCardPaymentMethod {
56
+ type: "hosted_card";
57
+ payment_session: string;
58
+ encrypted_data: string;
59
+ key_id: string;
60
+ }
61
+ export interface ChargeInput {
62
+ /** The amount the shopper saw and agreed to, in minor units. */
63
+ amount: number;
64
+ currency: string;
65
+ /** The app's own order reference. The Idempotency-Key is derived from it, so a retry never charges twice. */
66
+ orderReference: string;
67
+ /** Exactly what the card fields' `tokenize()` resolved to. Never card numbers. */
68
+ paymentMethod: HostedCardPaymentMethod | Record<string, unknown>;
69
+ /** What is being paid for, shown on the payment's one cart line. Default "Order <orderReference>". */
70
+ description?: string;
71
+ /**
72
+ * Raise only after a confirmed decline (status `failed`), so the next card
73
+ * gets its own Idempotency-Key. Keep it after an unknown outcome so the
74
+ * retry reconciles the same request. Default 0.
75
+ */
76
+ attempt?: number;
77
+ customerEmail?: string;
78
+ metadata?: Record<string, string>;
79
+ }
80
+ /** A Relyon payment, as `POST /v1/payments` answers it. */
81
+ export type ChargeResult = {
82
+ id: string;
83
+ object: "payment";
84
+ status: "succeeded" | "failed";
85
+ amount: number;
86
+ currency: string;
87
+ } & Record<string, unknown>;
88
+ export interface RefundInput {
89
+ /** Minor units to refund. Omit to refund the whole remaining balance. */
90
+ amount?: number;
91
+ reason?: string;
92
+ /** Default: a fresh key per call. Pass your own to make a retry safe. */
93
+ idempotencyKey?: string;
94
+ }
95
+ /** A Relyon refund, as `POST /v1/payments/{id}/refund` answers it. */
96
+ export type RefundResult = {
97
+ id: string;
98
+ object: "refund";
99
+ payment_id: string;
100
+ amount: number;
101
+ currency: string;
102
+ status: "succeeded";
103
+ } & Record<string, unknown>;
104
+ export interface WebhookInput {
105
+ /** The request body exactly as received, before any JSON parsing. */
106
+ rawBody: string | Uint8Array;
107
+ /** The `Relyon-Signature` header (or the request's headers). */
108
+ signature?: string | null;
109
+ headers?: Headers | Record<string, string | string[] | undefined>;
110
+ /** Default: `webhookSecret` from the options. */
111
+ secret?: string;
112
+ /** Unix seconds, for tests. Default now. */
113
+ nowSeconds?: number;
114
+ }
115
+ /** Thrown when a charge's outcome is unknown (a lost answer or a pending payment): retry with the same input. */
116
+ export declare class PaymentOutcomeUnknown extends Error {
117
+ readonly orderReference: string;
118
+ readonly idempotencyKey: string;
119
+ readonly code = "payment_outcome_unknown";
120
+ constructor(orderReference: string, idempotencyKey: string);
121
+ }
122
+ /** The Idempotency-Key for a charge: from the order reference, so a retry never charges twice. */
123
+ export declare function chargeIdempotencyKey(orderReference: string, attempt?: number): string;
124
+ /**
125
+ * Payments only: card payments in your own app. Create one payment session
126
+ * per checkout page, render the card fields, charge what `tokenize()`
127
+ * resolved to, refund, and verify webhooks. Needs no catalog, feeds, cart
128
+ * page or store hostname.
129
+ */
130
+ export declare class RelyonPayments {
131
+ readonly gateway: RelyonGateway;
132
+ readonly projectSpace: string | undefined;
133
+ private readonly webhookSecret;
134
+ constructor(options?: PaymentsOptions);
135
+ /** Where the checkout page loads the card fields from. */
136
+ get cardFieldsScriptUrl(): string;
137
+ /** True in Live (an explicit Live opt-in with a Live key). */
138
+ get livemode(): boolean;
139
+ /** True when no usable key is configured: every call is refused with `sandbox_key_pending`. */
140
+ get waitingForKey(): boolean;
141
+ /** `POST /v1/payment_sessions`: one single-use session for one checkout page. */
142
+ createSession(input: PaymentSessionInput): Promise<PaymentSession>;
143
+ /** A fresh payment session and the card fields for it, ready to place in the checkout page. */
144
+ cardFields(input: PaymentCardFieldsInput, scriptUrl?: string): Promise<PaymentCardFields>;
145
+ /**
146
+ * `POST /v1/payments`: charges exactly `amount`, with the payment method the
147
+ * card fields' `tokenize()` resolved to (`type: "hosted_card"`). A retry
148
+ * with the same order reference and attempt replays the first result.
149
+ * A pending or lost answer throws `PaymentOutcomeUnknown`: never treat it as
150
+ * "nothing was charged".
151
+ */
152
+ charge(input: ChargeInput): Promise<ChargeResult>;
153
+ /** `POST /v1/payments/{id}/refund`: refunds a succeeded payment, in part (`amount`) or in full. */
154
+ refund(paymentId: string, input?: RefundInput): Promise<RefundResult>;
155
+ /**
156
+ * True when the webhook's signature header (`Relyon-Signature`, or the
157
+ * `X-Relyon-Signature` Relyon's sender uses today) matches the raw body and the
158
+ * endpoint's signing secret, within five minutes. Fails closed: no secret,
159
+ * no header or a reserialized body is false.
160
+ */
161
+ verifyWebhook(input: WebhookInput): boolean;
162
+ }
163
+ /** Creates the payments-only client (layer 1). */
164
+ export declare function createPayments(options?: PaymentsOptions): RelyonPayments;
165
+ export { WEBHOOK_SIGNATURE_HEADER };
@@ -0,0 +1,192 @@
1
+ import { verifyEventSignature } from "./sdk/signatures.js";
2
+ import { PAYMENTS_PATH, PAYMENT_OBJECT, PAYMENT_REFUND_PATH, PAYMENT_SESSIONS_PATH, PAYMENT_SESSION_OBJECT, REFUND_OBJECT, WEBHOOK_SIGNATURE_HEADER, LEGACY_WEBHOOK_SIGNATURE_HEADER, } from "./wire-names.js";
3
+ import { RelyonGateway, RelyonUnavailableError, cardFieldsScriptUrl } from "./relyon.js";
4
+ import { kitEnvironment } from "./kit-environment.js";
5
+ import { escapeHtml, isRecord, randomId, sha256, upperCurrency } from "./util.js";
6
+ // Layer 1, payments only: card payments in the developer's own app, with no
7
+ // Relyon catalog, feeds, cart page or store hostname. One payment session per
8
+ // checkout page, Relyon's hosted card fields in the page, a charge for the
9
+ // amount the shopper saw, refunds, and webhook signature checks.
10
+ /** Relyon's API base URL when none is configured. */
11
+ export const DEFAULT_PAYMENTS_BASE_URL = "https://core.getrelyon.com/api";
12
+ /** Thrown when a charge's outcome is unknown (a lost answer or a pending payment): retry with the same input. */
13
+ export class PaymentOutcomeUnknown extends Error {
14
+ orderReference;
15
+ idempotencyKey;
16
+ code = "payment_outcome_unknown";
17
+ constructor(orderReference, idempotencyKey) {
18
+ super("Relyon's answer to this charge was lost or is still pending. Retry the same charge (same orderReference and attempt): it never charges twice.");
19
+ this.orderReference = orderReference;
20
+ this.idempotencyKey = idempotencyKey;
21
+ }
22
+ }
23
+ function isSession(data) {
24
+ return isRecord(data) && data.object === PAYMENT_SESSION_OBJECT && typeof data.id === "string"
25
+ && typeof data.client_token === "string" && data.client_token.length > 0;
26
+ }
27
+ function isCharge(data) {
28
+ return isRecord(data) && data.object === PAYMENT_OBJECT && typeof data.id === "string" && (data.status === "succeeded" || data.status === "failed");
29
+ }
30
+ function isPendingCharge(data) {
31
+ return isRecord(data) && data.object === PAYMENT_OBJECT && data.status === "pending";
32
+ }
33
+ function isRefund(data) {
34
+ return isRecord(data) && data.object === REFUND_OBJECT && typeof data.id === "string" && typeof data.payment_id === "string";
35
+ }
36
+ /** The Idempotency-Key for a charge: from the order reference, so a retry never charges twice. */
37
+ export function chargeIdempotencyKey(orderReference, attempt = 0) {
38
+ if (!Number.isSafeInteger(attempt) || attempt < 0)
39
+ throw new TypeError("charge's attempt must be a non-negative integer.");
40
+ return `kit-pay-${sha256(attempt === 0 ? orderReference : `${orderReference}#attempt-${attempt}`)}`;
41
+ }
42
+ function positiveAmount(amount, name) {
43
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount <= 0) {
44
+ throw new TypeError(`${name} must be a positive whole number of minor units (cents).`);
45
+ }
46
+ return amount;
47
+ }
48
+ function headerValue(headers, name) {
49
+ if (!headers)
50
+ return undefined;
51
+ if (typeof headers.get === "function")
52
+ return headers.get(name) ?? undefined;
53
+ const wanted = name.toLowerCase();
54
+ for (const [key, value] of Object.entries(headers)) {
55
+ if (key.toLowerCase() === wanted)
56
+ return Array.isArray(value) ? value[0] : value;
57
+ }
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Payments only: card payments in your own app. Create one payment session
62
+ * per checkout page, render the card fields, charge what `tokenize()`
63
+ * resolved to, refund, and verify webhooks. Needs no catalog, feeds, cart
64
+ * page or store hostname.
65
+ */
66
+ export class RelyonPayments {
67
+ gateway;
68
+ projectSpace;
69
+ webhookSecret;
70
+ constructor(options = {}) {
71
+ const env = kitEnvironment(options.env ?? process.env);
72
+ this.projectSpace = options.projectSpace ?? env.projectSpace;
73
+ this.webhookSecret = options.webhookSecret ?? env.webhookSecret;
74
+ this.gateway = new RelyonGateway({
75
+ baseUrl: options.baseUrl ?? env.baseUrl ?? DEFAULT_PAYMENTS_BASE_URL,
76
+ apiKey: options.apiKey ?? env.apiKey,
77
+ live: options.live ?? env.live,
78
+ // Resolved here from options.env, so the gateway never falls back to process.env.
79
+ projectSpace: this.projectSpace ?? "",
80
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
81
+ ...(options.fetch ? { fetch: options.fetch } : {}),
82
+ });
83
+ }
84
+ /** Where the checkout page loads the card fields from. */
85
+ get cardFieldsScriptUrl() { return cardFieldsScriptUrl(this.gateway.baseUrl); }
86
+ /** True in Live (an explicit Live opt-in with a Live key). */
87
+ get livemode() { return this.gateway.livemode; }
88
+ /** True when no usable key is configured: every call is refused with `sandbox_key_pending`. */
89
+ get waitingForKey() { return this.gateway.waitingForSandboxKey; }
90
+ /** `POST /v1/payment_sessions`: one single-use session for one checkout page. */
91
+ async createSession(input) {
92
+ const amount = positiveAmount(input.amount, "amount");
93
+ const { data } = await this.gateway.call((client) => client.POST(PAYMENT_SESSIONS_PATH, {
94
+ params: { header: { "Idempotency-Key": input.idempotencyKey ?? randomId("kit-ps-") } },
95
+ body: {
96
+ amount, currency: upperCurrency(input.currency), order_reference: input.orderReference,
97
+ ...(input.metadata ? { metadata: input.metadata } : {}),
98
+ },
99
+ }), isSession);
100
+ return data;
101
+ }
102
+ /** A fresh payment session and the card fields for it, ready to place in the checkout page. */
103
+ async cardFields(input, scriptUrl) {
104
+ const session = await this.createSession(input);
105
+ const src = scriptUrl ?? cardFieldsScriptUrl(this.gateway.baseUrl);
106
+ const scriptTag = `<script src="${escapeHtml(src)}" async></script>`;
107
+ const attributes = [
108
+ `id="${escapeHtml(input.elementId ?? "relyon-card-fields")}"`,
109
+ `client-token="${escapeHtml(session.client_token)}"`,
110
+ ...(input.fieldStyles ? [`field-styles="${escapeHtml(input.fieldStyles)}"`] : []),
111
+ ];
112
+ const element = `<relyon-card-fields ${attributes.join(" ")}></relyon-card-fields>`;
113
+ return { session, scriptTag, element, html: `${scriptTag}\n${element}` };
114
+ }
115
+ /**
116
+ * `POST /v1/payments`: charges exactly `amount`, with the payment method the
117
+ * card fields' `tokenize()` resolved to (`type: "hosted_card"`). A retry
118
+ * with the same order reference and attempt replays the first result.
119
+ * A pending or lost answer throws `PaymentOutcomeUnknown`: never treat it as
120
+ * "nothing was charged".
121
+ */
122
+ async charge(input) {
123
+ const amount = positiveAmount(input.amount, "amount");
124
+ const method = input.paymentMethod;
125
+ if (!isRecord(method) || typeof method.type !== "string") {
126
+ throw new TypeError('paymentMethod must be exactly what the card fields\' tokenize() resolved to (it has type: "hosted_card").');
127
+ }
128
+ const currency = upperCurrency(input.currency);
129
+ const idempotencyKey = chargeIdempotencyKey(input.orderReference, input.attempt ?? 0);
130
+ const title = (input.description ?? `Order ${input.orderReference}`).slice(0, 500);
131
+ const cart = {
132
+ currency,
133
+ lines: [{ merchant_product_id: "payment", title, quantity: 1, unit_amount: amount, amount }],
134
+ totals: { currency, subtotal: amount, discount: 0, shipping: 0, tax: 0, total: amount },
135
+ };
136
+ const channel = "web";
137
+ let answer;
138
+ try {
139
+ answer = await this.gateway.call((client) => client.POST(PAYMENTS_PATH, {
140
+ params: { header: { "Idempotency-Key": idempotencyKey } },
141
+ body: {
142
+ amount, currency, cart: cart,
143
+ // Passed through as the card fields produced it (the shipped parser reads `type`).
144
+ payment_method: method,
145
+ channel, order_reference: input.orderReference,
146
+ ...(input.customerEmail ? { customer_email: input.customerEmail } : {}),
147
+ ...(input.metadata ? { metadata: input.metadata } : {}),
148
+ },
149
+ }), (data) => isCharge(data) || isPendingCharge(data));
150
+ }
151
+ catch (error) {
152
+ if (error instanceof RelyonUnavailableError && !error.notSent) {
153
+ throw new PaymentOutcomeUnknown(input.orderReference, idempotencyKey);
154
+ }
155
+ throw error;
156
+ }
157
+ if (!isCharge(answer.data))
158
+ throw new PaymentOutcomeUnknown(input.orderReference, idempotencyKey);
159
+ return answer.data;
160
+ }
161
+ /** `POST /v1/payments/{id}/refund`: refunds a succeeded payment, in part (`amount`) or in full. */
162
+ async refund(paymentId, input = {}) {
163
+ if (typeof paymentId !== "string" || !paymentId)
164
+ throw new TypeError("refund needs the payment's ID (pay_…).");
165
+ if (input.amount !== undefined)
166
+ positiveAmount(input.amount, "amount");
167
+ // The SDK's generated client predates this operation; the path and body follow the contract.
168
+ const { data } = await this.gateway.call((client) => client.POST(PAYMENT_REFUND_PATH, {
169
+ params: { path: { id: paymentId }, header: { "Idempotency-Key": input.idempotencyKey ?? randomId("kit-rf-") } },
170
+ body: { ...(input.amount !== undefined ? { amount: input.amount } : {}), ...(input.reason !== undefined ? { reason: input.reason } : {}) },
171
+ }), isRefund);
172
+ return data;
173
+ }
174
+ /**
175
+ * True when the webhook's signature header (`Relyon-Signature`, or the
176
+ * `X-Relyon-Signature` Relyon's sender uses today) matches the raw body and the
177
+ * endpoint's signing secret, within five minutes. Fails closed: no secret,
178
+ * no header or a reserialized body is false.
179
+ */
180
+ verifyWebhook(input) {
181
+ const secret = input.secret ?? this.webhookSecret;
182
+ const signature = input.signature ?? headerValue(input.headers, WEBHOOK_SIGNATURE_HEADER) ?? headerValue(input.headers, LEGACY_WEBHOOK_SIGNATURE_HEADER);
183
+ if (!secret)
184
+ return false;
185
+ return verifyEventSignature({ rawBody: input.rawBody, signature, secret, ...(input.nowSeconds !== undefined ? { nowSeconds: input.nowSeconds } : {}) });
186
+ }
187
+ }
188
+ /** Creates the payments-only client (layer 1). */
189
+ export function createPayments(options = {}) {
190
+ return new RelyonPayments(options);
191
+ }
192
+ export { WEBHOOK_SIGNATURE_HEADER };
@@ -0,0 +1,58 @@
1
+ /** The workspace file pnpm looks for, at or above the project. */
2
+ export declare const PNPM_WORKSPACE_FILE = "pnpm-workspace.yaml";
3
+ /** The server frameworks the kit has adapters for, by package name. */
4
+ export declare const SERVER_FRAMEWORKS: Readonly<Record<string, string>>;
5
+ /** The workspace is too large to scan within init's limits; init then picks no package. */
6
+ export declare class WorkspaceScanLimitError extends Error {
7
+ constructor();
8
+ }
9
+ export interface PnpmWorkspace {
10
+ /** The real path of the directory holding pnpm-workspace.yaml. */
11
+ root: string;
12
+ /** Its `packages` globs; empty when it lists none (a settings-only file); null when init can't read it. */
13
+ patterns: string[] | null;
14
+ /** True when it sets `minimumReleaseAge`, which delays brand-new versions. */
15
+ minimumReleaseAge: boolean;
16
+ }
17
+ export interface WorkspacePackage {
18
+ /** Its real path, inside the workspace root. */
19
+ dir: string;
20
+ /** Relative to the root, with "/" separators. */
21
+ rel: string;
22
+ /** Its package.json name, when it is a valid package name. */
23
+ name: string | null;
24
+ /** The server frameworks it depends on (display names). */
25
+ frameworks: string[];
26
+ /** True when it already depends on @relyon/store-kit. */
27
+ hasKit: boolean;
28
+ }
29
+ /**
30
+ * The `packages` globs of a pnpm-workspace.yaml: the block list and the flow
31
+ * list forms pnpm documents. [] when the file has no `packages` key; null when
32
+ * the key is there in a form init doesn't read.
33
+ */
34
+ export declare function workspacePatterns(text: string): string[] | null;
35
+ /** True when a workspace-relative directory is one of the workspace's packages. */
36
+ export declare function matchesWorkspace(rel: string, patterns: readonly string[]): boolean;
37
+ /**
38
+ * The nearest pnpm-workspace.yaml at or above the project (already a real
39
+ * path). A link, or a file too large or unreadable, reads as `patterns: null`.
40
+ */
41
+ export declare function findPnpmWorkspace(project: string): Promise<PnpmWorkspace | null>;
42
+ /**
43
+ * The workspace's packages under its root, found by walking real directories
44
+ * only (links, node_modules and dot-directories are skipped) a few levels
45
+ * deep. The root itself is never one of them.
46
+ */
47
+ export declare function workspacePackages(root: string, patterns: readonly string[]): Promise<WorkspacePackage[]>;
48
+ /**
49
+ * The one package the kit belongs in: the only one that already depends on
50
+ * the kit, else the only one that runs a supported server framework. null
51
+ * when there is none or more than one (init then names the command instead).
52
+ */
53
+ export declare function serverPackage(packages: readonly WorkspacePackage[]): WorkspacePackage | null;
54
+ /**
55
+ * True when `dir` is a real directory strictly inside `root` with no link on
56
+ * the way: its real path is exactly the path init built.
57
+ */
58
+ export declare function insideRoot(root: string, dir: string): Promise<boolean>;