@tagadapay/headless-sdk 1.17.0 → 1.18.0
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.
- package/README.md +22 -0
- package/dist/core/modules/customer.d.ts +26 -4
- package/dist/core/modules/customer.d.ts.map +1 -1
- package/dist/core/modules/customer.js +50 -16
- package/dist/core/modules/customer.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/provider.d.ts +13 -2
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +35 -7
- package/dist/react/provider.js.map +1 -1
- package/dist/tagada-headless-commerce.min.js +2 -2
- package/dist/tagada-headless-commerce.min.js.map +4 -4
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +3 -3
- package/dist/tagada-headless.js +4 -4
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +1 -1
- package/dist/tagada-pixels.min.js +1 -1
- package/package.json +4 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/core/modules/commerce.ts", "../src/core/modules/portal/index.ts", "../src/core/modules/offers.ts", "../src/core/modules/customer.ts"],
|
|
4
|
-
"sourcesContent": ["// CDN chunk for capabilities that do not need to run during checkout bootstrap.\nexport { CustomerPortalModule } from './portal/index.js';\nexport { OffersModule } from './offers.js';\nexport { CustomerModule } from './customer.js';\n", "import type { HttpClient } from '../../http.js';\nimport type {\n Billing,\n PortalAcceptOfferInput,\n PortalAddToNextOrderInput,\n PortalAcceptOfferResult,\n PortalAddCardInput,\n PortalAddressInput,\n PortalBuyAgainLine,\n PortalBuyCreditPackInput,\n PortalCancelFlowInput,\n PortalCancelOfferInput,\n PortalCheckoutResult,\n PortalCredits,\n PortalCreditsOrderResult,\n PortalMe,\n PortalOffer,\n PortalProfileInput,\n PortalPublicConfig,\n PortalRedeemCreditsInput,\n PortalSubscriptionResult,\n PortalSwitchInput,\n PortalSwitchResult,\n PortalTargetResult,\n PortalVerifyCodeResult,\n} from './types.js';\n\n/**\n * Customer portal (Subscriptions V3): the store's portal config, the logged-in\n * customer, retention, plan switches, upsell links and credits.\n *\n * Log in with `requestCode` then `verifyCode`; every other call except\n * `getConfig` needs that session. Subscription actions (pause, skip, \u2026) live on\n * `client.customer`.\n *\n * Endpoints:\n * GET /api/v1/portal/config\n * GET /api/v1/portal/me\n * POST /api/v1/portal/cancel-flow\n * POST /api/v1/portal/cancel-flow/accept\n * POST /api/v1/portal/switch\n * GET /api/v1/portal/offers/:token\n * POST /api/v1/portal/offers/accept\n * POST /api/v1/portal/next-order\n * GET /api/v1/portal/credits\n * POST /api/v1/portal/credits/redeem\n * POST /api/v1/portal/credits/packs/buy\n * POST /api/v1/portal/profile, /profile/email-code\n * POST /api/v1/portal/addresses, /addresses/remove, /addresses/default\n * POST /api/v1/portal/payment-methods, /payment-methods/remove, /payment-methods/default\n * POST /api/v1/portal/retry-payment\n * POST /api/v1/portal/buy-again\n * POST /api/v1/portal/membership/join\n * POST /api/v1/subscriptions/send-now, /reactivate, /saved-card, /shipping-address, /skip-date, /unskip\n */\nexport class CustomerPortalModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n private readonly setToken: (token: string) => void,\n ) {}\n\n /** Email a login code to the customer. */\n async requestCode(email: string): Promise<void> {\n await this.http.post('/api/v1/cms/session/request-code', { email, storeId: this.storeId });\n }\n\n /** Exchange the emailed code for a session; later calls send it. */\n async verifyCode(email: string, code: string): Promise<PortalVerifyCodeResult> {\n const res = await this.http.post<PortalVerifyCodeResult>('/api/v1/cms/session/login', {\n email,\n code,\n storeId: this.storeId,\n });\n this.setToken(res.token);\n return res;\n }\n\n /** The store's published portal: design, retention, membership program, products. */\n async getConfig(): Promise<PortalPublicConfig> {\n return this.http.get<PortalPublicConfig>('/api/v1/portal/config', { params: { storeId: this.storeId } });\n }\n\n /** The logged-in customer: profile, orders, subscriptions, membership, credit ledger. */\n async getMe(): Promise<PortalMe> {\n return this.http.get<PortalMe>('/api/v1/portal/me');\n }\n\n /** Cancel a subscription or the membership after the reasons step. */\n async cancelFlow(input: PortalCancelFlowInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/cancel-flow', input);\n }\n\n /** Take the retention offer mapped to the chosen reason instead of cancelling. */\n async acceptCancelOffer(input: PortalCancelOfferInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/cancel-flow/accept', input);\n }\n\n /** Move a subscription or the membership to another option now, charged now. */\n async switchOption(input: PortalSwitchInput): Promise<PortalSwitchResult> {\n return this.http.post<PortalSwitchResult>('/api/v1/portal/switch', input);\n }\n\n /** The upsell a signed link (`/account/offer/<token>`) offers. No login: the token is the authorization. */\n async getOffer(token: string): Promise<PortalOffer> {\n return this.http.get<PortalOffer>(`/api/v1/portal/offers/${encodeURIComponent(token)}`);\n }\n\n /** Accept a signed upsell link and pay it with the card of the original order. A second accept charges nothing. */\n async acceptOffer(input: PortalAcceptOfferInput): Promise<PortalAcceptOfferResult> {\n return this.http.post<PortalAcceptOfferResult>('/api/v1/portal/offers/accept', input);\n }\n\n /** Ship a one-time item with the subscription's next renewal, charged with it; quantity 0 takes it off. */\n async addToNextOrder(input: PortalAddToNextOrderInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/next-order', input);\n }\n\n /** Credit balance and ledger of the logged-in customer. */\n async getCredits(): Promise<PortalCredits> {\n return this.http.get<PortalCredits>('/api/v1/portal/credits');\n }\n\n /** Pay a product with credits. */\n async redeemCredits(input: PortalRedeemCreditsInput): Promise<PortalCreditsOrderResult> {\n return this.http.post<PortalCreditsOrderResult>('/api/v1/portal/credits/redeem', input);\n }\n\n /** Buy a credit pack with the stored card. */\n async buyCreditPack(input: PortalBuyCreditPackInput): Promise<PortalCreditsOrderResult> {\n return this.http.post<PortalCreditsOrderResult>('/api/v1/portal/credits/packs/buy', input);\n }\n\n // \u2500\u2500 The customer's own account \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Email a code to a new address; `updateProfile` saves that email with it (`emailCode`). */\n async requestEmailChangeCode(email: string): Promise<void> {\n await this.http.post('/api/v1/portal/profile/email-code', { email });\n }\n\n /** The logged-in customer's name, email and phone. */\n async updateProfile(profile: PortalProfileInput): Promise<void> {\n await this.http.post('/api/v1/portal/profile', profile);\n }\n\n /** Add an address, or replace the one with that id; `isDefault` makes it the default. */\n async saveAddress(address: PortalAddressInput): Promise<{ addressId: string }> {\n return this.http.post('/api/v1/portal/addresses', address);\n }\n\n /** Remove an address; the default one stays until another is the default. */\n async removeAddress(addressId: string): Promise<void> {\n await this.http.post('/api/v1/portal/addresses/remove', { addressId });\n }\n\n async setDefaultAddress(addressId: string): Promise<void> {\n await this.http.post('/api/v1/portal/addresses/default', { addressId });\n }\n\n /** Save a card tokenized with `client.payment.tokenizeCard`. */\n async addCard(input: PortalAddCardInput): Promise<{ paymentMethodId: string }> {\n return this.http.post('/api/v1/portal/payment-methods', input);\n }\n\n /** Remove a saved card; refused while a live subscription is paid with it. */\n async removeCard(paymentMethodId: string): Promise<void> {\n await this.http.post('/api/v1/portal/payment-methods/remove', { paymentMethodId });\n }\n\n /** The default card also becomes the card of every live subscription. */\n async setDefaultPaymentMethod(paymentMethodId: string): Promise<void> {\n await this.http.post('/api/v1/portal/payment-methods/default', { paymentMethodId });\n }\n\n /** Charge a past-due subscription again now. */\n async retryPayment(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/portal/retry-payment', { subscriptionId });\n }\n\n /** Order products again at today's one-time price with the default card and address. */\n async buyAgain(lines: readonly PortalBuyAgainLine[]): Promise<PortalCheckoutResult> {\n return this.http.post('/api/v1/portal/buy-again', { lines: lines.map(({ variantId, quantity }) => ({ variantId, quantity })) });\n }\n\n /** Buy the Membership's monthly or yearly option with the default card. */\n async joinMembership(billing: Billing): Promise<PortalCheckoutResult> {\n return this.http.post('/api/v1/portal/membership/join', { billing });\n }\n\n /** Buy one product now at its one-time price with the default card and address. */\n async buyNow(variantId: string, quantity = 1): Promise<PortalCheckoutResult> {\n return this.buyAgain([{ variantId, quantity }]);\n }\n\n /** Charge and ship a subscription's next order today. */\n async sendNow(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/send-now', { subscriptionId });\n }\n\n /** Restart a cancelled subscription, or keep one set to end at its period end. */\n async reactivateSubscription(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/reactivate', { subscriptionId });\n }\n\n /** Bill a subscription on another saved card. */\n async setSubscriptionCard(subscriptionId: string, paymentMethodId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/saved-card', { subscriptionId, paymentMethodId });\n }\n\n /** Ship a subscription to an address of the book; null follows the default address. */\n async setSubscriptionAddress(subscriptionId: string, addressId: string | null): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/shipping-address', { subscriptionId, addressId });\n }\n\n /** Skip one upcoming delivery date (`YYYY-MM-DD`); skipping the next one moves the next charge. */\n async skipDate(subscriptionId: string, date: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/skip-date', { subscriptionId, date });\n }\n\n /** Take back a skipped delivery date (`YYYY-MM-DD`). */\n async unskipDate(subscriptionId: string, date: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/unskip', { subscriptionId, date });\n }\n}\n", "import type { HttpClient } from '../http.js';\nimport type {\n Offer,\n OfferPreview,\n OfferPayResult,\n ProcessPaymentResult,\n} from '../types.js';\nimport type { PaymentModule } from './payment.js';\n\n/**\n * Offers \u2014 upsells, downsells, order bumps, and post-purchase offers.\n *\n * Endpoints align with the plugin-sdk patterns:\n * GET /api/v1/offers/:id \u2014 single offer\n * GET /api/v1/stores/:storeId/offers \u2014 list store offers\n * POST /api/v1/offers/:offerId/preview \u2014 preview pricing\n * POST /api/v1/offers/:offerId/pay-preview \u2014 pay a previewed offer (one-click)\n * POST /api/v1/checkout-sessions/:id/toggle-order-bump \u2014 toggle order bump\n * GET /api/v1/post-purchase/:orderId/offers \u2014 post-purchase offers for an order\n * Post-purchase acceptance uses pay-preview; declining is a local decision.\n */\nexport class OffersModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n private readonly payment?: PaymentModule,\n ) {}\n\n // ---------------------------------------------------------------------------\n // Offer loading\n // ---------------------------------------------------------------------------\n\n /** Get a single offer by ID. */\n async getOffer(offerId: string): Promise<Offer> {\n return this.http.get<Offer>(`/api/v1/offers/${offerId}`);\n }\n\n /** List offers for the current store. Optionally filter by type or a set of IDs. */\n async listOffers(opts?: {\n type?: 'upsell' | 'orderbump';\n ids?: string[];\n }): Promise<Offer[]> {\n let url = `/api/v1/stores/${this.storeId}/offers`;\n\n const queryParts: string[] = [];\n if (opts?.type) queryParts.push(`type=${encodeURIComponent(opts.type)}`);\n if (opts?.ids?.length) {\n for (const id of opts.ids) queryParts.push(`ids=${encodeURIComponent(id)}`);\n }\n if (queryParts.length) url += `?${queryParts.join('&')}`;\n\n const res = await this.http.get<{ offers: Offer[] }>(url);\n return res.offers ?? [];\n }\n\n // ---------------------------------------------------------------------------\n // Preview & pay (one-click upsell flow from plugin-sdk)\n // ---------------------------------------------------------------------------\n\n /**\n * Preview offer pricing. Returns line items with amounts and totals.\n *\n * A Studio offer block is previewed under `blockoffer:<blockId>` and read from\n * the step its funnel session stands on: pass that session's id\n * (see {@link enterFunnelStep}).\n */\n async previewOffer(opts: {\n offerId: string;\n currency?: string;\n lineItems?: Array<{ lineItemId?: string; productId?: string; variantId: string; quantity: number }>;\n funnelSessionId?: string;\n }): Promise<OfferPreview> {\n return this.http.post<OfferPreview>(`/api/v1/offers/${opts.offerId}/preview`, {\n offerId: opts.offerId,\n currency: opts.currency ?? '',\n lineItems: opts.lineItems,\n funnelSessionId: opts.funnelSessionId,\n });\n }\n\n /**\n * Put the buyer on a step of a funnel, for pages the funnel does not serve\n * itself: its offer blocks are then previewed and accepted as\n * `blockoffer:<blockId>` with the returned `funnelSessionId`. Uses the\n * checkout session's token, so the funnel session is the paying customer's.\n * Pass `checkoutToken` at checkout to link that checkout to the funnel\n * session, and `funnelSessionId` to move an open session to another step.\n */\n async enterFunnelStep(opts: {\n funnelId: string;\n stepId: string;\n accountId: string;\n funnelSessionId?: string;\n checkoutToken?: string;\n }): Promise<{ funnelSessionId: string }> {\n const here = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';\n const res = await this.http.post<{ context: { sessionId: string } }>('/api/v1/funnel/initialize', {\n // Placeholder ids: the server takes the customer and the CMS session from the token.\n cmsSession: { customerId: 'anon_placeholder', sessionId: 'anon_placeholder', storeId: this.storeId, accountId: opts.accountId },\n funnelId: opts.funnelId,\n funnelStepId: opts.stepId,\n existingSessionId: opts.funnelSessionId,\n currentUrl: opts.checkoutToken ? `${here}/?checkoutToken=${encodeURIComponent(opts.checkoutToken)}` : undefined,\n draft: false,\n });\n return { funnelSessionId: res.context.sessionId };\n }\n\n /**\n * Pay a previously previewed offer (one-click charge).\n * Used after a main order so the stored payment instrument is reused.\n *\n * **Low-level API.** Returns the raw `OfferPayResult` \u2014 `requireAction`,\n * polling, and 3DS redirects are NOT handled. For most cases, use\n * {@link processOfferPayment} which orchestrates the full lifecycle.\n */\n async payPreviewedOffer(opts: {\n offerId: string;\n mainOrderId: string;\n currency?: string;\n lineItems?: Array<{ lineItemId?: string; productId?: string; variantId: string; quantity: number }>;\n returnUrl?: string;\n paymentInstrumentId?: string;\n funnelSessionId?: string;\n }): Promise<OfferPayResult> {\n return this.http.post<OfferPayResult>(`/api/v1/offers/${opts.offerId}/pay-preview`, {\n offerId: opts.offerId,\n currency: opts.currency ?? '',\n lineItems: opts.lineItems,\n returnUrl: opts.returnUrl ?? (typeof window !== 'undefined' ? window.location.href : ''),\n mainOrderId: opts.mainOrderId,\n paymentInstrumentId: opts.paymentInstrumentId,\n funnelSessionId: opts.funnelSessionId,\n });\n }\n\n /**\n * One-click upsell with full lifecycle handling.\n *\n * Like `payment.processPayment()` but for previewed offers: charges the\n * stored instrument from `mainOrderId`, runs any 3DS challenge or bank\n * redirect, polls until terminal, and returns a typed\n * `ProcessPaymentResult` (`succeeded` / `requires_redirect` /\n * `failed` / `pending`).\n *\n * Use this instead of the lower-level `payPreviewedOffer()` whenever you\n * don't need to inspect the raw `OfferPayResult` shape \u2014 which is most\n * of the time.\n *\n * @example\n * ```ts\n * const result = await tagada.offers.processOfferPayment({\n * offerId: 'offer_xxx',\n * mainOrderId: order.id,\n * returnUrl: window.location.href,\n * });\n *\n * switch (result.status) {\n * case 'succeeded':\n * window.location.href = '/upsell-2';\n * break;\n * case 'requires_redirect':\n * window.location.href = result.redirectUrl;\n * break;\n * case 'failed':\n * showError(result.error);\n * break;\n * }\n * ```\n */\n async processOfferPayment(opts: {\n offerId: string;\n mainOrderId: string;\n currency?: string;\n lineItems?: Array<{\n lineItemId?: string;\n productId?: string;\n variantId: string;\n quantity: number;\n }>;\n returnUrl?: string;\n paymentInstrumentId?: string;\n funnelSessionId?: string;\n }): Promise<ProcessPaymentResult> {\n if (!this.payment) {\n throw new Error(\n 'OffersModule: no PaymentModule injected. ' +\n 'Use createHeadlessClient() instead of constructing OffersModule directly.',\n );\n }\n const returnUrl =\n opts.returnUrl ?? (typeof window !== 'undefined' ? window.location.href : undefined);\n const payResult = await this.payPreviewedOffer({ ...opts, returnUrl });\n return this.payment.finalize(\n { payment: payResult.payment, order: payResult.order },\n { returnUrl },\n );\n }\n\n // ---------------------------------------------------------------------------\n // Order bumps (checkout-session scoped)\n // ---------------------------------------------------------------------------\n\n /** Toggle an order bump on/off within a checkout session. */\n async toggleOrderBump(opts: {\n checkoutSessionId: string;\n orderBumpOfferId: string;\n selected: boolean;\n }): Promise<unknown> {\n return this.http.post(\n `/api/v1/checkout-sessions/${opts.checkoutSessionId}/toggle-order-bump`,\n {\n orderBumpOfferId: opts.orderBumpOfferId,\n selected: opts.selected,\n },\n );\n }\n\n // ---------------------------------------------------------------------------\n // Post-purchase offers (order-scoped)\n // ---------------------------------------------------------------------------\n\n /** List post-purchase offers for an order. */\n async listPostPurchaseOffers(orderId: string): Promise<Offer[]> {\n const res = await this.http.get<Offer[]>(`/api/v1/post-purchase/${orderId}/offers`);\n return Array.isArray(res) ? res : [];\n }\n\n /** Accept a post-purchase offer. Only a confirmed charge returns success. */\n async acceptPostPurchaseOffer(opts: {\n orderId: string;\n offerId: string;\n items?: Array<{ variantId: string; quantity: number }>;\n }): Promise<{ success: boolean; error?: string }> {\n // The server matches overrides by line-item/product ID, not variant alone.\n // Resolve against this offer's quote so an unrelated variant cannot silently\n // fall back to charging the offer's default selection.\n let lineItems: Array<{ lineItemId: string; productId: string; variantId: string; quantity: number }> | undefined;\n if (opts.items?.length) {\n const quote = await this.http.post<{\n lineItems: Array<{ lineItemId: string; productId: string; variantId: string }>;\n preview: { options: Record<string, Array<{ id: string }>> };\n }>(`/api/v1/offers/${opts.offerId}/preview`, { offerId: opts.offerId, currency: '' });\n lineItems = [];\n for (const item of opts.items) {\n const matches = quote.lineItems.filter(line => line.variantId === item.variantId ||\n quote.preview.options[line.productId]?.some(variant => variant.id === item.variantId));\n if (matches.length !== 1 || lineItems.some(line => line.lineItemId === matches[0].lineItemId)) {\n return { success: false, error: 'Invalid selection' };\n }\n lineItems.push({ ...item, lineItemId: matches[0].lineItemId, productId: matches[0].productId });\n }\n }\n const result = await this.payPreviewedOffer({\n offerId: opts.offerId,\n mainOrderId: opts.orderId,\n lineItems,\n });\n if (result.payment.status === 'succeeded') return { success: true };\n return {\n success: false,\n error: result.payment.status === 'pending'\n ? 'Payment pending'\n : result.payment.status === 'requires_action' ||\n (result.payment.requireAction && result.payment.requireAction !== 'none')\n ? 'Payment requires authentication'\n : result.payment.requireActionData?.message || 'Payment declined',\n };\n }\n\n /** Decline locally; the backend has no persisted refusal and no charge is made. */\n async declinePostPurchaseOffer(opts: {\n orderId: string;\n offerId: string;\n }): Promise<{ success: boolean; error?: string }> {\n return { success: true };\n }\n}\n", "import type { HttpClient } from '../http.js';\nimport type { Customer, Order, Subscription } from '../types.js';\n\n/**\n * Customer data -- profile, orders, subscriptions.\n *\n * Requires either an API key or a session token for authentication.\n */\nexport class CustomerModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n ) {}\n\n /** Get customer profile by ID. */\n async getProfile(customerId: string): Promise<Customer> {\n const res = await this.http.get<{ customer: Customer }>(\n `/api/v1/customers/${customerId}`,\n { params: { storeId: this.storeId } },\n );\n return res.customer;\n }\n\n /** Get customer profile by email. */\n async getByEmail(email: string): Promise<Customer | null> {\n try {\n const res = await this.http.get<{ customer: Customer }>(\n '/api/v1/customers/by-email',\n { params: { email, storeId: this.storeId } },\n );\n return res.customer;\n } catch {\n return null;\n }\n }\n\n /**\n * Update the customer's email (`POST /api/v1/customers/:id`, the checkout's email step): the\n * route stores the email only. A portal customer's name and phone go through `portal.updateProfile`.\n */\n async updateProfile(\n customerId: string,\n data: Partial<Pick<Customer, 'email' | 'firstName' | 'lastName' | 'phone' | 'metadata'>>,\n ): Promise<Customer> {\n await this.http.post(`/api/v1/customers/${customerId}`, { customerId, data: { email: data.email } });\n return this.getProfile(customerId);\n }\n\n /** List orders for a customer. */\n async getOrders(\n customerId: string,\n opts?: { limit?: number; offset?: number },\n ): Promise<{ orders: Order[]; total: number }> {\n return this.http.get<{ orders: Order[]; total: number }>(\n `/api/v1/customers/${customerId}/orders`,\n { params: { storeId: this.storeId, limit: opts?.limit, offset: opts?.offset } },\n );\n }\n\n /**\n * Get a single order by ID.\n *\n * **Thank-you pages:** accepted one-click upsells create *child orders*\n * (`metadata.mainOrderId` = this order's id) that land asynchronously \u2014\n * the first fetch right after an accept usually misses them. Pass\n * `waitForRelatedOrders: true` to poll until `order.relatedOrders` is\n * non-empty or the timeout elapses. On timeout the latest snapshot is\n * returned (never throws), so an order with no accepted upsell simply\n * comes back with an empty `relatedOrders` after `timeoutMs`.\n *\n * @example\n * ```ts\n * // Thank-you page: show the main order AND the upsells\n * const order = await tagada.customer.getOrder(orderId, {\n * waitForRelatedOrders: true,\n * });\n * renderOrders([order, ...(order.relatedOrders ?? [])]);\n * ```\n */\n async getOrder(\n orderId: string,\n opts?: {\n /** Poll until `relatedOrders` is non-empty (or `timeoutMs` elapses). */\n waitForRelatedOrders?: boolean;\n /** Max total wait in ms. Default: 8000. */\n timeoutMs?: number;\n /** Delay between polls in ms. Default: 2000. */\n intervalMs?: number;\n },\n ): Promise<Order> {\n const fetchOrder = async (): Promise<Order> => {\n const res = await this.http.get<{ order: Order }>(`/api/v1/orders/${orderId}`, {\n params: { storeId: this.storeId },\n });\n return res.order;\n };\n\n let order = await fetchOrder();\n if (!opts?.waitForRelatedOrders || order.relatedOrders?.length) return order;\n\n const timeoutMs = opts.timeoutMs ?? 8000;\n const intervalMs = opts.intervalMs ?? 2000;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));\n order = await fetchOrder();\n if (order.relatedOrders?.length) return order;\n }\n return order;\n }\n\n /** List subscriptions for a customer. */\n async getSubscriptions(customerId: string): Promise<Subscription[]> {\n const res = await this.http.get<{ subscriptions: Subscription[] }>(\n `/api/v1/customers/${customerId}/subscriptions`,\n { params: { storeId: this.storeId } },\n );\n return res.subscriptions;\n }\n\n /** Get a single subscription by ID. */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n const res = await this.http.get<{ subscription: Subscription }>(\n `/api/v1/subscriptions/${subscriptionId}`,\n { params: { storeId: this.storeId } },\n );\n return res.subscription;\n }\n\n // ---------------------------------------------------------------------------\n // Subscription actions of the logged-in customer (customer portal session).\n // Each one is refused when the store turned that action off.\n // ---------------------------------------------------------------------------\n\n /** Pause billing. `resumeAt` (ISO date) resumes it on that day. */\n async pauseSubscription(subscriptionId: string, opts?: { resumeAt?: string }): Promise<void> {\n await this.http.post('/api/v1/subscriptions/pause', { subscriptionId, resumeAt: opts?.resumeAt });\n }\n\n /** Resume a paused subscription, or one scheduled for cancellation. */\n async resumeSubscription(subscriptionId: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/resume', { subscriptionId });\n }\n\n /** Defer the next charge by one billing period. */\n async skipSubscription(subscriptionId: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/skip', { subscriptionId });\n }\n\n /** Move the next billing date (ISO date, within a year). */\n async rescheduleSubscription(subscriptionId: string, nextBillingDate: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/reschedule', { subscriptionId, nextBillingDate });\n }\n\n /** Change how many units each delivery bills for. */\n async updateSubscriptionQuantity(subscriptionId: string, quantity: number): Promise<void> {\n await this.http.post('/api/v1/subscriptions/quantity', { subscriptionId, quantity });\n }\n\n /**\n * Move to another frequency of the same product: a recurring price id, or `{ optionId }` (a\n * purchase option of the product, priced for the subscription's variant).\n */\n async changeSubscriptionFrequency(\n subscriptionId: string,\n target: string | { optionId: string } | { priceId: string },\n ): Promise<void> {\n const body = typeof target === 'string' ? { priceId: target } : target;\n await this.http.post('/api/v1/subscriptions/frequency', { subscriptionId, ...body });\n }\n\n /**\n * Swap the product a subscription bills for: at one of its recurring prices, or at one of its\n * purchase options (`variantId` defaults to the product's default variant).\n */\n async swapSubscriptionProduct(\n subscriptionId: string,\n target: { productId: string; priceId: string } | { productId: string; optionId: string; variantId?: string },\n ): Promise<void> {\n await this.http.post('/api/v1/subscriptions/swap-product', { subscriptionId, ...target });\n }\n\n /** Attach a newly tokenized card to a subscription. */\n async updateSubscriptionPaymentMethod(subscriptionId: string, tagadaToken: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/payment-method', { subscriptionId, tagadaToken });\n }\n\n /**\n * Cancel a subscription, at the end of the paid period by default. Refused with HTTP 403 when the\n * store does not offer it for this product, or before the subscription's minimum paid orders\n * (error `name` `MINIMUM_ORDERS_NOT_REACHED`).\n */\n async cancelSubscription(subscriptionId: string, opts?: { cancelAtPeriodEnd?: boolean }): Promise<void> {\n await this.http.post('/api/v1/subscriptions/cancel', {\n subscriptionId,\n cancelAtPeriodEnd: opts?.cancelAtPeriodEnd ?? true,\n });\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;gdAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,yBAAAC,EAAA,iBAAAC,ICuDO,IAAMC,EAAN,KAA2B,CAChC,YACmBC,EACAC,EACAC,EACjB,CAHiB,UAAAF,EACA,aAAAC,EACA,cAAAC,CAChB,CAGH,MAAM,YAAYC,EAA8B,CAC9C,MAAM,KAAK,KAAK,KAAK,mCAAoC,CAAE,MAAAA,EAAO,QAAS,KAAK,OAAQ,CAAC,CAC3F,CAGA,MAAM,WAAWA,EAAeC,EAA+C,CAC7E,IAAMC,EAAM,MAAM,KAAK,KAAK,KAA6B,4BAA6B,CACpF,MAAAF,EACA,KAAAC,EACA,QAAS,KAAK,OAChB,CAAC,EACD,YAAK,SAASC,EAAI,KAAK,EAChBA,CACT,CAGA,MAAM,WAAyC,CAC7C,OAAO,KAAK,KAAK,IAAwB,wBAAyB,CAAE,OAAQ,CAAE,QAAS,KAAK,OAAQ,CAAE,CAAC,CACzG,CAGA,MAAM,OAA2B,CAC/B,OAAO,KAAK,KAAK,IAAc,mBAAmB,CACpD,CAGA,MAAM,WAAWC,EAA2D,CAC1E,OAAO,KAAK,KAAK,KAAyB,6BAA8BA,CAAK,CAC/E,CAGA,MAAM,kBAAkBA,EAA4D,CAClF,OAAO,KAAK,KAAK,KAAyB,oCAAqCA,CA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AY,CAAC,EACb,QAAWE,KAAQb,EAAK,MAAO,CAC7B,IAAMc,EAAUF,EAAM,UAAU,OAAOG,GAAK,CArPpD,IAAAd,EAqPuD,OAAAc,EAAK,YAAcF,EAAK,aACrEZ,EAAAW,EAAM,QAAQ,QAAQG,EAAK,SAAS,IAApC,YAAAd,EAAuC,KAAKe,GAAWA,EAAQ,KAAOH,EAAK,YAAU,EACvF,GAAIC,EAAQ,SAAW,GAAKH,EAAU,KAAKI,GAAQA,EAAK,aAAeD,EAAQ,CAAC,EAAE,UAAU,EAC1F,MAAO,CAAE,QAAS,GAAO,MAAO,mBAAoB,EAEtDH,EAAU,KAAK,CAAE,GAAGE,EAAM,WAAYC,EAAQ,CAAC,EAAE,WAAY,UAAWA,EAAQ,CAAC,EAAE,SAAU,CAAC,CAChG,CACF,CACA,IAAMG,EAAS,MAAM,KAAK,kBAAkB,CAC1C,QAASjB,EAAK,QACd,YAAaA,EAAK,QAClB,UAAAW,CACF,CAAC,EACD,OAAIM,EAAO,QAAQ,SAAW,YAAoB,CAAE,QAAS,EAAK,EAC3D,CACL,QAAS,GACT,MAAOA,EAAO,QAAQ,SAAW,UAC7B,kBACAA,EAAO,QAAQ,SAAW,mBACvBA,EAAO,QAAQ,eAAiBA,EAAO,QAAQ,gBAAkB,OAClE,oCACAP,EAAAO,EAAO,QAAQ,oBAAf,YAAAP,EAAkC,UAAW,kBACrD,CACF,CAGA,MAAM,yBAAyBV,EAGmB,CAChD,MAAO,CAAE,QAAS,EAAK,CACzB,CACF,
|
|
6
|
-
"names": ["commerce_exports", "__export", "CustomerModule", "CustomerPortalModule", "OffersModule", "CustomerPortalModule", "http", "storeId", "setToken", "email", "code", "res", "input", "token", "profile", "address", "addressId", "paymentMethodId", "subscriptionId", "lines", "variantId", "quantity", "billing", "date", "OffersModule", "http", "storeId", "payment", "offerId", "opts", "_a", "url", "queryParts", "id", "here", "returnUrl", "payResult", "orderId", "res", "_b", "lineItems", "quote", "item", "matches", "line", "variant", "result", "
|
|
3
|
+
"sources": ["../src/core/modules/commerce.ts", "../src/core/modules/portal/index.ts", "../src/core/modules/offers.ts", "../src/core/errors.ts", "../src/core/modules/customer.ts"],
|
|
4
|
+
"sourcesContent": ["// CDN chunk for capabilities that do not need to run during checkout bootstrap.\nexport { CustomerPortalModule } from './portal/index.js';\nexport { OffersModule } from './offers.js';\nexport { CustomerModule } from './customer.js';\n", "import type { HttpClient } from '../../http.js';\nimport type {\n Billing,\n PortalAcceptOfferInput,\n PortalAddToNextOrderInput,\n PortalAcceptOfferResult,\n PortalAddCardInput,\n PortalAddressInput,\n PortalBuyAgainLine,\n PortalBuyCreditPackInput,\n PortalCancelFlowInput,\n PortalCancelOfferInput,\n PortalCheckoutResult,\n PortalCredits,\n PortalCreditsOrderResult,\n PortalMe,\n PortalOffer,\n PortalProfileInput,\n PortalPublicConfig,\n PortalRedeemCreditsInput,\n PortalSubscriptionResult,\n PortalSwitchInput,\n PortalSwitchResult,\n PortalTargetResult,\n PortalVerifyCodeResult,\n} from './types.js';\n\n/**\n * Customer portal (Subscriptions V3): the store's portal config, the logged-in\n * customer, retention, plan switches, upsell links and credits.\n *\n * Log in with `requestCode` then `verifyCode`; every other call except\n * `getConfig` needs that session. Subscription actions (pause, skip, \u2026) live on\n * `client.customer`.\n *\n * Endpoints:\n * GET /api/v1/portal/config\n * GET /api/v1/portal/me\n * POST /api/v1/portal/cancel-flow\n * POST /api/v1/portal/cancel-flow/accept\n * POST /api/v1/portal/switch\n * GET /api/v1/portal/offers/:token\n * POST /api/v1/portal/offers/accept\n * POST /api/v1/portal/next-order\n * GET /api/v1/portal/credits\n * POST /api/v1/portal/credits/redeem\n * POST /api/v1/portal/credits/packs/buy\n * POST /api/v1/portal/profile, /profile/email-code\n * POST /api/v1/portal/addresses, /addresses/remove, /addresses/default\n * POST /api/v1/portal/payment-methods, /payment-methods/remove, /payment-methods/default\n * POST /api/v1/portal/retry-payment\n * POST /api/v1/portal/buy-again\n * POST /api/v1/portal/membership/join\n * POST /api/v1/subscriptions/send-now, /reactivate, /saved-card, /shipping-address, /skip-date, /unskip\n */\nexport class CustomerPortalModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n private readonly setToken: (token: string) => void,\n ) {}\n\n /** Email a login code to the customer. */\n async requestCode(email: string): Promise<void> {\n await this.http.post('/api/v1/cms/session/request-code', { email, storeId: this.storeId });\n }\n\n /** Exchange the emailed code for a session; later calls send it. */\n async verifyCode(email: string, code: string): Promise<PortalVerifyCodeResult> {\n const res = await this.http.post<PortalVerifyCodeResult>('/api/v1/cms/session/login', {\n email,\n code,\n storeId: this.storeId,\n });\n this.setToken(res.token);\n return res;\n }\n\n /** The store's published portal: design, retention, membership program, products. */\n async getConfig(): Promise<PortalPublicConfig> {\n return this.http.get<PortalPublicConfig>('/api/v1/portal/config', { params: { storeId: this.storeId } });\n }\n\n /** The logged-in customer: profile, orders, subscriptions, membership, credit ledger. */\n async getMe(): Promise<PortalMe> {\n return this.http.get<PortalMe>('/api/v1/portal/me');\n }\n\n /** Cancel a subscription or the membership after the reasons step. */\n async cancelFlow(input: PortalCancelFlowInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/cancel-flow', input);\n }\n\n /** Take the retention offer mapped to the chosen reason instead of cancelling. */\n async acceptCancelOffer(input: PortalCancelOfferInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/cancel-flow/accept', input);\n }\n\n /** Move a subscription or the membership to another option now, charged now. */\n async switchOption(input: PortalSwitchInput): Promise<PortalSwitchResult> {\n return this.http.post<PortalSwitchResult>('/api/v1/portal/switch', input);\n }\n\n /** The upsell a signed link (`/account/offer/<token>`) offers. No login: the token is the authorization. */\n async getOffer(token: string): Promise<PortalOffer> {\n return this.http.get<PortalOffer>(`/api/v1/portal/offers/${encodeURIComponent(token)}`);\n }\n\n /** Accept a signed upsell link and pay it with the card of the original order. A second accept charges nothing. */\n async acceptOffer(input: PortalAcceptOfferInput): Promise<PortalAcceptOfferResult> {\n return this.http.post<PortalAcceptOfferResult>('/api/v1/portal/offers/accept', input);\n }\n\n /** Ship a one-time item with the subscription's next renewal, charged with it; quantity 0 takes it off. */\n async addToNextOrder(input: PortalAddToNextOrderInput): Promise<PortalTargetResult> {\n return this.http.post<PortalTargetResult>('/api/v1/portal/next-order', input);\n }\n\n /** Credit balance and ledger of the logged-in customer. */\n async getCredits(): Promise<PortalCredits> {\n return this.http.get<PortalCredits>('/api/v1/portal/credits');\n }\n\n /** Pay a product with credits. */\n async redeemCredits(input: PortalRedeemCreditsInput): Promise<PortalCreditsOrderResult> {\n return this.http.post<PortalCreditsOrderResult>('/api/v1/portal/credits/redeem', input);\n }\n\n /** Buy a credit pack with the stored card. */\n async buyCreditPack(input: PortalBuyCreditPackInput): Promise<PortalCreditsOrderResult> {\n return this.http.post<PortalCreditsOrderResult>('/api/v1/portal/credits/packs/buy', input);\n }\n\n // \u2500\u2500 The customer's own account \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Email a code to a new address; `updateProfile` saves that email with it (`emailCode`). */\n async requestEmailChangeCode(email: string): Promise<void> {\n await this.http.post('/api/v1/portal/profile/email-code', { email });\n }\n\n /** The logged-in customer's name, email and phone. */\n async updateProfile(profile: PortalProfileInput): Promise<void> {\n await this.http.post('/api/v1/portal/profile', profile);\n }\n\n /** Add an address, or replace the one with that id; `isDefault` makes it the default. */\n async saveAddress(address: PortalAddressInput): Promise<{ addressId: string }> {\n return this.http.post('/api/v1/portal/addresses', address);\n }\n\n /** Remove an address; the default one stays until another is the default. */\n async removeAddress(addressId: string): Promise<void> {\n await this.http.post('/api/v1/portal/addresses/remove', { addressId });\n }\n\n async setDefaultAddress(addressId: string): Promise<void> {\n await this.http.post('/api/v1/portal/addresses/default', { addressId });\n }\n\n /** Save a card tokenized with `client.payment.tokenizeCard`. */\n async addCard(input: PortalAddCardInput): Promise<{ paymentMethodId: string }> {\n return this.http.post('/api/v1/portal/payment-methods', input);\n }\n\n /** Remove a saved card; refused while a live subscription is paid with it. */\n async removeCard(paymentMethodId: string): Promise<void> {\n await this.http.post('/api/v1/portal/payment-methods/remove', { paymentMethodId });\n }\n\n /** The default card also becomes the card of every live subscription. */\n async setDefaultPaymentMethod(paymentMethodId: string): Promise<void> {\n await this.http.post('/api/v1/portal/payment-methods/default', { paymentMethodId });\n }\n\n /** Charge a past-due subscription again now. */\n async retryPayment(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/portal/retry-payment', { subscriptionId });\n }\n\n /** Order products again at today's one-time price with the default card and address. */\n async buyAgain(lines: readonly PortalBuyAgainLine[]): Promise<PortalCheckoutResult> {\n return this.http.post('/api/v1/portal/buy-again', { lines: lines.map(({ variantId, quantity }) => ({ variantId, quantity })) });\n }\n\n /** Buy the Membership's monthly or yearly option with the default card. */\n async joinMembership(billing: Billing): Promise<PortalCheckoutResult> {\n return this.http.post('/api/v1/portal/membership/join', { billing });\n }\n\n /** Buy one product now at its one-time price with the default card and address. */\n async buyNow(variantId: string, quantity = 1): Promise<PortalCheckoutResult> {\n return this.buyAgain([{ variantId, quantity }]);\n }\n\n /** Charge and ship a subscription's next order today. */\n async sendNow(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/send-now', { subscriptionId });\n }\n\n /** Restart a cancelled subscription, or keep one set to end at its period end. */\n async reactivateSubscription(subscriptionId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/reactivate', { subscriptionId });\n }\n\n /** Bill a subscription on another saved card. */\n async setSubscriptionCard(subscriptionId: string, paymentMethodId: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/saved-card', { subscriptionId, paymentMethodId });\n }\n\n /** Ship a subscription to an address of the book; null follows the default address. */\n async setSubscriptionAddress(subscriptionId: string, addressId: string | null): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/shipping-address', { subscriptionId, addressId });\n }\n\n /** Skip one upcoming delivery date (`YYYY-MM-DD`); skipping the next one moves the next charge. */\n async skipDate(subscriptionId: string, date: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/skip-date', { subscriptionId, date });\n }\n\n /** Take back a skipped delivery date (`YYYY-MM-DD`). */\n async unskipDate(subscriptionId: string, date: string): Promise<PortalSubscriptionResult> {\n return this.http.post('/api/v1/subscriptions/unskip', { subscriptionId, date });\n }\n}\n", "import type { HttpClient } from '../http.js';\nimport type {\n Offer,\n OfferPreview,\n OfferPayResult,\n ProcessPaymentResult,\n} from '../types.js';\nimport type { PaymentModule } from './payment.js';\n\n/**\n * Offers \u2014 upsells, downsells, order bumps, and post-purchase offers.\n *\n * Endpoints align with the plugin-sdk patterns:\n * GET /api/v1/offers/:id \u2014 single offer\n * GET /api/v1/stores/:storeId/offers \u2014 list store offers\n * POST /api/v1/offers/:offerId/preview \u2014 preview pricing\n * POST /api/v1/offers/:offerId/pay-preview \u2014 pay a previewed offer (one-click)\n * POST /api/v1/checkout-sessions/:id/toggle-order-bump \u2014 toggle order bump\n * GET /api/v1/post-purchase/:orderId/offers \u2014 post-purchase offers for an order\n * Post-purchase acceptance uses pay-preview; declining is a local decision.\n */\nexport class OffersModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n private readonly payment?: PaymentModule,\n ) {}\n\n // ---------------------------------------------------------------------------\n // Offer loading\n // ---------------------------------------------------------------------------\n\n /** Get a single offer by ID. */\n async getOffer(offerId: string): Promise<Offer> {\n return this.http.get<Offer>(`/api/v1/offers/${offerId}`);\n }\n\n /** List offers for the current store. Optionally filter by type or a set of IDs. */\n async listOffers(opts?: {\n type?: 'upsell' | 'orderbump';\n ids?: string[];\n }): Promise<Offer[]> {\n let url = `/api/v1/stores/${this.storeId}/offers`;\n\n const queryParts: string[] = [];\n if (opts?.type) queryParts.push(`type=${encodeURIComponent(opts.type)}`);\n if (opts?.ids?.length) {\n for (const id of opts.ids) queryParts.push(`ids=${encodeURIComponent(id)}`);\n }\n if (queryParts.length) url += `?${queryParts.join('&')}`;\n\n const res = await this.http.get<{ offers: Offer[] }>(url);\n return res.offers ?? [];\n }\n\n // ---------------------------------------------------------------------------\n // Preview & pay (one-click upsell flow from plugin-sdk)\n // ---------------------------------------------------------------------------\n\n /**\n * Preview offer pricing. Returns line items with amounts and totals.\n *\n * A Studio offer block is previewed under `blockoffer:<blockId>` and read from\n * the step its funnel session stands on: pass that session's id\n * (see {@link enterFunnelStep}).\n */\n async previewOffer(opts: {\n offerId: string;\n currency?: string;\n lineItems?: Array<{ lineItemId?: string; productId?: string; variantId: string; quantity: number }>;\n funnelSessionId?: string;\n }): Promise<OfferPreview> {\n return this.http.post<OfferPreview>(`/api/v1/offers/${opts.offerId}/preview`, {\n offerId: opts.offerId,\n currency: opts.currency ?? '',\n lineItems: opts.lineItems,\n funnelSessionId: opts.funnelSessionId,\n });\n }\n\n /**\n * Put the buyer on a step of a funnel, for pages the funnel does not serve\n * itself: its offer blocks are then previewed and accepted as\n * `blockoffer:<blockId>` with the returned `funnelSessionId`. Uses the\n * checkout session's token, so the funnel session is the paying customer's.\n * Pass `checkoutToken` at checkout to link that checkout to the funnel\n * session, and `funnelSessionId` to move an open session to another step.\n */\n async enterFunnelStep(opts: {\n funnelId: string;\n stepId: string;\n accountId: string;\n funnelSessionId?: string;\n checkoutToken?: string;\n }): Promise<{ funnelSessionId: string }> {\n const here = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';\n const res = await this.http.post<{ context: { sessionId: string } }>('/api/v1/funnel/initialize', {\n // Placeholder ids: the server takes the customer and the CMS session from the token.\n cmsSession: { customerId: 'anon_placeholder', sessionId: 'anon_placeholder', storeId: this.storeId, accountId: opts.accountId },\n funnelId: opts.funnelId,\n funnelStepId: opts.stepId,\n existingSessionId: opts.funnelSessionId,\n currentUrl: opts.checkoutToken ? `${here}/?checkoutToken=${encodeURIComponent(opts.checkoutToken)}` : undefined,\n draft: false,\n });\n return { funnelSessionId: res.context.sessionId };\n }\n\n /**\n * Pay a previously previewed offer (one-click charge).\n * Used after a main order so the stored payment instrument is reused.\n *\n * **Low-level API.** Returns the raw `OfferPayResult` \u2014 `requireAction`,\n * polling, and 3DS redirects are NOT handled. For most cases, use\n * {@link processOfferPayment} which orchestrates the full lifecycle.\n */\n async payPreviewedOffer(opts: {\n offerId: string;\n mainOrderId: string;\n currency?: string;\n lineItems?: Array<{ lineItemId?: string; productId?: string; variantId: string; quantity: number }>;\n returnUrl?: string;\n paymentInstrumentId?: string;\n funnelSessionId?: string;\n }): Promise<OfferPayResult> {\n return this.http.post<OfferPayResult>(`/api/v1/offers/${opts.offerId}/pay-preview`, {\n offerId: opts.offerId,\n currency: opts.currency ?? '',\n lineItems: opts.lineItems,\n returnUrl: opts.returnUrl ?? (typeof window !== 'undefined' ? window.location.href : ''),\n mainOrderId: opts.mainOrderId,\n paymentInstrumentId: opts.paymentInstrumentId,\n funnelSessionId: opts.funnelSessionId,\n });\n }\n\n /**\n * One-click upsell with full lifecycle handling.\n *\n * Like `payment.processPayment()` but for previewed offers: charges the\n * stored instrument from `mainOrderId`, runs any 3DS challenge or bank\n * redirect, polls until terminal, and returns a typed\n * `ProcessPaymentResult` (`succeeded` / `requires_redirect` /\n * `failed` / `pending`).\n *\n * Use this instead of the lower-level `payPreviewedOffer()` whenever you\n * don't need to inspect the raw `OfferPayResult` shape \u2014 which is most\n * of the time.\n *\n * @example\n * ```ts\n * const result = await tagada.offers.processOfferPayment({\n * offerId: 'offer_xxx',\n * mainOrderId: order.id,\n * returnUrl: window.location.href,\n * });\n *\n * switch (result.status) {\n * case 'succeeded':\n * window.location.href = '/upsell-2';\n * break;\n * case 'requires_redirect':\n * window.location.href = result.redirectUrl;\n * break;\n * case 'failed':\n * showError(result.error);\n * break;\n * }\n * ```\n */\n async processOfferPayment(opts: {\n offerId: string;\n mainOrderId: string;\n currency?: string;\n lineItems?: Array<{\n lineItemId?: string;\n productId?: string;\n variantId: string;\n quantity: number;\n }>;\n returnUrl?: string;\n paymentInstrumentId?: string;\n funnelSessionId?: string;\n }): Promise<ProcessPaymentResult> {\n if (!this.payment) {\n throw new Error(\n 'OffersModule: no PaymentModule injected. ' +\n 'Use createHeadlessClient() instead of constructing OffersModule directly.',\n );\n }\n const returnUrl =\n opts.returnUrl ?? (typeof window !== 'undefined' ? window.location.href : undefined);\n const payResult = await this.payPreviewedOffer({ ...opts, returnUrl });\n return this.payment.finalize(\n { payment: payResult.payment, order: payResult.order },\n { returnUrl },\n );\n }\n\n // ---------------------------------------------------------------------------\n // Order bumps (checkout-session scoped)\n // ---------------------------------------------------------------------------\n\n /** Toggle an order bump on/off within a checkout session. */\n async toggleOrderBump(opts: {\n checkoutSessionId: string;\n orderBumpOfferId: string;\n selected: boolean;\n }): Promise<unknown> {\n return this.http.post(\n `/api/v1/checkout-sessions/${opts.checkoutSessionId}/toggle-order-bump`,\n {\n orderBumpOfferId: opts.orderBumpOfferId,\n selected: opts.selected,\n },\n );\n }\n\n // ---------------------------------------------------------------------------\n // Post-purchase offers (order-scoped)\n // ---------------------------------------------------------------------------\n\n /** List post-purchase offers for an order. */\n async listPostPurchaseOffers(orderId: string): Promise<Offer[]> {\n const res = await this.http.get<Offer[]>(`/api/v1/post-purchase/${orderId}/offers`);\n return Array.isArray(res) ? res : [];\n }\n\n /** Accept a post-purchase offer. Only a confirmed charge returns success. */\n async acceptPostPurchaseOffer(opts: {\n orderId: string;\n offerId: string;\n items?: Array<{ variantId: string; quantity: number }>;\n }): Promise<{ success: boolean; error?: string }> {\n // The server matches overrides by line-item/product ID, not variant alone.\n // Resolve against this offer's quote so an unrelated variant cannot silently\n // fall back to charging the offer's default selection.\n let lineItems: Array<{ lineItemId: string; productId: string; variantId: string; quantity: number }> | undefined;\n if (opts.items?.length) {\n const quote = await this.http.post<{\n lineItems: Array<{ lineItemId: string; productId: string; variantId: string }>;\n preview: { options: Record<string, Array<{ id: string }>> };\n }>(`/api/v1/offers/${opts.offerId}/preview`, { offerId: opts.offerId, currency: '' });\n lineItems = [];\n for (const item of opts.items) {\n const matches = quote.lineItems.filter(line => line.variantId === item.variantId ||\n quote.preview.options[line.productId]?.some(variant => variant.id === item.variantId));\n if (matches.length !== 1 || lineItems.some(line => line.lineItemId === matches[0].lineItemId)) {\n return { success: false, error: 'Invalid selection' };\n }\n lineItems.push({ ...item, lineItemId: matches[0].lineItemId, productId: matches[0].productId });\n }\n }\n const result = await this.payPreviewedOffer({\n offerId: opts.offerId,\n mainOrderId: opts.orderId,\n lineItems,\n });\n if (result.payment.status === 'succeeded') return { success: true };\n return {\n success: false,\n error: result.payment.status === 'pending'\n ? 'Payment pending'\n : result.payment.status === 'requires_action' ||\n (result.payment.requireAction && result.payment.requireAction !== 'none')\n ? 'Payment requires authentication'\n : result.payment.requireActionData?.message || 'Payment declined',\n };\n }\n\n /** Decline locally; the backend has no persisted refusal and no charge is made. */\n async declinePostPurchaseOffer(opts: {\n orderId: string;\n offerId: string;\n }): Promise<{ success: boolean; error?: string }> {\n return { success: true };\n }\n}\n", "/** Base error for all TagadaPay headless SDK errors. */\nexport class TagadaError extends Error {\n public readonly code: string;\n public readonly statusCode?: number;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n statusCode?: number,\n details?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'TagadaError';\n this.code = code;\n this.statusCode = statusCode;\n this.details = details;\n }\n}\n\n/** Thrown when the API returns 401/403. */\nexport class TagadaAuthError extends TagadaError {\n constructor(message = 'Authentication failed. Check your API key or checkout token.') {\n super(message, 'auth_error', 401);\n this.name = 'TagadaAuthError';\n }\n}\n\n/** Thrown when the API returns 422 with validation errors. */\nexport class TagadaValidationError extends TagadaError {\n public readonly errors: Array<{ field: string; message: string }>;\n /**\n * Application error code from the API, when it sends one \u2014 e.g.\n * `MISSING_SHIPPING_ADDRESS` when a cart containing a shippable product is\n * paid with no address (#TAG-1989). Branch on this rather than on the\n * message, which is customer-facing and may be reworded.\n */\n public readonly appCode?: string;\n\n constructor(\n message: string,\n errors: Array<{ field: string; message: string }> = [],\n appCode?: string,\n details?: Record<string, unknown>,\n ) {\n super(message, 'validation_error', 422, { errors, ...details });\n this.name = 'TagadaValidationError';\n this.errors = errors;\n this.appCode = appCode;\n }\n}\n\n/** Thrown when a resource is not found (404). */\nexport class TagadaNotFoundError extends TagadaError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'not_found', 404);\n this.name = 'TagadaNotFoundError';\n }\n}\n\n/** Thrown when the API returns 429. */\nexport class TagadaRateLimitError extends TagadaError {\n public readonly retryAfterMs: number;\n\n constructor(retryAfterMs = 1000) {\n super(`Rate limited. Retry after ${retryAfterMs}ms.`, 'rate_limit', 429);\n this.name = 'TagadaRateLimitError';\n this.retryAfterMs = retryAfterMs;\n }\n}\n\n/** Thrown when a payment fails or requires action. */\nexport class TagadaPaymentError extends TagadaError {\n public readonly paymentId?: string;\n public readonly requireAction?: string;\n\n constructor(\n message: string,\n opts?: { paymentId?: string; requireAction?: string; details?: Record<string, unknown> },\n ) {\n super(message, 'payment_error', undefined, opts?.details);\n this.name = 'TagadaPaymentError';\n this.paymentId = opts?.paymentId;\n this.requireAction = opts?.requireAction;\n }\n}\n\n/** Thrown on network / fetch failures. */\nexport class TagadaNetworkError extends TagadaError {\n constructor(message = 'Network request failed. Check your connection.') {\n super(message, 'network_error');\n this.name = 'TagadaNetworkError';\n }\n}\n", "import { TagadaError, TagadaNotFoundError } from '../errors.js';\nimport type { HttpClient } from '../http.js';\nimport type { Customer, Order, Subscription } from '../types.js';\n\n/** One row of `GET /api/v1/subscriptions`. */\ninterface CustomerSubscriptionRow {\n id: string;\n status: Subscription['status'];\n customerId: string;\n priceId: string;\n currency: string;\n cancelAtPeriodEnd: boolean;\n currentPeriodStart: string;\n currentPeriodEnd: string;\n priceInterval: string | null;\n priceIntervalCount: number | null;\n priceCurrencyOptions: Record<string, { amount: number }> | null;\n}\n\nfunction toSubscription(row: CustomerSubscriptionRow, storeId: string): Subscription {\n return {\n ...row,\n storeId,\n amount: row.priceCurrencyOptions?.[row.currency]?.amount ?? 0,\n interval: row.priceInterval ?? '',\n intervalCount: row.priceIntervalCount ?? 1,\n };\n}\n\n/**\n * Customer data -- profile, orders, subscriptions.\n *\n * Requires either an API key or a session token for authentication.\n */\nexport class CustomerModule {\n constructor(\n private readonly http: HttpClient,\n private readonly storeId: string,\n ) {}\n\n /** Get customer profile by ID. */\n async getProfile(customerId: string): Promise<Customer> {\n const res = await this.http.get<{ customer: Customer }>(\n `/api/v1/customers/${customerId}`,\n { params: { storeId: this.storeId } },\n );\n return res.customer;\n }\n\n /**\n * Not available: no route finds a customer by email for a storefront session. The only email\n * search (`POST /api/v1/customers/search`) needs a secret API key of the whole account, which a\n * storefront must never ship. Always rejects with a `TagadaError` of code `not_supported`, without\n * sending a request. For the logged-in customer use `portal.getMe()` (Subscriptions V3 stores) or\n * `getProfile(customerId)`.\n *\n * @deprecated There is no API route behind it.\n */\n async getByEmail(email: string): Promise<Customer | null> {\n throw new TagadaError(\n 'customer.getByEmail is not available: no API route finds a customer by email for a storefront session.',\n 'not_supported',\n );\n }\n\n /**\n * Update the customer's email (`POST /api/v1/customers/:id`, the checkout's email step): the\n * route stores the email only. A portal customer's name and phone go through `portal.updateProfile`.\n */\n async updateProfile(\n customerId: string,\n data: Partial<Pick<Customer, 'email' | 'firstName' | 'lastName' | 'phone' | 'metadata'>>,\n ): Promise<Customer> {\n await this.http.post(`/api/v1/customers/${customerId}`, { customerId, data: { email: data.email } });\n return this.getProfile(customerId);\n }\n\n /**\n * The customer's orders on this store, newest first (`GET /api/v1/orders/customer/:customerId`).\n * Needs a session of that customer: the checkout session, or a portal login\n * (`portal.verifyCode`). Another customer's id rejects with `TagadaNotFoundError`. The route sends\n * every order at once: `limit` and `offset` slice them here, `total` counts them all.\n */\n async getOrders(\n customerId: string,\n opts?: { limit?: number; offset?: number },\n ): Promise<{ orders: Order[]; total: number }> {\n const { orders } = await this.http.get<{ orders: Order[] }>(`/api/v1/orders/customer/${customerId}`, {\n params: { storeId: this.storeId },\n });\n const start = opts?.offset ?? 0;\n const end = opts?.limit === undefined ? undefined : start + opts.limit;\n return { orders: orders.slice(start, end), total: orders.length };\n }\n\n /**\n * Get a single order by ID.\n *\n * **Thank-you pages:** accepted one-click upsells create *child orders*\n * (`metadata.mainOrderId` = this order's id) that land asynchronously \u2014\n * the first fetch right after an accept usually misses them. Pass\n * `waitForRelatedOrders: true` to poll until `order.relatedOrders` is\n * non-empty or the timeout elapses. On timeout the latest snapshot is\n * returned (never throws), so an order with no accepted upsell simply\n * comes back with an empty `relatedOrders` after `timeoutMs`.\n *\n * @example\n * ```ts\n * // Thank-you page: show the main order AND the upsells\n * const order = await tagada.customer.getOrder(orderId, {\n * waitForRelatedOrders: true,\n * });\n * renderOrders([order, ...(order.relatedOrders ?? [])]);\n * ```\n */\n async getOrder(\n orderId: string,\n opts?: {\n /** Poll until `relatedOrders` is non-empty (or `timeoutMs` elapses). */\n waitForRelatedOrders?: boolean;\n /** Max total wait in ms. Default: 8000. */\n timeoutMs?: number;\n /** Delay between polls in ms. Default: 2000. */\n intervalMs?: number;\n },\n ): Promise<Order> {\n const fetchOrder = async (): Promise<Order> => {\n const res = await this.http.get<{ order: Order }>(`/api/v1/orders/${orderId}`, {\n params: { storeId: this.storeId },\n });\n return res.order;\n };\n\n let order = await fetchOrder();\n if (!opts?.waitForRelatedOrders || order.relatedOrders?.length) return order;\n\n const timeoutMs = opts.timeoutMs ?? 8000;\n const intervalMs = opts.intervalMs ?? 2000;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));\n order = await fetchOrder();\n if (order.relatedOrders?.length) return order;\n }\n return order;\n }\n\n /**\n * The customer's subscriptions on this store, newest first (`GET /api/v1/subscriptions`). The\n * route answers for the customer of the session: the checkout session, or a portal login\n * (`portal.verifyCode`), which a Subscriptions V3 store requires. Another customer's id gets `[]`.\n * Only the 20 most recent come back: the route's page size cannot travel in a query string.\n */\n async getSubscriptions(customerId: string): Promise<Subscription[]> {\n const { items } = await this.http.get<{ items: CustomerSubscriptionRow[] }>('/api/v1/subscriptions');\n return items.filter((row) => row.customerId === customerId).map((row) => toSubscription(row, this.storeId));\n }\n\n /**\n * One subscription of the session's customer. No route reads a subscription by id: this picks it\n * from `getSubscriptions`' route, so it needs the same session and finds only the 20 most recent.\n * Rejects with `TagadaNotFoundError` when it is not among them.\n */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n const { items } = await this.http.get<{ items: CustomerSubscriptionRow[] }>('/api/v1/subscriptions');\n const row = items.find((item) => item.id === subscriptionId);\n if (!row) throw new TagadaNotFoundError('Subscription', subscriptionId);\n return toSubscription(row, this.storeId);\n }\n\n // ---------------------------------------------------------------------------\n // Subscription actions of the logged-in customer (customer portal session).\n // Each one is refused when the store turned that action off.\n // ---------------------------------------------------------------------------\n\n /** Pause billing. `resumeAt` (ISO date) resumes it on that day. */\n async pauseSubscription(subscriptionId: string, opts?: { resumeAt?: string }): Promise<void> {\n await this.http.post('/api/v1/subscriptions/pause', { subscriptionId, resumeAt: opts?.resumeAt });\n }\n\n /** Resume a paused subscription, or one scheduled for cancellation. */\n async resumeSubscription(subscriptionId: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/resume', { subscriptionId });\n }\n\n /** Defer the next charge by one billing period. */\n async skipSubscription(subscriptionId: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/skip', { subscriptionId });\n }\n\n /** Move the next billing date (ISO date, within a year). */\n async rescheduleSubscription(subscriptionId: string, nextBillingDate: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/reschedule', { subscriptionId, nextBillingDate });\n }\n\n /** Change how many units each delivery bills for. */\n async updateSubscriptionQuantity(subscriptionId: string, quantity: number): Promise<void> {\n await this.http.post('/api/v1/subscriptions/quantity', { subscriptionId, quantity });\n }\n\n /**\n * Move to another frequency of the same product: a recurring price id, or `{ optionId }` (a\n * purchase option of the product, priced for the subscription's variant).\n */\n async changeSubscriptionFrequency(\n subscriptionId: string,\n target: string | { optionId: string } | { priceId: string },\n ): Promise<void> {\n const body = typeof target === 'string' ? { priceId: target } : target;\n await this.http.post('/api/v1/subscriptions/frequency', { subscriptionId, ...body });\n }\n\n /**\n * Swap the product a subscription bills for: at one of its recurring prices, or at one of its\n * purchase options (`variantId` defaults to the product's default variant).\n */\n async swapSubscriptionProduct(\n subscriptionId: string,\n target: { productId: string; priceId: string } | { productId: string; optionId: string; variantId?: string },\n ): Promise<void> {\n await this.http.post('/api/v1/subscriptions/swap-product', { subscriptionId, ...target });\n }\n\n /** Attach a newly tokenized card to a subscription. */\n async updateSubscriptionPaymentMethod(subscriptionId: string, tagadaToken: string): Promise<void> {\n await this.http.post('/api/v1/subscriptions/payment-method', { subscriptionId, tagadaToken });\n }\n\n /**\n * Cancel a subscription, at the end of the paid period by default. Refused with HTTP 403 when the\n * store does not offer it for this product, or before the subscription's minimum paid orders\n * (error `name` `MINIMUM_ORDERS_NOT_REACHED`).\n */\n async cancelSubscription(subscriptionId: string, opts?: { cancelAtPeriodEnd?: boolean }): Promise<void> {\n await this.http.post('/api/v1/subscriptions/cancel', {\n subscriptionId,\n cancelAtPeriodEnd: opts?.cancelAtPeriodEnd ?? true,\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;gdAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,yBAAAC,EAAA,iBAAAC,ICuDO,IAAMC,EAAN,KAA2B,CAChC,YACmBC,EACAC,EACAC,EACjB,CAHiB,UAAAF,EACA,aAAAC,EACA,cAAAC,CAChB,CAGH,MAAM,YAAYC,E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ACf,MAAM,KAAK,KAAK,KAAK,qCAAsC,CAAE,eAAAL,EAAgB,GAAGK,CAAO,CAAC,CAC1F,CAGA,MAAM,gCAAgCL,EAAwBO,EAAoC,CAChG,MAAM,KAAK,KAAK,KAAK,uCAAwC,CAAE,eAAAP,EAAgB,YAAAO,CAAY,CAAC,CAC9F,CAOA,MAAM,mBAAmBP,EAAwBZ,EAAuD,CACtG,MAAM,KAAK,KAAK,KAAK,+BAAgC,CACnD,eAAAY,EACA,mBAAmBZ,GAAA,YAAAA,EAAM,oBAAqB,EAChD,CAAC,CACH,CACF",
|
|
6
|
+
"names": ["commerce_exports", "__export", "CustomerModule", "CustomerPortalModule", "OffersModule", "CustomerPortalModule", "http", "storeId", "setToken", "email", "code", "res", "input", "token", "profile", "address", "addressId", "paymentMethodId", "subscriptionId", "lines", "variantId", "quantity", "billing", "date", "OffersModule", "http", "storeId", "payment", "offerId", "opts", "_a", "url", "queryParts", "id", "here", "returnUrl", "payResult", "orderId", "res", "_b", "lineItems", "quote", "item", "matches", "line", "variant", "result", "TagadaError", "message", "code", "statusCode", "details", "TagadaNotFoundError", "TagadaError", "resource", "id", "toSubscription", "row", "storeId", "_a", "_b", "CustomerModule", "http", "customerId", "email", "TagadaError", "data", "opts", "orders", "start", "end", "orderId", "fetchOrder", "order", "timeoutMs", "intervalMs", "deadline", "resolve", "items", "subscriptionId", "item", "TagadaNotFoundError", "nextBillingDate", "quantity", "target", "body", "tagadaToken"]
|
|
7
7
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.18.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessReactBundle=(()=>{var wt=Object.create;var le=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var M=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var bt=(s,e)=>{for(var t in e)le(s,t,{get:e[t],enumerable:!0})},je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!It.call(s,n)&&n!==t&&le(s,n,{get:()=>e[n],enumerable:!(r=Ct(e,n))||r.enumerable});return s};var Oe=(s,e,t)=>(t=s!=null?wt(kt(s)):{},je(e||!s||!s.__esModule?le(t,"default",{value:s,enumerable:!0}):t,s)),Rt=s=>je(le({},"__esModule",{value:!0}),s);var Qt={};bt(Qt,{CurrencyUtils:()=>W,GoogleAutocompleteCore:()=>K,ISODataCore:()=>B,TagadaHeadlessProvider:()=>et,formatMoney:()=>He,loadGoogleMapsScript:()=>ae,parseTokensFromUrl:()=>Ke,useCatalog:()=>ct,useCheckout:()=>rt,useCountryOptions:()=>ht,useCustomer:()=>ot,useGoogleAutocomplete:()=>gt,useHeadlessClient:()=>O,useISOData:()=>Te,useOffers:()=>it,useOrder:()=>at,usePayment:()=>st,useRegionOptions:()=>yt,useRx:()=>ut,useStep:()=>lt});var Q=M("react");var q=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},pe=class extends q{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},me=class extends q{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},X=class extends q{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},ge=class extends q{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var te=class extends q{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $e={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},re=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??$e[e]??$e.production}async request(e,t={}){var h;let{method:r="GET",body:n,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[m,C]of Object.entries(o))C!==void 0&&y.set(m,String(C));let l=y.toString();l&&(u+=`?${l}`)}let g={"Content-Type":"application/json",...i},d=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));d&&(g["x-cms-token"]=d);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let l=await y.text();return l?JSON.parse(l):{}}throw await this.handleErrorResponse(y,e),new q("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof q?y:y instanceof DOMException&&y.name==="AbortError"?new te(`Request to ${e} timed out after ${this.timeout}ms.`):new te(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=At(r.data),i=r.message||r.error||(typeof n.message=="string"?n.message:void 0)||(typeof r.data=="string"&&Object.keys(n).length===0?r.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new pe(i);case 404:throw new X(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new me(i,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new ge(a)}default:throw new q(i,"api_error",e.status,r)}}};function At(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var ne=class s{constructor(e,t,r,n){this.http=e;this.storeId=t;this.onTokenChange=r;this.onSession=n}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,g;let t=e.items.map(d=>({variantId:d.variantId,priceId:d.priceId,...d.sellingPlanId!==void 0?{sellingPlanId:d.sellingPlanId}:{},...d.trialDays!==void 0?{trialDays:d.trialDays}:{},...d.trialPrice!==void 0?{trialPrice:d.trialPrice}:{},quantity:d.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl),e.funnelSessionId&&(r.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(r.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(r.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(r.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(r.customerTags=e.customerTags);let n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);let i=await this.http.post("/api/v1/checkout/session/init",r),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:r,...n}=e,i=await this.createSession(n),o=r??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,...n.sellingPlanId!==void 0?{sellingPlanId:n.sellingPlanId}:{},quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return xt({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(r=>this.normalizeShippingRate(r))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),c=i.map(d=>{let f=d.price,p=d.variant??(f==null?void 0:f.variant)??{},h=d.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},l=(a?y[a]:void 0)??y[Object.keys(y)[0]],m=(l==null?void 0:l.amount)??0;return{id:d.id,variantId:d.variantId,priceId:d.priceId,productName:h.name??"",variantName:p.name??"",quantity:d.quantity??1,unitAmount:m,totalAmount:m*(d.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??h.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAdjustedAmount??n.totalAmount??u.reduce((d,f)=>d+(f.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,r={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(r).some(n=>n!==void 0&&n!=="")?r:void 0}},Ke=ne.parseTokensFromUrl;function xt(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function fe(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(e)?e:void 0}function he(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(r)?r:void 0}function Be(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var _e="headless",Le="1.17.0";var ze="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-pixels.min.js";function We(s,e){return e()?Promise.resolve():new Promise((t,r)=>{let n=document.createElement("script");n.src=s,n.async=!0,n.onload=()=>t(),n.onerror=()=>r(new Error("runtime script failed to load")),document.head.appendChild(n)})}async function Tt(){if(typeof window>"u")return null;if(ze){let s=window;return s.TagadaPixels?s.TagadaPixels:(await We(ze,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ve="__tgd_track",Et="__tgd_aid",Ot="__tgd_sid",Je=50,_t=2e3,Qe=1e3,Lt=64;function Pe(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ye(s){if(!s)return;let e={};for(let[t,r]of Object.entries(s))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var Ut={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function Ue(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Nt(s){let e={};for(let t of s){let{provider:r,id:n,idKey:i,...o}=t;(e[r]??(e[r]=[])).push({...o,enabled:!0,[i]:n,events:t.events??{}})}return e}var ye=class{constructor(e,t,r){this.baseUrl=e;this.storeId=t;this.funnelKey=r;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Ve)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Ve,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let r=(t==null?void 0:t.path)??window.location.pathname,n=`${e}|${r}`,i=Date.now(),o=this.lastStep.get(n);o!==void 0&&i-o<Qe||(this.remember(n,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:r}),this.pixels().then(a=>a==null?void 0:a.pageView(r,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let r=this.currentStepId;if(r===null)return;let n=Ut[e],i=`${n??e}_${Ue()}`;this.push({kind:"event",stepId:r,name:e,at:Date.now(),eventId:i,props:Ye(t)}),this.pixels().then(o=>n?o==null?void 0:o.track(n,t,{stepId:r,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:r})),this.core().then(o=>o==null?void 0:o.track(e,{...Ye(t)??{},step_id:r,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[r,n]of this.lastStep)t-n>=Qe&&this.lastStep.delete(r);for(;this.lastStep.size>=Lt;){let r=this.lastStep.keys().next();if(r.done===!0)break;this.lastStep.delete(r.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,r){this.off()||this.pixels().then(n=>{var i;return n==null?void 0:n.track(e,{value:r.amount,currency:r.currency,contents:r.items,num_items:(i=r.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,r){this.off()||(this.signals.push({signal:e,value:t,detail:r}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:r}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let r=await t.json();return this.manifestHash=r.manifestHash||null,r}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let r=await this.config();if(!r||!r.collect&&!r.experiments)return null;let n=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await We(n+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:r.collect?new URL(r.collect.url).origin:n,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let r=await Tt();if(r===null)return null;let n=r.createPixelEngine({pixels:Nt(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await n.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],n}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=Je){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),_t))}}identifier(e,t){try{let r=e==="local"?localStorage:sessionStorage,n=r.getItem(t);if(n)return n;let i=Ue();return r.setItem(t,i),i}catch{return Ue()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Je),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},anonymousId:this.identifier("local",Et),sessionId:this.identifier("session",Ot),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let r=JSON.stringify(t),n=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(n,new Blob([r],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(n,{method:"POST",body:r,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Dt=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Mt(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,r=s.settings??{},n=r.processors,i=r.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=n==null?void 0:n[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var Se=class{constructor(e,t,r,n,i,o){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let r=this.readInjectedStepConfig();if(r)return this.lastPaymentSetup=r,r;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof X))throw i}let n=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=n,n}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r=Array.isArray(t)?t.map(Mt):(t==null?void 0:t.methods)??[],n={};for(let i of r){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;n[o]=i}return n}async getExpressMethods(e,t){var i,o,a,c,u,g,d,f,p,h;let r=await this.getPaymentSetup(e,t),n={};for(let[y,l]of Object.entries(r)){if(!l.enabled)continue;if(y.startsWith("express_checkout:")&&l.methods){let R={available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if((i=l.methods.apple_pay)!=null&&i.enabled){let w=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...R,type:"apple_pay",available:!!w}}(c=l.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay={...R,type:"google_pay"}),(g=l.methods.link)!=null&&g.enabled&&(n.link={...R,type:"link"}),(d=l.methods.klarna_express)!=null&&d.enabled&&(n.klarna={...R,type:"klarna_express"});continue}if(!l.express)continue;let m=l.method,C={type:m,available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if(m==="apple_pay"||l.type==="apple_pay"){let R=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));n.applePay={...C,available:!!R}}else m==="google_pay"||l.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((h=this.onSignal)==null||h.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay=C):m==="paypal"?n.paypal=C:m==="klarna"||m==="klarna_express"?n.klarna=C:m==="link"&&(n.link=C)}return n}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let r=await this.getPaymentSetup(e,t);return Object.entries(r).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress:r,billingAddress:n}=t;if(!r&&!n)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:r,billingAddress:n})}async processApplePay(e){var a,c,u,g,d,f,p,h,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:fe(e.shippingContact),billingAddress:fe(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((d=e.shippingContact)==null?void 0:d.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((h=e.billingContact)==null?void 0:h.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(r.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let r=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},n=r(this.readInjectedStepConfig())??r(this.lastPaymentSetup);if(n)return n;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return r(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:he(e.shippingAddress),billingAddress:he(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,r),{status:"succeeded",payment:r,order:e.order}):r.status==="failed"||r.status==="declined"?{status:"failed",error:((o=r.requireActionData)==null?void 0:o.message)||((a=r.requireActionData)==null?void 0:a.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>c.delete(g));let u=c.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var i,o;let r=(i=t.metadata)==null?void 0:i.redirect,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,method:((o=r==null?void 0:r.method)==null?void 0:o.toUpperCase())||"GET",postData:r==null?void 0:r.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let r=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let n;try{n=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new n.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){var a;let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<n;){let c;try{c=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,r));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(c.status==="failed"||c.status==="declined")return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,r))}return{status:"pending",paymentId:e}}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}emitPaid(e,t){var r;if(!(!e||!this.onPaid))try{let n=(r=this.checkout)==null?void 0:r.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:Pe(n==null?void 0:n.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var V=typeof document>"u"?null:document.currentScript,Ft=V!=null&&V.src?new URL("tagada-headless-commerce.min.js",V.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-headless-commerce.min.js",we;function ee(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(we||(we=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,V!=null&&V.nonce&&(t.nonce=V.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw we=void 0,s})),we)}var se=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])se.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ie=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])ie.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var oe=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])oe.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var Ce=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var ve=class{constructor(e,t,r,n,i){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new q("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new q("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=r.customer)==null?void 0:o.locale)??qt(),userAgent:Gt(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=r.customer)==null?void 0:c.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var d,f,p,h;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:o}=e,a=n.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),u={email:((d=i.customer)==null?void 0:d.email)??((f=n.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??n.currency,locale:(h=i.customer)==null?void 0:h.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function qt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Gt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var ke=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var Ie=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,r,n,i;return((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.arm)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:r}of this.subscribers.splice(0))try{e?e.onVariant(t,r):r(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,r,n,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.payload)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,r;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:r.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var Ne=class{constructor(e){let t=e.environment??"production",r=re.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new re({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new ye(r,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new Ie(()=>this.track.core(),this.config.bootstrap);let n=i=>{this._sessionToken=i};this.checkout=new ne(this.http,this.config.storeId,n,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:Pe(i.items)})),this.payment=new Se(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new se(this.http,this.config.storeId,this.payment),this.customer=new ie(this.http,this.config.storeId),this.portal=new oe(this.http,this.config.storeId,n),this.catalog=new Ce(this.http,this.config.storeId),this.funnel=new ve(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new ke(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Ze(s){return new Ne(s)}var tt=M("react/jsx-runtime"),Xe=(0,Q.createContext)(null);function et({storeId:s,environment:e,apiKey:t,baseUrl:r,config:n,children:i}){let o=(0,Q.useMemo)(()=>Ze(n??{storeId:s,environment:e,apiKey:t,baseUrl:r}),[s,e,t,r,n]),a=(0,Q.useMemo)(()=>({client:o}),[o]);return(0,tt.jsx)(Xe.Provider,{value:a,children:i})}function O(){let s=(0,Q.useContext)(Xe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var _=M("react");function rt(s,e){let t=O(),[r,n]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[a,c]=(0,_.useState)(null),u=(0,_.useCallback)(async()=>{if(s){o(!0),c(null);try{let w=await t.checkout.loadSession(s,e);n(w)}catch(w){c(w instanceof Error?w:new Error(String(w)))}finally{o(!1)}}},[t,s,e]);(0,_.useEffect)(()=>{u()},[u]);let g=(0,_.useCallback)(async w=>{o(!0),c(null);try{let P=await t.checkout.createSession(w),v=new URL(window.location.href);v.searchParams.set("checkoutToken",P.checkoutToken),v.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",v.toString());let E=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);n(E)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),d=(0,_.useCallback)(async w=>{c(null);try{return await t.checkout.createSessionUrl(w)}catch(P){let v=P instanceof Error?P:new Error(String(P));throw c(v),v}},[t]),f=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateCart(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),p=(0,_.useCallback)(async w=>{r&&await t.checkout.updateCustomer(r.id,w)},[t,r]),h=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),y=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateCustomerAndAddress(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),l=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),m=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),C=(0,_.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),R=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]);return{session:r,isLoading:i,error:a,refresh:u,createSession:g,createSessionUrl:d,updateCart:f,updateCustomer:p,updateAddress:h,updateCustomerAndAddress:y,applyPromo:l,removePromo:m,getShippingRates:C,selectShippingRate:R}}var x=M("react");var nt=new Set;function be(s){return nt.has(s)?!1:(nt.add(s),!0)}function st(s){let e=O(),[t,r]=(0,x.useState)(null),[n,i]=(0,x.useState)(null),[o,a]=(0,x.useState)(null),[c,u]=(0,x.useState)(!1),[g,d]=(0,x.useState)(null),[f,p]=(0,x.useState)(null),h=(0,x.useRef)(!1),y=(0,x.useRef)(!1),l=(0,x.useRef)(s);l.current=s,(0,x.useEffect)(()=>{if(typeof window>"u"||y.current)return;let b=new URLSearchParams(window.location.search),S=b.get("paymentAction"),k=b.get("paymentActionStatus"),U=b.get("paymentId");if(S!=="requireAction"||k!=="completed"||!U||(y.current=!0,!be(U)))return;u(!0),p(null),(async()=>{var I,A,j,Z;try{let D=await e.payment.resumeAfterRedirect(U),Ee=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(St=>Ee.delete(St));let Pt=Ee.toString()?`${window.location.pathname}?${Ee.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Pt),D.status==="succeeded"?(A=(I=l.current)==null?void 0:I.onPaymentSuccess)==null||A.call(I,D):D.status==="failed"&&(p(new Error(D.error)),(Z=(j=l.current)==null?void 0:j.onPaymentFailed)==null||Z.call(j,D))}catch(D){p(D instanceof Error?D:new Error(String(D)))}finally{u(!1)}})()},[e]);let m=(0,x.useCallback)(async(b,S)=>{var U;if(h.current)return;h.current=!0;let k=S!=null&&S.paymentSetupConfig?{paymentSetupConfig:S.paymentSetupConfig}:(U=l.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:l.current.paymentSetupConfig}:void 0;try{let[N,I,A]=await Promise.all([e.payment.getPaymentSetup(b,k),e.payment.getExpressMethods(b,k),e.payment.getStoreConfig()]);r(N),i(I),a(A)}catch(N){h.current=!1,p(N instanceof Error?N:new Error(String(N)))}},[e]),C=(0,x.useCallback)(async b=>{var S,k,U,N;u(!0),p(null);try{let I=await e.payment.processPayment(b);if(I.status==="requires_redirect"){if(I.method==="POST"&&I.postData){let A=document.createElement("form");A.method="POST",A.action=I.redirectUrl;for(let[j,Z]of Object.entries(I.postData)){let D=document.createElement("input");D.type="hidden",D.name=j,D.value=Z,A.appendChild(D)}document.body.appendChild(A),A.submit()}else window.location.href=I.redirectUrl;return I}return I.status==="succeeded"?(k=(S=l.current)==null?void 0:S.onPaymentSuccess)==null||k.call(S,I):I.status==="failed"&&(p(new Error(I.error)),(N=(U=l.current)==null?void 0:U.onPaymentFailed)==null||N.call(U,I)),I}catch(I){let A=I instanceof Error?I:new Error(String(I));return p(A),{status:"failed",error:A.message}}finally{u(!1)}},[e]),R=(0,x.useCallback)(b=>async()=>{u(!0),p(null);try{return await b()}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[]),w=(0,x.useCallback)(async b=>{u(!0),p(null);try{let S=await e.payment.pay(b);return d(S),S}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[e]),P=(0,x.useCallback)(b=>e.payment.tokenizeCard(b),[e]),v=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApplePay(b))();return d(k),k},[e,R]),E=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processGooglePay(b))();return d(k),k},[e,R]),z=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApm(b))();return d(k),k},[e,R]),H=(0,x.useCallback)(b=>e.payment.pollPaymentStatus(b),[e]);return{paymentSetup:t,expressMethods:n,storeConfig:o,isProcessing:c,result:g,error:f,loadPaymentSetup:m,processPayment:C,pay:w,tokenizeCard:P,processApplePay:v,processGooglePay:E,processApm:z,pollStatus:H}}var T=M("react");function it(s){let e=O(),[t,r]=(0,T.useState)(null),[n,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),g=(0,T.useRef)(s);g.current=s;let d=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var S;if(typeof window>"u"||(S=g.current)!=null&&S.disableAutoResume||d.current)return;let v=new URLSearchParams(window.location.search),E=v.get("paymentAction"),z=v.get("paymentActionStatus"),H=v.get("paymentId");if(E!=="requireAction"||z!=="completed"||!H||(d.current=!0,!be(H)))return;a(!0),u(null),(async()=>{var k,U,N,I;try{let A=await e.payment.resumeAfterRedirect(H),j=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(D=>j.delete(D));let Z=j.toString()?`${window.location.pathname}?${j.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Z),A.status==="succeeded"?(U=(k=g.current)==null?void 0:k.onOfferAccepted)==null||U.call(k,A):A.status==="failed"&&(u(new Error(A.error)),(I=(N=g.current)==null?void 0:N.onOfferDeclined)==null||I.call(N,A))}catch(A){u(A instanceof Error?A:new Error(String(A)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async v=>{a(!0),u(null);try{return await v()}catch(E){let z=E instanceof Error?E:new Error(String(E));throw u(z),z}finally{a(!1)}},[]),p=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.getOffer(v);return r(E),E}),[e,f]),h=(0,T.useCallback)(v=>e.offers.listOffers(v),[e]),y=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.previewOffer(v);return i(E),E}),[e,f]),l=(0,T.useCallback)(v=>f(()=>e.offers.payPreviewedOffer(v)),[e,f]),m=(0,T.useCallback)(async v=>{var E,z,H,b;a(!0),u(null);try{let S=await e.offers.processOfferPayment(v);if(S.status==="requires_redirect"){if(S.method==="POST"&&S.postData){let k=document.createElement("form");k.method="POST",k.action=S.redirectUrl;for(let[U,N]of Object.entries(S.postData)){let I=document.createElement("input");I.type="hidden",I.name=U,I.value=N,k.appendChild(I)}document.body.appendChild(k),k.submit()}else window.location.href=S.redirectUrl;return S}return S.status==="succeeded"?(z=(E=g.current)==null?void 0:E.onOfferAccepted)==null||z.call(E,S):S.status==="failed"&&(u(new Error(S.error)),(b=(H=g.current)==null?void 0:H.onOfferDeclined)==null||b.call(H,S)),S}catch(S){let k=S instanceof Error?S:new Error(String(S));return u(k),{status:"failed",error:k.message}}finally{a(!1)}},[e]),C=(0,T.useCallback)(v=>e.offers.toggleOrderBump(v),[e]),R=(0,T.useCallback)(v=>e.offers.listPostPurchaseOffers(v),[e]),w=(0,T.useCallback)(v=>f(()=>e.offers.acceptPostPurchaseOffer(v)),[e,f]),P=(0,T.useCallback)(v=>f(()=>e.offers.declinePostPurchaseOffer(v)),[e,f]);return{offer:t,preview:n,isLoading:o,error:c,getOffer:p,listOffers:h,previewOffer:y,processOfferPayment:m,payPreviewedOffer:l,toggleOrderBump:C,listPostPurchaseOffers:R,acceptPostPurchaseOffer:w,declinePostPurchaseOffer:P}}var G=M("react");function ot(s){let e=O(),[t,r]=(0,G.useState)(null),[n,i]=(0,G.useState)([]),[o,a]=(0,G.useState)([]),[c,u]=(0,G.useState)(!1),[g,d]=(0,G.useState)(null),f=(0,G.useCallback)(async l=>{u(!0),d(null);try{let m=await e.customer.getProfile(l);r(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}finally{u(!1)}},[e]),p=(0,G.useCallback)(async l=>{try{let m=await e.customer.getOrders(l);i(m.orders)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),h=(0,G.useCallback)(async l=>{try{let m=await e.customer.getSubscriptions(l);a(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),y=(0,G.useCallback)(async(l,m)=>{try{let C=await e.customer.updateProfile(l,m);r(C)}catch(C){d(C instanceof Error?C:new Error(String(C)))}},[e]);return(0,G.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:n,subscriptions:o,isLoading:c,error:g,loadCustomer:f,loadOrders:p,loadSubscriptions:h,updateProfile:y}}var $=M("react");function at(s,e){let t=O(),[r,n]=(0,$.useState)(null),[i,o]=(0,$.useState)(!1),[a,c]=(0,$.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,g=(e==null?void 0:e.watchTimeoutMs)??8e3,d=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,$.useRef)(0),p=(0,$.useCallback)(async()=>{if(s)try{let h=await t.customer.getOrder(s);n(h)}catch(h){c(h instanceof Error?h:new Error(String(h)))}},[t,s]);return(0,$.useEffect)(()=>{if(!s)return;let h=++f.current,y=()=>f.current===h;return o(!0),c(null),(async()=>{var l,m;try{let C=await t.customer.getOrder(s);if(!y()||(n(C),o(!1),!u||(l=C.relatedOrders)!=null&&l.length))return;let R=Date.now()+g;for(;Date.now()<R&&y();){if(await new Promise(w=>setTimeout(w,d)),!y()||(C=await t.customer.getOrder(s),!y()))return;if((m=C.relatedOrders)!=null&&m.length){n(C);return}}}catch(C){if(!y())return;c(C instanceof Error?C:new Error(String(C))),o(!1)}})(),()=>{f.current++}},[t,s,u,g,d]),{order:r,relatedOrders:(r==null?void 0:r.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var Y=M("react");function ct(){let s=O(),[e,t]=(0,Y.useState)([]),[r,n]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)(null),a=(0,Y.useCallback)(async u=>{n(!0),o(null);try{let g=await s.catalog.getProducts(u);return t(g),g}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]),c=(0,Y.useCallback)(async u=>{n(!0),o(null);try{return await s.catalog.getProduct(u)}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:a,loadProduct:c}}var F=M("react");var Ht=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function ut(){let s=O(),[e,t]=(0,F.useState)([]),[r,n]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let g=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,l)}catch(m){let C=m instanceof Error?m:new Error(String(m));throw c(C),C}finally{o(!1)}},[s]),d=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,l)}catch(m){let C=m instanceof Error?m:new Error(String(m));throw c(C),C}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.submitCase(y);return n(l),l}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.getCasesForOrder(y);return t(l.cases),l.cases}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),h=(0,F.useCallback)(({orderId:y,checkoutToken:l},m)=>{u.current&&clearInterval(u.current);let C=(m==null?void 0:m.intervalMs)??5e3,R=async()=>{var w;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:l});t(P.cases),(w=m==null?void 0:m.onUpdate)==null||w.call(m,P.cases),P.cases.length>0&&P.cases.every(v=>Ht.has(v.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let v=P instanceof Error?P:new Error(String(P));c(v)}};return R(),u.current=setInterval(R,C),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:r,isLoading:i,error:a,isRequiredForProduct:g,getQuestionsForProduct:d,submitCase:f,fetchCasesForOrder:p,pollOrder:h}}var dt=M("react");function lt(s,e){let t=O(),r=e?JSON.stringify(e):"";(0,dt.useEffect)(()=>{t.track.step(s,e)},[t,s,r])}var L=M("react");var pt=!1,mt=!1,Re=[];function De(){mt=!0;for(let s of Re)s();Re.length=0}function ae(s,e={}){var t,r;return mt||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(De(),Promise.resolve()):pt?new Promise(n=>Re.push(n)):(pt=!0,new Promise((n,i)=>{if(Re.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,d;(d=(g=window.google)==null?void 0:g.maps)!=null&&d.places?De():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>De(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var K=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,g,d;o(c===((d=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:d.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var c,u,g;i(a===((g=(u=(c=window.google)==null?void 0:c.maps)==null?void 0:u.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",o="",a="",c="",u="",g="";for(let p of e.address_components??[]){let h=p.types;h.includes("subpremise")&&(t.subpremise=p.long_name),h.includes("street_number")&&(t.streetNumber=p.long_name),h.includes("premise")&&(r=p.long_name),h.includes("route")&&(t.route=p.long_name),h.includes("neighborhood")&&(n=p.long_name),h.includes("sublocality_level_5")&&(i=p.long_name),h.includes("sublocality_level_4")&&(o=p.long_name),h.includes("sublocality_level_3")&&(a=p.long_name),h.includes("sublocality_level_2")&&(c=p.long_name),h.includes("sublocality_level_1")&&(u=p.long_name),h.includes("locality")&&(t.locality=p.long_name),h.includes("postal_town")&&(g=p.long_name),h.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),h.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),h.includes("country")&&(t.country=p.short_name),h.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=g||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let d=t.streetNumber||r,f=t.route||i||o||a||n;if(t.subpremise&&d&&f)t.fullStreetAddress=`${t.subpremise}/${d} ${f}`;else if(d&&f)if(r&&o&&a){let p=`${a}-${o}-${r}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${d} ${f}`;else f?t.fullStreetAddress=f:d&&(t.fullStreetAddress=d);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function gt(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[g,d]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),h=(0,L.useCallback)(()=>{ae(e,{language:t,region:r,version:n}).then(()=>d(!0))},[e,t,r,n]);(0,L.useEffect)(()=>{!e||i||h()},[e,i,h]),(0,L.useEffect)(()=>{if(g&&p.current){let{input:w,country:P}=p.current;p.current=null,y(w,P)}},[g]);let y=(0,L.useCallback)((w,P)=>{if(!g){i&&(p.current={input:w,country:P},h());return}if(w.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let v=await K.searchPlaces(w,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(v),u(!1)},300)},[g,i,h]),l=(0,L.useCallback)(w=>K.getPlaceDetails(w),[]),m=(0,L.useCallback)(w=>K.extractAddressComponents(w),[]),C=(0,L.useCallback)(w=>K.extractFormattedAddress(w),[]),R=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:g,searchPlaces:y,getPlaceDetails:l,extractAddressComponents:m,extractFormattedAddress:C,clearPredictions:R}}var J=M("react");var ft="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",qe=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],ce=new Map,Ae=new Map,Me=new Map,Fe=new Map;async function jt(s){let e=ce.get(s);if(e)return e;let t=Me.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return ce.set(s,i),Me.delete(s),i})(),Me.set(s,t),t)}async function $t(s){let e=Ae.get(s);if(e)return e;let t=Fe.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return Ae.set(s,i),Fe.delete(s),i})(),Fe.set(s,t),t)}function Kt(s){return ce.get(s)||ce.get("en")||{}}function Bt(s){return Ae.get(s)||Ae.get("en")||{}}async function ue(s="en"){await Promise.all([jt(s),$t(s)])}var xe=(s="en")=>{let e=Kt(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},Ge=(s,e="en")=>{let r=Bt(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function de(s){return ce.has(s)}var B=class s{static ensureLoaded(e="en"){return ue(e)}static getCountries(e="en"){let t=xe(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return xe(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return Ge(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return de(e)}static getAvailableLanguages(){return qe}};function Te(s="en"){let[e,t]=(0,J.useState)(de(s));return(0,J.useEffect)(()=>{let r=!1;return ue(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,J.useMemo)(()=>e?{countries:B.getCountries(s),getRegions:r=>B.getRegions(r,s),findRegion:(r,n)=>B.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>B.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function ht(s="en"){let{countries:e,isLoaded:t}=Te(s);return(0,J.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function yt(s,e="en"){let{getRegions:t,isLoaded:r}=Te(e);return(0,J.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var zt={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Vt={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},Jt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),W=class s{static getSymbol(e){return zt[e]??e}static getName(e){return Vt[e]??e}static getDecimalPlaces(e){return Jt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function He(s,e="USD",t="en-US"){let r=W.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${W.getSymbol(e)}${n.toFixed(r)}`}}return Rt(Qt);})();
|
|
6
|
+
"use strict";var TagadaHeadlessReactBundle=(()=>{var Ct=Object.create;var le=Object.defineProperty;var wt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var M=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var bt=(s,e)=>{for(var t in e)le(s,t,{get:e[t],enumerable:!0})},je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!It.call(s,n)&&n!==t&&le(s,n,{get:()=>e[n],enumerable:!(r=wt(e,n))||r.enumerable});return s};var Oe=(s,e,t)=>(t=s!=null?Ct(kt(s)):{},je(e||!s||!s.__esModule?le(t,"default",{value:s,enumerable:!0}):t,s)),Rt=s=>je(le({},"__esModule",{value:!0}),s);var Wt={};bt(Wt,{CurrencyUtils:()=>W,GoogleAutocompleteCore:()=>K,ISODataCore:()=>B,TagadaHeadlessProvider:()=>et,formatMoney:()=>Ge,loadGoogleMapsScript:()=>ae,parseTokensFromUrl:()=>Ke,useCatalog:()=>ct,useCheckout:()=>rt,useCountryOptions:()=>ht,useCustomer:()=>ot,useGoogleAutocomplete:()=>gt,useHeadlessClient:()=>O,useISOData:()=>Te,useOffers:()=>it,useOrder:()=>at,usePayment:()=>st,useRegionOptions:()=>yt,useRx:()=>ut,useStep:()=>lt});var Q=M("react");var H=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},pe=class extends H{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},me=class extends H{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},X=class extends H{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},ge=class extends H{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var te=class extends H{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $e={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},re=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??$e[e]??$e.production}async request(e,t={}){var h;let{method:r="GET",body:n,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[m,w]of Object.entries(o))w!==void 0&&y.set(m,String(w));let l=y.toString();l&&(u+=`?${l}`)}let g={"Content-Type":"application/json",...i},d=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));d&&(g["x-cms-token"]=d);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let l=await y.text();return l?JSON.parse(l):{}}throw await this.handleErrorResponse(y,e),new H("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof H?y:y instanceof DOMException&&y.name==="AbortError"?new te(`Request to ${e} timed out after ${this.timeout}ms.`):new te(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=At(r.data),i=r.message||r.error||(typeof n.message=="string"?n.message:void 0)||(typeof r.data=="string"&&Object.keys(n).length===0?r.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new pe(i);case 404:throw new X(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new me(i,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new ge(a)}default:throw new H(i,"api_error",e.status,r)}}};function At(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var ne=class s{constructor(e,t,r,n){this.http=e;this.storeId=t;this.onTokenChange=r;this.onSession=n}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,g;let t=e.items.map(d=>({variantId:d.variantId,priceId:d.priceId,...d.sellingPlanId!==void 0?{sellingPlanId:d.sellingPlanId}:{},...d.trialDays!==void 0?{trialDays:d.trialDays}:{},...d.trialPrice!==void 0?{trialPrice:d.trialPrice}:{},quantity:d.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl),e.funnelSessionId&&(r.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(r.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(r.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(r.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(r.customerTags=e.customerTags);let n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);let i=await this.http.post("/api/v1/checkout/session/init",r),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:r,...n}=e,i=await this.createSession(n),o=r??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,...n.sellingPlanId!==void 0?{sellingPlanId:n.sellingPlanId}:{},quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return xt({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(r=>this.normalizeShippingRate(r))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),c=i.map(d=>{let f=d.price,p=d.variant??(f==null?void 0:f.variant)??{},h=d.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},l=(a?y[a]:void 0)??y[Object.keys(y)[0]],m=(l==null?void 0:l.amount)??0;return{id:d.id,variantId:d.variantId,priceId:d.priceId,productName:h.name??"",variantName:p.name??"",quantity:d.quantity??1,unitAmount:m,totalAmount:m*(d.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??h.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAdjustedAmount??n.totalAmount??u.reduce((d,f)=>d+(f.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,r={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(r).some(n=>n!==void 0&&n!=="")?r:void 0}},Ke=ne.parseTokensFromUrl;function xt(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function fe(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(e)?e:void 0}function he(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(r)?r:void 0}function Be(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var _e="headless",Le="1.18.0";var ze="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-pixels.min.js";function We(s,e){return e()?Promise.resolve():new Promise((t,r)=>{let n=document.createElement("script");n.src=s,n.async=!0,n.onload=()=>t(),n.onerror=()=>r(new Error("runtime script failed to load")),document.head.appendChild(n)})}async function Tt(){if(typeof window>"u")return null;if(ze){let s=window;return s.TagadaPixels?s.TagadaPixels:(await We(ze,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ve="__tgd_track",Et="__tgd_aid",Ot="__tgd_sid",Je=50,_t=2e3,Qe=1e3,Lt=64;function Pe(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ye(s){if(!s)return;let e={};for(let[t,r]of Object.entries(s))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var Ut={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function Ue(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Nt(s){let e={};for(let t of s){let{provider:r,id:n,idKey:i,...o}=t;(e[r]??(e[r]=[])).push({...o,enabled:!0,[i]:n,events:t.events??{}})}return e}var ye=class{constructor(e,t,r){this.baseUrl=e;this.storeId=t;this.funnelKey=r;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Ve)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Ve,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let r=(t==null?void 0:t.path)??window.location.pathname,n=`${e}|${r}`,i=Date.now(),o=this.lastStep.get(n);o!==void 0&&i-o<Qe||(this.remember(n,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:r}),this.pixels().then(a=>a==null?void 0:a.pageView(r,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let r=this.currentStepId;if(r===null)return;let n=Ut[e],i=`${n??e}_${Ue()}`;this.push({kind:"event",stepId:r,name:e,at:Date.now(),eventId:i,props:Ye(t)}),this.pixels().then(o=>n?o==null?void 0:o.track(n,t,{stepId:r,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:r})),this.core().then(o=>o==null?void 0:o.track(e,{...Ye(t)??{},step_id:r,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[r,n]of this.lastStep)t-n>=Qe&&this.lastStep.delete(r);for(;this.lastStep.size>=Lt;){let r=this.lastStep.keys().next();if(r.done===!0)break;this.lastStep.delete(r.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,r){this.off()||this.pixels().then(n=>{var i;return n==null?void 0:n.track(e,{value:r.amount,currency:r.currency,contents:r.items,num_items:(i=r.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,r){this.off()||(this.signals.push({signal:e,value:t,detail:r}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:r}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let r=await t.json();return this.manifestHash=r.manifestHash||null,r}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let r=await this.config();if(!r||!r.collect&&!r.experiments)return null;let n=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await We(n+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:r.collect?new URL(r.collect.url).origin:n,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let r=await Tt();if(r===null)return null;let n=r.createPixelEngine({pixels:Nt(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await n.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],n}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=Je){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),_t))}}identifier(e,t){try{let r=e==="local"?localStorage:sessionStorage,n=r.getItem(t);if(n)return n;let i=Ue();return r.setItem(t,i),i}catch{return Ue()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Je),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},anonymousId:this.identifier("local",Et),sessionId:this.identifier("session",Ot),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let r=JSON.stringify(t),n=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(n,new Blob([r],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(n,{method:"POST",body:r,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Dt=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Mt(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,r=s.settings??{},n=r.processors,i=r.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=n==null?void 0:n[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var Se=class{constructor(e,t,r,n,i,o){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let r=this.readInjectedStepConfig();if(r)return this.lastPaymentSetup=r,r;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof X))throw i}let n=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=n,n}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r=Array.isArray(t)?t.map(Mt):(t==null?void 0:t.methods)??[],n={};for(let i of r){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;n[o]=i}return n}async getExpressMethods(e,t){var i,o,a,c,u,g,d,f,p,h;let r=await this.getPaymentSetup(e,t),n={};for(let[y,l]of Object.entries(r)){if(!l.enabled)continue;if(y.startsWith("express_checkout:")&&l.methods){let R={available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if((i=l.methods.apple_pay)!=null&&i.enabled){let C=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...R,type:"apple_pay",available:!!C}}(c=l.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay={...R,type:"google_pay"}),(g=l.methods.link)!=null&&g.enabled&&(n.link={...R,type:"link"}),(d=l.methods.klarna_express)!=null&&d.enabled&&(n.klarna={...R,type:"klarna_express"});continue}if(!l.express)continue;let m=l.method,w={type:m,available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if(m==="apple_pay"||l.type==="apple_pay"){let R=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));n.applePay={...w,available:!!R}}else m==="google_pay"||l.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((h=this.onSignal)==null||h.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay=w):m==="paypal"?n.paypal=w:m==="klarna"||m==="klarna_express"?n.klarna=w:m==="link"&&(n.link=w)}return n}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let r=await this.getPaymentSetup(e,t);return Object.entries(r).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl})}async syncWalletContact(e,t){let{shippingAddress:r,billingAddress:n}=t;if(!r&&!n)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:r,billingAddress:n})}async processApplePay(e){var a,c,u,g,d,f,p,h,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:fe(e.shippingContact),billingAddress:fe(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((d=e.shippingContact)==null?void 0:d.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((h=e.billingContact)==null?void 0:h.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(r.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let r=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},n=r(this.readInjectedStepConfig())??r(this.lastPaymentSetup);if(n)return n;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return r(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:he(e.shippingAddress),billingAddress:he(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,r),{status:"succeeded",payment:r,order:e.order}):r.status==="failed"||r.status==="declined"?{status:"failed",error:((o=r.requireActionData)==null?void 0:o.message)||((a=r.requireActionData)==null?void 0:a.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>c.delete(g));let u=c.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var i,o;let r=(i=t.metadata)==null?void 0:i.redirect,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,method:((o=r==null?void 0:r.method)==null?void 0:o.toUpperCase())||"GET",postData:r==null?void 0:r.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let r=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let n;try{n=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new n.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){var a;let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<n;){let c;try{c=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,r));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(c.status==="failed"||c.status==="declined")return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,r))}return{status:"pending",paymentId:e}}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}emitPaid(e,t){var r;if(!(!e||!this.onPaid))try{let n=(r=this.checkout)==null?void 0:r.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:Pe(n==null?void 0:n.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var V=typeof document>"u"?null:document.currentScript,Ft=V!=null&&V.src?new URL("tagada-headless-commerce.min.js",V.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.18.0/dist/tagada-headless-commerce.min.js",Ce;function ee(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(Ce||(Ce=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,V!=null&&V.nonce&&(t.nonce=V.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw Ce=void 0,s})),Ce)}var se=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])se.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ie=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])ie.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var oe=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])oe.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var we=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var ve=class{constructor(e,t,r,n,i){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new H("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new H("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=r.customer)==null?void 0:o.locale)??Ht(),userAgent:qt(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=r.customer)==null?void 0:c.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var d,f,p,h;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:o}=e,a=n.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),u={email:((d=i.customer)==null?void 0:d.email)??((f=n.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??n.currency,locale:(h=i.customer)==null?void 0:h.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function Ht(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function qt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var ke=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var Ie=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,r,n,i;return((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.arm)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:r}of this.subscribers.splice(0))try{e?e.onVariant(t,r):r(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,r,n,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.payload)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,r;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:r.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var Ne=class{constructor(e){let t=e.environment??"production",r=re.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new re({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new ye(r,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new Ie(()=>this.track.core(),this.config.bootstrap);let n=i=>{this._sessionToken=i};this.checkout=new ne(this.http,this.config.storeId,n,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:Pe(i.items)})),this.payment=new Se(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new se(this.http,this.config.storeId,this.payment),this.customer=new ie(this.http,this.config.storeId),this.portal=new oe(this.http,this.config.storeId,n),this.catalog=new we(this.http,this.config.storeId),this.funnel=new ve(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new ke(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Ze(s){return new Ne(s)}var tt=M("react/jsx-runtime"),Xe=(0,Q.createContext)(null);function Gt(s){let e={storeId:s.storeId,environment:s.environment,apiKey:s.apiKey,baseUrl:s.baseUrl,accountId:s.accountId,funnel:s.funnel,timeout:s.timeout,bootstrap:s.bootstrap};return JSON.stringify(e)}function jt(s){if(s.config)return s.config;let{storeId:e,environment:t,apiKey:r,baseUrl:n}=s;return{storeId:e,environment:t,apiKey:r,baseUrl:n}}function et(s){let e=jt(s),t=Gt(e),r=(0,Q.useMemo)(()=>Ze(e),[t]),n=(0,Q.useMemo)(()=>({client:r}),[r]);return(0,tt.jsx)(Xe.Provider,{value:n,children:s.children})}function O(){let s=(0,Q.useContext)(Xe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var _=M("react");function rt(s,e){let t=O(),[r,n]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[a,c]=(0,_.useState)(null),u=(0,_.useCallback)(async()=>{if(s){o(!0),c(null);try{let C=await t.checkout.loadSession(s,e);n(C)}catch(C){c(C instanceof Error?C:new Error(String(C)))}finally{o(!1)}}},[t,s,e]);(0,_.useEffect)(()=>{u()},[u]);let g=(0,_.useCallback)(async C=>{o(!0),c(null);try{let P=await t.checkout.createSession(C),v=new URL(window.location.href);v.searchParams.set("checkoutToken",P.checkoutToken),v.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",v.toString());let E=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);n(E)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),d=(0,_.useCallback)(async C=>{c(null);try{return await t.checkout.createSessionUrl(C)}catch(P){let v=P instanceof Error?P:new Error(String(P));throw c(v),v}},[t]),f=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateCart(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),p=(0,_.useCallback)(async C=>{r&&await t.checkout.updateCustomer(r.id,C)},[t,r]),h=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),y=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateCustomerAndAddress(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),l=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),m=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),w=(0,_.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),R=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]);return{session:r,isLoading:i,error:a,refresh:u,createSession:g,createSessionUrl:d,updateCart:f,updateCustomer:p,updateAddress:h,updateCustomerAndAddress:y,applyPromo:l,removePromo:m,getShippingRates:w,selectShippingRate:R}}var x=M("react");var nt=new Set;function be(s){return nt.has(s)?!1:(nt.add(s),!0)}function st(s){let e=O(),[t,r]=(0,x.useState)(null),[n,i]=(0,x.useState)(null),[o,a]=(0,x.useState)(null),[c,u]=(0,x.useState)(!1),[g,d]=(0,x.useState)(null),[f,p]=(0,x.useState)(null),h=(0,x.useRef)(!1),y=(0,x.useRef)(!1),l=(0,x.useRef)(s);l.current=s,(0,x.useEffect)(()=>{if(typeof window>"u"||y.current)return;let b=new URLSearchParams(window.location.search),S=b.get("paymentAction"),k=b.get("paymentActionStatus"),U=b.get("paymentId");if(S!=="requireAction"||k!=="completed"||!U||(y.current=!0,!be(U)))return;u(!0),p(null),(async()=>{var I,A,j,Z;try{let D=await e.payment.resumeAfterRedirect(U),Ee=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(St=>Ee.delete(St));let Pt=Ee.toString()?`${window.location.pathname}?${Ee.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Pt),D.status==="succeeded"?(A=(I=l.current)==null?void 0:I.onPaymentSuccess)==null||A.call(I,D):D.status==="failed"&&(p(new Error(D.error)),(Z=(j=l.current)==null?void 0:j.onPaymentFailed)==null||Z.call(j,D))}catch(D){p(D instanceof Error?D:new Error(String(D)))}finally{u(!1)}})()},[e]);let m=(0,x.useCallback)(async(b,S)=>{var U;if(h.current)return;h.current=!0;let k=S!=null&&S.paymentSetupConfig?{paymentSetupConfig:S.paymentSetupConfig}:(U=l.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:l.current.paymentSetupConfig}:void 0;try{let[N,I,A]=await Promise.all([e.payment.getPaymentSetup(b,k),e.payment.getExpressMethods(b,k),e.payment.getStoreConfig()]);r(N),i(I),a(A)}catch(N){h.current=!1,p(N instanceof Error?N:new Error(String(N)))}},[e]),w=(0,x.useCallback)(async b=>{var S,k,U,N;u(!0),p(null);try{let I=await e.payment.processPayment(b);if(I.status==="requires_redirect"){if(I.method==="POST"&&I.postData){let A=document.createElement("form");A.method="POST",A.action=I.redirectUrl;for(let[j,Z]of Object.entries(I.postData)){let D=document.createElement("input");D.type="hidden",D.name=j,D.value=Z,A.appendChild(D)}document.body.appendChild(A),A.submit()}else window.location.href=I.redirectUrl;return I}return I.status==="succeeded"?(k=(S=l.current)==null?void 0:S.onPaymentSuccess)==null||k.call(S,I):I.status==="failed"&&(p(new Error(I.error)),(N=(U=l.current)==null?void 0:U.onPaymentFailed)==null||N.call(U,I)),I}catch(I){let A=I instanceof Error?I:new Error(String(I));return p(A),{status:"failed",error:A.message}}finally{u(!1)}},[e]),R=(0,x.useCallback)(b=>async()=>{u(!0),p(null);try{return await b()}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[]),C=(0,x.useCallback)(async b=>{u(!0),p(null);try{let S=await e.payment.pay(b);return d(S),S}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[e]),P=(0,x.useCallback)(b=>e.payment.tokenizeCard(b),[e]),v=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApplePay(b))();return d(k),k},[e,R]),E=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processGooglePay(b))();return d(k),k},[e,R]),z=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApm(b))();return d(k),k},[e,R]),G=(0,x.useCallback)(b=>e.payment.pollPaymentStatus(b),[e]);return{paymentSetup:t,expressMethods:n,storeConfig:o,isProcessing:c,result:g,error:f,loadPaymentSetup:m,processPayment:w,pay:C,tokenizeCard:P,processApplePay:v,processGooglePay:E,processApm:z,pollStatus:G}}var T=M("react");function it(s){let e=O(),[t,r]=(0,T.useState)(null),[n,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),g=(0,T.useRef)(s);g.current=s;let d=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var S;if(typeof window>"u"||(S=g.current)!=null&&S.disableAutoResume||d.current)return;let v=new URLSearchParams(window.location.search),E=v.get("paymentAction"),z=v.get("paymentActionStatus"),G=v.get("paymentId");if(E!=="requireAction"||z!=="completed"||!G||(d.current=!0,!be(G)))return;a(!0),u(null),(async()=>{var k,U,N,I;try{let A=await e.payment.resumeAfterRedirect(G),j=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(D=>j.delete(D));let Z=j.toString()?`${window.location.pathname}?${j.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Z),A.status==="succeeded"?(U=(k=g.current)==null?void 0:k.onOfferAccepted)==null||U.call(k,A):A.status==="failed"&&(u(new Error(A.error)),(I=(N=g.current)==null?void 0:N.onOfferDeclined)==null||I.call(N,A))}catch(A){u(A instanceof Error?A:new Error(String(A)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async v=>{a(!0),u(null);try{return await v()}catch(E){let z=E instanceof Error?E:new Error(String(E));throw u(z),z}finally{a(!1)}},[]),p=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.getOffer(v);return r(E),E}),[e,f]),h=(0,T.useCallback)(v=>e.offers.listOffers(v),[e]),y=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.previewOffer(v);return i(E),E}),[e,f]),l=(0,T.useCallback)(v=>f(()=>e.offers.payPreviewedOffer(v)),[e,f]),m=(0,T.useCallback)(async v=>{var E,z,G,b;a(!0),u(null);try{let S=await e.offers.processOfferPayment(v);if(S.status==="requires_redirect"){if(S.method==="POST"&&S.postData){let k=document.createElement("form");k.method="POST",k.action=S.redirectUrl;for(let[U,N]of Object.entries(S.postData)){let I=document.createElement("input");I.type="hidden",I.name=U,I.value=N,k.appendChild(I)}document.body.appendChild(k),k.submit()}else window.location.href=S.redirectUrl;return S}return S.status==="succeeded"?(z=(E=g.current)==null?void 0:E.onOfferAccepted)==null||z.call(E,S):S.status==="failed"&&(u(new Error(S.error)),(b=(G=g.current)==null?void 0:G.onOfferDeclined)==null||b.call(G,S)),S}catch(S){let k=S instanceof Error?S:new Error(String(S));return u(k),{status:"failed",error:k.message}}finally{a(!1)}},[e]),w=(0,T.useCallback)(v=>e.offers.toggleOrderBump(v),[e]),R=(0,T.useCallback)(v=>e.offers.listPostPurchaseOffers(v),[e]),C=(0,T.useCallback)(v=>f(()=>e.offers.acceptPostPurchaseOffer(v)),[e,f]),P=(0,T.useCallback)(v=>f(()=>e.offers.declinePostPurchaseOffer(v)),[e,f]);return{offer:t,preview:n,isLoading:o,error:c,getOffer:p,listOffers:h,previewOffer:y,processOfferPayment:m,payPreviewedOffer:l,toggleOrderBump:w,listPostPurchaseOffers:R,acceptPostPurchaseOffer:C,declinePostPurchaseOffer:P}}var q=M("react");function ot(s){let e=O(),[t,r]=(0,q.useState)(null),[n,i]=(0,q.useState)([]),[o,a]=(0,q.useState)([]),[c,u]=(0,q.useState)(!1),[g,d]=(0,q.useState)(null),f=(0,q.useCallback)(async l=>{u(!0),d(null);try{let m=await e.customer.getProfile(l);r(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}finally{u(!1)}},[e]),p=(0,q.useCallback)(async l=>{try{let m=await e.customer.getOrders(l);i(m.orders)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),h=(0,q.useCallback)(async l=>{try{let m=await e.customer.getSubscriptions(l);a(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),y=(0,q.useCallback)(async(l,m)=>{try{let w=await e.customer.updateProfile(l,m);r(w)}catch(w){d(w instanceof Error?w:new Error(String(w)))}},[e]);return(0,q.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:n,subscriptions:o,isLoading:c,error:g,loadCustomer:f,loadOrders:p,loadSubscriptions:h,updateProfile:y}}var $=M("react");function at(s,e){let t=O(),[r,n]=(0,$.useState)(null),[i,o]=(0,$.useState)(!1),[a,c]=(0,$.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,g=(e==null?void 0:e.watchTimeoutMs)??8e3,d=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,$.useRef)(0),p=(0,$.useCallback)(async()=>{if(s)try{let h=await t.customer.getOrder(s);n(h)}catch(h){c(h instanceof Error?h:new Error(String(h)))}},[t,s]);return(0,$.useEffect)(()=>{if(!s)return;let h=++f.current,y=()=>f.current===h;return o(!0),c(null),(async()=>{var l,m;try{let w=await t.customer.getOrder(s);if(!y()||(n(w),o(!1),!u||(l=w.relatedOrders)!=null&&l.length))return;let R=Date.now()+g;for(;Date.now()<R&&y();){if(await new Promise(C=>setTimeout(C,d)),!y()||(w=await t.customer.getOrder(s),!y()))return;if((m=w.relatedOrders)!=null&&m.length){n(w);return}}}catch(w){if(!y())return;c(w instanceof Error?w:new Error(String(w))),o(!1)}})(),()=>{f.current++}},[t,s,u,g,d]),{order:r,relatedOrders:(r==null?void 0:r.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var Y=M("react");function ct(){let s=O(),[e,t]=(0,Y.useState)([]),[r,n]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)(null),a=(0,Y.useCallback)(async u=>{n(!0),o(null);try{let g=await s.catalog.getProducts(u);return t(g),g}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]),c=(0,Y.useCallback)(async u=>{n(!0),o(null);try{return await s.catalog.getProduct(u)}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:a,loadProduct:c}}var F=M("react");var $t=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function ut(){let s=O(),[e,t]=(0,F.useState)([]),[r,n]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let g=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,l)}catch(m){let w=m instanceof Error?m:new Error(String(m));throw c(w),w}finally{o(!1)}},[s]),d=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,l)}catch(m){let w=m instanceof Error?m:new Error(String(m));throw c(w),w}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.submitCase(y);return n(l),l}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.getCasesForOrder(y);return t(l.cases),l.cases}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),h=(0,F.useCallback)(({orderId:y,checkoutToken:l},m)=>{u.current&&clearInterval(u.current);let w=(m==null?void 0:m.intervalMs)??5e3,R=async()=>{var C;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:l});t(P.cases),(C=m==null?void 0:m.onUpdate)==null||C.call(m,P.cases),P.cases.length>0&&P.cases.every(v=>$t.has(v.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let v=P instanceof Error?P:new Error(String(P));c(v)}};return R(),u.current=setInterval(R,w),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:r,isLoading:i,error:a,isRequiredForProduct:g,getQuestionsForProduct:d,submitCase:f,fetchCasesForOrder:p,pollOrder:h}}var dt=M("react");function lt(s,e){let t=O(),r=e?JSON.stringify(e):"";(0,dt.useEffect)(()=>{t.track.step(s,e)},[t,s,r])}var L=M("react");var pt=!1,mt=!1,Re=[];function De(){mt=!0;for(let s of Re)s();Re.length=0}function ae(s,e={}){var t,r;return mt||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(De(),Promise.resolve()):pt?new Promise(n=>Re.push(n)):(pt=!0,new Promise((n,i)=>{if(Re.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,d;(d=(g=window.google)==null?void 0:g.maps)!=null&&d.places?De():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>De(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var K=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,g,d;o(c===((d=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:d.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var c,u,g;i(a===((g=(u=(c=window.google)==null?void 0:c.maps)==null?void 0:u.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",o="",a="",c="",u="",g="";for(let p of e.address_components??[]){let h=p.types;h.includes("subpremise")&&(t.subpremise=p.long_name),h.includes("street_number")&&(t.streetNumber=p.long_name),h.includes("premise")&&(r=p.long_name),h.includes("route")&&(t.route=p.long_name),h.includes("neighborhood")&&(n=p.long_name),h.includes("sublocality_level_5")&&(i=p.long_name),h.includes("sublocality_level_4")&&(o=p.long_name),h.includes("sublocality_level_3")&&(a=p.long_name),h.includes("sublocality_level_2")&&(c=p.long_name),h.includes("sublocality_level_1")&&(u=p.long_name),h.includes("locality")&&(t.locality=p.long_name),h.includes("postal_town")&&(g=p.long_name),h.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),h.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),h.includes("country")&&(t.country=p.short_name),h.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=g||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let d=t.streetNumber||r,f=t.route||i||o||a||n;if(t.subpremise&&d&&f)t.fullStreetAddress=`${t.subpremise}/${d} ${f}`;else if(d&&f)if(r&&o&&a){let p=`${a}-${o}-${r}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${d} ${f}`;else f?t.fullStreetAddress=f:d&&(t.fullStreetAddress=d);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function gt(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[g,d]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),h=(0,L.useCallback)(()=>{ae(e,{language:t,region:r,version:n}).then(()=>d(!0))},[e,t,r,n]);(0,L.useEffect)(()=>{!e||i||h()},[e,i,h]),(0,L.useEffect)(()=>{if(g&&p.current){let{input:C,country:P}=p.current;p.current=null,y(C,P)}},[g]);let y=(0,L.useCallback)((C,P)=>{if(!g){i&&(p.current={input:C,country:P},h());return}if(C.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let v=await K.searchPlaces(C,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(v),u(!1)},300)},[g,i,h]),l=(0,L.useCallback)(C=>K.getPlaceDetails(C),[]),m=(0,L.useCallback)(C=>K.extractAddressComponents(C),[]),w=(0,L.useCallback)(C=>K.extractFormattedAddress(C),[]),R=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:g,searchPlaces:y,getPlaceDetails:l,extractAddressComponents:m,extractFormattedAddress:w,clearPredictions:R}}var J=M("react");var ft="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",He=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],ce=new Map,Ae=new Map,Me=new Map,Fe=new Map;async function Kt(s){let e=ce.get(s);if(e)return e;let t=Me.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return ce.set(s,i),Me.delete(s),i})(),Me.set(s,t),t)}async function Bt(s){let e=Ae.get(s);if(e)return e;let t=Fe.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return Ae.set(s,i),Fe.delete(s),i})(),Fe.set(s,t),t)}function zt(s){return ce.get(s)||ce.get("en")||{}}function Vt(s){return Ae.get(s)||Ae.get("en")||{}}async function ue(s="en"){await Promise.all([Kt(s),Bt(s)])}var xe=(s="en")=>{let e=zt(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},qe=(s,e="en")=>{let r=Vt(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function de(s){return ce.has(s)}var B=class s{static ensureLoaded(e="en"){return ue(e)}static getCountries(e="en"){let t=xe(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return xe(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return qe(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return de(e)}static getAvailableLanguages(){return He}};function Te(s="en"){let[e,t]=(0,J.useState)(de(s));return(0,J.useEffect)(()=>{let r=!1;return ue(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,J.useMemo)(()=>e?{countries:B.getCountries(s),getRegions:r=>B.getRegions(r,s),findRegion:(r,n)=>B.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>B.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function ht(s="en"){let{countries:e,isLoaded:t}=Te(s);return(0,J.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function yt(s,e="en"){let{getRegions:t,isLoaded:r}=Te(e);return(0,J.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var Jt={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Qt={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},Yt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),W=class s{static getSymbol(e){return Jt[e]??e}static getName(e){return Qt[e]??e}static getDecimalPlaces(e){return Yt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function Ge(s,e="USD",t="en-US"){let r=W.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${W.getSymbol(e)}${n.toFixed(r)}`}}return Rt(Wt);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessReactBundle){ window.TagadaHeadlessReact=TagadaHeadlessReactBundle;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless-react.min.js.map
|