PageSourceSearch

https://podcompany.com/cdn/shop/t/128/assets/mulberry-integrations.js?v=158918758724898433761787048988

js podcompany.com collected 2026-09-28 11:08:51 UTC 23,061 bytes, 2 lines download raw bytes

1let product=null,selectedVariant=null,selectedWarranty=null,selectedWarrantyVariantId=null,inlineWidget=null,lastVariantId=null,warrantyAddInProgress=!1,mulberryCartSyncInProgress=!1,mulberryCartSyncQueue=Promise.resolve(),mulberryPdpOffers=[],mulberryPdpReady=!1,mulberryPdpStartAttempts=0;const mulberryPdpSubscribers=new Set,PDP_START_RETRY_MS=500,PDP_START_MAX_ATTEMPTS=120,BUTTONS_WRAPPER_SELECTOR=".product-form__buttons",ADD_BUTTON_SELECTOR=".product-form__submit",CONTAINER_ID="mulberry-offer-container",SUBSCRIPTION_CHECKBOX_SELECTOR="#add-subscription-temp",DEBUG_PREFIX="[Mulberry PDP]";function getMulberryPdpState(){return{ready:mulberryPdpReady,offers:mulberryPdpOffers.slice(),selectedWarranty,variantId:selectedVariant?.id||getCurrentVariantId()||null}}function notifyMulberryPdpSubscribers(){if(!mulberryPdpSubscribers.size)return;const state=getMulberryPdpState();mulberryPdpSubscribers.forEach(function(subscriber){try{subscriber(state)}catch(error){logError("Mulberry PDP subscriber failed",error)}})}function setMulberryPdpState(offers=mulberryPdpOffers,ready=mulberryPdpReady){mulberryPdpOffers=Array.isArray(offers)?offers:[],mulberryPdpReady=!!ready,notifyMulberryPdpSubscribers()}function getMulberryOfferKey(offer){return offer?.warranty_offer_id??offer?.offer_id??offer?.id??null}function publishMulberryPdpBridge(){window.mulberryPdp||(window.mulberryPdp={getState:getMulberryPdpState,subscribe:function(subscriber){if(typeof subscriber!="function")return function(){};mulberryPdpSubscribers.add(subscriber);try{subscriber(getMulberryPdpState())}catch(error){logError("Mulberry PDP subscriber failed",error)}return function(){mulberryPdpSubscribers.delete(subscriber)}},selectWarranty:function(offer,shouldSelect=!0){if(!shouldSelect){clearSelectedWarranty("theme protection plan deselected");return}const offerId=getMulberryOfferKey(offer);if(!(mulberryPdpOffers.indexOf(offer)!==-1||offerId!=null&&mulberryPdpOffers.some(function(currentOffer){return`${getMulberryOfferKey(currentOffer)}`==`${offerId}`})))throw new Error("Mulberry protection plan is no longer available");storeSelectedWarranty(offer,!0)},openCoverageModal:function(offer){const coverage=offer||selectedWarranty||mulberryPdpOffers[0]||null,faq=window.mulberry?.faq;return!coverage||typeof faq?.init!="function"||typeof faq?.open!="function"?!1:(faq.init({coverage}),faq.open(),!0)}})}function logDebug(message,data){if(typeof data>"u"){console.log(DEBUG_PREFIX,message);return}console.log(DEBUG_PREFIX,message,data)}function logWarning(message,data){if(typeof data>"u"){console.warn(DEBUG_PREFIX,message);return}console.warn(DEBUG_PREFIX,message,data)}function logError(message,error){console.error(DEBUG_PREFIX,message,error)}function getAddButton(){return document.querySelector(ADD_BUTTON_SELECTOR)}function getButtonsWrapper(){return getAddButton()?.closest(BUTTONS_WRAPPER_SELECTOR)||document.querySelector(BUTTONS_WRAPPER_SELECTOR)}function getProductForm(){return getAddButton()?.closest("form")||document.querySelector('form[action*="/cart/add"]')}function normalisePositiveInteger(value,fallback=1){const number=parseInt(value,10);return Number.isFinite(number)&&number>0?number:fallback}function getQuantity(){const input=getProductForm()?.querySelector('input[name="quantity"]')||document.querySelector('input[name="quantity"]');return normalisePositiveInteger(input?.value,1)}function getCurrentVariantId(){const formVariant=getProductForm()?.querySelector('[name="id"]')?.value,urlVariant=new URLSearchParams(window.location.search).get("variant");return formVariant||window.selectedVariantId||window.mulberryShop?.selectedVariantId||urlVariant||""}function ensureInlineContainer(){const wrapper=getButtonsWrapper();if(!wrapper?.parentNode)return null;let container=document.getElementById(CONTAINER_ID);return container||(container=document.createElement("div"),container.id=CONTAINER_ID,container.className="mulberry-offer-container"),(container.parentNode!==wrapper.parentNode||container.nextElementSibling!==wrapper)&&wrapper.parentNode.insertBefore(container,wrapper),container}function findProductVariant(variantId){return!variantId||!product?.variants?.length?null:product.variants.find(function(variant){return`${variant.id}`==`${variantId}`})||null}function getSelectedVariant(variantId=getCurrentVariantId()){return selectedVariant=findProductVariant(variantId)||product?.variants?.[0]||null,selectedVariant?(lastVariantId=`${selectedVariant.id}`,window.selectedVariant=selectedVariant,window.mulberryShop.selectedVariantId=selectedVariant.id,selectedVariant):null}async function getOffersForVariant(variant){if(!variant)return[];logDebug("Requesting offers",{variantId:`${variant.id}`,price:variant.price});const offers=await window.mulberry.core.getWarrantyOffer({detail
1:{...product,id:variant.id},id:variant.id,title:product.title,price:variant.price});return logDebug("Offers received",{variantId:`${variant.id}`,offerCount:offers?.length||0}),offers||[]}function restoreSelectedWarrantyGlobals(){selectedWarranty&&(window.selectedWarranty=selectedWarranty,window.selectedOffer=selectedWarranty,window.productForWarranty=product)}function clearSelectedWarranty(reason="unspecified"){logDebug("Clearing selected warranty",{reason,hadWarranty:!!selectedWarranty,warrantyVariantId:selectedWarrantyVariantId}),selectedWarranty=null,selectedWarrantyVariantId=null,window.selectedWarranty=null,window.selectedOffer=null,window.productForWarranty=null,notifyMulberryPdpSubscribers()}function storeSelectedWarranty(warranty,selectionState){if(logDebug("onWarrantyToggle callback",{selectionState,hasWarrantyArgument:!!warranty,currentVariantId:getCurrentVariantId()}),selectionState===!1||!warranty){clearSelectedWarranty("Mulberry widget deselected");return}const offer=warranty?.offer||warranty?.selectedOffer||warranty;if(!offer){logWarning("Warranty callback did not contain an offer",warranty);return}selectedWarranty=offer,selectedWarrantyVariantId=`${getCurrentVariantId()}`,restoreSelectedWarrantyGlobals(),logDebug("Warranty selected",{warrantyVariantId:selectedWarrantyVariantId,offer}),notifyMulberryPdpSubscribers()}function getCurrentWarrantySelection(){return selectedWarranty||window.selectedWarranty||window.selectedOffer||null}async function refreshOffers(force=!1){if(!product||!inlineWidget)return;const currentVariantId=getCurrentVariantId();if(!force&&currentVariantId&&`${currentVariantId}`==`${lastVariantId}`)return;clearSelectedWarranty("product variant changed"),setMulberryPdpState([],!1),inlineWidget?.deselectOffer&&inlineWidget.deselectOffer();const variant=getSelectedVariant(currentVariantId),offers=await getOffersForVariant(variant),container=ensureInlineContainer();container&&(container.style.display=offers.length?"block":"none"),inlineWidget?.updateOffer&&inlineWidget.updateOffer(offers),setMulberryPdpState(offers,!0)}async function addWarrantyToCart({offer,variant,quantity}){if(!offer||!variant)return logWarning("Warranty add skipped because context was incomplete",{hasOffer:!!offer,hasVariant:!!variant}),!1;if(warrantyAddInProgress)return logWarning("Warranty add skipped because another warranty add is running"),!1;warrantyAddInProgress=!0;try{logDebug("Resolving Shopify warranty variant",{mainVariantId:`${variant.id}`,quantity,offer});const warrantyVariant=await window.mulberryShop.getWarrantyVariant(offer);if(logDebug("Warranty variant resolved",{warrantyVariant}),!warrantyVariant?.shopify_variant_id)throw new Error("Mulberry did not return a Shopify warranty variant.");return logDebug("Adding warranty to cart",{warrantyShopifyVariantId:warrantyVariant.shopify_variant_id,connectedMainVariantId:`${variant.id}`,quantity:normalisePositiveInteger(quantity,1)}),await window.mulberryShop.addWarrantyToCart(warrantyVariant.shopify_variant_id,{...product,variantId:`${variant.id}`,quantity:normalisePositiveInteger(quantity,1)},offer),logDebug("Warranty successfully added to cart"),clearSelectedWarranty("warranty successfully added"),!0}finally{warrantyAddInProgress=!1}}function isCartAddRequest(input){const url=typeof input=="string"?input:input?.url||"";try{const parsedUrl=new URL(url,window.location.origin);return parsedUrl.pathname==="/cart/add"||parsedUrl.pathname==="/cart/add.js"}catch{return url.includes("/cart/add")}}function getMatchingProductLine(items){return Array.isArray(items)&&items.find(function(item){return!!findProductVariant(item?.id||item?.variant_id)})||null}function parseKeyValueCartBody(collection){const directVariantId=collection.get("id"),directQuantity=collection.get("quantity");if(directVariantId)return{variantId:`${directVariantId}`,quantity:directQuantity,itemIds:[`${directVariantId}`],source:"direct fields"};const itemIds=[],quantitiesByIndex={};for(const[key,value]of collection.entries()){key.match(/^items\[(\d+)\]\[(?:id|variant_id)\]$/)&&itemIds.push(`${value}`);const quantityMatch=key.match(/^items\[(\d+)\]\[quantity\]$/);quantityMatch&&(quantitiesByIndex[quantityMatch[1]]=value)}let matchingVariantId=null,matchingQuantity=null;for(const[key,value]of collection.entries()){const idMatch=key.match(/^items\[(\d+)\]\[(?:id|variant_id)\]$/);if(idMatch&&findProductVariant(value)){matchingVariantId=`${value}`,matchingQuantity=quantitiesByIndex[idMatch[1]]||null;break}}return{variantId:matchingVariantId,quantity:matchingQuantity,itemIds,source:"items fields"}}function parseCartBodyValue(body){if(!body)return{variantId:null,quantity:null,itemIds:[],source:"empty body"};if(body instanceof FormData||body instanceof URLSearchParams)return parseKeyValueCartBody(body);if(typeof body=="object"){if(Array.isArray(body.items)){const matchingLine=getMatchingProductLine(body.items);return{variantId:matchingLine?.id||matchingLine?.variant_id||null,quantity:matchingLine?.quantity||null,itemIds:body.items.map(function(item){return`${item?.
1id||item?.variant_id||""}`}).filter(Boolean),source:"JSON items array"}}return{variantId:body.id||body.variant_id||null,quantity:body.quantity||null,itemIds:[`${body.id||body.variant_id||""}`].filter(Boolean),source:"JSON object"}}if(typeof body!="string")return{variantId:null,quantity:null,itemIds:[],source:typeof body};const trimmedBody=body.trim();if(!trimmedBody)return{variantId:null,quantity:null,itemIds:[],source:"empty string"};try{return parseCartBodyValue(JSON.parse(trimmedBody))}catch{return parseKeyValueCartBody(new URLSearchParams(trimmedBody))}}async function getCartAddContext(input,options){let body=options?.body||null;if(!body&&typeof Request<"u"&&input instanceof Request)try{body=await input.clone().text()}catch(error){logWarning("Could not read Request body",error)}const parsedBody=parseCartBodyValue(body),requestVariant=findProductVariant(parsedBody.variantId);return{parsedBody,variant:requestVariant,quantity:normalisePositiveInteger(parsedBody.quantity,getQuantity()),isMainProductRequest:!!requestVariant}}function installCartAddInterceptor(){if(window.__mulberryCartAddInterceptorInstalled)return;window.__mulberryCartAddInterceptorInstalled=!0;const originalFetch=window.fetch.bind(window);window.fetch=async function(input,options){if(!isCartAddRequest(input)||warrantyAddInProgress)return originalFetch(input,options);const offer=getCurrentWarrantySelection(),cartContext=await getCartAddContext(input,options);if(logDebug("Intercepted /cart/add request",{parsedBody:cartContext.parsedBody,isMainProductRequest:cartContext.isMainProductRequest,matchedVariantId:cartContext.variant?`${cartContext.variant.id}`:null,currentProductVariantId:getCurrentVariantId(),hasSelectedWarranty:!!offer,selectedWarrantyVariantId}),!cartContext.isMainProductRequest){logDebug("Passing through non-main/byproduct cart add");const response2=await originalFetch(input,options);return restoreSelectedWarrantyGlobals(),logDebug("Byproduct cart add completed",{status:response2.status,hasSelectedWarrantyAfterRequest:!!getCurrentWarrantySelection()}),response2}if(!offer)return logWarning("Main product request detected, but no selected Mulberry offer was found"),originalFetch(input,options);if(selectedWarrantyVariantId&&`${selectedWarrantyVariantId}`!=`${cartContext.variant.id}`)return logWarning("Selected warranty belongs to another variant",{selectedWarrantyVariantId,requestVariantId:`${cartContext.variant.id}`}),originalFetch(input,options);const warrantyContext={offer,variant:cartContext.variant,quantity:cartContext.quantity};logDebug("Main product request matched; sending main product first",{variantId:`${warrantyContext.variant.id}`,quantity:warrantyContext.quantity});const response=await originalFetch(input,options);if(logDebug("Main product response received",{status:response.status,ok:response.ok}),!response.ok)return logWarning("Main product failed, so warranty was not added"),response;try{await addWarrantyToCart(warrantyContext)}catch(error){logError("Main product was added, but warranty add failed",error)}return response},logDebug("Cart add interceptor installed")}function bindSubscriptionCheckboxDebug(){window.__mulberrySubscriptionCheckboxDebugBound||(window.__mulberrySubscriptionCheckboxDebugBound=!0,document.addEventListener("change",function(event){const target=event.target;!(target instanceof Element)||!target.matches(SUBSCRIPTION_CHECKBOX_SELECTOR)||logDebug("Subscription checkbox changed",{checked:target.checked,hasSelectedWarranty:!!getCurrentWarrantySelection(),selectedWarrantyVariantId})},!0))}function isCartChangeOrUpdateRequest(input){const url=typeof input=="string"?input:input?.url||"";try{const parsedUrl=new URL(url,window.location.origin);return parsedUrl.pathname==="/cart/change"||parsedUrl.pathname==="/cart/change.js"||parsedUrl.pathname==="/cart/update"||parsedUrl.pathname==="/cart/update.js"}catch{return url.includes("/cart/change")||url.includes("/cart/update")}}function getConnectedMainVariantId(cartItem){return cartItem?.properties?._variantId||cartItem?.properties?._variant_id||""}function isMulberryWarrantyItem(cartItem){return!!getConnectedMainVariantId(cartItem)}async function getCurrentCart(fetchFunction){const cartUrl=`${window.Shopify?.routes?.root||"/"}cart.js`,response=await fetchFunction(cartUrl,{method:"GET",credentials:"same-origin",headers:{Accept:"application/json"}});if(!response.ok)throw new Error(`Unable to fetch cart (${response.status}).`);return response.json()}async function getCartJson(){const cartUrl=`${window.Shopify?.routes?.root||"/"}cart.js`,response=await fetch(cartUrl,{method:"GET",credentials:"same-origin",headers:{Accept:"application/json"}});if(!response.ok)throw new Error(`Unable to fetch cart (${response.status}).`);return response.json()}function isSectionalMulberryItem(item){const properties=item?.properties||{};return!!(properties._warranty_duration_months||properties._variantId)}async function removeOrphanMulberryWarrantyItems(){const cart=await getCartJson(),normalVariantIds=new Set(cart.items.filter(function(item){return!isMulberryWarrantyItem(item)}).map(function(item){return`${item.variant_id||item.id}`})),orphanWarrantyItems=cart.items.filter(function(item){if(!isMulberryWarrantyItem(item))return!1;const connectedVariantId=`${getConnectedMainVariantId(item)}`;return!connectedVariantId||!normalVariantIds.has(connectedVariantId)});for(const item of orphanWarrantyItems){if(!item.key)continue;logDebug("Removing orphan Mulberry warranty",{warrantyLineKey:item.key,connectedVariantId:getConnectedMainVariantId(item)});const response=await fetch(`${window.Shopify?.routes?.root||"/"}cart/change.js`,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:item.key,quantity:0})});if(!response.ok)throw new Error(`Unable to remove orphan warranty (${response.status}).`)}}function buildMulberryQuantityUpdates(cart){const items=Array.isArray(cart?.items)?cart.items:[],mainQuantities=new Map;
1items.forEach(function(item){if(isMulberryWarrantyItem(item))return;const variantId=item?.variant_id||item?.id;if(!variantId)return;const key=`${variantId}`,currentQuantity=parseInt(item.quantity,10)||0,existingQuantity=mainQuantities.get(key)||0;mainQuantities.set(key,existingQuantity+currentQuantity)});const updates={},debugItems=[];return items.forEach(function(item){if(!isMulberryWarrantyItem(item))return;const connectedVariantId=`${getConnectedMainVariantId(item)}`,desiredQuantity=mainQuantities.get(connectedVariantId)||0,currentQuantity=parseInt(item.quantity,10)||0;debugItems.push({warrantyLineKey:item.key,connectedVariantId,currentQuantity,desiredQuantity}),item.key&&currentQuantity!==desiredQuantity&&(updates[item.key]=desiredQuantity)}),{updates,debugItems}}async function rerenderMulberryCart(){logDebug("Re-rendering Mulberry cart");try{window.mulberryShop?.cart?.render&&await window.mulberryShop.cart.render({refresh:!0})}catch(error){logWarning("Mulberry cart render failed",error)}}async function removeAndSyncMulberryOffers(){if(mulberryCartSyncInProgress)return logDebug("Mulberry cart sync already in progress"),!1;mulberryCartSyncInProgress=!0;try{const firstCart=await getCartJson();logDebug("Starting Mulberry warranty removal and quantity sync",{items:firstCart.items.map(function(item){return{key:item.key,variantId:item.variant_id,quantity:item.quantity,properties:item.properties,connectedVariantId:getConnectedMainVariantId(item)}})});try{const newCart=await window.mulberryShop.removeDetachedWarranty(firstCart);logDebug("removeDetachedWarranty result",newCart),await window.mulberryShop.cart.syncQuantities(newCart||firstCart),logDebug("Mulberry warranty quantities synced")}catch(error){logError("Error during warranty removal and cart sync",error)}try{await removeOrphanMulberryWarrantyItems(),logDebug("Orphan Mulberry warranty cleanup completed")}catch(error){logError("Error during orphan Mulberry warranty cleanup",error)}return await rerenderMulberryCart(),!0}catch(error){return logError("Unable to remove and sync Mulberry warranties",error),!1}finally{mulberryCartSyncInProgress=!1}}function queueMulberryCartSync(){const operation=mulberryCartSyncQueue.then(function(){return removeAndSyncMulberryOffers()},function(){return removeAndSyncMulberryOffers()});return mulberryCartSyncQueue=operation.catch(function(){}),operation}function bindVariantChanges(){if(window.__mulberryVariantListenersBound)return;window.__mulberryVariantListenersBound=!0;let refreshTimer=null;function scheduleRefresh(){window.clearTimeout(refreshTimer),refreshTimer=window.setTimeout(function(){refreshOffers().catch(function(error){logError("Unable to refresh offers",error)})},180)}document.addEventListener("change",function(event){const target=event.target;target instanceof Element&&(target.matches('[name="id"]')||target.closest("variant-selects")||target.closest("variant-radios"))&&scheduleRefresh()}),document.addEventListener("click",function(event){const target=event.target;target instanceof Element&&(target.closest("[data-option-value]")||target.closest("[data-variant-id]")||target.closest("variant-selects")||target.closest("variant-radios"))&&scheduleRefresh()}),window.addEventListener("popstate",scheduleRefresh)}async function initMulberryPdp(){if(window.__mulberryPdpInitialized)return;const container=ensureInlineContainer();if(!container){logWarning("Could not find product buttons wrapper");return}window.__mulberryPdpInitialized=!0,window.mb_gtm_is_disabled=!0,window.mulberry.core.settings.has_inline=!0,window.mulberry.core.settings.has_modal=!1,installCartAddInterceptor(),bindSubscriptionCheckboxDebug(),bindVariantChanges(),logDebug("Loading product data"),product=(await window.mulberryShop.getProductData(window.mulberryShop.getProductUrl())).product,logDebug("Product data loaded",{productId:product?.id,title:product?.title,variantIds:product?.variants?.map(function(variant2){return`${variant2.id}`})||[]});const variant=getSelectedVariant(),offers=await getOffersForVariant(variant);container.style.display=offers.length?"block":"none",inlineWidget=
1await window.mulberry.inline.init({selector:`#${CONTAINER_ID}`,offers,settings:window.mulberry.core.settings,onWarrantyToggle:function(warranty,isSelected){storeSelectedWarranty(warranty,isSelected)}}),ensureInlineContainer(),setMulberryPdpState(offers,!0),window.__mulberryDebugState=function(){return{currentVariantId:getCurrentVariantId(),selectedWarranty,selectedWarrantyVariantId,warrantyAddInProgress,mulberryCartSyncInProgress,productVariantIds:product?.variants?.map(function(variant2){return`${variant2.id}`})||[]}},logDebug("Mulberry PDP initialised. Run window.__mulberryDebugState() to inspect the current state.")}function startMulberryPdp(){if(window.location.pathname.includes("/products/")){if(!window.mulberryShop||!window.mulberry?.core?.settings||!window.mulberry?.inline){mulberryPdpStartAttempts<PDP_START_MAX_ATTEMPTS&&(mulberryPdpStartAttempts+=1,window.setTimeout(startMulberryPdp,PDP_START_RETRY_MS));return}initMulberryPdp().catch(function(error){window.__mulberryPdpInitialized=!1,setMulberryPdpState([],!1),logError("Unable to initialise Mulberry PDP",error)})}}publishMulberryPdpBridge(),document.addEventListener("mulberry-shopify:loaded",function(){startMulberryCartSync(),startMulberryPdp()}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",function(){startMulberryCartSync(),startMulberryPdp()}):(startMulberryCartSync(),startMulberryPdp());function installCartChangeSyncInterceptor(){if(window.__mulberryCartChangeSyncInstalled)return;window.__mulberryCartChangeSyncInstalled=!0;const previousFetch=window.fetch.bind(window);window.fetch=async function(input,options){if(mulberryCartSyncInProgress||!isCartChangeOrUpdateRequest(input))return previousFetch(input,options);const requestUrl=typeof input=="string"?input:input?.url||"";logDebug("Detected theme cart line-item request",{url:requestUrl,body:options?.body||null});const originalResponse=await previousFetch(input,options);if(logDebug("Theme cart line-item request completed",{status:originalResponse.status,ok:originalResponse.ok}),!originalResponse.ok)return originalResponse;try{const synced=await queueMulberryCartSync();logDebug("Mulberry cart quantity sync completed before UpCart redraw",{synced});const finalCart=await getCartJson();return logDebug("Returning final synced cart to UpCart",{itemCount:finalCart.item_count,items:finalCart.items.map(function(item){return{key:item.key,quantity:item.quantity,connectedVariantId:getConnectedMainVariantId(item)}})}),new Response(JSON.stringify(finalCart),{status:originalResponse.status,statusText:originalResponse.statusText,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}catch(error){return logError("Mulberry sync failed before UpCart response",error),originalResponse}},logDebug("Cart change sync interceptor installed")}function startMulberryCartSync(){window.mulberryShop&&(installCartChangeSyncInterceptor(),logDebug("Global Mulberry cart sync started"))}
2//# sourceMappingURL=/cdn/shop/t/128/assets/mulberry-integrations.js.map?v=158918758724898433761787048988

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.