1var e,t,s,r,i,n;import{a as o}from"./BaseElement.DAzHg0T6.min.js";import{s as a}from"./ritual-toast-alerts.KyYWqiIz.min.js";import{s as c}from"./subscriptions-controller-context.BzuBHjsi.min.js";import{d as u}from"./decodeTranslations.DHn6qj_a.min.js";import{p as d}from"./parseGid.Bunh0C3h.min.js";import{v as l,w as h,x as p,r as g,y as m,z as f,D as y}from"./recharge.awW-VVyH.min.js";import{f as _}from"./recommendedProducts.B9ZCJfLv.min.js";import{b as v,l as b,c as S,e as w,f as C,h as D,j as L,k,m as A,n as I,o as R,p as O,t as T,u as F,v as E,w as x,x as V,y as j,z as P,A as G,B as M,q as N}from"./vendor.BxRSgd5H.min.js";import{n as W,r as q,k as B,b as U,t as $}from"./vendor-lit.Cg17OMaX.min.js";import"./vendor-shoelace.DOLpg2zr.min.js";import"./preload-helper.DIa93bio.min.js";function z(e){return"string"==typeof e&&e.length>0}function H(e){return"number"==typeof e?Number.isFinite(e)?String(e):null:z(e)?e:null}function Y(e,t,s){return`${e}:v${t}:${s}`}function J({prefix:e,schemaVersion:t,ttlMs:s,customerId:r,validatePayload:i}){const n=H(r);if(!n)return null;try{const r=sessionStorage.getItem(Y(e,t,n));if(!r)return null;const o=JSON.parse(r);return(null==o?void 0:o.version)!==t||(null==o?void 0:o.customerId)!==n||"number"!=typeof(null==o?void 0:o.writtenAt)||Date.now()-o.writtenAt>s?null:i(o.payload)?o.payload:null}catch(o){return console.warn(`[RechargeStorageCache:${e}] read failed, degrading to cold path`,o),null}}function Q({prefix:e,schemaVersion:t,customerId:s,payload:r}){const i=H(s);if(i)try{const s={version:t,writtenAt:Date.now(),customerId:i,payload:r};sessionStorage.setItem(Y(e,t,i),JSON.stringify(s))}catch(n){console.warn(`[RechargeStorageCache:${e}] write failed, continuing without cache`,n)}}function X(e){try{const t=[];for(let s=0;s<sessionStorage.length;s++){const r=sessionStorage.key(s);(null==r?void 0:r.startsWith(`${e}:`))&&t.push(r)}t.forEach(e=>sessionStorage.removeItem(e))}catch{}}function K(e,t){return!H(t)&&(X(e),!0)}const Z="add_to_sub_eligibility_cache";function ee(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sessionStatus&&Array.isArray(t.subscriptions)}function te(e,t){Q({prefix:Z,schemaVersion:1,customerId:e,payload:t})}const se=/^[1-9]\d{0,19}$/;async function re(e){try{const t=JSON.parse(await e.text());return null===t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}}function ie(e){return"string"==typeof e&&""!==e?e:null}function ne(e){let t,s=!1,r=null;return{ensure:()=>s?Promise.resolve(t):r||(r=(async()=>{try{const r=await e();return s=!0,t=r,r}finally{r=null}})(),r),get loaded(){return s},get pending(){return null!==r},reset(){s=!1,t=void 0,r=null}}}const oe="rc_account_cache",ae=new Set(["payment_method"]);function ce(e){if(!e||"object"!=typeof e)return e;const t={};for(const[s,r]of Object.entries(e))ae.has(s)||(t[s]=r);return t}function ue(e){if(!e||"object"!=typeof e)return!1;const t=e;return(null===t.customer||"object"==typeof t.customer&&null!==t.customer)&&Array.isArray(t.deliverySchedule)&&"object"==typeof t.subscriptionOrders&&null!==t.subscriptionOrders&&(null===t.variantEnrichmentData||"object"==typeof t.variantEnrichmentData)}function de(e){var t;return null==e.purchase_item_id&&(0===Number(e.unit_price)||"free_gift"===(null==(t=e.offer_attributes)?void 0:t.type))}function le(e,t,s){const r={};for(const i of e??[]){if(!i||null==i.id)continue;const e=(i.line_items??[]).filter(de).map(e=>he(i,e,t,s));e.length&&(r[String(i.id)]=e)}return r}function he(e,t,s,r){var i;const n=null==(i=t.external_variant_id)?void 0:i.ecommerce,o=null!=n?null==s?void 0:s[String(n)]:void 0,a=function(e,t){if(null==e||!t)return null;const s=Number(t[String(e)]);return Number.isFinite(s)&&s>0?s:null}(n,r);return{external_product_id:t.external_product_id,external_variant_id:t.external_variant_id,images:t.images??{},offer_attributes:t.offer_attributes??null,original_price:t.original_price??"0.00",properties:t.properties??[],quantity:t.quantity??1,unit_price:t.unit_price??"0.00",variant_title:t.variant_title??null,product_title:t.title,plan_type:"onetime",is_skippable:!1,is_skipped:!1,is_prepaid:!1,subscription_id:0,subtotal_price:t.total_price??"0.00",address_id:e.address_id,charge_id:e.id,next_charge_scheduled_at:null,charge_interval_frequency:null,order_interval_frequency:null,order_interval_unit:null,is_free_gift:!0,gift_value:a,...o?{...o,allow_option_swap:!1,swap_options:null}:{}}}const pe="rc_session_cache";function ge(e){return!!e&&"object"==typeof e&&z(e.apiToken)}function me(e){return J({prefix:pe,schemaVersion:1,ttlMs:6e5,customerId:e,validatePayload:ge})}function fe(e,t){t&&z(t.apiToken)&&H(t.customerId)&&Q({prefix:pe,schemaVersion:1,
1customerId:e,payload:t})}function ye(e,t){const s={};return e.forEach((e,r)=>{const i=t[r];i&&(s[e]=function(e){return!0===e.availableForSale&&!0!==e.currentlyNotInStock}(i))}),s}const _e=e=>`gid://shopify/ProductVariant/${e}`;var ve=Object.defineProperty,be=Object.getOwnPropertyDescriptor,Se=(e,t,s,r)=>{for(var i,n=r>1?void 0:r?be(t,s):t,o=e.length-1;o>=0;o--)(i=e[o])&&(n=(r?i(t,s,n):i(n))||n);return r&&n&&ve(t,s,n),n};const we=5e3,Ce=u(window.recharge.translations.toastMessages),De={product_added:({productName:e})=>({message:Ce.productAdded.replace("{{product}}",e),variant:"success",icon:"icon-interface-check",duration:we}),shipping_address_created:()=>({message:Ce.shippingAddressCreated,variant:"success",icon:"icon-account-shipping",duration:we}),shipping_address_updated:()=>({message:Ce.shippingAddressUpdated,variant:"success",icon:"icon-account-shipping",duration:we}),shipping_address_deleted:()=>({message:Ce.shippingAddressDeleted,variant:"success",icon:"icon-account-shipping",duration:we}),payment_method_updated:()=>({message:Ce.paymentMethodUpdated,variant:"success",icon:"icon-account-credit-card",duration:we}),cadence_changed:({period:e})=>({message:Ce.cadenceChanged.replace("{{period}}",e),variant:"success",icon:"icon-account-recurring",duration:we}),shipment_rescheduled:({shipDate:e})=>{const t=N.PlainDate.from(e).toLocaleString("en-US",{month:"long",day:"numeric"});return{message:Ce.shipmentRescheduled.replace("{{shipDate}}",t),variant:"success",icon:"icon-account-week",duration:we}},variant_option_switched:({optionName:e,productName:t})=>({message:Ce.variantOptionSwitched.replace("{{option}}",e).replace("{{product}}",t),variant:"success",icon:"icon-account-vegan",duration:we}),product_skipped:({productName:e})=>({message:Ce.productSkipped.replace("{{product}}",e),variant:"success",icon:"icon-account-skip",duration:we}),product_unsubscribed:({productName:e})=>({message:Ce.productUnsubscribed.replace("{{product}}",e),variant:"danger",icon:"icon-account-remove",duration:we}),product_added_back:({productName:e})=>({message:Ce.productAddedBack.replace("{{product}}",e),variant:"success",icon:"icon-interface-check",duration:we}),subscription_updated:({productName:e})=>({message:Ce.subscriptionUpdated.replace("{{product}}",e),variant:"success",icon:"icon-interface-check",duration:we}),subscription_quantity_updated:({productName:e})=>({message:Ce.subscriptionQuantityUpdated.replace("{{product}}",e),variant:"success",icon:"icon-account-recurring",duration:we}),contact_information_updated:()=>({message:Ce.contactInformationUpdated,variant:"success",icon:"icon-interface-check",duration:we}),discount_applied:()=>({message:Ce.discountApplied,variant:"success",icon:"icon-interface-check",duration:we,announce:!1}),discount_removed:()=>({message:Ce.discountRemoved,variant:"success",icon:"icon-account-remove",duration:we,announce:!1}),free_gift_claimed:()=>({message:Ce.freeGiftClaimed,variant:"success",icon:"icon-interface-check",duration:we}),warning:({message:e})=>({message:e,variant:"warning",icon:"icon-interface-alert",duration:we}),error:({message:e})=>({message:e,variant:"danger",icon:"icon-interface-error",duration:we})},Le=new Set;let ke=null;var Ae;v({...window.recharge.config,loginRetryFn:function(){if(ke)return ke;const e="rc-bootstrap:login-retry:start",t="rc-bootstrap:login-retry:end";try{performance.mark(e)}catch{}let s=!1;return ke=(async()=>{try{const e=await D();return fe(window.recharge.customer.id,e),e}catch(e){return console.error("[Recharge] loginRetryFn failed",e),function(e){!function({prefix:e,schemaVersion:t,customerId:s}){const r=H(s);if(r)try{sessionStorage.removeItem(Y(e,t,r))}catch{}}({prefix:pe,schemaVersion:1,customerId:e})}(window.recharge.customer.id),void(s=function(e){const t=null==e?void 0:e.status;return 401===t||403===t}(e))}finally{ke=null}})(),ke.then(r=>{let i=0;try{performance.mark(t);const s=performance.measure("rc-bootstrap:login-retry",e,t);i=s?Math.round(s.duration):0}catch{}var n;n={session:r??null,durationMs:i,demote:s},Le.forEach(e=>{try{e(n)}catch(t){console.error("[Recharge] live session handler failed",t)}})}),ke}}),Ae=null==(t=null==(e=window.recharge)?void 0:e.customer)?void 0:t.id,K(pe,Ae),function(e){K(oe,e)}(null==(r=null==(s=window.recharge)?void 0:s.customer)?void 0:r.id),function(e){K(Z,e)}(null==(n=null==(i=window.recharge)?void 0:i.customer)?void 0:n.id),document.addEventListener("click",e=>{try{const t=e.target;if(!(t instanceof Element))return;const s=t.closest("a[href]"),r=null==s?void 0:s.getAttribute("href");if(!r||!r.includes("/account/logout"))return;X(pe),X(oe),X(Z)}catch{}},{capture:!0});const Ie=["subscriptions","addresses"],Re=["addresses","announcements","metafields","payment_methods","punch_card_progress","referral_info","subscriptions"];function Oe(e){var t;const s=null==(t=null==e?void 0:e.include)?void 0:t.subscriptions;return Array.isArray(s)?new Map(s.map(e=>[Number(e.id),e])):new Map}
1function Te(e,t,s){return Array.isArray(e)&&t?e.map(e=>{var r;const i=function(e){var t;const s=null==(t=null==e?void 0:e.external_variant_id)?void 0:t.ecommerce;return null==s?null:String(s)}(e);if(!i)return e;const n=t[i];if(!n)return e;const o=(null==(r=n.swap_options)?void 0:r.length)?n.swap_options.filter(e=>{const s=d(e.variant_id),r=t[s.id];return f({currentOptions:n.selected_options,candidateOptions:null==r?void 0:r.selected_options,swapOptionLabel:n.swap_option_label})}).map(e=>{const r=d(e.variant_id),i=t[r.id],n=(null==s?void 0:s[r.id])??!0;return{...e,available_for_sale:((null==i?void 0:i.available_for_sale)??!1)&&n}}):null;return{...e,product_subtitle:n.product_subtitle??null,variant_sub_title:n.variant_sub_title??null,sku:n.sku??null,serving_size:n.serving_size??null,essence:n.essence??null,available_for_sale:n.available_for_sale??null,featured_image_override:n.featured_image_override??null,quantity_rule:n.quantity_rule??null,allow_option_swap:n.allow_option_swap??null,swap_option_label:n.swap_option_label??null,swap_option_description:n.swap_option_description??null,swap_options:o,selected_options:n.selected_options??null}}):e}function Fe(e,t,s,r=null){if(!Array.isArray(e)||0===e.length)return{};const i={},n=e=>{if(!e)return null;const t=String(e);return""===t?null:t},o=(e,s)=>{const r=null==s?void 0:s.subscription_id,i=r?t.get(Number(r)):null;return{...s,address_id:e.address_id,charge_id:e.charge_id,next_charge_scheduled_at:(null==i?void 0:i.next_charge_scheduled_at)??null,charge_interval_frequency:(null==i?void 0:i.charge_interval_frequency)??null,order_interval_frequency:(null==i?void 0:i.order_interval_frequency)??null,order_interval_unit:(null==i?void 0:i.order_interval_unit)??null}};for(const c of e){const e=(null==c?void 0:c.date)??null,t=(Array.isArray(null==c?void 0:c.orders)?c.orders:[]).filter(e=>n(null==e?void 0:e.charge_id));if(!t.length)continue;const a=t.flatMap(e=>e.line_items.map(t=>o(e,t)));if(!a.length)continue;const u=Te(a,s,r),d=new Map;for(const s of a){if(s.is_skipped)continue;const e=n(s.charge_id);e&&(d.has(s.address_id)||d.set(s.address_id,e))}for(const s of t){const t=n(s.charge_id);t&&(i[t]={...s,ship_date:e,line_items:[]})}for(const s of u){const e=s.is_skipped?d.get(s.address_id)??n(s.charge_id):n(s.charge_id);if(!e)continue;const t=i[e];t&&t.line_items.push(s)}}const a={};for(const[c,u]of Object.entries(i))u.line_items.length&&(a[c]={...u,can_skip_line_items:m(u.line_items)});return a}function Ee(e){return"string"==typeof e&&/^\d{4}-\d{2}-\d{2}$/.test(e)}function xe(e){return"string"==typeof e&&e.trim().length>0}function Ve(e={}){return{first_name:e.first_name??e.firstName??null,last_name:e.last_name??e.lastName??null,address1:e.address1??null,address2:e.address2??null,city:e.city??null,province:e.province??e.state??null,zip:e.zip??e.postal_code??e.postalCode??null,country_code:e.country_code??e.countryCode??e.country??null,phone:e.phone??null,company:e.company??null}}function je(e){if(null==e)return null;if("object"==typeof e&&xe(null==e?void 0:e.ecommerce))return{ecommerce:String(e.ecommerce)};if("string"==typeof e||"number"==typeof e){const t=String(e).trim();return t?{ecommerce:t}:null}return null}const Pe={ok:!0},Ge={ok:!1};let Me=class extends o{constructor(){super(),this.bootstrapScope="full",this.session=null,this.sessionStatus="pending",this.subscriptions=[],this.addresses=[],this.orders=[],this.subscriptionOrders={},this.onTheWayOrders=[],this.chargeDiscounts={},this.chargeGifts={},this._giftSourceCharges=null,this.lastDroppedDiscountCode={},this.chargeDiscountTotals={},this.chargeDiscountWrites={},this.reconcileSuppressionDepth=new Map,this.hydratingChargeDiscounts=new Map,this.creditSummary=null,this.variantEnrichmentData=null,this.recommendedProducts=[],this.customer=null,this.deliverySchedule=[],this.essenceFlavorIcons=window.recharge.essenceFlavorIcons??[],this.loading=!0,this.locked=!1,this.error=null,this.ordersLoading=!0,this.chargeGiftsLoading=!0,this.creditLoading=!0,this.onTheWayLoading=!0,this.swapVariantStock=null,this.swapVariantStockPending=!1,this._swapVariantStockInFlight=0,this._variantEnrichmentLoaded=!1,this._recommendedProductsLoaded=!1,this._swapVariantStockRequested=new Set,this._ordersLoader=ne(()=>this.fetchOrders()),this._chargeGiftsLoader=ne(()=>this.fetchChargeGifts()),this._creditLoader=ne(()=>this.fetchCreditSummary()),this._onTheWayLoader=ne(()=>this.fetchOnTheWayOrders()),this._unregisterLiveSessionHandler=null,this.contextValue={state:{session:null,sessionStatus:"pending",subscriptions:[],addresses:[],orders:[],onTheWayOrders:[],subscriptionOrders:{},chargeDiscounts:{},chargeGifts:{},lastDroppedDiscountCode:{},variantEnrichmentData:null,recommendedProducts:[],customer:null,deliverySchedule:[],essenceFlavorIcons:[],loading:!0,locked:!1,error:null,swapVariantStockPending:!1,ordersLoading:!0,creditLoading:!0,onTheWayLoading:!0,chargeGiftsLoading:!0},actions:{refresh:async()=>{},cancelSubscription:async()=>Pe,activateSubscription:async()=>Pe,rescheduleCharge:async()=>Pe,claimFreeGift:async()=>Ge,createSubscription:async()=>Pe,getCancelSubscriptionUrl:async()=>({...Pe,url:null}),updateSubscription:async()=>Pe,skipCharge:async()=>Pe,unskipCharge:async()=>Pe,applyDiscountToCharge:async()=>({...Pe,discounts:[],totalDiscounts:"0.00"}),removeDiscountsFromCharge:async()=>Pe,dismissDroppedDiscountCode:()=>{},hydrateChargeDiscounts:async()=>({...Pe,discounts:[]}),createAddress:async()=>Pe,updateAddress:async()=>Pe,deleteAddress:async()=>Pe,getEssenceFlavorIconByName:()=>null,showConfirmation:()=>{},ensureOrders:async()=>{},ensureCredit:async()=>{},ensureOnTheWay:async()=>{},ensureChargeGifts:async()=>{}}},this._minimalBootstrapForAddToSubRequested=!1,this._rumStageDurations={},this._rumFailedLegs=[],this._rumSoftFailures=[],this._rumEmitted=!1,this._rumSessionCacheHit=!1,this._rumAccountCacheHit=!1,this._rumBackgroun
1dRevalidateEmitted=!1,this._suppressPendingFlash=!1,this.contextValue={...this.contextValue,actions:{refresh:async()=>(this._ordersLoader.reset(),this._creditLoader.reset(),this._onTheWayLoader.reset(),this._chargeGiftsLoader.reset(),this.bootstrap()),cancelSubscription:async e=>this.handleCancelSubscription(e),activateSubscription:async e=>this.handleActivateSubscription(e),rescheduleCharge:async e=>this.handleRescheduleCharge(e),claimFreeGift:async e=>this.handleClaimFreeGift(e),getCancelSubscriptionUrl:async(e,t)=>this.getCancelSubscriptionUrl(e,t),createSubscription:async e=>this.handleCreateSubscription(e),updateSubscription:async(e,t,s,r)=>this.handleUpdateSubscription(e,t,s,r),skipCharge:async(e,t,s,r)=>this.handleSkipCharge(e,t,s,r),unskipCharge:async(e,t,s,r)=>this.handleUnskipCharge(e,t,s,r),applyDiscountToCharge:async e=>this.handleApplyDiscountToCharge(e),removeDiscountsFromCharge:async e=>this.handleRemoveDiscountsFromCharge(e),dismissDroppedDiscountCode:e=>this.clearDroppedDiscountCode(e),hydrateChargeDiscounts:async e=>this.handleHydrateChargeDiscounts(e),createAddress:async e=>this.handleCreateAddress(e),updateAddress:async e=>this.handleUpdateAddress(e),deleteAddress:async e=>this.handleDeleteAddress(e),getEssenceFlavorIconByName:e=>l(this.essenceFlavorIcons,e),showConfirmation:(e,...t)=>this.showConfirmation(e,...t),ensureOrders:async()=>this.ensureOrders(),ensureCredit:async()=>this.ensureCredit(),ensureOnTheWay:async()=>this.ensureOnTheWay(),ensureChargeGifts:async()=>this.ensureChargeGifts()}}}connectedCallback(){var e,t;if(super.connectedCallback(),this.hydrateFromAddToSubEligibilityCache(),"full"!==this.bootstrapScope)return this.loading=!1,void this.settleLazyLegs();this.clearMarkSafe("rc-bootstrap:total:start"),this.markSafe("rc-bootstrap:total:start"),null==(e=this._unregisterLiveSessionHandler)||e.call(this),this._unregisterLiveSessionHandler=(t=({session:e,durationMs:t,demote:s})=>this.handleLiveSessionResult(e,t,s),Le.add(t),()=>Le.delete(t)),this.timeLeg("variant-enrichment",()=>this.ensureVariantEnrichmentData()),this.hydrateFromAccountCache(),this.bootstrap({updateLoading:!this._rumAccountCacheHit})}hydrateFromAddToSubEligibilityCache(){const e=function(e){return J({prefix:Z,schemaVersion:1,ttlMs:18e5,customerId:e,validatePayload:ee})}(window.recharge.customer.id);if(e&&(this.sessionStatus=e.sessionStatus,this.subscriptions=e.subscriptions,"authenticated"===e.sessionStatus)){const e=me(window.recharge.customer.id);e&&(this.session=e)}}ensureMinimalBootstrapForAddToSub(){"minimal"===this.bootstrapScope&&(this._minimalBootstrapForAddToSubRequested||"unauthenticated"!==this.sessionStatus&&(this.session||(this._minimalBootstrapForAddToSubRequested=!0,this.bootstrap({updateLoading:!1}))))}hydrateFromAccountCache(){var e,t,s,r;const i=window.recharge.customer.id,n=function(e){return J({prefix:oe,schemaVersion:1,ttlMs:18e4,customerId:e,validatePayload:ue})}(i);if(!n)return;this._rumAccountCacheHit=!0,this._suppressPendingFlash=!0;const o=me(i);o?(this._rumSessionCacheHit=!0,this.session=o,this.sessionStatus=o.customerId?"authenticated":"unauthenticated"):this.sessionStatus="authenticated",this.customer=n.customer,this.subscriptions=(null==(t=null==(e=n.customer)?void 0:e.include)?void 0:t.subscriptions)??[],this.addresses=(null==(r=null==(s=n.customer)?void 0:s.include)?void 0:r.addresses)??[],this.deliverySchedule=n.deliverySchedule,this.variantEnrichmentData=n.variantEnrichmentData,this.subscriptionOrders=Fe(n.deliverySchedule,Oe(n.customer),n.variantEnrichmentData,null),this.ensureSwapVariantStock(),this.loading=!1,this.emitBootstrapRum({errored:!1,partial:!1})}disconnectedCallback(){var e;super.disconnectedCallback(),null==(e=this._unregisterLiveSessionHandler)||e.call(this),this._unregisterLiveSessionHandler=null}handleLiveSessionResult(e,t,s){if(this._rumStageDurations["login-retry"]=t,e)return this.session=e,void(this.sessionStatus=e.customerId?"authenticated":"unauthenticated");this._rumFailedLegs.push("login-retry"),s&&(this.session=null,this.sessionStatus="error")}get isMinimalBootstrap(){return"minimal"===this.bootstrapScope}syncContextValue(){const e=this.customer?this.creditSummary?{...this.customer,credit_summary:this.creditSummary}:this.customer:null;this.contextValue={...this.contextValue,state:{session:this.session,sessionStatus:this.sessionStatus,subscriptions:this.subscriptions,addresses:this.addresses,orders:this.orders,onTheWayOrders:this.onTheWayOrders,subscriptionOrders:this.subscriptionOrders,chargeDiscounts:this.chargeDiscounts,chargeGifts:this.chargeGifts,lastDroppedDiscountCode:this.lastDroppedDiscountCode,variantEnrichmentData:this.variantEnrichmentData,swapVariantStockPending:this.swapVariantStockPending,recommendedProducts:this.recommendedProducts,customer:e,deliverySchedule:this.deliverySchedule,essenceFlavorIcons:this.essenceFlavorIcons,loading:this.loading,locked:this.locked,error:this.error,ordersLoading:this.ordersLoading,creditLoading:this.creditLoading,onTheWayLoading:this.onTheWayLoading,chargeGiftsLoading:this.chargeGiftsLoading}}}willUpdate(e){super.willUpdate(e),this.syncContextValue(),window.recharge.debugMode&&console.log("[
1SubscriptionsController] context state:",this.contextValue.state)}updated(e){super.updated(e),this.handleSubscriptionsPageRedirect(),this.dispatchControllerUpdatedIfRelevant(e)}dispatchControllerUpdatedIfRelevant(e){Me.RELEVANT_BRIDGE_PROPS.some(t=>e.has(t))&&document.dispatchEvent(new CustomEvent("subscriptions-controller:updated",{bubbles:!0}))}handleSubscriptionsPageRedirect(){var e;if(null==(e=window.Shopify)?void 0:e.designMode)return;if(this.loading||this.error||"/pages/account/subscriptions"!==window.location.pathname)return;const t=this.subscriptionOrders??{};if(1!==Object.keys(t).length)return;const s=Object.values(t)[0];window.location.replace(`/pages/account/subscription?chargeId=${s.charge_id}`)}async ensureOnTheWay(){this.session&&await this._onTheWayLoader.ensure()}async fetchOnTheWayOrders(){this.onTheWayLoading=!0;try{await this.timeLazyLeg("on-the-way-orders",async e=>{const t=await fetch("/apps/api/on-the-way-orders",{method:"GET",headers:{Accept:"application/json"},credentials:"same-origin",cache:"no-store"});if(!t.ok)return console.error("[OnTheWayOrders] HTTP error",t.status,await t.text()),e(),void(this.onTheWayOrders=[]);const s=await t.json();this.onTheWayOrders=(null==s?void 0:s.orders)??[]})}catch(e){console.error("[OnTheWayOrders] fetch failed:",e),this.onTheWayOrders=[]}finally{this.onTheWayLoading=!1,this.dispatchOnTheWayOrdersUpdated()}}dispatchOnTheWayOrdersUpdated(){document.dispatchEvent(new CustomEvent("subscriptions-controller:on-the-way-orders-updated",{detail:{orders:this.onTheWayOrders},bubbles:!0}))}async ensureChargeGifts(){this.session&&await this._chargeGiftsLoader.ensure()}async fetchChargeGifts(){var e;const t=this.session;if(t){this.chargeGiftsLoading=!0;try{const{charges:s}=await this.timeLazyLeg("charge-gifts",()=>b(t,{status:["queued"],limit:250}));this._giftSourceCharges=s??[],this.chargeGifts=le(this._giftSourceCharges,this.variantEnrichmentData,null==(e=window.recharge)?void 0:e.giftValues)}catch(s){console.error("[Recharge] ensureChargeGifts error",s),this._giftSourceCharges=null,this.chargeGifts={}}finally{this.chargeGiftsLoading=!1}}}async ensureVariantEnrichmentData(){var e;if(!this._variantEnrichmentLoaded){this._variantEnrichmentLoaded=!0;try{const t=await fetch("/apps/api/get-variant-enrichment-data",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Variant enrichment request failed: ${t.status}`);const s=await t.json();this.variantEnrichmentData=s,this.rederiveSubscriptionOrders(),this.ensureSwapVariantStock(),this._giftSourceCharges&&(this.chargeGifts=le(this._giftSourceCharges,this.variantEnrichmentData,null==(e=window.recharge)?void 0:e.giftValues))}catch(t){console.error("[VariantEnrichment] error",t);try{this._rumSoftFailures.push("variant-enrichment")}catch{}}}}rederiveSubscriptionOrders(){if(!Array.isArray(this.deliverySchedule)||!this.customer)return;const e=Oe(this.customer);this.subscriptionOrders=Fe(this.deliverySchedule,e,this.variantEnrichmentData,this.swapVariantStock)}async ensureSwapVariantStock(){const e=function(e){if(!e)return[];const t=new Set;for(const s of Object.values(e))if(null==s?void 0:s.allow_option_swap)for(const e of s.swap_options??[]){const{id:s}=d(e.variant_id);s&&t.add(s)}return[...t]}(this.variantEnrichmentData).filter(e=>!this._swapVariantStockRequested.has(e));if(e.length){e.forEach(e=>this._swapVariantStockRequested.add(e)),this._swapVariantStockInFlight+=1,this.swapVariantStockPending=!0;try{await this.timeLazyLeg("swap-variant-stock",async()=>{const t=await async function(e,{fetchImpl:t=fetch,accessToken:s=window.__STOREFRONT_ACCESS_TOKEN__,routeRoot:r=(e=>{return null==(e=null==(t=window.Shopify)?void 0:t.routes)?void 0:e.root;var t})()??"/"}={}){var i,n;const o=[...new Set(e.filter(Boolean))];if(!o.length)return{};if(!s)throw new Error("Storefront access token is not configured");const a=`${"/"===r?"":r}/api/2026-01/graphql.json`,c={};for(const u of(e=>{const t=[];for(let s=0;s<e.length;s+=250)t.push(e.slice(s,s+250));return t})(o)){const e=await t(a,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":s},body:JSON.stringify({query:"\n query SwapVariantStock($ids: [ID!]!) {\n nodes(ids: $ids) {\
1n ... on ProductVariant {\n id\n availableForSale\n currentlyNotInStock\n }\n }\n }\n",variables:{ids:u.map(_e)}})});if(!e.ok)throw new Error(`Storefront variant stock request failed: ${e.status}`);const r=await e.json();if(null==(i=r.errors)?void 0:i.length)throw new Error(`Storefront variant stock query errored: ${r.errors.map(e=>e.message).join("; ")}`);Object.assign(c,ye(u,(null==(n=r.data)?void 0:n.nodes)??[]))}return c}(e);this.swapVariantStock={...this.swapVariantStock??{},...t},this.rederiveSubscriptionOrders()})}catch(t){console.warn("[SwapVariantStock] error",t)}finally{this._swapVariantStockInFlight-=1,this.swapVariantStockPending=this._swapVariantStockInFlight>0}}}async ensureRecommendedProducts(){if(!this._recommendedProductsLoaded&&this.customer){this._recommendedProductsLoaded=!0;try{const e=function(e){var t;const s=null==(t=null==e?void 0:e.include)?void 0:t.subscriptions;if(!Array.isArray(s)||0===s.length)return[];const r=s.filter(e=>"active"===String(null==e?void 0:e.status).toLowerCase()).map(e=>{var t;return String((null==(t=null==e?void 0:e.external_product_id)?void 0:t.ecommerce)??"").trim()}).filter(Boolean);return Array.from(new Set(r))}(this.customer);if(window.recharge.debugMode&&console.log("[Recs] sending productIds:",e),!e.length)return void(this.recommendedProducts=[]);const t=await fetch("/apps/api/product-recommendations-batch",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({productIds:e,intent:"RELATED",countryCode:window.recharge.countryCode})});if(!t.ok)throw new Error(`Recommendations request failed: ${t.status}`);const s=await t.json();window.recharge.debugMode&&console.log("[Recs] response json:",s),this.recommendedProducts=Array.isArray(null==s?void 0:s.products)?_(s.products):[]}catch(e){console.error("[Recs] error",e),this.recommendedProducts=[]}}}async fetchDeliverySchedule(){const e=this.session;return e?S(e,{future_interval:y}):[]}async ensureOrders(){this.session&&await this._ordersLoader.ensure()}async fetchOrders(){const e=this.session;if(e){this.ordersLoading=!0;try{const{orders:t}=await this.timeLazyLeg("orders",()=>w(e,{limit:1,sort_by:"processed_at-desc"}));this.orders=t}catch(t){console.error("[Recharge] ensureOrders error",t),this.orders=[]}finally{this.ordersLoading=!1}}}async ensureCredit(){this.session&&await this._creditLoader.ensure()}async fetchCreditSummary(){const e=this.session;if(e){this.creditLoading=!0;try{this.creditSummary=await this.timeLazyLeg("credit-summary",()=>C(e))}catch(t){console.error("[Recharge] ensureCredit error",t)}finally{this.creditLoading=!1}}}markSafe(e){try{performance.mark(e)}catch{}}clearMarkSafe(e){try{performance.clearMarks(e)}catch{}}recordStageDuration(e,t,s){try{const r=performance.measure(`rc-bootstrap:${e}`,t,s);if(!r)return;this._rumStageDurations[e]=Math.round(r.duration)}catch{}}async timeLeg(e,t){const s=`rc-bootstrap:${e}:start`,r=`rc-bootstrap:${e}:end`;this.markSafe(s);try{const i=await t();return this.markSafe(r),this.recordStageDuration(e,s,r),i}catch(i){this.markSafe(r),this.recordStageDuration(e,s,r);try{this._rumFailedLegs.push(e)}catch{}throw i}}settleLazyLegs(){this.ordersLoading=!1,this.creditLoading=!1,this.onTheWayLoading=!1,this.chargeGiftsLoading=!1}async timeLazyLeg(e,t){const s=`rc-bootstrap:${e}:start`,r=`rc-bootstrap:${e}:end`;this.markSafe(s);let i=!1;const n=()=>{i=!0};try{const o=await t(n);return this.markSafe(r),this.emitLazyLegRum({leg:e,durationMs:this.measureMs(e,s,r),failed:i}),o}catch(o){throw this.markSafe(r),this.emitLazyLegRum({leg:e,durationMs:this.measureMs(e,s,r),failed:!0}),o}}measureMs(e,t,s){try{const r=performance.measure(`rc-bootstrap:${e}`,t,s);return r?Math.round(r.duration):0}catch{return 0}}emitLazyLegRum({leg:e,durationMs:t,failed:s}){if("full"===this.bootstrapScope)try{const r=window.amplitude;if("function"!=typeof(null==r?void 0:r.track))return;r.track("account_bootstrap_lazy_leg",{leg:e,pathname:window.location.pathname,durationMs:t,failed:s})}catch{}}emitBootstrapRum({errored:e,partial:t=!1}){if("full"===this.bootstrapScope)if(this._rumEmitted)this.emitBackgroun
1dRevalidateRum({errored:e,partial:t});else{this._rumEmitted=!0;try{this.markSafe("rc-bootstrap:total:end"),this.recordStageDuration("total","rc-bootstrap:total:start","rc-bootstrap:total:end");const s=window.amplitude;if("function"!=typeof(null==s?void 0:s.track))return;s.track("account_bootstrap",{rumSchemaVersion:4,blockingLegs:["customer","delivery-schedule"],bootstrapScope:this.bootstrapScope,pathname:window.location.pathname,errored:e,partial:t,failedLegs:[...this._rumFailedLegs],softFailures:[...this._rumSoftFailures],durationsMs:{...this._rumStageDurations},sessionCacheHit:this._rumSessionCacheHit,hydratedFromCache:this._rumAccountCacheHit})}catch{}}}emitBackgroundRevalidateRum({errored:e,partial:t}){if(this._rumAccountCacheHit&&!this._rumBackgroundRevalidateEmitted){this._rumBackgroundRevalidateEmitted=!0;try{const s=window.amplitude;if("function"!=typeof(null==s?void 0:s.track))return;const r={...this._rumStageDurations};delete r.total,this.markSafe("rc-bootstrap:revalidate:end"),s.track("account_bootstrap_background_revalidate",{pathname:window.location.pathname,errored:e,partial:t,failedLegs:[...this._rumFailedLegs],softFailures:[...this._rumSoftFailures],durationsMs:{...r,total:this.measureMs("revalidate-total","rc-bootstrap:total:start","rc-bootstrap:revalidate:end")}})}catch{}}}async bootstrap({updateLoading:e=!0}={}){var t,s,r,i;try{e&&(this.loading=!0),this.error=null;const o="authenticated"===this.sessionStatus&&null!=this.session||this._suppressPendingFlash;this._suppressPendingFlash=!1,o||(this.sessionStatus="pending");try{const e=window.recharge.customer.id,t=me(e);t?(this._rumSessionCacheHit=!0,this.session=t):(this._rumSessionCacheHit=!1,this.session=await this.timeLeg("login",()=>D()),fe(e,this.session)),this.sessionStatus=this.session.customerId?"authenticated":"unauthenticated"}catch(n){return console.error("Failed to get customer session: ",n),this.session=null,this.sessionStatus="error",e&&(this.loading=!1),this.settleLazyLegs(),void this.emitBootstrapRum({errored:!0})}if("authenticated"!==this.sessionStatus)return te(window.recharge.customer.id,{sessionStatus:this.sessionStatus,subscriptions:[]}),e&&(this.loading=!1),this.settleLazyLegs(),void this.emitBootstrapRum({errored:!1});const a=this.session,c=this.isMinimalBootstrap?Ie:Re,[u,d]=await Promise.allSettled([this.timeLeg("customer",()=>L(a,{include:c})),this.timeLeg("delivery-schedule",()=>this.fetchDeliverySchedule())]),{fatal:l,partial:h}=function({customerResult:e,deliveryScheduleResult:t}){const s="rejected"===e.status;return{fatal:s,partial:s||"rejected"===t.status}}({customerResult:u,deliveryScheduleResult:d});if(l)return console.error("[Recharge] bootstrap customer fetch failed","rejected"===u.status?u.reason:null),this.customer=null,this.subscriptions=[],this.addresses=[],this.deliverySchedule=[],this.subscriptionOrders={},this.error="rejected"===u.status?u.reason:null,e&&(this.loading=!1),void this.emitBootstrapRum({errored:!0,partial:h});this.customer="fulfilled"===u.status?u.value??null:null,this.subscriptions=(null==(s=null==(t=this.customer)?void 0:t.include)?void 0:s.subscriptions)||[],this.addresses=(null==(i=null==(r=this.customer)?void 0:r.include)?void 0:i.addresses)||[],"fulfilled"===d.status?this.deliverySchedule=d.value:(console.error("[Recharge] bootstrap delivery-schedule fetch failed",d.reason),this.deliverySchedule=[]);const p=Oe(this.customer);this.subscriptionOrders=Fe(this.deliverySchedule,p,this.variantEnrichmentData,this.swapVariantStock),this.reconcileChargeDiscounts({partial:h}),this.isMinimalBootstrap||h||function(e,t){var s,r,i,n,o,a;Q({prefix:oe,schemaVersion:1,customerId:e,payload:{customer:(i=t.customer,i?{id:i.id,analytics_data:i.analytics_data,apply_credit_to_next_recurring_charge:i.apply_credit_to_next_recurring_charge,apply_credit_to_next_recurring_charge_channel:i.apply_credit_to_next_recurring_charge_channel,backup_payment_methods_enabled:i.backup_payment_methods_enabled,can_add_payment_method:i.can_add_payment_method,created_at:i.created_at,email:i.email,external_customer_id:i.external_customer_id,first_charge_processed_at:i.first_charge_processed_at,first_name:i.first_name,has_payment_method_in_dunning:i.has_payment_method_in_dunning,has_valid_payment_method:i.has_valid_payment_method,hash:i.hash,last_name:i.last_name,payment_method_fallback_on_failure_disabled:i.payment_method_fallback_on_failure_disabled,phone:i.phone,subscription_related_charge_streak:i.subscription_related_charge_streak,subscriptions_active_count:i.subscriptions_active_count,subscriptions_total_count:i.subscriptions_total_count,tax_exempt:i.tax_exempt,updated_at:i.updated_at,include:{addresses:null==(n=i.include)?void 0:n.addresses,subscriptions:null==(o=i.include)?void 0:o.subscriptions,referral_info:null==(a=i.include)?void 0:a.referral_info}}:null),deliverySchedule:(r=t.deliverySchedule,Array.isArray(r)?r.map(e=>({...e,orders:Array.isArray(null==e?void 0:e.orders)?e.orders.map(e=>ce(e)):null==e?void 0:e.orders})):[]),subscriptionOrders:(s=t.subscriptionOrders,s&&"object"==typeof s?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ce(t)])):s),variantEnrichmentData:t.variantEnrichmentData}})}(window.recharge.customer.id,{customer:this.customer,deliverySchedule:this.deliverySchedule,subscriptionOrders:Fe(this.deliverySchedule,p,this.variantEnrichmentData,null),variantEnrichmentData:this.variantEnrichmentData}),te(window.recharge.customer.id,{sessionStatus:this.sessionStatus,subscriptions:this.subscriptions}),this.isMinimalBootstrap?(this.orders=[],this.onTheWayOrders=[],this.ordersLoading=!1,this.creditLoading=!1,this.onTheWayLoading=!1,this.chargeGiftsLoading=!1):this.ensureRecommendedProducts(),e&&(this.loading=!1),this.emitBootstrapRum({errored:!1,partial:h})}catch(n){console.error("[Recharge] bootstrap error",n),this.error=n,e&&(this.loading=!1),this.emitBootstrapRum({errored:!0,partial:!0})}finally{this.syncWindowSubscriberFlag()}}async handleCancelSubscription(e){const t=null==e?void 0:e.subscriptionId;if(!t)return console.warn("[SubscriptionsController] cancel missing subscriptionId"),Ge;const s=(null==e?void 0:e.reason)||"No longer needed",r="boolean"!=typeof(null==e?void 0:e.send_email)||e.send_email;return this.withLock(async()=>
1{if(!this.session)return console.warn("customer session missing"),Ge;try{return this.error=null,await k(this.session,t,{cancellation_reason:s,send_email:r}),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] cancelSubscription error",e),this.error=e,Ge}})}async handleActivateSubscription(e){const t=null==e?void 0:e.subscriptionId;return t?this.withLock(async()=>{if(!this.session)return console.warn("customer session missing"),Ge;try{return this.error=null,await A(this.session,t),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] activateSubscription error",e),this.error=e,Ge}}):(console.warn("[SubscriptionsController] activate missing subscriptionId"),Ge)}async handleRescheduleCharge(e){const t=null==e?void 0:e.chargeId,s=null==e?void 0:e.date;return t?s&&Ee(s)?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] reschedule missing session"),Ge;try{this.error=null;const e=await I(this.session,Number(t),String(s));return this.commitChargeDiscountsFromCharge(t,e),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] rescheduleCharge error",e),this.error=e,Ge}}):(console.warn("[SubscriptionsController] reschedule missing/invalid date (YYYY-MM-DD)",s),Ge):(console.warn("[SubscriptionsController] reschedule missing chargeId"),Ge)}async handleClaimFreeGift(e){const t=function(e){if("number"!=typeof e&&"string"!=typeof e)return null;const t=String(e).trim();return se.test(t)?t:null}(null==e?void 0:e.chargeId);return t?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] claimFreeGift missing session"),Ge;try{this.error=null;const e=await async function(e,t=(e,t)=>fetch(e,t)){const s=await t("/apps/api/claim-free-gift",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",cache:"no-store",body:JSON.stringify({chargeId:e})});if(s.ok){const e=await re(s);return{ok:!0,status:s.status,chargeId:ie(null==e?void 0:e.chargeId),tagged:"boolean"==typeof(null==e?void 0:e.tagged)?e.tagged:null,giftLineCount:"number"==typeof(null==e?void 0:e.giftLineCount)?e.giftLineCount:null}}if(s.status>=500)return{ok:!1,status:s.status,code:null,message:null};const r=await re(s);return{ok:!1,status:s.status,code:ie(null==r?void 0:r.code),message:ie(null==r?void 0:r.error)}}(t);return e.ok?(!1===e.tagged&&console.error("[ClaimFreeGift] gift added but the claimed tag was not written",{chargeId:t}),(e.giftLineCount??0)>1&&console.error("[ClaimFreeGift] charge carries more than one gift",{chargeId:t,giftLineCount:e.giftLineCount}),this._chargeGiftsLoader.reset(),await this.bootstrap({updateLoading:!1}),{...Pe,chargeId:Number(t)}):(console.warn("[ClaimFreeGift] claim rejected",{chargeId:t,status:e.status,code:e.code,message:e.message}),{...Ge,status:e.status,code:e.code??void 0,message:e.message??void 0})}catch(e){return console.error("[ClaimFreeGift] request failed",e),this.error=e,Ge}}):(console.warn("[SubscriptionsController] claimFreeGift missing/invalid chargeId",null==e?void 0:e.chargeId),Ge)}async handleCreateSubscription(e){const t=(null==e?void 0:e.address_id)??(null==e?void 0:e.addressId)??(null==e?void 0:e.addressID),s=null==e?void 0:e.quantity,r=(null==e?void 0:e.plan_id)??(null==e?void 0:e.planId),i=(null==e?void 0:e.external_variant_id)??(null==e?void 0:e.externalVariantId)??(null==e?void 0:e.variant_id)??(null==e?void 0:e.variantId),n=(null==e?void 0:e.external_product_id)??(null==e?void 0:e.externalProductId)??(null==e?void 0:e.product_id)??(null==e?void 0:e.productId),o=je(i),a=je(n),c=(null==e?void 0:e.charge_interval_frequency)??(null==e?void 0:e.chargeIntervalFrequency),u=(null==e?void 0:e.order_interval_frequency)??(null==e?void 0:e.orderIntervalFrequency),d=(null==e?void 0:e.order_interval_unit)??(null==e?void 0:e.orderIntervalUnit),l=(null==e?void 0:e.next_charge_scheduled_at)??(null==e?void 0:e.nextChargeScheduledAt);if(!t||"number"!=typeof t)return console.warn("[SubscriptionsController] createSubscription missing address_id"),Ge;if(!s||"number"!=typeof s)return console.warn("[SubscriptionsController] createSubscription missing quantity"),Ge;if(!o)return console.warn("[SubscriptionsController] createSubscription missing external_variant_id"),Ge;const h="number"==typeof r&&Number.isFinite(r),p="number"==typeof c&&"number"==typeof u&&xe(d);return h||p?l&&!Ee(String(l))?(console.warn("[SubscriptionsController] createSubscription invali
1d next_charge_scheduled_at (YYYY-MM-DD)",l),Ge):this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] createSubscription missing session"),Ge;try{this.error=null;const i={address_id:Number(t),quantity:Number(s),external_variant_id:o,...a?{external_product_id:a}:{},...h?{plan_id:Number(r)}:{},...h?{}:{charge_interval_frequency:Number(c),order_interval_frequency:Number(u),order_interval_unit:String(d)},...l?{next_charge_scheduled_at:String(l)}:{},...Array.isArray(null==e?void 0:e.properties)?{properties:e.properties}:{}};return await R(this.session,i,{commit:!0}),await this.bootstrap({updateLoading:!1}),this._recommendedProductsLoaded=!1,this.ensureRecommendedProducts(),Pe}catch(i){return console.error("[Recharge] createSubscription error",i),this.error=i,Ge}}):(console.warn("[SubscriptionsController] createSubscription missing cadence: provide plan_id OR (charge_interval_frequency + order_interval_frequency + order_interval_unit)"),Ge)}async getCancelSubscriptionUrl(e,t=new URL("/pages/account/subscriptions",window.location.origin).toString()){return e?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] getCancelSubscriptionUrl missing session"),{...Ge,url:null};try{this.error=null;const s=await O(this.session,e,t);return{...Pe,url:s}}catch(s){return console.error("[Recharge] getCancelSubscriptionUrl error",s),this.error=s,{...Ge,url:null}}}):(console.warn("[SubscriptionsController] subscriptionId missing"),{...Ge,url:null})}async handleCreateAddress(e){const t=Ve(e);return xe(t.address1)&&xe(t.zip)?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] createAddress missing session"),Ge;try{return this.error=null,await T(this.session,t),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] createAddress error",e),this.error=e,Ge}}):(console.warn("[SubscriptionsController] createAddress missing address1/zip"),Ge)}async handleUpdateAddress(e){const t=(null==e?void 0:e.addressId)??(null==e?void 0:e.id);if(!t)return console.warn("[SubscriptionsController] updateAddress missing addressId"),Ge;const s=Ve(e);return this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] updateAddress missing session"),Ge;try{return this.error=null,await F(this.session,Number(t),s,{commit:!0}),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] updateAddress error",e),this.error=e,{...Ge,...h(e)}}})}async handleDeleteAddress(e){const t=(null==e?void 0:e.addressId)??(null==e?void 0:e.id);return t?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] deleteAddress missing session"),Ge;try{return this.error=null,await E(this.session,Number(t)),await this.bootstrap({updateLoading:!1}),Pe}catch(e){return console.error("[Recharge] deleteAddress error",e),this.error=e,Ge}}):(console.warn("[SubscriptionsController] deleteAddress missing addressId"),Ge)}async handleUpdateSubscription(e,t,s=!0,r){return e?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] updateSubscription missing session"),Ge;try{return this.error=null,await x(this.session,e,t,r),await this.bootstrap({updateLoading:s}),Pe}catch(i){return console.error("[Recharge] updateSubscription error",i),this.error=i,Ge}}):(console.warn("[SubscriptionsController] updateSubscription missing subscriptionId"),Ge)}async handleSkipCharge(e,t,s,r=!0){return e&&(null==t?void 0:t.length)?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] skipCharge missing session"),Ge;try{this.error=null;const i=await V(this.session,e,t,s);return this.commitChargeDiscountsFromCharge(e,i),await this.bootstrap({updateLoading:r}),Pe}catch(i){return console.error("[Recharge] skipCharge error",i),this.error=i,Ge}}):(console.warn("[SubscriptionsController] skipCharge missing chargeId or purchaseItemIds"),Ge)}async handleUnskipCharge(e,t,s,r=!0){return e&&(null==t?void 0:t.length)?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] unskipCharge missing session"),Ge;try{this.error=null;const i=await j(this.session,e,t,s);return this.commitChargeDiscountsFromCharge(e,i),await this.bootstrap({updateLoading:r}),Pe}catch(i){return console.error("[Recharge] unskipCharge error",i),this.error=i,Ge}}):(console.warn("[SubscriptionsController] unskipCharge missing chargeId or purchaseItemIds"),Ge)}async handleApplyDiscountToCharge(e){var t;const s=null==e?void 0:e.chargeId,r=null==(t=null==e?void 0:e.code)?void 0:t.trim();return s?r?this.withLock(async()=>
1{if(!this.session)return console.warn("[SubscriptionsController] applyDiscountToCharge missing session"),Ge;try{this.error=null;const t=await P(this.session,s,r),i=t.discounts??[];return this.commitChargeDiscounts(s,i,t.total_discounts),this.clearDroppedDiscountCode(s),await this.withReconcileSuppressed(s,()=>this.bootstrap({updateLoading:(null==e?void 0:e.updateLoading)??!1})),{...Pe,discounts:i,totalDiscounts:t.total_discounts}}catch(t){return console.error("[Recharge] applyDiscountToCharge error",t),this.error=t,{...Ge,...p(t)}}}):(console.warn("[SubscriptionsController] applyDiscountToCharge missing code"),Ge):(console.warn("[SubscriptionsController] applyDiscountToCharge missing chargeId"),Ge)}async handleRemoveDiscountsFromCharge(e){const t=null==e?void 0:e.chargeId;return t?this.withLock(async()=>{if(!this.session)return console.warn("[SubscriptionsController] removeDiscountsFromCharge missing session"),Ge;try{this.error=null;const s=await G(this.session,t);return this.commitChargeDiscounts(t,s.discounts??[],s.total_discounts),this.clearDroppedDiscountCode(t),await this.withReconcileSuppressed(t,()=>this.bootstrap({updateLoading:(null==e?void 0:e.updateLoading)??!1})),Pe}catch(s){return console.error("[Recharge] removeDiscountsFromCharge error",s),this.error=s,{...Ge,...p(s)}}}):(console.warn("[SubscriptionsController] removeDiscountsFromCharge missing chargeId"),Ge)}async handleHydrateChargeDiscounts(e){if(!e)return console.warn("[SubscriptionsController] hydrateChargeDiscounts missing chargeId"),Ge;const t=String(e),s=this.hydratingChargeDiscounts.get(t);if(s)return s;const r=this.session;if(!r)return console.warn("[SubscriptionsController] hydrateChargeDiscounts missing session"),Ge;const i=this.fetchChargeDiscounts(r,t,e);this.hydratingChargeDiscounts.set(t,i);try{return await i}finally{this.hydratingChargeDiscounts.delete(t)}}async fetchChargeDiscounts(e,t,s){const r=this.chargeDiscountWrites[t]??0;try{const i=await M(e,s),n=i.discounts??[];return(this.chargeDiscountWrites[t]??0)!==r?{...Pe,discounts:this.chargeDiscounts[t]??[]}:(this.commitChargeDiscounts(t,n,i.total_discounts),{...Pe,discounts:n})}catch(i){return console.error("[Recharge] getCharge (discount hydration) error",i),{...Ge,...p(i)}}}reconcileChargeDiscounts({partial:e}){var t;if(e)return;const s=Object.keys(this.chargeDiscounts);if(!s.length)return;const r={...this.chargeDiscounts},i={...this.lastDroppedDiscountCode};let n=!1;for(const o of s){if(this.reconcileSuppressionDepth.has(o))continue;const e=this.chargeDiscounts[o];if(!(null==e?void 0:e.length))continue;const s=this.subscriptionOrders[o];if(!s){delete r[o],delete this.chargeDiscountTotals[o],n=!0;continue}if(s.has_uncommitted_changes)continue;if(0!==Number(s.total_discounts))continue;if(e.some(e=>"shipping"===e.value_type))continue;if(!(Number(this.chargeDiscountTotals[o])>0))continue;const a=null==(t=e[0])?void 0:t.code;a&&(i[o]=a),delete r[o],delete this.chargeDiscountTotals[o],n=!0}n&&(this.chargeDiscounts=r,this.lastDroppedDiscountCode=i)}async withReconcileSuppressed(e,t){const s=String(e);this.reconcileSuppressionDepth.set(s,(this.reconcileSuppressionDepth.get(s)??0)+1);try{await t()}finally{const e=(this.reconcileSuppressionDepth.get(s)??1)-1;e>0?this.reconcileSuppressionDepth.set(s,e):this.reconcileSuppressionDepth.delete(s)}}clearDroppedDiscountCode(e){const t=String(e);if(!(t in this.lastDroppedDiscountCode))return;const s={...this.lastDroppedDiscountCode};delete s[t],this.lastDroppedDiscountCode=s}commitChargeDiscounts(e,t,s){const r=String(e);this.chargeDiscounts={...this.chargeDiscounts,[r]:t},this.chargeDiscountTotals[r]=s,this.chargeDiscountWrites[r]=(this.chargeDiscountWrites[r]??0)+1}forgetChargeDiscounts(e){const t=String(e);if(this.chargeDiscountWrites[t]=(this.chargeDiscountWrites[t]??0)+1,delete this.chargeDiscountTotals[t],!(t in this.chargeDiscounts))return;const s={...this.chargeDiscounts};delete s[t],this.chargeDiscounts=s}commitChargeDiscountsFromCharge(e,t){var s;if(!Array.isArray(null==t?void 0:t.discounts))return;const r=String(e),i=null==t.id?r:String(t.id),n=this.chargeDiscounts[r];if(t.discounts.length?this.commitChargeDiscounts(i,t.discounts,t.total_discounts):this.forgetChargeDiscounts(i),i!==r&&this.forgetChargeDiscounts(r),!(null==n?void 0:n.length)||t.discounts.length)return;const o=null==(s=n[0])?void 0:s.code;o&&(this.lastDroppedDiscountCode={...this.lastDroppedDiscountCode,[r]:o,[i]:o})}async withLock(e){this.locked=!0;try{return await e()}finally{this.locked=!1}}syncWindowSubscriberFlag(){const e=g({loading:this.loading,sessionStatus:this.sessionStatus,error:this.error,subscriptions:this.subscriptions,subscriptionOrders:this.subscriptionOrders});"preserve"!==e&&(window.recharge.customer.isSubscriber="show"===e)}render(){return U`<slot></slot>`}showConfirmation(e,...t){const s=De[e](...t);a(s)}};Me.RELEVANT_BRIDGE_PROPS=["session","sessionStatus","subscriptions","addresses","subscriptionOrders","locked"],Se([W({type:String,attribute:"data-bootstrap-scope"})],Me.prototype,"bootstrapScope",2),Se([q()],Me.prototype,"session",2),Se([q()],Me.prototype,"sessionStatus",2),Se([q()],Me.prototype,"subscriptions",2),Se([q()],Me.prototype,"addresses",2),Se([q()],Me.prototype,"orders",2),Se([q()],Me.prototype,"subscriptionOrders",2),Se([q()],Me.prototype,"onTheWayOrders",2),Se([q()],Me.prototype,"chargeDiscounts",2),Se([q()],Me.prototype,"chargeGifts",2),Se([q()],Me.prototype,"lastDroppedDiscountCode",2),Se([q()],Me.prototype,"creditSummary",2),Se([q()],Me.prototype,"variantEnrichmentData",2),Se([q()],Me.prototype,"recommendedProducts",2),Se([q()],Me.prototype,"customer",2),Se([q()],Me.prototype,"deliverySchedule",2),Se([q()],Me.prototype,"essenceFlavorIcons",2),Se([q()],Me.prototype,"loading",2),Se([q()],Me.prototype,"locked",2),Se([q()],Me.prototype,"error",2),Se([q()],Me.prototype,"ordersLoading",2),Se([q()],Me.prototype,"chargeGiftsLoading",2),Se([q()],Me.prototype,"creditLoading",2),Se([q()],Me.prototype,"onTheWayLoading",2),Se([q()],Me.prototype,"swapVariantStock",2),Se([q()],Me.prototype,"swapVariantStockPending",2),Se([B({context:c}),q()],Me.prototype,"contextValue",2),Me=Se([$("subscriptions-controller")],Me);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.