@nextblock-cms/ecom 0.21.3 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/index.cjs +1 -1
  2. package/index.es.js +31 -31
  3. package/lib/components/Checkout.cjs +1 -1
  4. package/lib/components/Checkout.es.js +2 -1
  5. package/lib/coupon-server.cjs +1 -1
  6. package/lib/coupon-server.d.ts +65 -1
  7. package/lib/coupon-server.es.js +151 -91
  8. package/lib/coupons.cjs +1 -1
  9. package/lib/coupons.d.ts +13 -0
  10. package/lib/coupons.es.js +5 -4
  11. package/lib/invoice-server.cjs +2 -2
  12. package/lib/invoice-server.es.js +22 -22
  13. package/lib/order-access-token.cjs +1 -0
  14. package/lib/order-access-token.d.ts +2 -0
  15. package/lib/order-access-token.es.js +18 -0
  16. package/lib/pages/cms/orders/actions.cjs +3 -3
  17. package/lib/pages/cms/orders/actions.es.js +48 -26
  18. package/lib/pages/cms/orders/export-actions.cjs +1 -1
  19. package/lib/pages/cms/orders/export-actions.d.ts +42 -1
  20. package/lib/pages/cms/orders/export-actions.es.js +18 -16
  21. package/lib/pages/cms/orders/server-actions.cjs +1 -1
  22. package/lib/pages/cms/orders/server-actions.es.js +25 -15
  23. package/lib/pages/cms/products/actions.cjs +4 -4
  24. package/lib/pages/cms/products/actions.es.js +44 -41
  25. package/lib/pages/cms/products/inventory/actions.cjs +2 -2
  26. package/lib/pages/cms/products/inventory/actions.es.js +23 -23
  27. package/lib/pages/cms/products/server-actions.cjs +1 -1
  28. package/lib/pages/cms/products/server-actions.es.js +109 -108
  29. package/lib/pages/cms/shipping/server-actions.cjs +1 -1
  30. package/lib/pages/cms/shipping/server-actions.es.js +27 -26
  31. package/lib/payment-config.cjs +1 -1
  32. package/lib/payment-config.d.ts +4 -2
  33. package/lib/payment-config.es.js +73 -72
  34. package/lib/product-actions.cjs +1 -1
  35. package/lib/product-actions.es.js +6 -6
  36. package/lib/providers/checkout-items.cjs +1 -0
  37. package/lib/providers/checkout-items.d.ts +30 -0
  38. package/lib/providers/checkout-items.es.js +43 -0
  39. package/lib/providers/freemius.cjs +1 -1
  40. package/lib/providers/freemius.d.ts +1 -1
  41. package/lib/providers/freemius.es.js +166 -144
  42. package/lib/providers/stripe.cjs +1 -1
  43. package/lib/providers/stripe.d.ts +1 -1
  44. package/lib/providers/stripe.es.js +191 -146
  45. package/lib/server-actions/coupon-actions.cjs +1 -1
  46. package/lib/server-actions/coupon-actions.d.ts +11 -12
  47. package/lib/server-actions/coupon-actions.es.js +19 -11
  48. package/lib/server-actions/require-ecom-role.cjs +1 -0
  49. package/lib/server-actions/require-ecom-role.d.ts +5825 -0
  50. package/lib/server-actions/require-ecom-role.es.js +24 -0
  51. package/lib/server-actions/shipping-actions.cjs +1 -1
  52. package/lib/server-actions/shipping-actions.es.js +4 -4
  53. package/lib/server-actions/tax-actions.cjs +1 -1
  54. package/lib/server-actions/tax-actions.es.js +22 -18
  55. package/lib/shipping/checkout-shipping-method.cjs +7 -0
  56. package/lib/shipping/checkout-shipping-method.d.ts +115 -0
  57. package/lib/shipping/checkout-shipping-method.es.js +167 -0
  58. package/lib/shipping/resolver.cjs +1 -7
  59. package/lib/shipping/resolver.d.ts +7 -12
  60. package/lib/shipping/resolver.es.js +13 -38
  61. package/package.json +4 -4
  62. package/server.cjs +1 -1
  63. package/server.d.ts +1 -0
  64. package/server.es.js +49 -48
package/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./lib/types.cjs"),t=require("./lib/currency.cjs"),n=require("./lib/currency-store.cjs"),r=require("./lib/CurrencyProvider.cjs"),i=require("./lib/cart-store.cjs"),a=require("./lib/use-cart.cjs"),o=require("./lib/trials.cjs"),s=require("./lib/coupons.cjs"),c=require("./lib/components/CouponForm.cjs"),l=require("./lib/components/CartDrawer.cjs"),u=require("./lib/variation-utils.cjs"),d=require("./lib/components/Cart.cjs"),f=require("./lib/PaymentReadinessProvider.cjs"),p=require("./lib/customer.cjs"),m=require("./lib/components/Checkout.cjs"),h=require("./lib/components/CartIcon.cjs"),g=require("./lib/components/CurrencySwitcher.cjs"),_=require("./lib/components/AddToCartButton.cjs"),v=require("./lib/components/ProductCard.cjs"),y=require("./lib/components/ProductGrid.cjs"),b=require("./lib/invoice-ui.cjs"),x=require("./lib/components/ProductGallery.cjs"),S=require("./lib/components/SimpleTiptapRenderer.cjs"),C=require("./lib/components/FeaturedProduct.cjs"),w=require("./lib/components/AccountNavigationMenu.cjs"),T=require("./lib/components/CustomerProfileForm.cjs"),E=require("./lib/components/SubscriptionSelector.cjs"),D=require("./lib/invoice.cjs"),O=require("./lib/order-tax-details.cjs"),k=require("./lib/components/InvoiceDocument.cjs"),A=require("./lib/components/InvoiceViewerShell.cjs"),j=require("./lib/components/FreemiusLicensePanel.cjs"),M=require("./lib/product-schema.cjs"),N=require("./lib/pages/cms/products/components/ProductCategorySelector.cjs"),P=require("./lib/pages/cms/products/components/ProductForm.cjs"),F=require("./lib/product-context.cjs"),I=require("./lib/components/ProductDetailsLayout.cjs");exports.AccountNavigationMenu=w.AccountNavigationMenu,exports.AddToCartButton=_.AddToCartButton,exports.CURRENCY_ROUNDING_MODES=t.CURRENCY_ROUNDING_MODES,exports.Cart=d.Cart,exports.CartDrawer=l.CartDrawer,exports.CartIcon=h.CartIcon,exports.Checkout=m.Checkout,exports.CouponForm=c.CouponForm,exports.CurrencyProvider=r.CurrencyProvider,exports.CurrencySwitcher=g.CurrencySwitcher,exports.CustomerProfileForm=T.CustomerProfileForm,exports.DEFAULT_ENABLED_PAYMENT_PROVIDERS=e.DEFAULT_ENABLED_PAYMENT_PROVIDERS,exports.DEFAULT_INVOICE_SETTINGS=D.DEFAULT_INVOICE_SETTINGS,exports.FeaturedProduct=C.FeaturedProduct,exports.FreemiusLicensePanel=j.FreemiusLicensePanel,exports.INVOICE_SETTINGS_KEY=D.INVOICE_SETTINGS_KEY,exports.InvoiceDocument=k.InvoiceDocument,exports.InvoiceViewerShell=A.InvoiceViewerShell,exports.PaymentReadinessProvider=f.PaymentReadinessProvider,exports.ProductCard=v.ProductCard,exports.ProductCategorySelector=N.ProductCategorySelector,exports.ProductDetailsLayout=I.ProductDetailsLayout,exports.ProductForm=P.ProductForm,exports.ProductGallery=x.ProductGallery,exports.ProductGrid=y.ProductGrid,exports.ProductProvider=F.ProductProvider,exports.SimpleTiptapRenderer=S.SimpleTiptapRenderer,exports.SubscriptionSelector=E.SubscriptionSelector,exports.addressesMatch=p.addressesMatch,exports.aggregateOrderTaxLines=O.aggregateOrderTaxLines,exports.applyCurrencyRounding=t.applyCurrencyRounding,exports.applyVariantSelection=u.applyVariantSelection,exports.buildCombinationKey=u.buildCombinationKey,exports.buildInvoiceDocumentLabels=b.buildInvoiceDocumentLabels,exports.buildOrderTaxDetailsFromCalculation=O.buildOrderTaxDetailsFromCalculation,exports.buildOrderTaxDetailsFromStripeSession=O.buildOrderTaxDetailsFromStripeSession,exports.buildVariantLabel=u.buildVariantLabel,exports.chooseInitialVariantSelections=u.chooseInitialVariantSelections,exports.convertMinorUnitAmount=t.convertMinorUnitAmount,exports.derivePaymentProviderFromProductType=e.derivePaymentProviderFromProductType,exports.describeCurrencyRoundingRule=t.describeCurrencyRoundingRule,exports.emptyCustomerAddress=p.emptyCustomerAddress,exports.emptyProviderDiscounts=s.emptyProviderDiscounts,exports.extractSelectedTermsByAttribute=u.extractSelectedTermsByAttribute,exports.findMatchingVariant=u.findMatchingVariant,exports.formatInvoiceCurrency=D.formatInvoiceCurrency,exports.formatInvoiceDate=D.formatInvoiceDate,exports.generateVariantDrafts=u.generateVariantDrafts,exports.getAvailableTermIdsForAttribute=u.getAvailableTermIdsForAttribute,exports.getCartItemActivePrice=i.getCartItemActivePrice,exports.getCartLineCouponKey=s.getCartLineCouponKey,exports.getCurrencyLookup=t.getCurrencyLookup,exports.getDefaultCurrency=t.getDefaultCurrency,exports.getExchangeRateForCurrency=t.getExchangeRateForCurrency,exports.getInvoiceAddressLines=D.getInvoiceAddressLines,exports.getInvoiceLocale=b.getInvoiceLocale,exports.getOrderTaxRateJurisdiction=O.getOrderTaxRateJurisdiction,exports.getOrderTaxRateLabel=O.getOrderTaxRateLabel,exports.getOrderTaxRatePercentage=O.getOrderTaxRatePercentage,exports.getProductPaymentProvider=e.getProductPaymentProvider,exports.getTrialCheckoutMode=o.getTrialCheckoutMode,exports.getTrialLabel=o.getTrialLabel,exports.getTrialPaymentRequirementLabel=o.getTrialPaymentRequirementLabel,exports.getTrialPeriodDays=o.getTrialPeriodDays,exports.getTrialSummary=o.getTrialSummary,exports.getVariantEffectivePriceRange=u.getVariantEffectivePriceRange,exports.inferCurrencyCodeFromLocale=t.inferCurrencyCodeFromLocale,exports.isCustomerAddressComplete=p.isCustomerAddressComplete,exports.isDigitalItem=e.isDigitalItem,exports.isDigitalProduct=e.isDigitalProduct,exports.isSaleWindowActive=t.isSaleWindowActive,exports.isScheduledPriceDue=t.isScheduledPriceDue,exports.localizeInvoicePresentationData=b.localizeInvoicePresentationData,exports.mapRawVariantRelations=u.mapRawVariantRelations,exports.normalizeCouponCode=s.normalizeCouponCode,exports.normalizeCurrencyRecord=t.normalizeCurrencyRecord,exports.normalizeCurrencyRoundingMode=t.normalizeCurrencyRoundingMode,exports.normalizeCustomerAddress=p.normalizeCustomerAddress,exports.normalizeEnabledPaymentProviders=e.normalizeEnabledPaymentProviders,exports.normalizeInvoiceSettings=D.normalizeInvoiceSettings,exports.normalizeOrderCustomerDetails=p.normalizeOrderCustomerDetails,exports.normalizeOrderTaxDetails=O.normalizeOrderTaxDetails,exports.normalizePriceMap=t.normalizePriceMap,exports.normalizeSalePriceMap=t.normalizeSalePriceMap,exports.normalizeSelectionsToAvailableVariants=u.normalizeSelectionsToAvailableVariants,exports.productSchema=M.productSchema,exports.resolveAttributeName=u.resolveAttributeName,exports.resolveEffectivePriceForCurrency=t.resolveEffectivePriceForCurrency,exports.resolvePriceForCurrency=t.resolvePriceForCurrency,exports.resolvePriceRangeForCurrency=t.resolvePriceRangeForCurrency,exports.resolveTermValue=u.resolveTermValue,exports.resolveTranslatedText=u.resolveTranslatedText,exports.serializeInvoiceSettings=D.serializeInvoiceSettings,exports.sortCurrencies=t.sortCurrencies,exports.toNoCookieEmbedSrc=S.toNoCookieEmbedSrc,exports.translateOrFallback=b.translateOrFallback,exports.translateOrderStatus=b.translateOrderStatus,exports.useCanPurchase=f.useCanPurchase,exports.useCart=a.useCart,exports.useCartStore=i.useCartStore,exports.useCartSubtotal=i.useCartSubtotal,exports.useCartTotalItems=i.useCartTotalItems,exports.useCurrency=r.useCurrency,exports.useCurrencyPreferenceStore=n.useCurrencyPreferenceStore,exports.useIsCartHydrated=a.useIsCartHydrated,exports.usePaymentReadiness=f.usePaymentReadiness,exports.useProduct=F.useProduct;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./lib/types.cjs"),t=require("./lib/currency.cjs"),n=require("./lib/currency-store.cjs"),r=require("./lib/CurrencyProvider.cjs"),i=require("./lib/cart-store.cjs"),a=require("./lib/use-cart.cjs"),o=require("./lib/trials.cjs"),s=require("./lib/coupons.cjs"),c=require("./lib/components/CouponForm.cjs"),l=require("./lib/components/CartDrawer.cjs"),u=require("./lib/variation-utils.cjs"),d=require("./lib/components/Cart.cjs"),f=require("./lib/PaymentReadinessProvider.cjs"),p=require("./lib/customer.cjs"),m=require("./lib/components/Checkout.cjs"),h=require("./lib/components/CartIcon.cjs"),g=require("./lib/components/CurrencySwitcher.cjs"),_=require("./lib/components/AddToCartButton.cjs"),v=require("./lib/components/ProductCard.cjs"),y=require("./lib/components/ProductGrid.cjs"),b=require("./lib/invoice-ui.cjs"),x=require("./lib/components/ProductGallery.cjs"),S=require("./lib/components/SimpleTiptapRenderer.cjs"),C=require("./lib/components/FeaturedProduct.cjs"),w=require("./lib/components/AccountNavigationMenu.cjs"),T=require("./lib/components/CustomerProfileForm.cjs"),E=require("./lib/components/SubscriptionSelector.cjs"),D=require("./lib/invoice.cjs"),O=require("./lib/order-tax-details.cjs"),k=require("./lib/components/InvoiceDocument.cjs"),A=require("./lib/components/InvoiceViewerShell.cjs"),j=require("./lib/components/FreemiusLicensePanel.cjs"),M=require("./lib/product-schema.cjs"),N=require("./lib/pages/cms/products/components/ProductCategorySelector.cjs"),P=require("./lib/pages/cms/products/components/ProductForm.cjs"),F=require("./lib/product-context.cjs"),I=require("./lib/components/ProductDetailsLayout.cjs");exports.AccountNavigationMenu=w.AccountNavigationMenu,exports.AddToCartButton=_.AddToCartButton,exports.COUPON_INVALID_ERROR_KEY=s.COUPON_INVALID_ERROR_KEY,exports.COUPON_INVALID_ERROR_MESSAGE=s.COUPON_INVALID_ERROR_MESSAGE,exports.COUPON_THROTTLED_ERROR_KEY=s.COUPON_THROTTLED_ERROR_KEY,exports.COUPON_THROTTLED_ERROR_MESSAGE=s.COUPON_THROTTLED_ERROR_MESSAGE,exports.CURRENCY_ROUNDING_MODES=t.CURRENCY_ROUNDING_MODES,exports.Cart=d.Cart,exports.CartDrawer=l.CartDrawer,exports.CartIcon=h.CartIcon,exports.Checkout=m.Checkout,exports.CouponForm=c.CouponForm,exports.CurrencyProvider=r.CurrencyProvider,exports.CurrencySwitcher=g.CurrencySwitcher,exports.CustomerProfileForm=T.CustomerProfileForm,exports.DEFAULT_ENABLED_PAYMENT_PROVIDERS=e.DEFAULT_ENABLED_PAYMENT_PROVIDERS,exports.DEFAULT_INVOICE_SETTINGS=D.DEFAULT_INVOICE_SETTINGS,exports.FeaturedProduct=C.FeaturedProduct,exports.FreemiusLicensePanel=j.FreemiusLicensePanel,exports.INVOICE_SETTINGS_KEY=D.INVOICE_SETTINGS_KEY,exports.InvoiceDocument=k.InvoiceDocument,exports.InvoiceViewerShell=A.InvoiceViewerShell,exports.PaymentReadinessProvider=f.PaymentReadinessProvider,exports.ProductCard=v.ProductCard,exports.ProductCategorySelector=N.ProductCategorySelector,exports.ProductDetailsLayout=I.ProductDetailsLayout,exports.ProductForm=P.ProductForm,exports.ProductGallery=x.ProductGallery,exports.ProductGrid=y.ProductGrid,exports.ProductProvider=F.ProductProvider,exports.SimpleTiptapRenderer=S.SimpleTiptapRenderer,exports.SubscriptionSelector=E.SubscriptionSelector,exports.addressesMatch=p.addressesMatch,exports.aggregateOrderTaxLines=O.aggregateOrderTaxLines,exports.applyCurrencyRounding=t.applyCurrencyRounding,exports.applyVariantSelection=u.applyVariantSelection,exports.buildCombinationKey=u.buildCombinationKey,exports.buildInvoiceDocumentLabels=b.buildInvoiceDocumentLabels,exports.buildOrderTaxDetailsFromCalculation=O.buildOrderTaxDetailsFromCalculation,exports.buildOrderTaxDetailsFromStripeSession=O.buildOrderTaxDetailsFromStripeSession,exports.buildVariantLabel=u.buildVariantLabel,exports.chooseInitialVariantSelections=u.chooseInitialVariantSelections,exports.convertMinorUnitAmount=t.convertMinorUnitAmount,exports.derivePaymentProviderFromProductType=e.derivePaymentProviderFromProductType,exports.describeCurrencyRoundingRule=t.describeCurrencyRoundingRule,exports.emptyCustomerAddress=p.emptyCustomerAddress,exports.emptyProviderDiscounts=s.emptyProviderDiscounts,exports.extractSelectedTermsByAttribute=u.extractSelectedTermsByAttribute,exports.findMatchingVariant=u.findMatchingVariant,exports.formatInvoiceCurrency=D.formatInvoiceCurrency,exports.formatInvoiceDate=D.formatInvoiceDate,exports.generateVariantDrafts=u.generateVariantDrafts,exports.getAvailableTermIdsForAttribute=u.getAvailableTermIdsForAttribute,exports.getCartItemActivePrice=i.getCartItemActivePrice,exports.getCartLineCouponKey=s.getCartLineCouponKey,exports.getCurrencyLookup=t.getCurrencyLookup,exports.getDefaultCurrency=t.getDefaultCurrency,exports.getExchangeRateForCurrency=t.getExchangeRateForCurrency,exports.getInvoiceAddressLines=D.getInvoiceAddressLines,exports.getInvoiceLocale=b.getInvoiceLocale,exports.getOrderTaxRateJurisdiction=O.getOrderTaxRateJurisdiction,exports.getOrderTaxRateLabel=O.getOrderTaxRateLabel,exports.getOrderTaxRatePercentage=O.getOrderTaxRatePercentage,exports.getProductPaymentProvider=e.getProductPaymentProvider,exports.getTrialCheckoutMode=o.getTrialCheckoutMode,exports.getTrialLabel=o.getTrialLabel,exports.getTrialPaymentRequirementLabel=o.getTrialPaymentRequirementLabel,exports.getTrialPeriodDays=o.getTrialPeriodDays,exports.getTrialSummary=o.getTrialSummary,exports.getVariantEffectivePriceRange=u.getVariantEffectivePriceRange,exports.inferCurrencyCodeFromLocale=t.inferCurrencyCodeFromLocale,exports.isCustomerAddressComplete=p.isCustomerAddressComplete,exports.isDigitalItem=e.isDigitalItem,exports.isDigitalProduct=e.isDigitalProduct,exports.isSaleWindowActive=t.isSaleWindowActive,exports.isScheduledPriceDue=t.isScheduledPriceDue,exports.localizeInvoicePresentationData=b.localizeInvoicePresentationData,exports.mapRawVariantRelations=u.mapRawVariantRelations,exports.normalizeCouponCode=s.normalizeCouponCode,exports.normalizeCurrencyRecord=t.normalizeCurrencyRecord,exports.normalizeCurrencyRoundingMode=t.normalizeCurrencyRoundingMode,exports.normalizeCustomerAddress=p.normalizeCustomerAddress,exports.normalizeEnabledPaymentProviders=e.normalizeEnabledPaymentProviders,exports.normalizeInvoiceSettings=D.normalizeInvoiceSettings,exports.normalizeOrderCustomerDetails=p.normalizeOrderCustomerDetails,exports.normalizeOrderTaxDetails=O.normalizeOrderTaxDetails,exports.normalizePriceMap=t.normalizePriceMap,exports.normalizeSalePriceMap=t.normalizeSalePriceMap,exports.normalizeSelectionsToAvailableVariants=u.normalizeSelectionsToAvailableVariants,exports.productSchema=M.productSchema,exports.resolveAttributeName=u.resolveAttributeName,exports.resolveEffectivePriceForCurrency=t.resolveEffectivePriceForCurrency,exports.resolvePriceForCurrency=t.resolvePriceForCurrency,exports.resolvePriceRangeForCurrency=t.resolvePriceRangeForCurrency,exports.resolveTermValue=u.resolveTermValue,exports.resolveTranslatedText=u.resolveTranslatedText,exports.serializeInvoiceSettings=D.serializeInvoiceSettings,exports.sortCurrencies=t.sortCurrencies,exports.toNoCookieEmbedSrc=S.toNoCookieEmbedSrc,exports.translateOrFallback=b.translateOrFallback,exports.translateOrderStatus=b.translateOrderStatus,exports.useCanPurchase=f.useCanPurchase,exports.useCart=a.useCart,exports.useCartStore=i.useCartStore,exports.useCartSubtotal=i.useCartSubtotal,exports.useCartTotalItems=i.useCartTotalItems,exports.useCurrency=r.useCurrency,exports.useCurrencyPreferenceStore=n.useCurrencyPreferenceStore,exports.useIsCartHydrated=a.useIsCartHydrated,exports.usePaymentReadiness=f.usePaymentReadiness,exports.useProduct=F.useProduct;
package/index.es.js CHANGED
@@ -5,34 +5,34 @@ import { CurrencyProvider as T, useCurrency as E } from "./lib/CurrencyProvider.
5
5
  import { getCartItemActivePrice as D, useCartStore as O, useCartSubtotal as k, useCartTotalItems as A } from "./lib/cart-store.es.js";
