PageSourceSearch

https://www.cartoys.com/cdn/shopifycloud/storefront/assets/storefront/remote_product_tracking-91d95044.js

js cartoys.com collected 2026-09-25 14:43:33 UTC 44,147 bytes, 1 lines download raw bytes

1(()=>{function ready(fn){if(document.readyState!=="loading"){fn()}else if(document.addEventListener){document.addEventListener("DOMContentLoaded",fn)}else{document.attachEvent("onreadystatechange",()=>{if(document.readyState!=="loading"){fn()}})}}var PLACEMENT_PATTERN=/^[a-z][a-z0-9_-]{0,29}$/;var DEFAULT_CONFIG={REMOTE_PRODUCT_PATTERN:/\/products\/([a-z0-9]+(?:-[a-z0-9]+)*)-([a-zA-Z0-9+/=:-]+)-([a-f0-9]{8})-remote(?:\?|$)/,OBSERVER_THRESHOLD:.5,DEBOUNCE_DELAY:500,MIN_ELEMENT_SIZE:10,MAX_PROCESSED_LINKS:1e3,DATA_ATTRIBUTE:"data-shopify-remote-tracking"};var isDev=(()=>{try{if(typeof window!=="undefined"&&window&&window.Shopify&&window.Shopify.remoteProductTrackingDebug===true){return true}}catch(_){}try{if(typeof window!=="undefined"&&window&&window.location){const host=window.location.hostname||"";if(host==="localhost"||host==="127.0.0.1"){return true}if(/\.my\.shop\.dev$/.test(host)){return true}}}catch(_){}return false})();var noop=function(){};var con=typeof console!=="undefined"?console:{log:noop,warn:noop,error:noop,info:noop,debug:noop};var logger={log:isDev?function(...args){try{con.log.apply(con,args)}catch(_){}}:noop,warn:isDev?function(...args){try{con.warn.apply(con,args)}catch(_){}}:noop,error:isDev?function(...args){try{con.error.apply(con,args)}catch(_){}}:noop,info:isDev?function(...args){try{con.info.apply(con,args)}catch(_){}}:noop,debug:isDev?function(...args){try{con.debug.apply(con,args)}catch(_){}}:noop};var logger_default=logger;var NIL_TRACKING_TOKEN="00000000-0000-0000-0000-000000000000";var DISALLOWED_TRACKING_TOKEN="00000000-0000-0000-5000-000000000000";var NO_META_READING={token:null,denied:false};function parseCollectiveEntries(raw){try{const parsed=JSON.parse(raw||"[]");return Array.isArray(parsed)?parsed:[]}catch{return[]}}var utils={sanitizePlacement(placement){const normalized=typeof placement==="string"?placement.toLowerCase().trim():"";if(!PLACEMENT_PATTERN.test(normalized)){logger_default.warn(`Invalid placement rejected: ${String(placement).slice(0,100)}`);return"other"}return normalized},generateImpressionId(){if(typeof crypto!=="undefined"&&typeof crypto.randomUUID==="function"){return crypto.randomUUID()}logger_default.log("\u26A0\uFE0F Using Math.random UUID fallback (crypto.randomUUID unavailable)");return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{const r=Math.random()*16|0;const v=c==="x"?r:r&3|8;return v.toString(16)})},getRequestIdentifier(){try{if(typeof performance!=="undefined"){const getPerformanceEntriesByType=performance.getEntriesByType;if(typeof getPerformanceEntriesByType==="function"){const navigationEntries=getPerformanceEntriesByType.call(performance,"navigation");const navigationEntry=navigationEntries?.[0];const requestIdentifier=navigationEntry?.serverTiming?.find(serverTimingEntry=>serverTimingEntry.name==="requestID")?.description;if(requestIdentifier){return requestIdentifier}}}}catch(error){logger_default.error("Error reading requestID from Server-Timing:",error)}return window.ShopifyAnalytics?.meta?.page?.requestId},toLong(v){if(v==null){return void 0}const n=Number(v);return Number.isFinite(n)?Math.trunc(n):void 0},isValidHref(href){return typeof href==="string"&&href.length>0&&href.length<2e3&&href.includes("/products/")},isRemoteProductLink(href){if(!this.isValidHref(href)){logger_default.log("\u274C Invalid href:",href);return false}const isMatch=DEFAULT_CONFIG.REMOTE_PRODUCT_PATTERN.test(href);if(!isMatch&&href.includes("-remote")){logger_default.log("\u274C Pattern mismatch for remote URL:",href);logger_default.log("   Pattern:",DEFAULT_CONFIG.REMOTE_PRODUCT_PATTERN)}return isMatch},getViewportInfo(){return{viewport_width:Math.max(0,window.innerWidth||document.documentElement.clientWidth||0),viewport_height:Math.max(0,window.innerHeight||document.documentElement.clientHeight||0)}},isValidToken(token){if(typeof token!=="string"){return null}if(token===NIL_TRACKING_TOKEN||token===DISALLOWED_TRACKING_TOKEN){return null}return token.length>5&&token.length<200?token:null},readCookieValue(cookieName){const prefix=`${cookieName}=`;const cookies=document.cookie.split(";");for(let i=0;i<cookies.length;
1i++){const cookie=cookies[i].trim();if(cookie.indexOf(prefix)===0){return cookie.substring(prefix.length)}}return null},readMetaTagReading(metaName){try{const meta=document.querySelector(`meta[name="${metaName}"]`);if(!meta){return NO_META_READING}const expiration=Number(meta.getAttribute("data-expiration"));if(!Number.isFinite(expiration)||expiration<=Date.now()){return NO_META_READING}const content=meta.getAttribute("content");if(content===DISALLOWED_TRACKING_TOKEN){return{token:null,denied:true}}return{token:this.isValidToken(content),denied:false}}catch(e){logger_default.error("Error reading token from meta tag:",e);return NO_META_READING}},resolveTrackingToken(accessorName,metaName,cookieName){try{const internal=window.Shopify?.customerPrivacy?.__internal;const accessor=internal?.[accessorName];if(typeof accessor==="function"){return this.isValidToken(accessor.call(internal,{generateFallback:false,tag:"storefront_remote_product_tracking"}))}}catch(e){logger_default.error("Error reading token from the Customer Privacy API:",e);return null}const meta=this.readMetaTagReading(metaName);if(meta.denied){return null}if(meta.token!==null){return meta.token}return this.isValidToken(this.readCookieValue(cookieName))},getSecureUserToken(){try{return this.resolveTrackingToken("uniqueToken","shopify-y","_shopify_y")}catch(e){logger_default.error("Error getting user token:",e)}return null},getWebSessionToken(){try{const validToken=this.resolveTrackingToken("visitToken","shopify-s","_shopify_s");logger_default.log("\u{1F511} Extracted _shopify_s token:",validToken?`${validToken.substring(0,20)}...`:"null");return validToken}catch(e){logger_default.error("Error getting web session token:",e)}return null},getElementPositionInfo(element){try{const rect=element.getBoundingClientRect();const viewport=this.getViewportInfo();return{x_pos:Math.round(Math.max(0,rect.left)),y_pos:Math.round(Math.max(0,rect.top)),above_fold:rect.top>=0&&rect.top<viewport.viewport_height,viewport_width:viewport.viewport_width,viewport_height:viewport.viewport_height}}catch(e){logger_default.error("Error getting element position:",e);return{}}},parseRemoteProductDataFromUrl(url){try{const remoteMatch=url.match(DEFAULT_CONFIG.REMOTE_PRODUCT_PATTERN);if(!remoteMatch){return null}const seoHandle=remoteMatch[1];const encodedPayload=remoteMatch[2];const signature=remoteMatch[3];const decodedPayload=atob(encodedPayload);const parts=decodedPayload.split(":");if(parts.length!==5||parts[0]!=="v1"){return null}const productId=parseInt(parts[1],10);const shopId=parseInt(parts[2],10);const adResponseId=parts[3]||void 0;const timestamp=parseInt(parts[4],10);return{advertiser_shop_id:shopId,advertiser_shop_name:null,product_id:productId,ad_response_id:adResponseId,timestamp,seo_handle:seoHandle,signature}}catch(e){logger_default.error("Error parsing remote product ID:",e);return null}},sanitizeString(str,maxLength){if(typeof str!=="string"){return""}return str.trim().substring(0,maxLength||100)},isTrustedEvent(event){return event&&event.isTrusted===true},checkMetaDataForProductId(handle){if(window.ShopifyAnalytics&&window.ShopifyAnalytics.meta&&window.ShopifyAnalytics.meta.products){const products=window.ShopifyAnalytics.meta.products;const match=products.find(product=>product.handle===handle&&product.id);if(match){const parsed=parseInt(match.id,10);if(Number.isFinite(parsed)){return parsed}}}if(window.ShopifyAnalytics&&window.ShopifyAnalytics.meta&&window.ShopifyAnalytics.meta.product){const product=window.ShopifyAnalytics.meta.product;if(product.handle===handle&&product.id){const parsed=parseInt(product.id,10);if(Number.isFinite(parsed)){return parsed}}}logger_default.log("\u274C checkMetaDataForProductId: Could not find product with handle:",handle);return null},isCollectiveProduct(handle){const meta=window.ShopifyAnalytics?.meta;if(!meta){return false}if(meta.product?.handle===handle&&meta.product.collective){return true}if(Array.isArray(meta.products)&&meta.products.some(product=>product.handle===handle&&product.collective)){return true}return meta.collectiveProducts instanceof Set&&meta.collectiveProducts.has(handle)},mergeCollectiveProductAttributionFromDom(root){const scope=root||document;const scripts=scope.querySelectorAll?.("script[data-shopify-collective-product-attribution]:not([data-shopify-collective-product-attribution-processed])");if(!scripts?.length){return}window.ShopifyAnalytics??={};window.ShopifyAnalytics.meta??={};window.ShopifyAnalytics.meta.collectiveProducts??=new Set;const handles=window.ShopifyAnalytics.meta.collectiveProducts;for(const script of scripts){script.setAttribute("data-shopify-collective-product-attribution-processed","true");for(const entry of parseCollectiveEntries(script.textContent)){if(typeof entry?.handle!=="string"||!entry.collective){continue}handles.add(entry.handle)}}},getProductOrigin(isRemote,handle){if(isRemote){return"Remote"}if(handle&&this.isCollectiveProduct(handle)){return"Collective-Static"}return"Organic"},parseOrganicProductIdFromUrl(url){const handle=this.parseOrganicProductHandleFromUrl(url);if(!handle){return null}return this.checkMetaDataForProductId(handle)},parseOrganicProductHandleFromUrl(url){try{const handleMatch=url.match(/\/products\/([^/?]+)/);if(!handleMatch){logger_default.log("\u274C parseOrganicProductHandle: Could not extract handle from href:",url);return null}return handleMatch[1]}catch(e){logger_default.error("Error parsing organic product handle:",e);return null}},parseOrganicProductIdFromLink(link){try{const href=link.getAttribute("href");if(!href){logger_default.log("\u274C parseOrganicProductIdFromLink: No href found on link");return null}const handleMatch=href.match(/\/products\/([^/?]+)/);if(!handleMatch){logger_default.log("\u274C parseOrganicProductIdFromLink: Could not extract handle from href:",href);return null}const linkHandle=handleMatch[1];return this.checkMetaDataForProductId(linkHandle)}catch(e){logger_default.error("\u274C parseOrganicProductIdFromLink: Error parsing organic product ID:",e);return null}},buildTrackingPayload(link,linkInfo,eventType,trackingContext){const positionInfo=this.getElementPositionInfo(link);const productInfo=this.isRemoteProductLink(linkInfo.href)?this.parseRemoteProductDataFromUrl(linkInfo.href):null;const payload={event_type:eventType||"remote_product_impression",timestamp:Date.now(),href:linkInfo.href,position:linkInfo.position,user_token:this.getSecureUserToken(),web_session_token:this.getWebSessionToken()};const contextData=trackingContext||{};
1Object.keys(contextData).forEach(key=>{if(contextData[key]!=null){if(key==="theme_store_id"&&contextData[key]===0){payload[key]=void 0}else{payload[key]=contextData[key]}}});payload.placement=this.sanitizePlacement(payload.placement);Object.keys(positionInfo).forEach(key=>{payload[key]=positionInfo[key]});if(linkInfo.above_fold!==void 0){payload.above_fold=linkInfo.above_fold}let eventData=payload.event_data;if(productInfo){Object.keys(productInfo).forEach(key=>{if(productInfo[key]!=null){payload[key]=productInfo[key]}});if(productInfo.product_id&&eventData){try{const eventDataProperties=typeof eventData==="string"?JSON.parse(eventData):eventData;eventData={...eventDataProperties,product_id:productInfo.product_id}}catch(e){logger_default.error("Error updating event_data with product_id:",e)}}}if(link.hasAttribute("data-predictive-search-link")){payload.placement="search";eventData={...eventData,search_query:this.extractSearchQueryFromFormInput(link),search_type:"typeahead"}}if(payload.recommendations_tracking_enabled&&!link.hasAttribute("data-predictive-search-link")){const recommendationsContainer=this.getRecommendationsContainer(link);if(recommendationsContainer){link.setAttribute("data-recommendations-link","true");payload.placement="recommendations";eventData={...eventData,recommendation_type:this.getRecommendationIntent(recommendationsContainer)}}}const stringifiedEventData=typeof eventData==="object"?JSON.stringify(eventData):"{}";return{...payload,event_data:stringifiedEventData}},getPredictiveSearchContainer(link){if(!link){return null}const predictiveSearchContainer=link.closest("predictive-search, predictive-search-component, [data-predictive-search], .predictive-search");if(predictiveSearchContainer!==null){return predictiveSearchContainer}const form=link.closest("form");if(form){const formAction=form.getAttribute("action");if(formAction&&(formAction==="/search"||formAction.endsWith("/search"))){return form}}return null},isInPredictiveSearch(link){const predictiveSearchContainer=this.getPredictiveSearchContainer(link);if(predictiveSearchContainer){link.setAttribute("data-predictive-search-link","true");return true}return false},extractSearchQueryFromFormInput(link){if(!link){return null}try{const form=link.closest("form");if(!form){return null}const formAction=form.getAttribute("action");if(!formAction||formAction!=="/search"&&!formAction.endsWith("/search")){return null}const searchInput=form.querySelector('input[type="search"]');if(searchInput&&searchInput.value){const query=searchInput.value.trim();if(query.length>0){return query}}return null}catch(e){logger_default.error("Error extracting search query from form input:",e);return null}},setPredictiveSearchPosition(link){const predictiveSearchContainer=this.getPredictiveSearchContainer(link);if(!predictiveSearchContainer){return}try{const allProductLinks=predictiveSearchContainer.querySelectorAll('a[href*="/products/"]');const seenHrefs=new Set;const uniqueProductLinkURLs=Array.from(allProductLinks).map(link2=>link2.getAttribute("href")||link2.href).filter(href=>{if(href&&!seenHrefs.has(href)){seenHrefs.add(href);return true}return false});const index=uniqueProductLinkURLs.indexOf(link.getAttribute("href"));if(index>=0){const position=index+1;link.setAttribute("data-product-position",position);link.setAttribute("data-product-link-position",position)}}catch(e){logger_default.error("Error setting predictive search position:",e)}},getRecommendationsContainer(link){if(!link){return null}return link.closest("product-recommendations, [data-product-recommendations], .product-recommendations")},getRecommendationIntent(container){if(container.dataset.intent){return container.dataset.intent}try{const dataUrl=container.dataset.url;if(dataUrl){const match=dataUrl.match(/[?&]intent=([^&]+)/);if(match){return match[1]}}}catch(e){}return"related"},setRecommendationsPosition(link){const container=this.getRecommendationsContainer(link);if(!container){return}try{const allProductLinks=container.querySelectorAll('a[href*="/products/"]');const seenHrefs=new Set;
1const uniqueProductLinkURLs=Array.from(allProductLinks).map(l=>l.getAttribute("href")||l.href).filter(href=>{if(href&&!seenHrefs.has(href)){seenHrefs.add(href);return true}return false});const index=uniqueProductLinkURLs.indexOf(link.getAttribute("href"));if(index>=0){const position=index+1;link.setAttribute("data-product-position",String(position));link.setAttribute("data-product-link-position",String(position))}}catch(e){logger_default.error("Error setting recommendations position:",e)}}};var utils_default=utils;var TrackingState=class{constructor(){this.processedLinks=new Set;this.renderedLinks=new Set;this.reportedDuplicateHandles=new Set;this.observer=null;this.mutationObserver=null;this.duplicateObservers=[];this.isInitialized=false;this.trackingContext=null}reset(){if(this.observer){try{this.observer.disconnect()}catch(e){}this.observer=null}if(this.mutationObserver){try{this.mutationObserver.disconnect()}catch(e){}this.mutationObserver=null}for(const obs of this.duplicateObservers){try{obs.disconnect()}catch(e){}}this.duplicateObservers=[];this.processedLinks.clear();this.renderedLinks.clear();this.reportedDuplicateHandles.clear();this.isInitialized=false;this.trackingContext=null}};var tracking_state_default=TrackingState;var PRODUCT_LINK_SELECTOR='a[href*="/products/"]';function filterProductLinks(links){return Array.from(links).filter(link=>{const isInPredictiveSearch=utils_default.isInPredictiveSearch(link);return isInPredictiveSearch||!link.closest("header")})}function normalizeHref(link){return(link.getAttribute("href")||link.href||"").trim()}function isLinkVisible(rect,minSize){return rect.width>=minSize&&rect.height>=minSize}function setAboveFoldAttribute(link,cachedRect=null){if(link.hasAttribute("data-above-fold")){return}const rect=cachedRect||link.getBoundingClientRect();const viewportHeight=window.innerHeight||document.documentElement.clientHeight;const elementMidpoint=rect.top+rect.height/2;const aboveFold=rect.top>=0&&elementMidpoint<viewportHeight;link.setAttribute("data-above-fold",aboveFold.toString())}function getImpressionDedupKey(href,remoteProductInfo){const info=remoteProductInfo??(utils_default.isRemoteProductLink(href)?utils_default.parseRemoteProductDataFromUrl(href):null);return info?.ad_response_id?`ad:${info.ad_response_id}`:href}function getUniqueProductLinks(links){const seenHrefs=new Set;return Array.from(links).filter(link=>{const href=normalizeHref(link);if(seenHrefs.has(href)){return false}seenHrefs.add(href);return true})}var RemoteProductTracker=class{constructor(config={}){this.config={...DEFAULT_CONFIG,...config};this.state=new tracking_state_default;this.scanTimeout=null;this.emailClickTracked=false}extractSearchQuery(eventData,monorailPayload){if(!eventData){return}try{const parsedEventData=typeof eventData==="string"?JSON.parse(eventData):eventData;if(parsedEventData.search_query){monorailPayload.search_query=parsedEventData.search_query}}catch(e){logger_default.error("Error parsing event_data for search_query:",e)}}trackRemoteProductRendered(link){try{const href=link.getAttribute("href");if(!utils_default.isRemoteProductLink(href)){return}if(this.state.renderedLinks.has(href)){return}if(this.state.renderedLinks.size>=this.config.MAX_PROCESSED_LINKS){return}this.state.renderedLinks.add(href);const linkInfo={href,text:utils_default.sanitizeString(link.textContent),position:parseInt(link.getAttribute("data-product-link-position"),10)||null};const payload=utils_default.buildTrackingPayload(link,linkInfo,"remote_product_rendered",this.state.trackingContext);if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){try{const positionLong=utils_default.toLong(payload.position);const monorailPayload={advertiser_shop_id:utils_default.toLong(payload.advertiser_shop_id),ad_response_id:payload.ad_response_id,position:positionLong??1,above_fold:payload.above_fold,viewport_width:payload.viewport_width,viewport_height:payload.viewport_height,x_pos:payload.x_pos,y_pos:payload.y_pos,session_id:payload.session_id,publisher_shop_id:utils_default.toLong(payload.publisher_shop_id),theme_id:utils_default.toLong(payload.theme_id),theme_store_id:utils_default.toLong(payload.theme_store_id),theme_published:payload.theme_published,user_token:payload.user_token,web_session_token:payload.web_session_token,placement:payload.placement,event_data:payload.event_data,request_id:utils_default.getRequestIdentifier(),request_path:window.location?.pathname};this.extractSearchQuery(payload.event_data,monorailPayload);logger_default.log("\u{1F4DD} Remote ad rendered:",monorailPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_remote_ad_rendered/1.1",monorailPayload)}catch(e){logger_default.error("Error sending rendered to Monorail:",e)}}}catch(e){logger_default.error("Error tracking rendered:",e)}}initTrackingContext(){const scriptElement=document.querySelector(`script[${this.config.DATA_ATTRIBUTE}]`);if(!scriptElement){logger_default.log("\u26A0\uFE0F No script element with data-shopify-remote-tracking found");return false}try{const contextData=scriptElement.getAttribute(this.config.DATA_ATTRIBUTE);this.state.trackingContext=contextData?JSON.parse(contextData):{};return true}catch(e){logger_default.error("Error initializing tracking context:",e);return false}}trackProductImpression(link){try{const href=normalizeHref(link);const isRemote=utils_default.isRemoteProductLink(href);const eventType=isRemote?"remote_product_impression":"product_impression";const remoteProductInfo=isRemote?utils_default.parseRemoteProductDataFromUrl(href):void 0;const dedupKey=getImpressionDedupKey(href,remoteProductInfo);if(this.state.processedLinks.has(dedupKey)){return}if(this.state.processedLinks.size>=this.config.MAX_PROCESSED_LINKS){return}this.state.processedLinks.add(dedupKey);let impressionId=link.getAttribute("data-impression-id");if(!impressionId){impressionId=utils_default.generateImpressionId();link.setAttribute("data-impression-id",impressionId)}const aboveFoldAttr=link.getAttribute("data-above-fold");const aboveFold=aboveFoldAttr==="true";const linkInfo={href,text:utils_default.sanitizeString(link.textContent),position:parseInt(link.getAttribute("data-product-link-position"),10)||0,above_fold:aboveFold};const payload=utils_default.buildTrackingPayload(link,linkInfo,eventType,this.state.trackingContext);if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){try{const positionLong=utils_default.toLong(payload.position);const advertiserShopId=isRemote?utils_default.toLong(payload.advertiser_shop_id):void 0;const productId=isRemote?remoteProductInfo?.product_id:utils_default.parseOrganicProductIdFromLink(link);const requestIdentifier=utils_default.getRequestIdentifier()??null;const pageUrl=window.location?window.location.href:null;const productHandle=isRemote?remoteProductInfo.seo_handle:utils_default.parseOrganicProductHandleFromUrl(href);const remoteProductPayload={advertiser_shop_id:advertiserShopId,ad_response_id:payload.ad_response_id,position:positionLong??1,above_fold:payload.above_fold,viewport_width:payload.viewport_width,viewport_height:payload.viewport_height,x_pos:payload.x_pos,y_pos:payload.y_pos,session_id:payload.session_id,publisher_shop_id:utils_default.toLong(payload.publisher_shop_id),theme_id:utils_default.toLong(payload.theme_id),theme_store_id:utils_default.toLong(payload.theme_store_id),theme_published:payload.theme_published,user_token:payload.user_token,web_session_token:payload.web_session_token,placement:payload.placement,event_data:payload.event_data};this.extractSearchQuery(payload.event_data,remoteProductPayload);
1const allProductsPayload={...remoteProductPayload,impression_id:impressionId,product_id:productId,origin:utils_default.getProductOrigin(isRemote,productHandle),request_id:requestIdentifier,page_url:pageUrl,product_handle:productHandle};if(isRemote){logger_default.log("\u{1F4DD} Remote ad impression:",remoteProductPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_remote_ad_impression/1.1",remoteProductPayload)}logger_default.log("\u{1F4DD} Product impression:",allProductsPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_product_impression/1.1",allProductsPayload)}catch(e){logger_default.error("Error sending impression to Monorail:",e)}}}catch(e){logger_default.error("Error tracking impression:",e)}}trackRemoteProductClick(event,link){try{const href=link.getAttribute("href");if(!utils_default.isRemoteProductLink(href)){return}const linkInfo={href,text:utils_default.sanitizeString(link.textContent),position:parseInt(link.getAttribute("data-product-link-position"),10)||null};const payload=utils_default.buildTrackingPayload(link,linkInfo,"remote_product_click",this.state.trackingContext);payload.click_x=event.clientX;payload.click_y=event.clientY;if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){try{const monorailPayload={publisher_shop_id:utils_default.toLong(payload.publisher_shop_id),advertiser_shop_id:utils_default.toLong(payload.advertiser_shop_id),ad_response_id:payload.ad_response_id,placement:payload.placement,web_session_token:payload.web_session_token,event_data:payload.event_data};this.extractSearchQuery(payload.event_data,monorailPayload);logger_default.log("\u{1F4DD} Remote ad click event:",monorailPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_remote_ad_click/1.2",monorailPayload)}catch(e){logger_default.error("Error sending remote product click to Monorail:",e)}}}catch(e){logger_default.error("Error tracking remote product click:",e)}}trackProductClick(event,link){try{const href=link.getAttribute("href");const isRemote=utils_default.isRemoteProductLink(href);const impressionId=link.getAttribute("data-impression-id");let productId=null;let productHandle=null;let advertiserShopId=null;let adResponseId=null;if(isRemote){const productInfo=utils_default.parseRemoteProductDataFromUrl(href);if(!productInfo||!productInfo.product_id){logger_default.log("\u274C trackProductClick: Could not parse remote product ID from:",href);return}productId=productInfo.product_id;productHandle=productInfo.seo_handle;advertiserShopId=productInfo.advertiser_shop_id;adResponseId=productInfo.ad_response_id}else{productId=utils_default.parseOrganicProductIdFromLink(link);const handleMatch=href.match(/\/products\/([^/?]+)/);if(handleMatch){productHandle=handleMatch[1]}}const origin=utils_default.getProductOrigin(isRemote,productHandle);const linkInfo={href,text:utils_default.sanitizeString(link.textContent),position:parseInt(link.getAttribute("data-product-link-position"),10)||0};const payload=utils_default.buildTrackingPayload(link,linkInfo,"product_click",this.state.trackingContext);const requestIdentifier=utils_default.getRequestIdentifier();const pageUrl=window.location?window.location.href:null;let eventData=payload.event_data;if(!eventData){eventData="{}"}else if(typeof eventData!=="string"){try{eventData=JSON.stringify(eventData)}catch(e){logger_default.error("\u274C trackProductClick: Error stringifying event_data:",e);eventData="{}"}}try{const parsedEventData=JSON.parse(eventData);if(!parsedEventData.product_id){parsedEventData.product_id=productId}eventData=JSON.stringify(parsedEventData)}catch(e){logger_default.error("\u274C trackProductClick: Error updating event_data with product_id:",e)}if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){try{const monorailPayload={impression_id:impressionId,publisher_shop_id:utils_default.toLong(payload.publisher_shop_id),product_id:utils_default.toLong(productId),product_handle:productHandle,origin,placement:payload.placement,event_data:eventData,position:payload.position,user_token:payload.user_token,session_id:payload.session_id,x_pos:payload.x_pos,y_pos:payload.y_pos};if(advertiserShopId){monorailPayload.advertiser_shop_id=utils_default.toLong(advertiserShopId)}if(adResponseId){monorailPayload.ad_response_id=adResponseId}if(payload.web_session_token){monorailPayload.web_session_token=payload.web_session_token}if(requestIdentifier){monorailPayload.request_id=requestIdentifier}if(pageUrl){monorailPayload.page_url=pageUrl}this.extractSearchQuery(eventData,monorailPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_product_click/2.0",monorailPayload);logger_default.log("\u2705 trackProductClick: Successfully sent to Monorail",monorailPayload)}catch(e){logger_default.error("\u274C trackProductClick: Error sending product click to Monorail:",e)}}}catch(e){logger_default.error("\u274C trackProductClick: Error tracking product click:",e)}}trackEmailRemoteProductClick(){try{if(this.emailClickTracked){return}const search=window.location&&window.location.search?window.location.search:"";const params=new URLSearchParams(search);const utmSource=params.get("utm_source");if(utmSource==="shopify_email"){try{if(typeof performance!=="undefined"){const getEntriesByType=performance.getEntriesByType;logger_default.log("getEntriesByType",getEntriesByType);if(typeof getEntriesByType==="function"){const navEntries=getEntriesByType.call(performance,"navigation");if(navEntries&&navEntries[0]&&navEntries[0].type){const navType=navEntries[0].type;if(navType==="reload"||navType==="back_forward"){return}}}}}catch(e){logger_default.error("Error checking navigation type:",e)}const isRemote=utils_default.isRemoteProductLink(window.location.pathname);let productId=null;let productHandle="";let advertiserShopId;let adResponseId;
1if(isRemote){const productInfo=utils_default.parseRemoteProductDataFromUrl(window.location.pathname);if(!productInfo){logger_default.log("\u274C trackEmailRemoteProductClick: Could not parse remote product ID from:",window.location.pathname);return}productId=productInfo.product_id;productHandle=productInfo.seo_handle;advertiserShopId=productInfo.advertiser_shop_id;adResponseId=productInfo.ad_response_id}else{productHandle=utils_default.parseOrganicProductHandleFromUrl(window.location.pathname);productId=utils_default.parseOrganicProductIdFromUrl(window.location.pathname)}const baseEventData=this.state.trackingContext?this.state.trackingContext.event_data:void 0;let eventData=baseEventData;if(productId&&baseEventData){try{let parsed=typeof baseEventData==="string"?JSON.parse(baseEventData):baseEventData;if(parsed==null||typeof parsed!=="object"){parsed={}}parsed.product_id=productId;eventData=JSON.stringify(parsed)}catch(e){logger_default.error("Error updating event_data for shopify-email:",e)}}if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){const remoteOnlyPayload={publisher_shop_id:utils_default.toLong(this.state.trackingContext&&this.state.trackingContext.publisher_shop_id),advertiser_shop_id:utils_default.toLong(advertiserShopId),ad_response_id:adResponseId,placement:"email",web_session_token:utils_default.getWebSessionToken(),event_data:eventData};const allProductsPayload={...remoteOnlyPayload,position:0,origin:utils_default.getProductOrigin(isRemote,productHandle),product_handle:productHandle,product_id:productId,request_id:utils_default.getRequestIdentifier()??null,page_url:window.location?window.location.href:null,user_token:utils_default.getSecureUserToken(),session_id:this.state.trackingContext?.session_id};if(isRemote){logger_default.log("\u{1F4DD} Shopify Email remote ad click:",remoteOnlyPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_remote_ad_click/1.2",remoteOnlyPayload)}logger_default.log("\u{1F4DD} Shopify Email all products click:",allProductsPayload);window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_product_click/2.0",allProductsPayload);this.emailClickTracked=true}}}catch(e){logger_default.error("Error tracking shopify-email remote product click:",e)}}observeRemoteProductLinks(){try{const allProductLinks=filterProductLinks(document.querySelectorAll(PRODUCT_LINK_SELECTOR));const allRemoteLinks=allProductLinks.filter(link=>utils_default.isRemoteProductLink(normalizeHref(link)));const uniqueRemoteLinks=getUniqueProductLinks(allRemoteLinks);const impressionData=new Map;const impressionTrackedKeys=new Set;for(let i=0;i<uniqueRemoteLinks.length&&impressionData.size<this.config.MAX_PROCESSED_LINKS;i++){const link=uniqueRemoteLinks[i];const href=normalizeHref(link);const dedupKey=getImpressionDedupKey(href);if(!impressionData.has(dedupKey)){impressionData.set(dedupKey,{position:impressionData.size+1,impressionId:utils_default.generateImpressionId()})}const linkRect=link.getBoundingClientRect();if(!isLinkVisible(linkRect,this.config.MIN_ELEMENT_SIZE)){continue}impressionTrackedKeys.add(dedupKey);if(!link.hasAttribute("data-remote-impression-tracked")){const{position,impressionId}=impressionData.get(dedupKey);link.setAttribute("data-remote-impression-tracked","true");if(link.hasAttribute("data-predictive-search-link")){utils_default.setPredictiveSearchPosition(link)}else if(link.hasAttribute("data-recommendations-link")){utils_default.setRecommendationsPosition(link)}else{link.setAttribute("data-product-position",position)}if(!link.hasAttribute("data-impression-id")){link.setAttribute("data-impression-id",impressionId)}logger_default.log("\u{1F3AF} Remote product impression tracked:",{href,position});this.trackRemoteProductRendered(link);setAboveFoldAttribute(link,linkRect);if(this.state.observer){this.state.observer.observe(link)}}}for(let i=0;i<allRemoteLinks.length;i++){const link=allRemoteLinks[i];const href=normalizeHref(link);const dedupKey=getImpressionDedupKey(href);if(link.hasAttribute("data-remote-click-tracked")){continue}if(impressionData.has(dedupKey)){const{position,impressionId}=impressionData.get(dedupKey);if(!link.hasAttribute("data-product-position")){link.setAttribute("data-product-position",position)}if(!link.hasAttribute("data-impression-id")){link.setAttribute("data-impression-id",impressionId)}}if(!impressionTrackedKeys.has(dedupKey)&&impressionData.has(dedupKey)){const linkRect=link.getBoundingClientRect();
1if(isLinkVisible(linkRect,this.config.MIN_ELEMENT_SIZE)){impressionTrackedKeys.add(dedupKey);link.setAttribute("data-remote-impression-tracked","true");this.trackRemoteProductRendered(link);setAboveFoldAttribute(link,linkRect);if(this.state.observer){this.state.observer.observe(link)}}}if(!link.hasAttribute("data-impression-id")){continue}link.setAttribute("data-remote-click-tracked","true");link.addEventListener("click",event=>{if(!utils_default.isTrustedEvent(event)){return}this.trackRemoteProductClick(event,link)},true);let container=link.closest("product-card");if(!container){container=link.closest("div")}if(container&&!container.hasAttribute("data-remote-card-tracked")){container.setAttribute("data-remote-card-tracked","true");container.addEventListener("click",event=>{if(!utils_default.isTrustedEvent(event)){return}const clickedLink=event.target.closest("a[data-remote-click-tracked]");if(clickedLink){return}const containerLinks=filterProductLinks(container.querySelectorAll(PRODUCT_LINK_SELECTOR));const containerLink=containerLinks[0];if(containerLink){this.trackRemoteProductClick(event,containerLink)}},true);logger_default.log("\u{1F3AF} Card listener attached to remote product link:",{href,containerElement:container.tagName,containerClass:container.className})}}}catch(e){logger_default.error("Error observing remote product links:",e)}}observeProductLinks(){try{const allProductLinks=filterProductLinks(document.querySelectorAll(PRODUCT_LINK_SELECTOR));const allValidLinks=allProductLinks.filter(link=>utils_default.isValidHref(normalizeHref(link)));const uniqueLinks=getUniqueProductLinks(allValidLinks);const impressionData=new Map;const impressionTrackedKeys=new Set;for(let i=0;i<uniqueLinks.length&&impressionData.size<this.config.MAX_PROCESSED_LINKS;i++){const link=uniqueLinks[i];const href=normalizeHref(link);const dedupKey=getImpressionDedupKey(href);if(!impressionData.has(dedupKey)){impressionData.set(dedupKey,{position:impressionData.size+1,impressionId:utils_default.generateImpressionId()})}const linkRect=link.getBoundingClientRect();if(!isLinkVisible(linkRect,this.config.MIN_ELEMENT_SIZE)){continue}impressionTrackedKeys.add(dedupKey);if(!link.hasAttribute("data-product-impression-tracked")){const{position,impressionId}=impressionData.get(dedupKey);link.setAttribute("data-product-impression-tracked","true");if(link.hasAttribute("data-predictive-search-link")){utils_default.setPredictiveSearchPosition(link)}else if(link.hasAttribute("data-recommendations-link")){utils_default.setRecommendationsPosition(link)}else{link.setAttribute("data-product-link-position",position)}if(!link.hasAttribute("data-impression-id")){link.setAttribute("data-impression-id",impressionId)}setAboveFoldAttribute(link,linkRect);if(this.state.observer){this.state.observer.observe(link)}}}for(let i=0;i<allValidLinks.length;i++){const link=allValidLinks[i];const href=normalizeHref(link);const dedupKey=getImpressionDedupKey(href);if(link.hasAttribute("data-product-click-tracked")){continue}if(impressionData.has(dedupKey)){const{position,impressionId}=impressionData.get(dedupKey);if(!link.hasAttribute("data-product-link-position")){link.setAttribute("data-product-link-position",position)}if(!link.hasAttribute("data-impression-id")){link.setAttribute("data-impression-id",impressionId)}}if(!impressionTrackedKeys.has(dedupKey)&&impressionData.has(dedupKey)){const linkRect=link.getBoundingClientRect();if(isLinkVisible(linkRect,this.config.MIN_ELEMENT_SIZE)){impressionTrackedKeys.add(dedupKey);link.setAttribute("data-product-impression-tracked","true");setAboveFoldAttribute(link,linkRect);if(this.state.observer){this.state.observer.observe(link)}}}if(!link.hasAttribute("data-impression-id")){continue}link.setAttribute("data-product-click-tracked","true");link.addEventListener("click",event=>{if(!utils_default.isTrustedEvent(event)){return}this.trackProductClick(event,link)},true);let container=link.closest("product-card");if(!container){container=link.closest("div")}if(container&&!container.hasAttribute("data-product-card-tracked")){container.setAttribute("data-product-card-tracked","true");container.addEventListener("click",event=>{if(!utils_default.isTrustedEvent(event)){return}const clickedLink=event.target.closest("a[data-product-click-tracked]");if(clickedLink){return}const containerLinks=filterProductLinks(container.querySelectorAll(PRODUCT_LINK_SELECTOR));const containerLink=containerLinks[0];if(containerLink&&utils_default.isValidHref(containerLink.getAttribute("href"))){this.trackProductClick(event,containerLink)}},true);logger_default.log("\u{1F3AF} Card listener attached to product link:",{href,containerElement:container.tagName,containerClass:container.className})}}logger_default.log("Processed",impressionData.size,"unique product links for impressions")}catch(e){logger_default.error("\u274C Error observing product links:",e)}}
1detectRecommendationDuplicates(){try{let getCachedProductInfo=function(href){if(parsedCache.has(href)){return parsedCache.get(href)}const info=utils_default.parseRemoteProductDataFromUrl(href);parsedCache.set(href,info);return info};const containers=document.querySelectorAll('product-recommendations[data-url*="/recommendations/products"], [data-product-recommendations][data-url*="/recommendations/products"], .product-recommendations[data-url*="/recommendations/products"]');if(containers.length<2){logger_default.log("\u26A0\uFE0F Found",containers.length,"recommendation container(s), need at least 2 to detect duplicates");return}logger_default.log("\u{1F50D} Found",containers.length,"recommendation container(s)");for(let c=0;c<containers.length;c++){const container=containers[c];if(container.getAttribute("data-recommendations-performed")==="false"){if(!container.hasAttribute("data-duplicate-observer-attached")){container.setAttribute("data-duplicate-observer-attached","true");const observer=new MutationObserver(()=>{if(container.getAttribute("data-recommendations-performed")==="false"){return}observer.disconnect();const idx=this.state.duplicateObservers.indexOf(observer);if(idx!==-1){this.state.duplicateObservers.splice(idx,1)}this.debouncedScan()});this.state.duplicateObservers.push(observer);observer.observe(container,{attributes:true,attributeFilter:["data-recommendations-performed"]});logger_default.log("\u23F3 Recommendation container not yet loaded, observing for changes")}return}}const parsedCache=new Map;const seenHandles=new Map;let duplicatesDetected=0;for(let c=0;c<containers.length;c++){const container=containers[c];const remoteLinks=container.querySelectorAll('a[data-remote-click-tracked="true"]');for(let i=0;i<remoteLinks.length;i++){const link=remoteLinks[i];if(link.hasAttribute("data-duplicate-detected")){continue}const href=normalizeHref(link);const productInfo=getCachedProductInfo(href);if(!productInfo||!productInfo.seo_handle){continue}const handle=productInfo.seo_handle;if(!seenHandles.has(handle)){seenHandles.set(handle,container);continue}if(seenHandles.get(handle)===container){continue}if(this.state.reportedDuplicateHandles.has(handle)){continue}if(duplicatesDetected>=this.config.MAX_PROCESSED_LINKS){break}this.state.reportedDuplicateHandles.add(handle);duplicatesDetected++;for(let d=0;d<containers.length;d++){const allLinks=containers[d].querySelectorAll('a[data-remote-click-tracked="true"]');for(let j=0;j<allLinks.length;j++){const rl=allLinks[j];const rlInfo=getCachedProductInfo(normalizeHref(rl));if(rlInfo&&rlInfo.seo_handle===handle){rl.setAttribute("data-duplicate-detected","true")}}}const position=parseInt(link.getAttribute("data-product-link-position"),10)||0;const monorailPayload={publisher_shop_id:utils_default.toLong(this.state.trackingContext?.publisher_shop_id),advertiser_shop_id:utils_default.toLong(productInfo.advertiser_shop_id),ad_response_id:productInfo.ad_response_id,user_token:utils_default.getSecureUserToken(),session_id:this.state.trackingContext?.session_id,web_session_token:utils_default.getWebSessionToken(),position,theme_id:utils_default.toLong(this.state.trackingContext?.theme_id),theme_published:this.state.trackingContext?.theme_published,theme_store_id:this.state.trackingContext?.theme_store_id===0?void 0:utils_default.toLong(this.state.trackingContext?.theme_store_id),event_data:JSON.stringify({product_id:productInfo.product_id,product_handle:handle})};logger_default.log("\u{1F4DD} Duplicate remote product detected in recommendations:",monorailPayload);if(window.ShopifyAnalytics&&window.ShopifyAnalytics.lib&&window.ShopifyAnalytics.lib.track){try{window.ShopifyAnalytics.lib.track("monorail://trekkie_storefront_remote_ad_recommendations_duplicate_detected/1.0",monorailPayload)}catch(e){logger_default.error("Error sending duplicate detection to Monorail:",e)}}}}}catch(e){logger_default.error("Error detecting recommendation duplicates:",e)}}debouncedScan(){clearTimeout(this.scanTimeout);this.scanTimeout=setTimeout(()=>{utils_default.mergeCollectiveProductAttributionFromDom();this.observeProductLinks();this.observeRemoteProductLinks();
1this.detectRecommendationDuplicates()},this.config.DEBOUNCE_DELAY)}initialize(){if(this.state.isInitialized){return}if(!window.IntersectionObserver||!document.querySelector){logger_default.warn("Browser doesn't support required features for tracking");return}if(!this.initTrackingContext()){return}try{this.state.observer=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(entry.isIntersecting){this.trackProductImpression(entry.target)}})},{threshold:this.config.OBSERVER_THRESHOLD});if(window.MutationObserver){this.state.mutationObserver=new MutationObserver(mutations=>{const shouldScan=mutations.some(mutation=>{return mutation.type==="childList"&&mutation.addedNodes.length>0&&Array.prototype.some.call(mutation.addedNodes,node=>{if(node.nodeType!==1){return false}if(node.tagName==="A"){const href=node.getAttribute&&node.getAttribute("href");if(href&&href.includes("/products/")){return true}}const productLinks=node.querySelectorAll?node.querySelectorAll(PRODUCT_LINK_SELECTOR):[];return filterProductLinks(productLinks).length>0})});if(shouldScan){this.debouncedScan()}});if(document.body){this.state.mutationObserver.observe(document.body,{childList:true,subtree:true})}}this.state.isInitialized=true;this.trackEmailRemoteProductClick();utils_default.mergeCollectiveProductAttributionFromDom();this.observeProductLinks();this.observeRemoteProductLinks();this.detectRecommendationDuplicates()}catch(e){logger_default.error("Error initializing tracking:",e)}}cleanup(){try{this.state.reset();clearTimeout(this.scanTimeout);this.emailClickTracked=false}catch(e){logger_default.error("Error during cleanup:",e)}}};logger_default.log("\u{1F680} Product Network tracking loaded!");ready(()=>{const tracker=new RemoteProductTracker;tracker.initialize();window.Shopify=window.Shopify||{};window.Shopify.remoteProductTracker=tracker;window.remoteProductTrackingCleanup=()=>tracker.cleanup()});if(document.readyState!=="loading"){setTimeout(()=>{if(window.Shopify?.remoteProductTracker){return}const tracker=new RemoteProductTracker;tracker.initialize();window.Shopify=window.Shopify||{};window.Shopify.remoteProductTracker=tracker;window.remoteProductTrackingCleanup=()=>tracker.cleanup()},0)}})();

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.