@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/storefront-tax-record.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { storefrontTaxRow, type StorefrontTaxRow } from './storefront-tax'\n\n/**\n * Writes `storefrontTaxCollected/{stripeId}` for every storefront sale that\n * carried tax (AGL-1904) — the row that makes tax collected under Aglyn's\n * registration visible to Aglyn's own quarterly return.\n *\n * ## The hole this closes\n *\n * AGL-1811 records one `platformRevenue` row per paid invoice and the Texas\n * return is their sum. That collection is deliberately scoped to AGLYN's own\n * charges: the console webhook only writes a row when the invoice's customer\n * resolves through the `stripeCustomers` index, which `writeOrgBilling` stamps\n * for Aglyn's billing customers and nothing else stamps. A storefront\n * shopper's customer is never in it.\n *\n * That scoping is correct for what it was built for and it left a gap: a\n * `mode: 'stripe'` storefront sale charges the shopper tax computed on\n * AGLYN's registrations (measured — see `storefront-tax.ts`), settles it into\n * Aglyn's platform balance, and NOTHING recorded it anywhere Aglyn's return\n * could see. The merchant's order document carries a `totals.taxCents`, but\n * that is the merchant's books, per host, and no return sums it.\n *\n * ## Why a SEPARATE collection rather than more `platformRevenue` rows\n *\n * Structural, and the reason must survive a future tidy-up: a\n * `platformRevenue` row's `netCents` is Aglyn's revenue, and a storefront\n * row's is mostly the MERCHANT's — it transfers straight out to the connected\n * account. Merging the two would make the return's \"total sales\" figure silently\n * include other companies' receipts. Keeping them in different collections\n * means no query, sum or future refactor can accidentally add them together;\n * the return reports the storefront figures as their own section, and what\n * belongs on which line of a filed return stays a question for the preparer\n * and for counsel rather than one this code answers.\n *\n * ## What is recorded, and what is not\n *\n * Recorded: cart, buy-now, reservation and draft-order sessions, plus every\n * storefront subscription INVOICE (opening cycle and renewals both — the\n * subscription's own `checkout.session.completed` is deliberately skipped so\n * the opening cycle is not counted twice, the same rule AGL-1811 applies).\n *\n * Manual-mode sales are recorded too, with `taxMode: 'manual'`, precisely so\n * the two modes can be told apart at read time instead of being invisible.\n * They are NOT Aglyn-collected and the return never sums them into the\n * Aglyn-liable figure.\n *\n * **Refunds are not yet reflected.** A refunded storefront sale keeps its full\n * tax on this record, so the Aglyn-liable figure is an OVER-statement of what\n * is owed rather than an under-statement. That direction is deliberate:\n * over-stating what is held for the state is correctable at filing time,\n * under-stating it is a shortfall discovered by an auditor. Stated here rather\n * than left to be discovered.\n *\n * Never throws. A recording failure logs and returns — a throw here propagates\n * through `runBillingWebhookHandlers` into a 500 that Stripe redelivers\n * forever, which is the AGL-1743 lesson.\n */\n\n/** The commerce session types that settle money on the platform account. */\nconst SESSION_TYPES = new Set([\n 'commerce-cart',\n 'commerce-order',\n 'commerce-reservation',\n 'commerce-draft',\n // A paid service booking (AGL-2000). It carries no tax by a stated\n // decision (`bookings/server.ts`), but it is a storefront sale and it was\n // absent from this set entirely — so it was not merely untaxed, it did not\n // appear in the record that would let anyone NOTICE it was untaxed or\n // reconcile it later. An untaxed sale that is recorded reads\n // `taxMode: 'none'`; an unrecorded one reads as nothing at all.\n 'booking-payment',\n])\n\n/**\n * Session types whose zero tax is a decision taken HERE, not by the merchant\n * (AGL-2000). Their rows are filed even at `taxMode: 'none'`, so an untaxed\n * service or stay is reconcilable instead of merely missing. See the note at\n * the `taxMode === 'none'` gate below.\n */\nconst PLATFORM_UNTAXED_TYPES = new Set(['booking-payment', 'commerce-reservation'])\n\nfunction stripeKey(): string {\n return String(process.env.STRIPE_SECRET_KEY ?? '')\n}\n\n/**\n * A Checkout Session's tax BREAKDOWN, which the webhook payload does not\n * carry: `total_details.breakdown` is an expandable field, so the delivered\n * object states `amount_tax` and nothing about the base it was applied to.\n *\n * Returns the expanded session, or null when the read cannot be made. Null is\n * not a failure that stops the recording — the row is written from the\n * delivered object with `taxLines: []`, and a taxed row with no stated base is\n * COUNTED in the return's `attention` rather than dropped or zeroed.\n */\nasync function expandedSession(sessionId: string): Promise<any | null> {\n const key = stripeKey()\n if (!key || !sessionId) return null\n try {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(\n sessionId,\n )}?expand[]=total_details.breakdown`,\n { headers: { Authorization: `Bearer ${key}` } },\n )\n if (!response.ok) return null\n const body = await response.json().catch(() => null)\n return body?.id ? body : null\n } catch {\n return null\n }\n}\n\n/** The host this Stripe object belongs to, from whichever metadata bag. */\nfunction hostIdOf(object: any): string {\n return String(\n object?.metadata?.hostId ??\n object?.subscription_details?.metadata?.hostId ??\n object?.parent?.subscription_details?.metadata?.hostId ??\n '',\n )\n}\n\nfunction metadataTypeOf(object: any): string {\n return String(\n object?.metadata?.type ??\n object?.subscription_details?.metadata?.type ??\n object?.parent?.subscription_details?.metadata?.type ??\n '',\n )\n}\n\n/**\n * Records one storefront sale's tax, or does nothing when this event is not\n * one. Returns the row written, for the specs — never for control flow.\n */\nexport async function recordStorefrontTax(\n type: string,\n object: any,\n): Promise<StorefrontTaxRow | null> {\n try {\n const metadataType = metadataTypeOf(object)\n const hostId = hostIdOf(object)\n if (!hostId) return null\n\n let kind: 'session' | 'invoice'\n let taxSource = object\n let manualTaxCents = 0\n if (\n type === 'checkout.session.completed' &&\n SESSION_TYPES.has(metadataType) &&\n object?.payment_status === 'paid'\n ) {\n kind = 'session'\n // The manual tax rides as an ordinary `line_items[1]` Stripe is never\n // told is tax (AGL-1711), so the session's own metadata snapshot is the\n // only witness to it. A cart session carries no such line at all.\n manualTaxCents = Math.max(0, Number(object?.metadata?.taxCents ?? 0)) || 0\n // Expanded whenever Stripe COMPUTED tax on this session — which since\n // AGL-1953 includes a `manual`-mode cart or draft order, where the tax\n // rides a real Tax Rate and Stripe therefore states a `taxable_amount`\n // for it. Gated on the delivered `amount_tax` rather than done\n // unconditionally so the buy-now and POS constructions, which report 0\n // there and answer from metadata, still cost no extra Stripe read.\n const stripeStatedTax = Number(\n object?.total_details?.amount_tax ?? 0,\n )\n if (\n object?.automatic_tax?.enabled === true ||\n (Number.isFinite(stripeStatedTax) && stripeStatedTax > 0)\n ) {\n taxSource = (await expandedSession(String(object?.id ?? ''))) ?? object\n }\n } else if (\n (type === 'invoice.paid' || type === 'invoice.payment_succeeded') &&\n metadataType === 'commerce-subscription'\n ) {\n // Every cycle including the opening one. The subscription's own\n // `checkout.session.completed` is NOT a second source — recording both\n // would count the opening sale twice (AGL-1811's rule, same reason).\n kind = 'invoice'\n } else {\n return null\n }\n\n const row = storefrontTaxRow(taxSource, { kind, hostId, manualTaxCents })\n if (!row) return null\n // Nothing to file and nothing to explain: no tax computed, no tax charged.\n // A `stripe-automatic` row is kept even at zero tax — that a Stripe Tax\n // sale answered \"not collecting\" is itself the audit answer to why a\n // jurisdiction is absent from the return.\n //\n // EXCEPT where the absence is AGLYN'S decision rather than the merchant's\n // (AGL-2000). A zero-tax commerce sale means the merchant configured no\n // tax — their call, their liability, nothing here to explain. A booking or\n // a reservation is untaxed because THIS CODEBASE decided not to compute a\n // goods rate on a service or a room (`bookings/server.ts`, `reserve.ts`),\n // and that is exactly the kind of absence somebody has to be able to find\n // later: it is the platform answering a tax question on a merchant's\n // revenue. Dropping those rows made the decision invisible in the one\n // place anyone would go looking for it.\n if (row.taxMode === 'none' && !PLATFORM_UNTAXED_TYPES.has(metadataType)) {\n return null\n }\n\n const documentId = String(object?.id ?? '')\n if (!documentId) return null\n const orgId = (await getOrgForHost(hostId).catch(() => null))?.orgId ?? null\n await firebaseAdmin\n .app()\n .firestore()\n .collection('storefrontTaxCollected')\n .doc(documentId)\n .set(\n {\n ...row,\n orgId,\n recordedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n // Keyed by the Stripe object id and merged, so a redelivery — and the\n // `invoice.paid` / `invoice.payment_succeeded` pair Stripe sends for\n // ONE payment — restamps a single document instead of duplicating a\n // taxable sale.\n { merge: true },\n )\n return row\n } catch (error) {\n console.error('[AGL-1904] storefront tax recording failed', error)\n return null\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","storefrontTaxRow","SESSION_TYPES","Set","PLATFORM_UNTAXED_TYPES","stripeKey","process","String","env","STRIPE_SECRET_KEY","expandedSession","sessionId","key","response","fetch","encodeURIComponent","headers","Authorization","ok","body","json","catch","id","hostIdOf","object","metadata","hostId","subscription_details","parent","metadataTypeOf","type","recordStorefrontTax","metadataType","kind","taxSource","manualTaxCents","has","payment_status","Math","max","Number","taxCents","stripeStatedTax","total_details","amount_tax","automatic_tax","enabled","isFinite","row","taxMode","documentId","orgId","app","firestore","collection","doc","set","recordedAt","FieldValue","serverTimestamp","merge","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAA+B,sBAAkB;AAE1E;;;;;;;;;;;;;;;;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E,gBAAgB;QAChB;YAAEC,OAAO;QAAK;QAElB,OAAOZ;IACT,EAAE,OAAOa,OAAO;QACdC,QAAQD,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax-record.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 { isDirectChargeObject } from './seller-stripe-account'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { storefrontTaxRow, type StorefrontTaxRow } from './storefront-tax'\n\n/**\n * Writes `storefrontTaxCollected/{stripeId}` for every storefront sale that\n * carried tax (AGL-1904) — the row that makes tax collected under Aglyn's\n * registration visible to Aglyn's own quarterly return.\n *\n * ## The hole this closes\n *\n * AGL-1811 records one `platformRevenue` row per paid invoice and the Texas\n * return is their sum. That collection is deliberately scoped to AGLYN's own\n * charges: the console webhook only writes a row when the invoice's customer\n * resolves through the `stripeCustomers` index, which `writeOrgBilling` stamps\n * for Aglyn's billing customers and nothing else stamps. A storefront\n * shopper's customer is never in it.\n *\n * That scoping is correct for what it was built for and it left a gap: a\n * `mode: 'stripe'` storefront sale charges the shopper tax computed on\n * AGLYN's registrations (measured — see `storefront-tax.ts`), settles it into\n * Aglyn's platform balance, and NOTHING recorded it anywhere Aglyn's return\n * could see. The merchant's order document carries a `totals.taxCents`, but\n * that is the merchant's books, per host, and no return sums it.\n *\n * ## Why a SEPARATE collection rather than more `platformRevenue` rows\n *\n * Structural, and the reason must survive a future tidy-up: a\n * `platformRevenue` row's `netCents` is Aglyn's revenue, and a storefront\n * row's is mostly the MERCHANT's — it transfers straight out to the connected\n * account. Merging the two would make the return's \"total sales\" figure silently\n * include other companies' receipts. Keeping them in different collections\n * means no query, sum or future refactor can accidentally add them together;\n * the return reports the storefront figures as their own section, and what\n * belongs on which line of a filed return stays a question for the preparer\n * and for counsel rather than one this code answers.\n *\n * ## What is recorded, and what is not\n *\n * Recorded: cart, buy-now, reservation and draft-order sessions, plus every\n * storefront subscription INVOICE (opening cycle and renewals both — the\n * subscription's own `checkout.session.completed` is deliberately skipped so\n * the opening cycle is not counted twice, the same rule AGL-1811 applies).\n *\n * Manual-mode sales are recorded too, with `taxMode: 'manual'`, precisely so\n * the two modes can be told apart at read time instead of being invisible.\n * They are NOT Aglyn-collected and the return never sums them into the\n * Aglyn-liable figure.\n *\n * **Refunds are not yet reflected.** A refunded storefront sale keeps its full\n * tax on this record, so the Aglyn-liable figure is an OVER-statement of what\n * is owed rather than an under-statement. That direction is deliberate:\n * over-stating what is held for the state is correctable at filing time,\n * under-stating it is a shortfall discovered by an auditor. Stated here rather\n * than left to be discovered.\n *\n * Never throws. A recording failure logs and returns — a throw here propagates\n * through `runBillingWebhookHandlers` into a 500 that Stripe redelivers\n * forever, which is the AGL-1743 lesson.\n */\n\n/** The commerce session types that settle money on the platform account. */\nconst SESSION_TYPES = new Set([\n 'commerce-cart',\n 'commerce-order',\n 'commerce-reservation',\n 'commerce-draft',\n // A paid service booking (AGL-2000). It carries no tax by a stated\n // decision (`bookings/server.ts`), but it is a storefront sale and it was\n // absent from this set entirely — so it was not merely untaxed, it did not\n // appear in the record that would let anyone NOTICE it was untaxed or\n // reconcile it later. An untaxed sale that is recorded reads\n // `taxMode: 'none'`; an unrecorded one reads as nothing at all.\n 'booking-payment',\n])\n\n/**\n * Session types whose zero tax is a decision taken HERE, not by the merchant\n * (AGL-2000). Their rows are filed even at `taxMode: 'none'`, so an untaxed\n * service or stay is reconcilable instead of merely missing. See the note at\n * the `taxMode === 'none'` gate below.\n */\nconst PLATFORM_UNTAXED_TYPES = new Set(['booking-payment', 'commerce-reservation'])\n\nfunction stripeKey(): string {\n return String(process.env.STRIPE_SECRET_KEY ?? '')\n}\n\n/**\n * A Checkout Session's tax BREAKDOWN, which the webhook payload does not\n * carry: `total_details.breakdown` is an expandable field, so the delivered\n * object states `amount_tax` and nothing about the base it was applied to.\n *\n * Returns the expanded session, or null when the read cannot be made. Null is\n * not a failure that stops the recording — the row is written from the\n * delivered object with `taxLines: []`, and a taxed row with no stated base is\n * COUNTED in the return's `attention` rather than dropped or zeroed.\n */\nasync function expandedSession(sessionId: string): Promise<any | null> {\n const key = stripeKey()\n if (!key || !sessionId) return null\n try {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(\n sessionId,\n )}?expand[]=total_details.breakdown`,\n { headers: { Authorization: `Bearer ${key}` } },\n )\n if (!response.ok) return null\n const body = await response.json().catch(() => null)\n return body?.id ? body : null\n } catch {\n return null\n }\n}\n\n/** The host this Stripe object belongs to, from whichever metadata bag. */\nfunction hostIdOf(object: any): string {\n return String(\n object?.metadata?.hostId ??\n object?.subscription_details?.metadata?.hostId ??\n object?.parent?.subscription_details?.metadata?.hostId ??\n '',\n )\n}\n\nfunction metadataTypeOf(object: any): string {\n return String(\n object?.metadata?.type ??\n object?.subscription_details?.metadata?.type ??\n object?.parent?.subscription_details?.metadata?.type ??\n '',\n )\n}\n\n/**\n * Records one storefront sale's tax, or does nothing when this event is not\n * one. Returns the row written, for the specs — never for control flow.\n */\nexport async function recordStorefrontTax(\n type: string,\n object: any,\n): Promise<StorefrontTaxRow | null> {\n try {\n // A DIRECT-charge sale is the seller's own: the seller collected the tax\n // against their own registrations and files it. It is not a facilitated\n // sale and has no place in Aglyn's return.\n if (isDirectChargeObject(object)) return null\n const metadataType = metadataTypeOf(object)\n const hostId = hostIdOf(object)\n if (!hostId) return null\n\n let kind: 'session' | 'invoice'\n let taxSource = object\n let manualTaxCents = 0\n if (\n type === 'checkout.session.completed' &&\n SESSION_TYPES.has(metadataType) &&\n object?.payment_status === 'paid'\n ) {\n kind = 'session'\n // The manual tax rides as an ordinary `line_items[1]` Stripe is never\n // told is tax (AGL-1711), so the session's own metadata snapshot is the\n // only witness to it. A cart session carries no such line at all.\n manualTaxCents = Math.max(0, Number(object?.metadata?.taxCents ?? 0)) || 0\n // Expanded whenever Stripe COMPUTED tax on this session — which since\n // AGL-1953 includes a `manual`-mode cart or draft order, where the tax\n // rides a real Tax Rate and Stripe therefore states a `taxable_amount`\n // for it. Gated on the delivered `amount_tax` rather than done\n // unconditionally so the buy-now and POS constructions, which report 0\n // there and answer from metadata, still cost no extra Stripe read.\n const stripeStatedTax = Number(\n object?.total_details?.amount_tax ?? 0,\n )\n if (\n object?.automatic_tax?.enabled === true ||\n (Number.isFinite(stripeStatedTax) && stripeStatedTax > 0)\n ) {\n taxSource = (await expandedSession(String(object?.id ?? ''))) ?? object\n }\n } else if (\n (type === 'invoice.paid' || type === 'invoice.payment_succeeded') &&\n metadataType === 'commerce-subscription'\n ) {\n // Every cycle including the opening one. The subscription's own\n // `checkout.session.completed` is NOT a second source — recording both\n // would count the opening sale twice (AGL-1811's rule, same reason).\n kind = 'invoice'\n } else {\n return null\n }\n\n const row = storefrontTaxRow(taxSource, { kind, hostId, manualTaxCents })\n if (!row) return null\n // Nothing to file and nothing to explain: no tax computed, no tax charged.\n // A `stripe-automatic` row is kept even at zero tax — that a Stripe Tax\n // sale answered \"not collecting\" is itself the audit answer to why a\n // jurisdiction is absent from the return.\n //\n // EXCEPT where the absence is AGLYN'S decision rather than the merchant's\n // (AGL-2000). A zero-tax commerce sale means the merchant configured no\n // tax — their call, their liability, nothing here to explain. A booking or\n // a reservation is untaxed because THIS CODEBASE decided not to compute a\n // goods rate on a service or a room (`bookings/server.ts`, `reserve.ts`),\n // and that is exactly the kind of absence somebody has to be able to find\n // later: it is the platform answering a tax question on a merchant's\n // revenue. Dropping those rows made the decision invisible in the one\n // place anyone would go looking for it.\n if (row.taxMode === 'none' && !PLATFORM_UNTAXED_TYPES.has(metadataType)) {\n return null\n }\n\n const documentId = String(object?.id ?? '')\n if (!documentId) return null\n const orgId = (await getOrgForHost(hostId).catch(() => null))?.orgId ?? null\n await firebaseAdmin\n .app()\n .firestore()\n .collection('storefrontTaxCollected')\n .doc(documentId)\n .set(\n {\n ...row,\n orgId,\n recordedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n // Keyed by the Stripe object id and merged, so a redelivery — and the\n // `invoice.paid` / `invoice.payment_succeeded` pair Stripe sends for\n // ONE payment — restamps a single document instead of duplicating a\n // taxable sale.\n { merge: true },\n )\n return row\n } catch (error) {\n console.error('[AGL-1904] storefront tax recording failed', error)\n return null\n }\n}\n"],"names":["isDirectChargeObject","firebaseAdmin","getOrgForHost","storefrontTaxRow","SESSION_TYPES","Set","PLATFORM_UNTAXED_TYPES","stripeKey","process","String","env","STRIPE_SECRET_KEY","expandedSession","sessionId","key","response","fetch","encodeURIComponent","headers","Authorization","ok","body","json","catch","id","hostIdOf","object","metadata","hostId","subscription_details","parent","metadataTypeOf","type","recordStorefrontTax","metadataType","kind","taxSource","manualTaxCents","has","payment_status","Math","max","Number","taxCents","stripeStatedTax","total_details","amount_tax","automatic_tax","enabled","isFinite","row","taxMode","documentId","orgId","app","firestore","collection","doc","set","recordedAt","FieldValue","serverTimestamp","merge","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAA+B,sBAAkB;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,0EAA0E,GAC1E,MAAMC,gBAAgB,IAAIC,IAAI;IAC5B;IACA;IACA;IACA;IACA,mEAAmE;IACnE,0EAA0E;IAC1E,2EAA2E;IAC3E,sEAAs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8CAA8CA;QAC5D,OAAO;IACT;AACF"}
@@ -89,6 +89,17 @@
89
89
  * and must be re-read with `expand[]=total_details.breakdown`; an invoice
90
90
  * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.
91
91
  *
92
+ * ## A DIRECT charge is the seller's tax, never the platform's
93
+ *
94
+ * A seller on its own full Stripe account sells by DIRECT charge: the session
95
+ * is created ON the seller's account (`Stripe-Account` header) and stamped
96
+ * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the
97
+ * SELLER's registrations, the tax settles into the seller's balance, and the
98
+ * seller remits it. Stripe still reports `liability: { type: "self" }`, but
99
+ * `self` is then the seller's account, so reading `self` as "the platform"
100
+ * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is
101
+ * therefore always `connected-account` here, whatever the field says.
102
+ *
92
103
  * Pure and total: unreadable input answers `null`, never throws — a recording
93
104
  * failure must never 500 a webhook into redelivery.
94
105
  */
@@ -105,8 +116,9 @@ export type { StorefrontTaxMode };
105
116
  /**
106
117
  * Whose registrations Stripe Tax computed against, from
107
118
  * `automatic_tax.liability.type`: `self` (the account the object lives on,
108
- * i.e. Aglyn's platform) or `account` (a named connected account).
109
- * Null whenever `taxMode` is not `stripe-automatic`.
119
+ * i.e. Aglyn's platform) or `account` (a named connected account). A DIRECT
120
+ * charge lives on the seller's account, so it is always `connected-account`
121
+ * (see the module note). Null whenever `taxMode` is not `stripe-automatic`.
110
122
  */
111
123
  export type StorefrontTaxLiability = 'platform' | 'connected-account';
112
124
  /** One entry of the stored tax breakdown. */
@@ -166,6 +178,11 @@ export declare function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[
166
178
  export interface StorefrontTaxContext {
167
179
  kind: 'session' | 'invoice';
168
180
  hostId: string;
181
+ /**
182
+ * The seller's account for a DIRECT charge, which names no transfer
183
+ * destination: the event's `account`, when the caller has it.
184
+ */
185
+ connectedAccountId?: string | null;
169
186
  /**
170
187
  * The manual-mode tax `checkout.ts` puts over as an ordinary line item.
171
188
  * Stripe is never told it is tax, so no Stripe field carries it and the
@@ -200,6 +217,20 @@ export declare function resolveStorefrontTax(object: unknown, manualTaxCents?: n
200
217
  * is the same answer the filed tax record gives for the same object.
201
218
  */
202
219
  export declare function storefrontTaxModeOf(object: unknown, manualTaxCents?: number): StorefrontTaxMode;
220
+ /**
221
+ * Whether a session, subscription or invoice was sold as a DIRECT charge on
222
+ * the seller's own account, from the `chargeModel` stamp the session doors
223
+ * write (an invoice carries its subscription's under `subscription_details`).
224
+ */
225
+ export declare function storefrontSaleIsDirect(object: unknown): boolean;
226
+ /**
227
+ * Who owns, and remits, the tax a storefront sale carried: the SELLER for
228
+ * any merchant-configured rate and for every direct charge, and the PLATFORM
229
+ * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was
230
+ * charged. The single answer a summary or a return should read rather than
231
+ * re-deriving it from the liability field.
232
+ */
233
+ export declare function storefrontTaxOwner(object: unknown, manualTaxCents?: number): 'platform' | 'seller' | 'none';
203
234
  /**
204
235
  * Decomposes a paid storefront session or invoice into the stored row, or
205
236
  * `null` when there is no host to attribute it to.
@@ -88,6 +88,17 @@
88
88
  * and must be re-read with `expand[]=total_details.breakdown`; an invoice
89
89
  * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.
90
90
  *
91
+ * ## A DIRECT charge is the seller's tax, never the platform's
92
+ *
93
+ * A seller on its own full Stripe account sells by DIRECT charge: the session
94
+ * is created ON the seller's account (`Stripe-Account` header) and stamped
95
+ * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the
96
+ * SELLER's registrations, the tax settles into the seller's balance, and the
97
+ * seller remits it. Stripe still reports `liability: { type: "self" }`, but
98
+ * `self` is then the seller's account, so reading `self` as "the platform"
99
+ * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is
100
+ * therefore always `connected-account` here, whatever the field says.
101
+ *
91
102
  * Pure and total: unreadable input answers `null`, never throws — a recording
92
103
  * failure must never 500 a webhook into redelivery.
93
104
  */ import { storefrontTaxMode } from "../model/commerce-tax-decision.js";
@@ -205,6 +216,30 @@ function taxLines(source) {
205
216
  */ export function storefrontTaxModeOf(object, manualTaxCents = 0) {
206
217
  return resolveStorefrontTax(object, manualTaxCents).taxMode;
207
218
  }
219
+ /**
220
+ * Whether a session, subscription or invoice was sold as a DIRECT charge on
221
+ * the seller's own account, from the `chargeModel` stamp the session doors
222
+ * write (an invoice carries its subscription's under `subscription_details`).
223
+ */ export function storefrontSaleIsDirect(object) {
224
+ var _ref, _ref1;
225
+ var _source_metadata, _source_subscription_details_metadata, _source_subscription_details, _source_parent_subscription_details_metadata, _source_parent_subscription_details, _source_parent;
226
+ const source = object;
227
+ return ((_ref = (_ref1 = source == null ? void 0 : (_source_metadata = source.metadata) == null ? void 0 : _source_metadata.chargeModel) != null ? _ref1 : source == null ? void 0 : (_source_subscription_details = source.subscription_details) == null ? void 0 : (_source_subscription_details_metadata = _source_subscription_details.metadata) == null ? void 0 : _source_subscription_details_metadata.chargeModel) != null ? _ref : source == null ? void 0 : (_source_parent = source.parent) == null ? void 0 : (_source_parent_subscription_details = _source_parent.subscription_details) == null ? void 0 : (_source_parent_subscription_details_metadata = _source_parent_subscription_details.metadata) == null ? void 0 : _source_parent_subscription_details_metadata.chargeModel) === 'direct';
228
+ }
229
+ /**
230
+ * Who owns, and remits, the tax a storefront sale carried: the SELLER for
231
+ * any merchant-configured rate and for every direct charge, and the PLATFORM
232
+ * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was
233
+ * charged. The single answer a summary or a return should read rather than
234
+ * re-deriving it from the liability field.
235
+ */ export function storefrontTaxOwner(object, manualTaxCents = 0) {
236
+ var _object_automatic_tax_liability, _object_automatic_tax;
237
+ const { automatic, taxMode } = resolveStorefrontTax(object, manualTaxCents);
238
+ if (taxMode === 'none') return 'none';
239
+ if (!automatic || storefrontSaleIsDirect(object)) return 'seller';
240
+ const liabilityType = asStringOrNull(object == null ? void 0 : (_object_automatic_tax = object.automatic_tax) == null ? void 0 : (_object_automatic_tax_liability = _object_automatic_tax.liability) == null ? void 0 : _object_automatic_tax_liability.type);
241
+ return liabilityType === 'account' ? 'seller' : 'platform';
242
+ }
208
243
  /**
209
244
  * Decomposes a paid storefront session or invoice into the stored row, or
210
245
  * `null` when there is no host to attribute it to.
@@ -212,14 +247,15 @@ function taxLines(source) {
212
247
  * The caller decides WHICH objects reach this — the commerce webhook
213
248
  * self-selects on `metadata.type`, exactly as every other section does.
214
249
  */ export function storefrontTaxRow(object, context) {
215
- var _ref, _ref1, _ref2, _asStringOrNull, _asStringOrNull1, _asStringOrNull2, _address, _asDate;
250
+ var _ref, _ref1, _ref2, _asStringOrNull, _ref3, _asStringOrNull1, _asStringOrNull2, _address, _asDate;
216
251
  var _source_automatic_tax_liability, _source_automatic_tax, _source_payment_intent_data_transfer_data, _source_payment_intent_data, _source_transfer_data, _source_metadata, _source_subscription_details_metadata, _source_subscription_details, _source_parent_subscription_details_metadata, _source_parent_subscription_details, _source_parent, _source_customer_details, _source_status_transitions;
217
252
  const source = object;
218
253
  const hostId = String((_ref = context == null ? void 0 : context.hostId) != null ? _ref : '');
219
254
  if (!hostId) return null;
220
255
  const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(source, context == null ? void 0 : context.manualTaxCents);
221
256
  const liabilityType = asStringOrNull(source == null ? void 0 : (_source_automatic_tax = source.automatic_tax) == null ? void 0 : (_source_automatic_tax_liability = _source_automatic_tax.liability) == null ? void 0 : _source_automatic_tax_liability.type);
222
- const taxLiability = !automatic ? null : liabilityType === 'account' ? 'connected-account' : // older API versions, where the only account a session could be
257
+ const direct = storefrontSaleIsDirect(source);
258
+ const taxLiability = !automatic ? null : direct || liabilityType === 'account' ? 'connected-account' : // older API versions, where the only account a session could be
223
259
  // liable under is the one it was created on — the platform.
224
260
  'platform';
225
261
  const grossCents = asCents(context.kind === 'invoice' ? source == null ? void 0 : source.amount_paid : source == null ? void 0 : source.amount_total);
@@ -230,7 +266,7 @@ function taxLines(source) {
230
266
  metadataType: (_ref2 = (_asStringOrNull = asStringOrNull(source == null ? void 0 : (_source_metadata = source.metadata) == null ? void 0 : _source_metadata.type)) != null ? _asStringOrNull : asStringOrNull(source == null ? void 0 : (_source_subscription_details = source.subscription_details) == null ? void 0 : (_source_subscription_details_metadata = _source_subscription_details.metadata) == null ? void 0 : _source_subscription_details_metadata.type)) != null ? _ref2 : asStringOrNull(source == null ? void 0 : (_source_parent = source.parent) == null ? void 0 : (_source_parent_subscription_details = _source_parent.subscription_details) == null ? void 0 : (_source_parent_subscription_details_metadata = _source_parent_subscription_details.metadata) == null ? void 0 : _source_parent_subscription_details_metadata.type),
231
267
  taxMode,
232
268
  taxLiability,
233
- connectedAccountId: (_asStringOrNull1 = asStringOrNull(transferDestination)) != null ? _asStringOrNull1 : asStringOrNull(transferDestination == null ? void 0 : transferDestination.id),
269
+ connectedAccountId: (_ref3 = (_asStringOrNull1 = asStringOrNull(transferDestination)) != null ? _asStringOrNull1 : asStringOrNull(transferDestination == null ? void 0 : transferDestination.id)) != null ? _ref3 : direct ? asStringOrNull(context == null ? void 0 : context.connectedAccountId) : null,
234
270
  grossCents,
235
271
  taxCents,
236
272
  netCents: grossCents - taxCents,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax.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 * What a storefront sale's TAX decomposes to (AGL-1904) — the record that\n * makes tax collected on a merchant's sale visible to Aglyn's own return.\n *\n * ## The observation this module exists to record\n *\n * Every storefront checkout — cart, buy-now, subscription — creates its\n * Checkout Session on the PLATFORM account: platform secret key, no\n * `Stripe-Account` header, no `on_behalf_of`, with\n * `payment_intent_data[transfer_data][destination]` pointing at the merchant's\n * connected account. `cart-checkout.ts` and `checkout.ts` then set\n * `automatic_tax[enabled]` when the store's tax mode is `stripe`.\n *\n * That was long suspected to mean Stripe Tax computes the shopper's tax\n * against AGLYN's registrations rather than the merchant's. It was MEASURED on\n * 2026-08-18, in test mode, as a two-arm experiment on exactly that session\n * shape (a $100 line, a Texas shopper address, `transfer_data[destination]`\n * set):\n *\n * - **Platform unregistered, destination connected account registered in\n * TX** → `amount_tax: 0`, one breakdown line with\n * `taxability_reason: \"not_collecting\"`, `taxable_amount: 0`.\n * - **Platform registered in TX, everything else byte-identical** →\n * `amount_tax: 825`, `taxability_reason: \"standard_rated\"`,\n * `taxable_amount: 10000`, rate 8.25% \"Texas\".\n *\n * Both sessions reported `automatic_tax.liability: { type: \"self\" }` — Stripe's\n * own word for \"the account this session was created on is the one liable\".\n * `transfer_data[destination]` had no effect on tax in either arm.\n *\n * So on a `mode: 'stripe'` store the tax charged to the shopper is computed on\n * Aglyn's registration footprint, lands in Aglyn's platform balance, and is\n * Aglyn's to remit. The live platform account has held an ACTIVE Texas state\n * sales tax registration since 2026-08-17, so this is not hypothetical.\n *\n * **This module describes that mechanism and records the money.** Aglyn IS a\n * marketplace facilitator for storefront sales, and the published Terms say so\n * at §10.7 (AGL-1956). Facilitator status still attaches by operation of\n * law rather than by our say-so, and §10.7 is deliberately narrow — Aglyn\n * collects and remits **where applicable law gives it an obligation**, not\n * universally — so this module still records the mechanism per sale and does\n * not stamp a per-merchant or per-jurisdiction verdict on any row.\n *\n * ## The two store modes are DIFFERENT FACTS and must never be summed\n *\n * `taxMode` is the whole point of this record, and it is derived from\n * `automatic_tax.enabled` — **never** from whether tax lines are present:\n *\n * - **`stripe-automatic`** — Stripe Tax computed it, against whichever\n * account `automatic_tax.liability` names. When that is `platform`, the\n * money is held under Aglyn's registration.\n * - **`manual`** — the merchant's own configured rate\n * (`checkout.ts` / `pos-order.ts`), applied to the merchant's own declared\n * origin. Aglyn's registrations never enter into it and the amount is not\n * Aglyn's to remit.\n *\n * The trap that makes the `automatic_tax.enabled` discriminator load-bearing:\n * a MANUAL-mode subscription renewal carries a real Stripe Tax Rate (AGL-1751\n * attaches one so the tax recurs), so its invoice arrives with a populated\n * `total_taxes[]` — indistinguishable from a Stripe Tax invoice if you look at\n * the tax lines. Summing tax lines would silently book merchant-configured tax\n * as Aglyn-collected. **Read the flag, not the lines.**\n *\n * ## The taxable base is kept, never inferred\n *\n * `taxable_amount` is what a return reports as \"taxable sales\". Deriving it as\n * `amount ÷ rate` needs a live read to resolve the rate id and rounds wrong at\n * the edges, so it is stored when Stripe states it and left `null` when it\n * does not — and a row whose base cannot be read is COUNTED OUT LOUD by the\n * return rather than treated as a zero-base sale.\n *\n * A Checkout Session's `total_details.breakdown` is not in the webhook payload\n * and must be re-read with `expand[]=total_details.breakdown`; an invoice\n * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.\n *\n * Pure and total: unreadable input answers `null`, never throws — a recording\n * failure must never 500 a webhook into redelivery.\n */\n\nimport {\n storefrontTaxMode,\n type StorefrontTaxMode,\n} from '../model/commerce-tax-decision'\n\n/**\n * Which machinery produced the tax on this sale. See the module note.\n *\n * The union and its derivation live in the MODEL since AGL-2451, because the\n * merchant's order document now carries the same fact (`HostOrder.taxMode`)\n * and two copies of a rule that must agree are one copy too many. Re-exported\n * here so this module stays the place the mechanism is documented.\n */\nexport type { StorefrontTaxMode }\n\n/**\n * Whose registrations Stripe Tax computed against, from\n * `automatic_tax.liability.type`: `self` (the account the object lives on,\n * i.e. Aglyn's platform) or `account` (a named connected account).\n * Null whenever `taxMode` is not `stripe-automatic`.\n */\nexport type StorefrontTaxLiability = 'platform' | 'connected-account'\n\n/** One entry of the stored tax breakdown. */\nexport interface StorefrontTaxLine {\n amountCents: number\n /** Stripe's stated reason, e.g. `standard_rated`, `not_collecting`. */\n taxabilityReason: string | null\n taxRateId: string | null\n /** Stripe's `taxable_amount`; null when the shape did not carry it. */\n taxableAmountCents: number | null\n /** e.g. `Texas` — from the expanded rate, for the working papers. */\n jurisdiction: string | null\n /** The rate's own state code, which is not the shopper's address. */\n rateState: string | null\n percentage: number | null\n}\n\n/** The per-transaction record `storefrontTaxCollected/{stripeId}` stores. */\nexport interface StorefrontTaxRow {\n /** `session` for one-time sales, `invoice` for subscription cycles. */\n kind: 'session' | 'invoice'\n hostId: string\n /** The commerce path — `commerce-cart`, `commerce-order`, … */\n metadataType: string | null\n taxMode: StorefrontTaxMode\n taxLiability: StorefrontTaxLiability | null\n /** The merchant's connected account, when the object names one. */\n connectedAccountId: string | null\n /** What the shopper actually paid, tax included. */\n grossCents: number\n taxCents: number\n /** Gross minus tax. NOT Aglyn's revenue — most of it is the merchant's. */\n netCents: number\n currency: string\n /** The jurisdiction input — the shopper's address on the Stripe object. */\n customerAddress: {\n country: string | null\n state: string | null\n city: string | null\n postalCode: string | null\n } | null\n taxLines: StorefrontTaxLine[]\n paidAt: Date | null\n}\n\nfunction asCents(value: unknown): number {\n const cents = Number(value ?? 0)\n return Number.isFinite(cents) ? Math.round(cents) : 0\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value ? value : null\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n const parsed = Number(value ?? NaN)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** Seconds-since-epoch to Date, or null for anything unreadable. */\nfunction asDate(value: unknown): Date | null {\n const seconds = Number(value ?? NaN)\n return Number.isFinite(seconds) && seconds > 0\n ? new Date(seconds * 1000)\n : null\n}\n\nfunction address(source: any): StorefrontTaxRow['customerAddress'] {\n if (!source || typeof source !== 'object') return null\n return {\n country: asStringOrNull(source.country),\n state: asStringOrNull(source.state),\n city: asStringOrNull(source.city),\n postalCode: asStringOrNull(source.postal_code),\n }\n}\n\n/**\n * The breakdown entries, from either shape.\n *\n * A Checkout Session expands them under `total_details.breakdown.taxes[]`\n * with the rate object inline; an invoice carries `total_taxes[]` (rate under\n * `tax_rate_details.tax_rate`) or the older `total_tax_amounts[]` (`tax_rate`,\n * an id or an expanded object). All three map onto one stored line.\n *\n * Exported for the POS hardware shop's own sales (AGL-4038), whose tax rows\n * keep the same lines: one reading of Stripe's breakdown for every half of\n * the return.\n */\nexport function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[] {\n return taxLines(source)\n}\n\nfunction taxLines(source: any): StorefrontTaxLine[] {\n const entries: any[] = Array.isArray(source?.total_details?.breakdown?.taxes)\n ? source.total_details.breakdown.taxes\n : Array.isArray(source?.total_taxes)\n ? source.total_taxes\n : Array.isArray(source?.total_tax_amounts)\n ? source.total_tax_amounts\n : []\n return entries.map((entry: any) => {\n const rate = entry?.rate ?? entry?.tax_rate_details?.tax_rate ?? entry?.tax_rate\n const rateObject = rate && typeof rate === 'object' ? rate : null\n // Distinguish an absent `taxable_amount` from a genuine zero: a zero base\n // is a real fact (`not_collecting`), an absent one means the base is\n // UNKNOWN, and the return has to be able to tell those apart.\n const taxableAmount = Number(entry?.taxable_amount ?? NaN)\n return {\n amountCents: asCents(entry?.amount),\n taxabilityReason: asStringOrNull(entry?.taxability_reason),\n taxRateId: asStringOrNull(rate) ?? asStringOrNull(rateObject?.id),\n taxableAmountCents: Number.isFinite(taxableAmount)\n ? Math.round(taxableAmount)\n : null,\n jurisdiction: asStringOrNull(rateObject?.jurisdiction),\n rateState: asStringOrNull(rateObject?.state),\n percentage:\n asNumberOrNull(rateObject?.effective_percentage) ??\n asNumberOrNull(rateObject?.percentage),\n }\n })\n}\n\n/** Sum of the stored lines' amounts. */\nfunction sumLines(lines: readonly StorefrontTaxLine[]): number {\n return lines.reduce((sum, line) => sum + line.amountCents, 0)\n}\n\nexport interface StorefrontTaxContext {\n kind: 'session' | 'invoice'\n hostId: string\n /**\n * The manual-mode tax `checkout.ts` puts over as an ordinary line item.\n * Stripe is never told it is tax, so no Stripe field carries it and the\n * session's own `metadata[taxCents]` is the only witness (AGL-1711).\n */\n manualTaxCents?: number\n}\n\n/** What one Stripe object says about the tax it carried. */\nexport interface ResolvedStorefrontTax {\n /** `automatic_tax.enabled` — the discriminator, never the tax lines. */\n automatic: boolean\n /** Stripe's own breakdown, present only on a `stripe-automatic` sale. */\n lines: StorefrontTaxLine[]\n taxCents: number\n taxMode: StorefrontTaxMode\n}\n\n/**\n * Reads the tax off one paid session or invoice — the SINGLE derivation, and\n * the reason it is its own exported function (AGL-2451).\n *\n * `storefrontTaxRow` builds the `storefrontTaxCollected` record from it, and\n * the four order-writing doors in `billing-webhook.ts` stamp `HostOrder.taxMode`\n * from it, so an order and the row filed for the same Stripe id cannot state\n * different regimes. Re-deriving the mode beside a second reading of the same\n * object is exactly how the two would drift.\n *\n * Pure and total: unreadable input answers `taxMode: 'none'`, never throws.\n */\nexport function resolveStorefrontTax(\n object: unknown,\n manualTaxCents = 0,\n): ResolvedStorefrontTax {\n const source = object as any\n const automatic = source?.automatic_tax?.enabled === true\n const lines = automatic ? taxLines(source) : []\n const manualCents = Math.max(0, asCents(manualTaxCents))\n // The flag, never the lines — see the module note. A manual-mode\n // subscription renewal carries real Stripe tax rates in `total_taxes[]`,\n // and booking those as Aglyn-collected would be the whole defect restated.\n //\n // Read on SESSIONS as well as invoices since AGL-1953: the cart and\n // draft-order paths now carry their manual tax as a real Stripe Tax Rate on\n // the line (the construction that survives a session-level coupon), so a\n // manual session reports a genuine `total_details.amount_tax`. The scalar is\n // the fallback because `total_details.breakdown` is expandable and absent\n // unless the recorder re-read it. Buy-now's `line_items[1]` construction\n // reports 0 in both shapes and still answers from `manualTaxCents` below.\n const manualLineCents = !automatic\n ? sumLines(taxLines(source)) ||\n asCents(source?.total_details?.amount_tax ?? source?.tax)\n : 0\n const taxCents = automatic\n ? // `total_details.amount_tax` on a session, `total_taxes[]` on an\n // invoice. Prefer the summed lines when they exist (a computed invoice\n // can send a 0/null scalar beside a populated array — AGL-1811's\n // measurement), and fall back to the scalar shapes otherwise.\n lines.length > 0\n ? sumLines(lines)\n : asCents(source?.total_details?.amount_tax ?? source?.tax)\n : Math.max(manualCents, manualLineCents)\n return {\n automatic,\n lines,\n taxCents,\n taxMode: storefrontTaxMode({ automatic, taxCents }),\n }\n}\n\n/**\n * Just the regime, for the order-writing doors (AGL-2451). Delegates, so this\n * is the same answer the filed tax record gives for the same object.\n */\nexport function storefrontTaxModeOf(\n object: unknown,\n manualTaxCents = 0,\n): StorefrontTaxMode {\n return resolveStorefrontTax(object, manualTaxCents).taxMode\n}\n\n/**\n * Decomposes a paid storefront session or invoice into the stored row, or\n * `null` when there is no host to attribute it to.\n *\n * The caller decides WHICH objects reach this — the commerce webhook\n * self-selects on `metadata.type`, exactly as every other section does.\n */\nexport function storefrontTaxRow(\n object: unknown,\n context: StorefrontTaxContext,\n): StorefrontTaxRow | null {\n const source = object as any\n const hostId = String(context?.hostId ?? '')\n if (!hostId) return null\n\n const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(\n source,\n context?.manualTaxCents,\n )\n\n const liabilityType = asStringOrNull(source?.automatic_tax?.liability?.type)\n const taxLiability: StorefrontTaxLiability | null = !automatic\n ? null\n : liabilityType === 'account'\n ? 'connected-account'\n : // `self`, and also an absent liability: Stripe omits the field on\n // older API versions, where the only account a session could be\n // liable under is the one it was created on — the platform.\n 'platform'\n\n const grossCents = asCents(\n context.kind === 'invoice' ? source?.amount_paid : source?.amount_total,\n )\n const transferDestination =\n source?.payment_intent_data?.transfer_data?.destination ??\n source?.transfer_data?.destination\n return {\n kind: context.kind,\n hostId,\n metadataType:\n asStringOrNull(source?.metadata?.type) ??\n asStringOrNull(source?.subscription_details?.metadata?.type) ??\n asStringOrNull(source?.parent?.subscription_details?.metadata?.type),\n taxMode,\n taxLiability,\n connectedAccountId:\n asStringOrNull(transferDestination) ??\n asStringOrNull((transferDestination as any)?.id),\n grossCents,\n taxCents,\n netCents: grossCents - taxCents,\n currency: asStringOrNull(source?.currency) ?? 'usd',\n customerAddress:\n address(source?.customer_details?.address) ??\n address(source?.customer_address),\n // Stripe's OWN breakdown, whenever Stripe stated one — never an invented\n // base. Buy-now's manual construction states none (Stripe was never told\n // the line was tax) and answers `[]`, which is the honest answer. The\n // cart, draft-order and subscription-renewal manual paths carry a real\n // Tax Rate, so Stripe DOES state a `taxable_amount` for them, and keeping\n // it gives `merchantManual` a real taxable-sales figure instead of a\n // permanent zero (AGL-1953). It never reaches the Aglyn-liable bucket:\n // the classification above is the flag, not these lines.\n taxLines: automatic ? lines : taxLines(source),\n paidAt:\n asDate(source?.status_transitions?.paid_at) ?? asDate(source?.created),\n }\n}\n"],"names":["storefrontTaxMode","asCents","value","cents","Number","isFinite","Math","round","asStringOrNull","asNumberOrNull","parsed","NaN","asDate","seconds","Date","address","source","country","state","city","postalCode","postal_code","stripeTaxBreakdownLines","taxLines","entries","Array","isArray","total_details","breakdown","taxes","total_taxes","total_tax_amounts","map","entry","rate","tax_rate_details","tax_rate","rateObject","taxableAmount","taxable_amount","amountCents","amount","taxabilityReason","taxability_reason","taxRateId","id","taxableAmountCents","jurisdiction","rateState","percentage","effective_percentage","sumLines","lines","reduce","sum","line","resolveStorefrontTax","object","manualTaxCents","automatic","automatic_tax","enabled","manualCents","max","manualLineCents","amount_tax","tax","taxCents","length","taxMode","storefrontTaxModeOf","storefrontTaxRow","context","hostId","String","liabilityType","liability","type","taxLiability","grossCents","kind","amount_paid","amount_total","transferDestination","payment_intent_data","transfer_data","destination","metadataType","metadata","subscription_details","parent","connectedAccountId","netCents","currency","customerAddress","customer_details","customer_address","paidAt","status_transitions","paid_at","created"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6EC,GAED,SACEA,iBAAiB,QAEZ,oCAAgC;AA+DvC,SAASC,QAAQC,KAAc;IAC7B,MAAMC,QAAQC,OAAOF,gBAAAA,QAAS;IAC9B,OAAOE,O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gBAAgB,qBAAxB/E,yBAA0BD,OAAO,aAAzCA,WACAA,QAAQC,0BAAAA,OAAQgF,gBAAgB;QAClC,yEAAyE;QACzE,yEAAyE;QACzE,sEAAsE;QACtE,uEAAuE;QACvE,0EAA0E;QAC1E,qEAAqE;QACrE,uEAAuE;QACvE,yDAAyD;QACzDzE,UAAUoC,YAAYP,QAAQ7B,SAASP;QACvCiF,MAAM,GACJrF,UAAAA,OAAOI,2BAAAA,6BAAAA,OAAQkF,kBAAkB,qBAA1BlF,2BAA4BmF,OAAO,aAA1CvF,UAA+CA,OAAOI,0BAAAA,OAAQoF,OAAO;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax.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 * What a storefront sale's TAX decomposes to (AGL-1904) — the record that\n * makes tax collected on a merchant's sale visible to Aglyn's own return.\n *\n * ## The observation this module exists to record\n *\n * Every storefront checkout — cart, buy-now, subscription — creates its\n * Checkout Session on the PLATFORM account: platform secret key, no\n * `Stripe-Account` header, no `on_behalf_of`, with\n * `payment_intent_data[transfer_data][destination]` pointing at the merchant's\n * connected account. `cart-checkout.ts` and `checkout.ts` then set\n * `automatic_tax[enabled]` when the store's tax mode is `stripe`.\n *\n * That was long suspected to mean Stripe Tax computes the shopper's tax\n * against AGLYN's registrations rather than the merchant's. It was MEASURED on\n * 2026-08-18, in test mode, as a two-arm experiment on exactly that session\n * shape (a $100 line, a Texas shopper address, `transfer_data[destination]`\n * set):\n *\n * - **Platform unregistered, destination connected account registered in\n * TX** → `amount_tax: 0`, one breakdown line with\n * `taxability_reason: \"not_collecting\"`, `taxable_amount: 0`.\n * - **Platform registered in TX, everything else byte-identical** →\n * `amount_tax: 825`, `taxability_reason: \"standard_rated\"`,\n * `taxable_amount: 10000`, rate 8.25% \"Texas\".\n *\n * Both sessions reported `automatic_tax.liability: { type: \"self\" }` — Stripe's\n * own word for \"the account this session was created on is the one liable\".\n * `transfer_data[destination]` had no effect on tax in either arm.\n *\n * So on a `mode: 'stripe'` store the tax charged to the shopper is computed on\n * Aglyn's registration footprint, lands in Aglyn's platform balance, and is\n * Aglyn's to remit. The live platform account has held an ACTIVE Texas state\n * sales tax registration since 2026-08-17, so this is not hypothetical.\n *\n * **This module describes that mechanism and records the money.** Aglyn IS a\n * marketplace facilitator for storefront sales, and the published Terms say so\n * at §10.7 (AGL-1956). Facilitator status still attaches by operation of\n * law rather than by our say-so, and §10.7 is deliberately narrow — Aglyn\n * collects and remits **where applicable law gives it an obligation**, not\n * universally — so this module still records the mechanism per sale and does\n * not stamp a per-merchant or per-jurisdiction verdict on any row.\n *\n * ## The two store modes are DIFFERENT FACTS and must never be summed\n *\n * `taxMode` is the whole point of this record, and it is derived from\n * `automatic_tax.enabled` — **never** from whether tax lines are present:\n *\n * - **`stripe-automatic`** — Stripe Tax computed it, against whichever\n * account `automatic_tax.liability` names. When that is `platform`, the\n * money is held under Aglyn's registration.\n * - **`manual`** — the merchant's own configured rate\n * (`checkout.ts` / `pos-order.ts`), applied to the merchant's own declared\n * origin. Aglyn's registrations never enter into it and the amount is not\n * Aglyn's to remit.\n *\n * The trap that makes the `automatic_tax.enabled` discriminator load-bearing:\n * a MANUAL-mode subscription renewal carries a real Stripe Tax Rate (AGL-1751\n * attaches one so the tax recurs), so its invoice arrives with a populated\n * `total_taxes[]` — indistinguishable from a Stripe Tax invoice if you look at\n * the tax lines. Summing tax lines would silently book merchant-configured tax\n * as Aglyn-collected. **Read the flag, not the lines.**\n *\n * ## The taxable base is kept, never inferred\n *\n * `taxable_amount` is what a return reports as \"taxable sales\". Deriving it as\n * `amount ÷ rate` needs a live read to resolve the rate id and rounds wrong at\n * the edges, so it is stored when Stripe states it and left `null` when it\n * does not — and a row whose base cannot be read is COUNTED OUT LOUD by the\n * return rather than treated as a zero-base sale.\n *\n * A Checkout Session's `total_details.breakdown` is not in the webhook payload\n * and must be re-read with `expand[]=total_details.breakdown`; an invoice\n * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.\n *\n * ## A DIRECT charge is the seller's tax, never the platform's\n *\n * A seller on its own full Stripe account sells by DIRECT charge: the session\n * is created ON the seller's account (`Stripe-Account` header) and stamped\n * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the\n * SELLER's registrations, the tax settles into the seller's balance, and the\n * seller remits it. Stripe still reports `liability: { type: \"self\" }`, but\n * `self` is then the seller's account, so reading `self` as \"the platform\"\n * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is\n * therefore always `connected-account` here, whatever the field says.\n *\n * Pure and total: unreadable input answers `null`, never throws — a recording\n * failure must never 500 a webhook into redelivery.\n */\n\nimport {\n storefrontTaxMode,\n type StorefrontTaxMode,\n} from '../model/commerce-tax-decision'\n\n/**\n * Which machinery produced the tax on this sale. See the module note.\n *\n * The union and its derivation live in the MODEL since AGL-2451, because the\n * merchant's order document now carries the same fact (`HostOrder.taxMode`)\n * and two copies of a rule that must agree are one copy too many. Re-exported\n * here so this module stays the place the mechanism is documented.\n */\nexport type { StorefrontTaxMode }\n\n/**\n * Whose registrations Stripe Tax computed against, from\n * `automatic_tax.liability.type`: `self` (the account the object lives on,\n * i.e. Aglyn's platform) or `account` (a named connected account). A DIRECT\n * charge lives on the seller's account, so it is always `connected-account`\n * (see the module note). Null whenever `taxMode` is not `stripe-automatic`.\n */\nexport type StorefrontTaxLiability = 'platform' | 'connected-account'\n\n/** One entry of the stored tax breakdown. */\nexport interface StorefrontTaxLine {\n amountCents: number\n /** Stripe's stated reason, e.g. `standard_rated`, `not_collecting`. */\n taxabilityReason: string | null\n taxRateId: string | null\n /** Stripe's `taxable_amount`; null when the shape did not carry it. */\n taxableAmountCents: number | null\n /** e.g. `Texas` — from the expanded rate, for the working papers. */\n jurisdiction: string | null\n /** The rate's own state code, which is not the shopper's address. */\n rateState: string | null\n percentage: number | null\n}\n\n/** The per-transaction record `storefrontTaxCollected/{stripeId}` stores. */\nexport interface StorefrontTaxRow {\n /** `session` for one-time sales, `invoice` for subscription cycles. */\n kind: 'session' | 'invoice'\n hostId: string\n /** The commerce path — `commerce-cart`, `commerce-order`, … */\n metadataType: string | null\n taxMode: StorefrontTaxMode\n taxLiability: StorefrontTaxLiability | null\n /** The merchant's connected account, when the object names one. */\n connectedAccountId: string | null\n /** What the shopper actually paid, tax included. */\n grossCents: number\n taxCents: number\n /** Gross minus tax. NOT Aglyn's revenue — most of it is the merchant's. */\n netCents: number\n currency: string\n /** The jurisdiction input — the shopper's address on the Stripe object. */\n customerAddress: {\n country: string | null\n state: string | null\n city: string | null\n postalCode: string | null\n } | null\n taxLines: StorefrontTaxLine[]\n paidAt: Date | null\n}\n\nfunction asCents(value: unknown): number {\n const cents = Number(value ?? 0)\n return Number.isFinite(cents) ? Math.round(cents) : 0\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value ? value : null\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n const parsed = Number(value ?? NaN)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** Seconds-since-epoch to Date, or null for anything unreadable. */\nfunction asDate(value: unknown): Date | null {\n const seconds = Number(value ?? NaN)\n return Number.isFinite(seconds) && seconds > 0\n ? new Date(seconds * 1000)\n : null\n}\n\nfunction address(source: any): StorefrontTaxRow['customerAddress'] {\n if (!source || typeof source !== 'object') return null\n return {\n country: asStringOrNull(source.country),\n state: asStringOrNull(source.state),\n city: asStringOrNull(source.city),\n postalCode: asStringOrNull(source.postal_code),\n }\n}\n\n/**\n * The breakdown entries, from either shape.\n *\n * A Checkout Session expands them under `total_details.breakdown.taxes[]`\n * with the rate object inline; an invoice carries `total_taxes[]` (rate under\n * `tax_rate_details.tax_rate`) or the older `total_tax_amounts[]` (`tax_rate`,\n * an id or an expanded object). All three map onto one stored line.\n *\n * Exported for the POS hardware shop's own sales (AGL-4038), whose tax rows\n * keep the same lines: one reading of Stripe's breakdown for every half of\n * the return.\n */\nexport function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[] {\n return taxLines(source)\n}\n\nfunction taxLines(source: any): StorefrontTaxLine[] {\n const entries: any[] = Array.isArray(source?.total_details?.breakdown?.taxes)\n ? source.total_details.breakdown.taxes\n : Array.isArray(source?.total_taxes)\n ? source.total_taxes\n : Array.isArray(source?.total_tax_amounts)\n ? source.total_tax_amounts\n : []\n return entries.map((entry: any) => {\n const rate = entry?.rate ?? entry?.tax_rate_details?.tax_rate ?? entry?.tax_rate\n const rateObject = rate && typeof rate === 'object' ? rate : null\n // Distinguish an absent `taxable_amount` from a genuine zero: a zero base\n // is a real fact (`not_collecting`), an absent one means the base is\n // UNKNOWN, and the return has to be able to tell those apart.\n const taxableAmount = Number(entry?.taxable_amount ?? NaN)\n return {\n amountCents: asCents(entry?.amount),\n taxabilityReason: asStringOrNull(entry?.taxability_reason),\n taxRateId: asStringOrNull(rate) ?? asStringOrNull(rateObject?.id),\n taxableAmountCents: Number.isFinite(taxableAmount)\n ? Math.round(taxableAmount)\n : null,\n jurisdiction: asStringOrNull(rateObject?.jurisdiction),\n rateState: asStringOrNull(rateObject?.state),\n percentage:\n asNumberOrNull(rateObject?.effective_percentage) ??\n asNumberOrNull(rateObject?.percentage),\n }\n })\n}\n\n/** Sum of the stored lines' amounts. */\nfunction sumLines(lines: readonly StorefrontTaxLine[]): number {\n return lines.reduce((sum, line) => sum + line.amountCents, 0)\n}\n\nexport interface StorefrontTaxContext {\n kind: 'session' | 'invoice'\n hostId: string\n /**\n * The seller's account for a DIRECT charge, which names no transfer\n * destination: the event's `account`, when the caller has it.\n */\n connectedAccountId?: string | null\n /**\n * The manual-mode tax `checkout.ts` puts over as an ordinary line item.\n * Stripe is never told it is tax, so no Stripe field carries it and the\n * session's own `metadata[taxCents]` is the only witness (AGL-1711).\n */\n manualTaxCents?: number\n}\n\n/** What one Stripe object says about the tax it carried. */\nexport interface ResolvedStorefrontTax {\n /** `automatic_tax.enabled` — the discriminator, never the tax lines. */\n automatic: boolean\n /** Stripe's own breakdown, present only on a `stripe-automatic` sale. */\n lines: StorefrontTaxLine[]\n taxCents: number\n taxMode: StorefrontTaxMode\n}\n\n/**\n * Reads the tax off one paid session or invoice — the SINGLE derivation, and\n * the reason it is its own exported function (AGL-2451).\n *\n * `storefrontTaxRow` builds the `storefrontTaxCollected` record from it, and\n * the four order-writing doors in `billing-webhook.ts` stamp `HostOrder.taxMode`\n * from it, so an order and the row filed for the same Stripe id cannot state\n * different regimes. Re-deriving the mode beside a second reading of the same\n * object is exactly how the two would drift.\n *\n * Pure and total: unreadable input answers `taxMode: 'none'`, never throws.\n */\nexport function resolveStorefrontTax(\n object: unknown,\n manualTaxCents = 0,\n): ResolvedStorefrontTax {\n const source = object as any\n const automatic = source?.automatic_tax?.enabled === true\n const lines = automatic ? taxLines(source) : []\n const manualCents = Math.max(0, asCents(manualTaxCents))\n // The flag, never the lines — see the module note. A manual-mode\n // subscription renewal carries real Stripe tax rates in `total_taxes[]`,\n // and booking those as Aglyn-collected would be the whole defect restated.\n //\n // Read on SESSIONS as well as invoices since AGL-1953: the cart and\n // draft-order paths now carry their manual tax as a real Stripe Tax Rate on\n // the line (the construction that survives a session-level coupon), so a\n // manual session reports a genuine `total_details.amount_tax`. The scalar is\n // the fallback because `total_details.breakdown` is expandable and absent\n // unless the recorder re-read it. Buy-now's `line_items[1]` construction\n // reports 0 in both shapes and still answers from `manualTaxCents` below.\n const manualLineCents = !automatic\n ? sumLines(taxLines(source)) ||\n asCents(source?.total_details?.amount_tax ?? source?.tax)\n : 0\n const taxCents = automatic\n ? // `total_details.amount_tax` on a session, `total_taxes[]` on an\n // invoice. Prefer the summed lines when they exist (a computed invoice\n // can send a 0/null scalar beside a populated array — AGL-1811's\n // measurement), and fall back to the scalar shapes otherwise.\n lines.length > 0\n ? sumLines(lines)\n : asCents(source?.total_details?.amount_tax ?? source?.tax)\n : Math.max(manualCents, manualLineCents)\n return {\n automatic,\n lines,\n taxCents,\n taxMode: storefrontTaxMode({ automatic, taxCents }),\n }\n}\n\n/**\n * Just the regime, for the order-writing doors (AGL-2451). Delegates, so this\n * is the same answer the filed tax record gives for the same object.\n */\nexport function storefrontTaxModeOf(\n object: unknown,\n manualTaxCents = 0,\n): StorefrontTaxMode {\n return resolveStorefrontTax(object, manualTaxCents).taxMode\n}\n\n/**\n * Whether a session, subscription or invoice was sold as a DIRECT charge on\n * the seller's own account, from the `chargeModel` stamp the session doors\n * write (an invoice carries its subscription's under `subscription_details`).\n */\nexport function storefrontSaleIsDirect(object: unknown): boolean {\n const source = object as any\n return (\n (source?.metadata?.chargeModel ??\n source?.subscription_details?.metadata?.chargeModel ??\n source?.parent?.subscription_details?.metadata?.chargeModel) === 'direct'\n )\n}\n\n/**\n * Who owns, and remits, the tax a storefront sale carried: the SELLER for\n * any merchant-configured rate and for every direct charge, and the PLATFORM\n * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was\n * charged. The single answer a summary or a return should read rather than\n * re-deriving it from the liability field.\n */\nexport function storefrontTaxOwner(\n object: unknown,\n manualTaxCents = 0,\n): 'platform' | 'seller' | 'none' {\n const { automatic, taxMode } = resolveStorefrontTax(object, manualTaxCents)\n if (taxMode === 'none') return 'none'\n if (!automatic || storefrontSaleIsDirect(object)) return 'seller'\n const liabilityType = asStringOrNull((object as any)?.automatic_tax?.liability?.type)\n return liabilityType === 'account' ? 'seller' : 'platform'\n}\n\n/**\n * Decomposes a paid storefront session or invoice into the stored row, or\n * `null` when there is no host to attribute it to.\n *\n * The caller decides WHICH objects reach this — the commerce webhook\n * self-selects on `metadata.type`, exactly as every other section does.\n */\nexport function storefrontTaxRow(\n object: unknown,\n context: StorefrontTaxContext,\n): StorefrontTaxRow | null {\n const source = object as any\n const hostId = String(context?.hostId ?? '')\n if (!hostId) return null\n\n const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(\n source,\n context?.manualTaxCents,\n )\n\n const liabilityType = asStringOrNull(source?.automatic_tax?.liability?.type)\n const direct = storefrontSaleIsDirect(source)\n const taxLiability: StorefrontTaxLiability | null = !automatic\n ? null\n : // A direct charge's `self` is the seller's account (module note).\n direct || liabilityType === 'account'\n ? 'connected-account'\n : // `self`, and also an absent liability: Stripe omits the field on\n // older API versions, where the only account a session could be\n // liable under is the one it was created on — the platform.\n 'platform'\n\n const grossCents = asCents(\n context.kind === 'invoice' ? source?.amount_paid : source?.amount_total,\n )\n const transferDestination =\n source?.payment_intent_data?.transfer_data?.destination ??\n source?.transfer_data?.destination\n return {\n kind: context.kind,\n hostId,\n metadataType:\n asStringOrNull(source?.metadata?.type) ??\n asStringOrNull(source?.subscription_details?.metadata?.type) ??\n asStringOrNull(source?.parent?.subscription_details?.metadata?.type),\n taxMode,\n taxLiability,\n connectedAccountId:\n asStringOrNull(transferDestination) ??\n asStringOrNull((transferDestination as any)?.id) ??\n (direct ? asStringOrNull(context?.connectedAccountId) : null),\n grossCents,\n taxCents,\n netCents: grossCents - taxCents,\n currency: asStringOrNull(source?.currency) ?? 'usd',\n customerAddress:\n address(source?.customer_details?.address) ??\n address(source?.customer_address),\n // Stripe's OWN breakdown, whenever Stripe stated one — never an invented\n // base. Buy-now's manual construction states none (Stripe was never told\n // the line was tax) and answers `[]`, which is the honest answer. The\n // cart, draft-order and subscription-renewal manual paths carry a real\n // Tax Rate, so Stripe DOES state a `taxable_amount` for them, and keeping\n // it gives `merchantManual` a real taxable-sales figure instead of a\n // permanent zero (AGL-1953). It never reaches the Aglyn-liable bucket:\n // the classification above is the flag, not these lines.\n taxLines: automatic ? lines : taxLines(source),\n paidAt:\n asDate(source?.status_transitions?.paid_at) ?? asDate(source?.created),\n }\n}\n"],"names":["storefrontTaxMode","asCents","value","cents","Number","isFinite","Math","round","asStringOrNull","asNumberOrNull","parsed","NaN","asDate","seconds","Date","address","source","country","state","city","postalCode","postal_code","stripeTaxBreakdownLines","taxLines","entries","Array","isArray","total_details","breakdown","taxes","total_taxes","total_tax_amounts","map","entry","rate","tax_rate_details","tax_rate","rateObject","taxableAmount","taxable_amount","amountCents","amount","taxabilityReason","taxability_reason","taxRateId","id","taxableAmountCents","jurisdiction","rateState","percentage","effective_percentage","sumLines","lines","reduce","sum","line","resolveStorefrontTax","object","manualTaxCents","automatic","automatic_tax","enabled","manualCents","max","manualLineCents","amount_tax","tax","taxCents","length","taxMode","storefrontTaxModeOf","storefrontSaleIsDirect","metadata","chargeModel","subscription_details","parent","storefrontTaxOwner","liabilityType","liability","type","storefrontTaxRow","context","hostId","String","direct","taxLiability","grossCents","kind","amount_paid","amount_total","transferDestination","payment_intent_data","transfer_data","destination","metadataType","connectedAccountId","netCents","currency","customerAddress","customer_details","customer_address","paidAt","status_transitions","paid_at","created"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwFC,GAED,SACEA,iBAAiB,QAEZ,oCAAgC;AAgEvC,SAASC,QAAQC,KAAc;IAC7B,MAAMC,QAAQC,OAAOF,gBAAAA,QAAS;IAC9B,OAAOE,OAAOC,QAAQ,CAACF,SAASG,KAAKC,KAAK,CAACJ,SAAS;AACtD;AAEA,SAASK,eAAeN,KAAc;IACpC,OAAO,OAAOA,UAAU,YAAYA,QAAQA,QAAQ;AACtD;AAEA,SAASO,eAAeP,KAAc;IACpC,MAAMQ,SAASN,OAAOF,gBAAAA,QAASS;IAC/B,OAAOP,OAAOC,QAAQ,CAACK,UAAUA,SAAS;AAC5C;AAEA,kEAAkE,GAClE,SAASE,OAAOV,KAAc;IAC5B,MAAM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AA,mBAAAA,OAAQwD,QAAQ,qBAAhBxD,iBAAkB+D,IAAI,aAArCvE,kBACAA,eAAeQ,2BAAAA,+BAAAA,OAAQ0D,oBAAoB,sBAA5B1D,wCAAAA,6BAA8BwD,QAAQ,qBAAtCxD,sCAAwC+D,IAAI,aAD3DvE,QAEAA,eAAeQ,2BAAAA,iBAAAA,OAAQ2D,MAAM,sBAAd3D,sCAAAA,eAAgB0D,oBAAoB,sBAApC1D,+CAAAA,oCAAsCwD,QAAQ,qBAA9CxD,6CAAgD+D,IAAI;QACrEV;QACAgB;QACAU,kBAAkB,GAChBvF,SAAAA,mBAAAA,eAAekF,gCAAflF,mBACAA,eAAgBkF,uCAAD,AAACA,oBAA6B7C,EAAE,aAD/CrC,QAEC4E,SAAS5E,eAAeyE,2BAAAA,QAASc,kBAAkB,IAAI;QAC1DT;QACAnB;QACA6B,UAAUV,aAAanB;QACvB8B,QAAQ,GAAEzF,mBAAAA,eAAeQ,0BAAAA,OAAQiF,QAAQ,aAA/BzF,mBAAoC;QAC9C0F,eAAe,GACbnF,WAAAA,QAAQC,2BAAAA,2BAAAA,OAAQmF,gBAAgB,qBAAxBnF,yBAA0BD,OAAO,aAAzCA,WACAA,QAAQC,0BAAAA,OAAQoF,gBAAgB;QAClC,yEAAyE;QACzE,yEAAyE;QACzE,sEAAsE;QACtE,uEAAuE;QACvE,0EAA0E;QAC1E,qEAAqE;QACrE,uEAAuE;QACvE,yDAAyD;QACzD7E,UAAUoC,YAAYP,QAAQ7B,SAASP;QACvCqF,MAAM,GACJzF,UAAAA,OAAOI,2BAAAA,6BAAAA,OAAQsF,kBAAkB,qBAA1BtF,2BAA4BuF,OAAO,aAA1C3F,UAA+CA,OAAOI,0BAAAA,OAAQwF,OAAO;IACzE;AACF"}
@@ -27,6 +27,16 @@
27
27
  * refunded share, as it always has.
28
28
  * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund
29
29
  * at Stripe and never a second one.
30
+ *
31
+ * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON
32
+ * that account with the `Stripe-Account` header: the money comes out of the
33
+ * seller's balance, where the sale settled, so there is no transfer to
34
+ * reverse and `reverse_transfer` is never sent. `refund_application_fee` is
35
+ * kept, so Aglyn hands its fee back on the refunded share exactly as it does
36
+ * on a destination charge. A payment intent the seller's account does not
37
+ * know (a sale from before the seller switched, or Aglyn's own hardware) is
38
+ * refunded on the platform as a destination charge, so a caller may pass the
39
+ * site's direct-charge account without first asking which kind the sale was.
30
40
  */
31
41
  export type StripeRefundResult = {
32
42
  ok: true;
@@ -42,6 +52,11 @@ export declare function createStripeRefund(input: {
42
52
  amountCents: number;
43
53
  idempotencyKey?: string | null;
44
54
  metadata?: Record<string, string>;
55
+ /**
56
+ * The seller's connected account when the sale was (or may have been) a
57
+ * DIRECT charge. Absent for a destination sale.
58
+ */
59
+ stripeAccount?: string | null;
45
60
  fetch?: typeof fetch;
46
61
  secretKey?: string;
47
62
  }): Promise<StripeRefundResult>;
@@ -26,9 +26,20 @@
26
26
  * refunded share, as it always has.
27
27
  * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund
28
28
  * at Stripe and never a second one.
29
+ *
30
+ * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON
31
+ * that account with the `Stripe-Account` header: the money comes out of the
32
+ * seller's balance, where the sale settled, so there is no transfer to
33
+ * reverse and `reverse_transfer` is never sent. `refund_application_fee` is
34
+ * kept, so Aglyn hands its fee back on the refunded share exactly as it does
35
+ * on a destination charge. A payment intent the seller's account does not
36
+ * know (a sale from before the seller switched, or Aglyn's own hardware) is
37
+ * refunded on the platform as a destination charge, so a caller may pass the
38
+ * site's direct-charge account without first asking which kind the sale was.
29
39
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
30
40
  export async function createStripeRefund(input) {
31
- var _input_secretKey, _input_metadata, _input_fetch, _ref;
41
+ var _input_secretKey, _input_fetch, _ref, _ref1;
42
+ var _refund_error, _refund_error1;
32
43
  const secretKey = (_input_secretKey = input.secretKey) != null ? _input_secretKey : process.env.STRIPE_SECRET_KEY;
33
44
  if (!secretKey) {
34
45
  return {
@@ -38,31 +49,48 @@ export async function createStripeRefund(input) {
38
49
  code: 'not_configured'
39
50
  };
40
51
  }
41
- const params = new URLSearchParams({
42
- payment_intent: input.paymentIntentId,
43
- amount: String(Math.round(input.amountCents)),
44
- reverse_transfer: 'true',
45
- refund_application_fee: 'true'
46
- });
47
- for (const [key, value] of Object.entries((_input_metadata = input.metadata) != null ? _input_metadata : {})){
48
- params.set(`metadata[${key}]`, value);
49
- }
50
52
  const send = (_input_fetch = input.fetch) != null ? _input_fetch : fetch;
51
- const response = await send('https://api.stripe.com/v1/refunds', {
52
- method: 'POST',
53
- headers: _extends({
54
- Authorization: `Bearer ${secretKey}`,
55
- 'Content-Type': 'application/x-www-form-urlencoded'
56
- }, input.idempotencyKey ? {
57
- 'Idempotency-Key': input.idempotencyKey
58
- } : {}),
59
- body: params.toString()
60
- });
61
- const refund = await Promise.resolve().then(()=>response.json()).catch(()=>({}));
53
+ const post = (stripeAccount)=>{
54
+ var _input_metadata;
55
+ const params = new URLSearchParams(_extends({
56
+ payment_intent: input.paymentIntentId,
57
+ amount: String(Math.round(input.amountCents))
58
+ }, stripeAccount ? {} : {
59
+ reverse_transfer: 'true'
60
+ }, {
61
+ refund_application_fee: 'true'
62
+ }));
63
+ for (const [key, value] of Object.entries((_input_metadata = input.metadata) != null ? _input_metadata : {})){
64
+ params.set(`metadata[${key}]`, value);
65
+ }
66
+ return send('https://api.stripe.com/v1/refunds', {
67
+ method: 'POST',
68
+ headers: _extends({
69
+ Authorization: `Bearer ${secretKey}`,
70
+ 'Content-Type': 'application/x-www-form-urlencoded'
71
+ }, input.idempotencyKey ? {
72
+ 'Idempotency-Key': input.idempotencyKey
73
+ } : {}, stripeAccount ? {
74
+ 'Stripe-Account': stripeAccount
75
+ } : {}),
76
+ body: params.toString()
77
+ });
78
+ };
79
+ const stripeAccount = typeof input.stripeAccount === 'string' && input.stripeAccount.trim() ? input.stripeAccount.trim() : null;
80
+ const read = async (sent)=>await Promise.resolve().then(()=>sent.json()).catch(()=>({}));
81
+ let response = await post(stripeAccount);
82
+ let refund = await read(response);
83
+ // Not the seller's payment: a destination sale on the platform. Stripe
84
+ // answers a payment intent another account owns as `resource_missing`, and
85
+ // scopes idempotency keys per account, so the same key is safe there.
86
+ if (stripeAccount && !response.ok && (response.status === 404 || (refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) === 'resource_missing' && ((_ref = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.param) != null ? _ref : 'payment_intent') === 'payment_intent')) {
87
+ response = await post(null);
88
+ refund = await read(response);
89
+ }
62
90
  if (!response.ok) {
63
- var _ref1, _ref2;
64
- var _refund_error, _refund_error1;
65
- const code = String((_ref1 = refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) != null ? _ref1 : '');
91
+ var _ref2, _ref3;
92
+ var _refund_error2, _refund_error3;
93
+ const code = String((_ref2 = refund == null ? void 0 : (_refund_error2 = refund.error) == null ? void 0 : _refund_error2.code) != null ? _ref2 : '');
66
94
  if (code === 'charge_disputed' || code === 'refund_disputed_payment') {
67
95
  return {
68
96
  ok: false,
@@ -75,12 +103,12 @@ export async function createStripeRefund(input) {
75
103
  ok: false,
76
104
  status: 502,
77
105
  code,
78
- error: (_ref2 = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.message) != null ? _ref2 : 'Refund failed'
106
+ error: (_ref3 = refund == null ? void 0 : (_refund_error3 = refund.error) == null ? void 0 : _refund_error3.message) != null ? _ref3 : 'Refund failed'
79
107
  };
80
108
  }
81
109
  return {
82
110
  ok: true,
83
- refundId: String((_ref = refund == null ? void 0 : refund.id) != null ? _ref : '')
111
+ refundId: String((_ref1 = refund == null ? void 0 : refund.id) != null ? _ref1 : '')
84
112
  };
85
113
  }
86
114
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stripe-refund.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 * ONE STRIPE REFUND, the way every commerce refund sends one (AGL-3609).\n *\n * Shared by the order dialog's refund (`refund.ts`) and a return at the\n * register (`pos-return.ts`), so both take the money back the same way:\n *\n * - `reverse_transfer`: a destination charge's money sits in the\n * merchant's connected account, so the refund pulls it back from there\n * rather than out of the platform's balance.\n * - `refund_application_fee`: the platform hands its fee back on the\n * refunded share, as it always has.\n * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund\n * at Stripe and never a second one.\n */\nexport type StripeRefundResult =\n | { ok: true; refundId: string }\n | { ok: false; status: number; error: string; code: string }\n\nexport async function createStripeRefund(input: {\n paymentIntentId: string\n amountCents: number\n idempotencyKey?: string | null\n metadata?: Record<string, string>\n fetch?: typeof fetch\n secretKey?: string\n}): Promise<StripeRefundResult> {\n const secretKey = input.secretKey ?? process.env.STRIPE_SECRET_KEY\n if (!secretKey) {\n return { ok: false, status: 501, error: 'Payments are not configured.', code: 'not_configured' }\n }\n const params = new URLSearchParams({\n payment_intent: input.paymentIntentId,\n amount: String(Math.round(input.amountCents)),\n reverse_transfer: 'true',\n refund_application_fee: 'true',\n })\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n params.set(`metadata[${key}]`, value)\n }\n const send = input.fetch ?? fetch\n const response = await send('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(input.idempotencyKey ? { 'Idempotency-Key': input.idempotencyKey } : {}),\n },\n body: params.toString(),\n })\n const refund = (await Promise.resolve()\n .then(() => response.json())\n .catch(() => ({}))) as {\n id?: string\n error?: { code?: string; message?: string }\n }\n if (!response.ok) {\n const code = String(refund?.error?.code ?? '')\n if (code === 'charge_disputed' || code === 'refund_disputed_payment') {\n return {\n ok: false,\n status: 409,\n code,\n error:\n 'Stripe refused this refund because the charge is disputed. ' +\n 'Respond to the dispute or accept it in the Stripe dashboard; ' +\n 'refund any remainder once it settles.',\n }\n }\n return { ok: false, status: 502, code, error: refund?.error?.message ?? 'Refund failed' }\n }\n return { ok: true, refundId: String(refund?.id ?? '') }\n}\n"],"names":["createStripeRefund","input","secretKey","process","env","STRIPE_SECRET_KEY","ok","status","error","code","params","URLSearchParams","payment_intent","paymentIntentId","amount","String","Math","round","amountCents","reverse_transfer","refund_application_fee","key","value","Object","entries","metadata","set","send","fetch","response","method","headers","Authorization","idempotencyKey","body","toString","refund","Promise","resolve","then","json","catch","message","refundId","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAKD,OAAO,eAAeA,mBAAmBC,KAOxC;QACmBA,kBAUwBA,iBAG7BA;IAbb,MAAMC,aAAYD,mBAAAA,MAAMC,SAAS,YAAfD,mBAAmBE,QAAQC,GAAG,CAACC,iBAAiB;IAClE,IAAI,CAACH,WAAW;QACd,OAAO;YAAEI,IAAI;YAAOC,QAAQ;YAAKC,OAAO;YAAgCC,MAAM;QAAiB;IACjG;IACA,MAAMC,SAAS,IAAIC,gBAAgB;QACjCC,gBAAgBX,MAAMY,eAAe;QACrCC,QAAQC,OAAOC,KAAKC,KAAK,CAAChB,MAAMiB,WAAW;QAC3CC,kBAAkB;QAClBC,wBAAwB;IAC1B;IACA,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,EAACvB,kBAAAA,MAAMwB,QAAQ,YAAdxB,kBAAkB,CAAC,GAAI;QAC/DS,OAAOgB,GAAG,CAAC,CAAC,SAAS,EAAEL,IAAI,CAAC,CAAC,EAAEC;IACjC;IACA,MAAMK,QAAO1B,eAAAA,MAAM2B,KAAK,YAAX3B,eAAe2B;IAC5B,MAAMC,WAAW,MAAMF,KAAK,qCAAqC;QAC/DG,QAAQ;QACRC,SAAS;YACPC,eAAe,CAAC,OAAO,EAAE9B,WAAW;YACpC,gBAAgB;WACZD,MAAMgC,cAAc,GAAG;YAAE,mBAAmBhC,MAAMgC,cAAc;QAAC,IAAI,CAAC;QAE5EC,MAAMxB,OAAOyB,QAAQ;IACvB;IACA,MAAMC,SAAU,MAAMC,QAAQC,OAAO,GAClCC,IAAI,CAAC,IAAMV,SAASW,IAAI,IACxBC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IAIjB,IAAI,CAACZ,SAASvB,EAAE,EAAE;;YACI8B,eAY0BA;QAZ9C,MAAM3B,OAAOM,gBAAOqB,2BAAAA,gBAAAA,OAAQ5B,KAAK,qBAAb4B,cAAe3B,IAAI,oBAAI;QAC3C,IAAIA,SAAS,qBAAqBA,SAAS,2BAA2B;YACpE,OAAO;gBACLH,IAAI;gBACJC,QAAQ;gBACRE;gBACAD,OACE,gEACA,kEACA;YACJ;QACF;QACA,OAAO;YAAEF,IAAI;YAAOC,QAAQ;YAAKE;YAAMD,KAAK,WAAE4B,2BAAAA,iBAAAA,OAAQ5B,KAAK,qBAAb4B,eAAeM,OAAO,oBAAI;QAAgB;IAC1F;IACA,OAAO;QAAEpC,IAAI;QAAMqC,UAAU5B,eAAOqB,0BAAAA,OAAQQ,EAAE,mBAAI;IAAI;AACxD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stripe-refund.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 * ONE STRIPE REFUND, the way every commerce refund sends one (AGL-3609).\n *\n * Shared by the order dialog's refund (`refund.ts`) and a return at the\n * register (`pos-return.ts`), so both take the money back the same way:\n *\n * - `reverse_transfer`: a destination charge's money sits in the\n * merchant's connected account, so the refund pulls it back from there\n * rather than out of the platform's balance.\n * - `refund_application_fee`: the platform hands its fee back on the\n * refunded share, as it always has.\n * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund\n * at Stripe and never a second one.\n *\n * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON\n * that account with the `Stripe-Account` header: the money comes out of the\n * seller's balance, where the sale settled, so there is no transfer to\n * reverse and `reverse_transfer` is never sent. `refund_application_fee` is\n * kept, so Aglyn hands its fee back on the refunded share exactly as it does\n * on a destination charge. A payment intent the seller's account does not\n * know (a sale from before the seller switched, or Aglyn's own hardware) is\n * refunded on the platform as a destination charge, so a caller may pass the\n * site's direct-charge account without first asking which kind the sale was.\n */\nexport type StripeRefundResult =\n | { ok: true; refundId: string }\n | { ok: false; status: number; error: string; code: string }\n\nexport async function createStripeRefund(input: {\n paymentIntentId: string\n amountCents: number\n idempotencyKey?: string | null\n metadata?: Record<string, string>\n /**\n * The seller's connected account when the sale was (or may have been) a\n * DIRECT charge. Absent for a destination sale.\n */\n stripeAccount?: string | null\n fetch?: typeof fetch\n secretKey?: string\n}): Promise<StripeRefundResult> {\n const secretKey = input.secretKey ?? process.env.STRIPE_SECRET_KEY\n if (!secretKey) {\n return { ok: false, status: 501, error: 'Payments are not configured.', code: 'not_configured' }\n }\n const send = input.fetch ?? fetch\n const post = (stripeAccount: string | null) => {\n const params = new URLSearchParams({\n payment_intent: input.paymentIntentId,\n amount: String(Math.round(input.amountCents)),\n ...(stripeAccount ? {} : { reverse_transfer: 'true' }),\n refund_application_fee: 'true',\n })\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n params.set(`metadata[${key}]`, value)\n }\n return send('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(input.idempotencyKey ? { 'Idempotency-Key': input.idempotencyKey } : {}),\n ...(stripeAccount ? { 'Stripe-Account': stripeAccount } : {}),\n },\n body: params.toString(),\n })\n }\n const stripeAccount =\n typeof input.stripeAccount === 'string' && input.stripeAccount.trim()\n ? input.stripeAccount.trim()\n : null\n type RefundBody = {\n id?: string\n error?: { code?: string; message?: string; param?: string }\n }\n const read = async (sent: Response): Promise<RefundBody> =>\n (await Promise.resolve()\n .then(() => sent.json())\n .catch(() => ({}))) as RefundBody\n let response = await post(stripeAccount)\n let refund = await read(response)\n // Not the seller's payment: a destination sale on the platform. Stripe\n // answers a payment intent another account owns as `resource_missing`, and\n // scopes idempotency keys per account, so the same key is safe there.\n if (\n stripeAccount &&\n !response.ok &&\n (response.status === 404 ||\n (refund?.error?.code === 'resource_missing' &&\n (refund?.error?.param ?? 'payment_intent') === 'payment_intent'))\n ) {\n response = await post(null)\n refund = await read(response)\n }\n if (!response.ok) {\n const code = String(refund?.error?.code ?? '')\n if (code === 'charge_disputed' || code === 'refund_disputed_payment') {\n return {\n ok: false,\n status: 409,\n code,\n error:\n 'Stripe refused this refund because the charge is disputed. ' +\n 'Respond to the dispute or accept it in the Stripe dashboard; ' +\n 'refund any remainder once it settles.',\n }\n }\n return { ok: false, status: 502, code, error: refund?.error?.message ?? 'Refund failed' }\n }\n return { ok: true, refundId: String(refund?.id ?? '') }\n}\n"],"names":["createStripeRefund","input","refund","secretKey","process","env","STRIPE_SECRET_KEY","ok","status","error","code","send","fetch","post","stripeAccount","params","URLSearchParams","payment_intent","paymentIntentId","amount","String","Math","round","amountCents","reverse_transfer","refund_application_fee","key","value","Object","entries","metadata","set","method","headers","Authorization","idempotencyKey","body","toString","trim","read","sent","Promise","resolve","then","json","catch","response","param","message","refundId","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC;AAKD,OAAO,eAAeA,mBAAmBC,KAYxC;QACmBA,kBAILA;QA2CRC,eACEA;IAhDP,MAAMC,aAAYF,mBAAAA,MAAME,SAAS,YAAfF,mBAAmBG,QAAQC,GAAG,CAACC,iBAAiB;IAClE,IAAI,CAACH,WAAW;QACd,OAAO;YAAEI,IAAI;YAAOC,QAAQ;YAAKC,OAAO;YAAgCC,MAAM;QAAiB;IACjG;IACA,MAAMC,QAAOV,eAAAA,MAAMW,KAAK,YAAXX,eAAeW;IAC5B,MAAMC,OAAO,CAACC;YAO8Bb;QAN1C,MAAMc,SAAS,IAAIC,gBAAgB;YACjCC,gBAAgBhB,MAAMiB,eAAe;YACrCC,QAAQC,OAAOC,KAAKC,KAAK,CAACrB,MAAMsB,WAAW;WACvCT,gBAAgB,CAAC,IAAI;YAAEU,kBAAkB;QAAO;YACpDC,wBAAwB;;QAE1B,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,EAAC5B,kBAAAA,MAAM6B,QAAQ,YAAd7B,kBAAkB,CAAC,GAAI;YAC/Dc,OAAOgB,GAAG,CAAC,CAAC,SAAS,EAAEL,IAAI,CAAC,CAAC,EAAEC;QACjC;QACA,OAAOhB,KAAK,qCAAqC;YAC/CqB,QAAQ;YACRC,SAAS;gBACPC,eAAe,CAAC,OAAO,EAAE/B,WAAW;gBACpC,gBAAgB;eACZF,MAAMkC,cAAc,GAAG;gBAAE,mBAAmBlC,MAAMkC,cAAc;YAAC,IAAI,CAAC,GACtErB,gBAAgB;gBAAE,kBAAkBA;YAAc,IAAI,CAAC;YAE7DsB,MAAMrB,OAAOsB,QAAQ;QACvB;IACF;IACA,MAAMvB,gBACJ,OAAOb,MAAMa,aAAa,KAAK,YAAYb,MAAMa,aAAa,CAACwB,IAAI,KAC/DrC,MAAMa,aAAa,CAACwB,IAAI,KACxB;IAKN,MAAMC,OAAO,OAAOC,OACjB,MAAMC,QAAQC,OAAO,GACnBC,IAAI,CAAC,IAAMH,KAAKI,IAAI,IACpBC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IACnB,IAAIC,WAAW,MAAMjC,KAAKC;IAC1B,IAAIZ,SAAS,MAAMqC,KAAKO;IACxB,uEAAuE;IACvE,2EAA2E;IAC3E,sEAAsE;IACtE,IACEhC,iBACA,CAACgC,SAASvC,EAAE,IACXuC,CAAAA,SAAStC,MAAM,KAAK,OAClBN,CAAAA,2BAAAA,gBAAAA,OAAQO,KAAK,qBAAbP,cAAeQ,IAAI,MAAK,sBACvB,SAACR,2BAAAA,iBAAAA,OAAQO,KAAK,qBAAbP,eAAe6C,KAAK,mBAAI,sBAAsB,gBAAgB,GACnE;QACAD,WAAW,MAAMjC,KAAK;QACtBX,SAAS,MAAMqC,KAAKO;IACtB;IACA,IAAI,CAACA,SAASvC,EAAE,EAAE;;YACIL,gBAY0BA;QAZ9C,MAAMQ,OAAOU,gBAAOlB,2BAAAA,iBAAAA,OAAQO,KAAK,qBAAbP,eAAeQ,IAAI,oBAAI;QAC3C,IAAIA,SAAS,qBAAqBA,SAAS,2BAA2B;YACpE,OAAO;gBACLH,IAAI;gBACJC,QAAQ;gBACRE;gBACAD,OACE,gEACA,kEACA;YACJ;QACF;QACA,OAAO;YAAEF,IAAI;YAAOC,QAAQ;YAAKE;YAAMD,KAAK,WAAEP,2BAAAA,iBAAAA,OAAQO,KAAK,qBAAbP,eAAe8C,OAAO,oBAAI;QAAgB;IAC1F;IACA,OAAO;QAAEzC,IAAI;QAAM0C,UAAU7B,gBAAOlB,0BAAAA,OAAQgD,EAAE,oBAAI;IAAI;AACxD"}
@@ -13,7 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { readSiteReturnHost, siteReturnUrl } from "@aglyn/aglyn/app-utils/site-return-url";
16
+ */ import { directSellerAccountForHost, fetchOnSellerThenPlatform } from "./seller-stripe-account.js";
17
+ import { readSiteReturnHost, siteReturnUrl } from "@aglyn/aglyn/app-utils/site-return-url";
17
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
19
  import { requireActiveMember } from "./membership.js";
19
20
  /**
@@ -53,6 +54,10 @@ import { requireActiveMember } from "./membership.js";
53
54
  });
54
55
  const subscriptions = await hostRef.collection('subscriptions').where('customerEmail', '==', email).limit(1).get();
55
56
  const customerId = (_subscriptions_docs_ = subscriptions.docs[0]) == null ? void 0 : _subscriptions_docs_.get('stripeCustomerId');
57
+ // A direct-charge subscription's customer lives on the seller's account,
58
+ // so the portal session is opened there; the seller's own portal
59
+ // settings in their Stripe Dashboard apply.
60
+ const sellerAccount = await directSellerAccountForHost(hostId);
56
61
  if (!customerId) {
57
62
  return res.status(404).json({
58
63
  error: 'No subscription found'
@@ -67,7 +72,7 @@ import { requireActiveMember } from "./membership.js";
67
72
  site: await readSiteReturnHost(hostRef),
68
73
  requestHost: String((_req_headers_host = req.headers.host) != null ? _req_headers_host : '')
69
74
  });
70
- const response = await fetch('https://api.stripe.com/v1/billing_portal/sessions', {
75
+ const response = await fetchOnSellerThenPlatform('https://api.stripe.com/v1/billing_portal/sessions', {
71
76
  method: 'POST',
72
77
  headers: {
73
78
  Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
@@ -77,7 +82,7 @@ import { requireActiveMember } from "./membership.js";
77
82
  customer: String(customerId),
78
83
  return_url: returnUrl
79
84
  }).toString()
80
- });
85
+ }, sellerAccount);
81
86
  const session = await response.json();
82
87
  if (!response.ok || !session.url) {
83
88
  console.error('Portal error', session == null ? void 0 : session.error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/subscription-portal.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 { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { requireActiveMember } from './membership'\n\n/**\n * Subscriber self-service (AGL-303): opens the Stripe Billing Portal for\n * the signed-in member's storefront subscription (cancel, switch\n * payment method). Member-gated; the portal customer is matched by the\n * member's email through the recorded subscription doc.\n */\nexport const subscriptionPortalHandler: 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: 'Billing is not configured.' })\n }\n const hostId = String(req.body?.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // open the billing portal — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const email = String(auth.member.get('email') ?? '')\n if (!email) return res.status(401).json({ error: 'Not signed in' })\n const subscriptions = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(1)\n .get()\n const customerId = subscriptions.docs[0]?.get('stripeCustomerId')\n if (!customerId) {\n return res.status(404).json({ error: 'No subscription found' })\n }\n // The site's own page, never a header's say-so (AGL-3363).\n const returnUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const response = await fetch(\n 'https://api.stripe.com/v1/billing_portal/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n customer: String(customerId),\n return_url: returnUrl,\n }).toString(),\n },\n )\n const session = await response.json()\n if (!response.ok || !session.url) {\n console.error('Portal error', session?.error)\n return res.status(502).json({ error: 'Portal unavailable' })\n }\n return res.status(200).json({ url: session.url })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Portal unavailable' })\n }\n}\n"],"names":["readSiteReturnHost","siteReturnUrl","firebaseAdmin","requireActiveMember","subscriptionPortalHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","hostId","String","body","auth","subscriptions","firestore","app","hostRef","collection","doc","email","member","get","where","limit","customerId","docs","returnUrl","candidates","headers","referer","host","site","requestHost","response","fetch","Authorization","URLSearchParams","customer","return_url","toString","session","ok","url","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,aAAa,QAAQ,yCAAwC;AAE1F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,kBAAc;AAElD;;;;;CAKC,GACD,OAAO,MAAMC,4BAA8C,OAAOC,KAAKC;;QAO/CD;IANtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOP,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA6B;IACpE;IACA,MAAMI,SAASC,gBAAOV,YAAAA,IAAIW,IAAI,qBAARX,UAAUS,MAAM,mBAAI;IAC1C,IAAI,CAACA,QAAQ,OAAOR,I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AAiB,EAAE;gBACxD,gBAAgB;YAClB;YACAG,MAAM,IAAIyB,gBAAgB;gBACxBC,UAAU3B,OAAOc;gBACjBc,YAAYZ;YACd,GAAGa,QAAQ;QACb;QAEF,MAAMC,UAAU,MAAMP,SAAS7B,IAAI;QACnC,IAAI,CAAC6B,SAASQ,EAAE,IAAI,CAACD,QAAQE,GAAG,EAAE;YAChCC,QAAQtC,KAAK,CAAC,gBAAgBmC,2BAAAA,QAASnC,KAAK;YAC5C,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAqB;QAC5D;QACA,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEsC,KAAKF,QAAQE,GAAG;QAAC;IACjD,EAAE,OAAOrC,OAAO;QACdsC,QAAQtC,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/subscription-portal.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { requireActiveMember } from './membership'\n\n/**\n * Subscriber self-service (AGL-303): opens the Stripe Billing Portal for\n * the signed-in member's storefront subscription (cancel, switch\n * payment method). Member-gated; the portal customer is matched by the\n * member's email through the recorded subscription doc.\n */\nexport const subscriptionPortalHandler: 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: 'Billing is not configured.' })\n }\n const hostId = String(req.body?.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // open the billing portal — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const email = String(auth.member.get('email') ?? '')\n if (!email) return res.status(401).json({ error: 'Not signed in' })\n const subscriptions = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(1)\n .get()\n const customerId = subscriptions.docs[0]?.get('stripeCustomerId')\n // A direct-charge subscription's customer lives on the seller's account,\n // so the portal session is opened there; the seller's own portal\n // settings in their Stripe Dashboard apply.\n const sellerAccount = await directSellerAccountForHost(hostId)\n if (!customerId) {\n return res.status(404).json({ error: 'No subscription found' })\n }\n // The site's own page, never a header's say-so (AGL-3363).\n const returnUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const response = await fetchOnSellerThenPlatform(\n 'https://api.stripe.com/v1/billing_portal/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n customer: String(customerId),\n return_url: returnUrl,\n }).toString(),\n },\n sellerAccount,\n )\n const session = await response.json()\n if (!response.ok || !session.url) {\n console.error('Portal error', session?.error)\n return res.status(502).json({ error: 'Portal unavailable' })\n }\n return res.status(200).json({ url: session.url })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Portal unavailable' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","readSiteReturnHost","siteReturnUrl","firebaseAdmin","requireActiveMember","subscriptionPortalHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","hostId","String","body","auth","subscriptions","firestore","app","hostRef","collection","doc","email","member","get","where","limit","customerId","docs","sellerAccount","returnUrl","candidates","headers","referer","host","site","requestHost","response","Authorization","URLSearchParams","customer","return_url","toString","session","ok","url","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,yCAAwC;AAE1F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,kBAAc;AAElD;;;;;CAKC,GACD,OAAO,MAAMC,4BAA8C,OAAOC,KAAKC;;QAO/CD;IANtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOP,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA6B;IACpE;IACA,MAAMI,SAASC,gBAAOV,YAAAA,IAAIW,IAAI,qBAARX,UAAUS,MAAM,mBAAI;IAC1C,IAAI,CAACA,QAAQ,OAAOR,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;IAAiB;IAEnE,IAAI;YAOmBO,kBAiBCZ,sBAEAA;YAZHa;QAbnB,gEAAgE;QAChE,mEAAmE;QACnE,MAAMD,OAAO,MAAMd,oBAAoBE,KAAKC,KAAKQ;QACjD,IAAI,CAACG,MAAM;QACX,MAAME,YAAYjB,cAAckB,GAAG,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