@aglyn/plugins-commerce 1.15.0 → 1.15.2

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 (87) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +8 -3
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
  7. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/subscriptions-card.component.js +4 -2
  9. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  10. package/src/lib/components/product-detail.js +7 -3
  11. package/src/lib/components/product-detail.js.map +1 -1
  12. package/src/lib/components/quote-page-body.js +7 -3
  13. package/src/lib/components/quote-page-body.js.map +1 -1
  14. package/src/lib/components/related-products.js +6 -3
  15. package/src/lib/components/related-products.js.map +1 -1
  16. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  17. package/src/lib/components/storefront-payment-element.js +11 -7
  18. package/src/lib/components/storefront-payment-element.js.map +1 -1
  19. package/src/lib/model/commerce-payment-methods.d.ts +26 -39
  20. package/src/lib/model/commerce-payment-methods.js +11 -118
  21. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  22. package/src/lib/server/billing-webhook.d.ts +23 -0
  23. package/src/lib/server/billing-webhook.js +162 -30
  24. package/src/lib/server/billing-webhook.js.map +1 -1
  25. package/src/lib/server/cancel-order.js +4 -3
  26. package/src/lib/server/cancel-order.js.map +1 -1
  27. package/src/lib/server/cart-checkout.js +61 -14
  28. package/src/lib/server/cart-checkout.js.map +1 -1
  29. package/src/lib/server/catalog.js +58 -22
  30. package/src/lib/server/catalog.js.map +1 -1
  31. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  32. package/src/lib/server/checkout-session-expiry.js +19 -5
  33. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  34. package/src/lib/server/checkout-status.js +4 -3
  35. package/src/lib/server/checkout-status.js.map +1 -1
  36. package/src/lib/server/checkout.js +42 -12
  37. package/src/lib/server/checkout.js.map +1 -1
  38. package/src/lib/server/connect.js +42 -11
  39. package/src/lib/server/connect.js.map +1 -1
  40. package/src/lib/server/draft-order.js +37 -12
  41. package/src/lib/server/draft-order.js.map +1 -1
  42. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  43. package/src/lib/server/manual-tax-rate.js +10 -6
  44. package/src/lib/server/manual-tax-rate.js.map +1 -1
  45. package/src/lib/server/native-checkout.d.ts +10 -3
  46. package/src/lib/server/native-checkout.js +8 -3
  47. package/src/lib/server/native-checkout.js.map +1 -1
  48. package/src/lib/server/payment-method-domains.d.ts +50 -9
  49. package/src/lib/server/payment-method-domains.js +150 -51
  50. package/src/lib/server/payment-method-domains.js.map +1 -1
  51. package/src/lib/server/payment-methods.js +3 -2
  52. package/src/lib/server/payment-methods.js.map +1 -1
  53. package/src/lib/server/pos-order.js +5 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/pos-stripe.d.ts +7 -7
  56. package/src/lib/server/pos-stripe.js +15 -13
  57. package/src/lib/server/pos-stripe.js.map +1 -1
  58. package/src/lib/server/pos-terminal.js +11 -3
  59. package/src/lib/server/pos-terminal.js.map +1 -1
  60. package/src/lib/server/quote-pay.d.ts +23 -1
  61. package/src/lib/server/quote-pay.js +112 -32
  62. package/src/lib/server/quote-pay.js.map +1 -1
  63. package/src/lib/server/quote.d.ts +2 -1
  64. package/src/lib/server/quote.js +12 -11
  65. package/src/lib/server/quote.js.map +1 -1
  66. package/src/lib/server/refund.js +13 -6
  67. package/src/lib/server/refund.js.map +1 -1
  68. package/src/lib/server/related.js +10 -3
  69. package/src/lib/server/related.js.map +1 -1
  70. package/src/lib/server/reserve.js +19 -6
  71. package/src/lib/server/reserve.js.map +1 -1
  72. package/src/lib/server/revenue-source.d.ts +6 -0
  73. package/src/lib/server/revenue-source.js +25 -9
  74. package/src/lib/server/revenue-source.js.map +1 -1
  75. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  76. package/src/lib/server/seller-stripe-account.js +99 -0
  77. package/src/lib/server/seller-stripe-account.js.map +1 -0
  78. package/src/lib/server/storefront-tax-record.js +6 -1
  79. package/src/lib/server/storefront-tax-record.js.map +1 -1
  80. package/src/lib/server/storefront-tax.d.ts +33 -2
  81. package/src/lib/server/storefront-tax.js +39 -3
  82. package/src/lib/server/storefront-tax.js.map +1 -1
  83. package/src/lib/server/stripe-refund.d.ts +15 -0
  84. package/src/lib/server/stripe-refund.js +54 -26
  85. package/src/lib/server/stripe-refund.js.map +1 -1
  86. package/src/lib/server/subscription-portal.js +8 -3
  87. package/src/lib/server/subscription-portal.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/draft-order.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 { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport {\n planCheckoutShippingWithCarriers,\n type CarrierShippingPlan,\n} from './carrier-shipping'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n type PromotionSlotHold,\n holdPromotionSlot,\n promotionHoldKey,\n} from './promotion-hold'\nimport {\n buildRoute,\n claimAttempt,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\n\n/**\n * Draft orders (AGL-287, Shopify parity): a manager builds an order in\n * the console and sends the buyer a payment link. Creates the order doc\n * (status `pending`, channel `draft`) with a sequential number, then a\n * Stripe Checkout session on the merchant's connected account whose\n * webhook completion flips the SAME doc to `paid`\n * (metadata type `commerce-draft`).\n */\nexport const draftOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const productId = String(body.productId ?? '')\n const variantId = String(body.variantId ?? '')\n const quantity = Math.max(1, Math.min(99, Math.round(Number(body.quantity ?? 1))))\n const email = String(body.email ?? '').trim()\n // A code the MERCHANT types while composing the order (AGL-305). The\n // storefront doors read this same field name, so one resolver answers it the\n // same way whoever pressed the button.\n const couponCode = String(body.couponCode ?? '').trim()\n // One draft attempt, minted by the console dialog (AGL-1697). Node\n // lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n let claim: AttemptClaim | null = null\n /**\n * The redemption slot this attempt reserved (AGL-305), hoisted so every\n * refusal below the claim — and the catch — can hand it back. A throw after\n * the hold is placed is exactly the case where a slot would otherwise stand\n * invisibly against the merchant's cap until its TTL lapsed, and this path\n * rolls its order document back on two of those refusals already.\n */\n let discountSlot: PromotionSlotHold | null = null\n let discountHoldKey = ''\n const releaseDiscountSlot = async (): Promise<void> => {\n const slot = discountSlot\n discountSlot = null\n discountHoldKey = ''\n if (slot) await slot.release()\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // AN ALLOWLIST (AGL-2262), matching `cancel-order.ts`, `fulfill-order.ts`\n // and the Firestore rules, whose host-write predicate is\n // `hostMemberRole(hostId) in ['admin','editor']`. The old\n // `!role || role === 'viewer'` denylist caught the stranger but admitted\n // every OTHER string — a legacy value, a typo, any role added later — on\n // the one route that mints a live Stripe payment link. `HostAccessRole`\n // has since grown an `author` (AGL-2334), which this allowlist refuses on\n // purpose — an author edits content and does not mint payment links — and\n // which the old denylist would have admitted. That is the allowlist form\n // earning its keep on a union that changed under it.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const productSnapshot = await hostRef\n .collection('products')\n .doc(productId)\n .get()\n const raw = productSnapshot.data() as any\n if (!raw || raw.deletedAt) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n const variant = variantId\n ? product.variants.find((item) => item.id === variantId)\n : product.variants[0]\n if (!variant) return res.status(404).json({ error: 'Unknown variant' })\n // A variant with no price yet (AGL-2916) cannot be invoiced: the link\n // would ask for nothing, or for no amount at all.\n if (!CommerceModel.variantHasPrice(variant)) {\n return res.status(400).json({ error: `Set a price for ${product.name} before selling it.` })\n }\n\n // Merchant account like the storefront checkout (AGL-284).\n const ownerOrg = await getOrgForHost(hostId)\n // Plan gate, re-asked per request exactly as the storefront checkout\n // asks it (AGL-1873, the AGL-481 pattern): a free or lapsed org must not\n // keep minting payment links — at the free plan's 0% transaction fee —\n // through the one commerce door that skipped the entitlement. Sits\n // ABOVE the attempt claim with the other deterministic refusals, so it\n // never burns the merchant's idempotency key.\n if (!Aglyn.checkEntitlement(ownerOrg?.org as any, 'commerce')) {\n return res.status(403).json({ error: 'Selling is not enabled' })\n }\n const ownerId = ownerOrg?.org?.ownerUid\n const ownerProfile = ownerId\n ? await firestore.collection('profiles').doc(String(ownerId)).get()\n : null\n const accountId = ownerProfile?.get('stripeAccountId')\n if (\n !merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `draft order host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n\n // Where Stripe returns the BUYER is the business's own site (AGL-4094):\n // the order's status page after paying, the site's home after backing\n // out — see the params below. The console Products page is only the\n // fallback for a site with no public address or no signing secret, which\n // no published site lacks. Console products is the plugin route keyed by\n // org slug + host SUBDOMAIN; server code cannot call\n // useConsoleHostRoute, so resolve them here. Without both, fall back to\n // the origin root rather than a fabricated dead path.\n const consoleSubdomain = (\n await firestore.collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const consoleOrgSlug = ownerOrg?.org?.slug as string | undefined\n // The console's own host, as the POS door reads it — never the `Origin`\n // header (AGL-3363). The CUSTOMER lands here after paying the link, so a\n // caller-written origin would send a merchant's customer anywhere.\n const origin = `https://${req.headers.host}`\n const consoleProductsUrl =\n consoleOrgSlug && consoleSubdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug: consoleOrgSlug,\n host: consoleSubdomain,\n pluginSlug: 'products',\n })}`\n : origin\n\n // WHAT THE COUNT SAYS, said out loud (AGL-2452).\n //\n // This handler contained no `canPurchase` and no `stockShortfall` — no\n // reference to inventory of any kind. It is the door that mints a LIVE,\n // payable Stripe link, and it would mint one for a sold-out variant whose\n // merchant had chosen `oversellPolicy: 'deny'`, with the `commerce-draft`\n // webhook branch then completing it into a `paid` order. `pos-order.ts`'s\n // own comment asserts \"every storefront door gates on it\"; that claim was\n // false for this one.\n //\n // WARN, NEVER BLOCK, matching the register (AGL-2357, the decision).\n // Both of these are MERCHANT-initiated doors rather than shopper-initiated\n // ones — the merchant may well be taking a deliberate pre-order or\n // backorder — so a stale count must not refuse a sale the merchant means to\n // make. What the merchant is entitled to is to be TOLD, which is the part\n // that was missing entirely. The refusal variant is a separate decision and\n // is not taken here.\n //\n // Computed from the SERVER's product document, and reported on the same\n // `stockWarnings` key and in the same `StockShortfall` shape the register\n // already returns, so one console surface can read either door.\n const shortfall = CommerceModel.stockShortfall(\n product,\n variantId || product.variants[0]?.id,\n quantity,\n )\n const stockWarnings: CommerceModel.StockShortfall[] = shortfall\n ? [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n requested: quantity,\n available: shortfall.available,\n },\n ]\n : []\n\n const unitAmountCents = Math.round(Number(variant.priceUsd) * 100)\n const lineItems: CommerceModel.OrderLineItem[] = [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: product.type,\n quantity,\n unitAmountCents,\n },\n ]\n const itemsCents = unitAmountCents * quantity\n // THE DISCOUNTS HUB, ON THIS PATH TOO (AGL-305).\n //\n // `hosts/{hostId}/discounts` reached the cart and buy-now and stopped\n // there, so a store running \"Summer sale, 10% off\" sold at 10% off through\n // both storefront doors and at FULL price the moment the merchant invoiced\n // the same buyer for the same goods through a payment link. No code has to\n // be typed for that gap to open: an automatic promotion applies itself on\n // the storefront and applied itself nowhere here, so the merchant's own\n // payment link quietly undercut — and here overcharged against — their own\n // advertised price.\n //\n // Resolved through the SAME `resolveDiscount` the other doors use, so one\n // code cannot mean two amounts.\n //\n // RESOLVED BEFORE THE TAX BLOCK BELOW, and that ordering is the whole\n // point rather than a convenience: the manual rate is computed against\n // `chargedItemsCents`, so the discount lands BEFORE tax and the taxable\n // base is the discounted one. It has to be — the session applies that same\n // rate as `line_items[0][tax_rates][0]`, which Stripe evaluates against the\n // line amount it actually charges. Reducing the line while taxing the list\n // price would make our stored `taxCents` disagree with the tax Stripe\n // collects, on every discounted draft.\n const draftDiscountLines = [{ productId, amountCents: itemsCents }]\n const hubDiscounts = await hostRef.collection('discounts').limit(100).get()\n const resolvedDiscount = CommerceModel.resolveDiscount(\n hubDiscounts.docs.map((docSnapshot) => ({\n ...(docSnapshot.data() as CommerceModel.HostDiscount),\n $id: docSnapshot.id,\n })),\n {\n ...(couponCode ? { code: couponCode } : {}),\n subtotalCents: itemsCents,\n productIds: [productId],\n lines: draftDiscountLines,\n },\n )\n // Above the claim and above the order write with every other deterministic\n // refusal, so a merchant who fixes the code and presses Send again strands\n // no `pending` draft and burns no key. A code that RESOLVES but confers\n // nothing leaves through here too — `codeProblem` carries the benefit's own\n // reason — which is what stops this door repeating the defect that charged\n // full shipping on a free-shipping code.\n if (resolvedDiscount?.codeProblem) {\n return res.status(400).json({ error: resolvedDiscount.codeProblem })\n }\n const appliedDiscountId =\n resolvedDiscount && resolvedDiscount.benefit.kind !== 'none'\n ? resolvedDiscount.discountId\n : ''\n const discountCents = appliedDiscountId ? resolvedDiscount!.discountCents : 0\n // Stripe's charge minimum is 50¢ — never price a payment link below it,\n // the same floor buy-now applies.\n const chargedItemsCents = discountCents\n ? Math.max(50, itemsCents - discountCents)\n : itemsCents\n // What was ACTUALLY taken off, after that floor. The stored totals record\n // this rather than the resolver's figure, so the parts sum to the total on\n // a draft the floor moved.\n const appliedDiscountCents = itemsCents - chargedItemsCents\n // The fee and `totals` are both built BELOW the shipping plan (AGL-2152):\n // Stripe's card cost rides the whole payment-link total, so neither can be\n // known until the tax (AGL-1953) and the shipping options are.\n\n // Shipping (AGL-1792), from the same settings document the two storefront\n // paths read. This handler contained no `shipping` string at all: a\n // merchant who configured zones and rates collected them on a cart\n // (AGL-1707) and on buy-now (AGL-1720), and nothing when they invoiced the\n // same buyer for the same parcel through a payment link. The session\n // collected no address either, so the merchant was not even told where to\n // send it — the webhook records one now that Stripe is asked for it.\n //\n // The premise AGL-1792 filed this under was that \"the destination IS known\n // — the merchant typed it\". It is not: the draft dialog collects a product,\n // a variant, a quantity and an email, and this handler reads exactly those.\n // So the destination is as unknown here as it is in the cart, and the same\n // asking machinery applies rather than none of it.\n //\n // CONDITIONAL on the product being physical, exactly as buy-now is: this\n // dialog invoices downloads and consulting too, and charging that buyer\n // postage would be worse than the bug. A missing `type` reads as physical,\n // matching the fee ladder above — the two reads must not disagree about\n // what a part-migrated doc is. The one-time condition buy-now also carries\n // is structural here: this path only ever builds `mode: 'payment'`.\n //\n // RESOLVED BEFORE THE ORDER DOCUMENT, because the plan can refuse and the\n // order is written before Stripe is called. Refusing after it would strand\n // a `pending` draft on the merchant's orders list for every attempt —\n // this path's version of the orphaned coupon AGL-1721 kept out of the cart.\n const storeSettings = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n const shippingSettings = storeSettings.get('shipping') as\n CommerceModel.ShippingSettings | undefined\n\n // Taxes (AGL-1953), from the same settings document. This handler had no\n // tax code at all in either mode, so a merchant who invoiced a buyer for\n // the same product they sell on the storefront charged them no tax — the\n // cart's defect, one door over, and worse here because the merchant\n // composed this order deliberately and would reasonably assume it matched\n // their store.\n //\n // Origin-based, exactly as buy-now and the cart resolve it. The AGL-1792\n // note above already established the premise: this dialog collects a\n // product, a variant, a quantity and an email, so the DESTINATION is as\n // unknown here as it is in the cart.\n //\n // Computed pure and BEFORE the claim so the stored totals can carry it;\n // the Stripe object it needs is minted below the point of no return.\n const taxSettings = (storeSettings.get('tax') ?? {}) as CommerceModel.TaxSettings\n // AGL-1999: an unset tax mode is NOT a decision, and it must not sell.\n // `mode` was `undefined` for every store whose owner never opened the\n // Taxes card — the default state of every new storefront — and each\n // branch below tested for a specific string, so no branch was taken, no\n // tax was computed, and the shopper was charged an untaxed total. See\n // `commerce-tax-decision.ts` for why refusing beats defaulting to either\n // mode. `mode: 'none'` is the explicit opt-out and passes straight\n // through.\n const taxDecision = CommerceModel.storefrontTaxDecision({\n settings: taxSettings,\n taxExempt: product.taxExempt,\n })\n if (taxDecision.kind === 'undecided') {\n return res\n .status(409)\n .json({ error: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE })\n }\n const taxMisconfigured =\n CommerceModel.storefrontTaxMisconfiguration(taxSettings)\n if (taxMisconfigured) {\n // AGL-2145: the merchant DECIDED to collect and the sale would have\n // charged zero anyway — an unfinished settings card, not a\n // jurisdiction miss. Refused in the same words and the same place as\n // the undecided case above.\n return res.status(409).json({ error: taxMisconfigured })\n }\n const useStripeTax = taxDecision.kind === 'stripe-automatic'\n const manualRate =\n taxDecision.kind === 'manual' &&\n !taxSettings.pricesIncludeTax\n ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {})\n : null\n // THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line\n // will actually be worth, and the session applies this same rate to that\n // line as a Stripe Tax Rate — so taxing `itemsCents` here would record a\n // figure Stripe never charges.\n const taxCents = manualRate\n ? CommerceModel.computeTaxCents(chargedItemsCents, manualRate.pct)\n : 0\n // Stripe Tax mode leaves this 0 at composition time and the webhook folds\n // the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n // Live carrier rates (AGL-3612), quoted for the destination the manager\n // names; see `carrier-shipping.ts`.\n const shippingPlan: CarrierShippingPlan =\n (product.type ?? 'physical') === 'physical'\n ? await planCheckoutShippingWithCarriers({\n hostId,\n settings: shippingSettings,\n cart: {\n subtotalCents: itemsCents,\n totalGrams:\n Math.max(0, Number(variant.weightGrams ?? 0)) * quantity,\n ...(quantity === 1 ? { parcel: CommerceModel.productParcelDimensions(product) } : {}),\n },\n destination: {\n country: body.shippingCountry,\n postalCode: body.shippingPostalCode,\n },\n })\n : { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [] }\n if (shippingPlan.needsPostalCode) {\n return res.status(400).json({\n error: 'Enter the postal code this order ships to.',\n needsShippingCountry: true,\n needsShippingPostalCode: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-required') {\n return res.status(400).json({\n error: 'Choose where this order ships to.',\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-unserved') {\n const declared = CommerceModel.normalizeCheckoutShippingCountry(\n body.shippingCountry,\n )\n return res.status(409).json({\n error: `This store does not ship to ${\n CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[declared as string] ??\n 'that country'\n }.`,\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n // No rate of the merchant's reaches this order (AGL-2232). Above the\n // order write and the payment link, like every other refusal here, so a\n // manager who fixes the tier table and presses Send again strands nothing.\n if (shippingPlan.refusal === 'cart-unpriceable') {\n return res\n .status(409)\n .json({ error: CommerceModel.CART_UNPRICEABLE_SHIPPING_MESSAGE })\n }\n // FREE SHIPPING IS A ZEROED RATE, NOT A REDUCTION (AGL-305), the same\n // construction the cart uses and for the same reason: nothing has picked a\n // rate yet, so there is no amount to take off. The buyer chooses after the\n // link is minted, so the only exact answer is to offer every rate at zero.\n //\n // Every rate rather than the cheapest, because `free_shipping` carries no\n // field naming one — and zeroing them all keeps the fee, the transfer floor\n // and the ceiling below honest, since all three read these same options.\n //\n // Derived from `shippingPlan.options` and read EVERYWHERE below in its\n // place; a reader that reached past this to `shippingPlan.options` would\n // price carriage the buyer is not being charged for.\n const shippingOptions =\n resolvedDiscount?.freeShipping === true\n ? shippingPlan.options.map((option) => ({ ...option, amountCents: 0 }))\n : shippingPlan.options\n\n // THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card\n // cost, passed through at cost, at the CARD rate: the link excludes every\n // buy-now-pay-later method, as an invoice's later pay links do\n // (`payLinkPaymentMethodControls`). A payment link is a destination charge, so\n // Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only\n // figure meant every tier carrying a 0% rate invoiced a buyer at a loss to\n // Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.\n //\n // `?? 'physical'` (AGL-2251), matching `checkout.ts` and the cart. Without\n // it a product doc carrying no `type` fell to `resolveTransactionFeePct`'s\n // digital branch, so a merchant's payment link took a different cut of the\n // same product than their storefront did.\n //\n // The base is the whole card total: the goods, the manual tax line, and the DEAREST shipping\n // option the link offers (the buyer picks after the link is minted and\n // `application_fee_amount` is fixed at creation, so reaching for the\n // cheapest would put the difference back on Aglyn). A store on Stripe Tax\n // is the one residual — that tax is computed inside Stripe afterwards.\n const shippingCeilingCents = shippingOptions.reduce(\n (most, option) =>\n Math.max(most, Math.max(0, Number(option.amountCents ?? 0))),\n 0,\n )\n // Both bases are the DISCOUNTED goods (AGL-305). The platform take is a\n // cut of what the merchant actually sells for, and Stripe's card cost is\n // passed through on what the card actually runs for — reading `itemsCents`\n // here would invoice the merchant a fee on money nobody paid.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n product.type ?? 'physical',\n chargedItemsCents,\n chargedItemsCents + taxCents + shippingCeilingCents,\n Aglyn.PAY_LINK_PROCESSING_PERCENT,\n )\n // Stripe Tax mode leaves the tax 0 at composition time and the webhook\n // folds the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const totals = CommerceModel.computeOrderTotals(lineItems, {\n feeCents,\n taxCents,\n // The line item still carries the LIST price, so the discount has to be\n // a named part of the totals or `itemsCents - discountCents + tax` would\n // not be the number on the payment link.\n discountCents: appliedDiscountCents,\n })\n\n // THE LINK CHARGES `chargedItemsCents`, EXACTLY (the AGL-2159 construction,\n // reused here because this path grew the same problem the moment it grew a\n // discount).\n //\n // A Stripe line is `quantity` units at ONE integer `unit_amount`, so it can\n // only express totals divisible by `quantity` — and a percentage discount\n // does not respect that. Dividing and multiplying back misses the intended\n // total by up to `quantity / 2` cents in either direction, which on this\n // path is worse than on buy-now: the frozen `totals` above are written to\n // the order document BEFORE the session is minted, so a link that charged\n // a different number would leave the merchant's own books disagreeing with\n // what their buyer paid, permanently and silently.\n //\n // So when the total does not divide evenly, the line becomes ONE unit at\n // the exact total with the count moved into the display name. The real\n // quantity is carried by the order document's line item, which is\n // untouched, so nothing downstream can tell the difference.\n //\n // The even case — every undiscounted draft, and most discounted ones —\n // keeps the per-unit shape byte for byte.\n const evenUnitAmountCents = Math.floor(chargedItemsCents / quantity)\n const remainderCents = chargedItemsCents - evenUnitAmountCents * quantity\n const chargedQuantity = remainderCents === 0 ? quantity : 1\n const chargedUnitAmountCents =\n remainderCents === 0 ? evenUnitAmountCents : chargedItemsCents\n const chargedLineName = `${product.name}${\n remainderCents === 0 ? '' : ` × ${quantity}`\n }`.slice(0, 120)\n\n // Point of no return (AGL-1697): everything past here writes an order and\n // mints a live payment link. Every deterministic refusal — unknown\n // product, payments not set up, the shipping-destination ask — sits above\n // this line, so none of them burns the key: the merchant fixes the input\n // and presses the same button. Before the claim, a double-submit minted a\n // SECOND order doc, burned a second sequential number, and returned two\n // live payment links bound to different orders, both payable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-draft',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This draft order is already being created',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // THE REDEMPTION SLOT IS RESERVED HERE (AGL-305), on the same terms the\n // storefront doors reserve it.\n //\n // A payment link lives until the buyer pays it, so between this handler and\n // the `commerce-draft` webhook branch that settles the slot there is a\n // window measured in days — far wider than a Checkout Session's. Reading\n // `redemptions` and hoping would let a merchant mint ten links against a\n // cap of one and have all ten pay.\n //\n // BELOW the claim because the hold is keyed by the attempt: a retry of one\n // attempt must be able to re-claim the slot it already holds rather than be\n // refused by it. An uncapped promotion writes nothing and returns an empty\n // `holdKey`, which is what tells the webhook to fall back to the plain\n // increment.\n if (appliedDiscountId) {\n const slot = await holdPromotionSlot({\n firestore,\n ref: hostRef.collection('discounts').doc(appliedDiscountId),\n holdKey: promotionHoldKey(claimed.claim.stripeKey),\n label: `draft discount ${appliedDiscountId}`,\n })\n if (!slot.ok) {\n // Refused rather than quietly repriced, and that is deliberate for the\n // AUTOMATIC case too: the merchant composed this order at a price the\n // promotion was part of, and minting the link at full price would\n // invoice their buyer more than the store advertises without saying so.\n // Nothing has been written yet, so the key goes back and the retry\n // prices correctly — `resolveDiscount` counts live holds and simply\n // stops offering an exhausted promotion.\n await claim.release()\n return res.status(409).json({\n error:\n couponCode && resolvedDiscount?.discount.code\n ? CommerceModel.PROMOTION_EXHAUSTED_MESSAGE\n : CommerceModel.PROMOTION_UNAVAILABLE_MESSAGE,\n })\n }\n if (slot.holdKey) {\n discountSlot = slot\n discountHoldKey = slot.holdKey\n }\n }\n\n // Order doc first (transactional number), then the payment link.\n const orderRef = hostRef.collection('orders').doc()\n const counterRef = hostRef.collection('counters').doc('orders')\n await firestore.runTransaction(async (transaction) => {\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n // With the fields the orders list queries by (AGL-3321).\n transaction.set(orderRef, CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: 'pending',\n channel: 'draft',\n lineItems,\n totals,\n // WHICH TAX REGIME THIS ORDER IS COMPOSED UNDER (AGL-2451), from the\n // decision taken above rather than from the frozen `taxCents` — a\n // Stripe Tax draft freezes 0 there and only the paid session knows the\n // figure, so a mode read back off the amount would call it `none`.\n //\n // Stamped at composition so a draft that is never paid still says what\n // it was priced under, and RESTATED by the `commerce-draft` webhook\n // branch from the session that actually charged it. The webhook's is\n // authoritative — it has Stripe's computed tax in hand — and for a\n // manual draft the two agree by construction.\n taxMode: CommerceModel.storefrontTaxModeForDecision(\n taxDecision,\n taxCents,\n ),\n customerEmail: email || null,\n // WHAT ITS INVOICE'S LASTING PAY LINK CHARGES LATER (AGL-4099). The\n // session below lapses in a day; an invoice for this draft opens a\n // fresh one from the stored order whenever the buyer presses Pay, and\n // offers the same shipping rates this link does, and counts the same\n // promotion once paid. Stored even when there are no rates, so an\n // invoice can tell \"ships nothing\" from a draft made before this.\n draftShipping: {\n countries: shippingOptions.length > 0 ? Array.from(shippingPlan.countries ?? []) : [],\n options: shippingOptions.map((option) => ({\n rateId: String(option.rateId ?? ''),\n name: String(option.name ?? ''),\n amountCents: Math.max(0, Math.round(Number(option.amountCents ?? 0))),\n })),\n },\n ...(appliedDiscountId ? { discountId: appliedDiscountId } : {}),\n timeline: [\n {\n atMs: Date.now(),\n event: 'draft',\n detail: `Draft created by ${decoded.email ?? decoded.uid}`,\n },\n ],\n createdAtMs: Date.now(),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }))\n })\n\n // The tax rate is minted here, BELOW the claim, because it creates a real\n // Stripe object (AGL-1953). Cached per host, so it is usually a read.\n let draftTaxRateId = ''\n if (taxCents > 0 && manualRate) {\n draftTaxRateId =\n (await resolveManualTaxRateId({\n hostRef,\n taxPct: manualRate.pct,\n taxLabel: manualRate.label || `Tax (${manualRate.pct}%)`,\n ...(claim.stripeKey\n ? { headers: { 'Idempotency-Key': `${claim.stripeKey}-tax-rate` } }\n : {}),\n })) ?? ''\n if (!draftTaxRateId) {\n // A VISIBLE refusal rather than an untaxed payment link — the silent\n // under-collection is the defect. The order doc is rolled back the\n // same way the session failure below rolls it back.\n await orderRef.delete().catch(() => undefined)\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n }\n // The buyer's way back, on the business's site: the order's status page\n // (which reads the paid state from the server) and the site's home.\n const siteData = hostSnapshot.data() as { cname?: unknown; subdomain?: unknown } | undefined\n const buyerStatusUrl = orderStatusUrl(siteData, hostId, orderRef.id)\n const buyerSiteUrl = buyerStatusUrl ? `${new URL(buyerStatusUrl).origin}/` : ''\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(useStripeTax ? { 'automatic_tax[enabled]': 'true' } : {}),\n ...(draftTaxRateId ? { 'line_items[0][tax_rates][0]': draftTaxRateId } : {}),\n 'line_items[0][quantity]': String(chargedQuantity),\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),\n 'line_items[0][price_data][product_data][name]': chargedLineName,\n // THE CONNECT SPLIT (AGL-1956). A Stripe Tax payment link computes its\n // tax against AGLYN's registrations and Aglyn remits it (AGL-1904), so\n // the merchant gets a FIXED `transfer_data[amount]` and no\n // `application_fee_amount`: the fee form transfers `amount_total − fee`,\n // and `amount_total` includes that tax. A manual-rate or untaxed link is\n // unchanged. See `commerce-connect-transfer.ts`.\n ...CommerceModel.destinationChargeParams({\n accountId: String(accountId),\n feeCents,\n taxOwner: useStripeTax ? 'platform' : 'merchant',\n // The DISCOUNTED goods (AGL-305): this is what the merchant is\n // transferred, and paying out the list price on a discounted link\n // would move money Stripe never collected.\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents: CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ...(email ? { customer_email: email } : {}),\n success_url: buyerStatusUrl ?? `${consoleProductsUrl}?draft=paid`,\n cancel_url: buyerSiteUrl || `${consoleProductsUrl}?draft=canceled`,\n 'metadata[type]': 'commerce-draft',\n 'metadata[hostId]': hostId,\n 'metadata[orderId]': orderRef.id,\n 'metadata[productId]': productId,\n ...(variantId ? { 'metadata[variantId]': variantId } : {}),\n 'metadata[feeCents]': String(feeCents),\n ...(shippingPlan.quotedPostalCode\n ? { 'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode }\n : {}),\n // WHAT THE WEBHOOK SETTLES (AGL-305), in the field names the\n // `checkout.session.completed` branch already reads for the cart. The\n // hold key's ABSENCE is what tells it to fall back to the unconditional\n // increment, which is right for an uncapped promotion.\n ...(appliedDiscountId\n ? { 'metadata[discountId]': appliedDiscountId }\n : {}),\n ...(discountHoldKey ? { 'metadata[discountHoldKey]': discountHoldKey } : {}),\n // See the AGL-1956 note in `checkout.ts` — recorded only on the shape\n // where the merchant's payout is no longer the whole charge.\n ...(useStripeTax\n ? {\n 'metadata[transferCents]': String(\n CommerceModel.platformLiableTransferCents({\n feeCents,\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents:\n CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ),\n 'metadata[transferShippingCents]': String(\n CommerceModel.shippingFloorCents(shippingOptions),\n ),\n }\n : {}),\n })\n // Both keys or neither (AGL-1720's rule, inherited). Stripe will not apply\n // a shipping rate without an address to ship to, and a merchant who\n // configured nothing plans to no options and so gets neither — a payment\n // link byte-identical to the one this handler built before shipping\n // existed on it.\n if (shippingOptions.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n shippingPlan.countries,\n )\n CommerceModel.appendCheckoutShippingParams(params, shippingOptions)\n }\n // The payment methods the merchant switched off reach the payment link\n // too (AGL-3629). A hosted Stripe page shows Apple Pay and Google Pay by\n // device and cannot hide them per merchant; everything else follows.\n // Klarna, Afterpay and Affirm are excluded whatever the store chose: the\n // link is an invoice, priced at the card rate above.\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.payLinkPaymentMethodControls(\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSettings.get('paymentMethods'),\n ),\n ),\n ),\n )\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that is a live payment link (AGL-1697). Stripe replays\n // the existing session for a repeated key instead of opening a\n // second one on the merchant's account, which covers the window\n // where our claim is written but the response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as {\n url?: string\n id?: string\n error?: any\n }\n if (!response.ok || !session.url) {\n console.error('Stripe draft-order error', session.error)\n await orderRef.delete().catch(() => undefined)\n // The draft did not happen — hand the key back rather than locking this\n // dialog out over one flaky moment. The retry re-derives the SAME\n // digest, so if Stripe did create the session it replays it.\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n await orderRef.set(\n { checkoutSessionId: session.id, paymentLinkUrl: session.url },\n { merge: true },\n )\n // Spread on the same terms as the register's: present only when there is\n // something to say, so a caller can test the key rather than a length.\n const payload = {\n orderId: orderRef.id,\n url: session.url,\n ...(stockWarnings.length > 0 ? { stockWarnings } : {}),\n }\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // (AGL-1691's rule). The order write may or may not have landed; the\n // merchant reconciles from the orders list, the same position they were\n // in before this endpoint had a claim at all. The redemption slot goes\n // back for the same reason — a throw is the one path that would otherwise\n // leave it standing against the cap until its TTL lapsed.\n await releaseDiscountSlot()\n await claim?.release()\n return res.status(500).json({ error: 'Draft order failed' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","planCheckoutShippingWithCarriers","resolveManualTaxRateId","orderStatusUrl","holdPromotionSlot","promotionHoldKey","buildRoute","claimAttempt","Route","draftOrderHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","productId","variantId","quantity","Math","max","min","round","Number","email","trim","couponCode","idempotencyKey","claim","discountSlot","discountHoldKey","releaseDiscountSlot","slot","release","storeSettings","taxSettings","product","variant","ownerOrg","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","productSnapshot","raw","data","deletedAt","liftLegacyProduct","variants","find","item","id","variantHasPrice","name","checkEntitlement","org","ownerId","ownerUid","ownerProfile","accountId","chargesEnabled","accountLivemode","subject","consoleSubdomain","consoleOrgSlug","slug","origin","host","consoleProductsUrl","HOST_PLUGIN","orgSlug","pluginSlug","shortfall","stockShortfall","stockWarnings","requested","available","unitAmountCents","priceUsd","lineItems","sku","productType","type","itemsCents","draftDiscountLines","amountCents","hubDiscounts","limit","resolvedDiscount","resolveDiscount","docs","map","docSnapshot","$id","code","subtotalCents","productIds","lines","codeProblem","appliedDiscountId","benefit","kind","discountId","discountCents","chargedItemsCents","appliedDiscountCents","shippingSettings","taxDecision","storefrontTaxDecision","settings","taxExempt","STOREFRONT_TAX_UNDECIDED_MESSAGE","taxMisconfigured","storefrontTaxMisconfiguration","useStripeTax","manualRate","pricesIncludeTax","resolveTaxRate","taxCents","computeTaxCents","pct","shippingPlan","cart","totalGrams","weightGrams","parcel","productParcelDimensions","destination","country","shippingCountry","postalCode","shippingPostalCode","countries","CHECKOUT_SHIPPING_COUNTRIES","options","needsPostalCode","needsShippingCountry","needsShippingPostalCode","shippingCountries","refusal","declared","normalizeCheckoutShippingCountry","CHECKOUT_SHIPPING_COUNTRY_NAMES","CART_UNPRICEABLE_SHIPPING_MESSAGE","shippingOptions","freeShipping","option","shippingCeilingCents","reduce","most","feeCents","resolveTransactionFeeCents","PAY_LINK_PROCESSING_PERCENT","totals","computeOrderTotals","evenUnitAmountCents","floor","remainderCents","chargedQuantity","chargedUnitAmountCents","chargedLineName","claimed","scopeId","orgId","key","busyMessage","replay","ref","holdKey","stripeKey","label","ok","discount","PROMOTION_EXHAUSTED_MESSAGE","PROMOTION_UNAVAILABLE_MESSAGE","orderRef","counterRef","runTransaction","transaction","counter","number","set","next","merge","withOrderListFields","channel","taxMode","storefrontTaxModeForDecision","customerEmail","draftShipping","Array","from","rateId","timeline","atMs","Date","now","event","detail","createdAtMs","createdAt","FieldValue","serverTimestamp","draftTaxRateId","taxPct","taxLabel","delete","catch","siteData","buyerStatusUrl","buyerSiteUrl","URL","params","URLSearchParams","mode","destinationChargeParams","taxOwner","merchantGoodsCents","shippingFloorCents","customer_email","success_url","cancel_url","quotedPostalCode","platformLiableTransferCents","appendShippingAddressCollectionParams","appendCheckoutShippingParams","appendStorefrontPaymentMethodParams","payLinkPaymentMethodControls","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","toString","session","url","console","checkoutSessionId","paymentLinkUrl","payload","orderId","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SACEC,gCAAgC,QAE3B,wBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAEEC,iBAAiB,EACjBC,gBAAgB,QACX,sBAAkB;AACzB,SACEC,UAAU,EACVC,YAAY,EACZC,KAAK,QAGA,sBAAqB;AAE5B;;;;;;;CAOC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QAOhCD,4BAM4BA,WACnCE,cACGA,iBACAA,iBACmCA,gBACvCA,aAIKA,kBAKxBF,MAAAA;IA1BF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF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KAAK,CAACA;QACd,wEAAwE;QACxE,qEAAqE;QACrE,wEAAwE;QACxE,uEAAuE;QACvE,0EAA0E;QAC1E,0DAA0D;QAC1D,MAAM8B;QACN,OAAMH,yBAAAA,MAAOK,OAAO;QACpB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/draft-order.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 { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport {\n planCheckoutShippingWithCarriers,\n type CarrierShippingPlan,\n} from './carrier-shipping'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE,\n sellerStripeTaxActive,\n} from './seller-stripe-account'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n type PromotionSlotHold,\n holdPromotionSlot,\n promotionHoldKey,\n} from './promotion-hold'\nimport {\n buildRoute,\n claimAttempt,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\n\n/**\n * Draft orders (AGL-287, Shopify parity): a manager builds an order in\n * the console and sends the buyer a payment link. Creates the order doc\n * (status `pending`, channel `draft`) with a sequential number, then a\n * Stripe Checkout session on the merchant's connected account whose\n * webhook completion flips the SAME doc to `paid`\n * (metadata type `commerce-draft`).\n */\nexport const draftOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const productId = String(body.productId ?? '')\n const variantId = String(body.variantId ?? '')\n const quantity = Math.max(1, Math.min(99, Math.round(Number(body.quantity ?? 1))))\n const email = String(body.email ?? '').trim()\n // A code the MERCHANT types while composing the order (AGL-305). The\n // storefront doors read this same field name, so one resolver answers it the\n // same way whoever pressed the button.\n const couponCode = String(body.couponCode ?? '').trim()\n // One draft attempt, minted by the console dialog (AGL-1697). Node\n // lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n let claim: AttemptClaim | null = null\n /**\n * The redemption slot this attempt reserved (AGL-305), hoisted so every\n * refusal below the claim — and the catch — can hand it back. A throw after\n * the hold is placed is exactly the case where a slot would otherwise stand\n * invisibly against the merchant's cap until its TTL lapsed, and this path\n * rolls its order document back on two of those refusals already.\n */\n let discountSlot: PromotionSlotHold | null = null\n let discountHoldKey = ''\n const releaseDiscountSlot = async (): Promise<void> => {\n const slot = discountSlot\n discountSlot = null\n discountHoldKey = ''\n if (slot) await slot.release()\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // AN ALLOWLIST (AGL-2262), matching `cancel-order.ts`, `fulfill-order.ts`\n // and the Firestore rules, whose host-write predicate is\n // `hostMemberRole(hostId) in ['admin','editor']`. The old\n // `!role || role === 'viewer'` denylist caught the stranger but admitted\n // every OTHER string — a legacy value, a typo, any role added later — on\n // the one route that mints a live Stripe payment link. `HostAccessRole`\n // has since grown an `author` (AGL-2334), which this allowlist refuses on\n // purpose — an author edits content and does not mint payment links — and\n // which the old denylist would have admitted. That is the allowlist form\n // earning its keep on a union that changed under it.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const productSnapshot = await hostRef\n .collection('products')\n .doc(productId)\n .get()\n const raw = productSnapshot.data() as any\n if (!raw || raw.deletedAt) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n const variant = variantId\n ? product.variants.find((item) => item.id === variantId)\n : product.variants[0]\n if (!variant) return res.status(404).json({ error: 'Unknown variant' })\n // A variant with no price yet (AGL-2916) cannot be invoiced: the link\n // would ask for nothing, or for no amount at all.\n if (!CommerceModel.variantHasPrice(variant)) {\n return res.status(400).json({ error: `Set a price for ${product.name} before selling it.` })\n }\n\n // Merchant account like the storefront checkout (AGL-284).\n const ownerOrg = await getOrgForHost(hostId)\n // Plan gate, re-asked per request exactly as the storefront checkout\n // asks it (AGL-1873, the AGL-481 pattern): a free or lapsed org must not\n // keep minting payment links — at the free plan's 0% transaction fee —\n // through the one commerce door that skipped the entitlement. Sits\n // ABOVE the attempt claim with the other deterministic refusals, so it\n // never burns the merchant's idempotency key.\n if (!Aglyn.checkEntitlement(ownerOrg?.org as any, 'commerce')) {\n return res.status(403).json({ error: 'Selling is not enabled' })\n }\n const ownerId = ownerOrg?.org?.ownerUid\n const ownerProfile = ownerId\n ? await firestore.collection('profiles').doc(String(ownerId)).get()\n : null\n const accountId = ownerProfile?.get('stripeAccountId')\n if (\n !merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `draft order host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n // A DIRECT charge opens the link ON the seller's own Stripe account\n // (`Stripe-Account`), with Aglyn's take as the application fee; the\n // destination path below is unchanged for every other seller.\n const chargeModel = saleChargeModel(ownerProfile?.get('stripeChargeModel'))\n const direct = chargeModel === 'direct'\n const onAccount = connectedAccountHeader(chargeModel, accountId)\n\n // Where Stripe returns the BUYER is the business's own site (AGL-4094):\n // the order's status page after paying, the site's home after backing\n // out — see the params below. The console Products page is only the\n // fallback for a site with no public address or no signing secret, which\n // no published site lacks. Console products is the plugin route keyed by\n // org slug + host SUBDOMAIN; server code cannot call\n // useConsoleHostRoute, so resolve them here. Without both, fall back to\n // the origin root rather than a fabricated dead path.\n const consoleSubdomain = (\n await firestore.collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const consoleOrgSlug = ownerOrg?.org?.slug as string | undefined\n // The console's own host, as the POS door reads it — never the `Origin`\n // header (AGL-3363). The CUSTOMER lands here after paying the link, so a\n // caller-written origin would send a merchant's customer anywhere.\n const origin = `https://${req.headers.host}`\n const consoleProductsUrl =\n consoleOrgSlug && consoleSubdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug: consoleOrgSlug,\n host: consoleSubdomain,\n pluginSlug: 'products',\n })}`\n : origin\n\n // WHAT THE COUNT SAYS, said out loud (AGL-2452).\n //\n // This handler contained no `canPurchase` and no `stockShortfall` — no\n // reference to inventory of any kind. It is the door that mints a LIVE,\n // payable Stripe link, and it would mint one for a sold-out variant whose\n // merchant had chosen `oversellPolicy: 'deny'`, with the `commerce-draft`\n // webhook branch then completing it into a `paid` order. `pos-order.ts`'s\n // own comment asserts \"every storefront door gates on it\"; that claim was\n // false for this one.\n //\n // WARN, NEVER BLOCK, matching the register (AGL-2357, the decision).\n // Both of these are MERCHANT-initiated doors rather than shopper-initiated\n // ones — the merchant may well be taking a deliberate pre-order or\n // backorder — so a stale count must not refuse a sale the merchant means to\n // make. What the merchant is entitled to is to be TOLD, which is the part\n // that was missing entirely. The refusal variant is a separate decision and\n // is not taken here.\n //\n // Computed from the SERVER's product document, and reported on the same\n // `stockWarnings` key and in the same `StockShortfall` shape the register\n // already returns, so one console surface can read either door.\n const shortfall = CommerceModel.stockShortfall(\n product,\n variantId || product.variants[0]?.id,\n quantity,\n )\n const stockWarnings: CommerceModel.StockShortfall[] = shortfall\n ? [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n requested: quantity,\n available: shortfall.available,\n },\n ]\n : []\n\n const unitAmountCents = Math.round(Number(variant.priceUsd) * 100)\n const lineItems: CommerceModel.OrderLineItem[] = [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: product.type,\n quantity,\n unitAmountCents,\n },\n ]\n const itemsCents = unitAmountCents * quantity\n // THE DISCOUNTS HUB, ON THIS PATH TOO (AGL-305).\n //\n // `hosts/{hostId}/discounts` reached the cart and buy-now and stopped\n // there, so a store running \"Summer sale, 10% off\" sold at 10% off through\n // both storefront doors and at FULL price the moment the merchant invoiced\n // the same buyer for the same goods through a payment link. No code has to\n // be typed for that gap to open: an automatic promotion applies itself on\n // the storefront and applied itself nowhere here, so the merchant's own\n // payment link quietly undercut — and here overcharged against — their own\n // advertised price.\n //\n // Resolved through the SAME `resolveDiscount` the other doors use, so one\n // code cannot mean two amounts.\n //\n // RESOLVED BEFORE THE TAX BLOCK BELOW, and that ordering is the whole\n // point rather than a convenience: the manual rate is computed against\n // `chargedItemsCents`, so the discount lands BEFORE tax and the taxable\n // base is the discounted one. It has to be — the session applies that same\n // rate as `line_items[0][tax_rates][0]`, which Stripe evaluates against the\n // line amount it actually charges. Reducing the line while taxing the list\n // price would make our stored `taxCents` disagree with the tax Stripe\n // collects, on every discounted draft.\n const draftDiscountLines = [{ productId, amountCents: itemsCents }]\n const hubDiscounts = await hostRef.collection('discounts').limit(100).get()\n const resolvedDiscount = CommerceModel.resolveDiscount(\n hubDiscounts.docs.map((docSnapshot) => ({\n ...(docSnapshot.data() as CommerceModel.HostDiscount),\n $id: docSnapshot.id,\n })),\n {\n ...(couponCode ? { code: couponCode } : {}),\n subtotalCents: itemsCents,\n productIds: [productId],\n lines: draftDiscountLines,\n },\n )\n // Above the claim and above the order write with every other deterministic\n // refusal, so a merchant who fixes the code and presses Send again strands\n // no `pending` draft and burns no key. A code that RESOLVES but confers\n // nothing leaves through here too — `codeProblem` carries the benefit's own\n // reason — which is what stops this door repeating the defect that charged\n // full shipping on a free-shipping code.\n if (resolvedDiscount?.codeProblem) {\n return res.status(400).json({ error: resolvedDiscount.codeProblem })\n }\n const appliedDiscountId =\n resolvedDiscount && resolvedDiscount.benefit.kind !== 'none'\n ? resolvedDiscount.discountId\n : ''\n const discountCents = appliedDiscountId ? resolvedDiscount!.discountCents : 0\n // Stripe's charge minimum is 50¢ — never price a payment link below it,\n // the same floor buy-now applies.\n const chargedItemsCents = discountCents\n ? Math.max(50, itemsCents - discountCents)\n : itemsCents\n // What was ACTUALLY taken off, after that floor. The stored totals record\n // this rather than the resolver's figure, so the parts sum to the total on\n // a draft the floor moved.\n const appliedDiscountCents = itemsCents - chargedItemsCents\n // The fee and `totals` are both built BELOW the shipping plan (AGL-2152):\n // Stripe's card cost rides the whole payment-link total, so neither can be\n // known until the tax (AGL-1953) and the shipping options are.\n\n // Shipping (AGL-1792), from the same settings document the two storefront\n // paths read. This handler contained no `shipping` string at all: a\n // merchant who configured zones and rates collected them on a cart\n // (AGL-1707) and on buy-now (AGL-1720), and nothing when they invoiced the\n // same buyer for the same parcel through a payment link. The session\n // collected no address either, so the merchant was not even told where to\n // send it — the webhook records one now that Stripe is asked for it.\n //\n // The premise AGL-1792 filed this under was that \"the destination IS known\n // — the merchant typed it\". It is not: the draft dialog collects a product,\n // a variant, a quantity and an email, and this handler reads exactly those.\n // So the destination is as unknown here as it is in the cart, and the same\n // asking machinery applies rather than none of it.\n //\n // CONDITIONAL on the product being physical, exactly as buy-now is: this\n // dialog invoices downloads and consulting too, and charging that buyer\n // postage would be worse than the bug. A missing `type` reads as physical,\n // matching the fee ladder above — the two reads must not disagree about\n // what a part-migrated doc is. The one-time condition buy-now also carries\n // is structural here: this path only ever builds `mode: 'payment'`.\n //\n // RESOLVED BEFORE THE ORDER DOCUMENT, because the plan can refuse and the\n // order is written before Stripe is called. Refusing after it would strand\n // a `pending` draft on the merchant's orders list for every attempt —\n // this path's version of the orphaned coupon AGL-1721 kept out of the cart.\n const storeSettings = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n const shippingSettings = storeSettings.get('shipping') as\n CommerceModel.ShippingSettings | undefined\n\n // Taxes (AGL-1953), from the same settings document. This handler had no\n // tax code at all in either mode, so a merchant who invoiced a buyer for\n // the same product they sell on the storefront charged them no tax — the\n // cart's defect, one door over, and worse here because the merchant\n // composed this order deliberately and would reasonably assume it matched\n // their store.\n //\n // Origin-based, exactly as buy-now and the cart resolve it. The AGL-1792\n // note above already established the premise: this dialog collects a\n // product, a variant, a quantity and an email, so the DESTINATION is as\n // unknown here as it is in the cart.\n //\n // Computed pure and BEFORE the claim so the stored totals can carry it;\n // the Stripe object it needs is minted below the point of no return.\n const taxSettings = (storeSettings.get('tax') ?? {}) as CommerceModel.TaxSettings\n // AGL-1999: an unset tax mode is NOT a decision, and it must not sell.\n // `mode` was `undefined` for every store whose owner never opened the\n // Taxes card — the default state of every new storefront — and each\n // branch below tested for a specific string, so no branch was taken, no\n // tax was computed, and the shopper was charged an untaxed total. See\n // `commerce-tax-decision.ts` for why refusing beats defaulting to either\n // mode. `mode: 'none'` is the explicit opt-out and passes straight\n // through.\n const taxDecision = CommerceModel.storefrontTaxDecision({\n settings: taxSettings,\n taxExempt: product.taxExempt,\n })\n if (taxDecision.kind === 'undecided') {\n return res\n .status(409)\n .json({ error: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE })\n }\n const taxMisconfigured =\n CommerceModel.storefrontTaxMisconfiguration(taxSettings)\n if (taxMisconfigured) {\n // AGL-2145: the merchant DECIDED to collect and the sale would have\n // charged zero anyway — an unfinished settings card, not a\n // jurisdiction miss. Refused in the same words and the same place as\n // the undecided case above.\n return res.status(409).json({ error: taxMisconfigured })\n }\n const useStripeTax = taxDecision.kind === 'stripe-automatic'\n // Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is\n // not set up, and a store that chose it must not sell untaxed. Above the\n // claim and the order write with the other tax refusals.\n if (\n direct &&\n useStripeTax &&\n !(await sellerStripeTaxActive(String(accountId)))\n ) {\n return res.status(409).json({ error: SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE })\n }\n const manualRate =\n taxDecision.kind === 'manual' &&\n !taxSettings.pricesIncludeTax\n ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {})\n : null\n // THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line\n // will actually be worth, and the session applies this same rate to that\n // line as a Stripe Tax Rate — so taxing `itemsCents` here would record a\n // figure Stripe never charges.\n const taxCents = manualRate\n ? CommerceModel.computeTaxCents(chargedItemsCents, manualRate.pct)\n : 0\n // Stripe Tax mode leaves this 0 at composition time and the webhook folds\n // the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n // Live carrier rates (AGL-3612), quoted for the destination the manager\n // names; see `carrier-shipping.ts`.\n const shippingPlan: CarrierShippingPlan =\n (product.type ?? 'physical') === 'physical'\n ? await planCheckoutShippingWithCarriers({\n hostId,\n settings: shippingSettings,\n cart: {\n subtotalCents: itemsCents,\n totalGrams:\n Math.max(0, Number(variant.weightGrams ?? 0)) * quantity,\n ...(quantity === 1 ? { parcel: CommerceModel.productParcelDimensions(product) } : {}),\n },\n destination: {\n country: body.shippingCountry,\n postalCode: body.shippingPostalCode,\n },\n })\n : { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [] }\n if (shippingPlan.needsPostalCode) {\n return res.status(400).json({\n error: 'Enter the postal code this order ships to.',\n needsShippingCountry: true,\n needsShippingPostalCode: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-required') {\n return res.status(400).json({\n error: 'Choose where this order ships to.',\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-unserved') {\n const declared = CommerceModel.normalizeCheckoutShippingCountry(\n body.shippingCountry,\n )\n return res.status(409).json({\n error: `This store does not ship to ${\n CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[declared as string] ??\n 'that country'\n }.`,\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n // No rate of the merchant's reaches this order (AGL-2232). Above the\n // order write and the payment link, like every other refusal here, so a\n // manager who fixes the tier table and presses Send again strands nothing.\n if (shippingPlan.refusal === 'cart-unpriceable') {\n return res\n .status(409)\n .json({ error: CommerceModel.CART_UNPRICEABLE_SHIPPING_MESSAGE })\n }\n // FREE SHIPPING IS A ZEROED RATE, NOT A REDUCTION (AGL-305), the same\n // construction the cart uses and for the same reason: nothing has picked a\n // rate yet, so there is no amount to take off. The buyer chooses after the\n // link is minted, so the only exact answer is to offer every rate at zero.\n //\n // Every rate rather than the cheapest, because `free_shipping` carries no\n // field naming one — and zeroing them all keeps the fee, the transfer floor\n // and the ceiling below honest, since all three read these same options.\n //\n // Derived from `shippingPlan.options` and read EVERYWHERE below in its\n // place; a reader that reached past this to `shippingPlan.options` would\n // price carriage the buyer is not being charged for.\n const shippingOptions =\n resolvedDiscount?.freeShipping === true\n ? shippingPlan.options.map((option) => ({ ...option, amountCents: 0 }))\n : shippingPlan.options\n\n // THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card\n // cost, passed through at cost, at the CARD rate: the link, like every\n // session a site opens, excludes buy-now-pay-later (AGL-4198). A payment\n // link is a destination charge, so\n // Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only\n // figure meant every tier carrying a 0% rate invoiced a buyer at a loss to\n // Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.\n //\n // `?? 'physical'` (AGL-2251), matching `checkout.ts` and the cart. Without\n // it a product doc carrying no `type` fell to `resolveTransactionFeePct`'s\n // digital branch, so a merchant's payment link took a different cut of the\n // same product than their storefront did.\n //\n // The base is the whole card total: the goods, the manual tax line, and the DEAREST shipping\n // option the link offers (the buyer picks after the link is minted and\n // `application_fee_amount` is fixed at creation, so reaching for the\n // cheapest would put the difference back on Aglyn). A store on Stripe Tax\n // is the one residual — that tax is computed inside Stripe afterwards.\n const shippingCeilingCents = shippingOptions.reduce(\n (most, option) =>\n Math.max(most, Math.max(0, Number(option.amountCents ?? 0))),\n 0,\n )\n // Both bases are the DISCOUNTED goods (AGL-305). The platform take is a\n // cut of what the merchant actually sells for, and Stripe's card cost is\n // passed through on what the card actually runs for — reading `itemsCents`\n // here would invoice the merchant a fee on money nobody paid.\n //\n // A direct charge's fee is the take alone: Stripe bills the seller its\n // own card fee and charges the platform nothing for the sale.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n product.type ?? 'physical',\n chargedItemsCents,\n chargedItemsCents + taxCents + shippingCeilingCents,\n direct ? { direct: true } : { stripeTax: useStripeTax },\n )\n // Stripe Tax mode leaves the tax 0 at composition time and the webhook\n // folds the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const totals = CommerceModel.computeOrderTotals(lineItems, {\n feeCents,\n taxCents,\n // The line item still carries the LIST price, so the discount has to be\n // a named part of the totals or `itemsCents - discountCents + tax` would\n // not be the number on the payment link.\n discountCents: appliedDiscountCents,\n })\n\n // THE LINK CHARGES `chargedItemsCents`, EXACTLY (the AGL-2159 construction,\n // reused here because this path grew the same problem the moment it grew a\n // discount).\n //\n // A Stripe line is `quantity` units at ONE integer `unit_amount`, so it can\n // only express totals divisible by `quantity` — and a percentage discount\n // does not respect that. Dividing and multiplying back misses the intended\n // total by up to `quantity / 2` cents in either direction, which on this\n // path is worse than on buy-now: the frozen `totals` above are written to\n // the order document BEFORE the session is minted, so a link that charged\n // a different number would leave the merchant's own books disagreeing with\n // what their buyer paid, permanently and silently.\n //\n // So when the total does not divide evenly, the line becomes ONE unit at\n // the exact total with the count moved into the display name. The real\n // quantity is carried by the order document's line item, which is\n // untouched, so nothing downstream can tell the difference.\n //\n // The even case — every undiscounted draft, and most discounted ones —\n // keeps the per-unit shape byte for byte.\n const evenUnitAmountCents = Math.floor(chargedItemsCents / quantity)\n const remainderCents = chargedItemsCents - evenUnitAmountCents * quantity\n const chargedQuantity = remainderCents === 0 ? quantity : 1\n const chargedUnitAmountCents =\n remainderCents === 0 ? evenUnitAmountCents : chargedItemsCents\n const chargedLineName = `${product.name}${\n remainderCents === 0 ? '' : ` × ${quantity}`\n }`.slice(0, 120)\n\n // Point of no return (AGL-1697): everything past here writes an order and\n // mints a live payment link. Every deterministic refusal — unknown\n // product, payments not set up, the shipping-destination ask — sits above\n // this line, so none of them burns the key: the merchant fixes the input\n // and presses the same button. Before the claim, a double-submit minted a\n // SECOND order doc, burned a second sequential number, and returned two\n // live payment links bound to different orders, both payable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-draft',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This draft order is already being created',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // THE REDEMPTION SLOT IS RESERVED HERE (AGL-305), on the same terms the\n // storefront doors reserve it.\n //\n // A payment link lives until the buyer pays it, so between this handler and\n // the `commerce-draft` webhook branch that settles the slot there is a\n // window measured in days — far wider than a Checkout Session's. Reading\n // `redemptions` and hoping would let a merchant mint ten links against a\n // cap of one and have all ten pay.\n //\n // BELOW the claim because the hold is keyed by the attempt: a retry of one\n // attempt must be able to re-claim the slot it already holds rather than be\n // refused by it. An uncapped promotion writes nothing and returns an empty\n // `holdKey`, which is what tells the webhook to fall back to the plain\n // increment.\n if (appliedDiscountId) {\n const slot = await holdPromotionSlot({\n firestore,\n ref: hostRef.collection('discounts').doc(appliedDiscountId),\n holdKey: promotionHoldKey(claimed.claim.stripeKey),\n label: `draft discount ${appliedDiscountId}`,\n })\n if (!slot.ok) {\n // Refused rather than quietly repriced, and that is deliberate for the\n // AUTOMATIC case too: the merchant composed this order at a price the\n // promotion was part of, and minting the link at full price would\n // invoice their buyer more than the store advertises without saying so.\n // Nothing has been written yet, so the key goes back and the retry\n // prices correctly — `resolveDiscount` counts live holds and simply\n // stops offering an exhausted promotion.\n await claim.release()\n return res.status(409).json({\n error:\n couponCode && resolvedDiscount?.discount.code\n ? CommerceModel.PROMOTION_EXHAUSTED_MESSAGE\n : CommerceModel.PROMOTION_UNAVAILABLE_MESSAGE,\n })\n }\n if (slot.holdKey) {\n discountSlot = slot\n discountHoldKey = slot.holdKey\n }\n }\n\n // Order doc first (transactional number), then the payment link.\n const orderRef = hostRef.collection('orders').doc()\n const counterRef = hostRef.collection('counters').doc('orders')\n await firestore.runTransaction(async (transaction) => {\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n // With the fields the orders list queries by (AGL-3321).\n transaction.set(orderRef, CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: 'pending',\n channel: 'draft',\n lineItems,\n totals,\n // WHICH TAX REGIME THIS ORDER IS COMPOSED UNDER (AGL-2451), from the\n // decision taken above rather than from the frozen `taxCents` — a\n // Stripe Tax draft freezes 0 there and only the paid session knows the\n // figure, so a mode read back off the amount would call it `none`.\n //\n // Stamped at composition so a draft that is never paid still says what\n // it was priced under, and RESTATED by the `commerce-draft` webhook\n // branch from the session that actually charged it. The webhook's is\n // authoritative — it has Stripe's computed tax in hand — and for a\n // manual draft the two agree by construction.\n taxMode: CommerceModel.storefrontTaxModeForDecision(\n taxDecision,\n taxCents,\n ),\n customerEmail: email || null,\n // WHAT ITS INVOICE'S LASTING PAY LINK CHARGES LATER (AGL-4099). The\n // session below lapses in a day; an invoice for this draft opens a\n // fresh one from the stored order whenever the buyer presses Pay, and\n // offers the same shipping rates this link does, and counts the same\n // promotion once paid. Stored even when there are no rates, so an\n // invoice can tell \"ships nothing\" from a draft made before this.\n draftShipping: {\n countries: shippingOptions.length > 0 ? Array.from(shippingPlan.countries ?? []) : [],\n options: shippingOptions.map((option) => ({\n rateId: String(option.rateId ?? ''),\n name: String(option.name ?? ''),\n amountCents: Math.max(0, Math.round(Number(option.amountCents ?? 0))),\n })),\n },\n ...(appliedDiscountId ? { discountId: appliedDiscountId } : {}),\n timeline: [\n {\n atMs: Date.now(),\n event: 'draft',\n detail: `Draft created by ${decoded.email ?? decoded.uid}`,\n },\n ],\n createdAtMs: Date.now(),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }))\n })\n\n // The tax rate is minted here, BELOW the claim, because it creates a real\n // Stripe object (AGL-1953). Cached per host, so it is usually a read.\n let draftTaxRateId = ''\n if (taxCents > 0 && manualRate) {\n draftTaxRateId =\n (await resolveManualTaxRateId({\n hostRef,\n taxPct: manualRate.pct,\n taxLabel: manualRate.label || `Tax (${manualRate.pct}%)`,\n ...(claim.stripeKey\n ? { headers: { 'Idempotency-Key': `${claim.stripeKey}-tax-rate` } }\n : {}),\n // A platform rate id does not resolve on the seller's account.\n ...(onAccount['Stripe-Account']\n ? { stripeAccount: onAccount['Stripe-Account'] }\n : {}),\n })) ?? ''\n if (!draftTaxRateId) {\n // A VISIBLE refusal rather than an untaxed payment link — the silent\n // under-collection is the defect. The order doc is rolled back the\n // same way the session failure below rolls it back.\n await orderRef.delete().catch(() => undefined)\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n }\n // The buyer's way back, on the business's site: the order's status page\n // (which reads the paid state from the server) and the site's home.\n const siteData = hostSnapshot.data() as { cname?: unknown; subdomain?: unknown } | undefined\n const buyerStatusUrl = orderStatusUrl(siteData, hostId, orderRef.id)\n const buyerSiteUrl = buyerStatusUrl ? `${new URL(buyerStatusUrl).origin}/` : ''\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(useStripeTax ? { 'automatic_tax[enabled]': 'true' } : {}),\n ...(draftTaxRateId ? { 'line_items[0][tax_rates][0]': draftTaxRateId } : {}),\n 'line_items[0][quantity]': String(chargedQuantity),\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),\n 'line_items[0][price_data][product_data][name]': chargedLineName,\n // THE CONNECT SPLIT (AGL-1956). A Stripe Tax payment link computes its\n // tax against AGLYN's registrations and Aglyn remits it (AGL-1904), so\n // the merchant gets a FIXED `transfer_data[amount]` and no\n // `application_fee_amount`: the fee form transfers `amount_total − fee`,\n // and `amount_total` includes that tax. A manual-rate or untaxed link is\n // unchanged. See `commerce-connect-transfer.ts`.\n //\n // A DIRECT charge is the seller's money from the start, its Stripe Tax\n // computed on the seller's own registrations and owed by them, so the\n // take is the whole split and nothing is transferred.\n ...(direct\n ? directChargeParams(feeCents)\n : CommerceModel.destinationChargeParams({\n accountId: String(accountId),\n feeCents,\n taxOwner: useStripeTax ? 'platform' : 'merchant',\n // The DISCOUNTED goods (AGL-305): this is what the merchant is\n // transferred, and paying out the list price on a discounted link\n // would move money Stripe never collected.\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents: CommerceModel.shippingFloorCents(shippingOptions),\n })),\n ...(email ? { customer_email: email } : {}),\n success_url: buyerStatusUrl ?? `${consoleProductsUrl}?draft=paid`,\n cancel_url: buyerSiteUrl || `${consoleProductsUrl}?draft=canceled`,\n 'metadata[type]': 'commerce-draft',\n 'metadata[hostId]': hostId,\n 'metadata[orderId]': orderRef.id,\n 'metadata[productId]': productId,\n ...(variantId ? { 'metadata[variantId]': variantId } : {}),\n 'metadata[feeCents]': String(feeCents),\n // What the webhook, refunds and reports read to find the payment on\n // the seller's account rather than the platform's.\n ...(direct ? { 'metadata[chargeModel]': 'direct' } : {}),\n ...(shippingPlan.quotedPostalCode\n ? { 'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode }\n : {}),\n // WHAT THE WEBHOOK SETTLES (AGL-305), in the field names the\n // `checkout.session.completed` branch already reads for the cart. The\n // hold key's ABSENCE is what tells it to fall back to the unconditional\n // increment, which is right for an uncapped promotion.\n ...(appliedDiscountId\n ? { 'metadata[discountId]': appliedDiscountId }\n : {}),\n ...(discountHoldKey ? { 'metadata[discountHoldKey]': discountHoldKey } : {}),\n // See the AGL-1956 note in `checkout.ts` — recorded only on the shape\n // where the merchant's payout is no longer the whole charge, which a\n // direct charge never is.\n ...(useStripeTax && !direct\n ? {\n 'metadata[transferCents]': String(\n CommerceModel.platformLiableTransferCents({\n feeCents,\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents:\n CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ),\n 'metadata[transferShippingCents]': String(\n CommerceModel.shippingFloorCents(shippingOptions),\n ),\n }\n : {}),\n })\n // Both keys or neither (AGL-1720's rule, inherited). Stripe will not apply\n // a shipping rate without an address to ship to, and a merchant who\n // configured nothing plans to no options and so gets neither — a payment\n // link byte-identical to the one this handler built before shipping\n // existed on it.\n if (shippingOptions.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n shippingPlan.countries,\n )\n CommerceModel.appendCheckoutShippingParams(params, shippingOptions)\n }\n // The payment methods the merchant switched off reach the payment link\n // too (AGL-3629). A hosted Stripe page shows Apple Pay and Google Pay by\n // device and cannot hide them per merchant; everything else follows.\n // Buy-now-pay-later is excluded too, whatever the store chose (AGL-4198).\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSettings.get('paymentMethods'),\n ),\n ),\n )\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that is a live payment link (AGL-1697). Stripe replays\n // the existing session for a repeated key instead of opening a\n // second one on the merchant's account, which covers the window\n // where our claim is written but the response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n ...onAccount,\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as {\n url?: string\n id?: string\n error?: any\n }\n if (!response.ok || !session.url) {\n console.error('Stripe draft-order error', session.error)\n await orderRef.delete().catch(() => undefined)\n // The draft did not happen — hand the key back rather than locking this\n // dialog out over one flaky moment. The retry re-derives the SAME\n // digest, so if Stripe did create the session it replays it.\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n await orderRef.set(\n { checkoutSessionId: session.id, paymentLinkUrl: session.url },\n { merge: true },\n )\n // Spread on the same terms as the register's: present only when there is\n // something to say, so a caller can test the key rather than a length.\n const payload = {\n orderId: orderRef.id,\n url: session.url,\n ...(stockWarnings.length > 0 ? { stockWarnings } : {}),\n }\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // (AGL-1691's rule). The order write may or may not have landed; the\n // merchant reconciles from the orders list, the same position they were\n // in before this endpoint had a claim at all. The redemption slot goes\n // back for the same reason — a throw is the one path that would otherwise\n // leave it standing against the cap until its TTL lapsed.\n await releaseDiscountSlot()\n await claim?.release()\n return res.status(500).json({ error: 'Draft order failed' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","planCheckoutShippingWithCarriers","resolveManualTaxRateId","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","orderStatusUrl","holdPromotionSlot","promotionHoldKey","buildRoute","claimAttempt","Route","draftOrderHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","productId","variantId","quantity","Math","max","min","round","Number","email","trim","couponCode","idempotencyKey","claim","discountSlot","discountHoldKey","releaseDiscountSlot","slot","release","storeSettings","taxSettings","product","variant","ownerOrg","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","productSnapshot","raw","data","deletedAt","liftLegacyProduct","variants","find","item","id","variantHasPrice","name","checkEntitlement","org","ownerId","ownerUid","ownerProfile","accountId","chargesEnabled","accountLivemode","subject","chargeModel","direct","onAccount","consoleSubdomain","consoleOrgSlug","slug","origin","host","consoleProductsUrl","HOST_PLUGIN","orgSlug","pluginSlug","shortfall","stockShortfall","stockWarnings","requested","available","unitAmountCents","priceUsd","lineItems","sku","productType","type","itemsCents","draftDiscountLines","amountCents","hubDiscounts","limit","resolvedDiscount","resolveDiscount","docs","map","docSnapshot","$id","code","subtotalCents","productIds","lines","codeProblem","appliedDiscountId","benefit","kind","discountId","discountCents","chargedItemsCents","appliedDiscountCents","shippingSettings","taxDecision","storefrontTaxDecision","settings","taxExempt","STOREFRONT_TAX_UNDECIDED_MESSAGE","taxMisconfigured","storefrontTaxMisconfiguration","useStripeTax","manualRate","pricesIncludeTax","resolveTaxRate","taxCents","computeTaxCents","pct","shippingPlan","cart","totalGrams","weightGrams","parcel","productParcelDimensions","destination","country","shippingCountry","postalCode","shippingPostalCode","countries","CHECKOUT_SHIPPING_COUNTRIES","options","needsPostalCode","needsShippingCountry","needsShippingPostalCode","shippingCountries","refusal","declared","normalizeCheckoutShippingCountry","CHECKOUT_SHIPPING_COUNTRY_NAMES","CART_UNPRICEABLE_SHIPPING_MESSAGE","shippingOptions","freeShipping","option","shippingCeilingCents","reduce","most","feeCents","resolveTransactionFeeCents","stripeTax","totals","computeOrderTotals","evenUnitAmountCents","floor","remainderCents","chargedQuantity","chargedUnitAmountCents","chargedLineName","claimed","scopeId","orgId","key","busyMessage","replay","ref","holdKey","stripeKey","label","ok","discount","PROMOTION_EXHAUSTED_MESSAGE","PROMOTION_UNAVAILABLE_MESSAGE","orderRef","counterRef","runTransaction","transaction","counter","number","set","next","merge","withOrderListFields","channel","taxMode","storefrontTaxModeForDecision","customerEmail","draftShipping","Array","from","rateId","timeline","atMs","Date","now","event","detail","createdAtMs","createdAt","FieldValue","serverTimestamp","draftTaxRateId","taxPct","taxLabel","stripeAccount","delete","catch","siteData","buyerStatusUrl","buyerSiteUrl","URL","params","URLSearchParams","mode","destinationChargeParams","taxOwner","merchantGoodsCents","shippingFloorCents","customer_email","success_url","cancel_url","quotedPostalCode","platformLiableTransferCents","appendShippingAddressCollectionParams","appendCheckoutShippingParams","appendStorefrontPaymentMethodParams","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","toString","session","url","console","checkoutSessionId","paymentLinkUrl","payload","orderId","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAo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CAAC,KAAKF;QACxB,OAAO9P,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC0P;IAC9B,EAAE,OAAOzP,OAAO;QACdsP,QAAQtP,KAAK,CAACA;QACd,wEAAwE;QACxE,qEAAqE;QACrE,wEAAwE;QACxE,uEAAuE;QACvE,0EAA0E;QAC1E,0DAA0D;QAC1D,MAAM8B;QACN,OAAMH,yBAAAA,MAAOK,OAAO;QACpB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
@@ -65,9 +65,10 @@
65
65
  * and for every current caller it is a visible 502 rather than a silent
66
66
  * untaxed sale.
67
67
  *
68
- * The rate is created on the PLATFORM account (no `Stripe-Account` header),
69
- * matching the session calls, because that is where the session lives — a
70
- * connected-account rate id would not resolve. Tax rates are immutable, so one
68
+ * The rate is created on the account the session lives on: the PLATFORM for
69
+ * a destination charge (no `Stripe-Account` header), the seller's own account
70
+ * for a direct charge (`stripeAccount`). A rate id from the other account
71
+ * would not resolve. Tax rates are immutable, so one
71
72
  * object exists per (percentage, label): a merchant who edits their zone rate
72
73
  * misses the cache and mints a fresh one, while the old object stays behind on
73
74
  * everything already carrying it, exactly as it should.
@@ -79,4 +80,11 @@ export declare function resolveManualTaxRateId(options: {
79
80
  taxLabel: string;
80
81
  /** Per-object idempotency header, derived by the caller (AGL-1714). */
81
82
  headers?: Record<string, string>;
83
+ /**
84
+ * The seller's connected account when the sale is a DIRECT charge: the
85
+ * session lives on that account, so the rate has to be minted there, and it
86
+ * is cached apart from the platform's rates because an id from one account
87
+ * never resolves on another.
88
+ */
89
+ stripeAccount?: string;
82
90
  }): Promise<string | null>;
@@ -64,20 +64,22 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
64
64
  * and for every current caller it is a visible 502 rather than a silent
65
65
  * untaxed sale.
66
66
  *
67
- * The rate is created on the PLATFORM account (no `Stripe-Account` header),
68
- * matching the session calls, because that is where the session lives — a
69
- * connected-account rate id would not resolve. Tax rates are immutable, so one
67
+ * The rate is created on the account the session lives on: the PLATFORM for
68
+ * a destination charge (no `Stripe-Account` header), the seller's own account
69
+ * for a direct charge (`stripeAccount`). A rate id from the other account
70
+ * would not resolve. Tax rates are immutable, so one
70
71
  * object exists per (percentage, label): a merchant who edits their zone rate
71
72
  * misses the cache and mints a fresh one, while the old object stays behind on
72
73
  * everything already carrying it, exactly as it should.
73
74
  */ export async function resolveManualTaxRateId(options) {
74
- var _cached_get;
75
+ var _options_stripeAccount, _cached_get;
75
76
  const { hostRef, taxPct, taxLabel, headers = {} } = options;
77
+ const stripeAccount = String((_options_stripeAccount = options.stripeAccount) != null ? _options_stripeAccount : '').trim();
76
78
  if (!(taxPct > 0)) return null;
77
79
  // ≤4 decimal places, which is all Stripe accepts on a tax rate.
78
80
  const percentage = Math.round(taxPct * 10000) / 10000;
79
81
  const displayLabel = (taxLabel || `Tax (${percentage}%)`).slice(0, 50);
80
- const cacheKey = `p${Math.round(percentage * 10000)}-${encodeURIComponent(displayLabel)}`;
82
+ const cacheKey = `${stripeAccount ? `${stripeAccount}-` : ''}p${Math.round(percentage * 10000)}-${encodeURIComponent(displayLabel)}`;
81
83
  const cacheRef = hostRef.collection('stripeTaxRates').doc(cacheKey);
82
84
  const cached = await cacheRef.get();
83
85
  const cachedId = String((_cached_get = cached.get('taxRateId')) != null ? _cached_get : '');
@@ -87,7 +89,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
87
89
  headers: _extends({
88
90
  Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
89
91
  'Content-Type': 'application/x-www-form-urlencoded'
90
- }, headers),
92
+ }, headers, stripeAccount ? {
93
+ 'Stripe-Account': stripeAccount
94
+ } : {}),
91
95
  body: new URLSearchParams({
92
96
  display_name: displayLabel,
93
97
  percentage: String(percentage),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/manual-tax-rate.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\n/**\n * A merchant's `manual`-mode tax as a real Stripe Tax Rate (AGL-1953).\n *\n * ## Why this exists as its own module\n *\n * AGL-1751 built exactly this — mint a Tax Rate on the platform account, cache\n * it under the host — inline in `checkout.ts`, for subscriptions. AGL-1953\n * needed the same thing for the cart and draft-order paths, and a second copy\n * of a money-shaped cache is how two paths quietly diverge. One implementation,\n * three callers.\n *\n * ## Why a TAX RATE and not another line item\n *\n * Buy-now's one-time construction (AGL-1711) appends the tax as an ordinary\n * `line_items[1]` product line Stripe is never told is tax. That works there\n * because buy-now prices its discount INTO the unit amount, so nothing at\n * session level can touch the tax line afterwards.\n *\n * **The cart cannot use it.** The cart applies its discounts, coupons and gift\n * cards as real Stripe coupons at `discounts[0][coupon]`, and a session-level\n * coupon is spread across every line — including a fake tax line. The tax would\n * be discounted along with the goods, and the `metadata[taxCents]` snapshot\n * would then over-state what was actually collected.\n *\n * A real tax rate is applied by Stripe AFTER the discount, which is the\n * behaviour we want and which was MEASURED rather than assumed. Test mode, a\n * $100.00 line carrying an 8.25% rate plus a $30.00 `amount_off` coupon:\n *\n * amount_subtotal 10000, amount_discount 3000, **amount_tax 578**,\n * breakdown.taxes[0].taxable_amount **7000**\n *\n * 578 is 8.25% of the discounted 7000, not of the 10000 subtotal. Stripe\n * discounts first and taxes the remainder, so the arithmetic stays right with\n * no snapshot to keep in step — and `total_details.amount_tax` becomes a real\n * field, so the order's own decomposition needs no metadata witness at all.\n *\n * ## This does NOT make the sale Stripe Tax\n *\n * `automatic_tax.enabled` stays `false` (confirmed on the same measured\n * session), which is the discriminator `storefront-tax.ts` reads. A rate minted\n * here is the merchant's own configured percentage against their own declared\n * origin; Aglyn's registrations never enter into it and the money is not\n * Aglyn's to remit. Reading tax-LINE presence instead of the flag would book\n * this as Aglyn-collected, which is the AGL-1904 trap stated in that module.\n */\n\n/**\n * The rate id for (percentage, label) on this host, minting and caching one on\n * first use. `null` means Stripe refused — the caller decides what that costs,\n * and for every current caller it is a visible 502 rather than a silent\n * untaxed sale.\n *\n * The rate is created on the PLATFORM account (no `Stripe-Account` header),\n * matching the session calls, because that is where the session lives — a\n * connected-account rate id would not resolve. Tax rates are immutable, so one\n * object exists per (percentage, label): a merchant who edits their zone rate\n * misses the cache and mints a fresh one, while the old object stays behind on\n * everything already carrying it, exactly as it should.\n */\nexport async function resolveManualTaxRateId(options: {\n /** `hosts/{hostId}` — the cache lives under it. */\n hostRef: any\n taxPct: number\n taxLabel: string\n /** Per-object idempotency header, derived by the caller (AGL-1714). */\n headers?: Record<string, string>\n}): Promise<string | null> {\n const { hostRef, taxPct, taxLabel, headers = {} } = options\n if (!(taxPct > 0)) return null\n // ≤4 decimal places, which is all Stripe accepts on a tax rate.\n const percentage = Math.round(taxPct * 10000) / 10000\n const displayLabel = (taxLabel || `Tax (${percentage}%)`).slice(0, 50)\n const cacheKey = `p${Math.round(percentage * 10000)}-${encodeURIComponent(\n displayLabel,\n )}`\n const cacheRef = hostRef.collection('stripeTaxRates').doc(cacheKey)\n const cached = await cacheRef.get()\n const cachedId = String(cached.get('taxRateId') ?? '')\n if (cachedId) return cachedId\n\n const response = await fetch('https://api.stripe.com/v1/tax_rates', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: new URLSearchParams({\n display_name: displayLabel,\n percentage: String(percentage),\n inclusive: 'false',\n }).toString(),\n })\n const taxRate = (await response.json()) as { id?: string; error?: any }\n if (!response.ok || !taxRate.id) {\n console.error('Stripe tax rate error', taxRate.error)\n return null\n }\n // Best-effort: the rate exists either way, and two concurrent misses racing\n // this write just means one orphan rate on the dashboard.\n await cacheRef\n .set({\n taxRateId: String(taxRate.id),\n pct: percentage,\n label: displayLabel,\n createdAtMs: Date.now(),\n })\n .catch(() => undefined)\n return String(taxRate.id)\n}\n"],"names":["resolveManualTaxRateId","options","cached","hostRef","taxPct","taxLabel","headers","percentage","Math","round","displayLabel","slice","cacheKey","encodeURIComponent","cacheRef","collection","doc","get","cachedId","String","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","body","URLSearchParams","display_name","inclusive","toString","taxRate","json","ok","id","console","error","set","taxRateId","pct","label","createdAtMs","Date","now","catch","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GAED;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeA,uBAAuBC,OAO5C;QAWyBC;IAVxB,MAAM,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,UAAU,CAAC,CAAC,EAAE,GAAGL;IACpD,IAAI,CAAEG,CAAAA,SAAS,CAAA,GAAI,OAAO;IAC1B,gEAAgE;IAChE,MAAMG,aAAaC,KAAKC,KAAK,CAACL,SAAS,SAAS;IAChD,MAAMM,eAAe,AAACL,CAAAA,YAAY,CAAC,KAAK,EAAEE,WAAW,EAAE,CAAC,AAAD,EAAGI,KAAK,CAAC,GAAG;IACnE,MAAMC,WAAW,CAAC,CAAC,EAAEJ,KAAKC,KAAK,CAACF,aAAa,OAAO,CAAC,EAAEM,mBACrDH,eACC;IACH,MAAMI,WAAWX,QAAQY,UAAU,CAAC,kBAAkBC,GAAG,CAACJ;IAC1D,MAAMV,SAAS,MAAMY,SAASG,GAAG;IACjC,MAAMC,WAAWC,QAAOjB,cAAAA,OAAOe,GAAG,CAAC,wBAAXf,cAA2B;IACnD,IAAIgB,UAAU,OAAOA;IAErB,MAAME,WAAW,MAAMC,MAAM,uCAAuC;QAClEC,QAAQ;QACRhB,SAAS;YACPiB,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;YACxD,gBAAgB;WACbpB;QAELqB,MAAM,IAAIC,gBAAgB;YACxBC,cAAcnB;YACdH,YAAYY,OAAOZ;YACnBuB,WAAW;QACb,GAAGC,QAAQ;IACb;IACA,MAAMC,UAAW,MAAMZ,SAASa,IAAI;IACpC,IAAI,CAACb,SAASc,EAAE,IAAI,CAACF,QAAQG,EAAE,EAAE;QAC/BC,QAAQC,KAAK,CAAC,yBAAyBL,QAAQK,KAAK;QACpD,OAAO;IACT;IACA,4EAA4E;IAC5E,0DAA0D;IAC1D,MAAMvB,SACHwB,GAAG,CAAC;QACHC,WAAWpB,OAAOa,QAAQG,EAAE;QAC5BK,KAAKjC;QACLkC,OAAO/B;QACPgC,aAAaC,KAAKC,GAAG;IACvB,GACCC,KAAK,CAAC,IAAMC;IACf,OAAO3B,OAAOa,QAAQG,EAAE;AAC1B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/manual-tax-rate.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\n/**\n * A merchant's `manual`-mode tax as a real Stripe Tax Rate (AGL-1953).\n *\n * ## Why this exists as its own module\n *\n * AGL-1751 built exactly this — mint a Tax Rate on the platform account, cache\n * it under the host — inline in `checkout.ts`, for subscriptions. AGL-1953\n * needed the same thing for the cart and draft-order paths, and a second copy\n * of a money-shaped cache is how two paths quietly diverge. One implementation,\n * three callers.\n *\n * ## Why a TAX RATE and not another line item\n *\n * Buy-now's one-time construction (AGL-1711) appends the tax as an ordinary\n * `line_items[1]` product line Stripe is never told is tax. That works there\n * because buy-now prices its discount INTO the unit amount, so nothing at\n * session level can touch the tax line afterwards.\n *\n * **The cart cannot use it.** The cart applies its discounts, coupons and gift\n * cards as real Stripe coupons at `discounts[0][coupon]`, and a session-level\n * coupon is spread across every line — including a fake tax line. The tax would\n * be discounted along with the goods, and the `metadata[taxCents]` snapshot\n * would then over-state what was actually collected.\n *\n * A real tax rate is applied by Stripe AFTER the discount, which is the\n * behaviour we want and which was MEASURED rather than assumed. Test mode, a\n * $100.00 line carrying an 8.25% rate plus a $30.00 `amount_off` coupon:\n *\n * amount_subtotal 10000, amount_discount 3000, **amount_tax 578**,\n * breakdown.taxes[0].taxable_amount **7000**\n *\n * 578 is 8.25% of the discounted 7000, not of the 10000 subtotal. Stripe\n * discounts first and taxes the remainder, so the arithmetic stays right with\n * no snapshot to keep in step — and `total_details.amount_tax` becomes a real\n * field, so the order's own decomposition needs no metadata witness at all.\n *\n * ## This does NOT make the sale Stripe Tax\n *\n * `automatic_tax.enabled` stays `false` (confirmed on the same measured\n * session), which is the discriminator `storefront-tax.ts` reads. A rate minted\n * here is the merchant's own configured percentage against their own declared\n * origin; Aglyn's registrations never enter into it and the money is not\n * Aglyn's to remit. Reading tax-LINE presence instead of the flag would book\n * this as Aglyn-collected, which is the AGL-1904 trap stated in that module.\n */\n\n/**\n * The rate id for (percentage, label) on this host, minting and caching one on\n * first use. `null` means Stripe refused — the caller decides what that costs,\n * and for every current caller it is a visible 502 rather than a silent\n * untaxed sale.\n *\n * The rate is created on the account the session lives on: the PLATFORM for\n * a destination charge (no `Stripe-Account` header), the seller's own account\n * for a direct charge (`stripeAccount`). A rate id from the other account\n * would not resolve. Tax rates are immutable, so one\n * object exists per (percentage, label): a merchant who edits their zone rate\n * misses the cache and mints a fresh one, while the old object stays behind on\n * everything already carrying it, exactly as it should.\n */\nexport async function resolveManualTaxRateId(options: {\n /** `hosts/{hostId}` — the cache lives under it. */\n hostRef: any\n taxPct: number\n taxLabel: string\n /** Per-object idempotency header, derived by the caller (AGL-1714). */\n headers?: Record<string, string>\n /**\n * The seller's connected account when the sale is a DIRECT charge: the\n * session lives on that account, so the rate has to be minted there, and it\n * is cached apart from the platform's rates because an id from one account\n * never resolves on another.\n */\n stripeAccount?: string\n}): Promise<string | null> {\n const { hostRef, taxPct, taxLabel, headers = {} } = options\n const stripeAccount = String(options.stripeAccount ?? '').trim()\n if (!(taxPct > 0)) return null\n // ≤4 decimal places, which is all Stripe accepts on a tax rate.\n const percentage = Math.round(taxPct * 10000) / 10000\n const displayLabel = (taxLabel || `Tax (${percentage}%)`).slice(0, 50)\n const cacheKey = `${stripeAccount ? `${stripeAccount}-` : ''}p${Math.round(\n percentage * 10000,\n )}-${encodeURIComponent(displayLabel)}`\n const cacheRef = hostRef.collection('stripeTaxRates').doc(cacheKey)\n const cached = await cacheRef.get()\n const cachedId = String(cached.get('taxRateId') ?? '')\n if (cachedId) return cachedId\n\n const response = await fetch('https://api.stripe.com/v1/tax_rates', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n ...(stripeAccount ? { 'Stripe-Account': stripeAccount } : {}),\n },\n body: new URLSearchParams({\n display_name: displayLabel,\n percentage: String(percentage),\n inclusive: 'false',\n }).toString(),\n })\n const taxRate = (await response.json()) as { id?: string; error?: any }\n if (!response.ok || !taxRate.id) {\n console.error('Stripe tax rate error', taxRate.error)\n return null\n }\n // Best-effort: the rate exists either way, and two concurrent misses racing\n // this write just means one orphan rate on the dashboard.\n await cacheRef\n .set({\n taxRateId: String(taxRate.id),\n pct: percentage,\n label: displayLabel,\n createdAtMs: Date.now(),\n })\n .catch(() => undefined)\n return String(taxRate.id)\n}\n"],"names":["resolveManualTaxRateId","options","cached","hostRef","taxPct","taxLabel","headers","stripeAccount","String","trim","percentage","Math","round","displayLabel","slice","cacheKey","encodeURIComponent","cacheRef","collection","doc","get","cachedId","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","body","URLSearchParams","display_name","inclusive","toString","taxRate","json","ok","id","console","error","set","taxRateId","pct","label","createdAtMs","Date","now","catch","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GAED;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeA,uBAAuBC,OAc5C;QAE8BA,wBAULC;IAXxB,MAAM,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,UAAU,CAAC,CAAC,EAAE,GAAGL;IACpD,MAAMM,gBAAgBC,QAAOP,yBAAAA,QAAQM,aAAa,YAArBN,yBAAyB,IAAIQ,IAAI;IAC9D,IAAI,CAAEL,CAAAA,SAAS,CAAA,GAAI,OAAO;IAC1B,gEAAgE;IAChE,MAAMM,aAAaC,KAAKC,KAAK,CAACR,SAAS,SAAS;IAChD,MAAMS,eAAe,AAACR,CAAAA,YAAY,CAAC,KAAK,EAAEK,WAAW,EAAE,CAAC,AAAD,EAAGI,KAAK,CAAC,GAAG;IACnE,MAAMC,WAAW,GAAGR,gBAAgB,GAAGA,cAAc,CAAC,CAAC,GAAG,GAAG,CAAC,EAAEI,KAAKC,KAAK,CACxEF,aAAa,OACb,CAAC,EAAEM,mBAAmBH,eAAe;IACvC,MAAMI,WAAWd,QAAQe,UAAU,CAAC,kBAAkBC,GAAG,CAACJ;IAC1D,MAAMb,SAAS,MAAMe,SAASG,GAAG;IACjC,MAAMC,WAAWb,QAAON,cAAAA,OAAOkB,GAAG,CAAC,wBAAXlB,cAA2B;IACnD,IAAImB,UAAU,OAAOA;IAErB,MAAMC,WAAW,MAAMC,MAAM,uCAAuC;QAClEC,QAAQ;QACRlB,SAAS;YACPmB,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;YACxD,gBAAgB;WACbtB,SACCC,gBAAgB;YAAE,kBAAkBA;QAAc,IAAI,CAAC;QAE7DsB,MAAM,IAAIC,gBAAgB;YACxBC,cAAclB;YACdH,YAAYF,OAAOE;YACnBsB,WAAW;QACb,GAAGC,QAAQ;IACb;IACA,MAAMC,UAAW,MAAMZ,SAASa,IAAI;IACpC,IAAI,CAACb,SAASc,EAAE,IAAI,CAACF,QAAQG,EAAE,EAAE;QAC/BC,QAAQC,KAAK,CAAC,yBAAyBL,QAAQK,KAAK;QACpD,OAAO;IACT;IACA,4EAA4E;IAC5E,0DAA0D;IAC1D,MAAMtB,SACHuB,GAAG,CAAC;QACHC,WAAWjC,OAAO0B,QAAQG,EAAE;QAC5BK,KAAKhC;QACLiC,OAAO9B;QACP+B,aAAaC,KAAKC,GAAG;IACvB,GACCC,KAAK,CAAC,IAAMC;IACf,OAAOxC,OAAO0B,QAAQG,EAAE;AAC1B"}
@@ -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,wBAAwB,QACnB,uCAAmC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4FC,GAED;;;CAGC,GACD,OAAO,MAAMC,iCAAiC,oBAAmB;AAEjE,wEAAwE,GACxE,OAAO,MAAMC,uBAAuB,0BAAkC;AAStE;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,eAAeC,0BACpBC,KAAgC;QAG9BC;IADF,MAAMC,iBAAiBC,QACrBF,kDAAAA,QAAQG,GAAG,CAACC,kCAAkC,YAA9CJ,kDAAkD,IAClDK,IAAI;IACN,IAAI,CAACJ,gBAAgB,OAAO;QAAEK,QAAQ;QAAOL,gBAAgB;IAAG;IAChE,6EAA6E;IAC7E,sEAAsE;IACtE,mEAAmE;IACnE,2EAA2E;IAC3E,8EAA8E;IAC9E,0EAA0E;IAC1E,IAAIM;IACJ,IAAI;QACFA,KAAK,MAAMb,4BAA4BG,sBAAsBE,gBAAAA,QAAS;IACxE,EAAE,eAAM;QACN,OAAO;YAAEO,QAAQ;YAAOL,gBAAgB;QAAG;IAC7C;IACA,OAAOM,KAAK;QAAED,QAAQ;QAAML;IAAe,IAAI;QAAEK,QAAQ;QAAOL,gBAAgB;IAAG;AACrF;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASO,0BACdC,MAAuB,EACvBC,SAAiB;IAEjBD,OAAOE,MAAM,CAAC;IACdF,OAAOE,MAAM,CAAC;IACdF,OAAOG,GAAG,CAAC,WAAW;IACtBH,OAAOG,GAAG,CAAC,cAAcF;IACzB,0EAA0E;IAC1E,2EAA2E;IAC3E,yDAAyD;IACzD,IAAID,OAAOI,GAAG,CAAC,YAAY,gBAAgB;QACzCJ,OAAOG,GAAG,CAAC,yCAAyC;IACtD;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,4BACdC,IAAwB;IAExB,OAAOA,KAAKT,MAAM,GACd;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4FC,GAED;;;CAGC,GACD,OAAO,MAAMC,iCAAiC,oBAAmB;AAEjE,wEAAwE,GACxE,OAAO,MAAMC,uBAAuB,0BAAkC;AAStE;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,eAAeC,0BACpBC,KAAgC;QAG9BC;IADF,MAAMC,iBAAiBC,QACrBF,kDAAAA,QAAQG,GAAG,CAACC,kCAAkC,YAA9CJ,kDAAkD,IAClDK,IAAI;IACN,IAAI,CAACJ,gBAAgB,OAAO;QAAEK,QAAQ;QAAOL,gBAAgB;IAAG;IAChE,6EAA6E;IAC7E,sEAAsE;IACtE,mEAAmE;IACnE,2EAA2E;IAC3E,8EAA8E;IAC9E,0EAA0E;IAC1E,IAAIM;IACJ,IAAI;QACFA,KAAK,MAAMb,4BAA4BG,sBAAsBE,gBAAAA,QAAS;IACxE,EAAE,eAAM;QACN,OAAO;YAAEO,QAAQ;YAAOL,gBAAgB;QAAG;IAC7C;IACA,OAAOM,KAAK;QAAED,QAAQ;QAAML;IAAe,IAAI;QAAEK,QAAQ;QAAOL,gBAAg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