6
6
  import { useCart as j, useIsCartHydrated as M } from "./lib/use-cart.es.js";
7
7
  import { getTrialCheckoutMode as N, getTrialLabel as P, getTrialPaymentRequirementLabel as F, getTrialPeriodDays as I, getTrialSummary as L } from "./lib/trials.es.js";
8
- import { emptyProviderDiscounts as R, getCartLineCouponKey as z, normalizeCouponCode as B } from "./lib/coupons.es.js";
9
- import { CouponForm as V } from "./lib/components/CouponForm.es.js";
10
- import { CartDrawer as H } from "./lib/components/CartDrawer.es.js";
11
- import { applyVariantSelection as U, buildCombinationKey as W, buildVariantLabel as G, chooseInitialVariantSelections as K, extractSelectedTermsByAttribute as q, findMatchingVariant as J, generateVariantDrafts as Y, getAvailableTermIdsForAttribute as X, getVariantEffectivePriceRange as Z, mapRawVariantRelations as Q, normalizeSelectionsToAvailableVariants as $, resolveAttributeName as ee, resolveTermValue as te, resolveTranslatedText as ne } from "./lib/variation-utils.es.js";
12
- import { Cart as re } from "./lib/components/Cart.es.js";
13
- import { PaymentReadinessProvider as ie, useCanPurchase as ae, usePaymentReadiness as oe } from "./lib/PaymentReadinessProvider.es.js";
14
- import { addressesMatch as se, emptyCustomerAddress as ce, isCustomerAddressComplete as le, normalizeCustomerAddress as ue, normalizeOrderCustomerDetails as de } from "./lib/customer.es.js";
15
- import { Checkout as fe } from "./lib/components/Checkout.es.js";
16
- import { CartIcon as pe } from "./lib/components/CartIcon.es.js";
17
- import { CurrencySwitcher as me } from "./lib/components/CurrencySwitcher.es.js";
18
- import { AddToCartButton as he } from "./lib/components/AddToCartButton.es.js";
19
- import { ProductCard as ge } from "./lib/components/ProductCard.es.js";
20
- import { ProductGrid as _e } from "./lib/components/ProductGrid.es.js";
21
- import { buildInvoiceDocumentLabels as ve, getInvoiceLocale as ye, localizeInvoicePresentationData as be, translateOrFallback as xe, translateOrderStatus as Se } from "./lib/invoice-ui.es.js";
22
- import { ProductGallery as Ce } from "./lib/components/ProductGallery.es.js";
23
- import { SimpleTiptapRenderer as we, toNoCookieEmbedSrc as Te } from "./lib/components/SimpleTiptapRenderer.es.js";
24
- import { FeaturedProduct as Ee } from "./lib/components/FeaturedProduct.es.js";
25
- import { AccountNavigationMenu as De } from "./lib/components/AccountNavigationMenu.es.js";
26
- import { CustomerProfileForm as Oe } from "./lib/components/CustomerProfileForm.es.js";
27
- import { SubscriptionSelector as ke } from "./lib/components/SubscriptionSelector.es.js";
28
- import { DEFAULT_INVOICE_SETTINGS as Ae, INVOICE_SETTINGS_KEY as je, formatInvoiceCurrency as Me, formatInvoiceDate as Ne, getInvoiceAddressLines as Pe, normalizeInvoiceSettings as Fe, serializeInvoiceSettings as Ie } from "./lib/invoice.es.js";
29
- import { aggregateOrderTaxLines as Le, buildOrderTaxDetailsFromCalculation as Re, buildOrderTaxDetailsFromStripeSession as ze, getOrderTaxRateJurisdiction as Be, getOrderTaxRateLabel as Ve, getOrderTaxRatePercentage as He, normalizeOrderTaxDetails as Ue } from "./lib/order-tax-details.es.js";
30
- import { InvoiceDocument as We } from "./lib/components/InvoiceDocument.es.js";
31
- import { InvoiceViewerShell as Ge } from "./lib/components/InvoiceViewerShell.es.js";
32
- import { FreemiusLicensePanel as Ke } from "./lib/components/FreemiusLicensePanel.es.js";
33
- import { productSchema as qe } from "./lib/product-schema.es.js";
34
- import { ProductCategorySelector as Je } from "./lib/pages/cms/products/components/ProductCategorySelector.es.js";
35
- import { ProductForm as Ye } from "./lib/pages/cms/products/components/ProductForm.es.js";
36
- import { ProductProvider as Xe, useProduct as Ze } from "./lib/product-context.es.js";
37
- import { ProductDetailsLayout as Qe } from "./lib/components/ProductDetailsLayout.es.js";
38
- export { De as AccountNavigationMenu, he as AddToCartButton, o as CURRENCY_ROUNDING_MODES, re as Cart, H as CartDrawer, pe as CartIcon, fe as Checkout, V as CouponForm, T as CurrencyProvider, me as CurrencySwitcher, Oe as CustomerProfileForm, e as DEFAULT_ENABLED_PAYMENT_PROVIDERS, Ae as DEFAULT_INVOICE_SETTINGS, Ee as FeaturedProduct, Ke as FreemiusLicensePanel, je as INVOICE_SETTINGS_KEY, We as InvoiceDocument, Ge as InvoiceViewerShell, ie as PaymentReadinessProvider, ge as ProductCard, Je as ProductCategorySelector, Qe as ProductDetailsLayout, Ye as ProductForm, Ce as ProductGallery, _e as ProductGrid, Xe as ProductProvider, we as SimpleTiptapRenderer, ke as SubscriptionSelector, se as addressesMatch, Le as aggregateOrderTaxLines, s as applyCurrencyRounding, U as applyVariantSelection, W as buildCombinationKey, ve as buildInvoiceDocumentLabels, Re as buildOrderTaxDetailsFromCalculation, ze as buildOrderTaxDetailsFromStripeSession, G as buildVariantLabel, K as chooseInitialVariantSelections, c as convertMinorUnitAmount, t as derivePaymentProviderFromProductType, l as describeCurrencyRoundingRule, ce as emptyCustomerAddress, R as emptyProviderDiscounts, q as extractSelectedTermsByAttribute, J as findMatchingVariant, Me as formatInvoiceCurrency, Ne as formatInvoiceDate, Y as generateVariantDrafts, X as getAvailableTermIdsForAttribute, D as getCartItemActivePrice, z as getCartLineCouponKey, u as getCurrencyLookup, d as getDefaultCurrency, f as getExchangeRateForCurrency, Pe as getInvoiceAddressLines, ye as getInvoiceLocale, Be as getOrderTaxRateJurisdiction, Ve as getOrderTaxRateLabel, He as getOrderTaxRatePercentage, n as getProductPaymentProvider, N as getTrialCheckoutMode, P as getTrialLabel, F as getTrialPaymentRequirementLabel, I as getTrialPeriodDays, L as getTrialSummary, Z as getVariantEffectivePriceRange, p as inferCurrencyCodeFromLocale, le as isCustomerAddressComplete, r as isDigitalItem, i as isDigitalProduct, m as isSaleWindowActive, h as isScheduledPriceDue, be as localizeInvoicePresentationData, Q as mapRawVariantRelations, B as normalizeCouponCode, g as normalizeCurrencyRecord, _ as normalizeCurrencyRoundingMode, ue as normalizeCustomerAddress, a as normalizeEnabledPaymentProviders, Fe as normalizeInvoiceSettings, de as normalizeOrderCustomerDetails, Ue as normalizeOrderTaxDetails, v as normalizePriceMap, y as normalizeSalePriceMap, $ as normalizeSelectionsToAvailableVariants, qe as productSchema, ee as resolveAttributeName, b as resolveEffectivePriceForCurrency, x as resolvePriceForCurrency, S as resolvePriceRangeForCurrency, te as resolveTermValue, ne as resolveTranslatedText, Ie as serializeInvoiceSettings, C as sortCurrencies, Te as toNoCookieEmbedSrc, xe as translateOrFallback, Se as translateOrderStatus, ae as useCanPurchase, j as useCart, O as useCartStore, k as useCartSubtotal, A as useCartTotalItems, E as useCurrency, w as useCurrencyPreferenceStore, M as useIsCartHydrated, oe as usePaymentReadiness, Ze as useProduct };
8
+ import { COUPON_INVALID_ERROR_KEY as R, COUPON_INVALID_ERROR_MESSAGE as z, COUPON_THROTTLED_ERROR_KEY as B, COUPON_THROTTLED_ERROR_MESSAGE as V, emptyProviderDiscounts as H, getCartLineCouponKey as U, normalizeCouponCode as W } from "./lib/coupons.es.js";
9
+ import { CouponForm as G } from "./lib/components/CouponForm.es.js";
10
+ import { CartDrawer as K } from "./lib/components/CartDrawer.es.js";
11
+ import { applyVariantSelection as q, buildCombinationKey as J, buildVariantLabel as Y, chooseInitialVariantSelections as X, extractSelectedTermsByAttribute as Z, findMatchingVariant as Q, generateVariantDrafts as $, getAvailableTermIdsForAttribute as ee, getVariantEffectivePriceRange as te, mapRawVariantRelations as ne, normalizeSelectionsToAvailableVariants as re, resolveAttributeName as ie, resolveTermValue as ae, resolveTranslatedText as oe } from "./lib/variation-utils.es.js";
12
+ import { Cart as se } from "./lib/components/Cart.es.js";
13
+ import { PaymentReadinessProvider as ce, useCanPurchase as le, usePaymentReadiness as ue } from "./lib/PaymentReadinessProvider.es.js";
14
+ import { addressesMatch as de, emptyCustomerAddress as fe, isCustomerAddressComplete as pe, normalizeCustomerAddress as me, normalizeOrderCustomerDetails as he } from "./lib/customer.es.js";
15
+ import { Checkout as ge } from "./lib/components/Checkout.es.js";
16
+ import { CartIcon as _e } from "./lib/components/CartIcon.es.js";
17
+ import { CurrencySwitcher as ve } from "./lib/components/CurrencySwitcher.es.js";
18
+ import { AddToCartButton as ye } from "./lib/components/AddToCartButton.es.js";
19
+ import { ProductCard as be } from "./lib/components/ProductCard.es.js";
20
+ import { ProductGrid as xe } from "./lib/components/ProductGrid.es.js";
21
+ import { buildInvoiceDocumentLabels as Se, getInvoiceLocale as Ce, localizeInvoicePresentationData as we, translateOrFallback as Te, translateOrderStatus as Ee } from "./lib/invoice-ui.es.js";
22
+ import { ProductGallery as De } from "./lib/components/ProductGallery.es.js";
23
+ import { SimpleTiptapRenderer as Oe, toNoCookieEmbedSrc as ke } from "./lib/components/SimpleTiptapRenderer.es.js";
24
+ import { FeaturedProduct as Ae } from "./lib/components/FeaturedProduct.es.js";
25
+ import { AccountNavigationMenu as je } from "./lib/components/AccountNavigationMenu.es.js";
26
+ import { CustomerProfileForm as Me } from "./lib/components/CustomerProfileForm.es.js";
27
+ import { SubscriptionSelector as Ne } from "./lib/components/SubscriptionSelector.es.js";
28
+ import { DEFAULT_INVOICE_SETTINGS as Pe, INVOICE_SETTINGS_KEY as Fe, formatInvoiceCurrency as Ie, formatInvoiceDate as Le, getInvoiceAddressLines as Re, normalizeInvoiceSettings as ze, serializeInvoiceSettings as Be } from "./lib/invoice.es.js";
29
+ import { aggregateOrderTaxLines as Ve, buildOrderTaxDetailsFromCalculation as He, buildOrderTaxDetailsFromStripeSession as Ue, getOrderTaxRateJurisdiction as We, getOrderTaxRateLabel as Ge, getOrderTaxRatePercentage as Ke, normalizeOrderTaxDetails as qe } from "./lib/order-tax-details.es.js";
30
+ import { InvoiceDocument as Je } from "./lib/components/InvoiceDocument.es.js";
31
+ import { InvoiceViewerShell as Ye } from "./lib/components/InvoiceViewerShell.es.js";
32
+ import { FreemiusLicensePanel as Xe } from "./lib/components/FreemiusLicensePanel.es.js";
33
+ import { productSchema as Ze } from "./lib/product-schema.es.js";
34
+ import { ProductCategorySelector as Qe } from "./lib/pages/cms/products/components/ProductCategorySelector.es.js";
35
+ import { ProductForm as $e } from "./lib/pages/cms/products/components/ProductForm.es.js";
36
+ import { ProductProvider as et, useProduct as tt } from "./lib/product-context.es.js";
37
+ import { ProductDetailsLayout as nt } from "./lib/components/ProductDetailsLayout.es.js";
38
+ export { je as AccountNavigationMenu, ye as AddToCartButton, R as COUPON_INVALID_ERROR_KEY, z as COUPON_INVALID_ERROR_MESSAGE, B as COUPON_THROTTLED_ERROR_KEY, V as COUPON_THROTTLED_ERROR_MESSAGE, o as CURRENCY_ROUNDING_MODES, se as Cart, K as CartDrawer, _e as CartIcon, ge as Checkout, G as CouponForm, T as CurrencyProvider, ve as CurrencySwitcher, Me as CustomerProfileForm, e as DEFAULT_ENABLED_PAYMENT_PROVIDERS, Pe as DEFAULT_INVOICE_SETTINGS, Ae as FeaturedProduct, Xe as FreemiusLicensePanel, Fe as INVOICE_SETTINGS_KEY, Je as InvoiceDocument, Ye as InvoiceViewerShell, ce as PaymentReadinessProvider, be as ProductCard, Qe as ProductCategorySelector, nt as ProductDetailsLayout, $e as ProductForm, De as ProductGallery, xe as ProductGrid, et as ProductProvider, Oe as SimpleTiptapRenderer, Ne as SubscriptionSelector, de as addressesMatch, Ve as aggregateOrderTaxLines, s as applyCurrencyRounding, q as applyVariantSelection, J as buildCombinationKey, Se as buildInvoiceDocumentLabels, He as buildOrderTaxDetailsFromCalculation, Ue as buildOrderTaxDetailsFromStripeSession, Y as buildVariantLabel, X as chooseInitialVariantSelections, c as convertMinorUnitAmount, t as derivePaymentProviderFromProductType, l as describeCurrencyRoundingRule, fe as emptyCustomerAddress, H as emptyProviderDiscounts, Z as extractSelectedTermsByAttribute, Q as findMatchingVariant, Ie as formatInvoiceCurrency, Le as formatInvoiceDate, $ as generateVariantDrafts, ee as getAvailableTermIdsForAttribute, D as getCartItemActivePrice, U as getCartLineCouponKey, u as getCurrencyLookup, d as getDefaultCurrency, f as getExchangeRateForCurrency, Re as getInvoiceAddressLines, Ce as getInvoiceLocale, We as getOrderTaxRateJurisdiction, Ge as getOrderTaxRateLabel, Ke as getOrderTaxRatePercentage, n as getProductPaymentProvider, N as getTrialCheckoutMode, P as getTrialLabel, F as getTrialPaymentRequirementLabel, I as getTrialPeriodDays, L as getTrialSummary, te as getVariantEffectivePriceRange, p as inferCurrencyCodeFromLocale, pe as isCustomerAddressComplete, r as isDigitalItem, i as isDigitalProduct, m as isSaleWindowActive, h as isScheduledPriceDue, we as localizeInvoicePresentationData, ne as mapRawVariantRelations, W as normalizeCouponCode, g as normalizeCurrencyRecord, _ as normalizeCurrencyRoundingMode, me as normalizeCustomerAddress, a as normalizeEnabledPaymentProviders, ze as normalizeInvoiceSettings, he as normalizeOrderCustomerDetails, qe as normalizeOrderTaxDetails, v as normalizePriceMap, y as normalizeSalePriceMap, re as normalizeSelectionsToAvailableVariants, Ze as productSchema, ie as resolveAttributeName, b as resolveEffectivePriceForCurrency, x as resolvePriceForCurrency, S as resolvePriceRangeForCurrency, ae as resolveTermValue, oe as resolveTranslatedText, Be as serializeInvoiceSettings, C as sortCurrencies, ke as toNoCookieEmbedSrc, Te as translateOrFallback, Ee as translateOrderStatus, le as useCanPurchase, j as useCart, O as useCartStore, k as useCartSubtotal, A as useCartTotalItems, E as useCurrency, w as useCurrencyPreferenceStore, M as useIsCartHydrated, ue as usePaymentReadiness, tt as useProduct };
@@ -1 +1 @@
1
- "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../types.cjs"),t=require("../CurrencyProvider.cjs"),n=require("../cart-store.cjs"),r=require("../use-cart.cjs"),i=require("../use-price-formatter.cjs"),a=require("../trials.cjs"),o=require("./CouponForm.cjs"),s=require("../countries.cjs"),c=require("../states.cjs"),ee=require("../server-actions/shipping-actions.cjs"),te=require("../PaymentReadinessProvider.cjs"),ne=require("../server-actions/tax-actions.cjs"),l=require("../customer.cjs");let re=require("@nextblock-cms/ui/badge"),ie=require("@nextblock-cms/ui/button"),u=require("react"),d=require("lucide-react"),ae=require("@nextblock-cms/utils"),f=require("react/jsx-runtime"),p=require("@nextblock-cms/ui/input"),m=require("@nextblock-cms/ui/label"),h=require("@nextblock-cms/ui/card"),oe=require("@nextblock-cms/ui/checkbox"),se=require("@nextblock-cms/ui/separator"),g=require("@nextblock-cms/ui/radio-group"),ce=require("@freemius/checkout");var le=process.env.NEXT_PUBLIC_IS_SANDBOX===`true`,_=`nextblock-checkout-draft-v1`;function v(e,t){return{...l.emptyCustomerAddress(),company_name:e?.company_name||``,recipient_name:e?.recipient_name||t||``,line1:e?.line1||``,line2:e?.line2||``,city:e?.city||``,state:e?.state||``,postal_code:e?.postal_code||``,country_code:s.normalizeCountryCode(e?.country_code)||`CA`}}function ue(e){let t=l.normalizeCustomerAddress(e);return!(!t?.country_code||!t.postal_code||c.countryUsesStructuredStates(t.country_code)&&!t.state)}function de(e,t,r){return e.reduce((e,i)=>{let{price:a,sale_price:o}=n.getCartItemActivePrice(i,{currencyCode:t,currencies:r});return e+(o??a)*i.quantity},0)}function fe({idPrefix:e,title:t,description:n,value:r,onChange:i}){let{t:a,lang:o}=(0,ae.useTranslations)(),ee=(0,u.useMemo)(()=>{try{return new Intl.DisplayNames([o],{type:`region`})}catch{return null}},[o]),te=a(`company_name`)===`company_name`?`Company name`:a(`company_name`),ne=a(`select_an_option`)===`select_an_option`?`Select an option`:a(`select_an_option`),l=a(`state_province`)===`state_province`?`State / Province`:a(`state_province`),re=c.getStatesForCountry(r.country_code),ie=c.countryUsesStructuredStates(r.country_code);return(0,f.jsxs)(h.Card,{children:[(0,f.jsxs)(h.CardHeader,{children:[(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.MapPin,{className:`w-5 h-5`}),t]}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[(0,f.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-company`,children:te}),(0,f.jsx)(p.Input,{id:`${e}-company`,name:`${e}-company`,autoComplete:`${e} organization`,value:r.company_name,onChange:e=>i({...r,company_name:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-name`,children:a(`full_name`)}),(0,f.jsx)(p.Input,{id:`${e}-name`,name:`${e}-name`,autoComplete:`${e} name`,required:!0,value:r.recipient_name,onChange:e=>i({...r,recipient_name:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-country`,children:a(`country`)}),(0,f.jsx)(`select`,{id:`${e}-country`,name:`${e}-country`,autoComplete:`${e} country`,required:!0,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,value:r.country_code,onChange:e=>{let t=e.target.value,n=c.getStatesForCountry(t);i({...r,country_code:t,state:n.some(e=>e.code===r.state)?r.state:``})},children:s.countries.map(e=>(0,f.jsx)(`option`,{value:e.code,children:ee?.of(e.code)??e.name},e.code))})]})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-line1`,children:a(`address_line_1`)}),(0,f.jsx)(p.Input,{id:`${e}-line1`,name:`${e}-line1`,autoComplete:`${e} address-line1`,required:!0,value:r.line1,onChange:e=>i({...r,line1:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-line2`,children:a(`address_line_2`)}),(0,f.jsx)(p.Input,{id:`${e}-line2`,name:`${e}-line2`,autoComplete:`${e} address-line2`,value:r.line2,onChange:e=>i({...r,line2:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-city`,children:a(`city`)}),(0,f.jsx)(p.Input,{id:`${e}-city`,name:`${e}-city`,autoComplete:`${e} address-level2`,required:!0,value:r.city,onChange:e=>i({...r,city:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-state`,children:a(`state_province`)}),ie?(0,f.jsxs)(`select`,{id:`${e}-state`,name:`${e}-state`,autoComplete:`${e} address-level1`,required:!0,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,value:r.state,onChange:e=>i({...r,state:e.target.value}),children:[(0,f.jsx)(`option`,{value:``,children:`${ne}: ${l}`}),re.map(e=>(0,f.jsx)(`option`,{value:e.code,children:c.getSubdivisionLabel(r.country_code,e,o)},e.code))]}):(0,f.jsx)(p.Input,{id:`${e}-state`,name:`${e}-state`,autoComplete:`${e} address-level1`,value:r.state,onChange:e=>i({...r,state:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-postal`,children:a(`postal_zip_code`)}),(0,f.jsx)(p.Input,{id:`${e}-postal`,name:`${e}-postal`,autoComplete:`${e} postal-code`,required:!0,value:r.postal_code,onChange:e=>i({...r,postal_code:e.target.value})})]})]})]})]})}function pe({title:e,description:t,badgeLabel:n,children:r}){return(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[(0,f.jsxs)(`div`,{children:[(0,f.jsx)(h.CardTitle,{role:`heading`,"aria-level":2,children:e}),(0,f.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t})]}),n?(0,f.jsx)(re.Badge,{variant:`secondary`,children:n}):null]})}),(0,f.jsx)(h.CardContent,{className:`space-y-4`,children:r})]})}var y=({initialCustomer:s})=>{let y=i.usePriceFormatter(),[me,he]=(0,u.useState)({}),[b,x]=(0,u.useState)(null),[S,C]=(0,u.useState)({}),[w,ge]=(0,u.useState)(s?.email||``),[T,_e]=(0,u.useState)(``),[E,ve]=(0,u.useState)(s?.phone||``),[ye,be]=(0,u.useState)(!1),[xe,Se]=(0,u.useState)(null),[Ce,D]=(0,u.useState)(!1),[we,Te]=(0,u.useState)(!1),[Ee,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)([]),[j,M]=(0,u.useState)(null),[N,P]=(0,u.useState)(null),[F,De]=(0,u.useState)(null),[I,Oe]=(0,u.useState)(()=>v(s?.billingAddress,s?.fullName)),[L,ke]=(0,u.useState)(()=>v(s?.shippingAddress??s?.billingAddress,s?.fullName)),[R,Ae]=(0,u.useState)(!s?.shippingAddress||l.addressesMatch(s?.billingAddress,s?.shippingAddress)),z=r.useCart(e=>e),{t:B,lang:je}=(0,ae.useTranslations)(),{activeCurrencyCode:V,currencies:H}=t.useCurrency(),Me=te.usePaymentReadiness(),U=z?.items??[],W=(0,u.useMemo)(()=>U.filter(t=>!e.isDigitalItem(t)),[U]),G=(0,u.useMemo)(()=>U.filter(t=>e.isDigitalItem(t)),[U]),K=s?.isAuthenticated??!1,q=(e,t,n)=>{let r=B(e,n);if(r!==e)return r;if(!n)return t;let i=t;return Object.entries(n).forEach(([e,t])=>{i=i.replace(RegExp(`\\{${e}\\}`,`g`),String(t))}),i},J=W.length>0,Ne=(0,u.useMemo)(()=>de(U,V,H),[V,H,U]),Pe=(0,u.useMemo)(()=>de(W,V,H),[V,H,W]),Fe=(0,u.useMemo)(()=>de(G,V,H),[V,H,G]),Ie=F?.providerDiscounts.stripe??0,Le=F?.providerDiscounts.freemius??0,Y=Math.max(0,Pe-Ie),Re=Math.max(0,Fe-Le),X=(0,u.useMemo)(()=>R?I:L,[I,L,R]),Z=(0,u.useMemo)(()=>J?X:I,[I,J,X]),Q=!J||ue(X),$=(0,u.useMemo)(()=>k.find(e=>e.id===j),[k,j]),ze=(0,u.useMemo)(()=>Y+($?.amount??0)+(N&&!N.isPendingExternalCalculation?N.amount:0),[Y,$,N]),Be=ze+Re;if((0,u.useEffect)(()=>{if(!(K||typeof window>`u`))try{let e=window.localStorage.getItem(_);if(!e)return;let t=JSON.parse(e);t.email&&ge(t.email),t.phone&&ve(t.phone),t.billingAddress&&Oe(v(t.billingAddress)),t.shippingAddress&&ke(v(t.shippingAddress)),typeof t.useBillingForShipping==`boolean`&&Ae(t.useBillingForShipping),(typeof t.selectedMethodId==`string`||t.selectedMethodId===null)&&M(t.selectedMethodId)}catch(e){console.error(`[Checkout] Failed to restore checkout draft:`,e)}},[K]),(0,u.useEffect)(()=>{if(typeof window<`u`)try{if(K){window.localStorage.removeItem(_);return}window.localStorage.setItem(_,JSON.stringify({email:w,phone:E,billingAddress:I,shippingAddress:L,useBillingForShipping:R,selectedMethodId:j}))}catch{}},[I,w,K,E,j,L,R]),(0,u.useEffect)(()=>{if(!J){A([]),M(null),D(!1);return}if(!Q){A([]),M(null),D(!1);return}let e=!1,t=setTimeout(async()=>{if(X.country_code){D(!0),Te(!1);try{let t=await ee.getShippingEstimates(Y,{country:X.country_code,state:X.state,postal_code:X.postal_code},je,V);if(e)return;if(t.success&&t.methods){let e=t.methods;A(e),M(t=>t&&e.some(e=>e.id===t)?t:e[0]?.id??null)}else A([]),M(null)}catch(t){if(e)return;console.error(`[Checkout] Failed to load shipping rates:`,t),A([]),M(null),Te(!0)}finally{e||D(!1)}}},400);return()=>{e=!0,clearTimeout(t)}},[V,J,Q,je,X.country_code,X.postal_code,X.state,Y]),(0,u.useEffect)(()=>{let e=!1,t=setTimeout(async()=>{if(!J||!Z.country_code){O(!1),P(null);return}if(c.countryUsesStructuredStates(Z.country_code)&&!Z.state){O(!1),P(null);return}O(!0);try{let t=await ne.getTaxEstimate(W,{country_code:Z.country_code,state:Z.state},V,F?.code??null,U);if(e)return;P(t.success&&t.tax?t.tax:null)}catch(t){if(e)return;console.error(`[Checkout] Failed to load the tax estimate:`,t),P(null)}finally{e||O(!1)}},300);return()=>{e=!0,clearTimeout(t)}},[V,J,W,Z.country_code,Z.state,F?.code,U]),(0,u.useEffect)(()=>{let e=e=>{e.persisted&&x(null)};return window.addEventListener(`pageshow`,e),()=>window.removeEventListener(`pageshow`,e)},[]),!z)return(0,f.jsxs)(`div`,{role:`status`,"aria-busy":`true`,className:`container mx-auto px-4 py-12 md:px-6`,children:[(0,f.jsx)(`span`,{className:`sr-only`,children:B(`loading`)===`loading`?`Loading…`:B(`loading`)}),(0,f.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,f.jsx)(`div`,{className:`mb-8 h-9 w-48 rounded-md bg-muted`}),(0,f.jsxs)(`div`,{className:`grid gap-8 lg:grid-cols-12 lg:items-start`,children:[(0,f.jsxs)(`div`,{className:`space-y-6 lg:col-span-8`,children:[(0,f.jsx)(`div`,{className:`h-56 rounded-xl border bg-muted/40`}),(0,f.jsx)(`div`,{className:`h-96 rounded-xl border bg-muted/40`})]}),(0,f.jsx)(`div`,{className:`lg:col-span-4`,children:(0,f.jsx)(`div`,{className:`h-72 rounded-xl border bg-muted/40`})})]})]})]});let Ve=()=>{be(!1),Se(null)},He=ye?(0,f.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center overscroll-contain bg-black/60 backdrop-blur-sm`,onClick:Ve,onKeyDown:e=>{e.key===`Escape`&&Ve()},children:(0,f.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`sandbox-checkout-title`,className:`relative bg-background border rounded-xl shadow-2xl p-8 max-w-md mx-4`,onClick:e=>e.stopPropagation(),children:[(0,f.jsx)(`button`,{type:`button`,autoFocus:!0,onClick:Ve,"aria-label":q(`close`,`Close`),className:`absolute top-4 right-4 inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring`,children:(0,f.jsx)(d.X,{className:`w-5 h-5`})}),(0,f.jsxs)(`div`,{className:`flex items-center gap-3 mb-4`,children:[(0,f.jsx)(`div`,{className:`p-2 rounded-full bg-amber-100 dark:bg-amber-900/20`,children:(0,f.jsx)(d.FlaskConical,{className:`h-6 w-6 text-amber-600 dark:text-amber-400`})}),(0,f.jsx)(`h2`,{id:`sandbox-checkout-title`,className:`text-xl font-semibold`,children:B(`ecommerce.checkout_successful`)})]}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-2`,children:B(`ecommerce.sandbox_notice`)}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-2`,children:xe===`stripe`?q(`ecommerce.sandbox_checkout_stripe_description`,`This simulated step represents the Stripe checkout for physical products.`):q(`ecommerce.sandbox_checkout_freemius_description`,`This simulated step represents the Freemius checkout for digital products.`)}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-6`,children:B(`ecommerce.license_notice`)}),(0,f.jsx)(`a`,{href:`https://nextblock.dev`,target:`_blank`,rel:`noopener noreferrer`,className:`block w-full text-center py-3 px-4 rounded-lg bg-primary text-primary-foreground font-semibold hover:opacity-90 transition-opacity`,children:B(`ecommerce.purchase_at`)})]})}):null,Ue=(e,t,n)=>(C(n=>({...n,[e]:t})),n&&document.getElementById(n)?.focus(),null),We=(e,t)=>t.recipient_name.trim()?t.line1.trim()?t.city.trim()?c.countryUsesStructuredStates(t.country_code)&&!t.state?`${e}-state`:t.postal_code.trim()?`${e}-line1`:`${e}-postal`:`${e}-city`:`${e}-line1`:`${e}-name`,Ge=e=>{if(!K&&(!w||!/^\S+@\S+\.\S+$/.test(w)))return _e(B(`ecommerce.invalid_email`)),Ue(e,B(`ecommerce.invalid_email`),`checkout-email`);let t=l.normalizeCustomerAddress(I);if(!l.isCustomerAddressComplete(t))return Ue(e,B(`checkout_complete_billing_address`),We(`billing`,I));let n=J?l.normalizeCustomerAddress(R?I:L):null;if(e===`stripe`){if(!l.isCustomerAddressComplete(n))return Ue(e,B(`checkout_complete_shipping_address`),R?We(`billing`,I):We(`shipping`,L));if(!j)return Ue(e,q(`ecommerce.shipping_method_required`,`Please select a shipping method before continuing.`))}return _e(``),{normalizedBillingAddress:t,normalizedShippingAddress:n}},Ke=async(e,t,n)=>{C(t=>({...t,[e]:``}));let r=Ge(e);if(r){if(le){let n=new Set(t.map(e=>e.id)),r=U.filter(e=>!n.has(e.id));if(z.setItems(r),r.length===0&&z.removeCoupon(),Se(e),be(!0),typeof window<`u`&&r.length===0)try{window.localStorage.removeItem(_)}catch{}return}x(n);try{let n=await fetch(`/api/checkout`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({items:t,customerEmail:K?void 0:w,customerPhone:E||null,billingAddress:r.normalizedBillingAddress,shippingAddress:e===`stripe`?r.normalizedShippingAddress:null,shippingMethodId:e===`stripe`?j:null,locale:je,currencyCode:V,couponCode:F?.code??z.appliedCoupon?.code??null,couponContextItems:U})}),i=await n.json();if(!n.ok){let t=i?.errorKey&&typeof i.errorKey==`string`?q(i.errorKey,i?.error||q(`ecommerce.generic_error`,`Something went wrong.`),i.errorParams):i?.error||B(`ecommerce.generic_error`);C(n=>({...n,[e]:t})),x(null);return}if(i.customProps&&i.customProps.provider===`freemius`){let t=i.customProps,n=null,r=()=>{window.location.href=`/checkout/success?session_id=${t.order_id}`},a=e=>(n||=fetch(`/api/checkout/freemius/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({orderId:t.order_id,checkoutResponse:e})}).then(async e=>{if(!e.ok){let t=await e.json().catch(()=>null);console.error(`Freemius checkout sync failed:`,t)}}),n),o={product_id:t.plugin_id,public_key:t.public_key,sandbox:t.sandbox},s={name:B(`ecommerce.checkout_overlay_title`),plan_id:t.plan_id,...t.billing_cycle?{billing_cycle:t.billing_cycle}:{},...t.trial?{trial:t.trial}:{},...t.coupon?{coupon:t.coupon}:{},user_email:t.user_email,user_firstname:t.user_firstname,user_lastname:t.user_lastname,sandbox:t.sandbox,purchaseCompleted:function(e){a(e)},success:function(e){(async()=>{try{await a(e)}finally{r()}})()}};try{new ce.Checkout(o).open(s),x(null)}catch(t){console.error(`[Checkout] Freemius overlay failed to open:`,t),C(t=>({...t,[e]:B(`ecommerce.checkout_popup_blocked`)})),i.url&&(window.location.href=i.url),x(null)}}else i.url?window.location.href=i.url:(C(t=>({...t,[e]:B(`ecommerce.checkout_failed`)+(i.error||q(`ecommerce.unknown_error`,`Unknown error`))})),x(null))}catch(t){console.error(t),C(t=>({...t,[e]:B(`ecommerce.generic_error`)})),x(null)}}};if(U.length===0)return(0,f.jsxs)(f.Fragment,{children:[He,(0,f.jsxs)(`div`,{className:`container mx-auto flex min-h-[50vh] flex-col items-center justify-center p-8 text-center`,children:[(0,f.jsx)(`h1`,{className:`mb-4 text-2xl font-bold`,children:B(`ecommerce.cart_empty`)}),(0,f.jsx)(`p`,{className:`mb-8 text-muted-foreground`,children:B(`ecommerce.cart_empty_description`)}),(0,f.jsx)(ie.Button,{asChild:!0,children:(0,f.jsx)(`a`,{href:`/shop`,children:B(`ecommerce.go_to_shop`)})})]})]});let qe=q(`ecommerce.checkout_payments_unavailable`,`This store is not able to take payments right now. Please contact the seller to complete your purchase.`),Je=Me.stripe?null:qe,Ye=Me.freemius?null:qe,Xe=Je||(J?Q?Ce?q(`ecommerce.calculating_shipping`,`Calculating shipping...`):j?null:k.length>0?B(`ecommerce.select_rate`):B(`ecommerce.no_rates_for_region`):q(`ecommerce.waiting_on_address_info`,`Complete your shipping address to view available shipping options.`):null),Ze=b!==null||Xe!==null,Qe=W.length===1?q(`ecommerce.item_count_one`,`{count} item`,{count:W.length}):q(`ecommerce.item_count_other`,`{count} items`,{count:W.length}),$e=G.length===1?q(`ecommerce.license_count_one`,`{count} license`,{count:G.length}):q(`ecommerce.license_count_other`,`{count} licenses`,{count:G.length}),et=t=>e.isDigitalItem(t)?q(`ecommerce.digital_label`,`Digital`):q(`ecommerce.physical_label`,`Physical`),tt=e=>e===`monthly`?q(`ecommerce.checkout_billing_cycle_monthly`,`Monthly subscription`):e===`annual`?q(`ecommerce.checkout_billing_cycle_annual`,`Annual subscription`):e===`lifetime`?q(`ecommerce.checkout_billing_cycle_lifetime`,`Lifetime subscription`):null;return(0,f.jsxs)(`div`,{className:`container mx-auto px-4 py-12 md:px-6`,children:[He,(0,f.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,f.jsx)(`h1`,{className:`mb-8 text-3xl font-bold`,children:B(`ecommerce.checkout`)}),(0,f.jsxs)(`div`,{className:`grid gap-8 lg:grid-cols-12 lg:items-start`,children:[(0,f.jsxs)(`div`,{className:`lg:col-span-8 space-y-6`,children:[(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.CreditCard,{className:`w-5 h-5`}),B(`ecommerce.contact_information`)]})}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[K?(0,f.jsx)(`div`,{className:`rounded-xl border bg-muted/20 p-4 text-sm text-muted-foreground`,children:B(`checkout_prefill_notice`,{email:s?.email||``})}):(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsxs)(m.Label,{htmlFor:`checkout-email`,children:[B(`ecommerce.email_address`),` `,(0,f.jsx)(`span`,{className:`text-destructive`,children:`*`})]}),(0,f.jsx)(p.Input,{id:`checkout-email`,name:`email`,type:`email`,autoComplete:`email`,spellCheck:!1,"aria-invalid":T?!0:void 0,"aria-describedby":T?`checkout-email-error`:void 0,placeholder:B(`ecommerce.email_placeholder`),value:w,onChange:e=>{ge(e.target.value),T&&_e(``)},required:!0}),T?(0,f.jsx)(`p`,{id:`checkout-email-error`,role:`alert`,className:`text-xs text-destructive mt-1`,children:T}):null]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`checkout-phone`,children:B(`phone_number`)}),(0,f.jsx)(p.Input,{id:`checkout-phone`,name:`phone`,type:`tel`,inputMode:`tel`,autoComplete:`tel`,placeholder:B(`optional`),value:E,onChange:e=>ve(e.target.value)})]})]})]}),(0,f.jsx)(fe,{idPrefix:`billing`,title:B(`billing_address`),description:B(`checkout_billing_address_help`),value:I,onChange:Oe}),J?(0,f.jsxs)(`div`,{className:`flex items-center space-x-3 rounded-xl border bg-muted/20 p-4`,children:[(0,f.jsx)(oe.Checkbox,{id:`use-billing-for-shipping`,checked:R,onCheckedChange:e=>Ae(!!e)}),(0,f.jsxs)(`div`,{className:`space-y-1`,children:[(0,f.jsx)(m.Label,{htmlFor:`use-billing-for-shipping`,className:`cursor-pointer`,children:B(`use_billing_for_shipping`)}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:B(`checkout_use_billing_for_shipping_help`)})]})]}):null,J&&!R?(0,f.jsx)(fe,{idPrefix:`shipping`,title:B(`shipping_address`),description:B(`checkout_shipping_address_help`),value:L,onChange:ke}):null,J?(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.ChevronRight,{className:`w-5 h-5 text-primary`}),B(`ecommerce.shipping_method`)]})}),(0,f.jsx)(h.CardContent,{children:Ce?(0,f.jsxs)(`div`,{role:`status`,className:`flex items-center justify-center py-6`,children:[(0,f.jsx)(d.Loader2,{className:`w-6 h-6 animate-spin text-muted-foreground`}),(0,f.jsx)(`span`,{className:`sr-only`,children:q(`ecommerce.calculating_shipping`,`Calculating shipping…`)})]}):we?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg bg-destructive/10 px-4 py-3 text-center text-sm text-destructive`,children:q(`ecommerce.shipping_calculation_failed`,`We couldn't calculate shipping right now. Please try again.`)}):k.length>0?(0,f.jsx)(g.RadioGroup,{value:j??``,onValueChange:M,"aria-label":B(`ecommerce.shipping_method`),className:`space-y-3`,children:k.map(e=>(0,f.jsxs)(m.Label,{htmlFor:`shipping-method-${e.id}`,className:`flex items-center justify-between gap-3 p-4 rounded-lg border-2 cursor-pointer transition-colors ${j===e.id?`border-primary bg-primary/5`:`border-border hover:border-muted-foreground/40`}`,children:[(0,f.jsxs)(`span`,{className:`flex min-w-0 items-center gap-3`,children:[(0,f.jsx)(g.RadioGroupItem,{id:`shipping-method-${e.id}`,value:e.id}),(0,f.jsx)(`span`,{className:`font-medium break-words`,children:e.name})]}),(0,f.jsx)(`span`,{className:`font-bold tabular-nums`,children:y(e.amount,V)})]},e.id))}):(0,f.jsx)(`div`,{className:`py-4 text-center text-muted-foreground bg-muted/30 rounded-lg italic`,children:Q?B(`ecommerce.no_rates_for_region`):q(`ecommerce.waiting_on_address_info`,`Complete your shipping address to view available shipping options.`)})})]}):null]}),(0,f.jsxs)(`div`,{className:`lg:col-span-4 space-y-6`,children:[(0,f.jsxs)(h.Card,{className:`top-6`,children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsx)(h.CardTitle,{role:`heading`,"aria-level":2,children:B(`ecommerce.order_summary`)})}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[(0,f.jsx)(`div`,{className:`space-y-3 max-h-[260px] overflow-y-auto pr-2`,children:U.map(e=>{let t=n.getCartItemActivePrice(e,{currencyCode:V,currencies:H}),r=a.getTrialSummary(e,B);return(0,f.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex gap-3`,children:[e.image_url?(0,f.jsx)(`div`,{className:`h-10 w-10 shrink-0 overflow-hidden rounded border bg-neutral-100`,children:(0,f.jsx)(`img`,{src:e.image_url,alt:e.title,className:`h-full w-full object-cover`})}):null,(0,f.jsxs)(`div`,{className:`grid gap-0.5`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium text-xs line-clamp-1`,children:e.title}),(0,f.jsx)(re.Badge,{variant:`outline`,className:`text-[9px] uppercase`,children:et(e)})]}),e.variant_label?(0,f.jsx)(`span`,{className:`text-[10px] text-muted-foreground line-clamp-1`,children:e.variant_label}):null,(0,f.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[B(`ecommerce.qty`),`: `,e.quantity]}),r?(0,f.jsxs)(`span`,{className:`text-[10px] font-medium text-emerald-700`,children:[r.label,` - `,r.paymentRequirementLabel]}):null]})]}),(0,f.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 shrink-0`,children:[(0,f.jsx)(`span`,{className:`font-medium text-xs`,children:y((t.sale_price??t.price)*e.quantity,V)}),t.sale_price?(0,f.jsx)(`span`,{className:`text-[9px] text-muted-foreground line-through`,children:y(t.price*e.quantity,V)}):null]})]},`${e.id}-${e.variant_id||`base`}`)})}),(0,f.jsx)(se.Separator,{}),(0,f.jsx)(o.CouponForm,{items:U,currencyCode:V,onQuoteChange:De}),(0,f.jsxs)(`div`,{className:`space-y-2 text-sm`,children:[(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:B(`ecommerce.subtotal`)}),(0,f.jsx)(`span`,{children:y(Ne,V)})]}),W.length>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-muted-foreground`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.physical_products`,`Physical products`)}),(0,f.jsx)(`span`,{children:y(Pe,V)})]}):null,G.length>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-muted-foreground`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.digital_products`,`Digital products`)}),(0,f.jsx)(`span`,{children:y(Fe,V)})]}):null,F?(0,f.jsxs)(`div`,{className:`flex justify-between text-emerald-600`,children:[(0,f.jsxs)(`span`,{children:[q(`ecommerce.discount`,`Discount`),` (`,F.code,`)`]}),(0,f.jsxs)(`span`,{children:[`-`,y(F.discountTotal,V)]})]}):null,(W.length>0||G.length>0)&&(0,f.jsxs)(`div`,{className:`flex justify-between font-bold text-lg pt-2 border-t mt-2`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.estimated_total`,`Estimated total`)}),(0,f.jsx)(`span`,{className:`text-primary`,children:y(Be,V)})]})]})]})]}),W.length>0?(0,f.jsxs)(pe,{title:q(`ecommerce.stripe_checkout_title`,`Stripe Checkout`),description:q(`ecommerce.stripe_checkout_description`,`Pay for physical products in one Stripe checkout session.`),badgeLabel:Qe,children:[(0,f.jsxs)(`div`,{className:`space-y-2 text-sm`,children:[(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.physical_subtotal`,`Physical subtotal`)}),(0,f.jsx)(`span`,{children:y(Pe,V)})]}),Ie>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-emerald-600`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.discount`,`Discount`)}),(0,f.jsxs)(`span`,{children:[`-`,y(Ie,V)]})]}):null,(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:B(`ecommerce.shipping`)}),(0,f.jsx)(`span`,{children:$?y($.amount,V):`-`})]}),(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.tax`,`Tax`)}),(0,f.jsx)(`span`,{children:Ee?`...`:N?.isPendingExternalCalculation?q(`ecommerce.tax_calculated_on_stripe`,`Calculated on Stripe`):N?y(N.amount,V):`-`})]}),N&&N.lines.length>0?(0,f.jsx)(`div`,{className:`rounded-lg bg-muted/20 px-3 py-2 text-xs text-muted-foreground`,children:N.lines.map(e=>(0,f.jsxs)(`div`,{className:`flex justify-between gap-3`,children:[(0,f.jsxs)(`span`,{children:[e.name,` (`,e.rate.toFixed(4),`%)`]}),(0,f.jsx)(`span`,{children:y(e.amount,V)})]},e.id||`${e.name}-${e.rate}`))}):null,(0,f.jsxs)(`div`,{className:`flex justify-between font-semibold pt-2 border-t`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.total_on_stripe`,`Total on Stripe`)}),(0,f.jsx)(`span`,{children:y(ze,V)})]})]}),(0,f.jsxs)(ie.Button,{className:`w-full`,size:`lg`,onClick:()=>Ke(`stripe`,W,`stripe`),disabled:Ze,children:[b===`stripe`?(0,f.jsx)(d.Loader2,{className:`mr-2 h-4 w-4 animate-spin`}):(0,f.jsx)(d.Package,{className:`mr-2 h-4 w-4`}),b===`stripe`?B(`ecommerce.processing`):q(`ecommerce.checkout_physical_products`,`Checkout Physical Products`)]}),Xe&&b===null?(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:Xe}):null,S.stripe?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:S.stripe}):null,(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:N?.isPendingExternalCalculation?q(`checkout_stripe_tax_finalized_notice`,`Tax will be finalized by Stripe Tax on the payment step.`):q(`ecommerce.shipping_taxes_collected_on_stripe`,`Shipping and taxes are only collected during the Stripe step for physical products.`)})]}):null,G.length>0?(0,f.jsxs)(pe,{title:q(`ecommerce.freemius_checkout_title`,`Freemius Checkout`),description:q(`ecommerce.freemius_checkout_description`,`Digital products use the Freemius checkout flow.`),badgeLabel:$e,children:[(0,f.jsx)(`div`,{className:`space-y-3`,children:G.map(e=>{let t=n.getCartItemActivePrice(e,{currencyCode:V,currencies:H}),r=a.getTrialSummary(e,B),i=`freemius:${e.id}`,o=r?me[i]||`paid`:void 0;return(0,f.jsxs)(`div`,{className:`rounded-lg border p-3 space-y-3`,children:[(0,f.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,f.jsxs)(`div`,{children:[(0,f.jsx)(`p`,{className:`font-medium`,children:e.title}),e.billing_cycle?(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground capitalize`,children:tt(e.billing_cycle)}):null,r?(0,f.jsxs)(`p`,{className:`text-xs font-medium text-emerald-700`,children:[r.label,` - `,r.paymentRequirementLabel]}):null]}),(0,f.jsx)(`span`,{className:`font-medium`,children:y(t.sale_price??t.price,V)})]}),r&&!e.trial_requires_payment_method&&(0,f.jsxs)(`div`,{className:`bg-muted/30 p-3 rounded-md border text-sm mt-2 mb-3`,children:[(0,f.jsx)(`p`,{className:`font-medium mb-3`,children:q(`ecommerce.freemius_trial_preference_title`,`How would you like to start your trial?`)}),(0,f.jsxs)(g.RadioGroup,{value:me[i]||`paid`,onValueChange:e=>he(t=>({...t,[i]:e})),className:`gap-3`,children:[(0,f.jsxs)(`div`,{className:`flex items-start space-x-3`,children:[(0,f.jsx)(g.RadioGroupItem,{value:`paid`,id:`${i}-paid`,className:`mt-1`}),(0,f.jsxs)(`div`,{className:`grid gap-1.5`,children:[(0,f.jsx)(m.Label,{htmlFor:`${i}-paid`,className:`font-medium leading-none cursor-pointer`,children:q(`ecommerce.freemius_trial_with_card`,`Enter Payment Details Now (Still get full trial length free)`)}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:q(`ecommerce.freemius_trial_with_card_help`,`You will not be billed until the trial ends. Cancel anytime.`)})]})]}),(0,f.jsxs)(`div`,{className:`flex items-start space-x-3`,children:[(0,f.jsx)(g.RadioGroupItem,{value:`free`,id:`${i}-free`,className:`mt-1`}),(0,f.jsx)(`div`,{className:`grid gap-1.5`,children:(0,f.jsx)(m.Label,{htmlFor:`${i}-free`,className:`font-medium leading-none cursor-pointer`,children:q(`ecommerce.freemius_trial_no_card`,`Start Free Trial (No card required)`)})})]})]})]}),(0,f.jsxs)(ie.Button,{className:`w-full h-auto min-h-[2.75rem] py-2`,onClick:()=>Ke(`freemius`,[{...e,...o?{trial_preference:o}:{}}],i),disabled:b!==null||Ye!==null,children:[b===i?(0,f.jsx)(d.Loader2,{className:`mr-2 h-4 w-4 shrink-0 animate-spin`}):(0,f.jsx)(d.Download,{className:`mr-2 h-4 w-4 shrink-0`}),(0,f.jsx)(`span`,{className:`whitespace-normal text-left`,children:b===i?B(`ecommerce.processing`):G.length>1?q(`ecommerce.checkout_product`,`Checkout {title}`,{title:e.title}):q(`ecommerce.checkout_digital_product`,`Checkout Digital Product`)})]})]},i)})}),(0,f.jsxs)(`div`,{className:`flex justify-between text-sm font-semibold border-t pt-3`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.digital_subtotal`,`Digital subtotal`)}),(0,f.jsx)(`span`,{children:y(Fe,V)})]}),Le>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-sm font-semibold text-emerald-600`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.discount`,`Discount`)}),(0,f.jsxs)(`span`,{children:[`-`,y(Le,V)]})]}):null,Ye?(0,f.jsx)(`div`,{className:`rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs`,children:Ye}):null,S.freemius?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:S.freemius}):null,(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:G.length>1?q(`ecommerce.freemius_multi_checkout_notice`,`Freemius licenses are completed one at a time, so each digital product gets its own checkout action.`):q(`ecommerce.freemius_tax_notice`,`Taxes and compliance for digital products are handled inside the Freemius checkout.`)})]}):null]})]})]})]})};exports.Checkout=y;
1
+ "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../types.cjs"),t=require("../CurrencyProvider.cjs"),n=require("../cart-store.cjs"),r=require("../use-cart.cjs"),i=require("../use-price-formatter.cjs"),a=require("../trials.cjs"),o=require("./CouponForm.cjs"),s=require("../countries.cjs"),c=require("../states.cjs"),ee=require("../server-actions/shipping-actions.cjs"),te=require("../PaymentReadinessProvider.cjs"),ne=require("../server-actions/tax-actions.cjs"),l=require("../customer.cjs");let re=require("@nextblock-cms/ui/badge"),ie=require("@nextblock-cms/ui/button"),u=require("react"),d=require("lucide-react"),ae=require("@nextblock-cms/utils"),f=require("react/jsx-runtime"),p=require("@nextblock-cms/ui/input"),m=require("@nextblock-cms/ui/label"),h=require("@nextblock-cms/ui/card"),oe=require("@nextblock-cms/ui/checkbox"),se=require("@nextblock-cms/ui/separator"),g=require("@nextblock-cms/ui/radio-group"),ce=require("@freemius/checkout");var le=process.env.NEXT_PUBLIC_IS_SANDBOX===`true`,_=`nextblock-checkout-draft-v1`;function v(e,t){return{...l.emptyCustomerAddress(),company_name:e?.company_name||``,recipient_name:e?.recipient_name||t||``,line1:e?.line1||``,line2:e?.line2||``,city:e?.city||``,state:e?.state||``,postal_code:e?.postal_code||``,country_code:s.normalizeCountryCode(e?.country_code)||`CA`}}function ue(e){let t=l.normalizeCustomerAddress(e);return!(!t?.country_code||!t.postal_code||c.countryUsesStructuredStates(t.country_code)&&!t.state)}function de(e,t,r){return e.reduce((e,i)=>{let{price:a,sale_price:o}=n.getCartItemActivePrice(i,{currencyCode:t,currencies:r});return e+(o??a)*i.quantity},0)}function fe({idPrefix:e,title:t,description:n,value:r,onChange:i}){let{t:a,lang:o}=(0,ae.useTranslations)(),ee=(0,u.useMemo)(()=>{try{return new Intl.DisplayNames([o],{type:`region`})}catch{return null}},[o]),te=a(`company_name`)===`company_name`?`Company name`:a(`company_name`),ne=a(`select_an_option`)===`select_an_option`?`Select an option`:a(`select_an_option`),l=a(`state_province`)===`state_province`?`State / Province`:a(`state_province`),re=c.getStatesForCountry(r.country_code),ie=c.countryUsesStructuredStates(r.country_code);return(0,f.jsxs)(h.Card,{children:[(0,f.jsxs)(h.CardHeader,{children:[(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.MapPin,{className:`w-5 h-5`}),t]}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[(0,f.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-company`,children:te}),(0,f.jsx)(p.Input,{id:`${e}-company`,name:`${e}-company`,autoComplete:`${e} organization`,value:r.company_name,onChange:e=>i({...r,company_name:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-name`,children:a(`full_name`)}),(0,f.jsx)(p.Input,{id:`${e}-name`,name:`${e}-name`,autoComplete:`${e} name`,required:!0,value:r.recipient_name,onChange:e=>i({...r,recipient_name:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-country`,children:a(`country`)}),(0,f.jsx)(`select`,{id:`${e}-country`,name:`${e}-country`,autoComplete:`${e} country`,required:!0,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,value:r.country_code,onChange:e=>{let t=e.target.value,n=c.getStatesForCountry(t);i({...r,country_code:t,state:n.some(e=>e.code===r.state)?r.state:``})},children:s.countries.map(e=>(0,f.jsx)(`option`,{value:e.code,children:ee?.of(e.code)??e.name},e.code))})]})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-line1`,children:a(`address_line_1`)}),(0,f.jsx)(p.Input,{id:`${e}-line1`,name:`${e}-line1`,autoComplete:`${e} address-line1`,required:!0,value:r.line1,onChange:e=>i({...r,line1:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-line2`,children:a(`address_line_2`)}),(0,f.jsx)(p.Input,{id:`${e}-line2`,name:`${e}-line2`,autoComplete:`${e} address-line2`,value:r.line2,onChange:e=>i({...r,line2:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-city`,children:a(`city`)}),(0,f.jsx)(p.Input,{id:`${e}-city`,name:`${e}-city`,autoComplete:`${e} address-level2`,required:!0,value:r.city,onChange:e=>i({...r,city:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-state`,children:a(`state_province`)}),ie?(0,f.jsxs)(`select`,{id:`${e}-state`,name:`${e}-state`,autoComplete:`${e} address-level1`,required:!0,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,value:r.state,onChange:e=>i({...r,state:e.target.value}),children:[(0,f.jsx)(`option`,{value:``,children:`${ne}: ${l}`}),re.map(e=>(0,f.jsx)(`option`,{value:e.code,children:c.getSubdivisionLabel(r.country_code,e,o)},e.code))]}):(0,f.jsx)(p.Input,{id:`${e}-state`,name:`${e}-state`,autoComplete:`${e} address-level1`,value:r.state,onChange:e=>i({...r,state:e.target.value})})]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`${e}-postal`,children:a(`postal_zip_code`)}),(0,f.jsx)(p.Input,{id:`${e}-postal`,name:`${e}-postal`,autoComplete:`${e} postal-code`,required:!0,value:r.postal_code,onChange:e=>i({...r,postal_code:e.target.value})})]})]})]})]})}function pe({title:e,description:t,badgeLabel:n,children:r}){return(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[(0,f.jsxs)(`div`,{children:[(0,f.jsx)(h.CardTitle,{role:`heading`,"aria-level":2,children:e}),(0,f.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t})]}),n?(0,f.jsx)(re.Badge,{variant:`secondary`,children:n}):null]})}),(0,f.jsx)(h.CardContent,{className:`space-y-4`,children:r})]})}var y=({initialCustomer:s})=>{let y=i.usePriceFormatter(),[me,he]=(0,u.useState)({}),[b,x]=(0,u.useState)(null),[S,C]=(0,u.useState)({}),[w,ge]=(0,u.useState)(s?.email||``),[T,_e]=(0,u.useState)(``),[E,ve]=(0,u.useState)(s?.phone||``),[ye,be]=(0,u.useState)(!1),[xe,Se]=(0,u.useState)(null),[Ce,D]=(0,u.useState)(!1),[we,Te]=(0,u.useState)(!1),[Ee,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)([]),[j,M]=(0,u.useState)(null),[N,P]=(0,u.useState)(null),[F,De]=(0,u.useState)(null),[I,Oe]=(0,u.useState)(()=>v(s?.billingAddress,s?.fullName)),[L,ke]=(0,u.useState)(()=>v(s?.shippingAddress??s?.billingAddress,s?.fullName)),[R,Ae]=(0,u.useState)(!s?.shippingAddress||l.addressesMatch(s?.billingAddress,s?.shippingAddress)),z=r.useCart(e=>e),{t:B,lang:je}=(0,ae.useTranslations)(),{activeCurrencyCode:V,currencies:H}=t.useCurrency(),Me=te.usePaymentReadiness(),U=z?.items??[],W=(0,u.useMemo)(()=>U.filter(t=>!e.isDigitalItem(t)),[U]),G=(0,u.useMemo)(()=>U.filter(t=>e.isDigitalItem(t)),[U]),K=s?.isAuthenticated??!1,q=(e,t,n)=>{let r=B(e,n);if(r!==e)return r;if(!n)return t;let i=t;return Object.entries(n).forEach(([e,t])=>{i=i.replace(RegExp(`\\{${e}\\}`,`g`),String(t))}),i},J=W.length>0,Ne=(0,u.useMemo)(()=>de(U,V,H),[V,H,U]),Pe=(0,u.useMemo)(()=>de(W,V,H),[V,H,W]),Fe=(0,u.useMemo)(()=>de(G,V,H),[V,H,G]),Ie=F?.providerDiscounts.stripe??0,Le=F?.providerDiscounts.freemius??0,Y=Math.max(0,Pe-Ie),Re=Math.max(0,Fe-Le),X=(0,u.useMemo)(()=>R?I:L,[I,L,R]),Z=(0,u.useMemo)(()=>J?X:I,[I,J,X]),Q=!J||ue(X),$=(0,u.useMemo)(()=>k.find(e=>e.id===j),[k,j]),ze=(0,u.useMemo)(()=>Y+($?.amount??0)+(N&&!N.isPendingExternalCalculation?N.amount:0),[Y,$,N]),Be=ze+Re;if((0,u.useEffect)(()=>{if(!(K||typeof window>`u`))try{let e=window.localStorage.getItem(_);if(!e)return;let t=JSON.parse(e);t.email&&ge(t.email),t.phone&&ve(t.phone),t.billingAddress&&Oe(v(t.billingAddress)),t.shippingAddress&&ke(v(t.shippingAddress)),typeof t.useBillingForShipping==`boolean`&&Ae(t.useBillingForShipping),(typeof t.selectedMethodId==`string`||t.selectedMethodId===null)&&M(t.selectedMethodId)}catch(e){console.error(`[Checkout] Failed to restore checkout draft:`,e)}},[K]),(0,u.useEffect)(()=>{if(typeof window<`u`)try{if(K){window.localStorage.removeItem(_);return}window.localStorage.setItem(_,JSON.stringify({email:w,phone:E,billingAddress:I,shippingAddress:L,useBillingForShipping:R,selectedMethodId:j}))}catch{}},[I,w,K,E,j,L,R]),(0,u.useEffect)(()=>{if(!J){A([]),M(null),D(!1);return}if(!Q){A([]),M(null),D(!1);return}let e=!1,t=setTimeout(async()=>{if(X.country_code){D(!0),Te(!1);try{let t=await ee.getShippingEstimates(Y,{country:X.country_code,state:X.state,postal_code:X.postal_code},je,V);if(e)return;if(t.success&&t.methods){let e=t.methods;A(e),M(t=>t&&e.some(e=>e.id===t)?t:e[0]?.id??null)}else A([]),M(null)}catch(t){if(e)return;console.error(`[Checkout] Failed to load shipping rates:`,t),A([]),M(null),Te(!0)}finally{e||D(!1)}}},400);return()=>{e=!0,clearTimeout(t)}},[V,J,Q,je,X.country_code,X.postal_code,X.state,Y]),(0,u.useEffect)(()=>{let e=!1,t=setTimeout(async()=>{if(!J||!Z.country_code){O(!1),P(null);return}if(c.countryUsesStructuredStates(Z.country_code)&&!Z.state){O(!1),P(null);return}O(!0);try{let t=await ne.getTaxEstimate(W,{country_code:Z.country_code,state:Z.state},V,F?.code??null,U);if(e)return;P(t.success&&t.tax?t.tax:null)}catch(t){if(e)return;console.error(`[Checkout] Failed to load the tax estimate:`,t),P(null)}finally{e||O(!1)}},300);return()=>{e=!0,clearTimeout(t)}},[V,J,W,Z.country_code,Z.state,F?.code,U]),(0,u.useEffect)(()=>{let e=e=>{e.persisted&&x(null)};return window.addEventListener(`pageshow`,e),()=>window.removeEventListener(`pageshow`,e)},[]),!z)return(0,f.jsxs)(`div`,{role:`status`,"aria-busy":`true`,className:`container mx-auto px-4 py-12 md:px-6`,children:[(0,f.jsx)(`span`,{className:`sr-only`,children:B(`loading`)===`loading`?`Loading…`:B(`loading`)}),(0,f.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,f.jsx)(`div`,{className:`mb-8 h-9 w-48 rounded-md bg-muted`}),(0,f.jsxs)(`div`,{className:`grid gap-8 lg:grid-cols-12 lg:items-start`,children:[(0,f.jsxs)(`div`,{className:`space-y-6 lg:col-span-8`,children:[(0,f.jsx)(`div`,{className:`h-56 rounded-xl border bg-muted/40`}),(0,f.jsx)(`div`,{className:`h-96 rounded-xl border bg-muted/40`})]}),(0,f.jsx)(`div`,{className:`lg:col-span-4`,children:(0,f.jsx)(`div`,{className:`h-72 rounded-xl border bg-muted/40`})})]})]})]});let Ve=()=>{be(!1),Se(null)},He=ye?(0,f.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center overscroll-contain bg-black/60 backdrop-blur-sm`,onClick:Ve,onKeyDown:e=>{e.key===`Escape`&&Ve()},children:(0,f.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`sandbox-checkout-title`,className:`relative bg-background border rounded-xl shadow-2xl p-8 max-w-md mx-4`,onClick:e=>e.stopPropagation(),children:[(0,f.jsx)(`button`,{type:`button`,autoFocus:!0,onClick:Ve,"aria-label":q(`close`,`Close`),className:`absolute top-4 right-4 inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring`,children:(0,f.jsx)(d.X,{className:`w-5 h-5`})}),(0,f.jsxs)(`div`,{className:`flex items-center gap-3 mb-4`,children:[(0,f.jsx)(`div`,{className:`p-2 rounded-full bg-amber-100 dark:bg-amber-900/20`,children:(0,f.jsx)(d.FlaskConical,{className:`h-6 w-6 text-amber-600 dark:text-amber-400`})}),(0,f.jsx)(`h2`,{id:`sandbox-checkout-title`,className:`text-xl font-semibold`,children:B(`ecommerce.checkout_successful`)})]}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-2`,children:B(`ecommerce.sandbox_notice`)}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-2`,children:xe===`stripe`?q(`ecommerce.sandbox_checkout_stripe_description`,`This simulated step represents the Stripe checkout for physical products.`):q(`ecommerce.sandbox_checkout_freemius_description`,`This simulated step represents the Freemius checkout for digital products.`)}),(0,f.jsx)(`p`,{className:`text-muted-foreground mb-6`,children:B(`ecommerce.license_notice`)}),(0,f.jsx)(`a`,{href:`https://nextblock.dev`,target:`_blank`,rel:`noopener noreferrer`,className:`block w-full text-center py-3 px-4 rounded-lg bg-primary text-primary-foreground font-semibold hover:opacity-90 transition-opacity`,children:B(`ecommerce.purchase_at`)})]})}):null,Ue=(e,t,n)=>(C(n=>({...n,[e]:t})),n&&document.getElementById(n)?.focus(),null),We=(e,t)=>t.recipient_name.trim()?t.line1.trim()?t.city.trim()?c.countryUsesStructuredStates(t.country_code)&&!t.state?`${e}-state`:t.postal_code.trim()?`${e}-line1`:`${e}-postal`:`${e}-city`:`${e}-line1`:`${e}-name`,Ge=e=>{if(!K&&(!w||!/^\S+@\S+\.\S+$/.test(w)))return _e(B(`ecommerce.invalid_email`)),Ue(e,B(`ecommerce.invalid_email`),`checkout-email`);let t=l.normalizeCustomerAddress(I);if(!l.isCustomerAddressComplete(t))return Ue(e,B(`checkout_complete_billing_address`),We(`billing`,I));let n=J?l.normalizeCustomerAddress(R?I:L):null;if(e===`stripe`){if(!l.isCustomerAddressComplete(n))return Ue(e,B(`checkout_complete_shipping_address`),R?We(`billing`,I):We(`shipping`,L));if(!j)return Ue(e,q(`ecommerce.shipping_method_required`,`Please select a shipping method before continuing.`))}return _e(``),{normalizedBillingAddress:t,normalizedShippingAddress:n}},Ke=async(e,t,n)=>{C(t=>({...t,[e]:``}));let r=Ge(e);if(r){if(le){let n=new Set(t.map(e=>e.id)),r=U.filter(e=>!n.has(e.id));if(z.setItems(r),r.length===0&&z.removeCoupon(),Se(e),be(!0),typeof window<`u`&&r.length===0)try{window.localStorage.removeItem(_)}catch{}return}x(n);try{let n=await fetch(`/api/checkout`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({items:t,customerEmail:K?void 0:w,customerPhone:E||null,billingAddress:r.normalizedBillingAddress,shippingAddress:e===`stripe`?r.normalizedShippingAddress:null,shippingMethodId:e===`stripe`?j:null,locale:je,currencyCode:V,couponCode:F?.code??z.appliedCoupon?.code??null,couponContextItems:U})}),i=await n.json();if(!n.ok){let t=i?.errorKey&&typeof i.errorKey==`string`?q(i.errorKey,i?.error||q(`ecommerce.generic_error`,`Something went wrong.`),i.errorParams):i?.error||B(`ecommerce.generic_error`);C(n=>({...n,[e]:t})),x(null);return}if(i.customProps&&i.customProps.provider===`freemius`){let t=i.customProps,n=null,r=()=>{let e=t.success_token?`&token=${encodeURIComponent(t.success_token)}`:``;window.location.href=`/checkout/success?session_id=${t.order_id}${e}`},a=e=>(n||=fetch(`/api/checkout/freemius/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({orderId:t.order_id,checkoutResponse:e})}).then(async e=>{if(!e.ok){let t=await e.json().catch(()=>null);console.error(`Freemius checkout sync failed:`,t)}}),n),o={product_id:t.plugin_id,public_key:t.public_key,sandbox:t.sandbox},s={name:B(`ecommerce.checkout_overlay_title`),plan_id:t.plan_id,...t.billing_cycle?{billing_cycle:t.billing_cycle}:{},...t.trial?{trial:t.trial}:{},...t.coupon?{coupon:t.coupon}:{},user_email:t.user_email,user_firstname:t.user_firstname,user_lastname:t.user_lastname,sandbox:t.sandbox,purchaseCompleted:function(e){a(e)},success:function(e){(async()=>{try{await a(e)}finally{r()}})()}};try{new ce.Checkout(o).open(s),x(null)}catch(t){console.error(`[Checkout] Freemius overlay failed to open:`,t),C(t=>({...t,[e]:B(`ecommerce.checkout_popup_blocked`)})),i.url&&(window.location.href=i.url),x(null)}}else i.url?window.location.href=i.url:(C(t=>({...t,[e]:B(`ecommerce.checkout_failed`)+(i.error||q(`ecommerce.unknown_error`,`Unknown error`))})),x(null))}catch(t){console.error(t),C(t=>({...t,[e]:B(`ecommerce.generic_error`)})),x(null)}}};if(U.length===0)return(0,f.jsxs)(f.Fragment,{children:[He,(0,f.jsxs)(`div`,{className:`container mx-auto flex min-h-[50vh] flex-col items-center justify-center p-8 text-center`,children:[(0,f.jsx)(`h1`,{className:`mb-4 text-2xl font-bold`,children:B(`ecommerce.cart_empty`)}),(0,f.jsx)(`p`,{className:`mb-8 text-muted-foreground`,children:B(`ecommerce.cart_empty_description`)}),(0,f.jsx)(ie.Button,{asChild:!0,children:(0,f.jsx)(`a`,{href:`/shop`,children:B(`ecommerce.go_to_shop`)})})]})]});let qe=q(`ecommerce.checkout_payments_unavailable`,`This store is not able to take payments right now. Please contact the seller to complete your purchase.`),Je=Me.stripe?null:qe,Ye=Me.freemius?null:qe,Xe=Je||(J?Q?Ce?q(`ecommerce.calculating_shipping`,`Calculating shipping...`):j?null:k.length>0?B(`ecommerce.select_rate`):B(`ecommerce.no_rates_for_region`):q(`ecommerce.waiting_on_address_info`,`Complete your shipping address to view available shipping options.`):null),Ze=b!==null||Xe!==null,Qe=W.length===1?q(`ecommerce.item_count_one`,`{count} item`,{count:W.length}):q(`ecommerce.item_count_other`,`{count} items`,{count:W.length}),$e=G.length===1?q(`ecommerce.license_count_one`,`{count} license`,{count:G.length}):q(`ecommerce.license_count_other`,`{count} licenses`,{count:G.length}),et=t=>e.isDigitalItem(t)?q(`ecommerce.digital_label`,`Digital`):q(`ecommerce.physical_label`,`Physical`),tt=e=>e===`monthly`?q(`ecommerce.checkout_billing_cycle_monthly`,`Monthly subscription`):e===`annual`?q(`ecommerce.checkout_billing_cycle_annual`,`Annual subscription`):e===`lifetime`?q(`ecommerce.checkout_billing_cycle_lifetime`,`Lifetime subscription`):null;return(0,f.jsxs)(`div`,{className:`container mx-auto px-4 py-12 md:px-6`,children:[He,(0,f.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,f.jsx)(`h1`,{className:`mb-8 text-3xl font-bold`,children:B(`ecommerce.checkout`)}),(0,f.jsxs)(`div`,{className:`grid gap-8 lg:grid-cols-12 lg:items-start`,children:[(0,f.jsxs)(`div`,{className:`lg:col-span-8 space-y-6`,children:[(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.CreditCard,{className:`w-5 h-5`}),B(`ecommerce.contact_information`)]})}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[K?(0,f.jsx)(`div`,{className:`rounded-xl border bg-muted/20 p-4 text-sm text-muted-foreground`,children:B(`checkout_prefill_notice`,{email:s?.email||``})}):(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsxs)(m.Label,{htmlFor:`checkout-email`,children:[B(`ecommerce.email_address`),` `,(0,f.jsx)(`span`,{className:`text-destructive`,children:`*`})]}),(0,f.jsx)(p.Input,{id:`checkout-email`,name:`email`,type:`email`,autoComplete:`email`,spellCheck:!1,"aria-invalid":T?!0:void 0,"aria-describedby":T?`checkout-email-error`:void 0,placeholder:B(`ecommerce.email_placeholder`),value:w,onChange:e=>{ge(e.target.value),T&&_e(``)},required:!0}),T?(0,f.jsx)(`p`,{id:`checkout-email-error`,role:`alert`,className:`text-xs text-destructive mt-1`,children:T}):null]}),(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(m.Label,{htmlFor:`checkout-phone`,children:B(`phone_number`)}),(0,f.jsx)(p.Input,{id:`checkout-phone`,name:`phone`,type:`tel`,inputMode:`tel`,autoComplete:`tel`,placeholder:B(`optional`),value:E,onChange:e=>ve(e.target.value)})]})]})]}),(0,f.jsx)(fe,{idPrefix:`billing`,title:B(`billing_address`),description:B(`checkout_billing_address_help`),value:I,onChange:Oe}),J?(0,f.jsxs)(`div`,{className:`flex items-center space-x-3 rounded-xl border bg-muted/20 p-4`,children:[(0,f.jsx)(oe.Checkbox,{id:`use-billing-for-shipping`,checked:R,onCheckedChange:e=>Ae(!!e)}),(0,f.jsxs)(`div`,{className:`space-y-1`,children:[(0,f.jsx)(m.Label,{htmlFor:`use-billing-for-shipping`,className:`cursor-pointer`,children:B(`use_billing_for_shipping`)}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:B(`checkout_use_billing_for_shipping_help`)})]})]}):null,J&&!R?(0,f.jsx)(fe,{idPrefix:`shipping`,title:B(`shipping_address`),description:B(`checkout_shipping_address_help`),value:L,onChange:ke}):null,J?(0,f.jsxs)(h.Card,{children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsxs)(h.CardTitle,{role:`heading`,"aria-level":2,className:`flex items-center gap-2`,children:[(0,f.jsx)(d.ChevronRight,{className:`w-5 h-5 text-primary`}),B(`ecommerce.shipping_method`)]})}),(0,f.jsx)(h.CardContent,{children:Ce?(0,f.jsxs)(`div`,{role:`status`,className:`flex items-center justify-center py-6`,children:[(0,f.jsx)(d.Loader2,{className:`w-6 h-6 animate-spin text-muted-foreground`}),(0,f.jsx)(`span`,{className:`sr-only`,children:q(`ecommerce.calculating_shipping`,`Calculating shipping…`)})]}):we?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg bg-destructive/10 px-4 py-3 text-center text-sm text-destructive`,children:q(`ecommerce.shipping_calculation_failed`,`We couldn't calculate shipping right now. Please try again.`)}):k.length>0?(0,f.jsx)(g.RadioGroup,{value:j??``,onValueChange:M,"aria-label":B(`ecommerce.shipping_method`),className:`space-y-3`,children:k.map(e=>(0,f.jsxs)(m.Label,{htmlFor:`shipping-method-${e.id}`,className:`flex items-center justify-between gap-3 p-4 rounded-lg border-2 cursor-pointer transition-colors ${j===e.id?`border-primary bg-primary/5`:`border-border hover:border-muted-foreground/40`}`,children:[(0,f.jsxs)(`span`,{className:`flex min-w-0 items-center gap-3`,children:[(0,f.jsx)(g.RadioGroupItem,{id:`shipping-method-${e.id}`,value:e.id}),(0,f.jsx)(`span`,{className:`font-medium break-words`,children:e.name})]}),(0,f.jsx)(`span`,{className:`font-bold tabular-nums`,children:y(e.amount,V)})]},e.id))}):(0,f.jsx)(`div`,{className:`py-4 text-center text-muted-foreground bg-muted/30 rounded-lg italic`,children:Q?B(`ecommerce.no_rates_for_region`):q(`ecommerce.waiting_on_address_info`,`Complete your shipping address to view available shipping options.`)})})]}):null]}),(0,f.jsxs)(`div`,{className:`lg:col-span-4 space-y-6`,children:[(0,f.jsxs)(h.Card,{className:`top-6`,children:[(0,f.jsx)(h.CardHeader,{children:(0,f.jsx)(h.CardTitle,{role:`heading`,"aria-level":2,children:B(`ecommerce.order_summary`)})}),(0,f.jsxs)(h.CardContent,{className:`space-y-4`,children:[(0,f.jsx)(`div`,{className:`space-y-3 max-h-[260px] overflow-y-auto pr-2`,children:U.map(e=>{let t=n.getCartItemActivePrice(e,{currencyCode:V,currencies:H}),r=a.getTrialSummary(e,B);return(0,f.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex gap-3`,children:[e.image_url?(0,f.jsx)(`div`,{className:`h-10 w-10 shrink-0 overflow-hidden rounded border bg-neutral-100`,children:(0,f.jsx)(`img`,{src:e.image_url,alt:e.title,className:`h-full w-full object-cover`})}):null,(0,f.jsxs)(`div`,{className:`grid gap-0.5`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium text-xs line-clamp-1`,children:e.title}),(0,f.jsx)(re.Badge,{variant:`outline`,className:`text-[9px] uppercase`,children:et(e)})]}),e.variant_label?(0,f.jsx)(`span`,{className:`text-[10px] text-muted-foreground line-clamp-1`,children:e.variant_label}):null,(0,f.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[B(`ecommerce.qty`),`: `,e.quantity]}),r?(0,f.jsxs)(`span`,{className:`text-[10px] font-medium text-emerald-700`,children:[r.label,` - `,r.paymentRequirementLabel]}):null]})]}),(0,f.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 shrink-0`,children:[(0,f.jsx)(`span`,{className:`font-medium text-xs`,children:y((t.sale_price??t.price)*e.quantity,V)}),t.sale_price?(0,f.jsx)(`span`,{className:`text-[9px] text-muted-foreground line-through`,children:y(t.price*e.quantity,V)}):null]})]},`${e.id}-${e.variant_id||`base`}`)})}),(0,f.jsx)(se.Separator,{}),(0,f.jsx)(o.CouponForm,{items:U,currencyCode:V,onQuoteChange:De}),(0,f.jsxs)(`div`,{className:`space-y-2 text-sm`,children:[(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:B(`ecommerce.subtotal`)}),(0,f.jsx)(`span`,{children:y(Ne,V)})]}),W.length>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-muted-foreground`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.physical_products`,`Physical products`)}),(0,f.jsx)(`span`,{children:y(Pe,V)})]}):null,G.length>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-muted-foreground`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.digital_products`,`Digital products`)}),(0,f.jsx)(`span`,{children:y(Fe,V)})]}):null,F?(0,f.jsxs)(`div`,{className:`flex justify-between text-emerald-600`,children:[(0,f.jsxs)(`span`,{children:[q(`ecommerce.discount`,`Discount`),` (`,F.code,`)`]}),(0,f.jsxs)(`span`,{children:[`-`,y(F.discountTotal,V)]})]}):null,(W.length>0||G.length>0)&&(0,f.jsxs)(`div`,{className:`flex justify-between font-bold text-lg pt-2 border-t mt-2`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.estimated_total`,`Estimated total`)}),(0,f.jsx)(`span`,{className:`text-primary`,children:y(Be,V)})]})]})]})]}),W.length>0?(0,f.jsxs)(pe,{title:q(`ecommerce.stripe_checkout_title`,`Stripe Checkout`),description:q(`ecommerce.stripe_checkout_description`,`Pay for physical products in one Stripe checkout session.`),badgeLabel:Qe,children:[(0,f.jsxs)(`div`,{className:`space-y-2 text-sm`,children:[(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.physical_subtotal`,`Physical subtotal`)}),(0,f.jsx)(`span`,{children:y(Pe,V)})]}),Ie>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-emerald-600`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.discount`,`Discount`)}),(0,f.jsxs)(`span`,{children:[`-`,y(Ie,V)]})]}):null,(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:B(`ecommerce.shipping`)}),(0,f.jsx)(`span`,{children:$?y($.amount,V):`-`})]}),(0,f.jsxs)(`div`,{className:`flex justify-between`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.tax`,`Tax`)}),(0,f.jsx)(`span`,{children:Ee?`...`:N?.isPendingExternalCalculation?q(`ecommerce.tax_calculated_on_stripe`,`Calculated on Stripe`):N?y(N.amount,V):`-`})]}),N&&N.lines.length>0?(0,f.jsx)(`div`,{className:`rounded-lg bg-muted/20 px-3 py-2 text-xs text-muted-foreground`,children:N.lines.map(e=>(0,f.jsxs)(`div`,{className:`flex justify-between gap-3`,children:[(0,f.jsxs)(`span`,{children:[e.name,` (`,e.rate.toFixed(4),`%)`]}),(0,f.jsx)(`span`,{children:y(e.amount,V)})]},e.id||`${e.name}-${e.rate}`))}):null,(0,f.jsxs)(`div`,{className:`flex justify-between font-semibold pt-2 border-t`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.total_on_stripe`,`Total on Stripe`)}),(0,f.jsx)(`span`,{children:y(ze,V)})]})]}),(0,f.jsxs)(ie.Button,{className:`w-full`,size:`lg`,onClick:()=>Ke(`stripe`,W,`stripe`),disabled:Ze,children:[b===`stripe`?(0,f.jsx)(d.Loader2,{className:`mr-2 h-4 w-4 animate-spin`}):(0,f.jsx)(d.Package,{className:`mr-2 h-4 w-4`}),b===`stripe`?B(`ecommerce.processing`):q(`ecommerce.checkout_physical_products`,`Checkout Physical Products`)]}),Xe&&b===null?(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:Xe}):null,S.stripe?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:S.stripe}):null,(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:N?.isPendingExternalCalculation?q(`checkout_stripe_tax_finalized_notice`,`Tax will be finalized by Stripe Tax on the payment step.`):q(`ecommerce.shipping_taxes_collected_on_stripe`,`Shipping and taxes are only collected during the Stripe step for physical products.`)})]}):null,G.length>0?(0,f.jsxs)(pe,{title:q(`ecommerce.freemius_checkout_title`,`Freemius Checkout`),description:q(`ecommerce.freemius_checkout_description`,`Digital products use the Freemius checkout flow.`),badgeLabel:$e,children:[(0,f.jsx)(`div`,{className:`space-y-3`,children:G.map(e=>{let t=n.getCartItemActivePrice(e,{currencyCode:V,currencies:H}),r=a.getTrialSummary(e,B),i=`freemius:${e.id}`,o=r?me[i]||`paid`:void 0;return(0,f.jsxs)(`div`,{className:`rounded-lg border p-3 space-y-3`,children:[(0,f.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,f.jsxs)(`div`,{children:[(0,f.jsx)(`p`,{className:`font-medium`,children:e.title}),e.billing_cycle?(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground capitalize`,children:tt(e.billing_cycle)}):null,r?(0,f.jsxs)(`p`,{className:`text-xs font-medium text-emerald-700`,children:[r.label,` - `,r.paymentRequirementLabel]}):null]}),(0,f.jsx)(`span`,{className:`font-medium`,children:y(t.sale_price??t.price,V)})]}),r&&!e.trial_requires_payment_method&&(0,f.jsxs)(`div`,{className:`bg-muted/30 p-3 rounded-md border text-sm mt-2 mb-3`,children:[(0,f.jsx)(`p`,{className:`font-medium mb-3`,children:q(`ecommerce.freemius_trial_preference_title`,`How would you like to start your trial?`)}),(0,f.jsxs)(g.RadioGroup,{value:me[i]||`paid`,onValueChange:e=>he(t=>({...t,[i]:e})),className:`gap-3`,children:[(0,f.jsxs)(`div`,{className:`flex items-start space-x-3`,children:[(0,f.jsx)(g.RadioGroupItem,{value:`paid`,id:`${i}-paid`,className:`mt-1`}),(0,f.jsxs)(`div`,{className:`grid gap-1.5`,children:[(0,f.jsx)(m.Label,{htmlFor:`${i}-paid`,className:`font-medium leading-none cursor-pointer`,children:q(`ecommerce.freemius_trial_with_card`,`Enter Payment Details Now (Still get full trial length free)`)}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:q(`ecommerce.freemius_trial_with_card_help`,`You will not be billed until the trial ends. Cancel anytime.`)})]})]}),(0,f.jsxs)(`div`,{className:`flex items-start space-x-3`,children:[(0,f.jsx)(g.RadioGroupItem,{value:`free`,id:`${i}-free`,className:`mt-1`}),(0,f.jsx)(`div`,{className:`grid gap-1.5`,children:(0,f.jsx)(m.Label,{htmlFor:`${i}-free`,className:`font-medium leading-none cursor-pointer`,children:q(`ecommerce.freemius_trial_no_card`,`Start Free Trial (No card required)`)})})]})]})]}),(0,f.jsxs)(ie.Button,{className:`w-full h-auto min-h-[2.75rem] py-2`,onClick:()=>Ke(`freemius`,[{...e,...o?{trial_preference:o}:{}}],i),disabled:b!==null||Ye!==null,children:[b===i?(0,f.jsx)(d.Loader2,{className:`mr-2 h-4 w-4 shrink-0 animate-spin`}):(0,f.jsx)(d.Download,{className:`mr-2 h-4 w-4 shrink-0`}),(0,f.jsx)(`span`,{className:`whitespace-normal text-left`,children:b===i?B(`ecommerce.processing`):G.length>1?q(`ecommerce.checkout_product`,`Checkout {title}`,{title:e.title}):q(`ecommerce.checkout_digital_product`,`Checkout Digital Product`)})]})]},i)})}),(0,f.jsxs)(`div`,{className:`flex justify-between text-sm font-semibold border-t pt-3`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.digital_subtotal`,`Digital subtotal`)}),(0,f.jsx)(`span`,{children:y(Fe,V)})]}),Le>0?(0,f.jsxs)(`div`,{className:`flex justify-between text-sm font-semibold text-emerald-600`,children:[(0,f.jsx)(`span`,{children:q(`ecommerce.discount`,`Discount`)}),(0,f.jsxs)(`span`,{children:[`-`,y(Le,V)]})]}):null,Ye?(0,f.jsx)(`div`,{className:`rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs`,children:Ye}):null,S.freemius?(0,f.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive`,children:S.freemius}):null,(0,f.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:G.length>1?q(`ecommerce.freemius_multi_checkout_notice`,`Freemius licenses are completed one at a time, so each digital product gets its own checkout action.`):q(`ecommerce.freemius_tax_notice`,`Taxes and compliance for digital products are handled inside the Freemius checkout.`)})]}):null]})]})]})]})};exports.Checkout=y;
@@ -548,7 +548,8 @@ var T = ({ initialCustomer: s }) => {
548
548
  }
