@volter/twin-stripe 0.1.2 → 2.0.1

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 (229) hide show
  1. package/README.md +96 -27
  2. package/client/dashboard-api.ts +286 -0
  3. package/client/stripe-mirror.css +272 -159
  4. package/client/stripe-mirror.tsx +1384 -541
  5. package/dist/client/dashboard-api.d.ts +107 -0
  6. package/dist/client/dashboard-api.js +238 -0
  7. package/dist/client/dashboard-api.ts +286 -0
  8. package/dist/client/stripe-mirror.bundle.js +236 -0
  9. package/dist/client/stripe-mirror.css +275 -0
  10. package/dist/client/stripe-mirror.d.ts +134 -0
  11. package/dist/client/stripe-mirror.js +823 -0
  12. package/dist/client/stripe-mirror.tsx +1534 -0
  13. package/dist/src/cli.d.ts +2 -0
  14. package/dist/src/cli.js +39 -0
  15. package/dist/src/generated/events.gen.json +1 -0
  16. package/dist/src/generated/surface.gen.json +1 -0
  17. package/dist/src/generated/ui.gen.json +1 -0
  18. package/dist/src/index.d.ts +14 -0
  19. package/dist/src/index.js +75 -0
  20. package/dist/src/manifest.d.ts +2 -0
  21. package/dist/src/manifest.js +1070 -0
  22. package/dist/src/screens/checkout.d.ts +31 -0
  23. package/dist/src/screens/checkout.js +255 -0
  24. package/dist/src/screens/connect-oauth.d.ts +27 -0
  25. package/dist/src/screens/connect-oauth.js +414 -0
  26. package/dist/src/screens/connect-settings.d.ts +22 -0
  27. package/dist/src/screens/connect-settings.js +103 -0
  28. package/dist/src/screens/consent-skin.d.ts +4 -0
  29. package/dist/src/screens/consent-skin.js +18 -0
  30. package/dist/src/screens/financial-connections.d.ts +5 -0
  31. package/dist/src/screens/financial-connections.js +90 -0
  32. package/dist/src/screens/identity.d.ts +5 -0
  33. package/dist/src/screens/identity.js +86 -0
  34. package/dist/src/screens/industries.d.ts +1 -0
  35. package/dist/src/screens/industries.js +267 -0
  36. package/dist/src/screens/onboarding.d.ts +13 -0
  37. package/dist/src/screens/onboarding.js +225 -0
  38. package/dist/src/screens/portal.d.ts +5 -0
  39. package/dist/src/screens/portal.js +216 -0
  40. package/dist/src/screens/public-details.d.ts +5 -0
  41. package/dist/src/screens/public-details.js +90 -0
  42. package/dist/src/semantics/after-payment.d.ts +22 -0
  43. package/dist/src/semantics/after-payment.js +99 -0
  44. package/dist/src/semantics/apps-secrets.d.ts +2 -0
  45. package/dist/src/semantics/apps-secrets.js +54 -0
  46. package/dist/src/semantics/balance.d.ts +11 -0
  47. package/dist/src/semantics/balance.js +195 -0
  48. package/dist/src/semantics/billing.d.ts +2 -0
  49. package/dist/src/semantics/billing.js +220 -0
  50. package/dist/src/semantics/charges.d.ts +28 -0
  51. package/dist/src/semantics/charges.js +209 -0
  52. package/dist/src/semantics/checkout.d.ts +15 -0
  53. package/dist/src/semantics/checkout.js +316 -0
  54. package/dist/src/semantics/connect.d.ts +5 -0
  55. package/dist/src/semantics/connect.js +493 -0
  56. package/dist/src/semantics/coupons.d.ts +6 -0
  57. package/dist/src/semantics/coupons.js +92 -0
  58. package/dist/src/semantics/credit-notes.d.ts +2 -0
  59. package/dist/src/semantics/credit-notes.js +172 -0
  60. package/dist/src/semantics/customers.d.ts +6 -0
  61. package/dist/src/semantics/customers.js +429 -0
  62. package/dist/src/semantics/disputes.d.ts +2 -0
  63. package/dist/src/semantics/disputes.js +51 -0
  64. package/dist/src/semantics/entitlements.d.ts +2 -0
  65. package/dist/src/semantics/entitlements.js +95 -0
  66. package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
  67. package/dist/src/semantics/ephemeral-keys.js +34 -0
  68. package/dist/src/semantics/files.d.ts +2 -0
  69. package/dist/src/semantics/files.js +125 -0
  70. package/dist/src/semantics/invoices.d.ts +18 -0
  71. package/dist/src/semantics/invoices.js +545 -0
  72. package/dist/src/semantics/issuing.d.ts +13 -0
  73. package/dist/src/semantics/issuing.js +575 -0
  74. package/dist/src/semantics/ledger.d.ts +59 -0
  75. package/dist/src/semantics/ledger.js +200 -0
  76. package/dist/src/semantics/payment-intents.d.ts +18 -0
  77. package/dist/src/semantics/payment-intents.js +404 -0
  78. package/dist/src/semantics/payment-links.d.ts +2 -0
  79. package/dist/src/semantics/payment-links.js +133 -0
  80. package/dist/src/semantics/payment-methods.d.ts +20 -0
  81. package/dist/src/semantics/payment-methods.js +140 -0
  82. package/dist/src/semantics/plans.d.ts +5 -0
  83. package/dist/src/semantics/plans.js +121 -0
  84. package/dist/src/semantics/platform.d.ts +9 -0
  85. package/dist/src/semantics/platform.js +206 -0
  86. package/dist/src/semantics/products.d.ts +2 -0
  87. package/dist/src/semantics/products.js +140 -0
  88. package/dist/src/semantics/radar.d.ts +2 -0
  89. package/dist/src/semantics/radar.js +83 -0
  90. package/dist/src/semantics/refunds.d.ts +9 -0
  91. package/dist/src/semantics/refunds.js +195 -0
  92. package/dist/src/semantics/renewals.d.ts +47 -0
  93. package/dist/src/semantics/renewals.js +251 -0
  94. package/dist/src/semantics/setup-intents.d.ts +2 -0
  95. package/dist/src/semantics/setup-intents.js +84 -0
  96. package/dist/src/semantics/shared.d.ts +82 -0
  97. package/dist/src/semantics/shared.js +203 -0
  98. package/dist/src/semantics/subscription-schedules.d.ts +2 -0
  99. package/dist/src/semantics/subscription-schedules.js +119 -0
  100. package/dist/src/semantics/subscriptions.d.ts +11 -0
  101. package/dist/src/semantics/subscriptions.js +605 -0
  102. package/dist/src/semantics/tax.d.ts +2 -0
  103. package/dist/src/semantics/tax.js +197 -0
  104. package/dist/src/semantics/terminal.d.ts +5 -0
  105. package/dist/src/semantics/terminal.js +182 -0
  106. package/dist/src/semantics/test-cards.d.ts +4 -0
  107. package/dist/src/semantics/test-cards.js +7 -0
  108. package/dist/src/semantics/test-clocks.d.ts +6 -0
  109. package/dist/src/semantics/test-clocks.js +73 -0
  110. package/dist/src/semantics/tokens.d.ts +4 -0
  111. package/dist/src/semantics/tokens.js +44 -0
  112. package/dist/src/semantics/transfers.d.ts +2 -0
  113. package/dist/src/semantics/transfers.js +154 -0
  114. package/dist/src/semantics/treasury.d.ts +2 -0
  115. package/dist/src/semantics/treasury.js +377 -0
  116. package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
  117. package/dist/src/semantics/webhook-endpoints.js +85 -0
  118. package/dist/src/stripe-budget.d.ts +55 -0
  119. package/dist/src/stripe-budget.js +155 -0
  120. package/dist/src/stripe-capabilities.d.ts +3 -0
  121. package/dist/src/stripe-capabilities.js +5695 -0
  122. package/dist/src/stripe-conformance.d.ts +43 -0
  123. package/dist/src/stripe-conformance.js +105 -0
  124. package/dist/src/stripe-connector.d.ts +161 -0
  125. package/dist/src/stripe-connector.js +414 -0
  126. package/dist/src/stripe-emit.d.ts +2 -0
  127. package/dist/src/stripe-emit.js +145 -0
  128. package/dist/src/stripe-events.d.ts +93 -0
  129. package/dist/src/stripe-events.js +392 -0
  130. package/dist/src/stripe-js.d.ts +4 -0
  131. package/dist/src/stripe-js.js +70 -0
  132. package/dist/src/stripe-mirror-ui.d.ts +15 -0
  133. package/dist/src/stripe-mirror-ui.js +87 -0
  134. package/dist/src/stripe-params.d.ts +3 -0
  135. package/dist/src/stripe-params.js +43 -0
  136. package/dist/src/stripe-perform-harness.d.ts +9 -0
  137. package/dist/src/stripe-perform-harness.js +26 -0
  138. package/dist/src/stripe-server.d.ts +33 -0
  139. package/dist/src/stripe-server.js +393 -0
  140. package/dist/src/stripe-shared.d.ts +109 -0
  141. package/dist/src/stripe-shared.js +276 -0
  142. package/dist/src/stripe-twin.d.ts +155 -0
  143. package/dist/src/stripe-twin.js +1232 -0
  144. package/dist/src/stripe-ui-conformance.d.ts +5 -0
  145. package/dist/src/stripe-ui-conformance.js +79 -0
  146. package/dist/src/stripe-ui-structure.d.ts +3 -0
  147. package/dist/src/stripe-ui-structure.js +168 -0
  148. package/dist/src/stripe-version.d.ts +12 -0
  149. package/dist/src/stripe-version.js +287 -0
  150. package/dist/test-fixtures/stripe-known-deviations.json +110 -0
  151. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
  152. package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
  153. package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
  154. package/dist/test-fixtures/stripe-schemas.json +3813 -0
  155. package/package.json +18 -10
  156. package/src/cli.ts +7 -7
  157. package/src/generated/events.gen.json +1 -0
  158. package/src/generated/surface.gen.json +1 -0
  159. package/src/generated/ui.gen.json +1 -0
  160. package/src/index.ts +34 -10
  161. package/src/manifest.ts +1102 -0
  162. package/src/screens/checkout.tsx +267 -0
  163. package/src/screens/connect-oauth.tsx +400 -0
  164. package/src/screens/connect-settings.tsx +121 -0
  165. package/src/screens/consent-skin.ts +20 -0
  166. package/src/screens/financial-connections.tsx +101 -0
  167. package/src/screens/identity.tsx +96 -0
  168. package/src/screens/industries.ts +267 -0
  169. package/src/screens/onboarding.tsx +243 -0
  170. package/src/screens/portal.tsx +220 -0
  171. package/src/screens/public-details.tsx +105 -0
  172. package/src/semantics/after-payment.ts +118 -0
  173. package/src/semantics/apps-secrets.ts +58 -0
  174. package/src/semantics/balance.ts +209 -0
  175. package/src/semantics/billing.ts +216 -0
  176. package/src/semantics/charges.ts +220 -0
  177. package/src/semantics/checkout.ts +310 -0
  178. package/src/semantics/connect.ts +487 -0
  179. package/src/semantics/coupons.ts +97 -0
  180. package/src/semantics/credit-notes.ts +168 -0
  181. package/src/semantics/customers.ts +432 -0
  182. package/src/semantics/disputes.ts +62 -0
  183. package/src/semantics/entitlements.ts +94 -0
  184. package/src/semantics/ephemeral-keys.ts +34 -0
  185. package/src/semantics/files.ts +143 -0
  186. package/src/semantics/invoices.ts +545 -0
  187. package/src/semantics/issuing.ts +590 -0
  188. package/src/semantics/ledger.ts +253 -0
  189. package/src/semantics/payment-intents.ts +420 -0
  190. package/src/semantics/payment-links.ts +148 -0
  191. package/src/semantics/payment-methods.ts +145 -0
  192. package/src/semantics/plans.ts +131 -0
  193. package/src/semantics/platform.ts +220 -0
  194. package/src/semantics/products.ts +154 -0
  195. package/src/semantics/radar.ts +85 -0
  196. package/src/semantics/refunds.ts +218 -0
  197. package/src/semantics/renewals.ts +274 -0
  198. package/src/semantics/setup-intents.ts +87 -0
  199. package/src/semantics/shared.ts +226 -0
  200. package/src/semantics/subscription-schedules.ts +129 -0
  201. package/src/semantics/subscriptions.ts +610 -0
  202. package/src/semantics/tax.ts +220 -0
  203. package/src/semantics/terminal.ts +195 -0
  204. package/src/semantics/test-cards.ts +7 -0
  205. package/src/semantics/test-clocks.ts +77 -0
  206. package/src/semantics/tokens.ts +52 -0
  207. package/src/semantics/transfers.ts +174 -0
  208. package/src/semantics/treasury.ts +383 -0
  209. package/src/semantics/webhook-endpoints.ts +87 -0
  210. package/src/stripe-budget.ts +4 -4
  211. package/src/stripe-capabilities.ts +2258 -380
  212. package/src/stripe-conformance.ts +19 -7
  213. package/src/stripe-connector.ts +68 -40
  214. package/src/stripe-emit.ts +15 -8
  215. package/src/stripe-events.ts +102 -40
  216. package/src/stripe-js.ts +70 -0
  217. package/src/stripe-mirror-ui.ts +28 -298
  218. package/src/stripe-params.ts +44 -0
  219. package/src/stripe-perform-harness.ts +29 -0
  220. package/src/stripe-server.ts +318 -38
  221. package/src/stripe-shared.ts +297 -0
  222. package/src/stripe-twin.ts +434 -5325
  223. package/src/stripe-ui-conformance.ts +70 -107
  224. package/src/stripe-ui-structure.ts +124 -348
  225. package/src/stripe-version.ts +281 -0
  226. package/test-fixtures/stripe-known-deviations.json +8 -8
  227. package/test-fixtures/stripe-openapi-operations.json +1188 -2855
  228. package/test-fixtures/stripe-schemas.json +85 -12
  229. package/src/stripe-form.ts +0 -35
