@aglyn/plugins-commerce 1.14.0 → 1.15.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 (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-account.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { memberNameSearchFields, memberSearchTokens } from './member-name-search'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { mintDownloadToken } from './download'\nimport { requireActiveMember } from './membership'\n\nexport interface AccountOrderView {\n id: string\n number: string\n status: CommerceModel.OrderStatus\n totalCents: number\n createdAtMs: number\n itemsSummary: string\n tracking?: { carrier?: string; trackingNumber?: string }\n}\n\n/**\n * Member account (AGL-294): profile + address book + order history for\n * the signed-in site member (AGL-109 session cookie). Orders match by\n * the member's email — guest purchases made with the same address show\n * up too, which is what buyers expect.\n */\nexport const membershipAccountHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(\n (req.method === 'GET' ? req.query.hostId : req.body?.hostId) ?? '',\n )\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-546/550): the shared guard 401s stale\n // sessions and 403s suspended members with the cookie cleared, so\n // the site stops presenting a signed-in shell; the account block\n // treats any non-OK response as signed-out, the graceful path here.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const { memberId, member: memberSnapshot } = auth\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const memberRef = hostRef.collection('siteMembers').doc(memberId)\n\n if (req.method === 'POST') {\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const addresses = Array.isArray(req.body?.addresses)\n ? (req.body.addresses as CommerceModel.OrderAddress[]).slice(0, 5).map(\n (address) => ({\n name: String(address.name ?? '').slice(0, 80),\n line1: String(address.line1 ?? '').slice(0, 120),\n line2: String(address.line2 ?? '').slice(0, 120),\n city: String(address.city ?? '').slice(0, 80),\n state: String(address.state ?? '').slice(0, 40),\n postalCode: String(address.postalCode ?? '').slice(0, 20),\n country: String(address.country ?? '').slice(0, 2).toUpperCase(),\n }),\n )\n : undefined\n await memberRef.set(\n {\n ...(displayName\n ? {\n ...memberNameSearchFields(displayName),\n // The Site users list's search reads the new name beside\n // the address the member signed up with (AGL-3321).\n searchTokens: memberSearchTokens(\n displayName,\n String(memberSnapshot.get('email') ?? ''),\n ),\n }\n : {}),\n ...(addresses ? { addresses } : {}),\n },\n { merge: true },\n )\n }\n\n const email = String(memberSnapshot.get('email') ?? '')\n const ordersSnapshot = await hostRef\n .collection('orders')\n .where('customerEmail', '==', email)\n .limit(25)\n .get()\n const orders: AccountOrderView[] = ordersSnapshot.docs\n .map((docSnapshot) => {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n const latestFulfillment = (order.fulfillments ?? []).slice(-1)[0]\n return {\n id: docSnapshot.id,\n number: CommerceModel.formatOrderNumber(order, docSnapshot.id),\n status: order.status,\n totalCents:\n order.totals?.totalCents ?? Number(order.amountCents ?? 0),\n createdAtMs:\n order.createdAtMs ??\n ((docSnapshot.get('createdAt')?.seconds ?? 0) * 1000 || 0),\n itemsSummary: (order.lineItems ?? [])\n .map((line) => `${line.quantity}× ${line.name}`)\n .join(', ')\n .slice(0, 140),\n ...(latestFulfillment?.trackingNumber\n ? {\n tracking: {\n carrier: latestFulfillment.carrier,\n trackingNumber: latestFulfillment.trackingNumber,\n },\n }\n : {}),\n }\n })\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n\n // Digital downloads (AGL-302): tokened links for digital lines on\n // paid orders; files resolve to the product's current list.\n const downloads: Array<{\n orderId: string\n productId: string\n productName: string\n url: string\n licenseKeys?: string[]\n }> = []\n for (const docSnapshot of ordersSnapshot.docs) {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n if (!CommerceModel.orderEntitlesProduct(order, 'any')) continue\n const orderKeys = (docSnapshot.get('licenseKeys') ?? {}) as Record<\n string,\n string[]\n >\n for (const line of order.lineItems ?? []) {\n if (line.productType !== 'digital') continue\n // PER LINE (AGL-2454). The status test above only ever moved on a FULL\n // refund, so this page went on listing the download link AND the\n // licence key for a line the merchant had refunded. The key string is\n // the one thing here that cannot be taken back once mailed — which is\n // exactly why it is retired from the pool rather than reissued — so\n // removing it from the account page is the only withdrawal available.\n if (!CommerceModel.orderEntitlesProduct(order, line.productId)) continue\n downloads.push({\n orderId: docSnapshot.id,\n productId: line.productId,\n productName: line.name,\n ...(orderKeys[line.productId]?.length\n ? { licenseKeys: orderKeys[line.productId] }\n : {}),\n url:\n `/api/commerce/download?hostId=${encodeURIComponent(hostId)}` +\n `&orderId=${encodeURIComponent(docSnapshot.id)}` +\n `&productId=${encodeURIComponent(line.productId)}` +\n `&token=${mintDownloadToken(hostId, docSnapshot.id)}`,\n })\n }\n }\n\n // Storefront subscriptions (AGL-303) with product names resolved.\n const subscriptionsSnapshot = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(10)\n .get()\n const subscriptions = await Promise.all(\n subscriptionsSnapshot.docs.map(async (docSnapshot) => {\n const productSnapshot = await hostRef\n .collection('products')\n .doc(String(docSnapshot.get('productId') ?? ''))\n .get()\n return {\n id: docSnapshot.id,\n productName: String(productSnapshot.get('name') ?? 'Subscription'),\n status: String(docSnapshot.get('status') ?? 'active'),\n currentPeriodEndMs: docSnapshot.get('currentPeriodEndMs') ?? null,\n }\n }),\n )\n\n return res.status(200).json({\n member: {\n email,\n displayName: memberSnapshot.get('displayName') ?? '',\n addresses: memberSnapshot.get('addresses') ?? [],\n },\n orders,\n downloads,\n subscriptions,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Account unavailable' })\n }\n}\n"],"names":["memberNameSearchFields","memberSearchTokens","CommerceModel","firebaseAdmin","mintDownloadToken","requireActiveMember","membershipAccountHandler","req","res","hostId","String","method","query","body","status","json","error","memberSnapshot","auth","memberId","member","firestore","app","hostRef","collection","doc","memberRef","displayName","slice","addresses","Array","isArray","map","address","name","line1","line2","city","state","postalCode","country","toUpperCase","undefined","set","searchTokens","get","merge","email","ordersSnapshot","where","limit","orders","docs","docSnapshot","order","liftLegacyOrder","data","latestFulfillment","fulfillments","id","number","formatOrderNumber","totalCents","totals","Number","amountCents","createdAtMs","seconds","itemsSummary","lineItems","line","quantity","join","trackingNumber","tracking","carrier","sort","a","b","downloads","orderEntitlesProduct","orderKeys","productType","productId","push","orderId","productName","length","licenseKeys","url","encodeURIComponent","subscriptionsSnapshot","subscriptions","Promise","all","productSnapshot","currentPeriodEndMs","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,EAAEC,kBAAkB,QAAQ,0BAAsB;AAEjF,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,iBAAiB,QAAQ,gBAAY;AAC9C,SAASC,mBAAmB,QAAQ,kBAAc;AAYlD;;;;;CAKC,GACD,OAAO,MAAMC,2BAA6C,OAAOC,KAAKC;QAEjED;QAA0CA;IAD7C,MAAME,SAASC,QACZH,OAAAA,IAAII,MAAM,KAAK,QAAQJ,IAAIK,KAAK,CAACH,MAAM,IAAGF,YAAAA,IAAIM,IAAI,qBAARN,UAAUE,MAAM,YAA1DF,OAA+D;IAElE,IAAI,CAACE,QAAQ,OAAOD,IAAIM,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAE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ACN2B;gBACApB,WAAW,GAAEV,uBAAAA,eAAe4B,GAAG,CAAC,0BAAnB5B,uBAAqC;gBAClDY,SAAS,GAAEZ,uBAAAA,eAAe4B,GAAG,CAAC,wBAAnB5B,uBAAmC,EAAE;YAClD;YACAkC;YACA4B;YACAa;QACF;IACF,EAAE,OAAO5E,OAAO;QACdiF,QAAQjF,KAAK,CAACA;QACd,OAAOR,IAAIM,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-account.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { memberNameSearchFields, memberSearchTokens } from './member-name-search'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { mintDownloadToken } from './download'\nimport { requireActiveMember } from './membership'\n\nexport interface AccountOrderView {\n id: string\n number: string\n status: CommerceModel.OrderStatus\n totalCents: number\n createdAtMs: number\n itemsSummary: string\n tracking?: { carrier?: string; trackingNumber?: string }\n}\n\n/** How many of each subscription's invoices the account page lists. */\nexport const ACCOUNT_INVOICE_WINDOW = 12\n\nexport interface AccountSubscriptionView {\n id: string\n productName: string\n status: string\n currentPeriodEndMs: number | null\n paidThroughMs?: number\n cancelAtPeriodEnd?: true\n /** What each cycle charges, tax included: what the subscriber pays. */\n priceCents?: number\n interval?: CommerceModel.SubscriptionBillingInterval\n invoices: Array<{\n id: string\n paidAtMs: number\n paidCents: number\n currency: string\n number?: string\n /** Stripe's hosted invoice, which carries the receipt download. */\n url?: string\n }>\n}\n\n/**\n * Member account (AGL-294): profile + address book + order history for\n * the signed-in site member (AGL-109 session cookie). Orders match by\n * the member's email — guest purchases made with the same address show\n * up too, which is what buyers expect.\n */\nexport const membershipAccountHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(\n (req.method === 'GET' ? req.query.hostId : req.body?.hostId) ?? '',\n )\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-546/550): the shared guard 401s stale\n // sessions and 403s suspended members with the cookie cleared, so\n // the site stops presenting a signed-in shell; the account block\n // treats any non-OK response as signed-out, the graceful path here.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const { memberId, member: memberSnapshot } = auth\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const memberRef = hostRef.collection('siteMembers').doc(memberId)\n\n if (req.method === 'POST') {\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const addresses = Array.isArray(req.body?.addresses)\n ? (req.body.addresses as CommerceModel.OrderAddress[]).slice(0, 5).map(\n (address) => ({\n name: String(address.name ?? '').slice(0, 80),\n line1: String(address.line1 ?? '').slice(0, 120),\n line2: String(address.line2 ?? '').slice(0, 120),\n city: String(address.city ?? '').slice(0, 80),\n state: String(address.state ?? '').slice(0, 40),\n postalCode: String(address.postalCode ?? '').slice(0, 20),\n country: String(address.country ?? '').slice(0, 2).toUpperCase(),\n }),\n )\n : undefined\n await memberRef.set(\n {\n ...(displayName\n ? {\n ...memberNameSearchFields(displayName),\n // The Site users list's search reads the new name beside\n // the address the member signed up with (AGL-3321).\n searchTokens: memberSearchTokens(\n displayName,\n String(memberSnapshot.get('email') ?? ''),\n ),\n }\n : {}),\n ...(addresses ? { addresses } : {}),\n },\n { merge: true },\n )\n }\n\n const email = String(memberSnapshot.get('email') ?? '')\n const ordersSnapshot = await hostRef\n .collection('orders')\n .where('customerEmail', '==', email)\n .limit(25)\n .get()\n const orders: AccountOrderView[] = ordersSnapshot.docs\n .map((docSnapshot) => {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n const latestFulfillment = (order.fulfillments ?? []).slice(-1)[0]\n return {\n id: docSnapshot.id,\n number: CommerceModel.formatOrderNumber(order, docSnapshot.id),\n status: order.status,\n totalCents:\n order.totals?.totalCents ?? Number(order.amountCents ?? 0),\n createdAtMs:\n order.createdAtMs ??\n ((docSnapshot.get('createdAt')?.seconds ?? 0) * 1000 || 0),\n itemsSummary: (order.lineItems ?? [])\n .map((line) => `${line.quantity}× ${line.name}`)\n .join(', ')\n .slice(0, 140),\n ...(latestFulfillment?.trackingNumber\n ? {\n tracking: {\n carrier: latestFulfillment.carrier,\n trackingNumber: latestFulfillment.trackingNumber,\n },\n }\n : {}),\n }\n })\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n\n // Digital downloads (AGL-302): tokened links for digital lines on\n // paid orders; files resolve to the product's current list.\n const downloads: Array<{\n orderId: string\n productId: string\n productName: string\n url: string\n licenseKeys?: string[]\n }> = []\n for (const docSnapshot of ordersSnapshot.docs) {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n if (!CommerceModel.orderEntitlesProduct(order, 'any')) continue\n const orderKeys = (docSnapshot.get('licenseKeys') ?? {}) as Record<\n string,\n string[]\n >\n for (const line of order.lineItems ?? []) {\n if (line.productType !== 'digital') continue\n // PER LINE (AGL-2454). The status test above only ever moved on a FULL\n // refund, so this page went on listing the download link AND the\n // licence key for a line the merchant had refunded. The key string is\n // the one thing here that cannot be taken back once mailed — which is\n // exactly why it is retired from the pool rather than reissued — so\n // removing it from the account page is the only withdrawal available.\n if (!CommerceModel.orderEntitlesProduct(order, line.productId)) continue\n downloads.push({\n orderId: docSnapshot.id,\n productId: line.productId,\n productName: line.name,\n ...(orderKeys[line.productId]?.length\n ? { licenseKeys: orderKeys[line.productId] }\n : {}),\n url:\n `/api/commerce/download?hostId=${encodeURIComponent(hostId)}` +\n `&orderId=${encodeURIComponent(docSnapshot.id)}` +\n `&productId=${encodeURIComponent(line.productId)}` +\n `&token=${mintDownloadToken(hostId, docSnapshot.id)}`,\n })\n }\n }\n\n // Storefront subscriptions (AGL-303) with product names resolved, and\n // what the subscriber needs to plan around (AGL-4191): the price, the one\n // date that matters next, and their recent invoices with Stripe's own\n // receipt link.\n const subscriptionsSnapshot = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(10)\n .get()\n const subscriptions: AccountSubscriptionView[] = await Promise.all(\n subscriptionsSnapshot.docs.map(async (docSnapshot) => {\n const soldLine = (docSnapshot.get('lineItems') ?? [])[0] as\n | { name?: string }\n | undefined\n const [productSnapshot, invoicesSnapshot] = await Promise.all([\n soldLine?.name\n ? null\n : hostRef\n .collection('products')\n .doc(String(docSnapshot.get('productId') ?? '') || 'missing')\n .get()\n .catch(() => null),\n // The billing history is extra: a failed read leaves it empty\n // rather than taking the whole account page down with it.\n (async () => {\n try {\n return await hostRef\n .collection('subscriptions')\n .doc(docSnapshot.id)\n .collection('invoices')\n .orderBy('paidAtMs', 'desc')\n .limit(ACCOUNT_INVOICE_WINDOW)\n .get()\n } catch {\n return null\n }\n })(),\n ])\n const totalCents = docSnapshot.get('totals.totalCents')\n const interval = CommerceModel.subscriptionInterval(\n docSnapshot.get('interval'),\n )\n return {\n id: docSnapshot.id,\n productName: String(\n soldLine?.name ?? productSnapshot?.get('name') ?? 'Subscription',\n ),\n status: String(docSnapshot.get('status') ?? 'active'),\n currentPeriodEndMs: docSnapshot.get('currentPeriodEndMs') ?? null,\n ...(docSnapshot.get('paidThroughMs')\n ? { paidThroughMs: Number(docSnapshot.get('paidThroughMs')) }\n : {}),\n ...(docSnapshot.get('cancelAtPeriodEnd') === true\n ? { cancelAtPeriodEnd: true }\n : {}),\n ...(typeof totalCents === 'number' ? { priceCents: totalCents } : {}),\n ...(interval ? { interval } : {}),\n invoices: (invoicesSnapshot?.docs ?? [])\n // A trial's opening $0 invoice is a record, not a payment.\n .filter((invoice) => Number(invoice.get('paidCents') ?? 0) > 0)\n .map((invoice) => ({\n id: invoice.id,\n paidAtMs: Number(invoice.get('paidAtMs') ?? 0),\n paidCents: Number(invoice.get('paidCents') ?? 0),\n currency: String(invoice.get('currency') ?? 'usd'),\n ...(invoice.get('number')\n ? { number: String(invoice.get('number')) }\n : {}),\n ...(invoice.get('hostedInvoiceUrl')\n ? { url: String(invoice.get('hostedInvoiceUrl')) }\n : {}),\n })),\n }\n }),\n )\n\n return res.status(200).json({\n member: {\n email,\n displayName: memberSnapshot.get('displayName') ?? '',\n addresses: memberSnapshot.get('addresses') ?? [],\n },\n orders,\n downloads,\n subscriptions,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Account unavailable' })\n }\n}\n"],"names":["memberNameSearchFields","memberSearchTokens","CommerceModel","firebaseAdmin","mintDownloadToken","requireActiveMember","ACCOUNT_INVOICE_WINDOW","membershipAccountHandler","req","res","hostId","String","method","query","body","status","json","error","memberSnapshot","auth","memberId","member","firestore","app","hostRef","collection","doc","memberRef","displayName","slice","addresses","Array","isArray","map","address","name","line1","line2","city","state","postalCode","country","toUpperCase","undefined","set","searchTokens","get","merge","email","ordersSnapshot","where","limit","orders","docs","docSnapshot","order","liftLegacyOrder","data","latestFulfillment","fulfillments","id","number","formatOrderNumber","totalCents","totals","Number","amountCents","createdAtMs","seconds","itemsSummary","lineItems","line","quantity","join","trackingNumber","tracking","carrier","sort","a","b","downloads","orderEntitlesProduct","orderKeys","productType","productId","push","orderId","productName","length","licenseKeys","url","encodeURIComponent","subscriptionsSnapshot","subscriptions","Promise","all","soldLine","productSnapshot","invoicesSnapshot","catch","orderBy","interval","subscriptionInterval","currentPeriodEndMs","paidThroughMs","cancelAtPeriodEnd","priceCents","invoices","filter","invoice","paidAtMs","paidCents","currency","console"],"mappings":"AAAA;;;;;;;;;;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AOR,IAAIM,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
@@ -151,8 +151,8 @@ export declare function resolveNativeCheckoutMode(orgId: string | null | undefin
151
151
  * `return_url`: Stripe rejects the pair outright on a `ui_mode` session, and a
152
152
  * 400 here would surface to the shopper as "Checkout failed" on a store that
153
153
  * was working an hour ago. Everything else in the param set — line items, the
154
- * tax line, `automatic_tax`, shipping options, the Connect destination, the
155
- * application fee, every `metadata[…]` key the webhook reads — is left exactly
154
+ * tax line, `automatic_tax`, shipping options, the Connect destination (or the
155
+ * `Stripe-Account` header a direct charge's caller sends), the application fee, every `metadata[…]` key the webhook reads — is left exactly
156
156
  * as the caller built it. That is the point: this function must be incapable of
157
157
  * changing what the shopper is charged.
158
158
  *
@@ -181,6 +181,13 @@ export interface NativeCheckoutPayload {
181
181
  * defaults answers exactly what it answered before.
182
182
  */
183
183
  wallets?: StorefrontCheckoutWallets;
184
+ /**
185
+ * The seller's connected account, present only for a DIRECT charge: the
186
+ * session was created on that account, so Stripe.js must be booted with
187
+ * `stripeAccount` or the client secret does not resolve. Absent for a
188
+ * destination sale, whose session lives on the platform account.
189
+ */
190
+ stripeAccount?: string;
184
191
  }
185
192
  export interface HostedCheckoutPayload {
186
193
  url: string;
@@ -201,4 +208,4 @@ export declare function readCheckoutSessionPayload(session: {
201
208
  url?: string;
202
209
  id?: string;
203
210
  client_secret?: string;
204
- }, mode: NativeCheckoutMode, wallets?: StorefrontCheckoutWallets): NativeCheckoutPayload | HostedCheckoutPayload | null;
211
+ }, mode: NativeCheckoutMode, wallets?: StorefrontCheckoutWallets, stripeAccount?: string): NativeCheckoutPayload | HostedCheckoutPayload | null;
@@ -171,8 +171,8 @@ import { storefrontWalletsHideAny } from "../model/commerce-payment-methods.js";
171
171
  * `return_url`: Stripe rejects the pair outright on a `ui_mode` session, and a
172
172
  * 400 here would surface to the shopper as "Checkout failed" on a store that
173
173
  * was working an hour ago. Everything else in the param set — line items, the
174
- * tax line, `automatic_tax`, shipping options, the Connect destination, the
175
- * application fee, every `metadata[…]` key the webhook reads — is left exactly
174
+ * tax line, `automatic_tax`, shipping options, the Connect destination (or the
175
+ * `Stripe-Account` header a direct charge's caller sends), the application fee, every `metadata[…]` key the webhook reads — is left exactly
176
176
  * as the caller built it. That is the point: this function must be incapable of
177
177
  * changing what the shopper is charged.
178
178
  *
@@ -212,17 +212,22 @@ import { storefrontWalletsHideAny } from "../model/commerce-payment-methods.js";
212
212
  * made every successful session look like a Stripe failure — a 502 to the
213
213
  * shopper, a released claim, and a real Checkout Session left open on the
214
214
  * account. So the check has to move with the mode, and it does.
215
- */ export function readCheckoutSessionPayload(session, mode, wallets) {
215
+ */ export function readCheckoutSessionPayload(session, mode, wallets, stripeAccount) {
216
+ // The hosted page needs nothing more: Stripe's own URL already knows which
217
+ // account the session is on.
216
218
  if (!mode.native) return (session == null ? void 0 : session.url) ? {
217
219
  url: session.url
218
220
  } : null;
219
221
  if (!(session == null ? void 0 : session.client_secret) || !(session == null ? void 0 : session.id)) return null;
222
+ const account = String(stripeAccount != null ? stripeAccount : '').trim();
220
223
  return _extends({
221
224
  clientSecret: String(session.client_secret),
222
225
  publishableKey: mode.publishableKey,
223
226
  sessionId: String(session.id)
224
227
  }, wallets && storefrontWalletsHideAny(wallets) ? {
225
228
  wallets
229
+ } : {}, account ? {
230
+ stripeAccount: account
226
231
  } : {});
227
232
  }
228
233
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/native-checkout.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin'\nimport {\n type StorefrontCheckoutWallets,\n storefrontWalletsHideAny,\n} from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944), the half of native payments\n * AGL-1132 said mattered more: a shopper on a merchant's own domain pays\n * without being bounced to `checkout.stripe.com` and back.\n *\n * ## Why a Checkout Session and not a bare PaymentIntent\n *\n * AGL-1132 recommended \"PaymentIntent + `<PaymentElement/>`\" for this surface,\n * and AGL-1944 asked for that to be a conscious re-decision rather than an\n * inherited one. It is: the Payment Element ships, the bare PaymentIntent does\n * not, and the difference is worth stating because it is the whole safety\n * argument.\n *\n * A PaymentIntent-backed flow would have to own totals, tax, shipping and the\n * platform fee itself — which means a SECOND place that computes what a shopper\n * owes. Two paths that price a cart independently is how a storefront starts\n * under-collecting tax without anyone noticing: nothing fails, the number is\n * just quietly wrong on one of them. It also emits `payment_intent.succeeded`\n * rather than `checkout.session.completed`, so every fulfilment branch in\n * `billing-webhook.ts` — orders, inventory, coupons, gift cards, licence keys,\n * subscriptions — would need a parallel implementation reading a different\n * object shape.\n *\n * `ui_mode: 'elements'` is the Payment Element backed by a Checkout Session\n * (`'custom'` before the 2026-03-25.dahlia API renamed it). The\n * shopper sees `<PaymentElement/>` inside the merchant's own layout — no Stripe\n * chrome, which is the thing AGL-1944 objected to about embedded Checkout — and\n * the server keeps the session builder it already has. So:\n *\n * - tax, shipping, inventory, coupons, the Connect destination and the fee\n * ladder are the SAME code, not a parallel implementation. Parity is by\n * construction rather than by test;\n * - `checkout.session.completed` still fires, so `billing-webhook.ts` needs\n * no change at all and stays the only thing that fulfils an order.\n *\n * ## The API version, and why it is pinned per-request\n *\n * Measured against live Stripe in test mode: `ui_mode: 'custom'` was refused at\n * the platform account's default API version with\n *\n * Invalid Stripe API version: 2020-08-27. In order to use `ui_mode:\n * custom`, you must upgrade to Stripe API version 2025-03-31.basil.\n *\n * Upgrading the ACCOUNT default would re-version every Stripe call in this\n * repo at once — a change whose blast radius nobody could review in one pass.\n * A `Stripe-Version` header pins one request instead, and the pin is contained\n * in a way worth being explicit about: webhook deliveries are versioned per\n * ENDPOINT, not per request, so the events `billing-webhook.ts` parses keep\n * arriving in exactly the shape it already reads. The only thing read off the\n * pinned response is `client_secret` and `id`, neither of which the version\n * affects.\n *\n * ### Dahlia (AGL-3410)\n *\n * The pin moved from `2025-03-31.basil` to `2026-03-25.dahlia` with the\n * Stripe.js 9 / react-stripe-js 6 upgrade, because the browser half now boots\n * Stripe.js's Dahlia release train, and Dahlia renamed the mode this module\n * sets: `custom` is refused outright and `elements` replaces it. Across the two\n * releases crossed (Clover, Dahlia) the only other Checkout-session break that\n * reaches a param built here is Clover's switch of new subscriptions to\n * FLEXIBLE billing mode — so a subscription session pins\n * `billing_mode[type]=classic` below, and the subscription it creates bills\n * exactly as the hosted path's does.\n *\n * ### Parity, measured (re-taken at dahlia 2026-10-06, AGL-3606)\n *\n * `tools/scripts/measure-native-checkout-parity.mjs` sends the same params\n * twice against Stripe TEST mode on a test connected account — once as the\n * hosted path does, once rewritten by `applyNativeCheckoutParams` with the\n * dahlia pin — and compares `amount_total` and `total_details`:\n *\n * - manual tax line + `fixed_amount` shipping + `application_fee_amount`:\n * **6212 in both** (the basil figure, unchanged);\n * - Stripe Tax (`automatic_tax`) + shipping + fixed `transfer_data[amount]`:\n * **5799 in both**;\n * - Stripe Tax, no shipping: **5000 in both**;\n * - manual tax, no shipping, application fee: **5413 in both**.\n *\n * Stripe Tax's own amount is 0 in both before an address exists and is then\n * computed by Stripe from the address on the SAME session object either way;\n * the in-page form shows it live from `session.total`. Re-run the script after\n * any change to the pinned version.\n *\n * ## What this module deliberately does NOT do\n *\n * It does not fulfil anything, and it hands the browser nothing it could use to\n * claim an order was paid. The client gets a `clientSecret` — which is an\n * instruction to Stripe, not an assertion about money — and the same\n * `session_id` the redirect flow already put in the return URL. Fulfilment\n * remains `checkout.session.completed` in `billing-webhook.ts`, exactly as with\n * the redirect. An in-page flow makes trusting the browser tempting; the\n * browser is the one participant that can lie about having paid.\n */\n\n/**\n * The API version `ui_mode: 'elements'` needs, pinned on the session-create\n * request only. Stated once so the header and the doc comment cannot drift.\n */\nexport const NATIVE_CHECKOUT_STRIPE_VERSION = '2026-03-25.dahlia'\n\n/** The flag both halves of native checkout share (AGL-1132, AGL-1944). */\nexport const NATIVE_CHECKOUT_FLAG = 'release_native_checkout' as const\n\nexport interface NativeCheckoutMode {\n /** True only when the flag is on for this org AND a publishable key exists. */\n native: boolean\n /** Empty unless `native` — the client needs it to boot Stripe.js. */\n publishableKey: string\n}\n\n/**\n * Two conditions, not one — the same pairing the console's route settled on.\n *\n * A `ui_mode` session returns a `client_secret` and NO `url`, so a browser that\n * cannot mount Stripe.js has nothing to navigate to. If the flag alone decided\n * this, flipping it in an environment without\n * `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` would replace a working redirect with a\n * dead Buy button on every storefront at once. Requiring the key here means the\n * worst case of a premature flag flip is the redirect we already ship.\n *\n * The key is set on `aglyn-tenant`, the Vercel project that serves\n * storefronts, for production, preview and development (added 2026-08-23,\n * which superseded a 2026-08-18 measurement that found it only on\n * `aglyn-console`). Since the release on 2026-10-06 (AGL-3606) the flag is on\n * by default, so every storefront deployment with the key opens the in-page\n * form, and one without it keeps the redirect.\n *\n * The org — never the host — is the rollout bucket, per AGL-1656: a hostId and\n * an orgId hash to different buckets, so bucketing on the host could land a\n * merchant's storefront and their console on opposite sides of the same\n * percentage.\n */\nexport async function resolveNativeCheckoutMode(\n orgId: string | null | undefined,\n): Promise<NativeCheckoutMode> {\n const publishableKey = String(\n process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? '',\n ).trim()\n if (!publishableKey) return { native: false, publishableKey: '' }\n // A flag lookup that throws must not take a sale down with it, and the catch\n // is a `try` rather than `.catch()` deliberately: Remote Config being\n // unreachable rejects, but the resolver being absent entirely — an\n // environment where the module never loaded — throws SYNCHRONOUSLY, before\n // there is a promise to attach a handler to. Only the block form covers both.\n // Either way the answer is the same and it is the safe one: the redirect.\n let on: boolean\n try {\n on = await isServerReleaseFlagOnForOrg(NATIVE_CHECKOUT_FLAG, orgId ?? null)\n } catch {\n return { native: false, publishableKey: '' }\n }\n return on ? { native: true, publishableKey } : { native: false, publishableKey: '' }\n}\n\n/**\n * Rewrite a built session param set for the Payment Element, in place.\n *\n * DELETES `success_url` and `cancel_url` rather than leaving them alongside\n * `return_url`: Stripe rejects the pair outright on a `ui_mode` session, and a\n * 400 here would surface to the shopper as \"Checkout failed\" on a store that\n * was working an hour ago. Everything else in the param set — line items, the\n * tax line, `automatic_tax`, shipping options, the Connect destination, the\n * application fee, every `metadata[…]` key the webhook reads — is left exactly\n * as the caller built it. That is the point: this function must be incapable of\n * changing what the shopper is charged.\n *\n * `returnUrl` is the caller's OWN `success_url` string, `{CHECKOUT_SESSION_ID}`\n * placeholder and all. Stripe substitutes it on an embedded-components return\n * exactly as it does on a hosted redirect (measured), so the storefront's\n * post-purchase reporting — which reads `session_id` off the query to name the\n * order it just completed (AGL-1641) — keeps working unchanged.\n */\nexport function applyNativeCheckoutParams(\n params: URLSearchParams,\n returnUrl: string,\n): void {\n params.delete('success_url')\n params.delete('cancel_url')\n params.set('ui_mode', 'elements')\n params.set('return_url', returnUrl)\n // The pinned version defaults a NEW subscription to flexible billing mode\n // (Clover); the hosted path, on the account default, creates classic ones.\n // Stated so both paths bill a subscription the same way.\n if (params.get('mode') === 'subscription') {\n params.set('subscription_data[billing_mode][type]', 'classic')\n }\n}\n\n/**\n * The `Stripe-Version` pin, as headers to spread into the session-create fetch.\n * Empty for the hosted path so its request is byte-identical to today's.\n */\nexport function nativeCheckoutStripeHeaders(\n mode: NativeCheckoutMode,\n): Record<string, string> {\n return mode.native\n ? { 'Stripe-Version': NATIVE_CHECKOUT_STRIPE_VERSION }\n : {}\n}\n\nexport interface NativeCheckoutPayload {\n /** Stripe's own instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /** The order document id, and the `session_id` the return URL carries. */\n sessionId: string\n /**\n * The wallets the merchant hid (AGL-3629), for the Payment Element's\n * `wallets` option — Stripe will not exclude Apple Pay, Google Pay or Link\n * on the session itself. Absent when nothing is hidden, so a store on the\n * defaults answers exactly what it answered before.\n */\n wallets?: StorefrontCheckoutWallets\n}\n\nexport interface HostedCheckoutPayload {\n url: string\n}\n\n/**\n * Read the created session into the payload the storefront gets back.\n *\n * Returns `null` when the session is unusable, which BOTH callers already treat\n * as \"nothing was sold\" — release the idempotency claim and answer 502. The\n * null case is the whole reason this is a function rather than a ternary: the\n * hosted path's liveness check was `!session.url`, and a `ui_mode` session\n * never has one. Left unchanged, switching a store to native mode would have\n * made every successful session look like a Stripe failure — a 502 to the\n * shopper, a released claim, and a real Checkout Session left open on the\n * account. So the check has to move with the mode, and it does.\n */\nexport function readCheckoutSessionPayload(\n session: { url?: string; id?: string; client_secret?: string },\n mode: NativeCheckoutMode,\n wallets?: StorefrontCheckoutWallets,\n): NativeCheckoutPayload | HostedCheckoutPayload | null {\n if (!mode.native) return session?.url ? { url: session.url } : null\n if (!session?.client_secret || !session?.id) return null\n return {\n clientSecret: String(session.client_secret),\n publishableKey: mode.publishableKey,\n sessionId: String(session.id),\n ...(wallets && storefrontWalletsHideAny(wallets) ? { wallets } : {}),\n }\n}\n"],"names":["isServerReleaseFlagOnForOrg","storefrontWalletsHideAny","NATIVE_CHECKOUT_STRIPE_VERSION","NATIVE_CHECKOUT_FLAG","resolveNativeCheckoutMode","orgId","process","publishableKey","String","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","trim","native","on","applyNativeCheckoutParams","params","returnUrl","delete","set","get","nativeCheckoutStripeHeaders","mode","readCheckoutSessionPayload","session","wallets","url","client_secret","id","clientSecret","sessionId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,2BAA2B,QAAQ,2BAA0B;AACtE,SAEEC,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ACd;QAAE,kBAAkBV;IAA+B,IACnD,CAAC;AACP;AAqBA;;;;;;;;;;;CAWC,GACD,OAAO,SAASoB,2BACdC,OAA8D,EAC9DF,IAAwB,EACxBG,OAAmC;IAEnC,IAAI,CAACH,KAAKT,MAAM,EAAE,OAAOW,CAAAA,2BAAAA,QAASE,GAAG,IAAG;QAAEA,KAAKF,QAAQE,GAAG;IAAC,IAAI;IAC/D,IAAI,EAACF,2BAAAA,QAASG,aAAa,KAAI,EAACH,2BAAAA,QAASI,EAAE,GAAE,OAAO;IACpD,OAAO;QACLC,cAAcpB,OAAOe,QAAQG,aAAa;QAC1CnB,gBAAgBc,KAAKd,cAAc;QACnCsB,WAAWrB,OAAOe,QAAQI,EAAE;OACxBH,WAAWvB,yBAAyBuB,WAAW;QAAEA;IAAQ,IAAI,CAAC;AAEtE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/native-checkout.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin'\nimport {\n type StorefrontCheckoutWallets,\n storefrontWalletsHideAny,\n} from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944), the half of native payments\n * AGL-1132 said mattered more: a shopper on a merchant's own domain pays\n * without being bounced to `checkout.stripe.com` and back.\n *\n * ## Why a Checkout Session and not a bare PaymentIntent\n *\n * AGL-1132 recommended \"PaymentIntent + `<PaymentElement/>`\" for this surface,\n * and AGL-1944 asked for that to be a conscious re-decision rather than an\n * inherited one. It is: the Payment Element ships, the bare PaymentIntent does\n * not, and the difference is worth stating because it is the whole safety\n * argument.\n *\n * A PaymentIntent-backed flow would have to own totals, tax, shipping and the\n * platform fee itself — which means a SECOND place that computes what a shopper\n * owes. Two paths that price a cart independently is how a storefront starts\n * under-collecting tax without anyone noticing: nothing fails, the number is\n * just quietly wrong on one of them. It also emits `payment_intent.succeeded`\n * rather than `checkout.session.completed`, so every fulfilment branch in\n * `billing-webhook.ts` — orders, inventory, coupons, gift cards, licence keys,\n * subscriptions — would need a parallel implementation reading a different\n * object shape.\n *\n * `ui_mode: 'elements'` is the Payment Element backed by a Checkout Session\n * (`'custom'` before the 2026-03-25.dahlia API renamed it). The\n * shopper sees `<PaymentElement/>` inside the merchant's own layout — no Stripe\n * chrome, which is the thing AGL-1944 objected to about embedded Checkout — and\n * the server keeps the session builder it already has. So:\n *\n * - tax, shipping, inventory, coupons, the Connect destination and the fee\n * ladder are the SAME code, not a parallel implementation. Parity is by\n * construction rather than by test;\n * - `checkout.session.completed` still fires, so `billing-webhook.ts` needs\n * no change at all and stays the only thing that fulfils an order.\n *\n * ## The API version, and why it is pinned per-request\n *\n * Measured against live Stripe in test mode: `ui_mode: 'custom'` was refused at\n * the platform account's default API version with\n *\n * Invalid Stripe API version: 2020-08-27. In order to use `ui_mode:\n * custom`, you must upgrade to Stripe API version 2025-03-31.basil.\n *\n * Upgrading the ACCOUNT default would re-version every Stripe call in this\n * repo at once — a change whose blast radius nobody could review in one pass.\n * A `Stripe-Version` header pins one request instead, and the pin is contained\n * in a way worth being explicit about: webhook deliveries are versioned per\n * ENDPOINT, not per request, so the events `billing-webhook.ts` parses keep\n * arriving in exactly the shape it already reads. The only thing read off the\n * pinned response is `client_secret` and `id`, neither of which the version\n * affects.\n *\n * ### Dahlia (AGL-3410)\n *\n * The pin moved from `2025-03-31.basil` to `2026-03-25.dahlia` with the\n * Stripe.js 9 / react-stripe-js 6 upgrade, because the browser half now boots\n * Stripe.js's Dahlia release train, and Dahlia renamed the mode this module\n * sets: `custom` is refused outright and `elements` replaces it. Across the two\n * releases crossed (Clover, Dahlia) the only other Checkout-session break that\n * reaches a param built here is Clover's switch of new subscriptions to\n * FLEXIBLE billing mode — so a subscription session pins\n * `billing_mode[type]=classic` below, and the subscription it creates bills\n * exactly as the hosted path's does.\n *\n * ### Parity, measured (re-taken at dahlia 2026-10-06, AGL-3606)\n *\n * `tools/scripts/measure-native-checkout-parity.mjs` sends the same params\n * twice against Stripe TEST mode on a test connected account — once as the\n * hosted path does, once rewritten by `applyNativeCheckoutParams` with the\n * dahlia pin — and compares `amount_total` and `total_details`:\n *\n * - manual tax line + `fixed_amount` shipping + `application_fee_amount`:\n * **6212 in both** (the basil figure, unchanged);\n * - Stripe Tax (`automatic_tax`) + shipping + fixed `transfer_data[amount]`:\n * **5799 in both**;\n * - Stripe Tax, no shipping: **5000 in both**;\n * - manual tax, no shipping, application fee: **5413 in both**.\n *\n * Stripe Tax's own amount is 0 in both before an address exists and is then\n * computed by Stripe from the address on the SAME session object either way;\n * the in-page form shows it live from `session.total`. Re-run the script after\n * any change to the pinned version.\n *\n * ## What this module deliberately does NOT do\n *\n * It does not fulfil anything, and it hands the browser nothing it could use to\n * claim an order was paid. The client gets a `clientSecret` — which is an\n * instruction to Stripe, not an assertion about money — and the same\n * `session_id` the redirect flow already put in the return URL. Fulfilment\n * remains `checkout.session.completed` in `billing-webhook.ts`, exactly as with\n * the redirect. An in-page flow makes trusting the browser tempting; the\n * browser is the one participant that can lie about having paid.\n */\n\n/**\n * The API version `ui_mode: 'elements'` needs, pinned on the session-create\n * request only. Stated once so the header and the doc comment cannot drift.\n */\nexport const NATIVE_CHECKOUT_STRIPE_VERSION = '2026-03-25.dahlia'\n\n/** The flag both halves of native checkout share (AGL-1132, AGL-1944). */\nexport const NATIVE_CHECKOUT_FLAG = 'release_native_checkout' as const\n\nexport interface NativeCheckoutMode {\n /** True only when the flag is on for this org AND a publishable key exists. */\n native: boolean\n /** Empty unless `native` — the client needs it to boot Stripe.js. */\n publishableKey: string\n}\n\n/**\n * Two conditions, not one — the same pairing the console's route settled on.\n *\n * A `ui_mode` session returns a `client_secret` and NO `url`, so a browser that\n * cannot mount Stripe.js has nothing to navigate to. If the flag alone decided\n * this, flipping it in an environment without\n * `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` would replace a working redirect with a\n * dead Buy button on every storefront at once. Requiring the key here means the\n * worst case of a premature flag flip is the redirect we already ship.\n *\n * The key is set on `aglyn-tenant`, the Vercel project that serves\n * storefronts, for production, preview and development (added 2026-08-23,\n * which superseded a 2026-08-18 measurement that found it only on\n * `aglyn-console`). Since the release on 2026-10-06 (AGL-3606) the flag is on\n * by default, so every storefront deployment with the key opens the in-page\n * form, and one without it keeps the redirect.\n *\n * The org — never the host — is the rollout bucket, per AGL-1656: a hostId and\n * an orgId hash to different buckets, so bucketing on the host could land a\n * merchant's storefront and their console on opposite sides of the same\n * percentage.\n */\nexport async function resolveNativeCheckoutMode(\n orgId: string | null | undefined,\n): Promise<NativeCheckoutMode> {\n const publishableKey = String(\n process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? '',\n ).trim()\n if (!publishableKey) return { native: false, publishableKey: '' }\n // A flag lookup that throws must not take a sale down with it, and the catch\n // is a `try` rather than `.catch()` deliberately: Remote Config being\n // unreachable rejects, but the resolver being absent entirely — an\n // environment where the module never loaded — throws SYNCHRONOUSLY, before\n // there is a promise to attach a handler to. Only the block form covers both.\n // Either way the answer is the same and it is the safe one: the redirect.\n let on: boolean\n try {\n on = await isServerReleaseFlagOnForOrg(NATIVE_CHECKOUT_FLAG, orgId ?? null)\n } catch {\n return { native: false, publishableKey: '' }\n }\n return on ? { native: true, publishableKey } : { native: false, publishableKey: '' }\n}\n\n/**\n * Rewrite a built session param set for the Payment Element, in place.\n *\n * DELETES `success_url` and `cancel_url` rather than leaving them alongside\n * `return_url`: Stripe rejects the pair outright on a `ui_mode` session, and a\n * 400 here would surface to the shopper as \"Checkout failed\" on a store that\n * was working an hour ago. Everything else in the param set — line items, the\n * tax line, `automatic_tax`, shipping options, the Connect destination (or the\n * `Stripe-Account` header a direct charge's caller sends), the application fee, every `metadata[…]` key the webhook reads — is left exactly\n * as the caller built it. That is the point: this function must be incapable of\n * changing what the shopper is charged.\n *\n * `returnUrl` is the caller's OWN `success_url` string, `{CHECKOUT_SESSION_ID}`\n * placeholder and all. Stripe substitutes it on an embedded-components return\n * exactly as it does on a hosted redirect (measured), so the storefront's\n * post-purchase reporting — which reads `session_id` off the query to name the\n * order it just completed (AGL-1641) — keeps working unchanged.\n */\nexport function applyNativeCheckoutParams(\n params: URLSearchParams,\n returnUrl: string,\n): void {\n params.delete('success_url')\n params.delete('cancel_url')\n params.set('ui_mode', 'elements')\n params.set('return_url', returnUrl)\n // The pinned version defaults a NEW subscription to flexible billing mode\n // (Clover); the hosted path, on the account default, creates classic ones.\n // Stated so both paths bill a subscription the same way.\n if (params.get('mode') === 'subscription') {\n params.set('subscription_data[billing_mode][type]', 'classic')\n }\n}\n\n/**\n * The `Stripe-Version` pin, as headers to spread into the session-create fetch.\n * Empty for the hosted path so its request is byte-identical to today's.\n */\nexport function nativeCheckoutStripeHeaders(\n mode: NativeCheckoutMode,\n): Record<string, string> {\n return mode.native\n ? { 'Stripe-Version': NATIVE_CHECKOUT_STRIPE_VERSION }\n : {}\n}\n\nexport interface NativeCheckoutPayload {\n /** Stripe's own instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /** The order document id, and the `session_id` the return URL carries. */\n sessionId: string\n /**\n * The wallets the merchant hid (AGL-3629), for the Payment Element's\n * `wallets` option — Stripe will not exclude Apple Pay, Google Pay or Link\n * on the session itself. Absent when nothing is hidden, so a store on the\n * defaults answers exactly what it answered before.\n */\n wallets?: StorefrontCheckoutWallets\n /**\n * The seller's connected account, present only for a DIRECT charge: the\n * session was created on that account, so Stripe.js must be booted with\n * `stripeAccount` or the client secret does not resolve. Absent for a\n * destination sale, whose session lives on the platform account.\n */\n stripeAccount?: string\n}\n\nexport interface HostedCheckoutPayload {\n url: string\n}\n\n/**\n * Read the created session into the payload the storefront gets back.\n *\n * Returns `null` when the session is unusable, which BOTH callers already treat\n * as \"nothing was sold\" — release the idempotency claim and answer 502. The\n * null case is the whole reason this is a function rather than a ternary: the\n * hosted path's liveness check was `!session.url`, and a `ui_mode` session\n * never has one. Left unchanged, switching a store to native mode would have\n * made every successful session look like a Stripe failure — a 502 to the\n * shopper, a released claim, and a real Checkout Session left open on the\n * account. So the check has to move with the mode, and it does.\n */\nexport function readCheckoutSessionPayload(\n session: { url?: string; id?: string; client_secret?: string },\n mode: NativeCheckoutMode,\n wallets?: StorefrontCheckoutWallets,\n stripeAccount?: string,\n): NativeCheckoutPayload | HostedCheckoutPayload | null {\n // The hosted page needs nothing more: Stripe's own URL already knows which\n // account the session is on.\n if (!mode.native) return session?.url ? { url: session.url } : null\n if (!session?.client_secret || !session?.id) return null\n const account = String(stripeAccount ?? '').trim()\n return {\n clientSecret: String(session.client_secret),\n publishableKey: mode.publishableKey,\n sessionId: String(session.id),\n ...(wallets && storefrontWalletsHideAny(wallets) ? { wallets } : {}),\n ...(account ? { stripeAccount: account } : {}),\n }\n}\n"],"names":["isServerReleaseFlagOnForOrg","storefrontWalletsHideAny","NATIVE_CHECKOUT_STRIPE_VERSION","NATIVE_CHECKOUT_FLAG","resolveNativeCheckoutMode","orgId","process","publishableKey","String","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","trim","native","on","applyNativeCheckoutParams","params","returnUrl","delete","set","get","nativeCheckoutStripeHeaders","mode","readCheckoutSessionPayload","session","wallets","stripeAccount","url","client_secret","id","account","clientSecret","sessionId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,2BAA2B,QAAQ,2BAA0B;AACtE,SAEEC,wBAAwB,QACnB,uCAAmC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAwB,EACxBG,OAAmC,EACnCC,aAAsB;IAEtB,2EAA2E;IAC3E,6BAA6B;IAC7B,IAAI,CAACJ,KAAKT,MAAM,EAAE,OAAOW,CAAAA,2BAAAA,QAASG,GAAG,IAAG;QAAEA,KAAKH,QAAQG,GAAG;IAAC,IAAI;IAC/D,IAAI,EAACH,2BAAAA,QAASI,aAAa,KAAI,EAACJ,2BAAAA,QAASK,EAAE,GAAE,OAAO;IACpD,MAAMC,UAAUrB,OAAOiB,wBAAAA,gBAAiB,IAAId,IAAI;IAChD,OAAO;QACLmB,cAActB,OAAOe,QAAQI,aAAa;QAC1CpB,gBAAgBc,KAAKd,cAAc;QACnCwB,WAAWvB,OAAOe,QAAQK,EAAE;OACxBJ,WAAWvB,yBAAyBuB,WAAW;QAAEA;IAAQ,IAAI,CAAC,GAC9DK,UAAU;QAAEJ,eAAeI;IAAQ,IAAI,CAAC;AAEhD"}
@@ -30,9 +30,14 @@ import { type SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url';
30
30
  * registered for the user running the charge." Storefront charges are
31
31
  * DESTINATION charges created by the platform with no `Stripe-Account` header
32
32
  * and no `on_behalf_of`, so the platform runs them and the platform's key
33
- * registers the domain, with no `Stripe-Account` header. A direct-charge flow
34
- * would register on the connected account instead; there is none today, and
35
- * `registerOnPlatform` is named for that reason.
33
+ * registers the domain, with no `Stripe-Account` header.
34
+ *
35
+ * A DIRECT-charge seller runs its own charges: the session is created on the
36
+ * seller's connected account, so Apple Pay and Google Pay show only on a
37
+ * domain registered ON THAT ACCOUNT (`Stripe-Account` header). Every entry
38
+ * point below takes the seller's account for that case, and the platform's
39
+ * registration is left as it is, because the seller's hardware purchases and
40
+ * any sale from before the switch still run on the platform.
36
41
  *
37
42
  * ## When
38
43
  *
@@ -54,8 +59,10 @@ import { type SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url';
54
59
  * `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a
55
60
  * checkout costs one document read rather than a Stripe round trip. The mode is
56
61
  * in the id because a test key and a live key register in different worlds and
57
- * a domain registered in one is not registered in the other. Server-only: the
58
- * rules deny every client.
62
+ * a domain registered in one is not registered in the other. A seller's
63
+ * registration is cached under its own id, `{mode}~{account}~{domain}`,
64
+ * because it is a different Stripe object from the platform's for the same
65
+ * name. Server-only: the rules deny every client.
59
66
  */
60
67
  export declare const PAYMENT_METHOD_DOMAINS_COLLECTION = "paymentMethodDomains";
61
68
  /** How long a recorded registration is trusted before Stripe is asked again. */
@@ -74,6 +81,11 @@ export interface PaymentMethodDomainStatus {
74
81
  export interface PaymentMethodDomainRecord {
75
82
  domain: string;
76
83
  mode: StripeMode;
84
+ /**
85
+ * The connected account the domain is registered on, for a direct-charge
86
+ * seller; absent or null for the platform's own registration.
87
+ */
88
+ stripeAccount?: string | null;
77
89
  stripeId: string | null;
78
90
  enabled: boolean;
79
91
  status: PaymentMethodDomainStatus;
@@ -109,8 +121,11 @@ export declare function stripeModeOfKey(key: string | undefined): StripeMode | n
109
121
  * must not try to register it.
110
122
  */
111
123
  export declare function registrableDomain(input: unknown): string | null;
112
- /** The cache document id for a domain in a mode. */
113
- export declare function paymentMethodDomainDocId(mode: StripeMode, domain: string): string;
124
+ /**
125
+ * The cache document id for a domain in a mode, on the platform or on one
126
+ * seller's connected account.
127
+ */
128
+ export declare function paymentMethodDomainDocId(mode: StripeMode, domain: string, stripeAccount?: string | null): string;
114
129
  /**
115
130
  * The domains a site's custom domain needs: the domain and its `www.` twin,
116
131
  * since the platform answers on both (`siteOwnHosts`).
@@ -123,6 +138,12 @@ export declare function customDomainNames(cname: unknown): string[];
123
138
  * so two checkouts racing on a fresh subdomain open one registration.
124
139
  */
125
140
  export declare function registerOnPlatform(domain: string, signal?: AbortSignal): Promise<StripeDomainObject>;
141
+ /**
142
+ * Register (or re-enable) one domain on a direct-charge seller's connected
143
+ * account: the same steps as {@link registerOnPlatform}, each sent with the
144
+ * seller's `Stripe-Account`.
145
+ */
146
+ export declare function registerOnAccount(domain: string, stripeAccount: string, signal?: AbortSignal): Promise<StripeDomainObject>;
126
147
  export interface EnsureDomainResult {
127
148
  domain: string;
128
149
  outcome: 'registered' | 'cached' | 'skipped' | 'failed';
@@ -140,6 +161,8 @@ export declare function ensurePaymentMethodDomain(rawDomain: string, options?: {
140
161
  hostId?: string | null;
141
162
  signal?: AbortSignal;
142
163
  force?: boolean;
164
+ /** Register on this direct-charge seller's account, not the platform. */
165
+ stripeAccount?: string | null;
143
166
  }): Promise<EnsureDomainResult>;
144
167
  /**
145
168
  * Disable a domain the platform no longer serves for a site. Stripe has no
@@ -147,7 +170,9 @@ export declare function ensurePaymentMethodDomain(rawDomain: string, options?: {
147
170
  * `ensurePaymentMethodDomain` re-enables the same registration if the name is
148
171
  * connected again.
149
172
  */
150
- export declare function disablePaymentMethodDomain(rawDomain: string): Promise<{
173
+ export declare function disablePaymentMethodDomain(rawDomain: string, options?: {
174
+ stripeAccount?: string | null;
175
+ }): Promise<{
151
176
  domain: string;
152
177
  outcome: 'disabled' | 'absent' | 'skipped' | 'failed';
153
178
  error?: string;
@@ -171,6 +196,11 @@ export declare function ensureCheckoutDomain(input: {
171
196
  site: SiteReturnHost | null | undefined;
172
197
  hostId: string;
173
198
  budgetMs?: number;
199
+ /**
200
+ * The seller's connected account when this checkout is a DIRECT charge:
201
+ * the session runs there, so the domain must be registered there.
202
+ */
203
+ stripeAccount?: string;
174
204
  }): Promise<EnsureDomainResult | null>;
175
205
  /** One page of the daily reconcile. */
176
206
  export declare const RECONCILE_PAGE_SIZE = 200;
@@ -188,6 +218,8 @@ export declare function reconcileCustomDomains(gate: {
188
218
  isLocked(hostId: string): Promise<boolean>;
189
219
  }, options?: {
190
220
  maxPages?: number;
221
+ /** The site's direct-charge seller account, or null (tests inject it). */
222
+ sellerAccount?: (hostId: string) => Promise<string | null>;
191
223
  }): Promise<{
192
224
  hosts: number;
193
225
  registered: number;
@@ -198,12 +230,21 @@ export declare function reconcileCustomDomains(gate: {
198
230
  export declare function onHostDomainAttached(payload: {
199
231
  hostId: string;
200
232
  domain: string;
233
+ }, options?: {
234
+ sellerAccount?: (hostId: string) => Promise<string | null>;
201
235
  }): Promise<void>;
202
236
  /** Core's `host.domain.released`: disable what no other site still serves. */
203
237
  export declare function onHostDomainReleased(payload: {
204
238
  hostId: string;
205
239
  domain: string;
240
+ }, options?: {
241
+ sellerAccount?: (hostId: string) => Promise<string | null>;
206
242
  }): Promise<void>;
207
243
  /** The registrations a settings card shows for one site. */
208
- export declare function readSiteDomainRecords(site: SiteReturnHost | null | undefined): Promise<PaymentMethodDomainRecord[]>;
244
+ export declare function readSiteDomainRecords(site: SiteReturnHost | null | undefined,
245
+ /**
246
+ * The site's direct-charge seller account: its registrations are the ones
247
+ * the site's checkout uses, so they are the ones to show.
248
+ */
249
+ stripeAccount?: string | null): Promise<PaymentMethodDomainRecord[]>;
209
250
  export {};