549
549
  if (i.customProps && i.customProps.provider === "freemius") {
550
550
  let t = i.customProps, n = null, r = () => {
551
- window.location.href = `/checkout/success?session_id=${t.order_id}`;
551
+ let e = t.success_token ? `&token=${encodeURIComponent(t.success_token)}` : "";
552
+ window.location.href = `/checkout/success?session_id=${t.order_id}${e}`;
552
553
  }, a = (e) => (n ||= fetch("/api/checkout/freemius/sync", {
553
554
  method: "POST",
554
555
  headers: { "Content-Type": "application/json" },
@@ -1 +1 @@
1
- const e=require("./currency.cjs"),t=require("./coupons.cjs");function n(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function r(e,t){return e===`all`||e===t}function i(e){return e===`stripe`||e===`freemius`?e:null}async function a(t){let{data:n,error:r}=await t.from(`currencies`).select(`code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount`).eq(`is_active`,!0).order(`code`,{ascending:!0});if(r)throw Error(r.message);return(n||[]).map(t=>e.normalizeCurrencyRecord(t))}async function o(n){let{client:r,items:o}=n,s=await a(r);if(s.length===0)throw Error(`No active currencies are configured.`);let c=s.find(e=>e.code===(n.currencyCode||``).toUpperCase())??e.getDefaultCurrency(s),l=[...new Set(o.map(e=>e.product_id).filter(Boolean))],u=[...new Set(o.map(e=>e.variant_id).filter(e=>!!e))];if(l.length===0)return{lines:[],currencies:s,selectedCurrency:c};let[{data:d,error:f},p]=await Promise.all([r.from(`products`).select(`id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, product_type, payment_provider, freemius_product_id, freemius_plan_id`).in(`id`,l),u.length?r.from(`product_variants`).select(`id, product_id, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at`).in(`id`,u):Promise.resolve({data:[],error:null})]);if(f)throw Error(f.message);if(p.error)throw Error(p.error.message);let m=d||[],h=p.data||[],g=new Map(m.map(e=>[e.id,e])),_=new Map(h.map(e=>[e.id,e])),v=[];for(let n of o){let r=g.get(n.product_id);if(!r)continue;let a=i(r.payment_provider)??(r.product_type===`digital`?`freemius`:`stripe`),o=n.variant_id?_.get(n.variant_id):null,l=o&&o.product_id===r.id?o:r,u=e.resolveEffectivePriceForCurrency({prices:e.normalizePriceMap(l.prices),salePrices:e.normalizeSalePriceMap(l.sale_prices),fallbackPrice:l.price,fallbackSalePrice:l.sale_price,saleStartAt:l.sale_start_at,saleEndAt:l.sale_end_at,scheduledPrice:l.scheduled_price,scheduledPrices:e.normalizePriceMap(l.scheduled_prices),scheduledPriceAt:l.scheduled_price_at,currencyCode:c.code,currencies:s}),d=a===`freemius`?1:Math.max(1,Number(n.quantity)||1),f=Math.max(0,u.sale_price??u.price);v.push({key:t.getCartLineCouponKey(n),product_id:r.id,variant_id:o?.id??null,title:r.title,quantity:d,provider:a,subtotal:f*d,freemius_product_id:r.freemius_product_id??null,freemius_plan_id:r.freemius_plan_id??null})}return{lines:v,currencies:s,selectedCurrency:c}}async function s(e,t){let{data:n,error:r}=await e.from(`coupon_products`).select(`product_id`).eq(`coupon_id`,t);if(r)throw Error(r.message);return new Set((n||[]).map(e=>e.product_id))}function c(e,t){let n=e.reduce((e,t)=>e+t.subtotal,0),r=Math.min(t,n);if(n<=0||r<=0)return new Map;let i=new Map,a=0;return e.forEach((t,o)=>{let s=o===e.length-1?r-a:Math.min(t.subtotal,Math.floor(r*t.subtotal/n));a+=s,i.set(t.key,s)}),i}async function l(e){let i=t.normalizeCouponCode(e.code);if(!i)return{success:!1,error:`Enter a coupon code.`,errorKey:`ecommerce.coupon_code_required`};if(!e.items.length)return{success:!1,error:`Add an item to your cart before applying a coupon.`,errorKey:`ecommerce.coupon_cart_empty`};let{data:a,error:l}=await e.client.from(`coupons`).select(`id, code, name, provider_scope, discount_type, discount_amount, is_active, starts_at, ends_at, redemption_limit, redemptions_count`).ilike(`code`,i).maybeSingle();if(l)throw Error(l.message);if(!a)return{success:!1,error:`Coupon code not found.`,errorKey:`ecommerce.coupon_not_found`};let u=a,d=new Date,f=n(u.starts_at),p=n(u.ends_at);if(!u.is_active)return{success:!1,error:`This coupon is not active.`,errorKey:`ecommerce.coupon_inactive`};if(f&&f>d)return{success:!1,error:`This coupon is not active yet.`,errorKey:`ecommerce.coupon_not_started`};if(p&&p<=d)return{success:!1,error:`This coupon has expired.`,errorKey:`ecommerce.coupon_expired`};if(u.redemption_limit!==null&&(u.redemptions_count??0)>=u.redemption_limit)return{success:!1,error:`This coupon has reached its redemption limit.`,errorKey:`ecommerce.coupon_limit_reached`};let[{lines:m},h]=await Promise.all([o({client:e.client,items:e.items,currencyCode:e.currencyCode}),s(e.client,u.id)]),g=h.size>0,_=m.filter(e=>e.subtotal>0&&r(u.provider_scope,e.provider)&&(!g||h.has(e.product_id)));if(_.length===0)return{success:!1,error:`This coupon does not apply to the items in your cart.`,errorKey:`ecommerce.coupon_not_applicable`};let v=u.discount_type===`fixed`?c(_,u.discount_amount):null,y=t.emptyProviderDiscounts(),b=_.map(e=>{let t=u.discount_type===`percent`?Math.min(e.subtotal,Math.round(e.subtotal*u.discount_amount/100)):v?.get(e.key)??0;return y[e.provider]+=t,{key:e.key,product_id:e.product_id,variant_id:e.variant_id,provider:e.provider,title:e.title,quantity:e.quantity,subtotal:e.subtotal,discount:t}});return{success:!0,quote:{couponId:u.id,code:u.code,name:u.name,discountType:u.discount_type,discountAmount:u.discount_amount,providerScope:u.provider_scope,eligibleSubtotal:_.reduce((e,t)=>e+t.subtotal,0),discountTotal:y.stripe+y.freemius,providerDiscounts:y,lineDiscounts:b}}}function u(e){let t=new Map;for(let n of e?.lineDiscounts??[])t.set(n.key,n.discount);return t}async function d(e){let{error:t}=await e.client.from(`coupon_redemptions`).insert({coupon_id:e.quote.couponId,order_id:e.orderId,coupon_code:e.quote.code,provider:e.provider,discount_total:Math.max(0,e.discountTotal),user_id:e.userId||null,customer_email:e.customerEmail||null,metadata:e.metadata||{}});if(t){console.error(`Failed to record coupon redemption:`,t);return}let{data:n}=await e.client.from(`coupons`).select(`redemptions_count`).eq(`id`,e.quote.couponId).single();await e.client.from(`coupons`).update({redemptions_count:(n?.redemptions_count??0)+1,updated_at:new Date().toISOString()}).eq(`id`,e.quote.couponId)}exports.getCouponQuote=l,exports.getQuoteLineDiscountMap=u,exports.recordCouponRedemption=d;
1
+ const e=require("./currency.cjs"),t=require("./coupons.cjs");require("server-only");function n(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function r(e,t){return e===`all`||e===t}function i(e){return e===`stripe`||e===`freemius`?e:null}async function a(t){let{data:n,error:r}=await t.from(`currencies`).select(`code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount`).eq(`is_active`,!0).order(`code`,{ascending:!0});if(r)throw Error(r.message);return(n||[]).map(t=>e.normalizeCurrencyRecord(t))}async function o(n){let{client:r,items:o}=n,s=await a(r);if(s.length===0)throw Error(`No active currencies are configured.`);let c=s.find(e=>e.code===(n.currencyCode||``).toUpperCase())??e.getDefaultCurrency(s),l=[...new Set(o.map(e=>e.product_id).filter(Boolean))],u=[...new Set(o.map(e=>e.variant_id).filter(e=>!!e))];if(l.length===0)return{lines:[],currencies:s,selectedCurrency:c};let[{data:d,error:f},p]=await Promise.all([r.from(`products`).select(`id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, product_type, payment_provider, freemius_product_id, freemius_plan_id`).in(`id`,l),u.length?r.from(`product_variants`).select(`id, product_id, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at`).in(`id`,u):Promise.resolve({data:[],error:null})]);if(f)throw Error(f.message);if(p.error)throw Error(p.error.message);let m=d||[],h=p.data||[],g=new Map(m.map(e=>[e.id,e])),_=new Map(h.map(e=>[e.id,e])),v=[];for(let n of o){let r=g.get(n.product_id);if(!r)continue;let a=i(r.payment_provider)??(r.product_type===`digital`?`freemius`:`stripe`),o=n.variant_id?_.get(n.variant_id):null,l=o&&o.product_id===r.id?o:r,u=e.resolveEffectivePriceForCurrency({prices:e.normalizePriceMap(l.prices),salePrices:e.normalizeSalePriceMap(l.sale_prices),fallbackPrice:l.price,fallbackSalePrice:l.sale_price,saleStartAt:l.sale_start_at,saleEndAt:l.sale_end_at,scheduledPrice:l.scheduled_price,scheduledPrices:e.normalizePriceMap(l.scheduled_prices),scheduledPriceAt:l.scheduled_price_at,currencyCode:c.code,currencies:s}),d=a===`freemius`?1:Math.max(1,Number(n.quantity)||1),f=Math.max(0,u.sale_price??u.price);v.push({key:t.getCartLineCouponKey(n),product_id:r.id,variant_id:o?.id??null,title:r.title,quantity:d,provider:a,subtotal:f*d,freemius_product_id:r.freemius_product_id??null,freemius_plan_id:r.freemius_plan_id??null})}return{lines:v,currencies:s,selectedCurrency:c}}async function s(e,t){let{data:n,error:r}=await e.from(`coupon_products`).select(`product_id`).eq(`coupon_id`,t);if(r)throw Error(r.message);return new Set((n||[]).map(e=>e.product_id))}function c(e,t){let n=e.reduce((e,t)=>e+t.subtotal,0),r=Math.min(t,n);if(n<=0||r<=0)return new Map;let i=new Map,a=0;return e.forEach((t,o)=>{let s=o===e.length-1?r-a:Math.min(t.subtotal,Math.floor(r*t.subtotal/n));a+=s,i.set(t.key,s)}),i}var l={not_found:{error:`Coupon code not found.`,errorKey:`ecommerce.coupon_not_found`},inactive:{error:`This coupon is not active.`,errorKey:`ecommerce.coupon_inactive`},not_started:{error:`This coupon is not active yet.`,errorKey:`ecommerce.coupon_not_started`},expired:{error:`This coupon has expired.`,errorKey:`ecommerce.coupon_expired`},limit_reached:{error:`This coupon has reached its redemption limit.`,errorKey:`ecommerce.coupon_limit_reached`},not_applicable:{error:`This coupon does not apply to the items in your cart.`,errorKey:`ecommerce.coupon_not_applicable`}};function u(e,n){return{success:!1,...n?l[e]:{error:t.COUPON_INVALID_ERROR_MESSAGE,errorKey:t.COUPON_INVALID_ERROR_KEY}}}async function d(e){let i=t.normalizeCouponCode(e.code),a=e.detailedErrors===!0;if(!i)return{success:!1,error:`Enter a coupon code.`,errorKey:`ecommerce.coupon_code_required`};if(!e.items.length)return{success:!1,error:`Add an item to your cart before applying a coupon.`,errorKey:`ecommerce.coupon_cart_empty`};let{data:l,error:d}=await e.client.from(`coupons`).select(`id, code, name, provider_scope, discount_type, discount_amount, is_active, starts_at, ends_at, redemption_limit, redemptions_count`).ilike(`code`,i).maybeSingle();if(d)throw Error(d.message);if(!l)return u(`not_found`,a);let f=l,p=new Date,m=n(f.starts_at),h=n(f.ends_at);if(!f.is_active)return u(`inactive`,a);if(m&&m>p)return u(`not_started`,a);if(h&&h<=p)return u(`expired`,a);if(f.redemption_limit!==null&&(f.redemptions_count??0)>=f.redemption_limit)return u(`limit_reached`,a);let[{lines:g},_]=await Promise.all([o({client:e.client,items:e.items,currencyCode:e.currencyCode}),s(e.client,f.id)]),v=_.size>0,y=g.filter(e=>e.subtotal>0&&r(f.provider_scope,e.provider)&&(!v||_.has(e.product_id)));if(y.length===0)return u(`not_applicable`,a);let b=f.discount_type===`fixed`?c(y,f.discount_amount):null,x=t.emptyProviderDiscounts(),S=y.map(e=>{let t=f.discount_type===`percent`?Math.min(e.subtotal,Math.round(e.subtotal*f.discount_amount/100)):b?.get(e.key)??0;return x[e.provider]+=t,{key:e.key,product_id:e.product_id,variant_id:e.variant_id,provider:e.provider,title:e.title,quantity:e.quantity,subtotal:e.subtotal,discount:t}});return{success:!0,quote:{couponId:f.id,code:f.code,name:f.name,discountType:f.discount_type,discountAmount:f.discount_amount,providerScope:f.provider_scope,eligibleSubtotal:y.reduce((e,t)=>e+t.subtotal,0),discountTotal:x.stripe+x.freemius,providerDiscounts:x,lineDiscounts:S}}}function f(e){let t=new Map;for(let n of e?.lineDiscounts??[])t.set(n.key,n.discount);return t}async function p(e){let n=e=>({success:!1,reason:e,error:t.COUPON_INVALID_ERROR_MESSAGE,errorKey:t.COUPON_INVALID_ERROR_KEY}),{data:r,error:i}=await e.client.from(`coupon_redemptions`).select(`id`).eq(`order_id`,e.orderId).maybeSingle();if(i)return console.error(`Failed to look up existing coupon redemption:`,i),n(`error`);if(r)return{success:!0,alreadyRecorded:!0};let{data:a,error:o}=await e.client.rpc(`redeem_coupon_atomically`,{p_coupon_id:e.quote.couponId});if(o)return console.error(`Failed to reserve coupon redemption:`,o),n(`error`);if(a!==!0)return n(`limit_reached`);let{error:s}=await e.client.from(`coupon_redemptions`).insert({coupon_id:e.quote.couponId,order_id:e.orderId,coupon_code:e.quote.code,provider:e.provider,discount_total:Math.max(0,e.discountTotal),user_id:e.userId||null,customer_email:e.customerEmail||null,metadata:e.metadata||{}});return s&&console.error(`Failed to record coupon redemption:`,s),{success:!0,alreadyRecorded:!1}}var m=30,h=12/60,g=5e3,_=`unknown`;function v(e){let t=e?.capacity??m,n=e?.refillPerSecond??h,r=e?.maxBuckets??g,i=t/n*1e3,a=new Map;function o(e){for(let[t,n]of a)e-n.updatedAt>=i&&a.delete(t);for(let e of a.keys()){if(a.size<r)break;a.delete(e)}}return{consume(e,i=Date.now()){let s=a.get(e);if(!s)a.size>=r&&o(i),s={tokens:t,updatedAt:i},a.set(e,s);else{let e=Math.max(0,i-s.updatedAt)/1e3;s.tokens=Math.min(t,s.tokens+e*n),s.updatedAt=i}return s.tokens<1?!1:(--s.tokens,!0)},get size(){return a.size}}}var y=v();function b(e,t){return y.consume(e,t)}function x(e){let[t]=(e??``).split(`,`);return(t?.trim()??``)||null}function S(e){return x(e.get(`x-vercel-forwarded-for`))??x(e.get(`x-real-ip`))??x(e.get(`x-forwarded-for`))??`unknown`}exports.COUPON_VALIDATION_UNKNOWN_CLIENT_KEY=_,exports.consumeCouponValidationToken=b,exports.createCouponValidationThrottle=v,exports.getCouponQuote=d,exports.getQuoteLineDiscountMap=f,exports.recordCouponRedemption=p,exports.resolveCouponValidationThrottleKey=S;
@@ -7,8 +7,45 @@ export declare function getCouponQuote(input: {
7
7
  code?: string | null;
8
8
  items: CartItem[];
9
9
  currencyCode?: string | null;
10
+ /**
11
+ * Return the specific rejection reason instead of the uniform shopper message. Only for
12
+ * authenticated CMS tooling: on a public path it re-opens the code-enumeration oracle.
13
+ */
14
+ detailedErrors?: boolean;
10
15
  }): Promise<CouponQuoteResult>;
11
16
  export declare function getQuoteLineDiscountMap(quote?: CouponQuote | null): Map<string, number>;
17
+ export type CouponRedemptionResult = {
18
+ success: true;
19
+ /** True when this order already held a redemption, so no new slot was taken. */
20
+ alreadyRecorded: boolean;
21
+ } | {
22
+ success: false;
23
+ /**
24
+ * `limit_reached`: `redeem_coupon_atomically` refused the slot (exhausted, or the coupon
25
+ * was deactivated/deleted since the quote). `error`: a database failure; nothing was
26
+ * recorded. Both carry the uniform shopper message, so a checkout that surfaces them
27
+ * tells a probing caller nothing a validation call would not.
28
+ */
29
+ reason: 'limit_reached' | 'error';
30
+ error: string;
31
+ errorKey: string;
32
+ };
33
+ /**
34
+ * Take one redemption slot for `quote.couponId` and record it against `orderId`.
35
+ *
36
+ * The counter is bumped by `public.redeem_coupon_atomically(uuid)` (migration 02022): a single
37
+ * locked `UPDATE ... WHERE redemptions_count < redemption_limit RETURNING`, so N concurrent
38
+ * checkouts of a `redemption_limit = N` coupon get exactly N `true`s and every later call gets
39
+ * `false`. The previous SELECT-then-UPDATE with an app-computed literal lost increments under
40
+ * concurrency and let the cap be bypassed. The RPC is EXECUTE-granted to `service_role` only,
41
+ * so `client` must be the service-role client (the providers already use it here).
42
+ *
43
+ * The slot is reserved BEFORE the audit row is inserted: if the insert then fails, the slot
44
+ * is lost rather than the cap exceeded, which is the conservative failure for a promotion.
45
+ * The call is idempotent per order so a retry (a redelivered webhook, once redemption moves
46
+ * to payment confirmation) cannot consume a second slot. Validation (`getCouponQuote`) never
47
+ * touches the counter.
48
+ */
12
49
  export declare function recordCouponRedemption(input: {
13
50
  client: SupabaseLikeClient;
14
51
  quote: CouponQuote;
@@ -18,5 +55,32 @@ export declare function recordCouponRedemption(input: {
18
55
  userId?: string | null;
19
56
  customerEmail?: string | null;
20
57
  metadata?: Record<string, unknown>;
21
- }): Promise<void>;
58
+ }): Promise<CouponRedemptionResult>;
59
+ /**
60
+ * Shared bucket for requests whose origin cannot be read. Unattributable requests are
61
+ * throttled TOGETHER, never exempted: "could not parse the address" must not mean "no limit".
62
+ */
63
+ export declare const COUPON_VALIDATION_UNKNOWN_CLIENT_KEY = "unknown";
64
+ export declare function createCouponValidationThrottle(options?: {
65
+ capacity?: number;
66
+ refillPerSecond?: number;
67
+ maxBuckets?: number;
68
+ }): {
69
+ /** Spend one token for `key`; false means the caller is over its budget right now. */
70
+ consume(key: string, now?: number): boolean;
71
+ readonly size: number;
72
+ };
73
+ /** Spend one validation token for `key` on the process-wide bucket set. */
74
+ export declare function consumeCouponValidationToken(key: string, now?: number): boolean;
75
+ /**
76
+ * Throttle key for a request: the client address as the platform reports it.
77
+ *
78
+ * `x-forwarded-for` is a list the client can prepend to, so on an appending proxy its leftmost
79
+ * entry is attacker-controlled and would mint a fresh bucket per request. `x-vercel-forwarded-for`
80
+ * and `x-real-ip` are overwritten by the proxy on every request, so they win. No address at all
81
+ * lands in the shared unknown bucket.
82
+ */
83
+ export declare function resolveCouponValidationThrottleKey(requestHeaders: {
84
+ get(name: string): string | null;
85
+ }): string;
22
86
  export {};