@@ -0,0 +1,31 @@
1
+ import { type SemanticsContext } from '@volter/world-core';
2
+ import { type Row } from '../semantics/shared.js';
3
+ export declare const money: (minor: unknown, currency: unknown) => string;
4
+ export declare const COUNTRIES: {
5
+ value: string;
6
+ label: string;
7
+ }[];
8
+ /** The expiry as the customer typed it. Stripe's field formats itself as it is typed: the digits `1230` read `12 / 30`,
9
+ * and a first digit above 1 is a month on its own (`5` reads `05 / `), so a person types the digits straight through
10
+ * (Checkout's own field, seen on checkout.stripe.com; docs.stripe.com/payments/checkout names no format to type). The
11
+ * page's script (@volter/world-ui Payment, `format: 'card-expiry'`) shows it formatted; this reads what is posted either
12
+ * way: `MM / YY`, `MM/YYYY`, or the bare digits `MMYY`, `MYY` (`530`) and `MMYYYY`; a month past 12 is read, and refused
13
+ * as invalid by cardAnswer. */
14
+ export declare function parseExpiry(raw: string): {
15
+ month: number;
16
+ year: number;
17
+ } | undefined;
18
+ /** The card's answer: undefined when it pays, else what Checkout says under the button. */
19
+ export declare function cardAnswer(v: Record<string, string>, nowSeconds: number, chargesNow: boolean): string | undefined;
20
+ /** checkout.stripe.com's pages, or undefined for any other request. */
21
+ /** The name the page shows: the session's own `branding_settings.display_name` where the create set one, else the
22
+ * public business name (stripe-shared.ts, publicBusinessName) of the account whose brand Checkout uses: "Checkout uses
23
+ * the brand settings of the connected account for destination charges with on_behalf_of and for platforms performing
24
+ * direct charges" (a session made with Stripe-Account), and otherwise the platform's; "If you omit a field in
25
+ * branding_settings, Checkout applies the default value from the Dashboard"
26
+ * (docs.stripe.com/payments/checkout/customization/appearance). */
27
+ export declare function merchantOf(ctx: SemanticsContext, stored: Row): string;
28
+ export declare function stripeCheckoutFlow(scope: {
29
+ root?: string;
30
+ clock?: () => string;
31
+ }): (request: Request) => Promise<Response | undefined>;
@@ -0,0 +1,255 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // STRIPE CHECKOUT — a hosted flow (docs/contributing/architecture.md, "Screens"): an application creates a
3
+ // Checkout Session and sends its customer to the session's `url` at checkout.stripe.com/c/pay/{id}; the
4
+ // customer pays there, the session completes (what the payment made is linked on it and
5
+ // checkout.session.completed is delivered), and Checkout redirects to success_url with
6
+ // {CHECKOUT_SESSION_ID} filled in, or the customer goes back to cancel_url
7
+ // (docs.stripe.com/payments/checkout/how-checkout-works). Paying is a move no API call makes: the external
8
+ // actor's move on the session's machine, taken here through the same handler context the API's handlers use.
9
+ // The page is authored from @volter/world-ui's payment piece under Stripe's skin, nothing of Stripe's page
10
+ // copied; its fields carry the ids tests of Checkout fill (email, cardNumber, cardExpiry, cardCvc,
11
+ // billingName, billingCountry, billingPostalCode) and its button the test id Stripe gives it.
12
+ //
13
+ // Where the documentation stops and the twin decides: test cards answer as docs.stripe.com/testing lists
14
+ // (4242… pays; 4000000000000002 declines; …9995 insufficient funds; …0069 expired; …0127 incorrect CVC;
15
+ // …0341 is saved but declines when charged, so it declines on a page that charges now and is saved on one that
16
+ // only sets the card up: setup mode, or a subscription's trial);
17
+ // any other number that passes the Luhn check pays, and a card that asks for authentication pays without
18
+ // the challenge. A subscription session with no customer makes one from the email, as Stripe does.
19
+ import { semanticsContext } from '@volter/world-core';
20
+ import { flowPage, Payment, PAYMENT_CSS } from '@volter/world-ui';
21
+ import surface from '../generated/surface.gen.json' with { type: 'json' };
22
+ import { manifest } from "../manifest.js";
23
+ import { completeSession, isOneTime } from "../semantics/checkout.js";
24
+ import { newCustomer } from "../semantics/customers.js";
25
+ import { created } from "../semantics/shared.js";
26
+ import { publicBusinessName } from "../stripe-shared.js";
27
+ import { applyCouponDiscount, PLATFORM_ACCOUNT_ID, resolveTrial } from "../stripe-twin.js";
28
+ import { formOf } from "./consent-skin.js";
29
+ const CS = 'checkout.session';
30
+ const COMPLETE_OPERATION = surface.operations.find((o) => o.id === 'PostCheckoutSessionsSession');
31
+ const DECLINES = {
32
+ '4000000000000002': 'Your card was declined.',
33
+ '4000000000009995': 'Your card has insufficient funds.',
34
+ '4000000000000069': 'Your card has expired.',
35
+ '4000000000000127': "Your card's security code is incorrect.",
36
+ };
37
+ const luhn = (digits) => {
38
+ let sum = 0;
39
+ for (let i = 0; i < digits.length; i++) {
40
+ let d = Number(digits[digits.length - 1 - i]);
41
+ if (i % 2 === 1) {
42
+ d *= 2;
43
+ if (d > 9)
44
+ d -= 9;
45
+ }
46
+ sum += d;
47
+ }
48
+ return digits.length >= 12 && sum % 10 === 0;
49
+ };
50
+ export const money = (minor, currency) => {
51
+ const c = typeof currency === 'string' ? currency.toUpperCase() : 'USD';
52
+ const zeroDecimal = ['JPY', 'KRW', 'VND', 'CLP', 'ISK', 'UGX', 'XAF', 'XOF'].includes(c);
53
+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: c }).format((Number(minor) || 0) / (zeroDecimal ? 1 : 100));
54
+ };
55
+ // Stripe's skin: its type, its blue submit, the summary on a tinted half.
56
+ const SKIN = `
57
+ body { color: #1a1a1a; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Ubuntu, sans-serif; }
58
+ .pay-summary { background: #f7f7f9; }
59
+ .pay-back, .pay-line small, .pay-total-lead span { color: #6b7280; }
60
+ .pay-field input, .pay-field select { border-color: #e0e0e0; background: #ffffff; }
61
+ .pay-error { color: #df1b41; }
62
+ .pay-submit { background: #0074d4; color: #ffffff; }
63
+ `;
64
+ export const COUNTRIES = [['US', 'United States'], ['GB', 'United Kingdom'], ['CA', 'Canada'], ['DE', 'Germany'], ['FR', 'France'], ['AU', 'Australia'], ['JP', 'Japan']].map(([value, label]) => ({ value: value, label: label }));
65
+ /** A subscription session's trial, when its subscription_data gives one: `trial_period_days`, or `trial_end`
66
+ * (docs.stripe.com/payments/checkout/free-trials), as resolveTrial makes the subscription's at completion. */
67
+ function trialOf(session, now) {
68
+ const data = session._subscription_data;
69
+ return session.mode === 'subscription' && data && typeof data === 'object' ? resolveTrial(data, now) : undefined;
70
+ }
71
+ /** A session line's inline price_data, when it was given one (semantics/checkout.ts keeps them). */
72
+ const inlineOf = (session, i) => session._price_data?.[i];
73
+ const recurringOf = (item) => (item.price && typeof item.price === 'object' ? item.price.recurring ?? undefined : undefined);
74
+ /** How often a price bills, as Checkout says it after the amount: "per month". Where the documentation stops and the twin
75
+ * decides: a price billing every several intervals reads "every 3 months". */
76
+ function cadenceOf(session) {
77
+ const lines = (session.line_items?.data) ?? [];
78
+ const recurring = lines.map((it, i) => recurringOf(it) ?? inlineOf(session, i)?.recurring).find(Boolean);
79
+ const interval = typeof recurring?.interval === 'string' ? recurring.interval : 'month';
80
+ const count = Math.max(1, Math.trunc(Number(recurring?.interval_count ?? 1)) || 1);
81
+ return count === 1 ? `per ${interval}` : `every ${count} ${interval}s`;
82
+ }
83
+ /** What a trial's Checkout says, as checkout.stripe.com shows it for a 14-day trial of a $12.99 monthly price: the lead
84
+ * "14 days free" over "Then $12.99 per month", the button "Start trial", and under it "After your trial ends, you will
85
+ * be charged $12.99 per month starting July 7, 2025. You can always cancel before then." (a live Checkout page's
86
+ * screenshot, github.com/stripe/stripe-react-native/issues/1975; Stripe's docs describe no wording). Where that stops
87
+ * and the twin decides: a one-day trial reads "1 day free", a trial set by `trial_end` counts its days rounded up, and
88
+ * the amount is the session's total, what the first invoice after the trial charges. */
89
+ function trialSummary(session, trial) {
90
+ const days = Math.ceil((trial.end - trial.start) / 86400);
91
+ const then = `${money(afterTrial(session), session.currency)} ${cadenceOf(session)}`;
92
+ const date = new Date(trial.end * 1000).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' });
93
+ return {
94
+ lead: { label: '', amount: `${days} ${days === 1 ? 'day' : 'days'} free`, detail: `Then ${then}` },
95
+ note: `After your trial ends, you will be charged ${then} starting ${date}. You can always cancel before then.`,
96
+ };
97
+ }
98
+ /** What each period after the trial charges, as the subscription's invoices will: its recurring line items (a one-time
99
+ * item is on the first invoice only, semantics/checkout.ts isOneTime), under the session's coupon unless the coupon is `once`, which the trial's own $0
100
+ * invoice takes (semantics/renewals.ts draftSubscriptionInvoice). */
101
+ function afterTrial(session) {
102
+ const items = ((session.line_items?.data) ?? []).filter((it, i) => !isOneTime(it, inlineOf(session, i)));
103
+ const subtotal = items.reduce((sum, it) => sum + (Number(it.amount_subtotal) || 0), 0);
104
+ const coupon = session._coupon;
105
+ return subtotal - (coupon && coupon.duration !== 'once' ? applyCouponDiscount(subtotal, coupon) : 0);
106
+ }
107
+ const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
108
+ /** The email of the session's customer when it has a valid one: "If the Customer already has a valid email set, the email
109
+ * will be prefilled and not editable in Checkout" (docs.stripe.com/api/checkout/sessions/create#create_checkout_session-customer). */
110
+ function customerEmailOf(session) {
111
+ const email = session._customer?.email;
112
+ return typeof email === 'string' && EMAIL.test(email) ? email : undefined;
113
+ }
114
+ function page(session, id, now, values = {}, error) {
115
+ const lines = ((session.line_items?.data) ?? []).map((item) => ({
116
+ name: String(item.description ?? 'Item'),
117
+ amount: money(item.amount_total, item.currency ?? session.currency),
118
+ ...(Number(item.quantity) > 1 ? { detail: `Qty ${String(item.quantity)}` } : {}),
119
+ }));
120
+ const mode = String(session.mode);
121
+ const merchant = String(session._merchant);
122
+ const trial = trialOf(session, now);
123
+ const submit = mode === 'setup' ? 'Save card' : mode === 'subscription' ? (trial ? 'Start trial' : 'Subscribe') : 'Pay';
124
+ const trialText = trial ? trialSummary(session, trial) : undefined;
125
+ const onFile = customerEmailOf(session);
126
+ const contact = onFile
127
+ ? [{ id: 'email', label: 'Email', type: 'email', autoComplete: 'email', value: onFile, readOnly: true }]
128
+ : typeof session.customer_email === 'string'
129
+ ? [{ id: 'email', label: 'Email', type: 'email', autoComplete: 'email', value: session.customer_email }]
130
+ : [{ id: 'email', label: 'Email', type: 'email', autoComplete: 'email', placeholder: 'email@example.com', value: values.email ?? '' }];
131
+ const card = [
132
+ { id: 'cardNumber', label: 'Card number', autoComplete: 'cc-number', placeholder: '1234 1234 1234 1234', value: values.cardNumber ?? '' },
133
+ { id: 'cardExpiry', label: 'Expiration', autoComplete: 'cc-exp', placeholder: 'MM / YY', value: values.cardExpiry ?? '', format: 'card-expiry' },
134
+ { id: 'cardCvc', label: 'CVC', autoComplete: 'cc-csc', placeholder: 'CVC', value: values.cardCvc ?? '' },
135
+ { id: 'billingName', label: 'Cardholder name', autoComplete: 'cc-name', placeholder: 'Full name on card', value: values.billingName ?? '' },
136
+ { id: 'billingCountry', label: 'Country or region', options: COUNTRIES, value: values.billingCountry ?? 'US' },
137
+ { id: 'billingPostalCode', label: 'ZIP', autoComplete: 'postal-code', placeholder: 'ZIP', value: values.billingPostalCode ?? '' },
138
+ ];
139
+ return flowPage({
140
+ title: 'Checkout',
141
+ css: [PAYMENT_CSS, SKIN],
142
+ status: error ? 402 : 200,
143
+ body: (_jsx(Payment, { merchant: merchant, lines: lines, ...(trialText ? { total: trialText.lead, note: trialText.note } : session.amount_total !== null && session.amount_total !== undefined ? { total: { label: mode === 'subscription' ? 'Subscribe' : `Pay ${merchant}`, amount: money(session.amount_total, session.currency) } } : {}), action: `/c/pay/${id}`, sections: [{ heading: 'Contact information', fields: contact }, { heading: 'Payment method', fields: card }], submit: { label: submit, testId: 'hosted-payment-submit-button' }, ...(typeof session.cancel_url === 'string' ? { back: { href: session.cancel_url, label: '← Back' } } : {}), ...(error ? { error } : {}) })),
144
+ });
145
+ }
146
+ const gone = () => flowPage({ title: 'Checkout', status: 404, css: [PAYMENT_CSS, SKIN], body: _jsx("main", { className: "pay-form", children: _jsx("h1", { children: "This Checkout Session is no longer active." }) }) });
147
+ /** Cards that are saved but decline when charged. */
148
+ const DECLINES_WHEN_CHARGED = { '4000000000000341': 'Your card was declined.' };
149
+ /** The expiry as the customer typed it. Stripe's field formats itself as it is typed: the digits `1230` read `12 / 30`,
150
+ * and a first digit above 1 is a month on its own (`5` reads `05 / `), so a person types the digits straight through
151
+ * (Checkout's own field, seen on checkout.stripe.com; docs.stripe.com/payments/checkout names no format to type). The
152
+ * page's script (@volter/world-ui Payment, `format: 'card-expiry'`) shows it formatted; this reads what is posted either
153
+ * way: `MM / YY`, `MM/YYYY`, or the bare digits `MMYY`, `MYY` (`530`) and `MMYYYY`; a month past 12 is read, and refused
154
+ * as invalid by cardAnswer. */
155
+ export function parseExpiry(raw) {
156
+ const split = /^\s*(\d{1,2})\s*\/\s*(\d{2}|\d{4})\s*$/.exec(raw);
157
+ const digits = raw.replace(/\s/g, '');
158
+ const bare = split ? undefined : /^(\d{2})(\d{2}|\d{4})$/.exec(digits) ?? /^([2-9])(\d{2})$/.exec(digits);
159
+ const m = split ?? bare;
160
+ if (!m)
161
+ return undefined;
162
+ return { month: Number(m[1]), year: m[2].length === 2 ? 2000 + Number(m[2]) : Number(m[2]) };
163
+ }
164
+ /** The card's answer: undefined when it pays, else what Checkout says under the button. */
165
+ export function cardAnswer(v, nowSeconds, chargesNow) {
166
+ const digits = (v.cardNumber ?? '').replace(/\D/g, '');
167
+ if (!digits)
168
+ return 'Your card number is incomplete.';
169
+ if (DECLINES[digits])
170
+ return DECLINES[digits];
171
+ if (chargesNow && DECLINES_WHEN_CHARGED[digits])
172
+ return DECLINES_WHEN_CHARGED[digits];
173
+ if (!luhn(digits))
174
+ return 'Your card number is invalid.';
175
+ const exp = parseExpiry(v.cardExpiry ?? '');
176
+ if (!exp)
177
+ return "Your card's expiration date is incomplete.";
178
+ const { month, year } = exp;
179
+ if (month < 1 || month > 12)
180
+ return "Your card's expiration date is invalid.";
181
+ const now = new Date(nowSeconds * 1000);
182
+ if (year < now.getUTCFullYear() || (year === now.getUTCFullYear() && month < now.getUTCMonth() + 1))
183
+ return "Your card's expiration year is in the past.";
184
+ if (!/^\d{3,4}$/.test(v.cardCvc ?? ''))
185
+ return "Your card's security code is incomplete.";
186
+ return undefined;
187
+ }
188
+ async function pay(ctx, id, session, v) {
189
+ const onFile = customerEmailOf(session);
190
+ const email = onFile ?? (typeof session.customer_email === 'string' ? session.customer_email : (v.email ?? '').trim());
191
+ if (session.mode !== 'setup' || !session.customer) {
192
+ if (!EMAIL.test(email))
193
+ return page(session, id, Number(ctx.now()), v, 'Your email address is incomplete.');
194
+ }
195
+ // a trial charges nothing now unless a one-time price is on the first invoice
196
+ const oneTimeDue = ((session.line_items?.data) ?? []).some((it, i) => isOneTime(it, inlineOf(session, i)));
197
+ const chargesNow = session.mode === 'payment' || (session.mode === 'subscription' && (!trialOf(session, Number(ctx.now())) || oneTimeDue));
198
+ const refused = cardAnswer(v, Number(ctx.now()), chargesNow);
199
+ if (refused)
200
+ return page(session, id, Number(ctx.now()), v, refused);
201
+ let existing = session;
202
+ // Checkout always makes a customer for a subscription; a payment makes one only when the session asks
203
+ if (!session.customer && (session.mode === 'subscription' || session.customer_creation === 'always')) {
204
+ const cid = ctx.mint('customer');
205
+ const customer = await created(ctx, 'customer', { id: cid, email, ...(v.billingName ? { name: v.billingName } : {}) }, { livemode: false, ...newCustomer(cid) });
206
+ existing = { ...session, customer: customer.id };
207
+ }
208
+ // "If the Customer does not have a valid email, Checkout will set the email entered during the session on the Customer" (the same page)
209
+ if (typeof session.customer === 'string' && !onFile && EMAIL.test(email))
210
+ await ctx.write('customer', session.customer, { email }, 'customer.update');
211
+ const details = {
212
+ customer_details: { email, name: v.billingName || null, address: { country: v.billingCountry || null, postal_code: v.billingPostalCode || null, city: null, line1: null, line2: null, state: null }, phone: null, tax_exempt: 'none', tax_ids: [] },
213
+ ...(existing.customer !== session.customer ? { customer: existing.customer } : {}),
214
+ };
215
+ const exp = parseExpiry(v.cardExpiry ?? '');
216
+ const done = await completeSession(ctx, id, existing, details, { number: (v.cardNumber ?? '').replace(/\D/g, ''), exp_month: exp.month, exp_year: exp.year });
217
+ if (done instanceof Response)
218
+ return gone();
219
+ const to = String(session.success_url).replaceAll('{CHECKOUT_SESSION_ID}', id);
220
+ return new Response(null, { status: 303, headers: { location: to } });
221
+ }
222
+ /** checkout.stripe.com's pages, or undefined for any other request. */
223
+ /** The name the page shows: the session's own `branding_settings.display_name` where the create set one, else the
224
+ * public business name (stripe-shared.ts, publicBusinessName) of the account whose brand Checkout uses: "Checkout uses
225
+ * the brand settings of the connected account for destination charges with on_behalf_of and for platforms performing
226
+ * direct charges" (a session made with Stripe-Account), and otherwise the platform's; "If you omit a field in
227
+ * branding_settings, Checkout applies the default value from the Dashboard"
228
+ * (docs.stripe.com/payments/checkout/customization/appearance). */
229
+ export function merchantOf(ctx, stored) {
230
+ const brand = stored._branding_settings?.display_name;
231
+ const behalf = stored._payment_intent_data?.on_behalf_of ?? stored._subscription_data?.on_behalf_of;
232
+ const account = typeof behalf === 'string' ? behalf : typeof stored._brand_account === 'string' ? stored._brand_account : PLATFORM_ACCOUNT_ID;
233
+ return typeof brand === 'string' && brand.trim() ? brand : publicBusinessName(ctx.get('account', account));
234
+ }
235
+ export function stripeCheckoutFlow(scope) {
236
+ return async (request) => {
237
+ const m = /^\/c\/pay\/(cs_[A-Za-z0-9_]+)\/?$/.exec(new URL(request.url).pathname);
238
+ if (!m || (request.method !== 'GET' && request.method !== 'POST'))
239
+ return undefined;
240
+ const id = m[1];
241
+ // the form is read before the context, which reads the request's body itself
242
+ const values = request.method === 'POST' ? await formOf(request.clone()) : {};
243
+ const ctx = await semanticsContext(manifest, request, COMPLETE_OPERATION, scope);
244
+ const session = ctx.get(CS, id);
245
+ if (!session)
246
+ return gone();
247
+ // an ended session's page is gone; paying on one is the customer's move the machine refuses
248
+ if (session.status !== 'open' && (request.method === 'GET' || ctx.legal(CS, 'status', COMPLETE_OPERATION.id, String(session.status), 'complete', id, 'external')))
249
+ return gone();
250
+ const stored = ctx.row(CS, id) ?? {};
251
+ const coupon = stored._discount?.coupon;
252
+ const full = { ...session, _subscription_data: stored._subscription_data, _price_data: stored._price_data, _merchant: merchantOf(ctx, stored), _coupon: typeof coupon === 'string' ? ctx.get('coupon', coupon) : undefined, _customer: typeof session.customer === 'string' ? ctx.get('customer', session.customer) : undefined };
253
+ return request.method === 'GET' ? page(full, id, Number(ctx.now())) : pay(ctx, id, full, values);
254
+ };
255
+ }
@@ -0,0 +1,27 @@
1
+ import { type SemanticsContext } from '@volter/world-core';
2
+ /** A code "expires in 5 minutes". */
3
+ export declare const CODE_TTL_SECONDS = 300;
4
+ /** One connection per connected account (the twin's one platform): its scope, tokens, and whether it was revoked. */
5
+ export declare const CONNECTIONS = "_oauth_connection";
6
+ type Scoped = {
7
+ root?: string;
8
+ clock?: () => string;
9
+ };
10
+ /** Whether a connected account's OAuth connection to the platform was revoked (deauthorized, or its code reused). */
11
+ export declare function connectionRevoked(ctx: SemanticsContext, account: string): boolean;
12
+ /** The connected account an OAuth key acts as — the connection's current access_token (sk_test_oauth_…) or its
13
+ * stripe_publishable_key (pk_test_oauth_…) — with the scope it was issued; undefined for any other key, and null for an
14
+ * OAuth-shaped key no live connection holds (revoked, replaced by a refresh, or never issued). */
15
+ export declare function oauthKeyAccount(ctx: SemanticsContext, key: string): {
16
+ account: string;
17
+ scope: string;
18
+ } | null | undefined;
19
+ /** The prefill the request carries, invalid values silently dropped (docs.stripe.com/connect/oauth-reference). Only
20
+ * what the new account's object shows the platform, or the page shows the person, is read: the person's birth date and
21
+ * the business address are the account application's, which the twin does not model (the test-mode skip). */
22
+ export declare function prefill(q: URLSearchParams): Record<string, string>;
23
+ /** A key shown the way Stripe's errors show one: its prefix and its last four. */
24
+ export declare const redactKey: (key: string) => string;
25
+ /** connect.stripe.com's OAuth endpoints, or undefined for any other request. */
26
+ export declare function stripeConnectOAuthFlow(scope: Scoped): (request: Request) => Promise<Response | undefined>;
27
+ export {};